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(ptr_as_ref_unchecked)]
23#![feature(rustc_attrs)]
24#![feature(rustdoc_internals)]
25#![recursion_limit = "256"]
26// tidy-alphabetical-end
27
28use std::cell::{Cell, Ref, RefCell};
29use std::collections::BTreeSet;
30use std::fmt::{self};
31use std::sync::Arc;
32
33use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion};
34use effective_visibilities::EffectiveVisibilitiesVisitor;
35use errors::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};
36use imports::{Import, ImportData, ImportKind, NameResolution, PendingBinding};
37use late::{
38    ForwardGenericParamBanReason, HasGenericParams, PathSource, PatternSource,
39    UnnecessaryQualification,
40};
41use macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef};
42use rustc_arena::{DroplessArena, TypedArena};
43use rustc_ast::node_id::NodeMap;
44use rustc_ast::{
45    self as ast, AngleBracketedArg, CRATE_NODE_ID, Crate, Expr, ExprKind, GenericArg, GenericArgs,
46    LitKind, NodeId, Path, attr,
47};
48use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap, FxIndexSet};
49use rustc_data_structures::intern::Interned;
50use rustc_data_structures::steal::Steal;
51use rustc_data_structures::sync::{FreezeReadGuard, FreezeWriteGuard};
52use rustc_data_structures::unord::{UnordMap, UnordSet};
53use rustc_errors::{Applicability, Diag, ErrCode, ErrorGuaranteed, LintBuffer};
54use rustc_expand::base::{DeriveResolution, SyntaxExtension, SyntaxExtensionKind};
55use rustc_feature::BUILTIN_ATTRIBUTES;
56use rustc_hir::attrs::StrippedCfgItem;
57use rustc_hir::def::Namespace::{self, *};
58use rustc_hir::def::{
59    self, CtorOf, DefKind, DocLinkResMap, LifetimeRes, MacroKinds, NonMacroAttrKind, PartialRes,
60    PerNS,
61};
62use rustc_hir::def_id::{CRATE_DEF_ID, CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalDefIdMap};
63use rustc_hir::definitions::DisambiguatorState;
64use rustc_hir::{PrimTy, TraitCandidate};
65use rustc_index::bit_set::DenseBitSet;
66use rustc_metadata::creader::CStore;
67use rustc_middle::metadata::ModChild;
68use rustc_middle::middle::privacy::EffectiveVisibilities;
69use rustc_middle::query::Providers;
70use rustc_middle::span_bug;
71use rustc_middle::ty::{
72    self, DelegationFnSig, Feed, MainDefinition, RegisteredTools, ResolverAstLowering,
73    ResolverGlobalCtxt, TyCtxt, TyCtxtFeed, Visibility,
74};
75use rustc_query_system::ich::StableHashingContext;
76use rustc_session::lint::BuiltinLintDiag;
77use rustc_session::lint::builtin::PRIVATE_MACRO_USE;
78use rustc_span::hygiene::{ExpnId, LocalExpnId, MacroKind, SyntaxContext, Transparency};
79use rustc_span::{DUMMY_SP, Ident, Macros20NormalizedIdent, Span, Symbol, kw, sym};
80use smallvec::{SmallVec, smallvec};
81use tracing::debug;
82
83type Res = def::Res<NodeId>;
84
85mod build_reduced_graph;
86mod check_unused;
87mod def_collector;
88mod diagnostics;
89mod effective_visibilities;
90mod errors;
91mod ident;
92mod imports;
93mod late;
94mod macros;
95pub mod rustdoc;
96
97pub use macros::registered_tools_ast;
98
99use crate::ref_mut::{CmCell, CmRefCell};
100
101rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
102
103#[derive(Debug)]
104enum Weak {
105    Yes,
106    No,
107}
108
109#[derive(Copy, Clone, PartialEq, Debug)]
110enum Determinacy {
111    Determined,
112    Undetermined,
113}
114
115impl Determinacy {
116    fn determined(determined: bool) -> Determinacy {
117        if determined { Determinacy::Determined } else { Determinacy::Undetermined }
118    }
119}
120
121/// A specific scope in which a name can be looked up.
122#[derive(Clone, Copy, Debug)]
123enum Scope<'ra> {
124    /// Inert attributes registered by derive macros.
125    DeriveHelpers(LocalExpnId),
126    /// Inert attributes registered by derive macros, but used before they are actually declared.
127    /// This scope will exist until the compatibility lint `LEGACY_DERIVE_HELPERS`
128    /// is turned into a hard error.
129    DeriveHelpersCompat,
130    /// Textual `let`-like scopes introduced by `macro_rules!` items.
131    MacroRules(MacroRulesScopeRef<'ra>),
132    /// Names declared in the given module.
133    /// The node ID is for reporting the `PROC_MACRO_DERIVE_RESOLUTION_FALLBACK`
134    /// lint if it should be reported.
135    Module(Module<'ra>, Option<NodeId>),
136    /// Names introduced by `#[macro_use]` attributes on `extern crate` items.
137    MacroUsePrelude,
138    /// Built-in attributes.
139    BuiltinAttrs,
140    /// Extern prelude names introduced by `extern crate` items.
141    ExternPreludeItems,
142    /// Extern prelude names introduced by `--extern` flags.
143    ExternPreludeFlags,
144    /// Tool modules introduced with `#![register_tool]`.
145    ToolPrelude,
146    /// Standard library prelude introduced with an internal `#[prelude_import]` import.
147    StdLibPrelude,
148    /// Built-in types.
149    BuiltinTypes,
150}
151
152/// Names from different contexts may want to visit different subsets of all specific scopes
153/// with different restrictions when looking up the resolution.
154#[derive(Clone, Copy, Debug)]
155enum ScopeSet<'ra> {
156    /// All scopes with the given namespace.
157    All(Namespace),
158    /// A module, then extern prelude (used for mixed 2015-2018 mode in macros).
159    ModuleAndExternPrelude(Namespace, Module<'ra>),
160    /// Just two extern prelude scopes.
161    ExternPrelude,
162    /// Same as `All(MacroNS)`, but with the given macro kind restriction.
163    Macro(MacroKind),
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: Vec<(Span, ast::Pat)>,
237    target: Vec<ast::Pat>,
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>, // FIXME(parallel): Use an atomic in parallel import resolution
599    /// Used to disambiguate underscore items (`const _: T = ...`) in the module.
600    underscore_disambiguator: CmCell<u32>,
601
602    /// Macro invocations that can expand into items in this module.
603    unexpanded_invocations: CmRefCell<FxHashSet<LocalExpnId>>,
604
605    /// Whether `#[no_implicit_prelude]` is active.
606    no_implicit_prelude: bool,
607
608    glob_importers: CmRefCell<Vec<Import<'ra>>>,
609    globs: CmRefCell<Vec<Import<'ra>>>,
610
611    /// Used to memoize the traits in this module for faster searches through all traits in scope.
612    traits:
613        CmRefCell<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: CmCell::new(0),
663            unexpanded_invocations: Default::default(),
664            no_implicit_prelude,
665            glob_importers: CmRefCell::new(Vec::new()),
666            globs: CmRefCell::new(Vec::new()),
667            traits: CmRefCell::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(resolver.as_ref());
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
1031struct ExternPreludeEntry<'ra> {
1032    /// Binding from an `extern crate` item.
1033    /// The boolean flag is true is `item_binding` is non-redundant, happens either when
1034    /// `flag_binding` is `None`, or when `extern crate` introducing `item_binding` used renaming.
1035    item_binding: Option<(NameBinding<'ra>, /* introduced by item */ bool)>,
1036    /// Binding from an `--extern` flag, lazily populated on first use.
1037    flag_binding: Option<Cell<(PendingBinding<'ra>, /* finalized */ bool)>>,
1038}
1039
1040impl ExternPreludeEntry<'_> {
1041    fn introduced_by_item(&self) -> bool {
1042        matches!(self.item_binding, Some((_, true)))
1043    }
1044
1045    fn flag() -> Self {
1046        ExternPreludeEntry {
1047            item_binding: None,
1048            flag_binding: Some(Cell::new((PendingBinding::Pending, false))),
1049        }
1050    }
1051}
1052
1053struct DeriveData {
1054    resolutions: Vec<DeriveResolution>,
1055    helper_attrs: Vec<(usize, Ident)>,
1056    has_derive_copy: bool,
1057}
1058
1059struct MacroData {
1060    ext: Arc<SyntaxExtension>,
1061    nrules: usize,
1062    macro_rules: bool,
1063}
1064
1065impl MacroData {
1066    fn new(ext: Arc<SyntaxExtension>) -> MacroData {
1067        MacroData { ext, nrules: 0, macro_rules: false }
1068    }
1069}
1070
1071pub struct ResolverOutputs {
1072    pub global_ctxt: ResolverGlobalCtxt,
1073    pub ast_lowering: ResolverAstLowering,
1074}
1075
1076/// The main resolver class.
1077///
1078/// This is the visitor that walks the whole crate.
1079pub struct Resolver<'ra, 'tcx> {
1080    tcx: TyCtxt<'tcx>,
1081
1082    /// Item with a given `LocalDefId` was defined during macro expansion with ID `ExpnId`.
1083    expn_that_defined: UnordMap<LocalDefId, ExpnId>,
1084
1085    graph_root: Module<'ra>,
1086
1087    /// Assert that we are in speculative resolution mode.
1088    assert_speculative: bool,
1089
1090    prelude: Option<Module<'ra>> = None,
1091    extern_prelude: FxIndexMap<Macros20NormalizedIdent, ExternPreludeEntry<'ra>>,
1092
1093    /// N.B., this is used only for better diagnostics, not name resolution itself.
1094    field_names: LocalDefIdMap<Vec<Ident>>,
1095    field_defaults: LocalDefIdMap<Vec<Symbol>>,
1096
1097    /// Span of the privacy modifier in fields of an item `DefId` accessible with dot syntax.
1098    /// Used for hints during error reporting.
1099    field_visibility_spans: FxHashMap<DefId, Vec<Span>>,
1100
1101    /// All imports known to succeed or fail.
1102    determined_imports: Vec<Import<'ra>> = Vec::new(),
1103
1104    /// All non-determined imports.
1105    indeterminate_imports: Vec<Import<'ra>> = Vec::new(),
1106
1107    // Spans for local variables found during pattern resolution.
1108    // Used for suggestions during error reporting.
1109    pat_span_map: NodeMap<Span>,
1110
1111    /// Resolutions for nodes that have a single resolution.
1112    partial_res_map: NodeMap<PartialRes>,
1113    /// Resolutions for import nodes, which have multiple resolutions in different namespaces.
1114    import_res_map: NodeMap<PerNS<Option<Res>>>,
1115    /// An import will be inserted into this map if it has been used.
1116    import_use_map: FxHashMap<Import<'ra>, Used>,
1117    /// Resolutions for labels (node IDs of their corresponding blocks or loops).
1118    label_res_map: NodeMap<NodeId>,
1119    /// Resolutions for lifetimes.
1120    lifetimes_res_map: NodeMap<LifetimeRes>,
1121    /// Lifetime parameters that lowering will have to introduce.
1122    extra_lifetime_params_map: NodeMap<Vec<(Ident, NodeId, LifetimeRes)>>,
1123
1124    /// `CrateNum` resolutions of `extern crate` items.
1125    extern_crate_map: UnordMap<LocalDefId, CrateNum>,
1126    module_children: LocalDefIdMap<Vec<ModChild>>,
1127    trait_map: NodeMap<Vec<TraitCandidate>>,
1128
1129    /// A map from nodes to anonymous modules.
1130    /// Anonymous modules are pseudo-modules that are implicitly created around items
1131    /// contained within blocks.
1132    ///
1133    /// For example, if we have this:
1134    ///
1135    ///  fn f() {
1136    ///      fn g() {
1137    ///          ...
1138    ///      }
1139    ///  }
1140    ///
1141    /// There will be an anonymous module created around `g` with the ID of the
1142    /// entry block for `f`.
1143    block_map: NodeMap<Module<'ra>>,
1144    /// A fake module that contains no definition and no prelude. Used so that
1145    /// some AST passes can generate identifiers that only resolve to local or
1146    /// lang items.
1147    empty_module: Module<'ra>,
1148    /// Eagerly populated map of all local non-block modules.
1149    local_module_map: FxIndexMap<LocalDefId, Module<'ra>>,
1150    /// Lazily populated cache of modules loaded from external crates.
1151    extern_module_map: RefCell<FxIndexMap<DefId, Module<'ra>>>,
1152    binding_parent_modules: FxHashMap<NameBinding<'ra>, Module<'ra>>,
1153
1154    /// Maps glob imports to the names of items actually imported.
1155    glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
1156    glob_error: Option<ErrorGuaranteed> = None,
1157    visibilities_for_hashing: Vec<(LocalDefId, Visibility)> = Vec::new(),
1158    used_imports: FxHashSet<NodeId>,
1159    maybe_unused_trait_imports: FxIndexSet<LocalDefId>,
1160
1161    /// Privacy errors are delayed until the end in order to deduplicate them.
1162    privacy_errors: Vec<PrivacyError<'ra>> = Vec::new(),
1163    /// Ambiguity errors are delayed for deduplication.
1164    ambiguity_errors: Vec<AmbiguityError<'ra>> = Vec::new(),
1165    /// `use` injections are delayed for better placement and deduplication.
1166    use_injections: Vec<UseError<'tcx>> = Vec::new(),
1167    /// Crate-local macro expanded `macro_export` referred to by a module-relative path.
1168    macro_expanded_macro_export_errors: BTreeSet<(Span, Span)> = BTreeSet::new(),
1169
1170    /// When a type is re-exported that has an inaccessible constructor because it has fields that
1171    /// are inaccessible from the import's scope, we mark that as the type won't be able to be built
1172    /// through the re-export. We use this information to extend the existing diagnostic.
1173    inaccessible_ctor_reexport: FxHashMap<Span, Span>,
1174
1175    arenas: &'ra ResolverArenas<'ra>,
1176    dummy_binding: NameBinding<'ra>,
1177    builtin_types_bindings: FxHashMap<Symbol, NameBinding<'ra>>,
1178    builtin_attrs_bindings: FxHashMap<Symbol, NameBinding<'ra>>,
1179    registered_tool_bindings: FxHashMap<Ident, NameBinding<'ra>>,
1180    macro_names: FxHashSet<Ident>,
1181    builtin_macros: FxHashMap<Symbol, SyntaxExtensionKind>,
1182    registered_tools: &'tcx RegisteredTools,
1183    macro_use_prelude: FxIndexMap<Symbol, NameBinding<'ra>>,
1184    /// Eagerly populated map of all local macro definitions.
1185    local_macro_map: FxHashMap<LocalDefId, &'ra MacroData>,
1186    /// Lazily populated cache of macro definitions loaded from external crates.
1187    extern_macro_map: RefCell<FxHashMap<DefId, &'ra MacroData>>,
1188    dummy_ext_bang: Arc<SyntaxExtension>,
1189    dummy_ext_derive: Arc<SyntaxExtension>,
1190    non_macro_attr: &'ra MacroData,
1191    local_macro_def_scopes: FxHashMap<LocalDefId, Module<'ra>>,
1192    ast_transform_scopes: FxHashMap<LocalExpnId, Module<'ra>>,
1193    unused_macros: FxIndexMap<LocalDefId, (NodeId, Ident)>,
1194    /// A map from the macro to all its potentially unused arms.
1195    unused_macro_rules: FxIndexMap<NodeId, DenseBitSet<usize>>,
1196    proc_macro_stubs: FxHashSet<LocalDefId>,
1197    /// Traces collected during macro resolution and validated when it's complete.
1198    // FIXME: Remove interior mutability when speculative resolution produces these as outputs.
1199    single_segment_macro_resolutions:
1200        RefCell<Vec<(Ident, MacroKind, ParentScope<'ra>, Option<NameBinding<'ra>>, Option<Span>)>>,
1201    multi_segment_macro_resolutions:
1202        RefCell<Vec<(Vec<Segment>, Span, MacroKind, ParentScope<'ra>, Option<Res>, Namespace)>>,
1203    builtin_attrs: Vec<(Ident, ParentScope<'ra>)>,
1204    /// `derive(Copy)` marks items they are applied to so they are treated specially later.
1205    /// Derive macros cannot modify the item themselves and have to store the markers in the global
1206    /// context, so they attach the markers to derive container IDs using this resolver table.
1207    containers_deriving_copy: FxHashSet<LocalExpnId>,
1208    /// Parent scopes in which the macros were invoked.
1209    /// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere.
1210    invocation_parent_scopes: FxHashMap<LocalExpnId, ParentScope<'ra>>,
1211    /// `macro_rules` scopes *produced* by expanding the macro invocations,
1212    /// include all the `macro_rules` items and other invocations generated by them.
1213    output_macro_rules_scopes: FxHashMap<LocalExpnId, MacroRulesScopeRef<'ra>>,
1214    /// `macro_rules` scopes produced by `macro_rules` item definitions.
1215    macro_rules_scopes: FxHashMap<LocalDefId, MacroRulesScopeRef<'ra>>,
1216    /// Helper attributes that are in scope for the given expansion.
1217    helper_attrs: FxHashMap<LocalExpnId, Vec<(Ident, NameBinding<'ra>)>>,
1218    /// Ready or in-progress results of resolving paths inside the `#[derive(...)]` attribute
1219    /// with the given `ExpnId`.
1220    derive_data: FxHashMap<LocalExpnId, DeriveData>,
1221
1222    /// Avoid duplicated errors for "name already defined".
1223    name_already_seen: FxHashMap<Symbol, Span>,
1224
1225    potentially_unused_imports: Vec<Import<'ra>> = Vec::new(),
1226
1227    potentially_unnecessary_qualifications: Vec<UnnecessaryQualification<'ra>> = Vec::new(),
1228
1229    /// Table for mapping struct IDs into struct constructor IDs,
1230    /// it's not used during normal resolution, only for better error reporting.
1231    /// Also includes of list of each fields visibility
1232    struct_constructors: LocalDefIdMap<(Res, Visibility<DefId>, Vec<Visibility<DefId>>)>,
1233
1234    lint_buffer: LintBuffer,
1235
1236    next_node_id: NodeId = CRATE_NODE_ID,
1237
1238    node_id_to_def_id: NodeMap<Feed<'tcx, LocalDefId>>,
1239
1240    disambiguator: DisambiguatorState,
1241
1242    /// Indices of unnamed struct or variant fields with unresolved attributes.
1243    placeholder_field_indices: FxHashMap<NodeId, usize>,
1244    /// When collecting definitions from an AST fragment produced by a macro invocation `ExpnId`
1245    /// we know what parent node that fragment should be attached to thanks to this table,
1246    /// and how the `impl Trait` fragments were introduced.
1247    invocation_parents: FxHashMap<LocalExpnId, InvocationParent>,
1248
1249    legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
1250    /// Amount of lifetime parameters for each item in the crate.
1251    item_generics_num_lifetimes: FxHashMap<LocalDefId, usize>,
1252    delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
1253
1254    main_def: Option<MainDefinition> = None,
1255    trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1256    /// A list of proc macro LocalDefIds, written out in the order in which
1257    /// they are declared in the static array generated by proc_macro_harness.
1258    proc_macros: Vec<LocalDefId> = Vec::new(),
1259    confused_type_with_std_module: FxIndexMap<Span, Span>,
1260    /// Whether lifetime elision was successful.
1261    lifetime_elision_allowed: FxHashSet<NodeId>,
1262
1263    /// Names of items that were stripped out via cfg with their corresponding cfg meta item.
1264    stripped_cfg_items: Vec<StrippedCfgItem<NodeId>> = Vec::new(),
1265
1266    effective_visibilities: EffectiveVisibilities,
1267    doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
1268    doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
1269    all_macro_rules: UnordSet<Symbol>,
1270
1271    /// Invocation ids of all glob delegations.
1272    glob_delegation_invoc_ids: FxHashSet<LocalExpnId>,
1273    /// Analogue of module `unexpanded_invocations` but in trait impls, excluding glob delegations.
1274    /// Needed because glob delegations wait for all other neighboring macros to expand.
1275    impl_unexpanded_invocations: FxHashMap<LocalDefId, FxHashSet<LocalExpnId>>,
1276    /// Simplified analogue of module `resolutions` but in trait impls, excluding glob delegations.
1277    /// Needed because glob delegations exclude explicitly defined names.
1278    impl_binding_keys: FxHashMap<LocalDefId, FxHashSet<BindingKey>>,
1279
1280    /// This is the `Span` where an `extern crate foo;` suggestion would be inserted, if `foo`
1281    /// could be a crate that wasn't imported. For diagnostics use only.
1282    current_crate_outer_attr_insert_span: Span,
1283
1284    mods_with_parse_errors: FxHashSet<DefId>,
1285
1286    /// Whether `Resolver::register_macros_for_all_crates` has been called once already, as we
1287    /// don't need to run it more than once.
1288    all_crate_macros_already_registered: bool = false,
1289
1290    // Stores pre-expansion and pre-placeholder-fragment-insertion names for `impl Trait` types
1291    // that were encountered during resolution. These names are used to generate item names
1292    // for APITs, so we don't want to leak details of resolution into these names.
1293    impl_trait_names: FxHashMap<NodeId, Symbol>,
1294}
1295
1296/// This provides memory for the rest of the crate. The `'ra` lifetime that is
1297/// used by many types in this crate is an abbreviation of `ResolverArenas`.
1298#[derive(Default)]
1299pub struct ResolverArenas<'ra> {
1300    modules: TypedArena<ModuleData<'ra>>,
1301    local_modules: RefCell<Vec<Module<'ra>>>,
1302    imports: TypedArena<ImportData<'ra>>,
1303    name_resolutions: TypedArena<RefCell<NameResolution<'ra>>>,
1304    ast_paths: TypedArena<ast::Path>,
1305    macros: TypedArena<MacroData>,
1306    dropless: DroplessArena,
1307}
1308
1309impl<'ra> ResolverArenas<'ra> {
1310    fn new_res_binding(
1311        &'ra self,
1312        res: Res,
1313        vis: Visibility<DefId>,
1314        span: Span,
1315        expansion: LocalExpnId,
1316    ) -> NameBinding<'ra> {
1317        self.alloc_name_binding(NameBindingData {
1318            kind: NameBindingKind::Res(res),
1319            ambiguity: None,
1320            warn_ambiguity: false,
1321            vis,
1322            span,
1323            expansion,
1324        })
1325    }
1326
1327    fn new_pub_res_binding(
1328        &'ra self,
1329        res: Res,
1330        span: Span,
1331        expn_id: LocalExpnId,
1332    ) -> NameBinding<'ra> {
1333        self.new_res_binding(res, Visibility::Public, span, expn_id)
1334    }
1335
1336    fn new_module(
1337        &'ra self,
1338        parent: Option<Module<'ra>>,
1339        kind: ModuleKind,
1340        expn_id: ExpnId,
1341        span: Span,
1342        no_implicit_prelude: bool,
1343    ) -> Module<'ra> {
1344        let (def_id, self_binding) = match kind {
1345            ModuleKind::Def(def_kind, def_id, _) => (
1346                Some(def_id),
1347                Some(self.new_pub_res_binding(Res::Def(def_kind, def_id), span, LocalExpnId::ROOT)),
1348            ),
1349            ModuleKind::Block => (None, None),
1350        };
1351        let module = Module(Interned::new_unchecked(self.modules.alloc(ModuleData::new(
1352            parent,
1353            kind,
1354            expn_id,
1355            span,
1356            no_implicit_prelude,
1357            self_binding,
1358        ))));
1359        if def_id.is_none_or(|def_id| def_id.is_local()) {
1360            self.local_modules.borrow_mut().push(module);
1361        }
1362        module
1363    }
1364    fn local_modules(&'ra self) -> std::cell::Ref<'ra, Vec<Module<'ra>>> {
1365        self.local_modules.borrow()
1366    }
1367    fn alloc_name_binding(&'ra self, name_binding: NameBindingData<'ra>) -> NameBinding<'ra> {
1368        Interned::new_unchecked(self.dropless.alloc(name_binding))
1369    }
1370    fn alloc_import(&'ra self, import: ImportData<'ra>) -> Import<'ra> {
1371        Interned::new_unchecked(self.imports.alloc(import))
1372    }
1373    fn alloc_name_resolution(&'ra self) -> &'ra RefCell<NameResolution<'ra>> {
1374        self.name_resolutions.alloc(Default::default())
1375    }
1376    fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> {
1377        self.dropless.alloc(Cell::new(scope))
1378    }
1379    fn alloc_macro_rules_binding(
1380        &'ra self,
1381        binding: MacroRulesBinding<'ra>,
1382    ) -> &'ra MacroRulesBinding<'ra> {
1383        self.dropless.alloc(binding)
1384    }
1385    fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {
1386        self.ast_paths.alloc_from_iter(paths.iter().cloned())
1387    }
1388    fn alloc_macro(&'ra self, macro_data: MacroData) -> &'ra MacroData {
1389        self.macros.alloc(macro_data)
1390    }
1391    fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {
1392        self.dropless.alloc_from_iter(spans)
1393    }
1394}
1395
1396impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1397    fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
1398        self
1399    }
1400}
1401
1402impl<'ra, 'tcx> AsRef<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1403    fn as_ref(&self) -> &Resolver<'ra, 'tcx> {
1404        self
1405    }
1406}
1407
1408impl<'tcx> Resolver<'_, 'tcx> {
1409    fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1410        self.opt_feed(node).map(|f| f.key())
1411    }
1412
1413    fn local_def_id(&self, node: NodeId) -> LocalDefId {
1414        self.feed(node).key()
1415    }
1416
1417    fn opt_feed(&self, node: NodeId) -> Option<Feed<'tcx, LocalDefId>> {
1418        self.node_id_to_def_id.get(&node).copied()
1419    }
1420
1421    fn feed(&self, node: NodeId) -> Feed<'tcx, LocalDefId> {
1422        self.opt_feed(node).unwrap_or_else(|| panic!("no entry for node id: `{node:?}`"))
1423    }
1424
1425    fn local_def_kind(&self, node: NodeId) -> DefKind {
1426        self.tcx.def_kind(self.local_def_id(node))
1427    }
1428
1429    /// Adds a definition with a parent definition.
1430    fn create_def(
1431        &mut self,
1432        parent: LocalDefId,
1433        node_id: ast::NodeId,
1434        name: Option<Symbol>,
1435        def_kind: DefKind,
1436        expn_id: ExpnId,
1437        span: Span,
1438    ) -> TyCtxtFeed<'tcx, LocalDefId> {
1439        assert!(
1440            !self.node_id_to_def_id.contains_key(&node_id),
1441            "adding a def for node-id {:?}, name {:?}, data {:?} but a previous def exists: {:?}",
1442            node_id,
1443            name,
1444            def_kind,
1445            self.tcx.definitions_untracked().def_key(self.node_id_to_def_id[&node_id].key()),
1446        );
1447
1448        // FIXME: remove `def_span` body, pass in the right spans here and call `tcx.at().create_def()`
1449        let feed = self.tcx.create_def(parent, name, def_kind, None, &mut self.disambiguator);
1450        let def_id = feed.def_id();
1451
1452        // Create the definition.
1453        if expn_id != ExpnId::root() {
1454            self.expn_that_defined.insert(def_id, expn_id);
1455        }
1456
1457        // A relative span's parent must be an absolute span.
1458        debug_assert_eq!(span.data_untracked().parent, None);
1459        let _id = self.tcx.untracked().source_span.push(span);
1460        debug_assert_eq!(_id, def_id);
1461
1462        // Some things for which we allocate `LocalDefId`s don't correspond to
1463        // anything in the AST, so they don't have a `NodeId`. For these cases
1464        // we don't need a mapping from `NodeId` to `LocalDefId`.
1465        if node_id != ast::DUMMY_NODE_ID {
1466            debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1467            self.node_id_to_def_id.insert(node_id, feed.downgrade());
1468        }
1469
1470        feed
1471    }
1472
1473    fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1474        if let Some(def_id) = def_id.as_local() {
1475            self.item_generics_num_lifetimes[&def_id]
1476        } else {
1477            self.tcx.generics_of(def_id).own_counts().lifetimes
1478        }
1479    }
1480
1481    pub fn tcx(&self) -> TyCtxt<'tcx> {
1482        self.tcx
1483    }
1484
1485    /// This function is very slow, as it iterates over the entire
1486    /// [Resolver::node_id_to_def_id] map just to find the [NodeId]
1487    /// that corresponds to the given [LocalDefId]. Only use this in
1488    /// diagnostics code paths.
1489    fn def_id_to_node_id(&self, def_id: LocalDefId) -> NodeId {
1490        self.node_id_to_def_id
1491            .items()
1492            .filter(|(_, v)| v.key() == def_id)
1493            .map(|(k, _)| *k)
1494            .get_only()
1495            .unwrap()
1496    }
1497}
1498
1499impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
1500    pub fn new(
1501        tcx: TyCtxt<'tcx>,
1502        attrs: &[ast::Attribute],
1503        crate_span: Span,
1504        current_crate_outer_attr_insert_span: Span,
1505        arenas: &'ra ResolverArenas<'ra>,
1506    ) -> Resolver<'ra, 'tcx> {
1507        let root_def_id = CRATE_DEF_ID.to_def_id();
1508        let mut local_module_map = FxIndexMap::default();
1509        let graph_root = arenas.new_module(
1510            None,
1511            ModuleKind::Def(DefKind::Mod, root_def_id, None),
1512            ExpnId::root(),
1513            crate_span,
1514            attr::contains_name(attrs, sym::no_implicit_prelude),
1515        );
1516        local_module_map.insert(CRATE_DEF_ID, graph_root);
1517        let empty_module = arenas.new_module(
1518            None,
1519            ModuleKind::Def(DefKind::Mod, root_def_id, None),
1520            ExpnId::root(),
1521            DUMMY_SP,
1522            true,
1523        );
1524
1525        let mut node_id_to_def_id = NodeMap::default();
1526        let crate_feed = tcx.create_local_crate_def_id(crate_span);
1527
1528        crate_feed.def_kind(DefKind::Mod);
1529        let crate_feed = crate_feed.downgrade();
1530        node_id_to_def_id.insert(CRATE_NODE_ID, crate_feed);
1531
1532        let mut invocation_parents = FxHashMap::default();
1533        invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);
1534
1535        let mut extern_prelude: FxIndexMap<_, _> = tcx
1536            .sess
1537            .opts
1538            .externs
1539            .iter()
1540            .filter_map(|(name, entry)| {
1541                // Make sure `self`, `super`, `_` etc do not get into extern prelude.
1542                // FIXME: reject `--extern self` and similar in option parsing instead.
1543                if entry.add_prelude
1544                    && let name = Symbol::intern(name)
1545                    && name.can_be_raw()
1546                {
1547                    let ident = Macros20NormalizedIdent::with_dummy_span(name);
1548                    Some((ident, ExternPreludeEntry::flag()))
1549                } else {
1550                    None
1551                }
1552            })
1553            .collect();
1554
1555        if !attr::contains_name(attrs, sym::no_core) {
1556            let ident = Macros20NormalizedIdent::with_dummy_span(sym::core);
1557            extern_prelude.insert(ident, ExternPreludeEntry::flag());
1558            if !attr::contains_name(attrs, sym::no_std) {
1559                let ident = Macros20NormalizedIdent::with_dummy_span(sym::std);
1560                extern_prelude.insert(ident, ExternPreludeEntry::flag());
1561            }
1562        }
1563
1564        let registered_tools = tcx.registered_tools(());
1565        let edition = tcx.sess.edition();
1566
1567        let mut resolver = Resolver {
1568            tcx,
1569
1570            expn_that_defined: Default::default(),
1571
1572            // The outermost module has def ID 0; this is not reflected in the
1573            // AST.
1574            graph_root,
1575            assert_speculative: false, // Only set/cleared in Resolver::resolve_imports for now
1576            prelude: None,
1577            extern_prelude,
1578
1579            field_names: Default::default(),
1580            field_defaults: Default::default(),
1581            field_visibility_spans: FxHashMap::default(),
1582
1583            pat_span_map: Default::default(),
1584            partial_res_map: Default::default(),
1585            import_res_map: Default::default(),
1586            import_use_map: Default::default(),
1587            label_res_map: Default::default(),
1588            lifetimes_res_map: Default::default(),
1589            extra_lifetime_params_map: Default::default(),
1590            extern_crate_map: Default::default(),
1591            module_children: Default::default(),
1592            trait_map: NodeMap::default(),
1593            empty_module,
1594            local_module_map,
1595            extern_module_map: Default::default(),
1596            block_map: Default::default(),
1597            binding_parent_modules: FxHashMap::default(),
1598            ast_transform_scopes: FxHashMap::default(),
1599
1600            glob_map: Default::default(),
1601            used_imports: FxHashSet::default(),
1602            maybe_unused_trait_imports: Default::default(),
1603            inaccessible_ctor_reexport: Default::default(),
1604
1605            arenas,
1606            dummy_binding: arenas.new_pub_res_binding(Res::Err, DUMMY_SP, LocalExpnId::ROOT),
1607            builtin_types_bindings: PrimTy::ALL
1608                .iter()
1609                .map(|prim_ty| {
1610                    let res = Res::PrimTy(*prim_ty);
1611                    let binding = arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT);
1612                    (prim_ty.name(), binding)
1613                })
1614                .collect(),
1615            builtin_attrs_bindings: BUILTIN_ATTRIBUTES
1616                .iter()
1617                .map(|builtin_attr| {
1618                    let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(builtin_attr.name));
1619                    let binding = arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT);
1620                    (builtin_attr.name, binding)
1621                })
1622                .collect(),
1623            registered_tool_bindings: registered_tools
1624                .iter()
1625                .map(|ident| {
1626                    let res = Res::ToolMod;
1627                    let binding = arenas.new_pub_res_binding(res, ident.span, LocalExpnId::ROOT);
1628                    (*ident, binding)
1629                })
1630                .collect(),
1631            macro_names: FxHashSet::default(),
1632            builtin_macros: Default::default(),
1633            registered_tools,
1634            macro_use_prelude: Default::default(),
1635            local_macro_map: Default::default(),
1636            extern_macro_map: Default::default(),
1637            dummy_ext_bang: Arc::new(SyntaxExtension::dummy_bang(edition)),
1638            dummy_ext_derive: Arc::new(SyntaxExtension::dummy_derive(edition)),
1639            non_macro_attr: arenas
1640                .alloc_macro(MacroData::new(Arc::new(SyntaxExtension::non_macro_attr(edition)))),
1641            invocation_parent_scopes: Default::default(),
1642            output_macro_rules_scopes: Default::default(),
1643            macro_rules_scopes: Default::default(),
1644            helper_attrs: Default::default(),
1645            derive_data: Default::default(),
1646            local_macro_def_scopes: FxHashMap::default(),
1647            name_already_seen: FxHashMap::default(),
1648            struct_constructors: Default::default(),
1649            unused_macros: Default::default(),
1650            unused_macro_rules: Default::default(),
1651            proc_macro_stubs: Default::default(),
1652            single_segment_macro_resolutions: Default::default(),
1653            multi_segment_macro_resolutions: Default::default(),
1654            builtin_attrs: Default::default(),
1655            containers_deriving_copy: Default::default(),
1656            lint_buffer: LintBuffer::default(),
1657            node_id_to_def_id,
1658            disambiguator: DisambiguatorState::new(),
1659            placeholder_field_indices: Default::default(),
1660            invocation_parents,
1661            legacy_const_generic_args: Default::default(),
1662            item_generics_num_lifetimes: Default::default(),
1663            trait_impls: Default::default(),
1664            confused_type_with_std_module: Default::default(),
1665            lifetime_elision_allowed: Default::default(),
1666            stripped_cfg_items: Default::default(),
1667            effective_visibilities: Default::default(),
1668            doc_link_resolutions: Default::default(),
1669            doc_link_traits_in_scope: Default::default(),
1670            all_macro_rules: Default::default(),
1671            delegation_fn_sigs: Default::default(),
1672            glob_delegation_invoc_ids: Default::default(),
1673            impl_unexpanded_invocations: Default::default(),
1674            impl_binding_keys: Default::default(),
1675            current_crate_outer_attr_insert_span,
1676            mods_with_parse_errors: Default::default(),
1677            impl_trait_names: Default::default(),
1678            ..
1679        };
1680
1681        let root_parent_scope = ParentScope::module(graph_root, resolver.arenas);
1682        resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1683        resolver.feed_visibility(crate_feed, Visibility::Public);
1684
1685        resolver
1686    }
1687
1688    fn new_local_module(
1689        &mut 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        if let Some(def_id) = module.opt_def_id() {
1698            self.local_module_map.insert(def_id.expect_local(), module);
1699        }
1700        module
1701    }
1702
1703    fn new_extern_module(
1704        &self,
1705        parent: Option<Module<'ra>>,
1706        kind: ModuleKind,
1707        expn_id: ExpnId,
1708        span: Span,
1709        no_implicit_prelude: bool,
1710    ) -> Module<'ra> {
1711        let module = self.arenas.new_module(parent, kind, expn_id, span, no_implicit_prelude);
1712        self.extern_module_map.borrow_mut().insert(module.def_id(), module);
1713        module
1714    }
1715
1716    fn new_local_macro(&mut self, def_id: LocalDefId, macro_data: MacroData) -> &'ra MacroData {
1717        let mac = self.arenas.alloc_macro(macro_data);
1718        self.local_macro_map.insert(def_id, mac);
1719        mac
1720    }
1721
1722    fn next_node_id(&mut self) -> NodeId {
1723        let start = self.next_node_id;
1724        let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1725        self.next_node_id = ast::NodeId::from_u32(next);
1726        start
1727    }
1728
1729    fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1730        let start = self.next_node_id;
1731        let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1732        self.next_node_id = ast::NodeId::from_usize(end);
1733        start..self.next_node_id
1734    }
1735
1736    pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1737        &mut self.lint_buffer
1738    }
1739
1740    pub fn arenas() -> ResolverArenas<'ra> {
1741        Default::default()
1742    }
1743
1744    fn feed_visibility(&mut self, feed: Feed<'tcx, LocalDefId>, vis: Visibility) {
1745        let feed = feed.upgrade(self.tcx);
1746        feed.visibility(vis.to_def_id());
1747        self.visibilities_for_hashing.push((feed.def_id(), vis));
1748    }
1749
1750    pub fn into_outputs(self) -> ResolverOutputs {
1751        let proc_macros = self.proc_macros;
1752        let expn_that_defined = self.expn_that_defined;
1753        let extern_crate_map = self.extern_crate_map;
1754        let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1755        let glob_map = self.glob_map;
1756        let main_def = self.main_def;
1757        let confused_type_with_std_module = self.confused_type_with_std_module;
1758        let effective_visibilities = self.effective_visibilities;
1759
1760        let stripped_cfg_items = self
1761            .stripped_cfg_items
1762            .into_iter()
1763            .filter_map(|item| {
1764                let parent_module =
1765                    self.node_id_to_def_id.get(&item.parent_module)?.key().to_def_id();
1766                Some(StrippedCfgItem { parent_module, ident: item.ident, cfg: item.cfg })
1767            })
1768            .collect();
1769
1770        let global_ctxt = ResolverGlobalCtxt {
1771            expn_that_defined,
1772            visibilities_for_hashing: self.visibilities_for_hashing,
1773            effective_visibilities,
1774            extern_crate_map,
1775            module_children: self.module_children,
1776            glob_map,
1777            maybe_unused_trait_imports,
1778            main_def,
1779            trait_impls: self.trait_impls,
1780            proc_macros,
1781            confused_type_with_std_module,
1782            doc_link_resolutions: self.doc_link_resolutions,
1783            doc_link_traits_in_scope: self.doc_link_traits_in_scope,
1784            all_macro_rules: self.all_macro_rules,
1785            stripped_cfg_items,
1786        };
1787        let ast_lowering = ty::ResolverAstLowering {
1788            legacy_const_generic_args: self.legacy_const_generic_args,
1789            partial_res_map: self.partial_res_map,
1790            import_res_map: self.import_res_map,
1791            label_res_map: self.label_res_map,
1792            lifetimes_res_map: self.lifetimes_res_map,
1793            extra_lifetime_params_map: self.extra_lifetime_params_map,
1794            next_node_id: self.next_node_id,
1795            node_id_to_def_id: self
1796                .node_id_to_def_id
1797                .into_items()
1798                .map(|(k, f)| (k, f.key()))
1799                .collect(),
1800            disambiguator: self.disambiguator,
1801            trait_map: self.trait_map,
1802            lifetime_elision_allowed: self.lifetime_elision_allowed,
1803            lint_buffer: Steal::new(self.lint_buffer),
1804            delegation_fn_sigs: self.delegation_fn_sigs,
1805        };
1806        ResolverOutputs { global_ctxt, ast_lowering }
1807    }
1808
1809    fn create_stable_hashing_context(&self) -> StableHashingContext<'_> {
1810        StableHashingContext::new(self.tcx.sess, self.tcx.untracked())
1811    }
1812
1813    fn cstore(&self) -> FreezeReadGuard<'_, CStore> {
1814        CStore::from_tcx(self.tcx)
1815    }
1816
1817    fn cstore_mut(&self) -> FreezeWriteGuard<'_, CStore> {
1818        CStore::from_tcx_mut(self.tcx)
1819    }
1820
1821    fn dummy_ext(&self, macro_kind: MacroKind) -> Arc<SyntaxExtension> {
1822        match macro_kind {
1823            MacroKind::Bang => Arc::clone(&self.dummy_ext_bang),
1824            MacroKind::Derive => Arc::clone(&self.dummy_ext_derive),
1825            MacroKind::Attr => Arc::clone(&self.non_macro_attr.ext),
1826        }
1827    }
1828
1829    /// Returns a conditionally mutable resolver.
1830    ///
1831    /// Currently only dependent on `assert_speculative`, if `assert_speculative` is false,
1832    /// the resolver will allow mutation; otherwise, it will be immutable.
1833    fn cm(&mut self) -> CmResolver<'_, 'ra, 'tcx> {
1834        CmResolver::new(self, !self.assert_speculative)
1835    }
1836
1837    /// Runs the function on each namespace.
1838    fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1839        f(self, TypeNS);
1840        f(self, ValueNS);
1841        f(self, MacroNS);
1842    }
1843
1844    fn per_ns_cm<'r, F: FnMut(&mut CmResolver<'r, 'ra, 'tcx>, Namespace)>(
1845        mut self: CmResolver<'r, 'ra, 'tcx>,
1846        mut f: F,
1847    ) {
1848        f(&mut self, TypeNS);
1849        f(&mut self, ValueNS);
1850        f(&mut self, MacroNS);
1851    }
1852
1853    fn is_builtin_macro(&self, res: Res) -> bool {
1854        self.get_macro(res).is_some_and(|macro_data| macro_data.ext.builtin_name.is_some())
1855    }
1856
1857    fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1858        loop {
1859            match ctxt.outer_expn_data().macro_def_id {
1860                Some(def_id) => return def_id,
1861                None => ctxt.remove_mark(),
1862            };
1863        }
1864    }
1865
1866    /// Entry point to crate resolution.
1867    pub fn resolve_crate(&mut self, krate: &Crate) {
1868        self.tcx.sess.time("resolve_crate", || {
1869            self.tcx.sess.time("finalize_imports", || self.finalize_imports());
1870            let exported_ambiguities = self.tcx.sess.time("compute_effective_visibilities", || {
1871                EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
1872            });
1873            self.tcx.sess.time("lint_reexports", || self.lint_reexports(exported_ambiguities));
1874            self.tcx
1875                .sess
1876                .time("finalize_macro_resolutions", || self.finalize_macro_resolutions(krate));
1877            self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate));
1878            self.tcx.sess.time("resolve_main", || self.resolve_main());
1879            self.tcx.sess.time("resolve_check_unused", || self.check_unused(krate));
1880            self.tcx.sess.time("resolve_report_errors", || self.report_errors(krate));
1881            self.tcx
1882                .sess
1883                .time("resolve_postprocess", || self.cstore_mut().postprocess(self.tcx, krate));
1884        });
1885
1886        // Make sure we don't mutate the cstore from here on.
1887        self.tcx.untracked().cstore.freeze();
1888    }
1889
1890    fn traits_in_scope(
1891        &mut self,
1892        current_trait: Option<Module<'ra>>,
1893        parent_scope: &ParentScope<'ra>,
1894        ctxt: SyntaxContext,
1895        assoc_item: Option<(Symbol, Namespace)>,
1896    ) -> Vec<TraitCandidate> {
1897        let mut found_traits = Vec::new();
1898
1899        if let Some(module) = current_trait {
1900            if self.trait_may_have_item(Some(module), assoc_item) {
1901                let def_id = module.def_id();
1902                found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
1903            }
1904        }
1905
1906        let scope_set = ScopeSet::All(TypeNS);
1907        self.cm().visit_scopes(scope_set, parent_scope, ctxt, None, |this, scope, _, _| {
1908            match scope {
1909                Scope::Module(module, _) => {
1910                    this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1911                }
1912                Scope::StdLibPrelude => {
1913                    if let Some(module) = this.prelude {
1914                        this.get_mut().traits_in_module(module, assoc_item, &mut found_traits);
1915                    }
1916                }
1917                Scope::ExternPreludeItems
1918                | Scope::ExternPreludeFlags
1919                | Scope::ToolPrelude
1920                | Scope::BuiltinTypes => {}
1921                _ => unreachable!(),
1922            }
1923            None::<()>
1924        });
1925
1926        found_traits
1927    }
1928
1929    fn traits_in_module(
1930        &mut self,
1931        module: Module<'ra>,
1932        assoc_item: Option<(Symbol, Namespace)>,
1933        found_traits: &mut Vec<TraitCandidate>,
1934    ) {
1935        module.ensure_traits(self);
1936        let traits = module.traits.borrow();
1937        for &(trait_name, trait_binding, trait_module) in traits.as_ref().unwrap().iter() {
1938            if self.trait_may_have_item(trait_module, assoc_item) {
1939                let def_id = trait_binding.res().def_id();
1940                let import_ids = self.find_transitive_imports(&trait_binding.kind, trait_name.0);
1941                found_traits.push(TraitCandidate { def_id, import_ids });
1942            }
1943        }
1944    }
1945
1946    // List of traits in scope is pruned on best effort basis. We reject traits not having an
1947    // associated item with the given name and namespace (if specified). This is a conservative
1948    // optimization, proper hygienic type-based resolution of associated items is done in typeck.
1949    // We don't reject trait aliases (`trait_module == None`) because we don't have access to their
1950    // associated items.
1951    fn trait_may_have_item(
1952        &self,
1953        trait_module: Option<Module<'ra>>,
1954        assoc_item: Option<(Symbol, Namespace)>,
1955    ) -> bool {
1956        match (trait_module, assoc_item) {
1957            (Some(trait_module), Some((name, ns))) => self
1958                .resolutions(trait_module)
1959                .borrow()
1960                .iter()
1961                .any(|(key, _name_resolution)| key.ns == ns && key.ident.name == name),
1962            _ => true,
1963        }
1964    }
1965
1966    fn find_transitive_imports(
1967        &mut self,
1968        mut kind: &NameBindingKind<'_>,
1969        trait_name: Ident,
1970    ) -> SmallVec<[LocalDefId; 1]> {
1971        let mut import_ids = smallvec![];
1972        while let NameBindingKind::Import { import, binding, .. } = kind {
1973            if let Some(node_id) = import.id() {
1974                let def_id = self.local_def_id(node_id);
1975                self.maybe_unused_trait_imports.insert(def_id);
1976                import_ids.push(def_id);
1977            }
1978            self.add_to_glob_map(*import, trait_name);
1979            kind = &binding.kind;
1980        }
1981        import_ids
1982    }
1983
1984    fn resolutions(&self, module: Module<'ra>) -> &'ra Resolutions<'ra> {
1985        if module.populate_on_access.get() {
1986            // FIXME(batched): Will be fixed in batched import resolution.
1987            module.populate_on_access.set(false);
1988            self.build_reduced_graph_external(module);
1989        }
1990        &module.0.0.lazy_resolutions
1991    }
1992
1993    fn resolution(
1994        &self,
1995        module: Module<'ra>,
1996        key: BindingKey,
1997    ) -> Option<Ref<'ra, NameResolution<'ra>>> {
1998        self.resolutions(module).borrow().get(&key).map(|resolution| resolution.borrow())
1999    }
2000
2001    fn resolution_or_default(
2002        &self,
2003        module: Module<'ra>,
2004        key: BindingKey,
2005    ) -> &'ra RefCell<NameResolution<'ra>> {
2006        self.resolutions(module)
2007            .borrow_mut()
2008            .entry(key)
2009            .or_insert_with(|| self.arenas.alloc_name_resolution())
2010    }
2011
2012    /// Test if AmbiguityError ambi is any identical to any one inside ambiguity_errors
2013    fn matches_previous_ambiguity_error(&self, ambi: &AmbiguityError<'_>) -> bool {
2014        for ambiguity_error in &self.ambiguity_errors {
2015            // if the span location and ident as well as its span are the same
2016            if ambiguity_error.kind == ambi.kind
2017                && ambiguity_error.ident == ambi.ident
2018                && ambiguity_error.ident.span == ambi.ident.span
2019                && ambiguity_error.b1.span == ambi.b1.span
2020                && ambiguity_error.b2.span == ambi.b2.span
2021                && ambiguity_error.misc1 == ambi.misc1
2022                && ambiguity_error.misc2 == ambi.misc2
2023            {
2024                return true;
2025            }
2026        }
2027        false
2028    }
2029
2030    fn record_use(&mut self, ident: Ident, used_binding: NameBinding<'ra>, used: Used) {
2031        self.record_use_inner(ident, used_binding, used, used_binding.warn_ambiguity);
2032    }
2033
2034    fn record_use_inner(
2035        &mut self,
2036        ident: Ident,
2037        used_binding: NameBinding<'ra>,
2038        used: Used,
2039        warn_ambiguity: bool,
2040    ) {
2041        if let Some((b2, kind)) = used_binding.ambiguity {
2042            let ambiguity_error = AmbiguityError {
2043                kind,
2044                ident,
2045                b1: used_binding,
2046                b2,
2047                misc1: AmbiguityErrorMisc::None,
2048                misc2: AmbiguityErrorMisc::None,
2049                warning: warn_ambiguity,
2050            };
2051            if !self.matches_previous_ambiguity_error(&ambiguity_error) {
2052                // avoid duplicated span information to be emit out
2053                self.ambiguity_errors.push(ambiguity_error);
2054            }
2055        }
2056        if let NameBindingKind::Import { import, binding } = used_binding.kind {
2057            if let ImportKind::MacroUse { warn_private: true } = import.kind {
2058                // Do not report the lint if the macro name resolves in stdlib prelude
2059                // even without the problematic `macro_use` import.
2060                let found_in_stdlib_prelude = self.prelude.is_some_and(|prelude| {
2061                    let empty_module = self.empty_module;
2062                    let arenas = self.arenas;
2063                    self.cm()
2064                        .maybe_resolve_ident_in_module(
2065                            ModuleOrUniformRoot::Module(prelude),
2066                            ident,
2067                            MacroNS,
2068                            &ParentScope::module(empty_module, arenas),
2069                            None,
2070                        )
2071                        .is_ok()
2072                });
2073                if !found_in_stdlib_prelude {
2074                    self.lint_buffer().buffer_lint(
2075                        PRIVATE_MACRO_USE,
2076                        import.root_id,
2077                        ident.span,
2078                        BuiltinLintDiag::MacroIsPrivate(ident),
2079                    );
2080                }
2081            }
2082            // Avoid marking `extern crate` items that refer to a name from extern prelude,
2083            // but not introduce it, as used if they are accessed from lexical scope.
2084            if used == Used::Scope
2085                && let Some(entry) = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident))
2086                && entry.item_binding == Some((used_binding, false))
2087            {
2088                return;
2089            }
2090            let old_used = self.import_use_map.entry(import).or_insert(used);
2091            if *old_used < used {
2092                *old_used = used;
2093            }
2094            if let Some(id) = import.id() {
2095                self.used_imports.insert(id);
2096            }
2097            self.add_to_glob_map(import, ident);
2098            self.record_use_inner(
2099                ident,
2100                binding,
2101                Used::Other,
2102                warn_ambiguity || binding.warn_ambiguity,
2103            );
2104        }
2105    }
2106
2107    #[inline]
2108    fn add_to_glob_map(&mut self, import: Import<'_>, ident: Ident) {
2109        if let ImportKind::Glob { id, .. } = import.kind {
2110            let def_id = self.local_def_id(id);
2111            self.glob_map.entry(def_id).or_default().insert(ident.name);
2112        }
2113    }
2114
2115    fn resolve_crate_root(&self, ident: Ident) -> Module<'ra> {
2116        debug!("resolve_crate_root({:?})", ident);
2117        let mut ctxt = ident.span.ctxt();
2118        let mark = if ident.name == kw::DollarCrate {
2119            // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
2120            // we don't want to pretend that the `macro_rules!` definition is in the `macro`
2121            // as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks.
2122            // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
2123            // definitions actually produced by `macro` and `macro` definitions produced by
2124            // `macro_rules!`, but at least such configurations are not stable yet.
2125            ctxt = ctxt.normalize_to_macro_rules();
2126            debug!(
2127                "resolve_crate_root: marks={:?}",
2128                ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
2129            );
2130            let mut iter = ctxt.marks().into_iter().rev().peekable();
2131            let mut result = None;
2132            // Find the last opaque mark from the end if it exists.
2133            while let Some(&(mark, transparency)) = iter.peek() {
2134                if transparency == Transparency::Opaque {
2135                    result = Some(mark);
2136                    iter.next();
2137                } else {
2138                    break;
2139                }
2140            }
2141            debug!(
2142                "resolve_crate_root: found opaque mark {:?} {:?}",
2143                result,
2144                result.map(|r| r.expn_data())
2145            );
2146            // Then find the last semi-opaque mark from the end if it exists.
2147            for (mark, transparency) in iter {
2148                if transparency == Transparency::SemiOpaque {
2149                    result = Some(mark);
2150                } else {
2151                    break;
2152                }
2153            }
2154            debug!(
2155                "resolve_crate_root: found semi-opaque mark {:?} {:?}",
2156                result,
2157                result.map(|r| r.expn_data())
2158            );
2159            result
2160        } else {
2161            debug!("resolve_crate_root: not DollarCrate");
2162            ctxt = ctxt.normalize_to_macros_2_0();
2163            ctxt.adjust(ExpnId::root())
2164        };
2165        let module = match mark {
2166            Some(def) => self.expn_def_scope(def),
2167            None => {
2168                debug!(
2169                    "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
2170                    ident, ident.span
2171                );
2172                return self.graph_root;
2173            }
2174        };
2175        let module = self.expect_module(
2176            module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
2177        );
2178        debug!(
2179            "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
2180            ident,
2181            module,
2182            module.kind.name(),
2183            ident.span
2184        );
2185        module
2186    }
2187
2188    fn resolve_self(&self, ctxt: &mut SyntaxContext, module: Module<'ra>) -> Module<'ra> {
2189        let mut module = self.expect_module(module.nearest_parent_mod());
2190        while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
2191            let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
2192            module = self.expect_module(parent.nearest_parent_mod());
2193        }
2194        module
2195    }
2196
2197    fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2198        debug!("(recording res) recording {:?} for {}", resolution, node_id);
2199        if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2200            panic!("path resolved multiple times ({prev_res:?} before, {resolution:?} now)");
2201        }
2202    }
2203
2204    fn record_pat_span(&mut self, node: NodeId, span: Span) {
2205        debug!("(recording pat) recording {:?} for {:?}", node, span);
2206        self.pat_span_map.insert(node, span);
2207    }
2208
2209    fn is_accessible_from(&self, vis: Visibility<impl Into<DefId>>, module: Module<'ra>) -> bool {
2210        vis.is_accessible_from(module.nearest_parent_mod(), self.tcx)
2211    }
2212
2213    fn set_binding_parent_module(&mut self, binding: NameBinding<'ra>, module: Module<'ra>) {
2214        if let Some(old_module) = self.binding_parent_modules.insert(binding, module) {
2215            if module != old_module {
2216                span_bug!(binding.span, "parent module is reset for binding");
2217            }
2218        }
2219    }
2220
2221    fn disambiguate_macro_rules_vs_modularized(
2222        &self,
2223        macro_rules: NameBinding<'ra>,
2224        modularized: NameBinding<'ra>,
2225    ) -> bool {
2226        // Some non-controversial subset of ambiguities "modularized macro name" vs "macro_rules"
2227        // is disambiguated to mitigate regressions from macro modularization.
2228        // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
2229        match (
2230            self.binding_parent_modules.get(&macro_rules),
2231            self.binding_parent_modules.get(&modularized),
2232        ) {
2233            (Some(macro_rules), Some(modularized)) => {
2234                macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
2235                    && modularized.is_ancestor_of(*macro_rules)
2236            }
2237            _ => false,
2238        }
2239    }
2240
2241    fn extern_prelude_get_item<'r>(
2242        mut self: CmResolver<'r, 'ra, 'tcx>,
2243        ident: Ident,
2244        finalize: bool,
2245    ) -> Option<NameBinding<'ra>> {
2246        let entry = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident));
2247        entry.and_then(|entry| entry.item_binding).map(|(binding, _)| {
2248            if finalize {
2249                self.get_mut().record_use(ident, binding, Used::Scope);
2250            }
2251            binding
2252        })
2253    }
2254
2255    fn extern_prelude_get_flag(&self, ident: Ident, finalize: bool) -> Option<NameBinding<'ra>> {
2256        let entry = self.extern_prelude.get(&Macros20NormalizedIdent::new(ident));
2257        entry.and_then(|entry| entry.flag_binding.as_ref()).and_then(|flag_binding| {
2258            let (pending_binding, finalized) = flag_binding.get();
2259            let binding = match pending_binding {
2260                PendingBinding::Ready(binding) => {
2261                    if finalize && !finalized {
2262                        self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span);
2263                    }
2264                    binding
2265                }
2266                PendingBinding::Pending => {
2267                    debug_assert!(!finalized);
2268                    let crate_id = if finalize {
2269                        self.cstore_mut().process_path_extern(self.tcx, ident.name, ident.span)
2270                    } else {
2271                        self.cstore_mut().maybe_process_path_extern(self.tcx, ident.name)
2272                    };
2273                    crate_id.map(|crate_id| {
2274                        let res = Res::Def(DefKind::Mod, crate_id.as_def_id());
2275                        self.arenas.new_pub_res_binding(res, DUMMY_SP, LocalExpnId::ROOT)
2276                    })
2277                }
2278            };
2279            flag_binding.set((PendingBinding::Ready(binding), finalize || finalized));
2280            binding.or_else(|| finalize.then_some(self.dummy_binding))
2281        })
2282    }
2283
2284    /// Rustdoc uses this to resolve doc link paths in a recoverable way. `PathResult<'a>`
2285    /// isn't something that can be returned because it can't be made to live that long,
2286    /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
2287    /// just that an error occurred.
2288    fn resolve_rustdoc_path(
2289        &mut self,
2290        path_str: &str,
2291        ns: Namespace,
2292        parent_scope: ParentScope<'ra>,
2293    ) -> Option<Res> {
2294        let segments: Result<Vec<_>, ()> = path_str
2295            .split("::")
2296            .enumerate()
2297            .map(|(i, s)| {
2298                let sym = if s.is_empty() {
2299                    if i == 0 {
2300                        // For a path like `::a::b`, use `kw::PathRoot` as the leading segment.
2301                        kw::PathRoot
2302                    } else {
2303                        return Err(()); // occurs in cases like `String::`
2304                    }
2305                } else {
2306                    Symbol::intern(s)
2307                };
2308                Ok(Segment::from_ident(Ident::with_dummy_span(sym)))
2309            })
2310            .collect();
2311        let Ok(segments) = segments else { return None };
2312
2313        match self.cm().maybe_resolve_path(&segments, Some(ns), &parent_scope, None) {
2314            PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
2315            PathResult::NonModule(path_res) => {
2316                path_res.full_res().filter(|res| !matches!(res, Res::Def(DefKind::Ctor(..), _)))
2317            }
2318            PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
2319                None
2320            }
2321            PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
2322        }
2323    }
2324
2325    /// Retrieves definition span of the given `DefId`.
2326    fn def_span(&self, def_id: DefId) -> Span {
2327        match def_id.as_local() {
2328            Some(def_id) => self.tcx.source_span(def_id),
2329            // Query `def_span` is not used because hashing its result span is expensive.
2330            None => self.cstore().def_span_untracked(def_id, self.tcx.sess),
2331        }
2332    }
2333
2334    fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
2335        match def_id.as_local() {
2336            Some(def_id) => self.field_names.get(&def_id).cloned(),
2337            None => Some(
2338                self.tcx
2339                    .associated_item_def_ids(def_id)
2340                    .iter()
2341                    .map(|&def_id| {
2342                        Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
2343                    })
2344                    .collect(),
2345            ),
2346        }
2347    }
2348
2349    fn field_defaults(&self, def_id: DefId) -> Option<Vec<Symbol>> {
2350        match def_id.as_local() {
2351            Some(def_id) => self.field_defaults.get(&def_id).cloned(),
2352            None => Some(
2353                self.tcx
2354                    .associated_item_def_ids(def_id)
2355                    .iter()
2356                    .filter_map(|&def_id| {
2357                        self.tcx.default_field(def_id).map(|_| self.tcx.item_name(def_id))
2358                    })
2359                    .collect(),
2360            ),
2361        }
2362    }
2363
2364    /// Checks if an expression refers to a function marked with
2365    /// `#[rustc_legacy_const_generics]` and returns the argument index list
2366    /// from the attribute.
2367    fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
2368        if let ExprKind::Path(None, path) = &expr.kind {
2369            // Don't perform legacy const generics rewriting if the path already
2370            // has generic arguments.
2371            if path.segments.last().unwrap().args.is_some() {
2372                return None;
2373            }
2374
2375            let res = self.partial_res_map.get(&expr.id)?.full_res()?;
2376            if let Res::Def(def::DefKind::Fn, def_id) = res {
2377                // We only support cross-crate argument rewriting. Uses
2378                // within the same crate should be updated to use the new
2379                // const generics style.
2380                if def_id.is_local() {
2381                    return None;
2382                }
2383
2384                if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
2385                    return v.clone();
2386                }
2387
2388                let attr = self.tcx.get_attr(def_id, sym::rustc_legacy_const_generics)?;
2389                let mut ret = Vec::new();
2390                for meta in attr.meta_item_list()? {
2391                    match meta.lit()?.kind {
2392                        LitKind::Int(a, _) => ret.push(a.get() as usize),
2393                        _ => panic!("invalid arg index"),
2394                    }
2395                }
2396                // Cache the lookup to avoid parsing attributes for an item multiple times.
2397                self.legacy_const_generic_args.insert(def_id, Some(ret.clone()));
2398                return Some(ret);
2399            }
2400        }
2401        None
2402    }
2403
2404    fn resolve_main(&mut self) {
2405        let module = self.graph_root;
2406        let ident = Ident::with_dummy_span(sym::main);
2407        let parent_scope = &ParentScope::module(module, self.arenas);
2408
2409        let Ok(name_binding) = self.cm().maybe_resolve_ident_in_module(
2410            ModuleOrUniformRoot::Module(module),
2411            ident,
2412            ValueNS,
2413            parent_scope,
2414            None,
2415        ) else {
2416            return;
2417        };
2418
2419        let res = name_binding.res();
2420        let is_import = name_binding.is_import();
2421        let span = name_binding.span;
2422        if let Res::Def(DefKind::Fn, _) = res {
2423            self.record_use(ident, name_binding, Used::Other);
2424        }
2425        self.main_def = Some(MainDefinition { res, is_import, span });
2426    }
2427}
2428
2429fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2430    let mut result = String::new();
2431    for (i, name) in names.filter(|name| *name != kw::PathRoot).enumerate() {
2432        if i > 0 {
2433            result.push_str("::");
2434        }
2435        if Ident::with_dummy_span(name).is_raw_guess() {
2436            result.push_str("r#");
2437        }
2438        result.push_str(name.as_str());
2439    }
2440    result
2441}
2442
2443fn path_names_to_string(path: &Path) -> String {
2444    names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2445}
2446
2447/// A somewhat inefficient routine to obtain the name of a module.
2448fn module_to_string(mut module: Module<'_>) -> Option<String> {
2449    let mut names = Vec::new();
2450    loop {
2451        if let ModuleKind::Def(.., name) = module.kind {
2452            if let Some(parent) = module.parent {
2453                // `unwrap` is safe: the presence of a parent means it's not the crate root.
2454                names.push(name.unwrap());
2455                module = parent
2456            } else {
2457                break;
2458            }
2459        } else {
2460            names.push(sym::opaque_module_name_placeholder);
2461            let Some(parent) = module.parent else {
2462                return None;
2463            };
2464            module = parent;
2465        }
2466    }
2467    if names.is_empty() {
2468        return None;
2469    }
2470    Some(names_to_string(names.iter().rev().copied()))
2471}
2472
2473#[derive(Copy, Clone, PartialEq, Debug)]
2474enum Stage {
2475    /// Resolving an import or a macro.
2476    /// Used when macro expansion is either not yet finished, or we are finalizing its results.
2477    /// Used by default as a more restrictive variant that can produce additional errors.
2478    Early,
2479    /// Resolving something in late resolution when all imports are resolved
2480    /// and all macros are expanded.
2481    Late,
2482}
2483
2484#[derive(Copy, Clone, Debug)]
2485struct Finalize {
2486    /// Node ID for linting.
2487    node_id: NodeId,
2488    /// Span of the whole path or some its characteristic fragment.
2489    /// E.g. span of `b` in `foo::{a, b, c}`, or full span for regular paths.
2490    path_span: Span,
2491    /// Span of the path start, suitable for prepending something to it.
2492    /// E.g. span of `foo` in `foo::{a, b, c}`, or full span for regular paths.
2493    root_span: Span,
2494    /// Whether to report privacy errors or silently return "no resolution" for them,
2495    /// similarly to speculative resolution.
2496    report_private: bool = true,
2497    /// Tracks whether an item is used in scope or used relatively to a module.
2498    used: Used = Used::Other,
2499    /// Finalizing early or late resolution.
2500    stage: Stage = Stage::Early,
2501}
2502
2503impl Finalize {
2504    fn new(node_id: NodeId, path_span: Span) -> Finalize {
2505        Finalize::with_root_span(node_id, path_span, path_span)
2506    }
2507
2508    fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2509        Finalize { node_id, path_span, root_span, .. }
2510    }
2511}
2512
2513pub fn provide(providers: &mut Providers) {
2514    providers.registered_tools = macros::registered_tools;
2515}
2516
2517/// A wrapper around `&mut Resolver` that may be mutable or immutable, depending on a conditions.
2518///
2519/// `Cm` stands for "conditionally mutable".
2520///
2521/// Prefer constructing it through [`Resolver::cm`] to ensure correctness.
2522type CmResolver<'r, 'ra, 'tcx> = ref_mut::RefOrMut<'r, Resolver<'ra, 'tcx>>;
2523
2524mod ref_mut {
2525    use std::cell::{BorrowMutError, Cell, Ref, RefCell, RefMut};
2526    use std::fmt;
2527    use std::ops::Deref;
2528
2529    use crate::Resolver;
2530
2531    /// A wrapper around a mutable reference that conditionally allows mutable access.
2532    pub(crate) struct RefOrMut<'a, T> {
2533        p: &'a mut T,
2534        mutable: bool,
2535    }
2536
2537    impl<'a, T> Deref for RefOrMut<'a, T> {
2538        type Target = T;
2539
2540        fn deref(&self) -> &Self::Target {
2541            self.p
2542        }
2543    }
2544
2545    impl<'a, T> AsRef<T> for RefOrMut<'a, T> {
2546        fn as_ref(&self) -> &T {
2547            self.p
2548        }
2549    }
2550
2551    impl<'a, T> RefOrMut<'a, T> {
2552        pub(crate) fn new(p: &'a mut T, mutable: bool) -> Self {
2553            RefOrMut { p, mutable }
2554        }
2555
2556        /// This is needed because this wraps a `&mut T` and is therefore not `Copy`.
2557        pub(crate) fn reborrow(&mut self) -> RefOrMut<'_, T> {
2558            RefOrMut { p: self.p, mutable: self.mutable }
2559        }
2560
2561        /// Returns a mutable reference to the inner value if allowed.
2562        ///
2563        /// # Panics
2564        /// Panics if the `mutable` flag is false.
2565        #[track_caller]
2566        pub(crate) fn get_mut(&mut self) -> &mut T {
2567            match self.mutable {
2568                false => panic!("Can't mutably borrow speculative resolver"),
2569                true => self.p,
2570            }
2571        }
2572
2573        /// Returns a mutable reference to the inner value without checking if
2574        /// it's in a mutable state.
2575        pub(crate) fn get_mut_unchecked(&mut self) -> &mut T {
2576            self.p
2577        }
2578    }
2579
2580    /// A wrapper around a [`Cell`] that only allows mutation based on a condition in the resolver.
2581    #[derive(Default)]
2582    pub(crate) struct CmCell<T>(Cell<T>);
2583
2584    impl<T: Copy + fmt::Debug> fmt::Debug for CmCell<T> {
2585        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2586            f.debug_tuple("CmCell").field(&self.get()).finish()
2587        }
2588    }
2589
2590    impl<T: Copy> Clone for CmCell<T> {
2591        #[inline]
2592        fn clone(&self) -> CmCell<T> {
2593            CmCell::new(self.get())
2594        }
2595    }
2596
2597    impl<T: Copy> CmCell<T> {
2598        pub(crate) const fn get(&self) -> T {
2599            self.0.get()
2600        }
2601
2602        pub(crate) fn update_unchecked(&self, f: impl FnOnce(T) -> T)
2603        where
2604            T: Copy,
2605        {
2606            let old = self.get();
2607            self.set_unchecked(f(old));
2608        }
2609    }
2610
2611    impl<T> CmCell<T> {
2612        pub(crate) const fn new(value: T) -> CmCell<T> {
2613            CmCell(Cell::new(value))
2614        }
2615
2616        pub(crate) fn set_unchecked(&self, val: T) {
2617            self.0.set(val);
2618        }
2619
2620        pub(crate) fn into_inner(self) -> T {
2621            self.0.into_inner()
2622        }
2623    }
2624
2625    /// A wrapper around a [`RefCell`] that only allows mutable borrows based on a condition in the resolver.
2626    #[derive(Default)]
2627    pub(crate) struct CmRefCell<T>(RefCell<T>);
2628
2629    impl<T> CmRefCell<T> {
2630        pub(crate) const fn new(value: T) -> CmRefCell<T> {
2631            CmRefCell(RefCell::new(value))
2632        }
2633
2634        #[inline]
2635        #[track_caller]
2636        pub(crate) fn borrow_mut_unchecked(&self) -> RefMut<'_, T> {
2637            self.0.borrow_mut()
2638        }
2639
2640        #[inline]
2641        #[track_caller]
2642        pub(crate) fn borrow_mut<'ra, 'tcx>(&self, r: &Resolver<'ra, 'tcx>) -> RefMut<'_, T> {
2643            if r.assert_speculative {
2644                panic!("Not allowed to mutably borrow a CmRefCell during speculative resolution");
2645            }
2646            self.borrow_mut_unchecked()
2647        }
2648
2649        #[inline]
2650        #[track_caller]
2651        pub(crate) fn try_borrow_mut_unchecked(&self) -> Result<RefMut<'_, T>, BorrowMutError> {
2652            self.0.try_borrow_mut()
2653        }
2654
2655        #[inline]
2656        #[track_caller]
2657        pub(crate) fn borrow(&self) -> Ref<'_, T> {
2658            self.0.borrow()
2659        }
2660    }
2661}