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`, where `X` is
53 /// a type parameter `X` with the given id `def_id`. This is a
54 /// subset of the full set of predicates.
56 /// This is used for one specific purpose: resolving "short-hand"
57 /// associated type references like `T::Item`. In principle, we
58 /// would do that by first getting the full set of predicates in
59 /// scope and then filtering down to find those that apply to `T`,
60 /// but this can lead to cycle errors. The problem is that we have
61 /// to do this resolution *in order to create the predicates in
62 /// the first place*. Hence, we have this "special pass".
63 fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx>;
65 /// Returns the lifetime to use when a lifetime is omitted (and not elided).
66 fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span)
67 -> Option<ty::Region<'tcx>>;
69 /// Returns the type to use when a type is omitted.
70 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
72 /// Returns `true` if `_` is allowed in type signatures in the current context.
73 fn allow_ty_infer(&self) -> bool;
75 /// Returns the const to use when a const is omitted.
79 param: Option<&ty::GenericParamDef>,
81 ) -> &'tcx Const<'tcx>;
83 /// Projecting an associated type from a (potentially)
84 /// higher-ranked trait reference is more complicated, because of
85 /// the possibility of late-bound regions appearing in the
86 /// associated type binding. This is not legal in function
87 /// signatures for that reason. In a function body, we can always
88 /// handle it because we can use inference variables to remove the
89 /// late-bound regions.
90 fn projected_ty_from_poly_trait_ref(
94 item_segment: &hir::PathSegment<'_>,
95 poly_trait_ref: ty::PolyTraitRef<'tcx>,
98 /// Normalize an associated type coming from the user.
99 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
101 /// Invoked when we encounter an error from some prior pass
102 /// (e.g., resolve) that is translated into a ty-error. This is
103 /// used to help suppress derived errors typeck might otherwise
105 fn set_tainted_by_errors(&self);
107 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
110 pub enum SizedByDefault {
116 struct ConvertedBinding<'a, 'tcx> {
118 kind: ConvertedBindingKind<'a, 'tcx>,
119 gen_args: &'a GenericArgs<'a>,
124 enum ConvertedBindingKind<'a, 'tcx> {
126 Constraint(&'a [hir::GenericBound<'a>]),
129 /// New-typed boolean indicating whether explicit late-bound lifetimes
130 /// are present in a set of generic arguments.
132 /// For example if we have some method `fn f<'a>(&'a self)` implemented
133 /// for some type `T`, although `f` is generic in the lifetime `'a`, `'a`
134 /// is late-bound so should not be provided explicitly. Thus, if `f` is
135 /// instantiated with some generic arguments providing `'a` explicitly,
136 /// we taint those arguments with `ExplicitLateBound::Yes` so that we
137 /// can provide an appropriate diagnostic later.
138 #[derive(Copy, Clone, PartialEq)]
139 pub enum ExplicitLateBound {
144 #[derive(Copy, Clone, PartialEq)]
145 pub enum IsMethodCall {
150 /// Denotes the "position" of a generic argument, indicating if it is a generic type,
151 /// generic function or generic method call.
152 #[derive(Copy, Clone, PartialEq)]
153 pub(crate) enum GenericArgPosition {
155 Value, // e.g., functions
159 /// A marker denoting that the generic arguments that were
160 /// provided did not match the respective generic parameters.
161 #[derive(Clone, Default)]
162 pub struct GenericArgCountMismatch {
163 /// Indicates whether a fatal error was reported (`Some`), or just a lint (`None`).
164 pub reported: Option<ErrorReported>,
165 /// A list of spans of arguments provided that were not valid.
166 pub invalid_args: Vec<Span>,
169 /// Decorates the result of a generic argument count mismatch
170 /// check with whether explicit late bounds were provided.
172 pub struct GenericArgCountResult {
173 pub explicit_late_bound: ExplicitLateBound,
174 pub correct: Result<(), GenericArgCountMismatch>,
177 pub trait CreateSubstsForGenericArgsCtxt<'a, 'tcx> {
178 fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'a>>, bool);
182 param: &ty::GenericParamDef,
183 arg: &GenericArg<'_>,
184 ) -> subst::GenericArg<'tcx>;
188 substs: Option<&[subst::GenericArg<'tcx>]>,
189 param: &ty::GenericParamDef,
191 ) -> subst::GenericArg<'tcx>;
194 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
195 pub fn ast_region_to_region(
197 lifetime: &hir::Lifetime,
198 def: Option<&ty::GenericParamDef>,
199 ) -> ty::Region<'tcx> {
200 let tcx = self.tcx();
201 let lifetime_name = |def_id| tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id));
203 let r = match tcx.named_region(lifetime.hir_id) {
204 Some(rl::Region::Static) => tcx.lifetimes.re_static,
206 Some(rl::Region::LateBound(debruijn, id, _)) => {
207 let name = lifetime_name(id.expect_local());
208 let br = ty::BoundRegion { kind: ty::BrNamed(id, name) };
209 tcx.mk_region(ty::ReLateBound(debruijn, br))
212 Some(rl::Region::LateBoundAnon(debruijn, index)) => {
213 let br = ty::BoundRegion { kind: ty::BrAnon(index) };
214 tcx.mk_region(ty::ReLateBound(debruijn, br))
217 Some(rl::Region::EarlyBound(index, id, _)) => {
218 let name = lifetime_name(id.expect_local());
219 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: id, index, name }))
222 Some(rl::Region::Free(scope, id)) => {
223 let name = lifetime_name(id.expect_local());
224 tcx.mk_region(ty::ReFree(ty::FreeRegion {
226 bound_region: ty::BrNamed(id, name),
229 // (*) -- not late-bound, won't change
233 self.re_infer(def, lifetime.span).unwrap_or_else(|| {
234 // This indicates an illegal lifetime
235 // elision. `resolve_lifetime` should have
236 // reported an error in this case -- but if
237 // not, let's error out.
238 tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
240 // Supply some dummy value. We don't have an
241 // `re_error`, annoyingly, so use `'static`.
242 tcx.lifetimes.re_static
247 debug!("ast_region_to_region(lifetime={:?}) yields {:?}", lifetime, r);
252 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
253 /// returns an appropriate set of substitutions for this particular reference to `I`.
254 pub fn ast_path_substs_for_ty(
258 item_segment: &hir::PathSegment<'_>,
259 ) -> SubstsRef<'tcx> {
260 let (substs, assoc_bindings, _) = self.create_substs_for_ast_path(
266 item_segment.infer_args,
270 if let Some(b) = assoc_bindings.first() {
271 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
277 /// Given the type/lifetime/const arguments provided to some path (along with
278 /// an implicit `Self`, if this is a trait reference), returns the complete
279 /// set of substitutions. This may involve applying defaulted type parameters.
280 /// Also returns back constraints on associated types.
285 /// T: std::ops::Index<usize, Output = u32>
286 /// ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4
289 /// 1. The `self_ty` here would refer to the type `T`.
290 /// 2. The path in question is the path to the trait `std::ops::Index`,
291 /// which will have been resolved to a `def_id`
292 /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
293 /// parameters are returned in the `SubstsRef`, the associated type bindings like
294 /// `Output = u32` are returned in the `Vec<ConvertedBinding...>` result.
296 /// Note that the type listing given here is *exactly* what the user provided.
298 /// For (generic) associated types
301 /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
304 /// We have the parent substs are the substs for the parent trait:
305 /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
306 /// type itself: `['a]`. The returned `SubstsRef` concatenates these two
307 /// lists: `[Vec<u8>, u8, 'a]`.
308 fn create_substs_for_ast_path<'a>(
312 parent_substs: &[subst::GenericArg<'tcx>],
313 seg: &hir::PathSegment<'_>,
314 generic_args: &'a hir::GenericArgs<'_>,
316 self_ty: Option<Ty<'tcx>>,
317 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, GenericArgCountResult) {
318 // If the type is parameterized by this region, then replace this
319 // region with the current anon region binding (in other words,
320 // whatever & would get replaced with).
322 "create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
324 def_id, self_ty, generic_args
327 let tcx = self.tcx();
328 let generics = tcx.generics_of(def_id);
329 debug!("generics: {:?}", generics);
331 if generics.has_self {
332 if generics.parent.is_some() {
333 // The parent is a trait so it should have at least one subst
334 // for the `Self` type.
335 assert!(!parent_substs.is_empty())
337 // This item (presumably a trait) needs a self-type.
338 assert!(self_ty.is_some());
341 assert!(self_ty.is_none() && parent_substs.is_empty());
344 let arg_count = Self::check_generic_arg_count(
351 GenericArgPosition::Type,
356 // Skip processing if type has no generic parameters.
357 // Traits always have `Self` as a generic parameter, which means they will not return early
358 // here and so associated type bindings will be handled regardless of whether there are any
359 // non-`Self` generic parameters.
360 if generics.params.len() == 0 {
361 return (tcx.intern_substs(&[]), vec![], arg_count);
364 let is_object = self_ty.map_or(false, |ty| ty == self.tcx().types.trait_object_dummy_self);
366 struct SubstsForAstPathCtxt<'a, 'tcx> {
367 astconv: &'a (dyn AstConv<'tcx> + 'a),
369 generic_args: &'a GenericArgs<'a>,
371 missing_type_params: Vec<String>,
372 inferred_params: Vec<Span>,
377 impl<'tcx, 'a> SubstsForAstPathCtxt<'tcx, 'a> {
378 fn default_needs_object_self(&mut self, param: &ty::GenericParamDef) -> bool {
379 let tcx = self.astconv.tcx();
380 if let GenericParamDefKind::Type { has_default, .. } = param.kind {
381 if self.is_object && has_default {
382 let default_ty = tcx.at(self.span).type_of(param.def_id);
383 let self_param = tcx.types.self_param;
384 if default_ty.walk().any(|arg| arg == self_param.into()) {
385 // There is no suitable inference default for a type parameter
386 // that references self, in an object type.
396 impl<'a, 'tcx> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for SubstsForAstPathCtxt<'a, 'tcx> {
397 fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'a>>, bool) {
398 if did == self.def_id {
399 (Some(self.generic_args), self.infer_args)
401 // The last component of this tuple is unimportant.
408 param: &ty::GenericParamDef,
409 arg: &GenericArg<'_>,
410 ) -> subst::GenericArg<'tcx> {
411 let tcx = self.astconv.tcx();
412 match (¶m.kind, arg) {
413 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
414 self.astconv.ast_region_to_region(<, Some(param)).into()
416 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
418 tcx.check_optional_stability(
423 // Default generic parameters may not be marked
424 // with stability attributes, i.e. when the
425 // default parameter was defined at the same time
426 // as the rest of the type. As such, we ignore missing
427 // stability attributes.
431 if let (hir::TyKind::Infer, false) =
432 (&ty.kind, self.astconv.allow_ty_infer())
434 self.inferred_params.push(ty.span);
435 tcx.ty_error().into()
437 self.astconv.ast_ty_to_ty(&ty).into()
440 (GenericParamDefKind::Const, GenericArg::Const(ct)) => {
441 ty::Const::from_opt_const_arg_anon_const(
443 ty::WithOptConstParam {
444 did: tcx.hir().local_def_id(ct.value.hir_id),
445 const_param_did: Some(param.def_id),
456 substs: Option<&[subst::GenericArg<'tcx>]>,
457 param: &ty::GenericParamDef,
459 ) -> subst::GenericArg<'tcx> {
460 let tcx = self.astconv.tcx();
462 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
463 GenericParamDefKind::Type { has_default, .. } => {
464 if !infer_args && has_default {
465 // No type parameter provided, but a default exists.
467 // If we are converting an object type, then the
468 // `Self` parameter is unknown. However, some of the
469 // other type parameters may reference `Self` in their
470 // defaults. This will lead to an ICE if we are not
472 if self.default_needs_object_self(param) {
473 self.missing_type_params.push(param.name.to_string());
474 tcx.ty_error().into()
476 // This is a default type parameter.
480 tcx.at(self.span).type_of(param.def_id).subst_spanned(
488 } else if infer_args {
489 // No type parameters were provided, we can infer all.
490 let param = if !self.default_needs_object_self(param) {
495 self.astconv.ty_infer(param, self.span).into()
497 // We've already errored above about the mismatch.
498 tcx.ty_error().into()
501 GenericParamDefKind::Const => {
502 let ty = tcx.at(self.span).type_of(param.def_id);
503 // FIXME(const_generics_defaults)
505 // No const parameters were provided, we can infer all.
506 self.astconv.ct_infer(ty, Some(param), self.span).into()
508 // We've already errored above about the mismatch.
509 tcx.const_error(ty).into()
516 let mut substs_ctx = SubstsForAstPathCtxt {
521 missing_type_params: vec![],
522 inferred_params: vec![],
526 let substs = Self::create_substs_for_generic_args(
536 self.complain_about_missing_type_params(
537 substs_ctx.missing_type_params,
540 generic_args.args.is_empty(),
543 // Convert associated-type bindings or constraints into a separate vector.
544 // Example: Given this:
546 // T: Iterator<Item = u32>
548 // The `T` is passed in as a self-type; the `Item = u32` is
549 // not a "type parameter" of the `Iterator` trait, but rather
550 // a restriction on `<T as Iterator>::Item`, so it is passed
552 let assoc_bindings = generic_args
556 let kind = match binding.kind {
557 hir::TypeBindingKind::Equality { ref ty } => {
558 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty))
560 hir::TypeBindingKind::Constraint { ref bounds } => {
561 ConvertedBindingKind::Constraint(bounds)
565 item_name: binding.ident,
567 gen_args: binding.gen_args,
574 "create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
575 generics, self_ty, substs
578 (substs, assoc_bindings, arg_count)
581 crate fn create_substs_for_associated_item(
586 item_segment: &hir::PathSegment<'_>,
587 parent_substs: SubstsRef<'tcx>,
588 ) -> SubstsRef<'tcx> {
589 if tcx.generics_of(item_def_id).params.is_empty() {
590 self.prohibit_generics(slice::from_ref(item_segment));
594 self.create_substs_for_ast_path(
600 item_segment.infer_args,
607 /// Instantiates the path for the given trait reference, assuming that it's
608 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
609 /// The type _cannot_ be a type other than a trait type.
611 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
612 /// are disallowed. Otherwise, they are pushed onto the vector given.
613 pub fn instantiate_mono_trait_ref(
615 trait_ref: &hir::TraitRef<'_>,
617 ) -> ty::TraitRef<'tcx> {
618 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
620 self.ast_path_to_mono_trait_ref(
622 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
624 trait_ref.path.segments.last().unwrap(),
628 /// The given trait-ref must actually be a trait.
629 pub(super) fn instantiate_poly_trait_ref_inner(
631 trait_ref: &hir::TraitRef<'_>,
633 constness: Constness,
635 bounds: &mut Bounds<'tcx>,
637 ) -> GenericArgCountResult {
638 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
640 debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
642 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
644 let (substs, assoc_bindings, arg_count) = self.create_substs_for_ast_trait_ref(
648 trait_ref.path.segments.last().unwrap(),
650 let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
652 bounds.trait_bounds.push((poly_trait_ref, span, constness));
654 let mut dup_bindings = FxHashMap::default();
655 for binding in &assoc_bindings {
656 // Specify type to assert that error was already reported in `Err` case.
657 let _: Result<_, ErrorReported> = self.add_predicates_for_ast_type_binding(
658 trait_ref.hir_ref_id,
666 // Okay to ignore `Err` because of `ErrorReported` (see above).
670 "instantiate_poly_trait_ref({:?}, bounds={:?}) -> {:?}",
671 trait_ref, bounds, poly_trait_ref
677 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
678 /// a full trait reference. The resulting trait reference is returned. This may also generate
679 /// auxiliary bounds, which are added to `bounds`.
684 /// poly_trait_ref = Iterator<Item = u32>
688 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
690 /// **A note on binders:** against our usual convention, there is an implied bounder around
691 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
692 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
693 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
694 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
696 pub fn instantiate_poly_trait_ref(
698 poly_trait_ref: &hir::PolyTraitRef<'_>,
699 constness: Constness,
701 bounds: &mut Bounds<'tcx>,
702 ) -> GenericArgCountResult {
703 self.instantiate_poly_trait_ref_inner(
704 &poly_trait_ref.trait_ref,
713 pub fn instantiate_lang_item_trait_ref(
715 lang_item: hir::LangItem,
718 args: &GenericArgs<'_>,
720 bounds: &mut Bounds<'tcx>,
722 let trait_def_id = self.tcx().require_lang_item(lang_item, Some(span));
724 let (substs, assoc_bindings, _) = self.create_substs_for_ast_path(
728 &hir::PathSegment::invalid(),
733 let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
734 bounds.trait_bounds.push((poly_trait_ref, span, Constness::NotConst));
736 let mut dup_bindings = FxHashMap::default();
737 for binding in assoc_bindings {
738 let _: Result<_, ErrorReported> = self.add_predicates_for_ast_type_binding(
750 fn ast_path_to_mono_trait_ref(
755 trait_segment: &hir::PathSegment<'_>,
756 ) -> ty::TraitRef<'tcx> {
757 let (substs, assoc_bindings, _) =
758 self.create_substs_for_ast_trait_ref(span, trait_def_id, self_ty, trait_segment);
759 if let Some(b) = assoc_bindings.first() {
760 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
762 ty::TraitRef::new(trait_def_id, substs)
765 fn create_substs_for_ast_trait_ref<'a>(
770 trait_segment: &'a hir::PathSegment<'a>,
771 ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, GenericArgCountResult) {
772 debug!("create_substs_for_ast_trait_ref(trait_segment={:?})", trait_segment);
774 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment);
776 self.create_substs_for_ast_path(
781 trait_segment.args(),
782 trait_segment.infer_args,
787 fn trait_defines_associated_type_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
789 .associated_items(trait_def_id)
790 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, trait_def_id)
794 // Returns `true` if a bounds list includes `?Sized`.
795 pub fn is_unsized(&self, ast_bounds: &[hir::GenericBound<'_>], span: Span) -> bool {
796 let tcx = self.tcx();
798 // Try to find an unbound in bounds.
799 let mut unbound = None;
800 for ab in ast_bounds {
801 if let hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = ab {
802 if unbound.is_none() {
803 unbound = Some(&ptr.trait_ref);
805 tcx.sess.emit_err(MultipleRelaxedDefaultBounds { span });
810 let kind_id = tcx.lang_items().require(LangItem::Sized);
813 // FIXME(#8559) currently requires the unbound to be built-in.
814 if let Ok(kind_id) = kind_id {
815 if tpb.path.res != Res::Def(DefKind::Trait, kind_id) {
818 "default bound relaxed for a type parameter, but \
819 this does nothing because the given bound is not \
820 a default; only `?Sized` is supported",
825 _ if kind_id.is_ok() => {
828 // No lang item for `Sized`, so we can't add it as a bound.
835 /// This helper takes a *converted* parameter type (`param_ty`)
836 /// and an *unconverted* list of bounds:
840 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
842 /// `param_ty`, in ty form
845 /// It adds these `ast_bounds` into the `bounds` structure.
847 /// **A note on binders:** there is an implied binder around
848 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
849 /// for more details.
853 ast_bounds: &[hir::GenericBound<'_>],
854 bounds: &mut Bounds<'tcx>,
856 let constness = self.default_constness_for_trait_bounds();
857 for ast_bound in ast_bounds {
859 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => {
860 self.instantiate_poly_trait_ref(b, constness, param_ty, bounds);
862 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::MaybeConst) => {
863 self.instantiate_poly_trait_ref(b, Constness::NotConst, param_ty, bounds);
865 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
866 hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => self
867 .instantiate_lang_item_trait_ref(
868 lang_item, span, hir_id, args, param_ty, bounds,
870 hir::GenericBound::Outlives(ref l) => bounds
872 .push((ty::Binder::bind(self.ast_region_to_region(l, None)), l.span)),
877 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
878 /// The self-type for the bounds is given by `param_ty`.
883 /// fn foo<T: Bar + Baz>() { }
884 /// ^ ^^^^^^^^^ ast_bounds
888 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
889 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
890 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
892 /// `span` should be the declaration size of the parameter.
893 pub fn compute_bounds(
896 ast_bounds: &[hir::GenericBound<'_>],
897 sized_by_default: SizedByDefault,
900 let mut bounds = Bounds::default();
902 self.add_bounds(param_ty, ast_bounds, &mut bounds);
903 bounds.trait_bounds.sort_by_key(|(t, _, _)| t.def_id());
905 bounds.implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
906 if !self.is_unsized(ast_bounds, span) { Some(span) } else { None }
914 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
917 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
918 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
919 /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
920 fn add_predicates_for_ast_type_binding(
922 hir_ref_id: hir::HirId,
923 trait_ref: ty::PolyTraitRef<'tcx>,
924 binding: &ConvertedBinding<'_, 'tcx>,
925 bounds: &mut Bounds<'tcx>,
927 dup_bindings: &mut FxHashMap<DefId, Span>,
929 ) -> Result<(), ErrorReported> {
930 // Given something like `U: SomeTrait<T = X>`, we want to produce a
931 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
932 // subtle in the event that `T` is defined in a supertrait of
933 // `SomeTrait`, because in that case we need to upcast.
935 // That is, consider this case:
938 // trait SubTrait: SuperTrait<i32> { }
939 // trait SuperTrait<A> { type T; }
941 // ... B: SubTrait<T = foo> ...
944 // We want to produce `<B as SuperTrait<i32>>::T == foo`.
947 "add_predicates_for_ast_type_binding(hir_ref_id {:?}, trait_ref {:?}, binding {:?}, bounds {:?}",
948 hir_ref_id, trait_ref, binding, bounds
950 let tcx = self.tcx();
953 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
954 // Simple case: X is defined in the current trait.
957 // Otherwise, we have to walk through the supertraits to find
959 self.one_bound_for_assoc_type(
960 || traits::supertraits(tcx, trait_ref),
961 || trait_ref.print_only_trait_path().to_string(),
964 || match binding.kind {
965 ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
971 let (assoc_ident, def_scope) =
972 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
974 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
975 // of calling `filter_by_name_and_kind`.
977 .associated_items(candidate.def_id())
978 .filter_by_name_unhygienic(assoc_ident.name)
980 i.kind == ty::AssocKind::Type && i.ident.normalize_to_macros_2_0() == assoc_ident
982 .expect("missing associated type");
984 if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
988 &format!("associated type `{}` is private", binding.item_name),
990 .span_label(binding.span, "private associated type")
993 tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span);
997 .entry(assoc_ty.def_id)
998 .and_modify(|prev_span| {
999 self.tcx().sess.emit_err(ValueOfAssociatedStructAlreadySpecified {
1001 prev_span: *prev_span,
1002 item_name: binding.item_name,
1003 def_path: tcx.def_path_str(assoc_ty.container.id()),
1006 .or_insert(binding.span);
1009 // Include substitutions for generic parameters of associated types
1010 let projection_ty = candidate.map_bound(|trait_ref| {
1011 let item_segment = hir::PathSegment {
1012 ident: assoc_ty.ident,
1015 args: Some(binding.gen_args),
1019 let substs_trait_ref_and_assoc_item = self.create_substs_for_associated_item(
1028 "add_predicates_for_ast_type_binding: substs for trait-ref and assoc_item: {:?}",
1029 substs_trait_ref_and_assoc_item
1033 item_def_id: assoc_ty.def_id,
1034 substs: substs_trait_ref_and_assoc_item,
1039 // Find any late-bound regions declared in `ty` that are not
1040 // declared in the trait-ref or assoc_ty. These are not well-formed.
1044 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1045 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1046 if let ConvertedBindingKind::Equality(ty) = binding.kind {
1047 let late_bound_in_trait_ref =
1048 tcx.collect_constrained_late_bound_regions(&projection_ty);
1049 let late_bound_in_ty =
1050 tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(ty));
1051 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
1052 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
1054 // FIXME: point at the type params that don't have appropriate lifetimes:
1055 // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
1056 // ---- ---- ^^^^^^^
1057 self.validate_late_bound_regions(
1058 late_bound_in_trait_ref,
1065 "binding for associated type `{}` references {}, \
1066 which does not appear in the trait input types",
1075 match binding.kind {
1076 ConvertedBindingKind::Equality(ref ty) => {
1077 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1078 // the "projection predicate" for:
1080 // `<T as Iterator>::Item = u32`
1081 bounds.projection_bounds.push((
1082 projection_ty.map_bound(|projection_ty| {
1084 "add_predicates_for_ast_type_binding: projection_ty {:?}, substs: {:?}",
1085 projection_ty, projection_ty.substs
1087 ty::ProjectionPredicate { projection_ty, ty }
1092 ConvertedBindingKind::Constraint(ast_bounds) => {
1093 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1095 // `<T as Iterator>::Item: Debug`
1097 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1098 // parameter to have a skipped binder.
1100 tcx.mk_projection(assoc_ty.def_id, projection_ty.skip_binder().substs);
1101 self.add_bounds(param_ty, ast_bounds, bounds);
1111 item_segment: &hir::PathSegment<'_>,
1113 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1114 self.normalize_ty(span, self.tcx().at(span).type_of(did).subst(self.tcx(), substs))
1117 fn conv_object_ty_poly_trait_ref(
1120 trait_bounds: &[hir::PolyTraitRef<'_>],
1121 lifetime: &hir::Lifetime,
1124 let tcx = self.tcx();
1126 let mut bounds = Bounds::default();
1127 let mut potential_assoc_types = Vec::new();
1128 let dummy_self = self.tcx().types.trait_object_dummy_self;
1129 for trait_bound in trait_bounds.iter().rev() {
1130 if let GenericArgCountResult {
1132 Err(GenericArgCountMismatch { invalid_args: cur_potential_assoc_types, .. }),
1134 } = self.instantiate_poly_trait_ref(
1136 Constness::NotConst,
1140 potential_assoc_types.extend(cur_potential_assoc_types);
1144 // Expand trait aliases recursively and check that only one regular (non-auto) trait
1145 // is used and no 'maybe' bounds are used.
1146 let expanded_traits =
1147 traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().map(|&(a, b, _)| (a, b)));
1148 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) =
1149 expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1150 if regular_traits.len() > 1 {
1151 let first_trait = ®ular_traits[0];
1152 let additional_trait = ®ular_traits[1];
1153 let mut err = struct_span_err!(
1155 additional_trait.bottom().1,
1157 "only auto traits can be used as additional traits in a trait object"
1159 additional_trait.label_with_exp_info(
1161 "additional non-auto trait",
1164 first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1166 "consider creating a new trait with all of these as super-traits and using that \
1167 trait here instead: `trait NewTrait: {} {{}}`",
1170 .map(|t| t.trait_ref().print_only_trait_path().to_string())
1171 .collect::<Vec<_>>()
1175 "auto-traits like `Send` and `Sync` are traits that have special properties; \
1176 for more information on them, visit \
1177 <https://doc.rust-lang.org/reference/special-types-and-traits.html#auto-traits>",
1182 if regular_traits.is_empty() && auto_traits.is_empty() {
1183 tcx.sess.emit_err(TraitObjectDeclaredWithNoTraits { span });
1184 return tcx.ty_error();
1187 // Check that there are no gross object safety violations;
1188 // most importantly, that the supertraits don't contain `Self`,
1190 for item in ®ular_traits {
1191 let object_safety_violations =
1192 astconv_object_safety_violations(tcx, item.trait_ref().def_id());
1193 if !object_safety_violations.is_empty() {
1194 report_object_safety_error(
1197 item.trait_ref().def_id(),
1198 &object_safety_violations[..],
1201 return tcx.ty_error();
1205 // Use a `BTreeSet` to keep output in a more consistent order.
1206 let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1208 let regular_traits_refs_spans = bounds
1211 .filter(|(trait_ref, _, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1213 for (base_trait_ref, span, constness) in regular_traits_refs_spans {
1214 assert_eq!(constness, Constness::NotConst);
1216 for obligation in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1218 "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1219 obligation.predicate
1222 let bound_predicate = obligation.predicate.kind();
1223 match bound_predicate.skip_binder() {
1224 ty::PredicateKind::Trait(pred, _) => {
1225 let pred = bound_predicate.rebind(pred);
1226 associated_types.entry(span).or_default().extend(
1227 tcx.associated_items(pred.def_id())
1228 .in_definition_order()
1229 .filter(|item| item.kind == ty::AssocKind::Type)
1230 .map(|item| item.def_id),
1233 ty::PredicateKind::Projection(pred) => {
1234 let pred = bound_predicate.rebind(pred);
1235 // A `Self` within the original bound will be substituted with a
1236 // `trait_object_dummy_self`, so check for that.
1237 let references_self =
1238 pred.skip_binder().ty.walk().any(|arg| arg == dummy_self.into());
1240 // If the projection output contains `Self`, force the user to
1241 // elaborate it explicitly to avoid a lot of complexity.
1243 // The "classicaly useful" case is the following:
1245 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1250 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1251 // but actually supporting that would "expand" to an infinitely-long type
1252 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1254 // Instead, we force the user to write
1255 // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1256 // the discussion in #56288 for alternatives.
1257 if !references_self {
1258 // Include projections defined on supertraits.
1259 bounds.projection_bounds.push((pred, span));
1267 for (projection_bound, _) in &bounds.projection_bounds {
1268 for def_ids in associated_types.values_mut() {
1269 def_ids.remove(&projection_bound.projection_def_id());
1273 self.complain_about_missing_associated_types(
1275 potential_assoc_types,
1279 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1280 // `dyn Trait + Send`.
1281 auto_traits.sort_by_key(|i| i.trait_ref().def_id());
1282 auto_traits.dedup_by_key(|i| i.trait_ref().def_id());
1283 debug!("regular_traits: {:?}", regular_traits);
1284 debug!("auto_traits: {:?}", auto_traits);
1286 // Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
1287 // removing the dummy `Self` type (`trait_object_dummy_self`).
1288 let trait_ref_to_existential = |trait_ref: ty::TraitRef<'tcx>| {
1289 if trait_ref.self_ty() != dummy_self {
1290 // FIXME: There appears to be a missing filter on top of `expand_trait_aliases`,
1291 // which picks up non-supertraits where clauses - but also, the object safety
1292 // completely ignores trait aliases, which could be object safety hazards. We
1293 // `delay_span_bug` here to avoid an ICE in stable even when the feature is
1294 // disabled. (#66420)
1295 tcx.sess.delay_span_bug(
1298 "trait_ref_to_existential called on {:?} with non-dummy Self",
1303 ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
1306 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1307 let existential_trait_refs =
1308 regular_traits.iter().map(|i| i.trait_ref().map_bound(trait_ref_to_existential));
1309 let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1310 bound.map_bound(|b| {
1311 let trait_ref = trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1312 ty::ExistentialProjection {
1314 item_def_id: b.projection_ty.item_def_id,
1315 substs: trait_ref.substs,
1320 let regular_trait_predicates = existential_trait_refs
1321 .map(|trait_ref| trait_ref.map_bound(ty::ExistentialPredicate::Trait));
1322 let auto_trait_predicates = auto_traits.into_iter().map(|trait_ref| {
1323 ty::Binder::dummy(ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()))
1325 let mut v = regular_trait_predicates
1326 .chain(auto_trait_predicates)
1328 existential_projections.map(|x| x.map_bound(ty::ExistentialPredicate::Projection)),
1330 .collect::<SmallVec<[_; 8]>>();
1331 v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
1333 let existential_predicates = tcx.mk_poly_existential_predicates(v.into_iter());
1335 // Use explicitly-specified region bound.
1336 let region_bound = if !lifetime.is_elided() {
1337 self.ast_region_to_region(lifetime, None)
1339 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1340 if tcx.named_region(lifetime.hir_id).is_some() {
1341 self.ast_region_to_region(lifetime, None)
1343 self.re_infer(None, span).unwrap_or_else(|| {
1344 let mut err = struct_span_err!(
1348 "the lifetime bound for this object type cannot be deduced \
1349 from context; please supply an explicit bound"
1352 // We will have already emitted an error E0106 complaining about a
1353 // missing named lifetime in `&dyn Trait`, so we elide this one.
1358 tcx.lifetimes.re_static
1363 debug!("region_bound: {:?}", region_bound);
1365 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1366 debug!("trait_object_type: {:?}", ty);
1370 fn report_ambiguous_associated_type(
1377 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1378 if let (Some(_), Ok(snippet)) = (
1379 self.tcx().sess.confused_type_with_std_module.borrow().get(&span),
1380 self.tcx().sess.source_map().span_to_snippet(span),
1382 err.span_suggestion(
1384 "you are looking for the module in `std`, not the primitive type",
1385 format!("std::{}", snippet),
1386 Applicability::MachineApplicable,
1389 err.span_suggestion(
1391 "use fully-qualified syntax",
1392 format!("<{} as {}>::{}", type_str, trait_str, name),
1393 Applicability::HasPlaceholders,
1399 // Search for a bound on a type parameter which includes the associated item
1400 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1401 // This function will fail if there are no suitable bounds or there is
1403 fn find_bound_for_assoc_item(
1405 ty_param_def_id: LocalDefId,
1408 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported> {
1409 let tcx = self.tcx();
1412 "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
1413 ty_param_def_id, assoc_name, span,
1417 &self.get_type_parameter_bounds(span, ty_param_def_id.to_def_id()).predicates;
1419 debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1421 let param_hir_id = tcx.hir().local_def_id_to_hir_id(ty_param_def_id);
1422 let param_name = tcx.hir().ty_param_name(param_hir_id);
1423 self.one_bound_for_assoc_type(
1425 traits::transitive_bounds(
1427 predicates.iter().filter_map(|(p, _)| {
1428 p.to_opt_poly_trait_ref().map(|trait_ref| trait_ref.value)
1432 || param_name.to_string(),
1439 // Checks that `bounds` contains exactly one element and reports appropriate
1440 // errors otherwise.
1441 fn one_bound_for_assoc_type<I>(
1443 all_candidates: impl Fn() -> I,
1444 ty_param_name: impl Fn() -> String,
1447 is_equality: impl Fn() -> Option<String>,
1448 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1450 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1452 let mut matching_candidates = all_candidates()
1453 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
1455 let bound = match matching_candidates.next() {
1456 Some(bound) => bound,
1458 self.complain_about_assoc_type_not_found(
1464 return Err(ErrorReported);
1468 debug!("one_bound_for_assoc_type: bound = {:?}", bound);
1470 if let Some(bound2) = matching_candidates.next() {
1471 debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2);
1473 let is_equality = is_equality();
1474 let bounds = array::IntoIter::new([bound, bound2]).chain(matching_candidates);
1475 let mut err = if is_equality.is_some() {
1476 // More specific Error Index entry.
1481 "ambiguous associated type `{}` in bounds of `{}`",
1490 "ambiguous associated type `{}` in bounds of `{}`",
1495 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1497 let mut where_bounds = vec![];
1498 for bound in bounds {
1499 let bound_id = bound.def_id();
1500 let bound_span = self
1502 .associated_items(bound_id)
1503 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, bound_id)
1504 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1506 if let Some(bound_span) = bound_span {
1510 "ambiguous `{}` from `{}`",
1512 bound.print_only_trait_path(),
1515 if let Some(constraint) = &is_equality {
1516 where_bounds.push(format!(
1517 " T: {trait}::{assoc} = {constraint}",
1518 trait=bound.print_only_trait_path(),
1520 constraint=constraint,
1523 err.span_suggestion(
1525 "use fully qualified syntax to disambiguate",
1529 bound.print_only_trait_path(),
1532 Applicability::MaybeIncorrect,
1537 "associated type `{}` could derive from `{}`",
1539 bound.print_only_trait_path(),
1543 if !where_bounds.is_empty() {
1545 "consider introducing a new type parameter `T` and adding `where` constraints:\
1546 \n where\n T: {},\n{}",
1548 where_bounds.join(",\n"),
1552 if !where_bounds.is_empty() {
1553 return Err(ErrorReported);
1559 // Create a type from a path to an associated type.
1560 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
1561 // and item_segment is the path segment for `D`. We return a type and a def for
1563 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
1564 // parameter or `Self`.
1565 pub fn associated_path_to_ty(
1567 hir_ref_id: hir::HirId,
1571 assoc_segment: &hir::PathSegment<'_>,
1572 permit_variants: bool,
1573 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> {
1574 let tcx = self.tcx();
1575 let assoc_ident = assoc_segment.ident;
1577 debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
1579 // Check if we have an enum variant.
1580 let mut variant_resolution = None;
1581 if let ty::Adt(adt_def, _) = qself_ty.kind() {
1582 if adt_def.is_enum() {
1583 let variant_def = adt_def
1586 .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did));
1587 if let Some(variant_def) = variant_def {
1588 if permit_variants {
1589 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span);
1590 self.prohibit_generics(slice::from_ref(assoc_segment));
1591 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
1593 variant_resolution = Some(variant_def.def_id);
1599 // Find the type of the associated item, and the trait where the associated
1600 // item is declared.
1601 let bound = match (&qself_ty.kind(), qself_res) {
1602 (_, Res::SelfTy(Some(_), Some((impl_def_id, _)))) => {
1603 // `Self` in an impl of a trait -- we have a concrete self type and a
1605 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
1606 Some(trait_ref) => trait_ref,
1608 // A cycle error occurred, most likely.
1609 return Err(ErrorReported);
1613 self.one_bound_for_assoc_type(
1614 || traits::supertraits(tcx, ty::Binder::bind(trait_ref)),
1615 || "Self".to_string(),
1623 Res::SelfTy(Some(param_did), None) | Res::Def(DefKind::TyParam, param_did),
1624 ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?,
1626 if variant_resolution.is_some() {
1627 // Variant in type position
1628 let msg = format!("expected type, found variant `{}`", assoc_ident);
1629 tcx.sess.span_err(span, &msg);
1630 } else if qself_ty.is_enum() {
1631 let mut err = struct_span_err!(
1635 "no variant named `{}` found for enum `{}`",
1640 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
1641 if let Some(suggested_name) = find_best_match_for_name(
1645 .map(|variant| variant.ident.name)
1646 .collect::<Vec<Symbol>>(),
1650 err.span_suggestion(
1652 "there is a variant with a similar name",
1653 suggested_name.to_string(),
1654 Applicability::MaybeIncorrect,
1659 format!("variant not found in `{}`", qself_ty),
1663 if let Some(sp) = tcx.hir().span_if_local(adt_def.did) {
1664 let sp = tcx.sess.source_map().guess_head_span(sp);
1665 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
1669 } else if !qself_ty.references_error() {
1670 // Don't print `TyErr` to the user.
1671 self.report_ambiguous_associated_type(
1673 &qself_ty.to_string(),
1678 return Err(ErrorReported);
1682 let trait_did = bound.def_id();
1683 let (assoc_ident, def_scope) =
1684 tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
1686 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1687 // of calling `filter_by_name_and_kind`.
1689 .associated_items(trait_did)
1690 .in_definition_order()
1692 i.kind.namespace() == Namespace::TypeNS
1693 && i.ident.normalize_to_macros_2_0() == assoc_ident
1695 .expect("missing associated type");
1697 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);
1698 let ty = self.normalize_ty(span, ty);
1700 let kind = DefKind::AssocTy;
1701 if !item.vis.is_accessible_from(def_scope, tcx) {
1702 let kind = kind.descr(item.def_id);
1703 let msg = format!("{} `{}` is private", kind, assoc_ident);
1705 .struct_span_err(span, &msg)
1706 .span_label(span, &format!("private {}", kind))
1709 tcx.check_stability(item.def_id, Some(hir_ref_id), span);
1711 if let Some(variant_def_id) = variant_resolution {
1712 tcx.struct_span_lint_hir(AMBIGUOUS_ASSOCIATED_ITEMS, hir_ref_id, span, |lint| {
1713 let mut err = lint.build("ambiguous associated item");
1714 let mut could_refer_to = |kind: DefKind, def_id, also| {
1715 let note_msg = format!(
1716 "`{}` could{} refer to the {} defined here",
1721 err.span_note(tcx.def_span(def_id), ¬e_msg);
1724 could_refer_to(DefKind::Variant, variant_def_id, "");
1725 could_refer_to(kind, item.def_id, " also");
1727 err.span_suggestion(
1729 "use fully-qualified syntax",
1730 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
1731 Applicability::MachineApplicable,
1737 Ok((ty, kind, item.def_id))
1743 opt_self_ty: Option<Ty<'tcx>>,
1745 trait_segment: &hir::PathSegment<'_>,
1746 item_segment: &hir::PathSegment<'_>,
1748 let tcx = self.tcx();
1750 let trait_def_id = tcx.parent(item_def_id).unwrap();
1752 debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
1754 let self_ty = if let Some(ty) = opt_self_ty {
1757 let path_str = tcx.def_path_str(trait_def_id);
1759 let def_id = self.item_def_id();
1761 debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
1763 let parent_def_id = def_id
1764 .and_then(|def_id| {
1765 def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
1767 .map(|hir_id| tcx.hir().get_parent_did(hir_id).to_def_id());
1769 debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
1771 // If the trait in segment is the same as the trait defining the item,
1772 // use the `<Self as ..>` syntax in the error.
1773 let is_part_of_self_trait_constraints = def_id == Some(trait_def_id);
1774 let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
1776 let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
1782 self.report_ambiguous_associated_type(
1786 item_segment.ident.name,
1788 return tcx.ty_error();
1791 debug!("qpath_to_ty: self_type={:?}", self_ty);
1793 let trait_ref = self.ast_path_to_mono_trait_ref(span, trait_def_id, self_ty, trait_segment);
1795 let item_substs = self.create_substs_for_associated_item(
1803 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1805 self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
1808 pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment<'a>>>(
1812 let mut has_err = false;
1813 for segment in segments {
1814 let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
1815 for arg in segment.args().args {
1816 let (span, kind) = match arg {
1817 hir::GenericArg::Lifetime(lt) => {
1823 (lt.span, "lifetime")
1825 hir::GenericArg::Type(ty) => {
1833 hir::GenericArg::Const(ct) => {
1842 let mut err = struct_span_err!(
1846 "{} arguments are not allowed for this type",
1849 err.span_label(span, format!("{} argument not allowed", kind));
1851 if err_for_lt && err_for_ty && err_for_ct {
1856 // Only emit the first error to avoid overloading the user with error messages.
1857 if let [binding, ..] = segment.args().bindings {
1859 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
1865 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
1866 pub fn def_ids_for_value_path_segments(
1868 segments: &[hir::PathSegment<'_>],
1869 self_ty: Option<Ty<'tcx>>,
1873 // We need to extract the type parameters supplied by the user in
1874 // the path `path`. Due to the current setup, this is a bit of a
1875 // tricky-process; the problem is that resolve only tells us the
1876 // end-point of the path resolution, and not the intermediate steps.
1877 // Luckily, we can (at least for now) deduce the intermediate steps
1878 // just from the end-point.
1880 // There are basically five cases to consider:
1882 // 1. Reference to a constructor of a struct:
1884 // struct Foo<T>(...)
1886 // In this case, the parameters are declared in the type space.
1888 // 2. Reference to a constructor of an enum variant:
1890 // enum E<T> { Foo(...) }
1892 // In this case, the parameters are defined in the type space,
1893 // but may be specified either on the type or the variant.
1895 // 3. Reference to a fn item or a free constant:
1899 // In this case, the path will again always have the form
1900 // `a::b::foo::<T>` where only the final segment should have
1901 // type parameters. However, in this case, those parameters are
1902 // declared on a value, and hence are in the `FnSpace`.
1904 // 4. Reference to a method or an associated constant:
1906 // impl<A> SomeStruct<A> {
1910 // Here we can have a path like
1911 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
1912 // may appear in two places. The penultimate segment,
1913 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
1914 // final segment, `foo::<B>` contains parameters in fn space.
1916 // The first step then is to categorize the segments appropriately.
1918 let tcx = self.tcx();
1920 assert!(!segments.is_empty());
1921 let last = segments.len() - 1;
1923 let mut path_segs = vec![];
1926 // Case 1. Reference to a struct constructor.
1927 DefKind::Ctor(CtorOf::Struct, ..) => {
1928 // Everything but the final segment should have no
1929 // parameters at all.
1930 let generics = tcx.generics_of(def_id);
1931 // Variant and struct constructors use the
1932 // generics of their parent type definition.
1933 let generics_def_id = generics.parent.unwrap_or(def_id);
1934 path_segs.push(PathSeg(generics_def_id, last));
1937 // Case 2. Reference to a variant constructor.
1938 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
1939 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
1940 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
1941 debug_assert!(adt_def.is_enum());
1943 } else if last >= 1 && segments[last - 1].args.is_some() {
1944 // Everything but the penultimate segment should have no
1945 // parameters at all.
1946 let mut def_id = def_id;
1948 // `DefKind::Ctor` -> `DefKind::Variant`
1949 if let DefKind::Ctor(..) = kind {
1950 def_id = tcx.parent(def_id).unwrap()
1953 // `DefKind::Variant` -> `DefKind::Enum`
1954 let enum_def_id = tcx.parent(def_id).unwrap();
1955 (enum_def_id, last - 1)
1957 // FIXME: lint here recommending `Enum::<...>::Variant` form
1958 // instead of `Enum::Variant::<...>` form.
1960 // Everything but the final segment should have no
1961 // parameters at all.
1962 let generics = tcx.generics_of(def_id);
1963 // Variant and struct constructors use the
1964 // generics of their parent type definition.
1965 (generics.parent.unwrap_or(def_id), last)
1967 path_segs.push(PathSeg(generics_def_id, index));
1970 // Case 3. Reference to a top-level value.
1971 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static => {
1972 path_segs.push(PathSeg(def_id, last));
1975 // Case 4. Reference to a method or associated const.
1976 DefKind::AssocFn | DefKind::AssocConst => {
1977 if segments.len() >= 2 {
1978 let generics = tcx.generics_of(def_id);
1979 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
1981 path_segs.push(PathSeg(def_id, last));
1984 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
1987 debug!("path_segs = {:?}", path_segs);
1992 // Check a type `Path` and convert it to a `Ty`.
1995 opt_self_ty: Option<Ty<'tcx>>,
1996 path: &hir::Path<'_>,
1997 permit_variants: bool,
1999 let tcx = self.tcx();
2002 "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2003 path.res, opt_self_ty, path.segments
2006 let span = path.span;
2008 Res::Def(DefKind::OpaqueTy, did) => {
2009 // Check for desugared `impl Trait`.
2010 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2011 let item_segment = path.segments.split_last().unwrap();
2012 self.prohibit_generics(item_segment.1);
2013 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2014 self.normalize_ty(span, tcx.mk_opaque(did, substs))
2021 | DefKind::ForeignTy,
2024 assert_eq!(opt_self_ty, None);
2025 self.prohibit_generics(path.segments.split_last().unwrap().1);
2026 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2028 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2029 // Convert "variant type" as if it were a real type.
2030 // The resulting `Ty` is type of the variant's enum for now.
2031 assert_eq!(opt_self_ty, None);
2034 self.def_ids_for_value_path_segments(&path.segments, None, kind, def_id);
2035 let generic_segs: FxHashSet<_> =
2036 path_segs.iter().map(|PathSeg(_, index)| index).collect();
2037 self.prohibit_generics(path.segments.iter().enumerate().filter_map(
2039 if !generic_segs.contains(&index) { Some(seg) } else { None }
2043 let PathSeg(def_id, index) = path_segs.last().unwrap();
2044 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2046 Res::Def(DefKind::TyParam, def_id) => {
2047 assert_eq!(opt_self_ty, None);
2048 self.prohibit_generics(path.segments);
2050 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
2051 let item_id = tcx.hir().get_parent_node(hir_id);
2052 let item_def_id = tcx.hir().local_def_id(item_id);
2053 let generics = tcx.generics_of(item_def_id);
2054 let index = generics.param_def_id_to_index[&def_id];
2055 tcx.mk_ty_param(index, tcx.hir().name(hir_id))
2057 Res::SelfTy(Some(_), None) => {
2058 // `Self` in trait or type alias.
2059 assert_eq!(opt_self_ty, None);
2060 self.prohibit_generics(path.segments);
2061 tcx.types.self_param
2063 Res::SelfTy(_, Some((def_id, forbid_generic))) => {
2064 // `Self` in impl (we know the concrete type).
2065 assert_eq!(opt_self_ty, None);
2066 self.prohibit_generics(path.segments);
2067 // Try to evaluate any array length constants.
2068 let normalized_ty = self.normalize_ty(span, tcx.at(span).type_of(def_id));
2069 if forbid_generic && normalized_ty.needs_subst() {
2070 let mut err = tcx.sess.struct_span_err(
2072 "generic `Self` types are currently not permitted in anonymous constants",
2074 if let Some(hir::Node::Item(&hir::Item {
2075 kind: hir::ItemKind::Impl(ref impl_),
2077 })) = tcx.hir().get_if_local(def_id)
2079 err.span_note(impl_.self_ty.span, "not a concrete type");
2087 Res::Def(DefKind::AssocTy, def_id) => {
2088 debug_assert!(path.segments.len() >= 2);
2089 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
2094 &path.segments[path.segments.len() - 2],
2095 path.segments.last().unwrap(),
2098 Res::PrimTy(prim_ty) => {
2099 assert_eq!(opt_self_ty, None);
2100 self.prohibit_generics(path.segments);
2102 hir::PrimTy::Bool => tcx.types.bool,
2103 hir::PrimTy::Char => tcx.types.char,
2104 hir::PrimTy::Int(it) => tcx.mk_mach_int(ty::int_ty(it)),
2105 hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(ty::uint_ty(uit)),
2106 hir::PrimTy::Float(ft) => tcx.mk_mach_float(ty::float_ty(ft)),
2107 hir::PrimTy::Str => tcx.types.str_,
2111 self.set_tainted_by_errors();
2112 self.tcx().ty_error()
2114 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2118 /// Parses the programmer's textual representation of a type into our
2119 /// internal notion of a type.
2120 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2121 self.ast_ty_to_ty_inner(ast_ty, false)
2124 /// Turns a `hir::Ty` into a `Ty`. For diagnostics' purposes we keep track of whether trait
2125 /// objects are borrowed like `&dyn Trait` to avoid emitting redundant errors.
2126 fn ast_ty_to_ty_inner(&self, ast_ty: &hir::Ty<'_>, borrowed: bool) -> Ty<'tcx> {
2127 debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})", ast_ty.hir_id, ast_ty, ast_ty.kind);
2129 let tcx = self.tcx();
2131 let result_ty = match ast_ty.kind {
2132 hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(&ty)),
2133 hir::TyKind::Ptr(ref mt) => {
2134 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(&mt.ty), mutbl: mt.mutbl })
2136 hir::TyKind::Rptr(ref region, ref mt) => {
2137 let r = self.ast_region_to_region(region, None);
2138 debug!("ast_ty_to_ty: r={:?}", r);
2139 let t = self.ast_ty_to_ty_inner(&mt.ty, true);
2140 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2142 hir::TyKind::Never => tcx.types.never,
2143 hir::TyKind::Tup(ref fields) => {
2144 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
2146 hir::TyKind::BareFn(ref bf) => {
2147 require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
2148 tcx.mk_fn_ptr(self.ty_of_fn(
2152 &hir::Generics::empty(),
2156 hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
2157 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime, borrowed)
2159 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2160 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
2161 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2162 self.res_to_ty(opt_self_ty, path, false)
2164 hir::TyKind::OpaqueDef(item_id, ref lifetimes) => {
2165 let opaque_ty = tcx.hir().expect_item(item_id.id);
2166 let def_id = tcx.hir().local_def_id(item_id.id).to_def_id();
2168 match opaque_ty.kind {
2169 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => {
2170 self.impl_trait_ty_to_ty(def_id, lifetimes, impl_trait_fn.is_some())
2172 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
2175 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2176 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
2177 let ty = self.ast_ty_to_ty(qself);
2179 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.kind {
2184 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2185 .map(|(ty, _, _)| ty)
2186 .unwrap_or_else(|_| tcx.ty_error())
2188 hir::TyKind::Path(hir::QPath::LangItem(lang_item, span)) => {
2189 let def_id = tcx.require_lang_item(lang_item, Some(span));
2190 let (substs, _, _) = self.create_substs_for_ast_path(
2194 &hir::PathSegment::invalid(),
2195 &GenericArgs::none(),
2199 self.normalize_ty(span, tcx.at(span).type_of(def_id).subst(tcx, substs))
2201 hir::TyKind::Array(ref ty, ref length) => {
2202 let length_def_id = tcx.hir().local_def_id(length.hir_id);
2203 let length = ty::Const::from_anon_const(tcx, length_def_id);
2204 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
2205 self.normalize_ty(ast_ty.span, array_ty)
2207 hir::TyKind::Typeof(ref _e) => {
2208 tcx.sess.emit_err(TypeofReservedKeywordUsed { span: ast_ty.span });
2211 hir::TyKind::Infer => {
2212 // Infer also appears as the type of arguments or return
2213 // values in a ExprKind::Closure, or as
2214 // the type of local variables. Both of these cases are
2215 // handled specially and will not descend into this routine.
2216 self.ty_infer(None, ast_ty.span)
2218 hir::TyKind::Err => tcx.ty_error(),
2221 debug!("ast_ty_to_ty: result_ty={:?}", result_ty);
2223 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2227 pub fn impl_trait_ty_to_ty(
2230 lifetimes: &[hir::GenericArg<'_>],
2231 replace_parent_lifetimes: bool,
2233 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2234 let tcx = self.tcx();
2236 let generics = tcx.generics_of(def_id);
2238 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2239 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2240 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2241 // Our own parameters are the resolved lifetimes.
2243 GenericParamDefKind::Lifetime => {
2244 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2245 self.ast_region_to_region(lifetime, None).into()
2254 // For RPIT (return position impl trait), only lifetimes
2255 // mentioned in the impl Trait predicate are captured by
2256 // the opaque type, so the lifetime parameters from the
2257 // parent item need to be replaced with `'static`.
2259 // For `impl Trait` in the types of statics, constants,
2260 // locals and type aliases. These capture all parent
2261 // lifetimes, so they can use their identity subst.
2262 GenericParamDefKind::Lifetime if replace_parent_lifetimes => {
2263 tcx.lifetimes.re_static.into()
2265 _ => tcx.mk_param_from_def(param),
2269 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2271 let ty = tcx.mk_opaque(def_id, substs);
2272 debug!("impl_trait_ty_to_ty: {}", ty);
2276 pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2278 hir::TyKind::Infer if expected_ty.is_some() => {
2279 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2280 expected_ty.unwrap()
2282 _ => self.ast_ty_to_ty(ty),
2288 unsafety: hir::Unsafety,
2290 decl: &hir::FnDecl<'_>,
2291 generics: &hir::Generics<'_>,
2292 ident_span: Option<Span>,
2293 ) -> ty::PolyFnSig<'tcx> {
2296 let tcx = self.tcx();
2298 // We proactively collect all the inferred type params to emit a single error per fn def.
2299 let mut visitor = PlaceholderHirTyCollector::default();
2300 for ty in decl.inputs {
2301 visitor.visit_ty(ty);
2303 walk_generics(&mut visitor, generics);
2305 let input_tys = decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
2306 let output_ty = match decl.output {
2307 hir::FnRetTy::Return(ref output) => {
2308 visitor.visit_ty(output);
2309 self.ast_ty_to_ty(output)
2311 hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(),
2314 debug!("ty_of_fn: output_ty={:?}", output_ty);
2317 ty::Binder::bind(tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, unsafety, abi));
2319 if !self.allow_ty_infer() {
2320 // We always collect the spans for placeholder types when evaluating `fn`s, but we
2321 // only want to emit an error complaining about them if infer types (`_`) are not
2322 // allowed. `allow_ty_infer` gates this behavior. We check for the presence of
2323 // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`.
2324 crate::collect::placeholder_type_error(
2326 ident_span.map(|sp| sp.shrink_to_hi()),
2327 &generics.params[..],
2333 // Find any late-bound regions declared in return type that do
2334 // not appear in the arguments. These are not well-formed.
2337 // for<'a> fn() -> &'a str <-- 'a is bad
2338 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2339 let inputs = bare_fn_ty.inputs();
2340 let late_bound_in_args =
2341 tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
2342 let output = bare_fn_ty.output();
2343 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2345 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
2350 "return type references {}, which is not constrained by the fn input types",
2358 fn validate_late_bound_regions(
2360 constrained_regions: FxHashSet<ty::BoundRegionKind>,
2361 referenced_regions: FxHashSet<ty::BoundRegionKind>,
2362 generate_err: impl Fn(&str) -> rustc_errors::DiagnosticBuilder<'tcx>,
2364 for br in referenced_regions.difference(&constrained_regions) {
2365 let br_name = match *br {
2366 ty::BrNamed(_, name) => format!("lifetime `{}`", name),
2367 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
2370 let mut err = generate_err(&br_name);
2372 if let ty::BrAnon(_) = *br {
2373 // The only way for an anonymous lifetime to wind up
2374 // in the return type but **also** be unconstrained is
2375 // if it only appears in "associated types" in the
2376 // input. See #47511 and #62200 for examples. In this case,
2377 // though we can easily give a hint that ought to be
2380 "lifetimes appearing in an associated type are not considered constrained",
2388 /// Given the bounds on an object, determines what single region bound (if any) we can
2389 /// use to summarize this type. The basic idea is that we will use the bound the user
2390 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2391 /// for region bounds. It may be that we can derive no bound at all, in which case
2392 /// we return `None`.
2393 fn compute_object_lifetime_bound(
2396 existential_predicates: &'tcx ty::List<ty::Binder<ty::ExistentialPredicate<'tcx>>>,
2397 ) -> Option<ty::Region<'tcx>> // if None, use the default
2399 let tcx = self.tcx();
2401 debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
2403 // No explicit region bound specified. Therefore, examine trait
2404 // bounds and see if we can derive region bounds from those.
2405 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
2407 // If there are no derived region bounds, then report back that we
2408 // can find no region bound. The caller will use the default.
2409 if derived_region_bounds.is_empty() {
2413 // If any of the derived region bounds are 'static, that is always
2415 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
2416 return Some(tcx.lifetimes.re_static);
2419 // Determine whether there is exactly one unique region in the set
2420 // of derived region bounds. If so, use that. Otherwise, report an
2422 let r = derived_region_bounds[0];
2423 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2424 tcx.sess.emit_err(AmbiguousLifetimeBound { span });