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