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