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