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