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