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::{Subst, Substs};
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 rscope::{AnonTypeScope, MaybeWithAnonTypes};
68 use util::common::{ErrorReported, FN_OUTPUT_NAME};
69 use util::nodemap::{NodeMap, FnvHashSet};
71 use std::cell::RefCell;
72 use syntax::{abi, ast};
73 use syntax::feature_gate::{GateIssue, emit_feature_err};
74 use syntax::parse::token::{self, keywords};
75 use syntax_pos::{Span, Pos};
76 use errors::DiagnosticBuilder;
78 pub trait AstConv<'gcx, 'tcx> {
79 fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
81 /// A cache used for the result of `ast_ty_to_ty_cache`
82 fn ast_ty_to_ty_cache(&self) -> &RefCell<NodeMap<Ty<'tcx>>>;
84 /// Returns the generic type and lifetime parameters for an item.
85 fn get_generics(&self, span: Span, id: DefId)
86 -> Result<&'tcx ty::Generics<'tcx>, ErrorReported>;
88 /// Identify the type scheme for an item with a type, like a type
89 /// alias, fn, or struct. This allows you to figure out the set of
90 /// type parameters defined on the item.
91 fn get_item_type_scheme(&self, span: Span, id: DefId)
92 -> Result<ty::TypeScheme<'tcx>, ErrorReported>;
94 /// Returns the `TraitDef` for a given trait. This allows you to
95 /// figure out the set of type parameters defined on the trait.
96 fn get_trait_def(&self, span: Span, id: DefId)
97 -> Result<&'tcx ty::TraitDef<'tcx>, ErrorReported>;
99 /// Ensure that the super-predicates for the trait with the given
100 /// id are available and also for the transitive set of
101 /// super-predicates.
102 fn ensure_super_predicates(&self, span: Span, id: DefId)
103 -> Result<(), ErrorReported>;
105 /// Returns the set of bounds in scope for the type parameter with
107 fn get_type_parameter_bounds(&self, span: Span, def_id: ast::NodeId)
108 -> Result<Vec<ty::PolyTraitRef<'tcx>>, ErrorReported>;
110 /// Returns true if the trait with id `trait_def_id` defines an
111 /// associated type with the name `name`.
112 fn trait_defines_associated_type_named(&self, trait_def_id: DefId, name: ast::Name)
115 /// Return an (optional) substitution to convert bound type parameters that
116 /// are in scope into free ones. This function should only return Some
117 /// within a fn body.
118 /// See ParameterEnvironment::free_substs for more information.
119 fn get_free_substs(&self) -> Option<&Substs<'tcx>>;
121 /// What type should we use when a type is omitted?
122 fn ty_infer(&self, span: Span) -> Ty<'tcx>;
124 /// Same as ty_infer, but with a known type parameter definition.
125 fn ty_infer_for_def(&self,
126 _def: &ty::TypeParameterDef<'tcx>,
127 _substs: &Substs<'tcx>,
128 span: Span) -> Ty<'tcx> {
132 /// Projecting an associated type from a (potentially)
133 /// higher-ranked trait reference is more complicated, because of
134 /// the possibility of late-bound regions appearing in the
135 /// associated type binding. This is not legal in function
136 /// signatures for that reason. In a function body, we can always
137 /// handle it because we can use inference variables to remove the
138 /// late-bound regions.
139 fn projected_ty_from_poly_trait_ref(&self,
141 poly_trait_ref: ty::PolyTraitRef<'tcx>,
142 item_name: ast::Name)
145 /// Project an associated type from a non-higher-ranked trait reference.
146 /// This is fairly straightforward and can be accommodated in any context.
147 fn projected_ty(&self,
149 _trait_ref: ty::TraitRef<'tcx>,
150 _item_name: ast::Name)
153 /// Invoked when we encounter an error from some prior pass
154 /// (e.g. resolve) that is translated into a ty-error. This is
155 /// used to help suppress derived errors typeck might otherwise
157 fn set_tainted_by_errors(&self);
160 #[derive(PartialEq, Eq)]
161 pub enum PathParamMode {
162 // Any path in a type context.
164 // The `module::Type` in `module::Type::method` in an expression.
168 struct ConvertedBinding<'tcx> {
169 item_name: ast::Name,
174 type TraitAndProjections<'tcx> = (ty::PolyTraitRef<'tcx>, Vec<ty::PolyProjectionPredicate<'tcx>>);
176 /// Dummy type used for the `Self` of a `TraitRef` created for converting
177 /// a trait object, and which gets removed in `ExistentialTraitRef`.
178 /// This type must not appear anywhere in other converted types.
179 const TRAIT_OBJECT_DUMMY_SELF: ty::TypeVariants<'static> = ty::TyInfer(ty::FreshTy(0));
181 pub fn ast_region_to_region(tcx: TyCtxt, lifetime: &hir::Lifetime)
183 let r = match tcx.named_region_map.defs.get(&lifetime.id) {
185 // should have been recorded by the `resolve_lifetime` pass
186 span_bug!(lifetime.span, "unresolved lifetime");
189 Some(&rl::DefStaticRegion) => {
193 Some(&rl::DefLateBoundRegion(debruijn, id)) => {
194 // If this region is declared on a function, it will have
195 // an entry in `late_bound`, but if it comes from
196 // `for<'a>` in some type or something, it won't
197 // necessarily have one. In that case though, we won't be
198 // changed from late to early bound, so we can just
200 let issue_32330 = tcx.named_region_map
204 .unwrap_or(ty::Issue32330::WontChange);
205 ty::ReLateBound(debruijn, ty::BrNamed(tcx.map.local_def_id(id),
210 Some(&rl::DefEarlyBoundRegion(index, _)) => {
211 ty::ReEarlyBound(ty::EarlyBoundRegion {
217 Some(&rl::DefFreeRegion(scope, id)) => {
218 // As in DefLateBoundRegion above, could be missing for some late-bound
219 // regions, but also for early-bound regions.
220 let issue_32330 = tcx.named_region_map
224 .unwrap_or(ty::Issue32330::WontChange);
225 ty::ReFree(ty::FreeRegion {
226 scope: scope.to_code_extent(&tcx.region_maps),
227 bound_region: ty::BrNamed(tcx.map.local_def_id(id),
232 // (*) -- not late-bound, won't change
236 debug!("ast_region_to_region(lifetime={:?} id={}) yields {:?}",
244 fn report_elision_failure(
245 db: &mut DiagnosticBuilder,
246 params: Vec<ElisionFailureInfo>)
248 let mut m = String::new();
249 let len = params.len();
251 let elided_params: Vec<_> = params.into_iter()
252 .filter(|info| info.lifetime_count > 0)
255 let elided_len = elided_params.len();
257 for (i, info) in elided_params.into_iter().enumerate() {
258 let ElisionFailureInfo {
259 name, lifetime_count: n, have_bound_regions
262 let help_name = if name.is_empty() {
263 format!("argument {}", i + 1)
265 format!("`{}`", name)
268 m.push_str(&(if n == 1 {
271 format!("one of {}'s {} elided {}lifetimes", help_name, n,
272 if have_bound_regions { "free " } else { "" } )
275 if elided_len == 2 && i == 0 {
277 } else if i + 2 == elided_len {
279 } else if i != elided_len - 1 {
287 "this function's return type contains a borrowed value, but \
288 there is no value for it to be borrowed from");
290 "consider giving it a 'static lifetime");
291 } else if elided_len == 0 {
293 "this function's return type contains a borrowed value with \
294 an elided lifetime, but the lifetime cannot be derived from \
297 "consider giving it an explicit bounded or 'static \
299 } else if elided_len == 1 {
301 "this function's return type contains a borrowed value, but \
302 the signature does not say which {} it is borrowed from",
306 "this function's return type contains a borrowed value, but \
307 the signature does not say whether it is borrowed from {}",
312 impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
313 pub fn opt_ast_region_to_region(&self,
314 rscope: &RegionScope,
316 opt_lifetime: &Option<hir::Lifetime>) -> ty::Region
318 let r = match *opt_lifetime {
319 Some(ref lifetime) => {
320 ast_region_to_region(self.tcx(), lifetime)
323 None => match rscope.anon_regions(default_span, 1) {
326 let ampersand_span = Span { hi: default_span.lo, ..default_span};
328 let mut err = struct_span_err!(self.tcx().sess, ampersand_span, E0106,
329 "missing lifetime specifier");
330 err.span_label(ampersand_span, &format!("expected lifetime parameter"));
332 if let Some(params) = params {
333 report_elision_failure(&mut err, params);
341 debug!("opt_ast_region_to_region(opt_lifetime={:?}) yields {:?}",
348 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
349 /// returns an appropriate set of substitutions for this particular reference to `I`.
350 pub fn ast_path_substs_for_ty(&self,
351 rscope: &RegionScope,
353 param_mode: PathParamMode,
355 item_segment: &hir::PathSegment)
356 -> &'tcx Substs<'tcx>
358 let tcx = self.tcx();
360 match item_segment.parameters {
361 hir::AngleBracketedParameters(_) => {}
362 hir::ParenthesizedParameters(..) => {
363 struct_span_err!(tcx.sess, span, E0214,
364 "parenthesized parameters may only be used with a trait")
365 .span_label(span, &format!("only traits may use parentheses"))
368 return Substs::for_item(tcx, def_id, |_, _| {
376 let (substs, assoc_bindings) =
377 self.create_substs_for_ast_path(rscope,
381 &item_segment.parameters,
384 assoc_bindings.first().map(|b| self.tcx().prohibit_projection(b.span));
389 /// Given the type/region arguments provided to some path (along with
390 /// an implicit Self, if this is a trait reference) returns the complete
391 /// set of substitutions. This may involve applying defaulted type parameters.
393 /// Note that the type listing given here is *exactly* what the user provided.
394 fn create_substs_for_ast_path(&self,
395 rscope: &RegionScope,
397 param_mode: PathParamMode,
399 parameters: &hir::PathParameters,
400 self_ty: Option<Ty<'tcx>>)
401 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
403 let tcx = self.tcx();
405 debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
407 def_id, self_ty, parameters);
409 let (lifetimes, num_types_provided) = match *parameters {
410 hir::AngleBracketedParameters(ref data) => {
411 if param_mode == PathParamMode::Optional && data.types.is_empty() {
412 (&data.lifetimes[..], None)
414 (&data.lifetimes[..], Some(data.types.len()))
417 hir::ParenthesizedParameters(_) => (&[][..], Some(1))
420 // If the type is parameterized by this region, then replace this
421 // region with the current anon region binding (in other words,
422 // whatever & would get replaced with).
423 let decl_generics = match self.get_generics(span, def_id) {
424 Ok(generics) => generics,
425 Err(ErrorReported) => {
426 // No convenient way to recover from a cycle here. Just bail. Sorry!
427 self.tcx().sess.abort_if_errors();
428 bug!("ErrorReported returned, but no errors reports?")
431 let expected_num_region_params = decl_generics.regions.len();
432 let supplied_num_region_params = lifetimes.len();
433 let regions = if expected_num_region_params == supplied_num_region_params {
434 lifetimes.iter().map(|l| ast_region_to_region(tcx, l)).collect()
437 rscope.anon_regions(span, expected_num_region_params);
439 if supplied_num_region_params != 0 || anon_regions.is_err() {
440 report_lifetime_number_error(tcx, span,
441 supplied_num_region_params,
442 expected_num_region_params);
446 Ok(anon_regions) => anon_regions,
447 Err(_) => (0..expected_num_region_params).map(|_| ty::ReStatic).collect()
451 // If a self-type was declared, one should be provided.
452 assert_eq!(decl_generics.has_self, self_ty.is_some());
454 // Check the number of type parameters supplied by the user.
455 if let Some(num_provided) = num_types_provided {
456 let ty_param_defs = &decl_generics.types[self_ty.is_some() as usize..];
457 check_type_argument_count(tcx, span, num_provided, ty_param_defs);
460 let is_object = self_ty.map_or(false, |ty| ty.sty == TRAIT_OBJECT_DUMMY_SELF);
461 let default_needs_object_self = |p: &ty::TypeParameterDef<'tcx>| {
462 if let Some(ref default) = p.default {
463 if is_object && default.has_self_ty() {
464 // There is no suitable inference default for a type parameter
465 // that references self, in an object type.
473 let mut output_assoc_binding = None;
474 let substs = Substs::for_item(tcx, def_id, |def, _| {
475 regions[def.index as usize]
477 let i = def.index as usize;
479 // Handle Self first, so we can adjust the index to match the AST.
480 if let (0, Some(ty)) = (i, self_ty) {
484 let i = i - self_ty.is_some() as usize;
485 if num_types_provided.map_or(false, |n| i < n) {
486 // A provided type parameter.
488 hir::AngleBracketedParameters(ref data) => {
489 self.ast_ty_arg_to_ty(rscope, Some(def), substs, &data.types[i])
491 hir::ParenthesizedParameters(ref data) => {
494 self.convert_parenthesized_parameters(rscope, substs, data);
495 output_assoc_binding = Some(assoc);
499 } else if num_types_provided.is_none() {
500 // No type parameters were provided, we can infer all.
501 let ty_var = if !default_needs_object_self(def) {
502 self.ty_infer_for_def(def, substs, span)
507 } else if let Some(default) = def.default {
508 // No type parameter provided, but a default exists.
510 // If we are converting an object type, then the
511 // `Self` parameter is unknown. However, some of the
512 // other type parameters may reference `Self` in their
513 // defaults. This will lead to an ICE if we are not
515 if default_needs_object_self(def) {
516 span_err!(tcx.sess, span, E0393,
517 "the type parameter `{}` must be explicitly specified \
518 in an object type because its default value `{}` references \
524 // This is a default type parameter.
525 default.subst_spanned(tcx, substs, Some(span))
528 // We've already errored above about the mismatch.
533 let assoc_bindings = match *parameters {
534 hir::AngleBracketedParameters(ref data) => {
535 data.bindings.iter().map(|b| {
538 ty: self.ast_ty_to_ty(rscope, &b.ty),
543 hir::ParenthesizedParameters(ref data) => {
544 vec![output_assoc_binding.unwrap_or_else(|| {
545 // This is an error condition, but we should
546 // get the associated type binding anyway.
547 self.convert_parenthesized_parameters(rscope, substs, data).1
552 debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}) -> {:?}",
553 decl_generics, self_ty, substs);
555 (substs, assoc_bindings)
558 /// Returns the appropriate lifetime to use for any output lifetimes
559 /// (if one exists) and a vector of the (pattern, number of lifetimes)
560 /// corresponding to each input type/pattern.
561 fn find_implied_output_region(&self,
562 input_tys: &[Ty<'tcx>],
563 input_pats: Vec<String>) -> ElidedLifetime
565 let tcx = self.tcx();
566 let mut lifetimes_for_params = Vec::new();
567 let mut possible_implied_output_region = None;
569 for (input_type, input_pat) in input_tys.iter().zip(input_pats) {
570 let mut regions = FnvHashSet();
571 let have_bound_regions = tcx.collect_regions(input_type, &mut regions);
573 debug!("find_implied_output_regions: collected {:?} from {:?} \
574 have_bound_regions={:?}", ®ions, input_type, have_bound_regions);
576 if regions.len() == 1 {
577 // there's a chance that the unique lifetime of this
578 // iteration will be the appropriate lifetime for output
579 // parameters, so lets store it.
580 possible_implied_output_region = regions.iter().cloned().next();
583 lifetimes_for_params.push(ElisionFailureInfo {
585 lifetime_count: regions.len(),
586 have_bound_regions: have_bound_regions
590 if lifetimes_for_params.iter().map(|e| e.lifetime_count).sum::<usize>() == 1 {
591 Ok(possible_implied_output_region.unwrap())
593 Err(Some(lifetimes_for_params))
597 fn convert_ty_with_lifetime_elision(&self,
598 elided_lifetime: ElidedLifetime,
600 anon_scope: Option<AnonTypeScope>)
603 match elided_lifetime {
604 Ok(implied_output_region) => {
605 let rb = ElidableRscope::new(implied_output_region);
606 self.ast_ty_to_ty(&MaybeWithAnonTypes::new(rb, anon_scope), ty)
608 Err(param_lifetimes) => {
609 // All regions must be explicitly specified in the output
610 // if the lifetime elision rules do not apply. This saves
611 // the user from potentially-confusing errors.
612 let rb = UnelidableRscope::new(param_lifetimes);
613 self.ast_ty_to_ty(&MaybeWithAnonTypes::new(rb, anon_scope), ty)
618 fn convert_parenthesized_parameters(&self,
619 rscope: &RegionScope,
620 region_substs: &Substs<'tcx>,
621 data: &hir::ParenthesizedParameterData)
622 -> (Ty<'tcx>, ConvertedBinding<'tcx>)
624 let anon_scope = rscope.anon_type_scope();
625 let binding_rscope = MaybeWithAnonTypes::new(BindingRscope::new(), anon_scope);
626 let inputs: Vec<_> = data.inputs.iter().map(|a_t| {
627 self.ast_ty_arg_to_ty(&binding_rscope, None, region_substs, a_t)
629 let input_params = vec![String::new(); inputs.len()];
630 let implied_output_region = self.find_implied_output_region(&inputs, input_params);
632 let (output, output_span) = match data.output {
633 Some(ref output_ty) => {
634 (self.convert_ty_with_lifetime_elision(implied_output_region,
640 (self.tcx().mk_nil(), data.span)
644 let output_binding = ConvertedBinding {
645 item_name: token::intern(FN_OUTPUT_NAME),
650 (self.tcx().mk_tup(inputs), output_binding)
653 pub fn instantiate_poly_trait_ref(&self,
654 rscope: &RegionScope,
655 ast_trait_ref: &hir::PolyTraitRef,
657 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
658 -> ty::PolyTraitRef<'tcx>
660 let trait_ref = &ast_trait_ref.trait_ref;
661 let trait_def_id = self.trait_def_id(trait_ref);
662 self.ast_path_to_poly_trait_ref(rscope,
664 PathParamMode::Explicit,
668 trait_ref.path.segments.last().unwrap(),
672 /// Instantiates the path for the given trait reference, assuming that it's
673 /// bound to a valid trait type. Returns the def_id for the defining trait.
674 /// Fails if the type is a type other than a trait type.
676 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
677 /// are disallowed. Otherwise, they are pushed onto the vector given.
678 pub fn instantiate_mono_trait_ref(&self,
679 rscope: &RegionScope,
680 trait_ref: &hir::TraitRef,
682 -> ty::TraitRef<'tcx>
684 let trait_def_id = self.trait_def_id(trait_ref);
685 self.ast_path_to_mono_trait_ref(rscope,
687 PathParamMode::Explicit,
690 trait_ref.path.segments.last().unwrap())
693 fn trait_def_id(&self, trait_ref: &hir::TraitRef) -> DefId {
694 let path = &trait_ref.path;
695 match self.tcx().expect_def(trait_ref.ref_id) {
696 Def::Trait(trait_def_id) => trait_def_id,
698 self.tcx().sess.fatal("cannot continue compilation due to previous error");
701 span_fatal!(self.tcx().sess, path.span, E0245, "`{}` is not a trait",
707 fn ast_path_to_poly_trait_ref(&self,
708 rscope: &RegionScope,
710 param_mode: PathParamMode,
713 path_id: ast::NodeId,
714 trait_segment: &hir::PathSegment,
715 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
716 -> ty::PolyTraitRef<'tcx>
718 debug!("ast_path_to_poly_trait_ref(trait_segment={:?})", trait_segment);
719 // The trait reference introduces a binding level here, so
720 // we need to shift the `rscope`. It'd be nice if we could
721 // do away with this rscope stuff and work this knowledge
722 // into resolve_lifetimes, as we do with non-omitted
723 // lifetimes. Oh well, not there yet.
724 let shifted_rscope = &ShiftedRscope::new(rscope);
726 let (substs, assoc_bindings) =
727 self.create_substs_for_ast_trait_ref(shifted_rscope,
733 let poly_trait_ref = ty::Binder(ty::TraitRef::new(trait_def_id, substs));
735 poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
736 // specify type to assert that error was already reported in Err case:
737 let predicate: Result<_, ErrorReported> =
738 self.ast_type_binding_to_poly_projection_predicate(path_id,
741 predicate.ok() // ok to ignore Err() because ErrorReported (see above)
744 debug!("ast_path_to_poly_trait_ref(trait_segment={:?}, projections={:?}) -> {:?}",
745 trait_segment, poly_projections, poly_trait_ref);
749 fn ast_path_to_mono_trait_ref(&self,
750 rscope: &RegionScope,
752 param_mode: PathParamMode,
755 trait_segment: &hir::PathSegment)
756 -> ty::TraitRef<'tcx>
758 let (substs, assoc_bindings) =
759 self.create_substs_for_ast_trait_ref(rscope,
765 assoc_bindings.first().map(|b| self.tcx().prohibit_projection(b.span));
766 ty::TraitRef::new(trait_def_id, substs)
769 fn create_substs_for_ast_trait_ref(&self,
770 rscope: &RegionScope,
772 param_mode: PathParamMode,
775 trait_segment: &hir::PathSegment)
776 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
778 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
781 let trait_def = match self.get_trait_def(span, trait_def_id) {
782 Ok(trait_def) => trait_def,
783 Err(ErrorReported) => {
784 // No convenient way to recover from a cycle here. Just bail. Sorry!
785 self.tcx().sess.abort_if_errors();
786 bug!("ErrorReported returned, but no errors reports?")
790 match trait_segment.parameters {
791 hir::AngleBracketedParameters(_) => {
792 // For now, require that parenthetical notation be used
793 // only with `Fn()` etc.
794 if !self.tcx().sess.features.borrow().unboxed_closures && trait_def.paren_sugar {
795 emit_feature_err(&self.tcx().sess.parse_sess.span_diagnostic,
796 "unboxed_closures", span, GateIssue::Language,
798 the precise format of `Fn`-family traits' \
799 type parameters is subject to change. \
800 Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead");
803 hir::ParenthesizedParameters(_) => {
804 // For now, require that parenthetical notation be used
805 // only with `Fn()` etc.
806 if !self.tcx().sess.features.borrow().unboxed_closures && !trait_def.paren_sugar {
807 emit_feature_err(&self.tcx().sess.parse_sess.span_diagnostic,
808 "unboxed_closures", span, GateIssue::Language,
810 parenthetical notation is only stable when used with `Fn`-family traits");
815 self.create_substs_for_ast_path(rscope,
819 &trait_segment.parameters,
823 fn ast_type_binding_to_poly_projection_predicate(
825 path_id: ast::NodeId,
826 trait_ref: ty::PolyTraitRef<'tcx>,
827 binding: &ConvertedBinding<'tcx>)
828 -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
830 let tcx = self.tcx();
832 // Given something like `U : SomeTrait<T=X>`, we want to produce a
833 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
834 // subtle in the event that `T` is defined in a supertrait of
835 // `SomeTrait`, because in that case we need to upcast.
837 // That is, consider this case:
840 // trait SubTrait : SuperTrait<int> { }
841 // trait SuperTrait<A> { type T; }
843 // ... B : SubTrait<T=foo> ...
846 // We want to produce `<B as SuperTrait<int>>::T == foo`.
848 // Find any late-bound regions declared in `ty` that are not
849 // declared in the trait-ref. These are not wellformed.
853 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
854 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
855 let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
856 let late_bound_in_ty = tcx.collect_referenced_late_bound_regions(&ty::Binder(binding.ty));
857 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
858 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
859 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
860 let br_name = match *br {
861 ty::BrNamed(_, name, _) => name,
865 "anonymous bound region {:?} in binding but not trait ref",
870 lint::builtin::HR_LIFETIME_IN_ASSOC_TYPE,
873 format!("binding for associated type `{}` references lifetime `{}`, \
874 which does not appear in the trait input types",
875 binding.item_name, br_name));
878 // Simple case: X is defined in the current trait.
879 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
880 return Ok(trait_ref.map_bound(|trait_ref| {
881 ty::ProjectionPredicate {
882 projection_ty: ty::ProjectionTy {
883 trait_ref: trait_ref,
884 item_name: binding.item_name,
891 // Otherwise, we have to walk through the supertraits to find
893 self.ensure_super_predicates(binding.span, trait_ref.def_id())?;
895 let candidates: Vec<ty::PolyTraitRef> =
896 traits::supertraits(tcx, trait_ref.clone())
897 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), binding.item_name))
900 let candidate = self.one_bound_for_assoc_type(candidates,
901 &trait_ref.to_string(),
902 &binding.item_name.as_str(),
905 Ok(candidate.map_bound(|trait_ref| {
906 ty::ProjectionPredicate {
907 projection_ty: ty::ProjectionTy {
908 trait_ref: trait_ref,
909 item_name: binding.item_name,
916 fn ast_path_to_ty(&self,
917 rscope: &RegionScope,
919 param_mode: PathParamMode,
921 item_segment: &hir::PathSegment)
924 let tcx = self.tcx();
925 let decl_ty = match self.get_item_type_scheme(span, did) {
926 Ok(type_scheme) => type_scheme.ty,
927 Err(ErrorReported) => {
928 return tcx.types.err;
932 let substs = self.ast_path_substs_for_ty(rscope,
938 // FIXME(#12938): This is a hack until we have full support for DST.
939 if Some(did) == self.tcx().lang_items.owned_box() {
940 assert_eq!(substs.types.len(), 1);
941 return self.tcx().mk_box(substs.types[0]);
944 decl_ty.subst(self.tcx(), substs)
947 fn ast_ty_to_object_trait_ref(&self,
948 rscope: &RegionScope,
951 bounds: &[hir::TyParamBound])
955 * In a type like `Foo + Send`, we want to wait to collect the
956 * full set of bounds before we make the object type, because we
957 * need them to infer a region bound. (For example, if we tried
958 * made a type from just `Foo`, then it wouldn't be enough to
959 * infer a 'static bound, and hence the user would get an error.)
960 * So this function is used when we're dealing with a sum type to
961 * convert the LHS. It only accepts a type that refers to a trait
962 * name, and reports an error otherwise.
965 let tcx = self.tcx();
967 hir::TyPath(None, ref path) => {
968 let resolution = tcx.expect_resolution(ty.id);
969 match resolution.base_def {
970 Def::Trait(trait_def_id) if resolution.depth == 0 => {
971 self.trait_path_to_object_type(rscope,
973 PathParamMode::Explicit,
976 path.segments.last().unwrap(),
978 partition_bounds(tcx, span, bounds))
981 struct_span_err!(tcx.sess, ty.span, E0172,
982 "expected a reference to a trait")
983 .span_label(ty.span, &format!("expected a trait"))
990 let mut err = struct_span_err!(tcx.sess, ty.span, E0178,
991 "expected a path on the left-hand side \
993 pprust::ty_to_string(ty));
994 err.span_label(ty.span, &format!("expected a path"));
995 let hi = bounds.iter().map(|x| match *x {
996 hir::TraitTyParamBound(ref tr, _) => tr.span.hi,
997 hir::RegionTyParamBound(ref r) => r.span.hi,
998 }).max_by_key(|x| x.to_usize());
999 let full_span = hi.map(|hi| Span {
1002 expn_id: ty.span.expn_id,
1004 match (&ty.node, full_span) {
1005 (&hir::TyRptr(None, ref mut_ty), Some(full_span)) => {
1006 let mutbl_str = if mut_ty.mutbl == hir::MutMutable { "mut " } else { "" };
1007 err.span_suggestion(full_span, "try adding parentheses (per RFC 438):",
1008 format!("&{}({} +{})",
1010 pprust::ty_to_string(&mut_ty.ty),
1011 pprust::bounds_to_string(bounds)));
1013 (&hir::TyRptr(Some(ref lt), ref mut_ty), Some(full_span)) => {
1014 let mutbl_str = if mut_ty.mutbl == hir::MutMutable { "mut " } else { "" };
1015 err.span_suggestion(full_span, "try adding parentheses (per RFC 438):",
1016 format!("&{} {}({} +{})",
1017 pprust::lifetime_to_string(lt),
1019 pprust::ty_to_string(&mut_ty.ty),
1020 pprust::bounds_to_string(bounds)));
1025 "perhaps you forgot parentheses? (per RFC 438)");
1034 /// Transform a PolyTraitRef into a PolyExistentialTraitRef by
1035 /// removing the dummy Self type (TRAIT_OBJECT_DUMMY_SELF).
1036 fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
1037 -> ty::ExistentialTraitRef<'tcx> {
1038 assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
1039 ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
1042 fn trait_path_to_object_type(&self,
1043 rscope: &RegionScope,
1045 param_mode: PathParamMode,
1046 trait_def_id: DefId,
1047 trait_path_ref_id: ast::NodeId,
1048 trait_segment: &hir::PathSegment,
1050 partitioned_bounds: PartitionedBounds)
1052 let tcx = self.tcx();
1054 let mut projection_bounds = vec![];
1055 let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
1056 let principal = self.ast_path_to_poly_trait_ref(rscope,
1063 &mut projection_bounds);
1065 let PartitionedBounds { builtin_bounds,
1070 if !trait_bounds.is_empty() {
1071 let b = &trait_bounds[0];
1072 let span = b.trait_ref.path.span;
1073 struct_span_err!(self.tcx().sess, span, E0225,
1074 "only the builtin traits can be used as closure or object bounds")
1075 .span_label(span, &format!("non-builtin trait used as bounds"))
1079 // Erase the dummy_self (TRAIT_OBJECT_DUMMY_SELF) used above.
1080 let existential_principal = principal.map_bound(|trait_ref| {
1081 self.trait_ref_to_existential(trait_ref)
1083 let existential_projections = projection_bounds.iter().map(|bound| {
1084 bound.map_bound(|b| {
1085 let p = b.projection_ty;
1086 ty::ExistentialProjection {
1087 trait_ref: self.trait_ref_to_existential(p.trait_ref),
1088 item_name: p.item_name,
1095 self.compute_object_lifetime_bound(span,
1097 existential_principal,
1100 let region_bound = match region_bound {
1103 match rscope.object_lifetime_default(span) {
1106 span_err!(self.tcx().sess, span, E0228,
1107 "the lifetime bound for this object type cannot be deduced \
1108 from context; please supply an explicit bound");
1115 debug!("region_bound: {:?}", region_bound);
1117 // ensure the super predicates and stop if we encountered an error
1118 if self.ensure_super_predicates(span, principal.def_id()).is_err() {
1119 return tcx.types.err;
1122 // check that there are no gross object safety violations,
1123 // most importantly, that the supertraits don't contain Self,
1125 let object_safety_violations =
1126 tcx.astconv_object_safety_violations(principal.def_id());
1127 if !object_safety_violations.is_empty() {
1128 tcx.report_object_safety_error(
1129 span, principal.def_id(), None, object_safety_violations)
1131 return tcx.types.err;
1134 let mut associated_types: FnvHashSet<(DefId, ast::Name)> =
1135 traits::supertraits(tcx, principal)
1137 let trait_def = tcx.lookup_trait_def(tr.def_id());
1138 trait_def.associated_type_names
1141 .map(move |associated_type_name| (tr.def_id(), associated_type_name))
1145 for projection_bound in &projection_bounds {
1146 let pair = (projection_bound.0.projection_ty.trait_ref.def_id,
1147 projection_bound.0.projection_ty.item_name);
1148 associated_types.remove(&pair);
1151 for (trait_def_id, name) in associated_types {
1152 struct_span_err!(tcx.sess, span, E0191,
1153 "the value of the associated type `{}` (from the trait `{}`) must be specified",
1155 tcx.item_path_str(trait_def_id))
1156 .span_label(span, &format!(
1157 "missing associated type `{}` value", name))
1161 let ty = tcx.mk_trait(ty::TraitObject {
1162 principal: existential_principal,
1163 region_bound: region_bound,
1164 builtin_bounds: builtin_bounds,
1165 projection_bounds: existential_projections
1167 debug!("trait_object_type: {:?}", ty);
1171 fn report_ambiguous_associated_type(&self,
1176 struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
1177 .span_label(span, &format!("ambiguous associated type"))
1178 .note(&format!("specify the type using the syntax `<{} as {}>::{}`",
1179 type_str, trait_str, name))
1184 // Search for a bound on a type parameter which includes the associated item
1185 // given by assoc_name. ty_param_node_id is the node id for the type parameter
1186 // (which might be `Self`, but only if it is the `Self` of a trait, not an
1187 // impl). This function will fail if there are no suitable bounds or there is
1189 fn find_bound_for_assoc_item(&self,
1190 ty_param_node_id: ast::NodeId,
1191 ty_param_name: ast::Name,
1192 assoc_name: ast::Name,
1194 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1196 let tcx = self.tcx();
1198 let bounds = match self.get_type_parameter_bounds(span, ty_param_node_id) {
1200 Err(ErrorReported) => {
1201 return Err(ErrorReported);
1205 // Ensure the super predicates and stop if we encountered an error.
1206 if bounds.iter().any(|b| self.ensure_super_predicates(span, b.def_id()).is_err()) {
1207 return Err(ErrorReported);
1210 // Check that there is exactly one way to find an associated type with the
1212 let suitable_bounds: Vec<_> =
1213 traits::transitive_bounds(tcx, &bounds)
1214 .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name))
1217 self.one_bound_for_assoc_type(suitable_bounds,
1218 &ty_param_name.as_str(),
1219 &assoc_name.as_str(),
1224 // Checks that bounds contains exactly one element and reports appropriate
1225 // errors otherwise.
1226 fn one_bound_for_assoc_type(&self,
1227 bounds: Vec<ty::PolyTraitRef<'tcx>>,
1228 ty_param_name: &str,
1231 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1233 if bounds.is_empty() {
1234 span_err!(self.tcx().sess, span, E0220,
1235 "associated type `{}` not found for `{}`",
1238 return Err(ErrorReported);
1241 if bounds.len() > 1 {
1242 let mut err = struct_span_err!(
1243 self.tcx().sess, span, E0221,
1244 "ambiguous associated type `{}` in bounds of `{}`",
1247 err.span_label(span, &format!("ambiguous associated type `{}`", assoc_name));
1249 for bound in &bounds {
1250 span_note!(&mut err, span,
1251 "associated type `{}` could derive from `{}`",
1258 Ok(bounds[0].clone())
1261 // Create a type from a path to an associated type.
1262 // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
1263 // and item_segment is the path segment for D. We return a type and a def for
1265 // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
1266 // parameter or Self.
1267 fn associated_path_def_to_ty(&self,
1271 item_segment: &hir::PathSegment)
1274 let tcx = self.tcx();
1275 let assoc_name = item_segment.name;
1277 debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
1279 tcx.prohibit_type_params(slice::ref_slice(item_segment));
1281 // Find the type of the associated item, and the trait where the associated
1282 // item is declared.
1283 let bound = match (&ty.sty, ty_path_def) {
1284 (_, Def::SelfTy(Some(trait_did), Some(impl_id))) => {
1285 // For Def::SelfTy() values inlined from another crate, the
1286 // impl_id will be DUMMY_NODE_ID, which would cause problems
1287 // here. But we should never run into an impl from another crate
1289 assert!(impl_id != ast::DUMMY_NODE_ID);
1291 // `Self` in an impl of a trait - we have a concrete self type and a
1293 let trait_ref = tcx.impl_trait_ref(tcx.map.local_def_id(impl_id)).unwrap();
1294 let trait_ref = if let Some(free_substs) = self.get_free_substs() {
1295 trait_ref.subst(tcx, free_substs)
1300 if self.ensure_super_predicates(span, trait_did).is_err() {
1301 return (tcx.types.err, Def::Err);
1304 let candidates: Vec<ty::PolyTraitRef> =
1305 traits::supertraits(tcx, ty::Binder(trait_ref))
1306 .filter(|r| self.trait_defines_associated_type_named(r.def_id(),
1310 match self.one_bound_for_assoc_type(candidates,
1312 &assoc_name.as_str(),
1315 Err(ErrorReported) => return (tcx.types.err, Def::Err),
1318 (&ty::TyParam(_), Def::SelfTy(Some(trait_did), None)) => {
1319 let trait_node_id = tcx.map.as_local_node_id(trait_did).unwrap();
1320 match self.find_bound_for_assoc_item(trait_node_id,
1321 keywords::SelfType.name(),
1325 Err(ErrorReported) => return (tcx.types.err, Def::Err),
1328 (&ty::TyParam(_), Def::TyParam(param_did)) => {
1329 let param_node_id = tcx.map.as_local_node_id(param_did).unwrap();
1330 let param_name = tcx.type_parameter_def(param_node_id).name;
1331 match self.find_bound_for_assoc_item(param_node_id,
1336 Err(ErrorReported) => return (tcx.types.err, Def::Err),
1340 // Don't print TyErr to the user.
1341 if !ty.references_error() {
1342 self.report_ambiguous_associated_type(span,
1345 &assoc_name.as_str());
1347 return (tcx.types.err, Def::Err);
1351 let trait_did = bound.0.def_id;
1352 let ty = self.projected_ty_from_poly_trait_ref(span, bound, assoc_name);
1354 let item_did = if let Some(trait_id) = tcx.map.as_local_node_id(trait_did) {
1355 // `ty::trait_items` used below requires information generated
1356 // by type collection, which may be in progress at this point.
1357 match tcx.map.expect_item(trait_id).node {
1358 hir::ItemTrait(_, _, _, ref trait_items) => {
1359 let item = trait_items.iter()
1360 .find(|i| i.name == assoc_name)
1361 .expect("missing associated type");
1362 tcx.map.local_def_id(item.id)
1367 let trait_items = tcx.trait_items(trait_did);
1368 let item = trait_items.iter().find(|i| i.name() == assoc_name);
1369 item.expect("missing associated type").def_id()
1372 (ty, Def::AssociatedTy(trait_did, item_did))
1375 fn qpath_to_ty(&self,
1376 rscope: &RegionScope,
1378 param_mode: PathParamMode,
1379 opt_self_ty: Option<Ty<'tcx>>,
1380 trait_def_id: DefId,
1381 trait_segment: &hir::PathSegment,
1382 item_segment: &hir::PathSegment)
1385 let tcx = self.tcx();
1387 tcx.prohibit_type_params(slice::ref_slice(item_segment));
1389 let self_ty = if let Some(ty) = opt_self_ty {
1392 let path_str = tcx.item_path_str(trait_def_id);
1393 self.report_ambiguous_associated_type(span,
1396 &item_segment.name.as_str());
1397 return tcx.types.err;
1400 debug!("qpath_to_ty: self_type={:?}", self_ty);
1402 let trait_ref = self.ast_path_to_mono_trait_ref(rscope,
1409 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1411 self.projected_ty(span, trait_ref, item_segment.name)
1414 /// Convert a type supplied as value for a type argument from AST into our
1415 /// our internal representation. This is the same as `ast_ty_to_ty` but that
1416 /// it applies the object lifetime default.
1420 /// * `this`, `rscope`: the surrounding context
1421 /// * `def`: the type parameter being instantiated (if available)
1422 /// * `region_substs`: a partial substitution consisting of
1423 /// only the region type parameters being supplied to this type.
1424 /// * `ast_ty`: the ast representation of the type being supplied
1425 fn ast_ty_arg_to_ty(&self,
1426 rscope: &RegionScope,
1427 def: Option<&ty::TypeParameterDef<'tcx>>,
1428 region_substs: &Substs<'tcx>,
1432 let tcx = self.tcx();
1434 if let Some(def) = def {
1435 let object_lifetime_default = def.object_lifetime_default.subst(tcx, region_substs);
1436 let rscope1 = &ObjectLifetimeDefaultRscope::new(rscope, object_lifetime_default);
1437 self.ast_ty_to_ty(rscope1, ast_ty)
1439 self.ast_ty_to_ty(rscope, ast_ty)
1443 // Check the base def in a PathResolution and convert it to a Ty. If there are
1444 // associated types in the PathResolution, these will need to be separately
1446 fn base_def_to_ty(&self,
1447 rscope: &RegionScope,
1449 param_mode: PathParamMode,
1451 opt_self_ty: Option<Ty<'tcx>>,
1452 base_path_ref_id: ast::NodeId,
1453 base_segments: &[hir::PathSegment])
1455 let tcx = self.tcx();
1457 debug!("base_def_to_ty(def={:?}, opt_self_ty={:?}, base_segments={:?})",
1458 def, opt_self_ty, base_segments);
1461 Def::Trait(trait_def_id) => {
1462 // N.B. this case overlaps somewhat with
1463 // TyObjectSum, see that fn for details
1465 tcx.prohibit_type_params(base_segments.split_last().unwrap().1);
1467 self.trait_path_to_object_type(rscope,
1472 base_segments.last().unwrap(),
1474 partition_bounds(tcx, span, &[]))
1476 Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) => {
1477 tcx.prohibit_type_params(base_segments.split_last().unwrap().1);
1478 self.ast_path_to_ty(rscope,
1482 base_segments.last().unwrap())
1484 Def::TyParam(did) => {
1485 tcx.prohibit_type_params(base_segments);
1487 let node_id = tcx.map.as_local_node_id(did).unwrap();
1488 let param = tcx.ty_param_defs.borrow().get(&node_id)
1489 .map(ty::ParamTy::for_def);
1490 if let Some(p) = param {
1493 // Only while computing defaults of earlier type
1494 // parameters can a type parameter be missing its def.
1495 struct_span_err!(tcx.sess, span, E0128,
1496 "type parameters with a default cannot use \
1497 forward declared identifiers")
1498 .span_label(span, &format!("defaulted type parameters \
1499 cannot be forward declared"))
1504 Def::SelfTy(_, Some(impl_id)) => {
1505 // Self in impl (we know the concrete type).
1507 // For Def::SelfTy() values inlined from another crate, the
1508 // impl_id will be DUMMY_NODE_ID, which would cause problems
1509 // here. But we should never run into an impl from another crate
1511 assert!(impl_id != ast::DUMMY_NODE_ID);
1513 tcx.prohibit_type_params(base_segments);
1514 let ty = tcx.node_id_to_type(impl_id);
1515 if let Some(free_substs) = self.get_free_substs() {
1516 ty.subst(tcx, free_substs)
1521 Def::SelfTy(Some(_), None) => {
1523 tcx.prohibit_type_params(base_segments);
1526 Def::AssociatedTy(trait_did, _) => {
1527 tcx.prohibit_type_params(&base_segments[..base_segments.len()-2]);
1528 self.qpath_to_ty(rscope,
1533 &base_segments[base_segments.len()-2],
1534 base_segments.last().unwrap())
1537 // Used as sentinel by callers to indicate the `<T>::A::B::C` form.
1538 // FIXME(#22519) This part of the resolution logic should be
1539 // avoided entirely for that form, once we stop needed a Def
1540 // for `associated_path_def_to_ty`.
1541 // Fixing this will also let use resolve <Self>::Foo the same way we
1542 // resolve Self::Foo, at the moment we can't resolve the former because
1543 // we don't have the trait information around, which is just sad.
1545 assert!(base_segments.is_empty());
1547 opt_self_ty.expect("missing T in <T>::a::b::c")
1549 Def::PrimTy(prim_ty) => {
1550 tcx.prim_ty_to_ty(base_segments, prim_ty)
1553 self.set_tainted_by_errors();
1554 return self.tcx().types.err;
1557 struct_span_err!(tcx.sess, span, E0248,
1558 "found value `{}` used as a type",
1559 tcx.item_path_str(def.def_id()))
1560 .span_label(span, &format!("value used as a type"))
1562 return self.tcx().types.err;
1567 // Resolve possibly associated type path into a type and final definition.
1568 // Note that both base_segments and assoc_segments may be empty, although not at same time.
1569 pub fn finish_resolving_def_to_ty(&self,
1570 rscope: &RegionScope,
1572 param_mode: PathParamMode,
1574 opt_self_ty: Option<Ty<'tcx>>,
1575 base_path_ref_id: ast::NodeId,
1576 base_segments: &[hir::PathSegment],
1577 assoc_segments: &[hir::PathSegment])
1578 -> (Ty<'tcx>, Def) {
1579 // Convert the base type.
1580 debug!("finish_resolving_def_to_ty(base_def={:?}, \
1581 base_segments={:?}, \
1582 assoc_segments={:?})",
1586 let base_ty = self.base_def_to_ty(rscope,
1593 debug!("finish_resolving_def_to_ty: base_def_to_ty returned {:?}", base_ty);
1595 // If any associated type segments remain, attempt to resolve them.
1596 let (mut ty, mut def) = (base_ty, base_def);
1597 for segment in assoc_segments {
1598 debug!("finish_resolving_def_to_ty: segment={:?}", segment);
1599 // This is pretty bad (it will fail except for T::A and Self::A).
1600 let (new_ty, new_def) = self.associated_path_def_to_ty(span, ty, def, segment);
1604 if def == Def::Err {
1611 /// Parses the programmer's textual representation of a type into our
1612 /// internal notion of a type.
1613 pub fn ast_ty_to_ty(&self, rscope: &RegionScope, ast_ty: &hir::Ty) -> Ty<'tcx> {
1614 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1617 let tcx = self.tcx();
1619 let cache = self.ast_ty_to_ty_cache();
1620 match cache.borrow().get(&ast_ty.id) {
1621 Some(ty) => { return ty; }
1625 let result_ty = match ast_ty.node {
1626 hir::TyVec(ref ty) => {
1627 tcx.mk_slice(self.ast_ty_to_ty(rscope, &ty))
1629 hir::TyObjectSum(ref ty, ref bounds) => {
1630 self.ast_ty_to_object_trait_ref(rscope, ast_ty.span, ty, bounds)
1632 hir::TyPtr(ref mt) => {
1633 tcx.mk_ptr(ty::TypeAndMut {
1634 ty: self.ast_ty_to_ty(rscope, &mt.ty),
1638 hir::TyRptr(ref region, ref mt) => {
1639 let r = self.opt_ast_region_to_region(rscope, ast_ty.span, region);
1640 debug!("TyRef r={:?}", r);
1642 &ObjectLifetimeDefaultRscope::new(
1644 ty::ObjectLifetimeDefault::Specific(r));
1645 let t = self.ast_ty_to_ty(rscope1, &mt.ty);
1646 tcx.mk_ref(tcx.mk_region(r), ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1651 hir::TyTup(ref fields) => {
1652 let flds = fields.iter()
1653 .map(|t| self.ast_ty_to_ty(rscope, &t))
1657 hir::TyBareFn(ref bf) => {
1658 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1659 let anon_scope = rscope.anon_type_scope();
1660 let (bare_fn_ty, _) =
1661 self.ty_of_method_or_bare_fn(bf.unsafety,
1668 // Find any late-bound regions declared in return type that do
1669 // not appear in the arguments. These are not wellformed.
1673 // for<'a> fn() -> &'a str <-- 'a is bad
1674 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1676 // Note that we do this check **here** and not in
1677 // `ty_of_bare_fn` because the latter is also used to make
1678 // the types for fn items, and we do not want to issue a
1679 // warning then. (Once we fix #32330, the regions we are
1680 // checking for here would be considered early bound
1682 let inputs = bare_fn_ty.sig.inputs();
1683 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(&inputs);
1684 let output = bare_fn_ty.sig.output();
1685 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1686 for br in late_bound_in_ret.difference(&late_bound_in_args) {
1687 let br_name = match *br {
1688 ty::BrNamed(_, name, _) => name,
1691 bf.decl.output.span(),
1692 "anonymous bound region {:?} in return but not args",
1697 lint::builtin::HR_LIFETIME_IN_ASSOC_TYPE,
1700 format!("return type references lifetime `{}`, \
1701 which does not appear in the trait input types",
1704 tcx.mk_fn_ptr(bare_fn_ty)
1706 hir::TyPolyTraitRef(ref bounds) => {
1707 self.conv_object_ty_poly_trait_ref(rscope, ast_ty.span, bounds)
1709 hir::TyImplTrait(ref bounds) => {
1710 use collect::{compute_bounds, SizedByDefault};
1712 // Create the anonymized type.
1713 let def_id = tcx.map.local_def_id(ast_ty.id);
1714 if let Some(anon_scope) = rscope.anon_type_scope() {
1715 let substs = anon_scope.fresh_substs(self, ast_ty.span);
1716 let ty = tcx.mk_anon(tcx.map.local_def_id(ast_ty.id), substs);
1718 // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`.
1719 let bounds = compute_bounds(self, ty, bounds,
1720 SizedByDefault::Yes,
1723 let predicates = bounds.predicates(tcx, ty);
1724 let predicates = tcx.lift_to_global(&predicates).unwrap();
1725 tcx.predicates.borrow_mut().insert(def_id, ty::GenericPredicates {
1727 predicates: predicates
1732 span_err!(tcx.sess, ast_ty.span, E0562,
1733 "`impl Trait` not allowed outside of function \
1734 and inherent method return types");
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(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(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 anon_scope: Option<AnonTypeScope>)
1804 -> (&'tcx ty::BareFnTy<'tcx>, ty::ExplicitSelfCategory) {
1805 self.ty_of_method_or_bare_fn(sig.unsafety,
1807 Some(untransformed_self_ty),
1813 pub fn ty_of_bare_fn(&self,
1814 unsafety: hir::Unsafety,
1817 anon_scope: Option<AnonTypeScope>)
1818 -> &'tcx ty::BareFnTy<'tcx> {
1819 self.ty_of_method_or_bare_fn(unsafety, abi, None, decl, None, anon_scope).0
1822 fn ty_of_method_or_bare_fn(&self,
1823 unsafety: hir::Unsafety,
1825 opt_untransformed_self_ty: Option<Ty<'tcx>>,
1827 arg_anon_scope: Option<AnonTypeScope>,
1828 ret_anon_scope: Option<AnonTypeScope>)
1829 -> (&'tcx ty::BareFnTy<'tcx>, ty::ExplicitSelfCategory)
1831 debug!("ty_of_method_or_bare_fn");
1833 // New region names that appear inside of the arguments of the function
1834 // declaration are bound to that function type.
1835 let rb = MaybeWithAnonTypes::new(BindingRscope::new(), arg_anon_scope);
1837 // `implied_output_region` is the region that will be assumed for any
1838 // region parameters in the return type. In accordance with the rules for
1839 // lifetime elision, we can determine it in two ways. First (determined
1840 // here), if self is by-reference, then the implied output region is the
1841 // region of the self parameter.
1842 let (self_ty, explicit_self_category) = match (opt_untransformed_self_ty, decl.get_self()) {
1843 (Some(untransformed_self_ty), Some(explicit_self)) => {
1844 let self_type = self.determine_self_type(&rb, untransformed_self_ty,
1846 (Some(self_type.0), self_type.1)
1848 _ => (None, ty::ExplicitSelfCategory::Static),
1851 // HACK(eddyb) replace the fake self type in the AST with the actual type.
1852 let arg_params = if self_ty.is_some() {
1857 let arg_tys: Vec<Ty> =
1858 arg_params.iter().map(|a| self.ty_of_arg(&rb, a, None)).collect();
1859 let arg_pats: Vec<String> =
1860 arg_params.iter().map(|a| pprust::pat_to_string(&a.pat)).collect();
1862 // Second, if there was exactly one lifetime (either a substitution or a
1863 // reference) in the arguments, then any anonymous regions in the output
1864 // have that lifetime.
1865 let implied_output_region = match explicit_self_category {
1866 ty::ExplicitSelfCategory::ByReference(region, _) => Ok(region),
1867 _ => self.find_implied_output_region(&arg_tys, arg_pats)
1870 let output_ty = match decl.output {
1871 hir::Return(ref output) =>
1872 self.convert_ty_with_lifetime_elision(implied_output_region,
1875 hir::DefaultReturn(..) => self.tcx().mk_nil(),
1878 (self.tcx().mk_bare_fn(ty::BareFnTy {
1881 sig: ty::Binder(ty::FnSig {
1882 inputs: self_ty.into_iter().chain(arg_tys).collect(),
1884 variadic: decl.variadic
1886 }), explicit_self_category)
1889 fn determine_self_type<'a>(&self,
1890 rscope: &RegionScope,
1891 untransformed_self_ty: Ty<'tcx>,
1892 explicit_self: &hir::ExplicitSelf)
1893 -> (Ty<'tcx>, ty::ExplicitSelfCategory)
1895 return match explicit_self.node {
1896 SelfKind::Value(..) => {
1897 (untransformed_self_ty, ty::ExplicitSelfCategory::ByValue)
1899 SelfKind::Region(ref lifetime, mutability) => {
1901 self.opt_ast_region_to_region(
1906 self.tcx().mk_region(region),
1908 ty: untransformed_self_ty,
1911 ty::ExplicitSelfCategory::ByReference(region, mutability))
1913 SelfKind::Explicit(ref ast_type, _) => {
1914 let explicit_type = self.ast_ty_to_ty(rscope, &ast_type);
1916 // We wish to (for now) categorize an explicit self
1917 // declaration like `self: SomeType` into either `self`,
1918 // `&self`, `&mut self`, or `Box<self>`. We do this here
1919 // by some simple pattern matching. A more precise check
1920 // is done later in `check_method_self_type()`.
1925 // impl Foo for &T {
1926 // // Legal declarations:
1927 // fn method1(self: &&T); // ExplicitSelfCategory::ByReference
1928 // fn method2(self: &T); // ExplicitSelfCategory::ByValue
1929 // fn method3(self: Box<&T>); // ExplicitSelfCategory::ByBox
1931 // // Invalid cases will be caught later by `check_method_self_type`:
1932 // fn method_err1(self: &mut T); // ExplicitSelfCategory::ByReference
1936 // To do the check we just count the number of "modifiers"
1937 // on each type and compare them. If they are the same or
1938 // the impl has more, we call it "by value". Otherwise, we
1939 // look at the outermost modifier on the method decl and
1940 // call it by-ref, by-box as appropriate. For method1, for
1941 // example, the impl type has one modifier, but the method
1942 // type has two, so we end up with
1943 // ExplicitSelfCategory::ByReference.
1945 let impl_modifiers = count_modifiers(untransformed_self_ty);
1946 let method_modifiers = count_modifiers(explicit_type);
1948 debug!("determine_explicit_self_category(self_info.untransformed_self_ty={:?} \
1949 explicit_type={:?} \
1951 untransformed_self_ty,
1956 let category = if impl_modifiers >= method_modifiers {
1957 ty::ExplicitSelfCategory::ByValue
1959 match explicit_type.sty {
1960 ty::TyRef(r, mt) => ty::ExplicitSelfCategory::ByReference(*r, mt.mutbl),
1961 ty::TyBox(_) => ty::ExplicitSelfCategory::ByBox,
1962 _ => ty::ExplicitSelfCategory::ByValue,
1966 (explicit_type, category)
1970 fn count_modifiers(ty: Ty) -> usize {
1972 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
1973 ty::TyBox(t) => count_modifiers(t) + 1,
1979 pub fn ty_of_closure(&self,
1980 unsafety: hir::Unsafety,
1983 expected_sig: Option<ty::FnSig<'tcx>>)
1984 -> ty::ClosureTy<'tcx>
1986 debug!("ty_of_closure(expected_sig={:?})",
1989 // new region names that appear inside of the fn decl are bound to
1990 // that function type
1991 let rb = rscope::BindingRscope::new();
1993 let input_tys: Vec<_> = decl.inputs.iter().enumerate().map(|(i, a)| {
1994 let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1995 // no guarantee that the correct number of expected args
1997 if i < e.inputs.len() {
2003 self.ty_of_arg(&rb, a, expected_arg_ty)
2006 let expected_ret_ty = expected_sig.map(|e| e.output);
2008 let is_infer = match decl.output {
2009 hir::Return(ref output) if output.node == hir::TyInfer => true,
2010 hir::DefaultReturn(..) => true,
2014 let output_ty = match decl.output {
2015 _ if is_infer && expected_ret_ty.is_some() =>
2016 expected_ret_ty.unwrap(),
2017 _ if is_infer => self.ty_infer(decl.output.span()),
2018 hir::Return(ref output) =>
2019 self.ast_ty_to_ty(&rb, &output),
2020 hir::DefaultReturn(..) => bug!(),
2023 debug!("ty_of_closure: input_tys={:?}", input_tys);
2024 debug!("ty_of_closure: output_ty={:?}", output_ty);
2029 sig: ty::Binder(ty::FnSig {inputs: input_tys,
2031 variadic: decl.variadic}),
2035 fn conv_object_ty_poly_trait_ref(&self,
2036 rscope: &RegionScope,
2038 ast_bounds: &[hir::TyParamBound])
2041 let mut partitioned_bounds = partition_bounds(self.tcx(), span, &ast_bounds[..]);
2043 let trait_bound = if !partitioned_bounds.trait_bounds.is_empty() {
2044 partitioned_bounds.trait_bounds.remove(0)
2046 span_err!(self.tcx().sess, span, E0224,
2047 "at least one non-builtin trait is required for an object type");
2048 return self.tcx().types.err;
2051 let trait_ref = &trait_bound.trait_ref;
2052 let trait_def_id = self.trait_def_id(trait_ref);
2053 self.trait_path_to_object_type(rscope,
2054 trait_ref.path.span,
2055 PathParamMode::Explicit,
2058 trait_ref.path.segments.last().unwrap(),
2063 /// Given the bounds on an object, determines what single region bound (if any) we can
2064 /// use to summarize this type. The basic idea is that we will use the bound the user
2065 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2066 /// for region bounds. It may be that we can derive no bound at all, in which case
2067 /// we return `None`.
2068 fn compute_object_lifetime_bound(&self,
2070 explicit_region_bounds: &[&hir::Lifetime],
2071 principal_trait_ref: ty::PolyExistentialTraitRef<'tcx>,
2072 builtin_bounds: ty::BuiltinBounds)
2073 -> Option<ty::Region> // if None, use the default
2075 let tcx = self.tcx();
2077 debug!("compute_opt_region_bound(explicit_region_bounds={:?}, \
2078 principal_trait_ref={:?}, builtin_bounds={:?})",
2079 explicit_region_bounds,
2080 principal_trait_ref,
2083 if explicit_region_bounds.len() > 1 {
2084 span_err!(tcx.sess, explicit_region_bounds[1].span, E0226,
2085 "only a single explicit lifetime bound is permitted");
2088 if !explicit_region_bounds.is_empty() {
2089 // Explicitly specified region bound. Use that.
2090 let r = explicit_region_bounds[0];
2091 return Some(ast_region_to_region(tcx, r));
2094 if let Err(ErrorReported) =
2095 self.ensure_super_predicates(span, principal_trait_ref.def_id()) {
2096 return Some(ty::ReStatic);
2099 // No explicit region bound specified. Therefore, examine trait
2100 // bounds and see if we can derive region bounds from those.
2101 let derived_region_bounds =
2102 object_region_bounds(tcx, principal_trait_ref, builtin_bounds);
2104 // If there are no derived region bounds, then report back that we
2105 // can find no region bound. The caller will use the default.
2106 if derived_region_bounds.is_empty() {
2110 // If any of the derived region bounds are 'static, that is always
2112 if derived_region_bounds.iter().any(|r| ty::ReStatic == *r) {
2113 return Some(ty::ReStatic);
2116 // Determine whether there is exactly one unique region in the set
2117 // of derived region bounds. If so, use that. Otherwise, report an
2119 let r = derived_region_bounds[0];
2120 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2121 span_err!(tcx.sess, span, E0227,
2122 "ambiguous lifetime bound, explicit lifetime bound required");
2128 pub struct PartitionedBounds<'a> {
2129 pub builtin_bounds: ty::BuiltinBounds,
2130 pub trait_bounds: Vec<&'a hir::PolyTraitRef>,
2131 pub region_bounds: Vec<&'a hir::Lifetime>,
2134 /// Divides a list of bounds from the AST into three groups: builtin bounds (Copy, Sized etc),
2135 /// general trait bounds, and region bounds.
2136 pub fn partition_bounds<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
2138 ast_bounds: &'b [hir::TyParamBound])
2139 -> PartitionedBounds<'b>
2141 let mut builtin_bounds = ty::BuiltinBounds::empty();
2142 let mut region_bounds = Vec::new();
2143 let mut trait_bounds = Vec::new();
2144 for ast_bound in ast_bounds {
2146 hir::TraitTyParamBound(ref b, hir::TraitBoundModifier::None) => {
2147 match tcx.expect_def(b.trait_ref.ref_id) {
2148 Def::Trait(trait_did) => {
2149 if tcx.try_add_builtin_trait(trait_did,
2150 &mut builtin_bounds) {
2151 let segments = &b.trait_ref.path.segments;
2152 let parameters = &segments[segments.len() - 1].parameters;
2153 if !parameters.types().is_empty() {
2154 check_type_argument_count(tcx, b.trait_ref.path.span,
2155 parameters.types().len(), &[]);
2157 if !parameters.lifetimes().is_empty() {
2158 report_lifetime_number_error(tcx, b.trait_ref.path.span,
2159 parameters.lifetimes().len(), 0);
2161 continue; // success
2165 // Not a trait? that's an error, but it'll get
2169 trait_bounds.push(b);
2171 hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {}
2172 hir::RegionTyParamBound(ref l) => {
2173 region_bounds.push(l);
2179 builtin_bounds: builtin_bounds,
2180 trait_bounds: trait_bounds,
2181 region_bounds: region_bounds,
2185 fn check_type_argument_count(tcx: TyCtxt, span: Span, supplied: usize,
2186 ty_param_defs: &[ty::TypeParameterDef]) {
2187 let accepted = ty_param_defs.len();
2188 let required = ty_param_defs.iter().take_while(|x| x.default.is_none()) .count();
2189 if supplied < required {
2190 let expected = if required < accepted {
2195 struct_span_err!(tcx.sess, span, E0243, "wrong number of type arguments")
2198 &format!("{} {} type arguments, found {}", expected, required, supplied)
2201 } else if supplied > accepted {
2202 let expected = if required == 0 {
2203 "expected no".to_string()
2204 } else if required < accepted {
2205 format!("expected at most {}", accepted)
2207 format!("expected {}", accepted)
2210 struct_span_err!(tcx.sess, span, E0244, "wrong number of type arguments")
2213 &format!("{} type arguments, found {}", expected, supplied)
2219 fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected: usize) {
2220 let label = if number < expected {
2222 format!("expected {} lifetime parameter", expected)
2224 format!("expected {} lifetime parameters", expected)
2227 let additional = number - expected;
2228 if additional == 1 {
2229 "unexpected lifetime parameter".to_string()
2231 format!("{} unexpected lifetime parameters", additional)
2234 struct_span_err!(tcx.sess, span, E0107,
2235 "wrong number of lifetime parameters: expected {}, found {}",
2237 .span_label(span, &label)
2241 // A helper struct for conveniently grouping a set of bounds which we pass to
2242 // and return from functions in multiple places.
2243 #[derive(PartialEq, Eq, Clone, Debug)]
2244 pub struct Bounds<'tcx> {
2245 pub region_bounds: Vec<ty::Region>,
2246 pub builtin_bounds: ty::BuiltinBounds,
2247 pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
2248 pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
2251 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
2252 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
2253 -> Vec<ty::Predicate<'tcx>>
2255 let mut vec = Vec::new();
2257 for builtin_bound in &self.builtin_bounds {
2258 match tcx.trait_ref_for_builtin_bound(builtin_bound, param_ty) {
2259 Ok(trait_ref) => { vec.push(trait_ref.to_predicate()); }
2260 Err(ErrorReported) => { }
2264 for ®ion_bound in &self.region_bounds {
2265 // account for the binder being introduced below; no need to shift `param_ty`
2266 // because, at present at least, it can only refer to early-bound regions
2267 let region_bound = ty::fold::shift_region(region_bound, 1);
2268 vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
2271 for bound_trait_ref in &self.trait_bounds {
2272 vec.push(bound_trait_ref.to_predicate());
2275 for projection in &self.projection_bounds {
2276 vec.push(projection.to_predicate());