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