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};
55 use middle::subst::{VecPerParamSpace};
57 use middle::ty::{self, RegionEscape, ToPolyTraitRef, Ty};
58 use rscope::{self, UnelidableRscope, RegionScope, SpecificRscope,
59 ShiftedRscope, BindingRscope};
61 use util::common::ErrorReported;
62 use util::nodemap::DefIdMap;
63 use util::ppaux::{self, Repr, UserString};
66 use std::iter::{repeat, AdditiveIterator};
67 use syntax::{abi, ast, ast_util};
68 use syntax::codemap::Span;
69 use syntax::parse::token;
70 use syntax::print::pprust;
72 pub trait AstConv<'tcx> {
73 fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx>;
75 fn get_item_type_scheme(&self, id: ast::DefId) -> ty::TypeScheme<'tcx>;
77 fn get_trait_def(&self, id: ast::DefId) -> Rc<ty::TraitDef<'tcx>>;
79 /// Return an (optional) substitution to convert bound type parameters that
80 /// are in scope into free ones. This function should only return Some
82 /// See ParameterEnvironment::free_substs for more information.
83 fn get_free_substs(&self) -> Option<&Substs<'tcx>> {
87 /// What type should we use when a type is omitted?
88 fn ty_infer(&self, span: Span) -> Ty<'tcx>;
90 /// Projecting an associated type from a (potentially)
91 /// higher-ranked trait reference is more complicated, because of
92 /// the possibility of late-bound regions appearing in the
93 /// associated type binding. This is not legal in function
94 /// signatures for that reason. In a function body, we can always
95 /// handle it because we can use inference variables to remove the
96 /// late-bound regions.
97 fn projected_ty_from_poly_trait_ref(&self,
99 poly_trait_ref: ty::PolyTraitRef<'tcx>,
100 item_name: ast::Name)
103 if ty::binds_late_bound_regions(self.tcx(), &poly_trait_ref) {
104 self.tcx().sess.span_err(
106 "cannot extract an associated type from a higher-ranked trait bound \
110 // no late-bound regions, we can just ignore the binder
111 self.projected_ty(span, poly_trait_ref.0.clone(), item_name)
115 /// Project an associated type from a non-higher-ranked trait reference.
116 /// This is fairly straightforward and can be accommodated in any context.
117 fn projected_ty(&self,
119 _trait_ref: Rc<ty::TraitRef<'tcx>>,
120 _item_name: ast::Name)
123 self.tcx().sess.span_err(
125 "associated types are not accepted in this context");
131 pub fn ast_region_to_region(tcx: &ty::ctxt, lifetime: &ast::Lifetime)
133 let r = match tcx.named_region_map.get(&lifetime.id) {
135 // should have been recorded by the `resolve_lifetime` pass
136 tcx.sess.span_bug(lifetime.span, "unresolved lifetime");
139 Some(&rl::DefStaticRegion) => {
143 Some(&rl::DefLateBoundRegion(debruijn, id)) => {
144 ty::ReLateBound(debruijn, ty::BrNamed(ast_util::local_def(id), lifetime.name))
147 Some(&rl::DefEarlyBoundRegion(space, index, id)) => {
148 ty::ReEarlyBound(id, space, index, lifetime.name)
151 Some(&rl::DefFreeRegion(scope, id)) => {
152 ty::ReFree(ty::FreeRegion {
154 bound_region: ty::BrNamed(ast_util::local_def(id),
160 debug!("ast_region_to_region(lifetime={} id={}) yields {}",
168 pub fn opt_ast_region_to_region<'tcx>(
169 this: &AstConv<'tcx>,
170 rscope: &RegionScope,
172 opt_lifetime: &Option<ast::Lifetime>) -> ty::Region
174 let r = match *opt_lifetime {
175 Some(ref lifetime) => {
176 ast_region_to_region(this.tcx(), lifetime)
180 match rscope.anon_regions(default_span, 1) {
182 debug!("optional region in illegal location");
183 span_err!(this.tcx().sess, default_span, E0106,
184 "missing lifetime specifier");
187 let mut m = String::new();
189 for (i, (name, n)) in v.into_iter().enumerate() {
190 let help_name = if name.is_empty() {
191 format!("argument {}", i + 1)
193 format!("`{}`", name)
196 m.push_str(if n == 1 {
199 format!("one of {}'s {} elided lifetimes", help_name, n)
202 if len == 2 && i == 0 {
204 } else if i == len - 2 {
206 } else if i != len - 1 {
211 span_help!(this.tcx().sess, default_span,
212 "this function's return type contains a borrowed value, but \
213 the signature does not say which {} it is borrowed from",
216 span_help!(this.tcx().sess, default_span,
217 "this function's return type contains a borrowed value, but \
218 there is no value for it to be borrowed from");
219 span_help!(this.tcx().sess, default_span,
220 "consider giving it a 'static lifetime");
222 span_help!(this.tcx().sess, default_span,
223 "this function's return type contains a borrowed value, but \
224 the signature does not say whether it is borrowed from {}",
238 debug!("opt_ast_region_to_region(opt_lifetime={}) yields {}",
239 opt_lifetime.repr(this.tcx()),
245 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
246 /// returns an appropriate set of substitutions for this particular reference to `I`.
247 fn ast_path_substs_for_ty<'tcx>(
248 this: &AstConv<'tcx>,
249 rscope: &RegionScope,
250 decl_generics: &ty::Generics<'tcx>,
254 let tcx = this.tcx();
256 // ast_path_substs() is only called to convert paths that are
257 // known to refer to traits, types, or structs. In these cases,
258 // all type parameters defined for the item being referenced will
259 // be in the TypeSpace or SelfSpace.
261 // Note: in the case of traits, the self parameter is also
262 // defined, but we don't currently create a `type_param_def` for
263 // `Self` because it is implicit.
264 assert!(decl_generics.regions.all(|d| d.space == TypeSpace));
265 assert!(decl_generics.types.all(|d| d.space != FnSpace));
267 let (regions, types, assoc_bindings) = match path.segments.last().unwrap().parameters {
268 ast::AngleBracketedParameters(ref data) => {
269 convert_angle_bracketed_parameters(this, rscope, data)
271 ast::ParenthesizedParameters(ref data) => {
274 "parenthesized parameters may only be used with a trait");
275 (Vec::new(), convert_parenthesized_parameters(this, data), Vec::new())
279 prohibit_projections(this.tcx(), assoc_bindings.as_slice());
281 create_substs_for_ast_path(this,
290 fn create_substs_for_ast_path<'tcx>(
291 this: &AstConv<'tcx>,
292 rscope: &RegionScope,
294 decl_generics: &ty::Generics<'tcx>,
295 self_ty: Option<Ty<'tcx>>,
296 types: Vec<Ty<'tcx>>,
297 regions: Vec<ty::Region>)
300 let tcx = this.tcx();
302 // If the type is parameterized by the this region, then replace this
303 // region with the current anon region binding (in other words,
304 // whatever & would get replaced with).
305 let expected_num_region_params = decl_generics.regions.len(TypeSpace);
306 let supplied_num_region_params = regions.len();
307 let regions = if expected_num_region_params == supplied_num_region_params {
311 rscope.anon_regions(span, expected_num_region_params);
313 if supplied_num_region_params != 0 || anon_regions.is_err() {
314 span_err!(tcx.sess, span, E0107,
315 "wrong number of lifetime parameters: expected {}, found {}",
316 expected_num_region_params, supplied_num_region_params);
320 Ok(v) => v.into_iter().collect(),
321 Err(_) => range(0, expected_num_region_params)
322 .map(|_| ty::ReStatic).collect() // hokey
326 // Convert the type parameters supplied by the user.
327 let ty_param_defs = decl_generics.types.get_slice(TypeSpace);
328 let supplied_ty_param_count = types.len();
329 let formal_ty_param_count =
331 .take_while(|x| !ty::is_associated_type(tcx, x.def_id))
333 let required_ty_param_count =
336 x.default.is_none() &&
337 !ty::is_associated_type(tcx, x.def_id)
340 if supplied_ty_param_count < required_ty_param_count {
341 let expected = if required_ty_param_count < formal_ty_param_count {
346 this.tcx().sess.span_fatal(span,
347 format!("wrong number of type arguments: {} {}, found {}",
349 required_ty_param_count,
350 supplied_ty_param_count)[]);
351 } else if supplied_ty_param_count > formal_ty_param_count {
352 let expected = if required_ty_param_count < formal_ty_param_count {
357 this.tcx().sess.span_fatal(span,
358 format!("wrong number of type arguments: {} {}, found {}",
360 formal_ty_param_count,
361 supplied_ty_param_count)[]);
364 if supplied_ty_param_count > required_ty_param_count
365 && !this.tcx().sess.features.borrow().default_type_params {
366 span_err!(this.tcx().sess, span, E0108,
367 "default type parameters are experimental and possibly buggy");
368 span_help!(this.tcx().sess, span,
369 "add #![feature(default_type_params)] to the crate attributes to enable");
372 let mut substs = Substs::new_type(types, regions);
376 // If no self-type is provided, it's still possible that
377 // one was declared, because this could be an object type.
380 // If a self-type is provided, one should have been
381 // "declared" (in other words, this should be a
383 assert!(decl_generics.types.get_self().is_some());
384 substs.types.push(SelfSpace, ty);
388 for param in ty_param_defs[supplied_ty_param_count..].iter() {
389 match param.default {
391 // This is a default type parameter.
392 let default = default.subst_spanned(tcx,
395 substs.types.push(TypeSpace, default);
398 tcx.sess.span_bug(span, "extra parameter without default");
406 struct ConvertedBinding<'tcx> {
407 item_name: ast::Name,
412 fn convert_angle_bracketed_parameters<'tcx>(this: &AstConv<'tcx>,
413 rscope: &RegionScope,
414 data: &ast::AngleBracketedParameterData)
417 Vec<ConvertedBinding<'tcx>>)
419 let regions: Vec<_> =
420 data.lifetimes.iter()
421 .map(|l| ast_region_to_region(this.tcx(), l))
426 .map(|t| ast_ty_to_ty(this, rscope, &**t))
429 let assoc_bindings: Vec<_> =
431 .map(|b| ConvertedBinding { item_name: b.ident.name,
432 ty: ast_ty_to_ty(this, rscope, &*b.ty),
436 (regions, types, assoc_bindings)
439 /// Returns the appropriate lifetime to use for any output lifetimes
440 /// (if one exists) and a vector of the (pattern, number of lifetimes)
441 /// corresponding to each input type/pattern.
442 fn find_implied_output_region(input_tys: &[Ty], input_pats: Vec<String>)
443 -> (Option<ty::Region>, Vec<(String, uint)>)
445 let mut lifetimes_for_params: Vec<(String, uint)> = Vec::new();
446 let mut possible_implied_output_region = None;
448 for (input_type, input_pat) in input_tys.iter().zip(input_pats.into_iter()) {
449 let mut accumulator = Vec::new();
450 ty::accumulate_lifetimes_in_type(&mut accumulator, *input_type);
452 if accumulator.len() == 1 {
453 // there's a chance that the unique lifetime of this
454 // iteration will be the appropriate lifetime for output
455 // parameters, so lets store it.
456 possible_implied_output_region = Some(accumulator[0])
459 lifetimes_for_params.push((input_pat, accumulator.len()));
462 let implied_output_region = if lifetimes_for_params.iter().map(|&(_, n)| n).sum() == 1 {
463 assert!(possible_implied_output_region.is_some());
464 possible_implied_output_region
468 (implied_output_region, lifetimes_for_params)
471 fn convert_ty_with_lifetime_elision<'tcx>(this: &AstConv<'tcx>,
472 implied_output_region: Option<ty::Region>,
473 param_lifetimes: Vec<(String, uint)>,
477 match implied_output_region {
478 Some(implied_output_region) => {
479 let rb = SpecificRscope::new(implied_output_region);
480 ast_ty_to_ty(this, &rb, ty)
483 // All regions must be explicitly specified in the output
484 // if the lifetime elision rules do not apply. This saves
485 // the user from potentially-confusing errors.
486 let rb = UnelidableRscope::new(param_lifetimes);
487 ast_ty_to_ty(this, &rb, ty)
492 fn convert_parenthesized_parameters<'tcx>(this: &AstConv<'tcx>,
493 data: &ast::ParenthesizedParameterData)
496 let binding_rscope = BindingRscope::new();
497 let inputs = data.inputs.iter()
498 .map(|a_t| ast_ty_to_ty(this, &binding_rscope, &**a_t))
499 .collect::<Vec<Ty<'tcx>>>();
501 let input_params: Vec<_> = repeat(String::new()).take(inputs.len()).collect();
502 let (implied_output_region,
503 params_lifetimes) = find_implied_output_region(&*inputs, input_params);
505 let input_ty = ty::mk_tup(this.tcx(), inputs);
507 let output = match data.output {
508 Some(ref output_ty) => convert_ty_with_lifetime_elision(this,
509 implied_output_region,
512 None => ty::mk_nil(this.tcx()),
515 vec![input_ty, output]
518 pub fn instantiate_poly_trait_ref<'tcx>(
519 this: &AstConv<'tcx>,
520 rscope: &RegionScope,
521 ast_trait_ref: &ast::PolyTraitRef,
522 self_ty: Option<Ty<'tcx>>,
523 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
524 -> ty::PolyTraitRef<'tcx>
526 let mut projections = Vec::new();
529 instantiate_trait_ref(this, rscope, &ast_trait_ref.trait_ref,
530 self_ty, Some(&mut projections));
532 for projection in projections.into_iter() {
533 poly_projections.push(ty::Binder(projection));
536 ty::Binder(trait_ref)
539 /// Instantiates the path for the given trait reference, assuming that it's
540 /// bound to a valid trait type. Returns the def_id for the defining trait.
541 /// Fails if the type is a type other than a trait type.
543 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
544 /// are disallowed. Otherwise, they are pushed onto the vector given.
545 pub fn instantiate_trait_ref<'tcx>(
546 this: &AstConv<'tcx>,
547 rscope: &RegionScope,
548 ast_trait_ref: &ast::TraitRef,
549 self_ty: Option<Ty<'tcx>>,
550 projections: Option<&mut Vec<ty::ProjectionPredicate<'tcx>>>)
551 -> Rc<ty::TraitRef<'tcx>>
553 match ::lookup_def_tcx(this.tcx(), ast_trait_ref.path.span, ast_trait_ref.ref_id) {
554 def::DefTrait(trait_def_id) => {
555 let trait_ref = ast_path_to_trait_ref(this,
561 this.tcx().trait_refs.borrow_mut().insert(ast_trait_ref.ref_id, trait_ref.clone());
565 this.tcx().sess.span_fatal(
566 ast_trait_ref.path.span,
567 format!("`{}` is not a trait", ast_trait_ref.path.user_string(this.tcx()))[]);
572 fn ast_path_to_trait_ref<'a,'tcx>(
573 this: &AstConv<'tcx>,
574 rscope: &RegionScope,
575 trait_def_id: ast::DefId,
576 self_ty: Option<Ty<'tcx>>,
578 mut projections: Option<&mut Vec<ty::ProjectionPredicate<'tcx>>>)
579 -> Rc<ty::TraitRef<'tcx>>
581 debug!("ast_path_to_trait_ref {}", path);
582 let trait_def = this.get_trait_def(trait_def_id);
584 // the trait reference introduces a binding level here, so
585 // we need to shift the `rscope`. It'd be nice if we could
586 // do away with this rscope stuff and work this knowledge
587 // into resolve_lifetimes, as we do with non-omitted
588 // lifetimes. Oh well, not there yet.
589 let shifted_rscope = ShiftedRscope::new(rscope);
591 let (regions, types, assoc_bindings) = match path.segments.last().unwrap().parameters {
592 ast::AngleBracketedParameters(ref data) => {
593 convert_angle_bracketed_parameters(this, &shifted_rscope, data)
595 ast::ParenthesizedParameters(ref data) => {
596 // For now, require that parenthetical notation be used
597 // only with `Fn()` etc.
598 if !this.tcx().sess.features.borrow().unboxed_closures &&
599 this.tcx().lang_items.fn_trait_kind(trait_def_id).is_none()
601 this.tcx().sess.span_err(path.span,
602 "parenthetical notation is only stable when \
603 used with the `Fn` family of traits");
604 span_help!(this.tcx().sess, path.span,
605 "add `#![feature(unboxed_closures)]` to \
606 the crate attributes to enable");
609 (Vec::new(), convert_parenthesized_parameters(this, data), Vec::new())
613 let substs = create_substs_for_ast_path(this,
620 let substs = this.tcx().mk_substs(substs);
622 let trait_ref = Rc::new(ty::TraitRef::new(trait_def_id, substs));
626 prohibit_projections(this.tcx(), assoc_bindings.as_slice());
629 for binding in assoc_bindings.iter() {
630 match ast_type_binding_to_projection_predicate(this, trait_ref.clone(),
632 Ok(pp) => { v.push(pp); }
633 Err(ErrorReported) => { }
642 fn ast_type_binding_to_projection_predicate<'tcx>(
643 this: &AstConv<'tcx>,
644 mut trait_ref: Rc<ty::TraitRef<'tcx>>,
645 self_ty: Option<Ty<'tcx>>,
646 binding: &ConvertedBinding<'tcx>)
647 -> Result<ty::ProjectionPredicate<'tcx>, ErrorReported>
649 let tcx = this.tcx();
651 // Given something like `U : SomeTrait<T=X>`, we want to produce a
652 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
653 // subtle in the event that `T` is defined in a supertrait of
654 // `SomeTrait`, because in that case we need to upcast.
656 // That is, consider this case:
659 // trait SubTrait : SuperTrait<int> { }
660 // trait SuperTrait<A> { type T; }
662 // ... B : SubTrait<T=foo> ...
665 // We want to produce `<B as SuperTrait<int>>::T == foo`.
667 // Simple case: X is defined in the current trait.
668 if trait_defines_associated_type_named(this, trait_ref.def_id, binding.item_name) {
669 return Ok(ty::ProjectionPredicate {
670 projection_ty: ty::ProjectionTy {
671 trait_ref: trait_ref,
672 item_name: binding.item_name,
678 // Otherwise, we have to walk through the supertraits to find
679 // those that do. This is complicated by the fact that, for an
680 // object type, the `Self` type is not present in the
681 // substitutions (after all, it's being constructed right now),
682 // but the `supertraits` iterator really wants one. To handle
683 // this, we currently insert a dummy type and then remove it
686 let dummy_self_ty = ty::mk_infer(tcx, ty::FreshTy(0));
687 if self_ty.is_none() { // if converting for an object type
688 let mut dummy_substs = trait_ref.substs.clone();
689 assert!(dummy_substs.self_ty().is_none());
690 dummy_substs.types.push(SelfSpace, dummy_self_ty);
691 trait_ref = Rc::new(ty::TraitRef::new(trait_ref.def_id,
692 tcx.mk_substs(dummy_substs)));
695 let mut candidates: Vec<ty::PolyTraitRef> =
696 traits::supertraits(tcx, trait_ref.to_poly_trait_ref())
697 .filter(|r| trait_defines_associated_type_named(this, r.def_id(), binding.item_name))
700 // If converting for an object type, then remove the dummy-ty from `Self` now.
702 if self_ty.is_none() {
703 for candidate in candidates.iter_mut() {
704 let mut dummy_substs = candidate.0.substs.clone();
705 assert!(dummy_substs.self_ty() == Some(dummy_self_ty));
706 dummy_substs.types.pop(SelfSpace);
707 *candidate = ty::Binder(Rc::new(ty::TraitRef::new(candidate.def_id(),
708 tcx.mk_substs(dummy_substs))));
712 if candidates.len() > 1 {
715 format!("ambiguous associated type: `{}` defined in multiple supertraits `{}`",
716 token::get_name(binding.item_name),
717 candidates.user_string(tcx)).as_slice());
718 return Err(ErrorReported);
721 let candidate = match candidates.pop() {
726 format!("no associated type `{}` defined in `{}`",
727 token::get_name(binding.item_name),
728 trait_ref.user_string(tcx)).as_slice());
729 return Err(ErrorReported);
733 if ty::binds_late_bound_regions(tcx, &candidate) {
736 format!("associated type `{}` defined in higher-ranked supertrait `{}`",
737 token::get_name(binding.item_name),
738 candidate.user_string(tcx)).as_slice());
739 return Err(ErrorReported);
742 Ok(ty::ProjectionPredicate {
743 projection_ty: ty::ProjectionTy {
744 trait_ref: candidate.0,
745 item_name: binding.item_name,
751 pub fn ast_path_to_ty<'tcx>(
752 this: &AstConv<'tcx>,
753 rscope: &RegionScope,
756 -> TypeAndSubsts<'tcx>
758 let tcx = this.tcx();
762 } = this.get_item_type_scheme(did);
764 let substs = ast_path_substs_for_ty(this,
768 let ty = decl_ty.subst(tcx, &substs);
769 TypeAndSubsts { substs: substs, ty: ty }
772 /// Returns the type that this AST path refers to. If the path has no type
773 /// parameters and the corresponding type has type parameters, fresh type
774 /// and/or region variables are substituted.
776 /// This is used when checking the constructor in struct literals.
777 pub fn ast_path_to_ty_relaxed<'tcx>(
778 this: &AstConv<'tcx>,
779 rscope: &RegionScope,
782 -> TypeAndSubsts<'tcx>
784 let tcx = this.tcx();
788 } = this.get_item_type_scheme(did);
791 generics.has_type_params(TypeSpace) || generics.has_region_params(TypeSpace);
795 path.segments.iter().all(|s| s.parameters.is_empty());
797 let substs = if needs_defaults {
798 let type_params: Vec<_> = range(0, generics.types.len(TypeSpace))
799 .map(|_| this.ty_infer(path.span)).collect();
801 rscope.anon_regions(path.span, generics.regions.len(TypeSpace))
803 Substs::new(VecPerParamSpace::params_from_type(type_params),
804 VecPerParamSpace::params_from_type(region_params))
806 ast_path_substs_for_ty(this, rscope, &generics, path)
809 let ty = decl_ty.subst(tcx, &substs);
816 /// Converts the given AST type to a built-in type. A "built-in type" is, at
817 /// present, either a core numeric type, a string, or `Box`.
818 pub fn ast_ty_to_builtin_ty<'tcx>(
819 this: &AstConv<'tcx>,
820 rscope: &RegionScope,
822 -> Option<Ty<'tcx>> {
823 match ast_ty_to_prim_ty(this.tcx(), ast_ty) {
824 Some(typ) => return Some(typ),
829 ast::TyPath(ref path, id) => {
830 let a_def = match this.tcx().def_map.borrow().get(&id) {
834 .span_bug(ast_ty.span,
835 format!("unbound path {}",
836 path.repr(this.tcx()))[])
841 // FIXME(#12938): This is a hack until we have full support for
845 def::DefStruct(did) if Some(did) == this.tcx().lang_items.owned_box() => {
846 let ty = ast_path_to_ty(this, rscope, did, path).ty;
848 ty::ty_struct(struct_def_id, ref substs) => {
849 assert_eq!(struct_def_id, did);
850 assert_eq!(substs.types.len(TypeSpace), 1);
851 let referent_ty = *substs.types.get(TypeSpace, 0);
852 Some(ty::mk_uniq(this.tcx(), referent_ty))
855 this.tcx().sess.span_bug(
857 format!("converting `Box` to `{}`",
858 ty.repr(this.tcx()))[]);
869 type TraitAndProjections<'tcx> = (ty::PolyTraitRef<'tcx>, Vec<ty::PolyProjectionPredicate<'tcx>>);
871 fn ast_ty_to_trait_ref<'tcx>(this: &AstConv<'tcx>,
872 rscope: &RegionScope,
874 bounds: &[ast::TyParamBound])
875 -> Result<TraitAndProjections<'tcx>, ErrorReported>
878 * In a type like `Foo + Send`, we want to wait to collect the
879 * full set of bounds before we make the object type, because we
880 * need them to infer a region bound. (For example, if we tried
881 * made a type from just `Foo`, then it wouldn't be enough to
882 * infer a 'static bound, and hence the user would get an error.)
883 * So this function is used when we're dealing with a sum type to
884 * convert the LHS. It only accepts a type that refers to a trait
885 * name, and reports an error otherwise.
889 ast::TyPath(ref path, id) => {
890 match this.tcx().def_map.borrow().get(&id) {
891 Some(&def::DefTrait(trait_def_id)) => {
892 let mut projection_bounds = Vec::new();
893 let trait_ref = ty::Binder(ast_path_to_trait_ref(this,
898 Some(&mut projection_bounds)));
899 let projection_bounds = projection_bounds.into_iter()
902 Ok((trait_ref, projection_bounds))
905 span_err!(this.tcx().sess, ty.span, E0172, "expected a reference to a trait");
911 span_err!(this.tcx().sess, ty.span, E0178,
912 "expected a path on the left-hand side of `+`, not `{}`",
913 pprust::ty_to_string(ty));
915 ast::TyRptr(None, ref mut_ty) => {
916 span_note!(this.tcx().sess, ty.span,
917 "perhaps you meant `&{}({} +{})`? (per RFC 438)",
918 ppaux::mutability_to_string(mut_ty.mutbl),
919 pprust::ty_to_string(&*mut_ty.ty),
920 pprust::bounds_to_string(bounds));
922 ast::TyRptr(Some(ref lt), ref mut_ty) => {
923 span_note!(this.tcx().sess, ty.span,
924 "perhaps you meant `&{} {}({} +{})`? (per RFC 438)",
925 pprust::lifetime_to_string(lt),
926 ppaux::mutability_to_string(mut_ty.mutbl),
927 pprust::ty_to_string(&*mut_ty.ty),
928 pprust::bounds_to_string(bounds));
932 span_note!(this.tcx().sess, ty.span,
933 "perhaps you forgot parentheses? (per RFC 438)");
941 fn trait_ref_to_object_type<'tcx>(this: &AstConv<'tcx>,
942 rscope: &RegionScope,
944 trait_ref: ty::PolyTraitRef<'tcx>,
945 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
946 bounds: &[ast::TyParamBound])
949 let existential_bounds = conv_existential_bounds(this,
952 Some(trait_ref.clone()),
956 let result = ty::mk_trait(this.tcx(), trait_ref, existential_bounds);
957 debug!("trait_ref_to_object_type: result={}",
958 result.repr(this.tcx()));
963 fn associated_path_def_to_ty<'tcx>(this: &AstConv<'tcx>,
965 provenance: def::TyParamProvenance,
966 assoc_name: ast::Name)
969 let tcx = this.tcx();
970 let ty_param_def_id = provenance.def_id();
972 let mut suitable_bounds: Vec<_>;
973 let ty_param_name: ast::Name;
974 { // contain scope of refcell:
975 let ty_param_defs = tcx.ty_param_defs.borrow();
976 let ty_param_def = &ty_param_defs[ty_param_def_id.node];
977 ty_param_name = ty_param_def.name;
979 // FIXME(#20300) -- search where clauses, not bounds
981 traits::transitive_bounds(tcx, ty_param_def.bounds.trait_bounds.as_slice())
982 .filter(|b| trait_defines_associated_type_named(this, b.def_id(), assoc_name))
986 if suitable_bounds.len() == 0 {
987 tcx.sess.span_err(ast_ty.span,
988 format!("associated type `{}` not found for type parameter `{}`",
989 token::get_name(assoc_name),
990 token::get_name(ty_param_name)).as_slice());
991 return this.tcx().types.err;
994 if suitable_bounds.len() > 1 {
995 tcx.sess.span_err(ast_ty.span,
996 format!("ambiguous associated type `{}` in bounds of `{}`",
997 token::get_name(assoc_name),
998 token::get_name(ty_param_name)).as_slice());
1000 for suitable_bound in suitable_bounds.iter() {
1001 span_note!(this.tcx().sess, ast_ty.span,
1002 "associated type `{}` could derive from `{}`",
1003 token::get_name(ty_param_name),
1004 suitable_bound.user_string(this.tcx()));
1008 let suitable_bound = suitable_bounds.pop().unwrap().clone();
1009 return this.projected_ty_from_poly_trait_ref(ast_ty.span, suitable_bound, assoc_name);
1012 fn trait_defines_associated_type_named(this: &AstConv,
1013 trait_def_id: ast::DefId,
1014 assoc_name: ast::Name)
1017 let tcx = this.tcx();
1018 let trait_def = ty::lookup_trait_def(tcx, trait_def_id);
1019 trait_def.associated_type_names.contains(&assoc_name)
1022 fn qpath_to_ty<'tcx>(this: &AstConv<'tcx>,
1023 rscope: &RegionScope,
1024 ast_ty: &ast::Ty, // the TyQPath
1028 debug!("qpath_to_ty(ast_ty={})",
1029 ast_ty.repr(this.tcx()));
1031 let self_type = ast_ty_to_ty(this, rscope, &*qpath.self_type);
1033 debug!("qpath_to_ty: self_type={}", self_type.repr(this.tcx()));
1035 let trait_ref = instantiate_trait_ref(this,
1041 debug!("qpath_to_ty: trait_ref={}", trait_ref.repr(this.tcx()));
1043 return this.projected_ty(ast_ty.span,
1045 qpath.item_name.name);
1048 // Parses the programmer's textual representation of a type into our
1049 // internal notion of a type.
1050 pub fn ast_ty_to_ty<'tcx>(
1051 this: &AstConv<'tcx>, rscope: &RegionScope, ast_ty: &ast::Ty) -> Ty<'tcx>
1053 debug!("ast_ty_to_ty(ast_ty={})",
1054 ast_ty.repr(this.tcx()));
1056 let tcx = this.tcx();
1058 let mut ast_ty_to_ty_cache = tcx.ast_ty_to_ty_cache.borrow_mut();
1059 match ast_ty_to_ty_cache.get(&ast_ty.id) {
1060 Some(&ty::atttce_resolved(ty)) => return ty,
1061 Some(&ty::atttce_unresolved) => {
1062 tcx.sess.span_fatal(ast_ty.span,
1063 "illegal recursive type; insert an enum \
1064 or struct in the cycle, if this is \
1067 None => { /* go on */ }
1069 ast_ty_to_ty_cache.insert(ast_ty.id, ty::atttce_unresolved);
1070 drop(ast_ty_to_ty_cache);
1072 let typ = ast_ty_to_builtin_ty(this, rscope, ast_ty).unwrap_or_else(|| {
1074 ast::TyVec(ref ty) => {
1075 ty::mk_vec(tcx, ast_ty_to_ty(this, rscope, &**ty), None)
1077 ast::TyObjectSum(ref ty, ref bounds) => {
1078 match ast_ty_to_trait_ref(this, rscope, &**ty, bounds[]) {
1079 Ok((trait_ref, projection_bounds)) => {
1080 trait_ref_to_object_type(this, rscope, ast_ty.span,
1081 trait_ref, projection_bounds, bounds[])
1083 Err(ErrorReported) => {
1084 this.tcx().types.err
1088 ast::TyPtr(ref mt) => {
1089 ty::mk_ptr(tcx, ty::mt {
1090 ty: ast_ty_to_ty(this, rscope, &*mt.ty),
1094 ast::TyRptr(ref region, ref mt) => {
1095 let r = opt_ast_region_to_region(this, rscope, ast_ty.span, region);
1096 debug!("ty_rptr r={}", r.repr(this.tcx()));
1097 let t = ast_ty_to_ty(this, rscope, &*mt.ty);
1098 ty::mk_rptr(tcx, tcx.mk_region(r), ty::mt {ty: t, mutbl: mt.mutbl})
1100 ast::TyTup(ref fields) => {
1101 let flds = fields.iter()
1102 .map(|t| ast_ty_to_ty(this, rscope, &**t))
1104 ty::mk_tup(tcx, flds)
1106 ast::TyParen(ref typ) => ast_ty_to_ty(this, rscope, &**typ),
1107 ast::TyBareFn(ref bf) => {
1108 if bf.decl.variadic && bf.abi != abi::C {
1109 tcx.sess.span_err(ast_ty.span,
1110 "variadic function must have C calling convention");
1112 let bare_fn = ty_of_bare_fn(this, bf.unsafety, bf.abi, &*bf.decl);
1113 ty::mk_bare_fn(tcx, None, tcx.mk_bare_fn(bare_fn))
1115 ast::TyPolyTraitRef(ref bounds) => {
1116 conv_ty_poly_trait_ref(this, rscope, ast_ty.span, bounds[])
1118 ast::TyPath(ref path, id) => {
1119 let a_def = match tcx.def_map.borrow().get(&id) {
1122 .span_bug(ast_ty.span,
1123 format!("unbound path {}",
1129 def::DefTrait(trait_def_id) => {
1130 // N.B. this case overlaps somewhat with
1131 // TyObjectSum, see that fn for details
1132 let mut projection_bounds = Vec::new();
1133 let trait_ref = ast_path_to_trait_ref(this,
1138 Some(&mut projection_bounds));
1139 let trait_ref = ty::Binder(trait_ref);
1140 let projection_bounds = projection_bounds.into_iter()
1143 trait_ref_to_object_type(this, rscope, path.span,
1144 trait_ref, projection_bounds, &[])
1146 def::DefTy(did, _) | def::DefStruct(did) => {
1147 ast_path_to_ty(this, rscope, did, path).ty
1149 def::DefTyParam(space, index, _, name) => {
1150 check_path_args(tcx, path, NO_TPS | NO_REGIONS);
1151 ty::mk_param(tcx, space, index, name)
1153 def::DefSelfTy(_) => {
1154 // n.b.: resolve guarantees that the this type only appears in a
1155 // trait, which we rely upon in various places when creating
1157 check_path_args(tcx, path, NO_TPS | NO_REGIONS);
1158 ty::mk_self_type(tcx)
1160 def::DefMod(id) => {
1161 tcx.sess.span_fatal(ast_ty.span,
1162 format!("found module name used as a type: {}",
1163 tcx.map.node_to_string(id.node))[]);
1165 def::DefPrimTy(_) => {
1166 panic!("DefPrimTy arm missed in previous ast_ty_to_prim_ty call");
1168 def::DefAssociatedTy(trait_type_id) => {
1169 let path_str = tcx.map.path_to_string(
1170 tcx.map.get_parent(trait_type_id.node));
1171 tcx.sess.span_err(ast_ty.span,
1172 format!("ambiguous associated \
1173 type; specify the type \
1174 using the syntax `<Type \
1183 this.tcx().types.err
1185 def::DefAssociatedPath(provenance, assoc_ident) => {
1186 associated_path_def_to_ty(this, ast_ty, provenance, assoc_ident.name)
1189 tcx.sess.span_fatal(ast_ty.span,
1190 format!("found value name used \
1196 ast::TyQPath(ref qpath) => {
1197 qpath_to_ty(this, rscope, ast_ty, &**qpath)
1199 ast::TyFixedLengthVec(ref ty, ref e) => {
1200 match const_eval::eval_const_expr_partial(tcx, &**e) {
1203 const_eval::const_int(i) =>
1204 ty::mk_vec(tcx, ast_ty_to_ty(this, rscope, &**ty),
1206 const_eval::const_uint(i) =>
1207 ty::mk_vec(tcx, ast_ty_to_ty(this, rscope, &**ty),
1210 tcx.sess.span_fatal(
1211 ast_ty.span, "expected constant expr for array length");
1216 tcx.sess.span_fatal(
1218 format!("expected constant expr for array \
1224 ast::TyTypeof(ref _e) => {
1225 tcx.sess.span_bug(ast_ty.span, "typeof is reserved but unimplemented");
1228 // TyInfer also appears as the type of arguments or return
1229 // values in a ExprClosure, or as
1230 // the type of local variables. Both of these cases are
1231 // handled specially and will not descend into this routine.
1232 this.ty_infer(ast_ty.span)
1237 tcx.ast_ty_to_ty_cache.borrow_mut().insert(ast_ty.id, ty::atttce_resolved(typ));
1241 pub fn ty_of_arg<'tcx>(this: &AstConv<'tcx>,
1242 rscope: &RegionScope,
1244 expected_ty: Option<Ty<'tcx>>)
1248 ast::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1249 ast::TyInfer => this.ty_infer(a.ty.span),
1250 _ => ast_ty_to_ty(this, rscope, &*a.ty),
1254 struct SelfInfo<'a, 'tcx> {
1255 untransformed_self_ty: Ty<'tcx>,
1256 explicit_self: &'a ast::ExplicitSelf,
1259 pub fn ty_of_method<'tcx>(this: &AstConv<'tcx>,
1260 unsafety: ast::Unsafety,
1261 untransformed_self_ty: Ty<'tcx>,
1262 explicit_self: &ast::ExplicitSelf,
1265 -> (ty::BareFnTy<'tcx>, ty::ExplicitSelfCategory) {
1266 let self_info = Some(SelfInfo {
1267 untransformed_self_ty: untransformed_self_ty,
1268 explicit_self: explicit_self,
1270 let (bare_fn_ty, optional_explicit_self_category) =
1271 ty_of_method_or_bare_fn(this,
1276 (bare_fn_ty, optional_explicit_self_category.unwrap())
1279 pub fn ty_of_bare_fn<'tcx>(this: &AstConv<'tcx>, unsafety: ast::Unsafety, abi: abi::Abi,
1280 decl: &ast::FnDecl) -> ty::BareFnTy<'tcx> {
1281 let (bare_fn_ty, _) = ty_of_method_or_bare_fn(this, unsafety, abi, None, decl);
1285 fn ty_of_method_or_bare_fn<'a, 'tcx>(this: &AstConv<'tcx>,
1286 unsafety: ast::Unsafety,
1288 opt_self_info: Option<SelfInfo<'a, 'tcx>>,
1290 -> (ty::BareFnTy<'tcx>, Option<ty::ExplicitSelfCategory>)
1292 debug!("ty_of_method_or_bare_fn");
1294 // New region names that appear inside of the arguments of the function
1295 // declaration are bound to that function type.
1296 let rb = rscope::BindingRscope::new();
1298 // `implied_output_region` is the region that will be assumed for any
1299 // region parameters in the return type. In accordance with the rules for
1300 // lifetime elision, we can determine it in two ways. First (determined
1301 // here), if self is by-reference, then the implied output region is the
1302 // region of the self parameter.
1303 let mut explicit_self_category_result = None;
1304 let (self_ty, mut implied_output_region) = match opt_self_info {
1305 None => (None, None),
1306 Some(self_info) => {
1307 // This type comes from an impl or trait; no late-bound
1308 // regions should be present.
1309 assert!(!self_info.untransformed_self_ty.has_escaping_regions());
1311 // Figure out and record the explicit self category.
1312 let explicit_self_category =
1313 determine_explicit_self_category(this, &rb, &self_info);
1314 explicit_self_category_result = Some(explicit_self_category);
1315 match explicit_self_category {
1316 ty::StaticExplicitSelfCategory => {
1319 ty::ByValueExplicitSelfCategory => {
1320 (Some(self_info.untransformed_self_ty), None)
1322 ty::ByReferenceExplicitSelfCategory(region, mutability) => {
1323 (Some(ty::mk_rptr(this.tcx(),
1324 this.tcx().mk_region(region),
1326 ty: self_info.untransformed_self_ty,
1331 ty::ByBoxExplicitSelfCategory => {
1332 (Some(ty::mk_uniq(this.tcx(), self_info.untransformed_self_ty)), None)
1338 // HACK(eddyb) replace the fake self type in the AST with the actual type.
1339 let input_params = if self_ty.is_some() {
1340 decl.inputs.slice_from(1)
1344 let input_tys = input_params.iter().map(|a| ty_of_arg(this, &rb, a, None));
1345 let input_pats: Vec<String> = input_params.iter()
1346 .map(|a| pprust::pat_to_string(&*a.pat))
1348 let self_and_input_tys: Vec<Ty> =
1349 self_ty.into_iter().chain(input_tys).collect();
1352 // Second, if there was exactly one lifetime (either a substitution or a
1353 // reference) in the arguments, then any anonymous regions in the output
1354 // have that lifetime.
1355 let lifetimes_for_params = if implied_output_region.is_none() {
1356 let input_tys = if self_ty.is_some() {
1357 // Skip the first argument if `self` is present.
1358 self_and_input_tys.slice_from(1)
1360 self_and_input_tys.slice_from(0)
1363 let (ior, lfp) = find_implied_output_region(input_tys, input_pats);
1364 implied_output_region = ior;
1370 let output_ty = match decl.output {
1371 ast::Return(ref output) if output.node == ast::TyInfer =>
1372 ty::FnConverging(this.ty_infer(output.span)),
1373 ast::Return(ref output) =>
1374 ty::FnConverging(convert_ty_with_lifetime_elision(this,
1375 implied_output_region,
1376 lifetimes_for_params,
1378 ast::NoReturn(_) => ty::FnDiverging
1384 sig: ty::Binder(ty::FnSig {
1385 inputs: self_and_input_tys,
1387 variadic: decl.variadic
1389 }, explicit_self_category_result)
1392 fn determine_explicit_self_category<'a, 'tcx>(this: &AstConv<'tcx>,
1393 rscope: &RegionScope,
1394 self_info: &SelfInfo<'a, 'tcx>)
1395 -> ty::ExplicitSelfCategory
1397 return match self_info.explicit_self.node {
1398 ast::SelfStatic => ty::StaticExplicitSelfCategory,
1399 ast::SelfValue(_) => ty::ByValueExplicitSelfCategory,
1400 ast::SelfRegion(ref lifetime, mutability, _) => {
1402 opt_ast_region_to_region(this,
1404 self_info.explicit_self.span,
1406 ty::ByReferenceExplicitSelfCategory(region, mutability)
1408 ast::SelfExplicit(ref ast_type, _) => {
1409 let explicit_type = ast_ty_to_ty(this, rscope, &**ast_type);
1411 // We wish to (for now) categorize an explicit self
1412 // declaration like `self: SomeType` into either `self`,
1413 // `&self`, `&mut self`, or `Box<self>`. We do this here
1414 // by some simple pattern matching. A more precise check
1415 // is done later in `check_method_self_type()`.
1420 // impl Foo for &T {
1421 // // Legal declarations:
1422 // fn method1(self: &&T); // ByReferenceExplicitSelfCategory
1423 // fn method2(self: &T); // ByValueExplicitSelfCategory
1424 // fn method3(self: Box<&T>); // ByBoxExplicitSelfCategory
1426 // // Invalid cases will be caught later by `check_method_self_type`:
1427 // fn method_err1(self: &mut T); // ByReferenceExplicitSelfCategory
1431 // To do the check we just count the number of "modifiers"
1432 // on each type and compare them. If they are the same or
1433 // the impl has more, we call it "by value". Otherwise, we
1434 // look at the outermost modifier on the method decl and
1435 // call it by-ref, by-box as appropriate. For method1, for
1436 // example, the impl type has one modifier, but the method
1437 // type has two, so we end up with
1438 // ByReferenceExplicitSelfCategory.
1440 let impl_modifiers = count_modifiers(self_info.untransformed_self_ty);
1441 let method_modifiers = count_modifiers(explicit_type);
1443 debug!("determine_explicit_self_category(self_info.untransformed_self_ty={} \
1446 self_info.untransformed_self_ty.repr(this.tcx()),
1447 explicit_type.repr(this.tcx()),
1451 if impl_modifiers >= method_modifiers {
1452 ty::ByValueExplicitSelfCategory
1454 match explicit_type.sty {
1455 ty::ty_rptr(r, mt) => ty::ByReferenceExplicitSelfCategory(*r, mt.mutbl),
1456 ty::ty_uniq(_) => ty::ByBoxExplicitSelfCategory,
1457 _ => ty::ByValueExplicitSelfCategory,
1463 fn count_modifiers(ty: Ty) -> uint {
1465 ty::ty_rptr(_, mt) => count_modifiers(mt.ty) + 1,
1466 ty::ty_uniq(t) => count_modifiers(t) + 1,
1472 pub fn ty_of_closure<'tcx>(
1473 this: &AstConv<'tcx>,
1474 unsafety: ast::Unsafety,
1475 onceness: ast::Onceness,
1476 bounds: ty::ExistentialBounds<'tcx>,
1477 store: ty::TraitStore,
1480 expected_sig: Option<ty::FnSig<'tcx>>)
1481 -> ty::ClosureTy<'tcx>
1483 debug!("ty_of_closure(expected_sig={})",
1484 expected_sig.repr(this.tcx()));
1486 // new region names that appear inside of the fn decl are bound to
1487 // that function type
1488 let rb = rscope::BindingRscope::new();
1490 let input_tys: Vec<_> = decl.inputs.iter().enumerate().map(|(i, a)| {
1491 let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1492 // no guarantee that the correct number of expected args
1494 if i < e.inputs.len() {
1500 ty_of_arg(this, &rb, a, expected_arg_ty)
1503 let expected_ret_ty = expected_sig.map(|e| e.output);
1505 let output_ty = match decl.output {
1506 ast::Return(ref output) if output.node == ast::TyInfer && expected_ret_ty.is_some() =>
1507 expected_ret_ty.unwrap(),
1508 ast::Return(ref output) if output.node == ast::TyInfer =>
1509 ty::FnConverging(this.ty_infer(output.span)),
1510 ast::Return(ref output) =>
1511 ty::FnConverging(ast_ty_to_ty(this, &rb, &**output)),
1512 ast::NoReturn(_) => ty::FnDiverging
1515 debug!("ty_of_closure: input_tys={}", input_tys.repr(this.tcx()));
1516 debug!("ty_of_closure: output_ty={}", output_ty.repr(this.tcx()));
1524 sig: ty::Binder(ty::FnSig {inputs: input_tys,
1526 variadic: decl.variadic}),
1530 /// Given an existential type like `Foo+'a+Bar`, this routine converts the `'a` and `Bar` intos an
1531 /// `ExistentialBounds` struct. The `main_trait_refs` argument specifies the `Foo` -- it is absent
1532 /// for closures. Eventually this should all be normalized, I think, so that there is no "main
1533 /// trait ref" and instead we just have a flat list of bounds as the existential type.
1534 pub fn conv_existential_bounds<'tcx>(
1535 this: &AstConv<'tcx>,
1536 rscope: &RegionScope,
1538 principal_trait_ref: Option<ty::PolyTraitRef<'tcx>>, // None for boxed closures
1539 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
1540 ast_bounds: &[ast::TyParamBound])
1541 -> ty::ExistentialBounds<'tcx>
1543 let partitioned_bounds =
1544 partition_bounds(this.tcx(), span, ast_bounds);
1546 conv_existential_bounds_from_partitioned_bounds(
1547 this, rscope, span, principal_trait_ref, projection_bounds, partitioned_bounds)
1550 fn conv_ty_poly_trait_ref<'tcx>(
1551 this: &AstConv<'tcx>,
1552 rscope: &RegionScope,
1554 ast_bounds: &[ast::TyParamBound])
1557 let mut partitioned_bounds = partition_bounds(this.tcx(), span, ast_bounds[]);
1559 let mut projection_bounds = Vec::new();
1560 let main_trait_bound = if !partitioned_bounds.trait_bounds.is_empty() {
1561 let trait_bound = partitioned_bounds.trait_bounds.remove(0);
1562 Some(instantiate_poly_trait_ref(this,
1566 &mut projection_bounds))
1568 this.tcx().sess.span_err(
1570 "at least one non-builtin trait is required for an object type");
1575 conv_existential_bounds_from_partitioned_bounds(this,
1578 main_trait_bound.clone(),
1580 partitioned_bounds);
1582 match main_trait_bound {
1583 None => this.tcx().types.err,
1584 Some(principal) => ty::mk_trait(this.tcx(), principal, bounds)
1588 pub fn conv_existential_bounds_from_partitioned_bounds<'tcx>(
1589 this: &AstConv<'tcx>,
1590 rscope: &RegionScope,
1592 principal_trait_ref: Option<ty::PolyTraitRef<'tcx>>, // None for boxed closures
1593 mut projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>, // Empty for boxed closures
1594 partitioned_bounds: PartitionedBounds)
1595 -> ty::ExistentialBounds<'tcx>
1597 let PartitionedBounds { builtin_bounds,
1602 if !trait_bounds.is_empty() {
1603 let b = &trait_bounds[0];
1604 this.tcx().sess.span_err(
1605 b.trait_ref.path.span,
1606 format!("only the builtin traits can be used \
1607 as closure or object bounds")[]);
1610 let region_bound = compute_region_bound(this,
1613 region_bounds.as_slice(),
1614 principal_trait_ref,
1617 ty::sort_bounds_list(projection_bounds.as_mut_slice());
1619 ty::ExistentialBounds {
1620 region_bound: region_bound,
1621 builtin_bounds: builtin_bounds,
1622 projection_bounds: projection_bounds,
1626 /// Given the bounds on a type parameter / existential type, determines what single region bound
1627 /// (if any) we can use to summarize this type. The basic idea is that we will use the bound the
1628 /// user provided, if they provided one, and otherwise search the supertypes of trait bounds for
1629 /// region bounds. It may be that we can derive no bound at all, in which case we return `None`.
1630 fn compute_opt_region_bound<'tcx>(tcx: &ty::ctxt<'tcx>,
1632 explicit_region_bounds: &[&ast::Lifetime],
1633 principal_trait_ref: Option<ty::PolyTraitRef<'tcx>>,
1634 builtin_bounds: ty::BuiltinBounds)
1635 -> Option<ty::Region>
1637 debug!("compute_opt_region_bound(explicit_region_bounds={}, \
1638 principal_trait_ref={}, builtin_bounds={})",
1639 explicit_region_bounds,
1640 principal_trait_ref.repr(tcx),
1641 builtin_bounds.repr(tcx));
1643 if explicit_region_bounds.len() > 1 {
1645 explicit_region_bounds[1].span,
1646 format!("only a single explicit lifetime bound is permitted").as_slice());
1649 if explicit_region_bounds.len() != 0 {
1650 // Explicitly specified region bound. Use that.
1651 let r = explicit_region_bounds[0];
1652 return Some(ast_region_to_region(tcx, r));
1655 // No explicit region bound specified. Therefore, examine trait
1656 // bounds and see if we can derive region bounds from those.
1657 let derived_region_bounds =
1658 ty::object_region_bounds(tcx, principal_trait_ref.as_ref(), builtin_bounds);
1660 // If there are no derived region bounds, then report back that we
1661 // can find no region bound.
1662 if derived_region_bounds.len() == 0 {
1666 // If any of the derived region bounds are 'static, that is always
1668 if derived_region_bounds.iter().any(|r| ty::ReStatic == *r) {
1669 return Some(ty::ReStatic);
1672 // Determine whether there is exactly one unique region in the set
1673 // of derived region bounds. If so, use that. Otherwise, report an
1675 let r = derived_region_bounds[0];
1676 if derived_region_bounds.slice_from(1).iter().any(|r1| r != *r1) {
1679 format!("ambiguous lifetime bound, \
1680 explicit lifetime bound required")[]);
1685 /// A version of `compute_opt_region_bound` for use where some region bound is required
1686 /// (existential types, basically). Reports an error if no region bound can be derived and we are
1687 /// in an `rscope` that does not provide a default.
1688 fn compute_region_bound<'tcx>(
1689 this: &AstConv<'tcx>,
1690 rscope: &RegionScope,
1692 region_bounds: &[&ast::Lifetime],
1693 principal_trait_ref: Option<ty::PolyTraitRef<'tcx>>, // None for closures
1694 builtin_bounds: ty::BuiltinBounds)
1697 match compute_opt_region_bound(this.tcx(), span, region_bounds,
1698 principal_trait_ref, builtin_bounds) {
1701 match rscope.default_region_bound(span) {
1704 this.tcx().sess.span_err(
1706 format!("explicit lifetime bound required")[]);
1714 pub struct PartitionedBounds<'a> {
1715 pub builtin_bounds: ty::BuiltinBounds,
1716 pub trait_bounds: Vec<&'a ast::PolyTraitRef>,
1717 pub region_bounds: Vec<&'a ast::Lifetime>,
1720 /// Divides a list of bounds from the AST into three groups: builtin bounds (Copy, Sized etc),
1721 /// general trait bounds, and region bounds.
1722 pub fn partition_bounds<'a>(tcx: &ty::ctxt,
1724 ast_bounds: &'a [ast::TyParamBound])
1725 -> PartitionedBounds<'a>
1727 let mut builtin_bounds = ty::empty_builtin_bounds();
1728 let mut region_bounds = Vec::new();
1729 let mut trait_bounds = Vec::new();
1730 let mut trait_def_ids = DefIdMap::new();
1731 for ast_bound in ast_bounds.iter() {
1733 ast::TraitTyParamBound(ref b, ast::TraitBoundModifier::None) => {
1734 match ::lookup_def_tcx(tcx, b.trait_ref.path.span, b.trait_ref.ref_id) {
1735 def::DefTrait(trait_did) => {
1736 match trait_def_ids.get(&trait_did) {
1737 // Already seen this trait. We forbid
1738 // duplicates in the list (for some
1742 tcx.sess, b.trait_ref.path.span, E0127,
1743 "trait `{}` already appears in the \
1745 b.trait_ref.path.user_string(tcx));
1748 "previous appearance is here");
1756 trait_def_ids.insert(trait_did, b.trait_ref.path.span);
1758 if ty::try_add_builtin_trait(tcx,
1760 &mut builtin_bounds) {
1761 // FIXME(#20302) -- we should check for things like Copy<T>
1762 continue; // success
1766 // Not a trait? that's an error, but it'll get
1770 trait_bounds.push(b);
1772 ast::TraitTyParamBound(_, ast::TraitBoundModifier::Maybe) => {}
1773 ast::RegionTyParamBound(ref l) => {
1774 region_bounds.push(l);
1780 builtin_bounds: builtin_bounds,
1781 trait_bounds: trait_bounds,
1782 region_bounds: region_bounds,
1786 fn prohibit_projections<'tcx>(tcx: &ty::ctxt<'tcx>,
1787 bindings: &[ConvertedBinding<'tcx>])
1789 for binding in bindings.iter().take(1) {
1792 "associated type bindings are not allowed here");