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