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