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