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