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()`
20 //! function triggers a recursive call to `type_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()` just looks up the item type in
24 //! `tcx.types` (using `TyCtxt::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 rustc_data_structures::accumulate_vec::AccumulateVec;
55 use hir::def_id::DefId;
56 use middle::resolve_lifetime as rl;
58 use rustc::ty::subst::{Kind, 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, FxHashSet};
71 use std::cell::RefCell;
73 use syntax::{abi, ast};
74 use syntax::feature_gate::{GateIssue, emit_feature_err};
75 use syntax::symbol::{Symbol, keywords};
77 use errors::DiagnosticBuilder;
79 pub trait AstConv<'gcx, 'tcx> {
80 fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
82 /// A cache used for the result of `ast_ty_to_ty_cache`
83 fn ast_ty_to_ty_cache(&self) -> &RefCell<NodeMap<Ty<'tcx>>>;
85 /// Returns the generic type and lifetime parameters for an item.
86 fn get_generics(&self, span: Span, id: DefId)
87 -> Result<&'tcx ty::Generics<'tcx>, ErrorReported>;
89 /// Identify the type for an item, like a type alias, fn, or struct.
90 fn get_item_type(&self, span: Span, id: DefId) -> Result<Ty<'tcx>, ErrorReported>;
92 /// Returns the `TraitDef` for a given trait. This allows you to
93 /// figure out the set of type parameters defined on the trait.
94 fn get_trait_def(&self, span: Span, id: DefId)
95 -> Result<&'tcx ty::TraitDef, ErrorReported>;
97 /// Ensure that the super-predicates for the trait with the given
98 /// id are available and also for the transitive set of
100 fn ensure_super_predicates(&self, span: Span, id: DefId)
101 -> Result<(), ErrorReported>;
103 /// Returns the set of bounds in scope for the type parameter with
105 fn get_type_parameter_bounds(&self, span: Span, def_id: ast::NodeId)
106 -> Result<Vec<ty::PolyTraitRef<'tcx>>, ErrorReported>;
108 /// Return an (optional) substitution to convert bound type parameters that
109 /// are in scope into free ones. This function should only return Some
110 /// within a fn body.
111 /// See ParameterEnvironment::free_substs for more information.
112 fn get_free_substs(&self) -> Option<&Substs<'tcx>>;
114 /// What type should we use when a type is omitted?
115 fn ty_infer(&self, span: Span) -> Ty<'tcx>;
117 /// Same as ty_infer, but with a known type parameter definition.
118 fn ty_infer_for_def(&self,
119 _def: &ty::TypeParameterDef<'tcx>,
120 _substs: &[Kind<'tcx>],
121 span: Span) -> Ty<'tcx> {
125 /// Projecting an associated type from a (potentially)
126 /// higher-ranked trait reference is more complicated, because of
127 /// the possibility of late-bound regions appearing in the
128 /// associated type binding. This is not legal in function
129 /// signatures for that reason. In a function body, we can always
130 /// handle it because we can use inference variables to remove the
131 /// late-bound regions.
132 fn projected_ty_from_poly_trait_ref(&self,
134 poly_trait_ref: ty::PolyTraitRef<'tcx>,
135 item_name: ast::Name)
138 /// Project an associated type from a non-higher-ranked trait reference.
139 /// This is fairly straightforward and can be accommodated in any context.
140 fn projected_ty(&self,
142 _trait_ref: ty::TraitRef<'tcx>,
143 _item_name: ast::Name)
146 /// Invoked when we encounter an error from some prior pass
147 /// (e.g. resolve) that is translated into a ty-error. This is
148 /// used to help suppress derived errors typeck might otherwise
150 fn set_tainted_by_errors(&self);
153 struct ConvertedBinding<'tcx> {
154 item_name: ast::Name,
159 /// Dummy type used for the `Self` of a `TraitRef` created for converting
160 /// a trait object, and which gets removed in `ExistentialTraitRef`.
161 /// This type must not appear anywhere in other converted types.
162 const TRAIT_OBJECT_DUMMY_SELF: ty::TypeVariants<'static> = ty::TyInfer(ty::FreshTy(0));
164 pub fn ast_region_to_region<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
165 lifetime: &hir::Lifetime)
166 -> &'tcx ty::Region {
167 let r = match tcx.named_region_map.defs.get(&lifetime.id) {
169 // should have been recorded by the `resolve_lifetime` pass
170 span_bug!(lifetime.span, "unresolved lifetime");
173 Some(&rl::DefStaticRegion) => {
177 Some(&rl::DefLateBoundRegion(debruijn, id)) => {
178 // If this region is declared on a function, it will have
179 // an entry in `late_bound`, but if it comes from
180 // `for<'a>` in some type or something, it won't
181 // necessarily have one. In that case though, we won't be
182 // changed from late to early bound, so we can just
184 let issue_32330 = tcx.named_region_map
188 .unwrap_or(ty::Issue32330::WontChange);
189 ty::ReLateBound(debruijn, ty::BrNamed(tcx.map.local_def_id(id),
194 Some(&rl::DefEarlyBoundRegion(index, _)) => {
195 ty::ReEarlyBound(ty::EarlyBoundRegion {
201 Some(&rl::DefFreeRegion(scope, id)) => {
202 // As in DefLateBoundRegion above, could be missing for some late-bound
203 // regions, but also for early-bound regions.
204 let issue_32330 = tcx.named_region_map
208 .unwrap_or(ty::Issue32330::WontChange);
209 ty::ReFree(ty::FreeRegion {
210 scope: scope.to_code_extent(&tcx.region_maps),
211 bound_region: ty::BrNamed(tcx.map.local_def_id(id),
216 // (*) -- not late-bound, won't change
220 debug!("ast_region_to_region(lifetime={:?} id={}) yields {:?}",
228 fn report_elision_failure(
230 db: &mut DiagnosticBuilder,
231 params: Vec<ElisionFailureInfo>)
233 let mut m = String::new();
234 let len = params.len();
236 let elided_params: Vec<_> = params.into_iter()
237 .filter(|info| info.lifetime_count > 0)
240 let elided_len = elided_params.len();
242 for (i, info) in elided_params.into_iter().enumerate() {
243 let ElisionFailureInfo {
244 parent, index, lifetime_count: n, have_bound_regions
247 let help_name = if let Some(body) = parent {
248 let arg = &tcx.map.body(body).arguments[index];
249 format!("`{}`", tcx.map.node_to_pretty_string(arg.pat.id))
251 format!("argument {}", index + 1)
254 m.push_str(&(if n == 1 {
257 format!("one of {}'s {} elided {}lifetimes", help_name, n,
258 if have_bound_regions { "free " } else { "" } )
261 if elided_len == 2 && i == 0 {
263 } else if i + 2 == elided_len {
265 } else if i != elided_len - 1 {
273 "this function's return type contains a borrowed value, but \
274 there is no value for it to be borrowed from");
276 "consider giving it a 'static lifetime");
277 } else if elided_len == 0 {
279 "this function's return type contains a borrowed value with \
280 an elided lifetime, but the lifetime cannot be derived from \
283 "consider giving it an explicit bounded or 'static \
285 } else if elided_len == 1 {
287 "this function's return type contains a borrowed value, but \
288 the signature does not say which {} it is borrowed from",
292 "this function's return type contains a borrowed value, but \
293 the signature does not say whether it is borrowed from {}",
298 impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
299 pub fn opt_ast_region_to_region(&self,
300 rscope: &RegionScope,
302 opt_lifetime: &Option<hir::Lifetime>) -> &'tcx ty::Region
304 let r = match *opt_lifetime {
305 Some(ref lifetime) => {
306 ast_region_to_region(self.tcx(), lifetime)
309 None => self.tcx().mk_region(match rscope.anon_regions(default_span, 1) {
312 let ampersand_span = Span { hi: default_span.lo, ..default_span};
314 let mut err = struct_span_err!(self.tcx().sess, ampersand_span, E0106,
315 "missing lifetime specifier");
316 err.span_label(ampersand_span, &format!("expected lifetime parameter"));
318 if let Some(params) = params {
319 report_elision_failure(self.tcx(), &mut err, params);
327 debug!("opt_ast_region_to_region(opt_lifetime={:?}) yields {:?}",
334 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
335 /// returns an appropriate set of substitutions for this particular reference to `I`.
336 pub fn ast_path_substs_for_ty(&self,
337 rscope: &RegionScope,
340 item_segment: &hir::PathSegment)
341 -> &'tcx Substs<'tcx>
343 let tcx = self.tcx();
345 match item_segment.parameters {
346 hir::AngleBracketedParameters(_) => {}
347 hir::ParenthesizedParameters(..) => {
348 struct_span_err!(tcx.sess, span, E0214,
349 "parenthesized parameters may only be used with a trait")
350 .span_label(span, &format!("only traits may use parentheses"))
353 return Substs::for_item(tcx, def_id, |_, _| {
354 tcx.mk_region(ty::ReStatic)
361 let (substs, assoc_bindings) =
362 self.create_substs_for_ast_path(rscope,
365 &item_segment.parameters,
368 assoc_bindings.first().map(|b| self.tcx().prohibit_projection(b.span));
373 /// Given the type/region arguments provided to some path (along with
374 /// an implicit Self, if this is a trait reference) returns the complete
375 /// set of substitutions. This may involve applying defaulted type parameters.
377 /// Note that the type listing given here is *exactly* what the user provided.
378 fn create_substs_for_ast_path(&self,
379 rscope: &RegionScope,
382 parameters: &hir::PathParameters,
383 self_ty: Option<Ty<'tcx>>)
384 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
386 let tcx = self.tcx();
388 debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
390 def_id, self_ty, parameters);
392 let (lifetimes, num_types_provided, infer_types) = match *parameters {
393 hir::AngleBracketedParameters(ref data) => {
394 (&data.lifetimes[..], data.types.len(), data.infer_types)
396 hir::ParenthesizedParameters(_) => (&[][..], 1, false)
399 // If the type is parameterized by this region, then replace this
400 // region with the current anon region binding (in other words,
401 // whatever & would get replaced with).
402 let decl_generics = match self.get_generics(span, def_id) {
403 Ok(generics) => generics,
404 Err(ErrorReported) => {
405 // No convenient way to recover from a cycle here. Just bail. Sorry!
406 self.tcx().sess.abort_if_errors();
407 bug!("ErrorReported returned, but no errors reports?")
410 let expected_num_region_params = decl_generics.regions.len();
411 let supplied_num_region_params = lifetimes.len();
412 let regions = if expected_num_region_params == supplied_num_region_params {
413 lifetimes.iter().map(|l| *ast_region_to_region(tcx, l)).collect()
416 rscope.anon_regions(span, expected_num_region_params);
418 if supplied_num_region_params != 0 || anon_regions.is_err() {
419 report_lifetime_number_error(tcx, span,
420 supplied_num_region_params,
421 expected_num_region_params);
425 Ok(anon_regions) => anon_regions,
426 Err(_) => (0..expected_num_region_params).map(|_| ty::ReStatic).collect()
430 // If a self-type was declared, one should be provided.
431 assert_eq!(decl_generics.has_self, self_ty.is_some());
433 // Check the number of type parameters supplied by the user.
434 let ty_param_defs = &decl_generics.types[self_ty.is_some() as usize..];
435 if !infer_types || num_types_provided > ty_param_defs.len() {
436 check_type_argument_count(tcx, span, num_types_provided, ty_param_defs);
439 let is_object = self_ty.map_or(false, |ty| ty.sty == TRAIT_OBJECT_DUMMY_SELF);
440 let default_needs_object_self = |p: &ty::TypeParameterDef<'tcx>| {
441 if let Some(ref default) = p.default {
442 if is_object && default.has_self_ty() {
443 // There is no suitable inference default for a type parameter
444 // that references self, in an object type.
452 let mut output_assoc_binding = None;
453 let substs = Substs::for_item(tcx, def_id, |def, _| {
454 let i = def.index as usize - self_ty.is_some() as usize;
455 tcx.mk_region(regions[i])
457 let i = def.index as usize;
459 // Handle Self first, so we can adjust the index to match the AST.
460 if let (0, Some(ty)) = (i, self_ty) {
464 let i = i - self_ty.is_some() as usize - decl_generics.regions.len();
465 if i < num_types_provided {
466 // A provided type parameter.
468 hir::AngleBracketedParameters(ref data) => {
469 self.ast_ty_arg_to_ty(rscope, Some(def), substs, &data.types[i])
471 hir::ParenthesizedParameters(ref data) => {
474 self.convert_parenthesized_parameters(rscope, substs, data);
475 output_assoc_binding = Some(assoc);
479 } else if infer_types {
480 // No type parameters were provided, we can infer all.
481 let ty_var = if !default_needs_object_self(def) {
482 self.ty_infer_for_def(def, substs, span)
487 } else if let Some(default) = def.default {
488 // No type parameter provided, but a default exists.
490 // If we are converting an object type, then the
491 // `Self` parameter is unknown. However, some of the
492 // other type parameters may reference `Self` in their
493 // defaults. This will lead to an ICE if we are not
495 if default_needs_object_self(def) {
496 struct_span_err!(tcx.sess, span, E0393,
497 "the type parameter `{}` must be explicitly specified",
499 .span_label(span, &format!("missing reference to `{}`", def.name))
500 .note(&format!("because of the default `Self` reference, \
501 type parameters must be specified on object types"))
505 // This is a default type parameter.
506 default.subst_spanned(tcx, substs, Some(span))
509 // We've already errored above about the mismatch.
514 let assoc_bindings = match *parameters {
515 hir::AngleBracketedParameters(ref data) => {
516 data.bindings.iter().map(|b| {
519 ty: self.ast_ty_to_ty(rscope, &b.ty),
524 hir::ParenthesizedParameters(ref data) => {
525 vec![output_assoc_binding.unwrap_or_else(|| {
526 // This is an error condition, but we should
527 // get the associated type binding anyway.
528 self.convert_parenthesized_parameters(rscope, substs, data).1
533 debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}) -> {:?}",
534 decl_generics, self_ty, substs);
536 (substs, assoc_bindings)
539 /// Returns the appropriate lifetime to use for any output lifetimes
540 /// (if one exists) and a vector of the (pattern, number of lifetimes)
541 /// corresponding to each input type/pattern.
542 fn find_implied_output_region<I>(&self,
543 input_tys: &[Ty<'tcx>],
544 parent: Option<hir::BodyId>,
545 input_indices: I) -> ElidedLifetime
546 where I: Iterator<Item=usize>
548 let tcx = self.tcx();
549 let mut lifetimes_for_params = Vec::with_capacity(input_tys.len());
550 let mut possible_implied_output_region = None;
551 let mut lifetimes = 0;
553 for (input_type, index) in input_tys.iter().zip(input_indices) {
554 let mut regions = FxHashSet();
555 let have_bound_regions = tcx.collect_regions(input_type, &mut regions);
557 debug!("find_implied_output_regions: collected {:?} from {:?} \
558 have_bound_regions={:?}", ®ions, input_type, have_bound_regions);
560 lifetimes += regions.len();
562 if lifetimes == 1 && regions.len() == 1 {
563 // there's a chance that the unique lifetime of this
564 // iteration will be the appropriate lifetime for output
565 // parameters, so lets store it.
566 possible_implied_output_region = regions.iter().cloned().next();
569 lifetimes_for_params.push(ElisionFailureInfo {
572 lifetime_count: regions.len(),
573 have_bound_regions: have_bound_regions
578 Ok(*possible_implied_output_region.unwrap())
580 Err(Some(lifetimes_for_params))
584 fn convert_ty_with_lifetime_elision(&self,
585 elided_lifetime: ElidedLifetime,
587 anon_scope: Option<AnonTypeScope>)
590 match elided_lifetime {
591 Ok(implied_output_region) => {
592 let rb = ElidableRscope::new(implied_output_region);
593 self.ast_ty_to_ty(&MaybeWithAnonTypes::new(rb, anon_scope), ty)
595 Err(param_lifetimes) => {
596 // All regions must be explicitly specified in the output
597 // if the lifetime elision rules do not apply. This saves
598 // the user from potentially-confusing errors.
599 let rb = UnelidableRscope::new(param_lifetimes);
600 self.ast_ty_to_ty(&MaybeWithAnonTypes::new(rb, anon_scope), ty)
605 fn convert_parenthesized_parameters(&self,
606 rscope: &RegionScope,
607 region_substs: &[Kind<'tcx>],
608 data: &hir::ParenthesizedParameterData)
609 -> (Ty<'tcx>, ConvertedBinding<'tcx>)
611 let anon_scope = rscope.anon_type_scope();
612 let binding_rscope = MaybeWithAnonTypes::new(BindingRscope::new(), anon_scope);
613 let inputs = self.tcx().mk_type_list(data.inputs.iter().map(|a_t| {
614 self.ast_ty_arg_to_ty(&binding_rscope, None, region_substs, a_t)
616 let input_params = 0..inputs.len();
617 let implied_output_region = self.find_implied_output_region(&inputs, None, input_params);
619 let (output, output_span) = match data.output {
620 Some(ref output_ty) => {
621 (self.convert_ty_with_lifetime_elision(implied_output_region,
627 (self.tcx().mk_nil(), data.span)
631 let output_binding = ConvertedBinding {
632 item_name: Symbol::intern(FN_OUTPUT_NAME),
637 (self.tcx().mk_ty(ty::TyTuple(inputs)), output_binding)
640 pub fn instantiate_poly_trait_ref(&self,
641 rscope: &RegionScope,
642 ast_trait_ref: &hir::PolyTraitRef,
644 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
645 -> ty::PolyTraitRef<'tcx>
647 let trait_ref = &ast_trait_ref.trait_ref;
648 let trait_def_id = self.trait_def_id(trait_ref);
649 self.ast_path_to_poly_trait_ref(rscope,
654 trait_ref.path.segments.last().unwrap(),
658 /// Instantiates the path for the given trait reference, assuming that it's
659 /// bound to a valid trait type. Returns the def_id for the defining trait.
660 /// Fails if the type is a type other than a trait type.
662 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
663 /// are disallowed. Otherwise, they are pushed onto the vector given.
664 pub fn instantiate_mono_trait_ref(&self,
665 rscope: &RegionScope,
666 trait_ref: &hir::TraitRef,
668 -> ty::TraitRef<'tcx>
670 let trait_def_id = self.trait_def_id(trait_ref);
671 self.ast_path_to_mono_trait_ref(rscope,
675 trait_ref.path.segments.last().unwrap())
678 fn trait_def_id(&self, trait_ref: &hir::TraitRef) -> DefId {
679 let path = &trait_ref.path;
681 Def::Trait(trait_def_id) => trait_def_id,
683 self.tcx().sess.fatal("cannot continue compilation due to previous error");
686 span_fatal!(self.tcx().sess, path.span, E0245, "`{}` is not a trait",
687 self.tcx().map.node_to_pretty_string(trait_ref.ref_id));
692 fn ast_path_to_poly_trait_ref(&self,
693 rscope: &RegionScope,
697 path_id: ast::NodeId,
698 trait_segment: &hir::PathSegment,
699 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
700 -> ty::PolyTraitRef<'tcx>
702 debug!("ast_path_to_poly_trait_ref(trait_segment={:?})", trait_segment);
703 // The trait reference introduces a binding level here, so
704 // we need to shift the `rscope`. It'd be nice if we could
705 // do away with this rscope stuff and work this knowledge
706 // into resolve_lifetimes, as we do with non-omitted
707 // lifetimes. Oh well, not there yet.
708 let shifted_rscope = &ShiftedRscope::new(rscope);
710 let (substs, assoc_bindings) =
711 self.create_substs_for_ast_trait_ref(shifted_rscope,
716 let poly_trait_ref = ty::Binder(ty::TraitRef::new(trait_def_id, substs));
718 poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
719 // specify type to assert that error was already reported in Err case:
720 let predicate: Result<_, ErrorReported> =
721 self.ast_type_binding_to_poly_projection_predicate(path_id,
724 predicate.ok() // ok to ignore Err() because ErrorReported (see above)
727 debug!("ast_path_to_poly_trait_ref(trait_segment={:?}, projections={:?}) -> {:?}",
728 trait_segment, poly_projections, poly_trait_ref);
732 fn ast_path_to_mono_trait_ref(&self,
733 rscope: &RegionScope,
737 trait_segment: &hir::PathSegment)
738 -> ty::TraitRef<'tcx>
740 let (substs, assoc_bindings) =
741 self.create_substs_for_ast_trait_ref(rscope,
746 assoc_bindings.first().map(|b| self.tcx().prohibit_projection(b.span));
747 ty::TraitRef::new(trait_def_id, substs)
750 fn create_substs_for_ast_trait_ref(&self,
751 rscope: &RegionScope,
755 trait_segment: &hir::PathSegment)
756 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
758 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
761 let trait_def = match self.get_trait_def(span, trait_def_id) {
762 Ok(trait_def) => trait_def,
763 Err(ErrorReported) => {
764 // No convenient way to recover from a cycle here. Just bail. Sorry!
765 self.tcx().sess.abort_if_errors();
766 bug!("ErrorReported returned, but no errors reports?")
770 match trait_segment.parameters {
771 hir::AngleBracketedParameters(_) => {
772 // For now, require that parenthetical notation be used
773 // only with `Fn()` etc.
774 if !self.tcx().sess.features.borrow().unboxed_closures && trait_def.paren_sugar {
775 emit_feature_err(&self.tcx().sess.parse_sess,
776 "unboxed_closures", span, GateIssue::Language,
778 the precise format of `Fn`-family traits' \
779 type parameters is subject to change. \
780 Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead");
783 hir::ParenthesizedParameters(_) => {
784 // For now, require that parenthetical notation be used
785 // only with `Fn()` etc.
786 if !self.tcx().sess.features.borrow().unboxed_closures && !trait_def.paren_sugar {
787 emit_feature_err(&self.tcx().sess.parse_sess,
788 "unboxed_closures", span, GateIssue::Language,
790 parenthetical notation is only stable when used with `Fn`-family traits");
795 self.create_substs_for_ast_path(rscope,
798 &trait_segment.parameters,
802 fn trait_defines_associated_type_named(&self,
804 assoc_name: ast::Name)
807 self.tcx().associated_items(trait_def_id).any(|item| {
808 item.kind == ty::AssociatedKind::Type && item.name == assoc_name
812 fn ast_type_binding_to_poly_projection_predicate(
814 path_id: ast::NodeId,
815 trait_ref: ty::PolyTraitRef<'tcx>,
816 binding: &ConvertedBinding<'tcx>)
817 -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
819 let tcx = self.tcx();
821 // Given something like `U : SomeTrait<T=X>`, we want to produce a
822 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
823 // subtle in the event that `T` is defined in a supertrait of
824 // `SomeTrait`, because in that case we need to upcast.
826 // That is, consider this case:
829 // trait SubTrait : SuperTrait<int> { }
830 // trait SuperTrait<A> { type T; }
832 // ... B : SubTrait<T=foo> ...
835 // We want to produce `<B as SuperTrait<int>>::T == foo`.
837 // Find any late-bound regions declared in `ty` that are not
838 // declared in the trait-ref. These are not wellformed.
842 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
843 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
844 let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
845 let late_bound_in_ty = tcx.collect_referenced_late_bound_regions(&ty::Binder(binding.ty));
846 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
847 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
848 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
849 let br_name = match *br {
850 ty::BrNamed(_, name, _) => name,
854 "anonymous bound region {:?} in binding but not trait ref",
859 lint::builtin::HR_LIFETIME_IN_ASSOC_TYPE,
862 format!("binding for associated type `{}` references lifetime `{}`, \
863 which does not appear in the trait input types",
864 binding.item_name, br_name));
867 // Simple case: X is defined in the current trait.
868 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
869 return Ok(trait_ref.map_bound(|trait_ref| {
870 ty::ProjectionPredicate {
871 projection_ty: ty::ProjectionTy {
872 trait_ref: trait_ref,
873 item_name: binding.item_name,
880 // Otherwise, we have to walk through the supertraits to find
882 self.ensure_super_predicates(binding.span, trait_ref.def_id())?;
885 traits::supertraits(tcx, trait_ref.clone())
886 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), binding.item_name));
888 let candidate = self.one_bound_for_assoc_type(candidates,
889 &trait_ref.to_string(),
890 &binding.item_name.as_str(),
893 Ok(candidate.map_bound(|trait_ref| {
894 ty::ProjectionPredicate {
895 projection_ty: ty::ProjectionTy {
896 trait_ref: trait_ref,
897 item_name: binding.item_name,
904 fn ast_path_to_ty(&self,
905 rscope: &RegionScope,
908 item_segment: &hir::PathSegment)
911 let tcx = self.tcx();
912 let decl_ty = match self.get_item_type(span, did) {
914 Err(ErrorReported) => {
915 return tcx.types.err;
919 let substs = self.ast_path_substs_for_ty(rscope,
924 // FIXME(#12938): This is a hack until we have full support for DST.
925 if Some(did) == self.tcx().lang_items.owned_box() {
926 assert_eq!(substs.types().count(), 1);
927 return self.tcx().mk_box(substs.type_at(0));
930 decl_ty.subst(self.tcx(), substs)
933 /// Transform a PolyTraitRef into a PolyExistentialTraitRef by
934 /// removing the dummy Self type (TRAIT_OBJECT_DUMMY_SELF).
935 fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
936 -> ty::ExistentialTraitRef<'tcx> {
937 assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
938 ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
941 fn trait_path_to_object_type(&self,
942 rscope: &RegionScope,
945 trait_path_ref_id: ast::NodeId,
946 trait_segment: &hir::PathSegment,
948 partitioned_bounds: PartitionedBounds)
950 let tcx = self.tcx();
952 let mut projection_bounds = vec![];
953 let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
954 let principal = self.ast_path_to_poly_trait_ref(rscope,
960 &mut projection_bounds);
962 let PartitionedBounds { trait_bounds,
966 let (auto_traits, trait_bounds) = split_auto_traits(tcx, trait_bounds);
968 if !trait_bounds.is_empty() {
969 let b = &trait_bounds[0];
970 let span = b.trait_ref.path.span;
971 struct_span_err!(self.tcx().sess, span, E0225,
972 "only Send/Sync traits can be used as additional traits in a trait object")
973 .span_label(span, &format!("non-Send/Sync additional trait"))
977 // Erase the dummy_self (TRAIT_OBJECT_DUMMY_SELF) used above.
978 let existential_principal = principal.map_bound(|trait_ref| {
979 self.trait_ref_to_existential(trait_ref)
981 let existential_projections = projection_bounds.iter().map(|bound| {
982 bound.map_bound(|b| {
983 let p = b.projection_ty;
984 ty::ExistentialProjection {
985 trait_ref: self.trait_ref_to_existential(p.trait_ref),
986 item_name: p.item_name,
992 // ensure the super predicates and stop if we encountered an error
993 if self.ensure_super_predicates(span, principal.def_id()).is_err() {
994 return tcx.types.err;
997 // check that there are no gross object safety violations,
998 // most importantly, that the supertraits don't contain Self,
1000 let object_safety_violations =
1001 tcx.astconv_object_safety_violations(principal.def_id());
1002 if !object_safety_violations.is_empty() {
1003 tcx.report_object_safety_error(
1004 span, principal.def_id(), object_safety_violations)
1006 return tcx.types.err;
1009 let mut associated_types = FxHashSet::default();
1010 for tr in traits::supertraits(tcx, principal) {
1011 associated_types.extend(tcx.associated_items(tr.def_id())
1012 .filter(|item| item.kind == ty::AssociatedKind::Type)
1013 .map(|item| (tr.def_id(), item.name)));
1016 for projection_bound in &projection_bounds {
1017 let pair = (projection_bound.0.projection_ty.trait_ref.def_id,
1018 projection_bound.0.projection_ty.item_name);
1019 associated_types.remove(&pair);
1022 for (trait_def_id, name) in associated_types {
1023 struct_span_err!(tcx.sess, span, E0191,
1024 "the value of the associated type `{}` (from the trait `{}`) must be specified",
1026 tcx.item_path_str(trait_def_id))
1027 .span_label(span, &format!(
1028 "missing associated type `{}` value", name))
1033 iter::once(ty::ExistentialPredicate::Trait(*existential_principal.skip_binder()))
1034 .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
1035 .chain(existential_projections
1036 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
1037 .collect::<AccumulateVec<[_; 8]>>();
1038 v.sort_by(|a, b| a.cmp(tcx, b));
1039 let existential_predicates = ty::Binder(tcx.mk_existential_predicates(v.into_iter()));
1041 let region_bound = self.compute_object_lifetime_bound(span,
1043 existential_predicates);
1045 let region_bound = match region_bound {
1048 tcx.mk_region(match rscope.object_lifetime_default(span) {
1051 span_err!(self.tcx().sess, span, E0228,
1052 "the lifetime bound for this object type cannot be deduced \
1053 from context; please supply an explicit bound");
1060 debug!("region_bound: {:?}", region_bound);
1062 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1063 debug!("trait_object_type: {:?}", ty);
1067 fn report_ambiguous_associated_type(&self,
1072 struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
1073 .span_label(span, &format!("ambiguous associated type"))
1074 .note(&format!("specify the type using the syntax `<{} as {}>::{}`",
1075 type_str, trait_str, name))
1080 // Search for a bound on a type parameter which includes the associated item
1081 // given by assoc_name. ty_param_node_id is the node id for the type parameter
1082 // (which might be `Self`, but only if it is the `Self` of a trait, not an
1083 // impl). This function will fail if there are no suitable bounds or there is
1085 fn find_bound_for_assoc_item(&self,
1086 ty_param_node_id: ast::NodeId,
1087 ty_param_name: ast::Name,
1088 assoc_name: ast::Name,
1090 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1092 let tcx = self.tcx();
1094 let bounds = match self.get_type_parameter_bounds(span, ty_param_node_id) {
1096 Err(ErrorReported) => {
1097 return Err(ErrorReported);
1101 // Ensure the super predicates and stop if we encountered an error.
1102 if bounds.iter().any(|b| self.ensure_super_predicates(span, b.def_id()).is_err()) {
1103 return Err(ErrorReported);
1106 // Check that there is exactly one way to find an associated type with the
1108 let suitable_bounds =
1109 traits::transitive_bounds(tcx, &bounds)
1110 .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
1112 self.one_bound_for_assoc_type(suitable_bounds,
1113 &ty_param_name.as_str(),
1114 &assoc_name.as_str(),
1119 // Checks that bounds contains exactly one element and reports appropriate
1120 // errors otherwise.
1121 fn one_bound_for_assoc_type<I>(&self,
1123 ty_param_name: &str,
1126 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1127 where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
1129 let bound = match bounds.next() {
1130 Some(bound) => bound,
1132 struct_span_err!(self.tcx().sess, span, E0220,
1133 "associated type `{}` not found for `{}`",
1136 .span_label(span, &format!("associated type `{}` not found", assoc_name))
1138 return Err(ErrorReported);
1142 if let Some(bound2) = bounds.next() {
1143 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
1144 let mut err = struct_span_err!(
1145 self.tcx().sess, span, E0221,
1146 "ambiguous associated type `{}` in bounds of `{}`",
1149 err.span_label(span, &format!("ambiguous associated type `{}`", assoc_name));
1151 for bound in bounds {
1152 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
1153 item.kind == ty::AssociatedKind::Type && item.name == assoc_name
1155 .and_then(|item| self.tcx().map.span_if_local(item.def_id));
1157 if let Some(span) = bound_span {
1158 err.span_label(span, &format!("ambiguous `{}` from `{}`",
1162 span_note!(&mut err, span,
1163 "associated type `{}` could derive from `{}`",
1174 // Create a type from a path to an associated type.
1175 // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
1176 // and item_segment is the path segment for D. We return a type and a def for
1178 // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
1179 // parameter or Self.
1180 pub fn associated_path_def_to_ty(&self,
1181 ref_id: ast::NodeId,
1185 item_segment: &hir::PathSegment)
1188 let tcx = self.tcx();
1189 let assoc_name = item_segment.name;
1191 debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
1193 tcx.prohibit_type_params(slice::ref_slice(item_segment));
1195 // Find the type of the associated item, and the trait where the associated
1196 // item is declared.
1197 let bound = match (&ty.sty, ty_path_def) {
1198 (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
1199 // `Self` in an impl of a trait - we have a concrete self type and a
1201 let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
1202 let trait_ref = if let Some(free_substs) = self.get_free_substs() {
1203 trait_ref.subst(tcx, free_substs)
1208 if self.ensure_super_predicates(span, trait_ref.def_id).is_err() {
1209 return (tcx.types.err, Def::Err);
1213 traits::supertraits(tcx, ty::Binder(trait_ref))
1214 .filter(|r| self.trait_defines_associated_type_named(r.def_id(),
1217 match self.one_bound_for_assoc_type(candidates,
1219 &assoc_name.as_str(),
1222 Err(ErrorReported) => return (tcx.types.err, Def::Err),
1225 (&ty::TyParam(_), Def::SelfTy(Some(trait_did), None)) => {
1226 let trait_node_id = tcx.map.as_local_node_id(trait_did).unwrap();
1227 match self.find_bound_for_assoc_item(trait_node_id,
1228 keywords::SelfType.name(),
1232 Err(ErrorReported) => return (tcx.types.err, Def::Err),
1235 (&ty::TyParam(_), Def::TyParam(param_did)) => {
1236 let param_node_id = tcx.map.as_local_node_id(param_did).unwrap();
1237 let param_name = tcx.type_parameter_def(param_node_id).name;
1238 match self.find_bound_for_assoc_item(param_node_id,
1243 Err(ErrorReported) => return (tcx.types.err, Def::Err),
1247 // Don't print TyErr to the user.
1248 if !ty.references_error() {
1249 self.report_ambiguous_associated_type(span,
1252 &assoc_name.as_str());
1254 return (tcx.types.err, Def::Err);
1258 let trait_did = bound.0.def_id;
1259 let ty = self.projected_ty_from_poly_trait_ref(span, bound, assoc_name);
1261 let item = tcx.associated_items(trait_did).find(|i| i.name == assoc_name);
1262 let def_id = item.expect("missing associated type").def_id;
1263 tcx.check_stability(def_id, ref_id, span);
1264 (ty, Def::AssociatedTy(def_id))
1267 fn qpath_to_ty(&self,
1268 rscope: &RegionScope,
1270 opt_self_ty: Option<Ty<'tcx>>,
1271 trait_def_id: DefId,
1272 trait_segment: &hir::PathSegment,
1273 item_segment: &hir::PathSegment)
1276 let tcx = self.tcx();
1278 tcx.prohibit_type_params(slice::ref_slice(item_segment));
1280 let self_ty = if let Some(ty) = opt_self_ty {
1283 let path_str = tcx.item_path_str(trait_def_id);
1284 self.report_ambiguous_associated_type(span,
1287 &item_segment.name.as_str());
1288 return tcx.types.err;
1291 debug!("qpath_to_ty: self_type={:?}", self_ty);
1293 let trait_ref = self.ast_path_to_mono_trait_ref(rscope,
1299 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1301 self.projected_ty(span, trait_ref, item_segment.name)
1304 /// Convert a type supplied as value for a type argument from AST into our
1305 /// our internal representation. This is the same as `ast_ty_to_ty` but that
1306 /// it applies the object lifetime default.
1310 /// * `this`, `rscope`: the surrounding context
1311 /// * `def`: the type parameter being instantiated (if available)
1312 /// * `region_substs`: a partial substitution consisting of
1313 /// only the region type parameters being supplied to this type.
1314 /// * `ast_ty`: the ast representation of the type being supplied
1315 fn ast_ty_arg_to_ty(&self,
1316 rscope: &RegionScope,
1317 def: Option<&ty::TypeParameterDef<'tcx>>,
1318 region_substs: &[Kind<'tcx>],
1322 let tcx = self.tcx();
1324 if let Some(def) = def {
1325 let object_lifetime_default = def.object_lifetime_default.subst(tcx, region_substs);
1326 let rscope1 = &ObjectLifetimeDefaultRscope::new(rscope, object_lifetime_default);
1327 self.ast_ty_to_ty(rscope1, ast_ty)
1329 self.ast_ty_to_ty(rscope, ast_ty)
1333 // Check a type Path and convert it to a Ty.
1334 pub fn def_to_ty(&self,
1335 rscope: &RegionScope,
1336 opt_self_ty: Option<Ty<'tcx>>,
1338 path_id: ast::NodeId,
1339 permit_variants: bool)
1341 let tcx = self.tcx();
1343 debug!("base_def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
1344 path.def, opt_self_ty, path.segments);
1346 let span = path.span;
1348 Def::Trait(trait_def_id) => {
1349 // N.B. this case overlaps somewhat with
1350 // TyTraitObject, see that fn for details
1352 assert_eq!(opt_self_ty, None);
1353 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1355 self.trait_path_to_object_type(rscope,
1359 path.segments.last().unwrap(),
1361 partition_bounds(&[]))
1363 Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) | Def::Union(did) => {
1364 assert_eq!(opt_self_ty, None);
1365 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1366 self.ast_path_to_ty(rscope, span, did, path.segments.last().unwrap())
1368 Def::Variant(did) if permit_variants => {
1369 // Convert "variant type" as if it were a real type.
1370 // The resulting `Ty` is type of the variant's enum for now.
1371 assert_eq!(opt_self_ty, None);
1372 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1373 self.ast_path_to_ty(rscope,
1375 tcx.parent_def_id(did).unwrap(),
1376 path.segments.last().unwrap())
1378 Def::TyParam(did) => {
1379 assert_eq!(opt_self_ty, None);
1380 tcx.prohibit_type_params(&path.segments);
1382 let node_id = tcx.map.as_local_node_id(did).unwrap();
1383 let param = tcx.ty_param_defs.borrow().get(&node_id)
1384 .map(ty::ParamTy::for_def);
1385 if let Some(p) = param {
1388 // Only while computing defaults of earlier type
1389 // parameters can a type parameter be missing its def.
1390 struct_span_err!(tcx.sess, span, E0128,
1391 "type parameters with a default cannot use \
1392 forward declared identifiers")
1393 .span_label(span, &format!("defaulted type parameters \
1394 cannot be forward declared"))
1399 Def::SelfTy(_, Some(def_id)) => {
1400 // Self in impl (we know the concrete type).
1402 assert_eq!(opt_self_ty, None);
1403 tcx.prohibit_type_params(&path.segments);
1404 let ty = tcx.item_type(def_id);
1405 if let Some(free_substs) = self.get_free_substs() {
1406 ty.subst(tcx, free_substs)
1411 Def::SelfTy(Some(_), None) => {
1413 assert_eq!(opt_self_ty, None);
1414 tcx.prohibit_type_params(&path.segments);
1417 Def::AssociatedTy(def_id) => {
1418 tcx.prohibit_type_params(&path.segments[..path.segments.len()-2]);
1419 let trait_did = tcx.parent_def_id(def_id).unwrap();
1420 self.qpath_to_ty(rscope,
1424 &path.segments[path.segments.len()-2],
1425 path.segments.last().unwrap())
1427 Def::PrimTy(prim_ty) => {
1428 assert_eq!(opt_self_ty, None);
1429 tcx.prim_ty_to_ty(&path.segments, prim_ty)
1432 self.set_tainted_by_errors();
1433 return self.tcx().types.err;
1435 _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1439 /// Parses the programmer's textual representation of a type into our
1440 /// internal notion of a type.
1441 pub fn ast_ty_to_ty(&self, rscope: &RegionScope, ast_ty: &hir::Ty) -> Ty<'tcx> {
1442 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1445 let tcx = self.tcx();
1447 let cache = self.ast_ty_to_ty_cache();
1448 if let Some(ty) = cache.borrow().get(&ast_ty.id) {
1452 let result_ty = match ast_ty.node {
1453 hir::TySlice(ref ty) => {
1454 tcx.mk_slice(self.ast_ty_to_ty(rscope, &ty))
1456 hir::TyPtr(ref mt) => {
1457 tcx.mk_ptr(ty::TypeAndMut {
1458 ty: self.ast_ty_to_ty(rscope, &mt.ty),
1462 hir::TyRptr(ref region, ref mt) => {
1463 let r = self.opt_ast_region_to_region(rscope, ast_ty.span, region);
1464 debug!("TyRef r={:?}", r);
1466 &ObjectLifetimeDefaultRscope::new(
1468 ty::ObjectLifetimeDefault::Specific(r));
1469 let t = self.ast_ty_to_ty(rscope1, &mt.ty);
1470 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1475 hir::TyTup(ref fields) => {
1476 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(rscope, &t)))
1478 hir::TyBareFn(ref bf) => {
1479 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1480 let anon_scope = rscope.anon_type_scope();
1481 let bare_fn_ty = self.ty_of_method_or_bare_fn(bf.unsafety,
1489 // Find any late-bound regions declared in return type that do
1490 // not appear in the arguments. These are not wellformed.
1494 // for<'a> fn() -> &'a str <-- 'a is bad
1495 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1497 // Note that we do this check **here** and not in
1498 // `ty_of_bare_fn` because the latter is also used to make
1499 // the types for fn items, and we do not want to issue a
1500 // warning then. (Once we fix #32330, the regions we are
1501 // checking for here would be considered early bound
1503 let inputs = bare_fn_ty.sig.inputs();
1504 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1505 &inputs.map_bound(|i| i.to_owned()));
1506 let output = bare_fn_ty.sig.output();
1507 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1508 for br in late_bound_in_ret.difference(&late_bound_in_args) {
1509 let br_name = match *br {
1510 ty::BrNamed(_, name, _) => name,
1513 bf.decl.output.span(),
1514 "anonymous bound region {:?} in return but not args",
1519 lint::builtin::HR_LIFETIME_IN_ASSOC_TYPE,
1522 format!("return type references lifetime `{}`, \
1523 which does not appear in the trait input types",
1526 tcx.mk_fn_ptr(bare_fn_ty)
1528 hir::TyTraitObject(ref bounds) => {
1529 self.conv_object_ty_poly_trait_ref(rscope, ast_ty.span, bounds)
1531 hir::TyImplTrait(ref bounds) => {
1532 use collect::{compute_bounds, SizedByDefault};
1534 // Create the anonymized type.
1535 let def_id = tcx.map.local_def_id(ast_ty.id);
1536 if let Some(anon_scope) = rscope.anon_type_scope() {
1537 let substs = anon_scope.fresh_substs(self, ast_ty.span);
1538 let ty = tcx.mk_anon(tcx.map.local_def_id(ast_ty.id), substs);
1540 // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`.
1541 let bounds = compute_bounds(self, ty, bounds,
1542 SizedByDefault::Yes,
1545 let predicates = bounds.predicates(tcx, ty);
1546 let predicates = tcx.lift_to_global(&predicates).unwrap();
1547 tcx.predicates.borrow_mut().insert(def_id, ty::GenericPredicates {
1549 predicates: predicates
1554 span_err!(tcx.sess, ast_ty.span, E0562,
1555 "`impl Trait` not allowed outside of function \
1556 and inherent method return types");
1560 hir::TyPath(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1561 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1562 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1563 self.ast_ty_to_ty(rscope, qself)
1565 self.def_to_ty(rscope, opt_self_ty, path, ast_ty.id, false)
1567 hir::TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1568 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1569 let ty = self.ast_ty_to_ty(rscope, qself);
1571 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
1576 self.associated_path_def_to_ty(ast_ty.id, ast_ty.span, ty, def, segment).0
1578 hir::TyArray(ref ty, length) => {
1579 if let Ok(length) = eval_length(tcx.global_tcx(), length, "array length") {
1580 tcx.mk_array(self.ast_ty_to_ty(rscope, &ty), length)
1582 self.tcx().types.err
1585 hir::TyTypeof(ref _e) => {
1586 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1587 "`typeof` is a reserved keyword but unimplemented")
1588 .span_label(ast_ty.span, &format!("reserved keyword"))
1594 // TyInfer also appears as the type of arguments or return
1595 // values in a ExprClosure, or as
1596 // the type of local variables. Both of these cases are
1597 // handled specially and will not descend into this routine.
1598 self.ty_infer(ast_ty.span)
1602 cache.borrow_mut().insert(ast_ty.id, result_ty);
1607 pub fn ty_of_arg(&self,
1608 rscope: &RegionScope,
1610 expected_ty: Option<Ty<'tcx>>)
1614 hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1615 hir::TyInfer => self.ty_infer(ty.span),
1616 _ => self.ast_ty_to_ty(rscope, ty),
1620 pub fn ty_of_method(&self,
1621 sig: &hir::MethodSig,
1622 opt_self_value_ty: Option<Ty<'tcx>>,
1623 body: Option<hir::BodyId>,
1624 anon_scope: Option<AnonTypeScope>)
1625 -> &'tcx ty::BareFnTy<'tcx> {
1626 self.ty_of_method_or_bare_fn(sig.unsafety,
1635 pub fn ty_of_bare_fn(&self,
1636 unsafety: hir::Unsafety,
1640 anon_scope: Option<AnonTypeScope>)
1641 -> &'tcx ty::BareFnTy<'tcx> {
1642 self.ty_of_method_or_bare_fn(unsafety, abi, None, decl, Some(body), None, anon_scope)
1645 fn ty_of_method_or_bare_fn(&self,
1646 unsafety: hir::Unsafety,
1648 opt_self_value_ty: Option<Ty<'tcx>>,
1650 body: Option<hir::BodyId>,
1651 arg_anon_scope: Option<AnonTypeScope>,
1652 ret_anon_scope: Option<AnonTypeScope>)
1653 -> &'tcx ty::BareFnTy<'tcx>
1655 debug!("ty_of_method_or_bare_fn");
1657 // New region names that appear inside of the arguments of the function
1658 // declaration are bound to that function type.
1659 let rb = MaybeWithAnonTypes::new(BindingRscope::new(), arg_anon_scope);
1661 let input_tys: Vec<Ty> =
1662 decl.inputs.iter().map(|a| self.ty_of_arg(&rb, a, None)).collect();
1664 let has_self = opt_self_value_ty.is_some();
1665 let explicit_self = opt_self_value_ty.map(|self_value_ty| {
1666 ExplicitSelf::determine(self_value_ty, input_tys[0])
1669 let implied_output_region = match explicit_self {
1670 // `implied_output_region` is the region that will be assumed for any
1671 // region parameters in the return type. In accordance with the rules for
1672 // lifetime elision, we can determine it in two ways. First (determined
1673 // here), if self is by-reference, then the implied output region is the
1674 // region of the self parameter.
1675 Some(ExplicitSelf::ByReference(region, _)) => Ok(*region),
1677 // Second, if there was exactly one lifetime (either a substitution or a
1678 // reference) in the arguments, then any anonymous regions in the output
1679 // have that lifetime.
1681 let arg_tys = &input_tys[has_self as usize..];
1682 let arg_params = has_self as usize..input_tys.len();
1683 self.find_implied_output_region(arg_tys, body, arg_params)
1688 let output_ty = match decl.output {
1689 hir::Return(ref output) =>
1690 self.convert_ty_with_lifetime_elision(implied_output_region,
1693 hir::DefaultReturn(..) => self.tcx().mk_nil(),
1696 debug!("ty_of_method_or_bare_fn: output_ty={:?}", output_ty);
1698 self.tcx().mk_bare_fn(ty::BareFnTy {
1701 sig: ty::Binder(self.tcx().mk_fn_sig(
1702 input_tys.into_iter(),
1709 pub fn ty_of_closure(&self,
1710 unsafety: hir::Unsafety,
1713 expected_sig: Option<ty::FnSig<'tcx>>)
1714 -> ty::ClosureTy<'tcx>
1716 debug!("ty_of_closure(expected_sig={:?})",
1719 // new region names that appear inside of the fn decl are bound to
1720 // that function type
1721 let rb = rscope::BindingRscope::new();
1723 let input_tys = decl.inputs.iter().enumerate().map(|(i, a)| {
1724 let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1725 // no guarantee that the correct number of expected args
1727 if i < e.inputs().len() {
1733 self.ty_of_arg(&rb, a, expected_arg_ty)
1736 let expected_ret_ty = expected_sig.as_ref().map(|e| e.output());
1738 let is_infer = match decl.output {
1739 hir::Return(ref output) if output.node == hir::TyInfer => true,
1740 hir::DefaultReturn(..) => true,
1744 let output_ty = match decl.output {
1745 _ if is_infer && expected_ret_ty.is_some() =>
1746 expected_ret_ty.unwrap(),
1747 _ if is_infer => self.ty_infer(decl.output.span()),
1748 hir::Return(ref output) =>
1749 self.ast_ty_to_ty(&rb, &output),
1750 hir::DefaultReturn(..) => bug!(),
1753 debug!("ty_of_closure: output_ty={:?}", output_ty);
1758 sig: ty::Binder(self.tcx().mk_fn_sig(input_tys, output_ty, decl.variadic)),
1762 fn conv_object_ty_poly_trait_ref(&self,
1763 rscope: &RegionScope,
1765 ast_bounds: &[hir::TyParamBound])
1768 let mut partitioned_bounds = partition_bounds(ast_bounds);
1770 let trait_bound = if !partitioned_bounds.trait_bounds.is_empty() {
1771 partitioned_bounds.trait_bounds.remove(0)
1773 span_err!(self.tcx().sess, span, E0224,
1774 "at least one non-builtin trait is required for an object type");
1775 return self.tcx().types.err;
1778 let trait_ref = &trait_bound.trait_ref;
1779 let trait_def_id = self.trait_def_id(trait_ref);
1780 self.trait_path_to_object_type(rscope,
1781 trait_ref.path.span,
1784 trait_ref.path.segments.last().unwrap(),
1789 /// Given the bounds on an object, determines what single region bound (if any) we can
1790 /// use to summarize this type. The basic idea is that we will use the bound the user
1791 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1792 /// for region bounds. It may be that we can derive no bound at all, in which case
1793 /// we return `None`.
1794 fn compute_object_lifetime_bound(&self,
1796 explicit_region_bounds: &[&hir::Lifetime],
1797 existential_predicates: ty::Binder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>)
1798 -> Option<&'tcx ty::Region> // if None, use the default
1800 let tcx = self.tcx();
1802 debug!("compute_opt_region_bound(explicit_region_bounds={:?}, \
1803 existential_predicates={:?})",
1804 explicit_region_bounds,
1805 existential_predicates);
1807 if explicit_region_bounds.len() > 1 {
1808 span_err!(tcx.sess, explicit_region_bounds[1].span, E0226,
1809 "only a single explicit lifetime bound is permitted");
1812 if let Some(&r) = explicit_region_bounds.get(0) {
1813 // Explicitly specified region bound. Use that.
1814 return Some(ast_region_to_region(tcx, r));
1817 if let Some(principal) = existential_predicates.principal() {
1818 if let Err(ErrorReported) = self.ensure_super_predicates(span, principal.def_id()) {
1819 return Some(tcx.mk_region(ty::ReStatic));
1823 // No explicit region bound specified. Therefore, examine trait
1824 // bounds and see if we can derive region bounds from those.
1825 let derived_region_bounds =
1826 object_region_bounds(tcx, existential_predicates);
1828 // If there are no derived region bounds, then report back that we
1829 // can find no region bound. The caller will use the default.
1830 if derived_region_bounds.is_empty() {
1834 // If any of the derived region bounds are 'static, that is always
1836 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1837 return Some(tcx.mk_region(ty::ReStatic));
1840 // Determine whether there is exactly one unique region in the set
1841 // of derived region bounds. If so, use that. Otherwise, report an
1843 let r = derived_region_bounds[0];
1844 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1845 span_err!(tcx.sess, span, E0227,
1846 "ambiguous lifetime bound, explicit lifetime bound required");
1852 pub struct PartitionedBounds<'a> {
1853 pub trait_bounds: Vec<&'a hir::PolyTraitRef>,
1854 pub region_bounds: Vec<&'a hir::Lifetime>,
1857 /// Divides a list of general trait bounds into two groups: builtin bounds (Sync/Send) and the
1858 /// remaining general trait bounds.
1859 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1860 trait_bounds: Vec<&'b hir::PolyTraitRef>)
1861 -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
1863 let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.into_iter().partition(|bound| {
1864 match bound.trait_ref.path.def {
1865 Def::Trait(trait_did) => {
1866 // Checks whether `trait_did` refers to one of the builtin
1867 // traits, like `Send`, and adds it to `auto_traits` if so.
1868 if Some(trait_did) == tcx.lang_items.send_trait() ||
1869 Some(trait_did) == tcx.lang_items.sync_trait() {
1870 let segments = &bound.trait_ref.path.segments;
1871 let parameters = &segments[segments.len() - 1].parameters;
1872 if !parameters.types().is_empty() {
1873 check_type_argument_count(tcx, bound.trait_ref.path.span,
1874 parameters.types().len(), &[]);
1876 if !parameters.lifetimes().is_empty() {
1877 report_lifetime_number_error(tcx, bound.trait_ref.path.span,
1878 parameters.lifetimes().len(), 0);
1889 let auto_traits = auto_traits.into_iter().map(|tr| {
1890 if let Def::Trait(trait_did) = tr.trait_ref.path.def {
1895 }).collect::<Vec<_>>();
1897 (auto_traits, trait_bounds)
1900 /// Divides a list of bounds from the AST into two groups: general trait bounds and region bounds
1901 pub fn partition_bounds<'a, 'b, 'gcx, 'tcx>(ast_bounds: &'b [hir::TyParamBound])
1902 -> PartitionedBounds<'b>
1904 let mut region_bounds = Vec::new();
1905 let mut trait_bounds = Vec::new();
1906 for ast_bound in ast_bounds {
1908 hir::TraitTyParamBound(ref b, hir::TraitBoundModifier::None) => {
1909 trait_bounds.push(b);
1911 hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {}
1912 hir::RegionTyParamBound(ref l) => {
1913 region_bounds.push(l);
1919 trait_bounds: trait_bounds,
1920 region_bounds: region_bounds,
1924 fn check_type_argument_count(tcx: TyCtxt, span: Span, supplied: usize,
1925 ty_param_defs: &[ty::TypeParameterDef]) {
1926 let accepted = ty_param_defs.len();
1927 let required = ty_param_defs.iter().take_while(|x| x.default.is_none()) .count();
1928 if supplied < required {
1929 let expected = if required < accepted {
1934 let arguments_plural = if required == 1 { "" } else { "s" };
1936 struct_span_err!(tcx.sess, span, E0243,
1937 "wrong number of type arguments: {} {}, found {}",
1938 expected, required, supplied)
1940 &format!("{} {} type argument{}",
1945 } else if supplied > accepted {
1946 let expected = if required < accepted {
1947 format!("expected at most {}", accepted)
1949 format!("expected {}", accepted)
1951 let arguments_plural = if accepted == 1 { "" } else { "s" };
1953 struct_span_err!(tcx.sess, span, E0244,
1954 "wrong number of type arguments: {}, found {}",
1958 &format!("{} type argument{}",
1959 if accepted == 0 { "expected no" } else { &expected },
1966 fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected: usize) {
1967 let label = if number < expected {
1969 format!("expected {} lifetime parameter", expected)
1971 format!("expected {} lifetime parameters", expected)
1974 let additional = number - expected;
1975 if additional == 1 {
1976 "unexpected lifetime parameter".to_string()
1978 format!("{} unexpected lifetime parameters", additional)
1981 struct_span_err!(tcx.sess, span, E0107,
1982 "wrong number of lifetime parameters: expected {}, found {}",
1984 .span_label(span, &label)
1988 // A helper struct for conveniently grouping a set of bounds which we pass to
1989 // and return from functions in multiple places.
1990 #[derive(PartialEq, Eq, Clone, Debug)]
1991 pub struct Bounds<'tcx> {
1992 pub region_bounds: Vec<&'tcx ty::Region>,
1993 pub implicitly_sized: bool,
1994 pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
1995 pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
1998 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
1999 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
2000 -> Vec<ty::Predicate<'tcx>>
2002 let mut vec = Vec::new();
2004 // If it could be sized, and is, add the sized predicate
2005 if self.implicitly_sized {
2006 if let Some(sized) = tcx.lang_items.sized_trait() {
2007 let trait_ref = ty::TraitRef {
2009 substs: tcx.mk_substs_trait(param_ty, &[])
2011 vec.push(trait_ref.to_predicate());
2015 for ®ion_bound in &self.region_bounds {
2016 // account for the binder being introduced below; no need to shift `param_ty`
2017 // because, at present at least, it can only refer to early-bound regions
2018 let region_bound = tcx.mk_region(ty::fold::shift_region(*region_bound, 1));
2019 vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
2022 for bound_trait_ref in &self.trait_bounds {
2023 vec.push(bound_trait_ref.to_predicate());
2026 for projection in &self.projection_bounds {
2027 vec.push(projection.to_predicate());
2034 pub enum ExplicitSelf<'tcx> {
2036 ByReference(&'tcx ty::Region, hir::Mutability),
2040 impl<'tcx> ExplicitSelf<'tcx> {
2041 /// We wish to (for now) categorize an explicit self
2042 /// declaration like `self: SomeType` into either `self`,
2043 /// `&self`, `&mut self`, or `Box<self>`. We do this here
2044 /// by some simple pattern matching. A more precise check
2045 /// is done later in `check_method_self_type()`.
2050 /// impl Foo for &T {
2051 /// // Legal declarations:
2052 /// fn method1(self: &&T); // ExplicitSelf::ByReference
2053 /// fn method2(self: &T); // ExplicitSelf::ByValue
2054 /// fn method3(self: Box<&T>); // ExplicitSelf::ByBox
2056 /// // Invalid cases will be caught later by `check_method_self_type`:
2057 /// fn method_err1(self: &mut T); // ExplicitSelf::ByReference
2061 /// To do the check we just count the number of "modifiers"
2062 /// on each type and compare them. If they are the same or
2063 /// the impl has more, we call it "by value". Otherwise, we
2064 /// look at the outermost modifier on the method decl and
2065 /// call it by-ref, by-box as appropriate. For method1, for
2066 /// example, the impl type has one modifier, but the method
2067 /// type has two, so we end up with
2068 /// ExplicitSelf::ByReference.
2069 pub fn determine(untransformed_self_ty: Ty<'tcx>,
2070 self_arg_ty: Ty<'tcx>)
2071 -> ExplicitSelf<'tcx> {
2072 fn count_modifiers(ty: Ty) -> usize {
2074 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
2075 ty::TyBox(t) => count_modifiers(t) + 1,
2080 let impl_modifiers = count_modifiers(untransformed_self_ty);
2081 let method_modifiers = count_modifiers(self_arg_ty);
2083 if impl_modifiers >= method_modifiers {
2084 ExplicitSelf::ByValue
2086 match self_arg_ty.sty {
2087 ty::TyRef(r, mt) => ExplicitSelf::ByReference(r, mt.mutbl),
2088 ty::TyBox(_) => ExplicitSelf::ByBox,
2089 _ => ExplicitSelf::ByValue,