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