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