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