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