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