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