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