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