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