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