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