Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Builtin bounds for closures and traits #7248

Closed
wants to merge 9 commits into from
24 changes: 18 additions & 6 deletions src/etc/vim/syntax/rust.vim
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
" Language: Rust
" Maintainer: Patrick Walton <pcwalton@mozilla.com>
" Maintainer: Ben Blum <bblum@cs.cmu.edu>
" Last Change: 2012 Dec 25
" Last Change: 2012 Jun 14

if version < 600
syntax clear
Expand All @@ -13,13 +13,16 @@ endif
syn keyword rustConditional match if else
syn keyword rustOperator as

syn match rustAssert "\<assert\(\w\)*!"
syn match rustFail "\<fail\(\w\)*!"
syn keyword rustKeyword break copy do drop extern
syn keyword rustKeyword for if impl let log
syn keyword rustKeyword copy do extern
syn keyword rustKeyword for impl let log
syn keyword rustKeyword loop mod once priv pub
syn keyword rustKeyword return
syn keyword rustKeyword unsafe use while
syn keyword rustKeyword unsafe while
syn keyword rustKeyword use nextgroup=rustModPath skipwhite
" FIXME: Scoped impl's name is also fallen in this category
syn keyword rustKeyword mod trait struct enum type nextgroup=rustIdentifier skipwhite
syn keyword rustKeyword fn nextgroup=rustFuncName skipwhite
Expand All @@ -45,7 +48,8 @@ syn keyword rustType c_longlong c_ulonglong intptr_t uintptr_t
syn keyword rustType off_t dev_t ino_t pid_t mode_t ssize_t

syn keyword rustTrait Const Copy Send Owned Sized " inherent traits
syn keyword rustTrait Eq Ord Num Ptr
syn keyword rustTrait Clone Decodable Encodable IterBytes Rand ToStr
syn keyword rustTrait Eq Ord TotalEq TotalOrd Num Ptr
syn keyword rustTrait Drop Add Sub Mul Quot Rem Neg BitAnd BitOr
syn keyword rustTrait BitXor Shl Shr Index

Expand All @@ -72,19 +76,21 @@ syn keyword rustConstant STDIN_FILENO STDOUT_FILENO STDERR_FILENO
" If foo::bar changes to foo.bar, change this ("::" to "\.").
" If foo::bar changes to Foo::bar, change this (first "\w" to "\u").
syn match rustModPath "\w\(\w\)*::[^<]"he=e-3,me=e-3
syn match rustModPath "\w\(\w\)*" contained " only for 'use path;'
syn match rustModPathSep "::"

syn match rustFuncCall "\w\(\w\)*("he=e-1,me=e-1
syn match rustFuncCall "\w\(\w\)*::<"he=e-3,me=e-3 " foo::<T>();

syn match rustMacro '\w\(\w\)*!'
syn match rustMacro '#\w\(\w\)*'
syn match rustMacro '\w\(\w\)*!' contains=rustAssert,rustFail
syn match rustMacro '#\w\(\w\)*' contains=rustAssert,rustFail

syn match rustFormat display "%\(\d\+\$\)\=[-+' #0*]*\(\d*\|\*\|\*\d\+\$\)\(\.\(\d*\|\*\|\*\d\+\$\)\)\=\([hlLjzt]\|ll\|hh\)\=\([aAbdiuoxXDOUfFeEgGcCsSpn?]\|\[\^\=.[^]]*\]\)" contained
syn match rustFormat display "%%" contained
syn region rustString start=+L\="+ skip=+\\\\\|\\"+ end=+"+ contains=rustTodo,rustFormat

syn region rustAttribute start="#\[" end="\]" contains=rustString
syn region rustAttribute start="#\[" end="\]" contains=rustString,rustDeriving
syn region rustDeriving start="deriving(" end=")" contains=rustTrait

