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()`
20 //! function triggers a recursive call to `type_scheme_of_item()`
21 //! (note that `ast_ty_to_ty()` will detect recursive types and report
22 //! an error). In the check phase, when the FnCtxt is used as the
23 //! `AstConv`, `get_item_type_scheme()` just looks up the item type in
24 //! `tcx.tcache` (using `ty::lookup_item_type`).
26 //! The `RegionScope` trait controls what happens when the user does
27 //! not specify a region in some location where a region is required
28 //! (e.g., if the user writes `&Foo` as a type rather than `&'a Foo`).
29 //! See the `rscope` module for more details.
31 //! Unlike the `AstConv` trait, the region scope can change as we descend
32 //! the type. This is to accommodate the fact that (a) fn types are binding
33 //! scopes and (b) the default region may change. To understand case (a),
34 //! consider something like:
36 //! type foo = { x: &a.int, y: |&a.int| }
38 //! The type of `x` is an error because there is no region `a` in scope.
39 //! In the type of `y`, however, region `a` is considered a bound region
40 //! as it does not already appear in scope.
42 //! Case (b) says that if you have a type:
43 //! type foo<'a> = ...;
44 //! type bar = fn(&foo, &a.foo)
45 //! The fully expanded version of type bar is:
46 //! type bar = fn(&'foo &, &a.foo<'a>)
47 //! Note that the self region for the `foo` defaulted to `&` in the first
48 //! case but `&a` in the second. Basically, defaults that appear inside
49 //! an rptr (`&r.T`) use the region `r` that appears in the rptr.
51 use middle::astconv_util::{prim_ty_to_ty, prohibit_type_params, prohibit_projection};
52 use middle::const_eval::{self, ConstVal};
53 use middle::const_eval::EvalHint::UncheckedExprHint;
55 use middle::def_id::DefId;
56 use middle::resolve_lifetime as rl;
57 use middle::privacy::{AllPublic, LastMod};
58 use middle::subst::{FnSpace, TypeSpace, SelfSpace, Subst, Substs, ParamSpace};
60 use middle::ty::{self, RegionEscape, Ty, ToPredicate, HasTypeFlags};
61 use middle::ty::wf::object_region_bounds;
62 use require_c_abi_if_variadic;
63 use rscope::{self, UnelidableRscope, RegionScope, ElidableRscope,
64 ObjectLifetimeDefaultRscope, ShiftedRscope, BindingRscope,
65 ElisionFailureInfo, ElidedLifetime};
66 use util::common::{ErrorReported, FN_OUTPUT_NAME};
67 use util::nodemap::FnvHashSet;
69 use syntax::{abi, ast};
70 use syntax::codemap::{Span, Pos};
71 use syntax::feature_gate::{GateIssue, emit_feature_err};
72 use syntax::parse::token;
74 use rustc_front::print::pprust;
76 use rustc_back::slice;
78 pub trait AstConv<'tcx> {
79 fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx>;
81 /// Identify the type scheme for an item with a type, like a type
82 /// alias, fn, or struct. This allows you to figure out the set of
83 /// type parameters defined on the item.
84 fn get_item_type_scheme(&self, span: Span, id: DefId)
85 -> Result<ty::TypeScheme<'tcx>, ErrorReported>;
87 /// Returns the `TraitDef` for a given trait. This allows you to
88 /// figure out the set of type parameters defined on the trait.
89 fn get_trait_def(&self, span: Span, id: DefId)
90 -> Result<&'tcx ty::TraitDef<'tcx>, ErrorReported>;
92 /// Ensure that the super-predicates for the trait with the given
93 /// id are available and also for the transitive set of
95 fn ensure_super_predicates(&self, span: Span, id: DefId)
96 -> Result<(), ErrorReported>;
98 /// Returns the set of bounds in scope for the type parameter with
100 fn get_type_parameter_bounds(&self, span: Span, def_id: ast::NodeId)
101 -> Result<Vec<ty::PolyTraitRef<'tcx>>, ErrorReported>;
103 /// Returns true if the trait with id `trait_def_id` defines an
104 /// associated type with the name `name`.
105 fn trait_defines_associated_type_named(&self, trait_def_id: DefId, name: ast::Name)
108 /// Return an (optional) substitution to convert bound type parameters that
109 /// are in scope into free ones. This function should only return Some
110 /// within a fn body.
111 /// See ParameterEnvironment::free_substs for more information.
112 fn get_free_substs(&self) -> Option<&Substs<'tcx>> {
116 /// What type should we use when a type is omitted?
118 param_and_substs: Option<ty::TypeParameterDef<'tcx>>,
119 substs: Option<&mut Substs<'tcx>>,
120 space: Option<ParamSpace>,
121 span: Span) -> Ty<'tcx>;
123 /// Projecting an associated type from a (potentially)
124 /// higher-ranked trait reference is more complicated, because of
125 /// the possibility of late-bound regions appearing in the
126 /// associated type binding. This is not legal in function
127 /// signatures for that reason. In a function body, we can always
128 /// handle it because we can use inference variables to remove the
129 /// late-bound regions.
130 fn projected_ty_from_poly_trait_ref(&self,
132 poly_trait_ref: ty::PolyTraitRef<'tcx>,
133 item_name: ast::Name)
136 if let Some(trait_ref) = self.tcx().no_late_bound_regions(&poly_trait_ref) {
137 self.projected_ty(span, trait_ref, item_name)
139 // no late-bound regions, we can just ignore the binder
140 span_err!(self.tcx().sess, span, E0212,
141 "cannot extract an associated type from a higher-ranked trait bound \
147 /// Project an associated type from a non-higher-ranked trait reference.
148 /// This is fairly straightforward and can be accommodated in any context.
149 fn projected_ty(&self,
151 _trait_ref: ty::TraitRef<'tcx>,
152 _item_name: ast::Name)
156 pub fn ast_region_to_region(tcx: &ty::ctxt, lifetime: &hir::Lifetime)
158 let r = match tcx.named_region_map.get(&lifetime.id) {
160 // should have been recorded by the `resolve_lifetime` pass
161 tcx.sess.span_bug(lifetime.span, "unresolved lifetime");
164 Some(&rl::DefStaticRegion) => {
168 Some(&rl::DefLateBoundRegion(debruijn, id)) => {
169 ty::ReLateBound(debruijn, ty::BrNamed(tcx.map.local_def_id(id), lifetime.name))
172 Some(&rl::DefEarlyBoundRegion(space, index, id)) => {
173 let def_id = tcx.map.local_def_id(id);
174 ty::ReEarlyBound(ty::EarlyBoundRegion {
182 Some(&rl::DefFreeRegion(scope, id)) => {
183 ty::ReFree(ty::FreeRegion {
184 scope: scope.to_code_extent(&tcx.region_maps),
185 bound_region: ty::BrNamed(tcx.map.local_def_id(id),
191 debug!("ast_region_to_region(lifetime={:?} id={}) yields {:?}",
199 fn report_elision_failure(
202 params: Vec<ElisionFailureInfo>)
204 let mut m = String::new();
205 let len = params.len();
206 let mut any_lifetimes = false;
208 for (i, info) in params.into_iter().enumerate() {
209 let ElisionFailureInfo {
210 name, lifetime_count: n, have_bound_regions
213 any_lifetimes = any_lifetimes || (n > 0);
215 let help_name = if name.is_empty() {
216 format!("argument {}", i + 1)
218 format!("`{}`", name)
221 m.push_str(&(if n == 1 {
224 format!("one of {}'s {} elided {}lifetimes", help_name, n,
225 if have_bound_regions { "free " } else { "" } )
228 if len == 2 && i == 0 {
230 } else if i + 2 == len {
232 } else if i + 1 != len {
238 fileline_help!(tcx.sess, default_span,
239 "this function's return type contains a borrowed value, but \
240 there is no value for it to be borrowed from");
241 fileline_help!(tcx.sess, default_span,
242 "consider giving it a 'static lifetime");
243 } else if !any_lifetimes {
244 fileline_help!(tcx.sess, default_span,
245 "this function's return type contains a borrowed value with \
246 an elided lifetime, but the lifetime cannot be derived from \
248 fileline_help!(tcx.sess, default_span,
249 "consider giving it an explicit bounded or 'static \
252 fileline_help!(tcx.sess, default_span,
253 "this function's return type contains a borrowed value, but \
254 the signature does not say which {} it is borrowed from",
257 fileline_help!(tcx.sess, default_span,
258 "this function's return type contains a borrowed value, but \
259 the signature does not say whether it is borrowed from {}",
264 pub fn opt_ast_region_to_region<'tcx>(
265 this: &AstConv<'tcx>,
266 rscope: &RegionScope,
268 opt_lifetime: &Option<hir::Lifetime>) -> ty::Region
270 let r = match *opt_lifetime {
271 Some(ref lifetime) => {
272 ast_region_to_region(this.tcx(), lifetime)
275 None => match rscope.anon_regions(default_span, 1) {
278 span_err!(this.tcx().sess, default_span, E0106,
279 "missing lifetime specifier");
280 if let Some(params) = params {
281 report_elision_failure(this.tcx(), default_span, params);
288 debug!("opt_ast_region_to_region(opt_lifetime={:?}) yields {:?}",
295 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
296 /// returns an appropriate set of substitutions for this particular reference to `I`.
297 pub fn ast_path_substs_for_ty<'tcx>(
298 this: &AstConv<'tcx>,
299 rscope: &RegionScope,
301 param_mode: PathParamMode,
302 decl_generics: &ty::Generics<'tcx>,
303 item_segment: &hir::PathSegment)
306 let tcx = this.tcx();
308 // ast_path_substs() is only called to convert paths that are
309 // known to refer to traits, types, or structs. In these cases,
310 // all type parameters defined for the item being referenced will
311 // be in the TypeSpace or SelfSpace.
313 // Note: in the case of traits, the self parameter is also
314 // defined, but we don't currently create a `type_param_def` for
315 // `Self` because it is implicit.
316 assert!(decl_generics.regions.all(|d| d.space == TypeSpace));
317 assert!(decl_generics.types.all(|d| d.space != FnSpace));
319 let (regions, types, assoc_bindings) = match item_segment.parameters {
320 hir::AngleBracketedParameters(ref data) => {
321 convert_angle_bracketed_parameters(this, rscope, span, decl_generics, data)
323 hir::ParenthesizedParameters(..) => {
324 span_err!(tcx.sess, span, E0214,
325 "parenthesized parameters may only be used with a trait");
326 let ty_param_defs = decl_generics.types.get_slice(TypeSpace);
328 ty_param_defs.iter().map(|_| tcx.types.err).collect(),
333 prohibit_projections(this.tcx(), &assoc_bindings);
335 create_substs_for_ast_path(this,
344 #[derive(PartialEq, Eq)]
345 pub enum PathParamMode {
346 // Any path in a type context.
348 // The `module::Type` in `module::Type::method` in an expression.
352 fn create_region_substs<'tcx>(
353 this: &AstConv<'tcx>,
354 rscope: &RegionScope,
356 decl_generics: &ty::Generics<'tcx>,
357 regions_provided: Vec<ty::Region>)
360 let tcx = this.tcx();
362 // If the type is parameterized by this region, then replace this
363 // region with the current anon region binding (in other words,
364 // whatever & would get replaced with).
365 let expected_num_region_params = decl_generics.regions.len(TypeSpace);
366 let supplied_num_region_params = regions_provided.len();
367 let regions = if expected_num_region_params == supplied_num_region_params {
371 rscope.anon_regions(span, expected_num_region_params);
373 if supplied_num_region_params != 0 || anon_regions.is_err() {
374 report_lifetime_number_error(tcx, span,
375 supplied_num_region_params,
376 expected_num_region_params);
380 Ok(anon_regions) => anon_regions,
381 Err(_) => (0..expected_num_region_params).map(|_| ty::ReStatic).collect()
384 Substs::new_type(vec![], regions)
387 /// Given the type/region arguments provided to some path (along with
388 /// an implicit Self, if this is a trait reference) returns the complete
389 /// set of substitutions. This may involve applying defaulted type parameters.
391 /// Note that the type listing given here is *exactly* what the user provided.
393 /// The `region_substs` should be the result of `create_region_substs`
394 /// -- that is, a substitution with no types but the correct number of
396 fn create_substs_for_ast_path<'tcx>(
397 this: &AstConv<'tcx>,
399 param_mode: PathParamMode,
400 decl_generics: &ty::Generics<'tcx>,
401 self_ty: Option<Ty<'tcx>>,
402 types_provided: Vec<Ty<'tcx>>,
403 region_substs: Substs<'tcx>)
406 let tcx = this.tcx();
408 debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}, \
409 types_provided={:?}, region_substs={:?})",
410 decl_generics, self_ty, types_provided,
413 assert_eq!(region_substs.regions().len(TypeSpace), decl_generics.regions.len(TypeSpace));
414 assert!(region_substs.types.is_empty());
416 // Convert the type parameters supplied by the user.
417 let ty_param_defs = decl_generics.types.get_slice(TypeSpace);
418 let formal_ty_param_count = ty_param_defs.len();
419 let required_ty_param_count = ty_param_defs.iter()
420 .take_while(|x| x.default.is_none())
423 let mut type_substs = get_type_substs_for_defs(this,
428 region_substs.clone(),
431 let supplied_ty_param_count = type_substs.len();
432 check_type_argument_count(this.tcx(), span, supplied_ty_param_count,
433 required_ty_param_count, formal_ty_param_count);
435 if supplied_ty_param_count < required_ty_param_count {
436 while type_substs.len() < required_ty_param_count {
437 type_substs.push(tcx.types.err);
439 } else if supplied_ty_param_count > formal_ty_param_count {
440 type_substs.truncate(formal_ty_param_count);
442 assert!(type_substs.len() >= required_ty_param_count &&
443 type_substs.len() <= formal_ty_param_count);
445 let mut substs = region_substs;
446 substs.types.extend(TypeSpace, type_substs.into_iter());
450 // If no self-type is provided, it's still possible that
451 // one was declared, because this could be an object type.
454 // If a self-type is provided, one should have been
455 // "declared" (in other words, this should be a
457 assert!(decl_generics.types.get_self().is_some());
458 substs.types.push(SelfSpace, ty);
462 let actual_supplied_ty_param_count = substs.types.len(TypeSpace);
463 for param in &ty_param_defs[actual_supplied_ty_param_count..] {
464 if let Some(default) = param.default {
465 // If we are converting an object type, then the
466 // `Self` parameter is unknown. However, some of the
467 // other type parameters may reference `Self` in their
468 // defaults. This will lead to an ICE if we are not
470 if self_ty.is_none() && default.has_self_ty() {
471 span_err!(tcx.sess, span, E0393,
472 "the type parameter `{}` must be explicitly specified \
473 in an object type because its default value `{}` references \
477 substs.types.push(TypeSpace, tcx.types.err);
479 // This is a default type parameter.
480 let default = default.subst_spanned(tcx,
483 substs.types.push(TypeSpace, default);
486 tcx.sess.span_bug(span, "extra parameter without default");
490 debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}) -> {:?}",
491 decl_generics, self_ty, substs);
496 /// Returns types_provided if it is not empty, otherwise populating the
497 /// type parameters with inference variables as appropriate.
498 fn get_type_substs_for_defs<'tcx>(this: &AstConv<'tcx>,
500 types_provided: Vec<Ty<'tcx>>,
501 param_mode: PathParamMode,
502 ty_param_defs: &[ty::TypeParameterDef<'tcx>],
503 mut substs: Substs<'tcx>,
504 self_ty: Option<Ty<'tcx>>)
507 fn default_type_parameter<'tcx>(p: &ty::TypeParameterDef<'tcx>, self_ty: Option<Ty<'tcx>>)
508 -> Option<ty::TypeParameterDef<'tcx>>
510 if let Some(ref default) = p.default {
511 if self_ty.is_none() && default.has_self_ty() {
512 // There is no suitable inference default for a type parameter
513 // that references self with no self-type provided.
521 if param_mode == PathParamMode::Optional && types_provided.is_empty() {
524 .map(|p| this.ty_infer(default_type_parameter(p, self_ty), Some(&mut substs),
525 Some(TypeSpace), span))
532 struct ConvertedBinding<'tcx> {
533 item_name: ast::Name,
538 fn convert_angle_bracketed_parameters<'tcx>(this: &AstConv<'tcx>,
539 rscope: &RegionScope,
541 decl_generics: &ty::Generics<'tcx>,
542 data: &hir::AngleBracketedParameterData)
545 Vec<ConvertedBinding<'tcx>>)
547 let regions: Vec<_> =
548 data.lifetimes.iter()
549 .map(|l| ast_region_to_region(this.tcx(), l))
553 create_region_substs(this, rscope, span, decl_generics, regions);
558 .map(|(i,t)| ast_ty_arg_to_ty(this, rscope, decl_generics,
559 i, ®ion_substs, t))
562 let assoc_bindings: Vec<_> =
564 .map(|b| ConvertedBinding { item_name: b.name,
565 ty: ast_ty_to_ty(this, rscope, &*b.ty),
569 (region_substs, types, assoc_bindings)
572 /// Returns the appropriate lifetime to use for any output lifetimes
573 /// (if one exists) and a vector of the (pattern, number of lifetimes)
574 /// corresponding to each input type/pattern.
575 fn find_implied_output_region<'tcx>(tcx: &ty::ctxt<'tcx>,
576 input_tys: &[Ty<'tcx>],
577 input_pats: Vec<String>) -> ElidedLifetime
579 let mut lifetimes_for_params = Vec::new();
580 let mut possible_implied_output_region = None;
582 for (input_type, input_pat) in input_tys.iter().zip(input_pats) {
583 let mut regions = FnvHashSet();
584 let have_bound_regions = tcx.collect_regions(input_type, &mut regions);
586 debug!("find_implied_output_regions: collected {:?} from {:?} \
587 have_bound_regions={:?}", ®ions, input_type, have_bound_regions);
589 if regions.len() == 1 {
590 // there's a chance that the unique lifetime of this
591 // iteration will be the appropriate lifetime for output
592 // parameters, so lets store it.
593 possible_implied_output_region = regions.iter().cloned().next();
596 lifetimes_for_params.push(ElisionFailureInfo {
598 lifetime_count: regions.len(),
599 have_bound_regions: have_bound_regions
603 if lifetimes_for_params.iter().map(|e| e.lifetime_count).sum::<usize>() == 1 {
604 Ok(possible_implied_output_region.unwrap())
606 Err(Some(lifetimes_for_params))
610 fn convert_ty_with_lifetime_elision<'tcx>(this: &AstConv<'tcx>,
611 elided_lifetime: ElidedLifetime,
615 match elided_lifetime {
616 Ok(implied_output_region) => {
617 let rb = ElidableRscope::new(implied_output_region);
618 ast_ty_to_ty(this, &rb, ty)
620 Err(param_lifetimes) => {
621 // All regions must be explicitly specified in the output
622 // if the lifetime elision rules do not apply. This saves
623 // the user from potentially-confusing errors.
624 let rb = UnelidableRscope::new(param_lifetimes);
625 ast_ty_to_ty(this, &rb, ty)
630 fn convert_parenthesized_parameters<'tcx>(this: &AstConv<'tcx>,
631 rscope: &RegionScope,
633 decl_generics: &ty::Generics<'tcx>,
634 data: &hir::ParenthesizedParameterData)
637 Vec<ConvertedBinding<'tcx>>)
640 create_region_substs(this, rscope, span, decl_generics, Vec::new());
642 let binding_rscope = BindingRscope::new();
645 .map(|a_t| ast_ty_arg_to_ty(this, &binding_rscope, decl_generics,
646 0, ®ion_substs, a_t))
647 .collect::<Vec<Ty<'tcx>>>();
649 let input_params = vec![String::new(); inputs.len()];
650 let implied_output_region = find_implied_output_region(this.tcx(), &inputs, input_params);
652 let input_ty = this.tcx().mk_tup(inputs);
654 let (output, output_span) = match data.output {
655 Some(ref output_ty) => {
656 (convert_ty_with_lifetime_elision(this,
657 implied_output_region,
662 (this.tcx().mk_nil(), data.span)
666 let output_binding = ConvertedBinding {
667 item_name: token::intern(FN_OUTPUT_NAME),
672 (region_substs, vec![input_ty], vec![output_binding])
675 pub fn instantiate_poly_trait_ref<'tcx>(
676 this: &AstConv<'tcx>,
677 rscope: &RegionScope,
678 ast_trait_ref: &hir::PolyTraitRef,
679 self_ty: Option<Ty<'tcx>>,
680 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
681 -> ty::PolyTraitRef<'tcx>
683 let trait_ref = &ast_trait_ref.trait_ref;
684 let trait_def_id = trait_def_id(this, trait_ref);
685 ast_path_to_poly_trait_ref(this,
688 PathParamMode::Explicit,
691 trait_ref.path.segments.last().unwrap(),
695 /// Instantiates the path for the given trait reference, assuming that it's
696 /// bound to a valid trait type. Returns the def_id for the defining trait.
697 /// Fails if the type is a type other than a trait type.
699 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
700 /// are disallowed. Otherwise, they are pushed onto the vector given.
701 pub fn instantiate_mono_trait_ref<'tcx>(
702 this: &AstConv<'tcx>,
703 rscope: &RegionScope,
704 trait_ref: &hir::TraitRef,
705 self_ty: Option<Ty<'tcx>>)
706 -> ty::TraitRef<'tcx>
708 let trait_def_id = trait_def_id(this, trait_ref);
709 ast_path_to_mono_trait_ref(this,
712 PathParamMode::Explicit,
715 trait_ref.path.segments.last().unwrap())
718 fn trait_def_id<'tcx>(this: &AstConv<'tcx>, trait_ref: &hir::TraitRef) -> DefId {
719 let path = &trait_ref.path;
720 match ::lookup_full_def(this.tcx(), path.span, trait_ref.ref_id) {
721 def::DefTrait(trait_def_id) => trait_def_id,
723 this.tcx().sess.fatal("cannot continue compilation due to previous error");
726 span_fatal!(this.tcx().sess, path.span, E0245, "`{}` is not a trait",
732 fn object_path_to_poly_trait_ref<'a,'tcx>(
733 this: &AstConv<'tcx>,
734 rscope: &RegionScope,
736 param_mode: PathParamMode,
738 trait_segment: &hir::PathSegment,
739 mut projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
740 -> ty::PolyTraitRef<'tcx>
742 ast_path_to_poly_trait_ref(this,
752 fn ast_path_to_poly_trait_ref<'a,'tcx>(
753 this: &AstConv<'tcx>,
754 rscope: &RegionScope,
756 param_mode: PathParamMode,
758 self_ty: Option<Ty<'tcx>>,
759 trait_segment: &hir::PathSegment,
760 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
761 -> ty::PolyTraitRef<'tcx>
763 debug!("ast_path_to_poly_trait_ref(trait_segment={:?})", trait_segment);
764 // The trait reference introduces a binding level here, so
765 // we need to shift the `rscope`. It'd be nice if we could
766 // do away with this rscope stuff and work this knowledge
767 // into resolve_lifetimes, as we do with non-omitted
768 // lifetimes. Oh well, not there yet.
769 let shifted_rscope = &ShiftedRscope::new(rscope);
771 let (substs, assoc_bindings) =
772 create_substs_for_ast_trait_ref(this,
779 let poly_trait_ref = ty::Binder(ty::TraitRef::new(trait_def_id, substs));
782 let converted_bindings =
785 .filter_map(|binding| {
786 // specify type to assert that error was already reported in Err case:
787 let predicate: Result<_, ErrorReported> =
788 ast_type_binding_to_poly_projection_predicate(this,
789 poly_trait_ref.clone(),
792 predicate.ok() // ok to ignore Err() because ErrorReported (see above)
794 poly_projections.extend(converted_bindings);
797 debug!("ast_path_to_poly_trait_ref(trait_segment={:?}, projections={:?}) -> {:?}",
798 trait_segment, poly_projections, poly_trait_ref);
802 fn ast_path_to_mono_trait_ref<'a,'tcx>(this: &AstConv<'tcx>,
803 rscope: &RegionScope,
805 param_mode: PathParamMode,
807 self_ty: Option<Ty<'tcx>>,
808 trait_segment: &hir::PathSegment)
809 -> ty::TraitRef<'tcx>
811 let (substs, assoc_bindings) =
812 create_substs_for_ast_trait_ref(this,
819 prohibit_projections(this.tcx(), &assoc_bindings);
820 ty::TraitRef::new(trait_def_id, substs)
823 fn create_substs_for_ast_trait_ref<'a,'tcx>(this: &AstConv<'tcx>,
824 rscope: &RegionScope,
826 param_mode: PathParamMode,
828 self_ty: Option<Ty<'tcx>>,
829 trait_segment: &hir::PathSegment)
830 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
832 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
835 let trait_def = match this.get_trait_def(span, trait_def_id) {
836 Ok(trait_def) => trait_def,
837 Err(ErrorReported) => {
838 // No convenient way to recover from a cycle here. Just bail. Sorry!
839 this.tcx().sess.abort_if_errors();
840 this.tcx().sess.bug("ErrorReported returned, but no errors reports?")
844 let (regions, types, assoc_bindings) = match trait_segment.parameters {
845 hir::AngleBracketedParameters(ref data) => {
846 // For now, require that parenthetical notation be used
847 // only with `Fn()` etc.
848 if !this.tcx().sess.features.borrow().unboxed_closures && trait_def.paren_sugar {
849 emit_feature_err(&this.tcx().sess.parse_sess.span_diagnostic,
850 "unboxed_closures", span, GateIssue::Language,
852 the precise format of `Fn`-family traits' type parameters is \
853 subject to change. Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead");
856 convert_angle_bracketed_parameters(this, rscope, span, &trait_def.generics, data)
858 hir::ParenthesizedParameters(ref data) => {
859 // For now, require that parenthetical notation be used
860 // only with `Fn()` etc.
861 if !this.tcx().sess.features.borrow().unboxed_closures && !trait_def.paren_sugar {
862 emit_feature_err(&this.tcx().sess.parse_sess.span_diagnostic,
863 "unboxed_closures", span, GateIssue::Language,
865 parenthetical notation is only stable when used with `Fn`-family traits");
868 convert_parenthesized_parameters(this, rscope, span, &trait_def.generics, data)
872 let substs = create_substs_for_ast_path(this,
880 (this.tcx().mk_substs(substs), assoc_bindings)
883 fn ast_type_binding_to_poly_projection_predicate<'tcx>(
884 this: &AstConv<'tcx>,
885 mut trait_ref: ty::PolyTraitRef<'tcx>,
886 self_ty: Option<Ty<'tcx>>,
887 binding: &ConvertedBinding<'tcx>)
888 -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
890 let tcx = this.tcx();
892 // Given something like `U : SomeTrait<T=X>`, we want to produce a
893 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
894 // subtle in the event that `T` is defined in a supertrait of
895 // `SomeTrait`, because in that case we need to upcast.
897 // That is, consider this case:
900 // trait SubTrait : SuperTrait<int> { }
901 // trait SuperTrait<A> { type T; }
903 // ... B : SubTrait<T=foo> ...
906 // We want to produce `<B as SuperTrait<int>>::T == foo`.
908 // Simple case: X is defined in the current trait.
909 if this.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
910 return Ok(ty::Binder(ty::ProjectionPredicate { // <-------------------+
911 projection_ty: ty::ProjectionTy { // |
912 trait_ref: trait_ref.skip_binder().clone(), // Binder moved here --+
913 item_name: binding.item_name,
919 // Otherwise, we have to walk through the supertraits to find
920 // those that do. This is complicated by the fact that, for an
921 // object type, the `Self` type is not present in the
922 // substitutions (after all, it's being constructed right now),
923 // but the `supertraits` iterator really wants one. To handle
924 // this, we currently insert a dummy type and then remove it
927 let dummy_self_ty = tcx.mk_infer(ty::FreshTy(0));
928 if self_ty.is_none() { // if converting for an object type
929 let mut dummy_substs = trait_ref.skip_binder().substs.clone(); // binder moved here -+
930 assert!(dummy_substs.self_ty().is_none()); // |
931 dummy_substs.types.push(SelfSpace, dummy_self_ty); // |
932 trait_ref = ty::Binder(ty::TraitRef::new(trait_ref.def_id(), // <------------+
933 tcx.mk_substs(dummy_substs)));
936 try!(this.ensure_super_predicates(binding.span, trait_ref.def_id()));
938 let mut candidates: Vec<ty::PolyTraitRef> =
939 traits::supertraits(tcx, trait_ref.clone())
940 .filter(|r| this.trait_defines_associated_type_named(r.def_id(), binding.item_name))
943 // If converting for an object type, then remove the dummy-ty from `Self` now.
945 if self_ty.is_none() {
946 for candidate in &mut candidates {
947 let mut dummy_substs = candidate.0.substs.clone();
948 assert!(dummy_substs.self_ty() == Some(dummy_self_ty));
949 dummy_substs.types.pop(SelfSpace);
950 *candidate = ty::Binder(ty::TraitRef::new(candidate.def_id(),
951 tcx.mk_substs(dummy_substs)));
955 let candidate = try!(one_bound_for_assoc_type(tcx,
957 &trait_ref.to_string(),
958 &binding.item_name.as_str(),
961 Ok(ty::Binder(ty::ProjectionPredicate { // <-------------------------+
962 projection_ty: ty::ProjectionTy { // |
963 trait_ref: candidate.skip_binder().clone(), // binder is moved up here --+
964 item_name: binding.item_name,
970 fn ast_path_to_ty<'tcx>(
971 this: &AstConv<'tcx>,
972 rscope: &RegionScope,
974 param_mode: PathParamMode,
976 item_segment: &hir::PathSegment)
979 let tcx = this.tcx();
980 let (generics, decl_ty) = match this.get_item_type_scheme(span, did) {
981 Ok(ty::TypeScheme { generics, ty: decl_ty }) => {
984 Err(ErrorReported) => {
985 return tcx.types.err;
989 let substs = ast_path_substs_for_ty(this,
996 // FIXME(#12938): This is a hack until we have full support for DST.
997 if Some(did) == this.tcx().lang_items.owned_box() {
998 assert_eq!(substs.types.len(TypeSpace), 1);
999 return this.tcx().mk_box(*substs.types.get(TypeSpace, 0));
1002 decl_ty.subst(this.tcx(), &substs)
1005 type TraitAndProjections<'tcx> = (ty::PolyTraitRef<'tcx>, Vec<ty::PolyProjectionPredicate<'tcx>>);
1007 fn ast_ty_to_trait_ref<'tcx>(this: &AstConv<'tcx>,
1008 rscope: &RegionScope,
1010 bounds: &[hir::TyParamBound])
1011 -> Result<TraitAndProjections<'tcx>, ErrorReported>
1014 * In a type like `Foo + Send`, we want to wait to collect the
1015 * full set of bounds before we make the object type, because we
1016 * need them to infer a region bound. (For example, if we tried
1017 * made a type from just `Foo`, then it wouldn't be enough to
1018 * infer a 'static bound, and hence the user would get an error.)
1019 * So this function is used when we're dealing with a sum type to
1020 * convert the LHS. It only accepts a type that refers to a trait
1021 * name, and reports an error otherwise.
1025 hir::TyPath(None, ref path) => {
1026 let def = match this.tcx().def_map.borrow().get(&ty.id) {
1027 Some(&def::PathResolution { base_def, depth: 0, .. }) => Some(base_def),
1031 Some(def::DefTrait(trait_def_id)) => {
1032 let mut projection_bounds = Vec::new();
1033 let trait_ref = object_path_to_poly_trait_ref(this,
1036 PathParamMode::Explicit,
1038 path.segments.last().unwrap(),
1039 &mut projection_bounds);
1040 Ok((trait_ref, projection_bounds))
1043 span_err!(this.tcx().sess, ty.span, E0172, "expected a reference to a trait");
1049 span_err!(this.tcx().sess, ty.span, E0178,
1050 "expected a path on the left-hand side of `+`, not `{}`",
1051 pprust::ty_to_string(ty));
1052 let hi = bounds.iter().map(|x| match *x {
1053 hir::TraitTyParamBound(ref tr, _) => tr.span.hi,
1054 hir::RegionTyParamBound(ref r) => r.span.hi,
1055 }).max_by_key(|x| x.to_usize());
1056 let full_span = hi.map(|hi| Span {
1059 expn_id: ty.span.expn_id,
1061 match (&ty.node, full_span) {
1062 (&hir::TyRptr(None, ref mut_ty), Some(full_span)) => {
1063 let mutbl_str = if mut_ty.mutbl == hir::MutMutable { "mut " } else { "" };
1065 .span_suggestion(full_span, "try adding parentheses (per RFC 438):",
1066 format!("&{}({} +{})",
1068 pprust::ty_to_string(&*mut_ty.ty),
1069 pprust::bounds_to_string(bounds)));
1071 (&hir::TyRptr(Some(ref lt), ref mut_ty), Some(full_span)) => {
1072 let mutbl_str = if mut_ty.mutbl == hir::MutMutable { "mut " } else { "" };
1074 .span_suggestion(full_span, "try adding parentheses (per RFC 438):",
1075 format!("&{} {}({} +{})",
1076 pprust::lifetime_to_string(lt),
1078 pprust::ty_to_string(&*mut_ty.ty),
1079 pprust::bounds_to_string(bounds)));
1083 fileline_help!(this.tcx().sess, ty.span,
1084 "perhaps you forgot parentheses? (per RFC 438)");
1092 fn trait_ref_to_object_type<'tcx>(this: &AstConv<'tcx>,
1093 rscope: &RegionScope,
1095 trait_ref: ty::PolyTraitRef<'tcx>,
1096 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
1097 bounds: &[hir::TyParamBound])
1100 let existential_bounds = conv_existential_bounds(this,
1107 let result = make_object_type(this, span, trait_ref, existential_bounds);
1108 debug!("trait_ref_to_object_type: result={:?}",
1114 fn make_object_type<'tcx>(this: &AstConv<'tcx>,
1116 principal: ty::PolyTraitRef<'tcx>,
1117 bounds: ty::ExistentialBounds<'tcx>)
1119 let tcx = this.tcx();
1120 let object = ty::TraitTy {
1121 principal: principal,
1124 let object_trait_ref =
1125 object.principal_trait_ref_with_self_ty(tcx, tcx.types.err);
1127 // ensure the super predicates and stop if we encountered an error
1128 if this.ensure_super_predicates(span, principal.def_id()).is_err() {
1129 return tcx.types.err;
1132 // check that there are no gross object safety violations,
1133 // most importantly, that the supertraits don't contain Self,
1135 let object_safety_violations =
1136 traits::astconv_object_safety_violations(tcx, principal.def_id());
1137 if !object_safety_violations.is_empty() {
1138 traits::report_object_safety_error(
1139 tcx, span, principal.def_id(), object_safety_violations);
1140 return tcx.types.err;
1143 let mut associated_types: FnvHashSet<(DefId, ast::Name)> =
1144 traits::supertraits(tcx, object_trait_ref)
1146 let trait_def = tcx.lookup_trait_def(tr.def_id());
1147 trait_def.associated_type_names
1150 .map(move |associated_type_name| (tr.def_id(), associated_type_name))
1154 for projection_bound in &object.bounds.projection_bounds {
1155 let pair = (projection_bound.0.projection_ty.trait_ref.def_id,
1156 projection_bound.0.projection_ty.item_name);
1157 associated_types.remove(&pair);
1160 for (trait_def_id, name) in associated_types {
1161 span_err!(tcx.sess, span, E0191,
1162 "the value of the associated type `{}` (from the trait `{}`) must be specified",
1164 tcx.item_path_str(trait_def_id));
1167 tcx.mk_trait(object.principal, object.bounds)
1170 fn report_ambiguous_associated_type(tcx: &ty::ctxt,
1175 span_err!(tcx.sess, span, E0223,
1176 "ambiguous associated type; specify the type using the syntax \
1178 type_str, trait_str, name);
1181 // Search for a bound on a type parameter which includes the associated item
1182 // given by assoc_name. ty_param_node_id is the node id for the type parameter
1183 // (which might be `Self`, but only if it is the `Self` of a trait, not an
1184 // impl). This function will fail if there are no suitable bounds or there is
1186 fn find_bound_for_assoc_item<'tcx>(this: &AstConv<'tcx>,
1187 ty_param_node_id: ast::NodeId,
1188 ty_param_name: ast::Name,
1189 assoc_name: ast::Name,
1191 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1193 let tcx = this.tcx();
1195 let bounds = match this.get_type_parameter_bounds(span, ty_param_node_id) {
1197 Err(ErrorReported) => {
1198 return Err(ErrorReported);
1202 // Ensure the super predicates and stop if we encountered an error.
1203 if bounds.iter().any(|b| this.ensure_super_predicates(span, b.def_id()).is_err()) {
1204 return Err(ErrorReported);
1207 // Check that there is exactly one way to find an associated type with the
1209 let suitable_bounds: Vec<_> =
1210 traits::transitive_bounds(tcx, &bounds)
1211 .filter(|b| this.trait_defines_associated_type_named(b.def_id(), assoc_name))
1214 one_bound_for_assoc_type(tcx,
1216 &ty_param_name.as_str(),
1217 &assoc_name.as_str(),
1222 // Checks that bounds contains exactly one element and reports appropriate
1223 // errors otherwise.
1224 fn one_bound_for_assoc_type<'tcx>(tcx: &ty::ctxt<'tcx>,
1225 bounds: Vec<ty::PolyTraitRef<'tcx>>,
1226 ty_param_name: &str,
1229 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1231 if bounds.is_empty() {
1232 span_err!(tcx.sess, span, E0220,
1233 "associated type `{}` not found for `{}`",
1236 return Err(ErrorReported);
1239 if bounds.len() > 1 {
1240 span_err!(tcx.sess, span, E0221,
1241 "ambiguous associated type `{}` in bounds of `{}`",
1245 for bound in &bounds {
1246 span_note!(tcx.sess, span,
1247 "associated type `{}` could derive from `{}`",
1253 Ok(bounds[0].clone())
1256 // Create a type from a path to an associated type.
1257 // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
1258 // and item_segment is the path segment for D. We return a type and a def for
1260 // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
1261 // parameter or Self.
1262 fn associated_path_def_to_ty<'tcx>(this: &AstConv<'tcx>,
1265 ty_path_def: def::Def,
1266 item_segment: &hir::PathSegment)
1267 -> (Ty<'tcx>, def::Def)
1269 let tcx = this.tcx();
1270 let assoc_name = item_segment.identifier.name;
1272 debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
1274 prohibit_type_params(tcx, slice::ref_slice(item_segment));
1276 // Find the type of the associated item, and the trait where the associated
1277 // item is declared.
1278 let bound = match (&ty.sty, ty_path_def) {
1279 (_, def::DefSelfTy(Some(trait_did), Some((impl_id, _)))) => {
1280 // `Self` in an impl of a trait - we have a concrete self type and a
1282 let trait_ref = tcx.impl_trait_ref(tcx.map.local_def_id(impl_id)).unwrap();
1283 let trait_ref = if let Some(free_substs) = this.get_free_substs() {
1284 trait_ref.subst(tcx, free_substs)
1289 if this.ensure_super_predicates(span, trait_did).is_err() {
1290 return (tcx.types.err, ty_path_def);
1293 let candidates: Vec<ty::PolyTraitRef> =
1294 traits::supertraits(tcx, ty::Binder(trait_ref))
1295 .filter(|r| this.trait_defines_associated_type_named(r.def_id(),
1299 match one_bound_for_assoc_type(tcx,
1302 &assoc_name.as_str(),
1305 Err(ErrorReported) => return (tcx.types.err, ty_path_def),
1308 (&ty::TyParam(_), def::DefSelfTy(Some(trait_did), None)) => {
1309 let trait_node_id = tcx.map.as_local_node_id(trait_did).unwrap();
1310 match find_bound_for_assoc_item(this,
1312 token::special_idents::type_self.name,
1316 Err(ErrorReported) => return (tcx.types.err, ty_path_def),
1319 (&ty::TyParam(_), def::DefTyParam(_, _, param_did, param_name)) => {
1320 let param_node_id = tcx.map.as_local_node_id(param_did).unwrap();
1321 match find_bound_for_assoc_item(this,
1327 Err(ErrorReported) => return (tcx.types.err, ty_path_def),
1331 report_ambiguous_associated_type(tcx,
1335 &assoc_name.as_str());
1336 return (tcx.types.err, ty_path_def);
1340 let trait_did = bound.0.def_id;
1341 let ty = this.projected_ty_from_poly_trait_ref(span, bound, assoc_name);
1343 let item_did = if let Some(trait_id) = tcx.map.as_local_node_id(trait_did) {
1344 // `ty::trait_items` used below requires information generated
1345 // by type collection, which may be in progress at this point.
1346 match tcx.map.expect_item(trait_id).node {
1347 hir::ItemTrait(_, _, _, ref trait_items) => {
1348 let item = trait_items.iter()
1349 .find(|i| i.name == assoc_name)
1350 .expect("missing associated type");
1351 tcx.map.local_def_id(item.id)
1356 let trait_items = tcx.trait_items(trait_did);
1357 let item = trait_items.iter().find(|i| i.name() == assoc_name);
1358 item.expect("missing associated type").def_id()
1361 (ty, def::DefAssociatedTy(trait_did, item_did))
1364 fn qpath_to_ty<'tcx>(this: &AstConv<'tcx>,
1365 rscope: &RegionScope,
1367 param_mode: PathParamMode,
1368 opt_self_ty: Option<Ty<'tcx>>,
1369 trait_def_id: DefId,
1370 trait_segment: &hir::PathSegment,
1371 item_segment: &hir::PathSegment)
1374 let tcx = this.tcx();
1376 prohibit_type_params(tcx, slice::ref_slice(item_segment));
1378 let self_ty = if let Some(ty) = opt_self_ty {
1381 let path_str = tcx.item_path_str(trait_def_id);
1382 report_ambiguous_associated_type(tcx,
1386 &item_segment.identifier.name.as_str());
1387 return tcx.types.err;
1390 debug!("qpath_to_ty: self_type={:?}", self_ty);
1392 let trait_ref = ast_path_to_mono_trait_ref(this,
1400 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1402 this.projected_ty(span, trait_ref, item_segment.identifier.name)
1405 /// Convert a type supplied as value for a type argument from AST into our
1406 /// our internal representation. This is the same as `ast_ty_to_ty` but that
1407 /// it applies the object lifetime default.
1411 /// * `this`, `rscope`: the surrounding context
1412 /// * `decl_generics`: the generics of the struct/enum/trait declaration being
1414 /// * `index`: the index of the type parameter being instantiated from the list
1415 /// (we assume it is in the `TypeSpace`)
1416 /// * `region_substs`: a partial substitution consisting of
1417 /// only the region type parameters being supplied to this type.
1418 /// * `ast_ty`: the ast representation of the type being supplied
1419 pub fn ast_ty_arg_to_ty<'tcx>(this: &AstConv<'tcx>,
1420 rscope: &RegionScope,
1421 decl_generics: &ty::Generics<'tcx>,
1423 region_substs: &Substs<'tcx>,
1427 let tcx = this.tcx();
1429 if let Some(def) = decl_generics.types.opt_get(TypeSpace, index) {
1430 let object_lifetime_default = def.object_lifetime_default.subst(tcx, region_substs);
1431 let rscope1 = &ObjectLifetimeDefaultRscope::new(rscope, object_lifetime_default);
1432 ast_ty_to_ty(this, rscope1, ast_ty)
1434 ast_ty_to_ty(this, rscope, ast_ty)
1438 // Check the base def in a PathResolution and convert it to a Ty. If there are
1439 // associated types in the PathResolution, these will need to be separately
1441 fn base_def_to_ty<'tcx>(this: &AstConv<'tcx>,
1442 rscope: &RegionScope,
1444 param_mode: PathParamMode,
1446 opt_self_ty: Option<Ty<'tcx>>,
1447 base_segments: &[hir::PathSegment])
1449 let tcx = this.tcx();
1452 def::DefTrait(trait_def_id) => {
1453 // N.B. this case overlaps somewhat with
1454 // TyObjectSum, see that fn for details
1455 let mut projection_bounds = Vec::new();
1457 let trait_ref = object_path_to_poly_trait_ref(this,
1462 base_segments.last().unwrap(),
1463 &mut projection_bounds);
1465 prohibit_type_params(tcx, base_segments.split_last().unwrap().1);
1466 trait_ref_to_object_type(this,
1473 def::DefTy(did, _) | def::DefStruct(did) => {
1474 prohibit_type_params(tcx, base_segments.split_last().unwrap().1);
1475 ast_path_to_ty(this,
1480 base_segments.last().unwrap())
1482 def::DefTyParam(space, index, _, name) => {
1483 prohibit_type_params(tcx, base_segments);
1484 tcx.mk_param(space, index, name)
1486 def::DefSelfTy(_, Some((_, self_ty_id))) => {
1487 // Self in impl (we know the concrete type).
1488 prohibit_type_params(tcx, base_segments);
1489 if let Some(&ty) = tcx.ast_ty_to_ty_cache.borrow().get(&self_ty_id) {
1490 if let Some(free_substs) = this.get_free_substs() {
1491 ty.subst(tcx, free_substs)
1496 tcx.sess.span_bug(span, "self type has not been fully resolved")
1499 def::DefSelfTy(Some(_), None) => {
1501 prohibit_type_params(tcx, base_segments);
1504 def::DefAssociatedTy(trait_did, _) => {
1505 prohibit_type_params(tcx, &base_segments[..base_segments.len()-2]);
1512 &base_segments[base_segments.len()-2],
1513 base_segments.last().unwrap())
1515 def::DefMod(id) => {
1516 // Used as sentinel by callers to indicate the `<T>::A::B::C` form.
1517 // FIXME(#22519) This part of the resolution logic should be
1518 // avoided entirely for that form, once we stop needed a Def
1519 // for `associated_path_def_to_ty`.
1520 // Fixing this will also let use resolve <Self>::Foo the same way we
1521 // resolve Self::Foo, at the moment we can't resolve the former because
1522 // we don't have the trait information around, which is just sad.
1524 if !base_segments.is_empty() {
1525 let id_node = tcx.map.as_local_node_id(id).unwrap();
1529 "found module name used as a type: {}",
1530 tcx.map.node_to_user_string(id_node));
1531 return this.tcx().types.err;
1534 opt_self_ty.expect("missing T in <T>::a::b::c")
1536 def::DefPrimTy(prim_ty) => {
1537 prim_ty_to_ty(tcx, base_segments, prim_ty)
1540 return this.tcx().types.err;
1543 let id_node = tcx.map.as_local_node_id(def.def_id()).unwrap();
1544 span_err!(tcx.sess, span, E0248,
1545 "found value `{}` used as a type",
1546 tcx.map.path_to_string(id_node));
1547 return this.tcx().types.err;
1552 // Note that both base_segments and assoc_segments may be empty, although not at
1554 pub fn finish_resolving_def_to_ty<'tcx>(this: &AstConv<'tcx>,
1555 rscope: &RegionScope,
1557 param_mode: PathParamMode,
1559 opt_self_ty: Option<Ty<'tcx>>,
1560 base_segments: &[hir::PathSegment],
1561 assoc_segments: &[hir::PathSegment])
1563 let mut ty = base_def_to_ty(this,
1571 // If any associated type segments remain, attempt to resolve them.
1572 for segment in assoc_segments {
1573 if ty.sty == ty::TyError {
1576 // This is pretty bad (it will fail except for T::A and Self::A).
1577 let (a_ty, a_def) = associated_path_def_to_ty(this,
1588 /// Parses the programmer's textual representation of a type into our
1589 /// internal notion of a type.
1590 pub fn ast_ty_to_ty<'tcx>(this: &AstConv<'tcx>,
1591 rscope: &RegionScope,
1595 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1598 let tcx = this.tcx();
1600 if let Some(&ty) = tcx.ast_ty_to_ty_cache.borrow().get(&ast_ty.id) {
1601 debug!("ast_ty_to_ty: id={:?} ty={:?} (cached)", ast_ty.id, ty);
1605 let typ = match ast_ty.node {
1606 hir::TyVec(ref ty) => {
1607 tcx.mk_slice(ast_ty_to_ty(this, rscope, &**ty))
1609 hir::TyObjectSum(ref ty, ref bounds) => {
1610 match ast_ty_to_trait_ref(this, rscope, &**ty, bounds) {
1611 Ok((trait_ref, projection_bounds)) => {
1612 trait_ref_to_object_type(this,
1619 Err(ErrorReported) => {
1620 this.tcx().types.err
1624 hir::TyPtr(ref mt) => {
1625 tcx.mk_ptr(ty::TypeAndMut {
1626 ty: ast_ty_to_ty(this, rscope, &*mt.ty),
1630 hir::TyRptr(ref region, ref mt) => {
1631 let r = opt_ast_region_to_region(this, rscope, ast_ty.span, region);
1632 debug!("TyRef r={:?}", r);
1634 &ObjectLifetimeDefaultRscope::new(
1636 ty::ObjectLifetimeDefault::Specific(r));
1637 let t = ast_ty_to_ty(this, rscope1, &*mt.ty);
1638 tcx.mk_ref(tcx.mk_region(r), ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1640 hir::TyTup(ref fields) => {
1641 let flds = fields.iter()
1642 .map(|t| ast_ty_to_ty(this, rscope, &**t))
1646 hir::TyBareFn(ref bf) => {
1647 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1648 let bare_fn = ty_of_bare_fn(this, bf.unsafety, bf.abi, &*bf.decl);
1649 tcx.mk_fn(None, tcx.mk_bare_fn(bare_fn))
1651 hir::TyPolyTraitRef(ref bounds) => {
1652 conv_ty_poly_trait_ref(this, rscope, ast_ty.span, bounds)
1654 hir::TyPath(ref maybe_qself, ref path) => {
1655 let path_res = if let Some(&d) = tcx.def_map.borrow().get(&ast_ty.id) {
1657 } else if let Some(hir::QSelf { position: 0, .. }) = *maybe_qself {
1658 // Create some fake resolution that can't possibly be a type.
1659 def::PathResolution {
1660 base_def: def::DefMod(tcx.map.local_def_id(ast::CRATE_NODE_ID)),
1661 last_private: LastMod(AllPublic),
1662 depth: path.segments.len()
1665 tcx.sess.span_bug(ast_ty.span, &format!("unbound path {:?}", ast_ty))
1667 let def = path_res.base_def;
1668 let base_ty_end = path.segments.len() - path_res.depth;
1669 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1670 ast_ty_to_ty(this, rscope, &qself.ty)
1672 let ty = finish_resolving_def_to_ty(this,
1675 PathParamMode::Explicit,
1678 &path.segments[..base_ty_end],
1679 &path.segments[base_ty_end..]);
1681 if path_res.depth != 0 && ty.sty != ty::TyError {
1682 // Write back the new resolution.
1683 tcx.def_map.borrow_mut().insert(ast_ty.id, def::PathResolution {
1685 last_private: path_res.last_private,
1692 hir::TyFixedLengthVec(ref ty, ref e) => {
1693 let hint = UncheckedExprHint(tcx.types.usize);
1694 match const_eval::eval_const_expr_partial(tcx, &e, hint, None) {
1698 tcx.mk_array(ast_ty_to_ty(this, rscope, &**ty),
1700 ConstVal::Uint(i) =>
1701 tcx.mk_array(ast_ty_to_ty(this, rscope, &**ty),
1704 span_err!(tcx.sess, ast_ty.span, E0249,
1705 "expected constant integer expression \
1707 this.tcx().types.err
1712 span_err!(tcx.sess, r.span, E0250,
1713 "array length constant evaluation error: {}",
1715 if !ast_ty.span.contains(r.span) {
1716 span_note!(tcx.sess, ast_ty.span, "for array length here")
1718 this.tcx().types.err
1722 hir::TyTypeof(ref _e) => {
1723 span_err!(tcx.sess, ast_ty.span, E0516,
1724 "`typeof` is a reserved keyword but unimplemented");
1728 // TyInfer also appears as the type of arguments or return
1729 // values in a ExprClosure, or as
1730 // the type of local variables. Both of these cases are
1731 // handled specially and will not descend into this routine.
1732 this.ty_infer(None, None, None, ast_ty.span)
1736 debug!("ast_ty_to_ty: id={:?} ty={:?}", ast_ty.id, typ);
1737 tcx.ast_ty_to_ty_cache.borrow_mut().insert(ast_ty.id, typ);
1741 pub fn ty_of_arg<'tcx>(this: &AstConv<'tcx>,
1742 rscope: &RegionScope,
1744 expected_ty: Option<Ty<'tcx>>)
1748 hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1749 hir::TyInfer => this.ty_infer(None, None, None, a.ty.span),
1750 _ => ast_ty_to_ty(this, rscope, &*a.ty),
1754 struct SelfInfo<'a, 'tcx> {
1755 untransformed_self_ty: Ty<'tcx>,
1756 explicit_self: &'a hir::ExplicitSelf,
1759 pub fn ty_of_method<'tcx>(this: &AstConv<'tcx>,
1760 sig: &hir::MethodSig,
1761 untransformed_self_ty: Ty<'tcx>)
1762 -> (ty::BareFnTy<'tcx>, ty::ExplicitSelfCategory) {
1763 let self_info = Some(SelfInfo {
1764 untransformed_self_ty: untransformed_self_ty,
1765 explicit_self: &sig.explicit_self,
1767 let (bare_fn_ty, optional_explicit_self_category) =
1768 ty_of_method_or_bare_fn(this,
1773 (bare_fn_ty, optional_explicit_self_category.unwrap())
1776 pub fn ty_of_bare_fn<'tcx>(this: &AstConv<'tcx>, unsafety: hir::Unsafety, abi: abi::Abi,
1777 decl: &hir::FnDecl) -> ty::BareFnTy<'tcx> {
1778 let (bare_fn_ty, _) = ty_of_method_or_bare_fn(this, unsafety, abi, None, decl);
1782 fn ty_of_method_or_bare_fn<'a, 'tcx>(this: &AstConv<'tcx>,
1783 unsafety: hir::Unsafety,
1785 opt_self_info: Option<SelfInfo<'a, 'tcx>>,
1787 -> (ty::BareFnTy<'tcx>, Option<ty::ExplicitSelfCategory>)
1789 debug!("ty_of_method_or_bare_fn");
1791 // New region names that appear inside of the arguments of the function
1792 // declaration are bound to that function type.
1793 let rb = rscope::BindingRscope::new();
1795 // `implied_output_region` is the region that will be assumed for any
1796 // region parameters in the return type. In accordance with the rules for
1797 // lifetime elision, we can determine it in two ways. First (determined
1798 // here), if self is by-reference, then the implied output region is the
1799 // region of the self parameter.
1800 let mut explicit_self_category_result = None;
1801 let (self_ty, implied_output_region) = match opt_self_info {
1802 None => (None, None),
1803 Some(self_info) => {
1804 // This type comes from an impl or trait; no late-bound
1805 // regions should be present.
1806 assert!(!self_info.untransformed_self_ty.has_escaping_regions());
1808 // Figure out and record the explicit self category.
1809 let explicit_self_category =
1810 determine_explicit_self_category(this, &rb, &self_info);
1811 explicit_self_category_result = Some(explicit_self_category);
1812 match explicit_self_category {
1813 ty::StaticExplicitSelfCategory => {
1816 ty::ByValueExplicitSelfCategory => {
1817 (Some(self_info.untransformed_self_ty), None)
1819 ty::ByReferenceExplicitSelfCategory(region, mutability) => {
1820 (Some(this.tcx().mk_ref(
1821 this.tcx().mk_region(region),
1823 ty: self_info.untransformed_self_ty,
1828 ty::ByBoxExplicitSelfCategory => {
1829 (Some(this.tcx().mk_box(self_info.untransformed_self_ty)), None)
1835 // HACK(eddyb) replace the fake self type in the AST with the actual type.
1836 let input_params = if self_ty.is_some() {
1841 let input_tys = input_params.iter().map(|a| ty_of_arg(this, &rb, a, None));
1842 let input_pats: Vec<String> = input_params.iter()
1843 .map(|a| pprust::pat_to_string(&*a.pat))
1845 let self_and_input_tys: Vec<Ty> =
1846 self_ty.into_iter().chain(input_tys).collect();
1849 // Second, if there was exactly one lifetime (either a substitution or a
1850 // reference) in the arguments, then any anonymous regions in the output
1851 // have that lifetime.
1852 let implied_output_region = match implied_output_region {
1855 let input_tys = if self_ty.is_some() {
1856 // Skip the first argument if `self` is present.
1857 &self_and_input_tys[1..]
1859 &self_and_input_tys[..]
1862 find_implied_output_region(this.tcx(), input_tys, input_pats)
1866 let output_ty = match decl.output {
1867 hir::Return(ref output) if output.node == hir::TyInfer =>
1868 ty::FnConverging(this.ty_infer(None, None, None, output.span)),
1869 hir::Return(ref output) =>
1870 ty::FnConverging(convert_ty_with_lifetime_elision(this,
1871 implied_output_region,
1873 hir::DefaultReturn(..) => ty::FnConverging(this.tcx().mk_nil()),
1874 hir::NoReturn(..) => ty::FnDiverging
1880 sig: ty::Binder(ty::FnSig {
1881 inputs: self_and_input_tys,
1883 variadic: decl.variadic
1885 }, explicit_self_category_result)
1888 fn determine_explicit_self_category<'a, 'tcx>(this: &AstConv<'tcx>,
1889 rscope: &RegionScope,
1890 self_info: &SelfInfo<'a, 'tcx>)
1891 -> ty::ExplicitSelfCategory
1893 return match self_info.explicit_self.node {
1894 hir::SelfStatic => ty::StaticExplicitSelfCategory,
1895 hir::SelfValue(_) => ty::ByValueExplicitSelfCategory,
1896 hir::SelfRegion(ref lifetime, mutability, _) => {
1898 opt_ast_region_to_region(this,
1900 self_info.explicit_self.span,
1902 ty::ByReferenceExplicitSelfCategory(region, mutability)
1904 hir::SelfExplicit(ref ast_type, _) => {
1905 let explicit_type = ast_ty_to_ty(this, rscope, &**ast_type);
1907 // We wish to (for now) categorize an explicit self
1908 // declaration like `self: SomeType` into either `self`,
1909 // `&self`, `&mut self`, or `Box<self>`. We do this here
1910 // by some simple pattern matching. A more precise check
1911 // is done later in `check_method_self_type()`.
1916 // impl Foo for &T {
1917 // // Legal declarations:
1918 // fn method1(self: &&T); // ByReferenceExplicitSelfCategory
1919 // fn method2(self: &T); // ByValueExplicitSelfCategory
1920 // fn method3(self: Box<&T>); // ByBoxExplicitSelfCategory
1922 // // Invalid cases will be caught later by `check_method_self_type`:
1923 // fn method_err1(self: &mut T); // ByReferenceExplicitSelfCategory
1927 // To do the check we just count the number of "modifiers"
1928 // on each type and compare them. If they are the same or
1929 // the impl has more, we call it "by value". Otherwise, we
1930 // look at the outermost modifier on the method decl and
1931 // call it by-ref, by-box as appropriate. For method1, for
1932 // example, the impl type has one modifier, but the method
1933 // type has two, so we end up with
1934 // ByReferenceExplicitSelfCategory.
1936 let impl_modifiers = count_modifiers(self_info.untransformed_self_ty);
1937 let method_modifiers = count_modifiers(explicit_type);
1939 debug!("determine_explicit_self_category(self_info.untransformed_self_ty={:?} \
1940 explicit_type={:?} \
1942 self_info.untransformed_self_ty,
1947 if impl_modifiers >= method_modifiers {
1948 ty::ByValueExplicitSelfCategory
1950 match explicit_type.sty {
1951 ty::TyRef(r, mt) => ty::ByReferenceExplicitSelfCategory(*r, mt.mutbl),
1952 ty::TyBox(_) => ty::ByBoxExplicitSelfCategory,
1953 _ => ty::ByValueExplicitSelfCategory,
1959 fn count_modifiers(ty: Ty) -> usize {
1961 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
1962 ty::TyBox(t) => count_modifiers(t) + 1,
1968 pub fn ty_of_closure<'tcx>(
1969 this: &AstConv<'tcx>,
1970 unsafety: hir::Unsafety,
1973 expected_sig: Option<ty::FnSig<'tcx>>)
1974 -> ty::ClosureTy<'tcx>
1976 debug!("ty_of_closure(expected_sig={:?})",
1979 // new region names that appear inside of the fn decl are bound to
1980 // that function type
1981 let rb = rscope::BindingRscope::new();
1983 let input_tys: Vec<_> = decl.inputs.iter().enumerate().map(|(i, a)| {
1984 let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1985 // no guarantee that the correct number of expected args
1987 if i < e.inputs.len() {
1993 ty_of_arg(this, &rb, a, expected_arg_ty)
1996 let expected_ret_ty = expected_sig.map(|e| e.output);
1998 let is_infer = match decl.output {
1999 hir::Return(ref output) if output.node == hir::TyInfer => true,
2000 hir::DefaultReturn(..) => true,
2004 let output_ty = match decl.output {
2005 _ if is_infer && expected_ret_ty.is_some() =>
2006 expected_ret_ty.unwrap(),
2008 ty::FnConverging(this.ty_infer(None, None, None, decl.output.span())),
2009 hir::Return(ref output) =>
2010 ty::FnConverging(ast_ty_to_ty(this, &rb, &**output)),
2011 hir::DefaultReturn(..) => unreachable!(),
2012 hir::NoReturn(..) => ty::FnDiverging
2015 debug!("ty_of_closure: input_tys={:?}", input_tys);
2016 debug!("ty_of_closure: output_ty={:?}", output_ty);
2021 sig: ty::Binder(ty::FnSig {inputs: input_tys,
2023 variadic: decl.variadic}),
2027 /// Given an existential type like `Foo+'a+Bar`, this routine converts the `'a` and `Bar` intos an
2028 /// `ExistentialBounds` struct. The `main_trait_refs` argument specifies the `Foo` -- it is absent
2029 /// for closures. Eventually this should all be normalized, I think, so that there is no "main
2030 /// trait ref" and instead we just have a flat list of bounds as the existential type.
2031 fn conv_existential_bounds<'tcx>(
2032 this: &AstConv<'tcx>,
2033 rscope: &RegionScope,
2035 principal_trait_ref: ty::PolyTraitRef<'tcx>,
2036 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
2037 ast_bounds: &[hir::TyParamBound])
2038 -> ty::ExistentialBounds<'tcx>
2040 let partitioned_bounds =
2041 partition_bounds(this.tcx(), span, ast_bounds);
2043 conv_existential_bounds_from_partitioned_bounds(
2044 this, rscope, span, principal_trait_ref, projection_bounds, partitioned_bounds)
2047 fn conv_ty_poly_trait_ref<'tcx>(
2048 this: &AstConv<'tcx>,
2049 rscope: &RegionScope,
2051 ast_bounds: &[hir::TyParamBound])
2054 let mut partitioned_bounds = partition_bounds(this.tcx(), span, &ast_bounds[..]);
2056 let mut projection_bounds = Vec::new();
2057 let main_trait_bound = if !partitioned_bounds.trait_bounds.is_empty() {
2058 let trait_bound = partitioned_bounds.trait_bounds.remove(0);
2059 instantiate_poly_trait_ref(this,
2063 &mut projection_bounds)
2065 span_err!(this.tcx().sess, span, E0224,
2066 "at least one non-builtin trait is required for an object type");
2067 return this.tcx().types.err;
2071 conv_existential_bounds_from_partitioned_bounds(this,
2074 main_trait_bound.clone(),
2076 partitioned_bounds);
2078 make_object_type(this, span, main_trait_bound, bounds)
2081 pub fn conv_existential_bounds_from_partitioned_bounds<'tcx>(
2082 this: &AstConv<'tcx>,
2083 rscope: &RegionScope,
2085 principal_trait_ref: ty::PolyTraitRef<'tcx>,
2086 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>, // Empty for boxed closures
2087 partitioned_bounds: PartitionedBounds)
2088 -> ty::ExistentialBounds<'tcx>
2090 let PartitionedBounds { builtin_bounds,
2095 if !trait_bounds.is_empty() {
2096 let b = &trait_bounds[0];
2097 span_err!(this.tcx().sess, b.trait_ref.path.span, E0225,
2098 "only the builtin traits can be used as closure or object bounds");
2102 compute_object_lifetime_bound(this,
2105 principal_trait_ref,
2108 let region_bound = match region_bound {
2111 match rscope.object_lifetime_default(span) {
2114 span_err!(this.tcx().sess, span, E0228,
2115 "the lifetime bound for this object type cannot be deduced \
2116 from context; please supply an explicit bound");
2123 debug!("region_bound: {:?}", region_bound);
2125 ty::ExistentialBounds::new(region_bound, builtin_bounds, projection_bounds)
2128 /// Given the bounds on an object, determines what single region bound
2129 /// (if any) we can use to summarize this type. The basic idea is that we will use the bound the
2130 /// user provided, if they provided one, and otherwise search the supertypes of trait bounds for
2131 /// region bounds. It may be that we can derive no bound at all, in which case we return `None`.
2132 fn compute_object_lifetime_bound<'tcx>(
2133 this: &AstConv<'tcx>,
2135 explicit_region_bounds: &[&hir::Lifetime],
2136 principal_trait_ref: ty::PolyTraitRef<'tcx>,
2137 builtin_bounds: ty::BuiltinBounds)
2138 -> Option<ty::Region> // if None, use the default
2140 let tcx = this.tcx();
2142 debug!("compute_opt_region_bound(explicit_region_bounds={:?}, \
2143 principal_trait_ref={:?}, builtin_bounds={:?})",
2144 explicit_region_bounds,
2145 principal_trait_ref,
2148 if explicit_region_bounds.len() > 1 {
2149 span_err!(tcx.sess, explicit_region_bounds[1].span, E0226,
2150 "only a single explicit lifetime bound is permitted");
2153 if !explicit_region_bounds.is_empty() {
2154 // Explicitly specified region bound. Use that.
2155 let r = explicit_region_bounds[0];
2156 return Some(ast_region_to_region(tcx, r));
2159 if let Err(ErrorReported) = this.ensure_super_predicates(span,principal_trait_ref.def_id()) {
2160 return Some(ty::ReStatic);
2163 // No explicit region bound specified. Therefore, examine trait
2164 // bounds and see if we can derive region bounds from those.
2165 let derived_region_bounds =
2166 object_region_bounds(tcx, &principal_trait_ref, builtin_bounds);
2168 // If there are no derived region bounds, then report back that we
2169 // can find no region bound. The caller will use the default.
2170 if derived_region_bounds.is_empty() {
2174 // If any of the derived region bounds are 'static, that is always
2176 if derived_region_bounds.iter().any(|r| ty::ReStatic == *r) {
2177 return Some(ty::ReStatic);
2180 // Determine whether there is exactly one unique region in the set
2181 // of derived region bounds. If so, use that. Otherwise, report an
2183 let r = derived_region_bounds[0];
2184 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2185 span_err!(tcx.sess, span, E0227,
2186 "ambiguous lifetime bound, explicit lifetime bound required");
2191 pub struct PartitionedBounds<'a> {
2192 pub builtin_bounds: ty::BuiltinBounds,
2193 pub trait_bounds: Vec<&'a hir::PolyTraitRef>,
2194 pub region_bounds: Vec<&'a hir::Lifetime>,
2197 /// Divides a list of bounds from the AST into three groups: builtin bounds (Copy, Sized etc),
2198 /// general trait bounds, and region bounds.
2199 pub fn partition_bounds<'a>(tcx: &ty::ctxt,
2201 ast_bounds: &'a [hir::TyParamBound])
2202 -> PartitionedBounds<'a>
2204 let mut builtin_bounds = ty::BuiltinBounds::empty();
2205 let mut region_bounds = Vec::new();
2206 let mut trait_bounds = Vec::new();
2207 for ast_bound in ast_bounds {
2209 hir::TraitTyParamBound(ref b, hir::TraitBoundModifier::None) => {
2210 match ::lookup_full_def(tcx, b.trait_ref.path.span, b.trait_ref.ref_id) {
2211 def::DefTrait(trait_did) => {
2212 if tcx.try_add_builtin_trait(trait_did,
2213 &mut builtin_bounds) {
2214 let segments = &b.trait_ref.path.segments;
2215 let parameters = &segments[segments.len() - 1].parameters;
2216 if !parameters.types().is_empty() {
2217 check_type_argument_count(tcx, b.trait_ref.path.span,
2218 parameters.types().len(), 0, 0);
2220 if !parameters.lifetimes().is_empty() {
2221 report_lifetime_number_error(tcx, b.trait_ref.path.span,
2222 parameters.lifetimes().len(), 0);
2224 continue; // success
2228 // Not a trait? that's an error, but it'll get
2232 trait_bounds.push(b);
2234 hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {}
2235 hir::RegionTyParamBound(ref l) => {
2236 region_bounds.push(l);
2242 builtin_bounds: builtin_bounds,
2243 trait_bounds: trait_bounds,
2244 region_bounds: region_bounds,
2248 fn prohibit_projections<'tcx>(tcx: &ty::ctxt<'tcx>,
2249 bindings: &[ConvertedBinding<'tcx>])
2251 for binding in bindings.iter().take(1) {
2252 prohibit_projection(tcx, binding.span);
2256 fn check_type_argument_count(tcx: &ty::ctxt, span: Span, supplied: usize,
2257 required: usize, accepted: usize) {
2258 if supplied < required {
2259 let expected = if required < accepted {
2264 span_err!(tcx.sess, span, E0243,
2265 "wrong number of type arguments: {} {}, found {}",
2266 expected, required, supplied);
2267 } else if supplied > accepted {
2268 let expected = if required < accepted {
2273 span_err!(tcx.sess, span, E0244,
2274 "wrong number of type arguments: {} {}, found {}",
2281 fn report_lifetime_number_error(tcx: &ty::ctxt, span: Span, number: usize, expected: usize) {
2282 span_err!(tcx.sess, span, E0107,
2283 "wrong number of lifetime parameters: expected {}, found {}",
2287 // A helper struct for conveniently grouping a set of bounds which we pass to
2288 // and return from functions in multiple places.
2289 #[derive(PartialEq, Eq, Clone, Debug)]
2290 pub struct Bounds<'tcx> {
2291 pub region_bounds: Vec<ty::Region>,
2292 pub builtin_bounds: ty::BuiltinBounds,
2293 pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
2294 pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
2297 impl<'tcx> Bounds<'tcx> {
2298 pub fn predicates(&self,
2299 tcx: &ty::ctxt<'tcx>,
2301 -> Vec<ty::Predicate<'tcx>>
2303 let mut vec = Vec::new();
2305 for builtin_bound in &self.builtin_bounds {
2306 match traits::trait_ref_for_builtin_bound(tcx, builtin_bound, param_ty) {
2307 Ok(trait_ref) => { vec.push(trait_ref.to_predicate()); }
2308 Err(ErrorReported) => { }
2312 for ®ion_bound in &self.region_bounds {
2313 // account for the binder being introduced below; no need to shift `param_ty`
2314 // because, at present at least, it can only refer to early-bound regions
2315 let region_bound = ty::fold::shift_region(region_bound, 1);
2316 vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
2319 for bound_trait_ref in &self.trait_bounds {
2320 vec.push(bound_trait_ref.to_predicate());
2323 for projection in &self.projection_bounds {
2324 vec.push(projection.to_predicate());