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