]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_resolve/src/lib.rs
Auto merge of #103691 - michaelwoerister:consistent-slice-and-str-cpp-like-debuginfo...
[rust.git] / compiler / rustc_resolve / src / lib.rs
1 //! This crate is responsible for the part of name resolution that doesn't require type checker.
2 //!
3 //! Module structure of the crate is built here.
4 //! Paths in macros, imports, expressions, types, patterns are resolved here.
5 //! Label and lifetime names are resolved here as well.
6 //!
7 //! Type-relative name resolution (methods, fields, associated items) happens in `rustc_hir_analysis`.
8
9 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
10 #![feature(assert_matches)]
11 #![feature(box_patterns)]
12 #![feature(drain_filter)]
13 #![feature(if_let_guard)]
14 #![feature(iter_intersperse)]
15 #![feature(let_chains)]
16 #![feature(never_type)]
17 #![recursion_limit = "256"]
18 #![allow(rustdoc::private_intra_doc_links)]
19 #![allow(rustc::potential_query_instability)]
20
21 #[macro_use]
22 extern crate tracing;
23
24 pub use rustc_hir::def::{Namespace, PerNS};
25
26 use rustc_arena::{DroplessArena, TypedArena};
27 use rustc_ast::node_id::NodeMap;
28 use rustc_ast::{self as ast, NodeId, CRATE_NODE_ID};
29 use rustc_ast::{AngleBracketedArg, Crate, Expr, ExprKind, GenericArg, GenericArgs, LitKind, Path};
30 use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
31 use rustc_data_structures::intern::Interned;
32 use rustc_data_structures::sync::Lrc;
33 use rustc_errors::{Applicability, DiagnosticBuilder, ErrorGuaranteed};
34 use rustc_expand::base::{DeriveResolutions, SyntaxExtension, SyntaxExtensionKind};
35 use rustc_hir::def::Namespace::*;
36 use rustc_hir::def::{self, CtorOf, DefKind, LifetimeRes, PartialRes};
37 use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId};
38 use rustc_hir::def_id::{CRATE_DEF_ID, LOCAL_CRATE};
39 use rustc_hir::definitions::{DefPathData, Definitions};
40 use rustc_hir::TraitCandidate;
41 use rustc_index::vec::IndexVec;
42 use rustc_metadata::creader::{CStore, CrateLoader};
43 use rustc_middle::metadata::ModChild;
44 use rustc_middle::middle::privacy::EffectiveVisibilities;
45 use rustc_middle::span_bug;
46 use rustc_middle::ty::{self, DefIdTree, MainDefinition, RegisteredTools};
47 use rustc_middle::ty::{ResolverGlobalCtxt, ResolverOutputs};
48 use rustc_query_system::ich::StableHashingContext;
49 use rustc_session::cstore::{CrateStore, MetadataLoaderDyn};
50 use rustc_session::lint::LintBuffer;
51 use rustc_session::Session;
52 use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency};
53 use rustc_span::source_map::Spanned;
54 use rustc_span::symbol::{kw, sym, Ident, Symbol};
55 use rustc_span::{Span, DUMMY_SP};
56
57 use smallvec::{smallvec, SmallVec};
58 use std::cell::{Cell, RefCell};
59 use std::collections::BTreeSet;
60 use std::{fmt, ptr};
61
62 use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion};
63 use imports::{Import, ImportKind, ImportResolver, NameResolution};
64 use late::{HasGenericParams, PathSource, PatternSource};
65 use macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef};
66
67 use crate::effective_visibilities::EffectiveVisibilitiesVisitor;
68
69 type Res = def::Res<NodeId>;
70
71 mod build_reduced_graph;
72 mod check_unused;
73 mod def_collector;
74 mod diagnostics;
75 mod effective_visibilities;
76 mod ident;
77 mod imports;
78 mod late;
79 mod macros;
80
81 enum Weak {
82     Yes,
83     No,
84 }
85
86 #[derive(Copy, Clone, PartialEq, Debug)]
87 pub enum Determinacy {
88     Determined,
89     Undetermined,
90 }
91
92 impl Determinacy {
93     fn determined(determined: bool) -> Determinacy {
94         if determined { Determinacy::Determined } else { Determinacy::Undetermined }
95     }
96 }
97
98 /// A specific scope in which a name can be looked up.
99 /// This enum is currently used only for early resolution (imports and macros),
100 /// but not for late resolution yet.
101 #[derive(Clone, Copy)]
102 enum Scope<'a> {
103     DeriveHelpers(LocalExpnId),
104     DeriveHelpersCompat,
105     MacroRules(MacroRulesScopeRef<'a>),
106     CrateRoot,
107     Module(Module<'a>),
108     MacroUsePrelude,
109     BuiltinAttrs,
110     ExternPrelude,
111     ToolPrelude,
112     StdLibPrelude,
113     BuiltinTypes,
114 }
115
116 /// Names from different contexts may want to visit different subsets of all specific scopes
117 /// with different restrictions when looking up the resolution.
118 /// This enum is currently used only for early resolution (imports and macros),
119 /// but not for late resolution yet.
120 #[derive(Clone, Copy)]
121 enum ScopeSet<'a> {
122     /// All scopes with the given namespace.
123     All(Namespace, /*is_import*/ bool),
124     /// Crate root, then extern prelude (used for mixed 2015-2018 mode in macros).
125     AbsolutePath(Namespace),
126     /// All scopes with macro namespace and the given macro kind restriction.
127     Macro(MacroKind),
128     /// All scopes with the given namespace, used for partially performing late resolution.
129     /// The node id enables lints and is used for reporting them.
130     Late(Namespace, Module<'a>, Option<NodeId>),
131 }
132
133 /// Everything you need to know about a name's location to resolve it.
134 /// Serves as a starting point for the scope visitor.
135 /// This struct is currently used only for early resolution (imports and macros),
136 /// but not for late resolution yet.
137 #[derive(Clone, Copy, Debug)]
138 pub struct ParentScope<'a> {
139     pub module: Module<'a>,
140     expansion: LocalExpnId,
141     pub macro_rules: MacroRulesScopeRef<'a>,
142     derives: &'a [ast::Path],
143 }
144
145 impl<'a> ParentScope<'a> {
146     /// Creates a parent scope with the passed argument used as the module scope component,
147     /// and other scope components set to default empty values.
148     pub fn module(module: Module<'a>, resolver: &Resolver<'a>) -> ParentScope<'a> {
149         ParentScope {
150             module,
151             expansion: LocalExpnId::ROOT,
152             macro_rules: resolver.arenas.alloc_macro_rules_scope(MacroRulesScope::Empty),
153             derives: &[],
154         }
155     }
156 }
157
158 #[derive(Copy, Debug, Clone)]
159 enum ImplTraitContext {
160     Existential,
161     Universal(LocalDefId),
162 }
163
164 struct BindingError {
165     name: Symbol,
166     origin: BTreeSet<Span>,
167     target: BTreeSet<Span>,
168     could_be_path: bool,
169 }
170
171 enum ResolutionError<'a> {
172     /// Error E0401: can't use type or const parameters from outer function.
173     GenericParamsFromOuterFunction(Res, HasGenericParams),
174     /// Error E0403: the name is already used for a type or const parameter in this generic
175     /// parameter list.
176     NameAlreadyUsedInParameterList(Symbol, Span),
177     /// Error E0407: method is not a member of trait.
178     MethodNotMemberOfTrait(Ident, String, Option<Symbol>),
179     /// Error E0437: type is not a member of trait.
180     TypeNotMemberOfTrait(Ident, String, Option<Symbol>),
181     /// Error E0438: const is not a member of trait.
182     ConstNotMemberOfTrait(Ident, String, Option<Symbol>),
183     /// Error E0408: variable `{}` is not bound in all patterns.
184     VariableNotBoundInPattern(BindingError, ParentScope<'a>),
185     /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm.
186     VariableBoundWithDifferentMode(Symbol, Span),
187     /// Error E0415: identifier is bound more than once in this parameter list.
188     IdentifierBoundMoreThanOnceInParameterList(Symbol),
189     /// Error E0416: identifier is bound more than once in the same pattern.
190     IdentifierBoundMoreThanOnceInSamePattern(Symbol),
191     /// Error E0426: use of undeclared label.
192     UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> },
193     /// Error E0429: `self` imports are only allowed within a `{ }` list.
194     SelfImportsOnlyAllowedWithin { root: bool, span_with_rename: Span },
195     /// Error E0430: `self` import can only appear once in the list.
196     SelfImportCanOnlyAppearOnceInTheList,
197     /// Error E0431: `self` import can only appear in an import list with a non-empty prefix.
198     SelfImportOnlyInImportListWithNonEmptyPrefix,
199     /// Error E0433: failed to resolve.
200     FailedToResolve { label: String, suggestion: Option<Suggestion> },
201     /// Error E0434: can't capture dynamic environment in a fn item.
202     CannotCaptureDynamicEnvironmentInFnItem,
203     /// Error E0435: attempt to use a non-constant value in a constant.
204     AttemptToUseNonConstantValueInConstant(
205         Ident,
206         /* suggestion */ &'static str,
207         /* current */ &'static str,
208     ),
209     /// Error E0530: `X` bindings cannot shadow `Y`s.
210     BindingShadowsSomethingUnacceptable {
211         shadowing_binding: PatternSource,
212         name: Symbol,
213         participle: &'static str,
214         article: &'static str,
215         shadowed_binding: Res,
216         shadowed_binding_span: Span,
217     },
218     /// Error E0128: generic parameters with a default cannot use forward-declared identifiers.
219     ForwardDeclaredGenericParam,
220     /// ERROR E0770: the type of const parameters must not depend on other generic parameters.
221     ParamInTyOfConstParam(Symbol),
222     /// generic parameters must not be used inside const evaluations.
223     ///
224     /// This error is only emitted when using `min_const_generics`.
225     ParamInNonTrivialAnonConst { name: Symbol, is_type: bool },
226     /// Error E0735: generic parameters with a default cannot use `Self`
227     SelfInGenericParamDefault,
228     /// Error E0767: use of unreachable label
229     UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },
230     /// Error E0323, E0324, E0325: mismatch between trait item and impl item.
231     TraitImplMismatch {
232         name: Symbol,
233         kind: &'static str,
234         trait_path: String,
235         trait_item_span: Span,
236         code: rustc_errors::DiagnosticId,
237     },
238     /// Error E0201: multiple impl items for the same trait item.
239     TraitImplDuplicate { name: Symbol, trait_item_span: Span, old_span: Span },
240     /// Inline asm `sym` operand must refer to a `fn` or `static`.
241     InvalidAsmSym,
242 }
243
244 enum VisResolutionError<'a> {
245     Relative2018(Span, &'a ast::Path),
246     AncestorOnly(Span),
247     FailedToResolve(Span, String, Option<Suggestion>),
248     ExpectedFound(Span, String, Res),
249     Indeterminate(Span),
250     ModuleOnly(Span),
251 }
252
253 /// A minimal representation of a path segment. We use this in resolve because we synthesize 'path
254 /// segments' which don't have the rest of an AST or HIR `PathSegment`.
255 #[derive(Clone, Copy, Debug)]
256 pub struct Segment {
257     ident: Ident,
258     id: Option<NodeId>,
259     /// Signals whether this `PathSegment` has generic arguments. Used to avoid providing
260     /// nonsensical suggestions.
261     has_generic_args: bool,
262     /// Signals whether this `PathSegment` has lifetime arguments.
263     has_lifetime_args: bool,
264     args_span: Span,
265 }
266
267 impl Segment {
268     fn from_path(path: &Path) -> Vec<Segment> {
269         path.segments.iter().map(|s| s.into()).collect()
270     }
271
272     fn from_ident(ident: Ident) -> Segment {
273         Segment {
274             ident,
275             id: None,
276             has_generic_args: false,
277             has_lifetime_args: false,
278             args_span: DUMMY_SP,
279         }
280     }
281
282     fn from_ident_and_id(ident: Ident, id: NodeId) -> Segment {
283         Segment {
284             ident,
285             id: Some(id),
286             has_generic_args: false,
287             has_lifetime_args: false,
288             args_span: DUMMY_SP,
289         }
290     }
291
292     fn names_to_string(segments: &[Segment]) -> String {
293         names_to_string(&segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>())
294     }
295 }
296
297 impl<'a> From<&'a ast::PathSegment> for Segment {
298     fn from(seg: &'a ast::PathSegment) -> Segment {
299         let has_generic_args = seg.args.is_some();
300         let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() {
301             match args {
302                 GenericArgs::AngleBracketed(args) => {
303                     let found_lifetimes = args
304                         .args
305                         .iter()
306                         .any(|arg| matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_))));
307                     (args.span, found_lifetimes)
308                 }
309                 GenericArgs::Parenthesized(args) => (args.span, true),
310             }
311         } else {
312             (DUMMY_SP, false)
313         };
314         Segment {
315             ident: seg.ident,
316             id: Some(seg.id),
317             has_generic_args,
318             has_lifetime_args,
319             args_span,
320         }
321     }
322 }
323
324 /// An intermediate resolution result.
325 ///
326 /// This refers to the thing referred by a name. The difference between `Res` and `Item` is that
327 /// items are visible in their whole block, while `Res`es only from the place they are defined
328 /// forward.
329 #[derive(Debug)]
330 enum LexicalScopeBinding<'a> {
331     Item(&'a NameBinding<'a>),
332     Res(Res),
333 }
334
335 impl<'a> LexicalScopeBinding<'a> {
336     fn res(self) -> Res {
337         match self {
338             LexicalScopeBinding::Item(binding) => binding.res(),
339             LexicalScopeBinding::Res(res) => res,
340         }
341     }
342 }
343
344 #[derive(Copy, Clone, Debug)]
345 enum ModuleOrUniformRoot<'a> {
346     /// Regular module.
347     Module(Module<'a>),
348
349     /// Virtual module that denotes resolution in crate root with fallback to extern prelude.
350     CrateRootAndExternPrelude,
351
352     /// Virtual module that denotes resolution in extern prelude.
353     /// Used for paths starting with `::` on 2018 edition.
354     ExternPrelude,
355
356     /// Virtual module that denotes resolution in current scope.
357     /// Used only for resolving single-segment imports. The reason it exists is that import paths
358     /// are always split into two parts, the first of which should be some kind of module.
359     CurrentScope,
360 }
361
362 impl ModuleOrUniformRoot<'_> {
363     fn same_def(lhs: Self, rhs: Self) -> bool {
364         match (lhs, rhs) {
365             (ModuleOrUniformRoot::Module(lhs), ModuleOrUniformRoot::Module(rhs)) => {
366                 ptr::eq(lhs, rhs)
367             }
368             (
369                 ModuleOrUniformRoot::CrateRootAndExternPrelude,
370                 ModuleOrUniformRoot::CrateRootAndExternPrelude,
371             )
372             | (ModuleOrUniformRoot::ExternPrelude, ModuleOrUniformRoot::ExternPrelude)
373             | (ModuleOrUniformRoot::CurrentScope, ModuleOrUniformRoot::CurrentScope) => true,
374             _ => false,
375         }
376     }
377 }
378
379 #[derive(Clone, Debug)]
380 enum PathResult<'a> {
381     Module(ModuleOrUniformRoot<'a>),
382     NonModule(PartialRes),
383     Indeterminate,
384     Failed {
385         span: Span,
386         label: String,
387         suggestion: Option<Suggestion>,
388         is_error_from_last_segment: bool,
389     },
390 }
391
392 impl<'a> PathResult<'a> {
393     fn failed(
394         span: Span,
395         is_error_from_last_segment: bool,
396         finalize: bool,
397         label_and_suggestion: impl FnOnce() -> (String, Option<Suggestion>),
398     ) -> PathResult<'a> {
399         let (label, suggestion) =
400             if finalize { label_and_suggestion() } else { (String::new(), None) };
401         PathResult::Failed { span, label, suggestion, is_error_from_last_segment }
402     }
403 }
404
405 #[derive(Debug)]
406 enum ModuleKind {
407     /// An anonymous module; e.g., just a block.
408     ///
409     /// ```
410     /// fn main() {
411     ///     fn f() {} // (1)
412     ///     { // This is an anonymous module
413     ///         f(); // This resolves to (2) as we are inside the block.
414     ///         fn f() {} // (2)
415     ///     }
416     ///     f(); // Resolves to (1)
417     /// }
418     /// ```
419     Block,
420     /// Any module with a name.
421     ///
422     /// This could be:
423     ///
424     /// * A normal module â€“ either `mod from_file;` or `mod from_block { }` â€“
425     ///   or the crate root (which is conceptually a top-level module).
426     ///   Note that the crate root's [name][Self::name] will be [`kw::Empty`].
427     /// * A trait or an enum (it implicitly contains associated types, methods and variant
428     ///   constructors).
429     Def(DefKind, DefId, Symbol),
430 }
431
432 impl ModuleKind {
433     /// Get name of the module.
434     pub fn name(&self) -> Option<Symbol> {
435         match self {
436             ModuleKind::Block => None,
437             ModuleKind::Def(.., name) => Some(*name),
438         }
439     }
440 }
441
442 /// A key that identifies a binding in a given `Module`.
443 ///
444 /// Multiple bindings in the same module can have the same key (in a valid
445 /// program) if all but one of them come from glob imports.
446 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
447 struct BindingKey {
448     /// The identifier for the binding, always the `normalize_to_macros_2_0` version of the
449     /// identifier.
450     ident: Ident,
451     ns: Namespace,
452     /// 0 if ident is not `_`, otherwise a value that's unique to the specific
453     /// `_` in the expanded AST that introduced this binding.
454     disambiguator: u32,
455 }
456
457 type Resolutions<'a> = RefCell<FxIndexMap<BindingKey, &'a RefCell<NameResolution<'a>>>>;
458
459 /// One node in the tree of modules.
460 ///
461 /// Note that a "module" in resolve is broader than a `mod` that you declare in Rust code. It may be one of these:
462 ///
463 /// * `mod`
464 /// * crate root (aka, top-level anonymous module)
465 /// * `enum`
466 /// * `trait`
467 /// * curly-braced block with statements
468 ///
469 /// You can use [`ModuleData::kind`] to determine the kind of module this is.
470 pub struct ModuleData<'a> {
471     /// The direct parent module (it may not be a `mod`, however).
472     parent: Option<Module<'a>>,
473     /// What kind of module this is, because this may not be a `mod`.
474     kind: ModuleKind,
475
476     /// Mapping between names and their (possibly in-progress) resolutions in this module.
477     /// Resolutions in modules from other crates are not populated until accessed.
478     lazy_resolutions: Resolutions<'a>,
479     /// True if this is a module from other crate that needs to be populated on access.
480     populate_on_access: Cell<bool>,
481
482     /// Macro invocations that can expand into items in this module.
483     unexpanded_invocations: RefCell<FxHashSet<LocalExpnId>>,
484
485     /// Whether `#[no_implicit_prelude]` is active.
486     no_implicit_prelude: bool,
487
488     glob_importers: RefCell<Vec<&'a Import<'a>>>,
489     globs: RefCell<Vec<&'a Import<'a>>>,
490
491     /// Used to memoize the traits in this module for faster searches through all traits in scope.
492     traits: RefCell<Option<Box<[(Ident, &'a NameBinding<'a>)]>>>,
493
494     /// Span of the module itself. Used for error reporting.
495     span: Span,
496
497     expansion: ExpnId,
498 }
499
500 type Module<'a> = &'a ModuleData<'a>;
501
502 impl<'a> ModuleData<'a> {
503     fn new(
504         parent: Option<Module<'a>>,
505         kind: ModuleKind,
506         expansion: ExpnId,
507         span: Span,
508         no_implicit_prelude: bool,
509     ) -> Self {
510         let is_foreign = match kind {
511             ModuleKind::Def(_, def_id, _) => !def_id.is_local(),
512             ModuleKind::Block => false,
513         };
514         ModuleData {
515             parent,
516             kind,
517             lazy_resolutions: Default::default(),
518             populate_on_access: Cell::new(is_foreign),
519             unexpanded_invocations: Default::default(),
520             no_implicit_prelude,
521             glob_importers: RefCell::new(Vec::new()),
522             globs: RefCell::new(Vec::new()),
523             traits: RefCell::new(None),
524             span,
525             expansion,
526         }
527     }
528
529     fn for_each_child<R, F>(&'a self, resolver: &mut R, mut f: F)
530     where
531         R: AsMut<Resolver<'a>>,
532         F: FnMut(&mut R, Ident, Namespace, &'a NameBinding<'a>),
533     {
534         for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() {
535             if let Some(binding) = name_resolution.borrow().binding {
536                 f(resolver, key.ident, key.ns, binding);
537             }
538         }
539     }
540
541     /// This modifies `self` in place. The traits will be stored in `self.traits`.
542     fn ensure_traits<R>(&'a self, resolver: &mut R)
543     where
544         R: AsMut<Resolver<'a>>,
545     {
546         let mut traits = self.traits.borrow_mut();
547         if traits.is_none() {
548             let mut collected_traits = Vec::new();
549             self.for_each_child(resolver, |_, name, ns, binding| {
550                 if ns != TypeNS {
551                     return;
552                 }
553                 if let Res::Def(DefKind::Trait | DefKind::TraitAlias, _) = binding.res() {
554                     collected_traits.push((name, binding))
555                 }
556             });
557             *traits = Some(collected_traits.into_boxed_slice());
558         }
559     }
560
561     fn res(&self) -> Option<Res> {
562         match self.kind {
563             ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)),
564             _ => None,
565         }
566     }
567
568     // Public for rustdoc.
569     pub fn def_id(&self) -> DefId {
570         self.opt_def_id().expect("`ModuleData::def_id` is called on a block module")
571     }
572
573     fn opt_def_id(&self) -> Option<DefId> {
574         match self.kind {
575             ModuleKind::Def(_, def_id, _) => Some(def_id),
576             _ => None,
577         }
578     }
579
580     // `self` resolves to the first module ancestor that `is_normal`.
581     fn is_normal(&self) -> bool {
582         matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _))
583     }
584
585     fn is_trait(&self) -> bool {
586         matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _))
587     }
588
589     fn nearest_item_scope(&'a self) -> Module<'a> {
590         match self.kind {
591             ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => {
592                 self.parent.expect("enum or trait module without a parent")
593             }
594             _ => self,
595         }
596     }
597
598     /// The [`DefId`] of the nearest `mod` item ancestor (which may be this module).
599     /// This may be the crate root.
600     fn nearest_parent_mod(&self) -> DefId {
601         match self.kind {
602             ModuleKind::Def(DefKind::Mod, def_id, _) => def_id,
603             _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),
604         }
605     }
606
607     fn is_ancestor_of(&self, mut other: &Self) -> bool {
608         while !ptr::eq(self, other) {
609             if let Some(parent) = other.parent {
610                 other = parent;
611             } else {
612                 return false;
613             }
614         }
615         true
616     }
617 }
618
619 impl<'a> fmt::Debug for ModuleData<'a> {
620     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
621         write!(f, "{:?}", self.res())
622     }
623 }
624
625 /// Records a possibly-private value, type, or module definition.
626 #[derive(Clone, Debug)]
627 pub struct NameBinding<'a> {
628     kind: NameBindingKind<'a>,
629     ambiguity: Option<(&'a NameBinding<'a>, AmbiguityKind)>,
630     expansion: LocalExpnId,
631     span: Span,
632     vis: ty::Visibility<DefId>,
633 }
634
635 pub trait ToNameBinding<'a> {
636     fn to_name_binding(self, arenas: &'a ResolverArenas<'a>) -> &'a NameBinding<'a>;
637 }
638
639 impl<'a> ToNameBinding<'a> for &'a NameBinding<'a> {
640     fn to_name_binding(self, _: &'a ResolverArenas<'a>) -> &'a NameBinding<'a> {
641         self
642     }
643 }
644
645 #[derive(Clone, Debug)]
646 enum NameBindingKind<'a> {
647     Res(Res),
648     Module(Module<'a>),
649     Import { binding: &'a NameBinding<'a>, import: &'a Import<'a>, used: Cell<bool> },
650 }
651
652 impl<'a> NameBindingKind<'a> {
653     /// Is this a name binding of an import?
654     fn is_import(&self) -> bool {
655         matches!(*self, NameBindingKind::Import { .. })
656     }
657 }
658
659 struct PrivacyError<'a> {
660     ident: Ident,
661     binding: &'a NameBinding<'a>,
662     dedup_span: Span,
663 }
664
665 struct UseError<'a> {
666     err: DiagnosticBuilder<'a, ErrorGuaranteed>,
667     /// Candidates which user could `use` to access the missing type.
668     candidates: Vec<ImportSuggestion>,
669     /// The `DefId` of the module to place the use-statements in.
670     def_id: DefId,
671     /// Whether the diagnostic should say "instead" (as in `consider importing ... instead`).
672     instead: bool,
673     /// Extra free-form suggestion.
674     suggestion: Option<(Span, &'static str, String, Applicability)>,
675     /// Path `Segment`s at the place of use that failed. Used for accurate suggestion after telling
676     /// the user to import the item directly.
677     path: Vec<Segment>,
678     /// Whether the expected source is a call
679     is_call: bool,
680 }
681
682 #[derive(Clone, Copy, PartialEq, Debug)]
683 enum AmbiguityKind {
684     Import,
685     BuiltinAttr,
686     DeriveHelper,
687     MacroRulesVsModularized,
688     GlobVsOuter,
689     GlobVsGlob,
690     GlobVsExpanded,
691     MoreExpandedVsOuter,
692 }
693
694 impl AmbiguityKind {
695     fn descr(self) -> &'static str {
696         match self {
697             AmbiguityKind::Import => "multiple potential import sources",
698             AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute",
699             AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute",
700             AmbiguityKind::MacroRulesVsModularized => {
701                 "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"
702             }
703             AmbiguityKind::GlobVsOuter => {
704                 "a conflict between a name from a glob import and an outer scope during import or macro resolution"
705             }
706             AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module",
707             AmbiguityKind::GlobVsExpanded => {
708                 "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"
709             }
710             AmbiguityKind::MoreExpandedVsOuter => {
711                 "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"
712             }
713         }
714     }
715 }
716
717 /// Miscellaneous bits of metadata for better ambiguity error reporting.
718 #[derive(Clone, Copy, PartialEq)]
719 enum AmbiguityErrorMisc {
720     SuggestCrate,
721     SuggestSelf,
722     FromPrelude,
723     None,
724 }
725
726 struct AmbiguityError<'a> {
727     kind: AmbiguityKind,
728     ident: Ident,
729     b1: &'a NameBinding<'a>,
730     b2: &'a NameBinding<'a>,
731     misc1: AmbiguityErrorMisc,
732     misc2: AmbiguityErrorMisc,
733 }
734
735 impl<'a> NameBinding<'a> {
736     fn module(&self) -> Option<Module<'a>> {
737         match self.kind {
738             NameBindingKind::Module(module) => Some(module),
739             NameBindingKind::Import { binding, .. } => binding.module(),
740             _ => None,
741         }
742     }
743
744     fn res(&self) -> Res {
745         match self.kind {
746             NameBindingKind::Res(res) => res,
747             NameBindingKind::Module(module) => module.res().unwrap(),
748             NameBindingKind::Import { binding, .. } => binding.res(),
749         }
750     }
751
752     fn is_ambiguity(&self) -> bool {
753         self.ambiguity.is_some()
754             || match self.kind {
755                 NameBindingKind::Import { binding, .. } => binding.is_ambiguity(),
756                 _ => false,
757             }
758     }
759
760     fn is_possibly_imported_variant(&self) -> bool {
761         match self.kind {
762             NameBindingKind::Import { binding, .. } => binding.is_possibly_imported_variant(),
763             NameBindingKind::Res(Res::Def(
764                 DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..),
765                 _,
766             )) => true,
767             NameBindingKind::Res(..) | NameBindingKind::Module(..) => false,
768         }
769     }
770
771     fn is_extern_crate(&self) -> bool {
772         match self.kind {
773             NameBindingKind::Import {
774                 import: &Import { kind: ImportKind::ExternCrate { .. }, .. },
775                 ..
776             } => true,
777             NameBindingKind::Module(&ModuleData {
778                 kind: ModuleKind::Def(DefKind::Mod, def_id, _),
779                 ..
780             }) => def_id.is_crate_root(),
781             _ => false,
782         }
783     }
784
785     fn is_import(&self) -> bool {
786         matches!(self.kind, NameBindingKind::Import { .. })
787     }
788
789     /// The binding introduced by `#[macro_export] macro_rules` is a public import, but it might
790     /// not be perceived as such by users, so treat it as a non-import in some diagnostics.
791     fn is_import_user_facing(&self) -> bool {
792         matches!(self.kind, NameBindingKind::Import { import, .. }
793             if !matches!(import.kind, ImportKind::MacroExport))
794     }
795
796     fn is_glob_import(&self) -> bool {
797         match self.kind {
798             NameBindingKind::Import { import, .. } => import.is_glob(),
799             _ => false,
800         }
801     }
802
803     fn is_importable(&self) -> bool {
804         !matches!(
805             self.res(),
806             Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _)
807         )
808     }
809
810     fn macro_kind(&self) -> Option<MacroKind> {
811         self.res().macro_kind()
812     }
813
814     // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
815     // at some expansion round `max(invoc, binding)` when they both emerged from macros.
816     // Then this function returns `true` if `self` may emerge from a macro *after* that
817     // in some later round and screw up our previously found resolution.
818     // See more detailed explanation in
819     // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
820     fn may_appear_after(
821         &self,
822         invoc_parent_expansion: LocalExpnId,
823         binding: &NameBinding<'_>,
824     ) -> bool {
825         // self > max(invoc, binding) => !(self <= invoc || self <= binding)
826         // Expansions are partially ordered, so "may appear after" is an inversion of
827         // "certainly appears before or simultaneously" and includes unordered cases.
828         let self_parent_expansion = self.expansion;
829         let other_parent_expansion = binding.expansion;
830         let certainly_before_other_or_simultaneously =
831             other_parent_expansion.is_descendant_of(self_parent_expansion);
832         let certainly_before_invoc_or_simultaneously =
833             invoc_parent_expansion.is_descendant_of(self_parent_expansion);
834         !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
835     }
836 }
837
838 #[derive(Default, Clone)]
839 pub struct ExternPreludeEntry<'a> {
840     extern_crate_item: Option<&'a NameBinding<'a>>,
841     pub introduced_by_item: bool,
842 }
843
844 /// Used for better errors for E0773
845 enum BuiltinMacroState {
846     NotYetSeen(SyntaxExtensionKind),
847     AlreadySeen(Span),
848 }
849
850 struct DeriveData {
851     resolutions: DeriveResolutions,
852     helper_attrs: Vec<(usize, Ident)>,
853     has_derive_copy: bool,
854 }
855
856 #[derive(Clone)]
857 struct MacroData {
858     ext: Lrc<SyntaxExtension>,
859     macro_rules: bool,
860 }
861
862 /// The main resolver class.
863 ///
864 /// This is the visitor that walks the whole crate.
865 pub struct Resolver<'a> {
866     session: &'a Session,
867
868     definitions: Definitions,
869     /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
870     expn_that_defined: FxHashMap<LocalDefId, ExpnId>,
871     /// Reference span for definitions.
872     source_span: IndexVec<LocalDefId, Span>,
873
874     graph_root: Module<'a>,
875
876     prelude: Option<Module<'a>>,
877     extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'a>>,
878
879     /// N.B., this is used only for better diagnostics, not name resolution itself.
880     has_self: FxHashSet<DefId>,
881
882     /// Names of fields of an item `DefId` accessible with dot syntax.
883     /// Used for hints during error reporting.
884     field_names: FxHashMap<DefId, Vec<Spanned<Symbol>>>,
885
886     /// All imports known to succeed or fail.
887     determined_imports: Vec<&'a Import<'a>>,
888
889     /// All non-determined imports.
890     indeterminate_imports: Vec<&'a Import<'a>>,
891
892     // Spans for local variables found during pattern resolution.
893     // Used for suggestions during error reporting.
894     pat_span_map: NodeMap<Span>,
895
896     /// Resolutions for nodes that have a single resolution.
897     partial_res_map: NodeMap<PartialRes>,
898     /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
899     import_res_map: NodeMap<PerNS<Option<Res>>>,
900     /// Resolutions for labels (node IDs of their corresponding blocks or loops).
901     label_res_map: NodeMap<NodeId>,
902     /// Resolutions for lifetimes.
903     lifetimes_res_map: NodeMap<LifetimeRes>,
904     /// Lifetime parameters that lowering will have to introduce.
905     extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>>,
906
907     /// `CrateNum` resolutions of `extern crate` items.
908     extern_crate_map: FxHashMap<LocalDefId, CrateNum>,
909     reexport_map: FxHashMap<LocalDefId, Vec<ModChild>>,
910     trait_map: NodeMap<Vec<TraitCandidate>>,
911
912     /// A map from nodes to anonymous modules.
913     /// Anonymous modules are pseudo-modules that are implicitly created around items
914     /// contained within blocks.
915     ///
916     /// For example, if we have this:
917     ///
918     ///  fn f() {
919     ///      fn g() {
920     ///          ...
921     ///      }
922     ///  }
923     ///
924     /// There will be an anonymous module created around `g` with the ID of the
925     /// entry block for `f`.
926     block_map: NodeMap<Module<'a>>,
927     /// A fake module that contains no definition and no prelude. Used so that
928     /// some AST passes can generate identifiers that only resolve to local or
929     /// language items.
930     empty_module: Module<'a>,
931     module_map: FxHashMap<DefId, Module<'a>>,
932     binding_parent_modules: FxHashMap<Interned<'a, NameBinding<'a>>, Module<'a>>,
933     underscore_disambiguator: u32,
934
935     /// Maps glob imports to the names of items actually imported.
936     glob_map: FxHashMap<LocalDefId, FxHashSet<Symbol>>,
937     /// Visibilities in "lowered" form, for all entities that have them.
938     visibilities: FxHashMap<LocalDefId, ty::Visibility>,
939     has_pub_restricted: bool,
940     used_imports: FxHashSet<NodeId>,
941     maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
942     maybe_unused_extern_crates: Vec<(LocalDefId, Span)>,
943
944     /// Privacy errors are delayed until the end in order to deduplicate them.
945     privacy_errors: Vec<PrivacyError<'a>>,
946     /// Ambiguity errors are delayed for deduplication.
947     ambiguity_errors: Vec<AmbiguityError<'a>>,
948     /// `use` injections are delayed for better placement and deduplication.
949     use_injections: Vec<UseError<'a>>,
950     /// Crate-local macro expanded `macro_export` referred to by a module-relative path.
951     macro_expanded_macro_export_errors: BTreeSet<(Span, Span)>,
952
953     arenas: &'a ResolverArenas<'a>,
954     dummy_binding: &'a NameBinding<'a>,
955
956     crate_loader: CrateLoader<'a>,
957     macro_names: FxHashSet<Ident>,
958     builtin_macros: FxHashMap<Symbol, BuiltinMacroState>,
959     /// A small map keeping true kinds of built-in macros that appear to be fn-like on
960     /// the surface (`macro` items in libcore), but are actually attributes or derives.
961     builtin_macro_kinds: FxHashMap<LocalDefId, MacroKind>,
962     registered_tools: RegisteredTools,
963     macro_use_prelude: FxHashMap<Symbol, &'a NameBinding<'a>>,
964     macro_map: FxHashMap<DefId, MacroData>,
965     dummy_ext_bang: Lrc<SyntaxExtension>,
966     dummy_ext_derive: Lrc<SyntaxExtension>,
967     non_macro_attr: Lrc<SyntaxExtension>,
968     local_macro_def_scopes: FxHashMap<LocalDefId, Module<'a>>,
969     ast_transform_scopes: FxHashMap<LocalExpnId, Module<'a>>,
970     unused_macros: FxHashMap<LocalDefId, (NodeId, Ident)>,
971     unused_macro_rules: FxHashMap<(LocalDefId, usize), (Ident, Span)>,
972     proc_macro_stubs: FxHashSet<LocalDefId>,
973     /// Traces collected during macro resolution and validated when it's complete.
974     single_segment_macro_resolutions:
975         Vec<(Ident, MacroKind, ParentScope<'a>, Option<&'a NameBinding<'a>>)>,
976     multi_segment_macro_resolutions:
977         Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'a>, Option<Res>)>,
978     builtin_attrs: Vec<(Ident, ParentScope<'a>)>,
979     /// `derive(Copy)` marks items they are applied to so they are treated specially later.
980     /// Derive macros cannot modify the item themselves and have to store the markers in the global
981     /// context, so they attach the markers to derive container IDs using this resolver table.
982     containers_deriving_copy: FxHashSet<LocalExpnId>,
983     /// Parent scopes in which the macros were invoked.
984     /// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere.
985     invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'a>>,
986     /// `macro_rules` scopes *produced* by expanding the macro invocations,
987     /// include all the `macro_rules` items and other invocations generated by them.
988     output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'a>>,
989     /// `macro_rules` scopes produced by `macro_rules` item definitions.
990     macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'a>>,
991     /// Helper attributes that are in scope for the given expansion.
992     helper_attrs: FxHashMap<LocalExpnId, Vec<Ident>>,
993     /// Ready or in-progress results of resolving paths inside the `#[derive(...)]` attribute
994     /// with the given `ExpnId`.
995     derive_data: FxHashMap<LocalExpnId, DeriveData>,
996
997     /// Avoid duplicated errors for "name already defined".
998     name_already_seen: FxHashMap<Symbol, Span>,
999
1000     potentially_unused_imports: Vec<&'a Import<'a>>,
1001
1002     /// Table for mapping struct IDs into struct constructor IDs,
1003     /// it's not used during normal resolution, only for better error reporting.
1004     /// Also includes of list of each fields visibility
1005     struct_constructors: DefIdMap<(Res, ty::Visibility<DefId>, Vec<ty::Visibility<DefId>>)>,
1006
1007     /// Features enabled for this crate.
1008     active_features: FxHashSet<Symbol>,
1009
1010     lint_buffer: LintBuffer,
1011
1012     next_node_id: NodeId,
1013
1014     node_id_to_def_id: FxHashMap<ast::NodeId, LocalDefId>,
1015     def_id_to_node_id: IndexVec<LocalDefId, ast::NodeId>,
1016
1017     /// Indices of unnamed struct or variant fields with unresolved attributes.
1018     placeholder_field_indices: FxHashMap<NodeId, usize>,
1019     /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId`
1020     /// we know what parent node that fragment should be attached to thanks to this table,
1021     /// and how the `impl Trait` fragments were introduced.
1022     invocation_parents: FxHashMap<LocalExpnId, (LocalDefId, ImplTraitContext)>,
1023
1024     /// Some way to know that we are in a *trait* impl in `visit_assoc_item`.
1025     /// FIXME: Replace with a more general AST map (together with some other fields).
1026     trait_impl_items: FxHashSet<LocalDefId>,
1027
1028     legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
1029     /// Amount of lifetime parameters for each item in the crate.
1030     item_generics_num_lifetimes: FxHashMap<LocalDefId, usize>,
1031
1032     main_def: Option<MainDefinition>,
1033     trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1034     /// A list of proc macro LocalDefIds, written out in the order in which
1035     /// they are declared in the static array generated by proc_macro_harness.
1036     proc_macros: Vec<NodeId>,
1037     confused_type_with_std_module: FxHashMap<Span, Span>,
1038
1039     effective_visibilities: EffectiveVisibilities,
1040 }
1041
1042 /// Nothing really interesting here; it just provides memory for the rest of the crate.
1043 #[derive(Default)]
1044 pub struct ResolverArenas<'a> {
1045     modules: TypedArena<ModuleData<'a>>,
1046     local_modules: RefCell<Vec<Module<'a>>>,
1047     imports: TypedArena<Import<'a>>,
1048     name_resolutions: TypedArena<RefCell<NameResolution<'a>>>,
1049     ast_paths: TypedArena<ast::Path>,
1050     dropless: DroplessArena,
1051 }
1052
1053 impl<'a> ResolverArenas<'a> {
1054     fn new_module(
1055         &'a self,
1056         parent: Option<Module<'a>>,
1057         kind: ModuleKind,
1058         expn_id: ExpnId,
1059         span: Span,
1060         no_implicit_prelude: bool,
1061         module_map: &mut FxHashMap<DefId, Module<'a>>,
1062     ) -> Module<'a> {
1063         let module =
1064             self.modules.alloc(ModuleData::new(parent, kind, expn_id, span, no_implicit_prelude));
1065         let def_id = module.opt_def_id();
1066         if def_id.map_or(true, |def_id| def_id.is_local()) {
1067             self.local_modules.borrow_mut().push(module);
1068         }
1069         if let Some(def_id) = def_id {
1070             module_map.insert(def_id, module);
1071         }
1072         module
1073     }
1074     fn local_modules(&'a self) -> std::cell::Ref<'a, Vec<Module<'a>>> {
1075         self.local_modules.borrow()
1076     }
1077     fn alloc_name_binding(&'a self, name_binding: NameBinding<'a>) -> &'a NameBinding<'a> {
1078         self.dropless.alloc(name_binding)
1079     }
1080     fn alloc_import(&'a self, import: Import<'a>) -> &'a Import<'_> {
1081         self.imports.alloc(import)
1082     }
1083     fn alloc_name_resolution(&'a self) -> &'a RefCell<NameResolution<'a>> {
1084         self.name_resolutions.alloc(Default::default())
1085     }
1086     fn alloc_macro_rules_scope(&'a self, scope: MacroRulesScope<'a>) -> MacroRulesScopeRef<'a> {
1087         Interned::new_unchecked(self.dropless.alloc(Cell::new(scope)))
1088     }
1089     fn alloc_macro_rules_binding(
1090         &'a self,
1091         binding: MacroRulesBinding<'a>,
1092     ) -> &'a MacroRulesBinding<'a> {
1093         self.dropless.alloc(binding)
1094     }
1095     fn alloc_ast_paths(&'a self, paths: &[ast::Path]) -> &'a [ast::Path] {
1096         self.ast_paths.alloc_from_iter(paths.iter().cloned())
1097     }
1098     fn alloc_pattern_spans(&'a self, spans: impl Iterator<Item = Span>) -> &'a [Span] {
1099         self.dropless.alloc_from_iter(spans)
1100     }
1101 }
1102
1103 impl<'a> AsMut<Resolver<'a>> for Resolver<'a> {
1104     fn as_mut(&mut self) -> &mut Resolver<'a> {
1105         self
1106     }
1107 }
1108
1109 impl<'a, 'b> DefIdTree for &'a Resolver<'b> {
1110     #[inline]
1111     fn opt_parent(self, id: DefId) -> Option<DefId> {
1112         match id.as_local() {
1113             Some(id) => self.definitions.def_key(id).parent,
1114             None => self.cstore().def_key(id).parent,
1115         }
1116         .map(|index| DefId { index, ..id })
1117     }
1118 }
1119
1120 impl Resolver<'_> {
1121     fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1122         self.node_id_to_def_id.get(&node).copied()
1123     }
1124
1125     pub fn local_def_id(&self, node: NodeId) -> LocalDefId {
1126         self.opt_local_def_id(node).unwrap_or_else(|| panic!("no entry for node id: `{:?}`", node))
1127     }
1128
1129     /// Adds a definition with a parent definition.
1130     fn create_def(
1131         &mut self,
1132         parent: LocalDefId,
1133         node_id: ast::NodeId,
1134         data: DefPathData,
1135         expn_id: ExpnId,
1136         span: Span,
1137     ) -> LocalDefId {
1138         assert!(
1139             !self.node_id_to_def_id.contains_key(&node_id),
1140             "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
1141             node_id,
1142             data,
1143             self.definitions.def_key(self.node_id_to_def_id[&node_id]),
1144         );
1145
1146         let def_id = self.definitions.create_def(parent, data);
1147
1148         // Create the definition.
1149         if expn_id != ExpnId::root() {
1150             self.expn_that_defined.insert(def_id, expn_id);
1151         }
1152
1153         // A relative span's parent must be an absolute span.
1154         debug_assert_eq!(span.data_untracked().parent, None);
1155         let _id = self.source_span.push(span);
1156         debug_assert_eq!(_id, def_id);
1157
1158         // Some things for which we allocate `LocalDefId`s don't correspond to
1159         // anything in the AST, so they don't have a `NodeId`. For these cases
1160         // we don't need a mapping from `NodeId` to `LocalDefId`.
1161         if node_id != ast::DUMMY_NODE_ID {
1162             debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1163             self.node_id_to_def_id.insert(node_id, def_id);
1164         }
1165         assert_eq!(self.def_id_to_node_id.push(node_id), def_id);
1166
1167         def_id
1168     }
1169
1170     fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1171         if let Some(def_id) = def_id.as_local() {
1172             self.item_generics_num_lifetimes[&def_id]
1173         } else {
1174             self.cstore().item_generics_num_lifetimes(def_id, self.session)
1175         }
1176     }
1177 }
1178
1179 impl<'a> Resolver<'a> {
1180     pub fn new(
1181         session: &'a Session,
1182         krate: &Crate,
1183         crate_name: &str,
1184         metadata_loader: Box<MetadataLoaderDyn>,
1185         arenas: &'a ResolverArenas<'a>,
1186     ) -> Resolver<'a> {
1187         let root_def_id = CRATE_DEF_ID.to_def_id();
1188         let mut module_map = FxHashMap::default();
1189         let graph_root = arenas.new_module(
1190             None,
1191             ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty),
1192             ExpnId::root(),
1193             krate.spans.inner_span,
1194             session.contains_name(&krate.attrs, sym::no_implicit_prelude),
1195             &mut module_map,
1196         );
1197         let empty_module = arenas.new_module(
1198             None,
1199             ModuleKind::Def(DefKind::Mod, root_def_id, kw::Empty),
1200             ExpnId::root(),
1201             DUMMY_SP,
1202             true,
1203             &mut FxHashMap::default(),
1204         );
1205
1206         let definitions = Definitions::new(session.local_stable_crate_id());
1207
1208         let mut visibilities = FxHashMap::default();
1209         visibilities.insert(CRATE_DEF_ID, ty::Visibility::Public);
1210
1211         let mut def_id_to_node_id = IndexVec::default();
1212         assert_eq!(def_id_to_node_id.push(CRATE_NODE_ID), CRATE_DEF_ID);
1213         let mut node_id_to_def_id = FxHashMap::default();
1214         node_id_to_def_id.insert(CRATE_NODE_ID, CRATE_DEF_ID);
1215
1216         let mut invocation_parents = FxHashMap::default();
1217         invocation_parents.insert(LocalExpnId::ROOT, (CRATE_DEF_ID, ImplTraitContext::Existential));
1218
1219         let mut source_span = IndexVec::default();
1220         let _id = source_span.push(krate.spans.inner_span);
1221         debug_assert_eq!(_id, CRATE_DEF_ID);
1222
1223         let mut extern_prelude: FxHashMap<Ident, ExternPreludeEntry<'_>> = session
1224             .opts
1225             .externs
1226             .iter()
1227             .filter(|(_, entry)| entry.add_prelude)
1228             .map(|(name, _)| (Ident::from_str(name), Default::default()))
1229             .collect();
1230
1231         if !session.contains_name(&krate.attrs, sym::no_core) {
1232             extern_prelude.insert(Ident::with_dummy_span(sym::core), Default::default());
1233             if !session.contains_name(&krate.attrs, sym::no_std) {
1234                 extern_prelude.insert(Ident::with_dummy_span(sym::std), Default::default());
1235             }
1236         }
1237
1238         let registered_tools = macros::registered_tools(session, &krate.attrs);
1239
1240         let features = session.features_untracked();
1241
1242         let mut resolver = Resolver {
1243             session,
1244
1245             definitions,
1246             expn_that_defined: Default::default(),
1247             source_span,
1248
1249             // The outermost module has def ID 0; this is not reflected in the
1250             // AST.
1251             graph_root,
1252             prelude: None,
1253             extern_prelude,
1254
1255             has_self: FxHashSet::default(),
1256             field_names: FxHashMap::default(),
1257
1258             determined_imports: Vec::new(),
1259             indeterminate_imports: Vec::new(),
1260
1261             pat_span_map: Default::default(),
1262             partial_res_map: Default::default(),
1263             import_res_map: Default::default(),
1264             label_res_map: Default::default(),
1265             lifetimes_res_map: Default::default(),
1266             extra_lifetime_params_map: Default::default(),
1267             extern_crate_map: Default::default(),
1268             reexport_map: FxHashMap::default(),
1269             trait_map: NodeMap::default(),
1270             underscore_disambiguator: 0,
1271             empty_module,
1272             module_map,
1273             block_map: Default::default(),
1274             binding_parent_modules: FxHashMap::default(),
1275             ast_transform_scopes: FxHashMap::default(),
1276
1277             glob_map: Default::default(),
1278             visibilities,
1279             has_pub_restricted: false,
1280             used_imports: FxHashSet::default(),
1281             maybe_unused_trait_imports: Default::default(),
1282             maybe_unused_extern_crates: Vec::new(),
1283
1284             privacy_errors: Vec::new(),
1285             ambiguity_errors: Vec::new(),
1286             use_injections: Vec::new(),
1287             macro_expanded_macro_export_errors: BTreeSet::new(),
1288
1289             arenas,
1290             dummy_binding: arenas.alloc_name_binding(NameBinding {
1291                 kind: NameBindingKind::Res(Res::Err),
1292                 ambiguity: None,
1293                 expansion: LocalExpnId::ROOT,
1294                 span: DUMMY_SP,
1295                 vis: ty::Visibility::Public,
1296             }),
1297
1298             crate_loader: CrateLoader::new(session, metadata_loader, crate_name),
1299             macro_names: FxHashSet::default(),
1300             builtin_macros: Default::default(),
1301             builtin_macro_kinds: Default::default(),
1302             registered_tools,
1303             macro_use_prelude: FxHashMap::default(),
1304             macro_map: FxHashMap::default(),
1305             dummy_ext_bang: Lrc::new(SyntaxExtension::dummy_bang(session.edition())),
1306             dummy_ext_derive: Lrc::new(SyntaxExtension::dummy_derive(session.edition())),
1307             non_macro_attr: Lrc::new(SyntaxExtension::non_macro_attr(session.edition())),
1308             invocation_parent_scopes: Default::default(),
1309             output_macro_rules_scopes: Default::default(),
1310             macro_rules_scopes: Default::default(),
1311             helper_attrs: Default::default(),
1312             derive_data: Default::default(),
1313             local_macro_def_scopes: FxHashMap::default(),
1314             name_already_seen: FxHashMap::default(),
1315             potentially_unused_imports: Vec::new(),
1316             struct_constructors: Default::default(),
1317             unused_macros: Default::default(),
1318             unused_macro_rules: Default::default(),
1319             proc_macro_stubs: Default::default(),
1320             single_segment_macro_resolutions: Default::default(),
1321             multi_segment_macro_resolutions: Default::default(),
1322             builtin_attrs: Default::default(),
1323             containers_deriving_copy: Default::default(),
1324             active_features: features
1325                 .declared_lib_features
1326                 .iter()
1327                 .map(|(feat, ..)| *feat)
1328                 .chain(features.declared_lang_features.iter().map(|(feat, ..)| *feat))
1329                 .collect(),
1330             lint_buffer: LintBuffer::default(),
1331             next_node_id: CRATE_NODE_ID,
1332             node_id_to_def_id,
1333             def_id_to_node_id,
1334             placeholder_field_indices: Default::default(),
1335             invocation_parents,
1336             trait_impl_items: Default::default(),
1337             legacy_const_generic_args: Default::default(),
1338             item_generics_num_lifetimes: Default::default(),
1339             main_def: Default::default(),
1340             trait_impls: Default::default(),
1341             proc_macros: Default::default(),
1342             confused_type_with_std_module: Default::default(),
1343             effective_visibilities: Default::default(),
1344         };
1345
1346         let root_parent_scope = ParentScope::module(graph_root, &resolver);
1347         resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1348
1349         resolver
1350     }
1351
1352     fn new_module(
1353         &mut self,
1354         parent: Option<Module<'a>>,
1355         kind: ModuleKind,
1356         expn_id: ExpnId,
1357         span: Span,
1358         no_implicit_prelude: bool,
1359     ) -> Module<'a> {
1360         let module_map = &mut self.module_map;
1361         self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude, module_map)
1362     }
1363
1364     pub fn next_node_id(&mut self) -> NodeId {
1365         let start = self.next_node_id;
1366         let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1367         self.next_node_id = ast::NodeId::from_u32(next);
1368         start
1369     }
1370
1371     pub fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1372         let start = self.next_node_id;
1373         let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1374         self.next_node_id = ast::NodeId::from_usize(end);
1375         start..self.next_node_id
1376     }
1377
1378     pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1379         &mut self.lint_buffer
1380     }
1381
1382     pub fn arenas() -> ResolverArenas<'a> {
1383         Default::default()
1384     }
1385
1386     pub fn into_outputs(self) -> ResolverOutputs {
1387         let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect();
1388         let definitions = self.definitions;
1389         let cstore = Box::new(self.crate_loader.into_cstore());
1390         let source_span = self.source_span;
1391         let expn_that_defined = self.expn_that_defined;
1392         let visibilities = self.visibilities;
1393         let has_pub_restricted = self.has_pub_restricted;
1394         let extern_crate_map = self.extern_crate_map;
1395         let reexport_map = self.reexport_map;
1396         let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1397         let maybe_unused_extern_crates = self.maybe_unused_extern_crates;
1398         let glob_map = self.glob_map;
1399         let main_def = self.main_def;
1400         let confused_type_with_std_module = self.confused_type_with_std_module;
1401         let effective_visibilities = self.effective_visibilities;
1402         let global_ctxt = ResolverGlobalCtxt {
1403             cstore,
1404             source_span,
1405             expn_that_defined,
1406             visibilities,
1407             has_pub_restricted,
1408             effective_visibilities,
1409             extern_crate_map,
1410             reexport_map,
1411             glob_map,
1412             maybe_unused_trait_imports,
1413             maybe_unused_extern_crates,
1414             extern_prelude: self
1415                 .extern_prelude
1416                 .iter()
1417                 .map(|(ident, entry)| (ident.name, entry.introduced_by_item))
1418                 .collect(),
1419             main_def,
1420             trait_impls: self.trait_impls,
1421             proc_macros,
1422             confused_type_with_std_module,
1423             registered_tools: self.registered_tools,
1424         };
1425         let ast_lowering = ty::ResolverAstLowering {
1426             legacy_const_generic_args: self.legacy_const_generic_args,
1427             partial_res_map: self.partial_res_map,
1428             import_res_map: self.import_res_map,
1429             label_res_map: self.label_res_map,
1430             lifetimes_res_map: self.lifetimes_res_map,
1431             extra_lifetime_params_map: self.extra_lifetime_params_map,
1432             next_node_id: self.next_node_id,
1433             node_id_to_def_id: self.node_id_to_def_id,
1434             def_id_to_node_id: self.def_id_to_node_id,
1435             trait_map: self.trait_map,
1436             builtin_macro_kinds: self.builtin_macro_kinds,
1437         };
1438         ResolverOutputs { definitions, global_ctxt, ast_lowering }
1439     }
1440
1441     pub fn clone_outputs(&self) -> ResolverOutputs {
1442         let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect();
1443         let definitions = self.definitions.clone();
1444         let cstore = Box::new(self.cstore().clone());
1445         let global_ctxt = ResolverGlobalCtxt {
1446             cstore,
1447             source_span: self.source_span.clone(),
1448             expn_that_defined: self.expn_that_defined.clone(),
1449             visibilities: self.visibilities.clone(),
1450             has_pub_restricted: self.has_pub_restricted,
1451             extern_crate_map: self.extern_crate_map.clone(),
1452             reexport_map: self.reexport_map.clone(),
1453             glob_map: self.glob_map.clone(),
1454             maybe_unused_trait_imports: self.maybe_unused_trait_imports.clone(),
1455             maybe_unused_extern_crates: self.maybe_unused_extern_crates.clone(),
1456             extern_prelude: self
1457                 .extern_prelude
1458                 .iter()
1459                 .map(|(ident, entry)| (ident.name, entry.introduced_by_item))
1460                 .collect(),
1461             main_def: self.main_def,
1462             trait_impls: self.trait_impls.clone(),
1463             proc_macros,
1464             confused_type_with_std_module: self.confused_type_with_std_module.clone(),
1465             registered_tools: self.registered_tools.clone(),
1466             effective_visibilities: self.effective_visibilities.clone(),
1467         };
1468         let ast_lowering = ty::ResolverAstLowering {
1469             legacy_const_generic_args: self.legacy_const_generic_args.clone(),
1470             partial_res_map: self.partial_res_map.clone(),
1471             import_res_map: self.import_res_map.clone(),
1472             label_res_map: self.label_res_map.clone(),
1473             lifetimes_res_map: self.lifetimes_res_map.clone(),
1474             extra_lifetime_params_map: self.extra_lifetime_params_map.clone(),
1475             next_node_id: self.next_node_id.clone(),
1476             node_id_to_def_id: self.node_id_to_def_id.clone(),
1477             def_id_to_node_id: self.def_id_to_node_id.clone(),
1478             trait_map: self.trait_map.clone(),
1479             builtin_macro_kinds: self.builtin_macro_kinds.clone(),
1480         };
1481         ResolverOutputs { definitions, global_ctxt, ast_lowering }
1482     }
1483
1484     fn create_stable_hashing_context(&self) -> StableHashingContext<'_> {
1485         StableHashingContext::new(
1486             self.session,
1487             &self.definitions,
1488             self.crate_loader.cstore(),
1489             &self.source_span,
1490         )
1491     }
1492
1493     pub fn cstore(&self) -> &CStore {
1494         self.crate_loader.cstore()
1495     }
1496
1497     fn dummy_ext(&self, macro_kind: MacroKind) -> Lrc<SyntaxExtension> {
1498         match macro_kind {
1499             MacroKind::Bang => self.dummy_ext_bang.clone(),
1500             MacroKind::Derive => self.dummy_ext_derive.clone(),
1501             MacroKind::Attr => self.non_macro_attr.clone(),
1502         }
1503     }
1504
1505     /// Runs the function on each namespace.
1506     fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1507         f(self, TypeNS);
1508         f(self, ValueNS);
1509         f(self, MacroNS);
1510     }
1511
1512     fn is_builtin_macro(&mut self, res: Res) -> bool {
1513         self.get_macro(res).map_or(false, |macro_data| macro_data.ext.builtin_name.is_some())
1514     }
1515
1516     fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1517         loop {
1518             match ctxt.outer_expn_data().macro_def_id {
1519                 Some(def_id) => return def_id,
1520                 None => ctxt.remove_mark(),
1521             };
1522         }
1523     }
1524
1525     /// Entry point to crate resolution.
1526     pub fn resolve_crate(&mut self, krate: &Crate) {
1527         self.session.time("resolve_crate", || {
1528             self.session.time("finalize_imports", || ImportResolver { r: self }.finalize_imports());
1529             self.session.time("compute_effective_visibilities", || {
1530                 EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
1531             });
1532             self.session.time("finalize_macro_resolutions", || self.finalize_macro_resolutions());
1533             self.session.time("late_resolve_crate", || self.late_resolve_crate(krate));
1534             self.session.time("resolve_main", || self.resolve_main());
1535             self.session.time("resolve_check_unused", || self.check_unused(krate));
1536             self.session.time("resolve_report_errors", || self.report_errors(krate));
1537             self.session.time("resolve_postprocess", || self.crate_loader.postprocess(krate));
1538         });
1539     }
1540
1541     pub fn traits_in_scope(
1542         &mut self,
1543         current_trait: Option<Module<'a>>,
1544         parent_scope: &ParentScope<'a>,
1545         ctxt: SyntaxContext,
1546         assoc_item: Option<(Symbol, Namespace)>,
1547     ) -> Vec<TraitCandidate> {
1548         let mut found_traits = Vec::new();
1549
1550         if let Some(module) = current_trait {
1551             if self.trait_may_have_item(Some(module), assoc_item) {
1552                 let def_id = module.def_id();
1553                 found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
1554             }
1555         }
1556
1557         self.visit_scopes(ScopeSet::All(TypeNS, false), parent_scope, ctxt, |this, scope, _, _| {
1558             match scope {
1559                 Scope::Module(module) => {
1560                     this.traits_in_module(module, assoc_item, &mut found_traits);
1561                 }
1562                 Scope::StdLibPrelude => {
1563                     if let Some(module) = this.prelude {
1564                         this.traits_in_module(module, assoc_item, &mut found_traits);
1565                     }
1566                 }
1567                 Scope::ExternPrelude | Scope::ToolPrelude | Scope::BuiltinTypes => {}
1568                 _ => unreachable!(),
1569             }
1570             None::<()>
1571         });
1572
1573         found_traits
1574     }
1575
1576     fn traits_in_module(
1577         &mut self,
1578         module: Module<'a>,
1579         assoc_item: Option<(Symbol, Namespace)>,
1580         found_traits: &mut Vec<TraitCandidate>,
1581     ) {
1582         module.ensure_traits(self);
1583         let traits = module.traits.borrow();
1584         for (trait_name, trait_binding) in traits.as_ref().unwrap().iter() {
1585             if self.trait_may_have_item(trait_binding.module(), assoc_item) {
1586                 let def_id = trait_binding.res().def_id();
1587                 let import_ids = self.find_transitive_imports(&trait_binding.kind, *trait_name);
1588                 found_traits.push(TraitCandidate { def_id, import_ids });
1589             }
1590         }
1591     }
1592
1593     // List of traits in scope is pruned on best effort basis. We reject traits not having an
1594     // associated item with the given name and namespace (if specified). This is a conservative
1595     // optimization, proper hygienic type-based resolution of associated items is done in typeck.
1596     // We don't reject trait aliases (`trait_module == None`) because we don't have access to their
1597     // associated items.
1598     fn trait_may_have_item(
1599         &mut self,
1600         trait_module: Option<Module<'a>>,
1601         assoc_item: Option<(Symbol, Namespace)>,
1602     ) -> bool {
1603         match (trait_module, assoc_item) {
1604             (Some(trait_module), Some((name, ns))) => {
1605                 self.resolutions(trait_module).borrow().iter().any(|resolution| {
1606                     let (&BindingKey { ident: assoc_ident, ns: assoc_ns, .. }, _) = resolution;
1607                     assoc_ns == ns && assoc_ident.name == name
1608                 })
1609             }
1610             _ => true,
1611         }
1612     }
1613
1614     fn find_transitive_imports(
1615         &mut self,
1616         mut kind: &NameBindingKind<'_>,
1617         trait_name: Ident,
1618     ) -> SmallVec<[LocalDefId; 1]> {
1619         let mut import_ids = smallvec![];
1620         while let NameBindingKind::Import { import, binding, .. } = kind {
1621             if let Some(node_id) = import.id() {
1622                 let def_id = self.local_def_id(node_id);
1623                 self.maybe_unused_trait_imports.insert(def_id);
1624                 import_ids.push(def_id);
1625             }
1626             self.add_to_glob_map(&import, trait_name);
1627             kind = &binding.kind;
1628         }
1629         import_ids
1630     }
1631
1632     fn new_key(&mut self, ident: Ident, ns: Namespace) -> BindingKey {
1633         let ident = ident.normalize_to_macros_2_0();
1634         let disambiguator = if ident.name == kw::Underscore {
1635             self.underscore_disambiguator += 1;
1636             self.underscore_disambiguator
1637         } else {
1638             0
1639         };
1640         BindingKey { ident, ns, disambiguator }
1641     }
1642
1643     fn resolutions(&mut self, module: Module<'a>) -> &'a Resolutions<'a> {
1644         if module.populate_on_access.get() {
1645             module.populate_on_access.set(false);
1646             self.build_reduced_graph_external(module);
1647         }
1648         &module.lazy_resolutions
1649     }
1650
1651     fn resolution(
1652         &mut self,
1653         module: Module<'a>,
1654         key: BindingKey,
1655     ) -> &'a RefCell<NameResolution<'a>> {
1656         *self
1657             .resolutions(module)
1658             .borrow_mut()
1659             .entry(key)
1660             .or_insert_with(|| self.arenas.alloc_name_resolution())
1661     }
1662
1663     fn record_use(
1664         &mut self,
1665         ident: Ident,
1666         used_binding: &'a NameBinding<'a>,
1667         is_lexical_scope: bool,
1668     ) {
1669         if let Some((b2, kind)) = used_binding.ambiguity {
1670             self.ambiguity_errors.push(AmbiguityError {
1671                 kind,
1672                 ident,
1673                 b1: used_binding,
1674                 b2,
1675                 misc1: AmbiguityErrorMisc::None,
1676                 misc2: AmbiguityErrorMisc::None,
1677             });
1678         }
1679         if let NameBindingKind::Import { import, binding, ref used } = used_binding.kind {
1680             // Avoid marking `extern crate` items that refer to a name from extern prelude,
1681             // but not introduce it, as used if they are accessed from lexical scope.
1682             if is_lexical_scope {
1683                 if let Some(entry) = self.extern_prelude.get(&ident.normalize_to_macros_2_0()) {
1684                     if let Some(crate_item) = entry.extern_crate_item {
1685                         if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item {
1686                             return;
1687                         }
1688                     }
1689                 }
1690             }
1691             used.set(true);
1692             import.used.set(true);
1693             if let Some(id) = import.id() {
1694                 self.used_imports.insert(id);
1695             }
1696             self.add_to_glob_map(&import, ident);
1697             self.record_use(ident, binding, false);
1698         }
1699     }
1700
1701     #[inline]
1702     fn add_to_glob_map(&mut self, import: &Import<'_>, ident: Ident) {
1703         if let ImportKind::Glob { id, .. } = import.kind {
1704             let def_id = self.local_def_id(id);
1705             self.glob_map.entry(def_id).or_default().insert(ident.name);
1706         }
1707     }
1708
1709     fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> {
1710         debug!("resolve_crate_root({:?})", ident);
1711         let mut ctxt = ident.span.ctxt();
1712         let mark = if ident.name == kw::DollarCrate {
1713             // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
1714             // we don't want to pretend that the `macro_rules!` definition is in the `macro`
1715             // as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks.
1716             // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
1717             // definitions actually produced by `macro` and `macro` definitions produced by
1718             // `macro_rules!`, but at least such configurations are not stable yet.
1719             ctxt = ctxt.normalize_to_macro_rules();
1720             debug!(
1721                 "resolve_crate_root: marks={:?}",
1722                 ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
1723             );
1724             let mut iter = ctxt.marks().into_iter().rev().peekable();
1725             let mut result = None;
1726             // Find the last opaque mark from the end if it exists.
1727             while let Some(&(mark, transparency)) = iter.peek() {
1728                 if transparency == Transparency::Opaque {
1729                     result = Some(mark);
1730                     iter.next();
1731                 } else {
1732                     break;
1733                 }
1734             }
1735             debug!(
1736                 "resolve_crate_root: found opaque mark {:?} {:?}",
1737                 result,
1738                 result.map(|r| r.expn_data())
1739             );
1740             // Then find the last semi-transparent mark from the end if it exists.
1741             for (mark, transparency) in iter {
1742                 if transparency == Transparency::SemiTransparent {
1743                     result = Some(mark);
1744                 } else {
1745                     break;
1746                 }
1747             }
1748             debug!(
1749                 "resolve_crate_root: found semi-transparent mark {:?} {:?}",
1750                 result,
1751                 result.map(|r| r.expn_data())
1752             );
1753             result
1754         } else {
1755             debug!("resolve_crate_root: not DollarCrate");
1756             ctxt = ctxt.normalize_to_macros_2_0();
1757             ctxt.adjust(ExpnId::root())
1758         };
1759         let module = match mark {
1760             Some(def) => self.expn_def_scope(def),
1761             None => {
1762                 debug!(
1763                     "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
1764                     ident, ident.span
1765                 );
1766                 return self.graph_root;
1767             }
1768         };
1769         let module = self.expect_module(
1770             module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
1771         );
1772         debug!(
1773             "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
1774             ident,
1775             module,
1776             module.kind.name(),
1777             ident.span
1778         );
1779         module
1780     }
1781
1782     fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> {
1783         let mut module = self.expect_module(module.nearest_parent_mod());
1784         while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
1785             let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
1786             module = self.expect_module(parent.nearest_parent_mod());
1787         }
1788         module
1789     }
1790
1791     fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
1792         debug!("(recording res) recording {:?} for {}", resolution, node_id);
1793         if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
1794             panic!("path resolved multiple times ({:?} before, {:?} now)", prev_res, resolution);
1795         }
1796     }
1797
1798     fn record_pat_span(&mut self, node: NodeId, span: Span) {
1799         debug!("(recording pat) recording {:?} for {:?}", node, span);
1800         self.pat_span_map.insert(node, span);
1801     }
1802
1803     fn is_accessible_from(
1804         &self,
1805         vis: ty::Visibility<impl Into<DefId>>,
1806         module: Module<'a>,
1807     ) -> bool {
1808         vis.is_accessible_from(module.nearest_parent_mod(), self)
1809     }
1810
1811     fn set_binding_parent_module(&mut self, binding: &'a NameBinding<'a>, module: Module<'a>) {
1812         if let Some(old_module) =
1813             self.binding_parent_modules.insert(Interned::new_unchecked(binding), module)
1814         {
1815             if !ptr::eq(module, old_module) {
1816                 span_bug!(binding.span, "parent module is reset for binding");
1817             }
1818         }
1819     }
1820
1821     fn disambiguate_macro_rules_vs_modularized(
1822         &self,
1823         macro_rules: &'a NameBinding<'a>,
1824         modularized: &'a NameBinding<'a>,
1825     ) -> bool {
1826         // Some non-controversial subset of ambiguities "modularized macro name" vs "macro_rules"
1827         // is disambiguated to mitigate regressions from macro modularization.
1828         // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
1829         match (
1830             self.binding_parent_modules.get(&Interned::new_unchecked(macro_rules)),
1831             self.binding_parent_modules.get(&Interned::new_unchecked(modularized)),
1832         ) {
1833             (Some(macro_rules), Some(modularized)) => {
1834                 macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
1835                     && modularized.is_ancestor_of(macro_rules)
1836             }
1837             _ => false,
1838         }
1839     }
1840
1841     fn extern_prelude_get(&mut self, ident: Ident, finalize: bool) -> Option<&'a NameBinding<'a>> {
1842         if ident.is_path_segment_keyword() {
1843             // Make sure `self`, `super` etc produce an error when passed to here.
1844             return None;
1845         }
1846         self.extern_prelude.get(&ident.normalize_to_macros_2_0()).cloned().and_then(|entry| {
1847             if let Some(binding) = entry.extern_crate_item {
1848                 if finalize && entry.introduced_by_item {
1849                     self.record_use(ident, binding, false);
1850                 }
1851                 Some(binding)
1852             } else {
1853                 let crate_id = if finalize {
1854                     let Some(crate_id) =
1855                         self.crate_loader.process_path_extern(ident.name, ident.span) else { return Some(self.dummy_binding); };
1856                     crate_id
1857                 } else {
1858                     self.crate_loader.maybe_process_path_extern(ident.name)?
1859                 };
1860                 let crate_root = self.expect_module(crate_id.as_def_id());
1861                 let vis = ty::Visibility::<LocalDefId>::Public;
1862                 Some((crate_root, vis, DUMMY_SP, LocalExpnId::ROOT).to_name_binding(self.arenas))
1863             }
1864         })
1865     }
1866
1867     /// Rustdoc uses this to resolve doc link paths in a recoverable way. `PathResult<'a>`
1868     /// isn't something that can be returned because it can't be made to live that long,
1869     /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
1870     /// just that an error occurred.
1871     pub fn resolve_rustdoc_path(
1872         &mut self,
1873         path_str: &str,
1874         ns: Namespace,
1875         mut parent_scope: ParentScope<'a>,
1876     ) -> Option<Res> {
1877         let mut segments =
1878             Vec::from_iter(path_str.split("::").map(Ident::from_str).map(Segment::from_ident));
1879         if let Some(segment) = segments.first_mut() {
1880             if segment.ident.name == kw::Crate {
1881                 // FIXME: `resolve_path` always resolves `crate` to the current crate root, but
1882                 // rustdoc wants it to resolve to the `parent_scope`'s crate root. This trick of
1883                 // replacing `crate` with `self` and changing the current module should achieve
1884                 // the same effect.
1885                 segment.ident.name = kw::SelfLower;
1886                 parent_scope.module =
1887                     self.expect_module(parent_scope.module.def_id().krate.as_def_id());
1888             } else if segment.ident.name == kw::Empty {
1889                 segment.ident.name = kw::PathRoot;
1890             }
1891         }
1892
1893         match self.maybe_resolve_path(&segments, Some(ns), &parent_scope) {
1894             PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
1895             PathResult::NonModule(path_res) => path_res.full_res(),
1896             PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
1897                 None
1898             }
1899             PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
1900         }
1901     }
1902
1903     /// For rustdoc.
1904     /// For local modules returns only reexports, for external modules returns all children.
1905     pub fn module_children_or_reexports(&self, def_id: DefId) -> Vec<ModChild> {
1906         if let Some(def_id) = def_id.as_local() {
1907             self.reexport_map.get(&def_id).cloned().unwrap_or_default()
1908         } else {
1909             self.cstore().module_children_untracked(def_id, self.session)
1910         }
1911     }
1912
1913     /// For rustdoc.
1914     pub fn macro_rules_scope(&self, def_id: LocalDefId) -> (MacroRulesScopeRef<'a>, Res) {
1915         let scope = *self.macro_rules_scopes.get(&def_id).expect("not a `macro_rules` item");
1916         match scope.get() {
1917             MacroRulesScope::Binding(mb) => (scope, mb.binding.res()),
1918             _ => unreachable!(),
1919         }
1920     }
1921
1922     /// Retrieves the span of the given `DefId` if `DefId` is in the local crate.
1923     #[inline]
1924     pub fn opt_span(&self, def_id: DefId) -> Option<Span> {
1925         def_id.as_local().map(|def_id| self.source_span[def_id])
1926     }
1927
1928     /// Retrieves the name of the given `DefId`.
1929     #[inline]
1930     pub fn opt_name(&self, def_id: DefId) -> Option<Symbol> {
1931         let def_key = match def_id.as_local() {
1932             Some(def_id) => self.definitions.def_key(def_id),
1933             None => self.cstore().def_key(def_id),
1934         };
1935         def_key.get_opt_name()
1936     }
1937
1938     /// Checks if an expression refers to a function marked with
1939     /// `#[rustc_legacy_const_generics]` and returns the argument index list
1940     /// from the attribute.
1941     pub fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
1942         if let ExprKind::Path(None, path) = &expr.kind {
1943             // Don't perform legacy const generics rewriting if the path already
1944             // has generic arguments.
1945             if path.segments.last().unwrap().args.is_some() {
1946                 return None;
1947             }
1948
1949             let res = self.partial_res_map.get(&expr.id)?.full_res()?;
1950             if let Res::Def(def::DefKind::Fn, def_id) = res {
1951                 // We only support cross-crate argument rewriting. Uses
1952                 // within the same crate should be updated to use the new
1953                 // const generics style.
1954                 if def_id.is_local() {
1955                     return None;
1956                 }
1957
1958                 if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
1959                     return v.clone();
1960                 }
1961
1962                 let attr = self
1963                     .cstore()
1964                     .item_attrs_untracked(def_id, self.session)
1965                     .find(|a| a.has_name(sym::rustc_legacy_const_generics))?;
1966                 let mut ret = Vec::new();
1967                 for meta in attr.meta_item_list()? {
1968                     match meta.literal()?.kind {
1969                         LitKind::Int(a, _) => ret.push(a as usize),
1970                         _ => panic!("invalid arg index"),
1971                     }
1972                 }
1973                 // Cache the lookup to avoid parsing attributes for an item multiple times.
1974                 self.legacy_const_generic_args.insert(def_id, Some(ret.clone()));
1975                 return Some(ret);
1976             }
1977         }
1978         None
1979     }
1980
1981     fn resolve_main(&mut self) {
1982         let module = self.graph_root;
1983         let ident = Ident::with_dummy_span(sym::main);
1984         let parent_scope = &ParentScope::module(module, self);
1985
1986         let Ok(name_binding) = self.maybe_resolve_ident_in_module(
1987             ModuleOrUniformRoot::Module(module),
1988             ident,
1989             ValueNS,
1990             parent_scope,
1991         ) else {
1992             return;
1993         };
1994
1995         let res = name_binding.res();
1996         let is_import = name_binding.is_import();
1997         let span = name_binding.span;
1998         if let Res::Def(DefKind::Fn, _) = res {
1999             self.record_use(ident, name_binding, false);
2000         }
2001         self.main_def = Some(MainDefinition { res, is_import, span });
2002     }
2003
2004     // Items that go to reexport table encoded to metadata and visible through it to other crates.
2005     fn is_reexport(&self, binding: &NameBinding<'a>) -> Option<def::Res<!>> {
2006         if binding.is_import() {
2007             let res = binding.res().expect_non_local();
2008             // Ambiguous imports are treated as errors at this point and are
2009             // not exposed to other crates (see #36837 for more details).
2010             if res != def::Res::Err && !binding.is_ambiguity() {
2011                 return Some(res);
2012             }
2013         }
2014
2015         return None;
2016     }
2017 }
2018
2019 fn names_to_string(names: &[Symbol]) -> String {
2020     let mut result = String::new();
2021     for (i, name) in names.iter().filter(|name| **name != kw::PathRoot).enumerate() {
2022         if i > 0 {
2023             result.push_str("::");
2024         }
2025         if Ident::with_dummy_span(*name).is_raw_guess() {
2026             result.push_str("r#");
2027         }
2028         result.push_str(name.as_str());
2029     }
2030     result
2031 }
2032
2033 fn path_names_to_string(path: &Path) -> String {
2034     names_to_string(&path.segments.iter().map(|seg| seg.ident.name).collect::<Vec<_>>())
2035 }
2036
2037 /// A somewhat inefficient routine to obtain the name of a module.
2038 fn module_to_string(module: Module<'_>) -> Option<String> {
2039     let mut names = Vec::new();
2040
2041     fn collect_mod(names: &mut Vec<Symbol>, module: Module<'_>) {
2042         if let ModuleKind::Def(.., name) = module.kind {
2043             if let Some(parent) = module.parent {
2044                 names.push(name);
2045                 collect_mod(names, parent);
2046             }
2047         } else {
2048             names.push(Symbol::intern("<opaque>"));
2049             collect_mod(names, module.parent.unwrap());
2050         }
2051     }
2052     collect_mod(&mut names, module);
2053
2054     if names.is_empty() {
2055         return None;
2056     }
2057     names.reverse();
2058     Some(names_to_string(&names))
2059 }
2060
2061 #[derive(Copy, Clone, Debug)]
2062 struct Finalize {
2063     /// Node ID for linting.
2064     node_id: NodeId,
2065     /// Span of the whole path or some its characteristic fragment.
2066     /// E.g. span of `b` in `foo::{a, b, c}`, or full span for regular paths.
2067     path_span: Span,
2068     /// Span of the path start, suitable for prepending something to it.
2069     /// E.g. span of `foo` in `foo::{a, b, c}`, or full span for regular paths.
2070     root_span: Span,
2071     /// Whether to report privacy errors or silently return "no resolution" for them,
2072     /// similarly to speculative resolution.
2073     report_private: bool,
2074 }
2075
2076 impl Finalize {
2077     fn new(node_id: NodeId, path_span: Span) -> Finalize {
2078         Finalize::with_root_span(node_id, path_span, path_span)
2079     }
2080
2081     fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2082         Finalize { node_id, path_span, root_span, report_private: true }
2083     }
2084 }