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