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