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