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