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