rustc_resolve/
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// tidy-alphabetical-start
10#![allow(internal_features)]
11#![allow(rustc::diagnostic_outside_of_impl)]
12#![allow(rustc::untranslatable_diagnostic)]
13#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
14#![doc(rust_logo)]
15#![feature(arbitrary_self_types)]
16#![feature(assert_matches)]
17#![feature(box_patterns)]
18#![feature(decl_macro)]
19#![feature(default_field_values)]
20#![feature(if_let_guard)]
21#![feature(iter_intersperse)]
22#![feature(rustc_attrs)]
23#![feature(rustdoc_internals)]
24#![recursion_limit = "256"]
25// tidy-alphabetical-end
26
27use std::cell::{Cell, Ref, RefCell};
28use std::collections::BTreeSet;
29use std::fmt;
30use std::sync::Arc;
31
32use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion};
33use effective_visibilities::EffectiveVisibilitiesVisitor;
34use errors::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};
35use imports::{Import, ImportData, ImportKind, NameResolution};
36use late::{
37    ForwardGenericParamBanReason, HasGenericParams, PathSource, PatternSource,
38    UnnecessaryQualification,
39};
40use macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef};
41use rustc_arena::{DroplessArena, TypedArena};
42use rustc_ast::node_id::NodeMap;
43use rustc_ast::{
44    self as ast, AngleBracketedArg, CRATE_NODE_ID, Crate, Expr, ExprKind, GenericArg, GenericArgs,
45    LitKind, NodeId, Path, attr,
46};
47use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
48use rustc_data_structures::intern::Interned;
49use rustc_data_structures::steal::Steal;
50use rustc_data_structures::sync::{FreezeReadGuard, FreezeWriteGuard};
51use rustc_data_structures::unord::{UnordMap, UnordSet};
52use rustc_errors::{Applicability, Diag, ErrCode, ErrorGuaranteed};
53use rustc_expand::base::{DeriveResolution, SyntaxExtension, SyntaxExtensionKind};
54use rustc_feature::BUILTIN_ATTRIBUTES;
55use rustc_hir::attrs::StrippedCfgItem;
56use rustc_hir::def::Namespace::{self, *};
57use rustc_hir::def::{
58    self, CtorOf, DefKind, DocLinkResMap, LifetimeRes, MacroKinds, NonMacroAttrKind, PartialRes,
59    PerNS,
60};
61use rustc_hir::def_id::{CRATE_DEF_ID, CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalDefIdMap};
62use rustc_hir::definitions::DisambiguatorState;
63use rustc_hir::{PrimTy, TraitCandidate};
64use rustc_index::bit_set::DenseBitSet;
65use rustc_metadata::creader::CStore;
66use rustc_middle::metadata::ModChild;
67use rustc_middle::middle::privacy::EffectiveVisibilities;
68use rustc_middle::query::Providers;
69use rustc_middle::span_bug;
70use rustc_middle::ty::{
71    self, DelegationFnSig, Feed, MainDefinition, RegisteredTools, ResolverAstLowering,
72    ResolverGlobalCtxt, TyCtxt, TyCtxtFeed, Visibility,
73};
74use rustc_query_system::ich::StableHashingContext;
75use rustc_session::lint::builtin::PRIVATE_MACRO_USE;
76use rustc_session::lint::{BuiltinLintDiag, LintBuffer};
77use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency};
78use rustc_span::{DUMMY_SP, Ident, Macros20NormalizedIdent, Span, Symbol, kw, sym};
79use smallvec::{SmallVec, smallvec};
80use tracing::debug;
81
82type Res = def::Res<NodeId>;
83
84mod build_reduced_graph;
85mod check_unused;
86mod def_collector;
87mod diagnostics;
88mod effective_visibilities;
89mod errors;
90mod ident;
91mod imports;
92mod late;
93mod macros;
94pub mod rustdoc;
95
96pub use macros::registered_tools_ast;
97
98rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
99
100#[derive(Debug)]
101enum Weak {
102    Yes,
103    No,
104}
105
106#[derive(Copy, Clone, PartialEq, Debug)]
107enum Determinacy {
108    Determined,
109    Undetermined,
110}
111
112impl Determinacy {
113    fn determined(determined: bool) -> Determinacy {
114        if determined { Determinacy::Determined } else { Determinacy::Undetermined }
115    }
116}
117
118/// A specific scope in which a name can be looked up.
119#[derive(Clone, Copy, Debug)]
120enum Scope<'ra> {
121    /// Inert attributes registered by derive macros.
122    DeriveHelpers(LocalExpnId),
123    /// Inert attributes registered by derive macros, but used before they are actually declared.
124    /// This scope will exist until the compatibility lint `LEGACY_DERIVE_HELPERS`
125    /// is turned into a hard error.
126    DeriveHelpersCompat,
127    /// Textual `let`-like scopes introduced by `macro_rules!` items.
128    MacroRules(MacroRulesScopeRef<'ra>),
129    /// Names declared in the given module.
130    /// The node ID is for reporting the `PROC_MACRO_DERIVE_RESOLUTION_FALLBACK`
131    /// lint if it should be reported.
132    Module(Module<'ra>, Option<NodeId>),
133    /// Names introduced by `#[macro_use]` attributes on `extern crate` items.
134    MacroUsePrelude,
135    /// Built-in attributes.
136    BuiltinAttrs,
137    /// Extern prelude names introduced by `extern crate` items.
138    ExternPreludeItems,
139    /// Extern prelude names introduced by `--extern` flags.
140    ExternPreludeFlags,
141    /// Tool modules introduced with `#![register_tool]`.
142    ToolPrelude,
143    /// Standard library prelude introduced with an internal `#[prelude_import]` import.
144    StdLibPrelude,
145    /// Built-in types.
146    BuiltinTypes,
147}
148
149/// Names from different contexts may want to visit different subsets of all specific scopes
150/// with different restrictions when looking up the resolution.
151#[derive(Clone, Copy, Debug)]
152enum ScopeSet<'ra> {
153    /// All scopes with the given namespace.
154    All(Namespace),
155    /// A module, then extern prelude (used for mixed 2015-2018 mode in macros).
156    ModuleAndExternPrelude(Namespace, Module<'ra>),
157    /// Just two extern prelude scopes.
158    ExternPrelude,
159    /// All scopes with macro namespace and the given macro kind restriction.
160    Macro(MacroKind),
161    /// All scopes with the given namespace, used for partially performing late resolution.
162    /// The node id enables lints and is used for reporting them.
163    Late(Namespace, Module<'ra>, Option<NodeId>),
164}
165
166/// Everything you need to know about a name's location to resolve it.
167/// Serves as a starting point for the scope visitor.
168/// This struct is currently used only for early resolution (imports and macros),
169/// but not for late resolution yet.
170#[derive(Clone, Copy, Debug)]
171struct ParentScope<'ra> {
172    module: Module<'ra>,
173    expansion: LocalExpnId,
174    macro_rules: MacroRulesScopeRef<'ra>,
175    derives: &'ra [ast::Path],
176}
177
178impl<'ra> ParentScope<'ra> {
179    /// Creates a parent scope with the passed argument used as the module scope component,
180    /// and other scope components set to default empty values.
181    fn module(module: Module<'ra>, arenas: &'ra ResolverArenas<'ra>) -> ParentScope<'ra> {
182        ParentScope {
183            module,
184            expansion: LocalExpnId::ROOT,
185            macro_rules: arenas.alloc_macro_rules_scope(MacroRulesScope::Empty),
186            derives: &[],
187        }
188    }
189}
190
191#[derive(Copy, Debug, Clone)]
192struct InvocationParent {
193    parent_def: LocalDefId,
194    impl_trait_context: ImplTraitContext,
195    in_attr: bool,
196}
197
198impl InvocationParent {
199    const ROOT: Self = Self {
200        parent_def: CRATE_DEF_ID,
201        impl_trait_context: ImplTraitContext::Existential,
202        in_attr: false,
203    };
204}
205
206#[derive(Copy, Debug, Clone)]
207enum ImplTraitContext {
208    Existential,
209    Universal,
210    InBinding,
211}
212
213/// Used for tracking import use types which will be used for redundant import checking.
214///
215/// ### Used::Scope Example
216///
217/// ```rust,compile_fail
218/// #![deny(redundant_imports)]
219/// use std::mem::drop;
220/// fn main() {
221///     let s = Box::new(32);
222///     drop(s);
223/// }
224/// ```
225///
226/// Used::Other is for other situations like module-relative uses.
227#[derive(Clone, Copy, PartialEq, PartialOrd, Debug)]
228enum Used {
229    Scope,
230    Other,
231}
232
233#[derive(Debug)]
234struct BindingError {
235    name: Ident,
236    origin: BTreeSet<Span>,
237    target: BTreeSet<Span>,
238    could_be_path: bool,
239}
240
241#[derive(Debug)]
242enum ResolutionError<'ra> {
243    /// Error E0401: can't use type or const parameters from outer item.
244    GenericParamsFromOuterItem(Res, HasGenericParams, DefKind),
245    /// Error E0403: the name is already used for a type or const parameter in this generic
246    /// parameter list.
247    NameAlreadyUsedInParameterList(Ident, Span),
248    /// Error E0407: method is not a member of trait.
249    MethodNotMemberOfTrait(Ident, String, Option<Symbol>),
250    /// Error E0437: type is not a member of trait.
251    TypeNotMemberOfTrait(Ident, String, Option<Symbol>),
252    /// Error E0438: const is not a member of trait.
253    ConstNotMemberOfTrait(Ident, String, Option<Symbol>),
254    /// Error E0408: variable `{}` is not bound in all patterns.
255    VariableNotBoundInPattern(BindingError, ParentScope<'ra>),
256    /// Error E0409: variable `{}` is bound in inconsistent ways within the same match arm.
257    VariableBoundWithDifferentMode(Ident, Span),
258    /// Error E0415: identifier is bound more than once in this parameter list.
259    IdentifierBoundMoreThanOnceInParameterList(Ident),
260    /// Error E0416: identifier is bound more than once in the same pattern.
261    IdentifierBoundMoreThanOnceInSamePattern(Ident),
262    /// Error E0426: use of undeclared label.
263    UndeclaredLabel { name: Symbol, suggestion: Option<LabelSuggestion> },
264    /// Error E0429: `self` imports are only allowed within a `{ }` list.
265    SelfImportsOnlyAllowedWithin { root: bool, span_with_rename: Span },
266    /// Error E0430: `self` import can only appear once in the list.
267    SelfImportCanOnlyAppearOnceInTheList,
268    /// Error E0431: `self` import can only appear in an import list with a non-empty prefix.
269    SelfImportOnlyInImportListWithNonEmptyPrefix,
270    /// Error E0433: failed to resolve.
271    FailedToResolve {
272        segment: Option<Symbol>,
273        label: String,
274        suggestion: Option<Suggestion>,
275        module: Option<ModuleOrUniformRoot<'ra>>,
276    },
277    /// Error E0434: can't capture dynamic environment in a fn item.
278    CannotCaptureDynamicEnvironmentInFnItem,
279    /// Error E0435: attempt to use a non-constant value in a constant.
280    AttemptToUseNonConstantValueInConstant {
281        ident: Ident,
282        suggestion: &'static str,
283        current: &'static str,
284        type_span: Option<Span>,
285    },
286    /// Error E0530: `X` bindings cannot shadow `Y`s.
287    BindingShadowsSomethingUnacceptable {
288        shadowing_binding: PatternSource,
289        name: Symbol,
290        participle: &'static str,
291        article: &'static str,
292        shadowed_binding: Res,
293        shadowed_binding_span: Span,
294    },
295    /// Error E0128: generic parameters with a default cannot use forward-declared identifiers.
296    ForwardDeclaredGenericParam(Symbol, ForwardGenericParamBanReason),
297    // FIXME(generic_const_parameter_types): This should give custom output specifying it's only
298    // problematic to use *forward declared* parameters when the feature is enabled.
299    /// ERROR E0770: the type of const parameters must not depend on other generic parameters.
300    ParamInTyOfConstParam { name: Symbol },
301    /// generic parameters must not be used inside const evaluations.
302    ///
303    /// This error is only emitted when using `min_const_generics`.
304    ParamInNonTrivialAnonConst { name: Symbol, param_kind: ParamKindInNonTrivialAnonConst },
305    /// generic parameters must not be used inside enum discriminants.
306    ///
307    /// This error is emitted even with `generic_const_exprs`.
308    ParamInEnumDiscriminant { name: Symbol, param_kind: ParamKindInEnumDiscriminant },
309    /// Error E0735: generic parameters with a default cannot use `Self`
310    ForwardDeclaredSelf(ForwardGenericParamBanReason),
311    /// Error E0767: use of unreachable label
312    UnreachableLabel { name: Symbol, definition_span: Span, suggestion: Option<LabelSuggestion> },
313    /// Error E0323, E0324, E0325: mismatch between trait item and impl item.
314    TraitImplMismatch {
315        name: Ident,
316        kind: &'static str,
317        trait_path: String,
318        trait_item_span: Span,
319        code: ErrCode,
320    },
321    /// Error E0201: multiple impl items for the same trait item.
322    TraitImplDuplicate { name: Ident, trait_item_span: Span, old_span: Span },
323    /// Inline asm `sym` operand must refer to a `fn` or `static`.
324    InvalidAsmSym,
325    /// `self` used instead of `Self` in a generic parameter
326    LowercaseSelf,
327    /// A never pattern has a binding.
328    BindingInNeverPattern,
329}
330
331enum VisResolutionError<'a> {
332    Relative2018(Span, &'a ast::Path),
333    AncestorOnly(Span),
334    FailedToResolve(Span, String, Option<Suggestion>),
335    ExpectedFound(Span, String, Res),
336    Indeterminate(Span),
337    ModuleOnly(Span),
338}
339
340/// A minimal representation of a path segment. We use this in resolve because we synthesize 'path
341/// segments' which don't have the rest of an AST or HIR `PathSegment`.
342#[derive(Clone, Copy, Debug)]
343struct Segment {
344    ident: Ident,
345    id: Option<NodeId>,
346    /// Signals whether this `PathSegment` has generic arguments. Used to avoid providing
347    /// nonsensical suggestions.
348    has_generic_args: bool,
349    /// Signals whether this `PathSegment` has lifetime arguments.
350    has_lifetime_args: bool,
351    args_span: Span,
352}
353
354impl Segment {
355    fn from_path(path: &Path) -> Vec<Segment> {
356        path.segments.iter().map(|s| s.into()).collect()
357    }
358
359    fn from_ident(ident: Ident) -> Segment {
360        Segment {
361            ident,
362            id: None,
363            has_generic_args: false,
364            has_lifetime_args: false,
365            args_span: DUMMY_SP,
366        }
367    }
368
369    fn from_ident_and_id(ident: Ident, id: NodeId) -> Segment {
370        Segment {
371            ident,
372            id: Some(id),
373            has_generic_args: false,
374            has_lifetime_args: false,
375            args_span: DUMMY_SP,
376        }
377    }
378
379    fn names_to_string(segments: &[Segment]) -> String {
380        names_to_string(segments.iter().map(|seg| seg.ident.name))
381    }
382}
383
384impl<'a> From<&'a ast::PathSegment> for Segment {
385    fn from(seg: &'a ast::PathSegment) -> Segment {
386        let has_generic_args = seg.args.is_some();
387        let (args_span, has_lifetime_args) = if let Some(args) = seg.args.as_deref() {
388            match args {
389                GenericArgs::AngleBracketed(args) => {
390                    let found_lifetimes = args
391                        .args
392                        .iter()
393                        .any(|arg| matches!(arg, AngleBracketedArg::Arg(GenericArg::Lifetime(_))));
394                    (args.span, found_lifetimes)
395                }
396                GenericArgs::Parenthesized(args) => (args.span, true),
397                GenericArgs::ParenthesizedElided(span) => (*span, true),
398            }
399        } else {
400            (DUMMY_SP, false)
401        };
402        Segment {
403            ident: seg.ident,
404            id: Some(seg.id),
405            has_generic_args,
406            has_lifetime_args,
407            args_span,
408        }
409    }
410}
411
412/// An intermediate resolution result.
413///
414/// This refers to the thing referred by a name. The difference between `Res` and `Item` is that
415/// items are visible in their whole block, while `Res`es only from the place they are defined
416/// forward.
417#[derive(Debug, Copy, Clone)]
418enum LexicalScopeBinding<'ra> {
419    Item(NameBinding<'ra>),
420    Res(Res),
421}
422
423impl<'ra> LexicalScopeBinding<'ra> {
424    fn res(self) -> Res {
425        match self {
426            LexicalScopeBinding::Item(binding) => binding.res(),
427            LexicalScopeBinding::Res(res) => res,
428        }
429    }
430}
431
432#[derive(Copy, Clone, PartialEq, Debug)]
433enum ModuleOrUniformRoot<'ra> {
434    /// Regular module.
435    Module(Module<'ra>),
436
437    /// Virtual module that denotes resolution in a module with fallback to extern prelude.
438    /// Used for paths starting with `::` coming from 2015 edition macros
439    /// used in 2018+ edition crates.
440    ModuleAndExternPrelude(Module<'ra>),
441
442    /// Virtual module that denotes resolution in extern prelude.
443    /// Used for paths starting with `::` on 2018 edition.
444    ExternPrelude,
445
446    /// Virtual module that denotes resolution in current scope.
447    /// Used only for resolving single-segment imports. The reason it exists is that import paths
448    /// are always split into two parts, the first of which should be some kind of module.
449    CurrentScope,
450}
451
452#[derive(Debug)]
453enum PathResult<'ra> {
454    Module(ModuleOrUniformRoot<'ra>),
455    NonModule(PartialRes),
456    Indeterminate,
457    Failed {
458        span: Span,
459        label: String,
460        suggestion: Option<Suggestion>,
461        is_error_from_last_segment: bool,
462        /// The final module being resolved, for instance:
463        ///
464        /// ```compile_fail
465        /// mod a {
466        ///     mod b {
467        ///         mod c {}
468        ///     }
469        /// }
470        ///
471        /// use a::not_exist::c;
472        /// ```
473        ///
474        /// In this case, `module` will point to `a`.
475        module: Option<ModuleOrUniformRoot<'ra>>,
476        /// The segment name of target
477        segment_name: Symbol,
478        error_implied_by_parse_error: bool,
479    },
480}
481
482impl<'ra> PathResult<'ra> {
483    fn failed(
484        ident: Ident,
485        is_error_from_last_segment: bool,
486        finalize: bool,
487        error_implied_by_parse_error: bool,
488        module: Option<ModuleOrUniformRoot<'ra>>,
489        label_and_suggestion: impl FnOnce() -> (String, Option<Suggestion>),
490    ) -> PathResult<'ra> {
491        let (label, suggestion) =
492            if finalize { label_and_suggestion() } else { (String::new(), None) };
493        PathResult::Failed {
494            span: ident.span,
495            segment_name: ident.name,
496            label,
497            suggestion,
498            is_error_from_last_segment,
499            module,
500            error_implied_by_parse_error,
501        }
502    }
503}
504
505#[derive(Debug)]
506enum ModuleKind {
507    /// An anonymous module; e.g., just a block.
508    ///
509    /// ```
510    /// fn main() {
511    ///     fn f() {} // (1)
512    ///     { // This is an anonymous module
513    ///         f(); // This resolves to (2) as we are inside the block.
514    ///         fn f() {} // (2)
515    ///     }
516    ///     f(); // Resolves to (1)
517    /// }
518    /// ```
519    Block,
520    /// Any module with a name.
521    ///
522    /// This could be:
523    ///
524    /// * A normal module – either `mod from_file;` or `mod from_block { }` –
525    ///   or the crate root (which is conceptually a top-level module).
526    ///   The crate root will have `None` for the symbol.
527    /// * A trait or an enum (it implicitly contains associated types, methods and variant
528    ///   constructors).
529    Def(DefKind, DefId, Option<Symbol>),
530}
531
532impl ModuleKind {
533    /// Get name of the module.
534    fn name(&self) -> Option<Symbol> {
535        match *self {
536            ModuleKind::Block => None,
537            ModuleKind::Def(.., name) => name,
538        }
539    }
540}
541
542/// A key that identifies a binding in a given `Module`.
543///
544/// Multiple bindings in the same module can have the same key (in a valid
545/// program) if all but one of them come from glob imports.
546#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
547struct BindingKey {
548    /// The identifier for the binding, always the `normalize_to_macros_2_0` version of the
549    /// identifier.
550    ident: Macros20NormalizedIdent,
551    ns: Namespace,
552    /// When we add an underscore binding (with ident `_`) to some module, this field has
553    /// a non-zero value that uniquely identifies this binding in that module.
554    /// For non-underscore bindings this field is zero.
555    /// When a key is constructed for name lookup (as opposed to name definition), this field is
556    /// also zero, even for underscore names, so for underscores the lookup will never succeed.
557    disambiguator: u32,
558}
559
560impl BindingKey {
561    fn new(ident: Ident, ns: Namespace) -> Self {
562        BindingKey { ident: Macros20NormalizedIdent::new(ident), ns, disambiguator: 0 }
563    }
564
565    fn new_disambiguated(
566        ident: Ident,
567        ns: Namespace,
568        disambiguator: impl FnOnce() -> u32,
569    ) -> BindingKey {
570        let disambiguator = if ident.name == kw::Underscore { disambiguator() } else { 0 };
571        BindingKey { ident: Macros20NormalizedIdent::new(ident), ns, disambiguator }
572    }
573}
574
575type Resolutions<'ra> = RefCell<FxIndexMap<BindingKey, &'ra RefCell<NameResolution<'ra>>>>;
576
577/// One node in the tree of modules.
578///
579/// Note that a "module" in resolve is broader than a `mod` that you declare in Rust code. It may be one of these:
580///
581/// * `mod`
582/// * crate root (aka, top-level anonymous module)
583/// * `enum`
584/// * `trait`
585/// * curly-braced block with statements
586///
587/// You can use [`ModuleData::kind`] to determine the kind of module this is.
588struct ModuleData<'ra> {
589    /// The direct parent module (it may not be a `mod`, however).
590    parent: Option<Module<'ra>>,
591    /// What kind of module this is, because this may not be a `mod`.
592    kind: ModuleKind,
593
594    /// Mapping between names and their (possibly in-progress) resolutions in this module.
595    /// Resolutions in modules from other crates are not populated until accessed.
596    lazy_resolutions: Resolutions<'ra>,
597    /// True if this is a module from other crate that needs to be populated on access.
598    populate_on_access: Cell<bool>,
599    /// Used to disambiguate underscore items (`const _: T = ...`) in the module.
600    underscore_disambiguator: Cell<u32>,
601
602    /// Macro invocations that can expand into items in this module.
603    unexpanded_invocations: RefCell<FxHashSet<LocalExpnId>>,
604
605    /// Whether `#[no_implicit_prelude]` is active.
606    no_implicit_prelude: bool,
607
608    glob_importers: RefCell<Vec<Import<'ra>>>,
609    globs: RefCell<Vec<Import<'ra>>>,
610
611    /// Used to memoize the traits in this module for faster searches through all traits in scope.
612    traits:
613        RefCell<Option<Box<[(Macros20NormalizedIdent, NameBinding<'ra>, Option<Module<'ra>>)]>>>,
614
615    /// Span of the module itself. Used for error reporting.
616    span: Span,
617
618    expansion: ExpnId,
619
620    /// Binding for implicitly declared names that come with a module,
621    /// like `self` (not yet used), or `crate`/`$crate` (for root modules).
622    self_binding: Option<NameBinding<'ra>>,
623}
624
625/// All modules are unique and allocated on a same arena,
626/// so we can use referential equality to compare them.
627#[derive(Clone, Copy, PartialEq, Eq, Hash)]
628#[rustc_pass_by_value]
629struct Module<'ra>(Interned<'ra, ModuleData<'ra>>);
630
631// Allows us to use Interned without actually enforcing (via Hash/PartialEq/...) uniqueness of the
632// contained data.
633// FIXME: We may wish to actually have at least debug-level assertions that Interned's guarantees
634// are upheld.
635impl std::hash::Hash for ModuleData<'_> {
636    fn hash<H>(&self, _: &mut H)
637    where
638        H: std::hash::Hasher,
639    {
640        unreachable!()
641    }
642}
643
644impl<'ra> ModuleData<'ra> {
645    fn new(
646        parent: Option<Module<'ra>>,
647        kind: ModuleKind,
648        expansion: ExpnId,
649        span: Span,
650        no_implicit_prelude: bool,
651        self_binding: Option<NameBinding<'ra>>,
652    ) -> Self {
653        let is_foreign = match kind {
654            ModuleKind::Def(_, def_id, _) => !def_id.is_local(),
655            ModuleKind::Block => false,
656        };
657        ModuleData {
658            parent,
659            kind,
660            lazy_resolutions: Default::default(),
661            populate_on_access: Cell::new(is_foreign),
662            underscore_disambiguator: Cell::new(0),
663            unexpanded_invocations: Default::default(),
664            no_implicit_prelude,
665            glob_importers: RefCell::new(Vec::new()),
666            globs: RefCell::new(Vec::new()),
667            traits: RefCell::new(None),
668            span,
669            expansion,
670            self_binding,
671        }
672    }
673}
674
675impl<'ra> Module<'ra> {
676    fn for_each_child<'tcx, R: AsRef<Resolver<'ra, 'tcx>>>(
677        self,
678        resolver: &R,
679        mut f: impl FnMut(&R, Macros20NormalizedIdent, Namespace, NameBinding<'ra>),
680    ) {
681        for (key, name_resolution) in resolver.as_ref().resolutions(self).borrow().iter() {
682            if let Some(binding) = name_resolution.borrow().best_binding() {
683                f(resolver, key.ident, key.ns, binding);
684            }
685        }
686    }
687
688    fn for_each_child_mut<'tcx, R: AsMut<Resolver<'ra, 'tcx>>>(
689        self,
690        resolver: &mut R,
691        mut f: impl FnMut(&mut R, Macros20NormalizedIdent, Namespace, NameBinding<'ra>),
692    ) {
693        for (key, name_resolution) in resolver.as_mut().resolutions(self).borrow().iter() {
694            if let Some(binding) = name_resolution.borrow().best_binding() {
695                f(resolver, key.ident, key.ns, binding);
696            }
697        }
698    }
699
700    /// This modifies `self` in place. The traits will be stored in `self.traits`.
701    fn ensure_traits<'tcx>(self, resolver: &impl AsRef<Resolver<'ra, 'tcx>>) {
702        let mut traits = self.traits.borrow_mut();
703        if traits.is_none() {
704            let mut collected_traits = Vec::new();
705            self.for_each_child(resolver, |r, name, ns, binding| {
706                if ns != TypeNS {
707                    return;
708                }
709                if let Res::Def(DefKind::Trait | DefKind::TraitAlias, def_id) = binding.res() {
710                    collected_traits.push((name, binding, r.as_ref().get_module(def_id)))
711                }
712            });
713            *traits = Some(collected_traits.into_boxed_slice());
714        }
715    }
716
717    fn res(self) -> Option<Res> {
718        match self.kind {
719            ModuleKind::Def(kind, def_id, _) => Some(Res::Def(kind, def_id)),
720            _ => None,
721        }
722    }
723
724    fn def_id(self) -> DefId {
725        self.opt_def_id().expect("`ModuleData::def_id` is called on a block module")
726    }
727
728    fn opt_def_id(self) -> Option<DefId> {
729        match self.kind {
730            ModuleKind::Def(_, def_id, _) => Some(def_id),
731            _ => None,
732        }
733    }
734
735    // `self` resolves to the first module ancestor that `is_normal`.
736    fn is_normal(self) -> bool {
737        matches!(self.kind, ModuleKind::Def(DefKind::Mod, _, _))
738    }
739
740    fn is_trait(self) -> bool {
741        matches!(self.kind, ModuleKind::Def(DefKind::Trait, _, _))
742    }
743
744    fn nearest_item_scope(self) -> Module<'ra> {
745        match self.kind {
746            ModuleKind::Def(DefKind::Enum | DefKind::Trait, ..) => {
747                self.parent.expect("enum or trait module without a parent")
748            }
749            _ => self,
750        }
751    }
752
753    /// The [`DefId`] of the nearest `mod` item ancestor (which may be this module).
754    /// This may be the crate root.
755    fn nearest_parent_mod(self) -> DefId {
756        match self.kind {
757            ModuleKind::Def(DefKind::Mod, def_id, _) => def_id,
758            _ => self.parent.expect("non-root module without parent").nearest_parent_mod(),
759        }
760    }
761
762    fn is_ancestor_of(self, mut other: Self) -> bool {
763        while self != other {
764            if let Some(parent) = other.parent {
765                other = parent;
766            } else {
767                return false;
768            }
769        }
770        true
771    }
772}
773
774impl<'ra> std::ops::Deref for Module<'ra> {
775    type Target = ModuleData<'ra>;
776
777    fn deref(&self) -> &Self::Target {
778        &self.0
779    }
780}
781
782impl<'ra> fmt::Debug for Module<'ra> {
783    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
784        match self.kind {
785            ModuleKind::Block => write!(f, "block"),
786            ModuleKind::Def(..) => write!(f, "{:?}", self.res()),
787        }
788    }
789}
790
791/// Records a possibly-private value, type, or module definition.
792#[derive(Clone, Copy, Debug)]
793struct NameBindingData<'ra> {
794    kind: NameBindingKind<'ra>,
795    ambiguity: Option<(NameBinding<'ra>, AmbiguityKind)>,
796    /// Produce a warning instead of an error when reporting ambiguities inside this binding.
797    /// May apply to indirect ambiguities under imports, so `ambiguity.is_some()` is not required.
798    warn_ambiguity: bool,
799    expansion: LocalExpnId,
800    span: Span,
801    vis: Visibility<DefId>,
802}
803
804/// All name bindings are unique and allocated on a same arena,
805/// so we can use referential equality to compare them.
806type NameBinding<'ra> = Interned<'ra, NameBindingData<'ra>>;
807
808// Allows us to use Interned without actually enforcing (via Hash/PartialEq/...) uniqueness of the
809// contained data.
810// FIXME: We may wish to actually have at least debug-level assertions that Interned's guarantees
811// are upheld.
812impl std::hash::Hash for NameBindingData<'_> {
813    fn hash<H>(&self, _: &mut H)
814    where
815        H: std::hash::Hasher,
816    {
817        unreachable!()
818    }
819}
820
821#[derive(Clone, Copy, Debug)]
822enum NameBindingKind<'ra> {
823    Res(Res),
824    Import { binding: NameBinding<'ra>, import: Import<'ra> },
825}
826
827impl<'ra> NameBindingKind<'ra> {
828    /// Is this a name binding of an import?
829    fn is_import(&self) -> bool {
830        matches!(*self, NameBindingKind::Import { .. })
831    }
832}
833
834#[derive(Debug)]
835struct PrivacyError<'ra> {
836    ident: Ident,
837    binding: NameBinding<'ra>,
838    dedup_span: Span,
839    outermost_res: Option<(Res, Ident)>,
840    parent_scope: ParentScope<'ra>,
841    /// Is the format `use a::{b,c}`?
842    single_nested: bool,
843    source: Option<ast::Expr>,
844}
845
846#[derive(Debug)]
847struct UseError<'a> {
848    err: Diag<'a>,
849    /// Candidates which user could `use` to access the missing type.
850    candidates: Vec<ImportSuggestion>,
851    /// The `DefId` of the module to place the use-statements in.
852    def_id: DefId,
853    /// Whether the diagnostic should say "instead" (as in `consider importing ... instead`).
854    instead: bool,
855    /// Extra free-form suggestion.
856    suggestion: Option<(Span, &'static str, String, Applicability)>,
857    /// Path `Segment`s at the place of use that failed. Used for accurate suggestion after telling
858    /// the user to import the item directly.
859    path: Vec<Segment>,
860    /// Whether the expected source is a call
861    is_call: bool,
862}
863
864#[derive(Clone, Copy, PartialEq, Debug)]
865enum AmbiguityKind {
866    BuiltinAttr,
867    DeriveHelper,
868    MacroRulesVsModularized,
869    GlobVsOuter,
870    GlobVsGlob,
871    GlobVsExpanded,
872    MoreExpandedVsOuter,
873}
874
875impl AmbiguityKind {
876    fn descr(self) -> &'static str {
877        match self {
878            AmbiguityKind::BuiltinAttr => "a name conflict with a builtin attribute",
879            AmbiguityKind::DeriveHelper => "a name conflict with a derive helper attribute",
880            AmbiguityKind::MacroRulesVsModularized => {
881                "a conflict between a `macro_rules` name and a non-`macro_rules` name from another module"
882            }
883            AmbiguityKind::GlobVsOuter => {
884                "a conflict between a name from a glob import and an outer scope during import or macro resolution"
885            }
886            AmbiguityKind::GlobVsGlob => "multiple glob imports of a name in the same module",
887            AmbiguityKind::GlobVsExpanded => {
888                "a conflict between a name from a glob import and a macro-expanded name in the same module during import or macro resolution"
889            }
890            AmbiguityKind::MoreExpandedVsOuter => {
891                "a conflict between a macro-expanded name and a less macro-expanded name from outer scope during import or macro resolution"
892            }
893        }
894    }
895}
896
897/// Miscellaneous bits of metadata for better ambiguity error reporting.
898#[derive(Clone, Copy, PartialEq)]
899enum AmbiguityErrorMisc {
900    SuggestCrate,
901    SuggestSelf,
902    FromPrelude,
903    None,
904}
905
906struct AmbiguityError<'ra> {
907    kind: AmbiguityKind,
908    ident: Ident,
909    b1: NameBinding<'ra>,
910    b2: NameBinding<'ra>,
911    misc1: AmbiguityErrorMisc,
912    misc2: AmbiguityErrorMisc,
913    warning: bool,
914}
915
916impl<'ra> NameBindingData<'ra> {
917    fn res(&self) -> Res {
918        match self.kind {
919            NameBindingKind::Res(res) => res,
920            NameBindingKind::Import { binding, .. } => binding.res(),
921        }
922    }
923
924    fn import_source(&self) -> NameBinding<'ra> {
925        match self.kind {
926            NameBindingKind::Import { binding, .. } => binding,
927            _ => unreachable!(),
928        }
929    }
930
931    fn is_ambiguity_recursive(&self) -> bool {
932        self.ambiguity.is_some()
933            || match self.kind {
934                NameBindingKind::Import { binding, .. } => binding.is_ambiguity_recursive(),
935                _ => false,
936            }
937    }
938
939    fn warn_ambiguity_recursive(&self) -> bool {
940        self.warn_ambiguity
941            || match self.kind {
942                NameBindingKind::Import { binding, .. } => binding.warn_ambiguity_recursive(),
943                _ => false,
944            }
945    }
946
947    fn is_possibly_imported_variant(&self) -> bool {
948        match self.kind {
949            NameBindingKind::Import { binding, .. } => binding.is_possibly_imported_variant(),
950            NameBindingKind::Res(Res::Def(
951                DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..),
952                _,
953            )) => true,
954            NameBindingKind::Res(..) => false,
955        }
956    }
957
958    fn is_extern_crate(&self) -> bool {
959        match self.kind {
960            NameBindingKind::Import { import, .. } => {
961                matches!(import.kind, ImportKind::ExternCrate { .. })
962            }
963            NameBindingKind::Res(Res::Def(_, def_id)) => def_id.is_crate_root(),
964            _ => false,
965        }
966    }
967
968    fn is_import(&self) -> bool {
969        matches!(self.kind, NameBindingKind::Import { .. })
970    }
971
972    /// The binding introduced by `#[macro_export] macro_rules` is a public import, but it might
973    /// not be perceived as such by users, so treat it as a non-import in some diagnostics.
974    fn is_import_user_facing(&self) -> bool {
975        matches!(self.kind, NameBindingKind::Import { import, .. }
976            if !matches!(import.kind, ImportKind::MacroExport))
977    }
978
979    fn is_glob_import(&self) -> bool {
980        match self.kind {
981            NameBindingKind::Import { import, .. } => import.is_glob(),
982            _ => false,
983        }
984    }
985
986    fn is_assoc_item(&self) -> bool {
987        matches!(self.res(), Res::Def(DefKind::AssocConst | DefKind::AssocFn | DefKind::AssocTy, _))
988    }
989
990    fn macro_kinds(&self) -> Option<MacroKinds> {
991        self.res().macro_kinds()
992    }
993
994    // Suppose that we resolved macro invocation with `invoc_parent_expansion` to binding `binding`
995    // at some expansion round `max(invoc, binding)` when they both emerged from macros.
996    // Then this function returns `true` if `self` may emerge from a macro *after* that
997    // in some later round and screw up our previously found resolution.
998    // See more detailed explanation in
999    // https://github.com/rust-lang/rust/pull/53778#issuecomment-419224049
1000    fn may_appear_after(
1001        &self,
1002        invoc_parent_expansion: LocalExpnId,
1003        binding: NameBinding<'_>,
1004    ) -> bool {
1005        // self > max(invoc, binding) => !(self <= invoc || self <= binding)
1006        // Expansions are partially ordered, so "may appear after" is an inversion of
1007        // "certainly appears before or simultaneously" and includes unordered cases.
1008        let self_parent_expansion = self.expansion;
1009        let other_parent_expansion = binding.expansion;
1010        let certainly_before_other_or_simultaneously =
1011            other_parent_expansion.is_descendant_of(self_parent_expansion);
1012        let certainly_before_invoc_or_simultaneously =
1013            invoc_parent_expansion.is_descendant_of(self_parent_expansion);
1014        !(certainly_before_other_or_simultaneously || certainly_before_invoc_or_simultaneously)
1015    }
1016
1017    // Its purpose is to postpone the determination of a single binding because
1018    // we can't predict whether it will be overwritten by recently expanded macros.
1019    // FIXME: How can we integrate it with the `update_resolution`?
1020    fn determined(&self) -> bool {
1021        match &self.kind {
1022            NameBindingKind::Import { binding, import, .. } if import.is_glob() => {
1023                import.parent_scope.module.unexpanded_invocations.borrow().is_empty()
1024                    && binding.determined()
1025            }
1026            _ => true,
1027        }
1028    }
1029}
1030
1031#[derive(Default, Clone)]
1032struct ExternPreludeEntry<'ra> {
1033    /// Binding from an `extern crate` item.
1034    item_binding: Option<NameBinding<'ra>>,
1035    /// Binding from an `--extern` flag, lazily populated on first use.
1036    flag_binding: Cell<Option<NameBinding<'ra>>>,
1037    /// There was no `--extern` flag introducing this name,
1038    /// `flag_binding` doesn't need to be populated.
1039    only_item: bool,
1040    /// `item_binding` is non-redundant, happens either when `only_item` is true,
1041    /// or when `extern crate` introducing `item_binding` used renaming.
1042    introduced_by_item: bool,
1043}
1044
1045struct DeriveData {
1046    resolutions: Vec<DeriveResolution>,
1047    helper_attrs: Vec<(usize, Ident)>,
1048    has_derive_copy: bool,
1049}
1050
1051struct MacroData {
1052    ext: Arc<SyntaxExtension>,
1053    nrules: usize,
1054    macro_rules: bool,
1055}
1056
1057impl MacroData {
1058    fn new(ext: Arc<SyntaxExtension>) -> MacroData {
1059        MacroData { ext, nrules: 0, macro_rules: false }
1060    }
1061}
1062
1063pub struct ResolverOutputs {
1064    pub global_ctxt: ResolverGlobalCtxt,
1065    pub ast_lowering: ResolverAstLowering,
1066}
1067
1068/// The main resolver class.
1069///
1070/// This is the visitor that walks the whole crate.
1071pub struct Resolver<'ra, 'tcx> {
1072    tcx: TyCtxt<'tcx>,
1073
1074    /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
1075    expn_that_defined: UnordMap<LocalDefId, ExpnId>,
1076
1077    graph_root: Module<'ra>,
1078
1079    /// Assert that we are in speculative resolution mode.
1080    assert_speculative: bool,
1081
1082    prelude: Option<Module<'ra>> = None,
1083    extern_prelude: FxIndexMap<Macros20NormalizedIdent, ExternPreludeEntry<'ra>>,
1084
1085    /// N.B., this is used only for better diagnostics, not name resolution itself.
1086    field_names: LocalDefIdMap<Vec<Ident>>,
1087    field_defaults: LocalDefIdMap<Vec<Symbol>>,
1088
1089    /// Span of the privacy modifier in fields of an item `DefId` accessible with dot syntax.
1090    /// Used for hints during error reporting.
1091    field_visibility_spans: FxHashMap<DefId, Vec<Span>>,
1092
1093    /// All imports known to succeed or fail.
1094    determined_imports: Vec<Import<'ra>> = Vec::new(),
1095
1096    /// All non-determined imports.
1097    indeterminate_imports: Vec<Import<'ra>> = Vec::new(),
1098
1099    // Spans for local variables found during pattern resolution.
1100    // Used for suggestions during error reporting.
1101    pat_span_map: NodeMap<Span>,
1102
1103    /// Resolutions for nodes that have a single resolution.
1104    partial_res_map: NodeMap<PartialRes>,
1105    /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
1106    import_res_map: NodeMap<PerNS<Option<Res>>>,
1107    /// An import will be inserted into this map if it has been used.
1108    import_use_map: FxHashMap<Import<'ra>, Used>,
1109    /// Resolutions for labels (node IDs of their corresponding blocks or loops).
1110    label_res_map: NodeMap<NodeId>,
1111    /// Resolutions for lifetimes.
1112    lifetimes_res_map: NodeMap<LifetimeRes>,
1113    /// Lifetime parameters that lowering will have to introduce.
1114    extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>>,
1115
1116    /// `CrateNum` resolutions of `extern crate` items.
1117    extern_crate_map: UnordMap<LocalDefId, CrateNum>,
1118    module_children: LocalDefIdMap<Vec<ModChild>>,
1119    trait_map: NodeMap<Vec<TraitCandidate>>,
1120
1121    /// A map from nodes to anonymous modules.
1122    /// Anonymous modules are pseudo-modules that are implicitly created around items
1123    /// contained within blocks.
1124    ///
1125    /// For example, if we have this:
1126    ///
1127    ///  fn f() {
1128    ///      fn g() {
1129    ///          ...
1130    ///      }
1131    ///  }
1132    ///
1133    /// There will be an anonymous module created around `g` with the ID of the
1134    /// entry block for `f`.
1135    block_map: NodeMap<Module<'ra>>,
1136    /// A fake module that contains no definition and no prelude. Used so that
1137    /// some AST passes can generate identifiers that only resolve to local or
1138    /// lang items.
1139    empty_module: Module<'ra>,
1140    /// Eagerly populated map of all local non-block modules.
1141    local_module_map: FxIndexMap<LocalDefId, Module<'ra>>,
1142    /// Lazily populated cache of modules loaded from external crates.
1143    extern_module_map: RefCell<FxIndexMap<DefId, Module<'ra>>>,
1144    binding_parent_modules: FxHashMap<NameBinding<'ra>, Module<'ra>>,
1145
1146    /// Maps glob imports to the names of items actually imported.
1147    glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
1148    glob_error: Option<ErrorGuaranteed> = None,
1149    visibilities_for_hashing: Vec<(LocalDefId, Visibility)> = Vec::new(),
1150    used_imports: FxHashSet<NodeId>,
1151    maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
1152
1153    /// Privacy errors are delayed until the end in order to deduplicate them.
1154    privacy_errors: Vec<PrivacyError<'ra>> = Vec::new(),
1155    /// Ambiguity errors are delayed for deduplication.
1156    ambiguity_errors: Vec<AmbiguityError<'ra>> = Vec::new(),
1157    /// `use` injections are delayed for better placement and deduplication.
1158    use_injections: Vec<UseError<'tcx>> = Vec::new(),
1159    /// Crate-local macro expanded `macro_export` referred to by a module-relative path.
1160    macro_expanded_macro_export_errors: BTreeSet<(Span, Span)> = BTreeSet::new(),
1161
1162    arenas: &'ra ResolverArenas<'ra>,
1163    dummy_binding: NameBinding<'ra>,
1164    builtin_types_bindings: FxHashMap<Symbol, NameBinding<'ra>>,
1165    builtin_attrs_bindings: FxHashMap<Symbol, NameBinding<'ra>>,
1166    registered_tool_bindings: FxHashMap<Ident, NameBinding<'ra>>,
1167    macro_names: FxHashSet<Ident>,
1168    builtin_macros: FxHashMap<Symbol, SyntaxExtensionKind>,
1169    registered_tools: &'tcx RegisteredTools,
1170    macro_use_prelude: FxIndexMap<Symbol, NameBinding<'ra>>,
1171    /// Eagerly populated map of all local macro definitions.
1172    local_macro_map: FxHashMap<LocalDefId, &'ra MacroData>,
1173    /// Lazily populated cache of macro definitions loaded from external crates.
1174    extern_macro_map: RefCell<FxHashMap<DefId, &'ra MacroData>>,
1175    dummy_ext_bang: Arc<SyntaxExtension>,
1176    dummy_ext_derive: Arc<SyntaxExtension>,
1177    non_macro_attr: &'ra MacroData,
1178    local_macro_def_scopes: FxHashMap<LocalDefId, Module<'ra>>,
1179    ast_transform_scopes: FxHashMap<LocalExpnId, Module<'ra>>,
1180    unused_macros: FxIndexMap<LocalDefId, (NodeId, Ident)>,
1181    /// A map from the macro to all its potentially unused arms.
1182    unused_macro_rules: FxIndexMap<NodeId, DenseBitSet<usize>>,
1183    proc_macro_stubs: FxHashSet<LocalDefId>,
1184    /// Traces collected during macro resolution and validated when it's complete.
1185    // FIXME: Remove interior mutability when speculative resolution produces these as outputs.
1186    single_segment_macro_resolutions:
1187        RefCell<Vec<(Ident, MacroKind, ParentScope<'ra>, Option<NameBinding<'ra>>, Option<Span>)>>,
1188    multi_segment_macro_resolutions:
1189        RefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'ra>, Option<Res>, Namespace)>>,
1190    builtin_attrs: Vec<(Ident, ParentScope<'ra>)>,
1191    /// `derive(Copy)` marks items they are applied to so they are treated specially later.
1192    /// Derive macros cannot modify the item themselves and have to store the markers in the global
1193    /// context, so they attach the markers to derive container IDs using this resolver table.
1194    containers_deriving_copy: FxHashSet<LocalExpnId>,
1195    /// Parent scopes in which the macros were invoked.
1196    /// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere.
1197    invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'ra>>,
1198    /// `macro_rules` scopes *produced* by expanding the macro invocations,
1199    /// include all the `macro_rules` items and other invocations generated by them.
1200    output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'ra>>,
1201    /// `macro_rules` scopes produced by `macro_rules` item definitions.
1202    macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'ra>>,
1203    /// Helper attributes that are in scope for the given expansion.
1204    helper_attrs: FxHashMap<LocalExpnId, Vec<(Ident, NameBinding<'ra>)>>,
1205    /// Ready or in-progress results of resolving paths inside the `#[derive(...)]` attribute
1206    /// with the given `ExpnId`.
1207    derive_data: FxHashMap<LocalExpnId, DeriveData>,
1208
1209    /// Avoid duplicated errors for "name already defined".
1210    name_already_seen: FxHashMap<Symbol, Span>,
1211
1212    potentially_unused_imports: Vec<Import<'ra>> = Vec::new(),
1213
1214    potentially_unnecessary_qualifications: Vec<UnnecessaryQualification<'ra>> = Vec::new(),
1215
1216    /// Table for mapping struct IDs into struct constructor IDs,
1217    /// it's not used during normal resolution, only for better error reporting.
1218    /// Also includes of list of each fields visibility
1219    struct_constructors: LocalDefIdMap<(Res, Visibility<DefId>, Vec<Visibility<DefId>>)>,
1220
1221    lint_buffer: LintBuffer,
1222
1223    next_node_id: NodeId = CRATE_NODE_ID,
1224
1225    node_id_to_def_id: NodeMap<Feed<'tcx, LocalDefId>>,
1226
1227    disambiguator: DisambiguatorState,
1228
1229    /// Indices of unnamed struct or variant fields with unresolved attributes.
1230    placeholder_field_indices: FxHashMap<NodeId, usize>,
1231    /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId`
1232    /// we know what parent node that fragment should be attached to thanks to this table,
1233    /// and how the `impl Trait` fragments were introduced.
1234    invocation_parents: FxHashMap<LocalExpnId, InvocationParent>,
1235
1236    legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
1237    /// Amount of lifetime parameters for each item in the crate.
1238    item_generics_num_lifetimes: FxHashMap<LocalDefId, usize>,
1239    delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
1240
1241    main_def: Option<MainDefinition> = None,
1242    trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1243    /// A list of proc macro LocalDefIds, written out in the order in which
1244    /// they are declared in the static array generated by proc_macro_harness.
1245    proc_macros: Vec<LocalDefId> = Vec::new(),
1246    confused_type_with_std_module: FxIndexMap<Span, Span>,
1247    /// Whether lifetime elision was successful.
1248    lifetime_elision_allowed: FxHashSet<NodeId>,
1249
1250    /// Names of items that were stripped out via cfg with their corresponding cfg meta item.
1251    stripped_cfg_items: Vec<StrippedCfgItem<NodeId>> = Vec::new(),
1252
1253    effective_visibilities: EffectiveVisibilities,
1254    doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
1255    doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
1256    all_macro_rules: UnordSet<Symbol>,
1257
1258    /// Invocation ids of all glob delegations.
1259    glob_delegation_invoc_ids: FxHashSet<LocalExpnId>,
1260    /// Analogue of module `unexpanded_invocations` but in trait impls, excluding glob delegations.
1261    /// Needed because glob delegations wait for all other neighboring macros to expand.
1262    impl_unexpanded_invocations: FxHashMap<LocalDefId, FxHashSet<LocalExpnId>>,
1263    /// Simplified analogue of module `resolutions` but in trait impls, excluding glob delegations.
1264    /// Needed because glob delegations exclude explicitly defined names.
1265    impl_binding_keys: FxHashMap<LocalDefId, FxHashSet<BindingKey>>,
1266
1267    /// This is the `Span` where an `extern crate foo;` suggestion would be inserted, if `foo`
1268    /// could be a crate that wasn't imported. For diagnostics use only.
1269    current_crate_outer_attr_insert_span: Span,
1270
1271    mods_with_parse_errors: FxHashSet<DefId>,
1272
1273    /// Whether `Resolver::register_macros_for_all_crates` has been called once already, as we
1274    /// don't need to run it more than once.
1275    all_crate_macros_already_registered: bool = false,
1276
1277    // Stores pre-expansion and pre-placeholder-fragment-insertion names for `impl Trait` types
1278    // that were encountered during resolution. These names are used to generate item names
1279    // for APITs, so we don't want to leak details of resolution into these names.
1280    impl_trait_names: FxHashMap<NodeId, Symbol>,
1281}
1282
1283/// This provides memory for the rest of the crate. The `'ra` lifetime that is
1284/// used by many types in this crate is an abbreviation of `ResolverArenas`.
1285#[derive(Default)]
1286pub struct ResolverArenas<'ra> {
1287    modules: TypedArena<ModuleData<'ra>>,
1288    local_modules: RefCell<Vec<Module<'ra>>>,
1289    imports: TypedArena<ImportData<'ra>>,
1290    name_resolutions: TypedArena<RefCell<NameResolution<'ra>>>,
1291    ast_paths: TypedArena<ast::Path>,
1292    macros: TypedArena<MacroData>,
1293    dropless: DroplessArena,
1294}
1295
1296impl<'ra> ResolverArenas<'ra> {
1297    fn new_res_binding(
1298        &'ra self,
1299        res: Res,
1300        vis: Visibility<DefId>,
1301        span: Span,
1302        expansion: LocalExpnId,
1303    ) -> NameBinding<'ra> {
1304        self.alloc_name_binding(NameBindingData {
1305            kind: NameBindingKind::Res(res),
1306            ambiguity: None,
1307            warn_ambiguity: false,
1308            vis,
1309            span,
1310            expansion,
1311        })
1312    }
1313
1314    fn new_pub_res_binding(
1315        &'ra self,
1316        res: Res,
1317        span: Span,
1318        expn_id: LocalExpnId,
1319    ) -> NameBinding<'ra> {
1320        self.new_res_binding(res, Visibility::Public, span, expn_id)
1321    }
1322
1323    fn new_module(
1324        &'ra self,
1325        parent: Option<Module<'ra>>,
1326        kind: ModuleKind,
1327        expn_id: ExpnId,
1328        span: Span,
1329        no_implicit_prelude: bool,
1330    ) -> Module<'ra> {
1331        let (def_id, self_binding) = match kind {
1332            ModuleKind::Def(def_kind, def_id, _) => (
1333                Some(def_id),
1334                Some(self.new_pub_res_binding(Res::Def(def_kind, def_id), span, LocalExpnId::ROOT)),
1335            ),
1336            ModuleKind::Block => (None, None),
1337        };
1338        let module = Module(Interned::new_unchecked(self.modules.alloc(ModuleData::new(
1339            parent,
1340            kind,
1341            expn_id,
1342            span,
1343            no_implicit_prelude,
1344            self_binding,
1345        ))));
1346        if def_id.is_none_or(|def_id| def_id.is_local()) {
1347            self.local_modules.borrow_mut().push(module);
1348        }
1349        module
1350    }
1351    fn local_modules(&'ra self) -> std::cell::Ref<'ra, Vec<Module<'ra>>> {
1352        self.local_modules.borrow()
1353    }
1354    fn alloc_name_binding(&'ra self, name_binding: NameBindingData<'ra>) -> NameBinding<'ra> {
1355        Interned::new_unchecked(self.dropless.alloc(name_binding))
1356    }
1357    fn alloc_import(&'ra self, import: ImportData<'ra>) -> Import<'ra> {
1358        Interned::new_unchecked(self.imports.alloc(import))
1359    }
1360    fn alloc_name_resolution(&'ra self) -> &'ra RefCell<NameResolution<'ra>> {
1361        self.name_resolutions.alloc(Default::default())
1362    }
1363    fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> {
1364        self.dropless.alloc(Cell::new(scope))
1365    }
1366    fn alloc_macro_rules_binding(
1367        &'ra self,
1368        binding: MacroRulesBinding<'ra>,
1369    ) -> &'ra MacroRulesBinding<'ra> {
1370        self.dropless.alloc(binding)
1371    }
1372    fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {
1373        self.ast_paths.alloc_from_iter(paths.iter().cloned())
1374    }
1375    fn alloc_macro(&'ra self, macro_data: MacroData) -> &'ra MacroData {
1376        self.macros.alloc(macro_data)
1377    }
1378    fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {
1379        self.dropless.alloc_from_iter(spans)
1380    }
1381}
1382
1383impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1384    fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
1385        self
1386    }
1387}
1388
1389impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1390    fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
1391        self
1392    }
1393}
1394
1395impl<'tcx> Resolver<'_, 'tcx> {
1396    fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1397        self.opt_feed(node).map(|f| f.key())
1398    }
1399
1400    fn local_def_id(&self, node: NodeId) -> LocalDefId {
1401        self.feed(node).key()
1402    }
1403
1404    fn opt_feed(&self, node: NodeId) -> Option<Feed<'tcx, LocalDefId>> {
1405        self.node_id_to_def_id.get(&node).copied()
1406    }
1407
1408    fn feed(&self, node: NodeId) -> Feed<'tcx, LocalDefId> {
1409        self.opt_feed(node).unwrap_or_else(|| panic!("no entry for node id: `{node:?}`"))
1410    }
1411
1412    fn local_def_kind(&self, node: NodeId) -> DefKind {
1413        self.tcx.def_kind(self.local_def_id(node))
1414    }
1415
1416    /// Adds a definition with a parent definition.
1417    fn create_def(
1418        &mut self,
1419        parent: LocalDefId,
1420        node_id: ast::NodeId,
1421        name: Option<Symbol>,
1422        def_kind: DefKind,
1423        expn_id: ExpnId,
1424        span: Span,
1425    ) -> TyCtxtFeed<'tcx, LocalDefId> {
1426        assert!(
1427            !self.node_id_to_def_id.contains_key(&node_id),
1428            "adding a def for node-id {:?}, name {:?}, data {:?} but a previous def exists: {:?}",
1429            node_id,
1430            name,
1431            def_kind,
1432            self.tcx.definitions_untracked().def_key(self.node_id_to_def_id[&node_id].key()),
1433        );
1434
1435        // FIXME: remove `def_span` body, pass in the right spans here and call `tcx.at().create_def()`
1436        let feed = self.tcx.create_def(parent, name, def_kind, None, &mut self.disambiguator);
1437        let def_id = feed.def_id();
1438
1439        // Create the definition.
1440        if expn_id != ExpnId::root() {
1441            self.expn_that_defined.insert(def_id, expn_id);
1442        }
1443
1444        // A relative span's parent must be an absolute span.
1445        debug_assert_eq!(span.data_untracked().parent, None);
1446        let _id = self.tcx.untracked().source_span.push(span);
1447        debug_assert_eq!(_id, def_id);
1448
1449        // Some things for which we allocate `LocalDefId`s don't correspond to
1450        // anything in the AST, so they don't have a `NodeId`. For these cases
1451        // we don't need a mapping from `NodeId` to `LocalDefId`.
1452        if node_id != ast::DUMMY_NODE_ID {
1453            debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1454            self.node_id_to_def_id.insert(node_id, feed.downgrade());
1455        }
1456
1457        feed
1458    }
1459
1460    fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1461        if let Some(def_id) = def_id.as_local() {
1462            self.item_generics_num_lifetimes[&def_id]
1463        } else {
1464            self.tcx.generics_of(def_id).own_counts().lifetimes
1465        }
1466    }
1467
1468    pub fn tcx(&self) -> TyCtxt<'tcx> {
1469        self.tcx
1470    }
1471
1472    /// This function is very slow, as it iterates over the entire
1473    /// [Resolver::node_id_to_def_id] map just to find the [NodeId]
1474    /// that corresponds to the given [LocalDefId]. Only use this in
1475    /// diagnostics code paths.
1476    fn def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
1477        self.node_id_to_def_id
1478            .items()
1479            .filter(|(_, v)| v.key() == def_id)
1480            .map(|(k, _)| *k)
1481            .get_only()
1482            .unwrap()
1483    }
1484}
1485
1486impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
1487    pub fn new(
1488        tcx: TyCtxt<'tcx>,
1489        attrs: &[ast::Attribute],
1490        crate_span: Span,
1491        current_crate_outer_attr_insert_span: Span,
1492        arenas: &'ra ResolverArenas<'ra>,
1493    ) -> Resolver<'ra, 'tcx> {
1494        let root_def_id = CRATE_DEF_ID.to_def_id();
1495        let mut local_module_map = FxIndexMap::default();
1496        let graph_root = arenas.new_module(
1497            None,
1498            ModuleKind::Def(DefKind::Mod, root_def_id, None),
1499            ExpnId::root(),
1500            crate_span,
1501            attr::contains_name(attrs, sym::no_implicit_prelude),
1502        );
1503        local_module_map.insert(CRATE_DEF_ID, graph_root);
1504        let empty_module = arenas.new_module(
1505            None,
1506            ModuleKind::Def(DefKind::Mod, root_def_id, None),
1507            ExpnId::root(),
1508            DUMMY_SP,
1509            true,
1510        );
1511
1512        let mut node_id_to_def_id = NodeMap::default();
1513        let crate_feed = tcx.create_local_crate_def_id(crate_span);
1514
1515        crate_feed.def_kind(DefKind::Mod);
1516        let crate_feed = crate_feed.downgrade();
1517        node_id_to_def_id.insert(CRATE_NODE_ID, crate_feed);
1518
1519        let mut invocation_parents = FxHashMap::default();
1520        invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);
1521
1522        let mut extern_prelude: FxIndexMap<_, _> = tcx
1523            .sess
1524            .opts
1525            .externs
1526            .iter()
1527            .filter_map(|(name, entry)| {
1528                // Make sure `self`, `super`, `_` etc do not get into extern prelude.
1529                // FIXME: reject `--extern self` and similar in option parsing instead.
1530                if entry.add_prelude
1531                    && let name = Symbol::intern(name)
1532                    && name.can_be_raw()
1533                {
1534                    Some((Macros20NormalizedIdent::with_dummy_span(name), Default::default()))
1535                } else {
1536                    None
1537                }
1538            })
1539            .collect();
1540
1541        if !attr::contains_name(attrs, sym::no_core) {
1542            extern_prelude
1543                .insert(Macros20NormalizedIdent::with_dummy_span(sym::core), Default::default());
1544            if !attr::contains_name(attrs, sym::no_std) {
1545                extern_prelude
1546                    .insert(Macros20NormalizedIdent::with_dummy_span(sym::std), Default::default());
1547            }
1548        }
1549
1550        let registered_tools = tcx.registered_tools(());
1551        let edition = tcx.sess.edition();
1552
1553        let mut resolver = Resolver {
1554            tcx,
1555
1556            expn_that_defined: Default::default(),
1557
1558            // The outermost module has def ID 0; this is not reflected in the
1559            // AST.
1560            graph_root,
1561            assert_speculative: false, // Only set/cleared in Resolver::resolve_imports for now
1562            prelude: None,
1563            extern_prelude,
1564
1565            field_names: Default::default(),
1566            field_defaults: Default::default(),
1567            field_visibility_spans: FxHashMap::default(),
1568
1569            pat_span_map: Default::default(),
1570            partial_res_map: Default::default(),
1571            import_res_map: Default::default(),
1572            import_use_map: Default::default(),
1573            label_res_map: Default::default(),
1574            lifetimes_res_map: Default::default(),
1575            extra_lifetime_params_map: Default::default(),
1576            extern_crate_map: Default::default(),
1577            module_children: Default::default(),
1578            trait_map: NodeMap::default(),
1579            empty_module,
1580            local_module_map,
1581            extern_module_map: Default::default(),
1582            block_map: Default::default(),
1583            binding_parent_modules: FxHashMap::default(),
1584            ast_transform_scopes: FxHashMap::default(),
1585
1586            glob_map: Default::default(),
1587            used_imports: FxHashSet::default(),
1588            maybe_unused_trait_imports: Default::default(),
1589
1590            arenas,
1591            dummy_binding: arenas.new_pub_res_binding(Res::Err, DUMMY_SP, LocalExpnId::ROOT),
1592            builtin_types_bindings: PrimTy::ALL
1593                .iter()
1594                .map(|prim_ty| {
1595                    let res = Res::PrimTy(*prim_ty);
1596                    let binding = arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT);
1597                    (prim_ty.name(), binding)
1598                })
1599                .collect(),
1600            builtin_attrs_bindings: BUILTIN_ATTRIBUTES
1601                .iter()
1602                .map(|builtin_attr| {
1603                    let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(builtin_attr.name));
1604                    let binding = arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT);
1605                    (builtin_attr.name, binding)
1606                })
1607                .collect(),
1608            registered_tool_bindings: registered_tools
1609                .iter()
1610                .map(|ident| {
1611                    let res = Res::ToolMod;
1612                    let binding = arenas.new_pub_res_binding(res, ident.span, LocalExpnId::ROOT);
1613                    (*ident, binding)
1614                })
1615                .collect(),
1616            macro_names: FxHashSet::default(),
1617            builtin_macros: Default::default(),
1618            registered_tools,
1619            macro_use_prelude: Default::default(),
1620            local_macro_map: Default::default(),
1621            extern_macro_map: Default::default(),
1622            dummy_ext_bang: Arc::new(SyntaxExtension::dummy_bang(edition)),
1623            dummy_ext_derive: Arc::new(SyntaxExtension::dummy_derive(edition)),
1624            non_macro_attr: arenas
1625                .alloc_macro(MacroData::new(Arc::new(SyntaxExtension::non_macro_attr(edition)))),
1626            invocation_parent_scopes: Default::default(),
1627            output_macro_rules_scopes: Default::default(),
1628            macro_rules_scopes: Default::default(),
1629            helper_attrs: Default::default(),
1630            derive_data: Default::default(),
1631            local_macro_def_scopes: FxHashMap::default(),
1632            name_already_seen: FxHashMap::default(),
1633            struct_constructors: Default::default(),
1634            unused_macros: Default::default(),
1635            unused_macro_rules: Default::default(),
1636            proc_macro_stubs: Default::default(),
1637            single_segment_macro_resolutions: Default::default(),
1638            multi_segment_macro_resolutions: Default::default(),
1639            builtin_attrs: Default::default(),
1640            containers_deriving_copy: Default::default(),
1641            lint_buffer: LintBuffer::default(),
1642            node_id_to_def_id,
1643            disambiguator: DisambiguatorState::new(),
1644            placeholder_field_indices: Default::default(),
1645            invocation_parents,
1646            legacy_const_generic_args: Default::default(),
1647            item_generics_num_lifetimes: Default::default(),
1648            trait_impls: Default::default(),
1649            confused_type_with_std_module: Default::default(),
1650            lifetime_elision_allowed: Default::default(),
1651            stripped_cfg_items: Default::default(),
1652            effective_visibilities: Default::default(),
1653            doc_link_resolutions: Default::default(),
1654            doc_link_traits_in_scope: Default::default(),
1655            all_macro_rules: Default::default(),
1656            delegation_fn_sigs: Default::default(),
1657            glob_delegation_invoc_ids: Default::default(),
1658            impl_unexpanded_invocations: Default::default(),
1659            impl_binding_keys: Default::default(),
1660            current_crate_outer_attr_insert_span,
1661            mods_with_parse_errors: Default::default(),
1662            impl_trait_names: Default::default(),
1663            ..
1664        };
1665
1666        let root_parent_scope = ParentScope::module(graph_root, resolver.arenas);
1667        resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1668        resolver.feed_visibility(crate_feed, Visibility::Public);
1669
1670        resolver
1671    }
1672
1673    fn new_local_module(
1674        &mut self,
1675        parent: Option<Module<'ra>>,
1676        kind: ModuleKind,
1677        expn_id: ExpnId,
1678        span: Span,
1679        no_implicit_prelude: bool,
1680    ) -> Module<'ra> {
1681        let module = self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude);
1682        if let Some(def_id) = module.opt_def_id() {
1683            self.local_module_map.insert(def_id.expect_local(), module);
1684        }
1685        module
1686    }
1687
1688    fn new_extern_module(
1689        &self,
1690        parent: Option<Module<'ra>>,
1691        kind: ModuleKind,
1692        expn_id: ExpnId,
1693        span: Span,
1694        no_implicit_prelude: bool,
1695    ) -> Module<'ra> {
1696        let module = self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude);
1697        self.extern_module_map.borrow_mut().insert(module.def_id(), module);
1698        module
1699    }
1700
1701    fn new_local_macro(&mut self, def_id: LocalDefId, macro_data: MacroData) -> &'ra MacroData {
1702        let mac = self.arenas.alloc_macro(macro_data);
1703        self.local_macro_map.insert(def_id, mac);
1704        mac
1705    }
1706
1707    fn next_node_id(&mut self) -> NodeId {
1708        let start = self.next_node_id;
1709        let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1710        self.next_node_id = ast::NodeId::from_u32(next);
1711        start
1712    }
1713
1714    fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1715        let start = self.next_node_id;
1716        let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1717        self.next_node_id = ast::NodeId::from_usize(end);
1718        start..self.next_node_id
1719    }
1720
1721    pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1722        &mut self.lint_buffer
1723    }
1724
1725    pub fn arenas() -> ResolverArenas<'ra> {
1726        Default::default()
1727    }
1728
1729    fn feed_visibility(&mut self, feed: Feed<'tcx, LocalDefId>, vis: Visibility) {
1730        let feed = feed.upgrade(self.tcx);
1731        feed.visibility(vis.to_def_id());
1732        self.visibilities_for_hashing.push((feed.def_id(), vis));
1733    }
1734
1735    pub fn into_outputs(self) -> ResolverOutputs {
1736        let proc_macros = self.proc_macros;
1737        let expn_that_defined = self.expn_that_defined;
1738        let extern_crate_map = self.extern_crate_map;
1739        let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1740        let glob_map = self.glob_map;
1741        let main_def = self.main_def;
1742        let confused_type_with_std_module = self.confused_type_with_std_module;
1743        let effective_visibilities = self.effective_visibilities;
1744
1745        let stripped_cfg_items = self
1746            .stripped_cfg_items
1747            .into_iter()
1748            .filter_map(|item| {
1749                let parent_module =
1750                    self.node_id_to_def_id.get(&item.parent_module)?.key().to_def_id();
1751                Some(StrippedCfgItem { parent_module, ident: item.ident, cfg: item.cfg })
1752            })
1753            .collect();
1754
1755        let global_ctxt = ResolverGlobalCtxt {
1756            expn_that_defined,
1757            visibilities_for_hashing: self.visibilities_for_hashing,
1758            effective_visibilities,
1759            extern_crate_map,
1760            module_children: self.module_children,
1761            glob_map,
1762            maybe_unused_trait_imports,
1763            main_def,
1764            trait_impls: self.trait_impls,
1765            proc_macros,
1766            confused_type_with_std_module,
1767            doc_link_resolutions: self.doc_link_resolutions,
1768            doc_link_traits_in_scope: self.doc_link_traits_in_scope,
1769            all_macro_rules: self.all_macro_rules,
1770            stripped_cfg_items,
1771        };
1772        let ast_lowering = ty::ResolverAstLowering {
1773            legacy_const_generic_args: self.legacy_const_generic_args,
1774            partial_res_map: self.partial_res_map,
1775            import_res_map: self.import_res_map,
1776            label_res_map: self.label_res_map,
1777            lifetimes_res_map: self.lifetimes_res_map,
1778            extra_lifetime_params_map: self.extra_lifetime_params_map,
1779            next_node_id: self.next_node_id,
1780            node_id_to_def_id: self
1781                .node_id_to_def_id
1782                .into_items()
1783                .map(|(k, f)| (k, f.key()))
1784                .collect(),
1785            disambiguator: self.disambiguator,
1786            trait_map: self.trait_map,
1787            lifetime_elision_allowed: self.lifetime_elision_allowed,
1788            lint_buffer: Steal::new(self.lint_buffer),
1789            delegation_fn_sigs: self.delegation_fn_sigs,
1790        };
1791        ResolverOutputs { global_ctxt, ast_lowering }
1792    }
1793
1794    fn create_stable_hashing_context(&self) -> StableHashingContext<'_> {
1795        StableHashingContext::new(self.tcx.sess, self.tcx.untracked())
1796    }
1797
1798    fn cstore(&self) -> FreezeReadGuard<'_, CStore> {
1799        CStore::from_tcx(self.tcx)
1800    }
1801
1802    fn cstore_mut(&self) -> FreezeWriteGuard<'_, CStore> {
1803        CStore::from_tcx_mut(self.tcx)
1804    }
1805
1806    fn dummy_ext(&self, macro_kind: MacroKind) -> Arc<SyntaxExtension> {
1807        match macro_kind {
1808            MacroKind::Bang => Arc::clone(&self.dummy_ext_bang),
1809            MacroKind::Derive => Arc::clone(&self.dummy_ext_derive),
1810            MacroKind::Attr => Arc::clone(&self.non_macro_attr.ext),
1811        }
1812    }
1813
1814    /// Returns a conditionally mutable resolver.
1815    ///
1816    /// Currently only dependent on `assert_speculative`, if `assert_speculative` is false,
1817    /// the resolver will allow mutation; otherwise, it will be immutable.
1818    fn cm(&mut self) -> CmResolver<'_, 'ra, 'tcx> {
1819        CmResolver::new(self, !self.assert_speculative)
1820    }
1821
1822    /// Runs the function on each namespace.
1823    fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1824        f(self, TypeNS);
1825        f(self, ValueNS);
1826        f(self, MacroNS);
1827    }
1828
1829    fn per_ns_cm<'r, F: FnMut(&mut CmResolver<'r, 'ra, 'tcx>, Namespace)>(
1830        mut self: CmResolver<'r, 'ra, 'tcx>,
1831        mut f: F,
1832    ) {
1833        f(&mut self, TypeNS);
1834        f(&mut self, ValueNS);
1835        f(&mut self, MacroNS);
1836    }
1837
1838    fn is_builtin_macro(&self, res: Res) -> bool {
1839        self.get_macro(res).is_some_and(|macro_data| macro_data.ext.builtin_name.is_some())
1840    }
1841
1842    fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1843        loop {
1844            match ctxt.outer_expn_data().macro_def_id {
1845                Some(def_id) => return def_id,
1846                None => ctxt.remove_mark(),
1847            };
1848        }
1849    }
1850
1851    /// Entry point to crate resolution.
1852    pub fn resolve_crate(&mut self, krate: &Crate) {
1853        self.tcx.sess.time("resolve_crate", || {
1854            self.tcx.sess.time("finalize_imports", || self.finalize_imports());
1855            let exported_ambiguities = self.tcx.sess.time("compute_effective_visibilities", || {
1856                EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
1857            });
1858            self.tcx.sess.time("lint_reexports", || self.lint_reexports(exported_ambiguities));
1859            self.tcx
1860                .sess
1861                .time("finalize_macro_resolutions", || self.finalize_macro_resolutions(krate));
1862            self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate));
1863            self.tcx.sess.time("resolve_main", || self.resolve_main());
1864            self.tcx.sess.time("resolve_check_unused", || self.check_unused(krate));
1865            self.tcx.sess.time("resolve_report_errors", || self.report_errors(krate));
1866            self.tcx
1867                .sess
1868                .time("resolve_postprocess", || self.cstore_mut().postprocess(self.tcx, krate));
1869        });
1870
1871        // Make sure we don't mutate the cstore from here on.
1872        self.tcx.untracked().cstore.freeze();
1873    }
1874
1875    fn traits_in_scope(
1876        &mut self,
1877        current_trait: Option<Module<'ra>>,
1878        parent_scope: &ParentScope<'ra>,
1879        ctxt: SyntaxContext,
1880        assoc_item: Option<(Symbol, Namespace)>,
1881    ) -> Vec<TraitCandidate> {
1882        let mut found_traits = Vec::new();
1883
1884        if let Some(module) = current_trait {
1885            if self.trait_may_have_item(Some(module), assoc_item) {
1886                let def_id = module.def_id();
1887                found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
1888            }
1889        }
1890
1891        self.cm().visit_scopes(ScopeSet::All(TypeNS), parent_scope, ctxt, |this, scope, _, _| {
1892            match scope {
1893                Scope::Module(module, _) => {
1894                    this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1895                }
1896                Scope::StdLibPrelude => {
1897                    if let Some(module) = this.prelude {
1898                        this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1899                    }
1900                }
1901                Scope::ExternPreludeItems
1902                | Scope::ExternPreludeFlags
1903                | Scope::ToolPrelude
1904                | Scope::BuiltinTypes => {}
1905                _ => unreachable!(),
1906            }
1907            None::<()>
1908        });
1909
1910        found_traits
1911    }
1912
1913    fn traits_in_module(
1914        &mut self,
1915        module: Module<'ra>,
1916        assoc_item: Option<(Symbol, Namespace)>,
1917        found_traits: &mut Vec<TraitCandidate>,
1918    ) {
1919        module.ensure_traits(self);
1920        let traits = module.traits.borrow();
1921        for &(trait_name, trait_binding, trait_module) in traits.as_ref().unwrap().iter() {
1922            if self.trait_may_have_item(trait_module, assoc_item) {
1923                let def_id = trait_binding.res().def_id();
1924                let import_ids = self.find_transitive_imports(&trait_binding.kind, trait_name.0);
1925                found_traits.push(TraitCandidate { def_id, import_ids });
1926            }
1927        }
1928    }
1929
1930    // List of traits in scope is pruned on best effort basis. We reject traits not having an
1931    // associated item with the given name and namespace (if specified). This is a conservative
1932    // optimization, proper hygienic type-based resolution of associated items is done in typeck.
1933    // We don't reject trait aliases (`trait_module == None`) because we don't have access to their
1934    // associated items.
1935    fn trait_may_have_item(
1936        &self,
1937        trait_module: Option<Module<'ra>>,
1938        assoc_item: Option<(Symbol, Namespace)>,
1939    ) -> bool {
1940        match (trait_module, assoc_item) {
1941            (Some(trait_module), Some((name, ns))) => self
1942                .resolutions(trait_module)
1943                .borrow()
1944                .iter()
1945                .any(|(key, _name_resolution)| key.ns == ns && key.ident.name == name),
1946            _ => true,
1947        }
1948    }
1949
1950    fn find_transitive_imports(
1951        &mut self,
1952        mut kind: &NameBindingKind<'_>,
1953        trait_name: Ident,
1954    ) -> SmallVec<[LocalDefId; 1]> {
1955        let mut import_ids = smallvec![];
1956        while let NameBindingKind::Import { import, binding, .. } = kind {
1957            if let Some(node_id) = import.id() {
1958                let def_id = self.local_def_id(node_id);
1959                self.maybe_unused_trait_imports.insert(def_id);
1960                import_ids.push(def_id);
1961            }
1962            self.add_to_glob_map(*import, trait_name);
1963            kind = &binding.kind;
1964        }
1965        import_ids
1966    }
1967
1968    fn resolutions(&self, module: Module<'ra>) -> &'ra Resolutions<'ra> {
1969        if module.populate_on_access.get() {
1970            module.populate_on_access.set(false);
1971            self.build_reduced_graph_external(module);
1972        }
1973        &module.0.0.lazy_resolutions
1974    }
1975
1976    fn resolution(
1977        &self,
1978        module: Module<'ra>,
1979        key: BindingKey,
1980    ) -> Option<Ref<'ra, NameResolution<'ra>>> {
1981        self.resolutions(module).borrow().get(&key).map(|resolution| resolution.borrow())
1982    }
1983
1984    fn resolution_or_default(
1985        &self,
1986        module: Module<'ra>,
1987        key: BindingKey,
1988    ) -> &'ra RefCell<NameResolution<'ra>> {
1989        self.resolutions(module)
1990            .borrow_mut()
1991            .entry(key)
1992            .or_insert_with(|| self.arenas.alloc_name_resolution())
1993    }
1994
1995    /// Test if AmbiguityError ambi is any identical to any one inside ambiguity_errors
1996    fn matches_previous_ambiguity_error(&self, ambi: &AmbiguityError<'_>) -> bool {
1997        for ambiguity_error in &self.ambiguity_errors {
1998            // if the span location and ident as well as its span are the same
1999            if ambiguity_error.kind == ambi.kind
2000                && ambiguity_error.ident == ambi.ident
2001                && ambiguity_error.ident.span == ambi.ident.span
2002                && ambiguity_error.b1.span == ambi.b1.span
2003                && ambiguity_error.b2.span == ambi.b2.span
2004                && ambiguity_error.misc1 == ambi.misc1
2005                && ambiguity_error.misc2 == ambi.misc2
2006            {
2007                return true;
2008            }
2009        }
2010        false
2011    }
2012
2013    fn record_use(&mut self, ident: Ident, used_binding: NameBinding<'ra>, used: Used) {
2014        self.record_use_inner(ident, used_binding, used, used_binding.warn_ambiguity);
2015    }
2016
2017    fn record_use_inner(
2018        &mut self,
2019        ident: Ident,
2020        used_binding: NameBinding<'ra>,
2021        used: Used,
2022        warn_ambiguity: bool,
2023    ) {
2024        if let Some((b2, kind)) = used_binding.ambiguity {
2025            let ambiguity_error = AmbiguityError {
2026                kind,
2027                ident,
2028                b1: used_binding,
2029                b2,
2030                misc1: AmbiguityErrorMisc::None,
2031                misc2: AmbiguityErrorMisc::None,
2032                warning: warn_ambiguity,
2033            };
2034            if !self.matches_previous_ambiguity_error(&ambiguity_error) {
2035                // avoid duplicated span information to be emit out
2036                self.ambiguity_errors.push(ambiguity_error);
2037            }
2038        }
2039        if let NameBindingKind::Import { import, binding } = used_binding.kind {
2040            if let ImportKind::MacroUse { warn_private: true } = import.kind {
2041                // Do not report the lint if the macro name resolves in stdlib prelude
2042                // even without the problematic `macro_use` import.
2043                let found_in_stdlib_prelude = self.prelude.is_some_and(|prelude| {
2044                    let empty_module = self.empty_module;
2045                    let arenas = self.arenas;
2046                    self.cm()
2047                        .maybe_resolve_ident_in_module(
2048                            ModuleOrUniformRoot::Module(prelude),
2049                            ident,
2050                            MacroNS,
2051                            &ParentScope::module(empty_module, arenas),
2052                            None,
2053                        )
2054                        .is_ok()
2055                });
2056                if !found_in_stdlib_prelude {
2057                    self.lint_buffer().buffer_lint(
2058                        PRIVATE_MACRO_USE,
2059                        import.root_id,
2060                        ident.span,
2061                        BuiltinLintDiag::MacroIsPrivate(ident),
2062                    );
2063                }
2064            }
2065            // Avoid marking `extern crate` items that refer to a name from extern prelude,
2066            // but not introduce it, as used if they are accessed from lexical scope.
2067            if used == Used::Scope {
2068                if let Some(entry) = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident)) {
2069                    if !entry.introduced_by_item && entry.item_binding == Some(used_binding) {
2070                        return;
2071                    }
2072                }
2073            }
2074            let old_used = self.import_use_map.entry(import).or_insert(used);
2075            if *old_used < used {
2076                *old_used = used;
2077            }
2078            if let Some(id) = import.id() {
2079                self.used_imports.insert(id);
2080            }
2081            self.add_to_glob_map(import, ident);
2082            self.record_use_inner(
2083                ident,
2084                binding,
2085                Used::Other,
2086                warn_ambiguity || binding.warn_ambiguity,
2087            );
2088        }
2089    }
2090
2091    #[inline]
2092    fn add_to_glob_map(&mut self, import: Import<'_>, ident: Ident) {
2093        if let ImportKind::Glob { id, .. } = import.kind {
2094            let def_id = self.local_def_id(id);
2095            self.glob_map.entry(def_id).or_default().insert(ident.name);
2096        }
2097    }
2098
2099    fn resolve_crate_root(&self, ident: Ident) -> Module<'ra> {
2100        debug!("resolve_crate_root({:?})", ident);
2101        let mut ctxt = ident.span.ctxt();
2102        let mark = if ident.name == kw::DollarCrate {
2103            // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
2104            // we don't want to pretend that the `macro_rules!` definition is in the `macro`
2105            // as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks.
2106            // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
2107            // definitions actually produced by `macro` and `macro` definitions produced by
2108            // `macro_rules!`, but at least such configurations are not stable yet.
2109            ctxt = ctxt.normalize_to_macro_rules();
2110            debug!(
2111                "resolve_crate_root: marks={:?}",
2112                ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
2113            );
2114            let mut iter = ctxt.marks().into_iter().rev().peekable();
2115            let mut result = None;
2116            // Find the last opaque mark from the end if it exists.
2117            while let Some(&(mark, transparency)) = iter.peek() {
2118                if transparency == Transparency::Opaque {
2119                    result = Some(mark);
2120                    iter.next();
2121                } else {
2122                    break;
2123                }
2124            }
2125            debug!(
2126                "resolve_crate_root: found opaque mark {:?} {:?}",
2127                result,
2128                result.map(|r| r.expn_data())
2129            );
2130            // Then find the last semi-opaque mark from the end if it exists.
2131            for (mark, transparency) in iter {
2132                if transparency == Transparency::SemiOpaque {
2133                    result = Some(mark);
2134                } else {
2135                    break;
2136                }
2137            }
2138            debug!(
2139                "resolve_crate_root: found semi-opaque mark {:?} {:?}",
2140                result,
2141                result.map(|r| r.expn_data())
2142            );
2143            result
2144        } else {
2145            debug!("resolve_crate_root: not DollarCrate");
2146            ctxt = ctxt.normalize_to_macros_2_0();
2147            ctxt.adjust(ExpnId::root())
2148        };
2149        let module = match mark {
2150            Some(def) => self.expn_def_scope(def),
2151            None => {
2152                debug!(
2153                    "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
2154                    ident, ident.span
2155                );
2156                return self.graph_root;
2157            }
2158        };
2159        let module = self.expect_module(
2160            module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
2161        );
2162        debug!(
2163            "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
2164            ident,
2165            module,
2166            module.kind.name(),
2167            ident.span
2168        );
2169        module
2170    }
2171
2172    fn resolve_self(&self, ctxt: &mut SyntaxContext, module: Module<'ra>) -> Module<'ra> {
2173        let mut module = self.expect_module(module.nearest_parent_mod());
2174        while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
2175            let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
2176            module = self.expect_module(parent.nearest_parent_mod());
2177        }
2178        module
2179    }
2180
2181    fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2182        debug!("(recording res) recording {:?} for {}", resolution, node_id);
2183        if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2184            panic!("path resolved multiple times ({prev_res:?} before, {resolution:?} now)");
2185        }
2186    }
2187
2188    fn record_pat_span(&mut self, node: NodeId, span: Span) {
2189        debug!("(recording pat) recording {:?} for {:?}", node, span);
2190        self.pat_span_map.insert(node, span);
2191    }
2192
2193    fn is_accessible_from(&self, vis: Visibility<impl Into<DefId>>, module: Module<'ra>) -> bool {
2194        vis.is_accessible_from(module.nearest_parent_mod(), self.tcx)
2195    }
2196
2197    fn set_binding_parent_module(&mut self, binding: NameBinding<'ra>, module: Module<'ra>) {
2198        if let Some(old_module) = self.binding_parent_modules.insert(binding, module) {
2199            if module != old_module {
2200                span_bug!(binding.span, "parent module is reset for binding");
2201            }
2202        }
2203    }
2204
2205    fn disambiguate_macro_rules_vs_modularized(
2206        &self,
2207        macro_rules: NameBinding<'ra>,
2208        modularized: NameBinding<'ra>,
2209    ) -> bool {
2210        // Some non-controversial subset of ambiguities "modularized macro name" vs "macro_rules"
2211        // is disambiguated to mitigate regressions from macro modularization.
2212        // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
2213        match (
2214            self.binding_parent_modules.get(&macro_rules),
2215            self.binding_parent_modules.get(&modularized),
2216        ) {
2217            (Some(macro_rules), Some(modularized)) => {
2218                macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
2219                    && modularized.is_ancestor_of(*macro_rules)
2220            }
2221            _ => false,
2222        }
2223    }
2224
2225    fn extern_prelude_get_item<'r>(
2226        mut self: CmResolver<'r, 'ra, 'tcx>,
2227        ident: Ident,
2228        finalize: bool,
2229    ) -> Option<NameBinding<'ra>> {
2230        let entry = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident));
2231        entry.and_then(|entry| entry.item_binding).map(|binding| {
2232            if finalize {
2233                self.get_mut().record_use(ident, binding, Used::Scope);
2234            }
2235            binding
2236        })
2237    }
2238
2239    fn extern_prelude_get_flag(&self, ident: Ident, finalize: bool) -> Option<NameBinding<'ra>> {
2240        let entry = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident));
2241        entry.and_then(|entry| match entry.flag_binding.get() {
2242            Some(binding) => {
2243                if finalize {
2244                    self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span);
2245                }
2246                Some(binding)
2247            }
2248            None if entry.only_item => None,
2249            None => {
2250                let crate_id = if finalize {
2251                    self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span)
2252                } else {
2253                    self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
2254                };
2255                match crate_id {
2256                    Some(crate_id) => {
2257                        let res = Res::Def(DefKind::Mod, crate_id.as_def_id());
2258                        let binding =
2259                            self.arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT);
2260                        entry.flag_binding.set(Some(binding));
2261                        Some(binding)
2262                    }
2263                    None => finalize.then_some(self.dummy_binding),
2264                }
2265            }
2266        })
2267    }
2268
2269    /// Rustdoc uses this to resolve doc link paths in a recoverable way. `PathResult<'a>`
2270    /// isn't something that can be returned because it can't be made to live that long,
2271    /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
2272    /// just that an error occurred.
2273    fn resolve_rustdoc_path(
2274        &mut self,
2275        path_str: &str,
2276        ns: Namespace,
2277        parent_scope: ParentScope<'ra>,
2278    ) -> Option<Res> {
2279        let segments: Result<Vec<_>, ()> = path_str
2280            .split("::")
2281            .enumerate()
2282            .map(|(i, s)| {
2283                let sym = if s.is_empty() {
2284                    if i == 0 {
2285                        // For a path like `::a::b`, use `kw::PathRoot` as the leading segment.
2286                        kw::PathRoot
2287                    } else {
2288                        return Err(()); // occurs in cases like `String::`
2289                    }
2290                } else {
2291                    Symbol::intern(s)
2292                };
2293                Ok(Segment::from_ident(Ident::with_dummy_span(sym)))
2294            })
2295            .collect();
2296        let Ok(segments) = segments else { return None };
2297
2298        match self.cm().maybe_resolve_path(&segments, Some(ns), &parent_scope, None) {
2299            PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
2300            PathResult::NonModule(path_res) => {
2301                path_res.full_res().filter(|res| !matches!(res, Res::Def(DefKind::Ctor(..), _)))
2302            }
2303            PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
2304                None
2305            }
2306            PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
2307        }
2308    }
2309
2310    /// Retrieves definition span of the given `DefId`.
2311    fn def_span(&self, def_id: DefId) -> Span {
2312        match def_id.as_local() {
2313            Some(def_id) => self.tcx.source_span(def_id),
2314            // Query `def_span` is not used because hashing its result span is expensive.
2315            None => self.cstore().def_span_untracked(def_id, self.tcx.sess),
2316        }
2317    }
2318
2319    fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
2320        match def_id.as_local() {
2321            Some(def_id) => self.field_names.get(&def_id).cloned(),
2322            None => Some(
2323                self.tcx
2324                    .associated_item_def_ids(def_id)
2325                    .iter()
2326                    .map(|&def_id| {
2327                        Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
2328                    })
2329                    .collect(),
2330            ),
2331        }
2332    }
2333
2334    fn field_defaults(&self, def_id: DefId) -> Option<Vec<Symbol>> {
2335        match def_id.as_local() {
2336            Some(def_id) => self.field_defaults.get(&def_id).cloned(),
2337            None => Some(
2338                self.tcx
2339                    .associated_item_def_ids(def_id)
2340                    .iter()
2341                    .filter_map(|&def_id| {
2342                        self.tcx.default_field(def_id).map(|_| self.tcx.item_name(def_id))
2343                    })
2344                    .collect(),
2345            ),
2346        }
2347    }
2348
2349    /// Checks if an expression refers to a function marked with
2350    /// `#[rustc_legacy_const_generics]` and returns the argument index list
2351    /// from the attribute.
2352    fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
2353        if let ExprKind::Path(None, path) = &expr.kind {
2354            // Don't perform legacy const generics rewriting if the path already
2355            // has generic arguments.
2356            if path.segments.last().unwrap().args.is_some() {
2357                return None;
2358            }
2359
2360            let res = self.partial_res_map.get(&expr.id)?.full_res()?;
2361            if let Res::Def(def::DefKind::Fn, def_id) = res {
2362                // We only support cross-crate argument rewriting. Uses
2363                // within the same crate should be updated to use the new
2364                // const generics style.
2365                if def_id.is_local() {
2366                    return None;
2367                }
2368
2369                if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
2370                    return v.clone();
2371                }
2372
2373                let attr = self.tcx.get_attr(def_id, sym::rustc_legacy_const_generics)?;
2374                let mut ret = Vec::new();
2375                for meta in attr.meta_item_list()? {
2376                    match meta.lit()?.kind {
2377                        LitKind::Int(a, _) => ret.push(a.get() as usize),
2378                        _ => panic!("invalid arg index"),
2379                    }
2380                }
2381                // Cache the lookup to avoid parsing attributes for an item multiple times.
2382                self.legacy_const_generic_args.insert(def_id, Some(ret.clone()));
2383                return Some(ret);
2384            }
2385        }
2386        None
2387    }
2388
2389    fn resolve_main(&mut self) {
2390        let module = self.graph_root;
2391        let ident = Ident::with_dummy_span(sym::main);
2392        let parent_scope = &ParentScope::module(module, self.arenas);
2393
2394        let Ok(name_binding) = self.cm().maybe_resolve_ident_in_module(
2395            ModuleOrUniformRoot::Module(module),
2396            ident,
2397            ValueNS,
2398            parent_scope,
2399            None,
2400        ) else {
2401            return;
2402        };
2403
2404        let res = name_binding.res();
2405        let is_import = name_binding.is_import();
2406        let span = name_binding.span;
2407        if let Res::Def(DefKind::Fn, _) = res {
2408            self.record_use(ident, name_binding, Used::Other);
2409        }
2410        self.main_def = Some(MainDefinition { res, is_import, span });
2411    }
2412}
2413
2414fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2415    let mut result = String::new();
2416    for (i, name) in names.filter(|name| *name != kw::PathRoot).enumerate() {
2417        if i > 0 {
2418            result.push_str("::");
2419        }
2420        if Ident::with_dummy_span(name).is_raw_guess() {
2421            result.push_str("r#");
2422        }
2423        result.push_str(name.as_str());
2424    }
2425    result
2426}
2427
2428fn path_names_to_string(path: &Path) -> String {
2429    names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2430}
2431
2432/// A somewhat inefficient routine to obtain the name of a module.
2433fn module_to_string(mut module: Module<'_>) -> Option<String> {
2434    let mut names = Vec::new();
2435    loop {
2436        if let ModuleKind::Def(.., name) = module.kind {
2437            if let Some(parent) = module.parent {
2438                // `unwrap` is safe: the presence of a parent means it's not the crate root.
2439                names.push(name.unwrap());
2440                module = parent
2441            } else {
2442                break;
2443            }
2444        } else {
2445            names.push(sym::opaque_module_name_placeholder);
2446            let Some(parent) = module.parent else {
2447                return None;
2448            };
2449            module = parent;
2450        }
2451    }
2452    if names.is_empty() {
2453        return None;
2454    }
2455    Some(names_to_string(names.iter().rev().copied()))
2456}
2457
2458#[derive(Copy, Clone, Debug)]
2459struct Finalize {
2460    /// Node ID for linting.
2461    node_id: NodeId,
2462    /// Span of the whole path or some its characteristic fragment.
2463    /// E.g. span of `b` in `foo::{a, b, c}`, or full span for regular paths.
2464    path_span: Span,
2465    /// Span of the path start, suitable for prepending something to it.
2466    /// E.g. span of `foo` in `foo::{a, b, c}`, or full span for regular paths.
2467    root_span: Span,
2468    /// Whether to report privacy errors or silently return "no resolution" for them,
2469    /// similarly to speculative resolution.
2470    report_private: bool,
2471    /// Tracks whether an item is used in scope or used relatively to a module.
2472    used: Used,
2473}
2474
2475impl Finalize {
2476    fn new(node_id: NodeId, path_span: Span) -> Finalize {
2477        Finalize::with_root_span(node_id, path_span, path_span)
2478    }
2479
2480    fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2481        Finalize { node_id, path_span, root_span, report_private: true, used: Used::Other }
2482    }
2483}
2484
2485pub fn provide(providers: &mut Providers) {
2486    providers.registered_tools = macros::registered_tools;
2487}
2488
2489mod ref_mut {
2490    use std::ops::Deref;
2491
2492    /// A wrapper around a mutable reference that conditionally allows mutable access.
2493    pub(crate) struct RefOrMut<'a, T> {
2494        p: &'a mut T,
2495        mutable: bool,
2496    }
2497
2498    impl<'a, T> Deref for RefOrMut<'a, T> {
2499        type Target = T;
2500
2501        fn deref(&self) -> &Self::Target {
2502            self.p
2503        }
2504    }
2505
2506    impl<'a, T> AsRef<T> for RefOrMut<'a, T> {
2507        fn as_ref(&self) -> &T {
2508            self.p
2509        }
2510    }
2511
2512    impl<'a, T> RefOrMut<'a, T> {
2513        pub(crate) fn new(p: &'a mut T, mutable: bool) -> Self {
2514            RefOrMut { p, mutable }
2515        }
2516
2517        /// This is needed because this wraps a `&mut T` and is therefore not `Copy`.
2518        pub(crate) fn reborrow(&mut self) -> RefOrMut<'_, T> {
2519            RefOrMut { p: self.p, mutable: self.mutable }
2520        }
2521
2522        /// Returns a mutable reference to the inner value if allowed.
2523        ///
2524        /// # Panics
2525        /// Panics if the `mutable` flag is false.
2526        #[track_caller]
2527        pub(crate) fn get_mut(&mut self) -> &mut T {
2528            match self.mutable {
2529                false => panic!("Can't mutably borrow speculative resolver"),
2530                true => self.p,
2531            }
2532        }
2533
2534        /// Returns a mutable reference to the inner value without checking if
2535        /// it's in a mutable state.
2536        pub(crate) fn get_mut_unchecked(&mut self) -> &mut T {
2537            self.p
2538        }
2539    }
2540}
2541
2542/// A wrapper around `&mut Resolver` that may be mutable or immutable, depending on a conditions.
2543///
2544/// `Cm` stands for "conditionally mutable".
2545///
2546/// Prefer constructing it through [`Resolver::cm`] to ensure correctness.
2547type CmResolver<'r, 'ra, 'tcx> = ref_mut::RefOrMut<'r, Resolver<'ra, 'tcx>>;