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::const_val::ConstVal;
52 use rustc_const_eval::{eval_const_expr_partial, ConstEvalErr};
53 use rustc_const_eval::EvalHint::UncheckedExprHint;
54 use rustc_const_eval::ErrKind::ErroneousReferencedConstant;
55 use hir::{self, SelfKind};
56 use hir::def::{self, Def};
57 use hir::def_id::DefId;
58 use hir::print as pprust;
59 use middle::resolve_lifetime as rl;
61 use rustc::ty::subst::{FnSpace, TypeSpace, SelfSpace, Subst, Substs, ParamSpace};
63 use rustc::ty::{self, Ty, TyCtxt, ToPredicate, TypeFoldable};
64 use rustc::ty::wf::object_region_bounds;
65 use rustc_back::slice;
66 use require_c_abi_if_variadic;
67 use rscope::{self, UnelidableRscope, RegionScope, ElidableRscope,
68 ObjectLifetimeDefaultRscope, ShiftedRscope, BindingRscope,
69 ElisionFailureInfo, ElidedLifetime};
70 use util::common::{ErrorReported, FN_OUTPUT_NAME};
71 use util::nodemap::{NodeMap, FnvHashSet};
73 use rustc_const_math::ConstInt;
74 use std::cell::RefCell;
75 use syntax::{abi, ast};
76 use syntax::codemap::{Span, Pos};
77 use syntax::errors::DiagnosticBuilder;
78 use syntax::feature_gate::{GateIssue, emit_feature_err};
79 use syntax::parse::token::{self, keywords};
81 pub trait AstConv<'gcx, 'tcx> {
82 fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
84 /// A cache used for the result of `ast_ty_to_ty_cache`
85 fn ast_ty_to_ty_cache(&self) -> &RefCell<NodeMap<Ty<'tcx>>>;
87 /// Identify the type scheme for an item with a type, like a type
88 /// alias, fn, or struct. This allows you to figure out the set of
89 /// type parameters defined on the item.
90 fn get_item_type_scheme(&self, span: Span, id: DefId)
91 -> Result<ty::TypeScheme<'tcx>, ErrorReported>;
93 /// Returns the `TraitDef` for a given trait. This allows you to
94 /// figure out the set of type parameters defined on the trait.
95 fn get_trait_def(&self, span: Span, id: DefId)
96 -> Result<&'tcx ty::TraitDef<'tcx>, ErrorReported>;
98 /// Ensure that the super-predicates for the trait with the given
99 /// id are available and also for the transitive set of
100 /// super-predicates.
101 fn ensure_super_predicates(&self, span: Span, id: DefId)
102 -> Result<(), ErrorReported>;
104 /// Returns the set of bounds in scope for the type parameter with
106 fn get_type_parameter_bounds(&self, span: Span, def_id: ast::NodeId)
107 -> Result<Vec<ty::PolyTraitRef<'tcx>>, ErrorReported>;
109 /// Returns true if the trait with id `trait_def_id` defines an
110 /// associated type with the name `name`.
111 fn trait_defines_associated_type_named(&self, trait_def_id: DefId, name: ast::Name)
114 /// Return an (optional) substitution to convert bound type parameters that
115 /// are in scope into free ones. This function should only return Some
116 /// within a fn body.
117 /// See ParameterEnvironment::free_substs for more information.
118 fn get_free_substs(&self) -> Option<&Substs<'tcx>>;
120 /// What type should we use when a type is omitted?
122 param_and_substs: Option<ty::TypeParameterDef<'tcx>>,
123 substs: Option<&mut Substs<'tcx>>,
124 space: Option<ParamSpace>,
125 span: Span) -> Ty<'tcx>;
127 /// Projecting an associated type from a (potentially)
128 /// higher-ranked trait reference is more complicated, because of
129 /// the possibility of late-bound regions appearing in the
130 /// associated type binding. This is not legal in function
131 /// signatures for that reason. In a function body, we can always
132 /// handle it because we can use inference variables to remove the
133 /// late-bound regions.
134 fn projected_ty_from_poly_trait_ref(&self,
136 poly_trait_ref: ty::PolyTraitRef<'tcx>,
137 item_name: ast::Name)
140 /// Project an associated type from a non-higher-ranked trait reference.
141 /// This is fairly straightforward and can be accommodated in any context.
142 fn projected_ty(&self,
144 _trait_ref: ty::TraitRef<'tcx>,
145 _item_name: ast::Name)
148 /// Invoked when we encounter an error from some prior pass
149 /// (e.g. resolve) that is translated into a ty-error. This is
150 /// used to help suppress derived errors typeck might otherwise
152 fn set_tainted_by_errors(&self);
155 #[derive(PartialEq, Eq)]
156 pub enum PathParamMode {
157 // Any path in a type context.
159 // The `module::Type` in `module::Type::method` in an expression.
163 struct ConvertedBinding<'tcx> {
164 item_name: ast::Name,
169 type TraitAndProjections<'tcx> = (ty::PolyTraitRef<'tcx>, Vec<ty::PolyProjectionPredicate<'tcx>>);
171 pub fn ast_region_to_region(tcx: TyCtxt, lifetime: &hir::Lifetime)
173 let r = match tcx.named_region_map.defs.get(&lifetime.id) {
175 // should have been recorded by the `resolve_lifetime` pass
176 span_bug!(lifetime.span, "unresolved lifetime");
179 Some(&rl::DefStaticRegion) => {
183 Some(&rl::DefLateBoundRegion(debruijn, id)) => {
184 // If this region is declared on a function, it will have
185 // an entry in `late_bound`, but if it comes from
186 // `for<'a>` in some type or something, it won't
187 // necessarily have one. In that case though, we won't be
188 // changed from late to early bound, so we can just
190 let issue_32330 = tcx.named_region_map
194 .unwrap_or(ty::Issue32330::WontChange);
195 ty::ReLateBound(debruijn, ty::BrNamed(tcx.map.local_def_id(id),
200 Some(&rl::DefEarlyBoundRegion(space, index, _)) => {
201 ty::ReEarlyBound(ty::EarlyBoundRegion {
208 Some(&rl::DefFreeRegion(scope, id)) => {
209 // As in DefLateBoundRegion above, could be missing for some late-bound
210 // regions, but also for early-bound regions.
211 let issue_32330 = tcx.named_region_map
215 .unwrap_or(ty::Issue32330::WontChange);
216 ty::ReFree(ty::FreeRegion {
217 scope: scope.to_code_extent(&tcx.region_maps),
218 bound_region: ty::BrNamed(tcx.map.local_def_id(id),
223 // (*) -- not late-bound, won't change
227 debug!("ast_region_to_region(lifetime={:?} id={}) yields {:?}",
235 fn report_elision_failure(
236 db: &mut DiagnosticBuilder,
237 params: Vec<ElisionFailureInfo>)
239 let mut m = String::new();
240 let len = params.len();
242 let elided_params: Vec<_> = params.into_iter()
243 .filter(|info| info.lifetime_count > 0)
246 let elided_len = elided_params.len();
248 for (i, info) in elided_params.into_iter().enumerate() {
249 let ElisionFailureInfo {
250 name, lifetime_count: n, have_bound_regions
253 let help_name = if name.is_empty() {
254 format!("argument {}", i + 1)
256 format!("`{}`", name)
259 m.push_str(&(if n == 1 {
262 format!("one of {}'s {} elided {}lifetimes", help_name, n,
263 if have_bound_regions { "free " } else { "" } )
266 if elided_len == 2 && i == 0 {
268 } else if i + 2 == elided_len {
270 } else if i != elided_len - 1 {
278 "this function's return type contains a borrowed value, but \
279 there is no value for it to be borrowed from");
281 "consider giving it a 'static lifetime");
282 } else if elided_len == 0 {
284 "this function's return type contains a borrowed value with \
285 an elided lifetime, but the lifetime cannot be derived from \
288 "consider giving it an explicit bounded or 'static \
290 } else if elided_len == 1 {
292 "this function's return type contains a borrowed value, but \
293 the signature does not say which {} it is borrowed from",
297 "this function's return type contains a borrowed value, but \
298 the signature does not say whether it is borrowed from {}",
303 impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
304 pub fn opt_ast_region_to_region(&self,
305 rscope: &RegionScope,
307 opt_lifetime: &Option<hir::Lifetime>) -> ty::Region
309 let r = match *opt_lifetime {
310 Some(ref lifetime) => {
311 ast_region_to_region(self.tcx(), lifetime)
314 None => match rscope.anon_regions(default_span, 1) {
317 let mut err = struct_span_err!(self.tcx().sess, default_span, E0106,
318 "missing lifetime specifier");
319 if let Some(params) = params {
320 report_elision_failure(&mut err, params);
328 debug!("opt_ast_region_to_region(opt_lifetime={:?}) yields {:?}",
335 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
336 /// returns an appropriate set of substitutions for this particular reference to `I`.
337 pub fn ast_path_substs_for_ty(&self,
338 rscope: &RegionScope,
340 param_mode: PathParamMode,
341 decl_generics: &ty::Generics<'tcx>,
342 item_segment: &hir::PathSegment)
345 let tcx = self.tcx();
347 // ast_path_substs() is only called to convert paths that are
348 // known to refer to traits, types, or structs. In these cases,
349 // all type parameters defined for the item being referenced will
350 // be in the TypeSpace or SelfSpace.
352 // Note: in the case of traits, the self parameter is also
353 // defined, but we don't currently create a `type_param_def` for
354 // `Self` because it is implicit.
355 assert!(decl_generics.regions.all(|d| d.space == TypeSpace));
356 assert!(decl_generics.types.all(|d| d.space != FnSpace));
358 let (regions, types, assoc_bindings) = match item_segment.parameters {
359 hir::AngleBracketedParameters(ref data) => {
360 self.convert_angle_bracketed_parameters(rscope, span, decl_generics, data)
362 hir::ParenthesizedParameters(..) => {
363 span_err!(tcx.sess, span, E0214,
364 "parenthesized parameters may only be used with a trait");
365 let ty_param_defs = decl_generics.types.get_slice(TypeSpace);
367 ty_param_defs.iter().map(|_| tcx.types.err).collect(),
372 assoc_bindings.first().map(|b| self.tcx().prohibit_projection(b.span));
374 self.create_substs_for_ast_path(span,
382 fn create_region_substs(&self,
383 rscope: &RegionScope,
385 decl_generics: &ty::Generics<'tcx>,
386 regions_provided: Vec<ty::Region>)
389 let tcx = self.tcx();
391 // If the type is parameterized by this region, then replace this
392 // region with the current anon region binding (in other words,
393 // whatever & would get replaced with).
394 let expected_num_region_params = decl_generics.regions.len(TypeSpace);
395 let supplied_num_region_params = regions_provided.len();
396 let regions = if expected_num_region_params == supplied_num_region_params {
400 rscope.anon_regions(span, expected_num_region_params);
402 if supplied_num_region_params != 0 || anon_regions.is_err() {
403 report_lifetime_number_error(tcx, span,
404 supplied_num_region_params,
405 expected_num_region_params);
409 Ok(anon_regions) => anon_regions,
410 Err(_) => (0..expected_num_region_params).map(|_| ty::ReStatic).collect()
413 Substs::new_type(vec![], regions)
416 /// Given the type/region arguments provided to some path (along with
417 /// an implicit Self, if this is a trait reference) returns the complete
418 /// set of substitutions. This may involve applying defaulted type parameters.
420 /// Note that the type listing given here is *exactly* what the user provided.
422 /// The `region_substs` should be the result of `create_region_substs`
423 /// -- that is, a substitution with no types but the correct number of
425 fn create_substs_for_ast_path(&self,
427 param_mode: PathParamMode,
428 decl_generics: &ty::Generics<'tcx>,
429 self_ty: Option<Ty<'tcx>>,
430 types_provided: Vec<Ty<'tcx>>,
431 region_substs: Substs<'tcx>)
434 let tcx = self.tcx();
436 debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}, \
437 types_provided={:?}, region_substs={:?})",
438 decl_generics, self_ty, types_provided,
441 assert_eq!(region_substs.regions.len(TypeSpace), decl_generics.regions.len(TypeSpace));
442 assert!(region_substs.types.is_empty());
444 // Convert the type parameters supplied by the user.
445 let ty_param_defs = decl_generics.types.get_slice(TypeSpace);
446 let formal_ty_param_count = ty_param_defs.len();
447 let required_ty_param_count = ty_param_defs.iter()
448 .take_while(|x| x.default.is_none())
451 let mut type_substs = self.get_type_substs_for_defs(span,
455 region_substs.clone(),
458 let supplied_ty_param_count = type_substs.len();
459 check_type_argument_count(self.tcx(), span, supplied_ty_param_count,
460 required_ty_param_count, formal_ty_param_count);
462 if supplied_ty_param_count < required_ty_param_count {
463 while type_substs.len() < required_ty_param_count {
464 type_substs.push(tcx.types.err);
466 } else if supplied_ty_param_count > formal_ty_param_count {
467 type_substs.truncate(formal_ty_param_count);
469 assert!(type_substs.len() >= required_ty_param_count &&
470 type_substs.len() <= formal_ty_param_count);
472 let mut substs = region_substs;
473 substs.types.extend(TypeSpace, type_substs.into_iter());
477 // If no self-type is provided, it's still possible that
478 // one was declared, because this could be an object type.
481 // If a self-type is provided, one should have been
482 // "declared" (in other words, this should be a
484 assert!(decl_generics.types.get_self().is_some());
485 substs.types.push(SelfSpace, ty);
489 let actual_supplied_ty_param_count = substs.types.len(TypeSpace);
490 for param in &ty_param_defs[actual_supplied_ty_param_count..] {
491 if let Some(default) = param.default {
492 // If we are converting an object type, then the
493 // `Self` parameter is unknown. However, some of the
494 // other type parameters may reference `Self` in their
495 // defaults. This will lead to an ICE if we are not
497 if self_ty.is_none() && default.has_self_ty() {
498 span_err!(tcx.sess, span, E0393,
499 "the type parameter `{}` must be explicitly specified \
500 in an object type because its default value `{}` references \
504 substs.types.push(TypeSpace, tcx.types.err);
506 // This is a default type parameter.
507 let default = default.subst_spanned(tcx,
510 substs.types.push(TypeSpace, default);
513 span_bug!(span, "extra parameter without default");
517 debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}) -> {:?}",
518 decl_generics, self_ty, substs);
523 /// Returns types_provided if it is not empty, otherwise populating the
524 /// type parameters with inference variables as appropriate.
525 fn get_type_substs_for_defs(&self,
527 types_provided: Vec<Ty<'tcx>>,
528 param_mode: PathParamMode,
529 ty_param_defs: &[ty::TypeParameterDef<'tcx>],
530 mut substs: Substs<'tcx>,
531 self_ty: Option<Ty<'tcx>>)
534 fn default_type_parameter<'tcx>(p: &ty::TypeParameterDef<'tcx>, self_ty: Option<Ty<'tcx>>)
535 -> Option<ty::TypeParameterDef<'tcx>>
537 if let Some(ref default) = p.default {
538 if self_ty.is_none() && default.has_self_ty() {
539 // There is no suitable inference default for a type parameter
540 // that references self with no self-type provided.
548 if param_mode == PathParamMode::Optional && types_provided.is_empty() {
551 .map(|p| self.ty_infer(default_type_parameter(p, self_ty), Some(&mut substs),
552 Some(TypeSpace), span))
559 fn convert_angle_bracketed_parameters(&self,
560 rscope: &RegionScope,
562 decl_generics: &ty::Generics<'tcx>,
563 data: &hir::AngleBracketedParameterData)
566 Vec<ConvertedBinding<'tcx>>)
568 let regions: Vec<_> =
569 data.lifetimes.iter()
570 .map(|l| ast_region_to_region(self.tcx(), l))
574 self.create_region_substs(rscope, span, decl_generics, regions);
579 .map(|(i,t)| self.ast_ty_arg_to_ty(rscope, decl_generics,
580 i, ®ion_substs, t))
583 let assoc_bindings: Vec<_> =
585 .map(|b| ConvertedBinding { item_name: b.name,
586 ty: self.ast_ty_to_ty(rscope, &b.ty),
590 (region_substs, types, assoc_bindings)
593 /// Returns the appropriate lifetime to use for any output lifetimes
594 /// (if one exists) and a vector of the (pattern, number of lifetimes)
595 /// corresponding to each input type/pattern.
596 fn find_implied_output_region(&self,
597 input_tys: &[Ty<'tcx>],
598 input_pats: Vec<String>) -> ElidedLifetime
600 let tcx = self.tcx();
601 let mut lifetimes_for_params = Vec::new();
602 let mut possible_implied_output_region = None;
604 for (input_type, input_pat) in input_tys.iter().zip(input_pats) {
605 let mut regions = FnvHashSet();
606 let have_bound_regions = tcx.collect_regions(input_type, &mut regions);
608 debug!("find_implied_output_regions: collected {:?} from {:?} \
609 have_bound_regions={:?}", ®ions, input_type, have_bound_regions);
611 if regions.len() == 1 {
612 // there's a chance that the unique lifetime of this
613 // iteration will be the appropriate lifetime for output
614 // parameters, so lets store it.
615 possible_implied_output_region = regions.iter().cloned().next();
618 lifetimes_for_params.push(ElisionFailureInfo {
620 lifetime_count: regions.len(),
621 have_bound_regions: have_bound_regions
625 if lifetimes_for_params.iter().map(|e| e.lifetime_count).sum::<usize>() == 1 {
626 Ok(possible_implied_output_region.unwrap())
628 Err(Some(lifetimes_for_params))
632 fn convert_ty_with_lifetime_elision(&self,
633 elided_lifetime: ElidedLifetime,
637 match elided_lifetime {
638 Ok(implied_output_region) => {
639 let rb = ElidableRscope::new(implied_output_region);
640 self.ast_ty_to_ty(&rb, ty)
642 Err(param_lifetimes) => {
643 // All regions must be explicitly specified in the output
644 // if the lifetime elision rules do not apply. This saves
645 // the user from potentially-confusing errors.
646 let rb = UnelidableRscope::new(param_lifetimes);
647 self.ast_ty_to_ty(&rb, ty)
652 fn convert_parenthesized_parameters(&self,
653 rscope: &RegionScope,
655 decl_generics: &ty::Generics<'tcx>,
656 data: &hir::ParenthesizedParameterData)
659 Vec<ConvertedBinding<'tcx>>)
662 self.create_region_substs(rscope, span, decl_generics, Vec::new());
664 let binding_rscope = BindingRscope::new();
667 .map(|a_t| self.ast_ty_arg_to_ty(&binding_rscope, decl_generics,
668 0, ®ion_substs, a_t))
669 .collect::<Vec<Ty<'tcx>>>();
671 let input_params = vec![String::new(); inputs.len()];
672 let implied_output_region = self.find_implied_output_region(&inputs, input_params);
674 let input_ty = self.tcx().mk_tup(inputs);
676 let (output, output_span) = match data.output {
677 Some(ref output_ty) => {
678 (self.convert_ty_with_lifetime_elision(implied_output_region, &output_ty),
682 (self.tcx().mk_nil(), data.span)
686 let output_binding = ConvertedBinding {
687 item_name: token::intern(FN_OUTPUT_NAME),
692 (region_substs, vec![input_ty], vec![output_binding])
695 pub fn instantiate_poly_trait_ref(&self,
696 rscope: &RegionScope,
697 ast_trait_ref: &hir::PolyTraitRef,
698 self_ty: Option<Ty<'tcx>>,
699 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
700 -> ty::PolyTraitRef<'tcx>
702 let trait_ref = &ast_trait_ref.trait_ref;
703 let trait_def_id = self.trait_def_id(trait_ref);
704 self.ast_path_to_poly_trait_ref(rscope,
706 PathParamMode::Explicit,
710 trait_ref.path.segments.last().unwrap(),
714 /// Instantiates the path for the given trait reference, assuming that it's
715 /// bound to a valid trait type. Returns the def_id for the defining trait.
716 /// Fails if the type is a type other than a trait type.
718 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
719 /// are disallowed. Otherwise, they are pushed onto the vector given.
720 pub fn instantiate_mono_trait_ref(&self,
721 rscope: &RegionScope,
722 trait_ref: &hir::TraitRef,
723 self_ty: Option<Ty<'tcx>>)
724 -> ty::TraitRef<'tcx>
726 let trait_def_id = self.trait_def_id(trait_ref);
727 self.ast_path_to_mono_trait_ref(rscope,
729 PathParamMode::Explicit,
732 trait_ref.path.segments.last().unwrap())
735 fn trait_def_id(&self, trait_ref: &hir::TraitRef) -> DefId {
736 let path = &trait_ref.path;
737 match ::lookup_full_def(self.tcx(), path.span, trait_ref.ref_id) {
738 Def::Trait(trait_def_id) => trait_def_id,
740 self.tcx().sess.fatal("cannot continue compilation due to previous error");
743 span_fatal!(self.tcx().sess, path.span, E0245, "`{}` is not a trait",
749 fn object_path_to_poly_trait_ref(&self,
750 rscope: &RegionScope,
752 param_mode: PathParamMode,
754 trait_path_ref_id: ast::NodeId,
755 trait_segment: &hir::PathSegment,
756 mut projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
757 -> ty::PolyTraitRef<'tcx>
759 self.ast_path_to_poly_trait_ref(rscope,
769 fn ast_path_to_poly_trait_ref(&self,
770 rscope: &RegionScope,
772 param_mode: PathParamMode,
774 self_ty: Option<Ty<'tcx>>,
775 path_id: ast::NodeId,
776 trait_segment: &hir::PathSegment,
777 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
778 -> ty::PolyTraitRef<'tcx>
780 debug!("ast_path_to_poly_trait_ref(trait_segment={:?})", trait_segment);
781 // The trait reference introduces a binding level here, so
782 // we need to shift the `rscope`. It'd be nice if we could
783 // do away with this rscope stuff and work this knowledge
784 // into resolve_lifetimes, as we do with non-omitted
785 // lifetimes. Oh well, not there yet.
786 let shifted_rscope = &ShiftedRscope::new(rscope);
788 let (substs, assoc_bindings) =
789 self.create_substs_for_ast_trait_ref(shifted_rscope,
795 let poly_trait_ref = ty::Binder(ty::TraitRef::new(trait_def_id, substs));
798 let converted_bindings =
801 .filter_map(|binding| {
802 // specify type to assert that error was already reported in Err case:
803 let predicate: Result<_, ErrorReported> =
804 self.ast_type_binding_to_poly_projection_predicate(path_id,
805 poly_trait_ref.clone(),
808 predicate.ok() // ok to ignore Err() because ErrorReported (see above)
810 poly_projections.extend(converted_bindings);
813 debug!("ast_path_to_poly_trait_ref(trait_segment={:?}, projections={:?}) -> {:?}",
814 trait_segment, poly_projections, poly_trait_ref);
818 fn ast_path_to_mono_trait_ref(&self,
819 rscope: &RegionScope,
821 param_mode: PathParamMode,
823 self_ty: Option<Ty<'tcx>>,
824 trait_segment: &hir::PathSegment)
825 -> ty::TraitRef<'tcx>
827 let (substs, assoc_bindings) =
828 self.create_substs_for_ast_trait_ref(rscope,
834 assoc_bindings.first().map(|b| self.tcx().prohibit_projection(b.span));
835 ty::TraitRef::new(trait_def_id, substs)
838 fn create_substs_for_ast_trait_ref(&self,
839 rscope: &RegionScope,
841 param_mode: PathParamMode,
843 self_ty: Option<Ty<'tcx>>,
844 trait_segment: &hir::PathSegment)
845 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
847 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
850 let trait_def = match self.get_trait_def(span, trait_def_id) {
851 Ok(trait_def) => trait_def,
852 Err(ErrorReported) => {
853 // No convenient way to recover from a cycle here. Just bail. Sorry!
854 self.tcx().sess.abort_if_errors();
855 bug!("ErrorReported returned, but no errors reports?")
859 let (regions, types, assoc_bindings) = match trait_segment.parameters {
860 hir::AngleBracketedParameters(ref data) => {
861 // For now, require that parenthetical notation be used
862 // only with `Fn()` etc.
863 if !self.tcx().sess.features.borrow().unboxed_closures && trait_def.paren_sugar {
864 emit_feature_err(&self.tcx().sess.parse_sess.span_diagnostic,
865 "unboxed_closures", span, GateIssue::Language,
867 the precise format of `Fn`-family traits' \
868 type parameters is subject to change. \
869 Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead");
872 self.convert_angle_bracketed_parameters(rscope, span, &trait_def.generics, data)
874 hir::ParenthesizedParameters(ref data) => {
875 // For now, require that parenthetical notation be used
876 // only with `Fn()` etc.
877 if !self.tcx().sess.features.borrow().unboxed_closures && !trait_def.paren_sugar {
878 emit_feature_err(&self.tcx().sess.parse_sess.span_diagnostic,
879 "unboxed_closures", span, GateIssue::Language,
881 parenthetical notation is only stable when used with `Fn`-family traits");
884 self.convert_parenthesized_parameters(rscope, span, &trait_def.generics, data)
888 let substs = self.create_substs_for_ast_path(span,
895 (self.tcx().mk_substs(substs), assoc_bindings)
898 fn ast_type_binding_to_poly_projection_predicate(
900 path_id: ast::NodeId,
901 mut trait_ref: ty::PolyTraitRef<'tcx>,
902 self_ty: Option<Ty<'tcx>>,
903 binding: &ConvertedBinding<'tcx>)
904 -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
906 let tcx = self.tcx();
908 // Given something like `U : SomeTrait<T=X>`, we want to produce a
909 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
910 // subtle in the event that `T` is defined in a supertrait of
911 // `SomeTrait`, because in that case we need to upcast.
913 // That is, consider this case:
916 // trait SubTrait : SuperTrait<int> { }
917 // trait SuperTrait<A> { type T; }
919 // ... B : SubTrait<T=foo> ...
922 // We want to produce `<B as SuperTrait<int>>::T == foo`.
924 // Find any late-bound regions declared in `ty` that are not
925 // declared in the trait-ref. These are not wellformed.
929 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
930 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
931 let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
932 let late_bound_in_ty = tcx.collect_referenced_late_bound_regions(&ty::Binder(binding.ty));
933 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
934 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
935 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
936 let br_name = match *br {
937 ty::BrNamed(_, name, _) => name,
941 "anonymous bound region {:?} in binding but not trait ref",
946 lint::builtin::HR_LIFETIME_IN_ASSOC_TYPE,
949 format!("binding for associated type `{}` references lifetime `{}`, \
950 which does not appear in the trait input types",
951 binding.item_name, br_name));
954 // Simple case: X is defined in the current trait.
955 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
956 return Ok(ty::Binder(ty::ProjectionPredicate { // <-------------------+
957 projection_ty: ty::ProjectionTy { // |
958 trait_ref: trait_ref.skip_binder().clone(), // Binder moved here --+
959 item_name: binding.item_name,
965 // Otherwise, we have to walk through the supertraits to find
966 // those that do. This is complicated by the fact that, for an
967 // object type, the `Self` type is not present in the
968 // substitutions (after all, it's being constructed right now),
969 // but the `supertraits` iterator really wants one. To handle
970 // this, we currently insert a dummy type and then remove it
973 let dummy_self_ty = tcx.mk_infer(ty::FreshTy(0));
974 if self_ty.is_none() { // if converting for an object type
975 let mut dummy_substs = trait_ref.skip_binder().substs.clone(); // binder moved here -+
976 assert!(dummy_substs.self_ty().is_none()); // |
977 dummy_substs.types.push(SelfSpace, dummy_self_ty); // |
978 trait_ref = ty::Binder(ty::TraitRef::new(trait_ref.def_id(), // <------------+
979 tcx.mk_substs(dummy_substs)));
982 self.ensure_super_predicates(binding.span, trait_ref.def_id())?;
984 let mut candidates: Vec<ty::PolyTraitRef> =
985 traits::supertraits(tcx, trait_ref.clone())
986 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), binding.item_name))
989 // If converting for an object type, then remove the dummy-ty from `Self` now.
991 if self_ty.is_none() {
992 for candidate in &mut candidates {
993 let mut dummy_substs = candidate.0.substs.clone();
994 assert!(dummy_substs.self_ty() == Some(dummy_self_ty));
995 dummy_substs.types.pop(SelfSpace);
996 *candidate = ty::Binder(ty::TraitRef::new(candidate.def_id(),
997 tcx.mk_substs(dummy_substs)));
1001 let candidate = self.one_bound_for_assoc_type(candidates,
1002 &trait_ref.to_string(),
1003 &binding.item_name.as_str(),
1006 Ok(ty::Binder(ty::ProjectionPredicate { // <-------------------------+
1007 projection_ty: ty::ProjectionTy { // |
1008 trait_ref: candidate.skip_binder().clone(), // binder is moved up here --+
1009 item_name: binding.item_name,
1015 fn ast_path_to_ty(&self,
1016 rscope: &RegionScope,
1018 param_mode: PathParamMode,
1020 item_segment: &hir::PathSegment)
1023 let tcx = self.tcx();
1024 let (generics, decl_ty) = match self.get_item_type_scheme(span, did) {
1025 Ok(ty::TypeScheme { generics, ty: decl_ty }) => {
1028 Err(ErrorReported) => {
1029 return tcx.types.err;
1033 let substs = self.ast_path_substs_for_ty(rscope,
1039 // FIXME(#12938): This is a hack until we have full support for DST.
1040 if Some(did) == self.tcx().lang_items.owned_box() {
1041 assert_eq!(substs.types.len(TypeSpace), 1);
1042 return self.tcx().mk_box(*substs.types.get(TypeSpace, 0));
1045 decl_ty.subst(self.tcx(), &substs)
1048 fn ast_ty_to_trait_ref(&self,
1049 rscope: &RegionScope,
1051 bounds: &[hir::TyParamBound])
1052 -> Result<TraitAndProjections<'tcx>, ErrorReported>
1055 * In a type like `Foo + Send`, we want to wait to collect the
1056 * full set of bounds before we make the object type, because we
1057 * need them to infer a region bound. (For example, if we tried
1058 * made a type from just `Foo`, then it wouldn't be enough to
1059 * infer a 'static bound, and hence the user would get an error.)
1060 * So this function is used when we're dealing with a sum type to
1061 * convert the LHS. It only accepts a type that refers to a trait
1062 * name, and reports an error otherwise.
1066 hir::TyPath(None, ref path) => {
1067 let def = match self.tcx().def_map.borrow().get(&ty.id) {
1068 Some(&def::PathResolution { base_def, depth: 0, .. }) => Some(base_def),
1072 Some(Def::Trait(trait_def_id)) => {
1073 let mut projection_bounds = Vec::new();
1075 self.object_path_to_poly_trait_ref(rscope,
1077 PathParamMode::Explicit,
1080 path.segments.last().unwrap(),
1081 &mut projection_bounds);
1082 Ok((trait_ref, projection_bounds))
1085 span_err!(self.tcx().sess, ty.span, E0172,
1086 "expected a reference to a trait");
1092 let mut err = struct_span_err!(self.tcx().sess, ty.span, E0178,
1093 "expected a path on the left-hand side \
1095 pprust::ty_to_string(ty));
1096 let hi = bounds.iter().map(|x| match *x {
1097 hir::TraitTyParamBound(ref tr, _) => tr.span.hi,
1098 hir::RegionTyParamBound(ref r) => r.span.hi,
1099 }).max_by_key(|x| x.to_usize());
1100 let full_span = hi.map(|hi| Span {
1103 expn_id: ty.span.expn_id,
1105 match (&ty.node, full_span) {
1106 (&hir::TyRptr(None, ref mut_ty), Some(full_span)) => {
1107 let mutbl_str = if mut_ty.mutbl == hir::MutMutable { "mut " } else { "" };
1108 err.span_suggestion(full_span, "try adding parentheses (per RFC 438):",
1109 format!("&{}({} +{})",
1111 pprust::ty_to_string(&mut_ty.ty),
1112 pprust::bounds_to_string(bounds)));
1114 (&hir::TyRptr(Some(ref lt), ref mut_ty), Some(full_span)) => {
1115 let mutbl_str = if mut_ty.mutbl == hir::MutMutable { "mut " } else { "" };
1116 err.span_suggestion(full_span, "try adding parentheses (per RFC 438):",
1117 format!("&{} {}({} +{})",
1118 pprust::lifetime_to_string(lt),
1120 pprust::ty_to_string(&mut_ty.ty),
1121 pprust::bounds_to_string(bounds)));
1126 "perhaps you forgot parentheses? (per RFC 438)");
1135 fn trait_ref_to_object_type(&self,
1136 rscope: &RegionScope,
1138 trait_ref: ty::PolyTraitRef<'tcx>,
1139 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
1140 bounds: &[hir::TyParamBound])
1143 let existential_bounds = self.conv_existential_bounds(rscope,
1149 let result = self.make_object_type(span, trait_ref, existential_bounds);
1150 debug!("trait_ref_to_object_type: result={:?}",
1156 fn make_object_type(&self,
1158 principal: ty::PolyTraitRef<'tcx>,
1159 bounds: ty::ExistentialBounds<'tcx>)
1161 let tcx = self.tcx();
1162 let object = ty::TraitTy {
1163 principal: principal,
1166 let object_trait_ref =
1167 object.principal_trait_ref_with_self_ty(tcx, tcx.types.err);
1169 // ensure the super predicates and stop if we encountered an error
1170 if self.ensure_super_predicates(span, principal.def_id()).is_err() {
1171 return tcx.types.err;
1174 // check that there are no gross object safety violations,
1175 // most importantly, that the supertraits don't contain Self,
1177 let object_safety_violations =
1178 tcx.astconv_object_safety_violations(principal.def_id());
1179 if !object_safety_violations.is_empty() {
1180 tcx.report_object_safety_error(
1181 span, principal.def_id(), None, object_safety_violations)
1183 return tcx.types.err;
1186 let mut associated_types: FnvHashSet<(DefId, ast::Name)> =
1187 traits::supertraits(tcx, object_trait_ref)
1189 let trait_def = tcx.lookup_trait_def(tr.def_id());
1190 trait_def.associated_type_names
1193 .map(move |associated_type_name| (tr.def_id(), associated_type_name))
1197 for projection_bound in &object.bounds.projection_bounds {
1198 let pair = (projection_bound.0.projection_ty.trait_ref.def_id,
1199 projection_bound.0.projection_ty.item_name);
1200 associated_types.remove(&pair);
1203 for (trait_def_id, name) in associated_types {
1204 span_err!(tcx.sess, span, E0191,
1205 "the value of the associated type `{}` (from the trait `{}`) must be specified",
1207 tcx.item_path_str(trait_def_id));
1210 tcx.mk_trait(object.principal, object.bounds)
1213 fn report_ambiguous_associated_type(&self,
1218 span_err!(self.tcx().sess, span, E0223,
1219 "ambiguous associated type; specify the type using the syntax \
1221 type_str, trait_str, name);
1224 // Search for a bound on a type parameter which includes the associated item
1225 // given by assoc_name. ty_param_node_id is the node id for the type parameter
1226 // (which might be `Self`, but only if it is the `Self` of a trait, not an
1227 // impl). This function will fail if there are no suitable bounds or there is
1229 fn find_bound_for_assoc_item(&self,
1230 ty_param_node_id: ast::NodeId,
1231 ty_param_name: ast::Name,
1232 assoc_name: ast::Name,
1234 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1236 let tcx = self.tcx();
1238 let bounds = match self.get_type_parameter_bounds(span, ty_param_node_id) {
1240 Err(ErrorReported) => {
1241 return Err(ErrorReported);
1245 // Ensure the super predicates and stop if we encountered an error.
1246 if bounds.iter().any(|b| self.ensure_super_predicates(span, b.def_id()).is_err()) {
1247 return Err(ErrorReported);
1250 // Check that there is exactly one way to find an associated type with the
1252 let suitable_bounds: Vec<_> =
1253 traits::transitive_bounds(tcx, &bounds)
1254 .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name))
1257 self.one_bound_for_assoc_type(suitable_bounds,
1258 &ty_param_name.as_str(),
1259 &assoc_name.as_str(),
1264 // Checks that bounds contains exactly one element and reports appropriate
1265 // errors otherwise.
1266 fn one_bound_for_assoc_type(&self,
1267 bounds: Vec<ty::PolyTraitRef<'tcx>>,
1268 ty_param_name: &str,
1271 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1273 if bounds.is_empty() {
1274 span_err!(self.tcx().sess, span, E0220,
1275 "associated type `{}` not found for `{}`",
1278 return Err(ErrorReported);
1281 if bounds.len() > 1 {
1282 let mut err = struct_span_err!(self.tcx().sess, span, E0221,
1283 "ambiguous associated type `{}` in bounds of `{}`",
1287 for bound in &bounds {
1288 span_note!(&mut err, span,
1289 "associated type `{}` could derive from `{}`",
1296 Ok(bounds[0].clone())
1299 // Create a type from a path to an associated type.
1300 // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
1301 // and item_segment is the path segment for D. We return a type and a def for
1303 // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
1304 // parameter or Self.
1305 fn associated_path_def_to_ty(&self,
1309 item_segment: &hir::PathSegment)
1312 let tcx = self.tcx();
1313 let assoc_name = item_segment.name;
1315 debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
1317 tcx.prohibit_type_params(slice::ref_slice(item_segment));
1319 // Find the type of the associated item, and the trait where the associated
1320 // item is declared.
1321 let bound = match (&ty.sty, ty_path_def) {
1322 (_, Def::SelfTy(Some(trait_did), Some(impl_id))) => {
1323 // `Self` in an impl of a trait - we have a concrete self type and a
1325 let trait_ref = tcx.impl_trait_ref(tcx.map.local_def_id(impl_id)).unwrap();
1326 let trait_ref = if let Some(free_substs) = self.get_free_substs() {
1327 trait_ref.subst(tcx, free_substs)
1332 if self.ensure_super_predicates(span, trait_did).is_err() {
1333 return (tcx.types.err, ty_path_def);
1336 let candidates: Vec<ty::PolyTraitRef> =
1337 traits::supertraits(tcx, ty::Binder(trait_ref))
1338 .filter(|r| self.trait_defines_associated_type_named(r.def_id(),
1342 match self.one_bound_for_assoc_type(candidates,
1344 &assoc_name.as_str(),
1347 Err(ErrorReported) => return (tcx.types.err, ty_path_def),
1350 (&ty::TyParam(_), Def::SelfTy(Some(trait_did), None)) => {
1351 let trait_node_id = tcx.map.as_local_node_id(trait_did).unwrap();
1352 match self.find_bound_for_assoc_item(trait_node_id,
1353 keywords::SelfType.name(),
1357 Err(ErrorReported) => return (tcx.types.err, ty_path_def),
1360 (&ty::TyParam(_), Def::TyParam(_, _, param_did, param_name)) => {
1361 let param_node_id = tcx.map.as_local_node_id(param_did).unwrap();
1362 match self.find_bound_for_assoc_item(param_node_id,
1367 Err(ErrorReported) => return (tcx.types.err, ty_path_def),
1371 self.report_ambiguous_associated_type(span,
1374 &assoc_name.as_str());
1375 return (tcx.types.err, ty_path_def);
1379 let trait_did = bound.0.def_id;
1380 let ty = self.projected_ty_from_poly_trait_ref(span, bound, assoc_name);
1382 let item_did = if let Some(trait_id) = tcx.map.as_local_node_id(trait_did) {
1383 // `ty::trait_items` used below requires information generated
1384 // by type collection, which may be in progress at this point.
1385 match tcx.map.expect_item(trait_id).node {
1386 hir::ItemTrait(_, _, _, ref trait_items) => {
1387 let item = trait_items.iter()
1388 .find(|i| i.name == assoc_name)
1389 .expect("missing associated type");
1390 tcx.map.local_def_id(item.id)
1395 let trait_items = tcx.trait_items(trait_did);
1396 let item = trait_items.iter().find(|i| i.name() == assoc_name);
1397 item.expect("missing associated type").def_id()
1400 (ty, Def::AssociatedTy(trait_did, item_did))
1403 fn qpath_to_ty(&self,
1404 rscope: &RegionScope,
1406 param_mode: PathParamMode,
1407 opt_self_ty: Option<Ty<'tcx>>,
1408 trait_def_id: DefId,
1409 trait_segment: &hir::PathSegment,
1410 item_segment: &hir::PathSegment)
1413 let tcx = self.tcx();
1415 tcx.prohibit_type_params(slice::ref_slice(item_segment));
1417 let self_ty = if let Some(ty) = opt_self_ty {
1420 let path_str = tcx.item_path_str(trait_def_id);
1421 self.report_ambiguous_associated_type(span,
1424 &item_segment.name.as_str());
1425 return tcx.types.err;
1428 debug!("qpath_to_ty: self_type={:?}", self_ty);
1430 let trait_ref = self.ast_path_to_mono_trait_ref(rscope,
1437 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1439 self.projected_ty(span, trait_ref, item_segment.name)
1442 /// Convert a type supplied as value for a type argument from AST into our
1443 /// our internal representation. This is the same as `ast_ty_to_ty` but that
1444 /// it applies the object lifetime default.
1448 /// * `this`, `rscope`: the surrounding context
1449 /// * `decl_generics`: the generics of the struct/enum/trait declaration being
1451 /// * `index`: the index of the type parameter being instantiated from the list
1452 /// (we assume it is in the `TypeSpace`)
1453 /// * `region_substs`: a partial substitution consisting of
1454 /// only the region type parameters being supplied to this type.
1455 /// * `ast_ty`: the ast representation of the type being supplied
1456 pub fn ast_ty_arg_to_ty(&self,
1457 rscope: &RegionScope,
1458 decl_generics: &ty::Generics<'tcx>,
1460 region_substs: &Substs<'tcx>,
1464 let tcx = self.tcx();
1466 if let Some(def) = decl_generics.types.opt_get(TypeSpace, index) {
1467 let object_lifetime_default = def.object_lifetime_default.subst(tcx, region_substs);
1468 let rscope1 = &ObjectLifetimeDefaultRscope::new(rscope, object_lifetime_default);
1469 self.ast_ty_to_ty(rscope1, ast_ty)
1471 self.ast_ty_to_ty(rscope, ast_ty)
1475 // Check the base def in a PathResolution and convert it to a Ty. If there are
1476 // associated types in the PathResolution, these will need to be separately
1478 fn base_def_to_ty(&self,
1479 rscope: &RegionScope,
1481 param_mode: PathParamMode,
1483 opt_self_ty: Option<Ty<'tcx>>,
1484 base_path_ref_id: ast::NodeId,
1485 base_segments: &[hir::PathSegment])
1487 let tcx = self.tcx();
1489 debug!("base_def_to_ty(def={:?}, opt_self_ty={:?}, base_segments={:?})",
1490 def, opt_self_ty, base_segments);
1493 Def::Trait(trait_def_id) => {
1494 // N.B. this case overlaps somewhat with
1495 // TyObjectSum, see that fn for details
1496 let mut projection_bounds = Vec::new();
1499 self.object_path_to_poly_trait_ref(rscope,
1504 base_segments.last().unwrap(),
1505 &mut projection_bounds);
1507 tcx.prohibit_type_params(base_segments.split_last().unwrap().1);
1508 self.trait_ref_to_object_type(rscope,
1514 Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) => {
1515 tcx.prohibit_type_params(base_segments.split_last().unwrap().1);
1516 self.ast_path_to_ty(rscope,
1520 base_segments.last().unwrap())
1522 Def::TyParam(space, index, _, name) => {
1523 tcx.prohibit_type_params(base_segments);
1524 tcx.mk_param(space, index, name)
1526 Def::SelfTy(_, Some(impl_id)) => {
1527 // Self in impl (we know the concrete type).
1528 tcx.prohibit_type_params(base_segments);
1529 let ty = tcx.node_id_to_type(impl_id);
1530 if let Some(free_substs) = self.get_free_substs() {
1531 ty.subst(tcx, free_substs)
1536 Def::SelfTy(Some(_), None) => {
1538 tcx.prohibit_type_params(base_segments);
1541 Def::AssociatedTy(trait_did, _) => {
1542 tcx.prohibit_type_params(&base_segments[..base_segments.len()-2]);
1543 self.qpath_to_ty(rscope,
1548 &base_segments[base_segments.len()-2],
1549 base_segments.last().unwrap())
1552 // Used as sentinel by callers to indicate the `<T>::A::B::C` form.
1553 // FIXME(#22519) This part of the resolution logic should be
1554 // avoided entirely for that form, once we stop needed a Def
1555 // for `associated_path_def_to_ty`.
1556 // Fixing this will also let use resolve <Self>::Foo the same way we
1557 // resolve Self::Foo, at the moment we can't resolve the former because
1558 // we don't have the trait information around, which is just sad.
1560 assert!(base_segments.is_empty());
1562 opt_self_ty.expect("missing T in <T>::a::b::c")
1564 Def::PrimTy(prim_ty) => {
1565 tcx.prim_ty_to_ty(base_segments, prim_ty)
1568 self.set_tainted_by_errors();
1569 return self.tcx().types.err;
1572 span_err!(tcx.sess, span, E0248,
1573 "found value `{}` used as a type",
1574 tcx.item_path_str(def.def_id()));
1575 return self.tcx().types.err;
1580 // Note that both base_segments and assoc_segments may be empty, although not at
1582 pub fn finish_resolving_def_to_ty(&self,
1583 rscope: &RegionScope,
1585 param_mode: PathParamMode,
1587 opt_self_ty: Option<Ty<'tcx>>,
1588 base_path_ref_id: ast::NodeId,
1589 base_segments: &[hir::PathSegment],
1590 assoc_segments: &[hir::PathSegment])
1591 -> (Ty<'tcx>, Def) {
1592 debug!("finish_resolving_def_to_ty(def={:?}, \
1593 base_segments={:?}, \
1594 assoc_segments={:?})",
1598 let mut ty = self.base_def_to_ty(rscope,
1605 debug!("finish_resolving_def_to_ty: base_def_to_ty returned {:?}", ty);
1606 // If any associated type segments remain, attempt to resolve them.
1607 for segment in assoc_segments {
1608 debug!("finish_resolving_def_to_ty: segment={:?}", segment);
1609 if ty.sty == ty::TyError {
1612 // This is pretty bad (it will fail except for T::A and Self::A).
1613 let (a_ty, a_def) = self.associated_path_def_to_ty(span,
1623 /// Parses the programmer's textual representation of a type into our
1624 /// internal notion of a type.
1625 pub fn ast_ty_to_ty(&self, rscope: &RegionScope, ast_ty: &hir::Ty) -> Ty<'tcx> {
1626 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1629 let tcx = self.tcx();
1631 let cache = self.ast_ty_to_ty_cache();
1632 match cache.borrow().get(&ast_ty.id) {
1633 Some(ty) => { return ty; }
1637 let result_ty = match ast_ty.node {
1638 hir::TyVec(ref ty) => {
1639 tcx.mk_slice(self.ast_ty_to_ty(rscope, &ty))
1641 hir::TyObjectSum(ref ty, ref bounds) => {
1642 match self.ast_ty_to_trait_ref(rscope, &ty, bounds) {
1643 Ok((trait_ref, projection_bounds)) => {
1644 self.trait_ref_to_object_type(rscope,
1650 Err(ErrorReported) => {
1651 self.tcx().types.err
1655 hir::TyPtr(ref mt) => {
1656 tcx.mk_ptr(ty::TypeAndMut {
1657 ty: self.ast_ty_to_ty(rscope, &mt.ty),
1661 hir::TyRptr(ref region, ref mt) => {
1662 let r = self.opt_ast_region_to_region(rscope, ast_ty.span, region);
1663 debug!("TyRef r={:?}", r);
1665 &ObjectLifetimeDefaultRscope::new(
1667 ty::ObjectLifetimeDefault::Specific(r));
1668 let t = self.ast_ty_to_ty(rscope1, &mt.ty);
1669 tcx.mk_ref(tcx.mk_region(r), ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1671 hir::TyTup(ref fields) => {
1672 let flds = fields.iter()
1673 .map(|t| self.ast_ty_to_ty(rscope, &t))
1677 hir::TyBareFn(ref bf) => {
1678 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1679 let bare_fn_ty = self.ty_of_bare_fn(bf.unsafety, bf.abi, &bf.decl);
1681 // Find any late-bound regions declared in return type that do
1682 // not appear in the arguments. These are not wellformed.
1686 // for<'a> fn() -> &'a str <-- 'a is bad
1687 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1689 // Note that we do this check **here** and not in
1690 // `ty_of_bare_fn` because the latter is also used to make
1691 // the types for fn items, and we do not want to issue a
1692 // warning then. (Once we fix #32330, the regions we are
1693 // checking for here would be considered early bound
1695 let inputs = bare_fn_ty.sig.inputs();
1696 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(&inputs);
1697 let output = bare_fn_ty.sig.output();
1698 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1699 for br in late_bound_in_ret.difference(&late_bound_in_args) {
1700 let br_name = match *br {
1701 ty::BrNamed(_, name, _) => name,
1704 bf.decl.output.span(),
1705 "anonymous bound region {:?} in return but not args",
1710 lint::builtin::HR_LIFETIME_IN_ASSOC_TYPE,
1713 format!("return type references lifetime `{}`, \
1714 which does not appear in the trait input types",
1717 tcx.mk_fn_ptr(bare_fn_ty)
1719 hir::TyPolyTraitRef(ref bounds) => {
1720 self.conv_ty_poly_trait_ref(rscope, ast_ty.span, bounds)
1722 hir::TyPath(ref maybe_qself, ref path) => {
1723 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1724 let path_res = if let Some(&d) = tcx.def_map.borrow().get(&ast_ty.id) {
1726 } else if let Some(hir::QSelf { position: 0, .. }) = *maybe_qself {
1727 // Create some fake resolution that can't possibly be a type.
1728 def::PathResolution {
1729 base_def: Def::Mod(tcx.map.local_def_id(ast::CRATE_NODE_ID)),
1730 depth: path.segments.len()
1733 span_bug!(ast_ty.span, "unbound path {:?}", ast_ty)
1735 let def = path_res.base_def;
1736 let base_ty_end = path.segments.len() - path_res.depth;
1737 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1738 self.ast_ty_to_ty(rscope, &qself.ty)
1740 let (ty, _def) = self.finish_resolving_def_to_ty(rscope,
1742 PathParamMode::Explicit,
1746 &path.segments[..base_ty_end],
1747 &path.segments[base_ty_end..]);
1749 if path_res.depth != 0 && ty.sty != ty::TyError {
1750 // Write back the new resolution.
1751 tcx.def_map.borrow_mut().insert(ast_ty.id, def::PathResolution {
1759 hir::TyFixedLengthVec(ref ty, ref e) => {
1760 let hint = UncheckedExprHint(tcx.types.usize);
1761 match eval_const_expr_partial(tcx.global_tcx(), &e, hint, None) {
1762 Ok(ConstVal::Integral(ConstInt::Usize(i))) => {
1763 let i = i.as_u64(tcx.sess.target.uint_type);
1764 assert_eq!(i as usize as u64, i);
1765 tcx.mk_array(self.ast_ty_to_ty(rscope, &ty), i as usize)
1768 span_err!(tcx.sess, ast_ty.span, E0249,
1769 "expected usize value for array length, got {}",
1771 self.tcx().types.err
1773 // array length errors happen before the global constant check
1774 // so we need to report the real error
1775 Err(ConstEvalErr { kind: ErroneousReferencedConstant(box r), ..}) |
1777 let mut err = struct_span_err!(tcx.sess, r.span, E0250,
1778 "array length constant \
1779 evaluation error: {}",
1781 if !ast_ty.span.contains(r.span) {
1782 span_note!(&mut err, ast_ty.span, "for array length here")
1785 self.tcx().types.err
1789 hir::TyTypeof(ref _e) => {
1790 span_err!(tcx.sess, ast_ty.span, E0516,
1791 "`typeof` is a reserved keyword but unimplemented");
1795 // TyInfer also appears as the type of arguments or return
1796 // values in a ExprClosure, or as
1797 // the type of local variables. Both of these cases are
1798 // handled specially and will not descend into this routine.
1799 self.ty_infer(None, None, None, ast_ty.span)
1803 cache.borrow_mut().insert(ast_ty.id, result_ty);
1808 pub fn ty_of_arg(&self,
1809 rscope: &RegionScope,
1811 expected_ty: Option<Ty<'tcx>>)
1815 hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1816 hir::TyInfer => self.ty_infer(None, None, None, a.ty.span),
1817 _ => self.ast_ty_to_ty(rscope, &a.ty),
1821 pub fn ty_of_method(&self,
1822 sig: &hir::MethodSig,
1823 untransformed_self_ty: Ty<'tcx>)
1824 -> (&'tcx ty::BareFnTy<'tcx>, ty::ExplicitSelfCategory) {
1825 let (bare_fn_ty, optional_explicit_self_category) =
1826 self.ty_of_method_or_bare_fn(sig.unsafety,
1828 Some(untransformed_self_ty),
1830 (bare_fn_ty, optional_explicit_self_category)
1833 pub fn ty_of_bare_fn(&self,
1834 unsafety: hir::Unsafety,
1837 -> &'tcx ty::BareFnTy<'tcx> {
1838 self.ty_of_method_or_bare_fn(unsafety, abi, None, decl).0
1841 fn ty_of_method_or_bare_fn<'a>(&self,
1842 unsafety: hir::Unsafety,
1844 opt_untransformed_self_ty: Option<Ty<'tcx>>,
1846 -> (&'tcx ty::BareFnTy<'tcx>, ty::ExplicitSelfCategory)
1848 debug!("ty_of_method_or_bare_fn");
1850 // New region names that appear inside of the arguments of the function
1851 // declaration are bound to that function type.
1852 let rb = rscope::BindingRscope::new();
1854 // `implied_output_region` is the region that will be assumed for any
1855 // region parameters in the return type. In accordance with the rules for
1856 // lifetime elision, we can determine it in two ways. First (determined
1857 // here), if self is by-reference, then the implied output region is the
1858 // region of the self parameter.
1859 let (self_ty, explicit_self_category) = match (opt_untransformed_self_ty, decl.get_self()) {
1860 (Some(untransformed_self_ty), Some(explicit_self)) => {
1861 let self_type = self.determine_self_type(&rb, untransformed_self_ty,
1863 (Some(self_type.0), self_type.1)
1865 _ => (None, ty::ExplicitSelfCategory::Static),
1868 // HACK(eddyb) replace the fake self type in the AST with the actual type.
1869 let arg_params = if self_ty.is_some() {
1874 let arg_tys: Vec<Ty> =
1875 arg_params.iter().map(|a| self.ty_of_arg(&rb, a, None)).collect();
1876 let arg_pats: Vec<String> =
1877 arg_params.iter().map(|a| pprust::pat_to_string(&a.pat)).collect();
1879 // Second, if there was exactly one lifetime (either a substitution or a
1880 // reference) in the arguments, then any anonymous regions in the output
1881 // have that lifetime.
1882 let implied_output_region = match explicit_self_category {
1883 ty::ExplicitSelfCategory::ByReference(region, _) => Ok(region),
1884 _ => self.find_implied_output_region(&arg_tys, arg_pats)
1887 let output_ty = match decl.output {
1888 hir::Return(ref output) =>
1889 ty::FnConverging(self.convert_ty_with_lifetime_elision(implied_output_region,
1891 hir::DefaultReturn(..) => ty::FnConverging(self.tcx().mk_nil()),
1892 hir::NoReturn(..) => ty::FnDiverging
1895 (self.tcx().mk_bare_fn(ty::BareFnTy {
1898 sig: ty::Binder(ty::FnSig {
1899 inputs: self_ty.into_iter().chain(arg_tys).collect(),
1901 variadic: decl.variadic
1903 }), explicit_self_category)
1906 fn determine_self_type<'a>(&self,
1907 rscope: &RegionScope,
1908 untransformed_self_ty: Ty<'tcx>,
1909 explicit_self: &hir::ExplicitSelf)
1910 -> (Ty<'tcx>, ty::ExplicitSelfCategory)
1912 return match explicit_self.node {
1913 SelfKind::Value(..) => {
1914 (untransformed_self_ty, ty::ExplicitSelfCategory::ByValue)
1916 SelfKind::Region(ref lifetime, mutability) => {
1918 self.opt_ast_region_to_region(
1923 self.tcx().mk_region(region),
1925 ty: untransformed_self_ty,
1928 ty::ExplicitSelfCategory::ByReference(region, mutability))
1930 SelfKind::Explicit(ref ast_type, _) => {
1931 let explicit_type = self.ast_ty_to_ty(rscope, &ast_type);
1933 // We wish to (for now) categorize an explicit self
1934 // declaration like `self: SomeType` into either `self`,
1935 // `&self`, `&mut self`, or `Box<self>`. We do this here
1936 // by some simple pattern matching. A more precise check
1937 // is done later in `check_method_self_type()`.
1942 // impl Foo for &T {
1943 // // Legal declarations:
1944 // fn method1(self: &&T); // ExplicitSelfCategory::ByReference
1945 // fn method2(self: &T); // ExplicitSelfCategory::ByValue
1946 // fn method3(self: Box<&T>); // ExplicitSelfCategory::ByBox
1948 // // Invalid cases will be caught later by `check_method_self_type`:
1949 // fn method_err1(self: &mut T); // ExplicitSelfCategory::ByReference
1953 // To do the check we just count the number of "modifiers"
1954 // on each type and compare them. If they are the same or
1955 // the impl has more, we call it "by value". Otherwise, we
1956 // look at the outermost modifier on the method decl and
1957 // call it by-ref, by-box as appropriate. For method1, for
1958 // example, the impl type has one modifier, but the method
1959 // type has two, so we end up with
1960 // ExplicitSelfCategory::ByReference.
1962 let impl_modifiers = count_modifiers(untransformed_self_ty);
1963 let method_modifiers = count_modifiers(explicit_type);
1965 debug!("determine_explicit_self_category(self_info.untransformed_self_ty={:?} \
1966 explicit_type={:?} \
1968 untransformed_self_ty,
1973 let category = if impl_modifiers >= method_modifiers {
1974 ty::ExplicitSelfCategory::ByValue
1976 match explicit_type.sty {
1977 ty::TyRef(r, mt) => ty::ExplicitSelfCategory::ByReference(*r, mt.mutbl),
1978 ty::TyBox(_) => ty::ExplicitSelfCategory::ByBox,
1979 _ => ty::ExplicitSelfCategory::ByValue,
1983 (explicit_type, category)
1987 fn count_modifiers(ty: Ty) -> usize {
1989 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
1990 ty::TyBox(t) => count_modifiers(t) + 1,
1996 pub fn ty_of_closure(&self,
1997 unsafety: hir::Unsafety,
2000 expected_sig: Option<ty::FnSig<'tcx>>)
2001 -> ty::ClosureTy<'tcx>
2003 debug!("ty_of_closure(expected_sig={:?})",
2006 // new region names that appear inside of the fn decl are bound to
2007 // that function type
2008 let rb = rscope::BindingRscope::new();
2010 let input_tys: Vec<_> = decl.inputs.iter().enumerate().map(|(i, a)| {
2011 let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
2012 // no guarantee that the correct number of expected args
2014 if i < e.inputs.len() {
2020 self.ty_of_arg(&rb, a, expected_arg_ty)
2023 let expected_ret_ty = expected_sig.map(|e| e.output);
2025 let is_infer = match decl.output {
2026 hir::Return(ref output) if output.node == hir::TyInfer => true,
2027 hir::DefaultReturn(..) => true,
2031 let output_ty = match decl.output {
2032 _ if is_infer && expected_ret_ty.is_some() =>
2033 expected_ret_ty.unwrap(),
2035 ty::FnConverging(self.ty_infer(None, None, None, decl.output.span())),
2036 hir::Return(ref output) =>
2037 ty::FnConverging(self.ast_ty_to_ty(&rb, &output)),
2038 hir::DefaultReturn(..) => bug!(),
2039 hir::NoReturn(..) => ty::FnDiverging
2042 debug!("ty_of_closure: input_tys={:?}", input_tys);
2043 debug!("ty_of_closure: output_ty={:?}", output_ty);
2048 sig: ty::Binder(ty::FnSig {inputs: input_tys,
2050 variadic: decl.variadic}),
2054 /// Given an existential type like `Foo+'a+Bar`, this routine converts
2055 /// the `'a` and `Bar` intos an `ExistentialBounds` struct.
2056 /// The `main_trait_refs` argument specifies the `Foo` -- it is absent
2057 /// for closures. Eventually this should all be normalized, I think,
2058 /// so that there is no "main trait ref" and instead we just have a flat
2059 /// list of bounds as the existential type.
2060 fn conv_existential_bounds(&self,
2061 rscope: &RegionScope,
2063 principal_trait_ref: ty::PolyTraitRef<'tcx>,
2064 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
2065 ast_bounds: &[hir::TyParamBound])
2066 -> ty::ExistentialBounds<'tcx>
2068 let partitioned_bounds =
2069 partition_bounds(self.tcx(), span, ast_bounds);
2071 self.conv_existential_bounds_from_partitioned_bounds(
2072 rscope, span, principal_trait_ref, projection_bounds, partitioned_bounds)
2075 fn conv_ty_poly_trait_ref(&self,
2076 rscope: &RegionScope,
2078 ast_bounds: &[hir::TyParamBound])
2081 let mut partitioned_bounds = partition_bounds(self.tcx(), span, &ast_bounds[..]);
2083 let mut projection_bounds = Vec::new();
2084 let main_trait_bound = if !partitioned_bounds.trait_bounds.is_empty() {
2085 let trait_bound = partitioned_bounds.trait_bounds.remove(0);
2086 self.instantiate_poly_trait_ref(rscope,
2089 &mut projection_bounds)
2091 span_err!(self.tcx().sess, span, E0224,
2092 "at least one non-builtin trait is required for an object type");
2093 return self.tcx().types.err;
2097 self.conv_existential_bounds_from_partitioned_bounds(rscope,
2099 main_trait_bound.clone(),
2101 partitioned_bounds);
2103 self.make_object_type(span, main_trait_bound, bounds)
2106 pub fn conv_existential_bounds_from_partitioned_bounds(&self,
2107 rscope: &RegionScope,
2109 principal_trait_ref: ty::PolyTraitRef<'tcx>,
2110 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>, // Empty for boxed closures
2111 partitioned_bounds: PartitionedBounds)
2112 -> ty::ExistentialBounds<'tcx>
2114 let PartitionedBounds { builtin_bounds,
2119 if !trait_bounds.is_empty() {
2120 let b = &trait_bounds[0];
2121 span_err!(self.tcx().sess, b.trait_ref.path.span, E0225,
2122 "only the builtin traits can be used as closure or object bounds");
2126 self.compute_object_lifetime_bound(span,
2128 principal_trait_ref,
2131 let region_bound = match region_bound {
2134 match rscope.object_lifetime_default(span) {
2137 span_err!(self.tcx().sess, span, E0228,
2138 "the lifetime bound for this object type cannot be deduced \
2139 from context; please supply an explicit bound");
2146 debug!("region_bound: {:?}", region_bound);
2148 ty::ExistentialBounds::new(region_bound, builtin_bounds, projection_bounds)
2151 /// Given the bounds on an object, determines what single region bound (if any) we can
2152 /// use to summarize this type. The basic idea is that we will use the bound the user
2153 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2154 /// for region bounds. It may be that we can derive no bound at all, in which case
2155 /// we return `None`.
2156 fn compute_object_lifetime_bound(&self,
2158 explicit_region_bounds: &[&hir::Lifetime],
2159 principal_trait_ref: ty::PolyTraitRef<'tcx>,
2160 builtin_bounds: ty::BuiltinBounds)
2161 -> Option<ty::Region> // if None, use the default
2163 let tcx = self.tcx();
2165 debug!("compute_opt_region_bound(explicit_region_bounds={:?}, \
2166 principal_trait_ref={:?}, builtin_bounds={:?})",
2167 explicit_region_bounds,
2168 principal_trait_ref,
2171 if explicit_region_bounds.len() > 1 {
2172 span_err!(tcx.sess, explicit_region_bounds[1].span, E0226,
2173 "only a single explicit lifetime bound is permitted");
2176 if !explicit_region_bounds.is_empty() {
2177 // Explicitly specified region bound. Use that.
2178 let r = explicit_region_bounds[0];
2179 return Some(ast_region_to_region(tcx, r));
2182 if let Err(ErrorReported) =
2183 self.ensure_super_predicates(span, principal_trait_ref.def_id()) {
2184 return Some(ty::ReStatic);
2187 // No explicit region bound specified. Therefore, examine trait
2188 // bounds and see if we can derive region bounds from those.
2189 let derived_region_bounds =
2190 object_region_bounds(tcx, &principal_trait_ref, builtin_bounds);
2192 // If there are no derived region bounds, then report back that we
2193 // can find no region bound. The caller will use the default.
2194 if derived_region_bounds.is_empty() {
2198 // If any of the derived region bounds are 'static, that is always
2200 if derived_region_bounds.iter().any(|r| ty::ReStatic == *r) {
2201 return Some(ty::ReStatic);
2204 // Determine whether there is exactly one unique region in the set
2205 // of derived region bounds. If so, use that. Otherwise, report an
2207 let r = derived_region_bounds[0];
2208 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2209 span_err!(tcx.sess, span, E0227,
2210 "ambiguous lifetime bound, explicit lifetime bound required");
2216 pub struct PartitionedBounds<'a> {
2217 pub builtin_bounds: ty::BuiltinBounds,
2218 pub trait_bounds: Vec<&'a hir::PolyTraitRef>,
2219 pub region_bounds: Vec<&'a hir::Lifetime>,
2222 /// Divides a list of bounds from the AST into three groups: builtin bounds (Copy, Sized etc),
2223 /// general trait bounds, and region bounds.
2224 pub fn partition_bounds<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
2226 ast_bounds: &'b [hir::TyParamBound])
2227 -> PartitionedBounds<'b>
2229 let mut builtin_bounds = ty::BuiltinBounds::empty();
2230 let mut region_bounds = Vec::new();
2231 let mut trait_bounds = Vec::new();
2232 for ast_bound in ast_bounds {
2234 hir::TraitTyParamBound(ref b, hir::TraitBoundModifier::None) => {
2235 match ::lookup_full_def(tcx, b.trait_ref.path.span, b.trait_ref.ref_id) {
2236 Def::Trait(trait_did) => {
2237 if tcx.try_add_builtin_trait(trait_did,
2238 &mut builtin_bounds) {
2239 let segments = &b.trait_ref.path.segments;
2240 let parameters = &segments[segments.len() - 1].parameters;
2241 if !parameters.types().is_empty() {
2242 check_type_argument_count(tcx, b.trait_ref.path.span,
2243 parameters.types().len(), 0, 0);
2245 if !parameters.lifetimes().is_empty() {
2246 report_lifetime_number_error(tcx, b.trait_ref.path.span,
2247 parameters.lifetimes().len(), 0);
2249 continue; // success
2253 // Not a trait? that's an error, but it'll get
2257 trait_bounds.push(b);
2259 hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {}
2260 hir::RegionTyParamBound(ref l) => {
2261 region_bounds.push(l);
2267 builtin_bounds: builtin_bounds,
2268 trait_bounds: trait_bounds,
2269 region_bounds: region_bounds,
2273 fn check_type_argument_count(tcx: TyCtxt, span: Span, supplied: usize,
2274 required: usize, accepted: usize) {
2275 if supplied < required {
2276 let expected = if required < accepted {
2281 span_err!(tcx.sess, span, E0243,
2282 "wrong number of type arguments: {} {}, found {}",
2283 expected, required, supplied);
2284 } else if supplied > accepted {
2285 let expected = if required < accepted {
2290 span_err!(tcx.sess, span, E0244,
2291 "wrong number of type arguments: {} {}, found {}",
2298 fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected: usize) {
2299 span_err!(tcx.sess, span, E0107,
2300 "wrong number of lifetime parameters: expected {}, found {}",
2304 // A helper struct for conveniently grouping a set of bounds which we pass to
2305 // and return from functions in multiple places.
2306 #[derive(PartialEq, Eq, Clone, Debug)]
2307 pub struct Bounds<'tcx> {
2308 pub region_bounds: Vec<ty::Region>,
2309 pub builtin_bounds: ty::BuiltinBounds,
2310 pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
2311 pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
2314 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
2315 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
2316 -> Vec<ty::Predicate<'tcx>>
2318 let mut vec = Vec::new();
2320 for builtin_bound in &self.builtin_bounds {
2321 match tcx.trait_ref_for_builtin_bound(builtin_bound, param_ty) {
2322 Ok(trait_ref) => { vec.push(trait_ref.to_predicate()); }
2323 Err(ErrorReported) => { }
2327 for ®ion_bound in &self.region_bounds {
2328 // account for the binder being introduced below; no need to shift `param_ty`
2329 // because, at present at least, it can only refer to early-bound regions
2330 let region_bound = ty::fold::shift_region(region_bound, 1);
2331 vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
2334 for bound_trait_ref in &self.trait_bounds {
2335 vec.push(bound_trait_ref.to_predicate());
2338 for projection in &self.projection_bounds {
2339 vec.push(projection.to_predicate());