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