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, ExplicitRscope};
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 fn report_elision_failure(
166 db: &mut DiagnosticBuilder,
167 params: Vec<ElisionFailureInfo>)
169 let mut m = String::new();
170 let len = params.len();
172 let elided_params: Vec<_> = params.into_iter()
173 .filter(|info| info.lifetime_count > 0)
176 let elided_len = elided_params.len();
178 for (i, info) in elided_params.into_iter().enumerate() {
179 let ElisionFailureInfo {
180 parent, index, lifetime_count: n, have_bound_regions
183 let help_name = if let Some(body) = parent {
184 let arg = &tcx.hir.body(body).arguments[index];
185 format!("`{}`", tcx.hir.node_to_pretty_string(arg.pat.id))
187 format!("argument {}", index + 1)
190 m.push_str(&(if n == 1 {
193 format!("one of {}'s {} elided {}lifetimes", help_name, n,
194 if have_bound_regions { "free " } else { "" } )
197 if elided_len == 2 && i == 0 {
199 } else if i + 2 == elided_len {
201 } else if i != elided_len - 1 {
209 "this function's return type contains a borrowed value, but \
210 there is no value for it to be borrowed from");
212 "consider giving it a 'static lifetime");
213 } else if elided_len == 0 {
215 "this function's return type contains a borrowed value with \
216 an elided lifetime, but the lifetime cannot be derived from \
219 "consider giving it an explicit bounded or 'static \
221 } else if elided_len == 1 {
223 "this function's return type contains a borrowed value, but \
224 the signature does not say which {} it is borrowed from",
228 "this function's return type contains a borrowed value, but \
229 the signature does not say whether it is borrowed from {}",
234 impl<'o, 'gcx: 'tcx, 'tcx> AstConv<'gcx, 'tcx>+'o {
235 pub fn ast_region_to_region(&self, lifetime: &hir::Lifetime) -> &'tcx ty::Region {
236 self.opt_ast_region_to_region(&ExplicitRscope, lifetime.span, Some(lifetime), None)
239 fn try_opt_ast_region_to_region(&self,
240 rscope: &RegionScope,
242 opt_lifetime: Option<&hir::Lifetime>,
243 def: Option<&ty::RegionParameterDef>)
244 -> Result<&'tcx ty::Region, Option<Vec<ElisionFailureInfo>>>
246 let tcx = self.tcx();
247 let name = opt_lifetime.map(|l| l.name);
248 let resolved = opt_lifetime.and_then(|l| tcx.named_region_map.defs.get(&l.id));
249 let r = tcx.mk_region(match resolved {
250 Some(&rl::DefStaticRegion) => {
254 Some(&rl::DefLateBoundRegion(debruijn, id)) => {
255 // If this region is declared on a function, it will have
256 // an entry in `late_bound`, but if it comes from
257 // `for<'a>` in some type or something, it won't
258 // necessarily have one. In that case though, we won't be
259 // changed from late to early bound, so we can just
261 let issue_32330 = tcx.named_region_map
265 .unwrap_or(ty::Issue32330::WontChange);
266 ty::ReLateBound(debruijn, ty::BrNamed(tcx.hir.local_def_id(id),
271 Some(&rl::DefEarlyBoundRegion(index, _)) => {
272 ty::ReEarlyBound(ty::EarlyBoundRegion {
278 Some(&rl::DefFreeRegion(scope, id)) => {
279 // As in DefLateBoundRegion above, could be missing for some late-bound
280 // regions, but also for early-bound regions.
281 let issue_32330 = tcx.named_region_map
285 .unwrap_or(ty::Issue32330::WontChange);
286 ty::ReFree(ty::FreeRegion {
287 scope: scope.to_code_extent(&tcx.region_maps),
288 bound_region: ty::BrNamed(tcx.hir.local_def_id(id),
293 // (*) -- not late-bound, won't change
296 None => rscope.anon_region(default_span, def)?
299 debug!("opt_ast_region_to_region(opt_lifetime={:?}) yields {:?}",
306 pub fn opt_ast_region_to_region(&self,
307 rscope: &RegionScope,
309 opt_lifetime: Option<&hir::Lifetime>,
310 def: Option<&ty::RegionParameterDef>) -> &'tcx ty::Region
312 let tcx = self.tcx();
313 self.try_opt_ast_region_to_region(rscope, default_span, opt_lifetime, def)
314 .unwrap_or_else(|params| {
315 let ampersand_span = Span { hi: default_span.lo, ..default_span};
317 let mut err = struct_span_err!(tcx.sess, ampersand_span, E0106,
318 "missing lifetime specifier");
319 err.span_label(ampersand_span, &format!("expected lifetime parameter"));
321 if let Some(params) = params {
322 report_elision_failure(tcx, &mut err, params);
325 tcx.mk_region(ty::ReStatic)
329 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
330 /// returns an appropriate set of substitutions for this particular reference to `I`.
331 pub fn ast_path_substs_for_ty(&self,
332 rscope: &RegionScope,
335 item_segment: &hir::PathSegment)
336 -> &'tcx Substs<'tcx>
338 let tcx = self.tcx();
340 match item_segment.parameters {
341 hir::AngleBracketedParameters(_) => {}
342 hir::ParenthesizedParameters(..) => {
343 struct_span_err!(tcx.sess, span, E0214,
344 "parenthesized parameters may only be used with a trait")
345 .span_label(span, &format!("only traits may use parentheses"))
348 return Substs::for_item(tcx, def_id, |_, _| {
349 tcx.mk_region(ty::ReStatic)
356 let (substs, assoc_bindings) =
357 self.create_substs_for_ast_path(rscope,
360 &item_segment.parameters,
363 assoc_bindings.first().map(|b| self.tcx().prohibit_projection(b.span));
368 /// Given the type/region arguments provided to some path (along with
369 /// an implicit Self, if this is a trait reference) returns the complete
370 /// set of substitutions. This may involve applying defaulted type parameters.
372 /// Note that the type listing given here is *exactly* what the user provided.
373 fn create_substs_for_ast_path(&self,
374 rscope: &RegionScope,
377 parameters: &hir::PathParameters,
378 self_ty: Option<Ty<'tcx>>)
379 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
381 let tcx = self.tcx();
383 debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
385 def_id, self_ty, parameters);
387 let (lifetimes, num_types_provided, infer_types) = match *parameters {
388 hir::AngleBracketedParameters(ref data) => {
389 (&data.lifetimes[..], data.types.len(), data.infer_types)
391 hir::ParenthesizedParameters(_) => (&[][..], 1, false)
394 // If the type is parameterized by this region, then replace this
395 // region with the current anon region binding (in other words,
396 // whatever & would get replaced with).
397 let decl_generics = match self.get_generics(span, def_id) {
398 Ok(generics) => generics,
399 Err(ErrorReported) => {
400 // No convenient way to recover from a cycle here. Just bail. Sorry!
401 self.tcx().sess.abort_if_errors();
402 bug!("ErrorReported returned, but no errors reports?")
405 let expected_num_region_params = decl_generics.regions.len();
406 let supplied_num_region_params = lifetimes.len();
407 let mut reported_lifetime_count_mismatch = false;
408 let mut report_lifetime_count_mismatch = || {
409 if !reported_lifetime_count_mismatch {
410 reported_lifetime_count_mismatch = true;
411 let all_infer = lifetimes.iter().all(|lt| lt.is_elided());
412 let supplied = if all_infer { 0 } else { supplied_num_region_params };
413 report_lifetime_number_error(tcx, span,
415 expected_num_region_params);
419 if expected_num_region_params != supplied_num_region_params {
420 report_lifetime_count_mismatch();
423 // If a self-type was declared, one should be provided.
424 assert_eq!(decl_generics.has_self, self_ty.is_some());
426 // Check the number of type parameters supplied by the user.
427 let ty_param_defs = &decl_generics.types[self_ty.is_some() as usize..];
428 if !infer_types || num_types_provided > ty_param_defs.len() {
429 check_type_argument_count(tcx, span, num_types_provided, ty_param_defs);
432 let is_object = self_ty.map_or(false, |ty| ty.sty == TRAIT_OBJECT_DUMMY_SELF);
433 let default_needs_object_self = |p: &ty::TypeParameterDef<'tcx>| {
434 if let Some(ref default) = p.default {
435 if is_object && default.has_self_ty() {
436 // There is no suitable inference default for a type parameter
437 // that references self, in an object type.
445 let mut output_assoc_binding = None;
446 let substs = Substs::for_item(tcx, def_id, |def, _| {
447 let i = def.index as usize - self_ty.is_some() as usize;
448 let l = lifetimes.get(i);
449 self.try_opt_ast_region_to_region(rscope, span, l, Some(def)).unwrap_or_else(|_| {
450 report_lifetime_count_mismatch();
451 tcx.mk_region(ty::ReStatic)
454 let i = def.index as usize;
456 // Handle Self first, so we can adjust the index to match the AST.
457 if let (0, Some(ty)) = (i, self_ty) {
461 let i = i - self_ty.is_some() as usize - decl_generics.regions.len();
462 if i < num_types_provided {
463 // A provided type parameter.
465 hir::AngleBracketedParameters(ref data) => {
466 self.ast_ty_arg_to_ty(rscope, Some(def), substs, &data.types[i])
468 hir::ParenthesizedParameters(ref data) => {
471 self.convert_parenthesized_parameters(rscope, substs, data);
472 output_assoc_binding = Some(assoc);
476 } else if infer_types {
477 // No type parameters were provided, we can infer all.
478 let ty_var = if !default_needs_object_self(def) {
479 self.ty_infer_for_def(def, substs, span)
484 } else if let Some(default) = def.default {
485 // No type parameter provided, but a default exists.
487 // If we are converting an object type, then the
488 // `Self` parameter is unknown. However, some of the
489 // other type parameters may reference `Self` in their
490 // defaults. This will lead to an ICE if we are not
492 if default_needs_object_self(def) {
493 struct_span_err!(tcx.sess, span, E0393,
494 "the type parameter `{}` must be explicitly specified",
496 .span_label(span, &format!("missing reference to `{}`", def.name))
497 .note(&format!("because of the default `Self` reference, \
498 type parameters must be specified on object types"))
502 // This is a default type parameter.
503 default.subst_spanned(tcx, substs, Some(span))
506 // We've already errored above about the mismatch.
511 let assoc_bindings = match *parameters {
512 hir::AngleBracketedParameters(ref data) => {
513 data.bindings.iter().map(|b| {
516 ty: self.ast_ty_to_ty(rscope, &b.ty),
521 hir::ParenthesizedParameters(ref data) => {
522 vec![output_assoc_binding.unwrap_or_else(|| {
523 // This is an error condition, but we should
524 // get the associated type binding anyway.
525 self.convert_parenthesized_parameters(rscope, substs, data).1
530 debug!("create_substs_for_ast_path(decl_generics={:?}, self_ty={:?}) -> {:?}",
531 decl_generics, self_ty, substs);
533 (substs, assoc_bindings)
536 /// Returns the appropriate lifetime to use for any output lifetimes
537 /// (if one exists) and a vector of the (pattern, number of lifetimes)
538 /// corresponding to each input type/pattern.
539 fn find_implied_output_region<I>(&self,
540 input_tys: &[Ty<'tcx>],
541 parent: Option<hir::BodyId>,
542 input_indices: I) -> ElidedLifetime
543 where I: Iterator<Item=usize>
545 let tcx = self.tcx();
546 let mut lifetimes_for_params = Vec::with_capacity(input_tys.len());
547 let mut possible_implied_output_region = None;
548 let mut lifetimes = 0;
550 for (input_type, index) in input_tys.iter().zip(input_indices) {
551 let mut regions = FxHashSet();
552 let have_bound_regions = tcx.collect_regions(input_type, &mut regions);
554 debug!("find_implied_output_regions: collected {:?} from {:?} \
555 have_bound_regions={:?}", ®ions, input_type, have_bound_regions);
557 lifetimes += regions.len();
559 if lifetimes == 1 && regions.len() == 1 {
560 // there's a chance that the unique lifetime of this
561 // iteration will be the appropriate lifetime for output
562 // parameters, so lets store it.
563 possible_implied_output_region = regions.iter().cloned().next();
566 lifetimes_for_params.push(ElisionFailureInfo {
569 lifetime_count: regions.len(),
570 have_bound_regions: have_bound_regions
575 Ok(*possible_implied_output_region.unwrap())
577 Err(Some(lifetimes_for_params))
581 fn convert_ty_with_lifetime_elision(&self,
582 elided_lifetime: ElidedLifetime,
584 anon_scope: Option<AnonTypeScope>)
587 match elided_lifetime {
588 Ok(implied_output_region) => {
589 let rb = ElidableRscope::new(implied_output_region);
590 self.ast_ty_to_ty(&MaybeWithAnonTypes::new(rb, anon_scope), ty)
592 Err(param_lifetimes) => {
593 // All regions must be explicitly specified in the output
594 // if the lifetime elision rules do not apply. This saves
595 // the user from potentially-confusing errors.
596 let rb = UnelidableRscope::new(param_lifetimes);
597 self.ast_ty_to_ty(&MaybeWithAnonTypes::new(rb, anon_scope), ty)
602 fn convert_parenthesized_parameters(&self,
603 rscope: &RegionScope,
604 region_substs: &[Kind<'tcx>],
605 data: &hir::ParenthesizedParameterData)
606 -> (Ty<'tcx>, ConvertedBinding<'tcx>)
608 let anon_scope = rscope.anon_type_scope();
609 let binding_rscope = MaybeWithAnonTypes::new(BindingRscope::new(), anon_scope);
610 let inputs = self.tcx().mk_type_list(data.inputs.iter().map(|a_t| {
611 self.ast_ty_arg_to_ty(&binding_rscope, None, region_substs, a_t)
613 let input_params = 0..inputs.len();
614 let implied_output_region = self.find_implied_output_region(&inputs, None, input_params);
616 let (output, output_span) = match data.output {
617 Some(ref output_ty) => {
618 (self.convert_ty_with_lifetime_elision(implied_output_region,
624 (self.tcx().mk_nil(), data.span)
628 let output_binding = ConvertedBinding {
629 item_name: Symbol::intern(FN_OUTPUT_NAME),
634 (self.tcx().mk_ty(ty::TyTuple(inputs)), output_binding)
637 pub fn instantiate_poly_trait_ref(&self,
638 rscope: &RegionScope,
639 ast_trait_ref: &hir::PolyTraitRef,
641 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
642 -> ty::PolyTraitRef<'tcx>
644 let trait_ref = &ast_trait_ref.trait_ref;
645 let trait_def_id = self.trait_def_id(trait_ref);
646 self.ast_path_to_poly_trait_ref(rscope,
651 trait_ref.path.segments.last().unwrap(),
655 /// Instantiates the path for the given trait reference, assuming that it's
656 /// bound to a valid trait type. Returns the def_id for the defining trait.
657 /// Fails if the type is a type other than a trait type.
659 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
660 /// are disallowed. Otherwise, they are pushed onto the vector given.
661 pub fn instantiate_mono_trait_ref(&self,
662 rscope: &RegionScope,
663 trait_ref: &hir::TraitRef,
665 -> ty::TraitRef<'tcx>
667 let trait_def_id = self.trait_def_id(trait_ref);
668 self.ast_path_to_mono_trait_ref(rscope,
672 trait_ref.path.segments.last().unwrap())
675 fn trait_def_id(&self, trait_ref: &hir::TraitRef) -> DefId {
676 let path = &trait_ref.path;
678 Def::Trait(trait_def_id) => trait_def_id,
680 self.tcx().sess.fatal("cannot continue compilation due to previous error");
683 span_fatal!(self.tcx().sess, path.span, E0245, "`{}` is not a trait",
684 self.tcx().hir.node_to_pretty_string(trait_ref.ref_id));
689 fn ast_path_to_poly_trait_ref(&self,
690 rscope: &RegionScope,
694 path_id: ast::NodeId,
695 trait_segment: &hir::PathSegment,
696 poly_projections: &mut Vec<ty::PolyProjectionPredicate<'tcx>>)
697 -> ty::PolyTraitRef<'tcx>
699 debug!("ast_path_to_poly_trait_ref(trait_segment={:?})", trait_segment);
700 // The trait reference introduces a binding level here, so
701 // we need to shift the `rscope`. It'd be nice if we could
702 // do away with this rscope stuff and work this knowledge
703 // into resolve_lifetimes, as we do with non-omitted
704 // lifetimes. Oh well, not there yet.
705 let shifted_rscope = &ShiftedRscope::new(rscope);
707 let (substs, assoc_bindings) =
708 self.create_substs_for_ast_trait_ref(shifted_rscope,
713 let poly_trait_ref = ty::Binder(ty::TraitRef::new(trait_def_id, substs));
715 poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
716 // specify type to assert that error was already reported in Err case:
717 let predicate: Result<_, ErrorReported> =
718 self.ast_type_binding_to_poly_projection_predicate(path_id,
721 predicate.ok() // ok to ignore Err() because ErrorReported (see above)
724 debug!("ast_path_to_poly_trait_ref(trait_segment={:?}, projections={:?}) -> {:?}",
725 trait_segment, poly_projections, poly_trait_ref);
729 fn ast_path_to_mono_trait_ref(&self,
730 rscope: &RegionScope,
734 trait_segment: &hir::PathSegment)
735 -> ty::TraitRef<'tcx>
737 let (substs, assoc_bindings) =
738 self.create_substs_for_ast_trait_ref(rscope,
743 assoc_bindings.first().map(|b| self.tcx().prohibit_projection(b.span));
744 ty::TraitRef::new(trait_def_id, substs)
747 fn create_substs_for_ast_trait_ref(&self,
748 rscope: &RegionScope,
752 trait_segment: &hir::PathSegment)
753 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>)
755 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
758 let trait_def = match self.get_trait_def(span, trait_def_id) {
759 Ok(trait_def) => trait_def,
760 Err(ErrorReported) => {
761 // No convenient way to recover from a cycle here. Just bail. Sorry!
762 self.tcx().sess.abort_if_errors();
763 bug!("ErrorReported returned, but no errors reports?")
767 match trait_segment.parameters {
768 hir::AngleBracketedParameters(_) => {
769 // For now, require that parenthetical notation be used
770 // only with `Fn()` etc.
771 if !self.tcx().sess.features.borrow().unboxed_closures && trait_def.paren_sugar {
772 emit_feature_err(&self.tcx().sess.parse_sess,
773 "unboxed_closures", span, GateIssue::Language,
775 the precise format of `Fn`-family traits' \
776 type parameters is subject to change. \
777 Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead");
780 hir::ParenthesizedParameters(_) => {
781 // For now, require that parenthetical notation be used
782 // only with `Fn()` etc.
783 if !self.tcx().sess.features.borrow().unboxed_closures && !trait_def.paren_sugar {
784 emit_feature_err(&self.tcx().sess.parse_sess,
785 "unboxed_closures", span, GateIssue::Language,
787 parenthetical notation is only stable when used with `Fn`-family traits");
792 self.create_substs_for_ast_path(rscope,
795 &trait_segment.parameters,
799 fn trait_defines_associated_type_named(&self,
801 assoc_name: ast::Name)
804 self.tcx().associated_items(trait_def_id).any(|item| {
805 item.kind == ty::AssociatedKind::Type && item.name == assoc_name
809 fn ast_type_binding_to_poly_projection_predicate(
811 path_id: ast::NodeId,
812 trait_ref: ty::PolyTraitRef<'tcx>,
813 binding: &ConvertedBinding<'tcx>)
814 -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
816 let tcx = self.tcx();
818 // Given something like `U : SomeTrait<T=X>`, we want to produce a
819 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
820 // subtle in the event that `T` is defined in a supertrait of
821 // `SomeTrait`, because in that case we need to upcast.
823 // That is, consider this case:
826 // trait SubTrait : SuperTrait<int> { }
827 // trait SuperTrait<A> { type T; }
829 // ... B : SubTrait<T=foo> ...
832 // We want to produce `<B as SuperTrait<int>>::T == foo`.
834 // Find any late-bound regions declared in `ty` that are not
835 // declared in the trait-ref. These are not wellformed.
839 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
840 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
841 let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
842 let late_bound_in_ty = tcx.collect_referenced_late_bound_regions(&ty::Binder(binding.ty));
843 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
844 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
845 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
846 let br_name = match *br {
847 ty::BrNamed(_, name, _) => name,
851 "anonymous bound region {:?} in binding but not trait ref",
856 lint::builtin::HR_LIFETIME_IN_ASSOC_TYPE,
859 format!("binding for associated type `{}` references lifetime `{}`, \
860 which does not appear in the trait input types",
861 binding.item_name, br_name));
864 // Simple case: X is defined in the current trait.
865 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
866 return Ok(trait_ref.map_bound(|trait_ref| {
867 ty::ProjectionPredicate {
868 projection_ty: ty::ProjectionTy {
869 trait_ref: trait_ref,
870 item_name: binding.item_name,
877 // Otherwise, we have to walk through the supertraits to find
879 self.ensure_super_predicates(binding.span, trait_ref.def_id())?;
882 traits::supertraits(tcx, trait_ref.clone())
883 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), binding.item_name));
885 let candidate = self.one_bound_for_assoc_type(candidates,
886 &trait_ref.to_string(),
887 &binding.item_name.as_str(),
890 Ok(candidate.map_bound(|trait_ref| {
891 ty::ProjectionPredicate {
892 projection_ty: ty::ProjectionTy {
893 trait_ref: trait_ref,
894 item_name: binding.item_name,
901 fn ast_path_to_ty(&self,
902 rscope: &RegionScope,
905 item_segment: &hir::PathSegment)
908 let tcx = self.tcx();
909 let decl_ty = match self.get_item_type(span, did) {
911 Err(ErrorReported) => {
912 return tcx.types.err;
916 let substs = self.ast_path_substs_for_ty(rscope,
921 // FIXME(#12938): This is a hack until we have full support for DST.
922 if Some(did) == self.tcx().lang_items.owned_box() {
923 assert_eq!(substs.types().count(), 1);
924 return self.tcx().mk_box(substs.type_at(0));
927 decl_ty.subst(self.tcx(), substs)
930 /// Transform a PolyTraitRef into a PolyExistentialTraitRef by
931 /// removing the dummy Self type (TRAIT_OBJECT_DUMMY_SELF).
932 fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
933 -> ty::ExistentialTraitRef<'tcx> {
934 assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
935 ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
938 fn trait_path_to_object_type(&self,
939 rscope: &RegionScope,
942 trait_path_ref_id: ast::NodeId,
943 trait_segment: &hir::PathSegment,
945 partitioned_bounds: PartitionedBounds)
947 let tcx = self.tcx();
949 let mut projection_bounds = vec![];
950 let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
951 let principal = self.ast_path_to_poly_trait_ref(rscope,
957 &mut projection_bounds);
959 let PartitionedBounds { trait_bounds,
963 let (auto_traits, trait_bounds) = split_auto_traits(tcx, trait_bounds);
965 if !trait_bounds.is_empty() {
966 let b = &trait_bounds[0];
967 let span = b.trait_ref.path.span;
968 struct_span_err!(self.tcx().sess, span, E0225,
969 "only Send/Sync traits can be used as additional traits in a trait object")
970 .span_label(span, &format!("non-Send/Sync additional trait"))
974 // Erase the dummy_self (TRAIT_OBJECT_DUMMY_SELF) used above.
975 let existential_principal = principal.map_bound(|trait_ref| {
976 self.trait_ref_to_existential(trait_ref)
978 let existential_projections = projection_bounds.iter().map(|bound| {
979 bound.map_bound(|b| {
980 let p = b.projection_ty;
981 ty::ExistentialProjection {
982 trait_ref: self.trait_ref_to_existential(p.trait_ref),
983 item_name: p.item_name,
989 // ensure the super predicates and stop if we encountered an error
990 if self.ensure_super_predicates(span, principal.def_id()).is_err() {
991 return tcx.types.err;
994 // check that there are no gross object safety violations,
995 // most importantly, that the supertraits don't contain Self,
997 let object_safety_violations =
998 tcx.astconv_object_safety_violations(principal.def_id());
999 if !object_safety_violations.is_empty() {
1000 tcx.report_object_safety_error(
1001 span, principal.def_id(), object_safety_violations)
1003 return tcx.types.err;
1006 let mut associated_types = FxHashSet::default();
1007 for tr in traits::supertraits(tcx, principal) {
1008 associated_types.extend(tcx.associated_items(tr.def_id())
1009 .filter(|item| item.kind == ty::AssociatedKind::Type)
1010 .map(|item| (tr.def_id(), item.name)));
1013 for projection_bound in &projection_bounds {
1014 let pair = (projection_bound.0.projection_ty.trait_ref.def_id,
1015 projection_bound.0.projection_ty.item_name);
1016 associated_types.remove(&pair);
1019 for (trait_def_id, name) in associated_types {
1020 struct_span_err!(tcx.sess, span, E0191,
1021 "the value of the associated type `{}` (from the trait `{}`) must be specified",
1023 tcx.item_path_str(trait_def_id))
1024 .span_label(span, &format!(
1025 "missing associated type `{}` value", name))
1030 iter::once(ty::ExistentialPredicate::Trait(*existential_principal.skip_binder()))
1031 .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
1032 .chain(existential_projections
1033 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
1034 .collect::<AccumulateVec<[_; 8]>>();
1035 v.sort_by(|a, b| a.cmp(tcx, b));
1036 let existential_predicates = ty::Binder(tcx.mk_existential_predicates(v.into_iter()));
1038 let region_bound = self.compute_object_lifetime_bound(span,
1040 existential_predicates);
1042 let region_bound = match region_bound {
1045 tcx.mk_region(match rscope.object_lifetime_default(span) {
1048 span_err!(self.tcx().sess, span, E0228,
1049 "the lifetime bound for this object type cannot be deduced \
1050 from context; please supply an explicit bound");
1057 debug!("region_bound: {:?}", region_bound);
1059 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1060 debug!("trait_object_type: {:?}", ty);
1064 fn report_ambiguous_associated_type(&self,
1069 struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
1070 .span_label(span, &format!("ambiguous associated type"))
1071 .note(&format!("specify the type using the syntax `<{} as {}>::{}`",
1072 type_str, trait_str, name))
1077 // Search for a bound on a type parameter which includes the associated item
1078 // given by assoc_name. ty_param_node_id is the node id for the type parameter
1079 // (which might be `Self`, but only if it is the `Self` of a trait, not an
1080 // impl). This function will fail if there are no suitable bounds or there is
1082 fn find_bound_for_assoc_item(&self,
1083 ty_param_node_id: ast::NodeId,
1084 ty_param_name: ast::Name,
1085 assoc_name: ast::Name,
1087 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1089 let tcx = self.tcx();
1091 let bounds = match self.get_type_parameter_bounds(span, ty_param_node_id) {
1093 Err(ErrorReported) => {
1094 return Err(ErrorReported);
1098 // Ensure the super predicates and stop if we encountered an error.
1099 if bounds.iter().any(|b| self.ensure_super_predicates(span, b.def_id()).is_err()) {
1100 return Err(ErrorReported);
1103 // Check that there is exactly one way to find an associated type with the
1105 let suitable_bounds =
1106 traits::transitive_bounds(tcx, &bounds)
1107 .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
1109 self.one_bound_for_assoc_type(suitable_bounds,
1110 &ty_param_name.as_str(),
1111 &assoc_name.as_str(),
1116 // Checks that bounds contains exactly one element and reports appropriate
1117 // errors otherwise.
1118 fn one_bound_for_assoc_type<I>(&self,
1120 ty_param_name: &str,
1123 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1124 where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
1126 let bound = match bounds.next() {
1127 Some(bound) => bound,
1129 struct_span_err!(self.tcx().sess, span, E0220,
1130 "associated type `{}` not found for `{}`",
1133 .span_label(span, &format!("associated type `{}` not found", assoc_name))
1135 return Err(ErrorReported);
1139 if let Some(bound2) = bounds.next() {
1140 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
1141 let mut err = struct_span_err!(
1142 self.tcx().sess, span, E0221,
1143 "ambiguous associated type `{}` in bounds of `{}`",
1146 err.span_label(span, &format!("ambiguous associated type `{}`", assoc_name));
1148 for bound in bounds {
1149 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
1150 item.kind == ty::AssociatedKind::Type && item.name == assoc_name
1152 .and_then(|item| self.tcx().hir.span_if_local(item.def_id));
1154 if let Some(span) = bound_span {
1155 err.span_label(span, &format!("ambiguous `{}` from `{}`",
1159 span_note!(&mut err, span,
1160 "associated type `{}` could derive from `{}`",
1171 // Create a type from a path to an associated type.
1172 // For a path A::B::C::D, ty and ty_path_def are the type and def for A::B::C
1173 // and item_segment is the path segment for D. We return a type and a def for
1175 // Will fail except for T::A and Self::A; i.e., if ty/ty_path_def are not a type
1176 // parameter or Self.
1177 pub fn associated_path_def_to_ty(&self,
1178 ref_id: ast::NodeId,
1182 item_segment: &hir::PathSegment)
1185 let tcx = self.tcx();
1186 let assoc_name = item_segment.name;
1188 debug!("associated_path_def_to_ty: {:?}::{}", ty, assoc_name);
1190 tcx.prohibit_type_params(slice::ref_slice(item_segment));
1192 // Find the type of the associated item, and the trait where the associated
1193 // item is declared.
1194 let bound = match (&ty.sty, ty_path_def) {
1195 (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
1196 // `Self` in an impl of a trait - we have a concrete self type and a
1198 let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
1199 let trait_ref = if let Some(free_substs) = self.get_free_substs() {
1200 trait_ref.subst(tcx, free_substs)
1205 if self.ensure_super_predicates(span, trait_ref.def_id).is_err() {
1206 return (tcx.types.err, Def::Err);
1210 traits::supertraits(tcx, ty::Binder(trait_ref))
1211 .filter(|r| self.trait_defines_associated_type_named(r.def_id(),
1214 match self.one_bound_for_assoc_type(candidates,
1216 &assoc_name.as_str(),
1219 Err(ErrorReported) => return (tcx.types.err, Def::Err),
1222 (&ty::TyParam(_), Def::SelfTy(Some(trait_did), None)) => {
1223 let trait_node_id = tcx.hir.as_local_node_id(trait_did).unwrap();
1224 match self.find_bound_for_assoc_item(trait_node_id,
1225 keywords::SelfType.name(),
1229 Err(ErrorReported) => return (tcx.types.err, Def::Err),
1232 (&ty::TyParam(_), Def::TyParam(param_did)) => {
1233 let param_node_id = tcx.hir.as_local_node_id(param_did).unwrap();
1234 let param_name = tcx.type_parameter_def(param_node_id).name;
1235 match self.find_bound_for_assoc_item(param_node_id,
1240 Err(ErrorReported) => return (tcx.types.err, Def::Err),
1244 // Don't print TyErr to the user.
1245 if !ty.references_error() {
1246 self.report_ambiguous_associated_type(span,
1249 &assoc_name.as_str());
1251 return (tcx.types.err, Def::Err);
1255 let trait_did = bound.0.def_id;
1256 let ty = self.projected_ty_from_poly_trait_ref(span, bound, assoc_name);
1258 let item = tcx.associated_items(trait_did).find(|i| i.name == assoc_name);
1259 let def_id = item.expect("missing associated type").def_id;
1260 tcx.check_stability(def_id, ref_id, span);
1261 (ty, Def::AssociatedTy(def_id))
1264 fn qpath_to_ty(&self,
1265 rscope: &RegionScope,
1267 opt_self_ty: Option<Ty<'tcx>>,
1268 trait_def_id: DefId,
1269 trait_segment: &hir::PathSegment,
1270 item_segment: &hir::PathSegment)
1273 let tcx = self.tcx();
1275 tcx.prohibit_type_params(slice::ref_slice(item_segment));
1277 let self_ty = if let Some(ty) = opt_self_ty {
1280 let path_str = tcx.item_path_str(trait_def_id);
1281 self.report_ambiguous_associated_type(span,
1284 &item_segment.name.as_str());
1285 return tcx.types.err;
1288 debug!("qpath_to_ty: self_type={:?}", self_ty);
1290 let trait_ref = self.ast_path_to_mono_trait_ref(rscope,
1296 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1298 self.projected_ty(span, trait_ref, item_segment.name)
1301 /// Convert a type supplied as value for a type argument from AST into our
1302 /// our internal representation. This is the same as `ast_ty_to_ty` but that
1303 /// it applies the object lifetime default.
1307 /// * `this`, `rscope`: the surrounding context
1308 /// * `def`: the type parameter being instantiated (if available)
1309 /// * `region_substs`: a partial substitution consisting of
1310 /// only the region type parameters being supplied to this type.
1311 /// * `ast_ty`: the ast representation of the type being supplied
1312 fn ast_ty_arg_to_ty(&self,
1313 rscope: &RegionScope,
1314 def: Option<&ty::TypeParameterDef<'tcx>>,
1315 region_substs: &[Kind<'tcx>],
1319 let tcx = self.tcx();
1321 if let Some(def) = def {
1322 let object_lifetime_default = def.object_lifetime_default.subst(tcx, region_substs);
1323 let rscope1 = &ObjectLifetimeDefaultRscope::new(rscope, object_lifetime_default);
1324 self.ast_ty_to_ty(rscope1, ast_ty)
1326 self.ast_ty_to_ty(rscope, ast_ty)
1330 // Check a type Path and convert it to a Ty.
1331 pub fn def_to_ty(&self,
1332 rscope: &RegionScope,
1333 opt_self_ty: Option<Ty<'tcx>>,
1335 path_id: ast::NodeId,
1336 permit_variants: bool)
1338 let tcx = self.tcx();
1340 debug!("base_def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
1341 path.def, opt_self_ty, path.segments);
1343 let span = path.span;
1345 Def::Trait(trait_def_id) => {
1346 // N.B. this case overlaps somewhat with
1347 // TyTraitObject, see that fn for details
1349 assert_eq!(opt_self_ty, None);
1350 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1352 self.trait_path_to_object_type(rscope,
1356 path.segments.last().unwrap(),
1358 partition_bounds(&[]))
1360 Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) | Def::Union(did) => {
1361 assert_eq!(opt_self_ty, None);
1362 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1363 self.ast_path_to_ty(rscope, span, did, path.segments.last().unwrap())
1365 Def::Variant(did) if permit_variants => {
1366 // Convert "variant type" as if it were a real type.
1367 // The resulting `Ty` is type of the variant's enum for now.
1368 assert_eq!(opt_self_ty, None);
1369 tcx.prohibit_type_params(path.segments.split_last().unwrap().1);
1370 self.ast_path_to_ty(rscope,
1372 tcx.parent_def_id(did).unwrap(),
1373 path.segments.last().unwrap())
1375 Def::TyParam(did) => {
1376 assert_eq!(opt_self_ty, None);
1377 tcx.prohibit_type_params(&path.segments);
1379 let node_id = tcx.hir.as_local_node_id(did).unwrap();
1380 let param = tcx.ty_param_defs.borrow().get(&node_id)
1381 .map(ty::ParamTy::for_def);
1382 if let Some(p) = param {
1385 // Only while computing defaults of earlier type
1386 // parameters can a type parameter be missing its def.
1387 struct_span_err!(tcx.sess, span, E0128,
1388 "type parameters with a default cannot use \
1389 forward declared identifiers")
1390 .span_label(span, &format!("defaulted type parameters \
1391 cannot be forward declared"))
1396 Def::SelfTy(_, Some(def_id)) => {
1397 // Self in impl (we know the concrete type).
1399 assert_eq!(opt_self_ty, None);
1400 tcx.prohibit_type_params(&path.segments);
1402 // FIXME: Self type is not always computed when we are here because type parameter
1403 // bounds may affect Self type and have to be converted before it.
1404 let ty = if def_id.is_local() {
1405 tcx.item_types.borrow().get(&def_id).cloned()
1407 Some(tcx.item_type(def_id))
1409 if let Some(ty) = ty {
1410 if let Some(free_substs) = self.get_free_substs() {
1411 ty.subst(tcx, free_substs)
1416 tcx.sess.span_err(span, "`Self` type is used before it's determined");
1420 Def::SelfTy(Some(_), None) => {
1422 assert_eq!(opt_self_ty, None);
1423 tcx.prohibit_type_params(&path.segments);
1426 Def::AssociatedTy(def_id) => {
1427 tcx.prohibit_type_params(&path.segments[..path.segments.len()-2]);
1428 let trait_did = tcx.parent_def_id(def_id).unwrap();
1429 self.qpath_to_ty(rscope,
1433 &path.segments[path.segments.len()-2],
1434 path.segments.last().unwrap())
1436 Def::PrimTy(prim_ty) => {
1437 assert_eq!(opt_self_ty, None);
1438 tcx.prim_ty_to_ty(&path.segments, prim_ty)
1441 self.set_tainted_by_errors();
1442 return self.tcx().types.err;
1444 _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1448 /// Parses the programmer's textual representation of a type into our
1449 /// internal notion of a type.
1450 pub fn ast_ty_to_ty(&self, rscope: &RegionScope, ast_ty: &hir::Ty) -> Ty<'tcx> {
1451 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?})",
1454 let tcx = self.tcx();
1456 let cache = self.ast_ty_to_ty_cache();
1457 if let Some(ty) = cache.borrow().get(&ast_ty.id) {
1461 let result_ty = match ast_ty.node {
1462 hir::TySlice(ref ty) => {
1463 tcx.mk_slice(self.ast_ty_to_ty(rscope, &ty))
1465 hir::TyPtr(ref mt) => {
1466 tcx.mk_ptr(ty::TypeAndMut {
1467 ty: self.ast_ty_to_ty(rscope, &mt.ty),
1471 hir::TyRptr(ref region, ref mt) => {
1472 let r = self.opt_ast_region_to_region(rscope, ast_ty.span, Some(region), None);
1473 debug!("TyRef r={:?}", r);
1475 &ObjectLifetimeDefaultRscope::new(
1477 ty::ObjectLifetimeDefault::Specific(r));
1478 let t = self.ast_ty_to_ty(rscope1, &mt.ty);
1479 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1484 hir::TyTup(ref fields) => {
1485 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(rscope, &t)))
1487 hir::TyBareFn(ref bf) => {
1488 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1489 let anon_scope = rscope.anon_type_scope();
1490 let bare_fn_ty = self.ty_of_method_or_bare_fn(bf.unsafety,
1498 // Find any late-bound regions declared in return type that do
1499 // not appear in the arguments. These are not wellformed.
1503 // for<'a> fn() -> &'a str <-- 'a is bad
1504 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1506 // Note that we do this check **here** and not in
1507 // `ty_of_bare_fn` because the latter is also used to make
1508 // the types for fn items, and we do not want to issue a
1509 // warning then. (Once we fix #32330, the regions we are
1510 // checking for here would be considered early bound
1512 let inputs = bare_fn_ty.sig.inputs();
1513 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1514 &inputs.map_bound(|i| i.to_owned()));
1515 let output = bare_fn_ty.sig.output();
1516 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1517 for br in late_bound_in_ret.difference(&late_bound_in_args) {
1518 let br_name = match *br {
1519 ty::BrNamed(_, name, _) => name,
1522 bf.decl.output.span(),
1523 "anonymous bound region {:?} in return but not args",
1528 lint::builtin::HR_LIFETIME_IN_ASSOC_TYPE,
1531 format!("return type references lifetime `{}`, \
1532 which does not appear in the trait input types",
1535 tcx.mk_fn_ptr(bare_fn_ty)
1537 hir::TyTraitObject(ref bounds) => {
1538 self.conv_object_ty_poly_trait_ref(rscope, ast_ty.span, bounds)
1540 hir::TyImplTrait(ref bounds) => {
1541 use collect::{compute_bounds, SizedByDefault};
1543 // Create the anonymized type.
1544 let def_id = tcx.hir.local_def_id(ast_ty.id);
1545 if let Some(anon_scope) = rscope.anon_type_scope() {
1546 let substs = anon_scope.fresh_substs(self, ast_ty.span);
1547 let ty = tcx.mk_anon(tcx.hir.local_def_id(ast_ty.id), substs);
1549 // Collect the bounds, i.e. the `A+B+'c` in `impl A+B+'c`.
1550 let bounds = compute_bounds(self, ty, bounds,
1551 SizedByDefault::Yes,
1554 let predicates = bounds.predicates(tcx, ty);
1555 let predicates = tcx.lift_to_global(&predicates).unwrap();
1556 tcx.predicates.borrow_mut().insert(def_id, ty::GenericPredicates {
1558 predicates: predicates
1563 span_err!(tcx.sess, ast_ty.span, E0562,
1564 "`impl Trait` not allowed outside of function \
1565 and inherent method return types");
1569 hir::TyPath(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1570 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1571 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1572 self.ast_ty_to_ty(rscope, qself)
1574 self.def_to_ty(rscope, opt_self_ty, path, ast_ty.id, false)
1576 hir::TyPath(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1577 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1578 let ty = self.ast_ty_to_ty(rscope, qself);
1580 let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
1585 self.associated_path_def_to_ty(ast_ty.id, ast_ty.span, ty, def, segment).0
1587 hir::TyArray(ref ty, length) => {
1588 if let Ok(length) = eval_length(tcx.global_tcx(), length, "array length") {
1589 tcx.mk_array(self.ast_ty_to_ty(rscope, &ty), length)
1591 self.tcx().types.err
1594 hir::TyTypeof(ref _e) => {
1595 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1596 "`typeof` is a reserved keyword but unimplemented")
1597 .span_label(ast_ty.span, &format!("reserved keyword"))
1603 // TyInfer also appears as the type of arguments or return
1604 // values in a ExprClosure, or as
1605 // the type of local variables. Both of these cases are
1606 // handled specially and will not descend into this routine.
1607 self.ty_infer(ast_ty.span)
1611 cache.borrow_mut().insert(ast_ty.id, result_ty);
1616 pub fn ty_of_arg(&self,
1617 rscope: &RegionScope,
1619 expected_ty: Option<Ty<'tcx>>)
1623 hir::TyInfer if expected_ty.is_some() => expected_ty.unwrap(),
1624 hir::TyInfer => self.ty_infer(ty.span),
1625 _ => self.ast_ty_to_ty(rscope, ty),
1629 pub fn ty_of_method(&self,
1630 sig: &hir::MethodSig,
1631 opt_self_value_ty: Option<Ty<'tcx>>,
1632 body: Option<hir::BodyId>,
1633 anon_scope: Option<AnonTypeScope>)
1634 -> &'tcx ty::BareFnTy<'tcx> {
1635 self.ty_of_method_or_bare_fn(sig.unsafety,
1644 pub fn ty_of_bare_fn(&self,
1645 unsafety: hir::Unsafety,
1649 anon_scope: Option<AnonTypeScope>)
1650 -> &'tcx ty::BareFnTy<'tcx> {
1651 self.ty_of_method_or_bare_fn(unsafety, abi, None, decl, Some(body), None, anon_scope)
1654 fn ty_of_method_or_bare_fn(&self,
1655 unsafety: hir::Unsafety,
1657 opt_self_value_ty: Option<Ty<'tcx>>,
1659 body: Option<hir::BodyId>,
1660 arg_anon_scope: Option<AnonTypeScope>,
1661 ret_anon_scope: Option<AnonTypeScope>)
1662 -> &'tcx ty::BareFnTy<'tcx>
1664 debug!("ty_of_method_or_bare_fn");
1666 // New region names that appear inside of the arguments of the function
1667 // declaration are bound to that function type.
1668 let rb = MaybeWithAnonTypes::new(BindingRscope::new(), arg_anon_scope);
1670 let input_tys: Vec<Ty> =
1671 decl.inputs.iter().map(|a| self.ty_of_arg(&rb, a, None)).collect();
1673 let has_self = opt_self_value_ty.is_some();
1674 let explicit_self = opt_self_value_ty.map(|self_value_ty| {
1675 ExplicitSelf::determine(self_value_ty, input_tys[0])
1678 let implied_output_region = match explicit_self {
1679 // `implied_output_region` is the region that will be assumed for any
1680 // region parameters in the return type. In accordance with the rules for
1681 // lifetime elision, we can determine it in two ways. First (determined
1682 // here), if self is by-reference, then the implied output region is the
1683 // region of the self parameter.
1684 Some(ExplicitSelf::ByReference(region, _)) => Ok(*region),
1686 // Second, if there was exactly one lifetime (either a substitution or a
1687 // reference) in the arguments, then any anonymous regions in the output
1688 // have that lifetime.
1690 let arg_tys = &input_tys[has_self as usize..];
1691 let arg_params = has_self as usize..input_tys.len();
1692 self.find_implied_output_region(arg_tys, body, arg_params)
1697 let output_ty = match decl.output {
1698 hir::Return(ref output) =>
1699 self.convert_ty_with_lifetime_elision(implied_output_region,
1702 hir::DefaultReturn(..) => self.tcx().mk_nil(),
1705 debug!("ty_of_method_or_bare_fn: output_ty={:?}", output_ty);
1707 self.tcx().mk_bare_fn(ty::BareFnTy {
1710 sig: ty::Binder(self.tcx().mk_fn_sig(
1711 input_tys.into_iter(),
1718 pub fn ty_of_closure(&self,
1719 unsafety: hir::Unsafety,
1722 expected_sig: Option<ty::FnSig<'tcx>>)
1723 -> ty::ClosureTy<'tcx>
1725 debug!("ty_of_closure(expected_sig={:?})",
1728 // new region names that appear inside of the fn decl are bound to
1729 // that function type
1730 let rb = rscope::BindingRscope::new();
1732 let input_tys = decl.inputs.iter().enumerate().map(|(i, a)| {
1733 let expected_arg_ty = expected_sig.as_ref().and_then(|e| {
1734 // no guarantee that the correct number of expected args
1736 if i < e.inputs().len() {
1742 self.ty_of_arg(&rb, a, expected_arg_ty)
1745 let expected_ret_ty = expected_sig.as_ref().map(|e| e.output());
1747 let is_infer = match decl.output {
1748 hir::Return(ref output) if output.node == hir::TyInfer => true,
1749 hir::DefaultReturn(..) => true,
1753 let output_ty = match decl.output {
1754 _ if is_infer && expected_ret_ty.is_some() =>
1755 expected_ret_ty.unwrap(),
1756 _ if is_infer => self.ty_infer(decl.output.span()),
1757 hir::Return(ref output) =>
1758 self.ast_ty_to_ty(&rb, &output),
1759 hir::DefaultReturn(..) => bug!(),
1762 debug!("ty_of_closure: output_ty={:?}", output_ty);
1767 sig: ty::Binder(self.tcx().mk_fn_sig(input_tys, output_ty, decl.variadic)),
1771 fn conv_object_ty_poly_trait_ref(&self,
1772 rscope: &RegionScope,
1774 ast_bounds: &[hir::TyParamBound])
1777 let mut partitioned_bounds = partition_bounds(ast_bounds);
1779 let trait_bound = if !partitioned_bounds.trait_bounds.is_empty() {
1780 partitioned_bounds.trait_bounds.remove(0)
1782 span_err!(self.tcx().sess, span, E0224,
1783 "at least one non-builtin trait is required for an object type");
1784 return self.tcx().types.err;
1787 let trait_ref = &trait_bound.trait_ref;
1788 let trait_def_id = self.trait_def_id(trait_ref);
1789 self.trait_path_to_object_type(rscope,
1790 trait_ref.path.span,
1793 trait_ref.path.segments.last().unwrap(),
1798 /// Given the bounds on an object, determines what single region bound (if any) we can
1799 /// use to summarize this type. The basic idea is that we will use the bound the user
1800 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1801 /// for region bounds. It may be that we can derive no bound at all, in which case
1802 /// we return `None`.
1803 fn compute_object_lifetime_bound(&self,
1805 explicit_region_bounds: &[&hir::Lifetime],
1806 existential_predicates: ty::Binder<&'tcx ty::Slice<ty::ExistentialPredicate<'tcx>>>)
1807 -> Option<&'tcx ty::Region> // if None, use the default
1809 let tcx = self.tcx();
1811 debug!("compute_opt_region_bound(explicit_region_bounds={:?}, \
1812 existential_predicates={:?})",
1813 explicit_region_bounds,
1814 existential_predicates);
1816 if explicit_region_bounds.len() > 1 {
1817 span_err!(tcx.sess, explicit_region_bounds[1].span, E0226,
1818 "only a single explicit lifetime bound is permitted");
1821 if let Some(&r) = explicit_region_bounds.get(0) {
1822 // Explicitly specified region bound. Use that.
1823 return Some(self.ast_region_to_region(r));
1826 if let Some(principal) = existential_predicates.principal() {
1827 if let Err(ErrorReported) = self.ensure_super_predicates(span, principal.def_id()) {
1828 return Some(tcx.mk_region(ty::ReStatic));
1832 // No explicit region bound specified. Therefore, examine trait
1833 // bounds and see if we can derive region bounds from those.
1834 let derived_region_bounds =
1835 object_region_bounds(tcx, existential_predicates);
1837 // If there are no derived region bounds, then report back that we
1838 // can find no region bound. The caller will use the default.
1839 if derived_region_bounds.is_empty() {
1843 // If any of the derived region bounds are 'static, that is always
1845 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1846 return Some(tcx.mk_region(ty::ReStatic));
1849 // Determine whether there is exactly one unique region in the set
1850 // of derived region bounds. If so, use that. Otherwise, report an
1852 let r = derived_region_bounds[0];
1853 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1854 span_err!(tcx.sess, span, E0227,
1855 "ambiguous lifetime bound, explicit lifetime bound required");
1861 pub struct PartitionedBounds<'a> {
1862 pub trait_bounds: Vec<&'a hir::PolyTraitRef>,
1863 pub region_bounds: Vec<&'a hir::Lifetime>,
1866 /// Divides a list of general trait bounds into two groups: builtin bounds (Sync/Send) and the
1867 /// remaining general trait bounds.
1868 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1869 trait_bounds: Vec<&'b hir::PolyTraitRef>)
1870 -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
1872 let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.into_iter().partition(|bound| {
1873 match bound.trait_ref.path.def {
1874 Def::Trait(trait_did) => {
1875 // Checks whether `trait_did` refers to one of the builtin
1876 // traits, like `Send`, and adds it to `auto_traits` if so.
1877 if Some(trait_did) == tcx.lang_items.send_trait() ||
1878 Some(trait_did) == tcx.lang_items.sync_trait() {
1879 let segments = &bound.trait_ref.path.segments;
1880 let parameters = &segments[segments.len() - 1].parameters;
1881 if !parameters.types().is_empty() {
1882 check_type_argument_count(tcx, bound.trait_ref.path.span,
1883 parameters.types().len(), &[]);
1885 if !parameters.lifetimes().is_empty() {
1886 report_lifetime_number_error(tcx, bound.trait_ref.path.span,
1887 parameters.lifetimes().len(), 0);
1898 let auto_traits = auto_traits.into_iter().map(|tr| {
1899 if let Def::Trait(trait_did) = tr.trait_ref.path.def {
1904 }).collect::<Vec<_>>();
1906 (auto_traits, trait_bounds)
1909 /// Divides a list of bounds from the AST into two groups: general trait bounds and region bounds
1910 pub fn partition_bounds<'a, 'b, 'gcx, 'tcx>(ast_bounds: &'b [hir::TyParamBound])
1911 -> PartitionedBounds<'b>
1913 let mut region_bounds = Vec::new();
1914 let mut trait_bounds = Vec::new();
1915 for ast_bound in ast_bounds {
1917 hir::TraitTyParamBound(ref b, hir::TraitBoundModifier::None) => {
1918 trait_bounds.push(b);
1920 hir::TraitTyParamBound(_, hir::TraitBoundModifier::Maybe) => {}
1921 hir::RegionTyParamBound(ref l) => {
1922 region_bounds.push(l);
1928 trait_bounds: trait_bounds,
1929 region_bounds: region_bounds,
1933 fn check_type_argument_count(tcx: TyCtxt, span: Span, supplied: usize,
1934 ty_param_defs: &[ty::TypeParameterDef]) {
1935 let accepted = ty_param_defs.len();
1936 let required = ty_param_defs.iter().take_while(|x| x.default.is_none()) .count();
1937 if supplied < required {
1938 let expected = if required < accepted {
1943 let arguments_plural = if required == 1 { "" } else { "s" };
1945 struct_span_err!(tcx.sess, span, E0243,
1946 "wrong number of type arguments: {} {}, found {}",
1947 expected, required, supplied)
1949 &format!("{} {} type argument{}",
1954 } else if supplied > accepted {
1955 let expected = if required < accepted {
1956 format!("expected at most {}", accepted)
1958 format!("expected {}", accepted)
1960 let arguments_plural = if accepted == 1 { "" } else { "s" };
1962 struct_span_err!(tcx.sess, span, E0244,
1963 "wrong number of type arguments: {}, found {}",
1967 &format!("{} type argument{}",
1968 if accepted == 0 { "expected no" } else { &expected },
1975 fn report_lifetime_number_error(tcx: TyCtxt, span: Span, number: usize, expected: usize) {
1976 let label = if number < expected {
1978 format!("expected {} lifetime parameter", expected)
1980 format!("expected {} lifetime parameters", expected)
1983 let additional = number - expected;
1984 if additional == 1 {
1985 "unexpected lifetime parameter".to_string()
1987 format!("{} unexpected lifetime parameters", additional)
1990 struct_span_err!(tcx.sess, span, E0107,
1991 "wrong number of lifetime parameters: expected {}, found {}",
1993 .span_label(span, &label)
1997 // A helper struct for conveniently grouping a set of bounds which we pass to
1998 // and return from functions in multiple places.
1999 #[derive(PartialEq, Eq, Clone, Debug)]
2000 pub struct Bounds<'tcx> {
2001 pub region_bounds: Vec<&'tcx ty::Region>,
2002 pub implicitly_sized: bool,
2003 pub trait_bounds: Vec<ty::PolyTraitRef<'tcx>>,
2004 pub projection_bounds: Vec<ty::PolyProjectionPredicate<'tcx>>,
2007 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
2008 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
2009 -> Vec<ty::Predicate<'tcx>>
2011 let mut vec = Vec::new();
2013 // If it could be sized, and is, add the sized predicate
2014 if self.implicitly_sized {
2015 if let Some(sized) = tcx.lang_items.sized_trait() {
2016 let trait_ref = ty::TraitRef {
2018 substs: tcx.mk_substs_trait(param_ty, &[])
2020 vec.push(trait_ref.to_predicate());
2024 for ®ion_bound in &self.region_bounds {
2025 // account for the binder being introduced below; no need to shift `param_ty`
2026 // because, at present at least, it can only refer to early-bound regions
2027 let region_bound = tcx.mk_region(ty::fold::shift_region(*region_bound, 1));
2028 vec.push(ty::Binder(ty::OutlivesPredicate(param_ty, region_bound)).to_predicate());
2031 for bound_trait_ref in &self.trait_bounds {
2032 vec.push(bound_trait_ref.to_predicate());
2035 for projection in &self.projection_bounds {
2036 vec.push(projection.to_predicate());
2043 pub enum ExplicitSelf<'tcx> {
2045 ByReference(&'tcx ty::Region, hir::Mutability),
2049 impl<'tcx> ExplicitSelf<'tcx> {
2050 /// We wish to (for now) categorize an explicit self
2051 /// declaration like `self: SomeType` into either `self`,
2052 /// `&self`, `&mut self`, or `Box<self>`. We do this here
2053 /// by some simple pattern matching. A more precise check
2054 /// is done later in `check_method_self_type()`.
2059 /// impl Foo for &T {
2060 /// // Legal declarations:
2061 /// fn method1(self: &&T); // ExplicitSelf::ByReference
2062 /// fn method2(self: &T); // ExplicitSelf::ByValue
2063 /// fn method3(self: Box<&T>); // ExplicitSelf::ByBox
2065 /// // Invalid cases will be caught later by `check_method_self_type`:
2066 /// fn method_err1(self: &mut T); // ExplicitSelf::ByReference
2070 /// To do the check we just count the number of "modifiers"
2071 /// on each type and compare them. If they are the same or
2072 /// the impl has more, we call it "by value". Otherwise, we
2073 /// look at the outermost modifier on the method decl and
2074 /// call it by-ref, by-box as appropriate. For method1, for
2075 /// example, the impl type has one modifier, but the method
2076 /// type has two, so we end up with
2077 /// ExplicitSelf::ByReference.
2078 pub fn determine(untransformed_self_ty: Ty<'tcx>,
2079 self_arg_ty: Ty<'tcx>)
2080 -> ExplicitSelf<'tcx> {
2081 fn count_modifiers(ty: Ty) -> usize {
2083 ty::TyRef(_, mt) => count_modifiers(mt.ty) + 1,
2084 ty::TyBox(t) => count_modifiers(t) + 1,
2089 let impl_modifiers = count_modifiers(untransformed_self_ty);
2090 let method_modifiers = count_modifiers(self_arg_ty);
2092 if impl_modifiers >= method_modifiers {
2093 ExplicitSelf::ByValue
2095 match self_arg_ty.sty {
2096 ty::TyRef(r, mt) => ExplicitSelf::ByReference(r, mt.mutbl),
2097 ty::TyBox(_) => ExplicitSelf::ByBox,
2098 _ => ExplicitSelf::ByValue,