rustc_resolve/
lib.rs

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