]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/astconv.rs
Auto merge of #67970 - cjgillot:inherent, r=Centril
[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::{Applicability, DiagnosticId};
13 use rustc::hir::intravisit::Visitor;
14 use rustc::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
15 use rustc::traits;
16 use rustc::traits::astconv_object_safety_violations;
17 use rustc::traits::error_reporting::report_object_safety_error;
18 use rustc::traits::wf::object_region_bounds;
19 use rustc::ty::subst::{self, InternalSubsts, Subst, SubstsRef};
20 use rustc::ty::{self, Const, DefIdTree, ToPredicate, Ty, TyCtxt, TypeFoldable};
21 use rustc::ty::{GenericParamDef, GenericParamDefKind};
22 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
23 use rustc_hir as hir;
24 use rustc_hir::def::{CtorOf, DefKind, Res};
25 use rustc_hir::def_id::DefId;
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                     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                 }
1130             }
1131         }
1132
1133         let kind_id = tcx.lang_items().require(SizedTraitLangItem);
1134         match unbound {
1135             Some(tpb) => {
1136                 // FIXME(#8559) currently requires the unbound to be built-in.
1137                 if let Ok(kind_id) = kind_id {
1138                     if tpb.path.res != Res::Def(DefKind::Trait, kind_id) {
1139                         tcx.sess.span_warn(
1140                             span,
1141                             "default bound relaxed for a type parameter, but \
1142                              this does nothing because the given bound is not \
1143                              a default; only `?Sized` is supported",
1144                         );
1145                     }
1146                 }
1147             }
1148             _ if kind_id.is_ok() => {
1149                 return false;
1150             }
1151             // No lang item for `Sized`, so we can't add it as a bound.
1152             None => {}
1153         }
1154
1155         true
1156     }
1157
1158     /// This helper takes a *converted* parameter type (`param_ty`)
1159     /// and an *unconverted* list of bounds:
1160     ///
1161     /// ```
1162     /// fn foo<T: Debug>
1163     ///        ^  ^^^^^ `ast_bounds` parameter, in HIR form
1164     ///        |
1165     ///        `param_ty`, in ty form
1166     /// ```
1167     ///
1168     /// It adds these `ast_bounds` into the `bounds` structure.
1169     ///
1170     /// **A note on binders:** there is an implied binder around
1171     /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
1172     /// for more details.
1173     fn add_bounds(
1174         &self,
1175         param_ty: Ty<'tcx>,
1176         ast_bounds: &[hir::GenericBound<'_>],
1177         bounds: &mut Bounds<'tcx>,
1178     ) {
1179         let mut trait_bounds = Vec::new();
1180         let mut region_bounds = Vec::new();
1181
1182         for ast_bound in ast_bounds {
1183             match *ast_bound {
1184                 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => {
1185                     trait_bounds.push(b)
1186                 }
1187                 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
1188                 hir::GenericBound::Outlives(ref l) => region_bounds.push(l),
1189             }
1190         }
1191
1192         for bound in trait_bounds {
1193             let _ = self.instantiate_poly_trait_ref(bound, param_ty, bounds);
1194         }
1195
1196         bounds.region_bounds.extend(
1197             region_bounds.into_iter().map(|r| (self.ast_region_to_region(r, None), r.span)),
1198         );
1199     }
1200
1201     /// Translates a list of bounds from the HIR into the `Bounds` data structure.
1202     /// The self-type for the bounds is given by `param_ty`.
1203     ///
1204     /// Example:
1205     ///
1206     /// ```
1207     /// fn foo<T: Bar + Baz>() { }
1208     ///        ^  ^^^^^^^^^ ast_bounds
1209     ///        param_ty
1210     /// ```
1211     ///
1212     /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
1213     /// considered `Sized` unless there is an explicit `?Sized` bound.  This would be true in the
1214     /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
1215     ///
1216     /// `span` should be the declaration size of the parameter.
1217     pub fn compute_bounds(
1218         &self,
1219         param_ty: Ty<'tcx>,
1220         ast_bounds: &[hir::GenericBound<'_>],
1221         sized_by_default: SizedByDefault,
1222         span: Span,
1223     ) -> Bounds<'tcx> {
1224         let mut bounds = Bounds::default();
1225
1226         self.add_bounds(param_ty, ast_bounds, &mut bounds);
1227         bounds.trait_bounds.sort_by_key(|(t, _)| t.def_id());
1228
1229         bounds.implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
1230             if !self.is_unsized(ast_bounds, span) { Some(span) } else { None }
1231         } else {
1232             None
1233         };
1234
1235         bounds
1236     }
1237
1238     /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1239     /// onto `bounds`.
1240     ///
1241     /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1242     /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1243     /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1244     fn add_predicates_for_ast_type_binding(
1245         &self,
1246         hir_ref_id: hir::HirId,
1247         trait_ref: ty::PolyTraitRef<'tcx>,
1248         binding: &ConvertedBinding<'_, 'tcx>,
1249         bounds: &mut Bounds<'tcx>,
1250         speculative: bool,
1251         dup_bindings: &mut FxHashMap<DefId, Span>,
1252         path_span: Span,
1253     ) -> Result<(), ErrorReported> {
1254         let tcx = self.tcx();
1255
1256         if !speculative {
1257             // Given something like `U: SomeTrait<T = X>`, we want to produce a
1258             // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1259             // subtle in the event that `T` is defined in a supertrait of
1260             // `SomeTrait`, because in that case we need to upcast.
1261             //
1262             // That is, consider this case:
1263             //
1264             // ```
1265             // trait SubTrait: SuperTrait<int> { }
1266             // trait SuperTrait<A> { type T; }
1267             //
1268             // ... B: SubTrait<T = foo> ...
1269             // ```
1270             //
1271             // We want to produce `<B as SuperTrait<int>>::T == foo`.
1272
1273             // Find any late-bound regions declared in `ty` that are not
1274             // declared in the trait-ref. These are not well-formed.
1275             //
1276             // Example:
1277             //
1278             //     for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1279             //     for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1280             if let ConvertedBindingKind::Equality(ty) = binding.kind {
1281                 let late_bound_in_trait_ref =
1282                     tcx.collect_constrained_late_bound_regions(&trait_ref);
1283                 let late_bound_in_ty =
1284                     tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(ty));
1285                 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
1286                 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
1287                 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
1288                     let br_name = match *br {
1289                         ty::BrNamed(_, name) => name,
1290                         _ => {
1291                             span_bug!(
1292                                 binding.span,
1293                                 "anonymous bound region {:?} in binding but not trait ref",
1294                                 br
1295                             );
1296                         }
1297                     };
1298                     struct_span_err!(
1299                         tcx.sess,
1300                         binding.span,
1301                         E0582,
1302                         "binding for associated type `{}` references lifetime `{}`, \
1303                                      which does not appear in the trait input types",
1304                         binding.item_name,
1305                         br_name
1306                     )
1307                     .emit();
1308                 }
1309             }
1310         }
1311
1312         let candidate =
1313             if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1314                 // Simple case: X is defined in the current trait.
1315                 trait_ref
1316             } else {
1317                 // Otherwise, we have to walk through the supertraits to find
1318                 // those that do.
1319                 self.one_bound_for_assoc_type(
1320                     || traits::supertraits(tcx, trait_ref),
1321                     &trait_ref.print_only_trait_path().to_string(),
1322                     binding.item_name,
1323                     path_span,
1324                     match binding.kind {
1325                         ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1326                         _ => None,
1327                     },
1328                 )?
1329             };
1330
1331         let (assoc_ident, def_scope) =
1332             tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1333         let assoc_ty = tcx
1334             .associated_items(candidate.def_id())
1335             .find(|i| i.kind == ty::AssocKind::Type && i.ident.modern() == assoc_ident)
1336             .expect("missing associated type");
1337
1338         if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
1339             let msg = format!("associated type `{}` is private", binding.item_name);
1340             tcx.sess.span_err(binding.span, &msg);
1341         }
1342         tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span);
1343
1344         if !speculative {
1345             dup_bindings
1346                 .entry(assoc_ty.def_id)
1347                 .and_modify(|prev_span| {
1348                     struct_span_err!(
1349                         self.tcx().sess,
1350                         binding.span,
1351                         E0719,
1352                         "the value of the associated type `{}` (from trait `{}`) \
1353                          is already specified",
1354                         binding.item_name,
1355                         tcx.def_path_str(assoc_ty.container.id())
1356                     )
1357                     .span_label(binding.span, "re-bound here")
1358                     .span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
1359                     .emit();
1360                 })
1361                 .or_insert(binding.span);
1362         }
1363
1364         match binding.kind {
1365             ConvertedBindingKind::Equality(ref ty) => {
1366                 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1367                 // the "projection predicate" for:
1368                 //
1369                 // `<T as Iterator>::Item = u32`
1370                 bounds.projection_bounds.push((
1371                     candidate.map_bound(|trait_ref| ty::ProjectionPredicate {
1372                         projection_ty: ty::ProjectionTy::from_ref_and_name(
1373                             tcx,
1374                             trait_ref,
1375                             binding.item_name,
1376                         ),
1377                         ty,
1378                     }),
1379                     binding.span,
1380                 ));
1381             }
1382             ConvertedBindingKind::Constraint(ast_bounds) => {
1383                 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1384                 //
1385                 // `<T as Iterator>::Item: Debug`
1386                 //
1387                 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1388                 // parameter to have a skipped binder.
1389                 let param_ty = tcx.mk_projection(assoc_ty.def_id, candidate.skip_binder().substs);
1390                 self.add_bounds(param_ty, ast_bounds, bounds);
1391             }
1392         }
1393         Ok(())
1394     }
1395
1396     fn ast_path_to_ty(
1397         &self,
1398         span: Span,
1399         did: DefId,
1400         item_segment: &hir::PathSegment<'_>,
1401     ) -> Ty<'tcx> {
1402         let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1403         self.normalize_ty(span, self.tcx().at(span).type_of(did).subst(self.tcx(), substs))
1404     }
1405
1406     fn conv_object_ty_poly_trait_ref(
1407         &self,
1408         span: Span,
1409         trait_bounds: &[hir::PolyTraitRef<'_>],
1410         lifetime: &hir::Lifetime,
1411     ) -> Ty<'tcx> {
1412         let tcx = self.tcx();
1413
1414         let mut bounds = Bounds::default();
1415         let mut potential_assoc_types = Vec::new();
1416         let dummy_self = self.tcx().types.trait_object_dummy_self;
1417         for trait_bound in trait_bounds.iter().rev() {
1418             let cur_potential_assoc_types =
1419                 self.instantiate_poly_trait_ref(trait_bound, dummy_self, &mut bounds);
1420             potential_assoc_types.extend(cur_potential_assoc_types.into_iter().flatten());
1421         }
1422
1423         // Expand trait aliases recursively and check that only one regular (non-auto) trait
1424         // is used and no 'maybe' bounds are used.
1425         let expanded_traits =
1426             traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().cloned());
1427         let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) =
1428             expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1429         if regular_traits.len() > 1 {
1430             let first_trait = &regular_traits[0];
1431             let additional_trait = &regular_traits[1];
1432             let mut err = struct_span_err!(
1433                 tcx.sess,
1434                 additional_trait.bottom().1,
1435                 E0225,
1436                 "only auto traits can be used as additional traits in a trait object"
1437             );
1438             additional_trait.label_with_exp_info(
1439                 &mut err,
1440                 "additional non-auto trait",
1441                 "additional use",
1442             );
1443             first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1444             err.emit();
1445         }
1446
1447         if regular_traits.is_empty() && auto_traits.is_empty() {
1448             span_err!(tcx.sess, span, E0224, "at least one trait is required for an object type");
1449             return tcx.types.err;
1450         }
1451
1452         // Check that there are no gross object safety violations;
1453         // most importantly, that the supertraits don't contain `Self`,
1454         // to avoid ICEs.
1455         for item in &regular_traits {
1456             let object_safety_violations =
1457                 astconv_object_safety_violations(tcx, item.trait_ref().def_id());
1458             if !object_safety_violations.is_empty() {
1459                 report_object_safety_error(
1460                     tcx,
1461                     span,
1462                     item.trait_ref().def_id(),
1463                     object_safety_violations,
1464                 )
1465                 .emit();
1466                 return tcx.types.err;
1467             }
1468         }
1469
1470         // Use a `BTreeSet` to keep output in a more consistent order.
1471         let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1472
1473         let regular_traits_refs_spans = bounds
1474             .trait_bounds
1475             .into_iter()
1476             .filter(|(trait_ref, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1477
1478         for (base_trait_ref, span) in regular_traits_refs_spans {
1479             for trait_ref in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1480                 debug!(
1481                     "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1482                     trait_ref
1483                 );
1484                 match trait_ref {
1485                     ty::Predicate::Trait(pred) => {
1486                         associated_types.entry(span).or_default().extend(
1487                             tcx.associated_items(pred.def_id())
1488                                 .filter(|item| item.kind == ty::AssocKind::Type)
1489                                 .map(|item| item.def_id),
1490                         );
1491                     }
1492                     ty::Predicate::Projection(pred) => {
1493                         // A `Self` within the original bound will be substituted with a
1494                         // `trait_object_dummy_self`, so check for that.
1495                         let references_self = pred.skip_binder().ty.walk().any(|t| t == dummy_self);
1496
1497                         // If the projection output contains `Self`, force the user to
1498                         // elaborate it explicitly to avoid a lot of complexity.
1499                         //
1500                         // The "classicaly useful" case is the following:
1501                         // ```
1502                         //     trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1503                         //         type MyOutput;
1504                         //     }
1505                         // ```
1506                         //
1507                         // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1508                         // but actually supporting that would "expand" to an infinitely-long type
1509                         // `fix $ Ï„ â†’ dyn MyTrait<MyOutput = X, Output = <Ï„ as MyTrait>::MyOutput`.
1510                         //
1511                         // Instead, we force the user to write
1512                         // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1513                         // the discussion in #56288 for alternatives.
1514                         if !references_self {
1515                             // Include projections defined on supertraits.
1516                             bounds.projection_bounds.push((pred, span));
1517                         }
1518                     }
1519                     _ => (),
1520                 }
1521             }
1522         }
1523
1524         for (projection_bound, _) in &bounds.projection_bounds {
1525             for (_, def_ids) in &mut associated_types {
1526                 def_ids.remove(&projection_bound.projection_def_id());
1527             }
1528         }
1529
1530         self.complain_about_missing_associated_types(
1531             associated_types,
1532             potential_assoc_types,
1533             trait_bounds,
1534         );
1535
1536         // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1537         // `dyn Trait + Send`.
1538         auto_traits.sort_by_key(|i| i.trait_ref().def_id());
1539         auto_traits.dedup_by_key(|i| i.trait_ref().def_id());
1540         debug!("regular_traits: {:?}", regular_traits);
1541         debug!("auto_traits: {:?}", auto_traits);
1542
1543         // Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
1544         // removing the dummy `Self` type (`trait_object_dummy_self`).
1545         let trait_ref_to_existential = |trait_ref: ty::TraitRef<'tcx>| {
1546             if trait_ref.self_ty() != dummy_self {
1547                 // FIXME: There appears to be a missing filter on top of `expand_trait_aliases`,
1548                 // which picks up non-supertraits where clauses - but also, the object safety
1549                 // completely ignores trait aliases, which could be object safety hazards. We
1550                 // `delay_span_bug` here to avoid an ICE in stable even when the feature is
1551                 // disabled. (#66420)
1552                 tcx.sess.delay_span_bug(
1553                     DUMMY_SP,
1554                     &format!(
1555                         "trait_ref_to_existential called on {:?} with non-dummy Self",
1556                         trait_ref,
1557                     ),
1558                 );
1559             }
1560             ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
1561         };
1562
1563         // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1564         let existential_trait_refs = regular_traits
1565             .iter()
1566             .map(|i| i.trait_ref().map_bound(|trait_ref| trait_ref_to_existential(trait_ref)));
1567         let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1568             bound.map_bound(|b| {
1569                 let trait_ref = trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1570                 ty::ExistentialProjection {
1571                     ty: b.ty,
1572                     item_def_id: b.projection_ty.item_def_id,
1573                     substs: trait_ref.substs,
1574                 }
1575             })
1576         });
1577
1578         // Calling `skip_binder` is okay because the predicates are re-bound.
1579         let regular_trait_predicates = existential_trait_refs
1580             .map(|trait_ref| ty::ExistentialPredicate::Trait(*trait_ref.skip_binder()));
1581         let auto_trait_predicates = auto_traits
1582             .into_iter()
1583             .map(|trait_ref| ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()));
1584         let mut v = regular_trait_predicates
1585             .chain(auto_trait_predicates)
1586             .chain(
1587                 existential_projections
1588                     .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())),
1589             )
1590             .collect::<SmallVec<[_; 8]>>();
1591         v.sort_by(|a, b| a.stable_cmp(tcx, b));
1592         v.dedup();
1593         let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1594
1595         // Use explicitly-specified region bound.
1596         let region_bound = if !lifetime.is_elided() {
1597             self.ast_region_to_region(lifetime, None)
1598         } else {
1599             self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1600                 if tcx.named_region(lifetime.hir_id).is_some() {
1601                     self.ast_region_to_region(lifetime, None)
1602                 } else {
1603                     self.re_infer(None, span).unwrap_or_else(|| {
1604                         span_err!(
1605                             tcx.sess,
1606                             span,
1607                             E0228,
1608                             "the lifetime bound for this object type cannot be deduced \
1609                              from context; please supply an explicit bound"
1610                         );
1611                         tcx.lifetimes.re_static
1612                     })
1613                 }
1614             })
1615         };
1616         debug!("region_bound: {:?}", region_bound);
1617
1618         let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1619         debug!("trait_object_type: {:?}", ty);
1620         ty
1621     }
1622
1623     /// When there are any missing associated types, emit an E0191 error and attempt to supply a
1624     /// reasonable suggestion on how to write it. For the case of multiple associated types in the
1625     /// same trait bound have the same name (as they come from different super-traits), we instead
1626     /// emit a generic note suggesting using a `where` clause to constraint instead.
1627     fn complain_about_missing_associated_types(
1628         &self,
1629         associated_types: FxHashMap<Span, BTreeSet<DefId>>,
1630         potential_assoc_types: Vec<Span>,
1631         trait_bounds: &[hir::PolyTraitRef<'_>],
1632     ) {
1633         if !associated_types.values().any(|v| v.len() > 0) {
1634             return;
1635         }
1636         let tcx = self.tcx();
1637         // FIXME: Marked `mut` so that we can replace the spans further below with a more
1638         // appropriate one, but this should be handled earlier in the span assignment.
1639         let mut associated_types: FxHashMap<Span, Vec<_>> = associated_types
1640             .into_iter()
1641             .map(|(span, def_ids)| {
1642                 (span, def_ids.into_iter().map(|did| tcx.associated_item(did)).collect())
1643             })
1644             .collect();
1645         let mut names = vec![];
1646
1647         // Account for things like `dyn Foo + 'a`, like in tests `issue-22434.rs` and
1648         // `issue-22560.rs`.
1649         let mut trait_bound_spans: Vec<Span> = vec![];
1650         for (span, items) in &associated_types {
1651             if !items.is_empty() {
1652                 trait_bound_spans.push(*span);
1653             }
1654             for assoc_item in items {
1655                 let trait_def_id = assoc_item.container.id();
1656                 names.push(format!(
1657                     "`{}` (from trait `{}`)",
1658                     assoc_item.ident,
1659                     tcx.def_path_str(trait_def_id),
1660                 ));
1661             }
1662         }
1663
1664         match (&potential_assoc_types[..], &trait_bounds) {
1665             ([], [bound]) => match &bound.trait_ref.path.segments[..] {
1666                 // FIXME: `trait_ref.path.span` can point to a full path with multiple
1667                 // segments, even though `trait_ref.path.segments` is of length `1`. Work
1668                 // around that bug here, even though it should be fixed elsewhere.
1669                 // This would otherwise cause an invalid suggestion. For an example, look at
1670                 // `src/test/ui/issues/issue-28344.rs` where instead of the following:
1671                 //
1672                 //   error[E0191]: the value of the associated type `Output`
1673                 //                 (from trait `std::ops::BitXor`) must be specified
1674                 //   --> $DIR/issue-28344.rs:4:17
1675                 //    |
1676                 // LL |     let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
1677                 //    |                 ^^^^^^ help: specify the associated type:
1678                 //    |                              `BitXor<Output = Type>`
1679                 //
1680                 // we would output:
1681                 //
1682                 //   error[E0191]: the value of the associated type `Output`
1683                 //                 (from trait `std::ops::BitXor`) must be specified
1684                 //   --> $DIR/issue-28344.rs:4:17
1685                 //    |
1686                 // LL |     let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
1687                 //    |                 ^^^^^^^^^^^^^ help: specify the associated type:
1688                 //    |                                     `BitXor::bitor<Output = Type>`
1689                 [segment] if segment.args.is_none() => {
1690                     trait_bound_spans = vec![segment.ident.span];
1691                     associated_types = associated_types
1692                         .into_iter()
1693                         .map(|(_, items)| (segment.ident.span, items))
1694                         .collect();
1695                 }
1696                 _ => {}
1697             },
1698             _ => {}
1699         }
1700         names.sort();
1701         trait_bound_spans.sort();
1702         let mut err = struct_span_err!(
1703             tcx.sess,
1704             trait_bound_spans,
1705             E0191,
1706             "the value of the associated type{} {} must be specified",
1707             pluralize!(names.len()),
1708             names.join(", "),
1709         );
1710         let mut suggestions = vec![];
1711         let mut types_count = 0;
1712         let mut where_constraints = vec![];
1713         for (span, assoc_items) in &associated_types {
1714             let mut names: FxHashMap<_, usize> = FxHashMap::default();
1715             for item in assoc_items {
1716                 types_count += 1;
1717                 *names.entry(item.ident.name).or_insert(0) += 1;
1718             }
1719             let mut dupes = false;
1720             for item in assoc_items {
1721                 let prefix = if names[&item.ident.name] > 1 {
1722                     let trait_def_id = item.container.id();
1723                     dupes = true;
1724                     format!("{}::", tcx.def_path_str(trait_def_id))
1725                 } else {
1726                     String::new()
1727                 };
1728                 if let Some(sp) = tcx.hir().span_if_local(item.def_id) {
1729                     err.span_label(sp, format!("`{}{}` defined here", prefix, item.ident));
1730                 }
1731             }
1732             if potential_assoc_types.len() == assoc_items.len() {
1733                 // Only suggest when the amount of missing associated types equals the number of
1734                 // extra type arguments present, as that gives us a relatively high confidence
1735                 // that the user forgot to give the associtated type's name. The canonical
1736                 // example would be trying to use `Iterator<isize>` instead of
1737                 // `Iterator<Item = isize>`.
1738                 for (potential, item) in potential_assoc_types.iter().zip(assoc_items.iter()) {
1739                     if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(*potential) {
1740                         suggestions.push((*potential, format!("{} = {}", item.ident, snippet)));
1741                     }
1742                 }
1743             } else if let (Ok(snippet), false) =
1744                 (tcx.sess.source_map().span_to_snippet(*span), dupes)
1745             {
1746                 let types: Vec<_> =
1747                     assoc_items.iter().map(|item| format!("{} = Type", item.ident)).collect();
1748                 let code = if snippet.ends_with(">") {
1749                     // The user wrote `Trait<'a>` or similar and we don't have a type we can
1750                     // suggest, but at least we can clue them to the correct syntax
1751                     // `Trait<'a, Item = Type>` while accounting for the `<'a>` in the
1752                     // suggestion.
1753                     format!("{}, {}>", &snippet[..snippet.len() - 1], types.join(", "))
1754                 } else {
1755                     // The user wrote `Iterator`, so we don't have a type we can suggest, but at
1756                     // least we can clue them to the correct syntax `Iterator<Item = Type>`.
1757                     format!("{}<{}>", snippet, types.join(", "))
1758                 };
1759                 suggestions.push((*span, code));
1760             } else if dupes {
1761                 where_constraints.push(*span);
1762             }
1763         }
1764         let where_msg = "consider introducing a new type parameter, adding `where` constraints \
1765                          using the fully-qualified path to the associated types";
1766         if !where_constraints.is_empty() && suggestions.is_empty() {
1767             // If there are duplicates associated type names and a single trait bound do not
1768             // use structured suggestion, it means that there are multiple super-traits with
1769             // the same associated type name.
1770             err.help(where_msg);
1771         }
1772         if suggestions.len() != 1 {
1773             // We don't need this label if there's an inline suggestion, show otherwise.
1774             for (span, assoc_items) in &associated_types {
1775                 let mut names: FxHashMap<_, usize> = FxHashMap::default();
1776                 for item in assoc_items {
1777                     types_count += 1;
1778                     *names.entry(item.ident.name).or_insert(0) += 1;
1779                 }
1780                 let mut label = vec![];
1781                 for item in assoc_items {
1782                     let postfix = if names[&item.ident.name] > 1 {
1783                         let trait_def_id = item.container.id();
1784                         format!(" (from trait `{}`)", tcx.def_path_str(trait_def_id))
1785                     } else {
1786                         String::new()
1787                     };
1788                     label.push(format!("`{}`{}", item.ident, postfix));
1789                 }
1790                 if !label.is_empty() {
1791                     err.span_label(
1792                         *span,
1793                         format!(
1794                             "associated type{} {} must be specified",
1795                             pluralize!(label.len()),
1796                             label.join(", "),
1797                         ),
1798                     );
1799                 }
1800             }
1801         }
1802         if !suggestions.is_empty() {
1803             err.multipart_suggestion(
1804                 &format!("specify the associated type{}", pluralize!(types_count)),
1805                 suggestions,
1806                 Applicability::HasPlaceholders,
1807             );
1808             if !where_constraints.is_empty() {
1809                 err.span_help(where_constraints, where_msg);
1810             }
1811         }
1812         err.emit();
1813     }
1814
1815     fn report_ambiguous_associated_type(
1816         &self,
1817         span: Span,
1818         type_str: &str,
1819         trait_str: &str,
1820         name: ast::Name,
1821     ) {
1822         let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1823         if let (Some(_), Ok(snippet)) = (
1824             self.tcx().sess.confused_type_with_std_module.borrow().get(&span),
1825             self.tcx().sess.source_map().span_to_snippet(span),
1826         ) {
1827             err.span_suggestion(
1828                 span,
1829                 "you are looking for the module in `std`, not the primitive type",
1830                 format!("std::{}", snippet),
1831                 Applicability::MachineApplicable,
1832             );
1833         } else {
1834             err.span_suggestion(
1835                 span,
1836                 "use fully-qualified syntax",
1837                 format!("<{} as {}>::{}", type_str, trait_str, name),
1838                 Applicability::HasPlaceholders,
1839             );
1840         }
1841         err.emit();
1842     }
1843
1844     // Search for a bound on a type parameter which includes the associated item
1845     // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1846     // This function will fail if there are no suitable bounds or there is
1847     // any ambiguity.
1848     fn find_bound_for_assoc_item(
1849         &self,
1850         ty_param_def_id: DefId,
1851         assoc_name: ast::Ident,
1852         span: Span,
1853     ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported> {
1854         let tcx = self.tcx();
1855
1856         debug!(
1857             "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
1858             ty_param_def_id, assoc_name, span,
1859         );
1860
1861         let predicates = &self.get_type_parameter_bounds(span, ty_param_def_id).predicates;
1862
1863         debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1864
1865         let param_hir_id = tcx.hir().as_local_hir_id(ty_param_def_id).unwrap();
1866         let param_name = tcx.hir().ty_param_name(param_hir_id);
1867         self.one_bound_for_assoc_type(
1868             || {
1869                 traits::transitive_bounds(
1870                     tcx,
1871                     predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref()),
1872                 )
1873             },
1874             &param_name.as_str(),
1875             assoc_name,
1876             span,
1877             None,
1878         )
1879     }
1880
1881     // Checks that `bounds` contains exactly one element and reports appropriate
1882     // errors otherwise.
1883     fn one_bound_for_assoc_type<I>(
1884         &self,
1885         all_candidates: impl Fn() -> I,
1886         ty_param_name: &str,
1887         assoc_name: ast::Ident,
1888         span: Span,
1889         is_equality: Option<String>,
1890     ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1891     where
1892         I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1893     {
1894         let mut matching_candidates = all_candidates()
1895             .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
1896
1897         let bound = match matching_candidates.next() {
1898             Some(bound) => bound,
1899             None => {
1900                 self.complain_about_assoc_type_not_found(
1901                     all_candidates,
1902                     ty_param_name,
1903                     assoc_name,
1904                     span,
1905                 );
1906                 return Err(ErrorReported);
1907             }
1908         };
1909
1910         debug!("one_bound_for_assoc_type: bound = {:?}", bound);
1911
1912         if let Some(bound2) = matching_candidates.next() {
1913             debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2);
1914
1915             let bounds = iter::once(bound).chain(iter::once(bound2)).chain(matching_candidates);
1916             let mut err = if is_equality.is_some() {
1917                 // More specific Error Index entry.
1918                 struct_span_err!(
1919                     self.tcx().sess,
1920                     span,
1921                     E0222,
1922                     "ambiguous associated type `{}` in bounds of `{}`",
1923                     assoc_name,
1924                     ty_param_name
1925                 )
1926             } else {
1927                 struct_span_err!(
1928                     self.tcx().sess,
1929                     span,
1930                     E0221,
1931                     "ambiguous associated type `{}` in bounds of `{}`",
1932                     assoc_name,
1933                     ty_param_name
1934                 )
1935             };
1936             err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1937
1938             let mut where_bounds = vec![];
1939             for bound in bounds {
1940                 let bound_span = self
1941                     .tcx()
1942                     .associated_items(bound.def_id())
1943                     .find(|item| {
1944                         item.kind == ty::AssocKind::Type
1945                             && self.tcx().hygienic_eq(assoc_name, item.ident, bound.def_id())
1946                     })
1947                     .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1948
1949                 if let Some(bound_span) = bound_span {
1950                     err.span_label(
1951                         bound_span,
1952                         format!(
1953                             "ambiguous `{}` from `{}`",
1954                             assoc_name,
1955                             bound.print_only_trait_path(),
1956                         ),
1957                     );
1958                     if let Some(constraint) = &is_equality {
1959                         where_bounds.push(format!(
1960                             "        T: {trait}::{assoc} = {constraint}",
1961                             trait=bound.print_only_trait_path(),
1962                             assoc=assoc_name,
1963                             constraint=constraint,
1964                         ));
1965                     } else {
1966                         err.span_suggestion(
1967                             span,
1968                             "use fully qualified syntax to disambiguate",
1969                             format!(
1970                                 "<{} as {}>::{}",
1971                                 ty_param_name,
1972                                 bound.print_only_trait_path(),
1973                                 assoc_name,
1974                             ),
1975                             Applicability::MaybeIncorrect,
1976                         );
1977                     }
1978                 } else {
1979                     err.note(&format!(
1980                         "associated type `{}` could derive from `{}`",
1981                         ty_param_name,
1982                         bound.print_only_trait_path(),
1983                     ));
1984                 }
1985             }
1986             if !where_bounds.is_empty() {
1987                 err.help(&format!(
1988                     "consider introducing a new type parameter `T` and adding `where` constraints:\
1989                      \n    where\n        T: {},\n{}",
1990                     ty_param_name,
1991                     where_bounds.join(",\n"),
1992                 ));
1993             }
1994             err.emit();
1995             if !where_bounds.is_empty() {
1996                 return Err(ErrorReported);
1997             }
1998         }
1999         return Ok(bound);
2000     }
2001
2002     fn complain_about_assoc_type_not_found<I>(
2003         &self,
2004         all_candidates: impl Fn() -> I,
2005         ty_param_name: &str,
2006         assoc_name: ast::Ident,
2007         span: Span,
2008     ) where
2009         I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
2010     {
2011         // The fallback span is needed because `assoc_name` might be an `Fn()`'s `Output` without a
2012         // valid span, so we point at the whole path segment instead.
2013         let span = if assoc_name.span != DUMMY_SP { assoc_name.span } else { span };
2014         let mut err = struct_span_err!(
2015             self.tcx().sess,
2016             span,
2017             E0220,
2018             "associated type `{}` not found for `{}`",
2019             assoc_name,
2020             ty_param_name
2021         );
2022
2023         let all_candidate_names: Vec<_> = all_candidates()
2024             .map(|r| self.tcx().associated_items(r.def_id()))
2025             .flatten()
2026             .filter_map(
2027                 |item| if item.kind == ty::AssocKind::Type { Some(item.ident.name) } else { None },
2028             )
2029             .collect();
2030
2031         if let (Some(suggested_name), true) = (
2032             find_best_match_for_name(all_candidate_names.iter(), &assoc_name.as_str(), None),
2033             assoc_name.span != DUMMY_SP,
2034         ) {
2035             err.span_suggestion(
2036                 assoc_name.span,
2037                 "there is an associated type with a similar name",
2038                 suggested_name.to_string(),
2039                 Applicability::MaybeIncorrect,
2040             );
2041         } else {
2042             err.span_label(span, format!("associated type `{}` not found", assoc_name));
2043         }
2044
2045         err.emit();
2046     }
2047
2048     // Create a type from a path to an associated type.
2049     // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
2050     // and item_segment is the path segment for `D`. We return a type and a def for
2051     // the whole path.
2052     // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
2053     // parameter or `Self`.
2054     pub fn associated_path_to_ty(
2055         &self,
2056         hir_ref_id: hir::HirId,
2057         span: Span,
2058         qself_ty: Ty<'tcx>,
2059         qself_res: Res,
2060         assoc_segment: &hir::PathSegment<'_>,
2061         permit_variants: bool,
2062     ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> {
2063         let tcx = self.tcx();
2064         let assoc_ident = assoc_segment.ident;
2065
2066         debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
2067
2068         // Check if we have an enum variant.
2069         let mut variant_resolution = None;
2070         if let ty::Adt(adt_def, _) = qself_ty.kind {
2071             if adt_def.is_enum() {
2072                 let variant_def = adt_def
2073                     .variants
2074                     .iter()
2075                     .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did));
2076                 if let Some(variant_def) = variant_def {
2077                     if permit_variants {
2078                         tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span);
2079                         self.prohibit_generics(slice::from_ref(assoc_segment));
2080                         return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
2081                     } else {
2082                         variant_resolution = Some(variant_def.def_id);
2083                     }
2084                 }
2085             }
2086         }
2087
2088         // Find the type of the associated item, and the trait where the associated
2089         // item is declared.
2090         let bound = match (&qself_ty.kind, qself_res) {
2091             (_, Res::SelfTy(Some(_), Some(impl_def_id))) => {
2092                 // `Self` in an impl of a trait -- we have a concrete self type and a
2093                 // trait reference.
2094                 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
2095                     Some(trait_ref) => trait_ref,
2096                     None => {
2097                         // A cycle error occurred, most likely.
2098                         return Err(ErrorReported);
2099                     }
2100                 };
2101
2102                 self.one_bound_for_assoc_type(
2103                     || traits::supertraits(tcx, ty::Binder::bind(trait_ref)),
2104                     "Self",
2105                     assoc_ident,
2106                     span,
2107                     None,
2108                 )?
2109             }
2110             (&ty::Param(_), Res::SelfTy(Some(param_did), None))
2111             | (&ty::Param(_), Res::Def(DefKind::TyParam, param_did)) => {
2112                 self.find_bound_for_assoc_item(param_did, assoc_ident, span)?
2113             }
2114             _ => {
2115                 if variant_resolution.is_some() {
2116                     // Variant in type position
2117                     let msg = format!("expected type, found variant `{}`", assoc_ident);
2118                     tcx.sess.span_err(span, &msg);
2119                 } else if qself_ty.is_enum() {
2120                     let mut err = tcx.sess.struct_span_err(
2121                         assoc_ident.span,
2122                         &format!("no variant `{}` in enum `{}`", assoc_ident, qself_ty),
2123                     );
2124
2125                     let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
2126                     if let Some(suggested_name) = find_best_match_for_name(
2127                         adt_def.variants.iter().map(|variant| &variant.ident.name),
2128                         &assoc_ident.as_str(),
2129                         None,
2130                     ) {
2131                         err.span_suggestion(
2132                             assoc_ident.span,
2133                             "there is a variant with a similar name",
2134                             suggested_name.to_string(),
2135                             Applicability::MaybeIncorrect,
2136                         );
2137                     } else {
2138                         err.span_label(
2139                             assoc_ident.span,
2140                             format!("variant not found in `{}`", qself_ty),
2141                         );
2142                     }
2143
2144                     if let Some(sp) = tcx.hir().span_if_local(adt_def.did) {
2145                         let sp = tcx.sess.source_map().def_span(sp);
2146                         err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
2147                     }
2148
2149                     err.emit();
2150                 } else if !qself_ty.references_error() {
2151                     // Don't print `TyErr` to the user.
2152                     self.report_ambiguous_associated_type(
2153                         span,
2154                         &qself_ty.to_string(),
2155                         "Trait",
2156                         assoc_ident.name,
2157                     );
2158                 }
2159                 return Err(ErrorReported);
2160             }
2161         };
2162
2163         let trait_did = bound.def_id();
2164         let (assoc_ident, def_scope) =
2165             tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
2166         let item = tcx
2167             .associated_items(trait_did)
2168             .find(|i| Namespace::from(i.kind) == Namespace::Type && i.ident.modern() == assoc_ident)
2169             .expect("missing associated type");
2170
2171         let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);
2172         let ty = self.normalize_ty(span, ty);
2173
2174         let kind = DefKind::AssocTy;
2175         if !item.vis.is_accessible_from(def_scope, tcx) {
2176             let msg = format!("{} `{}` is private", kind.descr(item.def_id), assoc_ident);
2177             tcx.sess.span_err(span, &msg);
2178         }
2179         tcx.check_stability(item.def_id, Some(hir_ref_id), span);
2180
2181         if let Some(variant_def_id) = variant_resolution {
2182             let mut err = tcx.struct_span_lint_hir(
2183                 AMBIGUOUS_ASSOCIATED_ITEMS,
2184                 hir_ref_id,
2185                 span,
2186                 "ambiguous associated item",
2187             );
2188
2189             let mut could_refer_to = |kind: DefKind, def_id, also| {
2190                 let note_msg = format!(
2191                     "`{}` could{} refer to {} defined here",
2192                     assoc_ident,
2193                     also,
2194                     kind.descr(def_id)
2195                 );
2196                 err.span_note(tcx.def_span(def_id), &note_msg);
2197             };
2198             could_refer_to(DefKind::Variant, variant_def_id, "");
2199             could_refer_to(kind, item.def_id, " also");
2200
2201             err.span_suggestion(
2202                 span,
2203                 "use fully-qualified syntax",
2204                 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
2205                 Applicability::MachineApplicable,
2206             )
2207             .emit();
2208         }
2209
2210         Ok((ty, kind, item.def_id))
2211     }
2212
2213     fn qpath_to_ty(
2214         &self,
2215         span: Span,
2216         opt_self_ty: Option<Ty<'tcx>>,
2217         item_def_id: DefId,
2218         trait_segment: &hir::PathSegment<'_>,
2219         item_segment: &hir::PathSegment<'_>,
2220     ) -> Ty<'tcx> {
2221         let tcx = self.tcx();
2222
2223         let trait_def_id = tcx.parent(item_def_id).unwrap();
2224
2225         debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
2226
2227         let self_ty = if let Some(ty) = opt_self_ty {
2228             ty
2229         } else {
2230             let path_str = tcx.def_path_str(trait_def_id);
2231
2232             let def_id = self.item_def_id();
2233
2234             debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
2235
2236             let parent_def_id = def_id
2237                 .and_then(|def_id| tcx.hir().as_local_hir_id(def_id))
2238                 .map(|hir_id| tcx.hir().get_parent_did(hir_id));
2239
2240             debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
2241
2242             // If the trait in segment is the same as the trait defining the item,
2243             // use the `<Self as ..>` syntax in the error.
2244             let is_part_of_self_trait_constraints = def_id == Some(trait_def_id);
2245             let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
2246
2247             let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
2248                 "Self"
2249             } else {
2250                 "Type"
2251             };
2252
2253             self.report_ambiguous_associated_type(
2254                 span,
2255                 type_name,
2256                 &path_str,
2257                 item_segment.ident.name,
2258             );
2259             return tcx.types.err;
2260         };
2261
2262         debug!("qpath_to_ty: self_type={:?}", self_ty);
2263
2264         let trait_ref = self.ast_path_to_mono_trait_ref(span, trait_def_id, self_ty, trait_segment);
2265
2266         let item_substs = self.create_substs_for_associated_item(
2267             tcx,
2268             span,
2269             item_def_id,
2270             item_segment,
2271             trait_ref.substs,
2272         );
2273
2274         debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
2275
2276         self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
2277     }
2278
2279     pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment<'a>>>(
2280         &self,
2281         segments: T,
2282     ) -> bool {
2283         let mut has_err = false;
2284         for segment in segments {
2285             let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
2286             for arg in segment.generic_args().args {
2287                 let (span, kind) = match arg {
2288                     hir::GenericArg::Lifetime(lt) => {
2289                         if err_for_lt {
2290                             continue;
2291                         }
2292                         err_for_lt = true;
2293                         has_err = true;
2294                         (lt.span, "lifetime")
2295                     }
2296                     hir::GenericArg::Type(ty) => {
2297                         if err_for_ty {
2298                             continue;
2299                         }
2300                         err_for_ty = true;
2301                         has_err = true;
2302                         (ty.span, "type")
2303                     }
2304                     hir::GenericArg::Const(ct) => {
2305                         if err_for_ct {
2306                             continue;
2307                         }
2308                         err_for_ct = true;
2309                         (ct.span, "const")
2310                     }
2311                 };
2312                 let mut err = struct_span_err!(
2313                     self.tcx().sess,
2314                     span,
2315                     E0109,
2316                     "{} arguments are not allowed for this type",
2317                     kind,
2318                 );
2319                 err.span_label(span, format!("{} argument not allowed", kind));
2320                 err.emit();
2321                 if err_for_lt && err_for_ty && err_for_ct {
2322                     break;
2323                 }
2324             }
2325             for binding in segment.generic_args().bindings {
2326                 has_err = true;
2327                 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
2328                 break;
2329             }
2330         }
2331         has_err
2332     }
2333
2334     pub fn prohibit_assoc_ty_binding(tcx: TyCtxt<'_>, span: Span) {
2335         let mut err = struct_span_err!(
2336             tcx.sess,
2337             span,
2338             E0229,
2339             "associated type bindings are not allowed here"
2340         );
2341         err.span_label(span, "associated type not allowed here").emit();
2342     }
2343
2344     // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2345     pub fn def_ids_for_value_path_segments(
2346         &self,
2347         segments: &[hir::PathSegment<'_>],
2348         self_ty: Option<Ty<'tcx>>,
2349         kind: DefKind,
2350         def_id: DefId,
2351     ) -> Vec<PathSeg> {
2352         // We need to extract the type parameters supplied by the user in
2353         // the path `path`. Due to the current setup, this is a bit of a
2354         // tricky-process; the problem is that resolve only tells us the
2355         // end-point of the path resolution, and not the intermediate steps.
2356         // Luckily, we can (at least for now) deduce the intermediate steps
2357         // just from the end-point.
2358         //
2359         // There are basically five cases to consider:
2360         //
2361         // 1. Reference to a constructor of a struct:
2362         //
2363         //        struct Foo<T>(...)
2364         //
2365         //    In this case, the parameters are declared in the type space.
2366         //
2367         // 2. Reference to a constructor of an enum variant:
2368         //
2369         //        enum E<T> { Foo(...) }
2370         //
2371         //    In this case, the parameters are defined in the type space,
2372         //    but may be specified either on the type or the variant.
2373         //
2374         // 3. Reference to a fn item or a free constant:
2375         //
2376         //        fn foo<T>() { }
2377         //
2378         //    In this case, the path will again always have the form
2379         //    `a::b::foo::<T>` where only the final segment should have
2380         //    type parameters. However, in this case, those parameters are
2381         //    declared on a value, and hence are in the `FnSpace`.
2382         //
2383         // 4. Reference to a method or an associated constant:
2384         //
2385         //        impl<A> SomeStruct<A> {
2386         //            fn foo<B>(...)
2387         //        }
2388         //
2389         //    Here we can have a path like
2390         //    `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2391         //    may appear in two places. The penultimate segment,
2392         //    `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2393         //    final segment, `foo::<B>` contains parameters in fn space.
2394         //
2395         // The first step then is to categorize the segments appropriately.
2396
2397         let tcx = self.tcx();
2398
2399         assert!(!segments.is_empty());
2400         let last = segments.len() - 1;
2401
2402         let mut path_segs = vec![];
2403
2404         match kind {
2405             // Case 1. Reference to a struct constructor.
2406             DefKind::Ctor(CtorOf::Struct, ..) => {
2407                 // Everything but the final segment should have no
2408                 // parameters at all.
2409                 let generics = tcx.generics_of(def_id);
2410                 // Variant and struct constructors use the
2411                 // generics of their parent type definition.
2412                 let generics_def_id = generics.parent.unwrap_or(def_id);
2413                 path_segs.push(PathSeg(generics_def_id, last));
2414             }
2415
2416             // Case 2. Reference to a variant constructor.
2417             DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2418                 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
2419                 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
2420                     debug_assert!(adt_def.is_enum());
2421                     (adt_def.did, last)
2422                 } else if last >= 1 && segments[last - 1].args.is_some() {
2423                     // Everything but the penultimate segment should have no
2424                     // parameters at all.
2425                     let mut def_id = def_id;
2426
2427                     // `DefKind::Ctor` -> `DefKind::Variant`
2428                     if let DefKind::Ctor(..) = kind {
2429                         def_id = tcx.parent(def_id).unwrap()
2430                     }
2431
2432                     // `DefKind::Variant` -> `DefKind::Enum`
2433                     let enum_def_id = tcx.parent(def_id).unwrap();
2434                     (enum_def_id, last - 1)
2435                 } else {
2436                     // FIXME: lint here recommending `Enum::<...>::Variant` form
2437                     // instead of `Enum::Variant::<...>` form.
2438
2439                     // Everything but the final segment should have no
2440                     // parameters at all.
2441                     let generics = tcx.generics_of(def_id);
2442                     // Variant and struct constructors use the
2443                     // generics of their parent type definition.
2444                     (generics.parent.unwrap_or(def_id), last)
2445                 };
2446                 path_segs.push(PathSeg(generics_def_id, index));
2447             }
2448
2449             // Case 3. Reference to a top-level value.
2450             DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static => {
2451                 path_segs.push(PathSeg(def_id, last));
2452             }
2453
2454             // Case 4. Reference to a method or associated const.
2455             DefKind::Method | DefKind::AssocConst => {
2456                 if segments.len() >= 2 {
2457                     let generics = tcx.generics_of(def_id);
2458                     path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2459                 }
2460                 path_segs.push(PathSeg(def_id, last));
2461             }
2462
2463             kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2464         }
2465
2466         debug!("path_segs = {:?}", path_segs);
2467
2468         path_segs
2469     }
2470
2471     // Check a type `Path` and convert it to a `Ty`.
2472     pub fn res_to_ty(
2473         &self,
2474         opt_self_ty: Option<Ty<'tcx>>,
2475         path: &hir::Path<'_>,
2476         permit_variants: bool,
2477     ) -> Ty<'tcx> {
2478         let tcx = self.tcx();
2479
2480         debug!(
2481             "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2482             path.res, opt_self_ty, path.segments
2483         );
2484
2485         let span = path.span;
2486         match path.res {
2487             Res::Def(DefKind::OpaqueTy, did) => {
2488                 // Check for desugared `impl Trait`.
2489                 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2490                 let item_segment = path.segments.split_last().unwrap();
2491                 self.prohibit_generics(item_segment.1);
2492                 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2493                 self.normalize_ty(span, tcx.mk_opaque(did, substs))
2494             }
2495             Res::Def(DefKind::Enum, did)
2496             | Res::Def(DefKind::TyAlias, did)
2497             | Res::Def(DefKind::Struct, did)
2498             | Res::Def(DefKind::Union, did)
2499             | Res::Def(DefKind::ForeignTy, did) => {
2500                 assert_eq!(opt_self_ty, None);
2501                 self.prohibit_generics(path.segments.split_last().unwrap().1);
2502                 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2503             }
2504             Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2505                 // Convert "variant type" as if it were a real type.
2506                 // The resulting `Ty` is type of the variant's enum for now.
2507                 assert_eq!(opt_self_ty, None);
2508
2509                 let path_segs =
2510                     self.def_ids_for_value_path_segments(&path.segments, None, kind, def_id);
2511                 let generic_segs: FxHashSet<_> =
2512                     path_segs.iter().map(|PathSeg(_, index)| index).collect();
2513                 self.prohibit_generics(path.segments.iter().enumerate().filter_map(
2514                     |(index, seg)| {
2515                         if !generic_segs.contains(&index) { Some(seg) } else { None }
2516                     },
2517                 ));
2518
2519                 let PathSeg(def_id, index) = path_segs.last().unwrap();
2520                 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2521             }
2522             Res::Def(DefKind::TyParam, def_id) => {
2523                 assert_eq!(opt_self_ty, None);
2524                 self.prohibit_generics(path.segments);
2525
2526                 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
2527                 let item_id = tcx.hir().get_parent_node(hir_id);
2528                 let item_def_id = tcx.hir().local_def_id(item_id);
2529                 let generics = tcx.generics_of(item_def_id);
2530                 let index = generics.param_def_id_to_index[&def_id];
2531                 tcx.mk_ty_param(index, tcx.hir().name(hir_id))
2532             }
2533             Res::SelfTy(Some(_), None) => {
2534                 // `Self` in trait or type alias.
2535                 assert_eq!(opt_self_ty, None);
2536                 self.prohibit_generics(path.segments);
2537                 tcx.types.self_param
2538             }
2539             Res::SelfTy(_, Some(def_id)) => {
2540                 // `Self` in impl (we know the concrete type).
2541                 assert_eq!(opt_self_ty, None);
2542                 self.prohibit_generics(path.segments);
2543                 // Try to evaluate any array length constants.
2544                 self.normalize_ty(span, tcx.at(span).type_of(def_id))
2545             }
2546             Res::Def(DefKind::AssocTy, def_id) => {
2547                 debug_assert!(path.segments.len() >= 2);
2548                 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
2549                 self.qpath_to_ty(
2550                     span,
2551                     opt_self_ty,
2552                     def_id,
2553                     &path.segments[path.segments.len() - 2],
2554                     path.segments.last().unwrap(),
2555                 )
2556             }
2557             Res::PrimTy(prim_ty) => {
2558                 assert_eq!(opt_self_ty, None);
2559                 self.prohibit_generics(path.segments);
2560                 match prim_ty {
2561                     hir::PrimTy::Bool => tcx.types.bool,
2562                     hir::PrimTy::Char => tcx.types.char,
2563                     hir::PrimTy::Int(it) => tcx.mk_mach_int(it),
2564                     hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(uit),
2565                     hir::PrimTy::Float(ft) => tcx.mk_mach_float(ft),
2566                     hir::PrimTy::Str => tcx.mk_str(),
2567                 }
2568             }
2569             Res::Err => {
2570                 self.set_tainted_by_errors();
2571                 return self.tcx().types.err;
2572             }
2573             _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2574         }
2575     }
2576
2577     /// Parses the programmer's textual representation of a type into our
2578     /// internal notion of a type.
2579     pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2580         debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})", ast_ty.hir_id, ast_ty, ast_ty.kind);
2581
2582         let tcx = self.tcx();
2583
2584         let result_ty = match ast_ty.kind {
2585             hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(&ty)),
2586             hir::TyKind::Ptr(ref mt) => {
2587                 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(&mt.ty), mutbl: mt.mutbl })
2588             }
2589             hir::TyKind::Rptr(ref region, ref mt) => {
2590                 let r = self.ast_region_to_region(region, None);
2591                 debug!("ast_ty_to_ty: r={:?}", r);
2592                 let t = self.ast_ty_to_ty(&mt.ty);
2593                 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2594             }
2595             hir::TyKind::Never => tcx.types.never,
2596             hir::TyKind::Tup(ref fields) => {
2597                 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
2598             }
2599             hir::TyKind::BareFn(ref bf) => {
2600                 require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
2601                 tcx.mk_fn_ptr(self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl, &[], None))
2602             }
2603             hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
2604                 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
2605             }
2606             hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2607                 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
2608                 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2609                 self.res_to_ty(opt_self_ty, path, false)
2610             }
2611             hir::TyKind::Def(item_id, ref lifetimes) => {
2612                 let did = tcx.hir().local_def_id(item_id.id);
2613                 self.impl_trait_ty_to_ty(did, lifetimes)
2614             }
2615             hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2616                 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
2617                 let ty = self.ast_ty_to_ty(qself);
2618
2619                 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.kind {
2620                     path.res
2621                 } else {
2622                     Res::Err
2623                 };
2624                 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2625                     .map(|(ty, _, _)| ty)
2626                     .unwrap_or(tcx.types.err)
2627             }
2628             hir::TyKind::Array(ref ty, ref length) => {
2629                 let length = self.ast_const_to_const(length, tcx.types.usize);
2630                 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
2631                 self.normalize_ty(ast_ty.span, array_ty)
2632             }
2633             hir::TyKind::Typeof(ref _e) => {
2634                 struct_span_err!(
2635                     tcx.sess,
2636                     ast_ty.span,
2637                     E0516,
2638                     "`typeof` is a reserved keyword but unimplemented"
2639                 )
2640                 .span_label(ast_ty.span, "reserved keyword")
2641                 .emit();
2642
2643                 tcx.types.err
2644             }
2645             hir::TyKind::Infer => {
2646                 // Infer also appears as the type of arguments or return
2647                 // values in a ExprKind::Closure, or as
2648                 // the type of local variables. Both of these cases are
2649                 // handled specially and will not descend into this routine.
2650                 self.ty_infer(None, ast_ty.span)
2651             }
2652             hir::TyKind::Err => tcx.types.err,
2653         };
2654
2655         debug!("ast_ty_to_ty: result_ty={:?}", result_ty);
2656
2657         self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2658         result_ty
2659     }
2660
2661     /// Returns the `DefId` of the constant parameter that the provided expression is a path to.
2662     pub fn const_param_def_id(&self, expr: &hir::Expr<'_>) -> Option<DefId> {
2663         // Unwrap a block, so that e.g. `{ P }` is recognised as a parameter. Const arguments
2664         // currently have to be wrapped in curly brackets, so it's necessary to special-case.
2665         let expr = match &expr.kind {
2666             ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
2667                 block.expr.as_ref().unwrap()
2668             }
2669             _ => expr,
2670         };
2671
2672         match &expr.kind {
2673             ExprKind::Path(hir::QPath::Resolved(_, path)) => match path.res {
2674                 Res::Def(DefKind::ConstParam, did) => Some(did),
2675                 _ => None,
2676             },
2677             _ => None,
2678         }
2679     }
2680
2681     pub fn ast_const_to_const(
2682         &self,
2683         ast_const: &hir::AnonConst,
2684         ty: Ty<'tcx>,
2685     ) -> &'tcx ty::Const<'tcx> {
2686         debug!("ast_const_to_const(id={:?}, ast_const={:?})", ast_const.hir_id, ast_const);
2687
2688         let tcx = self.tcx();
2689         let def_id = tcx.hir().local_def_id(ast_const.hir_id);
2690
2691         let mut const_ = ty::Const {
2692             val: ty::ConstKind::Unevaluated(def_id, InternalSubsts::identity_for_item(tcx, def_id)),
2693             ty,
2694         };
2695
2696         let expr = &tcx.hir().body(ast_const.body).value;
2697         if let Some(def_id) = self.const_param_def_id(expr) {
2698             // Find the name and index of the const parameter by indexing the generics of the
2699             // parent item and construct a `ParamConst`.
2700             let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
2701             let item_id = tcx.hir().get_parent_node(hir_id);
2702             let item_def_id = tcx.hir().local_def_id(item_id);
2703             let generics = tcx.generics_of(item_def_id);
2704             let index = generics.param_def_id_to_index[&tcx.hir().local_def_id(hir_id)];
2705             let name = tcx.hir().name(hir_id);
2706             const_.val = ty::ConstKind::Param(ty::ParamConst::new(index, name));
2707         }
2708
2709         tcx.mk_const(const_)
2710     }
2711
2712     pub fn impl_trait_ty_to_ty(
2713         &self,
2714         def_id: DefId,
2715         lifetimes: &[hir::GenericArg<'_>],
2716     ) -> Ty<'tcx> {
2717         debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2718         let tcx = self.tcx();
2719
2720         let generics = tcx.generics_of(def_id);
2721
2722         debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2723         let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2724             if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2725                 // Our own parameters are the resolved lifetimes.
2726                 match param.kind {
2727                     GenericParamDefKind::Lifetime => {
2728                         if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2729                             self.ast_region_to_region(lifetime, None).into()
2730                         } else {
2731                             bug!()
2732                         }
2733                     }
2734                     _ => bug!(),
2735                 }
2736             } else {
2737                 // Replace all parent lifetimes with `'static`.
2738                 match param.kind {
2739                     GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
2740                     _ => tcx.mk_param_from_def(param),
2741                 }
2742             }
2743         });
2744         debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2745
2746         let ty = tcx.mk_opaque(def_id, substs);
2747         debug!("impl_trait_ty_to_ty: {}", ty);
2748         ty
2749     }
2750
2751     pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2752         match ty.kind {
2753             hir::TyKind::Infer if expected_ty.is_some() => {
2754                 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2755                 expected_ty.unwrap()
2756             }
2757             _ => self.ast_ty_to_ty(ty),
2758         }
2759     }
2760
2761     pub fn ty_of_fn(
2762         &self,
2763         unsafety: hir::Unsafety,
2764         abi: abi::Abi,
2765         decl: &hir::FnDecl<'_>,
2766         generic_params: &[hir::GenericParam<'_>],
2767         ident_span: Option<Span>,
2768     ) -> ty::PolyFnSig<'tcx> {
2769         debug!("ty_of_fn");
2770
2771         let tcx = self.tcx();
2772
2773         // We proactively collect all the infered type params to emit a single error per fn def.
2774         let mut visitor = PlaceholderHirTyCollector::default();
2775         for ty in decl.inputs {
2776             visitor.visit_ty(ty);
2777         }
2778         let input_tys = decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
2779         let output_ty = match decl.output {
2780             hir::FunctionRetTy::Return(ref output) => {
2781                 visitor.visit_ty(output);
2782                 self.ast_ty_to_ty(output)
2783             }
2784             hir::FunctionRetTy::DefaultReturn(..) => tcx.mk_unit(),
2785         };
2786
2787         debug!("ty_of_fn: output_ty={:?}", output_ty);
2788
2789         let bare_fn_ty =
2790             ty::Binder::bind(tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, unsafety, abi));
2791
2792         if !self.allow_ty_infer() {
2793             // We always collect the spans for placeholder types when evaluating `fn`s, but we
2794             // only want to emit an error complaining about them if infer types (`_`) are not
2795             // allowed. `allow_ty_infer` gates this behavior.
2796             crate::collect::placeholder_type_error(
2797                 tcx,
2798                 ident_span.unwrap_or(DUMMY_SP),
2799                 generic_params,
2800                 visitor.0,
2801                 ident_span.is_some(),
2802             );
2803         }
2804
2805         // Find any late-bound regions declared in return type that do
2806         // not appear in the arguments. These are not well-formed.
2807         //
2808         // Example:
2809         //     for<'a> fn() -> &'a str <-- 'a is bad
2810         //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2811         let inputs = bare_fn_ty.inputs();
2812         let late_bound_in_args =
2813             tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
2814         let output = bare_fn_ty.output();
2815         let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2816         for br in late_bound_in_ret.difference(&late_bound_in_args) {
2817             let lifetime_name = match *br {
2818                 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
2819                 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
2820             };
2821             let mut err = struct_span_err!(
2822                 tcx.sess,
2823                 decl.output.span(),
2824                 E0581,
2825                 "return type references {} \
2826                                             which is not constrained by the fn input types",
2827                 lifetime_name
2828             );
2829             if let ty::BrAnon(_) = *br {
2830                 // The only way for an anonymous lifetime to wind up
2831                 // in the return type but **also** be unconstrained is
2832                 // if it only appears in "associated types" in the
2833                 // input. See #47511 for an example. In this case,
2834                 // though we can easily give a hint that ought to be
2835                 // relevant.
2836                 err.note(
2837                     "lifetimes appearing in an associated type \
2838                           are not considered constrained",
2839                 );
2840             }
2841             err.emit();
2842         }
2843
2844         bare_fn_ty
2845     }
2846
2847     /// Given the bounds on an object, determines what single region bound (if any) we can
2848     /// use to summarize this type. The basic idea is that we will use the bound the user
2849     /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2850     /// for region bounds. It may be that we can derive no bound at all, in which case
2851     /// we return `None`.
2852     fn compute_object_lifetime_bound(
2853         &self,
2854         span: Span,
2855         existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
2856     ) -> Option<ty::Region<'tcx>> // if None, use the default
2857     {
2858         let tcx = self.tcx();
2859
2860         debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
2861
2862         // No explicit region bound specified. Therefore, examine trait
2863         // bounds and see if we can derive region bounds from those.
2864         let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
2865
2866         // If there are no derived region bounds, then report back that we
2867         // can find no region bound. The caller will use the default.
2868         if derived_region_bounds.is_empty() {
2869             return None;
2870         }
2871
2872         // If any of the derived region bounds are 'static, that is always
2873         // the best choice.
2874         if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
2875             return Some(tcx.lifetimes.re_static);
2876         }
2877
2878         // Determine whether there is exactly one unique region in the set
2879         // of derived region bounds. If so, use that. Otherwise, report an
2880         // error.
2881         let r = derived_region_bounds[0];
2882         if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2883             span_err!(
2884                 tcx.sess,
2885                 span,
2886                 E0227,
2887                 "ambiguous lifetime bound, explicit lifetime bound required"
2888             );
2889         }
2890         return Some(r);
2891     }
2892 }
2893
2894 /// Collects together a list of bounds that are applied to some type,
2895 /// after they've been converted into `ty` form (from the HIR
2896 /// representations). These lists of bounds occur in many places in
2897 /// Rust's syntax:
2898 ///
2899 /// ```
2900 /// trait Foo: Bar + Baz { }
2901 ///            ^^^^^^^^^ supertrait list bounding the `Self` type parameter
2902 ///
2903 /// fn foo<T: Bar + Baz>() { }
2904 ///           ^^^^^^^^^ bounding the type parameter `T`
2905 ///
2906 /// impl dyn Bar + Baz
2907 ///          ^^^^^^^^^ bounding the forgotten dynamic type
2908 /// ```
2909 ///
2910 /// Our representation is a bit mixed here -- in some cases, we
2911 /// include the self type (e.g., `trait_bounds`) but in others we do
2912 #[derive(Default, PartialEq, Eq, Clone, Debug)]
2913 pub struct Bounds<'tcx> {
2914     /// A list of region bounds on the (implicit) self type. So if you
2915     /// had `T: 'a + 'b` this might would be a list `['a, 'b]` (but
2916     /// the `T` is not explicitly included).
2917     pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
2918
2919     /// A list of trait bounds. So if you had `T: Debug` this would be
2920     /// `T: Debug`. Note that the self-type is explicit here.
2921     pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span)>,
2922
2923     /// A list of projection equality bounds. So if you had `T:
2924     /// Iterator<Item = u32>` this would include `<T as
2925     /// Iterator>::Item => u32`. Note that the self-type is explicit
2926     /// here.
2927     pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
2928
2929     /// `Some` if there is *no* `?Sized` predicate. The `span`
2930     /// is the location in the source of the `T` declaration which can
2931     /// be cited as the source of the `T: Sized` requirement.
2932     pub implicitly_sized: Option<Span>,
2933 }
2934
2935 impl<'tcx> Bounds<'tcx> {
2936     /// Converts a bounds list into a flat set of predicates (like
2937     /// where-clauses). Because some of our bounds listings (e.g.,
2938     /// regions) don't include the self-type, you must supply the
2939     /// self-type here (the `param_ty` parameter).
2940     pub fn predicates(
2941         &self,
2942         tcx: TyCtxt<'tcx>,
2943         param_ty: Ty<'tcx>,
2944     ) -> Vec<(ty::Predicate<'tcx>, Span)> {
2945         // If it could be sized, and is, add the `Sized` predicate.
2946         let sized_predicate = self.implicitly_sized.and_then(|span| {
2947             tcx.lang_items().sized_trait().map(|sized| {
2948                 let trait_ref = ty::Binder::bind(ty::TraitRef {
2949                     def_id: sized,
2950                     substs: tcx.mk_substs_trait(param_ty, &[]),
2951                 });
2952                 (trait_ref.to_predicate(), span)
2953             })
2954         });
2955
2956         sized_predicate
2957             .into_iter()
2958             .chain(
2959                 self.region_bounds
2960                     .iter()
2961                     .map(|&(region_bound, span)| {
2962                         // Account for the binder being introduced below; no need to shift `param_ty`
2963                         // because, at present at least, it either only refers to early-bound regions,
2964                         // or it's a generic associated type that deliberately has escaping bound vars.
2965                         let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
2966                         let outlives = ty::OutlivesPredicate(param_ty, region_bound);
2967                         (ty::Binder::bind(outlives).to_predicate(), span)
2968                     })
2969                     .chain(
2970                         self.trait_bounds
2971                             .iter()
2972                             .map(|&(bound_trait_ref, span)| (bound_trait_ref.to_predicate(), span)),
2973                     )
2974                     .chain(
2975                         self.projection_bounds
2976                             .iter()
2977                             .map(|&(projection, span)| (projection.to_predicate(), span)),
2978                     ),
2979             )
2980             .collect()
2981     }
2982 }