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