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