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