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_type_scheme()` 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_type_scheme()` 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, SelfSpace, Subst, Substs};
56 use middle::ty::{self, RegionEscape, ToPolyTraitRef, Ty};
57 use rscope::{self, UnelidableRscope, RegionScope, SpecificRscope,
58 ShiftedRscope, BindingRscope};
60 use util::common::ErrorReported;
61 use util::nodemap::DefIdMap;
62 use util::ppaux::{self, Repr, UserString};
65 use std::iter::{repeat, 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>;
74 fn get_item_type_scheme(&self, id: ast::DefId) -> ty::TypeScheme<'tcx>;
76 fn get_trait_def(&self, id: ast::DefId) -> Rc<ty::TraitDef<'tcx>>;
78 /// Return an (optional) substitution to convert bound type parameters that
79 /// are in scope into free ones. This function should only return Some
81 /// See ParameterEnvironment::free_substs for more information.
82 fn get_free_substs(&self) -> Option<&Substs<'tcx>> {
86 /// What type should we use when a type is omitted?
87 fn ty_infer(&self, span: Span) -> Ty<'tcx>;
89 /// Projecting an associated type from a (potentially)
90 /// higher-ranked trait reference is more complicated, because of
91 /// the possibility of late-bound regions appearing in the
92 /// associated type binding. This is not legal in function
93 /// signatures for that reason. In a function body, we can always
94 /// handle it because we can use inference variables to remove the
95 /// late-bound regions.
96 fn projected_ty_from_poly_trait_ref(&self,
98 poly_trait_ref: ty::PolyTraitRef<'tcx>,
102 if ty::binds_late_bound_regions(self.tcx(), &poly_trait_ref) {
103 self.tcx().sess.span_err(
105 "cannot extract an associated type from a higher-ranked trait bound \
109 // no late-bound regions, we can just ignore the binder
110 self.projected_ty(span, poly_trait_ref.0.clone(), item_name)
114 /// Project an associated type from a non-higher-ranked trait reference.
115 /// This is fairly straightforward and can be accommodated in any context.
116 fn projected_ty(&self,
118 _trait_ref: Rc<ty::TraitRef<'tcx>>,
119 _item_name: ast::Name)
122 self.tcx().sess.span_err(
124 "associated types are not accepted in this context");
130 pub fn ast_region_to_region(tcx: &ty::ctxt, lifetime: &ast::Lifetime)
132 let r = match tcx.named_region_map.get(&lifetime.id) {
134 // should have been recorded by the `resolve_lifetime` pass
135 tcx.sess.span_bug(lifetime.span, "unresolved lifetime");
138 Some(&rl::DefStaticRegion) => {
142 Some(&rl::DefLateBoundRegion(debruijn, id)) => {
143 ty::ReLateBound(debruijn, ty::BrNamed(ast_util::local_def(id), lifetime.name))
146 Some(&rl::DefEarlyBoundRegion(space, index, id)) => {
147 ty::ReEarlyBound(id, space, index, lifetime.name)
150 Some(&rl::DefFreeRegion(scope, id)) => {
151 ty::ReFree(ty::FreeRegion {
153 bound_region: ty::BrNamed(ast_util::local_def(id),
159 debug!("ast_region_to_region(lifetime={} id={}) yields {}",
167 pub fn opt_ast_region_to_region<'tcx>(
168 this: &AstConv<'tcx>,
169 rscope: &RegionScope,
171 opt_lifetime: &Option<ast::Lifetime>) -> ty::Region
173 let r = match *opt_lifetime {
174 Some(ref lifetime) => {
175 ast_region_to_region(this.tcx(), lifetime)
179 match rscope.anon_regions(default_span, 1) {
181 debug!("optional region in illegal location");
182 span_err!(this.tcx().sess, default_span, E0106,
183 "missing lifetime specifier");
186 let mut m = String::new();
188 for (i, (name, n)) in v.into_iter().enumerate() {
189 let help_name = if name.is_empty() {
190 format!("argument {}", i + 1)
192 format!("`{}`", name)
195 m.push_str(&(if n == 1 {
198 format!("one of {}'s {} elided lifetimes", help_name, n)
201 if len == 2 && i == 0 {
203 } else if i == len - 2 {
205 } else if i != len - 1 {
210 span_help!(this.tcx().sess, default_span,
211 "this function's return type contains a borrowed value, but \
212 the signature does not say which {} it is borrowed from",
215 span_help!(this.tcx().sess, default_span,
216 "this function's return type contains a borrowed value, but \
217 there is no value for it to be borrowed from");
218 span_help!(this.tcx().sess, default_span,
219 "consider giving it a 'static lifetime");
221 span_help!(this.tcx().sess, default_span,
222 "this function's return type contains a borrowed value, but \
223 the signature does not say whether it is borrowed from {}",
237 debug!("opt_ast_region_to_region(opt_lifetime={}) yields {}",
238 opt_lifetime.repr(this.tcx()),
244 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
245 /// returns an appropriate set of substitutions for this particular reference to `I`.
246 pub fn ast_path_substs_for_ty<'tcx>(
247 this: &AstConv<'tcx>,
248 rscope: &RegionScope,
249 decl_generics: &ty::Generics<'tcx>,
253 let tcx = this.tcx();
255 // ast_path_substs() is only called to convert paths that are
256 // known to refer to traits, types, or structs. In these cases,
257 // all type parameters defined for the item being referenced will
258 // be in the TypeSpace or SelfSpace.
260 // Note: in the case of traits, the self parameter is also
261 // defined, but we don't currently create a `type_param_def` for
262 // `Self` because it is implicit.
263 assert!(decl_generics.regions.all(|d| d.space == TypeSpace));
264 assert!(decl_generics.types.all(|d| d.space != FnSpace));
266 let (regions, types, assoc_bindings) = match path.segments.last().unwrap().parameters {
267 ast::AngleBracketedParameters(ref data) => {
268 convert_angle_bracketed_parameters(this, rscope, data)
270 ast::ParenthesizedParameters(ref data) => {
273 "parenthesized parameters may only be used with a trait");
274 (Vec::new(), convert_parenthesized_parameters(this, data), Vec::new())
278 prohibit_projections(this.tcx(), assoc_bindings.as_slice());
280 create_substs_for_ast_path(this,
289 fn create_substs_for_ast_path<'tcx>(
290 this: &AstConv<'tcx>,
291 rscope: &RegionScope,
293 decl_generics: &ty::Generics<'tcx>,
294 self_ty: Option<Ty<'tcx>>,
295 types: Vec<Ty<'tcx>>,
296 regions: Vec<ty::Region>)
299 let tcx = this.tcx();
301 // If the type is parameterized by the this region, then replace this
302 // region with the current anon region binding (in other words,
303 // whatever & would get replaced with).
304 let expected_num_region_params = decl_generics.regions.len(TypeSpace);
305 let supplied_num_region_params = regions.len();
306 let regions = if expected_num_region_params == supplied_num_region_params {
310 rscope.anon_regions(span, expected_num_region_params);
312 if supplied_num_region_params != 0 || anon_regions.is_err() {
313 span_err!(tcx.sess, span, E0107,
314 "wrong number of lifetime parameters: expected {}, found {}",
315 expected_num_region_params, supplied_num_region_params);
319 Ok(v) => v.into_iter().collect(),
320 Err(_) => range(0, expected_num_region_params)
321 .map(|_| ty::ReStatic).collect() // hokey
325 // Convert the type parameters supplied by the user.
326 let ty_param_defs = decl_generics.types.get_slice(TypeSpace);
327 let supplied_ty_param_count = types.len();
328 let formal_ty_param_count =
330 .take_while(|x| !ty::is_associated_type(tcx, x.def_id))
332 let required_ty_param_count =
335 x.default.is_none() &&
336 !ty::is_associated_type(tcx, x.def_id)
339 if supplied_ty_param_count < required_ty_param_count {
340 let expected = if required_ty_param_count < formal_ty_param_count {
345 this.tcx().sess.span_fatal(span,
346 &format!("wrong number of type arguments: {} {}, found {}",
348 required_ty_param_count,
349 supplied_ty_param_count)[]);
350 } else if supplied_ty_param_count > formal_ty_param_count {
351 let expected = if required_ty_param_count < formal_ty_param_count {
356 this.tcx().sess.span_fatal(span,
357 &format!("wrong number of type arguments: {} {}, found {}",
359 formal_ty_param_count,
360 supplied_ty_param_count)[]);
363 let mut substs = Substs::new_type(types, regions);
367 // If no self-type is provided, it's still possible that
368 // one was declared, because this could be an object type.
371 // If a self-type is provided, one should have been
372 // "declared" (in other words, this should be a
374 assert!(decl_generics.types.get_self().is_some());
375 substs.types.push(SelfSpace, ty);
379 for param in ty_param_defs[supplied_ty_param_count..].iter() {
380 match param.default {
382 // This is a default type parameter.
383 let default = default.subst_spanned(tcx,
386 substs.types.push(TypeSpace, default);
389 tcx.sess.span_bug(span, "extra parameter without default");
397 struct ConvertedBinding<'tcx> {
398 item_name: ast::Name,
403 fn convert_angle_bracketed_parameters<'tcx>(this: &AstConv<'tcx>,
404 rscope: &RegionScope,
405 data: &ast::AngleBracketedParameterData)
408 Vec<ConvertedBinding<'tcx>>)
410 let regions: Vec<_> =
411 data.lifetimes.iter()
412 .map(|l| ast_region_to_region(this.tcx(), l))
417 .map(|t| ast_ty_to_ty(this, rscope, &**t))
420 let assoc_bindings: Vec<_> =
422 .map(|b| ConvertedBinding { item_name: b.ident.name,
423 ty: ast_ty_to_ty(this, rscope, &*b.ty),
427 (regions, types, assoc_bindings)
430 /// Returns the appropriate lifetime to use for any output lifetimes
431 /// (if one exists) and a vector of the (pattern, number of lifetimes)
432 /// corresponding to each input type/pattern.
433 fn find_implied_output_region(input_tys: &[Ty], input_pats: Vec<String>)
434 -> (Option<ty::Region>, Vec<(String, uint)>)
436 let mut lifetimes_for_params: Vec<(String, uint)> = Vec::new();
437 let mut possible_implied_output_region = None;
439 for (input_type, input_pat) in input_tys.iter().zip(input_pats.into_iter()) {
440 let mut accumulator = Vec::new();
441 ty::accumulate_lifetimes_in_type(&mut accumulator, *input_type);
443 if accumulator.len() == 1 {
444 // there's a chance that the unique lifetime of this
445 // iteration will be the appropriate lifetime for output
446 // parameters, so lets store it.
447 possible_implied_output_region = Some(accumulator[0])
450 lifetimes_for_params.push((input_pat, accumulator.len()));
453 let implied_output_region = if lifetimes_for_params.iter().map(|&(_, n)| n).sum() == 1 {
454 assert!(possible_implied_output_region.is_some());
455 possible_implied_output_region
459 (implied_output_region, lifetimes_for_params)
462 fn convert_ty_with_lifetime_elision<'tcx>(this: &AstConv<'tcx>,
463 implied_output_region: Option<ty::Region>,
464 param_lifetimes: Vec<(String, uint)>,
468 match implied_output_region {
469 Some(implied_output_region) => {
470 let rb = SpecificRscope::new(implied_output_region);
471 ast_ty_to_ty(this, &rb, ty)
474 // All regions must be explicitly specified in the output
475 // if the lifetime elision rules do not apply. This saves
476 // the user from potentially-confusing errors.
477 let rb = UnelidableRscope::new(param_lifetimes);
478 ast_ty_to_ty(this, &rb, ty)
483 fn convert_parenthesized_parameters<'tcx>(this: &AstConv<'tcx>,
484 data: &ast::ParenthesizedParameterData)
487 let binding_rscope = BindingRscope::new();
488 let inputs = data.inputs.iter()
489 .map(|a_t| ast_ty_to_ty(this, &binding_rscope, &**a_t))
490 .collect::<Vec<Ty<'tcx>>>();
492 let input_params: Vec<_> = repeat(String::new()).take(inputs.len()).collect();
493 let (implied_output_region,
494 params_lifetimes) = find_implied_output_region(&*inputs, input_params);
496 let input_ty = ty::mk_tup(this.tcx(), inputs);
498 let output = match data.output {
499 Some(ref output_ty) => convert_ty_with_lifetime_elision(this,
500 implied_output_region,
503 None => ty::mk_nil(this.tcx()),
506 vec![input_ty, output]
509 pub fn instantiate_poly_trait_ref<'tcx>(
510 this: &AstConv<'tcx>,
511 rscope: &RegionScope,
512 ast_trait_ref: &ast::PolyTraitRef,
513 self_ty: Option<Ty<'tcx>>,
514 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
515 -> ty::PolyTraitRef<'tcx>
517 let mut projections = Vec::new();
520 instantiate_trait_ref(this, rscope, &ast_trait_ref.trait_ref,
521 self_ty, Some(&mut projections));
523 for projection in projections.into_iter() {
524 poly_projections.push(ty::Binder(projection));
527 ty::Binder(trait_ref)
530 /// Instantiates the path for the given trait reference, assuming that it's
531 /// bound to a valid trait type. Returns the def_id for the defining trait.
532 /// Fails if the type is a type other than a trait type.
534 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
535 /// are disallowed. Otherwise, they are pushed onto the vector given.
536 pub fn instantiate_trait_ref<'tcx>(
537 this: &AstConv<'tcx>,
538 rscope: &RegionScope,
539 ast_trait_ref: &ast::TraitRef,
540 self_ty: Option<Ty<'tcx>>,
541 projections: Option<&mut Vec<ty::ProjectionPredicate<'tcx>>>)
542 -> Rc<ty::TraitRef<'tcx>>
544 match ::lookup_def_tcx(this.tcx(), ast_trait_ref.path.span, ast_trait_ref.ref_id) {
545 def::DefTrait(trait_def_id) => {
546 let trait_ref = ast_path_to_trait_ref(this,
552 this.tcx().trait_refs.borrow_mut().insert(ast_trait_ref.ref_id, trait_ref.clone());
556 this.tcx().sess.span_fatal(
557 ast_trait_ref.path.span,
558 &format!("`{}` is not a trait",
559 ast_trait_ref.path.user_string(this.tcx()))[]);
564 fn ast_path_to_trait_ref<'a,'tcx>(
565 this: &AstConv<'tcx>,
566 rscope: &RegionScope,
567 trait_def_id: ast::DefId,
568 self_ty: Option<Ty<'tcx>>,
570 mut projections: Option<&mut Vec<ty::ProjectionPredicate<'tcx>>>)
571 -> Rc<ty::TraitRef<'tcx>>
573 debug!("ast_path_to_trait_ref {:?}", path);
574 let trait_def = this.get_trait_def(trait_def_id);
576 // the trait reference introduces a binding level here, so
577 // we need to shift the `rscope`. It'd be nice if we could
578 // do away with this rscope stuff and work this knowledge
579 // into resolve_lifetimes, as we do with non-omitted
580 // lifetimes. Oh well, not there yet.
581 let shifted_rscope = ShiftedRscope::new(rscope);
583 let (regions, types, assoc_bindings) = match path.segments.last().unwrap().parameters {
584 ast::AngleBracketedParameters(ref data) => {
585 // For now, require that parenthetical notation be used
586 // only with `Fn()` etc.
587 if !this.tcx().sess.features.borrow().unboxed_closures &&
588 this.tcx().lang_items.fn_trait_kind(trait_def_id).is_some()
590 this.tcx().sess.span_err(path.span,
591 "angle-bracket notation is not stable when \
592 used with the `Fn` family of traits, use parentheses");
593 span_help!(this.tcx().sess, path.span,
594 "add `#![feature(unboxed_closures)]` to \
595 the crate attributes to enable");
598 convert_angle_bracketed_parameters(this, &shifted_rscope, data)
600 ast::ParenthesizedParameters(ref data) => {
601 // For now, require that parenthetical notation be used
602 // only with `Fn()` etc.
603 if !this.tcx().sess.features.borrow().unboxed_closures &&
604 this.tcx().lang_items.fn_trait_kind(trait_def_id).is_none()
606 this.tcx().sess.span_err(path.span,
607 "parenthetical notation is only stable when \
608 used with the `Fn` family of traits");
609 span_help!(this.tcx().sess, path.span,
610 "add `#![feature(unboxed_closures)]` to \
611 the crate attributes to enable");
614 (Vec::new(), convert_parenthesized_parameters(this, data), Vec::new())
618 let substs = create_substs_for_ast_path(this,
625 let substs = this.tcx().mk_substs(substs);
627 let trait_ref = Rc::new(ty::TraitRef::new(trait_def_id, substs));
631 prohibit_projections(this.tcx(), assoc_bindings.as_slice());
634 for binding in assoc_bindings.iter() {
635 match ast_type_binding_to_projection_predicate(this, trait_ref.clone(),
637 Ok(pp) => { v.push(pp); }
638 Err(ErrorReported) => { }
647 fn ast_type_binding_to_projection_predicate<'tcx>(
648 this: &AstConv<'tcx>,
649 mut trait_ref: Rc<ty::TraitRef<'tcx>>,
650 self_ty: Option<Ty<'tcx>>,
651 binding: &ConvertedBinding<'tcx>)
652 -> Result<ty::ProjectionPredicate<'tcx>, ErrorReported>
654 let tcx = this.tcx();
656 // Given something like `U : SomeTrait<T=X>`, we want to produce a
657 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
658 // subtle in the event that `T` is defined in a supertrait of
659 // `SomeTrait`, because in that case we need to upcast.
661 // That is, consider this case:
664 // trait SubTrait : SuperTrait<int> { }
665 // trait SuperTrait<A> { type T; }
667 // ... B : SubTrait<T=foo> ...
670 // We want to produce `<B as SuperTrait<int>>::T == foo`.
672 // Simple case: X is defined in the current trait.
673 if trait_defines_associated_type_named(this, trait_ref.def_id, binding.item_name) {
674 return Ok(ty::ProjectionPredicate {
675 projection_ty: ty::ProjectionTy {
676 trait_ref: trait_ref,
677 item_name: binding.item_name,
683 // Otherwise, we have to walk through the supertraits to find
684 // those that do. This is complicated by the fact that, for an
685 // object type, the `Self` type is not present in the
686 // substitutions (after all, it's being constructed right now),
687 // but the `supertraits` iterator really wants one. To handle
688 // this, we currently insert a dummy type and then remove it
691 let dummy_self_ty = ty::mk_infer(tcx, ty::FreshTy(0));
692 if self_ty.is_none() { // if converting for an object type
693 let mut dummy_substs = trait_ref.substs.clone();
694 assert!(dummy_substs.self_ty().is_none());
695 dummy_substs.types.push(SelfSpace, dummy_self_ty);
696 trait_ref = Rc::new(ty::TraitRef::new(trait_ref.def_id,
697 tcx.mk_substs(dummy_substs)));
700 let mut candidates: Vec<ty::PolyTraitRef> =
701 traits::supertraits(tcx, trait_ref.to_poly_trait_ref())
702 .filter(|r| trait_defines_associated_type_named(this, r.def_id(), binding.item_name))
705 // If converting for an object type, then remove the dummy-ty from `Self` now.
707 if self_ty.is_none() {
708 for candidate in candidates.iter_mut() {
709 let mut dummy_substs = candidate.0.substs.clone();
710 assert!(dummy_substs.self_ty() == Some(dummy_self_ty));
711 dummy_substs.types.pop(SelfSpace);
712 *candidate = ty::Binder(Rc::new(ty::TraitRef::new(candidate.def_id(),
713 tcx.mk_substs(dummy_substs))));
717 if candidates.len() > 1 {
720 format!("ambiguous associated type: `{}` defined in multiple supertraits `{}`",
721 token::get_name(binding.item_name),
722 candidates.user_string(tcx)).as_slice());
723 return Err(ErrorReported);
726 let candidate = match candidates.pop() {
731 format!("no associated type `{}` defined in `{}`",
732 token::get_name(binding.item_name),
733 trait_ref.user_string(tcx)).as_slice());
734 return Err(ErrorReported);
738 if ty::binds_late_bound_regions(tcx, &candidate) {
741 format!("associated type `{}` defined in higher-ranked supertrait `{}`",
742 token::get_name(binding.item_name),
743 candidate.user_string(tcx)).as_slice());
744 return Err(ErrorReported);
747 Ok(ty::ProjectionPredicate {
748 projection_ty: ty::ProjectionTy {
749 trait_ref: candidate.0,
750 item_name: binding.item_name,
756 pub fn ast_path_to_ty<'tcx>(
757 this: &AstConv<'tcx>,
758 rscope: &RegionScope,
761 -> TypeAndSubsts<'tcx>
763 let tcx = this.tcx();
767 } = this.get_item_type_scheme(did);
769 let substs = ast_path_substs_for_ty(this,
773 let ty = decl_ty.subst(tcx, &substs);
774 TypeAndSubsts { substs: substs, ty: ty }
777 /// Converts the given AST type to a built-in type. A "built-in type" is, at
778 /// present, either a core numeric type, a string, or `Box`.
779 pub fn ast_ty_to_builtin_ty<'tcx>(
780 this: &AstConv<'tcx>,
781 rscope: &RegionScope,
783 -> Option<Ty<'tcx>> {
784 match ast_ty_to_prim_ty(this.tcx(), ast_ty) {
785 Some(typ) => return Some(typ),
790 ast::TyPath(ref path, id) => {
791 let a_def = match this.tcx().def_map.borrow().get(&id) {
795 .span_bug(ast_ty.span,
796 &format!("unbound path {}",
797 path.repr(this.tcx()))[])
802 // FIXME(#12938): This is a hack until we have full support for
806 def::DefStruct(did) if Some(did) == this.tcx().lang_items.owned_box() => {
807 let ty = ast_path_to_ty(this, rscope, did, path).ty;
809 ty::ty_struct(struct_def_id, ref substs) => {
810 assert_eq!(struct_def_id, did);
811 assert_eq!(substs.types.len(TypeSpace), 1);
812 let referent_ty = *substs.types.get(TypeSpace, 0);
813 Some(ty::mk_uniq(this.tcx(), referent_ty))
816 this.tcx().sess.span_bug(
818 &format!("converting `Box` to `{}`",
819 ty.repr(this.tcx()))[]);
830 type TraitAndProjections<'tcx> = (ty::PolyTraitRef<'tcx>, Vec<ty::PolyProjectionPredicate<'tcx>>);
832 fn ast_ty_to_trait_ref<'tcx>(this: &AstConv<'tcx>,
833 rscope: &RegionScope,
835 bounds: &[ast::TyParamBound])
836 -> Result<TraitAndProjections<'tcx>, ErrorReported>
839 * In a type like `Foo + Send`, we want to wait to collect the
840 * full set of bounds before we make the object type, because we
841 * need them to infer a region bound. (For example, if we tried
842 * made a type from just `Foo`, then it wouldn't be enough to
843 * infer a 'static bound, and hence the user would get an error.)
844 * So this function is used when we're dealing with a sum type to
845 * convert the LHS. It only accepts a type that refers to a trait
846 * name, and reports an error otherwise.
850 ast::TyPath(ref path, id) => {
851 match this.tcx().def_map.borrow().get(&id) {
852 Some(&def::DefTrait(trait_def_id)) => {
853 let mut projection_bounds = Vec::new();
854 let trait_ref = ty::Binder(ast_path_to_trait_ref(this,
859 Some(&mut projection_bounds)));
860 let projection_bounds = projection_bounds.into_iter()
863 Ok((trait_ref, projection_bounds))
866 span_err!(this.tcx().sess, ty.span, E0172, "expected a reference to a trait");
872 span_err!(this.tcx().sess, ty.span, E0178,
873 "expected a path on the left-hand side of `+`, not `{}`",
874 pprust::ty_to_string(ty));
876 ast::TyRptr(None, ref mut_ty) => {
877 span_note!(this.tcx().sess, ty.span,
878 "perhaps you meant `&{}({} +{})`? (per RFC 438)",
879 ppaux::mutability_to_string(mut_ty.mutbl),
880 pprust::ty_to_string(&*mut_ty.ty),
881 pprust::bounds_to_string(bounds));
883 ast::TyRptr(Some(ref lt), ref mut_ty) => {
884 span_note!(this.tcx().sess, ty.span,
885 "perhaps you meant `&{} {}({} +{})`? (per RFC 438)",
886 pprust::lifetime_to_string(lt),
887 ppaux::mutability_to_string(mut_ty.mutbl),
888 pprust::ty_to_string(&*mut_ty.ty),
889 pprust::bounds_to_string(bounds));
893 span_note!(this.tcx().sess, ty.span,
894 "perhaps you forgot parentheses? (per RFC 438)");
902 fn trait_ref_to_object_type<'tcx>(this: &AstConv<'tcx>,
903 rscope: &RegionScope,
905 trait_ref: ty::PolyTraitRef<'tcx>,
906 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
907 bounds: &[ast::TyParamBound])
910 let existential_bounds = conv_existential_bounds(this,
913 Some(trait_ref.clone()),
917 let result = ty::mk_trait(this.tcx(), trait_ref, existential_bounds);
918 debug!("trait_ref_to_object_type: result={}",
919 result.repr(this.tcx()));
924 fn associated_path_def_to_ty<'tcx>(this: &AstConv<'tcx>,
926 provenance: def::TyParamProvenance,
927 assoc_name: ast::Name)
930 let tcx = this.tcx();
931 let ty_param_def_id = provenance.def_id();
933 let mut suitable_bounds: Vec<_>;
934 let ty_param_name: ast::Name;
935 { // contain scope of refcell:
936 let ty_param_defs = tcx.ty_param_defs.borrow();
937 let ty_param_def = &ty_param_defs[ty_param_def_id.node];
938 ty_param_name = ty_param_def.name;
940 // FIXME(#20300) -- search where clauses, not bounds
942 traits::transitive_bounds(tcx, ty_param_def.bounds.trait_bounds.as_slice())
943 .filter(|b| trait_defines_associated_type_named(this, b.def_id(), assoc_name))
947 if suitable_bounds.len() == 0 {
948 tcx.sess.span_err(ast_ty.span,
949 format!("associated type `{}` not found for type parameter `{}`",
950 token::get_name(assoc_name),
951 token::get_name(ty_param_name)).as_slice());
952 return this.tcx().types.err;
955 if suitable_bounds.len() > 1 {
956 tcx.sess.span_err(ast_ty.span,
957 format!("ambiguous associated type `{}` in bounds of `{}`",
958 token::get_name(assoc_name),
959 token::get_name(ty_param_name)).as_slice());
961 for suitable_bound in suitable_bounds.iter() {
962 span_note!(this.tcx().sess, ast_ty.span,
963 "associated type `{}` could derive from `{}`",
964 token::get_name(ty_param_name),
965 suitable_bound.user_string(this.tcx()));
969 let suitable_bound = suitable_bounds.pop().unwrap().clone();
970 return this.projected_ty_from_poly_trait_ref(ast_ty.span, suitable_bound, assoc_name);
973 fn trait_defines_associated_type_named(this: &AstConv,
974 trait_def_id: ast::DefId,
975 assoc_name: ast::Name)
978 let tcx = this.tcx();
979 let trait_def = ty::lookup_trait_def(tcx, trait_def_id);
980 trait_def.associated_type_names.contains(&assoc_name)
983 fn qpath_to_ty<'tcx>(this: &AstConv<'tcx>,
984 rscope: &RegionScope,
985 ast_ty: &ast::Ty, // the TyQPath
989 debug!("qpath_to_ty(ast_ty={})",
990 ast_ty.repr(this.tcx()));
992 let self_type = ast_ty_to_ty(this, rscope, &*qpath.self_type);
994 debug!("qpath_to_ty: self_type={}", self_type.repr(this.tcx()));
996 let trait_ref = instantiate_trait_ref(this,
1002 debug!("qpath_to_ty: trait_ref={}", trait_ref.repr(this.tcx()));
1004 // `<T as Trait>::U<V>` shouldn't parse right now.
1005 assert!(qpath.item_path.parameters.is_empty());
1007 return this.projected_ty(ast_ty.span,
1009 qpath.item_path.identifier.name);
1012 // Parses the programmer's textual representation of a type into our
1013 // internal notion of a type.
1014 pub fn ast_ty_to_ty<'tcx>(
1015 this: &AstConv<'tcx>, rscope: &RegionScope, ast_ty: &ast::Ty) -> Ty<'tcx>
1017 debug!("ast_ty_to_ty(ast_ty={})",
1018 ast_ty.repr(this.tcx()));
1020 let tcx = this.tcx();
1022 let mut ast_ty_to_ty_cache = tcx.ast_ty_to_ty_cache.borrow_mut();
1023 match ast_ty_to_ty_cache.get(&ast_ty.id) {
1024 Some(&ty::atttce_resolved(ty)) => return ty,
1025 Some(&ty::atttce_unresolved) => {
1026 tcx.sess.span_fatal(ast_ty.span,
1027 "illegal recursive type; insert an enum \
1028 or struct in the cycle, if this is \
1031 None => { /* go on */ }
1033 ast_ty_to_ty_cache.insert(ast_ty.id, ty::atttce_unresolved);
1034 drop(ast_ty_to_ty_cache);
1036 let typ = ast_ty_to_builtin_ty(this, rscope, ast_ty).unwrap_or_else(|| {
1038 ast::TyVec(ref ty) => {
1039 ty::mk_vec(tcx, ast_ty_to_ty(this, rscope, &**ty), None)
1041 ast::TyObjectSum(ref ty, ref bounds) => {
1042 match ast_ty_to_trait_ref(this, rscope, &**ty, &bounds[]) {
1043 Ok((trait_ref, projection_bounds)) => {
1044 trait_ref_to_object_type(this,
1051 Err(ErrorReported) => {
1052 this.tcx().types.err
1056 ast::TyPtr(ref mt) => {
1057 ty::mk_ptr(tcx, ty::mt {
1058 ty: ast_ty_to_ty(this, rscope, &*mt.ty),
1062 ast::TyRptr(ref region, ref mt) => {
1063 let r = opt_ast_region_to_region(this, rscope, ast_ty.span, region);
1064 debug!("ty_rptr r={}", r.repr(this.tcx()));
1065 let t = ast_ty_to_ty(this, rscope, &*mt.ty);
1066 ty::mk_rptr(tcx, tcx.mk_region(r), ty::mt {ty: t, mutbl: mt.mutbl})
1068 ast::TyTup(ref fields) => {
1069 let flds = fields.iter()
1070 .map(|t| ast_ty_to_ty(this, rscope, &**t))
1072 ty::mk_tup(tcx, flds)
1074 ast::TyParen(ref typ) => ast_ty_to_ty(this, rscope, &**typ),
1075 ast::TyBareFn(ref bf) => {
1076 if bf.decl.variadic && bf.abi != abi::C {
1077 tcx.sess.span_err(ast_ty.span,
1078 "variadic function must have C calling convention");
1080 let bare_fn = ty_of_bare_fn(this, bf.unsafety, bf.abi, &*bf.decl);
1081 ty::mk_bare_fn(tcx, None, tcx.mk_bare_fn(bare_fn))
1083 ast::TyPolyTraitRef(ref bounds) => {
1084 conv_ty_poly_trait_ref(this, rscope, ast_ty.span, &bounds[])
1086 ast::TyPath(ref path, id) => {
1087 let a_def = match tcx.def_map.borrow().get(&id) {
1090 .span_bug(ast_ty.span,
1091 &format!("unbound path {}",
1097 def::DefTrait(trait_def_id) => {
1098 // N.B. this case overlaps somewhat with
1099 // TyObjectSum, see that fn for details
1100 let mut projection_bounds = Vec::new();
1101 let trait_ref = ast_path_to_trait_ref(this,
1106 Some(&mut projection_bounds));
1107 let trait_ref = ty::Binder(trait_ref);
1108 let projection_bounds = projection_bounds.into_iter()
1111 trait_ref_to_object_type(this, rscope, path.span,
1112 trait_ref, projection_bounds, &[])
1114 def::DefTy(did, _) | def::DefStruct(did) => {
1115 ast_path_to_ty(this, rscope, did, path).ty
1117 def::DefTyParam(space, index, _, name) => {
1118 check_path_args(tcx, path, NO_TPS | NO_REGIONS);
1119 ty::mk_param(tcx, space, index, name)
1121 def::DefSelfTy(_) => {
1122 // n.b.: resolve guarantees that the this type only appears in a
1123 // trait, which we rely upon in various places when creating
1125 check_path_args(tcx, path, NO_TPS | NO_REGIONS);
1126 ty::mk_self_type(tcx)
1128 def::DefMod(id) => {
1129 tcx.sess.span_fatal(ast_ty.span,
1130 &format!("found module name used as a type: {}",
1131 tcx.map.node_to_string(id.node))[]);
1133 def::DefPrimTy(_) => {
1134 panic!("DefPrimTy arm missed in previous ast_ty_to_prim_ty call");
1136 def::DefAssociatedTy(trait_type_id) => {
1137 let path_str = tcx.map.path_to_string(
1138 tcx.map.get_parent(trait_type_id.node));
1139 tcx.sess.span_err(ast_ty.span,
1140 &format!("ambiguous associated \
1141 type; specify the type \
1142 using the syntax `<Type \
1151 this.tcx().types.err
1153 def::DefAssociatedPath(provenance, assoc_ident) => {
1154 associated_path_def_to_ty(this, ast_ty, provenance, assoc_ident.name)
1157 tcx.sess.span_fatal(ast_ty.span,
1158 &format!("found value name used \
1164 ast::TyQPath(ref qpath) => {
1165 qpath_to_ty(this, rscope, ast_ty, &**qpath)
1167 ast::TyFixedLengthVec(ref ty, ref e) => {
1168 match const_eval::eval_const_expr_partial(tcx, &**e) {
1171 const_eval::const_int(i) =>
1172 ty::mk_vec(tcx, ast_ty_to_ty(this, rscope, &**ty),
1174 const_eval::const_uint(i) =>
1175 ty::mk_vec(tcx, ast_ty_to_ty(this, rscope, &**ty),
1178 tcx.sess.span_fatal(
1179 ast_ty.span, "expected constant expr for array length");
1184 tcx.sess.span_fatal(
1186 &format!("expected constant expr for array \
1192 ast::TyTypeof(ref _e) => {
1193 tcx.sess.span_bug(ast_ty.span, "typeof is reserved but unimplemented");
1196 // TyInfer also appears as the type of arguments or return
1197 // values in a ExprClosure, or as
1198 // the type of local variables. Both of these cases are
1199 // handled specially and will not descend into this routine.
1200 this.ty_infer(ast_ty.span)
1205 tcx.ast_ty_to_ty_cache.borrow_mut().insert(ast_ty.id, ty::atttce_resolved(typ));
1209 pub fn ty_of_arg<'tcx>(this: &AstConv<'tcx>,
1210 rscope: &RegionScope,
1212 expected_ty: Option<Ty<'tcx>>)
1216 ast::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1217 ast::TyInfer => this.ty_infer(a.ty.span),
1218 _ => ast_ty_to_ty(this, rscope, &*a.ty),
1222 struct SelfInfo<'a, 'tcx> {
1223 untransformed_self_ty: Ty<'tcx>,
1224 explicit_self: &'a ast::ExplicitSelf,
1227 pub fn ty_of_method<'tcx>(this: &AstConv<'tcx>,
1228 unsafety: ast::Unsafety,
1229 untransformed_self_ty: Ty<'tcx>,
1230 explicit_self: &ast::ExplicitSelf,
1233 -> (ty::BareFnTy<'tcx>, ty::ExplicitSelfCategory) {
1234 let self_info = Some(SelfInfo {
1235 untransformed_self_ty: untransformed_self_ty,
1236 explicit_self: explicit_self,
1238 let (bare_fn_ty, optional_explicit_self_category) =
1239 ty_of_method_or_bare_fn(this,
1244 (bare_fn_ty, optional_explicit_self_category.unwrap())
1247 pub fn ty_of_bare_fn<'tcx>(this: &AstConv<'tcx>, unsafety: ast::Unsafety, abi: abi::Abi,
1248 decl: &ast::FnDecl) -> ty::BareFnTy<'tcx> {
1249 let (bare_fn_ty, _) = ty_of_method_or_bare_fn(this, unsafety, abi, None, decl);
1253 fn ty_of_method_or_bare_fn<'a, 'tcx>(this: &AstConv<'tcx>,
1254 unsafety: ast::Unsafety,
1256 opt_self_info: Option<SelfInfo<'a, 'tcx>>,
1258 -> (ty::BareFnTy<'tcx>, Option<ty::ExplicitSelfCategory>)
1260 debug!("ty_of_method_or_bare_fn");
1262 // New region names that appear inside of the arguments of the function
1263 // declaration are bound to that function type.
1264 let rb = rscope::BindingRscope::new();
1266 // `implied_output_region` is the region that will be assumed for any
1267 // region parameters in the return type. In accordance with the rules for
1268 // lifetime elision, we can determine it in two ways. First (determined
1269 // here), if self is by-reference, then the implied output region is the
1270 // region of the self parameter.
1271 let mut explicit_self_category_result = None;
1272 let (self_ty, mut implied_output_region) = match opt_self_info {
1273 None => (None, None),
1274 Some(self_info) => {
1275 // This type comes from an impl or trait; no late-bound
1276 // regions should be present.
1277 assert!(!self_info.untransformed_self_ty.has_escaping_regions());
1279 // Figure out and record the explicit self category.
1280 let explicit_self_category =
1281 determine_explicit_self_category(this, &rb, &self_info);
1282 explicit_self_category_result = Some(explicit_self_category);
1283 match explicit_self_category {
1284 ty::StaticExplicitSelfCategory => {
1287 ty::ByValueExplicitSelfCategory => {
1288 (Some(self_info.untransformed_self_ty), None)
1290 ty::ByReferenceExplicitSelfCategory(region, mutability) => {
1291 (Some(ty::mk_rptr(this.tcx(),
1292 this.tcx().mk_region(region),
1294 ty: self_info.untransformed_self_ty,
1299 ty::ByBoxExplicitSelfCategory => {
1300 (Some(ty::mk_uniq(this.tcx(), self_info.untransformed_self_ty)), None)
1306 // HACK(eddyb) replace the fake self type in the AST with the actual type.
1307 let input_params = if self_ty.is_some() {
1308 decl.inputs.slice_from(1)
1312 let input_tys = input_params.iter().map(|a| ty_of_arg(this, &rb, a, None));
1313 let input_pats: Vec<String> = input_params.iter()
1314 .map(|a| pprust::pat_to_string(&*a.pat))
1316 let self_and_input_tys: Vec<Ty> =
1317 self_ty.into_iter().chain(input_tys).collect();
1320 // Second, if there was exactly one lifetime (either a substitution or a
1321 // reference) in the arguments, then any anonymous regions in the output
1322 // have that lifetime.
1323 let lifetimes_for_params = if implied_output_region.is_none() {
1324 let input_tys = if self_ty.is_some() {
1325 // Skip the first argument if `self` is present.
1326 self_and_input_tys.slice_from(1)
1328 self_and_input_tys.slice_from(0)
1331 let (ior, lfp) = find_implied_output_region(input_tys, input_pats);
1332 implied_output_region = ior;
1338 let output_ty = match decl.output {
1339 ast::Return(ref output) if output.node == ast::TyInfer =>
1340 ty::FnConverging(this.ty_infer(output.span)),
1341 ast::Return(ref output) =>
1342 ty::FnConverging(convert_ty_with_lifetime_elision(this,
1343 implied_output_region,
1344 lifetimes_for_params,
1346 ast::NoReturn(_) => ty::FnDiverging
1352 sig: ty::Binder(ty::FnSig {
1353 inputs: self_and_input_tys,
1355 variadic: decl.variadic
1357 }, explicit_self_category_result)
1360 fn determine_explicit_self_category<'a, 'tcx>(this: &AstConv<'tcx>,
1361 rscope: &RegionScope,
1362 self_info: &SelfInfo<'a, 'tcx>)
1363 -> ty::ExplicitSelfCategory
1365 return match self_info.explicit_self.node {
1366 ast::SelfStatic => ty::StaticExplicitSelfCategory,
1367 ast::SelfValue(_) => ty::ByValueExplicitSelfCategory,
1368 ast::SelfRegion(ref lifetime, mutability, _) => {
1370 opt_ast_region_to_region(this,
1372 self_info.explicit_self.span,
1374 ty::ByReferenceExplicitSelfCategory(region, mutability)
1376 ast::SelfExplicit(ref ast_type, _) => {
1377 let explicit_type = ast_ty_to_ty(this, rscope, &**ast_type);
1379 // We wish to (for now) categorize an explicit self
1380 // declaration like `self: SomeType` into either `self`,
1381 // `&self`, `&mut self`, or `Box<self>`. We do this here
1382 // by some simple pattern matching. A more precise check
1383 // is done later in `check_method_self_type()`.
1388 // impl Foo for &T {
1389 // // Legal declarations:
1390 // fn method1(self: &&T); // ByReferenceExplicitSelfCategory
1391 // fn method2(self: &T); // ByValueExplicitSelfCategory
1392 // fn method3(self: Box<&T>); // ByBoxExplicitSelfCategory
1394 // // Invalid cases will be caught later by `check_method_self_type`:
1395 // fn method_err1(self: &mut T); // ByReferenceExplicitSelfCategory
1399 // To do the check we just count the number of "modifiers"
1400 // on each type and compare them. If they are the same or
1401 // the impl has more, we call it "by value". Otherwise, we
1402 // look at the outermost modifier on the method decl and
1403 // call it by-ref, by-box as appropriate. For method1, for
1404 // example, the impl type has one modifier, but the method
1405 // type has two, so we end up with
1406 // ByReferenceExplicitSelfCategory.
1408 let impl_modifiers = count_modifiers(self_info.untransformed_self_ty);
1409 let method_modifiers = count_modifiers(explicit_type);
1411 debug!("determine_explicit_self_category(self_info.untransformed_self_ty={} \
1414 self_info.untransformed_self_ty.repr(this.tcx()),
1415 explicit_type.repr(this.tcx()),
1419 if impl_modifiers >= method_modifiers {
1420 ty::ByValueExplicitSelfCategory
1422 match explicit_type.sty {
1423 ty::ty_rptr(r, mt) => ty::ByReferenceExplicitSelfCategory(*r, mt.mutbl),
1424 ty::ty_uniq(_) => ty::ByBoxExplicitSelfCategory,
1425 _ => ty::ByValueExplicitSelfCategory,
1431 fn count_modifiers(ty: Ty) -> uint {
1433 ty::ty_rptr(_, mt) => count_modifiers(mt.ty) + 1,
1434 ty::ty_uniq(t) => count_modifiers(t) + 1,
1440 pub fn ty_of_closure<'tcx>(
1441 this: &AstConv<'tcx>,
1442 unsafety: ast::Unsafety,
1443 onceness: ast::Onceness,
1444 bounds: ty::ExistentialBounds<'tcx>,
1445 store: ty::TraitStore,
1448 expected_sig: Option<ty::FnSig<'tcx>>)
1449 -> ty::ClosureTy<'tcx>
1451 debug!("ty_of_closure(expected_sig={})",
1452 expected_sig.repr(this.tcx()));
1454 // new region names that appear inside of the fn decl are bound to
1455 // that function type
1456 let rb = rscope::BindingRscope::new();
1458 let input_tys: Vec<_> = decl.inputs.iter().enumerate().map(|(i, a)| {
1459 let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1460 // no guarantee that the correct number of expected args
1462 if i < e.inputs.len() {
1468 ty_of_arg(this, &rb, a, expected_arg_ty)
1471 let expected_ret_ty = expected_sig.map(|e| e.output);
1473 let output_ty = match decl.output {
1474 ast::Return(ref output) if output.node == ast::TyInfer && expected_ret_ty.is_some() =>
1475 expected_ret_ty.unwrap(),
1476 ast::Return(ref output) if output.node == ast::TyInfer =>
1477 ty::FnConverging(this.ty_infer(output.span)),
1478 ast::Return(ref output) =>
1479 ty::FnConverging(ast_ty_to_ty(this, &rb, &**output)),
1480 ast::NoReturn(_) => ty::FnDiverging
1483 debug!("ty_of_closure: input_tys={}", input_tys.repr(this.tcx()));
1484 debug!("ty_of_closure: output_ty={}", output_ty.repr(this.tcx()));
1492 sig: ty::Binder(ty::FnSig {inputs: input_tys,
1494 variadic: decl.variadic}),
1498 /// Given an existential type like `Foo+'a+Bar`, this routine converts the `'a` and `Bar` intos an
1499 /// `ExistentialBounds` struct. The `main_trait_refs` argument specifies the `Foo` -- it is absent
1500 /// for closures. Eventually this should all be normalized, I think, so that there is no "main
1501 /// trait ref" and instead we just have a flat list of bounds as the existential type.
1502 pub fn conv_existential_bounds<'tcx>(
1503 this: &AstConv<'tcx>,
1504 rscope: &RegionScope,
1506 principal_trait_ref: Option<ty::PolyTraitRef<'tcx>>, // None for boxed closures
1507 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
1508 ast_bounds: &[ast::TyParamBound])
1509 -> ty::ExistentialBounds<'tcx>
1511 let partitioned_bounds =
1512 partition_bounds(this.tcx(), span, ast_bounds);
1514 conv_existential_bounds_from_partitioned_bounds(
1515 this, rscope, span, principal_trait_ref, projection_bounds, partitioned_bounds)
1518 fn conv_ty_poly_trait_ref<'tcx>(
1519 this: &AstConv<'tcx>,
1520 rscope: &RegionScope,
1522 ast_bounds: &[ast::TyParamBound])
1525 let mut partitioned_bounds = partition_bounds(this.tcx(), span, &ast_bounds[]);
1527 let mut projection_bounds = Vec::new();
1528 let main_trait_bound = if !partitioned_bounds.trait_bounds.is_empty() {
1529 let trait_bound = partitioned_bounds.trait_bounds.remove(0);
1530 Some(instantiate_poly_trait_ref(this,
1534 &mut projection_bounds))
1536 this.tcx().sess.span_err(
1538 "at least one non-builtin trait is required for an object type");
1543 conv_existential_bounds_from_partitioned_bounds(this,
1546 main_trait_bound.clone(),
1548 partitioned_bounds);
1550 match main_trait_bound {
1551 None => this.tcx().types.err,
1552 Some(principal) => ty::mk_trait(this.tcx(), principal, bounds)
1556 pub fn conv_existential_bounds_from_partitioned_bounds<'tcx>(
1557 this: &AstConv<'tcx>,
1558 rscope: &RegionScope,
1560 principal_trait_ref: Option<ty::PolyTraitRef<'tcx>>, // None for boxed closures
1561 mut projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>, // Empty for boxed closures
1562 partitioned_bounds: PartitionedBounds)
1563 -> ty::ExistentialBounds<'tcx>
1565 let PartitionedBounds { builtin_bounds,
1570 if !trait_bounds.is_empty() {
1571 let b = &trait_bounds[0];
1572 this.tcx().sess.span_err(
1573 b.trait_ref.path.span,
1574 &format!("only the builtin traits can be used \
1575 as closure or object bounds")[]);
1578 let region_bound = compute_region_bound(this,
1581 region_bounds.as_slice(),
1582 principal_trait_ref,
1585 ty::sort_bounds_list(projection_bounds.as_mut_slice());
1587 ty::ExistentialBounds {
1588 region_bound: region_bound,
1589 builtin_bounds: builtin_bounds,
1590 projection_bounds: projection_bounds,
1594 /// Given the bounds on a type parameter / existential type, determines what single region bound
1595 /// (if any) we can use to summarize this type. The basic idea is that we will use the bound the
1596 /// user provided, if they provided one, and otherwise search the supertypes of trait bounds for
1597 /// region bounds. It may be that we can derive no bound at all, in which case we return `None`.
1598 fn compute_opt_region_bound<'tcx>(tcx: &ty::ctxt<'tcx>,
1600 explicit_region_bounds: &[&ast::Lifetime],
1601 principal_trait_ref: Option<ty::PolyTraitRef<'tcx>>,
1602 builtin_bounds: ty::BuiltinBounds)
1603 -> Option<ty::Region>
1605 debug!("compute_opt_region_bound(explicit_region_bounds={:?}, \
1606 principal_trait_ref={}, builtin_bounds={})",
1607 explicit_region_bounds,
1608 principal_trait_ref.repr(tcx),
1609 builtin_bounds.repr(tcx));
1611 if explicit_region_bounds.len() > 1 {
1613 explicit_region_bounds[1].span,
1614 format!("only a single explicit lifetime bound is permitted").as_slice());
1617 if explicit_region_bounds.len() != 0 {
1618 // Explicitly specified region bound. Use that.
1619 let r = explicit_region_bounds[0];
1620 return Some(ast_region_to_region(tcx, r));
1623 // No explicit region bound specified. Therefore, examine trait
1624 // bounds and see if we can derive region bounds from those.
1625 let derived_region_bounds =
1626 ty::object_region_bounds(tcx, principal_trait_ref.as_ref(), builtin_bounds);
1628 // If there are no derived region bounds, then report back that we
1629 // can find no region bound.
1630 if derived_region_bounds.len() == 0 {
1634 // If any of the derived region bounds are 'static, that is always
1636 if derived_region_bounds.iter().any(|r| ty::ReStatic == *r) {
1637 return Some(ty::ReStatic);
1640 // Determine whether there is exactly one unique region in the set
1641 // of derived region bounds. If so, use that. Otherwise, report an
1643 let r = derived_region_bounds[0];
1644 if derived_region_bounds.slice_from(1).iter().any(|r1| r != *r1) {
1647 &format!("ambiguous lifetime bound, \
1648 explicit lifetime bound required")[]);
1653 /// A version of `compute_opt_region_bound` for use where some region bound is required
1654 /// (existential types, basically). Reports an error if no region bound can be derived and we are
1655 /// in an `rscope` that does not provide a default.
1656 fn compute_region_bound<'tcx>(
1657 this: &AstConv<'tcx>,
1658 rscope: &RegionScope,
1660 region_bounds: &[&ast::Lifetime],
1661 principal_trait_ref: Option<ty::PolyTraitRef<'tcx>>, // None for closures
1662 builtin_bounds: ty::BuiltinBounds)
1665 match compute_opt_region_bound(this.tcx(), span, region_bounds,
1666 principal_trait_ref, builtin_bounds) {
1669 match rscope.default_region_bound(span) {
1672 this.tcx().sess.span_err(
1674 &format!("explicit lifetime bound required")[]);
1682 pub struct PartitionedBounds<'a> {
1683 pub builtin_bounds: ty::BuiltinBounds,
1684 pub trait_bounds: Vec<&'a ast::PolyTraitRef>,
1685 pub region_bounds: Vec<&'a ast::Lifetime>,
1688 /// Divides a list of bounds from the AST into three groups: builtin bounds (Copy, Sized etc),
1689 /// general trait bounds, and region bounds.
1690 pub fn partition_bounds<'a>(tcx: &ty::ctxt,
1692 ast_bounds: &'a [ast::TyParamBound])
1693 -> PartitionedBounds<'a>
1695 let mut builtin_bounds = ty::empty_builtin_bounds();
1696 let mut region_bounds = Vec::new();
1697 let mut trait_bounds = Vec::new();
1698 let mut trait_def_ids = DefIdMap::new();
1699 for ast_bound in ast_bounds.iter() {
1701 ast::TraitTyParamBound(ref b, ast::TraitBoundModifier::None) => {
1702 match ::lookup_def_tcx(tcx, b.trait_ref.path.span, b.trait_ref.ref_id) {
1703 def::DefTrait(trait_did) => {
1704 match trait_def_ids.get(&trait_did) {
1705 // Already seen this trait. We forbid
1706 // duplicates in the list (for some
1710 tcx.sess, b.trait_ref.path.span, E0127,
1711 "trait `{}` already appears in the \
1713 b.trait_ref.path.user_string(tcx));
1716 "previous appearance is here");
1724 trait_def_ids.insert(trait_did, b.trait_ref.path.span);
1726 if ty::try_add_builtin_trait(tcx,
1728 &mut builtin_bounds) {
1729 // FIXME(#20302) -- we should check for things like Copy<T>
1730 continue; // success
1734 // Not a trait? that's an error, but it'll get
1738 trait_bounds.push(b);
1740 ast::TraitTyParamBound(_, ast::TraitBoundModifier::Maybe) => {}
1741 ast::RegionTyParamBound(ref l) => {
1742 region_bounds.push(l);
1748 builtin_bounds: builtin_bounds,
1749 trait_bounds: trait_bounds,
1750 region_bounds: region_bounds,
1754 fn prohibit_projections<'tcx>(tcx: &ty::ctxt<'tcx>,
1755 bindings: &[ConvertedBinding<'tcx>])
1757 for binding in bindings.iter().take(1) {
1760 "associated type bindings are not allowed here");