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