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