rustc_resolve/
lib.rs

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