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