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