1 //! Conversion from AST representation of types to the `ty.rs` representation.
2 //! The main routine here is `ast_ty_to_ty()`; each use is parameterized by an
3 //! instance of `AstConv`.
5 use errors::{Applicability, DiagnosticId};
6 use hir::{self, GenericArg, GenericArgs};
8 use hir::def_id::DefId;
11 use middle::resolve_lifetime as rl;
12 use namespace::Namespace;
13 use rustc::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
15 use rustc::ty::{self, Ty, TyCtxt, ToPredicate, TypeFoldable};
16 use rustc::ty::{GenericParamDef, GenericParamDefKind};
17 use rustc::ty::subst::{Kind, Subst, Substs};
18 use rustc::ty::wf::object_region_bounds;
19 use rustc_data_structures::sync::Lrc;
20 use rustc_target::spec::abi;
21 use require_c_abi_if_variadic;
22 use smallvec::SmallVec;
24 use syntax::feature_gate::{GateIssue, emit_feature_err};
26 use syntax::util::lev_distance::find_best_match_for_name;
27 use syntax_pos::{DUMMY_SP, Span, MultiSpan};
28 use util::common::ErrorReported;
29 use util::nodemap::FxHashMap;
31 use std::collections::BTreeSet;
35 use super::{check_type_alias_enum_variants_enabled};
36 use rustc_data_structures::fx::FxHashSet;
39 pub struct PathSeg(pub DefId, pub usize);
41 pub trait AstConv<'gcx, 'tcx> {
42 fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
44 /// Returns the set of bounds in scope for the type parameter with
46 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId)
47 -> Lrc<ty::GenericPredicates<'tcx>>;
49 /// What lifetime should we use when a lifetime is omitted (and not elided)?
50 fn re_infer(&self, span: Span, _def: Option<&ty::GenericParamDef>)
51 -> Option<ty::Region<'tcx>>;
53 /// What type should we use when a type is omitted?
54 fn ty_infer(&self, span: Span) -> Ty<'tcx>;
56 /// Same as ty_infer, but with a known type parameter definition.
57 fn ty_infer_for_def(&self,
58 _def: &ty::GenericParamDef,
59 span: Span) -> Ty<'tcx> {
63 /// Projecting an associated type from a (potentially)
64 /// higher-ranked trait reference is more complicated, because of
65 /// the possibility of late-bound regions appearing in the
66 /// associated type binding. This is not legal in function
67 /// signatures for that reason. In a function body, we can always
68 /// handle it because we can use inference variables to remove the
69 /// late-bound regions.
70 fn projected_ty_from_poly_trait_ref(&self,
73 poly_trait_ref: ty::PolyTraitRef<'tcx>)
76 /// Normalize an associated type coming from the user.
77 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
79 /// Invoked when we encounter an error from some prior pass
80 /// (e.g., resolve) that is translated into a ty-error. This is
81 /// used to help suppress derived errors typeck might otherwise
83 fn set_tainted_by_errors(&self);
85 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
88 struct ConvertedBinding<'tcx> {
89 item_name: ast::Ident,
95 enum GenericArgPosition {
97 Value, // e.g., functions
101 /// Dummy type used for the `Self` of a `TraitRef` created for converting
102 /// a trait object, and which gets removed in `ExistentialTraitRef`.
103 /// This type must not appear anywhere in other converted types.
104 const TRAIT_OBJECT_DUMMY_SELF: ty::TyKind<'static> = ty::Infer(ty::FreshTy(0));
106 impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx> + 'o {
107 pub fn ast_region_to_region(&self,
108 lifetime: &hir::Lifetime,
109 def: Option<&ty::GenericParamDef>)
112 let tcx = self.tcx();
113 let lifetime_name = |def_id| {
114 tcx.hir().name(tcx.hir().as_local_node_id(def_id).unwrap()).as_interned_str()
117 let r = match tcx.named_region(lifetime.hir_id) {
118 Some(rl::Region::Static) => {
122 Some(rl::Region::LateBound(debruijn, id, _)) => {
123 let name = lifetime_name(id);
124 tcx.mk_region(ty::ReLateBound(debruijn,
125 ty::BrNamed(id, name)))
128 Some(rl::Region::LateBoundAnon(debruijn, index)) => {
129 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
132 Some(rl::Region::EarlyBound(index, id, _)) => {
133 let name = lifetime_name(id);
134 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
141 Some(rl::Region::Free(scope, id)) => {
142 let name = lifetime_name(id);
143 tcx.mk_region(ty::ReFree(ty::FreeRegion {
145 bound_region: ty::BrNamed(id, name)
148 // (*) -- not late-bound, won't change
152 self.re_infer(lifetime.span, def)
154 // This indicates an illegal lifetime
155 // elision. `resolve_lifetime` should have
156 // reported an error in this case -- but if
157 // not, let's error out.
158 tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
160 // Supply some dummy value. We don't have an
161 // `re_error`, annoyingly, so use `'static`.
167 debug!("ast_region_to_region(lifetime={:?}) yields {:?}",
174 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
175 /// returns an appropriate set of substitutions for this particular reference to `I`.
176 pub fn ast_path_substs_for_ty(&self,
179 item_segment: &hir::PathSegment)
180 -> &'tcx Substs<'tcx>
182 let (substs, assoc_bindings, _) = item_segment.with_generic_args(|generic_args| {
183 self.create_substs_for_ast_path(
187 item_segment.infer_types,
192 assoc_bindings.first().map(|b| Self::prohibit_assoc_ty_binding(self.tcx(), b.span));
197 /// Report error if there is an explicit type parameter when using `impl Trait`.
201 seg: &hir::PathSegment,
202 generics: &ty::Generics,
204 let explicit = !seg.infer_types;
205 let impl_trait = generics.params.iter().any(|param| match param.kind {
206 ty::GenericParamDefKind::Type {
207 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), ..
212 if explicit && impl_trait {
213 let mut err = struct_span_err! {
217 "cannot provide explicit type parameters when `impl Trait` is \
218 used in argument position."
227 /// Check that the correct number of generic arguments have been provided.
228 /// Used specifically for function calls.
229 pub fn check_generic_arg_count_for_call(
233 seg: &hir::PathSegment,
234 is_method_call: bool,
236 let empty_args = P(hir::GenericArgs {
237 args: HirVec::new(), bindings: HirVec::new(), parenthesized: false,
239 let suppress_mismatch = Self::check_impl_trait(tcx, span, seg, &def);
240 Self::check_generic_arg_count(
244 if let Some(ref args) = seg.args {
250 GenericArgPosition::MethodCall
252 GenericArgPosition::Value
254 def.parent.is_none() && def.has_self, // `has_self`
255 seg.infer_types || suppress_mismatch, // `infer_types`
259 /// Check that the correct number of generic arguments have been provided.
260 /// This is used both for datatypes and function calls.
261 fn check_generic_arg_count(
265 args: &hir::GenericArgs,
266 position: GenericArgPosition,
269 ) -> (bool, Option<Vec<Span>>) {
270 // At this stage we are guaranteed that the generic arguments are in the correct order, e.g.
271 // that lifetimes will proceed types. So it suffices to check the number of each generic
272 // arguments in order to validate them with respect to the generic parameters.
273 let param_counts = def.own_counts();
274 let arg_counts = args.own_counts();
275 let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
277 let mut defaults: ty::GenericParamCount = Default::default();
278 for param in &def.params {
280 GenericParamDefKind::Lifetime => {}
281 GenericParamDefKind::Type { has_default, .. } => {
282 defaults.types += has_default as usize
287 if position != GenericArgPosition::Type && !args.bindings.is_empty() {
288 AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span);
291 // Prohibit explicit lifetime arguments if late-bound lifetime parameters are present.
292 if !infer_lifetimes {
293 if let Some(span_late) = def.has_late_bound_regions {
294 let msg = "cannot specify lifetime arguments explicitly \
295 if late bound lifetime parameters are present";
296 let note = "the late bound lifetime parameter is introduced here";
297 let span = args.args[0].span();
298 if position == GenericArgPosition::Value
299 && arg_counts.lifetimes != param_counts.lifetimes {
300 let mut err = tcx.sess.struct_span_err(span, msg);
301 err.span_note(span_late, note);
305 let mut multispan = MultiSpan::from_span(span);
306 multispan.push_span_label(span_late, note.to_string());
307 tcx.lint_node(lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS,
308 args.args[0].id(), multispan, msg);
309 return (false, None);
314 let check_kind_count = |kind,
319 // We enforce the following: `required` <= `provided` <= `permitted`.
320 // For kinds without defaults (i.e., lifetimes), `required == permitted`.
321 // For other kinds (i.e., types), `permitted` may be greater than `required`.
322 if required <= provided && provided <= permitted {
323 return (false, None);
326 // Unfortunately lifetime and type parameter mismatches are typically styled
327 // differently in diagnostics, which means we have a few cases to consider here.
328 let (bound, quantifier) = if required != permitted {
329 if provided < required {
330 (required, "at least ")
331 } else { // provided > permitted
332 (permitted, "at most ")
338 let mut potential_assoc_types: Option<Vec<Span>> = None;
339 let (spans, label) = if required == permitted && provided > permitted {
340 // In the case when the user has provided too many arguments,
341 // we want to point to the unexpected arguments.
342 let spans: Vec<Span> = args.args[offset+permitted .. offset+provided]
344 .map(|arg| arg.span())
346 potential_assoc_types = Some(spans.clone());
347 (spans, format!( "unexpected {} argument", kind))
349 (vec![span], format!(
350 "expected {}{} {} argument{}",
354 if bound != 1 { "s" } else { "" },
358 let mut err = tcx.sess.struct_span_err_with_code(
361 "wrong number of {} arguments: expected {}{}, found {}",
367 DiagnosticId::Error("E0107".into())
370 err.span_label(span, label.as_str());
374 (provided > required, // `suppress_error`
375 potential_assoc_types)
378 if !infer_lifetimes || arg_counts.lifetimes > param_counts.lifetimes {
381 param_counts.lifetimes,
382 param_counts.lifetimes,
383 arg_counts.lifetimes,
388 || arg_counts.types > param_counts.types - defaults.types - has_self as usize {
391 param_counts.types - defaults.types - has_self as usize,
392 param_counts.types - has_self as usize,
394 arg_counts.lifetimes,
401 /// Creates the relevant generic argument substitutions
402 /// corresponding to a set of generic parameters. This is a
403 /// rather complex little function. Let me try to explain the
404 /// role of each of its parameters:
406 /// To start, we are given the `def_id` of the thing we are
407 /// creating the substitutions for, and a partial set of
408 /// substitutions `parent_substs`. In general, the substitutions
409 /// for an item begin with substitutions for all the "parents" of
410 /// that item -- e.g., for a method it might include the
411 /// parameters from the impl.
413 /// Therefore, the method begins by walking down these parents,
414 /// starting with the outermost parent and proceed inwards until
415 /// it reaches `def_id`. For each parent `P`, it will check `parent_substs`
416 /// first to see if the parent's substitutions are listed in there. If so,
417 /// we can append those and move on. Otherwise, it invokes the
418 /// three callback functions:
420 /// - `args_for_def_id`: given the def-id `P`, supplies back the
421 /// generic arguments that were given to that parent from within
422 /// the path; so e.g., if you have `<T as Foo>::Bar`, the def-id
423 /// might refer to the trait `Foo`, and the arguments might be
424 /// `[T]`. The boolean value indicates whether to infer values
425 /// for arguments whose values were not explicitly provided.
426 /// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`,
427 /// instantiate a `Kind`.
428 /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then
429 /// creates a suitable inference variable.
430 pub fn create_substs_for_generic_args<'a, 'b>(
431 tcx: TyCtxt<'a, 'gcx, 'tcx>,
433 parent_substs: &[Kind<'tcx>],
435 self_ty: Option<Ty<'tcx>>,
436 args_for_def_id: impl Fn(DefId) -> (Option<&'b GenericArgs>, bool),
437 provided_kind: impl Fn(&GenericParamDef, &GenericArg) -> Kind<'tcx>,
438 inferred_kind: impl Fn(Option<&[Kind<'tcx>]>, &GenericParamDef, bool) -> Kind<'tcx>,
439 ) -> &'tcx Substs<'tcx> {
440 // Collect the segments of the path; we need to substitute arguments
441 // for parameters throughout the entire path (wherever there are
442 // generic parameters).
443 let mut parent_defs = tcx.generics_of(def_id);
444 let count = parent_defs.count();
445 let mut stack = vec![(def_id, parent_defs)];
446 while let Some(def_id) = parent_defs.parent {
447 parent_defs = tcx.generics_of(def_id);
448 stack.push((def_id, parent_defs));
451 // We manually build up the substitution, rather than using convenience
452 // methods in `subst.rs`, so that we can iterate over the arguments and
453 // parameters in lock-step linearly, instead of trying to match each pair.
454 let mut substs: SmallVec<[Kind<'tcx>; 8]> = SmallVec::with_capacity(count);
456 // Iterate over each segment of the path.
457 while let Some((def_id, defs)) = stack.pop() {
458 let mut params = defs.params.iter().peekable();
460 // If we have already computed substitutions for parents, we can use those directly.
461 while let Some(¶m) = params.peek() {
462 if let Some(&kind) = parent_substs.get(param.index as usize) {
470 // `Self` is handled first, unless it's been handled in `parent_substs`.
472 if let Some(¶m) = params.peek() {
473 if param.index == 0 {
474 if let GenericParamDefKind::Type { .. } = param.kind {
475 substs.push(self_ty.map(|ty| ty.into())
476 .unwrap_or_else(|| inferred_kind(None, param, true)));
483 // Check whether this segment takes generic arguments and the user has provided any.
484 let (generic_args, infer_types) = args_for_def_id(def_id);
486 let mut args = generic_args.iter().flat_map(|generic_args| generic_args.args.iter())
490 // We're going to iterate through the generic arguments that the user
491 // provided, matching them with the generic parameters we expect.
492 // Mismatches can occur as a result of elided lifetimes, or for malformed
493 // input. We try to handle both sensibly.
494 match (args.peek(), params.peek()) {
495 (Some(&arg), Some(¶m)) => {
496 match (arg, ¶m.kind) {
497 (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime)
498 | (GenericArg::Type(_), GenericParamDefKind::Type { .. }) => {
499 substs.push(provided_kind(param, arg));
503 (GenericArg::Lifetime(_), GenericParamDefKind::Type { .. }) => {
504 // We expected a type argument, but got a lifetime
505 // argument. This is an error, but we need to handle it
506 // gracefully so we can report sensible errors. In this
507 // case, we're simply going to infer this argument.
510 (GenericArg::Type(_), GenericParamDefKind::Lifetime) => {
511 // We expected a lifetime argument, but got a type
512 // argument. That means we're inferring the lifetimes.
513 substs.push(inferred_kind(None, param, infer_types));
519 // We should never be able to reach this point with well-formed input.
520 // Getting to this point means the user supplied more arguments than
521 // there are parameters.
524 (None, Some(¶m)) => {
525 // If there are fewer arguments than parameters, it means
526 // we're inferring the remaining arguments.
528 GenericParamDefKind::Lifetime | GenericParamDefKind::Type { .. } => {
529 let kind = inferred_kind(Some(&substs), param, infer_types);
536 (None, None) => break,
541 tcx.intern_substs(&substs)
544 /// Given the type/region arguments provided to some path (along with
545 /// an implicit `Self`, if this is a trait reference) returns the complete
546 /// set of substitutions. This may involve applying defaulted type parameters.
548 /// Note that the type listing given here is *exactly* what the user provided.
549 fn create_substs_for_ast_path(&self,
552 generic_args: &hir::GenericArgs,
554 self_ty: Option<Ty<'tcx>>)
555 -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>, Option<Vec<Span>>)
557 // If the type is parameterized by this region, then replace this
558 // region with the current anon region binding (in other words,
559 // whatever & would get replaced with).
560 debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
562 def_id, self_ty, generic_args);
564 let tcx = self.tcx();
565 let generic_params = tcx.generics_of(def_id);
567 // If a self-type was declared, one should be provided.
568 assert_eq!(generic_params.has_self, self_ty.is_some());
570 let has_self = generic_params.has_self;
571 let (_, potential_assoc_types) = Self::check_generic_arg_count(
576 GenericArgPosition::Type,
581 let is_object = self_ty.map_or(false, |ty| ty.sty == TRAIT_OBJECT_DUMMY_SELF);
582 let default_needs_object_self = |param: &ty::GenericParamDef| {
583 if let GenericParamDefKind::Type { has_default, .. } = param.kind {
584 if is_object && has_default {
585 if tcx.at(span).type_of(param.def_id).has_self_ty() {
586 // There is no suitable inference default for a type parameter
587 // that references self, in an object type.
596 let substs = Self::create_substs_for_generic_args(
602 // Provide the generic args, and whether types should be inferred.
603 |_| (Some(generic_args), infer_types),
604 // Provide substitutions for parameters for which (valid) arguments have been provided.
606 match (¶m.kind, arg) {
607 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
608 self.ast_region_to_region(<, Some(param)).into()
610 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
611 self.ast_ty_to_ty(&ty).into()
616 // Provide substitutions for parameters for which arguments are inferred.
617 |substs, param, infer_types| {
619 GenericParamDefKind::Lifetime => tcx.types.re_static.into(),
620 GenericParamDefKind::Type { has_default, .. } => {
621 if !infer_types && has_default {
622 // No type parameter provided, but a default exists.
624 // If we are converting an object type, then the
625 // `Self` parameter is unknown. However, some of the
626 // other type parameters may reference `Self` in their
627 // defaults. This will lead to an ICE if we are not
629 if default_needs_object_self(param) {
630 struct_span_err!(tcx.sess, span, E0393,
631 "the type parameter `{}` must be explicitly \
635 format!("missing reference to `{}`", param.name))
636 .note(&format!("because of the default `Self` reference, \
637 type parameters must be specified on object \
642 // This is a default type parameter.
645 tcx.at(span).type_of(param.def_id)
646 .subst_spanned(tcx, substs.unwrap(), Some(span))
649 } else if infer_types {
650 // No type parameters were provided, we can infer all.
651 if !default_needs_object_self(param) {
652 self.ty_infer_for_def(param, span).into()
654 self.ty_infer(span).into()
657 // We've already errored above about the mismatch.
665 let assoc_bindings = generic_args.bindings.iter().map(|binding| {
667 item_name: binding.ident,
668 ty: self.ast_ty_to_ty(&binding.ty),
673 debug!("create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
674 generic_params, self_ty, substs);
676 (substs, assoc_bindings, potential_assoc_types)
679 /// Instantiates the path for the given trait reference, assuming that it's
680 /// bound to a valid trait type. Returns the def_id for the defining trait.
681 /// The type _cannot_ be a type other than a trait type.
683 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
684 /// are disallowed. Otherwise, they are pushed onto the vector given.
685 pub fn instantiate_mono_trait_ref(&self,
686 trait_ref: &hir::TraitRef,
688 -> ty::TraitRef<'tcx>
690 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
692 self.ast_path_to_mono_trait_ref(trait_ref.path.span,
693 trait_ref.trait_def_id(),
695 trait_ref.path.segments.last().unwrap())
698 /// The given trait-ref must actually be a trait.
699 pub(super) fn instantiate_poly_trait_ref_inner(&self,
700 trait_ref: &hir::TraitRef,
702 poly_projections: &mut Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
704 -> (ty::PolyTraitRef<'tcx>, Option<Vec<Span>>)
706 let trait_def_id = trait_ref.trait_def_id();
708 debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
710 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
712 let (substs, assoc_bindings, potential_assoc_types) = self.create_substs_for_ast_trait_ref(
716 trait_ref.path.segments.last().unwrap(),
718 let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
720 let mut dup_bindings = FxHashMap::default();
721 poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
722 // specify type to assert that error was already reported in Err case:
723 let predicate: Result<_, ErrorReported> =
724 self.ast_type_binding_to_poly_projection_predicate(
725 trait_ref.ref_id, poly_trait_ref, binding, speculative, &mut dup_bindings);
726 // okay to ignore Err because of ErrorReported (see above)
727 Some((predicate.ok()?, binding.span))
730 debug!("instantiate_poly_trait_ref({:?}, projections={:?}) -> {:?}",
731 trait_ref, poly_projections, poly_trait_ref);
732 (poly_trait_ref, potential_assoc_types)
735 pub fn instantiate_poly_trait_ref(&self,
736 poly_trait_ref: &hir::PolyTraitRef,
738 poly_projections: &mut Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>)
739 -> (ty::PolyTraitRef<'tcx>, Option<Vec<Span>>)
741 self.instantiate_poly_trait_ref_inner(&poly_trait_ref.trait_ref, self_ty,
742 poly_projections, false)
745 fn ast_path_to_mono_trait_ref(&self,
749 trait_segment: &hir::PathSegment)
750 -> ty::TraitRef<'tcx>
752 let (substs, assoc_bindings, _) =
753 self.create_substs_for_ast_trait_ref(span,
757 assoc_bindings.first().map(|b| AstConv::prohibit_assoc_ty_binding(self.tcx(), b.span));
758 ty::TraitRef::new(trait_def_id, substs)
761 fn create_substs_for_ast_trait_ref(
766 trait_segment: &hir::PathSegment,
767 ) -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>, Option<Vec<Span>>) {
768 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
771 let trait_def = self.tcx().trait_def(trait_def_id);
773 if !self.tcx().features().unboxed_closures &&
774 trait_segment.with_generic_args(|generic_args| generic_args.parenthesized)
775 != trait_def.paren_sugar {
776 // For now, require that parenthetical notation be used only with `Fn()` etc.
777 let msg = if trait_def.paren_sugar {
778 "the precise format of `Fn`-family traits' type parameters is subject to change. \
779 Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead"
781 "parenthetical notation is only stable when used with `Fn`-family traits"
783 emit_feature_err(&self.tcx().sess.parse_sess, "unboxed_closures",
784 span, GateIssue::Language, msg);
787 trait_segment.with_generic_args(|generic_args| {
788 self.create_substs_for_ast_path(span,
791 trait_segment.infer_types,
796 fn trait_defines_associated_type_named(&self,
798 assoc_name: ast::Ident)
801 self.tcx().associated_items(trait_def_id).any(|item| {
802 item.kind == ty::AssociatedKind::Type &&
803 self.tcx().hygienic_eq(assoc_name, item.ident, trait_def_id)
807 fn ast_type_binding_to_poly_projection_predicate(
810 trait_ref: ty::PolyTraitRef<'tcx>,
811 binding: &ConvertedBinding<'tcx>,
813 dup_bindings: &mut FxHashMap<DefId, Span>)
814 -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
816 let tcx = self.tcx();
819 // Given something like `U: SomeTrait<T = X>`, we want to produce a
820 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
821 // subtle in the event that `T` is defined in a supertrait of
822 // `SomeTrait`, because in that case we need to upcast.
824 // That is, consider this case:
827 // trait SubTrait: SuperTrait<int> { }
828 // trait SuperTrait<A> { type T; }
830 // ... B : SubTrait<T=foo> ...
833 // We want to produce `<B as SuperTrait<int>>::T == foo`.
835 // Find any late-bound regions declared in `ty` that are not
836 // declared in the trait-ref. These are not wellformed.
840 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
841 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
842 let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
843 let late_bound_in_ty =
844 tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(binding.ty));
845 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
846 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
847 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
848 let br_name = match *br {
849 ty::BrNamed(_, name) => name,
853 "anonymous bound region {:?} in binding but not trait ref",
857 struct_span_err!(tcx.sess,
860 "binding for associated type `{}` references lifetime `{}`, \
861 which does not appear in the trait input types",
862 binding.item_name, br_name)
867 let candidate = if self.trait_defines_associated_type_named(trait_ref.def_id(),
869 // Simple case: X is defined in the current trait.
872 // Otherwise, we have to walk through the supertraits to find
874 let candidates = traits::supertraits(tcx, trait_ref).filter(|r| {
875 self.trait_defines_associated_type_named(r.def_id(), binding.item_name)
877 self.one_bound_for_assoc_type(candidates, &trait_ref.to_string(),
878 binding.item_name, binding.span)
881 let (assoc_ident, def_scope) =
882 tcx.adjust_ident(binding.item_name, candidate.def_id(), ref_id);
883 let assoc_ty = tcx.associated_items(candidate.def_id()).find(|i| {
884 i.kind == ty::AssociatedKind::Type && i.ident.modern() == assoc_ident
885 }).expect("missing associated type");
887 if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
888 let msg = format!("associated type `{}` is private", binding.item_name);
889 tcx.sess.span_err(binding.span, &msg);
891 tcx.check_stability(assoc_ty.def_id, Some(ref_id), binding.span);
894 dup_bindings.entry(assoc_ty.def_id)
895 .and_modify(|prev_span| {
896 struct_span_err!(self.tcx().sess, binding.span, E0719,
897 "the value of the associated type `{}` (from the trait `{}`) \
898 is already specified",
900 tcx.item_path_str(assoc_ty.container.id()))
901 .span_label(binding.span, "re-bound here")
902 .span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
905 .or_insert(binding.span);
908 Ok(candidate.map_bound(|trait_ref| {
909 ty::ProjectionPredicate {
910 projection_ty: ty::ProjectionTy::from_ref_and_name(
920 fn ast_path_to_ty(&self,
923 item_segment: &hir::PathSegment)
926 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
929 self.tcx().at(span).type_of(did).subst(self.tcx(), substs)
933 /// Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
934 /// removing the dummy `Self` type (`TRAIT_OBJECT_DUMMY_SELF`).
935 fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
936 -> ty::ExistentialTraitRef<'tcx> {
937 assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
938 ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
941 fn conv_object_ty_poly_trait_ref(&self,
943 trait_bounds: &[hir::PolyTraitRef],
944 lifetime: &hir::Lifetime)
947 let tcx = self.tcx();
949 if trait_bounds.is_empty() {
950 span_err!(tcx.sess, span, E0224,
951 "at least one non-builtin trait is required for an object type");
952 return tcx.types.err;
955 let mut projection_bounds = Vec::new();
956 let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
957 let (principal, potential_assoc_types) = self.instantiate_poly_trait_ref(
960 &mut projection_bounds,
962 debug!("principal: {:?}", principal);
964 for trait_bound in trait_bounds[1..].iter() {
965 // sanity check for non-principal trait bounds
966 self.instantiate_poly_trait_ref(trait_bound,
971 let (mut auto_traits, trait_bounds) = split_auto_traits(tcx, &trait_bounds[1..]);
973 if !trait_bounds.is_empty() {
974 let b = &trait_bounds[0];
975 let span = b.trait_ref.path.span;
976 struct_span_err!(self.tcx().sess, span, E0225,
977 "only auto traits can be used as additional traits in a trait object")
978 .span_label(span, "non-auto additional trait")
982 // Check that there are no gross object safety violations;
983 // most importantly, that the supertraits don't contain `Self`,
985 let object_safety_violations =
986 tcx.global_tcx().astconv_object_safety_violations(principal.def_id());
987 if !object_safety_violations.is_empty() {
988 tcx.report_object_safety_error(
989 span, principal.def_id(), object_safety_violations)
991 return tcx.types.err;
994 // Use a `BTreeSet` to keep output in a more consistent order.
995 let mut associated_types = BTreeSet::default();
997 for tr in traits::elaborate_trait_ref(tcx, principal) {
998 debug!("conv_object_ty_poly_trait_ref: observing object predicate `{:?}`", tr);
1000 ty::Predicate::Trait(pred) => {
1001 associated_types.extend(tcx.associated_items(pred.def_id())
1002 .filter(|item| item.kind == ty::AssociatedKind::Type)
1003 .map(|item| item.def_id));
1005 ty::Predicate::Projection(pred) => {
1006 // A `Self` within the original bound will be substituted with a
1007 // `TRAIT_OBJECT_DUMMY_SELF`, so check for that.
1008 let references_self =
1009 pred.skip_binder().ty.walk().any(|t| t == dummy_self);
1011 // If the projection output contains `Self`, force the user to
1012 // elaborate it explicitly to avoid a bunch of complexity.
1014 // The "classicaly useful" case is the following:
1016 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1021 // Here, the user could theoretically write `dyn MyTrait<Output=X>`,
1022 // but actually supporting that would "expand" to an infinitely-long type
1023 // `fix $ τ → dyn MyTrait<MyOutput=X, Output=<τ as MyTrait>::MyOutput`.
1025 // Instead, we force the user to write `dyn MyTrait<MyOutput=X, Output=X>`,
1026 // which is uglier but works. See the discussion in #56288 for alternatives.
1027 if !references_self {
1028 // Include projections defined on supertraits,
1029 projection_bounds.push((pred, DUMMY_SP))
1036 for (projection_bound, _) in &projection_bounds {
1037 associated_types.remove(&projection_bound.projection_def_id());
1040 if !associated_types.is_empty() {
1041 let names = associated_types.iter().map(|item_def_id| {
1042 let assoc_item = tcx.associated_item(*item_def_id);
1043 let trait_def_id = assoc_item.container.id();
1045 "`{}` (from the trait `{}`)",
1047 tcx.item_path_str(trait_def_id),
1049 }).collect::<Vec<_>>().join(", ");
1050 let mut err = struct_span_err!(
1054 "the value of the associated type{} {} must be specified",
1055 if associated_types.len() == 1 { "" } else { "s" },
1058 let mut suggest = false;
1059 let mut potential_assoc_types_spans = vec![];
1060 if let Some(potential_assoc_types) = potential_assoc_types {
1061 if potential_assoc_types.len() == associated_types.len() {
1062 // Only suggest when the amount of missing associated types is equals to the
1063 // extra type arguments present, as that gives us a relatively high confidence
1064 // that the user forgot to give the associtated type's name. The canonical
1065 // example would be trying to use `Iterator<isize>` instead of
1066 // `Iterator<Item=isize>`.
1068 potential_assoc_types_spans = potential_assoc_types;
1071 let mut suggestions = vec![];
1072 for (i, item_def_id) in associated_types.iter().enumerate() {
1073 let assoc_item = tcx.associated_item(*item_def_id);
1076 format!("associated type `{}` must be specified", assoc_item.ident),
1078 if item_def_id.is_local() {
1080 tcx.def_span(*item_def_id),
1081 format!("`{}` defined here", assoc_item.ident),
1085 if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(
1086 potential_assoc_types_spans[i],
1089 potential_assoc_types_spans[i],
1090 format!("{} = {}", assoc_item.ident, snippet),
1095 if !suggestions.is_empty() {
1096 let msg = format!("if you meant to specify the associated {}, write",
1097 if suggestions.len() == 1 { "type" } else { "types" });
1098 err.multipart_suggestion(
1101 Applicability::MaybeIncorrect,
1107 // Erase the `dummy_self` (`TRAIT_OBJECT_DUMMY_SELF`) used above.
1108 let existential_principal = principal.map_bound(|trait_ref| {
1109 self.trait_ref_to_existential(trait_ref)
1111 let existential_projections = projection_bounds.iter().map(|(bound, _)| {
1112 bound.map_bound(|b| {
1113 let trait_ref = self.trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1114 ty::ExistentialProjection {
1116 item_def_id: b.projection_ty.item_def_id,
1117 substs: trait_ref.substs,
1122 // Dedup auto traits so that `dyn Trait + Send + Send` is the same as `dyn Trait + Send`.
1124 auto_traits.dedup();
1126 // Calling `skip_binder` is okay, because the predicates are re-bound.
1127 let principal = if tcx.trait_is_auto(existential_principal.def_id()) {
1128 ty::ExistentialPredicate::AutoTrait(existential_principal.def_id())
1130 ty::ExistentialPredicate::Trait(*existential_principal.skip_binder())
1133 iter::once(principal)
1134 .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
1135 .chain(existential_projections
1136 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
1137 .collect::<SmallVec<[_; 8]>>();
1138 v.sort_by(|a, b| a.stable_cmp(tcx, b));
1140 let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1142 // Use explicitly-specified region bound.
1143 let region_bound = if !lifetime.is_elided() {
1144 self.ast_region_to_region(lifetime, None)
1146 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1147 if tcx.named_region(lifetime.hir_id).is_some() {
1148 self.ast_region_to_region(lifetime, None)
1150 self.re_infer(span, None).unwrap_or_else(|| {
1151 span_err!(tcx.sess, span, E0228,
1152 "the lifetime bound for this object type cannot be deduced \
1153 from context; please supply an explicit bound");
1160 debug!("region_bound: {:?}", region_bound);
1162 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1163 debug!("trait_object_type: {:?}", ty);
1167 fn report_ambiguous_associated_type(&self,
1172 struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
1175 "use fully-qualified syntax",
1176 format!("<{} as {}>::{}", type_str, trait_str, name),
1177 Applicability::HasPlaceholders
1181 // Search for a bound on a type parameter which includes the associated item
1182 // given by `assoc_name`. `ty_param_def_id` is the `DefId` for the type parameter
1183 // This function will fail if there are no suitable bounds or there is
1185 fn find_bound_for_assoc_item(&self,
1186 ty_param_def_id: DefId,
1187 assoc_name: ast::Ident,
1189 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1191 let tcx = self.tcx();
1193 let predicates = &self.get_type_parameter_bounds(span, ty_param_def_id).predicates;
1194 let bounds = predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref());
1196 // Check that there is exactly one way to find an associated type with the
1198 let suitable_bounds = traits::transitive_bounds(tcx, bounds)
1199 .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
1201 let param_node_id = tcx.hir().as_local_node_id(ty_param_def_id).unwrap();
1202 let param_name = tcx.hir().ty_param_name(param_node_id);
1203 self.one_bound_for_assoc_type(suitable_bounds,
1204 ¶m_name.as_str(),
1209 // Checks that `bounds` contains exactly one element and reports appropriate
1210 // errors otherwise.
1211 fn one_bound_for_assoc_type<I>(&self,
1213 ty_param_name: &str,
1214 assoc_name: ast::Ident,
1216 -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1217 where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
1219 let bound = match bounds.next() {
1220 Some(bound) => bound,
1222 struct_span_err!(self.tcx().sess, span, E0220,
1223 "associated type `{}` not found for `{}`",
1226 .span_label(span, format!("associated type `{}` not found", assoc_name))
1228 return Err(ErrorReported);
1232 if let Some(bound2) = bounds.next() {
1233 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
1234 let mut err = struct_span_err!(
1235 self.tcx().sess, span, E0221,
1236 "ambiguous associated type `{}` in bounds of `{}`",
1239 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1241 for bound in bounds {
1242 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
1243 item.kind == ty::AssociatedKind::Type &&
1244 self.tcx().hygienic_eq(assoc_name, item.ident, bound.def_id())
1246 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1248 if let Some(span) = bound_span {
1249 err.span_label(span, format!("ambiguous `{}` from `{}`",
1253 span_note!(&mut err, span,
1254 "associated type `{}` could derive from `{}`",
1265 // Create a type from a path to an associated type.
1266 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
1267 // and item_segment is the path segment for `D`. We return a type and a def for
1269 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
1270 // parameter or `Self`.
1271 pub fn associated_path_to_ty(
1273 ref_id: ast::NodeId,
1277 assoc_segment: &hir::PathSegment,
1278 permit_variants: bool,
1279 ) -> (Ty<'tcx>, Def) {
1280 let tcx = self.tcx();
1281 let assoc_ident = assoc_segment.ident;
1283 debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
1285 self.prohibit_generics(slice::from_ref(assoc_segment));
1287 // Check if we have an enum variant.
1288 let mut variant_resolution = None;
1289 if let ty::Adt(adt_def, _) = qself_ty.sty {
1290 if adt_def.is_enum() {
1291 let variant_def = adt_def.variants.iter().find(|vd| {
1292 tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did)
1294 if let Some(variant_def) = variant_def {
1295 let def = Def::Variant(variant_def.did);
1296 if permit_variants {
1297 check_type_alias_enum_variants_enabled(tcx, span);
1298 tcx.check_stability(variant_def.did, Some(ref_id), span);
1299 return (qself_ty, def);
1301 variant_resolution = Some(def);
1307 // Find the type of the associated item, and the trait where the associated
1308 // item is declared.
1309 let bound = match (&qself_ty.sty, qself_def) {
1310 (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
1311 // `Self` in an impl of a trait -- we have a concrete self type and a
1313 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
1314 Some(trait_ref) => trait_ref,
1316 // A cycle error occurred, most likely.
1317 return (tcx.types.err, Def::Err);
1321 let candidates = traits::supertraits(tcx, ty::Binder::bind(trait_ref))
1322 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_ident));
1324 match self.one_bound_for_assoc_type(candidates, "Self", assoc_ident, span) {
1326 Err(ErrorReported) => return (tcx.types.err, Def::Err),
1329 (&ty::Param(_), Def::SelfTy(Some(param_did), None)) |
1330 (&ty::Param(_), Def::TyParam(param_did)) => {
1331 match self.find_bound_for_assoc_item(param_did, assoc_ident, span) {
1333 Err(ErrorReported) => return (tcx.types.err, Def::Err),
1337 if variant_resolution.is_some() {
1338 // Variant in type position
1339 let msg = format!("expected type, found variant `{}`", assoc_ident);
1340 tcx.sess.span_err(span, &msg);
1341 } else if qself_ty.is_enum() {
1342 // Report as incorrect enum variant rather than ambiguous type.
1343 let mut err = tcx.sess.struct_span_err(
1345 &format!("no variant `{}` on enum `{}`", &assoc_ident.as_str(), qself_ty),
1347 // Check if it was a typo.
1348 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
1349 if let Some(suggested_name) = find_best_match_for_name(
1350 adt_def.variants.iter().map(|variant| &variant.ident.name),
1351 &assoc_ident.as_str(),
1354 err.span_suggestion(
1357 format!("{}::{}", qself_ty, suggested_name),
1358 Applicability::MaybeIncorrect,
1361 err.span_label(span, "unknown variant");
1364 } else if !qself_ty.references_error() {
1365 // Don't print `TyErr` to the user.
1366 self.report_ambiguous_associated_type(span,
1367 &qself_ty.to_string(),
1369 &assoc_ident.as_str());
1371 return (tcx.types.err, Def::Err);
1375 let trait_did = bound.def_id();
1376 let (assoc_ident, def_scope) = tcx.adjust_ident(assoc_ident, trait_did, ref_id);
1377 let item = tcx.associated_items(trait_did).find(|i| {
1378 Namespace::from(i.kind) == Namespace::Type &&
1379 i.ident.modern() == assoc_ident
1380 }).expect("missing associated type");
1382 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, bound);
1383 let ty = self.normalize_ty(span, ty);
1385 let def = Def::AssociatedTy(item.def_id);
1386 if !item.vis.is_accessible_from(def_scope, tcx) {
1387 let msg = format!("{} `{}` is private", def.kind_name(), assoc_ident);
1388 tcx.sess.span_err(span, &msg);
1390 tcx.check_stability(item.def_id, Some(ref_id), span);
1392 if let Some(variant_def) = variant_resolution {
1393 let mut err = tcx.struct_span_lint_node(
1394 AMBIGUOUS_ASSOCIATED_ITEMS,
1397 "ambiguous associated item",
1400 let mut could_refer_to = |def: Def, also| {
1401 let note_msg = format!("`{}` could{} refer to {} defined here",
1402 assoc_ident, also, def.kind_name());
1403 err.span_note(tcx.def_span(def.def_id()), ¬e_msg);
1405 could_refer_to(variant_def, "");
1406 could_refer_to(def, " also");
1408 err.span_suggestion(
1410 "use fully-qualified syntax",
1411 format!("<{} as {}>::{}", qself_ty, "Trait", assoc_ident),
1412 Applicability::HasPlaceholders,
1419 fn qpath_to_ty(&self,
1421 opt_self_ty: Option<Ty<'tcx>>,
1423 trait_segment: &hir::PathSegment,
1424 item_segment: &hir::PathSegment)
1427 let tcx = self.tcx();
1428 let trait_def_id = tcx.parent_def_id(item_def_id).unwrap();
1430 self.prohibit_generics(slice::from_ref(item_segment));
1432 let self_ty = if let Some(ty) = opt_self_ty {
1435 let path_str = tcx.item_path_str(trait_def_id);
1436 self.report_ambiguous_associated_type(span,
1439 &item_segment.ident.as_str());
1440 return tcx.types.err;
1443 debug!("qpath_to_ty: self_type={:?}", self_ty);
1445 let trait_ref = self.ast_path_to_mono_trait_ref(span,
1450 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1452 self.normalize_ty(span, tcx.mk_projection(item_def_id, trait_ref.substs))
1455 pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment>>(
1456 &self, segments: T) -> bool {
1457 let mut has_err = false;
1458 for segment in segments {
1459 segment.with_generic_args(|generic_args| {
1460 let (mut err_for_lt, mut err_for_ty) = (false, false);
1461 for arg in &generic_args.args {
1462 let (mut span_err, span, kind) = match arg {
1463 hir::GenericArg::Lifetime(lt) => {
1464 if err_for_lt { continue }
1467 (struct_span_err!(self.tcx().sess, lt.span, E0110,
1468 "lifetime arguments are not allowed on this entity"),
1472 hir::GenericArg::Type(ty) => {
1473 if err_for_ty { continue }
1476 (struct_span_err!(self.tcx().sess, ty.span, E0109,
1477 "type arguments are not allowed on this entity"),
1482 span_err.span_label(span, format!("{} argument not allowed", kind))
1484 if err_for_lt && err_for_ty {
1488 for binding in &generic_args.bindings {
1490 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
1498 pub fn prohibit_assoc_ty_binding(tcx: TyCtxt, span: Span) {
1499 let mut err = struct_span_err!(tcx.sess, span, E0229,
1500 "associated type bindings are not allowed here");
1501 err.span_label(span, "associated type not allowed here").emit();
1504 pub fn def_ids_for_path_segments(&self,
1505 segments: &[hir::PathSegment],
1506 self_ty: Option<Ty<'tcx>>,
1509 // We need to extract the type parameters supplied by the user in
1510 // the path `path`. Due to the current setup, this is a bit of a
1511 // tricky-process; the problem is that resolve only tells us the
1512 // end-point of the path resolution, and not the intermediate steps.
1513 // Luckily, we can (at least for now) deduce the intermediate steps
1514 // just from the end-point.
1516 // There are basically five cases to consider:
1518 // 1. Reference to a constructor of a struct:
1520 // struct Foo<T>(...)
1522 // In this case, the parameters are declared in the type space.
1524 // 2. Reference to a constructor of an enum variant:
1526 // enum E<T> { Foo(...) }
1528 // In this case, the parameters are defined in the type space,
1529 // but may be specified either on the type or the variant.
1531 // 3. Reference to a fn item or a free constant:
1535 // In this case, the path will again always have the form
1536 // `a::b::foo::<T>` where only the final segment should have
1537 // type parameters. However, in this case, those parameters are
1538 // declared on a value, and hence are in the `FnSpace`.
1540 // 4. Reference to a method or an associated constant:
1542 // impl<A> SomeStruct<A> {
1546 // Here we can have a path like
1547 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
1548 // may appear in two places. The penultimate segment,
1549 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
1550 // final segment, `foo::<B>` contains parameters in fn space.
1552 // 5. Reference to a local variable
1554 // Local variables can't have any type parameters.
1556 // The first step then is to categorize the segments appropriately.
1558 let tcx = self.tcx();
1560 assert!(!segments.is_empty());
1561 let last = segments.len() - 1;
1563 let mut path_segs = vec![];
1566 // Case 1. Reference to a struct constructor.
1567 Def::StructCtor(def_id, ..) |
1568 Def::SelfCtor(.., def_id) => {
1569 // Everything but the final segment should have no
1570 // parameters at all.
1571 let generics = tcx.generics_of(def_id);
1572 // Variant and struct constructors use the
1573 // generics of their parent type definition.
1574 let generics_def_id = generics.parent.unwrap_or(def_id);
1575 path_segs.push(PathSeg(generics_def_id, last));
1578 // Case 2. Reference to a variant constructor.
1579 Def::Variant(def_id) |
1580 Def::VariantCtor(def_id, ..) => {
1581 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
1582 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
1583 debug_assert!(adt_def.is_enum());
1585 } else if last >= 1 && segments[last - 1].args.is_some() {
1586 // Everything but the penultimate segment should have no
1587 // parameters at all.
1588 let enum_def_id = tcx.parent_def_id(def_id).unwrap();
1589 (enum_def_id, last - 1)
1591 // FIXME: lint here recommending `Enum::<...>::Variant` form
1592 // instead of `Enum::Variant::<...>` form.
1594 // Everything but the final segment should have no
1595 // parameters at all.
1596 let generics = tcx.generics_of(def_id);
1597 // Variant and struct constructors use the
1598 // generics of their parent type definition.
1599 (generics.parent.unwrap_or(def_id), last)
1601 path_segs.push(PathSeg(generics_def_id, index));
1604 // Case 3. Reference to a top-level value.
1606 Def::Const(def_id) |
1607 Def::Static(def_id, _) => {
1608 path_segs.push(PathSeg(def_id, last));
1611 // Case 4. Reference to a method or associated const.
1612 Def::Method(def_id) |
1613 Def::AssociatedConst(def_id) => {
1614 if segments.len() >= 2 {
1615 let generics = tcx.generics_of(def_id);
1616 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
1618 path_segs.push(PathSeg(def_id, last));
1621 // Case 5. Local variable, no generics.
1622 Def::Local(..) | Def::Upvar(..) => {}
1624 _ => bug!("unexpected definition: {:?}", def),
1627 debug!("path_segs = {:?}", path_segs);
1632 // Check a type `Path` and convert it to a `Ty`.
1633 pub fn def_to_ty(&self,
1634 opt_self_ty: Option<Ty<'tcx>>,
1636 permit_variants: bool)
1638 let tcx = self.tcx();
1640 debug!("def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
1641 path.def, opt_self_ty, path.segments);
1643 let span = path.span;
1645 Def::Existential(did) => {
1646 // Check for desugared impl trait.
1647 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
1648 let item_segment = path.segments.split_last().unwrap();
1649 self.prohibit_generics(item_segment.1);
1650 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
1653 tcx.mk_opaque(did, substs),
1656 Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) |
1657 Def::Union(did) | Def::ForeignTy(did) => {
1658 assert_eq!(opt_self_ty, None);
1659 self.prohibit_generics(path.segments.split_last().unwrap().1);
1660 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
1662 Def::Variant(_) if permit_variants => {
1663 // Convert "variant type" as if it were a real type.
1664 // The resulting `Ty` is type of the variant's enum for now.
1665 assert_eq!(opt_self_ty, None);
1667 let path_segs = self.def_ids_for_path_segments(&path.segments, None, path.def);
1668 let generic_segs: FxHashSet<_> =
1669 path_segs.iter().map(|PathSeg(_, index)| index).collect();
1670 self.prohibit_generics(path.segments.iter().enumerate().filter_map(|(index, seg)| {
1671 if !generic_segs.contains(&index) {
1678 let PathSeg(def_id, index) = path_segs.last().unwrap();
1679 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
1681 Def::TyParam(did) => {
1682 assert_eq!(opt_self_ty, None);
1683 self.prohibit_generics(&path.segments);
1685 let node_id = tcx.hir().as_local_node_id(did).unwrap();
1686 let item_id = tcx.hir().get_parent_node(node_id);
1687 let item_def_id = tcx.hir().local_def_id(item_id);
1688 let generics = tcx.generics_of(item_def_id);
1689 let index = generics.param_def_id_to_index[&tcx.hir().local_def_id(node_id)];
1690 tcx.mk_ty_param(index, tcx.hir().name(node_id).as_interned_str())
1692 Def::SelfTy(_, Some(def_id)) => {
1693 // `Self` in impl (we know the concrete type).
1694 assert_eq!(opt_self_ty, None);
1695 self.prohibit_generics(&path.segments);
1696 tcx.at(span).type_of(def_id)
1698 Def::SelfTy(Some(_), None) => {
1700 assert_eq!(opt_self_ty, None);
1701 self.prohibit_generics(&path.segments);
1704 Def::AssociatedTy(def_id) => {
1705 debug_assert!(path.segments.len() >= 2);
1706 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
1707 self.qpath_to_ty(span,
1710 &path.segments[path.segments.len() - 2],
1711 path.segments.last().unwrap())
1713 Def::PrimTy(prim_ty) => {
1714 assert_eq!(opt_self_ty, None);
1715 self.prohibit_generics(&path.segments);
1717 hir::Bool => tcx.types.bool,
1718 hir::Char => tcx.types.char,
1719 hir::Int(it) => tcx.mk_mach_int(it),
1720 hir::Uint(uit) => tcx.mk_mach_uint(uit),
1721 hir::Float(ft) => tcx.mk_mach_float(ft),
1722 hir::Str => tcx.mk_str()
1726 self.set_tainted_by_errors();
1727 return self.tcx().types.err;
1729 _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1733 /// Parses the programmer's textual representation of a type into our
1734 /// internal notion of a type.
1735 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
1736 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})",
1737 ast_ty.id, ast_ty, ast_ty.node);
1739 let tcx = self.tcx();
1741 let result_ty = match ast_ty.node {
1742 hir::TyKind::Slice(ref ty) => {
1743 tcx.mk_slice(self.ast_ty_to_ty(&ty))
1745 hir::TyKind::Ptr(ref mt) => {
1746 tcx.mk_ptr(ty::TypeAndMut {
1747 ty: self.ast_ty_to_ty(&mt.ty),
1751 hir::TyKind::Rptr(ref region, ref mt) => {
1752 let r = self.ast_region_to_region(region, None);
1753 debug!("Ref r={:?}", r);
1754 let t = self.ast_ty_to_ty(&mt.ty);
1755 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1757 hir::TyKind::Never => {
1760 hir::TyKind::Tup(ref fields) => {
1761 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
1763 hir::TyKind::BareFn(ref bf) => {
1764 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1765 tcx.mk_fn_ptr(self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl))
1767 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
1768 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
1770 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1771 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1772 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1773 self.ast_ty_to_ty(qself)
1775 self.def_to_ty(opt_self_ty, path, false)
1777 hir::TyKind::Def(item_id, ref lifetimes) => {
1778 let did = tcx.hir().local_def_id(item_id.id);
1779 self.impl_trait_ty_to_ty(did, lifetimes)
1781 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1782 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1783 let ty = self.ast_ty_to_ty(qself);
1785 let def = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.node {
1790 self.associated_path_to_ty(ast_ty.id, ast_ty.span, ty, def, segment, false).0
1792 hir::TyKind::Array(ref ty, ref length) => {
1793 let length_def_id = tcx.hir().local_def_id(length.id);
1794 let substs = Substs::identity_for_item(tcx, length_def_id);
1795 let length = ty::LazyConst::Unevaluated(length_def_id, substs);
1796 let length = tcx.intern_lazy_const(length);
1797 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
1798 self.normalize_ty(ast_ty.span, array_ty)
1800 hir::TyKind::Typeof(ref _e) => {
1801 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1802 "`typeof` is a reserved keyword but unimplemented")
1803 .span_label(ast_ty.span, "reserved keyword")
1808 hir::TyKind::Infer => {
1809 // Infer also appears as the type of arguments or return
1810 // values in a ExprKind::Closure, or as
1811 // the type of local variables. Both of these cases are
1812 // handled specially and will not descend into this routine.
1813 self.ty_infer(ast_ty.span)
1815 hir::TyKind::Err => {
1820 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
1824 pub fn impl_trait_ty_to_ty(
1827 lifetimes: &[hir::GenericArg],
1829 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
1830 let tcx = self.tcx();
1832 let generics = tcx.generics_of(def_id);
1834 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
1835 let substs = Substs::for_item(tcx, def_id, |param, _| {
1836 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
1837 // Our own parameters are the resolved lifetimes.
1839 GenericParamDefKind::Lifetime => {
1840 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
1841 self.ast_region_to_region(lifetime, None).into()
1849 // Replace all parent lifetimes with 'static.
1851 GenericParamDefKind::Lifetime => {
1852 tcx.types.re_static.into()
1854 _ => tcx.mk_param_from_def(param)
1858 debug!("impl_trait_ty_to_ty: final substs = {:?}", substs);
1860 let ty = tcx.mk_opaque(def_id, substs);
1861 debug!("impl_trait_ty_to_ty: {}", ty);
1865 pub fn ty_of_arg(&self,
1867 expected_ty: Option<Ty<'tcx>>)
1871 hir::TyKind::Infer if expected_ty.is_some() => {
1872 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
1873 expected_ty.unwrap()
1875 _ => self.ast_ty_to_ty(ty),
1879 pub fn ty_of_fn(&self,
1880 unsafety: hir::Unsafety,
1883 -> ty::PolyFnSig<'tcx> {
1886 let tcx = self.tcx();
1888 decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
1890 let output_ty = match decl.output {
1891 hir::Return(ref output) => self.ast_ty_to_ty(output),
1892 hir::DefaultReturn(..) => tcx.mk_unit(),
1895 debug!("ty_of_fn: output_ty={:?}", output_ty);
1897 let bare_fn_ty = ty::Binder::bind(tcx.mk_fn_sig(
1905 // Find any late-bound regions declared in return type that do
1906 // not appear in the arguments. These are not well-formed.
1909 // for<'a> fn() -> &'a str <-- 'a is bad
1910 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1911 let inputs = bare_fn_ty.inputs();
1912 let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1913 &inputs.map_bound(|i| i.to_owned()));
1914 let output = bare_fn_ty.output();
1915 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1916 for br in late_bound_in_ret.difference(&late_bound_in_args) {
1917 let lifetime_name = match *br {
1918 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
1919 ty::BrAnon(_) | ty::BrFresh(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
1921 let mut err = struct_span_err!(tcx.sess,
1924 "return type references {} \
1925 which is not constrained by the fn input types",
1927 if let ty::BrAnon(_) = *br {
1928 // The only way for an anonymous lifetime to wind up
1929 // in the return type but **also** be unconstrained is
1930 // if it only appears in "associated types" in the
1931 // input. See #47511 for an example. In this case,
1932 // though we can easily give a hint that ought to be
1934 err.note("lifetimes appearing in an associated type \
1935 are not considered constrained");
1943 /// Given the bounds on an object, determines what single region bound (if any) we can
1944 /// use to summarize this type. The basic idea is that we will use the bound the user
1945 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1946 /// for region bounds. It may be that we can derive no bound at all, in which case
1947 /// we return `None`.
1948 fn compute_object_lifetime_bound(&self,
1950 existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>)
1951 -> Option<ty::Region<'tcx>> // if None, use the default
1953 let tcx = self.tcx();
1955 debug!("compute_opt_region_bound(existential_predicates={:?})",
1956 existential_predicates);
1958 // No explicit region bound specified. Therefore, examine trait
1959 // bounds and see if we can derive region bounds from those.
1960 let derived_region_bounds =
1961 object_region_bounds(tcx, existential_predicates);
1963 // If there are no derived region bounds, then report back that we
1964 // can find no region bound. The caller will use the default.
1965 if derived_region_bounds.is_empty() {
1969 // If any of the derived region bounds are 'static, that is always
1971 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1972 return Some(tcx.types.re_static);
1975 // Determine whether there is exactly one unique region in the set
1976 // of derived region bounds. If so, use that. Otherwise, report an
1978 let r = derived_region_bounds[0];
1979 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1980 span_err!(tcx.sess, span, E0227,
1981 "ambiguous lifetime bound, explicit lifetime bound required");
1987 /// Divides a list of general trait bounds into two groups: auto traits (e.g., Sync and Send) and
1988 /// the remaining general trait bounds.
1989 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1990 trait_bounds: &'b [hir::PolyTraitRef])
1991 -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
1993 let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.iter().partition(|bound| {
1994 // Checks whether `trait_did` is an auto trait and adds it to `auto_traits` if so.
1995 match bound.trait_ref.path.def {
1996 Def::Trait(trait_did) if tcx.trait_is_auto(trait_did) => {
2003 let auto_traits = auto_traits.into_iter().map(|tr| {
2004 if let Def::Trait(trait_did) = tr.trait_ref.path.def {
2009 }).collect::<Vec<_>>();
2011 (auto_traits, trait_bounds)
2014 // A helper struct for conveniently grouping a set of bounds which we pass to
2015 // and return from functions in multiple places.
2016 #[derive(PartialEq, Eq, Clone, Debug)]
2017 pub struct Bounds<'tcx> {
2018 pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
2019 pub implicitly_sized: Option<Span>,
2020 pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span)>,
2021 pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
2024 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
2025 pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
2026 -> Vec<(ty::Predicate<'tcx>, Span)>
2028 // If it could be sized, and is, add the sized predicate.
2029 let sized_predicate = self.implicitly_sized.and_then(|span| {
2030 tcx.lang_items().sized_trait().map(|sized| {
2031 let trait_ref = ty::TraitRef {
2033 substs: tcx.mk_substs_trait(param_ty, &[])
2035 (trait_ref.to_predicate(), span)
2039 sized_predicate.into_iter().chain(
2040 self.region_bounds.iter().map(|&(region_bound, span)| {
2041 // Account for the binder being introduced below; no need to shift `param_ty`
2042 // because, at present at least, it can only refer to early-bound regions.
2043 let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
2044 let outlives = ty::OutlivesPredicate(param_ty, region_bound);
2045 (ty::Binder::dummy(outlives).to_predicate(), span)
2047 self.trait_bounds.iter().map(|&(bound_trait_ref, span)| {
2048 (bound_trait_ref.to_predicate(), span)
2051 self.projection_bounds.iter().map(|&(projection, span)| {
2052 (projection.to_predicate(), span)