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