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