]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/late.rs
resolve: extract `try_resolve_as_non_binding`.
[rust.git] / src / librustc_resolve / late.rs
1 //! "Late resolution" is the pass that resolves most of names in a crate beside imports and macros.
2 //! It runs when the crate is fully expanded and its module structure is fully built.
3 //! So it just walks through the crate and resolves all the expressions, types, etc.
4 //!
5 //! If you wonder why there's no `early.rs`, that's because it's split into three files -
6 //! `build_reduced_graph.rs`, `macros.rs` and `resolve_imports.rs`.
7
8 use GenericParameters::*;
9 use RibKind::*;
10
11 use crate::{path_names_to_string, BindingError, CrateLint, LexicalScopeBinding};
12 use crate::{Module, ModuleOrUniformRoot, NameBindingKind, ParentScope, PathResult};
13 use crate::{ResolutionError, Resolver, Segment, UseError};
14
15 use log::debug;
16 use rustc::{bug, lint, span_bug};
17 use rustc::hir::def::{self, PartialRes, DefKind, CtorKind, PerNS};
18 use rustc::hir::def::Namespace::{self, *};
19 use rustc::hir::def_id::{DefId, CRATE_DEF_INDEX};
20 use rustc::hir::TraitCandidate;
21 use rustc::util::nodemap::FxHashMap;
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(
1331         &mut self,
1332         pat: &Pat,
1333         pat_src: PatternSource,
1334         // Maps idents to the node ID for the outermost pattern that binds them.
1335         bindings: &mut FxHashMap<Ident, NodeId>,
1336     ) {
1337         // Visit all direct subpatterns of this pattern.
1338         let outer_pat_id = pat.id;
1339         pat.walk(&mut |pat| {
1340             debug!("resolve_pattern pat={:?} node={:?}", pat, pat.node);
1341             match pat.node {
1342                 PatKind::Ident(bmode, ident, ref sub) => {
1343                     // First try to resolve the identifier as some existing entity,
1344                     // then fall back to a fresh binding.
1345                     let has_sub = sub.is_some();
1346                     let res = self.try_resolve_as_non_binding(pat_src, pat, bmode, ident, has_sub)
1347                         .unwrap_or_else(|| {
1348                             self.fresh_binding(ident, pat.id, outer_pat_id, pat_src, bindings)
1349                         });
1350                     self.r.record_partial_res(pat.id, PartialRes::new(res));
1351                 }
1352                 PatKind::TupleStruct(ref path, ..) => {
1353                     self.smart_resolve_path(pat.id, None, path, PathSource::TupleStruct);
1354                 }
1355                 PatKind::Path(ref qself, ref path) => {
1356                     self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat);
1357                 }
1358                 PatKind::Struct(ref path, ..) => {
1359                     self.smart_resolve_path(pat.id, None, path, PathSource::Struct);
1360                 }
1361                 _ => {}
1362             }
1363             true
1364         });
1365
1366         visit::walk_pat(self, pat);
1367     }
1368
1369     fn try_resolve_as_non_binding(
1370         &mut self,
1371         pat_src: PatternSource,
1372         pat: &Pat,
1373         bm: BindingMode,
1374         ident: Ident,
1375         has_sub: bool,
1376     ) -> Option<Res> {
1377         let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, pat.span)?.item()?;
1378         let res = binding.res();
1379
1380         // An immutable (no `mut`) by-value (no `ref`) binding pattern without
1381         // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could
1382         // also be interpreted as a path to e.g. a constant, variant, etc.
1383         let is_syntactic_ambiguity = !has_sub && bm == BindingMode::ByValue(Mutability::Immutable);
1384
1385         match res {
1386             Res::Def(DefKind::Ctor(_, CtorKind::Const), _) |
1387             Res::Def(DefKind::Const, _) if is_syntactic_ambiguity => {
1388                 // Disambiguate in favor of a unit struct/variant or constant pattern.
1389                 self.r.record_use(ident, ValueNS, binding, false);
1390                 Some(res)
1391             }
1392             Res::Def(DefKind::Ctor(..), _)
1393             | Res::Def(DefKind::Const, _)
1394             | Res::Def(DefKind::Static, _) => {
1395                 // This is unambiguously a fresh binding, either syntactically
1396                 // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves
1397                 // to something unusable as a pattern (e.g., constructor function),
1398                 // but we still conservatively report an error, see
1399                 // issues/33118#issuecomment-233962221 for one reason why.
1400                 self.r.report_error(
1401                     ident.span,
1402                     ResolutionError::BindingShadowsSomethingUnacceptable(
1403                         pat_src.descr(),
1404                         ident.name,
1405                         binding,
1406                     ),
1407                 );
1408                 None
1409             }
1410             Res::Def(DefKind::Fn, _) | Res::Err => {
1411                 // These entities are explicitly allowed to be shadowed by fresh bindings.
1412                 None
1413             }
1414             res => {
1415                 span_bug!(ident.span, "unexpected resolution for an \
1416                                         identifier in pattern: {:?}", res);
1417             }
1418         }
1419     }
1420
1421     // High-level and context dependent path resolution routine.
1422     // Resolves the path and records the resolution into definition map.
1423     // If resolution fails tries several techniques to find likely
1424     // resolution candidates, suggest imports or other help, and report
1425     // errors in user friendly way.
1426     fn smart_resolve_path(&mut self,
1427                           id: NodeId,
1428                           qself: Option<&QSelf>,
1429                           path: &Path,
1430                           source: PathSource<'_>) {
1431         self.smart_resolve_path_fragment(
1432             id,
1433             qself,
1434             &Segment::from_path(path),
1435             path.span,
1436             source,
1437             CrateLint::SimplePath(id),
1438         );
1439     }
1440
1441     fn smart_resolve_path_fragment(&mut self,
1442                                    id: NodeId,
1443                                    qself: Option<&QSelf>,
1444                                    path: &[Segment],
1445                                    span: Span,
1446                                    source: PathSource<'_>,
1447                                    crate_lint: CrateLint)
1448                                    -> PartialRes {
1449         let ns = source.namespace();
1450         let is_expected = &|res| source.is_expected(res);
1451
1452         let report_errors = |this: &mut Self, res: Option<Res>| {
1453             let (err, candidates) = this.smart_resolve_report_errors(path, span, source, res);
1454             let def_id = this.parent_scope.module.normal_ancestor_id;
1455             let node_id = this.r.definitions.as_local_node_id(def_id).unwrap();
1456             let better = res.is_some();
1457             this.r.use_injections.push(UseError { err, candidates, node_id, better });
1458             PartialRes::new(Res::Err)
1459         };
1460
1461         let partial_res = match self.resolve_qpath_anywhere(
1462             id,
1463             qself,
1464             path,
1465             ns,
1466             span,
1467             source.defer_to_typeck(),
1468             crate_lint,
1469         ) {
1470             Some(partial_res) if partial_res.unresolved_segments() == 0 => {
1471                 if is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err {
1472                     partial_res
1473                 } else {
1474                     // Add a temporary hack to smooth the transition to new struct ctor
1475                     // visibility rules. See #38932 for more details.
1476                     let mut res = None;
1477                     if let Res::Def(DefKind::Struct, def_id) = partial_res.base_res() {
1478                         if let Some((ctor_res, ctor_vis))
1479                                 = self.r.struct_constructors.get(&def_id).cloned() {
1480                             if is_expected(ctor_res) &&
1481                                self.r.is_accessible_from(ctor_vis, self.parent_scope.module) {
1482                                 let lint = lint::builtin::LEGACY_CONSTRUCTOR_VISIBILITY;
1483                                 self.r.session.buffer_lint(lint, id, span,
1484                                     "private struct constructors are not usable through \
1485                                      re-exports in outer modules",
1486                                 );
1487                                 res = Some(PartialRes::new(ctor_res));
1488                             }
1489                         }
1490                     }
1491
1492                     res.unwrap_or_else(|| report_errors(self, Some(partial_res.base_res())))
1493                 }
1494             }
1495             Some(partial_res) if source.defer_to_typeck() => {
1496                 // Not fully resolved associated item `T::A::B` or `<T as Tr>::A::B`
1497                 // or `<T>::A::B`. If `B` should be resolved in value namespace then
1498                 // it needs to be added to the trait map.
1499                 if ns == ValueNS {
1500                     let item_name = path.last().unwrap().ident;
1501                     let traits = self.get_traits_containing_item(item_name, ns);
1502                     self.r.trait_map.insert(id, traits);
1503                 }
1504
1505                 let mut std_path = vec![Segment::from_ident(Ident::with_dummy_span(sym::std))];
1506                 std_path.extend(path);
1507                 if self.r.primitive_type_table.primitive_types.contains_key(&path[0].ident.name) {
1508                     let cl = CrateLint::No;
1509                     let ns = Some(ns);
1510                     if let PathResult::Module(_) | PathResult::NonModule(_) =
1511                             self.resolve_path(&std_path, ns, false, span, cl) {
1512                         // check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
1513                         let item_span = path.iter().last().map(|segment| segment.ident.span)
1514                             .unwrap_or(span);
1515                         debug!("accessed item from `std` submodule as a bare type {:?}", std_path);
1516                         let mut hm = self.r.session.confused_type_with_std_module.borrow_mut();
1517                         hm.insert(item_span, span);
1518                         // In some places (E0223) we only have access to the full path
1519                         hm.insert(span, span);
1520                     }
1521                 }
1522                 partial_res
1523             }
1524             _ => report_errors(self, None)
1525         };
1526
1527         if let PathSource::TraitItem(..) = source {} else {
1528             // Avoid recording definition of `A::B` in `<T as A>::B::C`.
1529             self.r.record_partial_res(id, partial_res);
1530         }
1531         partial_res
1532     }
1533
1534     fn self_type_is_available(&mut self, span: Span) -> bool {
1535         let binding = self.resolve_ident_in_lexical_scope(
1536             Ident::with_dummy_span(kw::SelfUpper),
1537             TypeNS,
1538             None,
1539             span,
1540         );
1541         if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1542     }
1543
1544     fn self_value_is_available(&mut self, self_span: Span, path_span: Span) -> bool {
1545         let ident = Ident::new(kw::SelfLower, self_span);
1546         let binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, path_span);
1547         if let Some(LexicalScopeBinding::Res(res)) = binding { res != Res::Err } else { false }
1548     }
1549
1550     // Resolve in alternative namespaces if resolution in the primary namespace fails.
1551     fn resolve_qpath_anywhere(
1552         &mut self,
1553         id: NodeId,
1554         qself: Option<&QSelf>,
1555         path: &[Segment],
1556         primary_ns: Namespace,
1557         span: Span,
1558         defer_to_typeck: bool,
1559         crate_lint: CrateLint,
1560     ) -> Option<PartialRes> {
1561         let mut fin_res = None;
1562         for (i, ns) in [primary_ns, TypeNS, ValueNS].iter().cloned().enumerate() {
1563             if i == 0 || ns != primary_ns {
1564                 match self.resolve_qpath(id, qself, path, ns, span, crate_lint) {
1565                     // If defer_to_typeck, then resolution > no resolution,
1566                     // otherwise full resolution > partial resolution > no resolution.
1567                     Some(partial_res) if partial_res.unresolved_segments() == 0 ||
1568                                          defer_to_typeck =>
1569                         return Some(partial_res),
1570                     partial_res => if fin_res.is_none() { fin_res = partial_res },
1571                 }
1572             }
1573         }
1574
1575         // `MacroNS`
1576         assert!(primary_ns != MacroNS);
1577         if qself.is_none() {
1578             let path_seg = |seg: &Segment| PathSegment::from_ident(seg.ident);
1579             let path = Path { segments: path.iter().map(path_seg).collect(), span };
1580             if let Ok((_, res)) = self.r.resolve_macro_path(
1581                 &path, None, &self.parent_scope, false, false
1582             ) {
1583                 return Some(PartialRes::new(res));
1584             }
1585         }
1586
1587         fin_res
1588     }
1589
1590     /// Handles paths that may refer to associated items.
1591     fn resolve_qpath(
1592         &mut self,
1593         id: NodeId,
1594         qself: Option<&QSelf>,
1595         path: &[Segment],
1596         ns: Namespace,
1597         span: Span,
1598         crate_lint: CrateLint,
1599     ) -> Option<PartialRes> {
1600         debug!(
1601             "resolve_qpath(id={:?}, qself={:?}, path={:?}, ns={:?}, span={:?})",
1602             id,
1603             qself,
1604             path,
1605             ns,
1606             span,
1607         );
1608
1609         if let Some(qself) = qself {
1610             if qself.position == 0 {
1611                 // This is a case like `<T>::B`, where there is no
1612                 // trait to resolve.  In that case, we leave the `B`
1613                 // segment to be resolved by type-check.
1614                 return Some(PartialRes::with_unresolved_segments(
1615                     Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX)), path.len()
1616                 ));
1617             }
1618
1619             // Make sure `A::B` in `<T as A::B>::C` is a trait item.
1620             //
1621             // Currently, `path` names the full item (`A::B::C`, in
1622             // our example).  so we extract the prefix of that that is
1623             // the trait (the slice upto and including
1624             // `qself.position`). And then we recursively resolve that,
1625             // but with `qself` set to `None`.
1626             //
1627             // However, setting `qself` to none (but not changing the
1628             // span) loses the information about where this path
1629             // *actually* appears, so for the purposes of the crate
1630             // lint we pass along information that this is the trait
1631             // name from a fully qualified path, and this also
1632             // contains the full span (the `CrateLint::QPathTrait`).
1633             let ns = if qself.position + 1 == path.len() { ns } else { TypeNS };
1634             let partial_res = self.smart_resolve_path_fragment(
1635                 id,
1636                 None,
1637                 &path[..=qself.position],
1638                 span,
1639                 PathSource::TraitItem(ns),
1640                 CrateLint::QPathTrait {
1641                     qpath_id: id,
1642                     qpath_span: qself.path_span,
1643                 },
1644             );
1645
1646             // The remaining segments (the `C` in our example) will
1647             // have to be resolved by type-check, since that requires doing
1648             // trait resolution.
1649             return Some(PartialRes::with_unresolved_segments(
1650                 partial_res.base_res(),
1651                 partial_res.unresolved_segments() + path.len() - qself.position - 1,
1652             ));
1653         }
1654
1655         let result = match self.resolve_path(&path, Some(ns), true, span, crate_lint) {
1656             PathResult::NonModule(path_res) => path_res,
1657             PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => {
1658                 PartialRes::new(module.res().unwrap())
1659             }
1660             // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we
1661             // don't report an error right away, but try to fallback to a primitive type.
1662             // So, we are still able to successfully resolve something like
1663             //
1664             // use std::u8; // bring module u8 in scope
1665             // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8
1666             //     u8::max_value() // OK, resolves to associated function <u8>::max_value,
1667             //                     // not to non-existent std::u8::max_value
1668             // }
1669             //
1670             // Such behavior is required for backward compatibility.
1671             // The same fallback is used when `a` resolves to nothing.
1672             PathResult::Module(ModuleOrUniformRoot::Module(_)) |
1673             PathResult::Failed { .. }
1674                     if (ns == TypeNS || path.len() > 1) &&
1675                        self.r.primitive_type_table.primitive_types
1676                            .contains_key(&path[0].ident.name) => {
1677                 let prim = self.r.primitive_type_table.primitive_types[&path[0].ident.name];
1678                 PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1)
1679             }
1680             PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1681                 PartialRes::new(module.res().unwrap()),
1682             PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
1683                 self.r.report_error(span, ResolutionError::FailedToResolve { label, suggestion });
1684                 PartialRes::new(Res::Err)
1685             }
1686             PathResult::Module(..) | PathResult::Failed { .. } => return None,
1687             PathResult::Indeterminate => bug!("indetermined path result in resolve_qpath"),
1688         };
1689
1690         if path.len() > 1 && result.base_res() != Res::Err &&
1691            path[0].ident.name != kw::PathRoot &&
1692            path[0].ident.name != kw::DollarCrate {
1693             let unqualified_result = {
1694                 match self.resolve_path(
1695                     &[*path.last().unwrap()],
1696                     Some(ns),
1697                     false,
1698                     span,
1699                     CrateLint::No,
1700                 ) {
1701                     PathResult::NonModule(path_res) => path_res.base_res(),
1702                     PathResult::Module(ModuleOrUniformRoot::Module(module)) =>
1703                         module.res().unwrap(),
1704                     _ => return Some(result),
1705                 }
1706             };
1707             if result.base_res() == unqualified_result {
1708                 let lint = lint::builtin::UNUSED_QUALIFICATIONS;
1709                 self.r.session.buffer_lint(lint, id, span, "unnecessary qualification")
1710             }
1711         }
1712
1713         Some(result)
1714     }
1715
1716     fn with_resolved_label(&mut self, label: Option<Label>, id: NodeId, f: impl FnOnce(&mut Self)) {
1717         if let Some(label) = label {
1718             self.unused_labels.insert(id, label.ident.span);
1719             self.with_label_rib(NormalRibKind, |this| {
1720                 let ident = label.ident.modern_and_legacy();
1721                 this.label_ribs.last_mut().unwrap().bindings.insert(ident, id);
1722                 f(this);
1723             });
1724         } else {
1725             f(self);
1726         }
1727     }
1728
1729     fn resolve_labeled_block(&mut self, label: Option<Label>, id: NodeId, block: &Block) {
1730         self.with_resolved_label(label, id, |this| this.visit_block(block));
1731     }
1732
1733     fn resolve_expr(&mut self, expr: &Expr, parent: Option<&Expr>) {
1734         // First, record candidate traits for this expression if it could
1735         // result in the invocation of a method call.
1736
1737         self.record_candidate_traits_for_expr_if_necessary(expr);
1738
1739         // Next, resolve the node.
1740         match expr.node {
1741             ExprKind::Path(ref qself, ref path) => {
1742                 self.smart_resolve_path(expr.id, qself.as_ref(), path, PathSource::Expr(parent));
1743                 visit::walk_expr(self, expr);
1744             }
1745
1746             ExprKind::Struct(ref path, ..) => {
1747                 self.smart_resolve_path(expr.id, None, path, PathSource::Struct);
1748                 visit::walk_expr(self, expr);
1749             }
1750
1751             ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => {
1752                 let node_id = self.search_label(label.ident, |rib, ident| {
1753                     rib.bindings.get(&ident.modern_and_legacy()).cloned()
1754                 });
1755                 match node_id {
1756                     None => {
1757                         // Search again for close matches...
1758                         // Picks the first label that is "close enough", which is not necessarily
1759                         // the closest match
1760                         let close_match = self.search_label(label.ident, |rib, ident| {
1761                             let names = rib.bindings.iter().filter_map(|(id, _)| {
1762                                 if id.span.ctxt() == label.ident.span.ctxt() {
1763                                     Some(&id.name)
1764                                 } else {
1765                                     None
1766                                 }
1767                             });
1768                             find_best_match_for_name(names, &*ident.as_str(), None)
1769                         });
1770                         self.r.record_partial_res(expr.id, PartialRes::new(Res::Err));
1771                         self.r.report_error(
1772                             label.ident.span,
1773                             ResolutionError::UndeclaredLabel(&label.ident.as_str(), close_match),
1774                         );
1775                     }
1776                     Some(node_id) => {
1777                         // Since this res is a label, it is never read.
1778                         self.r.label_res_map.insert(expr.id, node_id);
1779                         self.unused_labels.remove(&node_id);
1780                     }
1781                 }
1782
1783                 // visit `break` argument if any
1784                 visit::walk_expr(self, expr);
1785             }
1786
1787             ExprKind::Let(ref pats, ref scrutinee) => {
1788                 self.visit_expr(scrutinee);
1789                 self.resolve_pats(pats, PatternSource::Let);
1790             }
1791
1792             ExprKind::If(ref cond, ref then, ref opt_else) => {
1793                 self.with_rib(ValueNS, NormalRibKind, |this| {
1794                     this.visit_expr(cond);
1795                     this.visit_block(then);
1796                 });
1797                 opt_else.as_ref().map(|expr| self.visit_expr(expr));
1798             }
1799
1800             ExprKind::Loop(ref block, label) => self.resolve_labeled_block(label, expr.id, &block),
1801
1802             ExprKind::While(ref cond, ref block, label) => {
1803                 self.with_resolved_label(label, expr.id, |this| {
1804                     this.with_rib(ValueNS, NormalRibKind, |this| {
1805                         this.visit_expr(cond);
1806                         this.visit_block(block);
1807                     })
1808                 });
1809             }
1810
1811             ExprKind::ForLoop(ref pat, ref iter_expr, ref block, label) => {
1812                 self.visit_expr(iter_expr);
1813                 self.with_rib(ValueNS, NormalRibKind, |this| {
1814                     this.resolve_pattern(pat, PatternSource::For, &mut FxHashMap::default());
1815                     this.resolve_labeled_block(label, expr.id, block);
1816                 });
1817             }
1818
1819             ExprKind::Block(ref block, label) => self.resolve_labeled_block(label, block.id, block),
1820
1821             // Equivalent to `visit::walk_expr` + passing some context to children.
1822             ExprKind::Field(ref subexpression, _) => {
1823                 self.resolve_expr(subexpression, Some(expr));
1824             }
1825             ExprKind::MethodCall(ref segment, ref arguments) => {
1826                 let mut arguments = arguments.iter();
1827                 self.resolve_expr(arguments.next().unwrap(), Some(expr));
1828                 for argument in arguments {
1829                     self.resolve_expr(argument, None);
1830                 }
1831                 self.visit_path_segment(expr.span, segment);
1832             }
1833
1834             ExprKind::Call(ref callee, ref arguments) => {
1835                 self.resolve_expr(callee, Some(expr));
1836                 for argument in arguments {
1837                     self.resolve_expr(argument, None);
1838                 }
1839             }
1840             ExprKind::Type(ref type_expr, _) => {
1841                 self.current_type_ascription.push(type_expr.span);
1842                 visit::walk_expr(self, expr);
1843                 self.current_type_ascription.pop();
1844             }
1845             // `async |x| ...` gets desugared to `|x| future_from_generator(|| ...)`, so we need to
1846             // resolve the arguments within the proper scopes so that usages of them inside the
1847             // closure are detected as upvars rather than normal closure arg usages.
1848             ExprKind::Closure(_, IsAsync::Async { .. }, _, ref fn_decl, ref body, _span) => {
1849                 self.with_rib(ValueNS, NormalRibKind, |this| {
1850                     // Resolve arguments:
1851                     this.resolve_params(&fn_decl.inputs);
1852                     // No need to resolve return type --
1853                     // the outer closure return type is `FunctionRetTy::Default`.
1854
1855                     // Now resolve the inner closure
1856                     {
1857                         // No need to resolve arguments: the inner closure has none.
1858                         // Resolve the return type:
1859                         visit::walk_fn_ret_ty(this, &fn_decl.output);
1860                         // Resolve the body
1861                         this.visit_expr(body);
1862                     }
1863                 });
1864             }
1865             _ => {
1866                 visit::walk_expr(self, expr);
1867             }
1868         }
1869     }
1870
1871     fn record_candidate_traits_for_expr_if_necessary(&mut self, expr: &Expr) {
1872         match expr.node {
1873             ExprKind::Field(_, ident) => {
1874                 // FIXME(#6890): Even though you can't treat a method like a
1875                 // field, we need to add any trait methods we find that match
1876                 // the field name so that we can do some nice error reporting
1877                 // later on in typeck.
1878                 let traits = self.get_traits_containing_item(ident, ValueNS);
1879                 self.r.trait_map.insert(expr.id, traits);
1880             }
1881             ExprKind::MethodCall(ref segment, ..) => {
1882                 debug!("(recording candidate traits for expr) recording traits for {}",
1883                        expr.id);
1884                 let traits = self.get_traits_containing_item(segment.ident, ValueNS);
1885                 self.r.trait_map.insert(expr.id, traits);
1886             }
1887             _ => {
1888                 // Nothing to do.
1889             }
1890         }
1891     }
1892
1893     fn get_traits_containing_item(&mut self, mut ident: Ident, ns: Namespace)
1894                                   -> Vec<TraitCandidate> {
1895         debug!("(getting traits containing item) looking for '{}'", ident.name);
1896
1897         let mut found_traits = Vec::new();
1898         // Look for the current trait.
1899         if let Some((module, _)) = self.current_trait_ref {
1900             if self.r.resolve_ident_in_module(
1901                 ModuleOrUniformRoot::Module(module),
1902                 ident,
1903                 ns,
1904                 &self.parent_scope,
1905                 false,
1906                 module.span,
1907             ).is_ok() {
1908                 let def_id = module.def_id().unwrap();
1909                 found_traits.push(TraitCandidate { def_id: def_id, import_ids: smallvec![] });
1910             }
1911         }
1912
1913         ident.span = ident.span.modern();
1914         let mut search_module = self.parent_scope.module;
1915         loop {
1916             self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits);
1917             search_module = unwrap_or!(
1918                 self.r.hygienic_lexical_parent(search_module, &mut ident.span), break
1919             );
1920         }
1921
1922         if let Some(prelude) = self.r.prelude {
1923             if !search_module.no_implicit_prelude {
1924                 self.get_traits_in_module_containing_item(ident, ns, prelude, &mut found_traits);
1925             }
1926         }
1927
1928         found_traits
1929     }
1930
1931     fn get_traits_in_module_containing_item(&mut self,
1932                                             ident: Ident,
1933                                             ns: Namespace,
1934                                             module: Module<'a>,
1935                                             found_traits: &mut Vec<TraitCandidate>) {
1936         assert!(ns == TypeNS || ns == ValueNS);
1937         let mut traits = module.traits.borrow_mut();
1938         if traits.is_none() {
1939             let mut collected_traits = Vec::new();
1940             module.for_each_child(self.r, |_, name, ns, binding| {
1941                 if ns != TypeNS { return }
1942                 match binding.res() {
1943                     Res::Def(DefKind::Trait, _) |
1944                     Res::Def(DefKind::TraitAlias, _) => collected_traits.push((name, binding)),
1945                     _ => (),
1946                 }
1947             });
1948             *traits = Some(collected_traits.into_boxed_slice());
1949         }
1950
1951         for &(trait_name, binding) in traits.as_ref().unwrap().iter() {
1952             // Traits have pseudo-modules that can be used to search for the given ident.
1953             if let Some(module) = binding.module() {
1954                 let mut ident = ident;
1955                 if ident.span.glob_adjust(
1956                     module.expansion,
1957                     binding.span,
1958                 ).is_none() {
1959                     continue
1960                 }
1961                 if self.r.resolve_ident_in_module_unadjusted(
1962                     ModuleOrUniformRoot::Module(module),
1963                     ident,
1964                     ns,
1965                     &self.parent_scope,
1966                     false,
1967                     module.span,
1968                 ).is_ok() {
1969                     let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
1970                     let trait_def_id = module.def_id().unwrap();
1971                     found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
1972                 }
1973             } else if let Res::Def(DefKind::TraitAlias, _) = binding.res() {
1974                 // For now, just treat all trait aliases as possible candidates, since we don't
1975                 // know if the ident is somewhere in the transitive bounds.
1976                 let import_ids = self.find_transitive_imports(&binding.kind, trait_name);
1977                 let trait_def_id = binding.res().def_id();
1978                 found_traits.push(TraitCandidate { def_id: trait_def_id, import_ids });
1979             } else {
1980                 bug!("candidate is not trait or trait alias?")
1981             }
1982         }
1983     }
1984
1985     fn find_transitive_imports(&mut self, mut kind: &NameBindingKind<'_>,
1986                                trait_name: Ident) -> SmallVec<[NodeId; 1]> {
1987         let mut import_ids = smallvec![];
1988         while let NameBindingKind::Import { directive, binding, .. } = kind {
1989             self.r.maybe_unused_trait_imports.insert(directive.id);
1990             self.r.add_to_glob_map(&directive, trait_name);
1991             import_ids.push(directive.id);
1992             kind = &binding.kind;
1993         };
1994         import_ids
1995     }
1996 }
1997
1998 impl<'a> Resolver<'a> {
1999     pub(crate) fn late_resolve_crate(&mut self, krate: &Crate) {
2000         let mut late_resolution_visitor = LateResolutionVisitor::new(self);
2001         visit::walk_crate(&mut late_resolution_visitor, krate);
2002         for (id, span) in late_resolution_visitor.unused_labels.iter() {
2003             self.session.buffer_lint(lint::builtin::UNUSED_LABELS, *id, *span, "unused label");
2004         }
2005     }
2006 }