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