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