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;
11 AmbiguousLifetimeBound, MultipleRelaxedDefaultBounds, TraitObjectDeclaredWithNoTraits,
12 TypeofReservedKeywordUsed, ValueOfAssociatedStructAlreadySpecified,
14 use crate::middle::resolve_lifetime as rl;
15 use crate::require_c_abi_if_c_variadic;
16 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
17 use rustc_errors::{struct_span_err, Applicability, ErrorReported, FatalError};
19 use rustc_hir::def::{CtorOf, DefKind, Namespace, Res};
20 use rustc_hir::def_id::{DefId, LocalDefId};
21 use rustc_hir::intravisit::{walk_generics, Visitor as _};
22 use rustc_hir::lang_items::LangItem;
23 use rustc_hir::{Constness, GenericArg, GenericArgs};
24 use rustc_middle::ty::subst::{self, InternalSubsts, Subst, SubstsRef};
25 use rustc_middle::ty::GenericParamDefKind;
26 use rustc_middle::ty::{self, Const, DefIdTree, Ty, TyCtxt, TypeFoldable};
27 use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
28 use rustc_span::lev_distance::find_best_match_for_name;
29 use rustc_span::symbol::{Ident, Symbol};
30 use rustc_span::{Span, DUMMY_SP};
31 use rustc_target::spec::abi;
32 use rustc_trait_selection::traits;
33 use rustc_trait_selection::traits::astconv_object_safety_violations;
34 use rustc_trait_selection::traits::error_reporting::report_object_safety_error;
35 use rustc_trait_selection::traits::wf::object_region_bounds;
37 use smallvec::SmallVec;
39 use std::collections::BTreeSet;
43 pub struct PathSeg(pub DefId, pub usize);
45 pub trait AstConv<'tcx> {
46 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
48 fn item_def_id(&self) -> Option<DefId>;
50 fn default_constness_for_trait_bounds(&self) -> Constness;
52 /// Returns predicates in scope of the form `X: Foo<T>`, where `X`
53 /// is a type parameter `X` with the given id `def_id` and T
54 /// matches `assoc_name`. This is a subset of the full set of
57 /// This is used for one specific purpose: resolving "short-hand"
58 /// associated type references like `T::Item`. In principle, we
59 /// would do that by first getting the full set of predicates in
60 /// scope and then filtering down to find those that apply to `T`,
61 /// but this can lead to cycle errors. The problem is that we have
62 /// to do this resolution *in order to create the predicates in
63 /// the first place*. Hence, we have this "special pass".
64 fn get_type_parameter_bounds(
69 ) -> ty::GenericPredicates<'tcx>;
71 /// Returns the lifetime to use when a lifetime is omitted (and not elided).
72 fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span)
73 -> Option<ty::Region<'tcx>>;
75 /// Returns the type to use when a type is omitted.
76 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
78 /// Returns `true` if `_` is allowed in type signatures in the current context.
79 fn allow_ty_infer(&self) -> bool;
81 /// Returns the const to use when a const is omitted.
85 param: Option<&ty::GenericParamDef>,
87 ) -> &'tcx Const<'tcx>;
89 /// Projecting an associated type from a (potentially)
90 /// higher-ranked trait reference is more complicated, because of
91 /// the possibility of late-bound regions appearing in the
92 /// associated type binding. This is not legal in function
93 /// signatures for that reason. In a function body, we can always
94 /// handle it because we can use inference variables to remove the
95 /// late-bound regions.
96 fn projected_ty_from_poly_trait_ref(
100 item_segment: &hir::PathSegment<'_>,
101 poly_trait_ref: ty::PolyTraitRef<'tcx>,
104 /// Normalize an associated type coming from the user.
105 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
107 /// Invoked when we encounter an error from some prior pass
108 /// (e.g., resolve) that is translated into a ty-error. This is
109 /// used to help suppress derived errors typeck might otherwise
111 fn set_tainted_by_errors(&self);
113 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
116 pub enum SizedByDefault {
122 struct ConvertedBinding<'a, 'tcx> {
125 kind: ConvertedBindingKind<'a, 'tcx>,
126 gen_args: &'a GenericArgs<'a>,
131 enum ConvertedBindingKind<'a, 'tcx> {
133 Constraint(&'a [hir::GenericBound<'a>]),
136 /// New-typed boolean indicating whether explicit late-bound lifetimes
137 /// are present in a set of generic arguments.
139 /// For example if we have some method `fn f<'a>(&'a self)` implemented
140 /// for some type `T`, although `f` is generic in the lifetime `'a`, `'a`
141 /// is late-bound so should not be provided explicitly. Thus, if `f` is
142 /// instantiated with some generic arguments providing `'a` explicitly,
143 /// we taint those arguments with `ExplicitLateBound::Yes` so that we
144 /// can provide an appropriate diagnostic later.
145 #[derive(Copy, Clone, PartialEq)]
146 pub enum ExplicitLateBound {
151 #[derive(Copy, Clone, PartialEq)]
152 pub enum IsMethodCall {
157 /// Denotes the "position" of a generic argument, indicating if it is a generic type,
158 /// generic function or generic method call.
159 #[derive(Copy, Clone, PartialEq)]
160 pub(crate) enum GenericArgPosition {
162 Value, // e.g., functions
166 /// A marker denoting that the generic arguments that were
167 /// provided did not match the respective generic parameters.
168 #[derive(Clone, Default)]
169 pub struct GenericArgCountMismatch {
170 /// Indicates whether a fatal error was reported (`Some`), or just a lint (`None`).
171 pub reported: Option<ErrorReported>,
172 /// A list of spans of arguments provided that were not valid.
173 pub invalid_args: Vec<Span>,
176 /// Decorates the result of a generic argument count mismatch
177 /// check with whether explicit late bounds were provided.
179 pub struct GenericArgCountResult {
180 pub explicit_late_bound: ExplicitLateBound,
181 pub correct: Result<(), GenericArgCountMismatch>,
184 pub trait CreateSubstsForGenericArgsCtxt<'a, 'tcx> {
185 fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'a>>, bool);
189 param: &ty::GenericParamDef,
190 arg: &GenericArg<'_>,
191 ) -> subst::GenericArg<'tcx>;
195 substs: Option<&[subst::GenericArg<'tcx>]>,
196 param: &ty::GenericParamDef,
198 ) -> subst::GenericArg<'tcx>;
201 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
202 #[tracing::instrument(level = "debug", skip(self))]
203 pub fn ast_region_to_region(
205 lifetime: &hir::Lifetime,
206 def: Option<&ty::GenericParamDef>,
207 ) -> ty::Region<'tcx> {
208 let tcx = self.tcx();
209 let lifetime_name = |def_id| tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id));
211 let r = match tcx.named_region(lifetime.hir_id) {
212 Some(rl::Region::Static) => tcx.lifetimes.re_static,
214 Some(rl::Region::LateBound(debruijn, index, def_id, _)) => {
215 let name = lifetime_name(def_id.expect_local());
216 let br = ty::BoundRegion {
217 var: ty::BoundVar::from_u32(index),
218 kind: ty::BrNamed(def_id, name),
220 tcx.mk_region(ty::ReLateBound(debruijn, br))
223 Some(rl::Region::LateBoundAnon(debruijn, index, anon_index)) => {
224 let br = ty::BoundRegion {
225 var: ty::BoundVar::from_u32(index),
226 kind: ty::BrAnon(anon_index),
228 tcx.mk_region(ty::ReLateBound(debruijn, br))
231 Some(rl::Region::EarlyBound(index, id, _)) => {
232 let name = lifetime_name(id.expect_local());
233 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: id, index, name }))
236 Some(rl::Region::Free(scope, id)) => {
237 let name = lifetime_name(id.expect_local());
238 tcx.mk_region(ty::ReFree(ty::FreeRegion {
240 bound_region: ty::BrNamed(id, name),
243 // (*) -- not late-bound, won't change
247 self.re_infer(def, lifetime.span).unwrap_or_else(|| {
248 debug!(?lifetime, "unelided lifetime in signature");
250 // This indicates an illegal lifetime
251 // elision. `resolve_lifetime` should have
252 // reported an error in this case -- but if
253 // not, let's error out.
254 tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
256 // Supply some dummy value. We don't have an
257 // `re_error`, annoyingly, so use `'static`.
258 tcx.lifetimes.re_static
263 debug!("ast_region_to_region(lifetime={:?}) yields {:?}", lifetime, r);
268 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
269 /// returns an appropriate set of substitutions for this particular reference to `I`.
270 pub fn ast_path_substs_for_ty(
274 item_segment: &hir::PathSegment<'_>,
275 ) -> SubstsRef<'tcx> {
276 let (substs, _) = self.create_substs_for_ast_path(
282 item_segment.infer_args,
285 let assoc_bindings = self.create_assoc_bindings_for_generic_args(item_segment.args());
287 if let Some(b) = assoc_bindings.first() {
288 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
294 /// Given the type/lifetime/const arguments provided to some path (along with
295 /// an implicit `Self`, if this is a trait reference), returns the complete
296 /// set of substitutions. This may involve applying defaulted type parameters.
297 /// Also returns back constraints on associated types.
302 /// T: std::ops::Index<usize, Output = u32>
303 /// ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4
306 /// 1. The `self_ty` here would refer to the type `T`.
307 /// 2. The path in question is the path to the trait `std::ops::Index`,
308 /// which will have been resolved to a `def_id`
309 /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
310 /// parameters are returned in the `SubstsRef`, the associated type bindings like
311 /// `Output = u32` are returned in the `Vec<ConvertedBinding...>` result.
313 /// Note that the type listing given here is *exactly* what the user provided.
315 /// For (generic) associated types
318 /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
321 /// We have the parent substs are the substs for the parent trait:
322 /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
323 /// type itself: `['a]`. The returned `SubstsRef` concatenates these two
324 /// lists: `[Vec<u8>, u8, 'a]`.
325 #[tracing::instrument(level = "debug", skip(self, span))]
326 fn create_substs_for_ast_path<'a>(
330 parent_substs: &[subst::GenericArg<'tcx>],
331 seg: &hir::PathSegment<'_>,
332 generic_args: &'a hir::GenericArgs<'_>,
334 self_ty: Option<Ty<'tcx>>,
335 ) -> (SubstsRef<'tcx>, GenericArgCountResult) {
336 // If the type is parameterized by this region, then replace this
337 // region with the current anon region binding (in other words,
338 // whatever & would get replaced with).
340 let tcx = self.tcx();
341 let generics = tcx.generics_of(def_id);
342 debug!("generics: {:?}", generics);
344 if generics.has_self {
345 if generics.parent.is_some() {
346 // The parent is a trait so it should have at least one subst
347 // for the `Self` type.
348 assert!(!parent_substs.is_empty())
350 // This item (presumably a trait) needs a self-type.
351 assert!(self_ty.is_some());
354 assert!(self_ty.is_none() && parent_substs.is_empty());
357 let arg_count = Self::check_generic_arg_count(
364 GenericArgPosition::Type,
369 // Skip processing if type has no generic parameters.
370 // Traits always have `Self` as a generic parameter, which means they will not return early
371 // here and so associated type bindings will be handled regardless of whether there are any
372 // non-`Self` generic parameters.
373 if generics.params.len() == 0 {
374 return (tcx.intern_substs(&[]), arg_count);
377 let is_object = self_ty.map_or(false, |ty| ty == self.tcx().types.trait_object_dummy_self);
379 struct SubstsForAstPathCtxt<'a, 'tcx> {
380 astconv: &'a (dyn AstConv<'tcx> + 'a),
382 generic_args: &'a GenericArgs<'a>,
384 missing_type_params: Vec<String>,
385 inferred_params: Vec<Span>,
390 impl<'tcx, 'a> SubstsForAstPathCtxt<'tcx, 'a> {
391 fn default_needs_object_self(&mut self, param: &ty::GenericParamDef) -> bool {
392 let tcx = self.astconv.tcx();
393 if let GenericParamDefKind::Type { has_default, .. } = param.kind {
394 if self.is_object && has_default {
395 let default_ty = tcx.at(self.span).type_of(param.def_id);
396 let self_param = tcx.types.self_param;
397 if default_ty.walk().any(|arg| arg == self_param.into()) {
398 // There is no suitable inference default for a type parameter
399 // that references self, in an object type.
409 impl<'a, 'tcx> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for SubstsForAstPathCtxt<'a, 'tcx> {
410 fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'a>>, bool) {
411 if did == self.def_id {
412 (Some(self.generic_args), self.infer_args)
414 // The last component of this tuple is unimportant.
421 param: &ty::GenericParamDef,
422 arg: &GenericArg<'_>,
423 ) -> subst::GenericArg<'tcx> {
424 let tcx = self.astconv.tcx();
425 match (¶m.kind, arg) {
426 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
427 self.astconv.ast_region_to_region(<, Some(param)).into()
429 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
431 tcx.check_optional_stability(
437 // Default generic parameters may not be marked
438 // with stability attributes, i.e. when the
439 // default parameter was defined at the same time
440 // as the rest of the type. As such, we ignore missing
441 // stability attributes.
445 if let (hir::TyKind::Infer, false) =
446 (&ty.kind, self.astconv.allow_ty_infer())
448 self.inferred_params.push(ty.span);
449 tcx.ty_error().into()
451 self.astconv.ast_ty_to_ty(&ty).into()
454 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => {
455 ty::Const::from_opt_const_arg_anon_const(
457 ty::WithOptConstParam {
458 did: tcx.hir().local_def_id(ct.value.hir_id),
459 const_param_did: Some(param.def_id),
464 (&GenericParamDefKind::Const { has_default }, hir::GenericArg::Infer(inf)) => {
466 tcx.const_param_default(param.def_id).into()
467 } else if self.astconv.allow_ty_infer() {
468 // FIXME(const_generics): Actually infer parameter here?
471 self.inferred_params.push(inf.span);
472 tcx.ty_error().into()
476 &GenericParamDefKind::Type { has_default, .. },
477 hir::GenericArg::Infer(inf),
480 tcx.check_optional_stability(
486 // Default generic parameters may not be marked
487 // with stability attributes, i.e. when the
488 // default parameter was defined at the same time
489 // as the rest of the type. As such, we ignore missing
490 // stability attributes.
494 if self.astconv.allow_ty_infer() {
495 self.astconv.ast_ty_to_ty(&inf.to_ty()).into()
497 self.inferred_params.push(inf.span);
498 tcx.ty_error().into()
507 substs: Option<&[subst::GenericArg<'tcx>]>,
508 param: &ty::GenericParamDef,
510 ) -> subst::GenericArg<'tcx> {
511 let tcx = self.astconv.tcx();
513 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
514 GenericParamDefKind::Type { has_default, .. } => {
515 if !infer_args && has_default {
516 // No type parameter provided, but a default exists.
518 // If we are converting an object type, then the
519 // `Self` parameter is unknown. However, some of the
520 // other type parameters may reference `Self` in their
521 // defaults. This will lead to an ICE if we are not
523 if self.default_needs_object_self(param) {
524 self.missing_type_params.push(param.name.to_string());
525 tcx.ty_error().into()
527 // This is a default type parameter.
531 tcx.at(self.span).type_of(param.def_id).subst_spanned(
539 } else if infer_args {
540 // No type parameters were provided, we can infer all.
541 let param = if !self.default_needs_object_self(param) {
546 self.astconv.ty_infer(param, self.span).into()
548 // We've already errored above about the mismatch.
549 tcx.ty_error().into()
552 GenericParamDefKind::Const { has_default } => {
553 let ty = tcx.at(self.span).type_of(param.def_id);
554 if !infer_args && has_default {
555 tcx.const_param_default(param.def_id)
556 .subst_spanned(tcx, substs.unwrap(), Some(self.span))
560 self.astconv.ct_infer(ty, Some(param), self.span).into()
562 // We've already errored above about the mismatch.
563 tcx.const_error(ty).into()
571 let mut substs_ctx = SubstsForAstPathCtxt {
576 missing_type_params: vec![],
577 inferred_params: vec![],
581 let substs = Self::create_substs_for_generic_args(
591 self.complain_about_missing_type_params(
592 substs_ctx.missing_type_params,
595 generic_args.args.is_empty(),
599 "create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
600 generics, self_ty, substs
606 fn create_assoc_bindings_for_generic_args<'a>(
608 generic_args: &'a hir::GenericArgs<'_>,
609 ) -> Vec<ConvertedBinding<'a, 'tcx>> {
610 // Convert associated-type bindings or constraints into a separate vector.
611 // Example: Given this:
613 // T: Iterator<Item = u32>
615 // The `T` is passed in as a self-type; the `Item = u32` is
616 // not a "type parameter" of the `Iterator` trait, but rather
617 // a restriction on `<T as Iterator>::Item`, so it is passed
619 let assoc_bindings = generic_args
623 let kind = match binding.kind {
624 hir::TypeBindingKind::Equality { ref ty } => {
625 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty))
627 hir::TypeBindingKind::Constraint { ref bounds } => {
628 ConvertedBindingKind::Constraint(bounds)
632 hir_id: binding.hir_id,
633 item_name: binding.ident,
635 gen_args: binding.gen_args,
644 crate fn create_substs_for_associated_item(
649 item_segment: &hir::PathSegment<'_>,
650 parent_substs: SubstsRef<'tcx>,
651 ) -> SubstsRef<'tcx> {
653 "create_substs_for_associated_item(span: {:?}, item_def_id: {:?}, item_segment: {:?}",
654 span, item_def_id, item_segment
656 if tcx.generics_of(item_def_id).params.is_empty() {
657 self.prohibit_generics(slice::from_ref(item_segment));
661 self.create_substs_for_ast_path(
667 item_segment.infer_args,
674 /// Instantiates the path for the given trait reference, assuming that it's
675 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
676 /// The type _cannot_ be a type other than a trait type.
678 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
679 /// are disallowed. Otherwise, they are pushed onto the vector given.
680 pub fn instantiate_mono_trait_ref(
682 trait_ref: &hir::TraitRef<'_>,
684 ) -> ty::TraitRef<'tcx> {
685 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
687 self.ast_path_to_mono_trait_ref(
689 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
691 trait_ref.path.segments.last().unwrap(),
695 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
696 /// a full trait reference. The resulting trait reference is returned. This may also generate
697 /// auxiliary bounds, which are added to `bounds`.
702 /// poly_trait_ref = Iterator<Item = u32>
706 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
708 /// **A note on binders:** against our usual convention, there is an implied bounder around
709 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
710 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
711 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
712 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
714 #[tracing::instrument(level = "debug", skip(self, span, constness, bounds, speculative))]
715 pub fn instantiate_poly_trait_ref(
717 trait_ref: &hir::TraitRef<'_>,
719 constness: Constness,
721 bounds: &mut Bounds<'tcx>,
723 ) -> GenericArgCountResult {
724 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
726 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
728 let tcx = self.tcx();
729 let bound_vars = tcx.late_bound_vars(trait_ref.hir_ref_id);
732 let (substs, arg_count) = self.create_substs_for_ast_trait_ref(
736 trait_ref.path.segments.last().unwrap(),
738 let assoc_bindings = self
739 .create_assoc_bindings_for_generic_args(trait_ref.path.segments.last().unwrap().args());
742 ty::Binder::bind_with_vars(ty::TraitRef::new(trait_def_id, substs), bound_vars);
744 debug!(?poly_trait_ref, ?assoc_bindings);
745 bounds.trait_bounds.push((poly_trait_ref, span, constness));
747 let mut dup_bindings = FxHashMap::default();
748 for binding in &assoc_bindings {
749 // Specify type to assert that error was already reported in `Err` case.
750 let _: Result<_, ErrorReported> = self.add_predicates_for_ast_type_binding(
751 trait_ref.hir_ref_id,
759 // Okay to ignore `Err` because of `ErrorReported` (see above).
765 pub fn instantiate_lang_item_trait_ref(
767 lang_item: hir::LangItem,
770 args: &GenericArgs<'_>,
772 bounds: &mut Bounds<'tcx>,
774 let trait_def_id = self.tcx().require_lang_item(lang_item, Some(span));
776 let (substs, _) = self.create_substs_for_ast_path(
780 &hir::PathSegment::invalid(),
785 let assoc_bindings = self.create_assoc_bindings_for_generic_args(args);
786 let tcx = self.tcx();
787 let bound_vars = tcx.late_bound_vars(hir_id);
789 ty::Binder::bind_with_vars(ty::TraitRef::new(trait_def_id, substs), bound_vars);
790 bounds.trait_bounds.push((poly_trait_ref, span, Constness::NotConst));
792 let mut dup_bindings = FxHashMap::default();
793 for binding in assoc_bindings {
794 let _: Result<_, ErrorReported> = self.add_predicates_for_ast_type_binding(
806 fn ast_path_to_mono_trait_ref(
811 trait_segment: &hir::PathSegment<'_>,
812 ) -> ty::TraitRef<'tcx> {
814 self.create_substs_for_ast_trait_ref(span, trait_def_id, self_ty, trait_segment);
815 let assoc_bindings = self.create_assoc_bindings_for_generic_args(trait_segment.args());
816 if let Some(b) = assoc_bindings.first() {
817 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
819 ty::TraitRef::new(trait_def_id, substs)
822 #[tracing::instrument(level = "debug", skip(self, span))]
823 fn create_substs_for_ast_trait_ref<'a>(
828 trait_segment: &'a hir::PathSegment<'a>,
829 ) -> (SubstsRef<'tcx>, GenericArgCountResult) {
830 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment);
832 self.create_substs_for_ast_path(
837 trait_segment.args(),
838 trait_segment.infer_args,
843 fn trait_defines_associated_type_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
845 .associated_items(trait_def_id)
846 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, trait_def_id)
850 // Returns `true` if a bounds list includes `?Sized`.
851 pub fn is_unsized(&self, ast_bounds: &[hir::GenericBound<'_>], span: Span) -> bool {
852 let tcx = self.tcx();
854 // Try to find an unbound in bounds.
855 let mut unbound = None;
856 for ab in ast_bounds {
857 if let hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = ab {
858 if unbound.is_none() {
859 unbound = Some(&ptr.trait_ref);
861 tcx.sess.emit_err(MultipleRelaxedDefaultBounds { span });
866 let kind_id = tcx.lang_items().require(LangItem::Sized);
869 // FIXME(#8559) currently requires the unbound to be built-in.
870 if let Ok(kind_id) = kind_id {
871 if tpb.path.res != Res::Def(DefKind::Trait, kind_id) {
874 "default bound relaxed for a type parameter, but \
875 this does nothing because the given bound is not \
876 a default; only `?Sized` is supported",
882 _ if kind_id.is_ok() => {
885 // No lang item for `Sized`, so we can't add it as a bound.
892 /// This helper takes a *converted* parameter type (`param_ty`)
893 /// and an *unconverted* list of bounds:
897 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
899 /// `param_ty`, in ty form
902 /// It adds these `ast_bounds` into the `bounds` structure.
904 /// **A note on binders:** there is an implied binder around
905 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
906 /// for more details.
907 #[tracing::instrument(level = "debug", skip(self, bounds))]
911 ast_bounds: &[hir::GenericBound<'_>],
912 bounds: &mut Bounds<'tcx>,
913 bound_vars: &'tcx ty::List<ty::BoundVariableKind>,
915 let constness = self.default_constness_for_trait_bounds();
916 for ast_bound in ast_bounds {
918 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => {
919 self.instantiate_poly_trait_ref(
928 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::MaybeConst) => {
929 self.instantiate_poly_trait_ref(
938 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
939 hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => self
940 .instantiate_lang_item_trait_ref(
941 lang_item, span, hir_id, args, param_ty, bounds,
943 hir::GenericBound::Outlives(ref l) => bounds.region_bounds.push((
944 ty::Binder::bind_with_vars(self.ast_region_to_region(l, None), bound_vars),
951 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
952 /// The self-type for the bounds is given by `param_ty`.
957 /// fn foo<T: Bar + Baz>() { }
958 /// ^ ^^^^^^^^^ ast_bounds
962 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
963 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
964 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
966 /// `span` should be the declaration size of the parameter.
967 pub fn compute_bounds(
970 ast_bounds: &[hir::GenericBound<'_>],
971 sized_by_default: SizedByDefault,
974 self.compute_bounds_inner(param_ty, &ast_bounds, sized_by_default, span)
977 /// Convert the bounds in `ast_bounds` that refer to traits which define an associated type
978 /// named `assoc_name` into ty::Bounds. Ignore the rest.
979 pub fn compute_bounds_that_match_assoc_type(
982 ast_bounds: &[hir::GenericBound<'_>],
983 sized_by_default: SizedByDefault,
987 let mut result = Vec::new();
989 for ast_bound in ast_bounds {
990 if let Some(trait_ref) = ast_bound.trait_ref() {
991 if let Some(trait_did) = trait_ref.trait_def_id() {
992 if self.tcx().trait_may_define_assoc_type(trait_did, assoc_name) {
993 result.push(ast_bound.clone());
999 self.compute_bounds_inner(param_ty, &result, sized_by_default, span)
1002 fn compute_bounds_inner(
1005 ast_bounds: &[hir::GenericBound<'_>],
1006 sized_by_default: SizedByDefault,
1009 let mut bounds = Bounds::default();
1011 self.add_bounds(param_ty, ast_bounds, &mut bounds, ty::List::empty());
1013 bounds.implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
1014 if !self.is_unsized(ast_bounds, span) { Some(span) } else { None }
1022 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1025 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1026 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1027 /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1028 #[tracing::instrument(
1030 skip(self, bounds, speculative, dup_bindings, path_span)
1032 fn add_predicates_for_ast_type_binding(
1034 hir_ref_id: hir::HirId,
1035 trait_ref: ty::PolyTraitRef<'tcx>,
1036 binding: &ConvertedBinding<'_, 'tcx>,
1037 bounds: &mut Bounds<'tcx>,
1039 dup_bindings: &mut FxHashMap<DefId, Span>,
1041 ) -> Result<(), ErrorReported> {
1042 // Given something like `U: SomeTrait<T = X>`, we want to produce a
1043 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1044 // subtle in the event that `T` is defined in a supertrait of
1045 // `SomeTrait`, because in that case we need to upcast.
1047 // That is, consider this case:
1050 // trait SubTrait: SuperTrait<i32> { }
1051 // trait SuperTrait<A> { type T; }
1053 // ... B: SubTrait<T = foo> ...
1056 // We want to produce `<B as SuperTrait<i32>>::T == foo`.
1058 let tcx = self.tcx();
1061 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1062 // Simple case: X is defined in the current trait.
1065 // Otherwise, we have to walk through the supertraits to find
1067 self.one_bound_for_assoc_type(
1068 || traits::supertraits(tcx, trait_ref),
1069 || trait_ref.print_only_trait_path().to_string(),
1072 || match binding.kind {
1073 ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1079 let (assoc_ident, def_scope) =
1080 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1082 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1083 // of calling `filter_by_name_and_kind`.
1085 .associated_items(candidate.def_id())
1086 .filter_by_name_unhygienic(assoc_ident.name)
1088 i.kind == ty::AssocKind::Type && i.ident.normalize_to_macros_2_0() == assoc_ident
1090 .expect("missing associated type");
1092 if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
1096 &format!("associated type `{}` is private", binding.item_name),
1098 .span_label(binding.span, "private associated type")
1101 tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span, None);
1105 .entry(assoc_ty.def_id)
1106 .and_modify(|prev_span| {
1107 self.tcx().sess.emit_err(ValueOfAssociatedStructAlreadySpecified {
1109 prev_span: *prev_span,
1110 item_name: binding.item_name,
1111 def_path: tcx.def_path_str(assoc_ty.container.id()),
1114 .or_insert(binding.span);
1117 // Include substitutions for generic parameters of associated types
1118 let projection_ty = candidate.map_bound(|trait_ref| {
1119 let ident = Ident::new(assoc_ty.ident.name, binding.item_name.span);
1120 let item_segment = hir::PathSegment {
1122 hir_id: Some(binding.hir_id),
1124 args: Some(binding.gen_args),
1128 let substs_trait_ref_and_assoc_item = self.create_substs_for_associated_item(
1137 "add_predicates_for_ast_type_binding: substs for trait-ref and assoc_item: {:?}",
1138 substs_trait_ref_and_assoc_item
1142 item_def_id: assoc_ty.def_id,
1143 substs: substs_trait_ref_and_assoc_item,
1148 // Find any late-bound regions declared in `ty` that are not
1149 // declared in the trait-ref or assoc_ty. These are not well-formed.
1153 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1154 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1155 if let ConvertedBindingKind::Equality(ty) = binding.kind {
1156 let late_bound_in_trait_ref =
1157 tcx.collect_constrained_late_bound_regions(&projection_ty);
1158 let late_bound_in_ty =
1159 tcx.collect_referenced_late_bound_regions(&trait_ref.rebind(ty));
1160 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
1161 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
1163 // FIXME: point at the type params that don't have appropriate lifetimes:
1164 // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
1165 // ---- ---- ^^^^^^^
1166 self.validate_late_bound_regions(
1167 late_bound_in_trait_ref,
1174 "binding for associated type `{}` references {}, \
1175 which does not appear in the trait input types",
1184 match binding.kind {
1185 ConvertedBindingKind::Equality(ref ty) => {
1186 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1187 // the "projection predicate" for:
1189 // `<T as Iterator>::Item = u32`
1190 bounds.projection_bounds.push((
1191 projection_ty.map_bound(|projection_ty| {
1193 "add_predicates_for_ast_type_binding: projection_ty {:?}, substs: {:?}",
1194 projection_ty, projection_ty.substs
1196 ty::ProjectionPredicate { projection_ty, ty }
1201 ConvertedBindingKind::Constraint(ast_bounds) => {
1202 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1204 // `<T as Iterator>::Item: Debug`
1206 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1207 // parameter to have a skipped binder.
1208 let param_ty = tcx.mk_ty(ty::Projection(projection_ty.skip_binder()));
1209 self.add_bounds(param_ty, ast_bounds, bounds, candidate.bound_vars());
1219 item_segment: &hir::PathSegment<'_>,
1221 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1222 self.normalize_ty(span, self.tcx().at(span).type_of(did).subst(self.tcx(), substs))
1225 fn conv_object_ty_poly_trait_ref(
1228 trait_bounds: &[hir::PolyTraitRef<'_>],
1229 lifetime: &hir::Lifetime,
1232 let tcx = self.tcx();
1234 let mut bounds = Bounds::default();
1235 let mut potential_assoc_types = Vec::new();
1236 let dummy_self = self.tcx().types.trait_object_dummy_self;
1237 for trait_bound in trait_bounds.iter().rev() {
1238 if let GenericArgCountResult {
1240 Err(GenericArgCountMismatch { invalid_args: cur_potential_assoc_types, .. }),
1242 } = self.instantiate_poly_trait_ref(
1243 &trait_bound.trait_ref,
1245 Constness::NotConst,
1250 potential_assoc_types.extend(cur_potential_assoc_types);
1254 // Expand trait aliases recursively and check that only one regular (non-auto) trait
1255 // is used and no 'maybe' bounds are used.
1256 let expanded_traits =
1257 traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().map(|&(a, b, _)| (a, b)));
1258 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) =
1259 expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1260 if regular_traits.len() > 1 {
1261 let first_trait = ®ular_traits[0];
1262 let additional_trait = ®ular_traits[1];
1263 let mut err = struct_span_err!(
1265 additional_trait.bottom().1,
1267 "only auto traits can be used as additional traits in a trait object"
1269 additional_trait.label_with_exp_info(
1271 "additional non-auto trait",
1274 first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1276 "consider creating a new trait with all of these as super-traits and using that \
1277 trait here instead: `trait NewTrait: {} {{}}`",
1280 .map(|t| t.trait_ref().print_only_trait_path().to_string())
1281 .collect::<Vec<_>>()
1285 "auto-traits like `Send` and `Sync` are traits that have special properties; \
1286 for more information on them, visit \
1287 <https://doc.rust-lang.org/reference/special-types-and-traits.html#auto-traits>",
1292 if regular_traits.is_empty() && auto_traits.is_empty() {
1293 tcx.sess.emit_err(TraitObjectDeclaredWithNoTraits { span });
1294 return tcx.ty_error();
1297 // Check that there are no gross object safety violations;
1298 // most importantly, that the supertraits don't contain `Self`,
1300 for item in ®ular_traits {
1301 let object_safety_violations =
1302 astconv_object_safety_violations(tcx, item.trait_ref().def_id());
1303 if !object_safety_violations.is_empty() {
1304 report_object_safety_error(
1307 item.trait_ref().def_id(),
1308 &object_safety_violations[..],
1311 return tcx.ty_error();
1315 // Use a `BTreeSet` to keep output in a more consistent order.
1316 let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1318 let regular_traits_refs_spans = bounds
1321 .filter(|(trait_ref, _, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1323 for (base_trait_ref, span, constness) in regular_traits_refs_spans {
1324 assert_eq!(constness, Constness::NotConst);
1326 for obligation in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1328 "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1329 obligation.predicate
1332 let bound_predicate = obligation.predicate.kind();
1333 match bound_predicate.skip_binder() {
1334 ty::PredicateKind::Trait(pred, _) => {
1335 let pred = bound_predicate.rebind(pred);
1336 associated_types.entry(span).or_default().extend(
1337 tcx.associated_items(pred.def_id())
1338 .in_definition_order()
1339 .filter(|item| item.kind == ty::AssocKind::Type)
1340 .map(|item| item.def_id),
1343 ty::PredicateKind::Projection(pred) => {
1344 let pred = bound_predicate.rebind(pred);
1345 // A `Self` within the original bound will be substituted with a
1346 // `trait_object_dummy_self`, so check for that.
1347 let references_self =
1348 pred.skip_binder().ty.walk().any(|arg| arg == dummy_self.into());
1350 // If the projection output contains `Self`, force the user to
1351 // elaborate it explicitly to avoid a lot of complexity.
1353 // The "classicaly useful" case is the following:
1355 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1360 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1361 // but actually supporting that would "expand" to an infinitely-long type
1362 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1364 // Instead, we force the user to write
1365 // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1366 // the discussion in #56288 for alternatives.
1367 if !references_self {
1368 // Include projections defined on supertraits.
1369 bounds.projection_bounds.push((pred, span));
1377 for (projection_bound, _) in &bounds.projection_bounds {
1378 for def_ids in associated_types.values_mut() {
1379 def_ids.remove(&projection_bound.projection_def_id());
1383 self.complain_about_missing_associated_types(
1385 potential_assoc_types,
1389 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1390 // `dyn Trait + Send`.
1391 // We remove duplicates by inserting into a `FxHashSet` to avoid re-ordering
1393 let mut duplicates = FxHashSet::default();
1394 auto_traits.retain(|i| duplicates.insert(i.trait_ref().def_id()));
1395 debug!("regular_traits: {:?}", regular_traits);
1396 debug!("auto_traits: {:?}", auto_traits);
1398 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1399 let existential_trait_refs = regular_traits.iter().map(|i| {
1400 i.trait_ref().map_bound(|trait_ref: ty::TraitRef<'tcx>| {
1401 if trait_ref.self_ty() != dummy_self {
1402 // FIXME: There appears to be a missing filter on top of `expand_trait_aliases`,
1403 // which picks up non-supertraits where clauses - but also, the object safety
1404 // completely ignores trait aliases, which could be object safety hazards. We
1405 // `delay_span_bug` here to avoid an ICE in stable even when the feature is
1406 // disabled. (#66420)
1407 tcx.sess.delay_span_bug(
1410 "trait_ref_to_existential called on {:?} with non-dummy Self",
1415 ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
1418 let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1419 bound.map_bound(|b| {
1420 if b.projection_ty.self_ty() != dummy_self {
1421 tcx.sess.delay_span_bug(
1423 &format!("trait_ref_to_existential called on {:?} with non-dummy Self", b),
1426 ty::ExistentialProjection::erase_self_ty(tcx, b)
1430 let regular_trait_predicates = existential_trait_refs
1431 .map(|trait_ref| trait_ref.map_bound(ty::ExistentialPredicate::Trait));
1432 let auto_trait_predicates = auto_traits.into_iter().map(|trait_ref| {
1433 ty::Binder::dummy(ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()))
1435 // N.b. principal, projections, auto traits
1436 // FIXME: This is actually wrong with multiple principals in regards to symbol mangling
1437 let mut v = regular_trait_predicates
1439 existential_projections.map(|x| x.map_bound(ty::ExistentialPredicate::Projection)),
1441 .chain(auto_trait_predicates)
1442 .collect::<SmallVec<[_; 8]>>();
1443 v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
1445 let existential_predicates = tcx.mk_poly_existential_predicates(v.into_iter());
1447 // Use explicitly-specified region bound.
1448 let region_bound = if !lifetime.is_elided() {
1449 self.ast_region_to_region(lifetime, None)
1451 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1452 if tcx.named_region(lifetime.hir_id).is_some() {
1453 self.ast_region_to_region(lifetime, None)
1455 self.re_infer(None, span).unwrap_or_else(|| {
1456 let mut err = struct_span_err!(
1460 "the lifetime bound for this object type cannot be deduced \
1461 from context; please supply an explicit bound"
1464 // We will have already emitted an error E0106 complaining about a
1465 // missing named lifetime in `&dyn Trait`, so we elide this one.
1470 tcx.lifetimes.re_static
1475 debug!("region_bound: {:?}", region_bound);
1477 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1478 debug!("trait_object_type: {:?}", ty);
1482 fn report_ambiguous_associated_type(
1489 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1490 if let (true, Ok(snippet)) = (
1493 .confused_type_with_std_module
1496 .any(|full_span| full_span.contains(span)),
1497 self.tcx().sess.source_map().span_to_snippet(span),
1499 err.span_suggestion(
1501 "you are looking for the module in `std`, not the primitive type",
1502 format!("std::{}", snippet),
1503 Applicability::MachineApplicable,
1506 err.span_suggestion(
1508 "use fully-qualified syntax",
1509 format!("<{} as {}>::{}", type_str, trait_str, name),
1510 Applicability::HasPlaceholders,
1516 // Search for a bound on a type parameter which includes the associated item
1517 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1518 // This function will fail if there are no suitable bounds or there is
1520 fn find_bound_for_assoc_item(
1522 ty_param_def_id: LocalDefId,
1525 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported> {
1526 let tcx = self.tcx();
1529 "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
1530 ty_param_def_id, assoc_name, span,
1533 let predicates = &self
1534 .get_type_parameter_bounds(span, ty_param_def_id.to_def_id(), assoc_name)
1537 debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1539 let param_hir_id = tcx.hir().local_def_id_to_hir_id(ty_param_def_id);
1540 let param_name = tcx.hir().ty_param_name(param_hir_id);
1541 self.one_bound_for_assoc_type(
1543 traits::transitive_bounds_that_define_assoc_type(
1545 predicates.iter().filter_map(|(p, _)| {
1546 p.to_opt_poly_trait_ref().map(|trait_ref| trait_ref.value)
1551 || param_name.to_string(),
1558 // Checks that `bounds` contains exactly one element and reports appropriate
1559 // errors otherwise.
1560 fn one_bound_for_assoc_type<I>(
1562 all_candidates: impl Fn() -> I,
1563 ty_param_name: impl Fn() -> String,
1566 is_equality: impl Fn() -> Option<String>,
1567 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1569 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1571 let mut matching_candidates = all_candidates()
1572 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
1574 let bound = match matching_candidates.next() {
1575 Some(bound) => bound,
1577 self.complain_about_assoc_type_not_found(
1583 return Err(ErrorReported);
1587 debug!("one_bound_for_assoc_type: bound = {:?}", bound);
1589 if let Some(bound2) = matching_candidates.next() {
1590 debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2);
1592 let is_equality = is_equality();
1593 let bounds = array::IntoIter::new([bound, bound2]).chain(matching_candidates);
1594 let mut err = if is_equality.is_some() {
1595 // More specific Error Index entry.
1600 "ambiguous associated type `{}` in bounds of `{}`",
1609 "ambiguous associated type `{}` in bounds of `{}`",
1614 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1616 let mut where_bounds = vec![];
1617 for bound in bounds {
1618 let bound_id = bound.def_id();
1619 let bound_span = self
1621 .associated_items(bound_id)
1622 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, bound_id)
1623 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1625 if let Some(bound_span) = bound_span {
1629 "ambiguous `{}` from `{}`",
1631 bound.print_only_trait_path(),
1634 if let Some(constraint) = &is_equality {
1635 where_bounds.push(format!(
1636 " T: {trait}::{assoc} = {constraint}",
1637 trait=bound.print_only_trait_path(),
1639 constraint=constraint,
1642 err.span_suggestion(
1644 "use fully qualified syntax to disambiguate",
1648 bound.print_only_trait_path(),
1651 Applicability::MaybeIncorrect,
1656 "associated type `{}` could derive from `{}`",
1658 bound.print_only_trait_path(),
1662 if !where_bounds.is_empty() {
1664 "consider introducing a new type parameter `T` and adding `where` constraints:\
1665 \n where\n T: {},\n{}",
1667 where_bounds.join(",\n"),
1671 if !where_bounds.is_empty() {
1672 return Err(ErrorReported);
1678 // Create a type from a path to an associated type.
1679 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
1680 // and item_segment is the path segment for `D`. We return a type and a def for
1682 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
1683 // parameter or `Self`.
1684 // NOTE: When this function starts resolving `Trait::AssocTy` successfully
1685 // it should also start reportint the `BARE_TRAIT_OBJECTS` lint.
1686 pub fn associated_path_to_ty(
1688 hir_ref_id: hir::HirId,
1692 assoc_segment: &hir::PathSegment<'_>,
1693 permit_variants: bool,
1694 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> {
1695 let tcx = self.tcx();
1696 let assoc_ident = assoc_segment.ident;
1698 debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
1700 // Check if we have an enum variant.
1701 let mut variant_resolution = None;
1702 if let ty::Adt(adt_def, _) = qself_ty.kind() {
1703 if adt_def.is_enum() {
1704 let variant_def = adt_def
1707 .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did));
1708 if let Some(variant_def) = variant_def {
1709 if permit_variants {
1710 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span, None);
1711 self.prohibit_generics(slice::from_ref(assoc_segment));
1712 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
1714 variant_resolution = Some(variant_def.def_id);
1720 // Find the type of the associated item, and the trait where the associated
1721 // item is declared.
1722 let bound = match (&qself_ty.kind(), qself_res) {
1723 (_, Res::SelfTy(Some(_), Some((impl_def_id, _)))) => {
1724 // `Self` in an impl of a trait -- we have a concrete self type and a
1726 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
1727 Some(trait_ref) => trait_ref,
1729 // A cycle error occurred, most likely.
1730 return Err(ErrorReported);
1734 self.one_bound_for_assoc_type(
1735 || traits::supertraits(tcx, ty::Binder::dummy(trait_ref)),
1736 || "Self".to_string(),
1744 Res::SelfTy(Some(param_did), None) | Res::Def(DefKind::TyParam, param_did),
1745 ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?,
1747 if variant_resolution.is_some() {
1748 // Variant in type position
1749 let msg = format!("expected type, found variant `{}`", assoc_ident);
1750 tcx.sess.span_err(span, &msg);
1751 } else if qself_ty.is_enum() {
1752 let mut err = struct_span_err!(
1756 "no variant named `{}` found for enum `{}`",
1761 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
1762 if let Some(suggested_name) = find_best_match_for_name(
1766 .map(|variant| variant.ident.name)
1767 .collect::<Vec<Symbol>>(),
1771 err.span_suggestion(
1773 "there is a variant with a similar name",
1774 suggested_name.to_string(),
1775 Applicability::MaybeIncorrect,
1780 format!("variant not found in `{}`", qself_ty),
1784 if let Some(sp) = tcx.hir().span_if_local(adt_def.did) {
1785 let sp = tcx.sess.source_map().guess_head_span(sp);
1786 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
1790 } else if !qself_ty.references_error() {
1791 // Don't print `TyErr` to the user.
1792 self.report_ambiguous_associated_type(
1794 &qself_ty.to_string(),
1799 return Err(ErrorReported);
1803 let trait_did = bound.def_id();
1804 let (assoc_ident, def_scope) =
1805 tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
1807 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1808 // of calling `filter_by_name_and_kind`.
1810 .associated_items(trait_did)
1811 .in_definition_order()
1813 i.kind.namespace() == Namespace::TypeNS
1814 && i.ident.normalize_to_macros_2_0() == assoc_ident
1816 .expect("missing associated type");
1818 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);
1819 let ty = self.normalize_ty(span, ty);
1821 let kind = DefKind::AssocTy;
1822 if !item.vis.is_accessible_from(def_scope, tcx) {
1823 let kind = kind.descr(item.def_id);
1824 let msg = format!("{} `{}` is private", kind, assoc_ident);
1826 .struct_span_err(span, &msg)
1827 .span_label(span, &format!("private {}", kind))
1830 tcx.check_stability(item.def_id, Some(hir_ref_id), span, None);
1832 if let Some(variant_def_id) = variant_resolution {
1833 tcx.struct_span_lint_hir(AMBIGUOUS_ASSOCIATED_ITEMS, hir_ref_id, span, |lint| {
1834 let mut err = lint.build("ambiguous associated item");
1835 let mut could_refer_to = |kind: DefKind, def_id, also| {
1836 let note_msg = format!(
1837 "`{}` could{} refer to the {} defined here",
1842 err.span_note(tcx.def_span(def_id), ¬e_msg);
1845 could_refer_to(DefKind::Variant, variant_def_id, "");
1846 could_refer_to(kind, item.def_id, " also");
1848 err.span_suggestion(
1850 "use fully-qualified syntax",
1851 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
1852 Applicability::MachineApplicable,
1858 Ok((ty, kind, item.def_id))
1864 opt_self_ty: Option<Ty<'tcx>>,
1866 trait_segment: &hir::PathSegment<'_>,
1867 item_segment: &hir::PathSegment<'_>,
1869 let tcx = self.tcx();
1871 let trait_def_id = tcx.parent(item_def_id).unwrap();
1873 debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
1875 let self_ty = if let Some(ty) = opt_self_ty {
1878 let path_str = tcx.def_path_str(trait_def_id);
1880 let def_id = self.item_def_id();
1882 debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
1884 let parent_def_id = def_id
1885 .and_then(|def_id| {
1886 def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
1888 .map(|hir_id| tcx.hir().get_parent_did(hir_id).to_def_id());
1890 debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
1892 // If the trait in segment is the same as the trait defining the item,
1893 // use the `<Self as ..>` syntax in the error.
1894 let is_part_of_self_trait_constraints = def_id == Some(trait_def_id);
1895 let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
1897 let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
1903 self.report_ambiguous_associated_type(
1907 item_segment.ident.name,
1909 return tcx.ty_error();
1912 debug!("qpath_to_ty: self_type={:?}", self_ty);
1914 let trait_ref = self.ast_path_to_mono_trait_ref(span, trait_def_id, self_ty, trait_segment);
1916 let item_substs = self.create_substs_for_associated_item(
1924 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1926 self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
1929 pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment<'a>>>(
1933 let mut has_err = false;
1934 for segment in segments {
1935 let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
1936 for arg in segment.args().args {
1937 let (span, kind) = match arg {
1938 hir::GenericArg::Lifetime(lt) => {
1944 (lt.span, "lifetime")
1946 hir::GenericArg::Type(ty) => {
1954 hir::GenericArg::Const(ct) => {
1962 hir::GenericArg::Infer(inf) => {
1968 (inf.span, "generic")
1971 let mut err = struct_span_err!(
1975 "{} arguments are not allowed for this type",
1978 err.span_label(span, format!("{} argument not allowed", kind));
1980 if err_for_lt && err_for_ty && err_for_ct {
1985 // Only emit the first error to avoid overloading the user with error messages.
1986 if let [binding, ..] = segment.args().bindings {
1988 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
1994 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
1995 pub fn def_ids_for_value_path_segments(
1997 segments: &[hir::PathSegment<'_>],
1998 self_ty: Option<Ty<'tcx>>,
2002 // We need to extract the type parameters supplied by the user in
2003 // the path `path`. Due to the current setup, this is a bit of a
2004 // tricky-process; the problem is that resolve only tells us the
2005 // end-point of the path resolution, and not the intermediate steps.
2006 // Luckily, we can (at least for now) deduce the intermediate steps
2007 // just from the end-point.
2009 // There are basically five cases to consider:
2011 // 1. Reference to a constructor of a struct:
2013 // struct Foo<T>(...)
2015 // In this case, the parameters are declared in the type space.
2017 // 2. Reference to a constructor of an enum variant:
2019 // enum E<T> { Foo(...) }
2021 // In this case, the parameters are defined in the type space,
2022 // but may be specified either on the type or the variant.
2024 // 3. Reference to a fn item or a free constant:
2028 // In this case, the path will again always have the form
2029 // `a::b::foo::<T>` where only the final segment should have
2030 // type parameters. However, in this case, those parameters are
2031 // declared on a value, and hence are in the `FnSpace`.
2033 // 4. Reference to a method or an associated constant:
2035 // impl<A> SomeStruct<A> {
2039 // Here we can have a path like
2040 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2041 // may appear in two places. The penultimate segment,
2042 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2043 // final segment, `foo::<B>` contains parameters in fn space.
2045 // The first step then is to categorize the segments appropriately.
2047 let tcx = self.tcx();
2049 assert!(!segments.is_empty());
2050 let last = segments.len() - 1;
2052 let mut path_segs = vec![];
2055 // Case 1. Reference to a struct constructor.
2056 DefKind::Ctor(CtorOf::Struct, ..) => {
2057 // Everything but the final segment should have no
2058 // parameters at all.
2059 let generics = tcx.generics_of(def_id);
2060 // Variant and struct constructors use the
2061 // generics of their parent type definition.
2062 let generics_def_id = generics.parent.unwrap_or(def_id);
2063 path_segs.push(PathSeg(generics_def_id, last));
2066 // Case 2. Reference to a variant constructor.
2067 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2068 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
2069 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
2070 debug_assert!(adt_def.is_enum());
2072 } else if last >= 1 && segments[last - 1].args.is_some() {
2073 // Everything but the penultimate segment should have no
2074 // parameters at all.
2075 let mut def_id = def_id;
2077 // `DefKind::Ctor` -> `DefKind::Variant`
2078 if let DefKind::Ctor(..) = kind {
2079 def_id = tcx.parent(def_id).unwrap()
2082 // `DefKind::Variant` -> `DefKind::Enum`
2083 let enum_def_id = tcx.parent(def_id).unwrap();
2084 (enum_def_id, last - 1)
2086 // FIXME: lint here recommending `Enum::<...>::Variant` form
2087 // instead of `Enum::Variant::<...>` form.
2089 // Everything but the final segment should have no
2090 // parameters at all.
2091 let generics = tcx.generics_of(def_id);
2092 // Variant and struct constructors use the
2093 // generics of their parent type definition.
2094 (generics.parent.unwrap_or(def_id), last)
2096 path_segs.push(PathSeg(generics_def_id, index));
2099 // Case 3. Reference to a top-level value.
2100 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static => {
2101 path_segs.push(PathSeg(def_id, last));
2104 // Case 4. Reference to a method or associated const.
2105 DefKind::AssocFn | DefKind::AssocConst => {
2106 if segments.len() >= 2 {
2107 let generics = tcx.generics_of(def_id);
2108 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2110 path_segs.push(PathSeg(def_id, last));
2113 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2116 debug!("path_segs = {:?}", path_segs);
2121 // Check a type `Path` and convert it to a `Ty`.
2124 opt_self_ty: Option<Ty<'tcx>>,
2125 path: &hir::Path<'_>,
2126 permit_variants: bool,
2128 let tcx = self.tcx();
2131 "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2132 path.res, opt_self_ty, path.segments
2135 let span = path.span;
2137 Res::Def(DefKind::OpaqueTy, did) => {
2138 // Check for desugared `impl Trait`.
2139 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2140 let item_segment = path.segments.split_last().unwrap();
2141 self.prohibit_generics(item_segment.1);
2142 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2143 self.normalize_ty(span, tcx.mk_opaque(did, substs))
2150 | DefKind::ForeignTy,
2153 assert_eq!(opt_self_ty, None);
2154 self.prohibit_generics(path.segments.split_last().unwrap().1);
2155 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2157 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2158 // Convert "variant type" as if it were a real type.
2159 // The resulting `Ty` is type of the variant's enum for now.
2160 assert_eq!(opt_self_ty, None);
2163 self.def_ids_for_value_path_segments(&path.segments, None, kind, def_id);
2164 let generic_segs: FxHashSet<_> =
2165 path_segs.iter().map(|PathSeg(_, index)| index).collect();
2166 self.prohibit_generics(path.segments.iter().enumerate().filter_map(
2168 if !generic_segs.contains(&index) { Some(seg) } else { None }
2172 let PathSeg(def_id, index) = path_segs.last().unwrap();
2173 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2175 Res::Def(DefKind::TyParam, def_id) => {
2176 assert_eq!(opt_self_ty, None);
2177 self.prohibit_generics(path.segments);
2179 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
2180 let item_id = tcx.hir().get_parent_node(hir_id);
2181 let item_def_id = tcx.hir().local_def_id(item_id);
2182 let generics = tcx.generics_of(item_def_id);
2183 let index = generics.param_def_id_to_index[&def_id];
2184 tcx.mk_ty_param(index, tcx.hir().name(hir_id))
2186 Res::SelfTy(Some(_), None) => {
2187 // `Self` in trait or type alias.
2188 assert_eq!(opt_self_ty, None);
2189 self.prohibit_generics(path.segments);
2190 tcx.types.self_param
2192 Res::SelfTy(_, Some((def_id, forbid_generic))) => {
2193 // `Self` in impl (we know the concrete type).
2194 assert_eq!(opt_self_ty, None);
2195 self.prohibit_generics(path.segments);
2196 // Try to evaluate any array length constants.
2197 let normalized_ty = self.normalize_ty(span, tcx.at(span).type_of(def_id));
2198 if forbid_generic && normalized_ty.needs_subst() {
2199 let mut err = tcx.sess.struct_span_err(
2201 "generic `Self` types are currently not permitted in anonymous constants",
2203 if let Some(hir::Node::Item(&hir::Item {
2204 kind: hir::ItemKind::Impl(ref impl_),
2206 })) = tcx.hir().get_if_local(def_id)
2208 err.span_note(impl_.self_ty.span, "not a concrete type");
2216 Res::Def(DefKind::AssocTy, def_id) => {
2217 debug_assert!(path.segments.len() >= 2);
2218 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
2223 &path.segments[path.segments.len() - 2],
2224 path.segments.last().unwrap(),
2227 Res::PrimTy(prim_ty) => {
2228 assert_eq!(opt_self_ty, None);
2229 self.prohibit_generics(path.segments);
2231 hir::PrimTy::Bool => tcx.types.bool,
2232 hir::PrimTy::Char => tcx.types.char,
2233 hir::PrimTy::Int(it) => tcx.mk_mach_int(ty::int_ty(it)),
2234 hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(ty::uint_ty(uit)),
2235 hir::PrimTy::Float(ft) => tcx.mk_mach_float(ty::float_ty(ft)),
2236 hir::PrimTy::Str => tcx.types.str_,
2240 self.set_tainted_by_errors();
2241 self.tcx().ty_error()
2243 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2247 /// Parses the programmer's textual representation of a type into our
2248 /// internal notion of a type.
2249 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2250 self.ast_ty_to_ty_inner(ast_ty, false)
2253 /// Turns a `hir::Ty` into a `Ty`. For diagnostics' purposes we keep track of whether trait
2254 /// objects are borrowed like `&dyn Trait` to avoid emitting redundant errors.
2255 #[tracing::instrument(level = "debug", skip(self))]
2256 fn ast_ty_to_ty_inner(&self, ast_ty: &hir::Ty<'_>, borrowed: bool) -> Ty<'tcx> {
2257 let tcx = self.tcx();
2259 let result_ty = match ast_ty.kind {
2260 hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(&ty)),
2261 hir::TyKind::Ptr(ref mt) => {
2262 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(&mt.ty), mutbl: mt.mutbl })
2264 hir::TyKind::Rptr(ref region, ref mt) => {
2265 let r = self.ast_region_to_region(region, None);
2267 let t = self.ast_ty_to_ty_inner(&mt.ty, true);
2268 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2270 hir::TyKind::Never => tcx.types.never,
2271 hir::TyKind::Tup(ref fields) => {
2272 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
2274 hir::TyKind::BareFn(ref bf) => {
2275 require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
2277 tcx.mk_fn_ptr(self.ty_of_fn(
2282 &hir::Generics::empty(),
2287 hir::TyKind::TraitObject(ref bounds, ref lifetime, _) => {
2288 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime, borrowed)
2290 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2291 debug!(?maybe_qself, ?path);
2292 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2293 self.res_to_ty(opt_self_ty, path, false)
2295 hir::TyKind::OpaqueDef(item_id, ref lifetimes) => {
2296 let opaque_ty = tcx.hir().item(item_id);
2297 let def_id = item_id.def_id.to_def_id();
2299 match opaque_ty.kind {
2300 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => {
2301 self.impl_trait_ty_to_ty(def_id, lifetimes, impl_trait_fn.is_some())
2303 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
2306 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2307 debug!(?qself, ?segment);
2308 let ty = self.ast_ty_to_ty(qself);
2310 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.kind {
2315 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2316 .map(|(ty, _, _)| ty)
2317 .unwrap_or_else(|_| tcx.ty_error())
2319 hir::TyKind::Path(hir::QPath::LangItem(lang_item, span)) => {
2320 let def_id = tcx.require_lang_item(lang_item, Some(span));
2321 let (substs, _) = self.create_substs_for_ast_path(
2325 &hir::PathSegment::invalid(),
2326 &GenericArgs::none(),
2330 self.normalize_ty(span, tcx.at(span).type_of(def_id).subst(tcx, substs))
2332 hir::TyKind::Array(ref ty, ref length) => {
2333 let length_def_id = tcx.hir().local_def_id(length.hir_id);
2334 let length = ty::Const::from_anon_const(tcx, length_def_id);
2335 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
2336 self.normalize_ty(ast_ty.span, array_ty)
2338 hir::TyKind::Typeof(ref e) => {
2339 tcx.sess.emit_err(TypeofReservedKeywordUsed { span: ast_ty.span });
2340 tcx.type_of(tcx.hir().local_def_id(e.hir_id))
2342 hir::TyKind::Infer => {
2343 // Infer also appears as the type of arguments or return
2344 // values in a ExprKind::Closure, or as
2345 // the type of local variables. Both of these cases are
2346 // handled specially and will not descend into this routine.
2347 self.ty_infer(None, ast_ty.span)
2349 hir::TyKind::Err => tcx.ty_error(),
2354 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2358 fn impl_trait_ty_to_ty(
2361 lifetimes: &[hir::GenericArg<'_>],
2362 replace_parent_lifetimes: bool,
2364 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2365 let tcx = self.tcx();
2367 let generics = tcx.generics_of(def_id);
2369 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2370 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2371 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2372 // Our own parameters are the resolved lifetimes.
2374 GenericParamDefKind::Lifetime => {
2375 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2376 self.ast_region_to_region(lifetime, None).into()
2385 // For RPIT (return position impl trait), only lifetimes
2386 // mentioned in the impl Trait predicate are captured by
2387 // the opaque type, so the lifetime parameters from the
2388 // parent item need to be replaced with `'static`.
2390 // For `impl Trait` in the types of statics, constants,
2391 // locals and type aliases. These capture all parent
2392 // lifetimes, so they can use their identity subst.
2393 GenericParamDefKind::Lifetime if replace_parent_lifetimes => {
2394 tcx.lifetimes.re_static.into()
2396 _ => tcx.mk_param_from_def(param),
2400 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2402 let ty = tcx.mk_opaque(def_id, substs);
2403 debug!("impl_trait_ty_to_ty: {}", ty);
2407 pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2409 hir::TyKind::Infer if expected_ty.is_some() => {
2410 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2411 expected_ty.unwrap()
2413 _ => self.ast_ty_to_ty(ty),
2420 unsafety: hir::Unsafety,
2422 decl: &hir::FnDecl<'_>,
2423 generics: &hir::Generics<'_>,
2424 ident_span: Option<Span>,
2425 hir_ty: Option<&hir::Ty<'_>>,
2426 ) -> ty::PolyFnSig<'tcx> {
2429 let tcx = self.tcx();
2430 let bound_vars = tcx.late_bound_vars(hir_id);
2431 debug!(?bound_vars);
2433 // We proactively collect all the inferred type params to emit a single error per fn def.
2434 let mut visitor = PlaceholderHirTyCollector::default();
2435 for ty in decl.inputs {
2436 visitor.visit_ty(ty);
2438 walk_generics(&mut visitor, generics);
2440 let input_tys = decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
2441 let output_ty = match decl.output {
2442 hir::FnRetTy::Return(ref output) => {
2443 visitor.visit_ty(output);
2444 self.ast_ty_to_ty(output)
2446 hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(),
2449 debug!("ty_of_fn: output_ty={:?}", output_ty);
2451 let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, unsafety, abi);
2452 let bare_fn_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
2454 if !self.allow_ty_infer() {
2455 // We always collect the spans for placeholder types when evaluating `fn`s, but we
2456 // only want to emit an error complaining about them if infer types (`_`) are not
2457 // allowed. `allow_ty_infer` gates this behavior. We check for the presence of
2458 // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`.
2460 crate::collect::placeholder_type_error(
2462 ident_span.map(|sp| sp.shrink_to_hi()),
2471 // Find any late-bound regions declared in return type that do
2472 // not appear in the arguments. These are not well-formed.
2475 // for<'a> fn() -> &'a str <-- 'a is bad
2476 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2477 let inputs = bare_fn_ty.inputs();
2478 let late_bound_in_args =
2479 tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
2480 let output = bare_fn_ty.output();
2481 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2483 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
2488 "return type references {}, which is not constrained by the fn input types",
2496 fn validate_late_bound_regions(
2498 constrained_regions: FxHashSet<ty::BoundRegionKind>,
2499 referenced_regions: FxHashSet<ty::BoundRegionKind>,
2500 generate_err: impl Fn(&str) -> rustc_errors::DiagnosticBuilder<'tcx>,
2502 for br in referenced_regions.difference(&constrained_regions) {
2503 let br_name = match *br {
2504 ty::BrNamed(_, name) => format!("lifetime `{}`", name),
2505 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
2508 let mut err = generate_err(&br_name);
2510 if let ty::BrAnon(_) = *br {
2511 // The only way for an anonymous lifetime to wind up
2512 // in the return type but **also** be unconstrained is
2513 // if it only appears in "associated types" in the
2514 // input. See #47511 and #62200 for examples. In this case,
2515 // though we can easily give a hint that ought to be
2518 "lifetimes appearing in an associated type are not considered constrained",
2526 /// Given the bounds on an object, determines what single region bound (if any) we can
2527 /// use to summarize this type. The basic idea is that we will use the bound the user
2528 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2529 /// for region bounds. It may be that we can derive no bound at all, in which case
2530 /// we return `None`.
2531 fn compute_object_lifetime_bound(
2534 existential_predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
2535 ) -> Option<ty::Region<'tcx>> // if None, use the default
2537 let tcx = self.tcx();
2539 debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
2541 // No explicit region bound specified. Therefore, examine trait
2542 // bounds and see if we can derive region bounds from those.
2543 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
2545 // If there are no derived region bounds, then report back that we
2546 // can find no region bound. The caller will use the default.
2547 if derived_region_bounds.is_empty() {
2551 // If any of the derived region bounds are 'static, that is always
2553 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
2554 return Some(tcx.lifetimes.re_static);
2557 // Determine whether there is exactly one unique region in the set
2558 // of derived region bounds. If so, use that. Otherwise, report an
2560 let r = derived_region_bounds[0];
2561 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2562 tcx.sess.emit_err(AmbiguousLifetimeBound { span });