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