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