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};
76 use syntax_pos::{Span, Pos};
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 fn ast_ty_to_object_trait_ref(&self,
934 rscope: &RegionScope,
937 bounds: &[hir::TyParamBound])
941 * In a type like `Foo + Send`, we want to wait to collect the
942 * full set of bounds before we make the object type, because we
943 * need them to infer a region bound. (For example, if we tried
944 * made a type from just `Foo`, then it wouldn't be enough to
945 * infer a 'static bound, and hence the user would get an error.)
946 * So this function is used when we're dealing with a sum type to
947 * convert the LHS. It only accepts a type that refers to a trait
948 * name, and reports an error otherwise.
951 let tcx = self.tcx();
953 hir::TyPath(hir::QPath::Resolved(None, ref path)) => {
954 if let Def::Trait(trait_def_id) = path.def {
955 self.trait_path_to_object_type(rscope,
959 path.segments.last().unwrap(),
961 partition_bounds(bounds))
963 struct_span_err!(tcx.sess, ty.span, E0172,
964 "expected a reference to a trait")
965 .span_label(ty.span, &format!("expected a trait"))
971 let mut err = struct_span_err!(tcx.sess, ty.span, E0178,
972 "expected a path on the left-hand side \
974 tcx.map.node_to_pretty_string(ty.id));
975 err.span_label(ty.span, &format!("expected a path"));
976 let hi = bounds.iter().map(|x| match *x {
977 hir::TraitTyParamBound(ref tr, _) => tr.span.hi,
978 hir::RegionTyParamBound(ref r) => r.span.hi,
979 }).max_by_key(|x| x.to_usize());
980 let full_span = hi.map(|hi| Span {
983 expn_id: ty.span.expn_id,
985 match (&ty.node, full_span) {
986 (&hir::TyRptr(ref lifetime, ref mut_ty), Some(full_span)) => {
987 let ty_str = hir::print::to_string(&tcx.map, |s| {
988 use syntax::print::pp::word;
989 use syntax::print::pprust::PrintState;
991 word(&mut s.s, "&")?;
992 s.print_opt_lifetime(lifetime)?;
993 s.print_mutability(mut_ty.mutbl)?;
995 s.print_type(&mut_ty.ty)?;
996 s.print_bounds(" +", bounds)?;
999 err.span_suggestion(full_span, "try adding parentheses (per RFC 438):",
1005 "perhaps you forgot parentheses? (per RFC 438)");
1014 /// Transform a PolyTraitRef into a PolyExistentialTraitRef by
1015 /// removing the dummy Self type (TRAIT_OBJECT_DUMMY_SELF).
1016 fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
1017 -> ty::ExistentialTraitRef<'tcx> {
1018 assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
1019 ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
1022 fn trait_path_to_object_type(&self,
1023 rscope: &RegionScope,
1025 trait_def_id: DefId,
1026 trait_path_ref_id: ast::NodeId,
1027 trait_segment: &hir::PathSegment,
1029 partitioned_bounds: PartitionedBounds)
1031 let tcx = self.tcx();
1033 let mut projection_bounds = vec![];
1034 let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
1035 let principal = self.ast_path_to_poly_trait_ref(rscope,
1041 &mut projection_bounds);
1043 let PartitionedBounds { trait_bounds,
1047 let (auto_traits, trait_bounds) = split_auto_traits(tcx, trait_bounds);
1049 if !trait_bounds.is_empty() {
1050 let b = &trait_bounds[0];
1051 let span = b.trait_ref.path.span;
1052 struct_span_err!(self.tcx().sess, span, E0225,
1053 "only Send/Sync traits can be used as additional traits in a trait object")
1054 .span_label(span, &format!("non-Send/Sync additional trait"))
1058 // Erase the dummy_self (TRAIT_OBJECT_DUMMY_SELF) used above.
1059 let existential_principal = principal.map_bound(|trait_ref| {
1060 self.trait_ref_to_existential(trait_ref)
1062 let existential_projections = projection_bounds.iter().map(|bound| {
1063 bound.map_bound(|b| {
1064 let p = b.projection_ty;
1065 ty::ExistentialProjection {
1066 trait_ref: self.trait_ref_to_existential(p.trait_ref),
1067 item_name: p.item_name,
1073 // ensure the super predicates and stop if we encountered an error
1074 if self.ensure_super_predicates(span, principal.def_id()).is_err() {
1075 return tcx.types.err;
1078 // check that there are no gross object safety violations,
1079 // most importantly, that the supertraits don't contain Self,
1081 let object_safety_violations =
1082 tcx.astconv_object_safety_violations(principal.def_id());
1083 if !object_safety_violations.is_empty() {
1084 tcx.report_object_safety_error(
1085 span, principal.def_id(), object_safety_violations)
1087 return tcx.types.err;
1090 let mut associated_types = FxHashSet::default();
1091 for tr in traits::supertraits(tcx, principal) {
1092 associated_types.extend(tcx.associated_items(tr.def_id())
1093 .filter(|item| item.kind == ty::AssociatedKind::Type)
1094 .map(|item| (tr.def_id(), item.name)));
1097 for projection_bound in &projection_bounds {
1098 let pair = (projection_bound.0.projection_ty.trait_ref.def_id,
1099 projection_bound.0.projection_ty.item_name);
1100 associated_types.remove(&pair);
1103 for (trait_def_id, name) in associated_types {
1104 struct_span_err!(tcx.sess, span, E0191,
1105 "the value of the associated type `{}` (from the trait `{}`) must be specified",
1107 tcx.item_path_str(trait_def_id))
1108 .span_label(span, &format!(
1109 "missing associated type `{}` value", name))
1114 iter::once(ty::ExistentialPredicate::Trait(*existential_principal.skip_binder()))
1115 .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
1116 .chain(existential_projections
1117 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
1118 .collect::<AccumulateVec<[_; 8]>>();
1119 v.sort_by(|a, b| a.cmp(tcx, b));
1120 let existential_predicates = ty::Binder(tcx.mk_existential_predicates(v.into_iter()));
1122 let region_bound = self.compute_object_lifetime_bound(span,
1124 existential_predicates);
1126 let region_bound = match region_bound {
1129 tcx.mk_region(match rscope.object_lifetime_default(span) {
1132 span_err!(self.tcx().sess, span, E0228,
1133 "the lifetime bound for this object type cannot be deduced \
1134 from context; please supply an explicit bound");
1141 debug!("region_bound: {:?}", region_bound);
1143 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1144 debug!("trait_object_type: {:?}", ty);
1148 fn report_ambiguous_associated_type(&self,
1153 struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
1154 .span_label(span, &format!("ambiguous associated type"))
1155 .note(&format!("specify the type using the syntax `<{} as {}>::{}`",
1156 type_str, trait_str, name))
1161 // Search for a bound on a type parameter which includes the associated item
1162 // given by assoc_name. ty_param_node_id is the node id for the type parameter
1163 // (which might be `Self`, but only if it is the `Self` of a trait, not an
1164 // impl). This function will fail if there are no suitable bounds or there is
1166 fn find_bound_for_assoc_item(&self,
1167 ty_param_node_id: ast::NodeId,
1168 ty_param_name: ast::Name,
1169 assoc_name: ast::Name,
1171 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1173 let tcx = self.tcx();
1175 let bounds = match self.get_type_parameter_bounds(span, ty_param_node_id) {
1177 Err(ErrorReported) => {
1178 return Err(ErrorReported);
1182 // Ensure the super predicates and stop if we encountered an error.
1183 if bounds.iter().any(|b| self.ensure_super_predicates(span, b.def_id()).is_err()) {
1184 return Err(ErrorReported);
1187 // Check that there is exactly one way to find an associated type with the
1189 let suitable_bounds =
1190 traits::transitive_bounds(tcx, &bounds)
1191 .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
1193 self.one_bound_for_assoc_type(suitable_bounds,
1194 &ty_param_name.as_str(),
1195 &assoc_name.as_str(),
1200 // Checks that bounds contains exactly one element and reports appropriate
1201 // errors otherwise.
1202 fn one_bound_for_assoc_type<I>(&self,
1204 ty_param_name: &str,
1207 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1208 where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
1210 let bound = match bounds.next() {
1211 Some(bound) => bound,
1213 struct_span_err!(self.tcx().sess, span, E0220,
1214 "associated type `{}` not found for `{}`",
1217 .span_label(span, &format!("associated type `{}` not found", assoc_name))
1219 return Err(ErrorReported);
1223 if let Some(bound2) = bounds.next() {
1224 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
1225 let mut err = struct_span_err!(
1226 self.tcx().sess, span, E0221,
1227 "ambiguous associated type `{}` in bounds of `{}`",
1230 err.span_label(span, &format!("ambiguous associated type `{}`", assoc_name));
1232 for bound in bounds {
1233 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
1234 item.kind == ty::AssociatedKind::Type && item.name == assoc_name
1236 .and_then(|item| self.tcx().map.span_if_local(item.def_id));
1238 if let Some(span) = bound_span {
1239 err.span_label(span, &format!("ambiguous `{}` from `{}`",
1243 span_note!(&mut err, span,
1244 "associated type `{}` could derive from `{}`",
1255 // Create a type from a path to an associated type.
1256 // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
1257 // and item_segment is the path segment for D. We return a type and a def for
1259 // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
1260 // parameter or Self.
1261 pub fn associated_path_def_to_ty(&self,
1262 ref_id: ast::NodeId,
1266 item_segment: &hir::PathSegment)
1269 let tcx = self.tcx();
1270 let assoc_name = item_segment.name;
1272 debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
1274 tcx.prohibit_type_params(slice::ref_slice(item_segment));
1276 // Find the type of the associated item, and the trait where the associated
1277 // item is declared.
1278 let bound = match (&ty.sty, ty_path_def) {
1279 (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
1280 // `Self` in an impl of a trait - we have a concrete self type and a
1282 let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
1283 let trait_ref = if let Some(free_substs) = self.get_free_substs() {
1284 trait_ref.subst(tcx, free_substs)
1289 if self.ensure_super_predicates(span, trait_ref.def_id).is_err() {
1290 return (tcx.types.err, Def::Err);
1294 traits::supertraits(tcx, ty::Binder(trait_ref))
1295 .filter(|r| self.trait_defines_associated_type_named(r.def_id(),
1298 match self.one_bound_for_assoc_type(candidates,
1300 &assoc_name.as_str(),
1303 Err(ErrorReported) => return (tcx.types.err, Def::Err),
1306 (&ty::TyParam(_), Def::SelfTy(Some(trait_did), None)) => {
1307 let trait_node_id = tcx.map.as_local_node_id(trait_did).unwrap();
1308 match self.find_bound_for_assoc_item(trait_node_id,
1309 keywords::SelfType.name(),
1313 Err(ErrorReported) => return (tcx.types.err, Def::Err),
1316 (&ty::TyParam(_), Def::TyParam(param_did)) => {
1317 let param_node_id = tcx.map.as_local_node_id(param_did).unwrap();
1318 let param_name = tcx.type_parameter_def(param_node_id).name;
1319 match self.find_bound_for_assoc_item(param_node_id,
1324 Err(ErrorReported) => return (tcx.types.err, Def::Err),
1328 // Don't print TyErr to the user.
1329 if !ty.references_error() {
1330 self.report_ambiguous_associated_type(span,
1333 &assoc_name.as_str());
1335 return (tcx.types.err, Def::Err);
1339 let trait_did = bound.0.def_id;
1340 let ty = self.projected_ty_from_poly_trait_ref(span, bound, assoc_name);
1342 let item = tcx.associated_items(trait_did).find(|i| i.name == assoc_name);
1343 let def_id = item.expect("missing associated type").def_id;
1344 tcx.check_stability(def_id, ref_id, span);
1345 (ty, Def::AssociatedTy(def_id))
1348 fn qpath_to_ty(&self,
1349 rscope: &RegionScope,
1351 opt_self_ty: Option<Ty<'tcx>>,
1352 trait_def_id: DefId,
1353 trait_segment: &hir::PathSegment,
1354 item_segment: &hir::PathSegment)
1357 let tcx = self.tcx();
1359 tcx.prohibit_type_params(slice::ref_slice(item_segment));
1361 let self_ty = if let Some(ty) = opt_self_ty {
1364 let path_str = tcx.item_path_str(trait_def_id);
1365 self.report_ambiguous_associated_type(span,
1368 &item_segment.name.as_str());
1369 return tcx.types.err;
1372 debug!("qpath_to_ty: self_type={:?}", self_ty);
1374 let trait_ref = self.ast_path_to_mono_trait_ref(rscope,
1380 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1382 self.projected_ty(span, trait_ref, item_segment.name)
1385 /// Convert a type supplied as value for a type argument from AST into our
1386 /// our internal representation. This is the same as `ast_ty_to_ty` but that
1387 /// it applies the object lifetime default.
1391 /// * `this`, `rscope`: the surrounding context
1392 /// * `def`: the type parameter being instantiated (if available)
1393 /// * `region_substs`: a partial substitution consisting of
1394 /// only the region type parameters being supplied to this type.
1395 /// * `ast_ty`: the ast representation of the type being supplied
1396 fn ast_ty_arg_to_ty(&self,
1397 rscope: &RegionScope,
1398 def: Option<&ty::TypeParameterDef<'tcx>>,
1399 region_substs: &[Kind<'tcx>],
1403 let tcx = self.tcx();
1405 if let Some(def) = def {
1406 let object_lifetime_default = def.object_lifetime_default.subst(tcx, region_substs);
1407 let rscope1 = &ObjectLifetimeDefaultRscope::new(rscope, object_lifetime_default);
1408 self.ast_ty_to_ty(rscope1, ast_ty)
1410 self.ast_ty_to_ty(rscope, ast_ty)
1414 // Check a type Path and convert it to a Ty.
1415 pub fn def_to_ty(&self,
1416 rscope: &RegionScope,
1417 opt_self_ty: Option<Ty<'tcx>>,
1419 path_id: ast::NodeId,
1420 permit_variants: bool)
1422 let tcx = self.tcx();
1424 debug!("base_def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
1425 path.def, opt_self_ty, path.segments);
1427 let span = path.span;
1429 Def::Trait(trait_def_id) => {
1430 // N.B. this case overlaps somewhat with
1431 // TyObjectSum, see that fn for details
1433 assert_eq!(opt_self_ty, None);
1434 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1436 self.trait_path_to_object_type(rscope,
1440 path.segments.last().unwrap(),
1442 partition_bounds(&[]))
1444 Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) | Def::Union(did) => {
1445 assert_eq!(opt_self_ty, None);
1446 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1447 self.ast_path_to_ty(rscope, span, did, path.segments.last().unwrap())
1449 Def::Variant(did) if permit_variants => {
1450 // Convert "variant type" as if it were a real type.
1451 // The resulting `Ty` is type of the variant's enum for now.
1452 assert_eq!(opt_self_ty, None);
1453 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1454 self.ast_path_to_ty(rscope,
1456 tcx.parent_def_id(did).unwrap(),
1457 path.segments.last().unwrap())
1459 Def::TyParam(did) => {
1460 assert_eq!(opt_self_ty, None);
1461 tcx.prohibit_type_params(&path.segments);
1463 let node_id = tcx.map.as_local_node_id(did).unwrap();
1464 let param = tcx.ty_param_defs.borrow().get(&node_id)
1465 .map(ty::ParamTy::for_def);
1466 if let Some(p) = param {
1469 // Only while computing defaults of earlier type
1470 // parameters can a type parameter be missing its def.
1471 struct_span_err!(tcx.sess, span, E0128,
1472 "type parameters with a default cannot use \
1473 forward declared identifiers")
1474 .span_label(span, &format!("defaulted type parameters \
1475 cannot be forward declared"))
1480 Def::SelfTy(_, Some(def_id)) => {
1481 // Self in impl (we know the concrete type).
1483 assert_eq!(opt_self_ty, None);
1484 tcx.prohibit_type_params(&path.segments);
1485 let ty = tcx.item_type(def_id);
1486 if let Some(free_substs) = self.get_free_substs() {
1487 ty.subst(tcx, free_substs)
1492 Def::SelfTy(Some(_), None) => {
1494 assert_eq!(opt_self_ty, None);
1495 tcx.prohibit_type_params(&path.segments);
1498 Def::AssociatedTy(def_id) => {
1499 tcx.prohibit_type_params(&path.segments[..path.segments.len()-2]);
1500 let trait_did = tcx.parent_def_id(def_id).unwrap();
1501 self.qpath_to_ty(rscope,
1505 &path.segments[path.segments.len()-2],
1506 path.segments.last().unwrap())
1508 Def::PrimTy(prim_ty) => {
1509 assert_eq!(opt_self_ty, None);
1510 tcx.prim_ty_to_ty(&path.segments, prim_ty)
1513 self.set_tainted_by_errors();
1514 return self.tcx().types.err;
1516 _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1520 /// Parses the programmer's textual representation of a type into our
1521 /// internal notion of a type.
1522 pub fn ast_ty_to_ty(&self, rscope: &RegionScope, ast_ty: &hir::Ty) -> Ty<'tcx> {
1523 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1526 let tcx = self.tcx();
1528 let cache = self.ast_ty_to_ty_cache();
1529 if let Some(ty) = cache.borrow().get(&ast_ty.id) {
1533 let result_ty = match ast_ty.node {
1534 hir::TySlice(ref ty) => {
1535 tcx.mk_slice(self.ast_ty_to_ty(rscope, &ty))
1537 hir::TyObjectSum(ref ty, ref bounds) => {
1538 self.ast_ty_to_object_trait_ref(rscope, ast_ty.span, ty, bounds)
1540 hir::TyPtr(ref mt) => {
1541 tcx.mk_ptr(ty::TypeAndMut {
1542 ty: self.ast_ty_to_ty(rscope, &mt.ty),
1546 hir::TyRptr(ref region, ref mt) => {
1547 let r = self.opt_ast_region_to_region(rscope, ast_ty.span, region);
1548 debug!("TyRef r={:?}", r);
1550 &ObjectLifetimeDefaultRscope::new(
1552 ty::ObjectLifetimeDefault::Specific(r));
1553 let t = self.ast_ty_to_ty(rscope1, &mt.ty);
1554 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1559 hir::TyTup(ref fields) => {
1560 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(rscope, &t)))
1562 hir::TyBareFn(ref bf) => {
1563 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1564 let anon_scope = rscope.anon_type_scope();
1565 let bare_fn_ty = self.ty_of_method_or_bare_fn(bf.unsafety,
1573 // Find any late-bound regions declared in return type that do
1574 // not appear in the arguments. These are not wellformed.
1578 // for<'a> fn() -> &'a str <-- 'a is bad
1579 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1581 // Note that we do this check **here** and not in
1582 // `ty_of_bare_fn` because the latter is also used to make
1583 // the types for fn items, and we do not want to issue a
1584 // warning then. (Once we fix #32330, the regions we are
1585 // checking for here would be considered early bound
1587 let inputs = bare_fn_ty.sig.inputs();
1588 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1589 &inputs.map_bound(|i| i.to_owned()));
1590 let output = bare_fn_ty.sig.output();
1591 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1592 for br in late_bound_in_ret.difference(&late_bound_in_args) {
1593 let br_name = match *br {
1594 ty::BrNamed(_, name, _) => name,
1597 bf.decl.output.span(),
1598 "anonymous bound region {:?} in return but not args",
1603 lint::builtin::HR_LIFETIME_IN_ASSOC_TYPE,
1606 format!("return type references lifetime `{}`, \
1607 which does not appear in the trait input types",
1610 tcx.mk_fn_ptr(bare_fn_ty)
1612 hir::TyPolyTraitRef(ref bounds) => {
1613 self.conv_object_ty_poly_trait_ref(rscope, ast_ty.span, bounds)
1615 hir::TyImplTrait(ref bounds) => {
1616 use collect::{compute_bounds, SizedByDefault};
1618 // Create the anonymized type.
1619 let def_id = tcx.map.local_def_id(ast_ty.id);
1620 if let Some(anon_scope) = rscope.anon_type_scope() {
1621 let substs = anon_scope.fresh_substs(self, ast_ty.span);
1622 let ty = tcx.mk_anon(tcx.map.local_def_id(ast_ty.id), substs);
1624 // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`.
1625 let bounds = compute_bounds(self, ty, bounds,
1626 SizedByDefault::Yes,
1629 let predicates = bounds.predicates(tcx, ty);
1630 let predicates = tcx.lift_to_global(&predicates).unwrap();
1631 tcx.predicates.borrow_mut().insert(def_id, ty::GenericPredicates {
1633 predicates: predicates
1638 span_err!(tcx.sess, ast_ty.span, E0562,
1639 "`impl Trait` not allowed outside of function \
1640 and inherent method return types");
1644 hir::TyPath(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1645 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1646 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1647 self.ast_ty_to_ty(rscope, qself)
1649 self.def_to_ty(rscope, opt_self_ty, path, ast_ty.id, false)
1651 hir::TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1652 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1653 let ty = self.ast_ty_to_ty(rscope, qself);
1655 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
1660 self.associated_path_def_to_ty(ast_ty.id, ast_ty.span, ty, def, segment).0
1662 hir::TyArray(ref ty, length) => {
1663 if let Ok(length) = eval_length(tcx.global_tcx(), length, "array length") {
1664 tcx.mk_array(self.ast_ty_to_ty(rscope, &ty), length)
1666 self.tcx().types.err
1669 hir::TyTypeof(ref _e) => {
1670 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1671 "`typeof` is a reserved keyword but unimplemented")
1672 .span_label(ast_ty.span, &format!("reserved keyword"))
1678 // TyInfer also appears as the type of arguments or return
1679 // values in a ExprClosure, or as
1680 // the type of local variables. Both of these cases are
1681 // handled specially and will not descend into this routine.
1682 self.ty_infer(ast_ty.span)
1686 cache.borrow_mut().insert(ast_ty.id, result_ty);
1691 pub fn ty_of_arg(&self,
1692 rscope: &RegionScope,
1694 expected_ty: Option<Ty<'tcx>>)
1698 hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1699 hir::TyInfer => self.ty_infer(ty.span),
1700 _ => self.ast_ty_to_ty(rscope, ty),
1704 pub fn ty_of_method(&self,
1705 sig: &hir::MethodSig,
1706 opt_self_value_ty: Option<Ty<'tcx>>,
1707 body: Option<hir::BodyId>,
1708 anon_scope: Option<AnonTypeScope>)
1709 -> &'tcx ty::BareFnTy<'tcx> {
1710 self.ty_of_method_or_bare_fn(sig.unsafety,
1719 pub fn ty_of_bare_fn(&self,
1720 unsafety: hir::Unsafety,
1724 anon_scope: Option<AnonTypeScope>)
1725 -> &'tcx ty::BareFnTy<'tcx> {
1726 self.ty_of_method_or_bare_fn(unsafety, abi, None, decl, Some(body), None, anon_scope)
1729 fn ty_of_method_or_bare_fn(&self,
1730 unsafety: hir::Unsafety,
1732 opt_self_value_ty: Option<Ty<'tcx>>,
1734 body: Option<hir::BodyId>,
1735 arg_anon_scope: Option<AnonTypeScope>,
1736 ret_anon_scope: Option<AnonTypeScope>)
1737 -> &'tcx ty::BareFnTy<'tcx>
1739 debug!("ty_of_method_or_bare_fn");
1741 // New region names that appear inside of the arguments of the function
1742 // declaration are bound to that function type.
1743 let rb = MaybeWithAnonTypes::new(BindingRscope::new(), arg_anon_scope);
1745 let input_tys: Vec<Ty> =
1746 decl.inputs.iter().map(|a| self.ty_of_arg(&rb, a, None)).collect();
1748 let has_self = opt_self_value_ty.is_some();
1749 let explicit_self = opt_self_value_ty.map(|self_value_ty| {
1750 ExplicitSelf::determine(self_value_ty, input_tys[0])
1753 let implied_output_region = match explicit_self {
1754 // `implied_output_region` is the region that will be assumed for any
1755 // region parameters in the return type. In accordance with the rules for
1756 // lifetime elision, we can determine it in two ways. First (determined
1757 // here), if self is by-reference, then the implied output region is the
1758 // region of the self parameter.
1759 Some(ExplicitSelf::ByReference(region, _)) => Ok(*region),
1761 // Second, if there was exactly one lifetime (either a substitution or a
1762 // reference) in the arguments, then any anonymous regions in the output
1763 // have that lifetime.
1765 let arg_tys = &input_tys[has_self as usize..];
1766 let arg_params = has_self as usize..input_tys.len();
1767 self.find_implied_output_region(arg_tys, body, arg_params)
1772 let output_ty = match decl.output {
1773 hir::Return(ref output) =>
1774 self.convert_ty_with_lifetime_elision(implied_output_region,
1777 hir::DefaultReturn(..) => self.tcx().mk_nil(),
1780 debug!("ty_of_method_or_bare_fn: output_ty={:?}", output_ty);
1782 self.tcx().mk_bare_fn(ty::BareFnTy {
1785 sig: ty::Binder(self.tcx().mk_fn_sig(
1786 input_tys.into_iter(),
1793 pub fn ty_of_closure(&self,
1794 unsafety: hir::Unsafety,
1797 expected_sig: Option<ty::FnSig<'tcx>>)
1798 -> ty::ClosureTy<'tcx>
1800 debug!("ty_of_closure(expected_sig={:?})",
1803 // new region names that appear inside of the fn decl are bound to
1804 // that function type
1805 let rb = rscope::BindingRscope::new();
1807 let input_tys = decl.inputs.iter().enumerate().map(|(i, a)| {
1808 let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1809 // no guarantee that the correct number of expected args
1811 if i < e.inputs().len() {
1817 self.ty_of_arg(&rb, a, expected_arg_ty)
1820 let expected_ret_ty = expected_sig.as_ref().map(|e| e.output());
1822 let is_infer = match decl.output {
1823 hir::Return(ref output) if output.node == hir::TyInfer => true,
1824 hir::DefaultReturn(..) => true,
1828 let output_ty = match decl.output {
1829 _ if is_infer && expected_ret_ty.is_some() =>
1830 expected_ret_ty.unwrap(),
1831 _ if is_infer => self.ty_infer(decl.output.span()),
1832 hir::Return(ref output) =>
1833 self.ast_ty_to_ty(&rb, &output),
1834 hir::DefaultReturn(..) => bug!(),
1837 debug!("ty_of_closure: output_ty={:?}", output_ty);
1842 sig: ty::Binder(self.tcx().mk_fn_sig(input_tys, output_ty, decl.variadic)),
1846 fn conv_object_ty_poly_trait_ref(&self,
1847 rscope: &RegionScope,
1849 ast_bounds: &[hir::TyParamBound])
1852 let mut partitioned_bounds = partition_bounds(ast_bounds);
1854 let trait_bound = if !partitioned_bounds.trait_bounds.is_empty() {
1855 partitioned_bounds.trait_bounds.remove(0)
1857 span_err!(self.tcx().sess, span, E0224,
1858 "at least one non-builtin trait is required for an object type");
1859 return self.tcx().types.err;
1862 let trait_ref = &trait_bound.trait_ref;
1863 let trait_def_id = self.trait_def_id(trait_ref);
1864 self.trait_path_to_object_type(rscope,
1865 trait_ref.path.span,
1868 trait_ref.path.segments.last().unwrap(),
1873 /// Given the bounds on an object, determines what single region bound (if any) we can
1874 /// use to summarize this type. The basic idea is that we will use the bound the user
1875 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1876 /// for region bounds. It may be that we can derive no bound at all, in which case
1877 /// we return `None`.
1878 fn compute_object_lifetime_bound(&self,
1880 explicit_region_bounds: &[&hir::Lifetime],
1881 existential_predicates: ty::Binder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>)
1882 -> Option<&'tcx ty::Region> // if None, use the default
1884 let tcx = self.tcx();
1886 debug!("compute_opt_region_bound(explicit_region_bounds={:?}, \
1887 existential_predicates={:?})",
1888 explicit_region_bounds,
1889 existential_predicates);
1891 if explicit_region_bounds.len() > 1 {
1892 span_err!(tcx.sess, explicit_region_bounds[1].span, E0226,
1893 "only a single explicit lifetime bound is permitted");
1896 if let Some(&r) = explicit_region_bounds.get(0) {
1897 // Explicitly specified region bound. Use that.
1898 return Some(ast_region_to_region(tcx, r));
1901 if let Some(principal) = existential_predicates.principal() {
1902 if let Err(ErrorReported) = self.ensure_super_predicates(span, principal.def_id()) {
1903 return Some(tcx.mk_region(ty::ReStatic));
1907 // No explicit region bound specified. Therefore, examine trait
1908 // bounds and see if we can derive region bounds from those.
1909 let derived_region_bounds =
1910 object_region_bounds(tcx, existential_predicates);
1912 // If there are no derived region bounds, then report back that we
1913 // can find no region bound. The caller will use the default.
1914 if derived_region_bounds.is_empty() {
1918 // If any of the derived region bounds are 'static, that is always
1920 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1921 return Some(tcx.mk_region(ty::ReStatic));
1924 // Determine whether there is exactly one unique region in the set
1925 // of derived region bounds. If so, use that. Otherwise, report an
1927 let r = derived_region_bounds[0];
1928 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1929 span_err!(tcx.sess, span, E0227,
1930 "ambiguous lifetime bound, explicit lifetime bound required");
1936 pub struct PartitionedBounds<'a> {
1937 pub trait_bounds: Vec<&'a hir::PolyTraitRef>,
1938 pub region_bounds: Vec<&'a hir::Lifetime>,
1941 /// Divides a list of general trait bounds into two groups: builtin bounds (Sync/Send) and the
1942 /// remaining general trait bounds.
1943 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1944 trait_bounds: Vec<&'b hir::PolyTraitRef>)
1945 -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
1947 let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.into_iter().partition(|bound| {
1948 match bound.trait_ref.path.def {
1949 Def::Trait(trait_did) => {
1950 // Checks whether `trait_did` refers to one of the builtin
1951 // traits, like `Send`, and adds it to `auto_traits` if so.
1952 if Some(trait_did) == tcx.lang_items.send_trait() ||
1953 Some(trait_did) == tcx.lang_items.sync_trait() {
1954 let segments = &bound.trait_ref.path.segments;
1955 let parameters = &segments[segments.len() - 1].parameters;
1956 if !parameters.types().is_empty() {
1957 check_type_argument_count(tcx, bound.trait_ref.path.span,
1958 parameters.types().len(), &[]);
1960 if !parameters.lifetimes().is_empty() {
1961 report_lifetime_number_error(tcx, bound.trait_ref.path.span,
1962 parameters.lifetimes().len(), 0);
1973 let auto_traits = auto_traits.into_iter().map(|tr| {
1974 if let Def::Trait(trait_did) = tr.trait_ref.path.def {
1979 }).collect::<Vec<_>>();
1981 (auto_traits, trait_bounds)
1984 /// Divides a list of bounds from the AST into two groups: general trait bounds and region bounds
1985 pub fn partition_bounds<'a, 'b, 'gcx, 'tcx>(ast_bounds: &'b [hir::TyParamBound])
1986 -> PartitionedBounds<'b>
1988 let mut region_bounds = Vec::new();
1989 let mut trait_bounds = Vec::new();
1990 for ast_bound in ast_bounds {
1992 hir::TraitTyParamBound(ref b, hir::TraitBoundModifier::None) => {
1993 trait_bounds.push(b);
1995 hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {}
1996 hir::RegionTyParamBound(ref l) => {
1997 region_bounds.push(l);
2003 trait_bounds: trait_bounds,
2004 region_bounds: region_bounds,
2008 fn check_type_argument_count(tcx: TyCtxt, span: Span, supplied: usize,
2009 ty_param_defs: &[ty::TypeParameterDef]) {
2010 let accepted = ty_param_defs.len();
2011 let required = ty_param_defs.iter().take_while(|x| x.default.is_none()) .count();
2012 if supplied < required {
2013 let expected = if required < accepted {
2018 let arguments_plural = if required == 1 { "" } else { "s" };
2020 struct_span_err!(tcx.sess, span, E0243,
2021 "wrong number of type arguments: {} {}, found {}",
2022 expected, required, supplied)
2024 &format!("{} {} type argument{}",
2029 } else if supplied > accepted {
2030 let expected = if required < accepted {
2031 format!("expected at most {}", accepted)
2033 format!("expected {}", accepted)
2035 let arguments_plural = if accepted == 1 { "" } else { "s" };
2037 struct_span_err!(tcx.sess, span, E0244,
2038 "wrong number of type arguments: {}, found {}",
2042 &format!("{} type argument{}",
2043 if accepted == 0 { "expected no" } else { &expected },
2050 fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected: usize) {
2051 let label = if number < expected {
2053 format!("expected {} lifetime parameter", expected)
2055 format!("expected {} lifetime parameters", expected)
2058 let additional = number - expected;
2059 if additional == 1 {
2060 "unexpected lifetime parameter".to_string()
2062 format!("{} unexpected lifetime parameters", additional)
2065 struct_span_err!(tcx.sess, span, E0107,
2066 "wrong number of lifetime parameters: expected {}, found {}",
2068 .span_label(span, &label)
2072 // A helper struct for conveniently grouping a set of bounds which we pass to
2073 // and return from functions in multiple places.
2074 #[derive(PartialEq, Eq, Clone, Debug)]
2075 pub struct Bounds<'tcx> {
2076 pub region_bounds: Vec<&'tcx ty::Region>,
2077 pub implicitly_sized: bool,
2078 pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
2079 pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
2082 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
2083 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
2084 -> Vec<ty::Predicate<'tcx>>
2086 let mut vec = Vec::new();
2088 // If it could be sized, and is, add the sized predicate
2089 if self.implicitly_sized {
2090 if let Some(sized) = tcx.lang_items.sized_trait() {
2091 let trait_ref = ty::TraitRef {
2093 substs: tcx.mk_substs_trait(param_ty, &[])
2095 vec.push(trait_ref.to_predicate());
2099 for ®ion_bound in &self.region_bounds {
2100 // account for the binder being introduced below; no need to shift `param_ty`
2101 // because, at present at least, it can only refer to early-bound regions
2102 let region_bound = tcx.mk_region(ty::fold::shift_region(*region_bound, 1));
2103 vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
2106 for bound_trait_ref in &self.trait_bounds {
2107 vec.push(bound_trait_ref.to_predicate());
2110 for projection in &self.projection_bounds {
2111 vec.push(projection.to_predicate());
2118 pub enum ExplicitSelf<'tcx> {
2120 ByReference(&'tcx ty::Region, hir::Mutability),
2124 impl<'tcx> ExplicitSelf<'tcx> {
2125 /// We wish to (for now) categorize an explicit self
2126 /// declaration like `self: SomeType` into either `self`,
2127 /// `&self`, `&mut self`, or `Box<self>`. We do this here
2128 /// by some simple pattern matching. A more precise check
2129 /// is done later in `check_method_self_type()`.
2134 /// impl Foo for &T {
2135 /// // Legal declarations:
2136 /// fn method1(self: &&T); // ExplicitSelf::ByReference
2137 /// fn method2(self: &T); // ExplicitSelf::ByValue
2138 /// fn method3(self: Box<&T>); // ExplicitSelf::ByBox
2140 /// // Invalid cases will be caught later by `check_method_self_type`:
2141 /// fn method_err1(self: &mut T); // ExplicitSelf::ByReference
2145 /// To do the check we just count the number of "modifiers"
2146 /// on each type and compare them. If they are the same or
2147 /// the impl has more, we call it "by value". Otherwise, we
2148 /// look at the outermost modifier on the method decl and
2149 /// call it by-ref, by-box as appropriate. For method1, for
2150 /// example, the impl type has one modifier, but the method
2151 /// type has two, so we end up with
2152 /// ExplicitSelf::ByReference.
2153 pub fn determine(untransformed_self_ty: Ty<'tcx>,
2154 self_arg_ty: Ty<'tcx>)
2155 -> ExplicitSelf<'tcx> {
2156 fn count_modifiers(ty: Ty) -> usize {
2158 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
2159 ty::TyBox(t) => count_modifiers(t) + 1,
2164 let impl_modifiers = count_modifiers(untransformed_self_ty);
2165 let method_modifiers = count_modifiers(self_arg_ty);
2167 if impl_modifiers >= method_modifiers {
2168 ExplicitSelf::ByValue
2170 match self_arg_ty.sty {
2171 ty::TyRef(r, mt) => ExplicitSelf::ByReference(r, mt.mutbl),
2172 ty::TyBox(_) => ExplicitSelf::ByBox,
2173 _ => ExplicitSelf::ByValue,