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