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