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