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