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    ///   The crate root will have `None` for the symbol.
507    /// * A trait or an enum (it implicitly contains associated types, methods and variant
508    ///   constructors).
509    Def(DefKind, DefId, Option<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) => 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: FxIndexMap<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    legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
1195    /// Amount of lifetime parameters for each item in the crate.
1196    item_generics_num_lifetimes: FxHashMap<LocalDefId, usize>,
1197    delegation_fn_sigs: LocalDefIdMap<DelegationFnSig>,
1198
1199    main_def: Option<MainDefinition>,
1200    trait_impls: FxIndexMap<DefId, Vec<LocalDefId>>,
1201    /// A list of proc macro LocalDefIds, written out in the order in which
1202    /// they are declared in the static array generated by proc_macro_harness.
1203    proc_macros: Vec<NodeId>,
1204    confused_type_with_std_module: FxIndexMap<Span, Span>,
1205    /// Whether lifetime elision was successful.
1206    lifetime_elision_allowed: FxHashSet<NodeId>,
1207
1208    /// Names of items that were stripped out via cfg with their corresponding cfg meta item.
1209    stripped_cfg_items: Vec<StrippedCfgItem<NodeId>>,
1210
1211    effective_visibilities: EffectiveVisibilities,
1212    doc_link_resolutions: FxIndexMap<LocalDefId, DocLinkResMap>,
1213    doc_link_traits_in_scope: FxIndexMap<LocalDefId, Vec<DefId>>,
1214    all_macro_rules: FxHashSet<Symbol>,
1215
1216    /// Invocation ids of all glob delegations.
1217    glob_delegation_invoc_ids: FxHashSet<LocalExpnId>,
1218    /// Analogue of module `unexpanded_invocations` but in trait impls, excluding glob delegations.
1219    /// Needed because glob delegations wait for all other neighboring macros to expand.
1220    impl_unexpanded_invocations: FxHashMap<LocalDefId, FxHashSet<LocalExpnId>>,
1221    /// Simplified analogue of module `resolutions` but in trait impls, excluding glob delegations.
1222    /// Needed because glob delegations exclude explicitly defined names.
1223    impl_binding_keys: FxHashMap<LocalDefId, FxHashSet<BindingKey>>,
1224
1225    /// This is the `Span` where an `extern crate foo;` suggestion would be inserted, if `foo`
1226    /// could be a crate that wasn't imported. For diagnostics use only.
1227    current_crate_outer_attr_insert_span: Span,
1228
1229    mods_with_parse_errors: FxHashSet<DefId>,
1230}
1231
1232/// This provides memory for the rest of the crate. The `'ra` lifetime that is
1233/// used by many types in this crate is an abbreviation of `ResolverArenas`.
1234#[derive(Default)]
1235pub struct ResolverArenas<'ra> {
1236    modules: TypedArena<ModuleData<'ra>>,
1237    local_modules: RefCell<Vec<Module<'ra>>>,
1238    imports: TypedArena<ImportData<'ra>>,
1239    name_resolutions: TypedArena<RefCell<NameResolution<'ra>>>,
1240    ast_paths: TypedArena<ast::Path>,
1241    dropless: DroplessArena,
1242}
1243
1244impl<'ra> ResolverArenas<'ra> {
1245    fn new_module(
1246        &'ra self,
1247        parent: Option<Module<'ra>>,
1248        kind: ModuleKind,
1249        expn_id: ExpnId,
1250        span: Span,
1251        no_implicit_prelude: bool,
1252        module_map: &mut FxIndexMap<DefId, Module<'ra>>,
1253        module_self_bindings: &mut FxHashMap<Module<'ra>, NameBinding<'ra>>,
1254    ) -> Module<'ra> {
1255        let module = Module(Interned::new_unchecked(self.modules.alloc(ModuleData::new(
1256            parent,
1257            kind,
1258            expn_id,
1259            span,
1260            no_implicit_prelude,
1261        ))));
1262        let def_id = module.opt_def_id();
1263        if def_id.is_none_or(|def_id| def_id.is_local()) {
1264            self.local_modules.borrow_mut().push(module);
1265        }
1266        if let Some(def_id) = def_id {
1267            module_map.insert(def_id, module);
1268            let vis = ty::Visibility::<DefId>::Public;
1269            let binding = (module, vis, module.span, LocalExpnId::ROOT).to_name_binding(self);
1270            module_self_bindings.insert(module, binding);
1271        }
1272        module
1273    }
1274    fn local_modules(&'ra self) -> std::cell::Ref<'ra, Vec<Module<'ra>>> {
1275        self.local_modules.borrow()
1276    }
1277    fn alloc_name_binding(&'ra self, name_binding: NameBindingData<'ra>) -> NameBinding<'ra> {
1278        Interned::new_unchecked(self.dropless.alloc(name_binding))
1279    }
1280    fn alloc_import(&'ra self, import: ImportData<'ra>) -> Import<'ra> {
1281        Interned::new_unchecked(self.imports.alloc(import))
1282    }
1283    fn alloc_name_resolution(&'ra self) -> &'ra RefCell<NameResolution<'ra>> {
1284        self.name_resolutions.alloc(Default::default())
1285    }
1286    fn alloc_macro_rules_scope(&'ra self, scope: MacroRulesScope<'ra>) -> MacroRulesScopeRef<'ra> {
1287        Interned::new_unchecked(self.dropless.alloc(Cell::new(scope)))
1288    }
1289    fn alloc_macro_rules_binding(
1290        &'ra self,
1291        binding: MacroRulesBinding<'ra>,
1292    ) -> &'ra MacroRulesBinding<'ra> {
1293        self.dropless.alloc(binding)
1294    }
1295    fn alloc_ast_paths(&'ra self, paths: &[ast::Path]) -> &'ra [ast::Path] {
1296        self.ast_paths.alloc_from_iter(paths.iter().cloned())
1297    }
1298    fn alloc_pattern_spans(&'ra self, spans: impl Iterator<Item = Span>) -> &'ra [Span] {
1299        self.dropless.alloc_from_iter(spans)
1300    }
1301}
1302
1303impl<'ra, 'tcx> AsMut<Resolver<'ra, 'tcx>> for Resolver<'ra, 'tcx> {
1304    fn as_mut(&mut self) -> &mut Resolver<'ra, 'tcx> {
1305        self
1306    }
1307}
1308
1309impl<'tcx> Resolver<'_, 'tcx> {
1310    fn opt_local_def_id(&self, node: NodeId) -> Option<LocalDefId> {
1311        self.opt_feed(node).map(|f| f.key())
1312    }
1313
1314    fn local_def_id(&self, node: NodeId) -> LocalDefId {
1315        self.feed(node).key()
1316    }
1317
1318    fn opt_feed(&self, node: NodeId) -> Option<Feed<'tcx, LocalDefId>> {
1319        self.node_id_to_def_id.get(&node).copied()
1320    }
1321
1322    fn feed(&self, node: NodeId) -> Feed<'tcx, LocalDefId> {
1323        self.opt_feed(node).unwrap_or_else(|| panic!("no entry for node id: `{node:?}`"))
1324    }
1325
1326    fn local_def_kind(&self, node: NodeId) -> DefKind {
1327        self.tcx.def_kind(self.local_def_id(node))
1328    }
1329
1330    /// Adds a definition with a parent definition.
1331    fn create_def(
1332        &mut self,
1333        parent: LocalDefId,
1334        node_id: ast::NodeId,
1335        name: Option<Symbol>,
1336        def_kind: DefKind,
1337        expn_id: ExpnId,
1338        span: Span,
1339    ) -> TyCtxtFeed<'tcx, LocalDefId> {
1340        let data = def_kind.def_path_data(name);
1341        assert!(
1342            !self.node_id_to_def_id.contains_key(&node_id),
1343            "adding a def'n for node-id {:?} and data {:?} but a previous def'n exists: {:?}",
1344            node_id,
1345            data,
1346            self.tcx.definitions_untracked().def_key(self.node_id_to_def_id[&node_id].key()),
1347        );
1348
1349        // FIXME: remove `def_span` body, pass in the right spans here and call `tcx.at().create_def()`
1350        let feed = self.tcx.create_def(parent, name, def_kind);
1351        let def_id = feed.def_id();
1352
1353        // Create the definition.
1354        if expn_id != ExpnId::root() {
1355            self.expn_that_defined.insert(def_id, expn_id);
1356        }
1357
1358        // A relative span's parent must be an absolute span.
1359        debug_assert_eq!(span.data_untracked().parent, None);
1360        let _id = self.tcx.untracked().source_span.push(span);
1361        debug_assert_eq!(_id, def_id);
1362
1363        // Some things for which we allocate `LocalDefId`s don't correspond to
1364        // anything in the AST, so they don't have a `NodeId`. For these cases
1365        // we don't need a mapping from `NodeId` to `LocalDefId`.
1366        if node_id != ast::DUMMY_NODE_ID {
1367            debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
1368            self.node_id_to_def_id.insert(node_id, feed.downgrade());
1369        }
1370        assert_eq!(self.def_id_to_node_id.push(node_id), def_id);
1371
1372        feed
1373    }
1374
1375    fn item_generics_num_lifetimes(&self, def_id: DefId) -> usize {
1376        if let Some(def_id) = def_id.as_local() {
1377            self.item_generics_num_lifetimes[&def_id]
1378        } else {
1379            self.tcx.generics_of(def_id).own_counts().lifetimes
1380        }
1381    }
1382
1383    pub fn tcx(&self) -> TyCtxt<'tcx> {
1384        self.tcx
1385    }
1386}
1387
1388impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
1389    pub fn new(
1390        tcx: TyCtxt<'tcx>,
1391        attrs: &[ast::Attribute],
1392        crate_span: Span,
1393        current_crate_outer_attr_insert_span: Span,
1394        arenas: &'ra ResolverArenas<'ra>,
1395    ) -> Resolver<'ra, 'tcx> {
1396        let root_def_id = CRATE_DEF_ID.to_def_id();
1397        let mut module_map = FxIndexMap::default();
1398        let mut module_self_bindings = FxHashMap::default();
1399        let graph_root = arenas.new_module(
1400            None,
1401            ModuleKind::Def(DefKind::Mod, root_def_id, None),
1402            ExpnId::root(),
1403            crate_span,
1404            attr::contains_name(attrs, sym::no_implicit_prelude),
1405            &mut module_map,
1406            &mut module_self_bindings,
1407        );
1408        let empty_module = arenas.new_module(
1409            None,
1410            ModuleKind::Def(DefKind::Mod, root_def_id, None),
1411            ExpnId::root(),
1412            DUMMY_SP,
1413            true,
1414            &mut Default::default(),
1415            &mut Default::default(),
1416        );
1417
1418        let mut def_id_to_node_id = IndexVec::default();
1419        assert_eq!(def_id_to_node_id.push(CRATE_NODE_ID), CRATE_DEF_ID);
1420        let mut node_id_to_def_id = NodeMap::default();
1421        let crate_feed = tcx.create_local_crate_def_id(crate_span);
1422
1423        crate_feed.def_kind(DefKind::Mod);
1424        let crate_feed = crate_feed.downgrade();
1425        node_id_to_def_id.insert(CRATE_NODE_ID, crate_feed);
1426
1427        let mut invocation_parents = FxHashMap::default();
1428        invocation_parents.insert(LocalExpnId::ROOT, InvocationParent::ROOT);
1429
1430        let mut extern_prelude: FxIndexMap<Ident, ExternPreludeEntry<'_>> = tcx
1431            .sess
1432            .opts
1433            .externs
1434            .iter()
1435            .filter(|(_, entry)| entry.add_prelude)
1436            .map(|(name, _)| (Ident::from_str(name), Default::default()))
1437            .collect();
1438
1439        if !attr::contains_name(attrs, sym::no_core) {
1440            extern_prelude.insert(Ident::with_dummy_span(sym::core), Default::default());
1441            if !attr::contains_name(attrs, sym::no_std) {
1442                extern_prelude.insert(Ident::with_dummy_span(sym::std), Default::default());
1443            }
1444        }
1445
1446        let registered_tools = tcx.registered_tools(());
1447
1448        let pub_vis = ty::Visibility::<DefId>::Public;
1449        let edition = tcx.sess.edition();
1450
1451        let mut resolver = Resolver {
1452            tcx,
1453
1454            expn_that_defined: Default::default(),
1455
1456            // The outermost module has def ID 0; this is not reflected in the
1457            // AST.
1458            graph_root,
1459            prelude: None,
1460            extern_prelude,
1461
1462            field_names: Default::default(),
1463            field_visibility_spans: FxHashMap::default(),
1464
1465            determined_imports: Vec::new(),
1466            indeterminate_imports: Vec::new(),
1467
1468            pat_span_map: Default::default(),
1469            partial_res_map: Default::default(),
1470            import_res_map: Default::default(),
1471            import_use_map: Default::default(),
1472            label_res_map: Default::default(),
1473            lifetimes_res_map: Default::default(),
1474            extra_lifetime_params_map: Default::default(),
1475            extern_crate_map: Default::default(),
1476            module_children: Default::default(),
1477            trait_map: NodeMap::default(),
1478            underscore_disambiguator: 0,
1479            empty_module,
1480            module_map,
1481            block_map: Default::default(),
1482            binding_parent_modules: FxHashMap::default(),
1483            ast_transform_scopes: FxHashMap::default(),
1484
1485            glob_map: Default::default(),
1486            glob_error: None,
1487            visibilities_for_hashing: Default::default(),
1488            used_imports: FxHashSet::default(),
1489            maybe_unused_trait_imports: Default::default(),
1490
1491            privacy_errors: Vec::new(),
1492            ambiguity_errors: Vec::new(),
1493            use_injections: Vec::new(),
1494            macro_expanded_macro_export_errors: BTreeSet::new(),
1495
1496            arenas,
1497            dummy_binding: (Res::Err, pub_vis, DUMMY_SP, LocalExpnId::ROOT).to_name_binding(arenas),
1498            builtin_types_bindings: PrimTy::ALL
1499                .iter()
1500                .map(|prim_ty| {
1501                    let binding = (Res::PrimTy(*prim_ty), pub_vis, DUMMY_SP, LocalExpnId::ROOT)
1502                        .to_name_binding(arenas);
1503                    (prim_ty.name(), binding)
1504                })
1505                .collect(),
1506            builtin_attrs_bindings: BUILTIN_ATTRIBUTES
1507                .iter()
1508                .map(|builtin_attr| {
1509                    let res = Res::NonMacroAttr(NonMacroAttrKind::Builtin(builtin_attr.name));
1510                    let binding =
1511                        (res, pub_vis, DUMMY_SP, LocalExpnId::ROOT).to_name_binding(arenas);
1512                    (builtin_attr.name, binding)
1513                })
1514                .collect(),
1515            registered_tool_bindings: registered_tools
1516                .iter()
1517                .map(|ident| {
1518                    let binding = (Res::ToolMod, pub_vis, ident.span, LocalExpnId::ROOT)
1519                        .to_name_binding(arenas);
1520                    (*ident, binding)
1521                })
1522                .collect(),
1523            module_self_bindings,
1524
1525            used_extern_options: Default::default(),
1526            macro_names: FxHashSet::default(),
1527            builtin_macros: Default::default(),
1528            registered_tools,
1529            macro_use_prelude: Default::default(),
1530            macro_map: FxHashMap::default(),
1531            dummy_ext_bang: Arc::new(SyntaxExtension::dummy_bang(edition)),
1532            dummy_ext_derive: Arc::new(SyntaxExtension::dummy_derive(edition)),
1533            non_macro_attr: MacroData::new(Arc::new(SyntaxExtension::non_macro_attr(edition))),
1534            invocation_parent_scopes: Default::default(),
1535            output_macro_rules_scopes: Default::default(),
1536            macro_rules_scopes: Default::default(),
1537            helper_attrs: Default::default(),
1538            derive_data: Default::default(),
1539            local_macro_def_scopes: FxHashMap::default(),
1540            name_already_seen: FxHashMap::default(),
1541            potentially_unused_imports: Vec::new(),
1542            potentially_unnecessary_qualifications: Default::default(),
1543            struct_constructors: Default::default(),
1544            unused_macros: Default::default(),
1545            unused_macro_rules: Default::default(),
1546            proc_macro_stubs: Default::default(),
1547            single_segment_macro_resolutions: Default::default(),
1548            multi_segment_macro_resolutions: Default::default(),
1549            builtin_attrs: Default::default(),
1550            containers_deriving_copy: Default::default(),
1551            lint_buffer: LintBuffer::default(),
1552            next_node_id: CRATE_NODE_ID,
1553            node_id_to_def_id,
1554            def_id_to_node_id,
1555            placeholder_field_indices: Default::default(),
1556            invocation_parents,
1557            legacy_const_generic_args: Default::default(),
1558            item_generics_num_lifetimes: Default::default(),
1559            main_def: Default::default(),
1560            trait_impls: Default::default(),
1561            proc_macros: Default::default(),
1562            confused_type_with_std_module: Default::default(),
1563            lifetime_elision_allowed: Default::default(),
1564            stripped_cfg_items: Default::default(),
1565            effective_visibilities: Default::default(),
1566            doc_link_resolutions: Default::default(),
1567            doc_link_traits_in_scope: Default::default(),
1568            all_macro_rules: Default::default(),
1569            delegation_fn_sigs: Default::default(),
1570            glob_delegation_invoc_ids: Default::default(),
1571            impl_unexpanded_invocations: Default::default(),
1572            impl_binding_keys: Default::default(),
1573            current_crate_outer_attr_insert_span,
1574            mods_with_parse_errors: Default::default(),
1575        };
1576
1577        let root_parent_scope = ParentScope::module(graph_root, &resolver);
1578        resolver.invocation_parent_scopes.insert(LocalExpnId::ROOT, root_parent_scope);
1579        resolver.feed_visibility(crate_feed, ty::Visibility::Public);
1580
1581        resolver
1582    }
1583
1584    fn new_module(
1585        &mut self,
1586        parent: Option<Module<'ra>>,
1587        kind: ModuleKind,
1588        expn_id: ExpnId,
1589        span: Span,
1590        no_implicit_prelude: bool,
1591    ) -> Module<'ra> {
1592        let module_map = &mut self.module_map;
1593        let module_self_bindings = &mut self.module_self_bindings;
1594        self.arenas.new_module(
1595            parent,
1596            kind,
1597            expn_id,
1598            span,
1599            no_implicit_prelude,
1600            module_map,
1601            module_self_bindings,
1602        )
1603    }
1604
1605    fn next_node_id(&mut self) -> NodeId {
1606        let start = self.next_node_id;
1607        let next = start.as_u32().checked_add(1).expect("input too large; ran out of NodeIds");
1608        self.next_node_id = ast::NodeId::from_u32(next);
1609        start
1610    }
1611
1612    fn next_node_ids(&mut self, count: usize) -> std::ops::Range<NodeId> {
1613        let start = self.next_node_id;
1614        let end = start.as_usize().checked_add(count).expect("input too large; ran out of NodeIds");
1615        self.next_node_id = ast::NodeId::from_usize(end);
1616        start..self.next_node_id
1617    }
1618
1619    pub fn lint_buffer(&mut self) -> &mut LintBuffer {
1620        &mut self.lint_buffer
1621    }
1622
1623    pub fn arenas() -> ResolverArenas<'ra> {
1624        Default::default()
1625    }
1626
1627    fn feed_visibility(&mut self, feed: Feed<'tcx, LocalDefId>, vis: ty::Visibility) {
1628        let feed = feed.upgrade(self.tcx);
1629        feed.visibility(vis.to_def_id());
1630        self.visibilities_for_hashing.push((feed.def_id(), vis));
1631    }
1632
1633    pub fn into_outputs(self) -> ResolverOutputs {
1634        let proc_macros = self.proc_macros.iter().map(|id| self.local_def_id(*id)).collect();
1635        let expn_that_defined = self.expn_that_defined;
1636        let extern_crate_map = self.extern_crate_map;
1637        let maybe_unused_trait_imports = self.maybe_unused_trait_imports;
1638        let glob_map = self.glob_map;
1639        let main_def = self.main_def;
1640        let confused_type_with_std_module = self.confused_type_with_std_module;
1641        let effective_visibilities = self.effective_visibilities;
1642
1643        let stripped_cfg_items = Steal::new(
1644            self.stripped_cfg_items
1645                .into_iter()
1646                .filter_map(|item| {
1647                    let parent_module =
1648                        self.node_id_to_def_id.get(&item.parent_module)?.key().to_def_id();
1649                    Some(StrippedCfgItem { parent_module, name: item.name, cfg: item.cfg })
1650                })
1651                .collect(),
1652        );
1653
1654        let global_ctxt = ResolverGlobalCtxt {
1655            expn_that_defined,
1656            visibilities_for_hashing: self.visibilities_for_hashing,
1657            effective_visibilities,
1658            extern_crate_map,
1659            module_children: self.module_children,
1660            glob_map,
1661            maybe_unused_trait_imports,
1662            main_def,
1663            trait_impls: self.trait_impls,
1664            proc_macros,
1665            confused_type_with_std_module,
1666            doc_link_resolutions: self.doc_link_resolutions,
1667            doc_link_traits_in_scope: self.doc_link_traits_in_scope,
1668            all_macro_rules: self.all_macro_rules,
1669            stripped_cfg_items,
1670        };
1671        let ast_lowering = ty::ResolverAstLowering {
1672            legacy_const_generic_args: self.legacy_const_generic_args,
1673            partial_res_map: self.partial_res_map,
1674            import_res_map: self.import_res_map,
1675            label_res_map: self.label_res_map,
1676            lifetimes_res_map: self.lifetimes_res_map,
1677            extra_lifetime_params_map: self.extra_lifetime_params_map,
1678            next_node_id: self.next_node_id,
1679            node_id_to_def_id: self
1680                .node_id_to_def_id
1681                .into_items()
1682                .map(|(k, f)| (k, f.key()))
1683                .collect(),
1684            trait_map: self.trait_map,
1685            lifetime_elision_allowed: self.lifetime_elision_allowed,
1686            lint_buffer: Steal::new(self.lint_buffer),
1687            delegation_fn_sigs: self.delegation_fn_sigs,
1688        };
1689        ResolverOutputs { global_ctxt, ast_lowering }
1690    }
1691
1692    fn create_stable_hashing_context(&self) -> StableHashingContext<'_> {
1693        StableHashingContext::new(self.tcx.sess, self.tcx.untracked())
1694    }
1695
1696    fn crate_loader<T>(&mut self, f: impl FnOnce(&mut CrateLoader<'_, '_>) -> T) -> T {
1697        f(&mut CrateLoader::new(
1698            self.tcx,
1699            &mut CStore::from_tcx_mut(self.tcx),
1700            &mut self.used_extern_options,
1701        ))
1702    }
1703
1704    fn cstore(&self) -> FreezeReadGuard<'_, CStore> {
1705        CStore::from_tcx(self.tcx)
1706    }
1707
1708    fn dummy_ext(&self, macro_kind: MacroKind) -> Arc<SyntaxExtension> {
1709        match macro_kind {
1710            MacroKind::Bang => Arc::clone(&self.dummy_ext_bang),
1711            MacroKind::Derive => Arc::clone(&self.dummy_ext_derive),
1712            MacroKind::Attr => Arc::clone(&self.non_macro_attr.ext),
1713        }
1714    }
1715
1716    /// Runs the function on each namespace.
1717    fn per_ns<F: FnMut(&mut Self, Namespace)>(&mut self, mut f: F) {
1718        f(self, TypeNS);
1719        f(self, ValueNS);
1720        f(self, MacroNS);
1721    }
1722
1723    fn is_builtin_macro(&mut self, res: Res) -> bool {
1724        self.get_macro(res).is_some_and(|macro_data| macro_data.ext.builtin_name.is_some())
1725    }
1726
1727    fn macro_def(&self, mut ctxt: SyntaxContext) -> DefId {
1728        loop {
1729            match ctxt.outer_expn_data().macro_def_id {
1730                Some(def_id) => return def_id,
1731                None => ctxt.remove_mark(),
1732            };
1733        }
1734    }
1735
1736    /// Entry point to crate resolution.
1737    pub fn resolve_crate(&mut self, krate: &Crate) {
1738        self.tcx.sess.time("resolve_crate", || {
1739            self.tcx.sess.time("finalize_imports", || self.finalize_imports());
1740            let exported_ambiguities = self.tcx.sess.time("compute_effective_visibilities", || {
1741                EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
1742            });
1743            self.tcx.sess.time("check_hidden_glob_reexports", || {
1744                self.check_hidden_glob_reexports(exported_ambiguities)
1745            });
1746            self.tcx
1747                .sess
1748                .time("finalize_macro_resolutions", || self.finalize_macro_resolutions(krate));
1749            self.tcx.sess.time("late_resolve_crate", || self.late_resolve_crate(krate));
1750            self.tcx.sess.time("resolve_main", || self.resolve_main());
1751            self.tcx.sess.time("resolve_check_unused", || self.check_unused(krate));
1752            self.tcx.sess.time("resolve_report_errors", || self.report_errors(krate));
1753            self.tcx
1754                .sess
1755                .time("resolve_postprocess", || self.crate_loader(|c| c.postprocess(krate)));
1756        });
1757
1758        // Make sure we don't mutate the cstore from here on.
1759        self.tcx.untracked().cstore.freeze();
1760    }
1761
1762    fn traits_in_scope(
1763        &mut self,
1764        current_trait: Option<Module<'ra>>,
1765        parent_scope: &ParentScope<'ra>,
1766        ctxt: SyntaxContext,
1767        assoc_item: Option<(Symbol, Namespace)>,
1768    ) -> Vec<TraitCandidate> {
1769        let mut found_traits = Vec::new();
1770
1771        if let Some(module) = current_trait {
1772            if self.trait_may_have_item(Some(module), assoc_item) {
1773                let def_id = module.def_id();
1774                found_traits.push(TraitCandidate { def_id, import_ids: smallvec![] });
1775            }
1776        }
1777
1778        self.visit_scopes(ScopeSet::All(TypeNS), parent_scope, ctxt, |this, scope, _, _| {
1779            match scope {
1780                Scope::Module(module, _) => {
1781                    this.traits_in_module(module, assoc_item, &mut found_traits);
1782                }
1783                Scope::StdLibPrelude => {
1784                    if let Some(module) = this.prelude {
1785                        this.traits_in_module(module, assoc_item, &mut found_traits);
1786                    }
1787                }
1788                Scope::ExternPrelude | Scope::ToolPrelude | Scope::BuiltinTypes => {}
1789                _ => unreachable!(),
1790            }
1791            None::<()>
1792        });
1793
1794        found_traits
1795    }
1796
1797    fn traits_in_module(
1798        &mut self,
1799        module: Module<'ra>,
1800        assoc_item: Option<(Symbol, Namespace)>,
1801        found_traits: &mut Vec<TraitCandidate>,
1802    ) {
1803        module.ensure_traits(self);
1804        let traits = module.traits.borrow();
1805        for (trait_name, trait_binding) in traits.as_ref().unwrap().iter() {
1806            if self.trait_may_have_item(trait_binding.module(), assoc_item) {
1807                let def_id = trait_binding.res().def_id();
1808                let import_ids = self.find_transitive_imports(&trait_binding.kind, *trait_name);
1809                found_traits.push(TraitCandidate { def_id, import_ids });
1810            }
1811        }
1812    }
1813
1814    // List of traits in scope is pruned on best effort basis. We reject traits not having an
1815    // associated item with the given name and namespace (if specified). This is a conservative
1816    // optimization, proper hygienic type-based resolution of associated items is done in typeck.
1817    // We don't reject trait aliases (`trait_module == None`) because we don't have access to their
1818    // associated items.
1819    fn trait_may_have_item(
1820        &mut self,
1821        trait_module: Option<Module<'ra>>,
1822        assoc_item: Option<(Symbol, Namespace)>,
1823    ) -> bool {
1824        match (trait_module, assoc_item) {
1825            (Some(trait_module), Some((name, ns))) => self
1826                .resolutions(trait_module)
1827                .borrow()
1828                .iter()
1829                .any(|(key, _name_resolution)| key.ns == ns && key.ident.name == name),
1830            _ => true,
1831        }
1832    }
1833
1834    fn find_transitive_imports(
1835        &mut self,
1836        mut kind: &NameBindingKind<'_>,
1837        trait_name: Ident,
1838    ) -> SmallVec<[LocalDefId; 1]> {
1839        let mut import_ids = smallvec![];
1840        while let NameBindingKind::Import { import, binding, .. } = kind {
1841            if let Some(node_id) = import.id() {
1842                let def_id = self.local_def_id(node_id);
1843                self.maybe_unused_trait_imports.insert(def_id);
1844                import_ids.push(def_id);
1845            }
1846            self.add_to_glob_map(*import, trait_name);
1847            kind = &binding.kind;
1848        }
1849        import_ids
1850    }
1851
1852    fn new_disambiguated_key(&mut self, ident: Ident, ns: Namespace) -> BindingKey {
1853        let ident = ident.normalize_to_macros_2_0();
1854        let disambiguator = if ident.name == kw::Underscore {
1855            self.underscore_disambiguator += 1;
1856            self.underscore_disambiguator
1857        } else {
1858            0
1859        };
1860        BindingKey { ident, ns, disambiguator }
1861    }
1862
1863    fn resolutions(&mut self, module: Module<'ra>) -> &'ra Resolutions<'ra> {
1864        if module.populate_on_access.get() {
1865            module.populate_on_access.set(false);
1866            self.build_reduced_graph_external(module);
1867        }
1868        &module.0.0.lazy_resolutions
1869    }
1870
1871    fn resolution(
1872        &mut self,
1873        module: Module<'ra>,
1874        key: BindingKey,
1875    ) -> &'ra RefCell<NameResolution<'ra>> {
1876        *self
1877            .resolutions(module)
1878            .borrow_mut()
1879            .entry(key)
1880            .or_insert_with(|| self.arenas.alloc_name_resolution())
1881    }
1882
1883    /// Test if AmbiguityError ambi is any identical to any one inside ambiguity_errors
1884    fn matches_previous_ambiguity_error(&self, ambi: &AmbiguityError<'_>) -> bool {
1885        for ambiguity_error in &self.ambiguity_errors {
1886            // if the span location and ident as well as its span are the same
1887            if ambiguity_error.kind == ambi.kind
1888                && ambiguity_error.ident == ambi.ident
1889                && ambiguity_error.ident.span == ambi.ident.span
1890                && ambiguity_error.b1.span == ambi.b1.span
1891                && ambiguity_error.b2.span == ambi.b2.span
1892                && ambiguity_error.misc1 == ambi.misc1
1893                && ambiguity_error.misc2 == ambi.misc2
1894            {
1895                return true;
1896            }
1897        }
1898        false
1899    }
1900
1901    fn record_use(&mut self, ident: Ident, used_binding: NameBinding<'ra>, used: Used) {
1902        self.record_use_inner(ident, used_binding, used, used_binding.warn_ambiguity);
1903    }
1904
1905    fn record_use_inner(
1906        &mut self,
1907        ident: Ident,
1908        used_binding: NameBinding<'ra>,
1909        used: Used,
1910        warn_ambiguity: bool,
1911    ) {
1912        if let Some((b2, kind)) = used_binding.ambiguity {
1913            let ambiguity_error = AmbiguityError {
1914                kind,
1915                ident,
1916                b1: used_binding,
1917                b2,
1918                misc1: AmbiguityErrorMisc::None,
1919                misc2: AmbiguityErrorMisc::None,
1920                warning: warn_ambiguity,
1921            };
1922            if !self.matches_previous_ambiguity_error(&ambiguity_error) {
1923                // avoid duplicated span information to be emit out
1924                self.ambiguity_errors.push(ambiguity_error);
1925            }
1926        }
1927        if let NameBindingKind::Import { import, binding } = used_binding.kind {
1928            if let ImportKind::MacroUse { warn_private: true } = import.kind {
1929                self.lint_buffer().buffer_lint(
1930                    PRIVATE_MACRO_USE,
1931                    import.root_id,
1932                    ident.span,
1933                    BuiltinLintDiag::MacroIsPrivate(ident),
1934                );
1935            }
1936            // Avoid marking `extern crate` items that refer to a name from extern prelude,
1937            // but not introduce it, as used if they are accessed from lexical scope.
1938            if used == Used::Scope {
1939                if let Some(entry) = self.extern_prelude.get(&ident.normalize_to_macros_2_0()) {
1940                    if !entry.introduced_by_item && entry.binding == Some(used_binding) {
1941                        return;
1942                    }
1943                }
1944            }
1945            let old_used = self.import_use_map.entry(import).or_insert(used);
1946            if *old_used < used {
1947                *old_used = used;
1948            }
1949            if let Some(id) = import.id() {
1950                self.used_imports.insert(id);
1951            }
1952            self.add_to_glob_map(import, ident);
1953            self.record_use_inner(
1954                ident,
1955                binding,
1956                Used::Other,
1957                warn_ambiguity || binding.warn_ambiguity,
1958            );
1959        }
1960    }
1961
1962    #[inline]
1963    fn add_to_glob_map(&mut self, import: Import<'_>, ident: Ident) {
1964        if let ImportKind::Glob { id, .. } = import.kind {
1965            let def_id = self.local_def_id(id);
1966            self.glob_map.entry(def_id).or_default().insert(ident.name);
1967        }
1968    }
1969
1970    fn resolve_crate_root(&mut self, ident: Ident) -> Module<'ra> {
1971        debug!("resolve_crate_root({:?})", ident);
1972        let mut ctxt = ident.span.ctxt();
1973        let mark = if ident.name == kw::DollarCrate {
1974            // When resolving `$crate` from a `macro_rules!` invoked in a `macro`,
1975            // we don't want to pretend that the `macro_rules!` definition is in the `macro`
1976            // as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks.
1977            // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!`
1978            // definitions actually produced by `macro` and `macro` definitions produced by
1979            // `macro_rules!`, but at least such configurations are not stable yet.
1980            ctxt = ctxt.normalize_to_macro_rules();
1981            debug!(
1982                "resolve_crate_root: marks={:?}",
1983                ctxt.marks().into_iter().map(|(i, t)| (i.expn_data(), t)).collect::<Vec<_>>()
1984            );
1985            let mut iter = ctxt.marks().into_iter().rev().peekable();
1986            let mut result = None;
1987            // Find the last opaque mark from the end if it exists.
1988            while let Some(&(mark, transparency)) = iter.peek() {
1989                if transparency == Transparency::Opaque {
1990                    result = Some(mark);
1991                    iter.next();
1992                } else {
1993                    break;
1994                }
1995            }
1996            debug!(
1997                "resolve_crate_root: found opaque mark {:?} {:?}",
1998                result,
1999                result.map(|r| r.expn_data())
2000            );
2001            // Then find the last semi-transparent mark from the end if it exists.
2002            for (mark, transparency) in iter {
2003                if transparency == Transparency::SemiTransparent {
2004                    result = Some(mark);
2005                } else {
2006                    break;
2007                }
2008            }
2009            debug!(
2010                "resolve_crate_root: found semi-transparent mark {:?} {:?}",
2011                result,
2012                result.map(|r| r.expn_data())
2013            );
2014            result
2015        } else {
2016            debug!("resolve_crate_root: not DollarCrate");
2017            ctxt = ctxt.normalize_to_macros_2_0();
2018            ctxt.adjust(ExpnId::root())
2019        };
2020        let module = match mark {
2021            Some(def) => self.expn_def_scope(def),
2022            None => {
2023                debug!(
2024                    "resolve_crate_root({:?}): found no mark (ident.span = {:?})",
2025                    ident, ident.span
2026                );
2027                return self.graph_root;
2028            }
2029        };
2030        let module = self.expect_module(
2031            module.opt_def_id().map_or(LOCAL_CRATE, |def_id| def_id.krate).as_def_id(),
2032        );
2033        debug!(
2034            "resolve_crate_root({:?}): got module {:?} ({:?}) (ident.span = {:?})",
2035            ident,
2036            module,
2037            module.kind.name(),
2038            ident.span
2039        );
2040        module
2041    }
2042
2043    fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'ra>) -> Module<'ra> {
2044        let mut module = self.expect_module(module.nearest_parent_mod());
2045        while module.span.ctxt().normalize_to_macros_2_0() != *ctxt {
2046            let parent = module.parent.unwrap_or_else(|| self.expn_def_scope(ctxt.remove_mark()));
2047            module = self.expect_module(parent.nearest_parent_mod());
2048        }
2049        module
2050    }
2051
2052    fn record_partial_res(&mut self, node_id: NodeId, resolution: PartialRes) {
2053        debug!("(recording res) recording {:?} for {}", resolution, node_id);
2054        if let Some(prev_res) = self.partial_res_map.insert(node_id, resolution) {
2055            panic!("path resolved multiple times ({prev_res:?} before, {resolution:?} now)");
2056        }
2057    }
2058
2059    fn record_pat_span(&mut self, node: NodeId, span: Span) {
2060        debug!("(recording pat) recording {:?} for {:?}", node, span);
2061        self.pat_span_map.insert(node, span);
2062    }
2063
2064    fn is_accessible_from(
2065        &self,
2066        vis: ty::Visibility<impl Into<DefId>>,
2067        module: Module<'ra>,
2068    ) -> bool {
2069        vis.is_accessible_from(module.nearest_parent_mod(), self.tcx)
2070    }
2071
2072    fn set_binding_parent_module(&mut self, binding: NameBinding<'ra>, module: Module<'ra>) {
2073        if let Some(old_module) = self.binding_parent_modules.insert(binding, module) {
2074            if module != old_module {
2075                span_bug!(binding.span, "parent module is reset for binding");
2076            }
2077        }
2078    }
2079
2080    fn disambiguate_macro_rules_vs_modularized(
2081        &self,
2082        macro_rules: NameBinding<'ra>,
2083        modularized: NameBinding<'ra>,
2084    ) -> bool {
2085        // Some non-controversial subset of ambiguities "modularized macro name" vs "macro_rules"
2086        // is disambiguated to mitigate regressions from macro modularization.
2087        // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general.
2088        match (
2089            self.binding_parent_modules.get(&macro_rules),
2090            self.binding_parent_modules.get(&modularized),
2091        ) {
2092            (Some(macro_rules), Some(modularized)) => {
2093                macro_rules.nearest_parent_mod() == modularized.nearest_parent_mod()
2094                    && modularized.is_ancestor_of(*macro_rules)
2095            }
2096            _ => false,
2097        }
2098    }
2099
2100    fn extern_prelude_get(&mut self, ident: Ident, finalize: bool) -> Option<NameBinding<'ra>> {
2101        if ident.is_path_segment_keyword() {
2102            // Make sure `self`, `super` etc produce an error when passed to here.
2103            return None;
2104        }
2105
2106        let norm_ident = ident.normalize_to_macros_2_0();
2107        let binding = self.extern_prelude.get(&norm_ident).cloned().and_then(|entry| {
2108            Some(if let Some(binding) = entry.binding {
2109                if finalize {
2110                    if !entry.is_import() {
2111                        self.crate_loader(|c| c.process_path_extern(ident.name, ident.span));
2112                    } else if entry.introduced_by_item {
2113                        self.record_use(ident, binding, Used::Other);
2114                    }
2115                }
2116                binding
2117            } else {
2118                let crate_id = if finalize {
2119                    let Some(crate_id) =
2120                        self.crate_loader(|c| c.process_path_extern(ident.name, ident.span))
2121                    else {
2122                        return Some(self.dummy_binding);
2123                    };
2124                    crate_id
2125                } else {
2126                    self.crate_loader(|c| c.maybe_process_path_extern(ident.name))?
2127                };
2128                let crate_root = self.expect_module(crate_id.as_def_id());
2129                let vis = ty::Visibility::<DefId>::Public;
2130                (crate_root, vis, DUMMY_SP, LocalExpnId::ROOT).to_name_binding(self.arenas)
2131            })
2132        });
2133
2134        if let Some(entry) = self.extern_prelude.get_mut(&norm_ident) {
2135            entry.binding = binding;
2136        }
2137
2138        binding
2139    }
2140
2141    /// Rustdoc uses this to resolve doc link paths in a recoverable way. `PathResult<'a>`
2142    /// isn't something that can be returned because it can't be made to live that long,
2143    /// and also it's a private type. Fortunately rustdoc doesn't need to know the error,
2144    /// just that an error occurred.
2145    fn resolve_rustdoc_path(
2146        &mut self,
2147        path_str: &str,
2148        ns: Namespace,
2149        parent_scope: ParentScope<'ra>,
2150    ) -> Option<Res> {
2151        let mut segments =
2152            Vec::from_iter(path_str.split("::").map(Ident::from_str).map(Segment::from_ident));
2153        if let Some(segment) = segments.first_mut() {
2154            if segment.ident.name == kw::Empty {
2155                segment.ident.name = kw::PathRoot;
2156            }
2157        }
2158
2159        match self.maybe_resolve_path(&segments, Some(ns), &parent_scope, None) {
2160            PathResult::Module(ModuleOrUniformRoot::Module(module)) => Some(module.res().unwrap()),
2161            PathResult::NonModule(path_res) => {
2162                path_res.full_res().filter(|res| !matches!(res, Res::Def(DefKind::Ctor(..), _)))
2163            }
2164            PathResult::Module(ModuleOrUniformRoot::ExternPrelude) | PathResult::Failed { .. } => {
2165                None
2166            }
2167            PathResult::Module(..) | PathResult::Indeterminate => unreachable!(),
2168        }
2169    }
2170
2171    /// Retrieves definition span of the given `DefId`.
2172    fn def_span(&self, def_id: DefId) -> Span {
2173        match def_id.as_local() {
2174            Some(def_id) => self.tcx.source_span(def_id),
2175            // Query `def_span` is not used because hashing its result span is expensive.
2176            None => self.cstore().def_span_untracked(def_id, self.tcx.sess),
2177        }
2178    }
2179
2180    fn field_idents(&self, def_id: DefId) -> Option<Vec<Ident>> {
2181        match def_id.as_local() {
2182            Some(def_id) => self.field_names.get(&def_id).cloned(),
2183            None => Some(
2184                self.tcx
2185                    .associated_item_def_ids(def_id)
2186                    .iter()
2187                    .map(|&def_id| {
2188                        Ident::new(self.tcx.item_name(def_id), self.tcx.def_span(def_id))
2189                    })
2190                    .collect(),
2191            ),
2192        }
2193    }
2194
2195    /// Checks if an expression refers to a function marked with
2196    /// `#[rustc_legacy_const_generics]` and returns the argument index list
2197    /// from the attribute.
2198    fn legacy_const_generic_args(&mut self, expr: &Expr) -> Option<Vec<usize>> {
2199        if let ExprKind::Path(None, path) = &expr.kind {
2200            // Don't perform legacy const generics rewriting if the path already
2201            // has generic arguments.
2202            if path.segments.last().unwrap().args.is_some() {
2203                return None;
2204            }
2205
2206            let res = self.partial_res_map.get(&expr.id)?.full_res()?;
2207            if let Res::Def(def::DefKind::Fn, def_id) = res {
2208                // We only support cross-crate argument rewriting. Uses
2209                // within the same crate should be updated to use the new
2210                // const generics style.
2211                if def_id.is_local() {
2212                    return None;
2213                }
2214
2215                if let Some(v) = self.legacy_const_generic_args.get(&def_id) {
2216                    return v.clone();
2217                }
2218
2219                let attr = self.tcx.get_attr(def_id, sym::rustc_legacy_const_generics)?;
2220                let mut ret = Vec::new();
2221                for meta in attr.meta_item_list()? {
2222                    match meta.lit()?.kind {
2223                        LitKind::Int(a, _) => ret.push(a.get() as usize),
2224                        _ => panic!("invalid arg index"),
2225                    }
2226                }
2227                // Cache the lookup to avoid parsing attributes for an item multiple times.
2228                self.legacy_const_generic_args.insert(def_id, Some(ret.clone()));
2229                return Some(ret);
2230            }
2231        }
2232        None
2233    }
2234
2235    fn resolve_main(&mut self) {
2236        let module = self.graph_root;
2237        let ident = Ident::with_dummy_span(sym::main);
2238        let parent_scope = &ParentScope::module(module, self);
2239
2240        let Ok(name_binding) = self.maybe_resolve_ident_in_module(
2241            ModuleOrUniformRoot::Module(module),
2242            ident,
2243            ValueNS,
2244            parent_scope,
2245            None,
2246        ) else {
2247            return;
2248        };
2249
2250        let res = name_binding.res();
2251        let is_import = name_binding.is_import();
2252        let span = name_binding.span;
2253        if let Res::Def(DefKind::Fn, _) = res {
2254            self.record_use(ident, name_binding, Used::Other);
2255        }
2256        self.main_def = Some(MainDefinition { res, is_import, span });
2257    }
2258}
2259
2260fn names_to_string(names: impl Iterator<Item = Symbol>) -> String {
2261    let mut result = String::new();
2262    for (i, name) in names.filter(|name| *name != kw::PathRoot).enumerate() {
2263        if i > 0 {
2264            result.push_str("::");
2265        }
2266        if Ident::with_dummy_span(name).is_raw_guess() {
2267            result.push_str("r#");
2268        }
2269        result.push_str(name.as_str());
2270    }
2271    result
2272}
2273
2274fn path_names_to_string(path: &Path) -> String {
2275    names_to_string(path.segments.iter().map(|seg| seg.ident.name))
2276}
2277
2278/// A somewhat inefficient routine to obtain the name of a module.
2279fn module_to_string(mut module: Module<'_>) -> Option<String> {
2280    let mut names = Vec::new();
2281    loop {
2282        if let ModuleKind::Def(.., name) = module.kind {
2283            if let Some(parent) = module.parent {
2284                // `unwrap` is safe: the presence of a parent means it's not the crate root.
2285                names.push(name.unwrap());
2286                module = parent
2287            } else {
2288                break;
2289            }
2290        } else {
2291            names.push(sym::opaque_module_name_placeholder);
2292            let Some(parent) = module.parent else {
2293                return None;
2294            };
2295            module = parent;
2296        }
2297    }
2298    if names.is_empty() {
2299        return None;
2300    }
2301    Some(names_to_string(names.iter().rev().copied()))
2302}
2303
2304#[derive(Copy, Clone, Debug)]
2305struct Finalize {
2306    /// Node ID for linting.
2307    node_id: NodeId,
2308    /// Span of the whole path or some its characteristic fragment.
2309    /// E.g. span of `b` in `foo::{a, b, c}`, or full span for regular paths.
2310    path_span: Span,
2311    /// Span of the path start, suitable for prepending something to it.
2312    /// E.g. span of `foo` in `foo::{a, b, c}`, or full span for regular paths.
2313    root_span: Span,
2314    /// Whether to report privacy errors or silently return "no resolution" for them,
2315    /// similarly to speculative resolution.
2316    report_private: bool,
2317    /// Tracks whether an item is used in scope or used relatively to a module.
2318    used: Used,
2319}
2320
2321impl Finalize {
2322    fn new(node_id: NodeId, path_span: Span) -> Finalize {
2323        Finalize::with_root_span(node_id, path_span, path_span)
2324    }
2325
2326    fn with_root_span(node_id: NodeId, path_span: Span, root_span: Span) -> Finalize {
2327        Finalize { node_id, path_span, root_span, report_private: true, used: Used::Other }
2328    }
2329}
2330
2331pub fn provide(providers: &mut Providers) {
2332    providers.registered_tools = macros::registered_tools;
2333}