" Number literals
syn match rustNumber display "\<[0-9][0-9_]*\>"
Expand Down Expand Up @@ -143,11 +149,17 @@ hi def link rustMacro Macro
hi def link rustType Type
hi def link rustTodo Todo
hi def link rustAttribute PreProc
hi def link rustDeriving PreProc
hi def link rustStorage StorageClass
hi def link rustLifetime Special

" Other Suggestions:
" hi rustAttribute ctermfg=cyan
" hi rustDeriving ctermfg=cyan
" hi rustAssert ctermfg=yellow
" hi rustFail ctermfg=red
" hi rustMacro ctermfg=magenta
" hi rustModPathSep ctermfg=grey

syn sync minlines=200
syn sync maxlines=500
Expand Down
3 changes: 2 additions & 1 deletion src/librustc/metadata/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -954,7 +954,8 @@ fn encode_info_for_item(ecx: &EncodeContext,
encode_name(ecx, ebml_w, item.ident);
encode_attributes(ebml_w, item.attrs);
match ty.node {
ast::ty_path(path, _) if path.idents.len() == 1 => {
ast::ty_path(path, bounds, _) if path.idents.len() == 1 => {
assert!(bounds.is_empty());
encode_impl_type_basename(ecx, ebml_w,
ast_util::path_to_ident(path));
}
Expand Down
3 changes: 2 additions & 1 deletion src/librustc/metadata/tydecode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,8 +311,9 @@ fn parse_ty(st: &mut PState, conv: conv_did) -> ty::t {
let substs = parse_substs(st, conv);
let store = parse_trait_store(st);
let mt = parse_mutability(st);
let bounds = parse_bounds(st, conv);
assert_eq!(next(st), ']');
return ty::mk_trait(st.tcx, def, substs, store, mt);
return ty::mk_trait(st.tcx, def, substs, store, mt, bounds.builtin_bounds);
}
'p' => {
let did = parse_def(st, TypeParameter, conv);
Expand Down
5 changes: 4 additions & 1 deletion src/librustc/metadata/tyencode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -261,13 +261,16 @@ fn enc_sty(w: @io::Writer, cx: @ctxt, st: ty::sty) {
enc_substs(w, cx, substs);
w.write_char(']');
}
ty::ty_trait(def, ref substs, store, mt) => {
ty::ty_trait(def, ref substs, store, mt, bounds) => {
w.write_str(&"x[");
w.write_str((cx.ds)(def));
w.write_char('|');
enc_substs(w, cx, substs);
enc_trait_store(w, cx, store);
enc_mutability(w, mt);
let bounds = ty::ParamBounds {builtin_bounds: bounds,
trait_bounds: ~[]};
enc_bounds(w, cx, &bounds);
w.write_char(']');
}
ty::ty_tup(ts) => {
Expand Down
123 changes: 83 additions & 40 deletions src/librustc/middle/kind.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,6 @@ pub fn check_crate(tcx: ty::ctxt,
tcx.sess.abort_if_errors();
}

type check_fn = @fn(Context, @freevar_entry);

fn check_struct_safe_for_destructor(cx: Context,
span: span,
struct_did: def_id) {
Expand Down Expand Up @@ -129,7 +127,8 @@ fn check_item(item: @item, (cx, visitor): (Context, visit::vt<Context>)) {
if cx.tcx.lang_items.drop_trait() == trait_def_id {
// Yes, it's a destructor.
match self_type.node {
ty_path(_, path_node_id) => {
ty_path(_, bounds, path_node_id) => {
assert!(bounds.is_empty());
let struct_def = cx.tcx.def_map.get_copy(
&path_node_id);
let struct_did =
Expand Down Expand Up @@ -162,30 +161,43 @@ fn check_item(item: @item, (cx, visitor): (Context, visit::vt<Context>)) {
// Yields the appropriate function to check the kind of closed over
// variables. `id` is the node_id for some expression that creates the
// closure.
fn with_appropriate_checker(cx: Context, id: node_id, b: &fn(check_fn)) {
fn check_for_uniq(cx: Context, fv: @freevar_entry) {
fn with_appropriate_checker(cx: Context, id: node_id,
b: &fn(checker: &fn(Context, @freevar_entry))) {
fn check_for_uniq(cx: Context, fv: @freevar_entry, bounds: ty::BuiltinBounds) {
// all captured data must be owned, regardless of whether it is
// moved in or copied in.
let id = ast_util::def_id_of_def(fv.def).node;
let var_t = ty::node_id_to_type(cx.tcx, id);

// FIXME(#3569): Once closure capabilities are restricted based on their
// incoming bounds, make this check conditional based on the bounds.
if !check_owned(cx, var_t, fv.span) { return; }

// check that only immutable variables are implicitly copied in
check_imm_free_var(cx, fv.def, fv.span);

check_freevar_bounds(cx, fv.span, var_t, bounds);
}

fn check_for_box(cx: Context, fv: @freevar_entry) {
fn check_for_box(cx: Context, fv: @freevar_entry, bounds: ty::BuiltinBounds) {
// all captured data must be owned
let id = ast_util::def_id_of_def(fv.def).node;
let var_t = ty::node_id_to_type(cx.tcx, id);

// FIXME(#3569): Once closure capabilities are restricted based on their
// incoming bounds, make this check conditional based on the bounds.
if !check_durable(cx.tcx, var_t, fv.span) { return; }

// check that only immutable variables are implicitly copied in
check_imm_free_var(cx, fv.def, fv.span);

check_freevar_bounds(cx, fv.span, var_t, bounds);
}

fn check_for_block(_cx: Context, _fv: @freevar_entry) {
// no restrictions
fn check_for_block(cx: Context, fv: @freevar_entry, bounds: ty::BuiltinBounds) {
let id = ast_util::def_id_of_def(fv.def).node;
let var_t = ty::node_id_to_type(cx.tcx, id);
check_freevar_bounds(cx, fv.span, var_t, bounds);
}

fn check_for_bare(cx: Context, fv: @freevar_entry) {
Expand All @@ -196,14 +208,14 @@ fn with_appropriate_checker(cx: Context, id: node_id, b: &fn(check_fn)) {

let fty = ty::node_id_to_type(cx.tcx, id);
match ty::get(fty).sty {
ty::ty_closure(ty::ClosureTy {sigil: OwnedSigil, _}) => {
b(check_for_uniq)
ty::ty_closure(ty::ClosureTy {sigil: OwnedSigil, bounds: bounds, _}) => {
b(|cx, fv| check_for_uniq(cx, fv, bounds))
}
ty::ty_closure(ty::ClosureTy {sigil: ManagedSigil, _}) => {
b(check_for_box)
ty::ty_closure(ty::ClosureTy {sigil: ManagedSigil, bounds: bounds, _}) => {
b(|cx, fv| check_for_box(cx, fv, bounds))
}
ty::ty_closure(ty::ClosureTy {sigil: BorrowedSigil, _}) => {
b(check_for_block)
ty::ty_closure(ty::ClosureTy {sigil: BorrowedSigil, bounds: bounds, _}) => {
b(|cx, fv| check_for_block(cx, fv, bounds))
}
ty::ty_bare_fn(_) => {
b(check_for_bare)
Expand Down Expand Up @@ -271,15 +283,21 @@ pub fn check_expr(e: @expr, (cx, v): (Context, visit::vt<Context>)) {
type_param_defs.repr(cx.tcx));
}
for ts.iter().zip(type_param_defs.iter()).advance |(&ty, type_param_def)| {
check_bounds(cx, type_parameter_id, e.span, ty, type_param_def)
check_typaram_bounds(cx, type_parameter_id, e.span, ty, type_param_def)
}
}
}

match e.node {
expr_cast(source, _) => {
check_cast_for_escaping_regions(cx, source, e);
check_kind_bounds_of_cast(cx, source, e);
match ty::get(ty::expr_ty(cx.tcx, e)).sty {
ty::ty_trait(_, _, store, _, bounds) => {
let source_ty = ty::expr_ty(cx.tcx, source);
check_trait_cast_bounds(cx, e.span, source_ty, bounds, store)
}
_ => { }
}
}
expr_copy(expr) => {
// Note: This is the only place where we must check whether the
Expand Down Expand Up @@ -307,14 +325,14 @@ pub fn check_expr(e: @expr, (cx, v): (Context, visit::vt<Context>)) {

fn check_ty(aty: @Ty, (cx, v): (Context, visit::vt<Context>)) {
match aty.node {
ty_path(_, id) => {
ty_path(_, _, id) => {
let r = cx.tcx.node_type_substs.find(&id);
for r.iter().advance |ts| {
let did = ast_util::def_id_of_def(cx.tcx.def_map.get_copy(&id));
let type_param_defs =
ty::lookup_item_type(cx.tcx, did).generics.type_param_defs;
for ts.iter().zip(type_param_defs.iter()).advance |(&ty, type_param_def)| {
check_bounds(cx, aty.id, aty.span, ty, type_param_def)
check_typaram_bounds(cx, aty.id, aty.span, ty, type_param_def)
}
}
}
Expand All @@ -323,20 +341,29 @@ fn check_ty(aty: @Ty, (cx, v): (Context, visit::vt<Context>)) {
visit::visit_ty(aty, (cx, v));
}

pub fn check_bounds(cx: Context,
_type_parameter_id: node_id,
sp: span,
ty: ty::t,
type_param_def: &ty::TypeParameterDef)
// Calls "any_missing" if any bounds were missing.
pub fn check_builtin_bounds(cx: Context, ty: ty::t, bounds: ty::BuiltinBounds,
any_missing: &fn(ty::BuiltinBounds))
{
let kind = ty::type_contents(cx.tcx, ty);
let mut missing = ty::EmptyBuiltinBounds();
for type_param_def.bounds.builtin_bounds.each |bound| {
for bounds.each |bound| {
if !kind.meets_bound(cx.tcx, bound) {
missing.add(bound);
}
}
if !missing.is_empty() {
any_missing(missing);
}
}

pub fn check_typaram_bounds(cx: Context,
_type_parameter_id: node_id,
sp: span,
ty: ty::t,
type_param_def: &ty::TypeParameterDef)
{
do check_builtin_bounds(cx, ty, type_param_def.bounds.builtin_bounds) |missing| {
cx.tcx.sess.span_err(
sp,
fmt!("instantiating a type parameter with an incompatible type \
Expand All @@ -346,6 +373,38 @@ pub fn check_bounds(cx: Context,
}
}

pub fn check_freevar_bounds(cx: Context, sp: span, ty: ty::t,
bounds: ty::BuiltinBounds)
{
do check_builtin_bounds(cx, ty, bounds) |missing| {
cx.tcx.sess.span_err(
sp,
fmt!("cannot capture variable of type `%s`, which does not fulfill \
`%s`, in a bounded closure",
ty_to_str(cx.tcx, ty), missing.user_string(cx.tcx)));
cx.tcx.sess.span_note(
sp,
fmt!("this closure's environment must satisfy `%s`",
bounds.user_string(cx.tcx)));
}
}

pub fn check_trait_cast_bounds(cx: Context, sp: span, ty: ty::t,
bounds: ty::BuiltinBounds, store: ty::TraitStore) {
do check_builtin_bounds(cx, ty, bounds) |missing| {
cx.tcx.sess.span_err(sp,
fmt!("cannot pack type `%s`, which does not fulfill \
`%s`, as a trait bounded by %s",
ty_to_str(cx.tcx, ty), missing.user_string(cx.tcx),
bounds.user_string(cx.tcx)));
}
// FIXME(#3569): Remove this check when the corresponding restriction
// is made with type contents.
if store == ty::UniqTraitStore && !ty::type_is_owned(cx.tcx, ty) {
cx.tcx.sess.span_err(sp, "uniquely-owned trait objects must be sendable");
}
}

fn is_nullary_variant(cx: Context, ex: @expr) -> bool {
match ex.node {
expr_path(_) => {
Expand Down Expand Up @@ -528,19 +587,3 @@ pub fn check_cast_for_escaping_regions(
cx.tcx.region_maps.is_subregion_of(r_sub, r_sup)
}
}

/// Ensures that values placed into a ~Trait are copyable and sendable.
pub fn check_kind_bounds_of_cast(cx: Context, source: @expr, target: @expr) {
let target_ty = ty::expr_ty(cx.tcx, target);
match ty::get(target_ty).sty {
ty::ty_trait(_, _, ty::UniqTraitStore, _) => {
let source_ty = ty::expr_ty(cx.tcx, source);
if !ty::type_is_owned(cx.tcx, source_ty) {
cx.tcx.sess.span_err(
target.span,
"uniquely-owned trait objects must be sendable");
}
}
_ => {} // Nothing to do.
}
}
2 changes: 1 addition & 1 deletion src/librustc/middle/lint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -713,7 +713,7 @@ fn check_item_ctypes(cx: &Context, it: @ast::item) {
let tys = vec::map(decl.inputs, |a| a.ty );
for vec::each(vec::append_one(tys, decl.output)) |ty| {
match ty.node {
ast::ty_path(_, id) => {
ast::ty_path(_, _, id) => {
match cx.tcx.def_map.get_copy(&id) {
ast::def_prim_ty(ast::ty_int(ast::ty_i)) => {
cx.span_lint(ctypes, ty.span,
Expand Down
4 changes: 2 additions & 2 deletions src/librustc/middle/region.rs
Original file line number Diff line number Diff line change
Expand Up @@ -804,7 +804,7 @@ pub fn determine_rp_in_ty(ty: @ast::Ty,
// then check whether it is region-parameterized and consider
// that as a direct dependency.
match ty.node {
ast::ty_path(path, id) => {
ast::ty_path(path, _bounds, id) => {
match cx.def_map.find(&id) {
Some(&ast::def_ty(did)) |
Some(&ast::def_trait(did)) |
Expand Down Expand Up @@ -840,7 +840,7 @@ pub fn determine_rp_in_ty(ty: @ast::Ty,
visit_mt(mt, (cx, visitor));
}

ast::ty_path(path, _) => {
ast::ty_path(path, _bounds, _) => {
// type parameters are---for now, anyway---always invariant
do cx.with_ambient_variance(rv_invariant) {
for path.types.each |tp| {
Expand Down
8 changes: 6 additions & 2 deletions src/librustc/middle/resolve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1250,7 +1250,7 @@ impl Resolver {
// If there are static methods, then create the module
// and add them.
match (trait_ref_opt, ty) {
(None, @Ty { node: ty_path(path, _), _ }) if
(None, @Ty { node: ty_path(path, _, _), _ }) if
has_static_methods && path.idents.len() == 1 => {
let name = path_to_ident(path);

Expand Down Expand Up @@ -4118,7 +4118,7 @@ impl Resolver {
// Like path expressions, the interpretation of path types depends
// on whether the path has multiple elements in it or not.

ty_path(path, path_id) => {
ty_path(path, bounds, path_id) => {
// This is a path in the type namespace. Walk through scopes
// scopes looking for it.
let mut result_def = None;
Expand Down Expand Up @@ -4177,6 +4177,10 @@ impl Resolver {
self.idents_to_str(path.idents)));
}
}

for bounds.each |bound| {
self.resolve_type_parameter_bound(bound, visitor);
}
}

ty_closure(c) => {
Expand Down
Loading