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