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`.
8 use crate::bounds::Bounds;
9 use crate::collect::PlaceholderHirTyCollector;
10 use crate::middle::resolve_lifetime as rl;
11 use crate::require_c_abi_if_c_variadic;
12 use rustc_ast::util::lev_distance::find_best_match_for_name;
13 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
14 use rustc_errors::{struct_span_err, Applicability, ErrorReported, FatalError};
16 use rustc_hir::def::{CtorOf, DefKind, Namespace, Res};
17 use rustc_hir::def_id::{DefId, LocalDefId};
18 use rustc_hir::intravisit::{walk_generics, Visitor as _};
19 use rustc_hir::lang_items::LangItem;
20 use rustc_hir::{Constness, GenericArg, GenericArgs};
21 use rustc_middle::ty::subst::{self, InternalSubsts, Subst, SubstsRef};
22 use rustc_middle::ty::GenericParamDefKind;
23 use rustc_middle::ty::{self, Const, DefIdTree, Ty, TyCtxt, TypeFoldable};
24 use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
25 use rustc_span::symbol::{Ident, Symbol};
26 use rustc_span::{Span, DUMMY_SP};
27 use rustc_target::spec::abi;
28 use rustc_trait_selection::traits;
29 use rustc_trait_selection::traits::astconv_object_safety_violations;
30 use rustc_trait_selection::traits::error_reporting::report_object_safety_error;
31 use rustc_trait_selection::traits::wf::object_region_bounds;
33 use smallvec::SmallVec;
34 use std::collections::BTreeSet;
39 pub struct PathSeg(pub DefId, pub usize);
41 pub trait AstConv<'tcx> {
42 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
44 fn item_def_id(&self) -> Option<DefId>;
46 fn default_constness_for_trait_bounds(&self) -> Constness;
48 /// Returns predicates in scope of the form `X: Foo`, where `X` is
49 /// a type parameter `X` with the given id `def_id`. This is a
50 /// subset of the full set of predicates.
52 /// This is used for one specific purpose: resolving "short-hand"
53 /// associated type references like `T::Item`. In principle, we
54 /// would do that by first getting the full set of predicates in
55 /// scope and then filtering down to find those that apply to `T`,
56 /// but this can lead to cycle errors. The problem is that we have
57 /// to do this resolution *in order to create the predicates in
58 /// the first place*. Hence, we have this "special pass".
59 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx>;
61 /// Returns the lifetime to use when a lifetime is omitted (and not elided).
62 fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span)
63 -> Option<ty::Region<'tcx>>;
65 /// Returns the type to use when a type is omitted.
66 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
68 /// Returns `true` if `_` is allowed in type signatures in the current context.
69 fn allow_ty_infer(&self) -> bool;
71 /// Returns the const to use when a const is omitted.
75 param: Option<&ty::GenericParamDef>,
77 ) -> &'tcx Const<'tcx>;
79 /// Projecting an associated type from a (potentially)
80 /// higher-ranked trait reference is more complicated, because of
81 /// the possibility of late-bound regions appearing in the
82 /// associated type binding. This is not legal in function
83 /// signatures for that reason. In a function body, we can always
84 /// handle it because we can use inference variables to remove the
85 /// late-bound regions.
86 fn projected_ty_from_poly_trait_ref(
90 item_segment: &hir::PathSegment<'_>,
91 poly_trait_ref: ty::PolyTraitRef<'tcx>,
94 /// Normalize an associated type coming from the user.
95 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
97 /// Invoked when we encounter an error from some prior pass
98 /// (e.g., resolve) that is translated into a ty-error. This is
99 /// used to help suppress derived errors typeck might otherwise
101 fn set_tainted_by_errors(&self);
103 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
106 pub enum SizedByDefault {
111 struct ConvertedBinding<'a, 'tcx> {
113 kind: ConvertedBindingKind<'a, 'tcx>,
117 enum ConvertedBindingKind<'a, 'tcx> {
119 Constraint(&'a [hir::GenericBound<'a>]),
122 /// New-typed boolean indicating whether explicit late-bound lifetimes
123 /// are present in a set of generic arguments.
125 /// For example if we have some method `fn f<'a>(&'a self)` implemented
126 /// for some type `T`, although `f` is generic in the lifetime `'a`, `'a`
127 /// is late-bound so should not be provided explicitly. Thus, if `f` is
128 /// instantiated with some generic arguments providing `'a` explicitly,
129 /// we taint those arguments with `ExplicitLateBound::Yes` so that we
130 /// can provide an appropriate diagnostic later.
131 #[derive(Copy, Clone, PartialEq)]
132 pub enum ExplicitLateBound {
137 /// Denotes the "position" of a generic argument, indicating if it is a generic type,
138 /// generic function or generic method call.
139 #[derive(Copy, Clone, PartialEq)]
140 pub(crate) enum GenericArgPosition {
142 Value, // e.g., functions
146 /// A marker denoting that the generic arguments that were
147 /// provided did not match the respective generic parameters.
148 #[derive(Clone, Default)]
149 pub struct GenericArgCountMismatch {
150 /// Indicates whether a fatal error was reported (`Some`), or just a lint (`None`).
151 pub reported: Option<ErrorReported>,
152 /// A list of spans of arguments provided that were not valid.
153 pub invalid_args: Vec<Span>,
156 /// Decorates the result of a generic argument count mismatch
157 /// check with whether explicit late bounds were provided.
159 pub struct GenericArgCountResult {
160 pub explicit_late_bound: ExplicitLateBound,
161 pub correct: Result<(), GenericArgCountMismatch>,
164 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
165 pub fn ast_region_to_region(
167 lifetime: &hir::Lifetime,
168 def: Option<&ty::GenericParamDef>,
169 ) -> ty::Region<'tcx> {
170 let tcx = self.tcx();
171 let lifetime_name = |def_id| tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id));
173 let r = match tcx.named_region(lifetime.hir_id) {
174 Some(rl::Region::Static) => tcx.lifetimes.re_static,
176 Some(rl::Region::LateBound(debruijn, id, _)) => {
177 let name = lifetime_name(id.expect_local());
178 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrNamed(id, name)))
181 Some(rl::Region::LateBoundAnon(debruijn, index)) => {
182 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
185 Some(rl::Region::EarlyBound(index, id, _)) => {
186 let name = lifetime_name(id.expect_local());
187 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: id, index, name }))
190 Some(rl::Region::Free(scope, id)) => {
191 let name = lifetime_name(id.expect_local());
192 tcx.mk_region(ty::ReFree(ty::FreeRegion {
194 bound_region: ty::BrNamed(id, name),
197 // (*) -- not late-bound, won't change
201 self.re_infer(def, lifetime.span).unwrap_or_else(|| {
202 // This indicates an illegal lifetime
203 // elision. `resolve_lifetime` should have
204 // reported an error in this case -- but if
205 // not, let's error out.
206 tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
208 // Supply some dummy value. We don't have an
209 // `re_error`, annoyingly, so use `'static`.
210 tcx.lifetimes.re_static
215 debug!("ast_region_to_region(lifetime={:?}) yields {:?}", lifetime, r);
220 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
221 /// returns an appropriate set of substitutions for this particular reference to `I`.
222 pub fn ast_path_substs_for_ty(
226 item_segment: &hir::PathSegment<'_>,
227 ) -> SubstsRef<'tcx> {
228 let (substs, assoc_bindings, _) = self.create_substs_for_ast_path(
232 item_segment.generic_args(),
233 item_segment.infer_args,
237 if let Some(b) = assoc_bindings.first() {
238 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
244 /// Given the type/lifetime/const arguments provided to some path (along with
245 /// an implicit `Self`, if this is a trait reference), returns the complete
246 /// set of substitutions. This may involve applying defaulted type parameters.
247 /// Also returns back constraints on associated types.
252 /// T: std::ops::Index<usize, Output = u32>
253 /// ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4
256 /// 1. The `self_ty` here would refer to the type `T`.
257 /// 2. The path in question is the path to the trait `std::ops::Index`,
258 /// which will have been resolved to a `def_id`
259 /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
260 /// parameters are returned in the `SubstsRef`, the associated type bindings like
261 /// `Output = u32` are returned in the `Vec<ConvertedBinding...>` result.
263 /// Note that the type listing given here is *exactly* what the user provided.
265 /// For (generic) associated types
268 /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
271 /// We have the parent substs are the substs for the parent trait:
272 /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
273 /// type itself: `['a]`. The returned `SubstsRef` concatenates these two
274 /// lists: `[Vec<u8>, u8, 'a]`.
275 fn create_substs_for_ast_path<'a>(
279 parent_substs: &[subst::GenericArg<'tcx>],
280 generic_args: &'a hir::GenericArgs<'_>,
282 self_ty: Option<Ty<'tcx>>,
283 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, GenericArgCountResult) {
284 // If the type is parameterized by this region, then replace this
285 // region with the current anon region binding (in other words,
286 // whatever & would get replaced with).
288 "create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
290 def_id, self_ty, generic_args
293 let tcx = self.tcx();
294 let generic_params = tcx.generics_of(def_id);
296 if generic_params.has_self {
297 if generic_params.parent.is_some() {
298 // The parent is a trait so it should have at least one subst
299 // for the `Self` type.
300 assert!(!parent_substs.is_empty())
302 // This item (presumably a trait) needs a self-type.
303 assert!(self_ty.is_some());
306 assert!(self_ty.is_none() && parent_substs.is_empty());
309 let arg_count = Self::check_generic_arg_count(
314 GenericArgPosition::Type,
319 let is_object = self_ty.map_or(false, |ty| ty == self.tcx().types.trait_object_dummy_self);
320 let default_needs_object_self = |param: &ty::GenericParamDef| {
321 if let GenericParamDefKind::Type { has_default, .. } = param.kind {
322 if is_object && has_default {
323 let default_ty = tcx.at(span).type_of(param.def_id);
324 let self_param = tcx.types.self_param;
325 if default_ty.walk().any(|arg| arg == self_param.into()) {
326 // There is no suitable inference default for a type parameter
327 // that references self, in an object type.
336 let mut missing_type_params = vec![];
337 let mut inferred_params = vec![];
338 let substs = Self::create_substs_for_generic_args(
345 // Provide the generic args, and whether types should be inferred.
348 (Some(generic_args), infer_args)
350 // The last component of this tuple is unimportant.
354 // Provide substitutions for parameters for which (valid) arguments have been provided.
355 |param, arg| match (¶m.kind, arg) {
356 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
357 self.ast_region_to_region(<, Some(param)).into()
359 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
360 if let (hir::TyKind::Infer, false) = (&ty.kind, self.allow_ty_infer()) {
361 inferred_params.push(ty.span);
362 tcx.ty_error().into()
364 self.ast_ty_to_ty(&ty).into()
367 (GenericParamDefKind::Const, GenericArg::Const(ct)) => {
368 ty::Const::from_opt_const_arg_anon_const(
370 ty::WithOptConstParam {
371 did: tcx.hir().local_def_id(ct.value.hir_id),
372 const_param_did: Some(param.def_id),
379 // Provide substitutions for parameters for which arguments are inferred.
380 |substs, param, infer_args| {
382 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
383 GenericParamDefKind::Type { has_default, .. } => {
384 if !infer_args && has_default {
385 // No type parameter provided, but a default exists.
387 // If we are converting an object type, then the
388 // `Self` parameter is unknown. However, some of the
389 // other type parameters may reference `Self` in their
390 // defaults. This will lead to an ICE if we are not
392 if default_needs_object_self(param) {
393 missing_type_params.push(param.name.to_string());
394 tcx.ty_error().into()
396 // This is a default type parameter.
399 tcx.at(span).type_of(param.def_id).subst_spanned(
407 } else if infer_args {
408 // No type parameters were provided, we can infer all.
410 if !default_needs_object_self(param) { Some(param) } else { None };
411 self.ty_infer(param, span).into()
413 // We've already errored above about the mismatch.
414 tcx.ty_error().into()
417 GenericParamDefKind::Const => {
418 let ty = tcx.at(span).type_of(param.def_id);
419 // FIXME(const_generics:defaults)
421 // No const parameters were provided, we can infer all.
422 self.ct_infer(ty, Some(param), span).into()
424 // We've already errored above about the mismatch.
425 tcx.const_error(ty).into()
432 self.complain_about_missing_type_params(
436 generic_args.args.is_empty(),
439 // Convert associated-type bindings or constraints into a separate vector.
440 // Example: Given this:
442 // T: Iterator<Item = u32>
444 // The `T` is passed in as a self-type; the `Item = u32` is
445 // not a "type parameter" of the `Iterator` trait, but rather
446 // a restriction on `<T as Iterator>::Item`, so it is passed
448 let assoc_bindings = generic_args
452 let kind = match binding.kind {
453 hir::TypeBindingKind::Equality { ref ty } => {
454 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty))
456 hir::TypeBindingKind::Constraint { ref bounds } => {
457 ConvertedBindingKind::Constraint(bounds)
460 ConvertedBinding { item_name: binding.ident, kind, span: binding.span }
465 "create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
466 generic_params, self_ty, substs
469 (substs, assoc_bindings, arg_count)
472 crate fn create_substs_for_associated_item(
477 item_segment: &hir::PathSegment<'_>,
478 parent_substs: SubstsRef<'tcx>,
479 ) -> SubstsRef<'tcx> {
480 if tcx.generics_of(item_def_id).params.is_empty() {
481 self.prohibit_generics(slice::from_ref(item_segment));
485 self.create_substs_for_ast_path(
489 item_segment.generic_args(),
490 item_segment.infer_args,
497 /// Instantiates the path for the given trait reference, assuming that it's
498 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
499 /// The type _cannot_ be a type other than a trait type.
501 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
502 /// are disallowed. Otherwise, they are pushed onto the vector given.
503 pub fn instantiate_mono_trait_ref(
505 trait_ref: &hir::TraitRef<'_>,
507 ) -> ty::TraitRef<'tcx> {
508 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
510 self.ast_path_to_mono_trait_ref(
512 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
514 trait_ref.path.segments.last().unwrap(),
518 /// The given trait-ref must actually be a trait.
519 pub(super) fn instantiate_poly_trait_ref_inner(
521 trait_ref: &hir::TraitRef<'_>,
523 constness: Constness,
525 bounds: &mut Bounds<'tcx>,
527 ) -> GenericArgCountResult {
528 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
530 debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
532 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
534 let (substs, assoc_bindings, arg_count) = self.create_substs_for_ast_trait_ref(
538 trait_ref.path.segments.last().unwrap(),
540 let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
542 bounds.trait_bounds.push((poly_trait_ref, span, constness));
544 let mut dup_bindings = FxHashMap::default();
545 for binding in &assoc_bindings {
546 // Specify type to assert that error was already reported in `Err` case.
547 let _: Result<_, ErrorReported> = self.add_predicates_for_ast_type_binding(
548 trait_ref.hir_ref_id,
556 // Okay to ignore `Err` because of `ErrorReported` (see above).
560 "instantiate_poly_trait_ref({:?}, bounds={:?}) -> {:?}",
561 trait_ref, bounds, poly_trait_ref
567 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
568 /// a full trait reference. The resulting trait reference is returned. This may also generate
569 /// auxiliary bounds, which are added to `bounds`.
574 /// poly_trait_ref = Iterator<Item = u32>
578 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
580 /// **A note on binders:** against our usual convention, there is an implied bounder around
581 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
582 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
583 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
584 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
586 pub fn instantiate_poly_trait_ref(
588 poly_trait_ref: &hir::PolyTraitRef<'_>,
589 constness: Constness,
591 bounds: &mut Bounds<'tcx>,
592 ) -> GenericArgCountResult {
593 self.instantiate_poly_trait_ref_inner(
594 &poly_trait_ref.trait_ref,
603 pub fn instantiate_lang_item_trait_ref(
605 lang_item: hir::LangItem,
608 args: &GenericArgs<'_>,
610 bounds: &mut Bounds<'tcx>,
612 let trait_def_id = self.tcx().require_lang_item(lang_item, Some(span));
614 let (substs, assoc_bindings, _) =
615 self.create_substs_for_ast_path(span, trait_def_id, &[], args, false, Some(self_ty));
616 let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
617 bounds.trait_bounds.push((poly_trait_ref, span, Constness::NotConst));
619 let mut dup_bindings = FxHashMap::default();
620 for binding in assoc_bindings {
621 let _: Result<_, ErrorReported> = self.add_predicates_for_ast_type_binding(
633 fn ast_path_to_mono_trait_ref(
638 trait_segment: &hir::PathSegment<'_>,
639 ) -> ty::TraitRef<'tcx> {
640 let (substs, assoc_bindings, _) =
641 self.create_substs_for_ast_trait_ref(span, trait_def_id, self_ty, trait_segment);
642 if let Some(b) = assoc_bindings.first() {
643 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
645 ty::TraitRef::new(trait_def_id, substs)
648 fn create_substs_for_ast_trait_ref<'a>(
653 trait_segment: &'a hir::PathSegment<'a>,
654 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, GenericArgCountResult) {
655 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})", trait_segment);
657 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment);
659 self.create_substs_for_ast_path(
663 trait_segment.generic_args(),
664 trait_segment.infer_args,
669 fn trait_defines_associated_type_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
671 .associated_items(trait_def_id)
672 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, trait_def_id)
676 // Returns `true` if a bounds list includes `?Sized`.
677 pub fn is_unsized(&self, ast_bounds: &[hir::GenericBound<'_>], span: Span) -> bool {
678 let tcx = self.tcx();
680 // Try to find an unbound in bounds.
681 let mut unbound = None;
682 for ab in ast_bounds {
683 if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
684 if unbound.is_none() {
685 unbound = Some(&ptr.trait_ref);
691 "type parameter has more than one relaxed default \
692 bound, only one is supported"
699 let kind_id = tcx.lang_items().require(LangItem::Sized);
702 // FIXME(#8559) currently requires the unbound to be built-in.
703 if let Ok(kind_id) = kind_id {
704 if tpb.path.res != Res::Def(DefKind::Trait, kind_id) {
707 "default bound relaxed for a type parameter, but \
708 this does nothing because the given bound is not \
709 a default; only `?Sized` is supported",
714 _ if kind_id.is_ok() => {
717 // No lang item for `Sized`, so we can't add it as a bound.
724 /// This helper takes a *converted* parameter type (`param_ty`)
725 /// and an *unconverted* list of bounds:
729 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
731 /// `param_ty`, in ty form
734 /// It adds these `ast_bounds` into the `bounds` structure.
736 /// **A note on binders:** there is an implied binder around
737 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
738 /// for more details.
742 ast_bounds: &[hir::GenericBound<'_>],
743 bounds: &mut Bounds<'tcx>,
745 let mut trait_bounds = Vec::new();
746 let mut region_bounds = Vec::new();
748 let constness = self.default_constness_for_trait_bounds();
749 for ast_bound in ast_bounds {
751 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => {
752 trait_bounds.push((b, constness))
754 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::MaybeConst) => {
755 trait_bounds.push((b, Constness::NotConst))
757 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
758 hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => self
759 .instantiate_lang_item_trait_ref(
760 lang_item, span, hir_id, args, param_ty, bounds,
762 hir::GenericBound::Outlives(ref l) => region_bounds.push(l),
766 for (bound, constness) in trait_bounds {
767 let _ = self.instantiate_poly_trait_ref(bound, constness, param_ty, bounds);
770 bounds.region_bounds.extend(
771 region_bounds.into_iter().map(|r| (self.ast_region_to_region(r, None), r.span)),
775 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
776 /// The self-type for the bounds is given by `param_ty`.
781 /// fn foo<T: Bar + Baz>() { }
782 /// ^ ^^^^^^^^^ ast_bounds
786 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
787 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
788 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
790 /// `span` should be the declaration size of the parameter.
791 pub fn compute_bounds(
794 ast_bounds: &[hir::GenericBound<'_>],
795 sized_by_default: SizedByDefault,
798 let mut bounds = Bounds::default();
800 self.add_bounds(param_ty, ast_bounds, &mut bounds);
801 bounds.trait_bounds.sort_by_key(|(t, _, _)| t.def_id());
803 bounds.implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
804 if !self.is_unsized(ast_bounds, span) { Some(span) } else { None }
812 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
815 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
816 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
817 /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
818 fn add_predicates_for_ast_type_binding(
820 hir_ref_id: hir::HirId,
821 trait_ref: ty::PolyTraitRef<'tcx>,
822 binding: &ConvertedBinding<'_, 'tcx>,
823 bounds: &mut Bounds<'tcx>,
825 dup_bindings: &mut FxHashMap<DefId, Span>,
827 ) -> Result<(), ErrorReported> {
828 let tcx = self.tcx();
831 // Given something like `U: SomeTrait<T = X>`, we want to produce a
832 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
833 // subtle in the event that `T` is defined in a supertrait of
834 // `SomeTrait`, because in that case we need to upcast.
836 // That is, consider this case:
839 // trait SubTrait: SuperTrait<i32> { }
840 // trait SuperTrait<A> { type T; }
842 // ... B: SubTrait<T = foo> ...
845 // We want to produce `<B as SuperTrait<i32>>::T == foo`.
847 // Find any late-bound regions declared in `ty` that are not
848 // declared in the trait-ref. These are not well-formed.
852 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
853 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
854 if let ConvertedBindingKind::Equality(ty) = binding.kind {
855 let late_bound_in_trait_ref =
856 tcx.collect_constrained_late_bound_regions(&trait_ref);
857 let late_bound_in_ty =
858 tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(ty));
859 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
860 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
862 // FIXME: point at the type params that don't have appropriate lifetimes:
863 // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
865 self.validate_late_bound_regions(
866 late_bound_in_trait_ref,
873 "binding for associated type `{}` references {}, \
874 which does not appear in the trait input types",
884 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
885 // Simple case: X is defined in the current trait.
888 // Otherwise, we have to walk through the supertraits to find
890 self.one_bound_for_assoc_type(
891 || traits::supertraits(tcx, trait_ref),
892 || trait_ref.print_only_trait_path().to_string(),
895 || match binding.kind {
896 ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
902 let (assoc_ident, def_scope) =
903 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
905 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
906 // of calling `filter_by_name_and_kind`.
908 .associated_items(candidate.def_id())
909 .filter_by_name_unhygienic(assoc_ident.name)
911 i.kind == ty::AssocKind::Type && i.ident.normalize_to_macros_2_0() == assoc_ident
913 .expect("missing associated type");
915 if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
919 &format!("associated type `{}` is private", binding.item_name),
921 .span_label(binding.span, "private associated type")
924 tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span);
928 .entry(assoc_ty.def_id)
929 .and_modify(|prev_span| {
934 "the value of the associated type `{}` (from trait `{}`) \
935 is already specified",
937 tcx.def_path_str(assoc_ty.container.id())
939 .span_label(binding.span, "re-bound here")
940 .span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
943 .or_insert(binding.span);
947 ConvertedBindingKind::Equality(ref ty) => {
948 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
949 // the "projection predicate" for:
951 // `<T as Iterator>::Item = u32`
952 bounds.projection_bounds.push((
953 candidate.map_bound(|trait_ref| ty::ProjectionPredicate {
954 projection_ty: ty::ProjectionTy::from_ref_and_name(
964 ConvertedBindingKind::Constraint(ast_bounds) => {
965 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
967 // `<T as Iterator>::Item: Debug`
969 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
970 // parameter to have a skipped binder.
971 let param_ty = tcx.mk_projection(assoc_ty.def_id, candidate.skip_binder().substs);
972 self.add_bounds(param_ty, ast_bounds, bounds);
982 item_segment: &hir::PathSegment<'_>,
984 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
985 self.normalize_ty(span, self.tcx().at(span).type_of(did).subst(self.tcx(), substs))
988 fn conv_object_ty_poly_trait_ref(
991 trait_bounds: &[hir::PolyTraitRef<'_>],
992 lifetime: &hir::Lifetime,
995 let tcx = self.tcx();
997 let mut bounds = Bounds::default();
998 let mut potential_assoc_types = Vec::new();
999 let dummy_self = self.tcx().types.trait_object_dummy_self;
1000 for trait_bound in trait_bounds.iter().rev() {
1001 if let GenericArgCountResult {
1003 Err(GenericArgCountMismatch { invalid_args: cur_potential_assoc_types, .. }),
1005 } = self.instantiate_poly_trait_ref(
1007 Constness::NotConst,
1011 potential_assoc_types.extend(cur_potential_assoc_types.into_iter());
1015 // Expand trait aliases recursively and check that only one regular (non-auto) trait
1016 // is used and no 'maybe' bounds are used.
1017 let expanded_traits =
1018 traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().map(|&(a, b, _)| (a, b)));
1019 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) =
1020 expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1021 if regular_traits.len() > 1 {
1022 let first_trait = ®ular_traits[0];
1023 let additional_trait = ®ular_traits[1];
1024 let mut err = struct_span_err!(
1026 additional_trait.bottom().1,
1028 "only auto traits can be used as additional traits in a trait object"
1030 additional_trait.label_with_exp_info(
1032 "additional non-auto trait",
1035 first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1037 "consider creating a new trait with all of these as super-traits and using that \
1038 trait here instead: `trait NewTrait: {} {{}}`",
1041 .map(|t| t.trait_ref().print_only_trait_path().to_string())
1042 .collect::<Vec<_>>()
1046 "auto-traits like `Send` and `Sync` are traits that have special properties; \
1047 for more information on them, visit \
1048 <https://doc.rust-lang.org/reference/special-types-and-traits.html#auto-traits>",
1053 if regular_traits.is_empty() && auto_traits.is_empty() {
1058 "at least one trait is required for an object type"
1061 return tcx.ty_error();
1064 // Check that there are no gross object safety violations;
1065 // most importantly, that the supertraits don't contain `Self`,
1067 for item in ®ular_traits {
1068 let object_safety_violations =
1069 astconv_object_safety_violations(tcx, item.trait_ref().def_id());
1070 if !object_safety_violations.is_empty() {
1071 report_object_safety_error(
1074 item.trait_ref().def_id(),
1075 &object_safety_violations[..],
1078 return tcx.ty_error();
1082 // Use a `BTreeSet` to keep output in a more consistent order.
1083 let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1085 let regular_traits_refs_spans = bounds
1088 .filter(|(trait_ref, _, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1090 for (base_trait_ref, span, constness) in regular_traits_refs_spans {
1091 assert_eq!(constness, Constness::NotConst);
1093 for obligation in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1095 "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1096 obligation.predicate
1099 match obligation.predicate.skip_binders() {
1100 ty::PredicateAtom::Trait(pred, _) => {
1101 let pred = ty::Binder::bind(pred);
1102 associated_types.entry(span).or_default().extend(
1103 tcx.associated_items(pred.def_id())
1104 .in_definition_order()
1105 .filter(|item| item.kind == ty::AssocKind::Type)
1106 .map(|item| item.def_id),
1109 ty::PredicateAtom::Projection(pred) => {
1110 let pred = ty::Binder::bind(pred);
1111 // A `Self` within the original bound will be substituted with a
1112 // `trait_object_dummy_self`, so check for that.
1113 let references_self =
1114 pred.skip_binder().ty.walk().any(|arg| arg == dummy_self.into());
1116 // If the projection output contains `Self`, force the user to
1117 // elaborate it explicitly to avoid a lot of complexity.
1119 // The "classicaly useful" case is the following:
1121 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1126 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1127 // but actually supporting that would "expand" to an infinitely-long type
1128 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1130 // Instead, we force the user to write
1131 // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1132 // the discussion in #56288 for alternatives.
1133 if !references_self {
1134 // Include projections defined on supertraits.
1135 bounds.projection_bounds.push((pred, span));
1143 for (projection_bound, _) in &bounds.projection_bounds {
1144 for def_ids in associated_types.values_mut() {
1145 def_ids.remove(&projection_bound.projection_def_id());
1149 self.complain_about_missing_associated_types(
1151 potential_assoc_types,
1155 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1156 // `dyn Trait + Send`.
1157 auto_traits.sort_by_key(|i| i.trait_ref().def_id());
1158 auto_traits.dedup_by_key(|i| i.trait_ref().def_id());
1159 debug!("regular_traits: {:?}", regular_traits);
1160 debug!("auto_traits: {:?}", auto_traits);
1162 // Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
1163 // removing the dummy `Self` type (`trait_object_dummy_self`).
1164 let trait_ref_to_existential = |trait_ref: ty::TraitRef<'tcx>| {
1165 if trait_ref.self_ty() != dummy_self {
1166 // FIXME: There appears to be a missing filter on top of `expand_trait_aliases`,
1167 // which picks up non-supertraits where clauses - but also, the object safety
1168 // completely ignores trait aliases, which could be object safety hazards. We
1169 // `delay_span_bug` here to avoid an ICE in stable even when the feature is
1170 // disabled. (#66420)
1171 tcx.sess.delay_span_bug(
1174 "trait_ref_to_existential called on {:?} with non-dummy Self",
1179 ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
1182 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1183 let existential_trait_refs =
1184 regular_traits.iter().map(|i| i.trait_ref().map_bound(trait_ref_to_existential));
1185 let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1186 bound.map_bound(|b| {
1187 let trait_ref = trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1188 ty::ExistentialProjection {
1190 item_def_id: b.projection_ty.item_def_id,
1191 substs: trait_ref.substs,
1196 // Calling `skip_binder` is okay because the predicates are re-bound.
1197 let regular_trait_predicates = existential_trait_refs
1198 .map(|trait_ref| ty::ExistentialPredicate::Trait(trait_ref.skip_binder()));
1199 let auto_trait_predicates = auto_traits
1201 .map(|trait_ref| ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()));
1202 let mut v = regular_trait_predicates
1203 .chain(auto_trait_predicates)
1205 existential_projections
1206 .map(|x| ty::ExistentialPredicate::Projection(x.skip_binder())),
1208 .collect::<SmallVec<[_; 8]>>();
1209 v.sort_by(|a, b| a.stable_cmp(tcx, b));
1211 let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1213 // Use explicitly-specified region bound.
1214 let region_bound = if !lifetime.is_elided() {
1215 self.ast_region_to_region(lifetime, None)
1217 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1218 if tcx.named_region(lifetime.hir_id).is_some() {
1219 self.ast_region_to_region(lifetime, None)
1221 self.re_infer(None, span).unwrap_or_else(|| {
1222 let mut err = struct_span_err!(
1226 "the lifetime bound for this object type cannot be deduced \
1227 from context; please supply an explicit bound"
1230 // We will have already emitted an error E0106 complaining about a
1231 // missing named lifetime in `&dyn Trait`, so we elide this one.
1236 tcx.lifetimes.re_static
1241 debug!("region_bound: {:?}", region_bound);
1243 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1244 debug!("trait_object_type: {:?}", ty);
1248 fn report_ambiguous_associated_type(
1255 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1256 if let (Some(_), Ok(snippet)) = (
1257 self.tcx().sess.confused_type_with_std_module.borrow().get(&span),
1258 self.tcx().sess.source_map().span_to_snippet(span),
1260 err.span_suggestion(
1262 "you are looking for the module in `std`, not the primitive type",
1263 format!("std::{}", snippet),
1264 Applicability::MachineApplicable,
1267 err.span_suggestion(
1269 "use fully-qualified syntax",
1270 format!("<{} as {}>::{}", type_str, trait_str, name),
1271 Applicability::HasPlaceholders,
1277 // Search for a bound on a type parameter which includes the associated item
1278 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1279 // This function will fail if there are no suitable bounds or there is
1281 fn find_bound_for_assoc_item(
1283 ty_param_def_id: LocalDefId,
1286 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported> {
1287 let tcx = self.tcx();
1290 "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
1291 ty_param_def_id, assoc_name, span,
1295 &self.get_type_parameter_bounds(span, ty_param_def_id.to_def_id()).predicates;
1297 debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1299 let param_hir_id = tcx.hir().local_def_id_to_hir_id(ty_param_def_id);
1300 let param_name = tcx.hir().ty_param_name(param_hir_id);
1301 self.one_bound_for_assoc_type(
1303 traits::transitive_bounds(
1305 predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref()),
1308 || param_name.to_string(),
1315 // Checks that `bounds` contains exactly one element and reports appropriate
1316 // errors otherwise.
1317 fn one_bound_for_assoc_type<I>(
1319 all_candidates: impl Fn() -> I,
1320 ty_param_name: impl Fn() -> String,
1323 is_equality: impl Fn() -> Option<String>,
1324 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1326 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1328 let mut matching_candidates = all_candidates()
1329 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
1331 let bound = match matching_candidates.next() {
1332 Some(bound) => bound,
1334 self.complain_about_assoc_type_not_found(
1340 return Err(ErrorReported);
1344 debug!("one_bound_for_assoc_type: bound = {:?}", bound);
1346 if let Some(bound2) = matching_candidates.next() {
1347 debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2);
1349 let is_equality = is_equality();
1350 let bounds = iter::once(bound).chain(iter::once(bound2)).chain(matching_candidates);
1351 let mut err = if is_equality.is_some() {
1352 // More specific Error Index entry.
1357 "ambiguous associated type `{}` in bounds of `{}`",
1366 "ambiguous associated type `{}` in bounds of `{}`",
1371 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1373 let mut where_bounds = vec![];
1374 for bound in bounds {
1375 let bound_id = bound.def_id();
1376 let bound_span = self
1378 .associated_items(bound_id)
1379 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, bound_id)
1380 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1382 if let Some(bound_span) = bound_span {
1386 "ambiguous `{}` from `{}`",
1388 bound.print_only_trait_path(),
1391 if let Some(constraint) = &is_equality {
1392 where_bounds.push(format!(
1393 " T: {trait}::{assoc} = {constraint}",
1394 trait=bound.print_only_trait_path(),
1396 constraint=constraint,
1399 err.span_suggestion(
1401 "use fully qualified syntax to disambiguate",
1405 bound.print_only_trait_path(),
1408 Applicability::MaybeIncorrect,
1413 "associated type `{}` could derive from `{}`",
1415 bound.print_only_trait_path(),
1419 if !where_bounds.is_empty() {
1421 "consider introducing a new type parameter `T` and adding `where` constraints:\
1422 \n where\n T: {},\n{}",
1424 where_bounds.join(",\n"),
1428 if !where_bounds.is_empty() {
1429 return Err(ErrorReported);
1435 // Create a type from a path to an associated type.
1436 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
1437 // and item_segment is the path segment for `D`. We return a type and a def for
1439 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
1440 // parameter or `Self`.
1441 pub fn associated_path_to_ty(
1443 hir_ref_id: hir::HirId,
1447 assoc_segment: &hir::PathSegment<'_>,
1448 permit_variants: bool,
1449 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> {
1450 let tcx = self.tcx();
1451 let assoc_ident = assoc_segment.ident;
1453 debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
1455 // Check if we have an enum variant.
1456 let mut variant_resolution = None;
1457 if let ty::Adt(adt_def, _) = qself_ty.kind {
1458 if adt_def.is_enum() {
1459 let variant_def = adt_def
1462 .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did));
1463 if let Some(variant_def) = variant_def {
1464 if permit_variants {
1465 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span);
1466 self.prohibit_generics(slice::from_ref(assoc_segment));
1467 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
1469 variant_resolution = Some(variant_def.def_id);
1475 // Find the type of the associated item, and the trait where the associated
1476 // item is declared.
1477 let bound = match (&qself_ty.kind, qself_res) {
1478 (_, Res::SelfTy(Some(_), Some(impl_def_id))) => {
1479 // `Self` in an impl of a trait -- we have a concrete self type and a
1481 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
1482 Some(trait_ref) => trait_ref,
1484 // A cycle error occurred, most likely.
1485 return Err(ErrorReported);
1489 self.one_bound_for_assoc_type(
1490 || traits::supertraits(tcx, ty::Binder::bind(trait_ref)),
1491 || "Self".to_string(),
1499 Res::SelfTy(Some(param_did), None) | Res::Def(DefKind::TyParam, param_did),
1500 ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?,
1502 if variant_resolution.is_some() {
1503 // Variant in type position
1504 let msg = format!("expected type, found variant `{}`", assoc_ident);
1505 tcx.sess.span_err(span, &msg);
1506 } else if qself_ty.is_enum() {
1507 let mut err = struct_span_err!(
1511 "no variant named `{}` found for enum `{}`",
1516 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
1517 if let Some(suggested_name) = find_best_match_for_name(
1518 adt_def.variants.iter().map(|variant| &variant.ident.name),
1522 err.span_suggestion(
1524 "there is a variant with a similar name",
1525 suggested_name.to_string(),
1526 Applicability::MaybeIncorrect,
1531 format!("variant not found in `{}`", qself_ty),
1535 if let Some(sp) = tcx.hir().span_if_local(adt_def.did) {
1536 let sp = tcx.sess.source_map().guess_head_span(sp);
1537 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
1541 } else if !qself_ty.references_error() {
1542 // Don't print `TyErr` to the user.
1543 self.report_ambiguous_associated_type(
1545 &qself_ty.to_string(),
1550 return Err(ErrorReported);
1554 let trait_did = bound.def_id();
1555 let (assoc_ident, def_scope) =
1556 tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
1558 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1559 // of calling `filter_by_name_and_kind`.
1561 .associated_items(trait_did)
1562 .in_definition_order()
1564 i.kind.namespace() == Namespace::TypeNS
1565 && i.ident.normalize_to_macros_2_0() == assoc_ident
1567 .expect("missing associated type");
1569 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);
1570 let ty = self.normalize_ty(span, ty);
1572 let kind = DefKind::AssocTy;
1573 if !item.vis.is_accessible_from(def_scope, tcx) {
1574 let kind = kind.descr(item.def_id);
1575 let msg = format!("{} `{}` is private", kind, assoc_ident);
1577 .struct_span_err(span, &msg)
1578 .span_label(span, &format!("private {}", kind))
1581 tcx.check_stability(item.def_id, Some(hir_ref_id), span);
1583 if let Some(variant_def_id) = variant_resolution {
1584 tcx.struct_span_lint_hir(AMBIGUOUS_ASSOCIATED_ITEMS, hir_ref_id, span, |lint| {
1585 let mut err = lint.build("ambiguous associated item");
1586 let mut could_refer_to = |kind: DefKind, def_id, also| {
1587 let note_msg = format!(
1588 "`{}` could{} refer to the {} defined here",
1593 err.span_note(tcx.def_span(def_id), ¬e_msg);
1596 could_refer_to(DefKind::Variant, variant_def_id, "");
1597 could_refer_to(kind, item.def_id, " also");
1599 err.span_suggestion(
1601 "use fully-qualified syntax",
1602 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
1603 Applicability::MachineApplicable,
1609 Ok((ty, kind, item.def_id))
1615 opt_self_ty: Option<Ty<'tcx>>,
1617 trait_segment: &hir::PathSegment<'_>,
1618 item_segment: &hir::PathSegment<'_>,
1620 let tcx = self.tcx();
1622 let trait_def_id = tcx.parent(item_def_id).unwrap();
1624 debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
1626 let self_ty = if let Some(ty) = opt_self_ty {
1629 let path_str = tcx.def_path_str(trait_def_id);
1631 let def_id = self.item_def_id();
1633 debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
1635 let parent_def_id = def_id
1636 .and_then(|def_id| {
1637 def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
1639 .map(|hir_id| tcx.hir().get_parent_did(hir_id).to_def_id());
1641 debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
1643 // If the trait in segment is the same as the trait defining the item,
1644 // use the `<Self as ..>` syntax in the error.
1645 let is_part_of_self_trait_constraints = def_id == Some(trait_def_id);
1646 let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
1648 let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
1654 self.report_ambiguous_associated_type(
1658 item_segment.ident.name,
1660 return tcx.ty_error();
1663 debug!("qpath_to_ty: self_type={:?}", self_ty);
1665 let trait_ref = self.ast_path_to_mono_trait_ref(span, trait_def_id, self_ty, trait_segment);
1667 let item_substs = self.create_substs_for_associated_item(
1675 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1677 self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
1680 pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment<'a>>>(
1684 let mut has_err = false;
1685 for segment in segments {
1686 let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
1687 for arg in segment.generic_args().args {
1688 let (span, kind) = match arg {
1689 hir::GenericArg::Lifetime(lt) => {
1695 (lt.span, "lifetime")
1697 hir::GenericArg::Type(ty) => {
1705 hir::GenericArg::Const(ct) => {
1714 let mut err = struct_span_err!(
1718 "{} arguments are not allowed for this type",
1721 err.span_label(span, format!("{} argument not allowed", kind));
1723 if err_for_lt && err_for_ty && err_for_ct {
1728 // Only emit the first error to avoid overloading the user with error messages.
1729 if let [binding, ..] = segment.generic_args().bindings {
1731 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
1737 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
1738 pub fn def_ids_for_value_path_segments(
1740 segments: &[hir::PathSegment<'_>],
1741 self_ty: Option<Ty<'tcx>>,
1745 // We need to extract the type parameters supplied by the user in
1746 // the path `path`. Due to the current setup, this is a bit of a
1747 // tricky-process; the problem is that resolve only tells us the
1748 // end-point of the path resolution, and not the intermediate steps.
1749 // Luckily, we can (at least for now) deduce the intermediate steps
1750 // just from the end-point.
1752 // There are basically five cases to consider:
1754 // 1. Reference to a constructor of a struct:
1756 // struct Foo<T>(...)
1758 // In this case, the parameters are declared in the type space.
1760 // 2. Reference to a constructor of an enum variant:
1762 // enum E<T> { Foo(...) }
1764 // In this case, the parameters are defined in the type space,
1765 // but may be specified either on the type or the variant.
1767 // 3. Reference to a fn item or a free constant:
1771 // In this case, the path will again always have the form
1772 // `a::b::foo::<T>` where only the final segment should have
1773 // type parameters. However, in this case, those parameters are
1774 // declared on a value, and hence are in the `FnSpace`.
1776 // 4. Reference to a method or an associated constant:
1778 // impl<A> SomeStruct<A> {
1782 // Here we can have a path like
1783 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
1784 // may appear in two places. The penultimate segment,
1785 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
1786 // final segment, `foo::<B>` contains parameters in fn space.
1788 // The first step then is to categorize the segments appropriately.
1790 let tcx = self.tcx();
1792 assert!(!segments.is_empty());
1793 let last = segments.len() - 1;
1795 let mut path_segs = vec![];
1798 // Case 1. Reference to a struct constructor.
1799 DefKind::Ctor(CtorOf::Struct, ..) => {
1800 // Everything but the final segment should have no
1801 // parameters at all.
1802 let generics = tcx.generics_of(def_id);
1803 // Variant and struct constructors use the
1804 // generics of their parent type definition.
1805 let generics_def_id = generics.parent.unwrap_or(def_id);
1806 path_segs.push(PathSeg(generics_def_id, last));
1809 // Case 2. Reference to a variant constructor.
1810 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
1811 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
1812 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
1813 debug_assert!(adt_def.is_enum());
1815 } else if last >= 1 && segments[last - 1].args.is_some() {
1816 // Everything but the penultimate segment should have no
1817 // parameters at all.
1818 let mut def_id = def_id;
1820 // `DefKind::Ctor` -> `DefKind::Variant`
1821 if let DefKind::Ctor(..) = kind {
1822 def_id = tcx.parent(def_id).unwrap()
1825 // `DefKind::Variant` -> `DefKind::Enum`
1826 let enum_def_id = tcx.parent(def_id).unwrap();
1827 (enum_def_id, last - 1)
1829 // FIXME: lint here recommending `Enum::<...>::Variant` form
1830 // instead of `Enum::Variant::<...>` form.
1832 // Everything but the final segment should have no
1833 // parameters at all.
1834 let generics = tcx.generics_of(def_id);
1835 // Variant and struct constructors use the
1836 // generics of their parent type definition.
1837 (generics.parent.unwrap_or(def_id), last)
1839 path_segs.push(PathSeg(generics_def_id, index));
1842 // Case 3. Reference to a top-level value.
1843 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static => {
1844 path_segs.push(PathSeg(def_id, last));
1847 // Case 4. Reference to a method or associated const.
1848 DefKind::AssocFn | DefKind::AssocConst => {
1849 if segments.len() >= 2 {
1850 let generics = tcx.generics_of(def_id);
1851 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
1853 path_segs.push(PathSeg(def_id, last));
1856 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
1859 debug!("path_segs = {:?}", path_segs);
1864 // Check a type `Path` and convert it to a `Ty`.
1867 opt_self_ty: Option<Ty<'tcx>>,
1868 path: &hir::Path<'_>,
1869 permit_variants: bool,
1871 let tcx = self.tcx();
1874 "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
1875 path.res, opt_self_ty, path.segments
1878 let span = path.span;
1880 Res::Def(DefKind::OpaqueTy, did) => {
1881 // Check for desugared `impl Trait`.
1882 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
1883 let item_segment = path.segments.split_last().unwrap();
1884 self.prohibit_generics(item_segment.1);
1885 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
1886 self.normalize_ty(span, tcx.mk_opaque(did, substs))
1893 | DefKind::ForeignTy,
1896 assert_eq!(opt_self_ty, None);
1897 self.prohibit_generics(path.segments.split_last().unwrap().1);
1898 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
1900 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
1901 // Convert "variant type" as if it were a real type.
1902 // The resulting `Ty` is type of the variant's enum for now.
1903 assert_eq!(opt_self_ty, None);
1906 self.def_ids_for_value_path_segments(&path.segments, None, kind, def_id);
1907 let generic_segs: FxHashSet<_> =
1908 path_segs.iter().map(|PathSeg(_, index)| index).collect();
1909 self.prohibit_generics(path.segments.iter().enumerate().filter_map(
1911 if !generic_segs.contains(&index) { Some(seg) } else { None }
1915 let PathSeg(def_id, index) = path_segs.last().unwrap();
1916 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
1918 Res::Def(DefKind::TyParam, def_id) => {
1919 assert_eq!(opt_self_ty, None);
1920 self.prohibit_generics(path.segments);
1922 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
1923 let item_id = tcx.hir().get_parent_node(hir_id);
1924 let item_def_id = tcx.hir().local_def_id(item_id);
1925 let generics = tcx.generics_of(item_def_id);
1926 let index = generics.param_def_id_to_index[&def_id];
1927 tcx.mk_ty_param(index, tcx.hir().name(hir_id))
1929 Res::SelfTy(Some(_), None) => {
1930 // `Self` in trait or type alias.
1931 assert_eq!(opt_self_ty, None);
1932 self.prohibit_generics(path.segments);
1933 tcx.types.self_param
1935 Res::SelfTy(_, Some(def_id)) => {
1936 // `Self` in impl (we know the concrete type).
1937 assert_eq!(opt_self_ty, None);
1938 self.prohibit_generics(path.segments);
1939 // Try to evaluate any array length constants.
1940 self.normalize_ty(span, tcx.at(span).type_of(def_id))
1942 Res::Def(DefKind::AssocTy, def_id) => {
1943 debug_assert!(path.segments.len() >= 2);
1944 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
1949 &path.segments[path.segments.len() - 2],
1950 path.segments.last().unwrap(),
1953 Res::PrimTy(prim_ty) => {
1954 assert_eq!(opt_self_ty, None);
1955 self.prohibit_generics(path.segments);
1957 hir::PrimTy::Bool => tcx.types.bool,
1958 hir::PrimTy::Char => tcx.types.char,
1959 hir::PrimTy::Int(it) => tcx.mk_mach_int(it),
1960 hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(uit),
1961 hir::PrimTy::Float(ft) => tcx.mk_mach_float(ft),
1962 hir::PrimTy::Str => tcx.types.str_,
1966 self.set_tainted_by_errors();
1967 self.tcx().ty_error()
1969 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
1973 /// Parses the programmer's textual representation of a type into our
1974 /// internal notion of a type.
1975 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
1976 self.ast_ty_to_ty_inner(ast_ty, false)
1979 /// Turns a `hir::Ty` into a `Ty`. For diagnostics' purposes we keep track of whether trait
1980 /// objects are borrowed like `&dyn Trait` to avoid emitting redundant errors.
1981 fn ast_ty_to_ty_inner(&self, ast_ty: &hir::Ty<'_>, borrowed: bool) -> Ty<'tcx> {
1982 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})", ast_ty.hir_id, ast_ty, ast_ty.kind);
1984 let tcx = self.tcx();
1986 let result_ty = match ast_ty.kind {
1987 hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(&ty)),
1988 hir::TyKind::Ptr(ref mt) => {
1989 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(&mt.ty), mutbl: mt.mutbl })
1991 hir::TyKind::Rptr(ref region, ref mt) => {
1992 let r = self.ast_region_to_region(region, None);
1993 debug!("ast_ty_to_ty: r={:?}", r);
1994 let t = self.ast_ty_to_ty_inner(&mt.ty, true);
1995 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
1997 hir::TyKind::Never => tcx.types.never,
1998 hir::TyKind::Tup(ref fields) => {
1999 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
2001 hir::TyKind::BareFn(ref bf) => {
2002 require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
2003 tcx.mk_fn_ptr(self.ty_of_fn(
2007 &hir::Generics::empty(),
2011 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
2012 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime, borrowed)
2014 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2015 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
2016 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2017 self.res_to_ty(opt_self_ty, path, false)
2019 hir::TyKind::OpaqueDef(item_id, ref lifetimes) => {
2020 let opaque_ty = tcx.hir().expect_item(item_id.id);
2021 let def_id = tcx.hir().local_def_id(item_id.id).to_def_id();
2023 match opaque_ty.kind {
2024 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => {
2025 self.impl_trait_ty_to_ty(def_id, lifetimes, impl_trait_fn.is_some())
2027 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
2030 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2031 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
2032 let ty = self.ast_ty_to_ty(qself);
2034 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.kind {
2039 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2040 .map(|(ty, _, _)| ty)
2041 .unwrap_or_else(|_| tcx.ty_error())
2043 hir::TyKind::Path(hir::QPath::LangItem(lang_item, span)) => {
2044 let def_id = tcx.require_lang_item(lang_item, Some(span));
2045 let (substs, _, _) = self.create_substs_for_ast_path(
2049 &GenericArgs::none(),
2053 self.normalize_ty(span, tcx.at(span).type_of(def_id).subst(tcx, substs))
2055 hir::TyKind::Array(ref ty, ref length) => {
2056 let length_def_id = tcx.hir().local_def_id(length.hir_id);
2057 let length = ty::Const::from_anon_const(tcx, length_def_id);
2058 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
2059 self.normalize_ty(ast_ty.span, array_ty)
2061 hir::TyKind::Typeof(ref _e) => {
2066 "`typeof` is a reserved keyword but unimplemented"
2068 .span_label(ast_ty.span, "reserved keyword")
2073 hir::TyKind::Infer => {
2074 // Infer also appears as the type of arguments or return
2075 // values in a ExprKind::Closure, or as
2076 // the type of local variables. Both of these cases are
2077 // handled specially and will not descend into this routine.
2078 self.ty_infer(None, ast_ty.span)
2080 hir::TyKind::Err => tcx.ty_error(),
2083 debug!("ast_ty_to_ty: result_ty={:?}", result_ty);
2085 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2089 pub fn impl_trait_ty_to_ty(
2092 lifetimes: &[hir::GenericArg<'_>],
2093 replace_parent_lifetimes: bool,
2095 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2096 let tcx = self.tcx();
2098 let generics = tcx.generics_of(def_id);
2100 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2101 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2102 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2103 // Our own parameters are the resolved lifetimes.
2105 GenericParamDefKind::Lifetime => {
2106 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2107 self.ast_region_to_region(lifetime, None).into()
2116 // For RPIT (return position impl trait), only lifetimes
2117 // mentioned in the impl Trait predicate are captured by
2118 // the opaque type, so the lifetime parameters from the
2119 // parent item need to be replaced with `'static`.
2121 // For `impl Trait` in the types of statics, constants,
2122 // locals and type aliases. These capture all parent
2123 // lifetimes, so they can use their identity subst.
2124 GenericParamDefKind::Lifetime if replace_parent_lifetimes => {
2125 tcx.lifetimes.re_static.into()
2127 _ => tcx.mk_param_from_def(param),
2131 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2133 let ty = tcx.mk_opaque(def_id, substs);
2134 debug!("impl_trait_ty_to_ty: {}", ty);
2138 pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2140 hir::TyKind::Infer if expected_ty.is_some() => {
2141 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2142 expected_ty.unwrap()
2144 _ => self.ast_ty_to_ty(ty),
2150 unsafety: hir::Unsafety,
2152 decl: &hir::FnDecl<'_>,
2153 generics: &hir::Generics<'_>,
2154 ident_span: Option<Span>,
2155 ) -> ty::PolyFnSig<'tcx> {
2158 let tcx = self.tcx();
2160 // We proactively collect all the inferred type params to emit a single error per fn def.
2161 let mut visitor = PlaceholderHirTyCollector::default();
2162 for ty in decl.inputs {
2163 visitor.visit_ty(ty);
2165 walk_generics(&mut visitor, generics);
2167 let input_tys = decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
2168 let output_ty = match decl.output {
2169 hir::FnRetTy::Return(ref output) => {
2170 visitor.visit_ty(output);
2171 self.ast_ty_to_ty(output)
2173 hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(),
2176 debug!("ty_of_fn: output_ty={:?}", output_ty);
2179 ty::Binder::bind(tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, unsafety, abi));
2181 if !self.allow_ty_infer() {
2182 // We always collect the spans for placeholder types when evaluating `fn`s, but we
2183 // only want to emit an error complaining about them if infer types (`_`) are not
2184 // allowed. `allow_ty_infer` gates this behavior. We check for the presence of
2185 // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`.
2186 crate::collect::placeholder_type_error(
2188 ident_span.map(|sp| sp.shrink_to_hi()),
2189 &generics.params[..],
2195 // Find any late-bound regions declared in return type that do
2196 // not appear in the arguments. These are not well-formed.
2199 // for<'a> fn() -> &'a str <-- 'a is bad
2200 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2201 let inputs = bare_fn_ty.inputs();
2202 let late_bound_in_args =
2203 tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
2204 let output = bare_fn_ty.output();
2205 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2207 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
2212 "return type references {}, which is not constrained by the fn input types",
2220 fn validate_late_bound_regions(
2222 constrained_regions: FxHashSet<ty::BoundRegion>,
2223 referenced_regions: FxHashSet<ty::BoundRegion>,
2224 generate_err: impl Fn(&str) -> rustc_errors::DiagnosticBuilder<'tcx>,
2226 for br in referenced_regions.difference(&constrained_regions) {
2227 let br_name = match *br {
2228 ty::BrNamed(_, name) => format!("lifetime `{}`", name),
2229 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
2232 let mut err = generate_err(&br_name);
2234 if let ty::BrAnon(_) = *br {
2235 // The only way for an anonymous lifetime to wind up
2236 // in the return type but **also** be unconstrained is
2237 // if it only appears in "associated types" in the
2238 // input. See #47511 and #62200 for examples. In this case,
2239 // though we can easily give a hint that ought to be
2242 "lifetimes appearing in an associated type are not considered constrained",
2250 /// Given the bounds on an object, determines what single region bound (if any) we can
2251 /// use to summarize this type. The basic idea is that we will use the bound the user
2252 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2253 /// for region bounds. It may be that we can derive no bound at all, in which case
2254 /// we return `None`.
2255 fn compute_object_lifetime_bound(
2258 existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
2259 ) -> Option<ty::Region<'tcx>> // if None, use the default
2261 let tcx = self.tcx();
2263 debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
2265 // No explicit region bound specified. Therefore, examine trait
2266 // bounds and see if we can derive region bounds from those.
2267 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
2269 // If there are no derived region bounds, then report back that we
2270 // can find no region bound. The caller will use the default.
2271 if derived_region_bounds.is_empty() {
2275 // If any of the derived region bounds are 'static, that is always
2277 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
2278 return Some(tcx.lifetimes.re_static);
2281 // Determine whether there is exactly one unique region in the set
2282 // of derived region bounds. If so, use that. Otherwise, report an
2284 let r = derived_region_bounds[0];
2285 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2290 "ambiguous lifetime bound, explicit lifetime bound required"