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