1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Conversion from AST representation of types to the ty.rs
12 //! representation. The main routine here is `ast_ty_to_ty()`: each use
13 //! is parameterized by an instance of `AstConv` and a `RegionScope`.
15 //! The parameterization of `ast_ty_to_ty()` is because it behaves
16 //! somewhat differently during the collect and check phases,
17 //! particularly with respect to looking up the types of top-level
18 //! items. In the collect phase, the crate context is used as the
19 //! `AstConv` instance; in this phase, the `get_item_ty()` function
20 //! triggers a recursive call to `ty_of_item()` (note that
21 //! `ast_ty_to_ty()` will detect recursive types and report an error).
22 //! In the check phase, when the FnCtxt is used as the `AstConv`,
23 //! `get_item_ty()` just looks up the item type in `tcx.tcache`.
25 //! The `RegionScope` trait controls what happens when the user does
26 //! not specify a region in some location where a region is required
27 //! (e.g., if the user writes `&Foo` as a type rather than `&'a Foo`).
28 //! See the `rscope` module for more details.
30 //! Unlike the `AstConv` trait, the region scope can change as we descend
31 //! the type. This is to accommodate the fact that (a) fn types are binding
32 //! scopes and (b) the default region may change. To understand case (a),
33 //! consider something like:
35 //! type foo = { x: &a.int, y: |&a.int| }
37 //! The type of `x` is an error because there is no region `a` in scope.
38 //! In the type of `y`, however, region `a` is considered a bound region
39 //! as it does not already appear in scope.
41 //! Case (b) says that if you have a type:
42 //! type foo<'a> = ...;
43 //! type bar = fn(&foo, &a.foo)
44 //! The fully expanded version of type bar is:
45 //! type bar = fn(&'foo &, &a.foo<'a>)
46 //! Note that the self region for the `foo` defaulted to `&` in the first
47 //! case but `&a` in the second. Basically, defaults that appear inside
48 //! an rptr (`&r.T`) use the region `r` that appears in the rptr.
50 use middle::astconv_util::{ast_ty_to_prim_ty, check_path_args, NO_TPS, NO_REGIONS};
51 use middle::const_eval;
53 use middle::resolve_lifetime as rl;
54 use middle::subst::{FnSpace, TypeSpace, AssocSpace, SelfSpace, Subst, Substs};
55 use middle::subst::{VecPerParamSpace};
56 use middle::ty::{mod, Ty};
57 use rscope::{mod, UnelidableRscope, RegionScope, SpecificRscope,
58 ShiftedRscope, BindingRscope};
60 use util::common::ErrorReported;
61 use util::nodemap::DefIdMap;
62 use util::ppaux::{mod, Repr, UserString};
65 use std::iter::AdditiveIterator;
66 use syntax::{abi, ast, ast_util};
67 use syntax::codemap::Span;
68 use syntax::parse::token;
69 use syntax::print::pprust;
71 pub trait AstConv<'tcx> {
72 fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx>;
73 fn get_item_ty(&self, id: ast::DefId) -> ty::Polytype<'tcx>;
74 fn get_trait_def(&self, id: ast::DefId) -> Rc<ty::TraitDef<'tcx>>;
76 /// What type should we use when a type is omitted?
77 fn ty_infer(&self, span: Span) -> Ty<'tcx>;
79 /// Returns true if associated types from the given trait and type are
80 /// allowed to be used here and false otherwise.
81 fn associated_types_of_trait_are_valid(&self,
86 /// Returns the binding of the given associated type for some type.
87 fn associated_type_binding(&self,
91 associated_type_id: ast::DefId)
95 pub fn ast_region_to_region(tcx: &ty::ctxt, lifetime: &ast::Lifetime)
97 let r = match tcx.named_region_map.get(&lifetime.id) {
99 // should have been recorded by the `resolve_lifetime` pass
100 tcx.sess.span_bug(lifetime.span, "unresolved lifetime");
103 Some(&rl::DefStaticRegion) => {
107 Some(&rl::DefLateBoundRegion(debruijn, id)) => {
108 ty::ReLateBound(debruijn, ty::BrNamed(ast_util::local_def(id), lifetime.name))
111 Some(&rl::DefEarlyBoundRegion(space, index, id)) => {
112 ty::ReEarlyBound(id, space, index, lifetime.name)
115 Some(&rl::DefFreeRegion(scope, id)) => {
116 ty::ReFree(ty::FreeRegion {
118 bound_region: ty::BrNamed(ast_util::local_def(id),
124 debug!("ast_region_to_region(lifetime={} id={}) yields {}",
132 pub fn opt_ast_region_to_region<'tcx, AC: AstConv<'tcx>, RS: RegionScope>(
136 opt_lifetime: &Option<ast::Lifetime>) -> ty::Region
138 let r = match *opt_lifetime {
139 Some(ref lifetime) => {
140 ast_region_to_region(this.tcx(), lifetime)
144 match rscope.anon_regions(default_span, 1) {
146 debug!("optional region in illegal location");
147 span_err!(this.tcx().sess, default_span, E0106,
148 "missing lifetime specifier");
151 let mut m = String::new();
153 for (i, (name, n)) in v.into_iter().enumerate() {
154 m.push_str(if n == 1 {
155 format!("`{}`", name)
157 format!("one of `{}`'s {} elided lifetimes", name, n)
160 if len == 2 && i == 0 {
162 } else if i == len - 2 {
164 } else if i != len - 1 {
169 span_help!(this.tcx().sess, default_span,
170 "this function's return type contains a borrowed value, but \
171 the signature does not say which {} it is borrowed from",
174 span_help!(this.tcx().sess, default_span,
175 "this function's return type contains a borrowed value, but \
176 there is no value for it to be borrowed from");
177 span_help!(this.tcx().sess, default_span,
178 "consider giving it a 'static lifetime");
180 span_help!(this.tcx().sess, default_span,
181 "this function's return type contains a borrowed value, but \
182 the signature does not say whether it is borrowed from {}",
196 debug!("opt_ast_region_to_region(opt_lifetime={}) yields {}",
197 opt_lifetime.repr(this.tcx()),
203 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
204 /// returns an appropriate set of substitutions for this particular reference to `I`.
205 fn ast_path_substs_for_ty<'tcx,AC,RS>(
208 decl_def_id: ast::DefId,
209 decl_generics: &ty::Generics<'tcx>,
210 self_ty: Option<Ty<'tcx>>,
213 where AC: AstConv<'tcx>, RS: RegionScope
215 let tcx = this.tcx();
217 // ast_path_substs() is only called to convert paths that are
218 // known to refer to traits, types, or structs. In these cases,
219 // all type parameters defined for the item being referenced will
220 // be in the TypeSpace or SelfSpace.
222 // Note: in the case of traits, the self parameter is also
223 // defined, but we don't currently create a `type_param_def` for
224 // `Self` because it is implicit.
225 assert!(decl_generics.regions.all(|d| d.space == TypeSpace));
226 assert!(decl_generics.types.all(|d| d.space != FnSpace));
228 let (regions, types) = match path.segments.last().unwrap().parameters {
229 ast::AngleBracketedParameters(ref data) => {
230 convert_angle_bracketed_parameters(this, rscope, data)
232 ast::ParenthesizedParameters(ref data) => {
233 span_err!(tcx.sess, path.span, E0169,
234 "parenthesized parameters may only be used with a trait");
235 (Vec::new(), convert_parenthesized_parameters(this, data))
239 create_substs_for_ast_path(this, rscope, path.span, decl_def_id,
240 decl_generics, self_ty, types, regions)
243 fn create_substs_for_ast_path<'tcx,AC,RS>(
247 decl_def_id: ast::DefId,
248 decl_generics: &ty::Generics<'tcx>,
249 self_ty: Option<Ty<'tcx>>,
250 types: Vec<Ty<'tcx>>,
251 regions: Vec<ty::Region>)
253 where AC: AstConv<'tcx>, RS: RegionScope
255 let tcx = this.tcx();
257 // If the type is parameterized by the this region, then replace this
258 // region with the current anon region binding (in other words,
259 // whatever & would get replaced with).
260 let expected_num_region_params = decl_generics.regions.len(TypeSpace);
261 let supplied_num_region_params = regions.len();
262 let regions = if expected_num_region_params == supplied_num_region_params {
266 rscope.anon_regions(span, expected_num_region_params);
268 if supplied_num_region_params != 0 || anon_regions.is_err() {
269 span_err!(tcx.sess, span, E0107,
270 "wrong number of lifetime parameters: expected {}, found {}",
271 expected_num_region_params, supplied_num_region_params);
275 Ok(v) => v.into_iter().collect(),
276 Err(_) => Vec::from_fn(expected_num_region_params,
277 |_| ty::ReStatic) // hokey
281 // Convert the type parameters supplied by the user.
282 let ty_param_defs = decl_generics.types.get_slice(TypeSpace);
283 let supplied_ty_param_count = types.len();
284 let formal_ty_param_count =
286 .take_while(|x| !ty::is_associated_type(tcx, x.def_id))
288 let required_ty_param_count =
291 x.default.is_none() &&
292 !ty::is_associated_type(tcx, x.def_id)
295 if supplied_ty_param_count < required_ty_param_count {
296 let expected = if required_ty_param_count < formal_ty_param_count {
301 this.tcx().sess.span_fatal(span,
302 format!("wrong number of type arguments: {} {}, found {}",
304 required_ty_param_count,
305 supplied_ty_param_count).as_slice());
306 } else if supplied_ty_param_count > formal_ty_param_count {
307 let expected = if required_ty_param_count < formal_ty_param_count {
312 this.tcx().sess.span_fatal(span,
313 format!("wrong number of type arguments: {} {}, found {}",
315 formal_ty_param_count,
316 supplied_ty_param_count).as_slice());
319 if supplied_ty_param_count > required_ty_param_count
320 && !this.tcx().sess.features.borrow().default_type_params {
321 span_err!(this.tcx().sess, span, E0108,
322 "default type parameters are experimental and possibly buggy");
323 span_help!(this.tcx().sess, span,
324 "add #![feature(default_type_params)] to the crate attributes to enable");
327 let mut substs = Substs::new_type(types, regions);
331 // If no self-type is provided, it's still possible that
332 // one was declared, because this could be an object type.
335 // If a self-type is provided, one should have been
336 // "declared" (in other words, this should be a
338 assert!(decl_generics.types.get_self().is_some());
339 substs.types.push(SelfSpace, ty);
343 for param in ty_param_defs[supplied_ty_param_count..].iter() {
344 match param.default {
346 // This is a default type parameter.
347 let default = default.subst_spanned(tcx,
350 substs.types.push(TypeSpace, default);
353 tcx.sess.span_bug(span, "extra parameter without default");
358 for param in decl_generics.types.get_slice(AssocSpace).iter() {
361 this.associated_type_binding(span,
370 fn convert_angle_bracketed_parameters<'tcx, AC, RS>(this: &AC,
372 data: &ast::AngleBracketedParameterData)
373 -> (Vec<ty::Region>, Vec<Ty<'tcx>>)
374 where AC: AstConv<'tcx>, RS: RegionScope
376 let regions: Vec<_> =
377 data.lifetimes.iter()
378 .map(|l| ast_region_to_region(this.tcx(), l))
383 .map(|t| ast_ty_to_ty(this, rscope, &**t))
389 fn convert_parenthesized_parameters<'tcx,AC>(this: &AC,
390 data: &ast::ParenthesizedParameterData)
392 where AC: AstConv<'tcx>
394 let binding_rscope = BindingRscope::new();
396 let inputs = data.inputs.iter()
397 .map(|a_t| ast_ty_to_ty(this, &binding_rscope, &**a_t))
399 let input_ty = ty::mk_tup(this.tcx(), inputs);
401 let output = match data.output {
402 Some(ref output_ty) => ast_ty_to_ty(this, &binding_rscope, &**output_ty),
403 None => ty::mk_nil(this.tcx()),
406 vec![input_ty, output]
409 pub fn instantiate_poly_trait_ref<'tcx,AC,RS>(
412 ast_trait_ref: &ast::PolyTraitRef,
413 self_ty: Option<Ty<'tcx>>)
414 -> Rc<ty::TraitRef<'tcx>>
415 where AC: AstConv<'tcx>, RS: RegionScope
417 instantiate_trait_ref(this, rscope, &ast_trait_ref.trait_ref, self_ty)
420 /// Instantiates the path for the given trait reference, assuming that it's bound to a valid trait
421 /// type. Returns the def_id for the defining trait. Fails if the type is a type other than a trait
423 pub fn instantiate_trait_ref<'tcx,AC,RS>(this: &AC,
425 ast_trait_ref: &ast::TraitRef,
426 self_ty: Option<Ty<'tcx>>)
427 -> Rc<ty::TraitRef<'tcx>>
428 where AC: AstConv<'tcx>,
431 match ::lookup_def_tcx(this.tcx(),
432 ast_trait_ref.path.span,
433 ast_trait_ref.ref_id) {
434 def::DefTrait(trait_def_id) => {
435 let trait_ref = Rc::new(ast_path_to_trait_ref(this, rscope, trait_def_id,
436 self_ty, &ast_trait_ref.path));
437 this.tcx().trait_refs.borrow_mut().insert(ast_trait_ref.ref_id,
442 this.tcx().sess.span_fatal(
443 ast_trait_ref.path.span,
444 format!("`{}` is not a trait", ast_trait_ref.path.user_string(this.tcx()))[]);
449 fn ast_path_to_trait_ref<'tcx,AC,RS>(
452 trait_def_id: ast::DefId,
453 self_ty: Option<Ty<'tcx>>,
455 -> ty::TraitRef<'tcx>
456 where AC: AstConv<'tcx>, RS: RegionScope
458 let trait_def = this.get_trait_def(trait_def_id);
460 // the trait reference introduces a binding level here, so
461 // we need to shift the `rscope`. It'd be nice if we could
462 // do away with this rscope stuff and work this knowledge
463 // into resolve_lifetimes, as we do with non-omitted
464 // lifetimes. Oh well, not there yet.
465 let shifted_rscope = ShiftedRscope::new(rscope);
467 let (regions, types) = match path.segments.last().unwrap().parameters {
468 ast::AngleBracketedParameters(ref data) => {
469 convert_angle_bracketed_parameters(this, &shifted_rscope, data)
471 ast::ParenthesizedParameters(ref data) => {
472 (Vec::new(), convert_parenthesized_parameters(this, data))
476 let substs = create_substs_for_ast_path(this,
485 ty::TraitRef::new(trait_def_id, substs)
488 pub fn ast_path_to_ty<'tcx, AC: AstConv<'tcx>, RS: RegionScope>(
493 -> TypeAndSubsts<'tcx>
495 let tcx = this.tcx();
499 } = this.get_item_ty(did);
501 let substs = ast_path_substs_for_ty(this,
507 let ty = decl_ty.subst(tcx, &substs);
508 TypeAndSubsts { substs: substs, ty: ty }
511 /// Returns the type that this AST path refers to. If the path has no type
512 /// parameters and the corresponding type has type parameters, fresh type
513 /// and/or region variables are substituted.
515 /// This is used when checking the constructor in struct literals.
516 pub fn ast_path_to_ty_relaxed<'tcx,AC,RS>(
521 -> TypeAndSubsts<'tcx>
522 where AC : AstConv<'tcx>, RS : RegionScope
524 let tcx = this.tcx();
528 } = this.get_item_ty(did);
531 generics.has_type_params(TypeSpace) || generics.has_region_params(TypeSpace);
535 path.segments.iter().all(|s| s.parameters.is_empty());
537 let substs = if needs_defaults {
538 let type_params = Vec::from_fn(generics.types.len(TypeSpace),
539 |_| this.ty_infer(path.span));
541 rscope.anon_regions(path.span, generics.regions.len(TypeSpace))
543 Substs::new(VecPerParamSpace::params_from_type(type_params),
544 VecPerParamSpace::params_from_type(region_params))
546 ast_path_substs_for_ty(this, rscope, did, &generics, None, path)
549 let ty = decl_ty.subst(tcx, &substs);
556 /// Converts the given AST type to a built-in type. A "built-in type" is, at
557 /// present, either a core numeric type, a string, or `Box`.
558 pub fn ast_ty_to_builtin_ty<'tcx, AC: AstConv<'tcx>, RS: RegionScope>(
562 -> Option<Ty<'tcx>> {
563 match ast_ty_to_prim_ty(this.tcx(), ast_ty) {
564 Some(typ) => return Some(typ),
569 ast::TyPath(ref path, id) => {
570 let a_def = match this.tcx().def_map.borrow().get(&id) {
574 .span_bug(ast_ty.span,
575 format!("unbound path {}",
576 path.repr(this.tcx())).as_slice())
581 // FIXME(#12938): This is a hack until we have full support for
585 def::DefStruct(did) if Some(did) == this.tcx().lang_items.owned_box() => {
586 let ty = ast_path_to_ty(this, rscope, did, path).ty;
588 ty::ty_struct(struct_def_id, ref substs) => {
589 assert_eq!(struct_def_id, did);
590 assert_eq!(substs.types.len(TypeSpace), 1);
591 let referent_ty = *substs.types.get(TypeSpace, 0);
592 Some(ty::mk_uniq(this.tcx(), referent_ty))
595 this.tcx().sess.span_bug(
597 format!("converting `Box` to `{}`",
598 ty.repr(this.tcx()))[]);
609 fn ast_ty_to_trait_ref<'tcx,AC,RS>(this: &AC,
612 bounds: &[ast::TyParamBound])
613 -> Result<ty::TraitRef<'tcx>, ErrorReported>
614 where AC : AstConv<'tcx>, RS : RegionScope
617 * In a type like `Foo + Send`, we want to wait to collect the
618 * full set of bounds before we make the object type, because we
619 * need them to infer a region bound. (For example, if we tried
620 * made a type from just `Foo`, then it wouldn't be enough to
621 * infer a 'static bound, and hence the user would get an error.)
622 * So this function is used when we're dealing with a sum type to
623 * convert the LHS. It only accepts a type that refers to a trait
624 * name, and reports an error otherwise.
628 ast::TyPath(ref path, id) => {
629 match this.tcx().def_map.borrow().get(&id) {
630 Some(&def::DefTrait(trait_def_id)) => {
631 return Ok(ast_path_to_trait_ref(this,
638 span_err!(this.tcx().sess, ty.span, E0172, "expected a reference to a trait");
644 span_err!(this.tcx().sess, ty.span, E0171,
645 "expected a path on the left-hand side of `+`, not `{}`",
646 pprust::ty_to_string(ty));
648 ast::TyRptr(None, ref mut_ty) => {
649 span_note!(this.tcx().sess, ty.span,
650 "perhaps you meant `&{}({} +{})`? (per RFC 248)",
651 ppaux::mutability_to_string(mut_ty.mutbl),
652 pprust::ty_to_string(&*mut_ty.ty),
653 pprust::bounds_to_string(bounds));
656 ast::TyRptr(Some(ref lt), ref mut_ty) => {
657 span_note!(this.tcx().sess, ty.span,
658 "perhaps you meant `&{} {}({} +{})`? (per RFC 248)",
659 pprust::lifetime_to_string(lt),
660 ppaux::mutability_to_string(mut_ty.mutbl),
661 pprust::ty_to_string(&*mut_ty.ty),
662 pprust::bounds_to_string(bounds));
666 span_note!(this.tcx().sess, ty.span,
667 "perhaps you forgot parentheses? (per RFC 248)");
676 fn trait_ref_to_object_type<'tcx,AC,RS>(this: &AC,
679 trait_ref: ty::TraitRef<'tcx>,
680 bounds: &[ast::TyParamBound])
682 where AC : AstConv<'tcx>, RS : RegionScope
684 let existential_bounds = conv_existential_bounds(this,
687 &[Rc::new(trait_ref.clone())],
690 let result = ty::mk_trait(this.tcx(), trait_ref, existential_bounds);
691 debug!("trait_ref_to_object_type: result={}",
692 result.repr(this.tcx()));
697 fn qpath_to_ty<'tcx,AC,RS>(this: &AC,
699 ast_ty: &ast::Ty, // the TyQPath
702 where AC: AstConv<'tcx>, RS: RegionScope
704 debug!("qpath_to_ty(ast_ty={})",
705 ast_ty.repr(this.tcx()));
707 let self_type = ast_ty_to_ty(this, rscope, &*qpath.self_type);
709 debug!("qpath_to_ty: self_type={}", self_type.repr(this.tcx()));
711 let trait_ref = instantiate_trait_ref(this,
716 debug!("qpath_to_ty: trait_ref={}", trait_ref.repr(this.tcx()));
718 let trait_def = this.get_trait_def(trait_ref.def_id);
720 for ty_param_def in trait_def.generics.types.get_slice(AssocSpace).iter() {
721 if ty_param_def.name == qpath.item_name.name {
722 debug!("qpath_to_ty: corresponding ty_param_def={}", ty_param_def);
723 return trait_ref.substs.type_for_def(ty_param_def);
727 this.tcx().sess.span_bug(ast_ty.span,
728 "this associated type didn't get added \
729 as a parameter for some reason")
732 // Parses the programmer's textual representation of a type into our
733 // internal notion of a type.
734 pub fn ast_ty_to_ty<'tcx, AC: AstConv<'tcx>, RS: RegionScope>(
735 this: &AC, rscope: &RS, ast_ty: &ast::Ty) -> Ty<'tcx>
737 debug!("ast_ty_to_ty(ast_ty={})",
738 ast_ty.repr(this.tcx()));
740 let tcx = this.tcx();
742 let mut ast_ty_to_ty_cache = tcx.ast_ty_to_ty_cache.borrow_mut();
743 match ast_ty_to_ty_cache.get(&ast_ty.id) {
744 Some(&ty::atttce_resolved(ty)) => return ty,
745 Some(&ty::atttce_unresolved) => {
746 tcx.sess.span_fatal(ast_ty.span,
747 "illegal recursive type; insert an enum \
748 or struct in the cycle, if this is \
751 None => { /* go on */ }
753 ast_ty_to_ty_cache.insert(ast_ty.id, ty::atttce_unresolved);
754 drop(ast_ty_to_ty_cache);
756 let typ = ast_ty_to_builtin_ty(this, rscope, ast_ty).unwrap_or_else(|| {
758 ast::TyVec(ref ty) => {
759 ty::mk_vec(tcx, ast_ty_to_ty(this, rscope, &**ty), None)
761 ast::TyObjectSum(ref ty, ref bounds) => {
762 match ast_ty_to_trait_ref(this, rscope, &**ty, bounds.as_slice()) {
764 trait_ref_to_object_type(this, rscope, ast_ty.span,
765 trait_ref, bounds.as_slice())
767 Err(ErrorReported) => {
772 ast::TyPtr(ref mt) => {
773 ty::mk_ptr(tcx, ty::mt {
774 ty: ast_ty_to_ty(this, rscope, &*mt.ty),
778 ast::TyRptr(ref region, ref mt) => {
779 let r = opt_ast_region_to_region(this, rscope, ast_ty.span, region);
780 debug!("ty_rptr r={}", r.repr(this.tcx()));
781 let t = ast_ty_to_ty(this, rscope, &*mt.ty);
782 ty::mk_rptr(tcx, r, ty::mt {ty: t, mutbl: mt.mutbl})
784 ast::TyTup(ref fields) => {
785 let flds = fields.iter()
786 .map(|t| ast_ty_to_ty(this, rscope, &**t))
788 ty::mk_tup(tcx, flds)
790 ast::TyParen(ref typ) => ast_ty_to_ty(this, rscope, &**typ),
791 ast::TyBareFn(ref bf) => {
792 if bf.decl.variadic && bf.abi != abi::C {
793 tcx.sess.span_err(ast_ty.span,
794 "variadic function must have C calling convention");
796 ty::mk_bare_fn(tcx, ty_of_bare_fn(this, bf.fn_style, bf.abi, &*bf.decl))
798 ast::TyClosure(ref f) => {
799 // Use corresponding trait store to figure out default bounds
800 // if none were specified.
801 let bounds = conv_existential_bounds(this,
805 f.bounds.as_slice());
806 let fn_decl = ty_of_closure(this,
810 ty::RegionTraitStore(
816 ty::mk_closure(tcx, fn_decl)
818 ast::TyProc(ref f) => {
819 // Use corresponding trait store to figure out default bounds
820 // if none were specified.
821 let bounds = conv_existential_bounds(this, rscope,
824 f.bounds.as_slice());
826 let fn_decl = ty_of_closure(this,
835 ty::mk_closure(tcx, fn_decl)
837 ast::TyPolyTraitRef(ref bounds) => {
838 conv_ty_poly_trait_ref(this, rscope, ast_ty.span, bounds.as_slice())
840 ast::TyPath(ref path, id) => {
841 let a_def = match tcx.def_map.borrow().get(&id) {
844 .span_bug(ast_ty.span,
845 format!("unbound path {}",
846 path.repr(tcx)).as_slice())
851 def::DefTrait(trait_def_id) => {
852 // N.B. this case overlaps somewhat with
853 // TyObjectSum, see that fn for details
854 let result = ast_path_to_trait_ref(this,
859 trait_ref_to_object_type(this, rscope, path.span, result, &[])
861 def::DefTy(did, _) | def::DefStruct(did) => {
862 ast_path_to_ty(this, rscope, did, path).ty
864 def::DefTyParam(space, id, n) => {
865 check_path_args(tcx, path, NO_TPS | NO_REGIONS);
866 ty::mk_param(tcx, space, n, id)
868 def::DefSelfTy(id) => {
869 // n.b.: resolve guarantees that the this type only appears in a
870 // trait, which we rely upon in various places when creating
872 check_path_args(tcx, path, NO_TPS | NO_REGIONS);
873 let did = ast_util::local_def(id);
874 ty::mk_self_type(tcx, did)
877 tcx.sess.span_fatal(ast_ty.span,
878 format!("found module name used as a type: {}",
879 tcx.map.node_to_string(id.node)).as_slice());
881 def::DefPrimTy(_) => {
882 panic!("DefPrimTy arm missed in previous ast_ty_to_prim_ty call");
884 def::DefAssociatedTy(trait_type_id) => {
885 let path_str = tcx.map.path_to_string(
886 tcx.map.get_parent(trait_type_id.node));
887 tcx.sess.span_err(ast_ty.span,
888 format!("ambiguous associated \
889 type; specify the type \
890 using the syntax `<Type \
902 tcx.sess.span_fatal(ast_ty.span,
903 format!("found value name used \
909 ast::TyQPath(ref qpath) => {
910 qpath_to_ty(this, rscope, ast_ty, &**qpath)
912 ast::TyFixedLengthVec(ref ty, ref e) => {
913 match const_eval::eval_const_expr_partial(tcx, &**e) {
916 const_eval::const_int(i) =>
917 ty::mk_vec(tcx, ast_ty_to_ty(this, rscope, &**ty),
919 const_eval::const_uint(i) =>
920 ty::mk_vec(tcx, ast_ty_to_ty(this, rscope, &**ty),
924 ast_ty.span, "expected constant expr for array length");
931 format!("expected constant expr for array \
937 ast::TyTypeof(ref _e) => {
938 tcx.sess.span_bug(ast_ty.span, "typeof is reserved but unimplemented");
941 // TyInfer also appears as the type of arguments or return
942 // values in a ExprClosure or ExprProc, or as
943 // the type of local variables. Both of these cases are
944 // handled specially and will not descend into this routine.
945 this.ty_infer(ast_ty.span)
950 tcx.ast_ty_to_ty_cache.borrow_mut().insert(ast_ty.id, ty::atttce_resolved(typ));
954 pub fn ty_of_arg<'tcx, AC: AstConv<'tcx>, RS: RegionScope>(this: &AC, rscope: &RS,
956 expected_ty: Option<Ty<'tcx>>)
959 ast::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
960 ast::TyInfer => this.ty_infer(a.ty.span),
961 _ => ast_ty_to_ty(this, rscope, &*a.ty),
965 struct SelfInfo<'a, 'tcx> {
966 untransformed_self_ty: Ty<'tcx>,
967 explicit_self: &'a ast::ExplicitSelf,
970 pub fn ty_of_method<'tcx, AC: AstConv<'tcx>>(
972 fn_style: ast::FnStyle,
973 untransformed_self_ty: Ty<'tcx>,
974 explicit_self: &ast::ExplicitSelf,
977 -> (ty::BareFnTy<'tcx>, ty::ExplicitSelfCategory) {
978 let self_info = Some(SelfInfo {
979 untransformed_self_ty: untransformed_self_ty,
980 explicit_self: explicit_self,
982 let (bare_fn_ty, optional_explicit_self_category) =
983 ty_of_method_or_bare_fn(this,
988 (bare_fn_ty, optional_explicit_self_category.unwrap())
991 pub fn ty_of_bare_fn<'tcx, AC: AstConv<'tcx>>(this: &AC, fn_style: ast::FnStyle, abi: abi::Abi,
992 decl: &ast::FnDecl) -> ty::BareFnTy<'tcx> {
993 let (bare_fn_ty, _) = ty_of_method_or_bare_fn(this, fn_style, abi, None, decl);
997 fn ty_of_method_or_bare_fn<'a, 'tcx, AC: AstConv<'tcx>>(
999 fn_style: ast::FnStyle,
1001 opt_self_info: Option<SelfInfo<'a, 'tcx>>,
1003 -> (ty::BareFnTy<'tcx>,
1004 Option<ty::ExplicitSelfCategory>) {
1005 debug!("ty_of_method_or_bare_fn");
1007 // New region names that appear inside of the arguments of the function
1008 // declaration are bound to that function type.
1009 let rb = rscope::BindingRscope::new();
1011 // `implied_output_region` is the region that will be assumed for any
1012 // region parameters in the return type. In accordance with the rules for
1013 // lifetime elision, we can determine it in two ways. First (determined
1014 // here), if self is by-reference, then the implied output region is the
1015 // region of the self parameter.
1016 let mut explicit_self_category_result = None;
1017 let (self_ty, mut implied_output_region) = match opt_self_info {
1018 None => (None, None),
1019 Some(self_info) => {
1020 // Figure out and record the explicit self category.
1021 let explicit_self_category =
1022 determine_explicit_self_category(this, &rb, &self_info);
1023 explicit_self_category_result = Some(explicit_self_category);
1024 match explicit_self_category {
1025 ty::StaticExplicitSelfCategory => {
1028 ty::ByValueExplicitSelfCategory => {
1029 (Some(self_info.untransformed_self_ty), None)
1031 ty::ByReferenceExplicitSelfCategory(region, mutability) => {
1032 (Some(ty::mk_rptr(this.tcx(),
1035 ty: self_info.untransformed_self_ty,
1040 ty::ByBoxExplicitSelfCategory => {
1041 (Some(ty::mk_uniq(this.tcx(),
1042 self_info.untransformed_self_ty)),
1049 // HACK(eddyb) replace the fake self type in the AST with the actual type.
1050 let input_params = if self_ty.is_some() {
1051 decl.inputs.slice_from(1)
1053 decl.inputs.as_slice()
1055 let input_tys = input_params.iter().map(|a| ty_of_arg(this, &rb, a, None));
1056 let input_pats: Vec<String> = input_params.iter()
1057 .map(|a| pprust::pat_to_string(&*a.pat))
1059 let self_and_input_tys: Vec<Ty> =
1060 self_ty.into_iter().chain(input_tys).collect();
1062 let mut lifetimes_for_params: Vec<(String, Vec<ty::Region>)> = Vec::new();
1064 // Second, if there was exactly one lifetime (either a substitution or a
1065 // reference) in the arguments, then any anonymous regions in the output
1066 // have that lifetime.
1067 if implied_output_region.is_none() {
1068 let mut self_and_input_tys_iter = self_and_input_tys.iter();
1069 if self_ty.is_some() {
1070 // Skip the first argument if `self` is present.
1071 drop(self_and_input_tys_iter.next())
1074 for (input_type, input_pat) in self_and_input_tys_iter.zip(input_pats.into_iter()) {
1075 let mut accumulator = Vec::new();
1076 ty::accumulate_lifetimes_in_type(&mut accumulator, *input_type);
1077 lifetimes_for_params.push((input_pat, accumulator));
1080 if lifetimes_for_params.iter().map(|&(_, ref x)| x.len()).sum() == 1 {
1081 implied_output_region =
1082 Some(lifetimes_for_params.iter()
1083 .filter_map(|&(_, ref x)|
1084 if x.len() == 1 { Some(x[0]) } else { None })
1089 let param_lifetimes: Vec<(String, uint)> = lifetimes_for_params.into_iter()
1090 .map(|(n, v)| (n, v.len()))
1091 .filter(|&(_, l)| l != 0)
1094 let output_ty = match decl.output {
1095 ast::Return(ref output) if output.node == ast::TyInfer =>
1096 ty::FnConverging(this.ty_infer(output.span)),
1097 ast::Return(ref output) =>
1098 ty::FnConverging(match implied_output_region {
1099 Some(implied_output_region) => {
1100 let rb = SpecificRscope::new(implied_output_region);
1101 ast_ty_to_ty(this, &rb, &**output)
1104 // All regions must be explicitly specified in the output
1105 // if the lifetime elision rules do not apply. This saves
1106 // the user from potentially-confusing errors.
1107 let rb = UnelidableRscope::new(param_lifetimes);
1108 ast_ty_to_ty(this, &rb, &**output)
1111 ast::NoReturn(_) => ty::FnDiverging
1118 inputs: self_and_input_tys,
1120 variadic: decl.variadic
1122 }, explicit_self_category_result)
1125 fn determine_explicit_self_category<'a, 'tcx, AC: AstConv<'tcx>,
1129 self_info: &SelfInfo<'a, 'tcx>)
1130 -> ty::ExplicitSelfCategory
1132 return match self_info.explicit_self.node {
1133 ast::SelfStatic => ty::StaticExplicitSelfCategory,
1134 ast::SelfValue(_) => ty::ByValueExplicitSelfCategory,
1135 ast::SelfRegion(ref lifetime, mutability, _) => {
1137 opt_ast_region_to_region(this,
1139 self_info.explicit_self.span,
1141 ty::ByReferenceExplicitSelfCategory(region, mutability)
1143 ast::SelfExplicit(ref ast_type, _) => {
1144 let explicit_type = ast_ty_to_ty(this, rscope, &**ast_type);
1146 // We wish to (for now) categorize an explicit self
1147 // declaration like `self: SomeType` into either `self`,
1148 // `&self`, `&mut self`, or `Box<self>`. We do this here
1149 // by some simple pattern matching. A more precise check
1150 // is done later in `check_method_self_type()`.
1155 // impl Foo for &T {
1156 // // Legal declarations:
1157 // fn method1(self: &&T); // ByReferenceExplicitSelfCategory
1158 // fn method2(self: &T); // ByValueExplicitSelfCategory
1159 // fn method3(self: Box<&T>); // ByBoxExplicitSelfCategory
1161 // // Invalid cases will be caught later by `check_method_self_type`:
1162 // fn method_err1(self: &mut T); // ByReferenceExplicitSelfCategory
1166 // To do the check we just count the number of "modifiers"
1167 // on each type and compare them. If they are the same or
1168 // the impl has more, we call it "by value". Otherwise, we
1169 // look at the outermost modifier on the method decl and
1170 // call it by-ref, by-box as appropriate. For method1, for
1171 // example, the impl type has one modifier, but the method
1172 // type has two, so we end up with
1173 // ByReferenceExplicitSelfCategory.
1175 let impl_modifiers = count_modifiers(self_info.untransformed_self_ty);
1176 let method_modifiers = count_modifiers(explicit_type);
1178 debug!("determine_explicit_self_category(self_info.untransformed_self_ty={} \
1181 self_info.untransformed_self_ty.repr(this.tcx()),
1182 explicit_type.repr(this.tcx()),
1186 if impl_modifiers >= method_modifiers {
1187 ty::ByValueExplicitSelfCategory
1189 match explicit_type.sty {
1190 ty::ty_rptr(r, mt) => ty::ByReferenceExplicitSelfCategory(r, mt.mutbl),
1191 ty::ty_uniq(_) => ty::ByBoxExplicitSelfCategory,
1192 _ => ty::ByValueExplicitSelfCategory,
1198 fn count_modifiers(ty: Ty) -> uint {
1200 ty::ty_rptr(_, mt) => count_modifiers(mt.ty) + 1,
1201 ty::ty_uniq(t) => count_modifiers(t) + 1,
1207 pub fn ty_of_closure<'tcx, AC: AstConv<'tcx>>(
1209 fn_style: ast::FnStyle,
1210 onceness: ast::Onceness,
1211 bounds: ty::ExistentialBounds,
1212 store: ty::TraitStore,
1215 expected_sig: Option<ty::FnSig<'tcx>>)
1216 -> ty::ClosureTy<'tcx>
1218 debug!("ty_of_closure(expected_sig={})",
1219 expected_sig.repr(this.tcx()));
1221 // new region names that appear inside of the fn decl are bound to
1222 // that function type
1223 let rb = rscope::BindingRscope::new();
1225 let input_tys: Vec<_> = decl.inputs.iter().enumerate().map(|(i, a)| {
1226 let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1227 // no guarantee that the correct number of expected args
1229 if i < e.inputs.len() {
1235 ty_of_arg(this, &rb, a, expected_arg_ty)
1238 let expected_ret_ty = expected_sig.map(|e| e.output);
1240 let output_ty = match decl.output {
1241 ast::Return(ref output) if output.node == ast::TyInfer && expected_ret_ty.is_some() =>
1242 expected_ret_ty.unwrap(),
1243 ast::Return(ref output) if output.node == ast::TyInfer =>
1244 ty::FnConverging(this.ty_infer(output.span)),
1245 ast::Return(ref output) =>
1246 ty::FnConverging(ast_ty_to_ty(this, &rb, &**output)),
1247 ast::NoReturn(_) => ty::FnDiverging
1250 debug!("ty_of_closure: input_tys={}", input_tys.repr(this.tcx()));
1251 debug!("ty_of_closure: output_ty={}", output_ty.repr(this.tcx()));
1259 sig: ty::FnSig {inputs: input_tys,
1261 variadic: decl.variadic}
1265 /// Given an existential type like `Foo+'a+Bar`, this routine converts the `'a` and `Bar` intos an
1266 /// `ExistentialBounds` struct. The `main_trait_refs` argument specifies the `Foo` -- it is absent
1267 /// for closures. Eventually this should all be normalized, I think, so that there is no "main
1268 /// trait ref" and instead we just have a flat list of bounds as the existential type.
1269 pub fn conv_existential_bounds<'tcx, AC: AstConv<'tcx>, RS:RegionScope>(
1273 main_trait_refs: &[Rc<ty::TraitRef<'tcx>>],
1274 ast_bounds: &[ast::TyParamBound])
1275 -> ty::ExistentialBounds
1277 let ast_bound_refs: Vec<&ast::TyParamBound> =
1278 ast_bounds.iter().collect();
1280 let partitioned_bounds =
1281 partition_bounds(this.tcx(), span, ast_bound_refs.as_slice());
1283 conv_existential_bounds_from_partitioned_bounds(
1284 this, rscope, span, main_trait_refs, partitioned_bounds)
1287 fn conv_ty_poly_trait_ref<'tcx, AC, RS>(
1291 ast_bounds: &[ast::TyParamBound])
1293 where AC: AstConv<'tcx>, RS:RegionScope
1295 let ast_bounds: Vec<&ast::TyParamBound> = ast_bounds.iter().collect();
1296 let mut partitioned_bounds = partition_bounds(this.tcx(), span, ast_bounds[]);
1298 let main_trait_bound = match partitioned_bounds.trait_bounds.remove(0) {
1299 Some(trait_bound) => {
1300 Some(instantiate_poly_trait_ref(this, rscope, trait_bound, None))
1303 this.tcx().sess.span_err(
1305 "at least one non-builtin trait is required for an object type");
1310 let bounds = conv_existential_bounds_from_partitioned_bounds(this,
1313 main_trait_bound.as_slice(),
1314 partitioned_bounds);
1316 match main_trait_bound {
1317 None => ty::mk_err(),
1318 Some(principal) => ty::mk_trait(this.tcx(), (*principal).clone(), bounds)
1322 pub fn conv_existential_bounds_from_partitioned_bounds<'tcx, AC, RS>(
1326 main_trait_refs: &[Rc<ty::TraitRef<'tcx>>],
1327 partitioned_bounds: PartitionedBounds)
1328 -> ty::ExistentialBounds
1329 where AC: AstConv<'tcx>, RS:RegionScope
1331 let PartitionedBounds { builtin_bounds,
1336 if !trait_bounds.is_empty() {
1337 let b = &trait_bounds[0];
1338 this.tcx().sess.span_err(
1339 b.trait_ref.path.span,
1340 format!("only the builtin traits can be used \
1341 as closure or object bounds").as_slice());
1344 // The "main trait refs", rather annoyingly, have no type
1345 // specified for the `Self` parameter of the trait. The reason for
1346 // this is that they are, after all, *existential* types, and
1347 // hence that type is unknown. However, leaving this type missing
1348 // causes the substitution code to go all awry when walking the
1349 // bounds, so here we clone those trait refs and insert ty::err as
1350 // the self type. Perhaps we should do this more generally, it'd
1351 // be convenient (or perhaps something else, i.e., ty::erased).
1352 let main_trait_refs: Vec<Rc<ty::TraitRef>> =
1353 main_trait_refs.iter()
1355 Rc::new(ty::TraitRef {
1357 substs: t.substs.with_self_ty(ty::mk_err()) }))
1360 let region_bound = compute_region_bound(this,
1364 region_bounds.as_slice(),
1365 main_trait_refs.as_slice());
1367 ty::ExistentialBounds {
1368 region_bound: region_bound,
1369 builtin_bounds: builtin_bounds,
1373 /// Given the bounds on a type parameter / existential type, determines what single region bound
1374 /// (if any) we can use to summarize this type. The basic idea is that we will use the bound the
1375 /// user provided, if they provided one, and otherwise search the supertypes of trait bounds for
1376 /// region bounds. It may be that we can derive no bound at all, in which case we return `None`.
1377 pub fn compute_opt_region_bound<'tcx>(tcx: &ty::ctxt<'tcx>,
1379 builtin_bounds: ty::BuiltinBounds,
1380 region_bounds: &[&ast::Lifetime],
1381 trait_bounds: &[Rc<ty::TraitRef<'tcx>>])
1382 -> Option<ty::Region>
1384 if region_bounds.len() > 1 {
1386 region_bounds[1].span,
1387 format!("only a single explicit lifetime bound is permitted").as_slice());
1390 if region_bounds.len() != 0 {
1391 // Explicitly specified region bound. Use that.
1392 let r = region_bounds[0];
1393 return Some(ast_region_to_region(tcx, r));
1396 // No explicit region bound specified. Therefore, examine trait
1397 // bounds and see if we can derive region bounds from those.
1398 let derived_region_bounds =
1399 ty::required_region_bounds(
1405 // If there are no derived region bounds, then report back that we
1406 // can find no region bound.
1407 if derived_region_bounds.len() == 0 {
1411 // If any of the derived region bounds are 'static, that is always
1413 if derived_region_bounds.iter().any(|r| ty::ReStatic == *r) {
1414 return Some(ty::ReStatic);
1417 // Determine whether there is exactly one unique region in the set
1418 // of derived region bounds. If so, use that. Otherwise, report an
1420 let r = derived_region_bounds[0];
1421 if derived_region_bounds.slice_from(1).iter().any(|r1| r != *r1) {
1424 format!("ambiguous lifetime bound, \
1425 explicit lifetime bound required").as_slice());
1430 /// A version of `compute_opt_region_bound` for use where some region bound is required
1431 /// (existential types, basically). Reports an error if no region bound can be derived and we are
1432 /// in an `rscope` that does not provide a default.
1433 fn compute_region_bound<'tcx, AC: AstConv<'tcx>, RS:RegionScope>(
1437 builtin_bounds: ty::BuiltinBounds,
1438 region_bounds: &[&ast::Lifetime],
1439 trait_bounds: &[Rc<ty::TraitRef<'tcx>>])
1442 match compute_opt_region_bound(this.tcx(), span, builtin_bounds,
1443 region_bounds, trait_bounds) {
1446 match rscope.default_region_bound(span) {
1449 this.tcx().sess.span_err(
1451 format!("explicit lifetime bound required").as_slice());
1459 pub struct PartitionedBounds<'a> {
1460 pub builtin_bounds: ty::BuiltinBounds,
1461 pub trait_bounds: Vec<&'a ast::PolyTraitRef>,
1462 pub region_bounds: Vec<&'a ast::Lifetime>,
1465 /// Divides a list of bounds from the AST into three groups: builtin bounds (Copy, Sized etc),
1466 /// general trait bounds, and region bounds.
1467 pub fn partition_bounds<'a>(tcx: &ty::ctxt,
1469 ast_bounds: &'a [&ast::TyParamBound])
1470 -> PartitionedBounds<'a>
1472 let mut builtin_bounds = ty::empty_builtin_bounds();
1473 let mut region_bounds = Vec::new();
1474 let mut trait_bounds = Vec::new();
1475 let mut trait_def_ids = DefIdMap::new();
1476 for &ast_bound in ast_bounds.iter() {
1478 ast::TraitTyParamBound(ref b) => {
1479 match ::lookup_def_tcx(tcx, b.trait_ref.path.span, b.trait_ref.ref_id) {
1480 def::DefTrait(trait_did) => {
1481 match trait_def_ids.get(&trait_did) {
1482 // Already seen this trait. We forbid
1483 // duplicates in the list (for some
1487 tcx.sess, b.trait_ref.path.span, E0127,
1488 "trait `{}` already appears in the \
1490 b.trait_ref.path.user_string(tcx));
1493 "previous appearance is here");
1501 trait_def_ids.insert(trait_did, b.trait_ref.path.span);
1503 if ty::try_add_builtin_trait(tcx,
1505 &mut builtin_bounds) {
1506 continue; // success
1510 // Not a trait? that's an error, but it'll get
1514 trait_bounds.push(b);
1516 ast::RegionTyParamBound(ref l) => {
1517 region_bounds.push(l);
1523 builtin_bounds: builtin_bounds,
1524 trait_bounds: trait_bounds,
1525 region_bounds: region_bounds,