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