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