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