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