]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_hir_analysis/src/astconv/mod.rs
New upstream version 1.67.1+dfsg1
[rustc.git] / compiler / rustc_hir_analysis / src / astconv / mod.rs
CommitLineData
0731742a
XL
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`.
1a4d82fc 4
3dfed10e
XL
5mod errors;
6mod generics;
dfeec247 7
3dfed10e 8use crate::bounds::Bounds;
5099ac24 9use crate::collect::HirPlaceholderCollector;
1b1a35ee
XL
10use crate::errors::{
11 AmbiguousLifetimeBound, MultipleRelaxedDefaultBounds, TraitObjectDeclaredWithNoTraits,
12 TypeofReservedKeywordUsed, ValueOfAssociatedStructAlreadySpecified,
13};
9fa01778 14use crate::middle::resolve_lifetime as rl;
dfeec247 15use crate::require_c_abi_if_c_variadic;
a2a8927a 16use rustc_ast::TraitObjectSyntax;
dfeec247 17use rustc_data_structures::fx::{FxHashMap, FxHashSet};
5e7ed085 18use rustc_errors::{
f2b60f7d
FG
19 struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, FatalError,
20 MultiSpan,
5e7ed085 21};
dfeec247 22use rustc_hir as hir;
74b04a01 23use rustc_hir::def::{CtorOf, DefKind, Namespace, Res};
f9f354fc 24use rustc_hir::def_id::{DefId, LocalDefId};
ba9703b0 25use rustc_hir::intravisit::{walk_generics, Visitor as _};
923072b8
FG
26use rustc_hir::{GenericArg, GenericArgs, OpaqueTyOrigin};
27use rustc_middle::middle::stability::AllowUnstable;
2b03887a 28use rustc_middle::ty::subst::{self, GenericArgKind, InternalSubsts, SubstsRef};
f2b60f7d 29use rustc_middle::ty::DynKind;
3dfed10e 30use rustc_middle::ty::GenericParamDefKind;
923072b8 31use rustc_middle::ty::{
064997fb 32 self, Const, DefIdTree, EarlyBinder, IsSuggestable, Ty, TyCtxt, TypeVisitable,
923072b8 33};
a2a8927a
XL
34use rustc_session::lint::builtin::{AMBIGUOUS_ASSOCIATED_ITEMS, BARE_TRAIT_OBJECTS};
35use rustc_span::edition::Edition;
fc512014 36use rustc_span::lev_distance::find_best_match_for_name;
923072b8 37use rustc_span::symbol::{kw, Ident, Symbol};
2b03887a 38use rustc_span::{sym, Span};
83c7162d 39use rustc_target::spec::abi;
ba9703b0
XL
40use rustc_trait_selection::traits;
41use rustc_trait_selection::traits::astconv_object_safety_violations;
064997fb
FG
42use rustc_trait_selection::traits::error_reporting::{
43 report_object_safety_error, suggestions::NextTypeParamName,
44};
ba9703b0 45use rustc_trait_selection::traits::wf::object_region_bounds;
0731742a 46
f2b60f7d 47use smallvec::{smallvec, SmallVec};
0731742a 48use std::collections::BTreeSet;
0731742a
XL
49use std::slice;
50
0731742a
XL
51#[derive(Debug)]
52pub struct PathSeg(pub DefId, pub usize);
e9174d1e 53
dc9dc135
XL
54pub trait AstConv<'tcx> {
55 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
1a4d82fc 56
487cf647 57 fn item_def_id(&self) -> DefId;
60c5eb7d 58
6a06907d
XL
59 /// Returns predicates in scope of the form `X: Foo<T>`, where `X`
60 /// is a type parameter `X` with the given id `def_id` and T
61 /// matches `assoc_name`. This is a subset of the full set of
62 /// predicates.
416331ca
XL
63 ///
64 /// This is used for one specific purpose: resolving "short-hand"
65 /// associated type references like `T::Item`. In principle, we
66 /// would do that by first getting the full set of predicates in
67 /// scope and then filtering down to find those that apply to `T`,
68 /// but this can lead to cycle errors. The problem is that we have
69 /// to do this resolution *in order to create the predicates in
70 /// the first place*. Hence, we have this "special pass".
6a06907d
XL
71 fn get_type_parameter_bounds(
72 &self,
73 span: Span,
74 def_id: DefId,
75 assoc_name: Ident,
76 ) -> ty::GenericPredicates<'tcx>;
c34b1796 77
dc9dc135 78 /// Returns the lifetime to use when a lifetime is omitted (and not elided).
dfeec247
XL
79 fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span)
80 -> Option<ty::Region<'tcx>>;
32a655c1 81
dc9dc135
XL
82 /// Returns the type to use when a type is omitted.
83 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
9e0c209e 84
dfeec247
XL
85 /// Returns `true` if `_` is allowed in type signatures in the current context.
86 fn allow_ty_infer(&self) -> bool;
87
dc9dc135
XL
88 /// Returns the const to use when a const is omitted.
89 fn ct_infer(
90 &self,
91 ty: Ty<'tcx>,
92 param: Option<&ty::GenericParamDef>,
93 span: Span,
5099ac24 94 ) -> Const<'tcx>;
1a4d82fc
JJ
95
96 /// Projecting an associated type from a (potentially)
97 /// higher-ranked trait reference is more complicated, because of
98 /// the possibility of late-bound regions appearing in the
99 /// associated type binding. This is not legal in function
100 /// signatures for that reason. In a function body, we can always
101 /// handle it because we can use inference variables to remove the
102 /// late-bound regions.
dfeec247
XL
103 fn projected_ty_from_poly_trait_ref(
104 &self,
105 span: Span,
106 item_def_id: DefId,
107 item_segment: &hir::PathSegment<'_>,
108 poly_trait_ref: ty::PolyTraitRef<'tcx>,
109 ) -> Ty<'tcx>;
1a4d82fc 110
8bb4bdeb 111 /// Normalize an associated type coming from the user.
487cf647
FG
112 ///
113 /// This should only be used by astconv. Use `FnCtxt::normalize`
114 /// or `ObligationCtxt::normalize` in downstream crates.
8bb4bdeb 115 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
a7813a04
XL
116
117 /// Invoked when we encounter an error from some prior pass
0731742a 118 /// (e.g., resolve) that is translated into a ty-error. This is
a7813a04
XL
119 /// used to help suppress derived errors typeck might otherwise
120 /// report.
487cf647 121 fn set_tainted_by_errors(&self, e: ErrorGuaranteed);
ea8adc8c
XL
122
123 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
a7813a04
XL
124}
125
5869c6ff 126#[derive(Debug)]
dc9dc135 127struct ConvertedBinding<'a, 'tcx> {
17df50a5 128 hir_id: hir::HirId,
f9f354fc 129 item_name: Ident,
dc9dc135 130 kind: ConvertedBindingKind<'a, 'tcx>,
5869c6ff 131 gen_args: &'a GenericArgs<'a>,
a7813a04 132 span: Span,
1a4d82fc
JJ
133}
134
5869c6ff 135#[derive(Debug)]
dc9dc135 136enum ConvertedBindingKind<'a, 'tcx> {
5099ac24 137 Equality(ty::Term<'tcx>),
dfeec247 138 Constraint(&'a [hir::GenericBound<'a>]),
dc9dc135
XL
139}
140
f9f354fc
XL
141/// New-typed boolean indicating whether explicit late-bound lifetimes
142/// are present in a set of generic arguments.
143///
144/// For example if we have some method `fn f<'a>(&'a self)` implemented
145/// for some type `T`, although `f` is generic in the lifetime `'a`, `'a`
146/// is late-bound so should not be provided explicitly. Thus, if `f` is
147/// instantiated with some generic arguments providing `'a` explicitly,
148/// we taint those arguments with `ExplicitLateBound::Yes` so that we
149/// can provide an appropriate diagnostic later.
f2b60f7d 150#[derive(Copy, Clone, PartialEq, Debug)]
f9f354fc
XL
151pub enum ExplicitLateBound {
152 Yes,
153 No,
154}
155
5869c6ff
XL
156#[derive(Copy, Clone, PartialEq)]
157pub enum IsMethodCall {
158 Yes,
159 No,
160}
161
3dfed10e
XL
162/// Denotes the "position" of a generic argument, indicating if it is a generic type,
163/// generic function or generic method call.
f9f354fc 164#[derive(Copy, Clone, PartialEq)]
3dfed10e 165pub(crate) enum GenericArgPosition {
b7449926 166 Type,
0731742a 167 Value, // e.g., functions
b7449926 168 MethodCall,
94b46f34
XL
169}
170
74b04a01
XL
171/// A marker denoting that the generic arguments that were
172/// provided did not match the respective generic parameters.
f2b60f7d 173#[derive(Clone, Default, Debug)]
74b04a01
XL
174pub struct GenericArgCountMismatch {
175 /// Indicates whether a fatal error was reported (`Some`), or just a lint (`None`).
5e7ed085 176 pub reported: Option<ErrorGuaranteed>,
74b04a01
XL
177 /// A list of spans of arguments provided that were not valid.
178 pub invalid_args: Vec<Span>,
179}
180
f9f354fc
XL
181/// Decorates the result of a generic argument count mismatch
182/// check with whether explicit late bounds were provided.
f2b60f7d 183#[derive(Clone, Debug)]
f9f354fc
XL
184pub struct GenericArgCountResult {
185 pub explicit_late_bound: ExplicitLateBound,
186 pub correct: Result<(), GenericArgCountMismatch>,
187}
188
fc512014
XL
189pub trait CreateSubstsForGenericArgsCtxt<'a, 'tcx> {
190 fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'a>>, bool);
191
192 fn provided_kind(
193 &mut self,
194 param: &ty::GenericParamDef,
195 arg: &GenericArg<'_>,
196 ) -> subst::GenericArg<'tcx>;
197
198 fn inferred_kind(
199 &mut self,
200 substs: Option<&[subst::GenericArg<'tcx>]>,
201 param: &ty::GenericParamDef,
202 infer_args: bool,
203 ) -> subst::GenericArg<'tcx>;
204}
205
dc9dc135 206impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
f2b60f7d 207 #[instrument(level = "debug", skip(self), ret)]
dfeec247
XL
208 pub fn ast_region_to_region(
209 &self,
32a655c1 210 lifetime: &hir::Lifetime,
dfeec247
XL
211 def: Option<&ty::GenericParamDef>,
212 ) -> ty::Region<'tcx> {
32a655c1 213 let tcx = self.tcx();
3dfed10e 214 let lifetime_name = |def_id| tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id));
ea8adc8c 215
f2b60f7d 216 match tcx.named_region(lifetime.hir_id) {
dfeec247 217 Some(rl::Region::Static) => tcx.lifetimes.re_static,
32a655c1 218
5e7ed085 219 Some(rl::Region::LateBound(debruijn, index, def_id)) => {
cdc7bbd5
XL
220 let name = lifetime_name(def_id.expect_local());
221 let br = ty::BoundRegion {
222 var: ty::BoundVar::from_u32(index),
223 kind: ty::BrNamed(def_id, name),
224 };
fc512014 225 tcx.mk_region(ty::ReLateBound(debruijn, br))
32a655c1
SL
226 }
227
f2b60f7d
FG
228 Some(rl::Region::EarlyBound(def_id)) => {
229 let name = tcx.hir().ty_param_name(def_id.expect_local());
230 let item_def_id = tcx.hir().ty_param_owner(def_id.expect_local());
231 let generics = tcx.generics_of(item_def_id);
232 let index = generics.param_def_id_to_index[&def_id];
233 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, index, name }))
32a655c1
SL
234 }
235
ea8adc8c 236 Some(rl::Region::Free(scope, id)) => {
f9f354fc 237 let name = lifetime_name(id.expect_local());
32a655c1 238 tcx.mk_region(ty::ReFree(ty::FreeRegion {
7cac9316 239 scope,
dfeec247 240 bound_region: ty::BrNamed(id, name),
32a655c1 241 }))
5bcae85e 242
0bf4aa26 243 // (*) -- not late-bound, won't change
32a655c1 244 }
5bcae85e 245
32a655c1 246 None => {
487cf647 247 self.re_infer(def, lifetime.ident.span).unwrap_or_else(|| {
cdc7bbd5
XL
248 debug!(?lifetime, "unelided lifetime in signature");
249
dfeec247
XL
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.
487cf647 254 tcx.sess.delay_span_bug(lifetime.ident.span, "unelided lifetime in signature");
dfeec247
XL
255
256 // Supply some dummy value. We don't have an
257 // `re_error`, annoyingly, so use `'static`.
258 tcx.lifetimes.re_static
259 })
32a655c1 260 }
f2b60f7d 261 }
a7813a04 262 }
1a4d82fc 263
a7813a04
XL
264 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
265 /// returns an appropriate set of substitutions for this particular reference to `I`.
dfeec247
XL
266 pub fn ast_path_substs_for_ty(
267 &self,
a7813a04 268 span: Span,
9e0c209e 269 def_id: DefId,
dfeec247
XL
270 item_segment: &hir::PathSegment<'_>,
271 ) -> SubstsRef<'tcx> {
cdc7bbd5 272 let (substs, _) = self.create_substs_for_ast_path(
dc9dc135
XL
273 span,
274 def_id,
dfeec247 275 &[],
5869c6ff
XL
276 item_segment,
277 item_segment.args(),
dc9dc135
XL
278 item_segment.infer_args,
279 None,
487cf647 280 ty::BoundConstness::NotConst,
dc9dc135 281 );
2b03887a 282 if let Some(b) = item_segment.args().bindings.first() {
f9f354fc
XL
283 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
284 }
1a4d82fc 285
9e0c209e 286 substs
a7813a04 287 }
c34b1796 288
48663c56 289 /// Given the type/lifetime/const arguments provided to some path (along with
dc9dc135 290 /// an implicit `Self`, if this is a trait reference), returns the complete
9e0c209e 291 /// set of substitutions. This may involve applying defaulted type parameters.
5e7ed085 292 /// Constraints on associated types are created from `create_assoc_bindings_for_generic_args`.
dc9dc135
XL
293 ///
294 /// Example:
295 ///
04454e1e
FG
296 /// ```ignore (illustrative)
297 /// T: std::ops::Index<usize, Output = u32>
298 /// // ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4
dc9dc135
XL
299 /// ```
300 ///
301 /// 1. The `self_ty` here would refer to the type `T`.
302 /// 2. The path in question is the path to the trait `std::ops::Index`,
303 /// which will have been resolved to a `def_id`
304 /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
305 /// parameters are returned in the `SubstsRef`, the associated type bindings like
5099ac24 306 /// `Output = u32` are returned from `create_assoc_bindings_for_generic_args`.
9e0c209e
SL
307 ///
308 /// Note that the type listing given here is *exactly* what the user provided.
dfeec247
XL
309 ///
310 /// For (generic) associated types
311 ///
04454e1e 312 /// ```ignore (illustrative)
dfeec247
XL
313 /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
314 /// ```
315 ///
316 /// We have the parent substs are the substs for the parent trait:
317 /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
318 /// type itself: `['a]`. The returned `SubstsRef` concatenates these two
319 /// lists: `[Vec<u8>, u8, 'a]`.
f2b60f7d 320 #[instrument(level = "debug", skip(self, span), ret)]
dfeec247
XL
321 fn create_substs_for_ast_path<'a>(
322 &self,
a7813a04 323 span: Span,
9e0c209e 324 def_id: DefId,
dfeec247 325 parent_substs: &[subst::GenericArg<'tcx>],
5869c6ff 326 seg: &hir::PathSegment<'_>,
dfeec247 327 generic_args: &'a hir::GenericArgs<'_>,
dc9dc135 328 infer_args: bool,
dfeec247 329 self_ty: Option<Ty<'tcx>>,
487cf647 330 constness: ty::BoundConstness,
cdc7bbd5 331 ) -> (SubstsRef<'tcx>, GenericArgCountResult) {
a7813a04
XL
332 // If the type is parameterized by this region, then replace this
333 // region with the current anon region binding (in other words,
334 // whatever & would get replaced with).
94b46f34 335
b7449926 336 let tcx = self.tcx();
5869c6ff
XL
337 let generics = tcx.generics_of(def_id);
338 debug!("generics: {:?}", generics);
85aaf69f 339
5869c6ff
XL
340 if generics.has_self {
341 if generics.parent.is_some() {
dfeec247
XL
342 // The parent is a trait so it should have at least one subst
343 // for the `Self` type.
344 assert!(!parent_substs.is_empty())
345 } else {
346 // This item (presumably a trait) needs a self-type.
347 assert!(self_ty.is_some());
348 }
349 } else {
487cf647 350 assert!(self_ty.is_none());
dfeec247 351 }
a7813a04 352
f9f354fc 353 let arg_count = Self::check_generic_arg_count(
0731742a 354 tcx,
b7449926 355 span,
5869c6ff
XL
356 def_id,
357 seg,
c295e0f8
XL
358 generics,
359 generic_args,
b7449926 360 GenericArgPosition::Type,
dfeec247 361 self_ty.is_some(),
dc9dc135 362 infer_args,
b7449926 363 );
1a4d82fc 364
fc512014
XL
365 // Skip processing if type has no generic parameters.
366 // Traits always have `Self` as a generic parameter, which means they will not return early
367 // here and so associated type bindings will be handled regardless of whether there are any
368 // non-`Self` generic parameters.
c295e0f8 369 if generics.params.is_empty() {
2b03887a 370 return (tcx.intern_substs(parent_substs), arg_count);
fc512014
XL
371 }
372
fc512014
XL
373 struct SubstsForAstPathCtxt<'a, 'tcx> {
374 astconv: &'a (dyn AstConv<'tcx> + 'a),
375 def_id: DefId,
376 generic_args: &'a GenericArgs<'a>,
377 span: Span,
fc512014
XL
378 inferred_params: Vec<Span>,
379 infer_args: bool,
fc512014 380 }
9e0c209e 381
fc512014
XL
382 impl<'a, 'tcx> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for SubstsForAstPathCtxt<'a, 'tcx> {
383 fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'a>>, bool) {
384 if did == self.def_id {
385 (Some(self.generic_args), self.infer_args)
74b04a01
XL
386 } else {
387 // The last component of this tuple is unimportant.
388 (None, false)
389 }
fc512014
XL
390 }
391
392 fn provided_kind(
393 &mut self,
394 param: &ty::GenericParamDef,
395 arg: &GenericArg<'_>,
396 ) -> subst::GenericArg<'tcx> {
397 let tcx = self.astconv.tcx();
a2a8927a
XL
398
399 let mut handle_ty_args = |has_default, ty: &hir::Ty<'_>| {
400 if has_default {
401 tcx.check_optional_stability(
402 param.def_id,
f2b60f7d 403 Some(arg.hir_id()),
a2a8927a
XL
404 arg.span(),
405 None,
923072b8 406 AllowUnstable::No,
a2a8927a
XL
407 |_, _| {
408 // Default generic parameters may not be marked
409 // with stability attributes, i.e. when the
410 // default parameter was defined at the same time
411 // as the rest of the type. As such, we ignore missing
412 // stability attributes.
413 },
064997fb 414 );
a2a8927a
XL
415 }
416 if let (hir::TyKind::Infer, false) = (&ty.kind, self.astconv.allow_ty_infer()) {
417 self.inferred_params.push(ty.span);
418 tcx.ty_error().into()
419 } else {
420 self.astconv.ast_ty_to_ty(ty).into()
421 }
422 };
423
fc512014
XL
424 match (&param.kind, arg) {
425 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
c295e0f8 426 self.astconv.ast_region_to_region(lt, Some(param)).into()
fc512014
XL
427 }
428 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
a2a8927a
XL
429 handle_ty_args(has_default, ty)
430 }
431 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Infer(inf)) => {
432 handle_ty_args(has_default, &inf.to_ty())
fc512014 433 }
cdc7bbd5 434 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => {
fc512014
XL
435 ty::Const::from_opt_const_arg_anon_const(
436 tcx,
437 ty::WithOptConstParam {
487cf647 438 did: ct.value.def_id,
fc512014 439 const_param_did: Some(param.def_id),
1b1a35ee
XL
440 },
441 )
fc512014 442 .into()
1b1a35ee 443 }
a2a8927a
XL
444 (&GenericParamDefKind::Const { .. }, hir::GenericArg::Infer(inf)) => {
445 let ty = tcx.at(self.span).type_of(param.def_id);
94222f64 446 if self.astconv.allow_ty_infer() {
a2a8927a 447 self.astconv.ct_infer(ty, Some(param), inf.span).into()
94222f64
XL
448 } else {
449 self.inferred_params.push(inf.span);
a2a8927a 450 tcx.const_error(ty).into()
94222f64
XL
451 }
452 }
fc512014 453 _ => unreachable!(),
dfeec247 454 }
fc512014
XL
455 }
456
457 fn inferred_kind(
458 &mut self,
459 substs: Option<&[subst::GenericArg<'tcx>]>,
460 param: &ty::GenericParamDef,
461 infer_args: bool,
462 ) -> subst::GenericArg<'tcx> {
463 let tcx = self.astconv.tcx();
b7449926 464 match param.kind {
5099ac24
FG
465 GenericParamDefKind::Lifetime => self
466 .astconv
467 .re_infer(Some(param), self.span)
468 .unwrap_or_else(|| {
469 debug!(?param, "unelided lifetime in signature");
470
471 // This indicates an illegal lifetime in a non-assoc-trait position
472 tcx.sess.delay_span_bug(self.span, "unelided lifetime in signature");
473
474 // Supply some dummy value. We don't have an
475 // `re_error`, annoyingly, so use `'static`.
476 tcx.lifetimes.re_static
477 })
478 .into(),
b7449926 479 GenericParamDefKind::Type { has_default, .. } => {
dc9dc135 480 if !infer_args && has_default {
b7449926 481 // No type parameter provided, but a default exists.
f2b60f7d
FG
482 let substs = substs.unwrap();
483 if substs.iter().any(|arg| match arg.unpack() {
484 GenericArgKind::Type(ty) => ty.references_error(),
485 _ => false,
486 }) {
487 // Avoid ICE #86756 when type error recovery goes awry.
488 return tcx.ty_error().into();
b7449926 489 }
f2b60f7d
FG
490 self.astconv
491 .normalize_ty(
492 self.span,
493 EarlyBinder(tcx.at(self.span).type_of(param.def_id))
494 .subst(tcx, substs),
495 )
496 .into()
dc9dc135 497 } else if infer_args {
f2b60f7d 498 self.astconv.ty_infer(Some(param), self.span).into()
94b46f34 499 } else {
b7449926 500 // We've already errored above about the mismatch.
f035d41b 501 tcx.ty_error().into()
94b46f34 502 }
94b46f34 503 }
cdc7bbd5 504 GenericParamDefKind::Const { has_default } => {
fc512014 505 let ty = tcx.at(self.span).type_of(param.def_id);
487cf647
FG
506 if ty.references_error() {
507 return tcx.const_error(ty).into();
508 }
cdc7bbd5 509 if !infer_args && has_default {
064997fb 510 tcx.bound_const_param_default(param.def_id)
04454e1e 511 .subst(tcx, substs.unwrap())
cdc7bbd5 512 .into()
dc9dc135 513 } else {
cdc7bbd5
XL
514 if infer_args {
515 self.astconv.ct_infer(ty, Some(param), self.span).into()
516 } else {
517 // We've already errored above about the mismatch.
518 tcx.const_error(ty).into()
519 }
dc9dc135 520 }
532ac7d7 521 }
a7813a04 522 }
fc512014
XL
523 }
524 }
525
526 let mut substs_ctx = SubstsForAstPathCtxt {
527 astconv: self,
528 def_id,
529 span,
530 generic_args,
fc512014
XL
531 inferred_params: vec![],
532 infer_args,
fc512014
XL
533 };
534 let substs = Self::create_substs_for_generic_args(
535 tcx,
536 def_id,
537 parent_substs,
538 self_ty.is_some(),
539 self_ty,
cdc7bbd5 540 &arg_count,
fc512014 541 &mut substs_ctx,
b7449926 542 );
1a4d82fc 543
487cf647 544 if let ty::BoundConstness::ConstIfConst = constness
2b03887a
FG
545 && generics.has_self && !tcx.has_attr(def_id, sym::const_trait)
546 {
547 tcx.sess.emit_err(crate::errors::ConstBoundForNonConstTrait { span } );
548 }
549
cdc7bbd5
XL
550 (substs, arg_count)
551 }
552
553 fn create_assoc_bindings_for_generic_args<'a>(
554 &self,
555 generic_args: &'a hir::GenericArgs<'_>,
556 ) -> Vec<ConvertedBinding<'a, 'tcx>> {
dc9dc135
XL
557 // Convert associated-type bindings or constraints into a separate vector.
558 // Example: Given this:
559 //
560 // T: Iterator<Item = u32>
561 //
562 // The `T` is passed in as a self-type; the `Item = u32` is
563 // not a "type parameter" of the `Iterator` trait, but rather
564 // a restriction on `<T as Iterator>::Item`, so it is passed
565 // back separately.
dfeec247
XL
566 let assoc_bindings = generic_args
567 .bindings
568 .iter()
dc9dc135
XL
569 .map(|binding| {
570 let kind = match binding.kind {
5099ac24
FG
571 hir::TypeBindingKind::Equality { ref term } => match term {
572 hir::Term::Ty(ref ty) => {
573 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty).into())
574 }
575 hir::Term::Const(ref c) => {
487cf647 576 let c = Const::from_anon_const(self.tcx(), c.def_id);
5099ac24
FG
577 ConvertedBindingKind::Equality(c.into())
578 }
579 },
580 hir::TypeBindingKind::Constraint { ref bounds } => {
dfeec247
XL
581 ConvertedBindingKind::Constraint(bounds)
582 }
dc9dc135 583 };
5869c6ff 584 ConvertedBinding {
17df50a5 585 hir_id: binding.hir_id,
5869c6ff
XL
586 item_name: binding.ident,
587 kind,
588 gen_args: binding.gen_args,
589 span: binding.span,
590 }
dc9dc135
XL
591 })
592 .collect();
a7813a04 593
cdc7bbd5 594 assoc_bindings
e9174d1e 595 }
e9174d1e 596
2b03887a 597 pub fn create_substs_for_associated_item(
dfeec247 598 &self,
dfeec247
XL
599 span: Span,
600 item_def_id: DefId,
601 item_segment: &hir::PathSegment<'_>,
602 parent_substs: SubstsRef<'tcx>,
603 ) -> SubstsRef<'tcx> {
17df50a5
XL
604 debug!(
605 "create_substs_for_associated_item(span: {:?}, item_def_id: {:?}, item_segment: {:?}",
606 span, item_def_id, item_segment
607 );
2b03887a
FG
608 let (args, _) = self.create_substs_for_ast_path(
609 span,
610 item_def_id,
611 parent_substs,
612 item_segment,
613 item_segment.args(),
614 item_segment.infer_args,
615 None,
487cf647 616 ty::BoundConstness::NotConst,
2b03887a 617 );
f2b60f7d 618
2b03887a
FG
619 if let Some(b) = item_segment.args().bindings.first() {
620 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
dfeec247 621 }
2b03887a
FG
622
623 args
dfeec247
XL
624 }
625
a7813a04 626 /// Instantiates the path for the given trait reference, assuming that it's
dc9dc135 627 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
0531ce1d 628 /// The type _cannot_ be a type other than a trait type.
a7813a04 629 ///
9fa01778 630 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
a7813a04 631 /// are disallowed. Otherwise, they are pushed onto the vector given.
dfeec247
XL
632 pub fn instantiate_mono_trait_ref(
633 &self,
634 trait_ref: &hir::TraitRef<'_>,
635 self_ty: Ty<'tcx>,
2b03887a 636 constness: ty::BoundConstness,
dfeec247 637 ) -> ty::TraitRef<'tcx> {
923072b8 638 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1.iter(), |_| {});
7cac9316 639
dfeec247
XL
640 self.ast_path_to_mono_trait_ref(
641 trait_ref.path.span,
ba9703b0 642 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
dfeec247
XL
643 self_ty,
644 trait_ref.path.segments.last().unwrap(),
5099ac24 645 true,
487cf647 646 constness,
dfeec247 647 )
1a4d82fc 648 }
c34b1796 649
c295e0f8
XL
650 fn instantiate_poly_trait_ref_inner(
651 &self,
652 hir_id: hir::HirId,
653 span: Span,
654 binding_span: Option<Span>,
655 constness: ty::BoundConstness,
656 bounds: &mut Bounds<'tcx>,
657 speculative: bool,
658 trait_ref_span: Span,
659 trait_def_id: DefId,
660 trait_segment: &hir::PathSegment<'_>,
661 args: &GenericArgs<'_>,
662 infer_args: bool,
663 self_ty: Ty<'tcx>,
664 ) -> GenericArgCountResult {
665 let (substs, arg_count) = self.create_substs_for_ast_path(
666 trait_ref_span,
667 trait_def_id,
668 &[],
669 trait_segment,
670 args,
671 infer_args,
672 Some(self_ty),
487cf647 673 constness,
c295e0f8
XL
674 );
675
676 let tcx = self.tcx();
677 let bound_vars = tcx.late_bound_vars(hir_id);
678 debug!(?bound_vars);
679
680 let assoc_bindings = self.create_assoc_bindings_for_generic_args(args);
681
682 let poly_trait_ref =
683 ty::Binder::bind_with_vars(ty::TraitRef::new(trait_def_id, substs), bound_vars);
684
685 debug!(?poly_trait_ref, ?assoc_bindings);
686 bounds.trait_bounds.push((poly_trait_ref, span, constness));
687
688 let mut dup_bindings = FxHashMap::default();
689 for binding in &assoc_bindings {
690 // Specify type to assert that error was already reported in `Err` case.
5e7ed085 691 let _: Result<_, ErrorGuaranteed> = self.add_predicates_for_ast_type_binding(
c295e0f8
XL
692 hir_id,
693 poly_trait_ref,
694 binding,
695 bounds,
696 speculative,
697 &mut dup_bindings,
698 binding_span.unwrap_or(binding.span),
2b03887a 699 constness,
c295e0f8 700 );
5e7ed085 701 // Okay to ignore `Err` because of `ErrorGuaranteed` (see above).
c295e0f8
XL
702 }
703
704 arg_count
705 }
706
cdc7bbd5
XL
707 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
708 /// a full trait reference. The resulting trait reference is returned. This may also generate
709 /// auxiliary bounds, which are added to `bounds`.
710 ///
711 /// Example:
712 ///
04454e1e 713 /// ```ignore (illustrative)
cdc7bbd5
XL
714 /// poly_trait_ref = Iterator<Item = u32>
715 /// self_ty = Foo
716 /// ```
717 ///
718 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
719 ///
720 /// **A note on binders:** against our usual convention, there is an implied bounder around
721 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
722 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
723 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
724 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
725 /// however.
f2b60f7d 726 #[instrument(level = "debug", skip(self, span, constness, bounds, speculative))]
c295e0f8 727 pub(crate) fn instantiate_poly_trait_ref(
dfeec247
XL
728 &self,
729 trait_ref: &hir::TraitRef<'_>,
416331ca 730 span: Span,
94222f64 731 constness: ty::BoundConstness,
9e0c209e 732 self_ty: Ty<'tcx>,
dc9dc135
XL
733 bounds: &mut Bounds<'tcx>,
734 speculative: bool,
f9f354fc 735 ) -> GenericArgCountResult {
c295e0f8
XL
736 let hir_id = trait_ref.hir_ref_id;
737 let binding_span = None;
738 let trait_ref_span = trait_ref.path.span;
ba9703b0 739 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
c295e0f8
XL
740 let trait_segment = trait_ref.path.segments.last().unwrap();
741 let args = trait_segment.args();
742 let infer_args = trait_segment.infer_args;
32a655c1 743
923072b8 744 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1.iter(), |_| {});
5099ac24 745 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, false);
7cac9316 746
c295e0f8
XL
747 self.instantiate_poly_trait_ref_inner(
748 hir_id,
749 span,
750 binding_span,
751 constness,
752 bounds,
753 speculative,
754 trait_ref_span,
a1dfa0c6 755 trait_def_id,
c295e0f8
XL
756 trait_segment,
757 args,
758 infer_args,
a1dfa0c6 759 self_ty,
c295e0f8 760 )
c34b1796
AL
761 }
762
c295e0f8 763 pub(crate) fn instantiate_lang_item_trait_ref(
3dfed10e
XL
764 &self,
765 lang_item: hir::LangItem,
766 span: Span,
767 hir_id: hir::HirId,
768 args: &GenericArgs<'_>,
769 self_ty: Ty<'tcx>,
770 bounds: &mut Bounds<'tcx>,
771 ) {
c295e0f8
XL
772 let binding_span = Some(span);
773 let constness = ty::BoundConstness::NotConst;
774 let speculative = false;
775 let trait_ref_span = span;
3dfed10e 776 let trait_def_id = self.tcx().require_lang_item(lang_item, Some(span));
c295e0f8
XL
777 let trait_segment = &hir::PathSegment::invalid();
778 let infer_args = false;
3dfed10e 779
c295e0f8
XL
780 self.instantiate_poly_trait_ref_inner(
781 hir_id,
5869c6ff 782 span,
c295e0f8
XL
783 binding_span,
784 constness,
785 bounds,
786 speculative,
787 trait_ref_span,
5869c6ff 788 trait_def_id,
c295e0f8 789 trait_segment,
5869c6ff 790 args,
c295e0f8
XL
791 infer_args,
792 self_ty,
5869c6ff 793 );
3dfed10e
XL
794 }
795
dfeec247
XL
796 fn ast_path_to_mono_trait_ref(
797 &self,
dc9dc135
XL
798 span: Span,
799 trait_def_id: DefId,
800 self_ty: Ty<'tcx>,
dfeec247 801 trait_segment: &hir::PathSegment<'_>,
5099ac24 802 is_impl: bool,
487cf647 803 constness: ty::BoundConstness,
dfeec247 804 ) -> ty::TraitRef<'tcx> {
5099ac24
FG
805 let (substs, _) = self.create_substs_for_ast_trait_ref(
806 span,
807 trait_def_id,
808 self_ty,
809 trait_segment,
810 is_impl,
2b03887a 811 constness,
5099ac24 812 );
2b03887a 813 if let Some(b) = trait_segment.args().bindings.first() {
3dfed10e 814 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
f9f354fc 815 }
a7813a04
XL
816 ty::TraitRef::new(trait_def_id, substs)
817 }
c34b1796 818
f2b60f7d 819 #[instrument(level = "debug", skip(self, span))]
dfeec247
XL
820 fn create_substs_for_ast_trait_ref<'a>(
821 &self,
822 span: Span,
823 trait_def_id: DefId,
824 self_ty: Ty<'tcx>,
825 trait_segment: &'a hir::PathSegment<'a>,
5099ac24 826 is_impl: bool,
487cf647 827 constness: ty::BoundConstness,
cdc7bbd5 828 ) -> (SubstsRef<'tcx>, GenericArgCountResult) {
5099ac24 829 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, is_impl);
dfeec247
XL
830
831 self.create_substs_for_ast_path(
832 span,
833 trait_def_id,
834 &[],
5869c6ff
XL
835 trait_segment,
836 trait_segment.args(),
dfeec247
XL
837 trait_segment.infer_args,
838 Some(self_ty),
2b03887a 839 constness,
dfeec247 840 )
a7813a04 841 }
1a4d82fc 842
f9f354fc 843 fn trait_defines_associated_type_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
74b04a01
XL
844 self.tcx()
845 .associated_items(trait_def_id)
846 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, trait_def_id)
847 .is_some()
476ff2be 848 }
5099ac24
FG
849 fn trait_defines_associated_const_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
850 self.tcx()
851 .associated_items(trait_def_id)
852 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Const, trait_def_id)
853 .is_some()
854 }
476ff2be 855
487cf647 856 /// Sets `implicitly_sized` to true on `Bounds` if necessary
c295e0f8
XL
857 pub(crate) fn add_implicitly_sized<'hir>(
858 &self,
859 bounds: &mut Bounds<'hir>,
860 ast_bounds: &'hir [hir::GenericBound<'hir>],
487cf647 861 self_ty_where_predicates: Option<(LocalDefId, &'hir [hir::WherePredicate<'hir>])>,
c295e0f8
XL
862 span: Span,
863 ) {
dc9dc135
XL
864 let tcx = self.tcx();
865
866 // Try to find an unbound in bounds.
867 let mut unbound = None;
c295e0f8
XL
868 let mut search_bounds = |ast_bounds: &'hir [hir::GenericBound<'hir>]| {
869 for ab in ast_bounds {
870 if let hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = ab {
871 if unbound.is_none() {
872 unbound = Some(&ptr.trait_ref);
873 } else {
874 tcx.sess.emit_err(MultipleRelaxedDefaultBounds { span });
875 }
dc9dc135
XL
876 }
877 }
c295e0f8
XL
878 };
879 search_bounds(ast_bounds);
880 if let Some((self_ty, where_clause)) = self_ty_where_predicates {
c295e0f8
XL
881 for clause in where_clause {
882 if let hir::WherePredicate::BoundPredicate(pred) = clause {
487cf647 883 if pred.is_param_bound(self_ty.to_def_id()) {
04454e1e 884 search_bounds(pred.bounds);
dc9dc135
XL
885 }
886 }
887 }
c295e0f8
XL
888 }
889
487cf647 890 let sized_def_id = tcx.lang_items().sized_trait();
c295e0f8 891 match (&sized_def_id, unbound) {
487cf647 892 (Some(sized_def_id), Some(tpb))
c295e0f8
XL
893 if tpb.path.res == Res::Def(DefKind::Trait, *sized_def_id) =>
894 {
895 // There was in fact a `?Sized` bound, return without doing anything
896 return;
dc9dc135 897 }
c295e0f8
XL
898 (_, Some(_)) => {
899 // There was a `?Trait` bound, but it was not `?Sized`; warn.
900 tcx.sess.span_warn(
901 span,
902 "default bound relaxed for a type parameter, but \
903 this does nothing because the given bound is not \
904 a default; only `?Sized` is supported",
905 );
906 // Otherwise, add implicitly sized if `Sized` is available.
907 }
908 _ => {
909 // There was no `?Sized` bound; add implicitly sized if `Sized` is available.
910 }
911 }
487cf647 912 if sized_def_id.is_none() {
dc9dc135 913 // No lang item for `Sized`, so we can't add it as a bound.
c295e0f8 914 return;
dc9dc135 915 }
c295e0f8 916 bounds.implicitly_sized = Some(span);
dc9dc135
XL
917 }
918
919 /// This helper takes a *converted* parameter type (`param_ty`)
920 /// and an *unconverted* list of bounds:
921 ///
ba9703b0 922 /// ```text
dc9dc135
XL
923 /// fn foo<T: Debug>
924 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
925 /// |
926 /// `param_ty`, in ty form
927 /// ```
928 ///
929 /// It adds these `ast_bounds` into the `bounds` structure.
930 ///
931 /// **A note on binders:** there is an implied binder around
932 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
933 /// for more details.
f2b60f7d 934 #[instrument(level = "debug", skip(self, ast_bounds, bounds))]
c295e0f8 935 pub(crate) fn add_bounds<'hir, I: Iterator<Item = &'hir hir::GenericBound<'hir>>>(
dfeec247 936 &self,
dc9dc135 937 param_ty: Ty<'tcx>,
c295e0f8 938 ast_bounds: I,
dc9dc135 939 bounds: &mut Bounds<'tcx>,
cdc7bbd5 940 bound_vars: &'tcx ty::List<ty::BoundVariableKind>,
dc9dc135 941 ) {
dc9dc135 942 for ast_bound in ast_bounds {
c295e0f8
XL
943 match ast_bound {
944 hir::GenericBound::Trait(poly_trait_ref, modifier) => {
945 let constness = match modifier {
946 hir::TraitBoundModifier::MaybeConst => ty::BoundConstness::ConstIfConst,
947 hir::TraitBoundModifier::None => ty::BoundConstness::NotConst,
948 hir::TraitBoundModifier::Maybe => continue,
949 };
950
951 let _ = self.instantiate_poly_trait_ref(
952 &poly_trait_ref.trait_ref,
953 poly_trait_ref.span,
954 constness,
cdc7bbd5
XL
955 param_ty,
956 bounds,
957 false,
958 );
dfeec247 959 }
c295e0f8
XL
960 &hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
961 self.instantiate_lang_item_trait_ref(
962 lang_item, span, hir_id, args, param_ty, bounds,
cdc7bbd5 963 );
dfeec247 964 }
c295e0f8
XL
965 hir::GenericBound::Outlives(lifetime) => {
966 let region = self.ast_region_to_region(lifetime, None);
487cf647
FG
967 bounds.region_bounds.push((
968 ty::Binder::bind_with_vars(region, bound_vars),
969 lifetime.ident.span,
970 ));
c295e0f8 971 }
dc9dc135
XL
972 }
973 }
dc9dc135
XL
974 }
975
976 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
977 /// The self-type for the bounds is given by `param_ty`.
978 ///
979 /// Example:
980 ///
04454e1e 981 /// ```ignore (illustrative)
dc9dc135 982 /// fn foo<T: Bar + Baz>() { }
04454e1e
FG
983 /// // ^ ^^^^^^^^^ ast_bounds
984 /// // param_ty
dc9dc135
XL
985 /// ```
986 ///
987 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
988 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
989 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
990 ///
991 /// `span` should be the declaration size of the parameter.
c295e0f8 992 pub(crate) fn compute_bounds(
dfeec247 993 &self,
dc9dc135 994 param_ty: Ty<'tcx>,
dfeec247 995 ast_bounds: &[hir::GenericBound<'_>],
6a06907d 996 ) -> Bounds<'tcx> {
c295e0f8 997 self.compute_bounds_inner(param_ty, ast_bounds)
6a06907d
XL
998 }
999
1000 /// Convert the bounds in `ast_bounds` that refer to traits which define an associated type
1001 /// named `assoc_name` into ty::Bounds. Ignore the rest.
c295e0f8 1002 pub(crate) fn compute_bounds_that_match_assoc_type(
6a06907d
XL
1003 &self,
1004 param_ty: Ty<'tcx>,
1005 ast_bounds: &[hir::GenericBound<'_>],
6a06907d
XL
1006 assoc_name: Ident,
1007 ) -> Bounds<'tcx> {
1008 let mut result = Vec::new();
1009
1010 for ast_bound in ast_bounds {
5e7ed085
FG
1011 if let Some(trait_ref) = ast_bound.trait_ref()
1012 && let Some(trait_did) = trait_ref.trait_def_id()
1013 && self.tcx().trait_may_define_assoc_type(trait_did, assoc_name)
1014 {
1015 result.push(ast_bound.clone());
6a06907d
XL
1016 }
1017 }
1018
c295e0f8 1019 self.compute_bounds_inner(param_ty, &result)
6a06907d
XL
1020 }
1021
1022 fn compute_bounds_inner(
1023 &self,
1024 param_ty: Ty<'tcx>,
cdc7bbd5 1025 ast_bounds: &[hir::GenericBound<'_>],
dc9dc135
XL
1026 ) -> Bounds<'tcx> {
1027 let mut bounds = Bounds::default();
1028
c295e0f8 1029 self.add_bounds(param_ty, ast_bounds.iter(), &mut bounds, ty::List::empty());
04454e1e 1030 debug!(?bounds);
dc9dc135
XL
1031
1032 bounds
1033 }
1034
1035 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1036 /// onto `bounds`.
1037 ///
1038 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1039 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1040 /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
f2b60f7d 1041 #[instrument(level = "debug", skip(self, bounds, speculative, dup_bindings, path_span))]
dc9dc135 1042 fn add_predicates_for_ast_type_binding(
a7813a04 1043 &self,
532ac7d7 1044 hir_ref_id: hir::HirId,
9e0c209e 1045 trait_ref: ty::PolyTraitRef<'tcx>,
dc9dc135
XL
1046 binding: &ConvertedBinding<'_, 'tcx>,
1047 bounds: &mut Bounds<'tcx>,
94b46f34 1048 speculative: bool,
dc9dc135 1049 dup_bindings: &mut FxHashMap<DefId, Span>,
dfeec247 1050 path_span: Span,
2b03887a 1051 constness: ty::BoundConstness,
5e7ed085 1052 ) -> Result<(), ErrorGuaranteed> {
5869c6ff
XL
1053 // Given something like `U: SomeTrait<T = X>`, we want to produce a
1054 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1055 // subtle in the event that `T` is defined in a supertrait of
1056 // `SomeTrait`, because in that case we need to upcast.
1057 //
1058 // That is, consider this case:
1059 //
1060 // ```
1061 // trait SubTrait: SuperTrait<i32> { }
1062 // trait SuperTrait<A> { type T; }
1063 //
1064 // ... B: SubTrait<T = foo> ...
1065 // ```
1066 //
1067 // We want to produce `<B as SuperTrait<i32>>::T == foo`.
3dfed10e 1068
5869c6ff 1069 let tcx = self.tcx();
a7813a04 1070
dfeec247
XL
1071 let candidate =
1072 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1073 // Simple case: X is defined in the current trait.
1074 trait_ref
1075 } else {
1076 // Otherwise, we have to walk through the supertraits to find
1077 // those that do.
1078 self.one_bound_for_assoc_type(
1079 || traits::supertraits(tcx, trait_ref),
1080 || trait_ref.print_only_trait_path().to_string(),
1081 binding.item_name,
1082 path_span,
1083 || match binding.kind {
1084 ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1085 _ => None,
1086 },
1087 )?
1088 };
ff7c6d11 1089
94b46f34 1090 let (assoc_ident, def_scope) =
dc9dc135 1091 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
74b04a01 1092
ba9703b0 1093 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
74b04a01 1094 // of calling `filter_by_name_and_kind`.
5099ac24
FG
1095 let find_item_of_kind = |kind| {
1096 tcx.associated_items(candidate.def_id())
1097 .filter_by_name_unhygienic(assoc_ident.name)
1098 .find(|i| i.kind == kind && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident)
1099 };
1100 let assoc_item = find_item_of_kind(ty::AssocKind::Type)
1101 .or_else(|| find_item_of_kind(ty::AssocKind::Const))
dfeec247 1102 .expect("missing associated type");
ff7c6d11 1103
064997fb 1104 if !assoc_item.visibility(tcx).is_accessible_from(def_scope, tcx) {
ba9703b0
XL
1105 tcx.sess
1106 .struct_span_err(
1107 binding.span,
064997fb 1108 &format!("{} `{}` is private", assoc_item.kind, binding.item_name),
ba9703b0 1109 )
064997fb 1110 .span_label(binding.span, &format!("private {}", assoc_item.kind))
ba9703b0 1111 .emit();
a7813a04 1112 }
5099ac24 1113 tcx.check_stability(assoc_item.def_id, Some(hir_ref_id), binding.span, None);
a7813a04 1114
94b46f34 1115 if !speculative {
dfeec247 1116 dup_bindings
5099ac24 1117 .entry(assoc_item.def_id)
94b46f34 1118 .and_modify(|prev_span| {
1b1a35ee
XL
1119 self.tcx().sess.emit_err(ValueOfAssociatedStructAlreadySpecified {
1120 span: binding.span,
1121 prev_span: *prev_span,
1122 item_name: binding.item_name,
064997fb 1123 def_path: tcx.def_path_str(assoc_item.container_id(tcx)),
1b1a35ee 1124 });
94b46f34
XL
1125 })
1126 .or_insert(binding.span);
1127 }
1128
5869c6ff
XL
1129 // Include substitutions for generic parameters of associated types
1130 let projection_ty = candidate.map_bound(|trait_ref| {
5099ac24 1131 let ident = Ident::new(assoc_item.name, binding.item_name.span);
5869c6ff 1132 let item_segment = hir::PathSegment {
17df50a5 1133 ident,
f2b60f7d
FG
1134 hir_id: binding.hir_id,
1135 res: Res::Err,
5869c6ff
XL
1136 args: Some(binding.gen_args),
1137 infer_args: false,
1138 };
1139
1140 let substs_trait_ref_and_assoc_item = self.create_substs_for_associated_item(
5869c6ff 1141 path_span,
5099ac24 1142 assoc_item.def_id,
5869c6ff
XL
1143 &item_segment,
1144 trait_ref.substs,
1145 );
1146
2b03887a 1147 debug!(?substs_trait_ref_and_assoc_item);
5869c6ff
XL
1148
1149 ty::ProjectionTy {
5099ac24 1150 item_def_id: assoc_item.def_id,
5869c6ff
XL
1151 substs: substs_trait_ref_and_assoc_item,
1152 }
1153 });
1154
1155 if !speculative {
1156 // Find any late-bound regions declared in `ty` that are not
5099ac24 1157 // declared in the trait-ref or assoc_item. These are not well-formed.
5869c6ff
XL
1158 //
1159 // Example:
1160 //
1161 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1162 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1163 if let ConvertedBindingKind::Equality(ty) = binding.kind {
1164 let late_bound_in_trait_ref =
1165 tcx.collect_constrained_late_bound_regions(&projection_ty);
1166 let late_bound_in_ty =
cdc7bbd5 1167 tcx.collect_referenced_late_bound_regions(&trait_ref.rebind(ty));
2b03887a
FG
1168 debug!(?late_bound_in_trait_ref);
1169 debug!(?late_bound_in_ty);
5869c6ff
XL
1170
1171 // FIXME: point at the type params that don't have appropriate lifetimes:
1172 // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
1173 // ---- ---- ^^^^^^^
1174 self.validate_late_bound_regions(
1175 late_bound_in_trait_ref,
1176 late_bound_in_ty,
1177 |br_name| {
1178 struct_span_err!(
1179 tcx.sess,
1180 binding.span,
1181 E0582,
1182 "binding for associated type `{}` references {}, \
1183 which does not appear in the trait input types",
1184 binding.item_name,
1185 br_name
1186 )
1187 },
1188 );
1189 }
1190 }
1191
dc9dc135 1192 match binding.kind {
064997fb 1193 ConvertedBindingKind::Equality(mut term) => {
dc9dc135
XL
1194 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1195 // the "projection predicate" for:
1196 //
1197 // `<T as Iterator>::Item = u32`
5099ac24
FG
1198 let assoc_item_def_id = projection_ty.skip_binder().item_def_id;
1199 let def_kind = tcx.def_kind(assoc_item_def_id);
f2b60f7d
FG
1200 match (def_kind, term.unpack()) {
1201 (hir::def::DefKind::AssocTy, ty::TermKind::Ty(_))
1202 | (hir::def::DefKind::AssocConst, ty::TermKind::Const(_)) => (),
5099ac24 1203 (_, _) => {
f2b60f7d 1204 let got = if let Some(_) = term.ty() { "type" } else { "constant" };
5099ac24 1205 let expected = def_kind.descr(assoc_item_def_id);
487cf647
FG
1206 let reported = tcx
1207 .sess
5099ac24
FG
1208 .struct_span_err(
1209 binding.span,
064997fb 1210 &format!("expected {expected} bound, found {got}"),
5099ac24
FG
1211 )
1212 .span_note(
1213 tcx.def_span(assoc_item_def_id),
064997fb 1214 &format!("{expected} defined here"),
5099ac24
FG
1215 )
1216 .emit();
064997fb 1217 term = match def_kind {
487cf647
FG
1218 hir::def::DefKind::AssocTy => {
1219 tcx.ty_error_with_guaranteed(reported).into()
1220 }
064997fb 1221 hir::def::DefKind::AssocConst => tcx
487cf647 1222 .const_error_with_guaranteed(
064997fb
FG
1223 tcx.bound_type_of(assoc_item_def_id)
1224 .subst(tcx, projection_ty.skip_binder().substs),
487cf647 1225 reported,
064997fb
FG
1226 )
1227 .into(),
1228 _ => unreachable!(),
1229 };
5099ac24
FG
1230 }
1231 }
dfeec247 1232 bounds.projection_bounds.push((
5099ac24
FG
1233 projection_ty.map_bound(|projection_ty| ty::ProjectionPredicate {
1234 projection_ty,
1235 term: term,
dfeec247
XL
1236 }),
1237 binding.span,
1238 ));
9e0c209e 1239 }
dc9dc135
XL
1240 ConvertedBindingKind::Constraint(ast_bounds) => {
1241 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1242 //
1243 // `<T as Iterator>::Item: Debug`
1244 //
1245 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1246 // parameter to have a skipped binder.
cdc7bbd5 1247 let param_ty = tcx.mk_ty(ty::Projection(projection_ty.skip_binder()));
c295e0f8 1248 self.add_bounds(param_ty, ast_bounds.iter(), bounds, candidate.bound_vars());
dc9dc135
XL
1249 }
1250 }
1251 Ok(())
1a4d82fc
JJ
1252 }
1253
dfeec247
XL
1254 fn ast_path_to_ty(
1255 &self,
a7813a04 1256 span: Span,
a7813a04 1257 did: DefId,
dfeec247
XL
1258 item_segment: &hir::PathSegment<'_>,
1259 ) -> Ty<'tcx> {
32a655c1 1260 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
04454e1e
FG
1261 self.normalize_ty(
1262 span,
1263 EarlyBinder(self.tcx().at(span).type_of(did)).subst(self.tcx(), substs),
1264 )
1a4d82fc
JJ
1265 }
1266
dfeec247
XL
1267 fn conv_object_ty_poly_trait_ref(
1268 &self,
32a655c1 1269 span: Span,
dfeec247
XL
1270 trait_bounds: &[hir::PolyTraitRef<'_>],
1271 lifetime: &hir::Lifetime,
3dfed10e 1272 borrowed: bool,
f2b60f7d 1273 representation: DynKind,
dfeec247 1274 ) -> Ty<'tcx> {
a7813a04 1275 let tcx = self.tcx();
9e0c209e 1276
dc9dc135
XL
1277 let mut bounds = Bounds::default();
1278 let mut potential_assoc_types = Vec::new();
532ac7d7 1279 let dummy_self = self.tcx().types.trait_object_dummy_self;
416331ca 1280 for trait_bound in trait_bounds.iter().rev() {
f9f354fc
XL
1281 if let GenericArgCountResult {
1282 correct:
1283 Err(GenericArgCountMismatch { invalid_args: cur_potential_assoc_types, .. }),
1284 ..
1285 } = self.instantiate_poly_trait_ref(
cdc7bbd5
XL
1286 &trait_bound.trait_ref,
1287 trait_bound.span,
94222f64 1288 ty::BoundConstness::NotConst,
416331ca
XL
1289 dummy_self,
1290 &mut bounds,
cdc7bbd5 1291 false,
74b04a01 1292 ) {
5869c6ff 1293 potential_assoc_types.extend(cur_potential_assoc_types);
74b04a01 1294 }
416331ca 1295 }
dc9dc135
XL
1296
1297 // Expand trait aliases recursively and check that only one regular (non-auto) trait
1298 // is used and no 'maybe' bounds are used.
74b04a01
XL
1299 let expanded_traits =
1300 traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().map(|&(a, b, _)| (a, b)));
04454e1e
FG
1301 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) = expanded_traits
1302 .filter(|i| i.trait_ref().self_ty().skip_binder() == dummy_self)
1303 .partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
dc9dc135
XL
1304 if regular_traits.len() > 1 {
1305 let first_trait = &regular_traits[0];
1306 let additional_trait = &regular_traits[1];
dfeec247
XL
1307 let mut err = struct_span_err!(
1308 tcx.sess,
1309 additional_trait.bottom().1,
1310 E0225,
dc9dc135
XL
1311 "only auto traits can be used as additional traits in a trait object"
1312 );
dfeec247
XL
1313 additional_trait.label_with_exp_info(
1314 &mut err,
1315 "additional non-auto trait",
1316 "additional use",
1317 );
1318 first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
3dfed10e 1319 err.help(&format!(
c295e0f8 1320 "consider creating a new trait with all of these as supertraits and using that \
3dfed10e
XL
1321 trait here instead: `trait NewTrait: {} {{}}`",
1322 regular_traits
1323 .iter()
1324 .map(|t| t.trait_ref().print_only_trait_path().to_string())
1325 .collect::<Vec<_>>()
1326 .join(" + "),
1327 ));
1328 err.note(
1329 "auto-traits like `Send` and `Sync` are traits that have special properties; \
1330 for more information on them, visit \
1331 <https://doc.rust-lang.org/reference/special-types-and-traits.html#auto-traits>",
1332 );
dc9dc135 1333 err.emit();
7cac9316
XL
1334 }
1335
dc9dc135 1336 if regular_traits.is_empty() && auto_traits.is_empty() {
04454e1e
FG
1337 let trait_alias_span = bounds
1338 .trait_bounds
1339 .iter()
1340 .map(|&(trait_ref, _, _)| trait_ref.def_id())
1341 .find(|&trait_ref| tcx.is_trait_alias(trait_ref))
1342 .map(|trait_ref| tcx.def_span(trait_ref));
487cf647
FG
1343 let reported =
1344 tcx.sess.emit_err(TraitObjectDeclaredWithNoTraits { span, trait_alias_span });
1345 return tcx.ty_error_with_guaranteed(reported);
9e0c209e
SL
1346 }
1347
a1dfa0c6
XL
1348 // Check that there are no gross object safety violations;
1349 // most importantly, that the supertraits don't contain `Self`,
1350 // to avoid ICEs.
dc9dc135
XL
1351 for item in &regular_traits {
1352 let object_safety_violations =
dfeec247 1353 astconv_object_safety_violations(tcx, item.trait_ref().def_id());
dc9dc135 1354 if !object_safety_violations.is_empty() {
487cf647 1355 let reported = report_object_safety_error(
dfeec247 1356 tcx,
dc9dc135
XL
1357 span,
1358 item.trait_ref().def_id(),
a2a8927a 1359 &object_safety_violations,
dfeec247
XL
1360 )
1361 .emit();
487cf647 1362 return tcx.ty_error_with_guaranteed(reported);
dc9dc135 1363 }
a7813a04
XL
1364 }
1365
a1dfa0c6 1366 // Use a `BTreeSet` to keep output in a more consistent order.
dfeec247 1367 let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
b7449926 1368
dfeec247
XL
1369 let regular_traits_refs_spans = bounds
1370 .trait_bounds
dc9dc135 1371 .into_iter()
dfeec247 1372 .filter(|(trait_ref, _, _)| !tcx.trait_is_auto(trait_ref.def_id()));
a7813a04 1373
dfeec247 1374 for (base_trait_ref, span, constness) in regular_traits_refs_spans {
94222f64 1375 assert_eq!(constness, ty::BoundConstness::NotConst);
a7813a04 1376
ba9703b0 1377 for obligation in traits::elaborate_trait_ref(tcx, base_trait_ref) {
dfeec247
XL
1378 debug!(
1379 "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
ba9703b0 1380 obligation.predicate
a1dfa0c6 1381 );
3dfed10e 1382
5869c6ff 1383 let bound_predicate = obligation.predicate.kind();
29967ef6 1384 match bound_predicate.skip_binder() {
487cf647 1385 ty::PredicateKind::Clause(ty::Clause::Trait(pred)) => {
29967ef6 1386 let pred = bound_predicate.rebind(pred);
dfeec247
XL
1387 associated_types.entry(span).or_default().extend(
1388 tcx.associated_items(pred.def_id())
74b04a01 1389 .in_definition_order()
dfeec247
XL
1390 .filter(|item| item.kind == ty::AssocKind::Type)
1391 .map(|item| item.def_id),
1392 );
1393 }
487cf647 1394 ty::PredicateKind::Clause(ty::Clause::Projection(pred)) => {
29967ef6 1395 let pred = bound_predicate.rebind(pred);
dfeec247
XL
1396 // A `Self` within the original bound will be substituted with a
1397 // `trait_object_dummy_self`, so check for that.
f2b60f7d
FG
1398 let references_self = match pred.skip_binder().term.unpack() {
1399 ty::TermKind::Ty(ty) => ty.walk().any(|arg| arg == dummy_self.into()),
1400 ty::TermKind::Const(c) => {
1401 c.ty().walk().any(|arg| arg == dummy_self.into())
1402 }
5099ac24 1403 };
dfeec247
XL
1404
1405 // If the projection output contains `Self`, force the user to
1406 // elaborate it explicitly to avoid a lot of complexity.
1407 //
5e7ed085 1408 // The "classically useful" case is the following:
dfeec247
XL
1409 // ```
1410 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1411 // type MyOutput;
1412 // }
1413 // ```
1414 //
1415 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1416 // but actually supporting that would "expand" to an infinitely-long type
1417 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1418 //
1419 // Instead, we force the user to write
1420 // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1421 // the discussion in #56288 for alternatives.
1422 if !references_self {
1423 // Include projections defined on supertraits.
1424 bounds.projection_bounds.push((pred, span));
1425 }
a1dfa0c6 1426 }
dfeec247 1427 _ => (),
a1dfa0c6
XL
1428 }
1429 }
dfeec247
XL
1430 }
1431
1432 for (projection_bound, _) in &bounds.projection_bounds {
74b04a01 1433 for def_ids in associated_types.values_mut() {
dfeec247 1434 def_ids.remove(&projection_bound.projection_def_id());
a1dfa0c6 1435 }
a7813a04 1436 }
9346a6ac 1437
dfeec247
XL
1438 self.complain_about_missing_associated_types(
1439 associated_types,
1440 potential_assoc_types,
1441 trait_bounds,
1442 );
1443
dc9dc135
XL
1444 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1445 // `dyn Trait + Send`.
6a06907d
XL
1446 // We remove duplicates by inserting into a `FxHashSet` to avoid re-ordering
1447 // the bounds
1448 let mut duplicates = FxHashSet::default();
1449 auto_traits.retain(|i| duplicates.insert(i.trait_ref().def_id()));
dc9dc135
XL
1450 debug!("regular_traits: {:?}", regular_traits);
1451 debug!("auto_traits: {:?}", auto_traits);
1452
532ac7d7 1453 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
6a06907d
XL
1454 let existential_trait_refs = regular_traits.iter().map(|i| {
1455 i.trait_ref().map_bound(|trait_ref: ty::TraitRef<'tcx>| {
f2b60f7d
FG
1456 assert_eq!(trait_ref.self_ty(), dummy_self);
1457
1458 // Verify that `dummy_self` did not leak inside default type parameters. This
1459 // could not be done at path creation, since we need to see through trait aliases.
1460 let mut missing_type_params = vec![];
1461 let mut references_self = false;
1462 let generics = tcx.generics_of(trait_ref.def_id);
1463 let substs: Vec<_> = trait_ref
1464 .substs
1465 .iter()
1466 .enumerate()
1467 .skip(1) // Remove `Self` for `ExistentialPredicate`.
1468 .map(|(index, arg)| {
1469 if arg == dummy_self.into() {
1470 let param = &generics.params[index];
1471 missing_type_params.push(param.name);
1472 return tcx.ty_error().into();
1473 } else if arg.walk().any(|arg| arg == dummy_self.into()) {
1474 references_self = true;
1475 return tcx.ty_error().into();
1476 }
1477 arg
1478 })
1479 .collect();
1480 let substs = tcx.intern_substs(&substs[..]);
1481
1482 let span = i.bottom().1;
1483 let empty_generic_args = trait_bounds.iter().any(|hir_bound| {
1484 hir_bound.trait_ref.path.res == Res::Def(DefKind::Trait, trait_ref.def_id)
1485 && hir_bound.span.contains(span)
1486 });
1487 self.complain_about_missing_type_params(
1488 missing_type_params,
1489 trait_ref.def_id,
1490 span,
1491 empty_generic_args,
1492 );
1493
1494 if references_self {
1495 let def_id = i.bottom().0.def_id();
1496 let mut err = struct_span_err!(
1497 tcx.sess,
1498 i.bottom().1,
1499 E0038,
1500 "the {} `{}` cannot be made into an object",
1501 tcx.def_kind(def_id).descr(def_id),
1502 tcx.item_name(def_id),
1503 );
1504 err.note(
1505 rustc_middle::traits::ObjectSafetyViolation::SupertraitSelf(smallvec![])
1506 .error_msg(),
6a06907d 1507 );
f2b60f7d 1508 err.emit();
6a06907d 1509 }
f2b60f7d
FG
1510
1511 ty::ExistentialTraitRef { def_id: trait_ref.def_id, substs }
6a06907d
XL
1512 })
1513 });
f2b60f7d 1514
dc9dc135 1515 let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
f2b60f7d
FG
1516 bound.map_bound(|mut b| {
1517 assert_eq!(b.projection_ty.self_ty(), dummy_self);
1518
1519 // Like for trait refs, verify that `dummy_self` did not leak inside default type
1520 // parameters.
1521 let references_self = b.projection_ty.substs.iter().skip(1).any(|arg| {
1522 if arg.walk().any(|arg| arg == dummy_self.into()) {
1523 return true;
1524 }
1525 false
1526 });
1527 if references_self {
1528 tcx.sess
1529 .delay_span_bug(span, "trait object projection bounds reference `Self`");
1530 let substs: Vec<_> = b
1531 .projection_ty
1532 .substs
1533 .iter()
1534 .map(|arg| {
1535 if arg.walk().any(|arg| arg == dummy_self.into()) {
1536 return tcx.ty_error().into();
1537 }
1538 arg
1539 })
1540 .collect();
1541 b.projection_ty.substs = tcx.intern_substs(&substs[..]);
a1dfa0c6 1542 }
f2b60f7d 1543
6a06907d 1544 ty::ExistentialProjection::erase_self_ty(tcx, b)
a1dfa0c6
XL
1545 })
1546 });
1547
5869c6ff
XL
1548 let regular_trait_predicates = existential_trait_refs
1549 .map(|trait_ref| trait_ref.map_bound(ty::ExistentialPredicate::Trait));
fc512014
XL
1550 let auto_trait_predicates = auto_traits.into_iter().map(|trait_ref| {
1551 ty::Binder::dummy(ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()))
1552 });
17df50a5
XL
1553 // N.b. principal, projections, auto traits
1554 // FIXME: This is actually wrong with multiple principals in regards to symbol mangling
dfeec247 1555 let mut v = regular_trait_predicates
dfeec247 1556 .chain(
5869c6ff 1557 existential_projections.map(|x| x.map_bound(ty::ExistentialPredicate::Projection)),
dfeec247 1558 )
17df50a5 1559 .chain(auto_trait_predicates)
b7449926 1560 .collect::<SmallVec<[_; 8]>>();
fc512014 1561 v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
0731742a 1562 v.dedup();
fc512014 1563 let existential_predicates = tcx.mk_poly_existential_predicates(v.into_iter());
476ff2be 1564
a1dfa0c6 1565 // Use explicitly-specified region bound.
32a655c1
SL
1566 let region_bound = if !lifetime.is_elided() {
1567 self.ast_region_to_region(lifetime, None)
1568 } else {
1569 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
9fa01778 1570 if tcx.named_region(lifetime.hir_id).is_some() {
32a655c1
SL
1571 self.ast_region_to_region(lifetime, None)
1572 } else {
dc9dc135 1573 self.re_infer(None, span).unwrap_or_else(|| {
3dfed10e 1574 let mut err = struct_span_err!(
dfeec247
XL
1575 tcx.sess,
1576 span,
1577 E0228,
dc9dc135 1578 "the lifetime bound for this object type cannot be deduced \
dfeec247 1579 from context; please supply an explicit bound"
3dfed10e
XL
1580 );
1581 if borrowed {
1582 // We will have already emitted an error E0106 complaining about a
1583 // missing named lifetime in `&dyn Trait`, so we elide this one.
1584 err.delay_as_bug();
1585 } else {
1586 err.emit();
1587 }
48663c56 1588 tcx.lifetimes.re_static
32a655c1
SL
1589 })
1590 }
1591 })
476ff2be 1592 };
476ff2be
SL
1593 debug!("region_bound: {:?}", region_bound);
1594
f2b60f7d 1595 let ty = tcx.mk_dynamic(existential_predicates, region_bound, representation);
9e0c209e
SL
1596 debug!("trait_object_type: {:?}", ty);
1597 ty
9346a6ac
AL
1598 }
1599
48663c56
XL
1600 fn report_ambiguous_associated_type(
1601 &self,
1602 span: Span,
1603 type_str: &str,
1604 trait_str: &str,
f9f354fc 1605 name: Symbol,
5e7ed085 1606 ) -> ErrorGuaranteed {
48663c56 1607 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
923072b8
FG
1608 if self
1609 .tcx()
1610 .resolutions(())
1611 .confused_type_with_std_module
1612 .keys()
1613 .any(|full_span| full_span.contains(span))
1614 {
48663c56 1615 err.span_suggestion(
923072b8 1616 span.shrink_to_lo(),
48663c56 1617 "you are looking for the module in `std`, not the primitive type",
923072b8 1618 "std::",
48663c56
XL
1619 Applicability::MachineApplicable,
1620 );
1621 } else {
1622 err.span_suggestion(
dfeec247
XL
1623 span,
1624 "use fully-qualified syntax",
1625 format!("<{} as {}>::{}", type_str, trait_str, name),
1626 Applicability::HasPlaceholders,
48663c56
XL
1627 );
1628 }
5e7ed085 1629 err.emit()
a7813a04 1630 }
9346a6ac 1631
a7813a04 1632 // Search for a bound on a type parameter which includes the associated item
dc9dc135 1633 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
8bb4bdeb 1634 // This function will fail if there are no suitable bounds or there is
a7813a04 1635 // any ambiguity.
dfeec247
XL
1636 fn find_bound_for_assoc_item(
1637 &self,
f9f354fc
XL
1638 ty_param_def_id: LocalDefId,
1639 assoc_name: Ident,
dfeec247 1640 span: Span,
5e7ed085 1641 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> {
a7813a04 1642 let tcx = self.tcx();
c34b1796 1643
416331ca
XL
1644 debug!(
1645 "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
dfeec247 1646 ty_param_def_id, assoc_name, span,
416331ca
XL
1647 );
1648
6a06907d
XL
1649 let predicates = &self
1650 .get_type_parameter_bounds(span, ty_param_def_id.to_def_id(), assoc_name)
1651 .predicates;
416331ca
XL
1652
1653 debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1654
04454e1e 1655 let param_name = tcx.hir().ty_param_name(ty_param_def_id);
dfeec247
XL
1656 self.one_bound_for_assoc_type(
1657 || {
6a06907d 1658 traits::transitive_bounds_that_define_assoc_type(
dfeec247 1659 tcx,
fc512014 1660 predicates.iter().filter_map(|(p, _)| {
a2a8927a 1661 Some(p.to_opt_poly_trait_pred()?.map_bound(|t| t.trait_ref))
fc512014 1662 }),
6a06907d 1663 assoc_name,
dfeec247
XL
1664 )
1665 },
1666 || param_name.to_string(),
1667 assoc_name,
1668 span,
1669 || None,
1670 )
9346a6ac
AL
1671 }
1672
a1dfa0c6 1673 // Checks that `bounds` contains exactly one element and reports appropriate
a7813a04 1674 // errors otherwise.
2b03887a 1675 #[instrument(level = "debug", skip(self, all_candidates, ty_param_name, is_equality), ret)]
dfeec247
XL
1676 fn one_bound_for_assoc_type<I>(
1677 &self,
1678 all_candidates: impl Fn() -> I,
1679 ty_param_name: impl Fn() -> String,
f9f354fc 1680 assoc_name: Ident,
dfeec247
XL
1681 span: Span,
1682 is_equality: impl Fn() -> Option<String>,
5e7ed085 1683 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed>
dfeec247
XL
1684 where
1685 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
a7813a04 1686 {
dfeec247
XL
1687 let mut matching_candidates = all_candidates()
1688 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
5099ac24
FG
1689 let mut const_candidates = all_candidates()
1690 .filter(|r| self.trait_defines_associated_const_named(r.def_id(), assoc_name));
dfeec247 1691
5099ac24
FG
1692 let (bound, next_cand) = match (matching_candidates.next(), const_candidates.next()) {
1693 (Some(bound), _) => (bound, matching_candidates.next()),
1694 (None, Some(bound)) => (bound, const_candidates.next()),
1695 (None, None) => {
5e7ed085 1696 let reported = self.complain_about_assoc_type_not_found(
dfeec247
XL
1697 all_candidates,
1698 &ty_param_name(),
1699 assoc_name,
1700 span,
1701 );
5e7ed085 1702 return Err(reported);
476ff2be
SL
1703 }
1704 };
2b03887a 1705 debug!(?bound);
416331ca 1706
5099ac24 1707 if let Some(bound2) = next_cand {
2b03887a 1708 debug!(?bound2);
416331ca 1709
dfeec247 1710 let is_equality = is_equality();
a2a8927a 1711 let bounds = IntoIterator::into_iter([bound, bound2]).chain(matching_candidates);
dfeec247
XL
1712 let mut err = if is_equality.is_some() {
1713 // More specific Error Index entry.
1714 struct_span_err!(
1715 self.tcx().sess,
1716 span,
1717 E0222,
1718 "ambiguous associated type `{}` in bounds of `{}`",
1719 assoc_name,
1720 ty_param_name()
1721 )
1722 } else {
1723 struct_span_err!(
1724 self.tcx().sess,
1725 span,
1726 E0221,
1727 "ambiguous associated type `{}` in bounds of `{}`",
1728 assoc_name,
1729 ty_param_name()
1730 )
1731 };
7cac9316 1732 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
9346a6ac 1733
dfeec247 1734 let mut where_bounds = vec![];
476ff2be 1735 for bound in bounds {
74b04a01 1736 let bound_id = bound.def_id();
dfeec247
XL
1737 let bound_span = self
1738 .tcx()
74b04a01
XL
1739 .associated_items(bound_id)
1740 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, bound_id)
416331ca 1741 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
476ff2be 1742
dfeec247
XL
1743 if let Some(bound_span) = bound_span {
1744 err.span_label(
1745 bound_span,
1746 format!(
1747 "ambiguous `{}` from `{}`",
1748 assoc_name,
1749 bound.print_only_trait_path(),
1750 ),
1751 );
1752 if let Some(constraint) = &is_equality {
1753 where_bounds.push(format!(
1754 " T: {trait}::{assoc} = {constraint}",
1755 trait=bound.print_only_trait_path(),
1756 assoc=assoc_name,
1757 constraint=constraint,
1758 ));
1759 } else {
c295e0f8
XL
1760 err.span_suggestion_verbose(
1761 span.with_hi(assoc_name.span.lo()),
dfeec247
XL
1762 "use fully qualified syntax to disambiguate",
1763 format!(
c295e0f8 1764 "<{} as {}>::",
dfeec247
XL
1765 ty_param_name(),
1766 bound.print_only_trait_path(),
dfeec247
XL
1767 ),
1768 Applicability::MaybeIncorrect,
1769 );
1770 }
c30ab7b3 1771 } else {
dfeec247
XL
1772 err.note(&format!(
1773 "associated type `{}` could derive from `{}`",
1774 ty_param_name(),
1775 bound.print_only_trait_path(),
1776 ));
c30ab7b3 1777 }
a7813a04 1778 }
dfeec247
XL
1779 if !where_bounds.is_empty() {
1780 err.help(&format!(
1781 "consider introducing a new type parameter `T` and adding `where` constraints:\
1782 \n where\n T: {},\n{}",
1783 ty_param_name(),
1784 where_bounds.join(",\n"),
1785 ));
1786 }
5e7ed085 1787 let reported = err.emit();
dfeec247 1788 if !where_bounds.is_empty() {
5e7ed085 1789 return Err(reported);
dfeec247 1790 }
9346a6ac 1791 }
5099ac24 1792
ba9703b0 1793 Ok(bound)
9346a6ac
AL
1794 }
1795
a7813a04 1796 // Create a type from a path to an associated type.
9fa01778 1797 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
a1dfa0c6 1798 // and item_segment is the path segment for `D`. We return a type and a def for
a7813a04 1799 // the whole path.
9fa01778 1800 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
a1dfa0c6 1801 // parameter or `Self`.
6a06907d 1802 // NOTE: When this function starts resolving `Trait::AssocTy` successfully
5e7ed085 1803 // it should also start reporting the `BARE_TRAIT_OBJECTS` lint.
2b03887a 1804 #[instrument(level = "debug", skip(self, hir_ref_id, span, qself, assoc_segment), fields(assoc_ident=?assoc_segment.ident), ret)]
9fa01778
XL
1805 pub fn associated_path_to_ty(
1806 &self,
532ac7d7 1807 hir_ref_id: hir::HirId,
9fa01778
XL
1808 span: Span,
1809 qself_ty: Ty<'tcx>,
923072b8 1810 qself: &hir::Ty<'_>,
dfeec247 1811 assoc_segment: &hir::PathSegment<'_>,
9fa01778 1812 permit_variants: bool,
5e7ed085 1813 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> {
a7813a04 1814 let tcx = self.tcx();
9fa01778 1815 let assoc_ident = assoc_segment.ident;
923072b8
FG
1816 let qself_res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.kind {
1817 path.res
1818 } else {
1819 Res::Err
1820 };
a7813a04 1821
9fa01778
XL
1822 // Check if we have an enum variant.
1823 let mut variant_resolution = None;
487cf647 1824 if let ty::Adt(adt_def, adt_substs) = qself_ty.kind() {
9fa01778 1825 if adt_def.is_enum() {
dfeec247 1826 let variant_def = adt_def
5e7ed085 1827 .variants()
dfeec247 1828 .iter()
5e7ed085 1829 .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident(tcx), adt_def.did()));
9fa01778 1830 if let Some(variant_def) = variant_def {
9fa01778 1831 if permit_variants {
17df50a5 1832 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span, None);
923072b8
FG
1833 self.prohibit_generics(slice::from_ref(assoc_segment).iter(), |err| {
1834 err.note("enum variants can't have type parameters");
1835 let type_name = tcx.item_name(adt_def.did());
1836 let msg = format!(
1837 "you might have meant to specity type parameters on enum \
1838 `{type_name}`"
1839 );
1840 let Some(args) = assoc_segment.args else { return; };
1841 // Get the span of the generics args *including* the leading `::`.
1842 let args_span = assoc_segment.ident.span.shrink_to_hi().to(args.span_ext);
1843 if tcx.generics_of(adt_def.did()).count() == 0 {
1844 // FIXME(estebank): we could also verify that the arguments being
1845 // work for the `enum`, instead of just looking if it takes *any*.
1846 err.span_suggestion_verbose(
1847 args_span,
1848 &format!("{type_name} doesn't have generic parameters"),
1849 "",
1850 Applicability::MachineApplicable,
1851 );
1852 return;
1853 }
1854 let Ok(snippet) = tcx.sess.source_map().span_to_snippet(args_span) else {
1855 err.note(&msg);
1856 return;
1857 };
1858 let (qself_sugg_span, is_self) = if let hir::TyKind::Path(
1859 hir::QPath::Resolved(_, ref path)
1860 ) = qself.kind {
1861 // If the path segment already has type params, we want to overwrite
1862 // them.
1863 match &path.segments[..] {
1864 // `segment` is the previous to last element on the path,
1865 // which would normally be the `enum` itself, while the last
1866 // `_` `PathSegment` corresponds to the variant.
1867 [.., hir::PathSegment {
1868 ident,
1869 args,
f2b60f7d 1870 res: Res::Def(DefKind::Enum, _),
923072b8
FG
1871 ..
1872 }, _] => (
1873 // We need to include the `::` in `Type::Variant::<Args>`
1874 // to point the span to `::<Args>`, not just `<Args>`.
1875 ident.span.shrink_to_hi().to(args.map_or(
1876 ident.span.shrink_to_hi(),
1877 |a| a.span_ext)),
1878 false,
1879 ),
1880 [segment] => (
1881 // We need to include the `::` in `Type::Variant::<Args>`
1882 // to point the span to `::<Args>`, not just `<Args>`.
1883 segment.ident.span.shrink_to_hi().to(segment.args.map_or(
1884 segment.ident.span.shrink_to_hi(),
1885 |a| a.span_ext)),
1886 kw::SelfUpper == segment.ident.name,
1887 ),
1888 _ => {
1889 err.note(&msg);
1890 return;
1891 }
1892 }
1893 } else {
1894 err.note(&msg);
1895 return;
1896 };
1897 let suggestion = vec![
1898 if is_self {
1899 // Account for people writing `Self::Variant::<Args>`, where
1900 // `Self` is the enum, and suggest replacing `Self` with the
1901 // appropriate type: `Type::<Args>::Variant`.
1902 (qself.span, format!("{type_name}{snippet}"))
1903 } else {
1904 (qself_sugg_span, snippet)
1905 },
1906 (args_span, String::new()),
1907 ];
1908 err.multipart_suggestion_verbose(
1909 &msg,
1910 suggestion,
1911 Applicability::MaybeIncorrect,
1912 );
1913 });
48663c56 1914 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
9fa01778 1915 } else {
48663c56 1916 variant_resolution = Some(variant_def.def_id);
9fa01778
XL
1917 }
1918 }
1919 }
487cf647
FG
1920
1921 // see if we can satisfy using an inherent associated type
1922 for &impl_ in tcx.inherent_impls(adt_def.did()) {
1923 let Some(assoc_ty_did) = self.lookup_assoc_ty(assoc_ident, hir_ref_id, span, impl_) else {
1924 continue;
1925 };
1926 let item_substs = self.create_substs_for_associated_item(
1927 span,
1928 assoc_ty_did,
1929 assoc_segment,
1930 adt_substs,
1931 );
1932 let ty = tcx.bound_type_of(assoc_ty_did).subst(tcx, item_substs);
1933 let ty = self.normalize_ty(span, ty);
1934 return Ok((ty, DefKind::AssocTy, assoc_ty_did));
1935 }
9fa01778 1936 }
a7813a04
XL
1937
1938 // Find the type of the associated item, and the trait where the associated
1939 // item is declared.
1b1a35ee 1940 let bound = match (&qself_ty.kind(), qself_res) {
2b03887a 1941 (_, Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. }) => {
0731742a 1942 // `Self` in an impl of a trait -- we have a concrete self type and a
a7813a04 1943 // trait reference.
5e7ed085
FG
1944 let Some(trait_ref) = tcx.impl_trait_ref(impl_def_id) else {
1945 // A cycle error occurred, most likely.
1946 let guar = tcx.sess.delay_span_bug(span, "expected cycle error");
1947 return Err(guar);
8bb4bdeb
XL
1948 };
1949
dfeec247 1950 self.one_bound_for_assoc_type(
136023e0 1951 || traits::supertraits(tcx, ty::Binder::dummy(trait_ref)),
dfeec247
XL
1952 || "Self".to_string(),
1953 assoc_ident,
1954 span,
1955 || None,
1956 )?
c1a9b12d 1957 }
ba9703b0
XL
1958 (
1959 &ty::Param(_),
2b03887a 1960 Res::SelfTyParam { trait_: param_did } | Res::Def(DefKind::TyParam, param_did),
f9f354fc 1961 ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?,
9fa01778 1962 _ => {
5e7ed085 1963 let reported = if variant_resolution.is_some() {
9fa01778
XL
1964 // Variant in type position
1965 let msg = format!("expected type, found variant `{}`", assoc_ident);
5e7ed085 1966 tcx.sess.span_err(span, &msg)
9fa01778 1967 } else if qself_ty.is_enum() {
dfeec247
XL
1968 let mut err = struct_span_err!(
1969 tcx.sess,
48663c56 1970 assoc_ident.span,
dfeec247
XL
1971 E0599,
1972 "no variant named `{}` found for enum `{}`",
1973 assoc_ident,
1974 qself_ty,
a1dfa0c6 1975 );
48663c56 1976
9fa01778
XL
1977 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
1978 if let Some(suggested_name) = find_best_match_for_name(
fc512014 1979 &adt_def
5e7ed085 1980 .variants()
fc512014 1981 .iter()
5099ac24 1982 .map(|variant| variant.name)
fc512014 1983 .collect::<Vec<Symbol>>(),
3dfed10e 1984 assoc_ident.name,
9fa01778
XL
1985 None,
1986 ) {
1987 err.span_suggestion(
48663c56
XL
1988 assoc_ident.span,
1989 "there is a variant with a similar name",
923072b8 1990 suggested_name,
9fa01778
XL
1991 Applicability::MaybeIncorrect,
1992 );
1993 } else {
416331ca
XL
1994 err.span_label(
1995 assoc_ident.span,
1996 format!("variant not found in `{}`", qself_ty),
1997 );
48663c56
XL
1998 }
1999
5e7ed085 2000 if let Some(sp) = tcx.hir().span_if_local(adt_def.did()) {
48663c56 2001 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
9fa01778 2002 }
48663c56 2003
5e7ed085 2004 err.emit()
487cf647 2005 } else if let Err(reported) = qself_ty.error_reported() {
5e7ed085
FG
2006 reported
2007 } else {
9fa01778 2008 // Don't print `TyErr` to the user.
48663c56
XL
2009 self.report_ambiguous_associated_type(
2010 span,
2011 &qself_ty.to_string(),
2012 "Trait",
e1599b0c 2013 assoc_ident.name,
5e7ed085
FG
2014 )
2015 };
2016 return Err(reported);
9346a6ac 2017 }
a7813a04 2018 };
c34b1796 2019
83c7162d 2020 let trait_did = bound.def_id();
487cf647
FG
2021 let Some(assoc_ty_did) = self.lookup_assoc_ty(assoc_ident, hir_ref_id, span, trait_did) else {
2022 // Assume that if it's not matched, there must be a const defined with the same name
2023 // but it was used in a type position.
5099ac24 2024 let msg = format!("found associated const `{assoc_ident}` when type was expected");
5e7ed085
FG
2025 let guar = tcx.sess.struct_span_err(span, &msg).emit();
2026 return Err(guar);
5099ac24 2027 };
041b39d2 2028
487cf647 2029 let ty = self.projected_ty_from_poly_trait_ref(span, assoc_ty_did, assoc_segment, bound);
041b39d2
XL
2030 let ty = self.normalize_ty(span, ty);
2031
48663c56 2032 if let Some(variant_def_id) = variant_resolution {
2b03887a
FG
2033 tcx.struct_span_lint_hir(
2034 AMBIGUOUS_ASSOCIATED_ITEMS,
2035 hir_ref_id,
2036 span,
2037 "ambiguous associated item",
2038 |lint| {
2039 let mut could_refer_to = |kind: DefKind, def_id, also| {
2040 let note_msg = format!(
2041 "`{}` could{} refer to the {} defined here",
2042 assoc_ident,
2043 also,
2044 kind.descr(def_id)
2045 );
2046 lint.span_note(tcx.def_span(def_id), &note_msg);
2047 };
9fa01778 2048
2b03887a 2049 could_refer_to(DefKind::Variant, variant_def_id, "");
487cf647 2050 could_refer_to(DefKind::AssocTy, assoc_ty_did, " also");
74b04a01 2051
2b03887a
FG
2052 lint.span_suggestion(
2053 span,
2054 "use fully-qualified syntax",
2055 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
2056 Applicability::MachineApplicable,
2057 );
9fa01778 2058
2b03887a
FG
2059 lint
2060 },
2061 );
9fa01778 2062 }
487cf647
FG
2063 Ok((ty, DefKind::AssocTy, assoc_ty_did))
2064 }
2065
2066 fn lookup_assoc_ty(
2067 &self,
2068 ident: Ident,
2069 block: hir::HirId,
2070 span: Span,
2071 scope: DefId,
2072 ) -> Option<DefId> {
2073 let tcx = self.tcx();
2074 let (ident, def_scope) = tcx.adjust_ident_and_get_scope(ident, scope, block);
2075
2076 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
2077 // of calling `find_by_name_and_kind`.
2078 let item = tcx.associated_items(scope).in_definition_order().find(|i| {
2079 i.kind.namespace() == Namespace::TypeNS
2080 && i.ident(tcx).normalize_to_macros_2_0() == ident
2081 })?;
2082
2083 let kind = DefKind::AssocTy;
2084 if !item.visibility(tcx).is_accessible_from(def_scope, tcx) {
2085 let kind = kind.descr(item.def_id);
2086 let msg = format!("{kind} `{ident}` is private");
2087 let def_span = self.tcx().def_span(item.def_id);
2088 tcx.sess
2089 .struct_span_err_with_code(span, &msg, rustc_errors::error_code!(E0624))
2090 .span_label(span, &format!("private {kind}"))
2091 .span_label(def_span, &format!("{kind} defined here"))
2092 .emit();
2093 }
2094 tcx.check_stability(item.def_id, Some(block), span, None);
2095
2096 Some(item.def_id)
a7813a04 2097 }
1a4d82fc 2098
dfeec247
XL
2099 fn qpath_to_ty(
2100 &self,
2101 span: Span,
2102 opt_self_ty: Option<Ty<'tcx>>,
2103 item_def_id: DefId,
2104 trait_segment: &hir::PathSegment<'_>,
2105 item_segment: &hir::PathSegment<'_>,
2b03887a 2106 constness: ty::BoundConstness,
dfeec247 2107 ) -> Ty<'tcx> {
a7813a04 2108 let tcx = self.tcx();
60c5eb7d 2109
04454e1e 2110 let trait_def_id = tcx.parent(item_def_id);
1a4d82fc 2111
60c5eb7d
XL
2112 debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
2113
3c0e092e 2114 let Some(self_ty) = opt_self_ty else {
532ac7d7 2115 let path_str = tcx.def_path_str(trait_def_id);
60c5eb7d
XL
2116
2117 let def_id = self.item_def_id();
2118
2119 debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
2120
487cf647 2121 let parent_def_id = def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
5099ac24 2122 .map(|hir_id| tcx.hir().get_parent_item(hir_id).to_def_id());
60c5eb7d
XL
2123
2124 debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
2125
2126 // If the trait in segment is the same as the trait defining the item,
2127 // use the `<Self as ..>` syntax in the error.
487cf647 2128 let is_part_of_self_trait_constraints = def_id == trait_def_id;
60c5eb7d
XL
2129 let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
2130
2131 let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
2132 "Self"
2133 } else {
2134 "Type"
2135 };
2136
487cf647 2137 let reported = self.report_ambiguous_associated_type(
48663c56 2138 span,
60c5eb7d 2139 type_name,
48663c56 2140 &path_str,
e1599b0c 2141 item_segment.ident.name,
48663c56 2142 );
487cf647 2143 return tcx.ty_error_with_guaranteed(reported)
a7813a04 2144 };
1a4d82fc 2145
a7813a04 2146 debug!("qpath_to_ty: self_type={:?}", self_ty);
1a4d82fc 2147
2b03887a
FG
2148 let trait_ref = self.ast_path_to_mono_trait_ref(
2149 span,
2150 trait_def_id,
2151 self_ty,
2152 trait_segment,
2153 false,
487cf647 2154 constness,
2b03887a 2155 );
dfeec247
XL
2156
2157 let item_substs = self.create_substs_for_associated_item(
dfeec247
XL
2158 span,
2159 item_def_id,
2160 item_segment,
2161 trait_ref.substs,
2162 );
1a4d82fc 2163
a7813a04 2164 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
85aaf69f 2165
dfeec247 2166 self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
8bb4bdeb
XL
2167 }
2168
923072b8 2169 pub fn prohibit_generics<'a>(
dfeec247 2170 &self,
923072b8 2171 segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
f2b60f7d 2172 extend: impl Fn(&mut Diagnostic),
dfeec247 2173 ) -> bool {
923072b8
FG
2174 let args = segments.clone().flat_map(|segment| segment.args().args);
2175
2176 let (lt, ty, ct, inf) =
2177 args.clone().fold((false, false, false, false), |(lt, ty, ct, inf), arg| match arg {
2178 hir::GenericArg::Lifetime(_) => (true, ty, ct, inf),
2179 hir::GenericArg::Type(_) => (lt, true, ct, inf),
2180 hir::GenericArg::Const(_) => (lt, ty, true, inf),
2181 hir::GenericArg::Infer(_) => (lt, ty, ct, true),
2182 });
2183 let mut emitted = false;
2184 if lt || ty || ct || inf {
2185 let types_and_spans: Vec<_> = segments
2186 .clone()
2187 .flat_map(|segment| {
f2b60f7d
FG
2188 if segment.args().args.is_empty() {
2189 None
2190 } else {
2191 Some((
2192 match segment.res {
2193 Res::PrimTy(ty) => format!("{} `{}`", segment.res.descr(), ty.name()),
923072b8
FG
2194 Res::Def(_, def_id)
2195 if let Some(name) = self.tcx().opt_item_name(def_id) => {
f2b60f7d 2196 format!("{} `{name}`", segment.res.descr())
923072b8
FG
2197 }
2198 Res::Err => "this type".to_string(),
f2b60f7d 2199 _ => segment.res.descr().to_string(),
923072b8
FG
2200 },
2201 segment.ident.span,
2202 ))
f2b60f7d 2203 }
923072b8
FG
2204 })
2205 .collect();
2206 let this_type = match &types_and_spans[..] {
2207 [.., _, (last, _)] => format!(
2208 "{} and {last}",
2209 types_and_spans[..types_and_spans.len() - 1]
2210 .iter()
2211 .map(|(x, _)| x.as_str())
2212 .intersperse(&", ")
2213 .collect::<String>()
2214 ),
2215 [(only, _)] => only.to_string(),
2216 [] => "this type".to_string(),
2217 };
2218
2219 let arg_spans: Vec<Span> = args.map(|arg| arg.span()).collect();
2220
2221 let mut kinds = Vec::with_capacity(4);
2222 if lt {
2223 kinds.push("lifetime");
2224 }
2225 if ty {
2226 kinds.push("type");
2227 }
2228 if ct {
2229 kinds.push("const");
dc9dc135 2230 }
923072b8
FG
2231 if inf {
2232 kinds.push("generic");
2233 }
2234 let (kind, s) = match kinds[..] {
2235 [.., _, last] => (
2236 format!(
2237 "{} and {last}",
2238 kinds[..kinds.len() - 1]
2239 .iter()
2240 .map(|&x| x)
2241 .intersperse(", ")
2242 .collect::<String>()
2243 ),
2244 "s",
2245 ),
2246 [only] => (format!("{only}"), ""),
2247 [] => unreachable!(),
2248 };
2249 let last_span = *arg_spans.last().unwrap();
2250 let span: MultiSpan = arg_spans.into();
2251 let mut err = struct_span_err!(
2252 self.tcx().sess,
2253 span,
2254 E0109,
2255 "{kind} arguments are not allowed on {this_type}",
2256 );
2257 err.span_label(last_span, format!("{kind} argument{s} not allowed"));
2258 for (what, span) in types_and_spans {
2259 err.span_label(span, format!("not allowed on {what}"));
2260 }
2261 extend(&mut err);
2262 err.emit();
2263 emitted = true;
2264 }
74b04a01 2265
923072b8 2266 for segment in segments {
74b04a01 2267 // Only emit the first error to avoid overloading the user with error messages.
2b03887a
FG
2268 if let Some(b) = segment.args().bindings.first() {
2269 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
923072b8 2270 return true;
dc9dc135 2271 }
8bb4bdeb 2272 }
923072b8 2273 emitted
8bb4bdeb
XL
2274 }
2275
48663c56
XL
2276 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2277 pub fn def_ids_for_value_path_segments(
2278 &self,
dfeec247 2279 segments: &[hir::PathSegment<'_>],
48663c56
XL
2280 self_ty: Option<Ty<'tcx>>,
2281 kind: DefKind,
2282 def_id: DefId,
2283 ) -> Vec<PathSeg> {
0731742a
XL
2284 // We need to extract the type parameters supplied by the user in
2285 // the path `path`. Due to the current setup, this is a bit of a
2286 // tricky-process; the problem is that resolve only tells us the
2287 // end-point of the path resolution, and not the intermediate steps.
2288 // Luckily, we can (at least for now) deduce the intermediate steps
2289 // just from the end-point.
2290 //
2291 // There are basically five cases to consider:
2292 //
2293 // 1. Reference to a constructor of a struct:
2294 //
2295 // struct Foo<T>(...)
2296 //
2297 // In this case, the parameters are declared in the type space.
2298 //
2299 // 2. Reference to a constructor of an enum variant:
2300 //
2301 // enum E<T> { Foo(...) }
2302 //
2303 // In this case, the parameters are defined in the type space,
2304 // but may be specified either on the type or the variant.
2305 //
2306 // 3. Reference to a fn item or a free constant:
2307 //
2308 // fn foo<T>() { }
2309 //
2310 // In this case, the path will again always have the form
2311 // `a::b::foo::<T>` where only the final segment should have
2312 // type parameters. However, in this case, those parameters are
2313 // declared on a value, and hence are in the `FnSpace`.
2314 //
2315 // 4. Reference to a method or an associated constant:
2316 //
2317 // impl<A> SomeStruct<A> {
2318 // fn foo<B>(...)
2319 // }
2320 //
2321 // Here we can have a path like
2322 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2323 // may appear in two places. The penultimate segment,
2324 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2325 // final segment, `foo::<B>` contains parameters in fn space.
2326 //
0731742a
XL
2327 // The first step then is to categorize the segments appropriately.
2328
2329 let tcx = self.tcx();
2330
2331 assert!(!segments.is_empty());
2332 let last = segments.len() - 1;
2333
2334 let mut path_segs = vec![];
2335
48663c56 2336 match kind {
0731742a 2337 // Case 1. Reference to a struct constructor.
48663c56 2338 DefKind::Ctor(CtorOf::Struct, ..) => {
0731742a
XL
2339 // Everything but the final segment should have no
2340 // parameters at all.
2341 let generics = tcx.generics_of(def_id);
2342 // Variant and struct constructors use the
2343 // generics of their parent type definition.
2344 let generics_def_id = generics.parent.unwrap_or(def_id);
2345 path_segs.push(PathSeg(generics_def_id, last));
2346 }
2347
2348 // Case 2. Reference to a variant constructor.
dfeec247 2349 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
0731742a
XL
2350 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
2351 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
2352 debug_assert!(adt_def.is_enum());
5e7ed085 2353 (adt_def.did(), last)
0731742a
XL
2354 } else if last >= 1 && segments[last - 1].args.is_some() {
2355 // Everything but the penultimate segment should have no
2356 // parameters at all.
532ac7d7
XL
2357 let mut def_id = def_id;
2358
48663c56
XL
2359 // `DefKind::Ctor` -> `DefKind::Variant`
2360 if let DefKind::Ctor(..) = kind {
04454e1e 2361 def_id = tcx.parent(def_id);
532ac7d7
XL
2362 }
2363
48663c56 2364 // `DefKind::Variant` -> `DefKind::Enum`
04454e1e 2365 let enum_def_id = tcx.parent(def_id);
0731742a
XL
2366 (enum_def_id, last - 1)
2367 } else {
2368 // FIXME: lint here recommending `Enum::<...>::Variant` form
2369 // instead of `Enum::Variant::<...>` form.
2370
2371 // Everything but the final segment should have no
2372 // parameters at all.
2373 let generics = tcx.generics_of(def_id);
2374 // Variant and struct constructors use the
2375 // generics of their parent type definition.
2376 (generics.parent.unwrap_or(def_id), last)
2377 };
2378 path_segs.push(PathSeg(generics_def_id, index));
2379 }
2380
2381 // Case 3. Reference to a top-level value.
5e7ed085 2382 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static(_) => {
0731742a
XL
2383 path_segs.push(PathSeg(def_id, last));
2384 }
2385
2386 // Case 4. Reference to a method or associated const.
ba9703b0 2387 DefKind::AssocFn | DefKind::AssocConst => {
0731742a
XL
2388 if segments.len() >= 2 {
2389 let generics = tcx.generics_of(def_id);
2390 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2391 }
2392 path_segs.push(PathSeg(def_id, last));
2393 }
2394
48663c56 2395 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
0731742a
XL
2396 }
2397
2398 debug!("path_segs = {:?}", path_segs);
2399
2400 path_segs
2401 }
2402
487cf647 2403 /// Check a type `Path` and convert it to a `Ty`.
dfeec247
XL
2404 pub fn res_to_ty(
2405 &self,
2406 opt_self_ty: Option<Ty<'tcx>>,
2407 path: &hir::Path<'_>,
2408 permit_variants: bool,
2409 ) -> Ty<'tcx> {
a7813a04
XL
2410 let tcx = self.tcx();
2411
dfeec247
XL
2412 debug!(
2413 "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2414 path.res, opt_self_ty, path.segments
2415 );
a7813a04 2416
476ff2be 2417 let span = path.span;
48663c56 2418 match path.res {
f2b60f7d 2419 Res::Def(DefKind::OpaqueTy | DefKind::ImplTraitPlaceholder, did) => {
dc9dc135 2420 // Check for desugared `impl Trait`.
487cf647 2421 assert!(tcx.is_type_alias_impl_trait(did));
8faf50e0 2422 let item_segment = path.segments.split_last().unwrap();
923072b8
FG
2423 self.prohibit_generics(item_segment.1.iter(), |err| {
2424 err.note("`impl Trait` types can't have type parameters");
2425 });
8faf50e0 2426 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
dfeec247 2427 self.normalize_ty(span, tcx.mk_opaque(did, substs))
8faf50e0 2428 }
ba9703b0
XL
2429 Res::Def(
2430 DefKind::Enum
2431 | DefKind::TyAlias
2432 | DefKind::Struct
2433 | DefKind::Union
2434 | DefKind::ForeignTy,
2435 did,
2436 ) => {
476ff2be 2437 assert_eq!(opt_self_ty, None);
923072b8 2438 self.prohibit_generics(path.segments.split_last().unwrap().1.iter(), |_| {});
32a655c1 2439 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
a7813a04 2440 }
48663c56 2441 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
c30ab7b3
SL
2442 // Convert "variant type" as if it were a real type.
2443 // The resulting `Ty` is type of the variant's enum for now.
476ff2be 2444 assert_eq!(opt_self_ty, None);
0731742a 2445
48663c56 2446 let path_segs =
c295e0f8 2447 self.def_ids_for_value_path_segments(path.segments, None, kind, def_id);
0731742a
XL
2448 let generic_segs: FxHashSet<_> =
2449 path_segs.iter().map(|PathSeg(_, index)| index).collect();
923072b8
FG
2450 self.prohibit_generics(
2451 path.segments.iter().enumerate().filter_map(|(index, seg)| {
dfeec247 2452 if !generic_segs.contains(&index) { Some(seg) } else { None }
923072b8
FG
2453 }),
2454 |err| {
2455 err.note("enum variants can't have type parameters");
dfeec247 2456 },
923072b8 2457 );
0731742a
XL
2458
2459 let PathSeg(def_id, index) = path_segs.last().unwrap();
2460 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
c30ab7b3 2461 }
dc9dc135 2462 Res::Def(DefKind::TyParam, def_id) => {
476ff2be 2463 assert_eq!(opt_self_ty, None);
923072b8
FG
2464 self.prohibit_generics(path.segments.iter(), |err| {
2465 if let Some(span) = tcx.def_ident_span(def_id) {
2466 let name = tcx.item_name(def_id);
2467 err.span_note(span, &format!("type parameter `{name}` defined here"));
2468 }
2469 });
9e0c209e 2470
04454e1e
FG
2471 let def_id = def_id.expect_local();
2472 let item_def_id = tcx.hir().ty_param_owner(def_id);
7cac9316 2473 let generics = tcx.generics_of(item_def_id);
04454e1e
FG
2474 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2475 tcx.mk_ty_param(index, tcx.hir().ty_param_name(def_id))
a7813a04 2476 }
2b03887a 2477 Res::SelfTyParam { .. } => {
dc9dc135 2478 // `Self` in trait or type alias.
476ff2be 2479 assert_eq!(opt_self_ty, None);
923072b8
FG
2480 self.prohibit_generics(path.segments.iter(), |err| {
2481 if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments[..] {
2482 err.span_suggestion_verbose(
2483 ident.span.shrink_to_hi().to(args.span_ext),
2484 "the `Self` type doesn't accept type parameters",
2485 "",
2486 Applicability::MaybeIncorrect,
2487 );
2488 }
2489 });
e1599b0c 2490 tcx.types.self_param
9346a6ac 2491 }
2b03887a 2492 Res::SelfTyAlias { alias_to: def_id, forbid_generic, .. } => {
dc9dc135 2493 // `Self` in impl (we know the concrete type).
476ff2be 2494 assert_eq!(opt_self_ty, None);
dc9dc135 2495 // Try to evaluate any array length constants.
5099ac24 2496 let ty = tcx.at(span).type_of(def_id);
923072b8
FG
2497 let span_of_impl = tcx.span_of_impl(def_id);
2498 self.prohibit_generics(path.segments.iter(), |err| {
2499 let def_id = match *ty.kind() {
2500 ty::Adt(self_def, _) => self_def.did(),
2501 _ => return,
2502 };
2503
2504 let type_name = tcx.item_name(def_id);
2505 let span_of_ty = tcx.def_ident_span(def_id);
2506 let generics = tcx.generics_of(def_id).count();
2507
2508 let msg = format!("`Self` is of type `{ty}`");
2509 if let (Ok(i_sp), Some(t_sp)) = (span_of_impl, span_of_ty) {
923072b8
FG
2510 let mut span: MultiSpan = vec![t_sp].into();
2511 span.push_span_label(
2512 i_sp,
2513 &format!("`Self` is on type `{type_name}` in this `impl`"),
2514 );
2515 let mut postfix = "";
2516 if generics == 0 {
2517 postfix = ", which doesn't have generic parameters";
2518 }
2519 span.push_span_label(
2520 t_sp,
2521 &format!("`Self` corresponds to this type{postfix}"),
2522 );
2523 err.span_note(span, &msg);
2524 } else {
2525 err.note(&msg);
2526 }
2527 for segment in path.segments {
2528 if let Some(args) = segment.args && segment.ident.name == kw::SelfUpper {
2529 if generics == 0 {
2530 // FIXME(estebank): we could also verify that the arguments being
2531 // work for the `enum`, instead of just looking if it takes *any*.
2532 err.span_suggestion_verbose(
2533 segment.ident.span.shrink_to_hi().to(args.span_ext),
2534 "the `Self` type doesn't accept type parameters",
2535 "",
2536 Applicability::MachineApplicable,
2537 );
2538 return;
2539 } else {
2540 err.span_suggestion_verbose(
2541 segment.ident.span,
2542 format!(
2543 "the `Self` type doesn't accept type parameters, use the \
2544 concrete type's name `{type_name}` instead if you want to \
2545 specify its type parameters"
2546 ),
064997fb 2547 type_name,
923072b8
FG
2548 Applicability::MaybeIncorrect,
2549 );
2550 }
2551 }
2552 }
2553 });
5099ac24
FG
2554 // HACK(min_const_generics): Forbid generic `Self` types
2555 // here as we can't easily do that during nameres.
2556 //
2557 // We do this before normalization as we otherwise allow
2558 // ```rust
2559 // trait AlwaysApplicable { type Assoc; }
2560 // impl<T: ?Sized> AlwaysApplicable for T { type Assoc = usize; }
2561 //
2562 // trait BindsParam<T> {
2563 // type ArrayTy;
2564 // }
2565 // impl<T> BindsParam<T> for <T as AlwaysApplicable>::Assoc {
2566 // type ArrayTy = [u8; Self::MAX];
2567 // }
2568 // ```
2569 // Note that the normalization happens in the param env of
2570 // the anon const, which is empty. This is why the
2571 // `AlwaysApplicable` impl needs a `T: ?Sized` bound for
2572 // this to compile if we were to normalize here.
2573 if forbid_generic && ty.needs_subst() {
1b1a35ee
XL
2574 let mut err = tcx.sess.struct_span_err(
2575 path.span,
2576 "generic `Self` types are currently not permitted in anonymous constants",
2577 );
2578 if let Some(hir::Node::Item(&hir::Item {
5869c6ff 2579 kind: hir::ItemKind::Impl(ref impl_),
1b1a35ee
XL
2580 ..
2581 })) = tcx.hir().get_if_local(def_id)
2582 {
5869c6ff 2583 err.span_note(impl_.self_ty.span, "not a concrete type");
1b1a35ee 2584 }
487cf647 2585 tcx.ty_error_with_guaranteed(err.emit())
1b1a35ee 2586 } else {
5099ac24 2587 self.normalize_ty(span, ty)
1b1a35ee 2588 }
a7813a04 2589 }
dc9dc135 2590 Res::Def(DefKind::AssocTy, def_id) => {
0731742a 2591 debug_assert!(path.segments.len() >= 2);
923072b8 2592 self.prohibit_generics(path.segments[..path.segments.len() - 2].iter(), |_| {});
2b03887a
FG
2593 // HACK: until we support `<Type as ~const Trait>`, assume all of them are.
2594 let constness = if tcx.has_attr(tcx.parent(def_id), sym::const_trait) {
2595 ty::BoundConstness::ConstIfConst
2596 } else {
2597 ty::BoundConstness::NotConst
2598 };
dfeec247
XL
2599 self.qpath_to_ty(
2600 span,
2601 opt_self_ty,
2602 def_id,
2603 &path.segments[path.segments.len() - 2],
2604 path.segments.last().unwrap(),
2b03887a 2605 constness,
dfeec247 2606 )
a7813a04 2607 }
48663c56 2608 Res::PrimTy(prim_ty) => {
476ff2be 2609 assert_eq!(opt_self_ty, None);
923072b8
FG
2610 self.prohibit_generics(path.segments.iter(), |err| {
2611 let name = prim_ty.name_str();
2612 for segment in path.segments {
2613 if let Some(args) = segment.args {
2614 err.span_suggestion_verbose(
2615 segment.ident.span.shrink_to_hi().to(args.span_ext),
2616 &format!("primitive type `{name}` doesn't have generic parameters"),
2617 "",
2618 Applicability::MaybeIncorrect,
2619 );
2620 }
2621 }
2622 });
8bb4bdeb 2623 match prim_ty {
dfeec247
XL
2624 hir::PrimTy::Bool => tcx.types.bool,
2625 hir::PrimTy::Char => tcx.types.char,
5869c6ff
XL
2626 hir::PrimTy::Int(it) => tcx.mk_mach_int(ty::int_ty(it)),
2627 hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(ty::uint_ty(uit)),
2628 hir::PrimTy::Float(ft) => tcx.mk_mach_float(ty::float_ty(ft)),
f035d41b 2629 hir::PrimTy::Str => tcx.types.str_,
8bb4bdeb 2630 }
a7813a04 2631 }
48663c56 2632 Res::Err => {
487cf647
FG
2633 let e = self
2634 .tcx()
2635 .sess
2636 .delay_span_bug(path.span, "path with `Res:Err` but no error emitted");
2637 self.set_tainted_by_errors(e);
2638 self.tcx().ty_error_with_guaranteed(e)
a7813a04 2639 }
dfeec247 2640 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
c34b1796 2641 }
9346a6ac 2642 }
c34b1796 2643
a7813a04
XL
2644 /// Parses the programmer's textual representation of a type into our
2645 /// internal notion of a type.
dfeec247 2646 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
a2a8927a
XL
2647 self.ast_ty_to_ty_inner(ast_ty, false, false)
2648 }
2649
2650 /// Parses the programmer's textual representation of a type into our
2651 /// internal notion of a type. This is meant to be used within a path.
2652 pub fn ast_ty_to_ty_in_path(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2653 self.ast_ty_to_ty_inner(ast_ty, false, true)
3dfed10e
XL
2654 }
2655
2656 /// Turns a `hir::Ty` into a `Ty`. For diagnostics' purposes we keep track of whether trait
2657 /// objects are borrowed like `&dyn Trait` to avoid emitting redundant errors.
f2b60f7d 2658 #[instrument(level = "debug", skip(self), ret)]
a2a8927a 2659 fn ast_ty_to_ty_inner(&self, ast_ty: &hir::Ty<'_>, borrowed: bool, in_path: bool) -> Ty<'tcx> {
a7813a04 2660 let tcx = self.tcx();
1a4d82fc 2661
e74abb32 2662 let result_ty = match ast_ty.kind {
c295e0f8 2663 hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(ty)),
8faf50e0 2664 hir::TyKind::Ptr(ref mt) => {
c295e0f8 2665 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(mt.ty), mutbl: mt.mutbl })
a7813a04 2666 }
8faf50e0 2667 hir::TyKind::Rptr(ref region, ref mt) => {
32a655c1 2668 let r = self.ast_region_to_region(region, None);
cdc7bbd5 2669 debug!(?r);
a2a8927a 2670 let t = self.ast_ty_to_ty_inner(mt.ty, true, false);
dfeec247 2671 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
a7813a04 2672 }
dfeec247 2673 hir::TyKind::Never => tcx.types.never,
c295e0f8
XL
2674 hir::TyKind::Tup(fields) => tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(t))),
2675 hir::TyKind::BareFn(bf) => {
2676 require_c_abi_if_c_variadic(tcx, bf.decl, bf.abi, ast_ty.span);
6a06907d 2677
74b04a01 2678 tcx.mk_fn_ptr(self.ty_of_fn(
cdc7bbd5 2679 ast_ty.hir_id,
74b04a01
XL
2680 bf.unsafety,
2681 bf.abi,
c295e0f8 2682 bf.decl,
74b04a01 2683 None,
6a06907d 2684 Some(ast_ty),
74b04a01 2685 ))
1a4d82fc 2686 }
f2b60f7d 2687 hir::TyKind::TraitObject(bounds, ref lifetime, repr) => {
a2a8927a 2688 self.maybe_lint_bare_trait(ast_ty, in_path);
f2b60f7d
FG
2689 let repr = match repr {
2690 TraitObjectSyntax::Dyn | TraitObjectSyntax::None => ty::Dyn,
2691 TraitObjectSyntax::DynStar => ty::DynStar,
2692 };
2693 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime, borrowed, repr)
a7813a04 2694 }
8faf50e0 2695 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
cdc7bbd5 2696 debug!(?maybe_qself, ?path);
dfeec247 2697 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
48663c56 2698 self.res_to_ty(opt_self_ty, path, false)
476ff2be 2699 }
f2b60f7d 2700 hir::TyKind::OpaqueDef(item_id, lifetimes, in_trait) => {
6a06907d 2701 let opaque_ty = tcx.hir().item(item_id);
2b03887a 2702 let def_id = item_id.owner_id.to_def_id();
f035d41b
XL
2703
2704 match opaque_ty.kind {
923072b8 2705 hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
f2b60f7d 2706 self.impl_trait_ty_to_ty(def_id, lifetimes, origin, in_trait)
923072b8 2707 }
f035d41b
XL
2708 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
2709 }
dc9dc135 2710 }
8faf50e0 2711 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
cdc7bbd5 2712 debug!(?qself, ?segment);
a2a8927a 2713 let ty = self.ast_ty_to_ty_inner(qself, false, true);
923072b8 2714 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, qself, segment, false)
dfeec247 2715 .map(|(ty, _, _)| ty)
f035d41b 2716 .unwrap_or_else(|_| tcx.ty_error())
a7813a04 2717 }
a2a8927a 2718 hir::TyKind::Path(hir::QPath::LangItem(lang_item, span, _)) => {
3dfed10e 2719 let def_id = tcx.require_lang_item(lang_item, Some(span));
cdc7bbd5 2720 let (substs, _) = self.create_substs_for_ast_path(
3dfed10e
XL
2721 span,
2722 def_id,
2723 &[],
5869c6ff 2724 &hir::PathSegment::invalid(),
3dfed10e
XL
2725 &GenericArgs::none(),
2726 true,
2727 None,
487cf647 2728 ty::BoundConstness::NotConst,
3dfed10e 2729 );
04454e1e
FG
2730 EarlyBinder(self.normalize_ty(span, tcx.at(span).type_of(def_id)))
2731 .subst(tcx, substs)
3dfed10e 2732 }
8faf50e0 2733 hir::TyKind::Array(ref ty, ref length) => {
a2a8927a
XL
2734 let length = match length {
2735 &hir::ArrayLen::Infer(_, span) => self.ct_infer(tcx.types.usize, None, span),
2736 hir::ArrayLen::Body(constant) => {
487cf647 2737 ty::Const::from_anon_const(tcx, constant.def_id)
a2a8927a
XL
2738 }
2739 };
2740
c295e0f8 2741 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(ty), length));
ea8adc8c 2742 self.normalize_ty(ast_ty.span, array_ty)
1a4d82fc 2743 }
cdc7bbd5 2744 hir::TyKind::Typeof(ref e) => {
487cf647 2745 let ty_erased = tcx.type_of(e.def_id);
f2b60f7d
FG
2746 let ty = tcx.fold_regions(ty_erased, |r, _| {
2747 if r.is_erased() { tcx.lifetimes.re_static } else { r }
2748 });
04454e1e
FG
2749 let span = ast_ty.span;
2750 tcx.sess.emit_err(TypeofReservedKeywordUsed {
2751 span,
2752 ty,
2753 opt_sugg: Some((span, Applicability::MachineApplicable))
064997fb 2754 .filter(|_| ty.is_suggestable(tcx, false)),
04454e1e
FG
2755 });
2756
2757 ty
a7813a04 2758 }
8faf50e0 2759 hir::TyKind::Infer => {
b7449926 2760 // Infer also appears as the type of arguments or return
94222f64 2761 // values in an ExprKind::Closure, or as
a7813a04
XL
2762 // the type of local variables. Both of these cases are
2763 // handled specially and will not descend into this routine.
dc9dc135 2764 self.ty_infer(None, ast_ty.span)
cc61c64b 2765 }
f035d41b 2766 hir::TyKind::Err => tcx.ty_error(),
a7813a04 2767 };
1a4d82fc 2768
ea8adc8c 2769 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
a7813a04 2770 result_ty
1a4d82fc 2771 }
1a4d82fc 2772
f2b60f7d 2773 #[instrument(level = "debug", skip(self), ret)]
cdc7bbd5 2774 fn impl_trait_ty_to_ty(
94b46f34
XL
2775 &self,
2776 def_id: DefId,
dfeec247 2777 lifetimes: &[hir::GenericArg<'_>],
923072b8 2778 origin: OpaqueTyOrigin,
f2b60f7d 2779 in_trait: bool,
94b46f34 2780 ) -> Ty<'tcx> {
ff7c6d11
XL
2781 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2782 let tcx = self.tcx();
94b46f34 2783
ff7c6d11
XL
2784 let generics = tcx.generics_of(def_id);
2785
ff7c6d11 2786 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
532ac7d7 2787 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
94b46f34
XL
2788 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2789 // Our own parameters are the resolved lifetimes.
487cf647
FG
2790 let GenericParamDefKind::Lifetime { .. } = param.kind else { bug!() };
2791 let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] else { bug!() };
2792 self.ast_region_to_region(lifetime, None).into()
94b46f34 2793 } else {
487cf647 2794 tcx.mk_param_from_def(param)
ff7c6d11 2795 }
94b46f34 2796 });
dc9dc135 2797 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
ff7c6d11 2798
f2b60f7d 2799 if in_trait { tcx.mk_projection(def_id, substs) } else { tcx.mk_opaque(def_id, substs) }
ff7c6d11
XL
2800 }
2801
dfeec247 2802 pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
e74abb32 2803 match ty.kind {
8faf50e0 2804 hir::TyKind::Infer if expected_ty.is_some() => {
ea8adc8c
XL
2805 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2806 expected_ty.unwrap()
2807 }
32a655c1 2808 _ => self.ast_ty_to_ty(ty),
a7813a04
XL
2809 }
2810 }
1a4d82fc 2811
2b03887a 2812 #[instrument(level = "debug", skip(self, hir_id, unsafety, abi, decl, generics, hir_ty), ret)]
dfeec247
XL
2813 pub fn ty_of_fn(
2814 &self,
cdc7bbd5 2815 hir_id: hir::HirId,
dfeec247
XL
2816 unsafety: hir::Unsafety,
2817 abi: abi::Abi,
2818 decl: &hir::FnDecl<'_>,
04454e1e 2819 generics: Option<&hir::Generics<'_>>,
6a06907d 2820 hir_ty: Option<&hir::Ty<'_>>,
dfeec247 2821 ) -> ty::PolyFnSig<'tcx> {
ea8adc8c 2822 let tcx = self.tcx();
cdc7bbd5
XL
2823 let bound_vars = tcx.late_bound_vars(hir_id);
2824 debug!(?bound_vars);
1a4d82fc 2825
74b04a01 2826 // We proactively collect all the inferred type params to emit a single error per fn def.
5099ac24 2827 let mut visitor = HirPlaceholderCollector::default();
04454e1e
FG
2828 let mut infer_replacements = vec![];
2829
2830 if let Some(generics) = generics {
2831 walk_generics(&mut visitor, generics);
dfeec247 2832 }
74b04a01 2833
04454e1e
FG
2834 let input_tys: Vec<_> = decl
2835 .inputs
2836 .iter()
2837 .enumerate()
2838 .map(|(i, a)| {
2839 if let hir::TyKind::Infer = a.kind && !self.allow_ty_infer() {
2840 if let Some(suggested_ty) =
2841 self.suggest_trait_fn_ty_for_impl_fn_infer(hir_id, Some(i))
2842 {
2843 infer_replacements.push((a.span, suggested_ty.to_string()));
2844 return suggested_ty;
2845 }
2846 }
2847
2848 // Only visit the type looking for `_` if we didn't fix the type above
2849 visitor.visit_ty(a);
2850 self.ty_of_arg(a, None)
2851 })
2852 .collect();
2853
a7813a04 2854 let output_ty = match decl.output {
c295e0f8 2855 hir::FnRetTy::Return(output) => {
04454e1e
FG
2856 if let hir::TyKind::Infer = output.kind
2857 && !self.allow_ty_infer()
2858 && let Some(suggested_ty) =
2859 self.suggest_trait_fn_ty_for_impl_fn_infer(hir_id, None)
2860 {
2861 infer_replacements.push((output.span, suggested_ty.to_string()));
2862 suggested_ty
2863 } else {
2864 visitor.visit_ty(output);
2865 self.ast_ty_to_ty(output)
2866 }
dfeec247 2867 }
74b04a01 2868 hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(),
a7813a04 2869 };
1a4d82fc 2870
2b03887a 2871 debug!(?output_ty);
9e0c209e 2872
04454e1e 2873 let fn_ty = tcx.mk_fn_sig(input_tys.into_iter(), output_ty, decl.c_variadic, unsafety, abi);
cdc7bbd5 2874 let bare_fn_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
dfeec247 2875
04454e1e 2876 if !self.allow_ty_infer() && !(visitor.0.is_empty() && infer_replacements.is_empty()) {
dfeec247
XL
2877 // We always collect the spans for placeholder types when evaluating `fn`s, but we
2878 // only want to emit an error complaining about them if infer types (`_`) are not
ba9703b0
XL
2879 // allowed. `allow_ty_infer` gates this behavior. We check for the presence of
2880 // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`.
6a06907d 2881
04454e1e 2882 let mut diag = crate::collect::placeholder_type_error_diag(
dfeec247 2883 tcx,
04454e1e 2884 generics,
dfeec247 2885 visitor.0,
04454e1e 2886 infer_replacements.iter().map(|(s, _)| *s).collect(),
ba9703b0 2887 true,
6a06907d 2888 hir_ty,
136023e0 2889 "function",
dfeec247 2890 );
04454e1e
FG
2891
2892 if !infer_replacements.is_empty() {
f2b60f7d
FG
2893 diag.multipart_suggestion(
2894 &format!(
04454e1e
FG
2895 "try replacing `_` with the type{} in the corresponding trait method signature",
2896 rustc_errors::pluralize!(infer_replacements.len()),
f2b60f7d
FG
2897 ),
2898 infer_replacements,
2899 Applicability::MachineApplicable,
2900 );
04454e1e
FG
2901 }
2902
2903 diag.emit();
dfeec247 2904 }
ea8adc8c
XL
2905
2906 // Find any late-bound regions declared in return type that do
0bf4aa26 2907 // not appear in the arguments. These are not well-formed.
ea8adc8c
XL
2908 //
2909 // Example:
2910 // for<'a> fn() -> &'a str <-- 'a is bad
2911 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2912 let inputs = bare_fn_ty.inputs();
dfeec247
XL
2913 let late_bound_in_args =
2914 tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
ea8adc8c
XL
2915 let output = bare_fn_ty.output();
2916 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
3dfed10e
XL
2917
2918 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
2919 struct_span_err!(
dfeec247
XL
2920 tcx.sess,
2921 decl.output.span(),
2922 E0581,
3dfed10e
XL
2923 "return type references {}, which is not constrained by the fn input types",
2924 br_name
2925 )
2926 });
2927
2928 bare_fn_ty
2929 }
2930
04454e1e
FG
2931 /// Given a fn_hir_id for a impl function, suggest the type that is found on the
2932 /// corresponding function in the trait that the impl implements, if it exists.
2933 /// If arg_idx is Some, then it corresponds to an input type index, otherwise it
2934 /// corresponds to the return type.
2935 fn suggest_trait_fn_ty_for_impl_fn_infer(
2936 &self,
2937 fn_hir_id: hir::HirId,
2938 arg_idx: Option<usize>,
2939 ) -> Option<Ty<'tcx>> {
2940 let tcx = self.tcx();
2941 let hir = tcx.hir();
2942
2943 let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
2944 hir.get(fn_hir_id) else { return None };
2945 let hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(i), .. }) =
2946 hir.get(hir.get_parent_node(fn_hir_id)) else { bug!("ImplItem should have Impl parent") };
2947
2b03887a
FG
2948 let trait_ref = self.instantiate_mono_trait_ref(
2949 i.of_trait.as_ref()?,
2950 self.ast_ty_to_ty(i.self_ty),
2951 ty::BoundConstness::NotConst,
2952 );
04454e1e
FG
2953
2954 let assoc = tcx.associated_items(trait_ref.def_id).find_by_name_and_kind(
2955 tcx,
2956 *ident,
2957 ty::AssocKind::Fn,
2958 trait_ref.def_id,
2959 )?;
2960
2961 let fn_sig = tcx.bound_fn_sig(assoc.def_id).subst(
2962 tcx,
2963 trait_ref.substs.extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
2964 );
2965
2966 let ty = if let Some(arg_idx) = arg_idx { fn_sig.input(arg_idx) } else { fn_sig.output() };
2967
2968 Some(tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), ty))
2969 }
2970
487cf647 2971 #[instrument(level = "trace", skip(self, generate_err))]
3dfed10e
XL
2972 fn validate_late_bound_regions(
2973 &self,
fc512014
XL
2974 constrained_regions: FxHashSet<ty::BoundRegionKind>,
2975 referenced_regions: FxHashSet<ty::BoundRegionKind>,
5e7ed085 2976 generate_err: impl Fn(&str) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>,
3dfed10e
XL
2977 ) {
2978 for br in referenced_regions.difference(&constrained_regions) {
2979 let br_name = match *br {
487cf647 2980 ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(..) | ty::BrEnv => {
923072b8
FG
2981 "an anonymous lifetime".to_string()
2982 }
3dfed10e 2983 ty::BrNamed(_, name) => format!("lifetime `{}`", name),
3dfed10e
XL
2984 };
2985
2986 let mut err = generate_err(&br_name);
2987
487cf647 2988 if let ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(..) = *br {
2c00a5a8
XL
2989 // The only way for an anonymous lifetime to wind up
2990 // in the return type but **also** be unconstrained is
2991 // if it only appears in "associated types" in the
3dfed10e 2992 // input. See #47511 and #62200 for examples. In this case,
2c00a5a8
XL
2993 // though we can easily give a hint that ought to be
2994 // relevant.
dfeec247 2995 err.note(
f2b60f7d 2996 "lifetimes appearing in an associated or opaque type are not considered constrained",
dfeec247 2997 );
f2b60f7d 2998 err.note("consider introducing a named lifetime parameter");
2c00a5a8 2999 }
3dfed10e 3000
2c00a5a8 3001 err.emit();
ea8adc8c 3002 }
a7813a04 3003 }
1a4d82fc 3004
a7813a04
XL
3005 /// Given the bounds on an object, determines what single region bound (if any) we can
3006 /// use to summarize this type. The basic idea is that we will use the bound the user
3007 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
3008 /// for region bounds. It may be that we can derive no bound at all, in which case
3009 /// we return `None`.
dfeec247
XL
3010 fn compute_object_lifetime_bound(
3011 &self,
a7813a04 3012 span: Span,
487cf647 3013 existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
dfeec247 3014 ) -> Option<ty::Region<'tcx>> // if None, use the default
a7813a04
XL
3015 {
3016 let tcx = self.tcx();
85aaf69f 3017
dfeec247 3018 debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
1a4d82fc 3019
a7813a04
XL
3020 // No explicit region bound specified. Therefore, examine trait
3021 // bounds and see if we can derive region bounds from those.
dfeec247 3022 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
1a4d82fc 3023
a7813a04
XL
3024 // If there are no derived region bounds, then report back that we
3025 // can find no region bound. The caller will use the default.
3026 if derived_region_bounds.is_empty() {
3027 return None;
3028 }
1a4d82fc 3029
a7813a04
XL
3030 // If any of the derived region bounds are 'static, that is always
3031 // the best choice.
5099ac24 3032 if derived_region_bounds.iter().any(|r| r.is_static()) {
48663c56 3033 return Some(tcx.lifetimes.re_static);
a7813a04 3034 }
1a4d82fc 3035
a7813a04
XL
3036 // Determine whether there is exactly one unique region in the set
3037 // of derived region bounds. If so, use that. Otherwise, report an
3038 // error.
3039 let r = derived_region_bounds[0];
3040 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1b1a35ee 3041 tcx.sess.emit_err(AmbiguousLifetimeBound { span });
a7813a04 3042 }
ba9703b0 3043 Some(r)
1a4d82fc 3044 }
a2a8927a 3045
064997fb 3046 /// Make sure that we are in the condition to suggest the blanket implementation.
f2b60f7d 3047 fn maybe_lint_blanket_trait_impl(&self, self_ty: &hir::Ty<'_>, diag: &mut Diagnostic) {
064997fb 3048 let tcx = self.tcx();
2b03887a 3049 let parent_id = tcx.hir().get_parent_item(self_ty.hir_id).def_id;
064997fb
FG
3050 if let hir::Node::Item(hir::Item {
3051 kind:
3052 hir::ItemKind::Impl(hir::Impl {
3053 self_ty: impl_self_ty, of_trait: Some(of_trait_ref), generics, ..
3054 }),
3055 ..
3056 }) = tcx.hir().get_by_def_id(parent_id) && self_ty.hir_id == impl_self_ty.hir_id
3057 {
3058 if !of_trait_ref.trait_def_id().map_or(false, |def_id| def_id.is_local()) {
3059 return;
3060 }
3061 let of_trait_span = of_trait_ref.path.span;
3062 // make sure that we are not calling unwrap to abort during the compilation
3063 let Ok(impl_trait_name) = tcx.sess.source_map().span_to_snippet(self_ty.span) else { return; };
3064 let Ok(of_trait_name) = tcx.sess.source_map().span_to_snippet(of_trait_span) else { return; };
3065 // check if the trait has generics, to make a correct suggestion
3066 let param_name = generics.params.next_type_param_name(None);
3067
3068 let add_generic_sugg = if let Some(span) = generics.span_for_param_suggestion() {
3069 (span, format!(", {}: {}", param_name, impl_trait_name))
3070 } else {
3071 (generics.span, format!("<{}: {}>", param_name, impl_trait_name))
3072 };
3073 diag.multipart_suggestion(
3074 format!("alternatively use a blanket \
3075 implementation to implement `{of_trait_name}` for \
3076 all types that also implement `{impl_trait_name}`"),
3077 vec![
3078 (self_ty.span, param_name),
3079 add_generic_sugg,
3080 ],
3081 Applicability::MaybeIncorrect,
3082 );
3083 }
3084 }
3085
a2a8927a
XL
3086 fn maybe_lint_bare_trait(&self, self_ty: &hir::Ty<'_>, in_path: bool) {
3087 let tcx = self.tcx();
3088 if let hir::TyKind::TraitObject([poly_trait_ref, ..], _, TraitObjectSyntax::None) =
3089 self_ty.kind
3090 {
3091 let needs_bracket = in_path
3092 && !tcx
3093 .sess
3094 .source_map()
3095 .span_to_prev_source(self_ty.span)
3096 .ok()
3097 .map_or(false, |s| s.trim_end().ends_with('<'));
3098
3099 let is_global = poly_trait_ref.trait_ref.path.is_global();
2b03887a
FG
3100
3101 let mut sugg = Vec::from_iter([(
3102 self_ty.span.shrink_to_lo(),
3103 format!(
3104 "{}dyn {}",
3105 if needs_bracket { "<" } else { "" },
3106 if is_global { "(" } else { "" },
a2a8927a 3107 ),
2b03887a
FG
3108 )]);
3109
3110 if is_global || needs_bracket {
3111 sugg.push((
a2a8927a
XL
3112 self_ty.span.shrink_to_hi(),
3113 format!(
3114 "{}{}",
3115 if is_global { ")" } else { "" },
3116 if needs_bracket { ">" } else { "" },
3117 ),
2b03887a
FG
3118 ));
3119 }
3120
a2a8927a
XL
3121 if self_ty.span.edition() >= Edition::Edition2021 {
3122 let msg = "trait objects must include the `dyn` keyword";
3123 let label = "add `dyn` keyword before this trait";
064997fb
FG
3124 let mut diag =
3125 rustc_errors::struct_span_err!(tcx.sess, self_ty.span, E0782, "{}", msg);
3126 diag.multipart_suggestion_verbose(label, sugg, Applicability::MachineApplicable);
3127 // check if the impl trait that we are considering is a impl of a local trait
3128 self.maybe_lint_blanket_trait_impl(&self_ty, &mut diag);
3129 diag.emit();
a2a8927a
XL
3130 } else {
3131 let msg = "trait objects without an explicit `dyn` are deprecated";
3132 tcx.struct_span_lint_hir(
3133 BARE_TRAIT_OBJECTS,
3134 self_ty.hir_id,
3135 self_ty.span,
2b03887a 3136 msg,
a2a8927a 3137 |lint| {
2b03887a 3138 lint.multipart_suggestion_verbose(
064997fb
FG
3139 "use `dyn`",
3140 sugg,
3141 Applicability::MachineApplicable,
3142 );
2b03887a
FG
3143 self.maybe_lint_blanket_trait_impl(&self_ty, lint);
3144 lint
a2a8927a
XL
3145 },
3146 );
3147 }
3148 }
3149 }
1a4d82fc 3150}