rustc_resolve/
lib.rs

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