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