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