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