]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/late.rs
check if impl_self is `Some`
[rust.git] / compiler / rustc_resolve / src / late.rs
1 // ignore-tidy-filelength
2 //! "Late resolution" is the pass that resolves most of names in a crate beside imports and macros.
3 //! It runs when the crate is fully expanded and its module structure is fully built.
4 //! So it just walks through the crate and resolves all the expressions, types, etc.
5 //!
6 //! If you wonder why there's no `early.rs`, that's because it's split into three files -
7 //! `build_reduced_graph.rs`, `macros.rs` and `imports.rs`.
8
9 use RibKind::*;
10
11 use crate::{path_names_to_string, BindingError, Finalize, LexicalScopeBinding};
12 use crate::{Module, ModuleOrUniformRoot, NameBinding, ParentScope, PathResult};
13 use crate::{ResolutionError, Resolver, Segment, UseError};
14
15 use rustc_ast::ptr::P;
16 use rustc_ast::visit::{self, AssocCtxt, BoundKind, FnCtxt, FnKind, Visitor};
17 use rustc_ast::*;
18 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
19 use rustc_errors::DiagnosticId;
20 use rustc_hir::def::Namespace::{self, *};
21 use rustc_hir::def::{self, CtorKind, DefKind, LifetimeRes, PartialRes, PerNS};
22 use rustc_hir::def_id::{DefId, LocalDefId, CRATE_DEF_ID, LOCAL_CRATE};
23 use rustc_hir::{BindingAnnotation, PrimTy, TraitCandidate};
24 use rustc_middle::middle::resolve_lifetime::Set1;
25 use rustc_middle::ty::DefIdTree;
26 use rustc_middle::{bug, span_bug};
27 use rustc_session::lint;
28 use rustc_span::symbol::{kw, sym, Ident, Symbol};
29 use rustc_span::{BytePos, Span};
30 use smallvec::{smallvec, SmallVec};
31
32 use rustc_span::source_map::{respan, Spanned};
33 use std::collections::{hash_map::Entry, BTreeSet};
34 use std::mem::{replace, take};
35
36 mod diagnostics;
37
38 type Res = def::Res<NodeId>;
39
40 type IdentMap<T> = FxHashMap<Ident, T>;
41
42 /// Map from the name in a pattern to its binding mode.
43 type BindingMap = IdentMap<BindingInfo>;
44
45 use diagnostics::{
46     ElisionFnParameter, LifetimeElisionCandidate, MissingLifetime, MissingLifetimeKind,
47 };
48
49 #[derive(Copy, Clone, Debug)]
50 struct BindingInfo {
51     span: Span,
52     annotation: BindingAnnotation,
53 }
54
55 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
56 pub enum PatternSource {
57     Match,
58     Let,
59     For,
60     FnParam,
61 }
62
63 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
64 enum IsRepeatExpr {
65     No,
66     Yes,
67 }
68
69 impl PatternSource {
70     pub fn descr(self) -> &'static str {
71         match self {
72             PatternSource::Match => "match binding",
73             PatternSource::Let => "let binding",
74             PatternSource::For => "for binding",
75             PatternSource::FnParam => "function parameter",
76         }
77     }
78 }
79
80 /// Denotes whether the context for the set of already bound bindings is a `Product`
81 /// or `Or` context. This is used in e.g., `fresh_binding` and `resolve_pattern_inner`.
82 /// See those functions for more information.
83 #[derive(PartialEq)]
84 enum PatBoundCtx {
85     /// A product pattern context, e.g., `Variant(a, b)`.
86     Product,
87     /// An or-pattern context, e.g., `p_0 | ... | p_n`.
88     Or,
89 }
90
91 /// Does this the item (from the item rib scope) allow generic parameters?
92 #[derive(Copy, Clone, Debug)]
93 pub(crate) enum HasGenericParams {
94     Yes(Span),
95     No,
96 }
97
98 /// May this constant have generics?
99 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
100 pub(crate) enum ConstantHasGenerics {
101     Yes,
102     No,
103 }
104
105 impl ConstantHasGenerics {
106     fn force_yes_if(self, b: bool) -> Self {
107         if b { Self::Yes } else { self }
108     }
109 }
110
111 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
112 pub(crate) enum ConstantItemKind {
113     Const,
114     Static,
115 }
116
117 /// The rib kind restricts certain accesses,
118 /// e.g. to a `Res::Local` of an outer item.
119 #[derive(Copy, Clone, Debug)]
120 pub(crate) enum RibKind<'a> {
121     /// No restriction needs to be applied.
122     NormalRibKind,
123
124     /// We passed through an impl or trait and are now in one of its
125     /// methods or associated types. Allow references to ty params that impl or trait
126     /// binds. Disallow any other upvars (including other ty params that are
127     /// upvars).
128     AssocItemRibKind,
129
130     /// We passed through a closure. Disallow labels.
131     ClosureOrAsyncRibKind,
132
133     /// We passed through an item scope. Disallow upvars.
134     ItemRibKind(HasGenericParams),
135
136     /// We're in a constant item. Can't refer to dynamic stuff.
137     ///
138     /// The item may reference generic parameters in trivial constant expressions.
139     /// All other constants aren't allowed to use generic params at all.
140     ConstantItemRibKind(ConstantHasGenerics, Option<(Ident, ConstantItemKind)>),
141
142     /// We passed through a module.
143     ModuleRibKind(Module<'a>),
144
145     /// We passed through a `macro_rules!` statement
146     MacroDefinition(DefId),
147
148     /// All bindings in this rib are generic parameters that can't be used
149     /// from the default of a generic parameter because they're not declared
150     /// before said generic parameter. Also see the `visit_generics` override.
151     ForwardGenericParamBanRibKind,
152
153     /// We are inside of the type of a const parameter. Can't refer to any
154     /// parameters.
155     ConstParamTyRibKind,
156
157     /// We are inside a `sym` inline assembly operand. Can only refer to
158     /// globals.
159     InlineAsmSymRibKind,
160 }
161
162 impl RibKind<'_> {
163     /// Whether this rib kind contains generic parameters, as opposed to local
164     /// variables.
165     pub(crate) fn contains_params(&self) -> bool {
166         match self {
167             NormalRibKind
168             | ClosureOrAsyncRibKind
169             | ConstantItemRibKind(..)
170             | ModuleRibKind(_)
171             | MacroDefinition(_)
172             | ConstParamTyRibKind
173             | InlineAsmSymRibKind => false,
174             AssocItemRibKind | ItemRibKind(_) | ForwardGenericParamBanRibKind => true,
175         }
176     }
177
178     /// This rib forbids referring to labels defined in upwards ribs.
179     fn is_label_barrier(self) -> bool {
180         match self {
181             NormalRibKind | MacroDefinition(..) => false,
182
183             AssocItemRibKind
184             | ClosureOrAsyncRibKind
185             | ItemRibKind(..)
186             | ConstantItemRibKind(..)
187             | ModuleRibKind(..)
188             | ForwardGenericParamBanRibKind
189             | ConstParamTyRibKind
190             | InlineAsmSymRibKind => true,
191         }
192     }
193 }
194
195 /// A single local scope.
196 ///
197 /// A rib represents a scope names can live in. Note that these appear in many places, not just
198 /// around braces. At any place where the list of accessible names (of the given namespace)
199 /// changes or a new restrictions on the name accessibility are introduced, a new rib is put onto a
200 /// stack. This may be, for example, a `let` statement (because it introduces variables), a macro,
201 /// etc.
202 ///
203 /// Different [rib kinds](enum@RibKind) are transparent for different names.
204 ///
205 /// The resolution keeps a separate stack of ribs as it traverses the AST for each namespace. When
206 /// resolving, the name is looked up from inside out.
207 #[derive(Debug)]
208 pub(crate) struct Rib<'a, R = Res> {
209     pub bindings: IdentMap<R>,
210     pub kind: RibKind<'a>,
211 }
212
213 impl<'a, R> Rib<'a, R> {
214     fn new(kind: RibKind<'a>) -> Rib<'a, R> {
215         Rib { bindings: Default::default(), kind }
216     }
217 }
218
219 #[derive(Clone, Copy, Debug)]
220 enum LifetimeUseSet {
221     One { use_span: Span, use_ctxt: visit::LifetimeCtxt },
222     Many,
223 }
224
225 #[derive(Copy, Clone, Debug)]
226 enum LifetimeRibKind {
227     /// This rib acts as a barrier to forbid reference to lifetimes of a parent item.
228     Item,
229
230     /// This rib declares generic parameters.
231     Generics { binder: NodeId, span: Span, kind: LifetimeBinderKind },
232
233     /// FIXME(const_generics): This patches over an ICE caused by non-'static lifetimes in const
234     /// generics. We are disallowing this until we can decide on how we want to handle non-'static
235     /// lifetimes in const generics. See issue #74052 for discussion.
236     ConstGeneric,
237
238     /// Non-static lifetimes are prohibited in anonymous constants under `min_const_generics`.
239     /// This function will emit an error if `generic_const_exprs` is not enabled, the body identified by
240     /// `body_id` is an anonymous constant and `lifetime_ref` is non-static.
241     AnonConst,
242
243     /// Create a new anonymous lifetime parameter and reference it.
244     ///
245     /// If `report_in_path`, report an error when encountering lifetime elision in a path:
246     /// ```compile_fail
247     /// struct Foo<'a> { x: &'a () }
248     /// async fn foo(x: Foo) {}
249     /// ```
250     ///
251     /// Note: the error should not trigger when the elided lifetime is in a pattern or
252     /// expression-position path:
253     /// ```
254     /// struct Foo<'a> { x: &'a () }
255     /// async fn foo(Foo { x: _ }: Foo<'_>) {}
256     /// ```
257     AnonymousCreateParameter { binder: NodeId, report_in_path: bool },
258
259     /// Give a hard error when either `&` or `'_` is written. Used to
260     /// rule out things like `where T: Foo<'_>`. Does not imply an
261     /// error on default object bounds (e.g., `Box<dyn Foo>`).
262     AnonymousReportError,
263
264     /// Replace all anonymous lifetimes by provided lifetime.
265     Elided(LifetimeRes),
266
267     /// Signal we cannot find which should be the anonymous lifetime.
268     ElisionFailure,
269 }
270
271 #[derive(Copy, Clone, Debug)]
272 enum LifetimeBinderKind {
273     BareFnType,
274     PolyTrait,
275     WhereBound,
276     Item,
277     Function,
278     Closure,
279     ImplBlock,
280 }
281
282 impl LifetimeBinderKind {
283     fn descr(self) -> &'static str {
284         use LifetimeBinderKind::*;
285         match self {
286             BareFnType => "type",
287             PolyTrait => "bound",
288             WhereBound => "bound",
289             Item => "item",
290             ImplBlock => "impl block",
291             Function => "function",
292             Closure => "closure",
293         }
294     }
295 }
296
297 #[derive(Debug)]
298 struct LifetimeRib {
299     kind: LifetimeRibKind,
300     // We need to preserve insertion order for async fns.
301     bindings: FxIndexMap<Ident, (NodeId, LifetimeRes)>,
302 }
303
304 impl LifetimeRib {
305     fn new(kind: LifetimeRibKind) -> LifetimeRib {
306         LifetimeRib { bindings: Default::default(), kind }
307     }
308 }
309
310 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
311 pub(crate) enum AliasPossibility {
312     No,
313     Maybe,
314 }
315
316 #[derive(Copy, Clone, Debug)]
317 pub(crate) enum PathSource<'a> {
318     // Type paths `Path`.
319     Type,
320     // Trait paths in bounds or impls.
321     Trait(AliasPossibility),
322     // Expression paths `path`, with optional parent context.
323     Expr(Option<&'a Expr>),
324     // Paths in path patterns `Path`.
325     Pat,
326     // Paths in struct expressions and patterns `Path { .. }`.
327     Struct,
328     // Paths in tuple struct patterns `Path(..)`.
329     TupleStruct(Span, &'a [Span]),
330     // `m::A::B` in `<T as m::A>::B::C`.
331     TraitItem(Namespace),
332 }
333
334 impl<'a> PathSource<'a> {
335     fn namespace(self) -> Namespace {
336         match self {
337             PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS,
338             PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct(..) => ValueNS,
339             PathSource::TraitItem(ns) => ns,
340         }
341     }
342
343     fn defer_to_typeck(self) -> bool {
344         match self {
345             PathSource::Type
346             | PathSource::Expr(..)
347             | PathSource::Pat
348             | PathSource::Struct
349             | PathSource::TupleStruct(..) => true,
350             PathSource::Trait(_) | PathSource::TraitItem(..) => false,
351         }
352     }
353
354     fn descr_expected(self) -> &'static str {
355         match &self {
356             PathSource::Type => "type",
357             PathSource::Trait(_) => "trait",
358             PathSource::Pat => "unit struct, unit variant or constant",
359             PathSource::Struct => "struct, variant or union type",
360             PathSource::TupleStruct(..) => "tuple struct or tuple variant",
361             PathSource::TraitItem(ns) => match ns {
362                 TypeNS => "associated type",
363                 ValueNS => "method or associated constant",
364                 MacroNS => bug!("associated macro"),
365             },
366             PathSource::Expr(parent) => match parent.as_ref().map(|p| &p.kind) {
367                 // "function" here means "anything callable" rather than `DefKind::Fn`,
368                 // this is not precise but usually more helpful than just "value".
369                 Some(ExprKind::Call(call_expr, _)) => match &call_expr.kind {
370                     // the case of `::some_crate()`
371                     ExprKind::Path(_, path)
372                         if path.segments.len() == 2
373                             && path.segments[0].ident.name == kw::PathRoot =>
374                     {
375                         "external crate"
376                     }
377                     ExprKind::Path(_, path) => {
378                         let mut msg = "function";
379                         if let Some(segment) = path.segments.iter().last() {
380                             if let Some(c) = segment.ident.to_string().chars().next() {
381                                 if c.is_uppercase() {
382                                     msg = "function, tuple struct or tuple variant";
383                                 }
384                             }
385                         }
386                         msg
387                     }
388                     _ => "function",
389                 },
390                 _ => "value",
391             },
392         }
393     }
394
395     fn is_call(self) -> bool {
396         matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. })))
397     }
398
399     pub(crate) fn is_expected(self, res: Res) -> bool {
400         match self {
401             PathSource::Type => matches!(
402                 res,
403                 Res::Def(
404                     DefKind::Struct
405                         | DefKind::Union
406                         | DefKind::Enum
407                         | DefKind::Trait
408                         | DefKind::TraitAlias
409                         | DefKind::TyAlias
410                         | DefKind::AssocTy
411                         | DefKind::TyParam
412                         | DefKind::OpaqueTy
413                         | DefKind::ForeignTy,
414                     _,
415                 ) | Res::PrimTy(..)
416                     | Res::SelfTyParam { .. }
417                     | Res::SelfTyAlias { .. }
418             ),
419             PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)),
420             PathSource::Trait(AliasPossibility::Maybe) => {
421                 matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
422             }
423             PathSource::Expr(..) => matches!(
424                 res,
425                 Res::Def(
426                     DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn)
427                         | DefKind::Const
428                         | DefKind::Static(_)
429                         | DefKind::Fn
430                         | DefKind::AssocFn
431                         | DefKind::AssocConst
432                         | DefKind::ConstParam,
433                     _,
434                 ) | Res::Local(..)
435                     | Res::SelfCtor(..)
436             ),
437             PathSource::Pat => {
438                 res.expected_in_unit_struct_pat()
439                     || matches!(res, Res::Def(DefKind::Const | DefKind::AssocConst, _))
440             }
441             PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(),
442             PathSource::Struct => matches!(
443                 res,
444                 Res::Def(
445                     DefKind::Struct
446                         | DefKind::Union
447                         | DefKind::Variant
448                         | DefKind::TyAlias
449                         | DefKind::AssocTy,
450                     _,
451                 ) | Res::SelfTyParam { .. }
452                     | Res::SelfTyAlias { .. }
453             ),
454             PathSource::TraitItem(ns) => match res {
455                 Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true,
456                 Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true,
457                 _ => false,
458             },
459         }
460     }
461
462     fn error_code(self, has_unexpected_resolution: bool) -> DiagnosticId {
463         use rustc_errors::error_code;
464         match (self, has_unexpected_resolution) {
465             (PathSource::Trait(_), true) => error_code!(E0404),
466             (PathSource::Trait(_), false) => error_code!(E0405),
467             (PathSource::Type, true) => error_code!(E0573),
468             (PathSource::Type, false) => error_code!(E0412),
469             (PathSource::Struct, true) => error_code!(E0574),
470             (PathSource::Struct, false) => error_code!(E0422),
471             (PathSource::Expr(..), true) => error_code!(E0423),
472             (PathSource::Expr(..), false) => error_code!(E0425),
473             (PathSource::Pat | PathSource::TupleStruct(..), true) => error_code!(E0532),
474             (PathSource::Pat | PathSource::TupleStruct(..), false) => error_code!(E0531),
475             (PathSource::TraitItem(..), true) => error_code!(E0575),
476             (PathSource::TraitItem(..), false) => error_code!(E0576),
477         }
478     }
479 }
480
481 #[derive(Default)]
482 struct DiagnosticMetadata<'ast> {
483     /// The current trait's associated items' ident, used for diagnostic suggestions.
484     current_trait_assoc_items: Option<&'ast [P<AssocItem>]>,
485
486     /// The current self type if inside an impl (used for better errors).
487     current_self_type: Option<Ty>,
488
489     /// The current self item if inside an ADT (used for better errors).
490     current_self_item: Option<NodeId>,
491
492     /// The current trait (used to suggest).
493     current_item: Option<&'ast Item>,
494
495     /// When processing generics and encountering a type not found, suggest introducing a type
496     /// param.
497     currently_processing_generics: bool,
498
499     /// The current enclosing (non-closure) function (used for better errors).
500     current_function: Option<(FnKind<'ast>, Span)>,
501
502     /// A list of labels as of yet unused. Labels will be removed from this map when
503     /// they are used (in a `break` or `continue` statement)
504     unused_labels: FxHashMap<NodeId, Span>,
505
506     /// Only used for better errors on `fn(): fn()`.
507     current_type_ascription: Vec<Span>,
508
509     /// Only used for better errors on `let x = { foo: bar };`.
510     /// In the case of a parse error with `let x = { foo: bar, };`, this isn't needed, it's only
511     /// needed for cases where this parses as a correct type ascription.
512     current_block_could_be_bare_struct_literal: Option<Span>,
513
514     /// Only used for better errors on `let <pat>: <expr, not type>;`.
515     current_let_binding: Option<(Span, Option<Span>, Option<Span>)>,
516
517     /// Used to detect possible `if let` written without `let` and to provide structured suggestion.
518     in_if_condition: Option<&'ast Expr>,
519
520     /// If we are currently in a trait object definition. Used to point at the bounds when
521     /// encountering a struct or enum.
522     current_trait_object: Option<&'ast [ast::GenericBound]>,
523
524     /// Given `where <T as Bar>::Baz: String`, suggest `where T: Bar<Baz = String>`.
525     current_where_predicate: Option<&'ast WherePredicate>,
526
527     current_type_path: Option<&'ast Ty>,
528
529     /// The current impl items (used to suggest).
530     current_impl_items: Option<&'ast [P<AssocItem>]>,
531
532     /// When processing impl trait
533     currently_processing_impl_trait: Option<(TraitRef, Ty)>,
534
535     /// Accumulate the errors due to missed lifetime elision,
536     /// and report them all at once for each function.
537     current_elision_failures: Vec<MissingLifetime>,
538 }
539
540 struct LateResolutionVisitor<'a, 'b, 'ast> {
541     r: &'b mut Resolver<'a>,
542
543     /// The module that represents the current item scope.
544     parent_scope: ParentScope<'a>,
545
546     /// The current set of local scopes for types and values.
547     /// FIXME #4948: Reuse ribs to avoid allocation.
548     ribs: PerNS<Vec<Rib<'a>>>,
549
550     /// The current set of local scopes, for labels.
551     label_ribs: Vec<Rib<'a, NodeId>>,
552
553     /// The current set of local scopes for lifetimes.
554     lifetime_ribs: Vec<LifetimeRib>,
555
556     /// We are looking for lifetimes in an elision context.
557     /// The set contains all the resolutions that we encountered so far.
558     /// They will be used to determine the correct lifetime for the fn return type.
559     /// The `LifetimeElisionCandidate` is used for diagnostics, to suggest introducing named
560     /// lifetimes.
561     lifetime_elision_candidates: Option<FxIndexMap<LifetimeRes, LifetimeElisionCandidate>>,
562
563     /// The trait that the current context can refer to.
564     current_trait_ref: Option<(Module<'a>, TraitRef)>,
565
566     /// Fields used to add information to diagnostic errors.
567     diagnostic_metadata: Box<DiagnosticMetadata<'ast>>,
568
569     /// State used to know whether to ignore resolution errors for function bodies.
570     ///
571     /// In particular, rustdoc uses this to avoid giving errors for `cfg()` items.
572     /// In most cases this will be `None`, in which case errors will always be reported.
573     /// If it is `true`, then it will be updated when entering a nested function or trait body.
574     in_func_body: bool,
575
576     /// Count the number of places a lifetime is used.
577     lifetime_uses: FxHashMap<LocalDefId, LifetimeUseSet>,
578 }
579
580 /// Walks the whole crate in DFS order, visiting each item, resolving names as it goes.
581 impl<'a: 'ast, 'ast> Visitor<'ast> for LateResolutionVisitor<'a, '_, 'ast> {
582     fn visit_attribute(&mut self, _: &'ast Attribute) {
583         // We do not want to resolve expressions that appear in attributes,
584         // as they do not correspond to actual code.
585     }
586     fn visit_item(&mut self, item: &'ast Item) {
587         let prev = replace(&mut self.diagnostic_metadata.current_item, Some(item));
588         // Always report errors in items we just entered.
589         let old_ignore = replace(&mut self.in_func_body, false);
590         self.with_lifetime_rib(LifetimeRibKind::Item, |this| this.resolve_item(item));
591         self.in_func_body = old_ignore;
592         self.diagnostic_metadata.current_item = prev;
593     }
594     fn visit_arm(&mut self, arm: &'ast Arm) {
595         self.resolve_arm(arm);
596     }
597     fn visit_block(&mut self, block: &'ast Block) {
598         self.resolve_block(block);
599     }
600     fn visit_anon_const(&mut self, constant: &'ast AnonConst) {
601         // We deal with repeat expressions explicitly in `resolve_expr`.
602         self.with_lifetime_rib(LifetimeRibKind::AnonConst, |this| {
603             this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
604                 this.resolve_anon_const(constant, IsRepeatExpr::No);
605             })
606         })
607     }
608     fn visit_expr(&mut self, expr: &'ast Expr) {
609         self.resolve_expr(expr, None);
610     }
611     fn visit_local(&mut self, local: &'ast Local) {
612         let local_spans = match local.pat.kind {
613             // We check for this to avoid tuple struct fields.
614             PatKind::Wild => None,
615             _ => Some((
616                 local.pat.span,
617                 local.ty.as_ref().map(|ty| ty.span),
618                 local.kind.init().map(|init| init.span),
619             )),
620         };
621         let original = replace(&mut self.diagnostic_metadata.current_let_binding, local_spans);
622         self.resolve_local(local);
623         self.diagnostic_metadata.current_let_binding = original;
624     }
625     fn visit_ty(&mut self, ty: &'ast Ty) {
626         let prev = self.diagnostic_metadata.current_trait_object;
627         let prev_ty = self.diagnostic_metadata.current_type_path;
628         match ty.kind {
629             TyKind::Rptr(None, _) => {
630                 // Elided lifetime in reference: we resolve as if there was some lifetime `'_` with
631                 // NodeId `ty.id`.
632                 // This span will be used in case of elision failure.
633                 let span = self.r.session.source_map().start_point(ty.span);
634                 self.resolve_elided_lifetime(ty.id, span);
635                 visit::walk_ty(self, ty);
636             }
637             TyKind::Path(ref qself, ref path) => {
638                 self.diagnostic_metadata.current_type_path = Some(ty);
639                 self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type);
640
641                 // Check whether we should interpret this as a bare trait object.
642                 if qself.is_none()
643                     && let Some(partial_res) = self.r.partial_res_map.get(&ty.id)
644                     && let Some(Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) = partial_res.full_res()
645                 {
646                     // This path is actually a bare trait object.  In case of a bare `Fn`-trait
647                     // object with anonymous lifetimes, we need this rib to correctly place the
648                     // synthetic lifetimes.
649                     let span = ty.span.shrink_to_lo().to(path.span.shrink_to_lo());
650                     self.with_generic_param_rib(
651                         &[],
652                         NormalRibKind,
653                         LifetimeRibKind::Generics {
654                             binder: ty.id,
655                             kind: LifetimeBinderKind::PolyTrait,
656                             span,
657                         },
658                         |this| this.visit_path(&path, ty.id),
659                     );
660                 } else {
661                     visit::walk_ty(self, ty)
662                 }
663             }
664             TyKind::ImplicitSelf => {
665                 let self_ty = Ident::with_dummy_span(kw::SelfUpper);
666                 let res = self
667                     .resolve_ident_in_lexical_scope(
668                         self_ty,
669                         TypeNS,
670                         Some(Finalize::new(ty.id, ty.span)),
671                         None,
672                     )
673                     .map_or(Res::Err, |d| d.res());
674                 self.r.record_partial_res(ty.id, PartialRes::new(res));
675                 visit::walk_ty(self, ty)
676             }
677             TyKind::ImplTrait(..) => {
678                 let candidates = self.lifetime_elision_candidates.take();
679                 visit::walk_ty(self, ty);
680                 self.lifetime_elision_candidates = candidates;
681             }
682             TyKind::TraitObject(ref bounds, ..) => {
683                 self.diagnostic_metadata.current_trait_object = Some(&bounds[..]);
684                 visit::walk_ty(self, ty)
685             }
686             TyKind::BareFn(ref bare_fn) => {
687                 let span = ty.span.shrink_to_lo().to(bare_fn.decl_span.shrink_to_lo());
688                 self.with_generic_param_rib(
689                     &bare_fn.generic_params,
690                     NormalRibKind,
691                     LifetimeRibKind::Generics {
692                         binder: ty.id,
693                         kind: LifetimeBinderKind::BareFnType,
694                         span,
695                     },
696                     |this| {
697                         this.visit_generic_params(&bare_fn.generic_params, false);
698                         this.with_lifetime_rib(
699                             LifetimeRibKind::AnonymousCreateParameter {
700                                 binder: ty.id,
701                                 report_in_path: false,
702                             },
703                             |this| {
704                                 this.resolve_fn_signature(
705                                     ty.id,
706                                     false,
707                                     // We don't need to deal with patterns in parameters, because
708                                     // they are not possible for foreign or bodiless functions.
709                                     bare_fn
710                                         .decl
711                                         .inputs
712                                         .iter()
713                                         .map(|Param { ty, .. }| (None, &**ty)),
714                                     &bare_fn.decl.output,
715                                 )
716                             },
717                         );
718                     },
719                 )
720             }
721             _ => visit::walk_ty(self, ty),
722         }
723         self.diagnostic_metadata.current_trait_object = prev;
724         self.diagnostic_metadata.current_type_path = prev_ty;
725     }
726     fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef) {
727         let span = tref.span.shrink_to_lo().to(tref.trait_ref.path.span.shrink_to_lo());
728         self.with_generic_param_rib(
729             &tref.bound_generic_params,
730             NormalRibKind,
731             LifetimeRibKind::Generics {
732                 binder: tref.trait_ref.ref_id,
733                 kind: LifetimeBinderKind::PolyTrait,
734                 span,
735             },
736             |this| {
737                 this.visit_generic_params(&tref.bound_generic_params, false);
738                 this.smart_resolve_path(
739                     tref.trait_ref.ref_id,
740                     None,
741                     &tref.trait_ref.path,
742                     PathSource::Trait(AliasPossibility::Maybe),
743                 );
744                 this.visit_trait_ref(&tref.trait_ref);
745             },
746         );
747     }
748     fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
749         match foreign_item.kind {
750             ForeignItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
751                 self.with_lifetime_rib(LifetimeRibKind::Item, |this| {
752                     this.with_generic_param_rib(
753                         &generics.params,
754                         ItemRibKind(HasGenericParams::Yes(generics.span)),
755                         LifetimeRibKind::Generics {
756                             binder: foreign_item.id,
757                             kind: LifetimeBinderKind::Item,
758                             span: generics.span,
759                         },
760                         |this| visit::walk_foreign_item(this, foreign_item),
761                     )
762                 });
763             }
764             ForeignItemKind::Fn(box Fn { ref generics, .. }) => {
765                 self.with_lifetime_rib(LifetimeRibKind::Item, |this| {
766                     this.with_generic_param_rib(
767                         &generics.params,
768                         ItemRibKind(HasGenericParams::Yes(generics.span)),
769                         LifetimeRibKind::Generics {
770                             binder: foreign_item.id,
771                             kind: LifetimeBinderKind::Function,
772                             span: generics.span,
773                         },
774                         |this| visit::walk_foreign_item(this, foreign_item),
775                     )
776                 });
777             }
778             ForeignItemKind::Static(..) => {
779                 self.with_item_rib(|this| {
780                     visit::walk_foreign_item(this, foreign_item);
781                 });
782             }
783             ForeignItemKind::MacCall(..) => {
784                 panic!("unexpanded macro in resolve!")
785             }
786         }
787     }
788     fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, fn_id: NodeId) {
789         let previous_value = self.diagnostic_metadata.current_function;
790         match fn_kind {
791             // Bail if the function is foreign, and thus cannot validly have
792             // a body, or if there's no body for some other reason.
793             FnKind::Fn(FnCtxt::Foreign, _, sig, _, generics, _)
794             | FnKind::Fn(_, _, sig, _, generics, None) => {
795                 self.visit_fn_header(&sig.header);
796                 self.visit_generics(generics);
797                 self.with_lifetime_rib(
798                     LifetimeRibKind::AnonymousCreateParameter {
799                         binder: fn_id,
800                         report_in_path: false,
801                     },
802                     |this| {
803                         this.resolve_fn_signature(
804                             fn_id,
805                             sig.decl.has_self(),
806                             sig.decl.inputs.iter().map(|Param { ty, .. }| (None, &**ty)),
807                             &sig.decl.output,
808                         );
809
810                         this.record_lifetime_params_for_async(
811                             fn_id,
812                             sig.header.asyncness.opt_return_id(),
813                         );
814                     },
815                 );
816                 return;
817             }
818             FnKind::Fn(..) => {
819                 self.diagnostic_metadata.current_function = Some((fn_kind, sp));
820             }
821             // Do not update `current_function` for closures: it suggests `self` parameters.
822             FnKind::Closure(..) => {}
823         };
824         debug!("(resolving function) entering function");
825
826         // Create a value rib for the function.
827         self.with_rib(ValueNS, ClosureOrAsyncRibKind, |this| {
828             // Create a label rib for the function.
829             this.with_label_rib(ClosureOrAsyncRibKind, |this| {
830                 match fn_kind {
831                     FnKind::Fn(_, _, sig, _, generics, body) => {
832                         this.visit_generics(generics);
833
834                         let declaration = &sig.decl;
835                         let async_node_id = sig.header.asyncness.opt_return_id();
836
837                         this.with_lifetime_rib(
838                             LifetimeRibKind::AnonymousCreateParameter {
839                                 binder: fn_id,
840                                 report_in_path: async_node_id.is_some(),
841                             },
842                             |this| {
843                                 this.resolve_fn_signature(
844                                     fn_id,
845                                     declaration.has_self(),
846                                     declaration
847                                         .inputs
848                                         .iter()
849                                         .map(|Param { pat, ty, .. }| (Some(&**pat), &**ty)),
850                                     &declaration.output,
851                                 )
852                             },
853                         );
854
855                         this.record_lifetime_params_for_async(fn_id, async_node_id);
856
857                         if let Some(body) = body {
858                             // Ignore errors in function bodies if this is rustdoc
859                             // Be sure not to set this until the function signature has been resolved.
860                             let previous_state = replace(&mut this.in_func_body, true);
861                             // Resolve the function body, potentially inside the body of an async closure
862                             this.with_lifetime_rib(
863                                 LifetimeRibKind::Elided(LifetimeRes::Infer),
864                                 |this| this.visit_block(body),
865                             );
866
867                             debug!("(resolving function) leaving function");
868                             this.in_func_body = previous_state;
869                         }
870                     }
871                     FnKind::Closure(binder, declaration, body) => {
872                         this.visit_closure_binder(binder);
873
874                         this.with_lifetime_rib(
875                             match binder {
876                                 // We do not have any explicit generic lifetime parameter.
877                                 ClosureBinder::NotPresent => {
878                                     LifetimeRibKind::AnonymousCreateParameter {
879                                         binder: fn_id,
880                                         report_in_path: false,
881                                     }
882                                 }
883                                 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
884                             },
885                             // Add each argument to the rib.
886                             |this| this.resolve_params(&declaration.inputs),
887                         );
888                         this.with_lifetime_rib(
889                             match binder {
890                                 ClosureBinder::NotPresent => {
891                                     LifetimeRibKind::Elided(LifetimeRes::Infer)
892                                 }
893                                 ClosureBinder::For { .. } => LifetimeRibKind::AnonymousReportError,
894                             },
895                             |this| visit::walk_fn_ret_ty(this, &declaration.output),
896                         );
897
898                         // Ignore errors in function bodies if this is rustdoc
899                         // Be sure not to set this until the function signature has been resolved.
900                         let previous_state = replace(&mut this.in_func_body, true);
901                         // Resolve the function body, potentially inside the body of an async closure
902                         this.with_lifetime_rib(
903                             LifetimeRibKind::Elided(LifetimeRes::Infer),
904                             |this| this.visit_expr(body),
905                         );
906
907                         debug!("(resolving function) leaving function");
908                         this.in_func_body = previous_state;
909                     }
910                 }
911             })
912         });
913         self.diagnostic_metadata.current_function = previous_value;
914     }
915     fn visit_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
916         self.resolve_lifetime(lifetime, use_ctxt)
917     }
918
919     fn visit_generics(&mut self, generics: &'ast Generics) {
920         self.visit_generic_params(
921             &generics.params,
922             self.diagnostic_metadata.current_self_item.is_some(),
923         );
924         for p in &generics.where_clause.predicates {
925             self.visit_where_predicate(p);
926         }
927     }
928
929     fn visit_closure_binder(&mut self, b: &'ast ClosureBinder) {
930         match b {
931             ClosureBinder::NotPresent => {}
932             ClosureBinder::For { generic_params, .. } => {
933                 self.visit_generic_params(
934                     &generic_params,
935                     self.diagnostic_metadata.current_self_item.is_some(),
936                 );
937             }
938         }
939     }
940
941     fn visit_generic_arg(&mut self, arg: &'ast GenericArg) {
942         debug!("visit_generic_arg({:?})", arg);
943         let prev = replace(&mut self.diagnostic_metadata.currently_processing_generics, true);
944         match arg {
945             GenericArg::Type(ref ty) => {
946                 // We parse const arguments as path types as we cannot distinguish them during
947                 // parsing. We try to resolve that ambiguity by attempting resolution the type
948                 // namespace first, and if that fails we try again in the value namespace. If
949                 // resolution in the value namespace succeeds, we have an generic const argument on
950                 // our hands.
951                 if let TyKind::Path(ref qself, ref path) = ty.kind {
952                     // We cannot disambiguate multi-segment paths right now as that requires type
953                     // checking.
954                     if path.segments.len() == 1 && path.segments[0].args.is_none() {
955                         let mut check_ns = |ns| {
956                             self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns)
957                                 .is_some()
958                         };
959                         if !check_ns(TypeNS) && check_ns(ValueNS) {
960                             // This must be equivalent to `visit_anon_const`, but we cannot call it
961                             // directly due to visitor lifetimes so we have to copy-paste some code.
962                             //
963                             // Note that we might not be inside of an repeat expression here,
964                             // but considering that `IsRepeatExpr` is only relevant for
965                             // non-trivial constants this is doesn't matter.
966                             self.with_constant_rib(
967                                 IsRepeatExpr::No,
968                                 ConstantHasGenerics::Yes,
969                                 None,
970                                 |this| {
971                                     this.smart_resolve_path(
972                                         ty.id,
973                                         qself.as_ref(),
974                                         path,
975                                         PathSource::Expr(None),
976                                     );
977
978                                     if let Some(ref qself) = *qself {
979                                         this.visit_ty(&qself.ty);
980                                     }
981                                     this.visit_path(path, ty.id);
982                                 },
983                             );
984
985                             self.diagnostic_metadata.currently_processing_generics = prev;
986                             return;
987                         }
988                     }
989                 }
990
991                 self.visit_ty(ty);
992             }
993             GenericArg::Lifetime(lt) => self.visit_lifetime(lt, visit::LifetimeCtxt::GenericArg),
994             GenericArg::Const(ct) => self.visit_anon_const(ct),
995         }
996         self.diagnostic_metadata.currently_processing_generics = prev;
997     }
998
999     fn visit_assoc_constraint(&mut self, constraint: &'ast AssocConstraint) {
1000         self.visit_ident(constraint.ident);
1001         if let Some(ref gen_args) = constraint.gen_args {
1002             // Forbid anonymous lifetimes in GAT parameters until proper semantics are decided.
1003             self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1004                 this.visit_generic_args(gen_args)
1005             });
1006         }
1007         match constraint.kind {
1008             AssocConstraintKind::Equality { ref term } => match term {
1009                 Term::Ty(ty) => self.visit_ty(ty),
1010                 Term::Const(c) => self.visit_anon_const(c),
1011             },
1012             AssocConstraintKind::Bound { ref bounds } => {
1013                 walk_list!(self, visit_param_bound, bounds, BoundKind::Bound);
1014             }
1015         }
1016     }
1017
1018     fn visit_path_segment(&mut self, path_segment: &'ast PathSegment) {
1019         if let Some(ref args) = path_segment.args {
1020             match &**args {
1021                 GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, args),
1022                 GenericArgs::Parenthesized(p_args) => {
1023                     // Probe the lifetime ribs to know how to behave.
1024                     for rib in self.lifetime_ribs.iter().rev() {
1025                         match rib.kind {
1026                             // We are inside a `PolyTraitRef`.  The lifetimes are
1027                             // to be intoduced in that (maybe implicit) `for<>` binder.
1028                             LifetimeRibKind::Generics {
1029                                 binder,
1030                                 kind: LifetimeBinderKind::PolyTrait,
1031                                 ..
1032                             } => {
1033                                 self.with_lifetime_rib(
1034                                     LifetimeRibKind::AnonymousCreateParameter {
1035                                         binder,
1036                                         report_in_path: false,
1037                                     },
1038                                     |this| {
1039                                         this.resolve_fn_signature(
1040                                             binder,
1041                                             false,
1042                                             p_args.inputs.iter().map(|ty| (None, &**ty)),
1043                                             &p_args.output,
1044                                         )
1045                                     },
1046                                 );
1047                                 break;
1048                             }
1049                             // We have nowhere to introduce generics.  Code is malformed,
1050                             // so use regular lifetime resolution to avoid spurious errors.
1051                             LifetimeRibKind::Item | LifetimeRibKind::Generics { .. } => {
1052                                 visit::walk_generic_args(self, args);
1053                                 break;
1054                             }
1055                             LifetimeRibKind::AnonymousCreateParameter { .. }
1056                             | LifetimeRibKind::AnonymousReportError
1057                             | LifetimeRibKind::Elided(_)
1058                             | LifetimeRibKind::ElisionFailure
1059                             | LifetimeRibKind::AnonConst
1060                             | LifetimeRibKind::ConstGeneric => {}
1061                         }
1062                     }
1063                 }
1064             }
1065         }
1066     }
1067
1068     fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
1069         debug!("visit_where_predicate {:?}", p);
1070         let previous_value =
1071             replace(&mut self.diagnostic_metadata.current_where_predicate, Some(p));
1072         self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1073             if let WherePredicate::BoundPredicate(WhereBoundPredicate {
1074                 ref bounded_ty,
1075                 ref bounds,
1076                 ref bound_generic_params,
1077                 span: predicate_span,
1078                 ..
1079             }) = p
1080             {
1081                 let span = predicate_span.shrink_to_lo().to(bounded_ty.span.shrink_to_lo());
1082                 this.with_generic_param_rib(
1083                     &bound_generic_params,
1084                     NormalRibKind,
1085                     LifetimeRibKind::Generics {
1086                         binder: bounded_ty.id,
1087                         kind: LifetimeBinderKind::WhereBound,
1088                         span,
1089                     },
1090                     |this| {
1091                         this.visit_generic_params(&bound_generic_params, false);
1092                         this.visit_ty(bounded_ty);
1093                         for bound in bounds {
1094                             this.visit_param_bound(bound, BoundKind::Bound)
1095                         }
1096                     },
1097                 );
1098             } else {
1099                 visit::walk_where_predicate(this, p);
1100             }
1101         });
1102         self.diagnostic_metadata.current_where_predicate = previous_value;
1103     }
1104
1105     fn visit_inline_asm(&mut self, asm: &'ast InlineAsm) {
1106         for (op, _) in &asm.operands {
1107             match op {
1108                 InlineAsmOperand::In { expr, .. }
1109                 | InlineAsmOperand::Out { expr: Some(expr), .. }
1110                 | InlineAsmOperand::InOut { expr, .. } => self.visit_expr(expr),
1111                 InlineAsmOperand::Out { expr: None, .. } => {}
1112                 InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
1113                     self.visit_expr(in_expr);
1114                     if let Some(out_expr) = out_expr {
1115                         self.visit_expr(out_expr);
1116                     }
1117                 }
1118                 InlineAsmOperand::Const { anon_const, .. } => {
1119                     // Although this is `DefKind::AnonConst`, it is allowed to reference outer
1120                     // generic parameters like an inline const.
1121                     self.resolve_inline_const(anon_const);
1122                 }
1123                 InlineAsmOperand::Sym { sym } => self.visit_inline_asm_sym(sym),
1124             }
1125         }
1126     }
1127
1128     fn visit_inline_asm_sym(&mut self, sym: &'ast InlineAsmSym) {
1129         // This is similar to the code for AnonConst.
1130         self.with_rib(ValueNS, InlineAsmSymRibKind, |this| {
1131             this.with_rib(TypeNS, InlineAsmSymRibKind, |this| {
1132                 this.with_label_rib(InlineAsmSymRibKind, |this| {
1133                     this.smart_resolve_path(
1134                         sym.id,
1135                         sym.qself.as_ref(),
1136                         &sym.path,
1137                         PathSource::Expr(None),
1138                     );
1139                     visit::walk_inline_asm_sym(this, sym);
1140                 });
1141             })
1142         });
1143     }
1144 }
1145
1146 impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> {
1147     fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b, 'ast> {
1148         // During late resolution we only track the module component of the parent scope,
1149         // although it may be useful to track other components as well for diagnostics.
1150         let graph_root = resolver.graph_root;
1151         let parent_scope = ParentScope::module(graph_root, resolver);
1152         let start_rib_kind = ModuleRibKind(graph_root);
1153         LateResolutionVisitor {
1154             r: resolver,
1155             parent_scope,
1156             ribs: PerNS {
1157                 value_ns: vec![Rib::new(start_rib_kind)],
1158                 type_ns: vec![Rib::new(start_rib_kind)],
1159                 macro_ns: vec![Rib::new(start_rib_kind)],
1160             },
1161             label_ribs: Vec::new(),
1162             lifetime_ribs: Vec::new(),
1163             lifetime_elision_candidates: None,
1164             current_trait_ref: None,
1165             diagnostic_metadata: Box::new(DiagnosticMetadata::default()),
1166             // errors at module scope should always be reported
1167             in_func_body: false,
1168             lifetime_uses: Default::default(),
1169         }
1170     }
1171
1172     fn maybe_resolve_ident_in_lexical_scope(
1173         &mut self,
1174         ident: Ident,
1175         ns: Namespace,
1176     ) -> Option<LexicalScopeBinding<'a>> {
1177         self.r.resolve_ident_in_lexical_scope(
1178             ident,
1179             ns,
1180             &self.parent_scope,
1181             None,
1182             &self.ribs[ns],
1183             None,
1184         )
1185     }
1186
1187     fn resolve_ident_in_lexical_scope(
1188         &mut self,
1189         ident: Ident,
1190         ns: Namespace,
1191         finalize: Option<Finalize>,
1192         ignore_binding: Option<&'a NameBinding<'a>>,
1193     ) -> Option<LexicalScopeBinding<'a>> {
1194         self.r.resolve_ident_in_lexical_scope(
1195             ident,
1196             ns,
1197             &self.parent_scope,
1198             finalize,
1199             &self.ribs[ns],
1200             ignore_binding,
1201         )
1202     }
1203
1204     fn resolve_path(
1205         &mut self,
1206         path: &[Segment],
1207         opt_ns: Option<Namespace>, // `None` indicates a module path in import
1208         finalize: Option<Finalize>,
1209     ) -> PathResult<'a> {
1210         self.r.resolve_path_with_ribs(
1211             path,
1212             opt_ns,
1213             &self.parent_scope,
1214             finalize,
1215             Some(&self.ribs),
1216             None,
1217         )
1218     }
1219
1220     // AST resolution
1221     //
1222     // We maintain a list of value ribs and type ribs.
1223     //
1224     // Simultaneously, we keep track of the current position in the module
1225     // graph in the `parent_scope.module` pointer. When we go to resolve a name in
1226     // the value or type namespaces, we first look through all the ribs and
1227     // then query the module graph. When we resolve a name in the module
1228     // namespace, we can skip all the ribs (since nested modules are not
1229     // allowed within blocks in Rust) and jump straight to the current module
1230     // graph node.
1231     //
1232     // Named implementations are handled separately. When we find a method
1233     // call, we consult the module node to find all of the implementations in
1234     // scope. This information is lazily cached in the module node. We then
1235     // generate a fake "implementation scope" containing all the
1236     // implementations thus found, for compatibility with old resolve pass.
1237
1238     /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`).
1239     fn with_rib<T>(
1240         &mut self,
1241         ns: Namespace,
1242         kind: RibKind<'a>,
1243         work: impl FnOnce(&mut Self) -> T,
1244     ) -> T {
1245         self.ribs[ns].push(Rib::new(kind));
1246         let ret = work(self);
1247         self.ribs[ns].pop();
1248         ret
1249     }
1250
1251     fn with_scope<T>(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
1252         if let Some(module) = self.r.get_module(self.r.local_def_id(id).to_def_id()) {
1253             // Move down in the graph.
1254             let orig_module = replace(&mut self.parent_scope.module, module);
1255             self.with_rib(ValueNS, ModuleRibKind(module), |this| {
1256                 this.with_rib(TypeNS, ModuleRibKind(module), |this| {
1257                     let ret = f(this);
1258                     this.parent_scope.module = orig_module;
1259                     ret
1260                 })
1261             })
1262         } else {
1263             f(self)
1264         }
1265     }
1266
1267     fn visit_generic_params(&mut self, params: &'ast [GenericParam], add_self_upper: bool) {
1268         // For type parameter defaults, we have to ban access
1269         // to following type parameters, as the InternalSubsts can only
1270         // provide previous type parameters as they're built. We
1271         // put all the parameters on the ban list and then remove
1272         // them one by one as they are processed and become available.
1273         let mut forward_ty_ban_rib = Rib::new(ForwardGenericParamBanRibKind);
1274         let mut forward_const_ban_rib = Rib::new(ForwardGenericParamBanRibKind);
1275         for param in params.iter() {
1276             match param.kind {
1277                 GenericParamKind::Type { .. } => {
1278                     forward_ty_ban_rib
1279                         .bindings
1280                         .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1281                 }
1282                 GenericParamKind::Const { .. } => {
1283                     forward_const_ban_rib
1284                         .bindings
1285                         .insert(Ident::with_dummy_span(param.ident.name), Res::Err);
1286                 }
1287                 GenericParamKind::Lifetime => {}
1288             }
1289         }
1290
1291         // rust-lang/rust#61631: The type `Self` is essentially
1292         // another type parameter. For ADTs, we consider it
1293         // well-defined only after all of the ADT type parameters have
1294         // been provided. Therefore, we do not allow use of `Self`
1295         // anywhere in ADT type parameter defaults.
1296         //
1297         // (We however cannot ban `Self` for defaults on *all* generic
1298         // lists; e.g. trait generics can usefully refer to `Self`,
1299         // such as in the case of `trait Add<Rhs = Self>`.)
1300         if add_self_upper {
1301             // (`Some` if + only if we are in ADT's generics.)
1302             forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err);
1303         }
1304
1305         self.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
1306             for param in params {
1307                 match param.kind {
1308                     GenericParamKind::Lifetime => {
1309                         for bound in &param.bounds {
1310                             this.visit_param_bound(bound, BoundKind::Bound);
1311                         }
1312                     }
1313                     GenericParamKind::Type { ref default } => {
1314                         for bound in &param.bounds {
1315                             this.visit_param_bound(bound, BoundKind::Bound);
1316                         }
1317
1318                         if let Some(ref ty) = default {
1319                             this.ribs[TypeNS].push(forward_ty_ban_rib);
1320                             this.ribs[ValueNS].push(forward_const_ban_rib);
1321                             this.visit_ty(ty);
1322                             forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1323                             forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1324                         }
1325
1326                         // Allow all following defaults to refer to this type parameter.
1327                         forward_ty_ban_rib
1328                             .bindings
1329                             .remove(&Ident::with_dummy_span(param.ident.name));
1330                     }
1331                     GenericParamKind::Const { ref ty, kw_span: _, ref default } => {
1332                         // Const parameters can't have param bounds.
1333                         assert!(param.bounds.is_empty());
1334
1335                         this.ribs[TypeNS].push(Rib::new(ConstParamTyRibKind));
1336                         this.ribs[ValueNS].push(Rib::new(ConstParamTyRibKind));
1337                         this.with_lifetime_rib(LifetimeRibKind::ConstGeneric, |this| {
1338                             this.visit_ty(ty)
1339                         });
1340                         this.ribs[TypeNS].pop().unwrap();
1341                         this.ribs[ValueNS].pop().unwrap();
1342
1343                         if let Some(ref expr) = default {
1344                             this.ribs[TypeNS].push(forward_ty_ban_rib);
1345                             this.ribs[ValueNS].push(forward_const_ban_rib);
1346                             this.with_lifetime_rib(LifetimeRibKind::ConstGeneric, |this| {
1347                                 this.resolve_anon_const(expr, IsRepeatExpr::No)
1348                             });
1349                             forward_const_ban_rib = this.ribs[ValueNS].pop().unwrap();
1350                             forward_ty_ban_rib = this.ribs[TypeNS].pop().unwrap();
1351                         }
1352
1353                         // Allow all following defaults to refer to this const parameter.
1354                         forward_const_ban_rib
1355                             .bindings
1356                             .remove(&Ident::with_dummy_span(param.ident.name));
1357                     }
1358                 }
1359             }
1360         })
1361     }
1362
1363     #[instrument(level = "debug", skip(self, work))]
1364     fn with_lifetime_rib<T>(
1365         &mut self,
1366         kind: LifetimeRibKind,
1367         work: impl FnOnce(&mut Self) -> T,
1368     ) -> T {
1369         self.lifetime_ribs.push(LifetimeRib::new(kind));
1370         let outer_elision_candidates = self.lifetime_elision_candidates.take();
1371         let ret = work(self);
1372         self.lifetime_elision_candidates = outer_elision_candidates;
1373         self.lifetime_ribs.pop();
1374         ret
1375     }
1376
1377     #[instrument(level = "debug", skip(self))]
1378     fn resolve_lifetime(&mut self, lifetime: &'ast Lifetime, use_ctxt: visit::LifetimeCtxt) {
1379         let ident = lifetime.ident;
1380
1381         if ident.name == kw::StaticLifetime {
1382             self.record_lifetime_res(
1383                 lifetime.id,
1384                 LifetimeRes::Static,
1385                 LifetimeElisionCandidate::Named,
1386             );
1387             return;
1388         }
1389
1390         if ident.name == kw::UnderscoreLifetime {
1391             return self.resolve_anonymous_lifetime(lifetime, false);
1392         }
1393
1394         let mut indices = (0..self.lifetime_ribs.len()).rev();
1395         for i in &mut indices {
1396             let rib = &self.lifetime_ribs[i];
1397             let normalized_ident = ident.normalize_to_macros_2_0();
1398             if let Some(&(_, res)) = rib.bindings.get(&normalized_ident) {
1399                 self.record_lifetime_res(lifetime.id, res, LifetimeElisionCandidate::Named);
1400
1401                 if let LifetimeRes::Param { param, .. } = res {
1402                     match self.lifetime_uses.entry(param) {
1403                         Entry::Vacant(v) => {
1404                             debug!("First use of {:?} at {:?}", res, ident.span);
1405                             let use_set = self
1406                                 .lifetime_ribs
1407                                 .iter()
1408                                 .rev()
1409                                 .find_map(|rib| match rib.kind {
1410                                     // Do not suggest eliding a lifetime where an anonymous
1411                                     // lifetime would be illegal.
1412                                     LifetimeRibKind::Item
1413                                     | LifetimeRibKind::AnonymousReportError
1414                                     | LifetimeRibKind::ElisionFailure => Some(LifetimeUseSet::Many),
1415                                     // An anonymous lifetime is legal here, go ahead.
1416                                     LifetimeRibKind::AnonymousCreateParameter { .. } => {
1417                                         Some(LifetimeUseSet::One { use_span: ident.span, use_ctxt })
1418                                     }
1419                                     // Only report if eliding the lifetime would have the same
1420                                     // semantics.
1421                                     LifetimeRibKind::Elided(r) => Some(if res == r {
1422                                         LifetimeUseSet::One { use_span: ident.span, use_ctxt }
1423                                     } else {
1424                                         LifetimeUseSet::Many
1425                                     }),
1426                                     LifetimeRibKind::Generics { .. }
1427                                     | LifetimeRibKind::ConstGeneric
1428                                     | LifetimeRibKind::AnonConst => None,
1429                                 })
1430                                 .unwrap_or(LifetimeUseSet::Many);
1431                             debug!(?use_ctxt, ?use_set);
1432                             v.insert(use_set);
1433                         }
1434                         Entry::Occupied(mut o) => {
1435                             debug!("Many uses of {:?} at {:?}", res, ident.span);
1436                             *o.get_mut() = LifetimeUseSet::Many;
1437                         }
1438                     }
1439                 }
1440                 return;
1441             }
1442
1443             match rib.kind {
1444                 LifetimeRibKind::Item => break,
1445                 LifetimeRibKind::ConstGeneric => {
1446                     self.emit_non_static_lt_in_const_generic_error(lifetime);
1447                     self.record_lifetime_res(
1448                         lifetime.id,
1449                         LifetimeRes::Error,
1450                         LifetimeElisionCandidate::Ignore,
1451                     );
1452                     return;
1453                 }
1454                 LifetimeRibKind::AnonConst => {
1455                     self.maybe_emit_forbidden_non_static_lifetime_error(lifetime);
1456                     self.record_lifetime_res(
1457                         lifetime.id,
1458                         LifetimeRes::Error,
1459                         LifetimeElisionCandidate::Ignore,
1460                     );
1461                     return;
1462                 }
1463                 _ => {}
1464             }
1465         }
1466
1467         let mut outer_res = None;
1468         for i in indices {
1469             let rib = &self.lifetime_ribs[i];
1470             let normalized_ident = ident.normalize_to_macros_2_0();
1471             if let Some((&outer, _)) = rib.bindings.get_key_value(&normalized_ident) {
1472                 outer_res = Some(outer);
1473                 break;
1474             }
1475         }
1476
1477         self.emit_undeclared_lifetime_error(lifetime, outer_res);
1478         self.record_lifetime_res(lifetime.id, LifetimeRes::Error, LifetimeElisionCandidate::Named);
1479     }
1480
1481     #[instrument(level = "debug", skip(self))]
1482     fn resolve_anonymous_lifetime(&mut self, lifetime: &Lifetime, elided: bool) {
1483         debug_assert_eq!(lifetime.ident.name, kw::UnderscoreLifetime);
1484
1485         let missing_lifetime = MissingLifetime {
1486             id: lifetime.id,
1487             span: lifetime.ident.span,
1488             kind: if elided {
1489                 MissingLifetimeKind::Ampersand
1490             } else {
1491                 MissingLifetimeKind::Underscore
1492             },
1493             count: 1,
1494         };
1495         let elision_candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1496         for i in (0..self.lifetime_ribs.len()).rev() {
1497             let rib = &mut self.lifetime_ribs[i];
1498             debug!(?rib.kind);
1499             match rib.kind {
1500                 LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1501                     let res = self.create_fresh_lifetime(lifetime.id, lifetime.ident, binder);
1502                     self.record_lifetime_res(lifetime.id, res, elision_candidate);
1503                     return;
1504                 }
1505                 LifetimeRibKind::AnonymousReportError => {
1506                     let (msg, note) = if elided {
1507                         (
1508                             "`&` without an explicit lifetime name cannot be used here",
1509                             "explicit lifetime name needed here",
1510                         )
1511                     } else {
1512                         ("`'_` cannot be used here", "`'_` is a reserved lifetime name")
1513                     };
1514                     rustc_errors::struct_span_err!(
1515                         self.r.session,
1516                         lifetime.ident.span,
1517                         E0637,
1518                         "{}",
1519                         msg,
1520                     )
1521                     .span_label(lifetime.ident.span, note)
1522                     .emit();
1523
1524                     self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1525                     return;
1526                 }
1527                 LifetimeRibKind::Elided(res) => {
1528                     self.record_lifetime_res(lifetime.id, res, elision_candidate);
1529                     return;
1530                 }
1531                 LifetimeRibKind::ElisionFailure => {
1532                     self.diagnostic_metadata.current_elision_failures.push(missing_lifetime);
1533                     self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1534                     return;
1535                 }
1536                 LifetimeRibKind::Item => break,
1537                 LifetimeRibKind::Generics { .. }
1538                 | LifetimeRibKind::ConstGeneric
1539                 | LifetimeRibKind::AnonConst => {}
1540             }
1541         }
1542         self.record_lifetime_res(lifetime.id, LifetimeRes::Error, elision_candidate);
1543         self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
1544     }
1545
1546     #[instrument(level = "debug", skip(self))]
1547     fn resolve_elided_lifetime(&mut self, anchor_id: NodeId, span: Span) {
1548         let id = self.r.next_node_id();
1549         let lt = Lifetime { id, ident: Ident::new(kw::UnderscoreLifetime, span) };
1550
1551         self.record_lifetime_res(
1552             anchor_id,
1553             LifetimeRes::ElidedAnchor { start: id, end: NodeId::from_u32(id.as_u32() + 1) },
1554             LifetimeElisionCandidate::Ignore,
1555         );
1556         self.resolve_anonymous_lifetime(&lt, true);
1557     }
1558
1559     #[instrument(level = "debug", skip(self))]
1560     fn create_fresh_lifetime(&mut self, id: NodeId, ident: Ident, binder: NodeId) -> LifetimeRes {
1561         debug_assert_eq!(ident.name, kw::UnderscoreLifetime);
1562         debug!(?ident.span);
1563
1564         // Leave the responsibility to create the `LocalDefId` to lowering.
1565         let param = self.r.next_node_id();
1566         let res = LifetimeRes::Fresh { param, binder };
1567
1568         // Record the created lifetime parameter so lowering can pick it up and add it to HIR.
1569         self.r
1570             .extra_lifetime_params_map
1571             .entry(binder)
1572             .or_insert_with(Vec::new)
1573             .push((ident, param, res));
1574         res
1575     }
1576
1577     #[instrument(level = "debug", skip(self))]
1578     fn resolve_elided_lifetimes_in_path(
1579         &mut self,
1580         path_id: NodeId,
1581         partial_res: PartialRes,
1582         path: &[Segment],
1583         source: PathSource<'_>,
1584         path_span: Span,
1585     ) {
1586         let proj_start = path.len() - partial_res.unresolved_segments();
1587         for (i, segment) in path.iter().enumerate() {
1588             if segment.has_lifetime_args {
1589                 continue;
1590             }
1591             let Some(segment_id) = segment.id else {
1592                 continue;
1593             };
1594
1595             // Figure out if this is a type/trait segment,
1596             // which may need lifetime elision performed.
1597             let type_def_id = match partial_res.base_res() {
1598                 Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => self.r.parent(def_id),
1599                 Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => self.r.parent(def_id),
1600                 Res::Def(DefKind::Struct, def_id)
1601                 | Res::Def(DefKind::Union, def_id)
1602                 | Res::Def(DefKind::Enum, def_id)
1603                 | Res::Def(DefKind::TyAlias, def_id)
1604                 | Res::Def(DefKind::Trait, def_id)
1605                     if i + 1 == proj_start =>
1606                 {
1607                     def_id
1608                 }
1609                 _ => continue,
1610             };
1611
1612             let expected_lifetimes = self.r.item_generics_num_lifetimes(type_def_id);
1613             if expected_lifetimes == 0 {
1614                 continue;
1615             }
1616
1617             let node_ids = self.r.next_node_ids(expected_lifetimes);
1618             self.record_lifetime_res(
1619                 segment_id,
1620                 LifetimeRes::ElidedAnchor { start: node_ids.start, end: node_ids.end },
1621                 LifetimeElisionCandidate::Ignore,
1622             );
1623
1624             let inferred = match source {
1625                 PathSource::Trait(..) | PathSource::TraitItem(..) | PathSource::Type => false,
1626                 PathSource::Expr(..)
1627                 | PathSource::Pat
1628                 | PathSource::Struct
1629                 | PathSource::TupleStruct(..) => true,
1630             };
1631             if inferred {
1632                 // Do not create a parameter for patterns and expressions: type checking can infer
1633                 // the appropriate lifetime for us.
1634                 for id in node_ids {
1635                     self.record_lifetime_res(
1636                         id,
1637                         LifetimeRes::Infer,
1638                         LifetimeElisionCandidate::Named,
1639                     );
1640                 }
1641                 continue;
1642             }
1643
1644             let elided_lifetime_span = if segment.has_generic_args {
1645                 // If there are brackets, but not generic arguments, then use the opening bracket
1646                 segment.args_span.with_hi(segment.args_span.lo() + BytePos(1))
1647             } else {
1648                 // If there are no brackets, use the identifier span.
1649                 // HACK: we use find_ancestor_inside to properly suggest elided spans in paths
1650                 // originating from macros, since the segment's span might be from a macro arg.
1651                 segment.ident.span.find_ancestor_inside(path_span).unwrap_or(path_span)
1652             };
1653             let ident = Ident::new(kw::UnderscoreLifetime, elided_lifetime_span);
1654
1655             let missing_lifetime = MissingLifetime {
1656                 id: node_ids.start,
1657                 span: elided_lifetime_span,
1658                 kind: if segment.has_generic_args {
1659                     MissingLifetimeKind::Comma
1660                 } else {
1661                     MissingLifetimeKind::Brackets
1662                 },
1663                 count: expected_lifetimes,
1664             };
1665             let mut should_lint = true;
1666             for rib in self.lifetime_ribs.iter().rev() {
1667                 match rib.kind {
1668                     // In create-parameter mode we error here because we don't want to support
1669                     // deprecated impl elision in new features like impl elision and `async fn`,
1670                     // both of which work using the `CreateParameter` mode:
1671                     //
1672                     //     impl Foo for std::cell::Ref<u32> // note lack of '_
1673                     //     async fn foo(_: std::cell::Ref<u32>) { ... }
1674                     LifetimeRibKind::AnonymousCreateParameter { report_in_path: true, .. } => {
1675                         let sess = self.r.session;
1676                         let mut err = rustc_errors::struct_span_err!(
1677                             sess,
1678                             path_span,
1679                             E0726,
1680                             "implicit elided lifetime not allowed here"
1681                         );
1682                         rustc_errors::add_elided_lifetime_in_path_suggestion(
1683                             sess.source_map(),
1684                             &mut err,
1685                             expected_lifetimes,
1686                             path_span,
1687                             !segment.has_generic_args,
1688                             elided_lifetime_span,
1689                         );
1690                         err.note("assuming a `'static` lifetime...");
1691                         err.emit();
1692                         should_lint = false;
1693
1694                         for id in node_ids {
1695                             self.record_lifetime_res(
1696                                 id,
1697                                 LifetimeRes::Error,
1698                                 LifetimeElisionCandidate::Named,
1699                             );
1700                         }
1701                         break;
1702                     }
1703                     // Do not create a parameter for patterns and expressions.
1704                     LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
1705                         // Group all suggestions into the first record.
1706                         let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1707                         for id in node_ids {
1708                             let res = self.create_fresh_lifetime(id, ident, binder);
1709                             self.record_lifetime_res(
1710                                 id,
1711                                 res,
1712                                 replace(&mut candidate, LifetimeElisionCandidate::Named),
1713                             );
1714                         }
1715                         break;
1716                     }
1717                     LifetimeRibKind::Elided(res) => {
1718                         let mut candidate = LifetimeElisionCandidate::Missing(missing_lifetime);
1719                         for id in node_ids {
1720                             self.record_lifetime_res(
1721                                 id,
1722                                 res,
1723                                 replace(&mut candidate, LifetimeElisionCandidate::Ignore),
1724                             );
1725                         }
1726                         break;
1727                     }
1728                     LifetimeRibKind::ElisionFailure => {
1729                         self.diagnostic_metadata.current_elision_failures.push(missing_lifetime);
1730                         for id in node_ids {
1731                             self.record_lifetime_res(
1732                                 id,
1733                                 LifetimeRes::Error,
1734                                 LifetimeElisionCandidate::Ignore,
1735                             );
1736                         }
1737                         break;
1738                     }
1739                     // `LifetimeRes::Error`, which would usually be used in the case of
1740                     // `ReportError`, is unsuitable here, as we don't emit an error yet.  Instead,
1741                     // we simply resolve to an implicit lifetime, which will be checked later, at
1742                     // which point a suitable error will be emitted.
1743                     LifetimeRibKind::AnonymousReportError | LifetimeRibKind::Item => {
1744                         for id in node_ids {
1745                             self.record_lifetime_res(
1746                                 id,
1747                                 LifetimeRes::Error,
1748                                 LifetimeElisionCandidate::Ignore,
1749                             );
1750                         }
1751                         self.report_missing_lifetime_specifiers(vec![missing_lifetime], None);
1752                         break;
1753                     }
1754                     LifetimeRibKind::Generics { .. }
1755                     | LifetimeRibKind::ConstGeneric
1756                     | LifetimeRibKind::AnonConst => {}
1757                 }
1758             }
1759
1760             if should_lint {
1761                 self.r.lint_buffer.buffer_lint_with_diagnostic(
1762                     lint::builtin::ELIDED_LIFETIMES_IN_PATHS,
1763                     segment_id,
1764                     elided_lifetime_span,
1765                     "hidden lifetime parameters in types are deprecated",
1766                     lint::BuiltinLintDiagnostics::ElidedLifetimesInPaths(
1767                         expected_lifetimes,
1768                         path_span,
1769                         !segment.has_generic_args,
1770                         elided_lifetime_span,
1771                     ),
1772                 );
1773             }
1774         }
1775     }
1776
1777     #[instrument(level = "debug", skip(self))]
1778     fn record_lifetime_res(
1779         &mut self,
1780         id: NodeId,
1781         res: LifetimeRes,
1782         candidate: LifetimeElisionCandidate,
1783     ) {
1784         if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
1785             panic!(
1786                 "lifetime {:?} resolved multiple times ({:?} before, {:?} now)",
1787                 id, prev_res, res
1788             )
1789         }
1790         match res {
1791             LifetimeRes::Param { .. } | LifetimeRes::Fresh { .. } | LifetimeRes::Static => {
1792                 if let Some(ref mut candidates) = self.lifetime_elision_candidates {
1793                     candidates.insert(res, candidate);
1794                 }
1795             }
1796             LifetimeRes::Infer | LifetimeRes::Error | LifetimeRes::ElidedAnchor { .. } => {}
1797         }
1798     }
1799
1800     #[instrument(level = "debug", skip(self))]
1801     fn record_lifetime_param(&mut self, id: NodeId, res: LifetimeRes) {
1802         if let Some(prev_res) = self.r.lifetimes_res_map.insert(id, res) {
1803             panic!(
1804                 "lifetime parameter {:?} resolved multiple times ({:?} before, {:?} now)",
1805                 id, prev_res, res
1806             )
1807         }
1808     }
1809
1810     /// Perform resolution of a function signature, accounting for lifetime elision.
1811     #[instrument(level = "debug", skip(self, inputs))]
1812     fn resolve_fn_signature(
1813         &mut self,
1814         fn_id: NodeId,
1815         has_self: bool,
1816         inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)> + Clone,
1817         output_ty: &'ast FnRetTy,
1818     ) {
1819         // Add each argument to the rib.
1820         let elision_lifetime = self.resolve_fn_params(has_self, inputs);
1821         debug!(?elision_lifetime);
1822
1823         let outer_failures = take(&mut self.diagnostic_metadata.current_elision_failures);
1824         let output_rib = if let Ok(res) = elision_lifetime.as_ref() {
1825             LifetimeRibKind::Elided(*res)
1826         } else {
1827             LifetimeRibKind::ElisionFailure
1828         };
1829         self.with_lifetime_rib(output_rib, |this| visit::walk_fn_ret_ty(this, &output_ty));
1830         let elision_failures =
1831             replace(&mut self.diagnostic_metadata.current_elision_failures, outer_failures);
1832         if !elision_failures.is_empty() {
1833             let Err(failure_info) = elision_lifetime else { bug!() };
1834             self.report_missing_lifetime_specifiers(elision_failures, Some(failure_info));
1835         }
1836     }
1837
1838     /// Resolve inside function parameters and parameter types.
1839     /// Returns the lifetime for elision in fn return type,
1840     /// or diagnostic information in case of elision failure.
1841     fn resolve_fn_params(
1842         &mut self,
1843         has_self: bool,
1844         inputs: impl Iterator<Item = (Option<&'ast Pat>, &'ast Ty)>,
1845     ) -> Result<LifetimeRes, (Vec<MissingLifetime>, Vec<ElisionFnParameter>)> {
1846         let outer_candidates =
1847             replace(&mut self.lifetime_elision_candidates, Some(Default::default()));
1848
1849         let mut elision_lifetime = None;
1850         let mut lifetime_count = 0;
1851         let mut parameter_info = Vec::new();
1852
1853         let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
1854         for (index, (pat, ty)) in inputs.enumerate() {
1855             debug!(?pat, ?ty);
1856             if let Some(pat) = pat {
1857                 self.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
1858             }
1859             self.visit_ty(ty);
1860
1861             if let Some(ref candidates) = self.lifetime_elision_candidates {
1862                 let new_count = candidates.len();
1863                 let local_count = new_count - lifetime_count;
1864                 if local_count != 0 {
1865                     parameter_info.push(ElisionFnParameter {
1866                         index,
1867                         ident: if let Some(pat) = pat && let PatKind::Ident(_, ident, _) = pat.kind {
1868                             Some(ident)
1869                         } else {
1870                             None
1871                         },
1872                         lifetime_count: local_count,
1873                         span: ty.span,
1874                     });
1875                 }
1876                 lifetime_count = new_count;
1877             }
1878
1879             // Handle `self` specially.
1880             if index == 0 && has_self {
1881                 let self_lifetime = self.find_lifetime_for_self(ty);
1882                 if let Set1::One(lifetime) = self_lifetime {
1883                     elision_lifetime = Some(lifetime);
1884                     self.lifetime_elision_candidates = None;
1885                 } else {
1886                     self.lifetime_elision_candidates = Some(Default::default());
1887                     lifetime_count = 0;
1888                 }
1889             }
1890             debug!("(resolving function / closure) recorded parameter");
1891         }
1892
1893         let all_candidates = replace(&mut self.lifetime_elision_candidates, outer_candidates);
1894         debug!(?all_candidates);
1895
1896         if let Some(res) = elision_lifetime {
1897             return Ok(res);
1898         }
1899
1900         // We do not have a `self` candidate, look at the full list.
1901         let all_candidates = all_candidates.unwrap();
1902         if all_candidates.len() == 1 {
1903             Ok(*all_candidates.first().unwrap().0)
1904         } else {
1905             let all_candidates = all_candidates
1906                 .into_iter()
1907                 .filter_map(|(_, candidate)| match candidate {
1908                     LifetimeElisionCandidate::Ignore | LifetimeElisionCandidate::Named => None,
1909                     LifetimeElisionCandidate::Missing(missing) => Some(missing),
1910                 })
1911                 .collect();
1912             Err((all_candidates, parameter_info))
1913         }
1914     }
1915
1916     /// List all the lifetimes that appear in the provided type.
1917     fn find_lifetime_for_self(&self, ty: &'ast Ty) -> Set1<LifetimeRes> {
1918         struct SelfVisitor<'r, 'a> {
1919             r: &'r Resolver<'a>,
1920             impl_self: Option<Res>,
1921             lifetime: Set1<LifetimeRes>,
1922         }
1923
1924         impl SelfVisitor<'_, '_> {
1925             // Look for `self: &'a Self` - also desugared from `&'a self`,
1926             // and if that matches, use it for elision and return early.
1927             fn is_self_ty(&self, ty: &Ty) -> bool {
1928                 match ty.kind {
1929                     TyKind::ImplicitSelf => true,
1930                     TyKind::Path(None, _) => {
1931                         let path_res = self.r.partial_res_map[&ty.id].full_res();
1932                         if let Some(Res::SelfTyParam { .. } | Res::SelfTyAlias { .. }) = path_res {
1933                             return true;
1934                         }
1935                         self.impl_self.is_some() && path_res == self.impl_self
1936                     }
1937                     _ => false,
1938                 }
1939             }
1940         }
1941
1942         impl<'a> Visitor<'a> for SelfVisitor<'_, '_> {
1943             fn visit_ty(&mut self, ty: &'a Ty) {
1944                 trace!("SelfVisitor considering ty={:?}", ty);
1945                 if let TyKind::Rptr(lt, ref mt) = ty.kind && self.is_self_ty(&mt.ty) {
1946                     let lt_id = if let Some(lt) = lt {
1947                         lt.id
1948                     } else {
1949                         let res = self.r.lifetimes_res_map[&ty.id];
1950                         let LifetimeRes::ElidedAnchor { start, .. } = res else { bug!() };
1951                         start
1952                     };
1953                     let lt_res = self.r.lifetimes_res_map[&lt_id];
1954                     trace!("SelfVisitor inserting res={:?}", lt_res);
1955                     self.lifetime.insert(lt_res);
1956                 }
1957                 visit::walk_ty(self, ty)
1958             }
1959         }
1960
1961         let impl_self = self
1962             .diagnostic_metadata
1963             .current_self_type
1964             .as_ref()
1965             .and_then(|ty| {
1966                 if let TyKind::Path(None, _) = ty.kind {
1967                     self.r.partial_res_map.get(&ty.id)
1968                 } else {
1969                     None
1970                 }
1971             })
1972             .and_then(|res| res.full_res())
1973             .filter(|res| {
1974                 // Permit the types that unambiguously always
1975                 // result in the same type constructor being used
1976                 // (it can't differ between `Self` and `self`).
1977                 matches!(
1978                     res,
1979                     Res::Def(DefKind::Struct | DefKind::Union | DefKind::Enum, _,) | Res::PrimTy(_)
1980                 )
1981             });
1982         let mut visitor = SelfVisitor { r: self.r, impl_self, lifetime: Set1::Empty };
1983         visitor.visit_ty(ty);
1984         trace!("SelfVisitor found={:?}", visitor.lifetime);
1985         visitor.lifetime
1986     }
1987
1988     /// Searches the current set of local scopes for labels. Returns the `NodeId` of the resolved
1989     /// label and reports an error if the label is not found or is unreachable.
1990     fn resolve_label(&mut self, mut label: Ident) -> Result<(NodeId, Span), ResolutionError<'a>> {
1991         let mut suggestion = None;
1992
1993         for i in (0..self.label_ribs.len()).rev() {
1994             let rib = &self.label_ribs[i];
1995
1996             if let MacroDefinition(def) = rib.kind {
1997                 // If an invocation of this macro created `ident`, give up on `ident`
1998                 // and switch to `ident`'s source from the macro definition.
1999                 if def == self.r.macro_def(label.span.ctxt()) {
2000                     label.span.remove_mark();
2001                 }
2002             }
2003
2004             let ident = label.normalize_to_macro_rules();
2005             if let Some((ident, id)) = rib.bindings.get_key_value(&ident) {
2006                 let definition_span = ident.span;
2007                 return if self.is_label_valid_from_rib(i) {
2008                     Ok((*id, definition_span))
2009                 } else {
2010                     Err(ResolutionError::UnreachableLabel {
2011                         name: label.name,
2012                         definition_span,
2013                         suggestion,
2014                     })
2015                 };
2016             }
2017
2018             // Diagnostics: Check if this rib contains a label with a similar name, keep track of
2019             // the first such label that is encountered.
2020             suggestion = suggestion.or_else(|| self.suggestion_for_label_in_rib(i, label));
2021         }
2022
2023         Err(ResolutionError::UndeclaredLabel { name: label.name, suggestion })
2024     }
2025
2026     /// Determine whether or not a label from the `rib_index`th label rib is reachable.
2027     fn is_label_valid_from_rib(&self, rib_index: usize) -> bool {
2028         let ribs = &self.label_ribs[rib_index + 1..];
2029
2030         for rib in ribs {
2031             if rib.kind.is_label_barrier() {
2032                 return false;
2033             }
2034         }
2035
2036         true
2037     }
2038
2039     fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) {
2040         debug!("resolve_adt");
2041         self.with_current_self_item(item, |this| {
2042             this.with_generic_param_rib(
2043                 &generics.params,
2044                 ItemRibKind(HasGenericParams::Yes(generics.span)),
2045                 LifetimeRibKind::Generics {
2046                     binder: item.id,
2047                     kind: LifetimeBinderKind::Item,
2048                     span: generics.span,
2049                 },
2050                 |this| {
2051                     let item_def_id = this.r.local_def_id(item.id).to_def_id();
2052                     this.with_self_rib(
2053                         Res::SelfTyAlias {
2054                             alias_to: item_def_id,
2055                             forbid_generic: false,
2056                             is_trait_impl: false,
2057                         },
2058                         |this| {
2059                             visit::walk_item(this, item);
2060                         },
2061                     );
2062                 },
2063             );
2064         });
2065     }
2066
2067     fn future_proof_import(&mut self, use_tree: &UseTree) {
2068         let segments = &use_tree.prefix.segments;
2069         if !segments.is_empty() {
2070             let ident = segments[0].ident;
2071             if ident.is_path_segment_keyword() || ident.span.rust_2015() {
2072                 return;
2073             }
2074
2075             let nss = match use_tree.kind {
2076                 UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..],
2077                 _ => &[TypeNS],
2078             };
2079             let report_error = |this: &Self, ns| {
2080                 let what = if ns == TypeNS { "type parameters" } else { "local variables" };
2081                 if this.should_report_errs() {
2082                     this.r
2083                         .session
2084                         .span_err(ident.span, &format!("imports cannot refer to {}", what));
2085                 }
2086             };
2087
2088             for &ns in nss {
2089                 match self.maybe_resolve_ident_in_lexical_scope(ident, ns) {
2090                     Some(LexicalScopeBinding::Res(..)) => {
2091                         report_error(self, ns);
2092                     }
2093                     Some(LexicalScopeBinding::Item(binding)) => {
2094                         if let Some(LexicalScopeBinding::Res(..)) =
2095                             self.resolve_ident_in_lexical_scope(ident, ns, None, Some(binding))
2096                         {
2097                             report_error(self, ns);
2098                         }
2099                     }
2100                     None => {}
2101                 }
2102             }
2103         } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind {
2104             for (use_tree, _) in use_trees {
2105                 self.future_proof_import(use_tree);
2106             }
2107         }
2108     }
2109
2110     fn resolve_item(&mut self, item: &'ast Item) {
2111         let name = item.ident.name;
2112         debug!("(resolving item) resolving {} ({:?})", name, item.kind);
2113
2114         match item.kind {
2115             ItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
2116                 self.with_generic_param_rib(
2117                     &generics.params,
2118                     ItemRibKind(HasGenericParams::Yes(generics.span)),
2119                     LifetimeRibKind::Generics {
2120                         binder: item.id,
2121                         kind: LifetimeBinderKind::Item,
2122                         span: generics.span,
2123                     },
2124                     |this| visit::walk_item(this, item),
2125                 );
2126             }
2127
2128             ItemKind::Fn(box Fn { ref generics, .. }) => {
2129                 self.with_generic_param_rib(
2130                     &generics.params,
2131                     ItemRibKind(HasGenericParams::Yes(generics.span)),
2132                     LifetimeRibKind::Generics {
2133                         binder: item.id,
2134                         kind: LifetimeBinderKind::Function,
2135                         span: generics.span,
2136                     },
2137                     |this| visit::walk_item(this, item),
2138                 );
2139             }
2140
2141             ItemKind::Enum(_, ref generics)
2142             | ItemKind::Struct(_, ref generics)
2143             | ItemKind::Union(_, ref generics) => {
2144                 self.resolve_adt(item, generics);
2145             }
2146
2147             ItemKind::Impl(box Impl {
2148                 ref generics,
2149                 ref of_trait,
2150                 ref self_ty,
2151                 items: ref impl_items,
2152                 ..
2153             }) => {
2154                 self.diagnostic_metadata.current_impl_items = Some(impl_items);
2155                 self.resolve_implementation(generics, of_trait, &self_ty, item.id, impl_items);
2156                 self.diagnostic_metadata.current_impl_items = None;
2157             }
2158
2159             ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => {
2160                 // Create a new rib for the trait-wide type parameters.
2161                 self.with_generic_param_rib(
2162                     &generics.params,
2163                     ItemRibKind(HasGenericParams::Yes(generics.span)),
2164                     LifetimeRibKind::Generics {
2165                         binder: item.id,
2166                         kind: LifetimeBinderKind::Item,
2167                         span: generics.span,
2168                     },
2169                     |this| {
2170                         let local_def_id = this.r.local_def_id(item.id).to_def_id();
2171                         this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2172                             this.visit_generics(generics);
2173                             walk_list!(this, visit_param_bound, bounds, BoundKind::SuperTraits);
2174                             this.resolve_trait_items(items);
2175                         });
2176                     },
2177                 );
2178             }
2179
2180             ItemKind::TraitAlias(ref generics, ref bounds) => {
2181                 // Create a new rib for the trait-wide type parameters.
2182                 self.with_generic_param_rib(
2183                     &generics.params,
2184                     ItemRibKind(HasGenericParams::Yes(generics.span)),
2185                     LifetimeRibKind::Generics {
2186                         binder: item.id,
2187                         kind: LifetimeBinderKind::Item,
2188                         span: generics.span,
2189                     },
2190                     |this| {
2191                         let local_def_id = this.r.local_def_id(item.id).to_def_id();
2192                         this.with_self_rib(Res::SelfTyParam { trait_: local_def_id }, |this| {
2193                             this.visit_generics(generics);
2194                             walk_list!(this, visit_param_bound, bounds, BoundKind::Bound);
2195                         });
2196                     },
2197                 );
2198             }
2199
2200             ItemKind::Mod(..) | ItemKind::ForeignMod(_) => {
2201                 self.with_scope(item.id, |this| {
2202                     visit::walk_item(this, item);
2203                 });
2204             }
2205
2206             ItemKind::Static(ref ty, _, ref expr) | ItemKind::Const(_, ref ty, ref expr) => {
2207                 self.with_item_rib(|this| {
2208                     this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
2209                         this.visit_ty(ty);
2210                     });
2211                     this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2212                         if let Some(expr) = expr {
2213                             let constant_item_kind = match item.kind {
2214                                 ItemKind::Const(..) => ConstantItemKind::Const,
2215                                 ItemKind::Static(..) => ConstantItemKind::Static,
2216                                 _ => unreachable!(),
2217                             };
2218                             // We already forbid generic params because of the above item rib,
2219                             // so it doesn't matter whether this is a trivial constant.
2220                             this.with_constant_rib(
2221                                 IsRepeatExpr::No,
2222                                 ConstantHasGenerics::Yes,
2223                                 Some((item.ident, constant_item_kind)),
2224                                 |this| this.visit_expr(expr),
2225                             );
2226                         }
2227                     });
2228                 });
2229             }
2230
2231             ItemKind::Use(ref use_tree) => {
2232                 self.future_proof_import(use_tree);
2233             }
2234
2235             ItemKind::ExternCrate(..) | ItemKind::MacroDef(..) => {
2236                 // do nothing, these are just around to be encoded
2237             }
2238
2239             ItemKind::GlobalAsm(_) => {
2240                 visit::walk_item(self, item);
2241             }
2242
2243             ItemKind::MacCall(_) => panic!("unexpanded macro in resolve!"),
2244         }
2245     }
2246
2247     fn with_generic_param_rib<'c, F>(
2248         &'c mut self,
2249         params: &'c [GenericParam],
2250         kind: RibKind<'a>,
2251         lifetime_kind: LifetimeRibKind,
2252         f: F,
2253     ) where
2254         F: FnOnce(&mut Self),
2255     {
2256         debug!("with_generic_param_rib");
2257         let LifetimeRibKind::Generics { binder, span: generics_span, kind: generics_kind, .. }
2258             = lifetime_kind else { panic!() };
2259
2260         let mut function_type_rib = Rib::new(kind);
2261         let mut function_value_rib = Rib::new(kind);
2262         let mut function_lifetime_rib = LifetimeRib::new(lifetime_kind);
2263         let mut seen_bindings = FxHashMap::default();
2264         // Store all seen lifetimes names from outer scopes.
2265         let mut seen_lifetimes = FxHashSet::default();
2266
2267         // We also can't shadow bindings from the parent item
2268         if let AssocItemRibKind = kind {
2269             let mut add_bindings_for_ns = |ns| {
2270                 let parent_rib = self.ribs[ns]
2271                     .iter()
2272                     .rfind(|r| matches!(r.kind, ItemRibKind(_)))
2273                     .expect("associated item outside of an item");
2274                 seen_bindings
2275                     .extend(parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span)));
2276             };
2277             add_bindings_for_ns(ValueNS);
2278             add_bindings_for_ns(TypeNS);
2279         }
2280
2281         // Forbid shadowing lifetime bindings
2282         for rib in self.lifetime_ribs.iter().rev() {
2283             seen_lifetimes.extend(rib.bindings.iter().map(|(ident, _)| *ident));
2284             if let LifetimeRibKind::Item = rib.kind {
2285                 break;
2286             }
2287         }
2288
2289         for param in params {
2290             let ident = param.ident.normalize_to_macros_2_0();
2291             debug!("with_generic_param_rib: {}", param.id);
2292
2293             if let GenericParamKind::Lifetime = param.kind
2294                 && let Some(&original) = seen_lifetimes.get(&ident)
2295             {
2296                 diagnostics::signal_lifetime_shadowing(self.r.session, original, param.ident);
2297                 // Record lifetime res, so lowering knows there is something fishy.
2298                 self.record_lifetime_param(param.id, LifetimeRes::Error);
2299                 continue;
2300             }
2301
2302             match seen_bindings.entry(ident) {
2303                 Entry::Occupied(entry) => {
2304                     let span = *entry.get();
2305                     let err = ResolutionError::NameAlreadyUsedInParameterList(ident.name, span);
2306                     self.report_error(param.ident.span, err);
2307                     if let GenericParamKind::Lifetime = param.kind {
2308                         // Record lifetime res, so lowering knows there is something fishy.
2309                         self.record_lifetime_param(param.id, LifetimeRes::Error);
2310                         continue;
2311                     }
2312                 }
2313                 Entry::Vacant(entry) => {
2314                     entry.insert(param.ident.span);
2315                 }
2316             }
2317
2318             if param.ident.name == kw::UnderscoreLifetime {
2319                 rustc_errors::struct_span_err!(
2320                     self.r.session,
2321                     param.ident.span,
2322                     E0637,
2323                     "`'_` cannot be used here"
2324                 )
2325                 .span_label(param.ident.span, "`'_` is a reserved lifetime name")
2326                 .emit();
2327                 // Record lifetime res, so lowering knows there is something fishy.
2328                 self.record_lifetime_param(param.id, LifetimeRes::Error);
2329                 continue;
2330             }
2331
2332             if param.ident.name == kw::StaticLifetime {
2333                 rustc_errors::struct_span_err!(
2334                     self.r.session,
2335                     param.ident.span,
2336                     E0262,
2337                     "invalid lifetime parameter name: `{}`",
2338                     param.ident,
2339                 )
2340                 .span_label(param.ident.span, "'static is a reserved lifetime name")
2341                 .emit();
2342                 // Record lifetime res, so lowering knows there is something fishy.
2343                 self.record_lifetime_param(param.id, LifetimeRes::Error);
2344                 continue;
2345             }
2346
2347             let def_id = self.r.local_def_id(param.id);
2348
2349             // Plain insert (no renaming).
2350             let (rib, def_kind) = match param.kind {
2351                 GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam),
2352                 GenericParamKind::Const { .. } => (&mut function_value_rib, DefKind::ConstParam),
2353                 GenericParamKind::Lifetime => {
2354                     let res = LifetimeRes::Param { param: def_id, binder };
2355                     self.record_lifetime_param(param.id, res);
2356                     function_lifetime_rib.bindings.insert(ident, (param.id, res));
2357                     continue;
2358                 }
2359             };
2360
2361             let res = match kind {
2362                 ItemRibKind(..) | AssocItemRibKind => Res::Def(def_kind, def_id.to_def_id()),
2363                 NormalRibKind => Res::Err,
2364                 _ => span_bug!(param.ident.span, "Unexpected rib kind {:?}", kind),
2365             };
2366             self.r.record_partial_res(param.id, PartialRes::new(res));
2367             rib.bindings.insert(ident, res);
2368         }
2369
2370         self.lifetime_ribs.push(function_lifetime_rib);
2371         self.ribs[ValueNS].push(function_value_rib);
2372         self.ribs[TypeNS].push(function_type_rib);
2373
2374         f(self);
2375
2376         self.ribs[TypeNS].pop();
2377         self.ribs[ValueNS].pop();
2378         let function_lifetime_rib = self.lifetime_ribs.pop().unwrap();
2379
2380         // Do not account for the parameters we just bound for function lifetime elision.
2381         if let Some(ref mut candidates) = self.lifetime_elision_candidates {
2382             for (_, res) in function_lifetime_rib.bindings.values() {
2383                 candidates.remove(res);
2384             }
2385         }
2386
2387         if let LifetimeBinderKind::BareFnType
2388         | LifetimeBinderKind::WhereBound
2389         | LifetimeBinderKind::Function
2390         | LifetimeBinderKind::ImplBlock = generics_kind
2391         {
2392             self.maybe_report_lifetime_uses(generics_span, params)
2393         }
2394     }
2395
2396     fn with_label_rib(&mut self, kind: RibKind<'a>, f: impl FnOnce(&mut Self)) {
2397         self.label_ribs.push(Rib::new(kind));
2398         f(self);
2399         self.label_ribs.pop();
2400     }
2401
2402     fn with_item_rib(&mut self, f: impl FnOnce(&mut Self)) {
2403         let kind = ItemRibKind(HasGenericParams::No);
2404         self.with_lifetime_rib(LifetimeRibKind::Item, |this| {
2405             this.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f))
2406         })
2407     }
2408
2409     // HACK(min_const_generics,const_evaluatable_unchecked): We
2410     // want to keep allowing `[0; std::mem::size_of::<*mut T>()]`
2411     // with a future compat lint for now. We do this by adding an
2412     // additional special case for repeat expressions.
2413     //
2414     // Note that we intentionally still forbid `[0; N + 1]` during
2415     // name resolution so that we don't extend the future
2416     // compat lint to new cases.
2417     #[instrument(level = "debug", skip(self, f))]
2418     fn with_constant_rib(
2419         &mut self,
2420         is_repeat: IsRepeatExpr,
2421         may_use_generics: ConstantHasGenerics,
2422         item: Option<(Ident, ConstantItemKind)>,
2423         f: impl FnOnce(&mut Self),
2424     ) {
2425         self.with_rib(ValueNS, ConstantItemRibKind(may_use_generics, item), |this| {
2426             this.with_rib(
2427                 TypeNS,
2428                 ConstantItemRibKind(
2429                     may_use_generics.force_yes_if(is_repeat == IsRepeatExpr::Yes),
2430                     item,
2431                 ),
2432                 |this| {
2433                     this.with_label_rib(ConstantItemRibKind(may_use_generics, item), f);
2434                 },
2435             )
2436         });
2437     }
2438
2439     fn with_current_self_type<T>(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T {
2440         // Handle nested impls (inside fn bodies)
2441         let previous_value =
2442             replace(&mut self.diagnostic_metadata.current_self_type, Some(self_type.clone()));
2443         let result = f(self);
2444         self.diagnostic_metadata.current_self_type = previous_value;
2445         result
2446     }
2447
2448     fn with_current_self_item<T>(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T {
2449         let previous_value =
2450             replace(&mut self.diagnostic_metadata.current_self_item, Some(self_item.id));
2451         let result = f(self);
2452         self.diagnostic_metadata.current_self_item = previous_value;
2453         result
2454     }
2455
2456     /// When evaluating a `trait` use its associated types' idents for suggestions in E0412.
2457     fn resolve_trait_items(&mut self, trait_items: &'ast [P<AssocItem>]) {
2458         let trait_assoc_items =
2459             replace(&mut self.diagnostic_metadata.current_trait_assoc_items, Some(&trait_items));
2460
2461         let walk_assoc_item =
2462             |this: &mut Self, generics: &Generics, kind, item: &'ast AssocItem| {
2463                 this.with_generic_param_rib(
2464                     &generics.params,
2465                     AssocItemRibKind,
2466                     LifetimeRibKind::Generics { binder: item.id, span: generics.span, kind },
2467                     |this| visit::walk_assoc_item(this, item, AssocCtxt::Trait),
2468                 );
2469             };
2470
2471         for item in trait_items {
2472             match &item.kind {
2473                 AssocItemKind::Const(_, ty, default) => {
2474                     self.visit_ty(ty);
2475                     // Only impose the restrictions of `ConstRibKind` for an
2476                     // actual constant expression in a provided default.
2477                     if let Some(expr) = default {
2478                         // We allow arbitrary const expressions inside of associated consts,
2479                         // even if they are potentially not const evaluatable.
2480                         //
2481                         // Type parameters can already be used and as associated consts are
2482                         // not used as part of the type system, this is far less surprising.
2483                         self.with_lifetime_rib(
2484                             LifetimeRibKind::Elided(LifetimeRes::Infer),
2485                             |this| {
2486                                 this.with_constant_rib(
2487                                     IsRepeatExpr::No,
2488                                     ConstantHasGenerics::Yes,
2489                                     None,
2490                                     |this| this.visit_expr(expr),
2491                                 )
2492                             },
2493                         );
2494                     }
2495                 }
2496                 AssocItemKind::Fn(box Fn { generics, .. }) => {
2497                     walk_assoc_item(self, generics, LifetimeBinderKind::Function, item);
2498                 }
2499                 AssocItemKind::Type(box TyAlias { generics, .. }) => self
2500                     .with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
2501                         walk_assoc_item(this, generics, LifetimeBinderKind::Item, item)
2502                     }),
2503                 AssocItemKind::MacCall(_) => {
2504                     panic!("unexpanded macro in resolve!")
2505                 }
2506             };
2507         }
2508
2509         self.diagnostic_metadata.current_trait_assoc_items = trait_assoc_items;
2510     }
2511
2512     /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`).
2513     fn with_optional_trait_ref<T>(
2514         &mut self,
2515         opt_trait_ref: Option<&TraitRef>,
2516         self_type: &'ast Ty,
2517         f: impl FnOnce(&mut Self, Option<DefId>) -> T,
2518     ) -> T {
2519         let mut new_val = None;
2520         let mut new_id = None;
2521         if let Some(trait_ref) = opt_trait_ref {
2522             let path: Vec<_> = Segment::from_path(&trait_ref.path);
2523             self.diagnostic_metadata.currently_processing_impl_trait =
2524                 Some((trait_ref.clone(), self_type.clone()));
2525             let res = self.smart_resolve_path_fragment(
2526                 None,
2527                 &path,
2528                 PathSource::Trait(AliasPossibility::No),
2529                 Finalize::new(trait_ref.ref_id, trait_ref.path.span),
2530             );
2531             self.diagnostic_metadata.currently_processing_impl_trait = None;
2532             if let Some(def_id) = res.expect_full_res().opt_def_id() {
2533                 new_id = Some(def_id);
2534                 new_val = Some((self.r.expect_module(def_id), trait_ref.clone()));
2535             }
2536         }
2537         let original_trait_ref = replace(&mut self.current_trait_ref, new_val);
2538         let result = f(self, new_id);
2539         self.current_trait_ref = original_trait_ref;
2540         result
2541     }
2542
2543     fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) {
2544         let mut self_type_rib = Rib::new(NormalRibKind);
2545
2546         // Plain insert (no renaming, since types are not currently hygienic)
2547         self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res);
2548         self.ribs[ns].push(self_type_rib);
2549         f(self);
2550         self.ribs[ns].pop();
2551     }
2552
2553     fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) {
2554         self.with_self_rib_ns(TypeNS, self_res, f)
2555     }
2556
2557     fn resolve_implementation(
2558         &mut self,
2559         generics: &'ast Generics,
2560         opt_trait_reference: &'ast Option<TraitRef>,
2561         self_type: &'ast Ty,
2562         item_id: NodeId,
2563         impl_items: &'ast [P<AssocItem>],
2564     ) {
2565         debug!("resolve_implementation");
2566         // If applicable, create a rib for the type parameters.
2567         self.with_generic_param_rib(
2568             &generics.params,
2569             ItemRibKind(HasGenericParams::Yes(generics.span)),
2570             LifetimeRibKind::Generics {
2571                 span: generics.span,
2572                 binder: item_id,
2573                 kind: LifetimeBinderKind::ImplBlock,
2574             },
2575             |this| {
2576                 // Dummy self type for better errors if `Self` is used in the trait path.
2577                 this.with_self_rib(Res::SelfTyParam { trait_: LOCAL_CRATE.as_def_id() }, |this| {
2578                     this.with_lifetime_rib(
2579                         LifetimeRibKind::AnonymousCreateParameter {
2580                             binder: item_id,
2581                             report_in_path: true
2582                         },
2583                         |this| {
2584                             // Resolve the trait reference, if necessary.
2585                             this.with_optional_trait_ref(
2586                                 opt_trait_reference.as_ref(),
2587                                 self_type,
2588                                 |this, trait_id| {
2589                                     let item_def_id = this.r.local_def_id(item_id);
2590
2591                                     // Register the trait definitions from here.
2592                                     if let Some(trait_id) = trait_id {
2593                                         this.r
2594                                             .trait_impls
2595                                             .entry(trait_id)
2596                                             .or_default()
2597                                             .push(item_def_id);
2598                                     }
2599
2600                                     let item_def_id = item_def_id.to_def_id();
2601                                     let res = Res::SelfTyAlias {
2602                                         alias_to: item_def_id,
2603                                         forbid_generic: false,
2604                                         is_trait_impl: trait_id.is_some()
2605                                     };
2606                                     this.with_self_rib(res, |this| {
2607                                         if let Some(trait_ref) = opt_trait_reference.as_ref() {
2608                                             // Resolve type arguments in the trait path.
2609                                             visit::walk_trait_ref(this, trait_ref);
2610                                         }
2611                                         // Resolve the self type.
2612                                         this.visit_ty(self_type);
2613                                         // Resolve the generic parameters.
2614                                         this.visit_generics(generics);
2615
2616                                         // Resolve the items within the impl.
2617                                         this.with_current_self_type(self_type, |this| {
2618                                             this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| {
2619                                                 debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)");
2620                                                 let mut seen_trait_items = Default::default();
2621                                                 for item in impl_items {
2622                                                     this.resolve_impl_item(&**item, &mut seen_trait_items);
2623                                                 }
2624                                             });
2625                                         });
2626                                     });
2627                                 },
2628                             )
2629                         },
2630                     );
2631                 });
2632             },
2633         );
2634     }
2635
2636     fn resolve_impl_item(
2637         &mut self,
2638         item: &'ast AssocItem,
2639         seen_trait_items: &mut FxHashMap<DefId, Span>,
2640     ) {
2641         use crate::ResolutionError::*;
2642         match &item.kind {
2643             AssocItemKind::Const(_, ty, default) => {
2644                 debug!("resolve_implementation AssocItemKind::Const");
2645                 // If this is a trait impl, ensure the const
2646                 // exists in trait
2647                 self.check_trait_item(
2648                     item.id,
2649                     item.ident,
2650                     &item.kind,
2651                     ValueNS,
2652                     item.span,
2653                     seen_trait_items,
2654                     |i, s, c| ConstNotMemberOfTrait(i, s, c),
2655                 );
2656
2657                 self.visit_ty(ty);
2658                 if let Some(expr) = default {
2659                     // We allow arbitrary const expressions inside of associated consts,
2660                     // even if they are potentially not const evaluatable.
2661                     //
2662                     // Type parameters can already be used and as associated consts are
2663                     // not used as part of the type system, this is far less surprising.
2664                     self.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Infer), |this| {
2665                         this.with_constant_rib(
2666                             IsRepeatExpr::No,
2667                             ConstantHasGenerics::Yes,
2668                             None,
2669                             |this| this.visit_expr(expr),
2670                         )
2671                     });
2672                 }
2673             }
2674             AssocItemKind::Fn(box Fn { generics, .. }) => {
2675                 debug!("resolve_implementation AssocItemKind::Fn");
2676                 // We also need a new scope for the impl item type parameters.
2677                 self.with_generic_param_rib(
2678                     &generics.params,
2679                     AssocItemRibKind,
2680                     LifetimeRibKind::Generics {
2681                         binder: item.id,
2682                         span: generics.span,
2683                         kind: LifetimeBinderKind::Function,
2684                     },
2685                     |this| {
2686                         // If this is a trait impl, ensure the method
2687                         // exists in trait
2688                         this.check_trait_item(
2689                             item.id,
2690                             item.ident,
2691                             &item.kind,
2692                             ValueNS,
2693                             item.span,
2694                             seen_trait_items,
2695                             |i, s, c| MethodNotMemberOfTrait(i, s, c),
2696                         );
2697
2698                         visit::walk_assoc_item(this, item, AssocCtxt::Impl)
2699                     },
2700                 );
2701             }
2702             AssocItemKind::Type(box TyAlias { generics, .. }) => {
2703                 debug!("resolve_implementation AssocItemKind::Type");
2704                 // We also need a new scope for the impl item type parameters.
2705                 self.with_generic_param_rib(
2706                     &generics.params,
2707                     AssocItemRibKind,
2708                     LifetimeRibKind::Generics {
2709                         binder: item.id,
2710                         span: generics.span,
2711                         kind: LifetimeBinderKind::Item,
2712                     },
2713                     |this| {
2714                         this.with_lifetime_rib(LifetimeRibKind::AnonymousReportError, |this| {
2715                             // If this is a trait impl, ensure the type
2716                             // exists in trait
2717                             this.check_trait_item(
2718                                 item.id,
2719                                 item.ident,
2720                                 &item.kind,
2721                                 TypeNS,
2722                                 item.span,
2723                                 seen_trait_items,
2724                                 |i, s, c| TypeNotMemberOfTrait(i, s, c),
2725                             );
2726
2727                             visit::walk_assoc_item(this, item, AssocCtxt::Impl)
2728                         });
2729                     },
2730                 );
2731             }
2732             AssocItemKind::MacCall(_) => {
2733                 panic!("unexpanded macro in resolve!")
2734             }
2735         }
2736     }
2737
2738     fn check_trait_item<F>(
2739         &mut self,
2740         id: NodeId,
2741         mut ident: Ident,
2742         kind: &AssocItemKind,
2743         ns: Namespace,
2744         span: Span,
2745         seen_trait_items: &mut FxHashMap<DefId, Span>,
2746         err: F,
2747     ) where
2748         F: FnOnce(Ident, String, Option<Symbol>) -> ResolutionError<'a>,
2749     {
2750         // If there is a TraitRef in scope for an impl, then the method must be in the trait.
2751         let Some((module, _)) = &self.current_trait_ref else { return; };
2752         ident.span.normalize_to_macros_2_0_and_adjust(module.expansion);
2753         let key = self.r.new_key(ident, ns);
2754         let mut binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
2755         debug!(?binding);
2756         if binding.is_none() {
2757             // We could not find the trait item in the correct namespace.
2758             // Check the other namespace to report an error.
2759             let ns = match ns {
2760                 ValueNS => TypeNS,
2761                 TypeNS => ValueNS,
2762                 _ => ns,
2763             };
2764             let key = self.r.new_key(ident, ns);
2765             binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding);
2766             debug!(?binding);
2767         }
2768         let Some(binding) = binding else {
2769             // We could not find the method: report an error.
2770             let candidate = self.find_similarly_named_assoc_item(ident.name, kind);
2771             let path = &self.current_trait_ref.as_ref().unwrap().1.path;
2772             let path_names = path_names_to_string(path);
2773             self.report_error(span, err(ident, path_names, candidate));
2774             return;
2775         };
2776
2777         let res = binding.res();
2778         let Res::Def(def_kind, id_in_trait) = res else { bug!() };
2779
2780         match seen_trait_items.entry(id_in_trait) {
2781             Entry::Occupied(entry) => {
2782                 self.report_error(
2783                     span,
2784                     ResolutionError::TraitImplDuplicate {
2785                         name: ident.name,
2786                         old_span: *entry.get(),
2787                         trait_item_span: binding.span,
2788                     },
2789                 );
2790                 return;
2791             }
2792             Entry::Vacant(entry) => {
2793                 entry.insert(span);
2794             }
2795         };
2796
2797         match (def_kind, kind) {
2798             (DefKind::AssocTy, AssocItemKind::Type(..))
2799             | (DefKind::AssocFn, AssocItemKind::Fn(..))
2800             | (DefKind::AssocConst, AssocItemKind::Const(..)) => {
2801                 self.r.record_partial_res(id, PartialRes::new(res));
2802                 return;
2803             }
2804             _ => {}
2805         }
2806
2807         // The method kind does not correspond to what appeared in the trait, report.
2808         let path = &self.current_trait_ref.as_ref().unwrap().1.path;
2809         let (code, kind) = match kind {
2810             AssocItemKind::Const(..) => (rustc_errors::error_code!(E0323), "const"),
2811             AssocItemKind::Fn(..) => (rustc_errors::error_code!(E0324), "method"),
2812             AssocItemKind::Type(..) => (rustc_errors::error_code!(E0325), "type"),
2813             AssocItemKind::MacCall(..) => span_bug!(span, "unexpanded macro"),
2814         };
2815         let trait_path = path_names_to_string(path);
2816         self.report_error(
2817             span,
2818             ResolutionError::TraitImplMismatch {
2819                 name: ident.name,
2820                 kind,
2821                 code,
2822                 trait_path,
2823                 trait_item_span: binding.span,
2824             },
2825         );
2826     }
2827
2828     fn resolve_params(&mut self, params: &'ast [Param]) {
2829         let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
2830         for Param { pat, ty, .. } in params {
2831             self.resolve_pattern(pat, PatternSource::FnParam, &mut bindings);
2832             self.visit_ty(ty);
2833             debug!("(resolving function / closure) recorded parameter");
2834         }
2835     }
2836
2837     fn resolve_local(&mut self, local: &'ast Local) {
2838         debug!("resolving local ({:?})", local);
2839         // Resolve the type.
2840         walk_list!(self, visit_ty, &local.ty);
2841
2842         // Resolve the initializer.
2843         if let Some((init, els)) = local.kind.init_else_opt() {
2844             self.visit_expr(init);
2845
2846             // Resolve the `else` block
2847             if let Some(els) = els {
2848                 self.visit_block(els);
2849             }
2850         }
2851
2852         // Resolve the pattern.
2853         self.resolve_pattern_top(&local.pat, PatternSource::Let);
2854     }
2855
2856     /// build a map from pattern identifiers to binding-info's.
2857     /// this is done hygienically. This could arise for a macro
2858     /// that expands into an or-pattern where one 'x' was from the
2859     /// user and one 'x' came from the macro.
2860     fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap {
2861         let mut binding_map = FxHashMap::default();
2862
2863         pat.walk(&mut |pat| {
2864             match pat.kind {
2865                 PatKind::Ident(annotation, ident, ref sub_pat)
2866                     if sub_pat.is_some() || self.is_base_res_local(pat.id) =>
2867                 {
2868                     binding_map.insert(ident, BindingInfo { span: ident.span, annotation });
2869                 }
2870                 PatKind::Or(ref ps) => {
2871                     // Check the consistency of this or-pattern and
2872                     // then add all bindings to the larger map.
2873                     for bm in self.check_consistent_bindings(ps) {
2874                         binding_map.extend(bm);
2875                     }
2876                     return false;
2877                 }
2878                 _ => {}
2879             }
2880
2881             true
2882         });
2883
2884         binding_map
2885     }
2886
2887     fn is_base_res_local(&self, nid: NodeId) -> bool {
2888         matches!(
2889             self.r.partial_res_map.get(&nid).map(|res| res.expect_full_res()),
2890             Some(Res::Local(..))
2891         )
2892     }
2893
2894     /// Checks that all of the arms in an or-pattern have exactly the
2895     /// same set of bindings, with the same binding modes for each.
2896     fn check_consistent_bindings(&mut self, pats: &[P<Pat>]) -> Vec<BindingMap> {
2897         let mut missing_vars = FxHashMap::default();
2898         let mut inconsistent_vars = FxHashMap::default();
2899
2900         // 1) Compute the binding maps of all arms.
2901         let maps = pats.iter().map(|pat| self.binding_mode_map(pat)).collect::<Vec<_>>();
2902
2903         // 2) Record any missing bindings or binding mode inconsistencies.
2904         for (map_outer, pat_outer) in pats.iter().enumerate().map(|(idx, pat)| (&maps[idx], pat)) {
2905             // Check against all arms except for the same pattern which is always self-consistent.
2906             let inners = pats
2907                 .iter()
2908                 .enumerate()
2909                 .filter(|(_, pat)| pat.id != pat_outer.id)
2910                 .flat_map(|(idx, _)| maps[idx].iter())
2911                 .map(|(key, binding)| (key.name, map_outer.get(&key), binding));
2912
2913             for (name, info, &binding_inner) in inners {
2914                 match info {
2915                     None => {
2916                         // The inner binding is missing in the outer.
2917                         let binding_error =
2918                             missing_vars.entry(name).or_insert_with(|| BindingError {
2919                                 name,
2920                                 origin: BTreeSet::new(),
2921                                 target: BTreeSet::new(),
2922                                 could_be_path: name.as_str().starts_with(char::is_uppercase),
2923                             });
2924                         binding_error.origin.insert(binding_inner.span);
2925                         binding_error.target.insert(pat_outer.span);
2926                     }
2927                     Some(binding_outer) => {
2928                         if binding_outer.annotation != binding_inner.annotation {
2929                             // The binding modes in the outer and inner bindings differ.
2930                             inconsistent_vars
2931                                 .entry(name)
2932                                 .or_insert((binding_inner.span, binding_outer.span));
2933                         }
2934                     }
2935                 }
2936             }
2937         }
2938
2939         // 3) Report all missing variables we found.
2940         let mut missing_vars = missing_vars.into_iter().collect::<Vec<_>>();
2941         missing_vars.sort_by_key(|&(sym, ref _err)| sym);
2942
2943         for (name, mut v) in missing_vars.into_iter() {
2944             if inconsistent_vars.contains_key(&name) {
2945                 v.could_be_path = false;
2946             }
2947             self.report_error(
2948                 *v.origin.iter().next().unwrap(),
2949                 ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
2950             );
2951         }
2952
2953         // 4) Report all inconsistencies in binding modes we found.
2954         let mut inconsistent_vars = inconsistent_vars.iter().collect::<Vec<_>>();
2955         inconsistent_vars.sort();
2956         for (name, v) in inconsistent_vars {
2957             self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1));
2958         }
2959
2960         // 5) Finally bubble up all the binding maps.
2961         maps
2962     }
2963
2964     /// Check the consistency of the outermost or-patterns.
2965     fn check_consistent_bindings_top(&mut self, pat: &'ast Pat) {
2966         pat.walk(&mut |pat| match pat.kind {
2967             PatKind::Or(ref ps) => {
2968                 self.check_consistent_bindings(ps);
2969                 false
2970             }
2971             _ => true,
2972         })
2973     }
2974
2975     fn resolve_arm(&mut self, arm: &'ast Arm) {
2976         self.with_rib(ValueNS, NormalRibKind, |this| {
2977             this.resolve_pattern_top(&arm.pat, PatternSource::Match);
2978             walk_list!(this, visit_expr, &arm.guard);
2979             this.visit_expr(&arm.body);
2980         });
2981     }
2982
2983     /// Arising from `source`, resolve a top level pattern.
2984     fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) {
2985         let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
2986         self.resolve_pattern(pat, pat_src, &mut bindings);
2987     }
2988
2989     fn resolve_pattern(
2990         &mut self,
2991         pat: &'ast Pat,
2992         pat_src: PatternSource,
2993         bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
2994     ) {
2995         // We walk the pattern before declaring the pattern's inner bindings,
2996         // so that we avoid resolving a literal expression to a binding defined
2997         // by the pattern.
2998         visit::walk_pat(self, pat);
2999         self.resolve_pattern_inner(pat, pat_src, bindings);
3000         // This has to happen *after* we determine which pat_idents are variants:
3001         self.check_consistent_bindings_top(pat);
3002     }
3003
3004     /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`.
3005     ///
3006     /// ### `bindings`
3007     ///
3008     /// A stack of sets of bindings accumulated.
3009     ///
3010     /// In each set, `PatBoundCtx::Product` denotes that a found binding in it should
3011     /// be interpreted as re-binding an already bound binding. This results in an error.
3012     /// Meanwhile, `PatBound::Or` denotes that a found binding in the set should result
3013     /// in reusing this binding rather than creating a fresh one.
3014     ///
3015     /// When called at the top level, the stack must have a single element
3016     /// with `PatBound::Product`. Otherwise, pushing to the stack happens as
3017     /// or-patterns (`p_0 | ... | p_n`) are encountered and the context needs
3018     /// to be switched to `PatBoundCtx::Or` and then `PatBoundCtx::Product` for each `p_i`.
3019     /// When each `p_i` has been dealt with, the top set is merged with its parent.
3020     /// When a whole or-pattern has been dealt with, the thing happens.
3021     ///
3022     /// See the implementation and `fresh_binding` for more details.
3023     fn resolve_pattern_inner(
3024         &mut self,
3025         pat: &Pat,
3026         pat_src: PatternSource,
3027         bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
3028     ) {
3029         // Visit all direct subpatterns of this pattern.
3030         pat.walk(&mut |pat| {
3031             debug!("resolve_pattern pat={:?} node={:?}", pat, pat.kind);
3032             match pat.kind {
3033                 PatKind::Ident(bmode, ident, ref sub) => {
3034                     // First try to resolve the identifier as some existing entity,
3035                     // then fall back to a fresh binding.
3036                     let has_sub = sub.is_some();
3037                     let res = self
3038                         .try_resolve_as_non_binding(pat_src, bmode, ident, has_sub)
3039                         .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings));
3040                     self.r.record_partial_res(pat.id, PartialRes::new(res));
3041                     self.r.record_pat_span(pat.id, pat.span);
3042                 }
3043                 PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => {
3044                     self.smart_resolve_path(
3045                         pat.id,
3046                         qself.as_ref(),
3047                         path,
3048                         PathSource::TupleStruct(
3049                             pat.span,
3050                             self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)),
3051                         ),
3052                     );
3053                 }
3054                 PatKind::Path(ref qself, ref path) => {
3055                     self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
3056                 }
3057                 PatKind::Struct(ref qself, ref path, ..) => {
3058                     self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Struct);
3059                 }
3060                 PatKind::Or(ref ps) => {
3061                     // Add a new set of bindings to the stack. `Or` here records that when a
3062                     // binding already exists in this set, it should not result in an error because
3063                     // `V1(a) | V2(a)` must be allowed and are checked for consistency later.
3064                     bindings.push((PatBoundCtx::Or, Default::default()));
3065                     for p in ps {
3066                         // Now we need to switch back to a product context so that each
3067                         // part of the or-pattern internally rejects already bound names.
3068                         // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad.
3069                         bindings.push((PatBoundCtx::Product, Default::default()));
3070                         self.resolve_pattern_inner(p, pat_src, bindings);
3071                         // Move up the non-overlapping bindings to the or-pattern.
3072                         // Existing bindings just get "merged".
3073                         let collected = bindings.pop().unwrap().1;
3074                         bindings.last_mut().unwrap().1.extend(collected);
3075                     }
3076                     // This or-pattern itself can itself be part of a product,
3077                     // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`.
3078                     // Both cases bind `a` again in a product pattern and must be rejected.
3079                     let collected = bindings.pop().unwrap().1;
3080                     bindings.last_mut().unwrap().1.extend(collected);
3081
3082                     // Prevent visiting `ps` as we've already done so above.
3083                     return false;
3084                 }
3085                 _ => {}
3086             }
3087             true
3088         });
3089     }
3090
3091     fn fresh_binding(
3092         &mut self,
3093         ident: Ident,
3094         pat_id: NodeId,
3095         pat_src: PatternSource,
3096         bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet<Ident>); 1]>,
3097     ) -> Res {
3098         // Add the binding to the local ribs, if it doesn't already exist in the bindings map.
3099         // (We must not add it if it's in the bindings map because that breaks the assumptions
3100         // later passes make about or-patterns.)
3101         let ident = ident.normalize_to_macro_rules();
3102
3103         let mut bound_iter = bindings.iter().filter(|(_, set)| set.contains(&ident));
3104         // Already bound in a product pattern? e.g. `(a, a)` which is not allowed.
3105         let already_bound_and = bound_iter.clone().any(|(ctx, _)| *ctx == PatBoundCtx::Product);
3106         // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`.
3107         // This is *required* for consistency which is checked later.
3108         let already_bound_or = bound_iter.any(|(ctx, _)| *ctx == PatBoundCtx::Or);
3109
3110         if already_bound_and {
3111             // Overlap in a product pattern somewhere; report an error.
3112             use ResolutionError::*;
3113             let error = match pat_src {
3114                 // `fn f(a: u8, a: u8)`:
3115                 PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList,
3116                 // `Variant(a, a)`:
3117                 _ => IdentifierBoundMoreThanOnceInSamePattern,
3118             };
3119             self.report_error(ident.span, error(ident.name));
3120         }
3121
3122         // Record as bound if it's valid:
3123         let ident_valid = ident.name != kw::Empty;
3124         if ident_valid {
3125             bindings.last_mut().unwrap().1.insert(ident);
3126         }
3127
3128         if already_bound_or {
3129             // `Variant1(a) | Variant2(a)`, ok
3130             // Reuse definition from the first `a`.
3131             self.innermost_rib_bindings(ValueNS)[&ident]
3132         } else {
3133             let res = Res::Local(pat_id);
3134             if ident_valid {
3135                 // A completely fresh binding add to the set if it's valid.
3136                 self.innermost_rib_bindings(ValueNS).insert(ident, res);
3137             }
3138             res
3139         }
3140     }
3141
3142     fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut IdentMap<Res> {
3143         &mut self.ribs[ns].last_mut().unwrap().bindings
3144     }
3145
3146     fn try_resolve_as_non_binding(
3147         &mut self,
3148         pat_src: PatternSource,
3149         ann: BindingAnnotation,
3150         ident: Ident,
3151         has_sub: bool,
3152     ) -> Option<Res> {
3153         // An immutable (no `mut`) by-value (no `ref`) binding pattern without
3154         // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
3155         // also be interpreted as a path to e.g. a constant, variant, etc.
3156         let is_syntactic_ambiguity = !has_sub && ann == BindingAnnotation::NONE;
3157
3158         let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?;
3159         let (res, binding) = match ls_binding {
3160             LexicalScopeBinding::Item(binding)
3161                 if is_syntactic_ambiguity && binding.is_ambiguity() =>
3162             {
3163                 // For ambiguous bindings we don't know all their definitions and cannot check
3164                 // whether they can be shadowed by fresh bindings or not, so force an error.
3165                 // issues/33118#issuecomment-233962221 (see below) still applies here,
3166                 // but we have to ignore it for backward compatibility.
3167                 self.r.record_use(ident, binding, false);
3168                 return None;
3169             }
3170             LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)),
3171             LexicalScopeBinding::Res(res) => (res, None),
3172         };
3173
3174         match res {
3175             Res::SelfCtor(_) // See #70549.
3176             | Res::Def(
3177                 DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::ConstParam,
3178                 _,
3179             ) if is_syntactic_ambiguity => {
3180                 // Disambiguate in favor of a unit struct/variant or constant pattern.
3181                 if let Some(binding) = binding {
3182                     self.r.record_use(ident, binding, false);
3183                 }
3184                 Some(res)
3185             }
3186             Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::Static(_), _) => {
3187                 // This is unambiguously a fresh binding, either syntactically
3188                 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
3189                 // to something unusable as a pattern (e.g., constructor function),
3190                 // but we still conservatively report an error, see
3191                 // issues/33118#issuecomment-233962221 for one reason why.
3192                 let binding = binding.expect("no binding for a ctor or static");
3193                 self.report_error(
3194                     ident.span,
3195                     ResolutionError::BindingShadowsSomethingUnacceptable {
3196                         shadowing_binding: pat_src,
3197                         name: ident.name,
3198                         participle: if binding.is_import() { "imported" } else { "defined" },
3199                         article: binding.res().article(),
3200                         shadowed_binding: binding.res(),
3201                         shadowed_binding_span: binding.span,
3202                     },
3203                 );
3204                 None
3205             }
3206             Res::Def(DefKind::ConstParam, def_id) => {
3207                 // Same as for DefKind::Const above, but here, `binding` is `None`, so we
3208                 // have to construct the error differently
3209                 self.report_error(
3210                     ident.span,
3211                     ResolutionError::BindingShadowsSomethingUnacceptable {
3212                         shadowing_binding: pat_src,
3213                         name: ident.name,
3214                         participle: "defined",
3215                         article: res.article(),
3216                         shadowed_binding: res,
3217                         shadowed_binding_span: self.r.opt_span(def_id).expect("const parameter defined outside of local crate"),
3218                     }
3219                 );
3220                 None
3221             }
3222             Res::Def(DefKind::Fn, _) | Res::Local(..) | Res::Err => {
3223                 // These entities are explicitly allowed to be shadowed by fresh bindings.
3224                 None
3225             }
3226             Res::SelfCtor(_) => {
3227                 // We resolve `Self` in pattern position as an ident sometimes during recovery,
3228                 // so delay a bug instead of ICEing.
3229                 self.r.session.delay_span_bug(
3230                     ident.span,
3231                     "unexpected `SelfCtor` in pattern, expected identifier"
3232                 );
3233                 None
3234             }
3235             _ => span_bug!(
3236                 ident.span,
3237                 "unexpected resolution for an identifier in pattern: {:?}",
3238                 res,
3239             ),
3240         }
3241     }
3242
3243     // High-level and context dependent path resolution routine.
3244     // Resolves the path and records the resolution into definition map.
3245     // If resolution fails tries several techniques to find likely
3246     // resolution candidates, suggest imports or other help, and report
3247     // errors in user friendly way.
3248     fn smart_resolve_path(
3249         &mut self,
3250         id: NodeId,
3251         qself: Option<&QSelf>,
3252         path: &Path,
3253         source: PathSource<'ast>,
3254     ) {
3255         self.smart_resolve_path_fragment(
3256             qself,
3257             &Segment::from_path(path),
3258             source,
3259             Finalize::new(id, path.span),
3260         );
3261     }
3262
3263     fn smart_resolve_path_fragment(
3264         &mut self,
3265         qself: Option<&QSelf>,
3266         path: &[Segment],
3267         source: PathSource<'ast>,
3268         finalize: Finalize,
3269     ) -> PartialRes {
3270         debug!(
3271             "smart_resolve_path_fragment(qself={:?}, path={:?}, finalize={:?})",
3272             qself, path, finalize,
3273         );
3274         let ns = source.namespace();
3275
3276         let Finalize { node_id, path_span, .. } = finalize;
3277         let report_errors = |this: &mut Self, res: Option<Res>| {
3278             if this.should_report_errs() {
3279                 let (err, candidates) =
3280                     this.smart_resolve_report_errors(path, path_span, source, res);
3281
3282                 let def_id = this.parent_scope.module.nearest_parent_mod();
3283                 let instead = res.is_some();
3284                 let suggestion =
3285                     if res.is_none() { this.report_missing_type_error(path) } else { None };
3286
3287                 this.r.use_injections.push(UseError {
3288                     err,
3289                     candidates,
3290                     def_id,
3291                     instead,
3292                     suggestion,
3293                     path: path.into(),
3294                     is_call: source.is_call(),
3295                 });
3296             }
3297
3298             PartialRes::new(Res::Err)
3299         };
3300
3301         // For paths originating from calls (like in `HashMap::new()`), tries
3302         // to enrich the plain `failed to resolve: ...` message with hints
3303         // about possible missing imports.
3304         //
3305         // Similar thing, for types, happens in `report_errors` above.
3306         let report_errors_for_call = |this: &mut Self, parent_err: Spanned<ResolutionError<'a>>| {
3307             if !source.is_call() {
3308                 return Some(parent_err);
3309             }
3310
3311             // Before we start looking for candidates, we have to get our hands
3312             // on the type user is trying to perform invocation on; basically:
3313             // we're transforming `HashMap::new` into just `HashMap`.
3314             let path = match path.split_last() {
3315                 Some((_, path)) if !path.is_empty() => path,
3316                 _ => return Some(parent_err),
3317             };
3318
3319             let (mut err, candidates) =
3320                 this.smart_resolve_report_errors(path, path_span, PathSource::Type, None);
3321
3322             if candidates.is_empty() {
3323                 err.cancel();
3324                 return Some(parent_err);
3325             }
3326
3327             // There are two different error messages user might receive at
3328             // this point:
3329             // - E0412 cannot find type `{}` in this scope
3330             // - E0433 failed to resolve: use of undeclared type or module `{}`
3331             //
3332             // The first one is emitted for paths in type-position, and the
3333             // latter one - for paths in expression-position.
3334             //
3335             // Thus (since we're in expression-position at this point), not to
3336             // confuse the user, we want to keep the *message* from E0432 (so
3337             // `parent_err`), but we want *hints* from E0412 (so `err`).
3338             //
3339             // And that's what happens below - we're just mixing both messages
3340             // into a single one.
3341             let mut parent_err = this.r.into_struct_error(parent_err.span, parent_err.node);
3342
3343             err.message = take(&mut parent_err.message);
3344             err.code = take(&mut parent_err.code);
3345             err.children = take(&mut parent_err.children);
3346
3347             parent_err.cancel();
3348
3349             let def_id = this.parent_scope.module.nearest_parent_mod();
3350
3351             if this.should_report_errs() {
3352                 this.r.use_injections.push(UseError {
3353                     err,
3354                     candidates,
3355                     def_id,
3356                     instead: false,
3357                     suggestion: None,
3358                     path: path.into(),
3359                     is_call: source.is_call(),
3360                 });
3361             } else {
3362                 err.cancel();
3363             }
3364
3365             // We don't return `Some(parent_err)` here, because the error will
3366             // be already printed as part of the `use` injections
3367             None
3368         };
3369
3370         let partial_res = match self.resolve_qpath_anywhere(
3371             qself,
3372             path,
3373             ns,
3374             path_span,
3375             source.defer_to_typeck(),
3376             finalize,
3377         ) {
3378             Ok(Some(partial_res)) if let Some(res) = partial_res.full_res() => {
3379                 if source.is_expected(res) || res == Res::Err {
3380                     partial_res
3381                 } else {
3382                     report_errors(self, Some(res))
3383                 }
3384             }
3385
3386             Ok(Some(partial_res)) if source.defer_to_typeck() => {
3387                 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
3388                 // or `<T>::A::B`. If `B` should be resolved in value namespace then
3389                 // it needs to be added to the trait map.
3390                 if ns == ValueNS {
3391                     let item_name = path.last().unwrap().ident;
3392                     let traits = self.traits_in_scope(item_name, ns);
3393                     self.r.trait_map.insert(node_id, traits);
3394                 }
3395
3396                 if PrimTy::from_name(path[0].ident.name).is_some() {
3397                     let mut std_path = Vec::with_capacity(1 + path.len());
3398
3399                     std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std)));
3400                     std_path.extend(path);
3401                     if let PathResult::Module(_) | PathResult::NonModule(_) =
3402                         self.resolve_path(&std_path, Some(ns), None)
3403                     {
3404                         // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
3405                         let item_span =
3406                             path.iter().last().map_or(path_span, |segment| segment.ident.span);
3407
3408                         self.r.confused_type_with_std_module.insert(item_span, path_span);
3409                         self.r.confused_type_with_std_module.insert(path_span, path_span);
3410                     }
3411                 }
3412
3413                 partial_res
3414             }
3415
3416             Err(err) => {
3417                 if let Some(err) = report_errors_for_call(self, err) {
3418                     self.report_error(err.span, err.node);
3419                 }
3420
3421                 PartialRes::new(Res::Err)
3422             }
3423
3424             _ => report_errors(self, None),
3425         };
3426
3427         if !matches!(source, PathSource::TraitItem(..)) {
3428             // Avoid recording definition of `A::B` in `<T as A>::B::C`.
3429             self.r.record_partial_res(node_id, partial_res);
3430             self.resolve_elided_lifetimes_in_path(node_id, partial_res, path, source, path_span);
3431         }
3432
3433         partial_res
3434     }
3435
3436     fn self_type_is_available(&mut self) -> bool {
3437         let binding = self
3438             .maybe_resolve_ident_in_lexical_scope(Ident::with_dummy_span(kw::SelfUpper), TypeNS);
3439         if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
3440     }
3441
3442     fn self_value_is_available(&mut self, self_span: Span) -> bool {
3443         let ident = Ident::new(kw::SelfLower, self_span);
3444         let binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS);
3445         if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
3446     }
3447
3448     /// A wrapper around [`Resolver::report_error`].
3449     ///
3450     /// This doesn't emit errors for function bodies if this is rustdoc.
3451     fn report_error(&mut self, span: Span, resolution_error: ResolutionError<'a>) {
3452         if self.should_report_errs() {
3453             self.r.report_error(span, resolution_error);
3454         }
3455     }
3456
3457     #[inline]
3458     /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items.
3459     fn should_report_errs(&self) -> bool {
3460         !(self.r.session.opts.actually_rustdoc && self.in_func_body)
3461     }
3462
3463     // Resolve in alternative namespaces if resolution in the primary namespace fails.
3464     fn resolve_qpath_anywhere(
3465         &mut self,
3466         qself: Option<&QSelf>,
3467         path: &[Segment],
3468         primary_ns: Namespace,
3469         span: Span,
3470         defer_to_typeck: bool,
3471         finalize: Finalize,
3472     ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
3473         let mut fin_res = None;
3474
3475         for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() {
3476             if i == 0 || ns != primary_ns {
3477                 match self.resolve_qpath(qself, path, ns, finalize)? {
3478                     Some(partial_res)
3479                         if partial_res.unresolved_segments() == 0 || defer_to_typeck =>
3480                     {
3481                         return Ok(Some(partial_res));
3482                     }
3483                     partial_res => {
3484                         if fin_res.is_none() {
3485                             fin_res = partial_res;
3486                         }
3487                     }
3488                 }
3489             }
3490         }
3491
3492         assert!(primary_ns != MacroNS);
3493
3494         if qself.is_none() {
3495             let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
3496             let path = Path { segments: path.iter().map(path_seg).collect(), span, tokens: None };
3497             if let Ok((_, res)) =
3498                 self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false)
3499             {
3500                 return Ok(Some(PartialRes::new(res)));
3501             }
3502         }
3503
3504         Ok(fin_res)
3505     }
3506
3507     /// Handles paths that may refer to associated items.
3508     fn resolve_qpath(
3509         &mut self,
3510         qself: Option<&QSelf>,
3511         path: &[Segment],
3512         ns: Namespace,
3513         finalize: Finalize,
3514     ) -> Result<Option<PartialRes>, Spanned<ResolutionError<'a>>> {
3515         debug!(
3516             "resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
3517             qself, path, ns, finalize,
3518         );
3519
3520         if let Some(qself) = qself {
3521             if qself.position == 0 {
3522                 // This is a case like `<T>::B`, where there is no
3523                 // trait to resolve.  In that case, we leave the `B`
3524                 // segment to be resolved by type-check.
3525                 return Ok(Some(PartialRes::with_unresolved_segments(
3526                     Res::Def(DefKind::Mod, CRATE_DEF_ID.to_def_id()),
3527                     path.len(),
3528                 )));
3529             }
3530
3531             // Make sure `A::B` in `<T as A::B>::C` is a trait item.
3532             //
3533             // Currently, `path` names the full item (`A::B::C`, in
3534             // our example).  so we extract the prefix of that that is
3535             // the trait (the slice upto and including
3536             // `qself.position`). And then we recursively resolve that,
3537             // but with `qself` set to `None`.
3538             let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
3539             let partial_res = self.smart_resolve_path_fragment(
3540                 None,
3541                 &path[..=qself.position],
3542                 PathSource::TraitItem(ns),
3543                 Finalize::with_root_span(finalize.node_id, finalize.path_span, qself.path_span),
3544             );
3545
3546             // The remaining segments (the `C` in our example) will
3547             // have to be resolved by type-check, since that requires doing
3548             // trait resolution.
3549             return Ok(Some(PartialRes::with_unresolved_segments(
3550                 partial_res.base_res(),
3551                 partial_res.unresolved_segments() + path.len() - qself.position - 1,
3552             )));
3553         }
3554
3555         let result = match self.resolve_path(&path, Some(ns), Some(finalize)) {
3556             PathResult::NonModule(path_res) => path_res,
3557             PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
3558                 PartialRes::new(module.res().unwrap())
3559             }
3560             // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
3561             // don't report an error right away, but try to fallback to a primitive type.
3562             // So, we are still able to successfully resolve something like
3563             //
3564             // use std::u8; // bring module u8 in scope
3565             // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
3566             //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
3567             //                     // not to non-existent std::u8::max_value
3568             // }
3569             //
3570             // Such behavior is required for backward compatibility.
3571             // The same fallback is used when `a` resolves to nothing.
3572             PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. }
3573                 if (ns == TypeNS || path.len() > 1)
3574                     && PrimTy::from_name(path[0].ident.name).is_some() =>
3575             {
3576                 let prim = PrimTy::from_name(path[0].ident.name).unwrap();
3577                 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
3578             }
3579             PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
3580                 PartialRes::new(module.res().unwrap())
3581             }
3582             PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
3583                 return Err(respan(span, ResolutionError::FailedToResolve { label, suggestion }));
3584             }
3585             PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None),
3586             PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"),
3587         };
3588
3589         if path.len() > 1
3590             && let Some(res) = result.full_res()
3591             && res != Res::Err
3592             && path[0].ident.name != kw::PathRoot
3593             && path[0].ident.name != kw::DollarCrate
3594         {
3595             let unqualified_result = {
3596                 match self.resolve_path(&[*path.last().unwrap()], Some(ns), None) {
3597                     PathResult::NonModule(path_res) => path_res.expect_full_res(),
3598                     PathResult::Module(ModuleOrUniformRoot::Module(module)) => {
3599                         module.res().unwrap()
3600                     }
3601                     _ => return Ok(Some(result)),
3602                 }
3603             };
3604             if res == unqualified_result {
3605                 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
3606                 self.r.lint_buffer.buffer_lint(
3607                     lint,
3608                     finalize.node_id,
3609                     finalize.path_span,
3610                     "unnecessary qualification",
3611                 )
3612             }
3613         }
3614
3615         Ok(Some(result))
3616     }
3617
3618     fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
3619         if let Some(label) = label {
3620             if label.ident.as_str().as_bytes()[1] != b'_' {
3621                 self.diagnostic_metadata.unused_labels.insert(id, label.ident.span);
3622             }
3623
3624             if let Ok((_, orig_span)) = self.resolve_label(label.ident) {
3625                 diagnostics::signal_label_shadowing(self.r.session, orig_span, label.ident)
3626             }
3627
3628             self.with_label_rib(NormalRibKind, |this| {
3629                 let ident = label.ident.normalize_to_macro_rules();
3630                 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
3631                 f(this);
3632             });
3633         } else {
3634             f(self);
3635         }
3636     }
3637
3638     fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &'ast Block) {
3639         self.with_resolved_label(label, id, |this| this.visit_block(block));
3640     }
3641
3642     fn resolve_block(&mut self, block: &'ast Block) {
3643         debug!("(resolving block) entering block");
3644         // Move down in the graph, if there's an anonymous module rooted here.
3645         let orig_module = self.parent_scope.module;
3646         let anonymous_module = self.r.block_map.get(&block.id).cloned(); // clones a reference
3647
3648         let mut num_macro_definition_ribs = 0;
3649         if let Some(anonymous_module) = anonymous_module {
3650             debug!("(resolving block) found anonymous module, moving down");
3651             self.ribs[ValueNS].push(Rib::new(ModuleRibKind(anonymous_module)));
3652             self.ribs[TypeNS].push(Rib::new(ModuleRibKind(anonymous_module)));
3653             self.parent_scope.module = anonymous_module;
3654         } else {
3655             self.ribs[ValueNS].push(Rib::new(NormalRibKind));
3656         }
3657
3658         let prev = self.diagnostic_metadata.current_block_could_be_bare_struct_literal.take();
3659         if let (true, [Stmt { kind: StmtKind::Expr(expr), .. }]) =
3660             (block.could_be_bare_literal, &block.stmts[..])
3661             && let ExprKind::Type(..) = expr.kind
3662         {
3663             self.diagnostic_metadata.current_block_could_be_bare_struct_literal =
3664             Some(block.span);
3665         }
3666         // Descend into the block.
3667         for stmt in &block.stmts {
3668             if let StmtKind::Item(ref item) = stmt.kind
3669                 && let ItemKind::MacroDef(..) = item.kind {
3670                 num_macro_definition_ribs += 1;
3671                 let res = self.r.local_def_id(item.id).to_def_id();
3672                 self.ribs[ValueNS].push(Rib::new(MacroDefinition(res)));
3673                 self.label_ribs.push(Rib::new(MacroDefinition(res)));
3674             }
3675
3676             self.visit_stmt(stmt);
3677         }
3678         self.diagnostic_metadata.current_block_could_be_bare_struct_literal = prev;
3679
3680         // Move back up.
3681         self.parent_scope.module = orig_module;
3682         for _ in 0..num_macro_definition_ribs {
3683             self.ribs[ValueNS].pop();
3684             self.label_ribs.pop();
3685         }
3686         self.ribs[ValueNS].pop();
3687         if anonymous_module.is_some() {
3688             self.ribs[TypeNS].pop();
3689         }
3690         debug!("(resolving block) leaving block");
3691     }
3692
3693     fn resolve_anon_const(&mut self, constant: &'ast AnonConst, is_repeat: IsRepeatExpr) {
3694         debug!("resolve_anon_const {:?} is_repeat: {:?}", constant, is_repeat);
3695         self.with_constant_rib(
3696             is_repeat,
3697             if constant.value.is_potential_trivial_const_param() {
3698                 ConstantHasGenerics::Yes
3699             } else {
3700                 ConstantHasGenerics::No
3701             },
3702             None,
3703             |this| visit::walk_anon_const(this, constant),
3704         );
3705     }
3706
3707     fn resolve_inline_const(&mut self, constant: &'ast AnonConst) {
3708         debug!("resolve_anon_const {constant:?}");
3709         self.with_constant_rib(IsRepeatExpr::No, ConstantHasGenerics::Yes, None, |this| {
3710             visit::walk_anon_const(this, constant)
3711         });
3712     }
3713
3714     fn resolve_expr(&mut self, expr: &'ast Expr, parent: Option<&'ast Expr>) {
3715         // First, record candidate traits for this expression if it could
3716         // result in the invocation of a method call.
3717
3718         self.record_candidate_traits_for_expr_if_necessary(expr);
3719
3720         // Next, resolve the node.
3721         match expr.kind {
3722             ExprKind::Path(ref qself, ref path) => {
3723                 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
3724                 visit::walk_expr(self, expr);
3725             }
3726
3727             ExprKind::Struct(ref se) => {
3728                 self.smart_resolve_path(expr.id, se.qself.as_ref(), &se.path, PathSource::Struct);
3729                 visit::walk_expr(self, expr);
3730             }
3731
3732             ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
3733                 match self.resolve_label(label.ident) {
3734                     Ok((node_id, _)) => {
3735                         // Since this res is a label, it is never read.
3736                         self.r.label_res_map.insert(expr.id, node_id);
3737                         self.diagnostic_metadata.unused_labels.remove(&node_id);
3738                     }
3739                     Err(error) => {
3740                         self.report_error(label.ident.span, error);
3741                     }
3742                 }
3743
3744                 // visit `break` argument if any
3745                 visit::walk_expr(self, expr);
3746             }
3747
3748             ExprKind::Break(None, Some(ref e)) => {
3749                 // We use this instead of `visit::walk_expr` to keep the parent expr around for
3750                 // better diagnostics.
3751                 self.resolve_expr(e, Some(&expr));
3752             }
3753
3754             ExprKind::Let(ref pat, ref scrutinee, _) => {
3755                 self.visit_expr(scrutinee);
3756                 self.resolve_pattern_top(pat, PatternSource::Let);
3757             }
3758
3759             ExprKind::If(ref cond, ref then, ref opt_else) => {
3760                 self.with_rib(ValueNS, NormalRibKind, |this| {
3761                     let old = this.diagnostic_metadata.in_if_condition.replace(cond);
3762                     this.visit_expr(cond);
3763                     this.diagnostic_metadata.in_if_condition = old;
3764                     this.visit_block(then);
3765                 });
3766                 if let Some(expr) = opt_else {
3767                     self.visit_expr(expr);
3768                 }
3769             }
3770
3771             ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
3772
3773             ExprKind::While(ref cond, ref block, label) => {
3774                 self.with_resolved_label(label, expr.id, |this| {
3775                     this.with_rib(ValueNS, NormalRibKind, |this| {
3776                         let old = this.diagnostic_metadata.in_if_condition.replace(cond);
3777                         this.visit_expr(cond);
3778                         this.diagnostic_metadata.in_if_condition = old;
3779                         this.visit_block(block);
3780                     })
3781                 });
3782             }
3783
3784             ExprKind::ForLoop(ref pat, ref iter_expr, ref block, label) => {
3785                 self.visit_expr(iter_expr);
3786                 self.with_rib(ValueNS, NormalRibKind, |this| {
3787                     this.resolve_pattern_top(pat, PatternSource::For);
3788                     this.resolve_labeled_block(label, expr.id, block);
3789                 });
3790             }
3791
3792             ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
3793
3794             // Equivalent to `visit::walk_expr` + passing some context to children.
3795             ExprKind::Field(ref subexpression, _) => {
3796                 self.resolve_expr(subexpression, Some(expr));
3797             }
3798             ExprKind::MethodCall(ref segment, ref receiver, ref arguments, _) => {
3799                 self.resolve_expr(receiver, Some(expr));
3800                 for argument in arguments {
3801                     self.resolve_expr(argument, None);
3802                 }
3803                 self.visit_path_segment(segment);
3804             }
3805
3806             ExprKind::Call(ref callee, ref arguments) => {
3807                 self.resolve_expr(callee, Some(expr));
3808                 let const_args = self.r.legacy_const_generic_args(callee).unwrap_or_default();
3809                 for (idx, argument) in arguments.iter().enumerate() {
3810                     // Constant arguments need to be treated as AnonConst since
3811                     // that is how they will be later lowered to HIR.
3812                     if const_args.contains(&idx) {
3813                         self.with_constant_rib(
3814                             IsRepeatExpr::No,
3815                             if argument.is_potential_trivial_const_param() {
3816                                 ConstantHasGenerics::Yes
3817                             } else {
3818                                 ConstantHasGenerics::No
3819                             },
3820                             None,
3821                             |this| {
3822                                 this.resolve_expr(argument, None);
3823                             },
3824                         );
3825                     } else {
3826                         self.resolve_expr(argument, None);
3827                     }
3828                 }
3829             }
3830             ExprKind::Type(ref type_expr, ref ty) => {
3831                 // `ParseSess::type_ascription_path_suggestions` keeps spans of colon tokens in
3832                 // type ascription. Here we are trying to retrieve the span of the colon token as
3833                 // well, but only if it's written without spaces `expr:Ty` and therefore confusable
3834                 // with `expr::Ty`, only in this case it will match the span from
3835                 // `type_ascription_path_suggestions`.
3836                 self.diagnostic_metadata
3837                     .current_type_ascription
3838                     .push(type_expr.span.between(ty.span));
3839                 visit::walk_expr(self, expr);
3840                 self.diagnostic_metadata.current_type_ascription.pop();
3841             }
3842             // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
3843             // resolve the arguments within the proper scopes so that usages of them inside the
3844             // closure are detected as upvars rather than normal closure arg usages.
3845             ExprKind::Closure(_, _, Async::Yes { .. }, _, ref fn_decl, ref body, _span) => {
3846                 self.with_rib(ValueNS, NormalRibKind, |this| {
3847                     this.with_label_rib(ClosureOrAsyncRibKind, |this| {
3848                         // Resolve arguments:
3849                         this.resolve_params(&fn_decl.inputs);
3850                         // No need to resolve return type --
3851                         // the outer closure return type is `FnRetTy::Default`.
3852
3853                         // Now resolve the inner closure
3854                         {
3855                             // No need to resolve arguments: the inner closure has none.
3856                             // Resolve the return type:
3857                             visit::walk_fn_ret_ty(this, &fn_decl.output);
3858                             // Resolve the body
3859                             this.visit_expr(body);
3860                         }
3861                     })
3862                 });
3863             }
3864             // For closures, ClosureOrAsyncRibKind is added in visit_fn
3865             ExprKind::Closure(ClosureBinder::For { ref generic_params, span }, ..) => {
3866                 self.with_generic_param_rib(
3867                     &generic_params,
3868                     NormalRibKind,
3869                     LifetimeRibKind::Generics {
3870                         binder: expr.id,
3871                         kind: LifetimeBinderKind::Closure,
3872                         span,
3873                     },
3874                     |this| visit::walk_expr(this, expr),
3875                 );
3876             }
3877             ExprKind::Closure(..) => visit::walk_expr(self, expr),
3878             ExprKind::Async(..) => {
3879                 self.with_label_rib(ClosureOrAsyncRibKind, |this| visit::walk_expr(this, expr));
3880             }
3881             ExprKind::Repeat(ref elem, ref ct) => {
3882                 self.visit_expr(elem);
3883                 self.with_lifetime_rib(LifetimeRibKind::AnonConst, |this| {
3884                     this.with_lifetime_rib(LifetimeRibKind::Elided(LifetimeRes::Static), |this| {
3885                         this.resolve_anon_const(ct, IsRepeatExpr::Yes)
3886                     })
3887                 });
3888             }
3889             ExprKind::ConstBlock(ref ct) => {
3890                 self.resolve_inline_const(ct);
3891             }
3892             ExprKind::Index(ref elem, ref idx) => {
3893                 self.resolve_expr(elem, Some(expr));
3894                 self.visit_expr(idx);
3895             }
3896             _ => {
3897                 visit::walk_expr(self, expr);
3898             }
3899         }
3900     }
3901
3902     fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &'ast Expr) {
3903         match expr.kind {
3904             ExprKind::Field(_, ident) => {
3905                 // FIXME(#6890): Even though you can't treat a method like a
3906                 // field, we need to add any trait methods we find that match
3907                 // the field name so that we can do some nice error reporting
3908                 // later on in typeck.
3909                 let traits = self.traits_in_scope(ident, ValueNS);
3910                 self.r.trait_map.insert(expr.id, traits);
3911             }
3912             ExprKind::MethodCall(ref segment, ..) => {
3913                 debug!("(recording candidate traits for expr) recording traits for {}", expr.id);
3914                 let traits = self.traits_in_scope(segment.ident, ValueNS);
3915                 self.r.trait_map.insert(expr.id, traits);
3916             }
3917             _ => {
3918                 // Nothing to do.
3919             }
3920         }
3921     }
3922
3923     fn traits_in_scope(&mut self, ident: Ident, ns: Namespace) -> Vec<TraitCandidate> {
3924         self.r.traits_in_scope(
3925             self.current_trait_ref.as_ref().map(|(module, _)| *module),
3926             &self.parent_scope,
3927             ident.span.ctxt(),
3928             Some((ident.name, ns)),
3929         )
3930     }
3931
3932     /// Construct the list of in-scope lifetime parameters for async lowering.
3933     /// We include all lifetime parameters, either named or "Fresh".
3934     /// The order of those parameters does not matter, as long as it is
3935     /// deterministic.
3936     fn record_lifetime_params_for_async(
3937         &mut self,
3938         fn_id: NodeId,
3939         async_node_id: Option<(NodeId, Span)>,
3940     ) {
3941         if let Some((async_node_id, _)) = async_node_id {
3942             let mut extra_lifetime_params =
3943                 self.r.extra_lifetime_params_map.get(&fn_id).cloned().unwrap_or_default();
3944             for rib in self.lifetime_ribs.iter().rev() {
3945                 extra_lifetime_params.extend(
3946                     rib.bindings.iter().map(|(&ident, &(node_id, res))| (ident, node_id, res)),
3947                 );
3948                 match rib.kind {
3949                     LifetimeRibKind::Item => break,
3950                     LifetimeRibKind::AnonymousCreateParameter { binder, .. } => {
3951                         if let Some(earlier_fresh) = self.r.extra_lifetime_params_map.get(&binder) {
3952                             extra_lifetime_params.extend(earlier_fresh);
3953                         }
3954                     }
3955                     _ => {}
3956                 }
3957             }
3958             self.r.extra_lifetime_params_map.insert(async_node_id, extra_lifetime_params);
3959         }
3960     }
3961 }
3962
3963 struct LifetimeCountVisitor<'a, 'b> {
3964     r: &'b mut Resolver<'a>,
3965 }
3966
3967 /// Walks the whole crate in DFS order, visiting each item, counting the declared number of
3968 /// lifetime generic parameters.
3969 impl<'ast> Visitor<'ast> for LifetimeCountVisitor<'_, '_> {
3970     fn visit_item(&mut self, item: &'ast Item) {
3971         match &item.kind {
3972             ItemKind::TyAlias(box TyAlias { ref generics, .. })
3973             | ItemKind::Fn(box Fn { ref generics, .. })
3974             | ItemKind::Enum(_, ref generics)
3975             | ItemKind::Struct(_, ref generics)
3976             | ItemKind::Union(_, ref generics)
3977             | ItemKind::Impl(box Impl { ref generics, .. })
3978             | ItemKind::Trait(box Trait { ref generics, .. })
3979             | ItemKind::TraitAlias(ref generics, _) => {
3980                 let def_id = self.r.local_def_id(item.id);
3981                 let count = generics
3982                     .params
3983                     .iter()
3984                     .filter(|param| matches!(param.kind, ast::GenericParamKind::Lifetime { .. }))
3985                     .count();
3986                 self.r.item_generics_num_lifetimes.insert(def_id, count);
3987             }
3988
3989             ItemKind::Mod(..)
3990             | ItemKind::ForeignMod(..)
3991             | ItemKind::Static(..)
3992             | ItemKind::Const(..)
3993             | ItemKind::Use(..)
3994             | ItemKind::ExternCrate(..)
3995             | ItemKind::MacroDef(..)
3996             | ItemKind::GlobalAsm(..)
3997             | ItemKind::MacCall(..) => {}
3998         }
3999         visit::walk_item(self, item)
4000     }
4001 }
4002
4003 impl<'a> Resolver<'a> {
4004     pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
4005         visit::walk_crate(&mut LifetimeCountVisitor { r: self }, krate);
4006         let mut late_resolution_visitor = LateResolutionVisitor::new(self);
4007         visit::walk_crate(&mut late_resolution_visitor, krate);
4008         for (id, span) in late_resolution_visitor.diagnostic_metadata.unused_labels.iter() {
4009             self.lint_buffer.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");
4010         }
4011     }
4012 }