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 rustc_const_eval::eval_length;
52 use hir::{self, SelfKind};
53 use hir::def::{Def, PathResolution};
54 use hir::def_id::DefId;
55 use hir::print as pprust;
56 use middle::resolve_lifetime as rl;
58 use rustc::ty::subst::{FnSpace, TypeSpace, SelfSpace, Subst, Substs, ParamSpace};
60 use rustc::ty::{self, Ty, TyCtxt, ToPredicate, TypeFoldable};
61 use rustc::ty::wf::object_region_bounds;
62 use rustc_back::slice;
63 use require_c_abi_if_variadic;
64 use rscope::{self, UnelidableRscope, RegionScope, ElidableRscope,
65 ObjectLifetimeDefaultRscope, ShiftedRscope, BindingRscope,
66 ElisionFailureInfo, ElidedLifetime};
67 use util::common::{ErrorReported, FN_OUTPUT_NAME};
68 use util::nodemap::{NodeMap, FnvHashSet};
70 use std::cell::RefCell;
71 use syntax::{abi, ast};
72 use syntax::feature_gate::{GateIssue, emit_feature_err};
73 use syntax::parse::token::{self, keywords};
74 use syntax_pos::{Span, Pos};
75 use errors::DiagnosticBuilder;
77 pub trait AstConv<'gcx, 'tcx> {
78 fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
80 /// A cache used for the result of `ast_ty_to_ty_cache`
81 fn ast_ty_to_ty_cache(&self) -> &RefCell<NodeMap<Ty<'tcx>>>;
83 /// Identify the type scheme for an item with a type, like a type
84 /// alias, fn, or struct. This allows you to figure out the set of
85 /// type parameters defined on the item.
86 fn get_item_type_scheme(&self, span: Span, id: DefId)
87 -> Result<ty::TypeScheme<'tcx>, ErrorReported>;
89 /// Returns the `TraitDef` for a given trait. This allows you to
90 /// figure out the set of type parameters defined on the trait.
91 fn get_trait_def(&self, span: Span, id: DefId)
92 -> Result<&'tcx ty::TraitDef<'tcx>, ErrorReported>;
94 /// Ensure that the super-predicates for the trait with the given
95 /// id are available and also for the transitive set of
97 fn ensure_super_predicates(&self, span: Span, id: DefId)
98 -> Result<(), ErrorReported>;
100 /// Returns the set of bounds in scope for the type parameter with
102 fn get_type_parameter_bounds(&self, span: Span, def_id: ast::NodeId)
103 -> Result<Vec<ty::PolyTraitRef<'tcx>>, ErrorReported>;
105 /// Returns true if the trait with id `trait_def_id` defines an
106 /// associated type with the name `name`.
107 fn trait_defines_associated_type_named(&self, trait_def_id: DefId, name: ast::Name)
110 /// Return an (optional) substitution to convert bound type parameters that
111 /// are in scope into free ones. This function should only return Some
112 /// within a fn body.
113 /// See ParameterEnvironment::free_substs for more information.
114 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 /// Project an associated type from a non-higher-ranked trait reference.
137 /// This is fairly straightforward and can be accommodated in any context.
138 fn projected_ty(&self,
140 _trait_ref: ty::TraitRef<'tcx>,
141 _item_name: ast::Name)
144 /// Invoked when we encounter an error from some prior pass
145 /// (e.g. resolve) that is translated into a ty-error. This is
146 /// used to help suppress derived errors typeck might otherwise
148 fn set_tainted_by_errors(&self);
151 #[derive(PartialEq, Eq)]
152 pub enum PathParamMode {
153 // Any path in a type context.
155 // The `module::Type` in `module::Type::method` in an expression.
159 struct ConvertedBinding<'tcx> {
160 item_name: ast::Name,
165 type TraitAndProjections<'tcx> = (ty::PolyTraitRef<'tcx>, Vec<ty::PolyProjectionPredicate<'tcx>>);
167 pub fn ast_region_to_region(tcx: TyCtxt, lifetime: &hir::Lifetime)
169 let r = match tcx.named_region_map.defs.get(&lifetime.id) {
171 // should have been recorded by the `resolve_lifetime` pass
172 span_bug!(lifetime.span, "unresolved lifetime");
175 Some(&rl::DefStaticRegion) => {
179 Some(&rl::DefLateBoundRegion(debruijn, id)) => {
180 // If this region is declared on a function, it will have
181 // an entry in `late_bound`, but if it comes from
182 // `for<'a>` in some type or something, it won't
183 // necessarily have one. In that case though, we won't be
184 // changed from late to early bound, so we can just
186 let issue_32330 = tcx.named_region_map
190 .unwrap_or(ty::Issue32330::WontChange);
191 ty::ReLateBound(debruijn, ty::BrNamed(tcx.map.local_def_id(id),
196 Some(&rl::DefEarlyBoundRegion(space, index, _)) => {
197 ty::ReEarlyBound(ty::EarlyBoundRegion {
204 Some(&rl::DefFreeRegion(scope, id)) => {
205 // As in DefLateBoundRegion above, could be missing for some late-bound
206 // regions, but also for early-bound regions.
207 let issue_32330 = tcx.named_region_map
211 .unwrap_or(ty::Issue32330::WontChange);
212 ty::ReFree(ty::FreeRegion {
213 scope: scope.to_code_extent(&tcx.region_maps),
214 bound_region: ty::BrNamed(tcx.map.local_def_id(id),
219 // (*) -- not late-bound, won't change
223 debug!("ast_region_to_region(lifetime={:?} id={}) yields {:?}",
231 fn report_elision_failure(
232 db: &mut DiagnosticBuilder,
233 params: Vec<ElisionFailureInfo>)
235 let mut m = String::new();
236 let len = params.len();
238 let elided_params: Vec<_> = params.into_iter()
239 .filter(|info| info.lifetime_count > 0)
242 let elided_len = elided_params.len();
244 for (i, info) in elided_params.into_iter().enumerate() {
245 let ElisionFailureInfo {
246 name, lifetime_count: n, have_bound_regions
249 let help_name = if name.is_empty() {
250 format!("argument {}", i + 1)
252 format!("`{}`", name)
255 m.push_str(&(if n == 1 {
258 format!("one of {}'s {} elided {}lifetimes", help_name, n,
259 if have_bound_regions { "free " } else { "" } )
262 if elided_len == 2 && i == 0 {
264 } else if i + 2 == elided_len {
266 } else if i != elided_len - 1 {
274 "this function's return type contains a borrowed value, but \
275 there is no value for it to be borrowed from");
277 "consider giving it a 'static lifetime");
278 } else if elided_len == 0 {
280 "this function's return type contains a borrowed value with \
281 an elided lifetime, but the lifetime cannot be derived from \
284 "consider giving it an explicit bounded or 'static \
286 } else if elided_len == 1 {
288 "this function's return type contains a borrowed value, but \
289 the signature does not say which {} it is borrowed from",
293 "this function's return type contains a borrowed value, but \
294 the signature does not say whether it is borrowed from {}",
299 impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
300 pub fn opt_ast_region_to_region(&self,
301 rscope: &RegionScope,
303 opt_lifetime: &Option<hir::Lifetime>) -> ty::Region
305 let r = match *opt_lifetime {
306 Some(ref lifetime) => {
307 ast_region_to_region(self.tcx(), lifetime)
310 None => match rscope.anon_regions(default_span, 1) {
313 let ampersand_span = Span { hi: default_span.lo, ..default_span};
315 let mut err = struct_span_err!(self.tcx().sess, ampersand_span, E0106,
316 "missing lifetime specifier");
317 err.span_label(ampersand_span, &format!("expected lifetime parameter"));
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 self.tcx().expect_def(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 resolution = self.tcx().expect_resolution(ty.id);
1068 match resolution.base_def {
1069 Def::Trait(trait_def_id) if resolution.depth == 0 => {
1070 let mut projection_bounds = Vec::new();
1072 self.object_path_to_poly_trait_ref(rscope,
1074 PathParamMode::Explicit,
1077 path.segments.last().unwrap(),
1078 &mut projection_bounds);
1079 Ok((trait_ref, projection_bounds))
1082 struct_span_err!(self.tcx().sess, ty.span, E0172,
1083 "expected a reference to a trait")
1084 .span_label(ty.span, &format!("expected a trait"))
1091 let mut err = struct_span_err!(self.tcx().sess, ty.span, E0178,
1092 "expected a path on the left-hand side \
1094 pprust::ty_to_string(ty));
1095 err.span_label(ty.span, &format!("expected a path"));
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 struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
1219 .span_label(span, &format!("ambiguous associated type"))
1220 .note(&format!("specify the type using the syntax `<{} as {}>::{}`",
1221 type_str, trait_str, name))
1226 // Search for a bound on a type parameter which includes the associated item
1227 // given by assoc_name. ty_param_node_id is the node id for the type parameter
1228 // (which might be `Self`, but only if it is the `Self` of a trait, not an
1229 // impl). This function will fail if there are no suitable bounds or there is
1231 fn find_bound_for_assoc_item(&self,
1232 ty_param_node_id: ast::NodeId,
1233 ty_param_name: ast::Name,
1234 assoc_name: ast::Name,
1236 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1238 let tcx = self.tcx();
1240 let bounds = match self.get_type_parameter_bounds(span, ty_param_node_id) {
1242 Err(ErrorReported) => {
1243 return Err(ErrorReported);
1247 // Ensure the super predicates and stop if we encountered an error.
1248 if bounds.iter().any(|b| self.ensure_super_predicates(span, b.def_id()).is_err()) {
1249 return Err(ErrorReported);
1252 // Check that there is exactly one way to find an associated type with the
1254 let suitable_bounds: Vec<_> =
1255 traits::transitive_bounds(tcx, &bounds)
1256 .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name))
1259 self.one_bound_for_assoc_type(suitable_bounds,
1260 &ty_param_name.as_str(),
1261 &assoc_name.as_str(),
1266 // Checks that bounds contains exactly one element and reports appropriate
1267 // errors otherwise.
1268 fn one_bound_for_assoc_type(&self,
1269 bounds: Vec<ty::PolyTraitRef<'tcx>>,
1270 ty_param_name: &str,
1273 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1275 if bounds.is_empty() {
1276 span_err!(self.tcx().sess, span, E0220,
1277 "associated type `{}` not found for `{}`",
1280 return Err(ErrorReported);
1283 if bounds.len() > 1 {
1284 let mut err = struct_span_err!(self.tcx().sess, span, E0221,
1285 "ambiguous associated type `{}` in bounds of `{}`",
1289 for bound in &bounds {
1290 span_note!(&mut err, span,
1291 "associated type `{}` could derive from `{}`",
1298 Ok(bounds[0].clone())
1301 // Create a type from a path to an associated type.
1302 // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
1303 // and item_segment is the path segment for D. We return a type and a def for
1305 // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
1306 // parameter or Self.
1307 fn associated_path_def_to_ty(&self,
1311 item_segment: &hir::PathSegment)
1314 let tcx = self.tcx();
1315 let assoc_name = item_segment.name;
1317 debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
1319 tcx.prohibit_type_params(slice::ref_slice(item_segment));
1321 // Find the type of the associated item, and the trait where the associated
1322 // item is declared.
1323 let bound = match (&ty.sty, ty_path_def) {
1324 (_, Def::SelfTy(Some(trait_did), Some(impl_id))) => {
1325 // For Def::SelfTy() values inlined from another crate, the
1326 // impl_id will be DUMMY_NODE_ID, which would cause problems
1327 // here. But we should never run into an impl from another crate
1329 assert!(impl_id != ast::DUMMY_NODE_ID);
1331 // `Self` in an impl of a trait - we have a concrete self type and a
1333 let trait_ref = tcx.impl_trait_ref(tcx.map.local_def_id(impl_id)).unwrap();
1334 let trait_ref = if let Some(free_substs) = self.get_free_substs() {
1335 trait_ref.subst(tcx, free_substs)
1340 if self.ensure_super_predicates(span, trait_did).is_err() {
1341 return (tcx.types.err, Def::Err);
1344 let candidates: Vec<ty::PolyTraitRef> =
1345 traits::supertraits(tcx, ty::Binder(trait_ref))
1346 .filter(|r| self.trait_defines_associated_type_named(r.def_id(),
1350 match self.one_bound_for_assoc_type(candidates,
1352 &assoc_name.as_str(),
1355 Err(ErrorReported) => return (tcx.types.err, Def::Err),
1358 (&ty::TyParam(_), Def::SelfTy(Some(trait_did), None)) => {
1359 let trait_node_id = tcx.map.as_local_node_id(trait_did).unwrap();
1360 match self.find_bound_for_assoc_item(trait_node_id,
1361 keywords::SelfType.name(),
1365 Err(ErrorReported) => return (tcx.types.err, Def::Err),
1368 (&ty::TyParam(_), Def::TyParam(_, _, param_did, param_name)) => {
1369 let param_node_id = tcx.map.as_local_node_id(param_did).unwrap();
1370 match self.find_bound_for_assoc_item(param_node_id,
1375 Err(ErrorReported) => return (tcx.types.err, Def::Err),
1379 self.report_ambiguous_associated_type(span,
1382 &assoc_name.as_str());
1383 return (tcx.types.err, Def::Err);
1387 let trait_did = bound.0.def_id;
1388 let ty = self.projected_ty_from_poly_trait_ref(span, bound, assoc_name);
1390 let item_did = if let Some(trait_id) = tcx.map.as_local_node_id(trait_did) {
1391 // `ty::trait_items` used below requires information generated
1392 // by type collection, which may be in progress at this point.
1393 match tcx.map.expect_item(trait_id).node {
1394 hir::ItemTrait(_, _, _, ref trait_items) => {
1395 let item = trait_items.iter()
1396 .find(|i| i.name == assoc_name)
1397 .expect("missing associated type");
1398 tcx.map.local_def_id(item.id)
1403 let trait_items = tcx.trait_items(trait_did);
1404 let item = trait_items.iter().find(|i| i.name() == assoc_name);
1405 item.expect("missing associated type").def_id()
1408 (ty, Def::AssociatedTy(trait_did, item_did))
1411 fn qpath_to_ty(&self,
1412 rscope: &RegionScope,
1414 param_mode: PathParamMode,
1415 opt_self_ty: Option<Ty<'tcx>>,
1416 trait_def_id: DefId,
1417 trait_segment: &hir::PathSegment,
1418 item_segment: &hir::PathSegment)
1421 let tcx = self.tcx();
1423 tcx.prohibit_type_params(slice::ref_slice(item_segment));
1425 let self_ty = if let Some(ty) = opt_self_ty {
1428 let path_str = tcx.item_path_str(trait_def_id);
1429 self.report_ambiguous_associated_type(span,
1432 &item_segment.name.as_str());
1433 return tcx.types.err;
1436 debug!("qpath_to_ty: self_type={:?}", self_ty);
1438 let trait_ref = self.ast_path_to_mono_trait_ref(rscope,
1445 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1447 self.projected_ty(span, trait_ref, item_segment.name)
1450 /// Convert a type supplied as value for a type argument from AST into our
1451 /// our internal representation. This is the same as `ast_ty_to_ty` but that
1452 /// it applies the object lifetime default.
1456 /// * `this`, `rscope`: the surrounding context
1457 /// * `decl_generics`: the generics of the struct/enum/trait declaration being
1459 /// * `index`: the index of the type parameter being instantiated from the list
1460 /// (we assume it is in the `TypeSpace`)
1461 /// * `region_substs`: a partial substitution consisting of
1462 /// only the region type parameters being supplied to this type.
1463 /// * `ast_ty`: the ast representation of the type being supplied
1464 pub fn ast_ty_arg_to_ty(&self,
1465 rscope: &RegionScope,
1466 decl_generics: &ty::Generics<'tcx>,
1468 region_substs: &Substs<'tcx>,
1472 let tcx = self.tcx();
1474 if let Some(def) = decl_generics.types.opt_get(TypeSpace, index) {
1475 let object_lifetime_default = def.object_lifetime_default.subst(tcx, region_substs);
1476 let rscope1 = &ObjectLifetimeDefaultRscope::new(rscope, object_lifetime_default);
1477 self.ast_ty_to_ty(rscope1, ast_ty)
1479 self.ast_ty_to_ty(rscope, ast_ty)
1483 // Check the base def in a PathResolution and convert it to a Ty. If there are
1484 // associated types in the PathResolution, these will need to be separately
1486 fn base_def_to_ty(&self,
1487 rscope: &RegionScope,
1489 param_mode: PathParamMode,
1491 opt_self_ty: Option<Ty<'tcx>>,
1492 base_path_ref_id: ast::NodeId,
1493 base_segments: &[hir::PathSegment])
1495 let tcx = self.tcx();
1497 debug!("base_def_to_ty(def={:?}, opt_self_ty={:?}, base_segments={:?})",
1498 def, opt_self_ty, base_segments);
1501 Def::Trait(trait_def_id) => {
1502 // N.B. this case overlaps somewhat with
1503 // TyObjectSum, see that fn for details
1504 let mut projection_bounds = Vec::new();
1507 self.object_path_to_poly_trait_ref(rscope,
1512 base_segments.last().unwrap(),
1513 &mut projection_bounds);
1515 tcx.prohibit_type_params(base_segments.split_last().unwrap().1);
1516 self.trait_ref_to_object_type(rscope,
1522 Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) => {
1523 tcx.prohibit_type_params(base_segments.split_last().unwrap().1);
1524 self.ast_path_to_ty(rscope,
1528 base_segments.last().unwrap())
1530 Def::TyParam(space, index, _, name) => {
1531 tcx.prohibit_type_params(base_segments);
1532 tcx.mk_param(space, index, name)
1534 Def::SelfTy(_, Some(impl_id)) => {
1535 // Self in impl (we know the concrete type).
1537 // For Def::SelfTy() values inlined from another crate, the
1538 // impl_id will be DUMMY_NODE_ID, which would cause problems
1539 // here. But we should never run into an impl from another crate
1541 assert!(impl_id != ast::DUMMY_NODE_ID);
1543 tcx.prohibit_type_params(base_segments);
1544 let ty = tcx.node_id_to_type(impl_id);
1545 if let Some(free_substs) = self.get_free_substs() {
1546 ty.subst(tcx, free_substs)
1551 Def::SelfTy(Some(_), None) => {
1553 tcx.prohibit_type_params(base_segments);
1556 Def::AssociatedTy(trait_did, _) => {
1557 tcx.prohibit_type_params(&base_segments[..base_segments.len()-2]);
1558 self.qpath_to_ty(rscope,
1563 &base_segments[base_segments.len()-2],
1564 base_segments.last().unwrap())
1567 // Used as sentinel by callers to indicate the `<T>::A::B::C` form.
1568 // FIXME(#22519) This part of the resolution logic should be
1569 // avoided entirely for that form, once we stop needed a Def
1570 // for `associated_path_def_to_ty`.
1571 // Fixing this will also let use resolve <Self>::Foo the same way we
1572 // resolve Self::Foo, at the moment we can't resolve the former because
1573 // we don't have the trait information around, which is just sad.
1575 assert!(base_segments.is_empty());
1577 opt_self_ty.expect("missing T in <T>::a::b::c")
1579 Def::PrimTy(prim_ty) => {
1580 tcx.prim_ty_to_ty(base_segments, prim_ty)
1583 self.set_tainted_by_errors();
1584 return self.tcx().types.err;
1587 span_err!(tcx.sess, span, E0248,
1588 "found value `{}` used as a type",
1589 tcx.item_path_str(def.def_id()));
1590 return self.tcx().types.err;
1595 // Resolve possibly associated type path into a type and final definition.
1596 // Note that both base_segments and assoc_segments may be empty, although not at same time.
1597 pub fn finish_resolving_def_to_ty(&self,
1598 rscope: &RegionScope,
1600 param_mode: PathParamMode,
1602 opt_self_ty: Option<Ty<'tcx>>,
1603 base_path_ref_id: ast::NodeId,
1604 base_segments: &[hir::PathSegment],
1605 assoc_segments: &[hir::PathSegment])
1606 -> (Ty<'tcx>, Def) {
1607 // Convert the base type.
1608 debug!("finish_resolving_def_to_ty(base_def={:?}, \
1609 base_segments={:?}, \
1610 assoc_segments={:?})",
1614 let base_ty = self.base_def_to_ty(rscope,
1621 debug!("finish_resolving_def_to_ty: base_def_to_ty returned {:?}", base_ty);
1623 // If any associated type segments remain, attempt to resolve them.
1624 let (mut ty, mut def) = (base_ty, base_def);
1625 for segment in assoc_segments {
1626 debug!("finish_resolving_def_to_ty: segment={:?}", segment);
1627 // This is pretty bad (it will fail except for T::A and Self::A).
1628 let (new_ty, new_def) = self.associated_path_def_to_ty(span, ty, def, segment);
1632 if def == Def::Err {
1639 /// Parses the programmer's textual representation of a type into our
1640 /// internal notion of a type.
1641 pub fn ast_ty_to_ty(&self, rscope: &RegionScope, ast_ty: &hir::Ty) -> Ty<'tcx> {
1642 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1645 let tcx = self.tcx();
1647 let cache = self.ast_ty_to_ty_cache();
1648 match cache.borrow().get(&ast_ty.id) {
1649 Some(ty) => { return ty; }
1653 let result_ty = match ast_ty.node {
1654 hir::TyVec(ref ty) => {
1655 tcx.mk_slice(self.ast_ty_to_ty(rscope, &ty))
1657 hir::TyObjectSum(ref ty, ref bounds) => {
1658 match self.ast_ty_to_trait_ref(rscope, &ty, bounds) {
1659 Ok((trait_ref, projection_bounds)) => {
1660 self.trait_ref_to_object_type(rscope,
1666 Err(ErrorReported) => {
1667 self.tcx().types.err
1671 hir::TyPtr(ref mt) => {
1672 tcx.mk_ptr(ty::TypeAndMut {
1673 ty: self.ast_ty_to_ty(rscope, &mt.ty),
1677 hir::TyRptr(ref region, ref mt) => {
1678 let r = self.opt_ast_region_to_region(rscope, ast_ty.span, region);
1679 debug!("TyRef r={:?}", r);
1681 &ObjectLifetimeDefaultRscope::new(
1683 ty::ObjectLifetimeDefault::Specific(r));
1684 let t = self.ast_ty_to_ty(rscope1, &mt.ty);
1685 tcx.mk_ref(tcx.mk_region(r), ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1687 hir::TyTup(ref fields) => {
1688 let flds = fields.iter()
1689 .map(|t| self.ast_ty_to_ty(rscope, &t))
1693 hir::TyBareFn(ref bf) => {
1694 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1695 let bare_fn_ty = self.ty_of_bare_fn(bf.unsafety, bf.abi, &bf.decl);
1697 // Find any late-bound regions declared in return type that do
1698 // not appear in the arguments. These are not wellformed.
1702 // for<'a> fn() -> &'a str <-- 'a is bad
1703 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1705 // Note that we do this check **here** and not in
1706 // `ty_of_bare_fn` because the latter is also used to make
1707 // the types for fn items, and we do not want to issue a
1708 // warning then. (Once we fix #32330, the regions we are
1709 // checking for here would be considered early bound
1711 let inputs = bare_fn_ty.sig.inputs();
1712 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(&inputs);
1713 let output = bare_fn_ty.sig.output();
1714 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1715 for br in late_bound_in_ret.difference(&late_bound_in_args) {
1716 let br_name = match *br {
1717 ty::BrNamed(_, name, _) => name,
1720 bf.decl.output.span(),
1721 "anonymous bound region {:?} in return but not args",
1726 lint::builtin::HR_LIFETIME_IN_ASSOC_TYPE,
1729 format!("return type references lifetime `{}`, \
1730 which does not appear in the trait input types",
1733 tcx.mk_fn_ptr(bare_fn_ty)
1735 hir::TyPolyTraitRef(ref bounds) => {
1736 self.conv_ty_poly_trait_ref(rscope, ast_ty.span, bounds)
1738 hir::TyPath(ref maybe_qself, ref path) => {
1739 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1740 let path_res = tcx.expect_resolution(ast_ty.id);
1741 let base_ty_end = path.segments.len() - path_res.depth;
1742 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1743 self.ast_ty_to_ty(rscope, &qself.ty)
1745 let (ty, def) = self.finish_resolving_def_to_ty(rscope,
1747 PathParamMode::Explicit,
1751 &path.segments[..base_ty_end],
1752 &path.segments[base_ty_end..]);
1754 // Write back the new resolution.
1755 if path_res.depth != 0 {
1756 tcx.def_map.borrow_mut().insert(ast_ty.id, PathResolution::new(def));
1761 hir::TyFixedLengthVec(ref ty, ref e) => {
1762 if let Ok(length) = eval_length(tcx.global_tcx(), &e, "array length") {
1763 tcx.mk_array(self.ast_ty_to_ty(rscope, &ty), length)
1765 self.tcx().types.err
1768 hir::TyTypeof(ref _e) => {
1769 span_err!(tcx.sess, ast_ty.span, E0516,
1770 "`typeof` is a reserved keyword but unimplemented");
1774 // TyInfer also appears as the type of arguments or return
1775 // values in a ExprClosure, or as
1776 // the type of local variables. Both of these cases are
1777 // handled specially and will not descend into this routine.
1778 self.ty_infer(None, None, None, ast_ty.span)
1782 cache.borrow_mut().insert(ast_ty.id, result_ty);
1787 pub fn ty_of_arg(&self,
1788 rscope: &RegionScope,
1790 expected_ty: Option<Ty<'tcx>>)
1794 hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1795 hir::TyInfer => self.ty_infer(None, None, None, a.ty.span),
1796 _ => self.ast_ty_to_ty(rscope, &a.ty),
1800 pub fn ty_of_method(&self,
1801 sig: &hir::MethodSig,
1802 untransformed_self_ty: Ty<'tcx>)
1803 -> (&'tcx ty::BareFnTy<'tcx>, ty::ExplicitSelfCategory) {
1804 let (bare_fn_ty, optional_explicit_self_category) =
1805 self.ty_of_method_or_bare_fn(sig.unsafety,
1807 Some(untransformed_self_ty),
1809 (bare_fn_ty, optional_explicit_self_category)
1812 pub fn ty_of_bare_fn(&self,
1813 unsafety: hir::Unsafety,
1816 -> &'tcx ty::BareFnTy<'tcx> {
1817 self.ty_of_method_or_bare_fn(unsafety, abi, None, decl).0
1820 fn ty_of_method_or_bare_fn<'a>(&self,
1821 unsafety: hir::Unsafety,
1823 opt_untransformed_self_ty: Option<Ty<'tcx>>,
1825 -> (&'tcx ty::BareFnTy<'tcx>, ty::ExplicitSelfCategory)
1827 debug!("ty_of_method_or_bare_fn");
1829 // New region names that appear inside of the arguments of the function
1830 // declaration are bound to that function type.
1831 let rb = rscope::BindingRscope::new();
1833 // `implied_output_region` is the region that will be assumed for any
1834 // region parameters in the return type. In accordance with the rules for
1835 // lifetime elision, we can determine it in two ways. First (determined
1836 // here), if self is by-reference, then the implied output region is the
1837 // region of the self parameter.
1838 let (self_ty, explicit_self_category) = match (opt_untransformed_self_ty, decl.get_self()) {
1839 (Some(untransformed_self_ty), Some(explicit_self)) => {
1840 let self_type = self.determine_self_type(&rb, untransformed_self_ty,
1842 (Some(self_type.0), self_type.1)
1844 _ => (None, ty::ExplicitSelfCategory::Static),
1847 // HACK(eddyb) replace the fake self type in the AST with the actual type.
1848 let arg_params = if self_ty.is_some() {
1853 let arg_tys: Vec<Ty> =
1854 arg_params.iter().map(|a| self.ty_of_arg(&rb, a, None)).collect();
1855 let arg_pats: Vec<String> =
1856 arg_params.iter().map(|a| pprust::pat_to_string(&a.pat)).collect();
1858 // Second, if there was exactly one lifetime (either a substitution or a
1859 // reference) in the arguments, then any anonymous regions in the output
1860 // have that lifetime.
1861 let implied_output_region = match explicit_self_category {
1862 ty::ExplicitSelfCategory::ByReference(region, _) => Ok(region),
1863 _ => self.find_implied_output_region(&arg_tys, arg_pats)
1866 let output_ty = match decl.output {
1867 hir::Return(ref output) =>
1868 ty::FnConverging(self.convert_ty_with_lifetime_elision(implied_output_region,
1870 hir::DefaultReturn(..) => ty::FnConverging(self.tcx().mk_nil()),
1871 hir::NoReturn(..) => ty::FnDiverging
1874 (self.tcx().mk_bare_fn(ty::BareFnTy {
1877 sig: ty::Binder(ty::FnSig {
1878 inputs: self_ty.into_iter().chain(arg_tys).collect(),
1880 variadic: decl.variadic
1882 }), explicit_self_category)
1885 fn determine_self_type<'a>(&self,
1886 rscope: &RegionScope,
1887 untransformed_self_ty: Ty<'tcx>,
1888 explicit_self: &hir::ExplicitSelf)
1889 -> (Ty<'tcx>, ty::ExplicitSelfCategory)
1891 return match explicit_self.node {
1892 SelfKind::Value(..) => {
1893 (untransformed_self_ty, ty::ExplicitSelfCategory::ByValue)
1895 SelfKind::Region(ref lifetime, mutability) => {
1897 self.opt_ast_region_to_region(
1902 self.tcx().mk_region(region),
1904 ty: untransformed_self_ty,
1907 ty::ExplicitSelfCategory::ByReference(region, mutability))
1909 SelfKind::Explicit(ref ast_type, _) => {
1910 let explicit_type = self.ast_ty_to_ty(rscope, &ast_type);
1912 // We wish to (for now) categorize an explicit self
1913 // declaration like `self: SomeType` into either `self`,
1914 // `&self`, `&mut self`, or `Box<self>`. We do this here
1915 // by some simple pattern matching. A more precise check
1916 // is done later in `check_method_self_type()`.
1921 // impl Foo for &T {
1922 // // Legal declarations:
1923 // fn method1(self: &&T); // ExplicitSelfCategory::ByReference
1924 // fn method2(self: &T); // ExplicitSelfCategory::ByValue
1925 // fn method3(self: Box<&T>); // ExplicitSelfCategory::ByBox
1927 // // Invalid cases will be caught later by `check_method_self_type`:
1928 // fn method_err1(self: &mut T); // ExplicitSelfCategory::ByReference
1932 // To do the check we just count the number of "modifiers"
1933 // on each type and compare them. If they are the same or
1934 // the impl has more, we call it "by value". Otherwise, we
1935 // look at the outermost modifier on the method decl and
1936 // call it by-ref, by-box as appropriate. For method1, for
1937 // example, the impl type has one modifier, but the method
1938 // type has two, so we end up with
1939 // ExplicitSelfCategory::ByReference.
1941 let impl_modifiers = count_modifiers(untransformed_self_ty);
1942 let method_modifiers = count_modifiers(explicit_type);
1944 debug!("determine_explicit_self_category(self_info.untransformed_self_ty={:?} \
1945 explicit_type={:?} \
1947 untransformed_self_ty,
1952 let category = if impl_modifiers >= method_modifiers {
1953 ty::ExplicitSelfCategory::ByValue
1955 match explicit_type.sty {
1956 ty::TyRef(r, mt) => ty::ExplicitSelfCategory::ByReference(*r, mt.mutbl),
1957 ty::TyBox(_) => ty::ExplicitSelfCategory::ByBox,
1958 _ => ty::ExplicitSelfCategory::ByValue,
1962 (explicit_type, category)
1966 fn count_modifiers(ty: Ty) -> usize {
1968 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
1969 ty::TyBox(t) => count_modifiers(t) + 1,
1975 pub fn ty_of_closure(&self,
1976 unsafety: hir::Unsafety,
1979 expected_sig: Option<ty::FnSig<'tcx>>)
1980 -> ty::ClosureTy<'tcx>
1982 debug!("ty_of_closure(expected_sig={:?})",
1985 // new region names that appear inside of the fn decl are bound to
1986 // that function type
1987 let rb = rscope::BindingRscope::new();
1989 let input_tys: Vec<_> = decl.inputs.iter().enumerate().map(|(i, a)| {
1990 let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1991 // no guarantee that the correct number of expected args
1993 if i < e.inputs.len() {
1999 self.ty_of_arg(&rb, a, expected_arg_ty)
2002 let expected_ret_ty = expected_sig.map(|e| e.output);
2004 let is_infer = match decl.output {
2005 hir::Return(ref output) if output.node == hir::TyInfer => true,
2006 hir::DefaultReturn(..) => true,
2010 let output_ty = match decl.output {
2011 _ if is_infer && expected_ret_ty.is_some() =>
2012 expected_ret_ty.unwrap(),
2014 ty::FnConverging(self.ty_infer(None, None, None, decl.output.span())),
2015 hir::Return(ref output) =>
2016 ty::FnConverging(self.ast_ty_to_ty(&rb, &output)),
2017 hir::DefaultReturn(..) => bug!(),
2018 hir::NoReturn(..) => ty::FnDiverging
2021 debug!("ty_of_closure: input_tys={:?}", input_tys);
2022 debug!("ty_of_closure: output_ty={:?}", output_ty);
2027 sig: ty::Binder(ty::FnSig {inputs: input_tys,
2029 variadic: decl.variadic}),
2033 /// Given an existential type like `Foo+'a+Bar`, this routine converts
2034 /// the `'a` and `Bar` intos an `ExistentialBounds` struct.
2035 /// The `main_trait_refs` argument specifies the `Foo` -- it is absent
2036 /// for closures. Eventually this should all be normalized, I think,
2037 /// so that there is no "main trait ref" and instead we just have a flat
2038 /// list of bounds as the existential type.
2039 fn conv_existential_bounds(&self,
2040 rscope: &RegionScope,
2042 principal_trait_ref: ty::PolyTraitRef<'tcx>,
2043 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
2044 ast_bounds: &[hir::TyParamBound])
2045 -> ty::ExistentialBounds<'tcx>
2047 let partitioned_bounds =
2048 partition_bounds(self.tcx(), span, ast_bounds);
2050 self.conv_existential_bounds_from_partitioned_bounds(
2051 rscope, span, principal_trait_ref, projection_bounds, partitioned_bounds)
2054 fn conv_ty_poly_trait_ref(&self,
2055 rscope: &RegionScope,
2057 ast_bounds: &[hir::TyParamBound])
2060 let mut partitioned_bounds = partition_bounds(self.tcx(), span, &ast_bounds[..]);
2062 let mut projection_bounds = Vec::new();
2063 let main_trait_bound = if !partitioned_bounds.trait_bounds.is_empty() {
2064 let trait_bound = partitioned_bounds.trait_bounds.remove(0);
2065 self.instantiate_poly_trait_ref(rscope,
2068 &mut projection_bounds)
2070 span_err!(self.tcx().sess, span, E0224,
2071 "at least one non-builtin trait is required for an object type");
2072 return self.tcx().types.err;
2076 self.conv_existential_bounds_from_partitioned_bounds(rscope,
2078 main_trait_bound.clone(),
2080 partitioned_bounds);
2082 self.make_object_type(span, main_trait_bound, bounds)
2085 pub fn conv_existential_bounds_from_partitioned_bounds(&self,
2086 rscope: &RegionScope,
2088 principal_trait_ref: ty::PolyTraitRef<'tcx>,
2089 projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>, // Empty for boxed closures
2090 partitioned_bounds: PartitionedBounds)
2091 -> ty::ExistentialBounds<'tcx>
2093 let PartitionedBounds { builtin_bounds,
2098 if !trait_bounds.is_empty() {
2099 let b = &trait_bounds[0];
2100 let span = b.trait_ref.path.span;
2101 struct_span_err!(self.tcx().sess, span, E0225,
2102 "only the builtin traits can be used as closure or object bounds")
2103 .span_label(span, &format!("non-builtin trait used as bounds"))
2108 self.compute_object_lifetime_bound(span,
2110 principal_trait_ref,
2113 let region_bound = match region_bound {
2116 match rscope.object_lifetime_default(span) {
2119 span_err!(self.tcx().sess, span, E0228,
2120 "the lifetime bound for this object type cannot be deduced \
2121 from context; please supply an explicit bound");
2128 debug!("region_bound: {:?}", region_bound);
2130 ty::ExistentialBounds::new(region_bound, builtin_bounds, projection_bounds)
2133 /// Given the bounds on an object, determines what single region bound (if any) we can
2134 /// use to summarize this type. The basic idea is that we will use the bound the user
2135 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2136 /// for region bounds. It may be that we can derive no bound at all, in which case
2137 /// we return `None`.
2138 fn compute_object_lifetime_bound(&self,
2140 explicit_region_bounds: &[&hir::Lifetime],
2141 principal_trait_ref: ty::PolyTraitRef<'tcx>,
2142 builtin_bounds: ty::BuiltinBounds)
2143 -> Option<ty::Region> // if None, use the default
2145 let tcx = self.tcx();
2147 debug!("compute_opt_region_bound(explicit_region_bounds={:?}, \
2148 principal_trait_ref={:?}, builtin_bounds={:?})",
2149 explicit_region_bounds,
2150 principal_trait_ref,
2153 if explicit_region_bounds.len() > 1 {
2154 span_err!(tcx.sess, explicit_region_bounds[1].span, E0226,
2155 "only a single explicit lifetime bound is permitted");
2158 if !explicit_region_bounds.is_empty() {
2159 // Explicitly specified region bound. Use that.
2160 let r = explicit_region_bounds[0];
2161 return Some(ast_region_to_region(tcx, r));
2164 if let Err(ErrorReported) =
2165 self.ensure_super_predicates(span, principal_trait_ref.def_id()) {
2166 return Some(ty::ReStatic);
2169 // No explicit region bound specified. Therefore, examine trait
2170 // bounds and see if we can derive region bounds from those.
2171 let derived_region_bounds =
2172 object_region_bounds(tcx, &principal_trait_ref, builtin_bounds);
2174 // If there are no derived region bounds, then report back that we
2175 // can find no region bound. The caller will use the default.
2176 if derived_region_bounds.is_empty() {
2180 // If any of the derived region bounds are 'static, that is always
2182 if derived_region_bounds.iter().any(|r| ty::ReStatic == *r) {
2183 return Some(ty::ReStatic);
2186 // Determine whether there is exactly one unique region in the set
2187 // of derived region bounds. If so, use that. Otherwise, report an
2189 let r = derived_region_bounds[0];
2190 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2191 span_err!(tcx.sess, span, E0227,
2192 "ambiguous lifetime bound, explicit lifetime bound required");
2198 pub struct PartitionedBounds<'a> {
2199 pub builtin_bounds: ty::BuiltinBounds,
2200 pub trait_bounds: Vec<&'a hir::PolyTraitRef>,
2201 pub region_bounds: Vec<&'a hir::Lifetime>,
2204 /// Divides a list of bounds from the AST into three groups: builtin bounds (Copy, Sized etc),
2205 /// general trait bounds, and region bounds.
2206 pub fn partition_bounds<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
2208 ast_bounds: &'b [hir::TyParamBound])
2209 -> PartitionedBounds<'b>
2211 let mut builtin_bounds = ty::BuiltinBounds::empty();
2212 let mut region_bounds = Vec::new();
2213 let mut trait_bounds = Vec::new();
2214 for ast_bound in ast_bounds {
2216 hir::TraitTyParamBound(ref b, hir::TraitBoundModifier::None) => {
2217 match tcx.expect_def(b.trait_ref.ref_id) {
2218 Def::Trait(trait_did) => {
2219 if tcx.try_add_builtin_trait(trait_did,
2220 &mut builtin_bounds) {
2221 let segments = &b.trait_ref.path.segments;
2222 let parameters = &segments[segments.len() - 1].parameters;
2223 if !parameters.types().is_empty() {
2224 check_type_argument_count(tcx, b.trait_ref.path.span,
2225 parameters.types().len(), 0, 0);
2227 if !parameters.lifetimes().is_empty() {
2228 report_lifetime_number_error(tcx, b.trait_ref.path.span,
2229 parameters.lifetimes().len(), 0);
2231 continue; // success
2235 // Not a trait? that's an error, but it'll get
2239 trait_bounds.push(b);
2241 hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {}
2242 hir::RegionTyParamBound(ref l) => {
2243 region_bounds.push(l);
2249 builtin_bounds: builtin_bounds,
2250 trait_bounds: trait_bounds,
2251 region_bounds: region_bounds,
2255 fn check_type_argument_count(tcx: TyCtxt, span: Span, supplied: usize,
2256 required: usize, accepted: usize) {
2257 if supplied < required {
2258 let expected = if required < accepted {
2263 struct_span_err!(tcx.sess, span, E0243, "wrong number of type arguments")
2266 &format!("{} {} type arguments, found {}", expected, required, supplied)
2269 } else if supplied > accepted {
2270 let expected = if required == 0 {
2271 "expected no".to_string()
2272 } else if required < accepted {
2273 format!("expected at most {}", accepted)
2275 format!("expected {}", accepted)
2278 struct_span_err!(tcx.sess, span, E0244, "wrong number of type arguments")
2281 &format!("{} type arguments, found {}", expected, supplied)
2287 fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected: usize) {
2288 let label = if number < expected {
2290 format!("expected {} lifetime parameter", expected)
2292 format!("expected {} lifetime parameters", expected)
2295 let additional = number - expected;
2296 if additional == 1 {
2297 "unexpected lifetime parameter".to_string()
2299 format!("{} unexpected lifetime parameters", additional)
2302 struct_span_err!(tcx.sess, span, E0107,
2303 "wrong number of lifetime parameters: expected {}, found {}",
2305 .span_label(span, &label)
2309 // A helper struct for conveniently grouping a set of bounds which we pass to
2310 // and return from functions in multiple places.
2311 #[derive(PartialEq, Eq, Clone, Debug)]
2312 pub struct Bounds<'tcx> {
2313 pub region_bounds: Vec<ty::Region>,
2314 pub builtin_bounds: ty::BuiltinBounds,
2315 pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
2316 pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
2319 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
2320 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
2321 -> Vec<ty::Predicate<'tcx>>
2323 let mut vec = Vec::new();
2325 for builtin_bound in &self.builtin_bounds {
2326 match tcx.trait_ref_for_builtin_bound(builtin_bound, param_ty) {
2327 Ok(trait_ref) => { vec.push(trait_ref.to_predicate()); }
2328 Err(ErrorReported) => { }
2332 for ®ion_bound in &self.region_bounds {
2333 // account for the binder being introduced below; no need to shift `param_ty`
2334 // because, at present at least, it can only refer to early-bound regions
2335 let region_bound = ty::fold::shift_region(region_bound, 1);
2336 vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
2339 for bound_trait_ref in &self.trait_bounds {
2340 vec.push(bound_trait_ref.to_predicate());
2343 for projection in &self.projection_bounds {
2344 vec.push(projection.to_predicate());