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