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