Skip to main content

hir_def/
nameres.rs

1//! This module implements import-resolution/macro expansion algorithm.
2//!
3//! The result of this module is `DefMap`: a data structure which contains:
4//!
5//!   * a tree of modules for the crate
6//!   * for each module, a set of items visible in the module (directly declared
7//!     or imported)
8//!
9//! Note that `DefMap` contains fully macro expanded code.
10//!
11//! Computing `DefMap` can be partitioned into several logically
12//! independent "phases". The phases are mutually recursive though, there's no
13//! strict ordering.
14//!
15//! ## Collecting RawItems
16//!
17//! This happens in the `raw` module, which parses a single source file into a
18//! set of top-level items. Nested imports are desugared to flat imports in this
19//! phase. Macro calls are represented as a triple of `(Path, Option<Name>,
20//! TokenTree)`.
21//!
22//! ## Collecting Modules
23//!
24//! This happens in the `collector` module. In this phase, we recursively walk
25//! tree of modules, collect raw items from submodules, populate module scopes
26//! with defined items (so, we assign item ids in this phase) and record the set
27//! of unresolved imports and macros.
28//!
29//! While we walk tree of modules, we also record macro_rules definitions and
30//! expand calls to macro_rules defined macros.
31//!
32//! ## Resolving Imports
33//!
34//! We maintain a list of currently unresolved imports. On every iteration, we
35//! try to resolve some imports from this list. If the import is resolved, we
36//! record it, by adding an item to current module scope and, if necessary, by
37//! recursively populating glob imports.
38//!
39//! ## Resolving Macros
40//!
41//! macro_rules from the same crate use a global mutable namespace. We expand
42//! them immediately, when we collect modules.
43//!
44//! Macros from other crates (including proc-macros) can be used with
45//! `foo::bar!` syntax. We handle them similarly to imports. There's a list of
46//! unexpanded macros. On every iteration, we try to resolve each macro call
47//! path and, upon success, we run macro expansion and "collect module" phase on
48//! the result
49
50pub mod assoc;
51pub mod attr_resolution;
52mod collector;
53pub mod diagnostics;
54mod mod_resolution;
55mod path_resolution;
56pub mod proc_macro;
57
58#[cfg(test)]
59mod tests;
60
61use std::ops::{Deref, DerefMut, Index, IndexMut};
62
63use base_db::{Crate, SourceDatabase};
64use either::Either;
65use hir_expand::{
66    EditionedFileId, ErasedAstId, HirFileId, InFile, MacroCallId, mod_path::ModPath, name::Name,
67    proc_macro::ProcMacroKind,
68};
69use intern::{Symbol, sym};
70use itertools::Itertools;
71use rustc_hash::FxHashMap;
72use span::{Edition, FileAstId, FileId, ROOT_ERASED_FILE_AST_ID};
73use stdx::format_to;
74use syntax::{AstNode, SmolStr, SyntaxNode, ToSmolStr, ast};
75use thin_vec::ThinVec;
76use triomphe::Arc;
77use tt::TextRange;
78
79use crate::{
80    AstId, BlockId, BlockIdLt, BuiltinDeriveImplId, ExternCrateId, FunctionId, FxIndexMap, Lookup,
81    MacroCallStyles, MacroExpander, MacroId, ModuleId, ModuleIdLt, ProcMacroId, ThinFxHashMap,
82    UseId,
83    item_scope::{BuiltinShadowMode, ItemScope},
84    item_tree::TreeId,
85    nameres::{diagnostics::DefDiagnostic, path_resolution::ResolveMode},
86    per_ns::PerNs,
87    unstable_features::UnstableFeatures,
88    visibility::{Visibility, VisibilityExplicitness},
89};
90
91pub use self::path_resolution::ResolvePathResultPrefixInfo;
92
93#[cfg(test)]
94thread_local! {
95    /// HACK: In order to test builtin derive expansion, we gate their fast path with this atomic when cfg(test).
96    pub(crate) static ENABLE_BUILTIN_DERIVE_FAST_PATH: std::cell::Cell<bool> =
97        const { std::cell::Cell::new(true) };
98}
99
100#[inline]
101#[cfg(test)]
102fn enable_builtin_derive_fast_path() -> bool {
103    ENABLE_BUILTIN_DERIVE_FAST_PATH.get()
104}
105
106#[inline(always)]
107#[cfg(not(test))]
108fn enable_builtin_derive_fast_path() -> bool {
109    true
110}
111
112const PREDEFINED_TOOLS: &[SmolStr] = &[
113    SmolStr::new_static("clippy"),
114    SmolStr::new_static("rustfmt"),
115    SmolStr::new_static("diagnostic"),
116    SmolStr::new_static("miri"),
117    SmolStr::new_static("rust_analyzer"),
118];
119
120/// Parts of the def map that are only needed when analyzing code in the same crate.
121///
122/// There are some data in the def map (e.g. extern prelude) that is only needed when analyzing
123/// things in the same crate (and maybe in the IDE layer), e.g. the extern prelude. If we put
124/// it in the DefMap dependant DefMaps will be invalidated when they change (e.g. when we add
125/// a dependency to the crate). Instead we split them out of the DefMap into a LocalDefMap struct.
126/// `crate_local_def_map()` returns both, and `crate_def_map()` returns only the external-relevant
127/// DefMap.
128#[derive(Debug, PartialEq, Eq, Default)]
129pub struct LocalDefMap {
130    // FIXME: There are probably some other things that could be here, but this is less severe and you
131    // need to be careful with things that block def maps also have.
132    /// The extern prelude which contains all root modules of external crates that are in scope.
133    extern_prelude: FxIndexMap<Name, (ModuleId, Option<ExternCrateId>)>,
134}
135
136impl std::hash::Hash for LocalDefMap {
137    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
138        let LocalDefMap { extern_prelude } = self;
139        extern_prelude.len().hash(state);
140        for (name, (crate_root, extern_crate)) in extern_prelude {
141            name.hash(state);
142            crate_root.hash(state);
143            extern_crate.hash(state);
144        }
145    }
146}
147
148impl LocalDefMap {
149    pub(crate) const EMPTY: &Self =
150        &Self { extern_prelude: FxIndexMap::with_hasher(rustc_hash::FxBuildHasher) };
151
152    fn shrink_to_fit(&mut self) {
153        let Self { extern_prelude } = self;
154        extern_prelude.shrink_to_fit();
155    }
156
157    pub(crate) fn extern_prelude(
158        &self,
159    ) -> impl DoubleEndedIterator<Item = (&Name, (ModuleId, Option<ExternCrateId>))> + '_ {
160        self.extern_prelude.iter().map(|(name, &def)| (name, def))
161    }
162}
163
164/// Contains the results of (early) name resolution.
165///
166/// A `DefMap` stores the module tree and the definitions that are in scope in every module after
167/// item-level macros have been expanded.
168///
169/// Every crate has a primary `DefMap` whose root is the crate's main file (`main.rs`/`lib.rs`),
170/// computed by the `crate_def_map` query. Additionally, every block expression introduces the
171/// opportunity to write arbitrary item and module hierarchies, and thus gets its own `DefMap` that
172/// is computed by the `block_def_map` query.
173#[derive(Debug, PartialEq, Eq)]
174pub struct DefMap {
175    /// The crate this `DefMap` belongs to.
176    krate: Crate,
177    /// When this is a block def map, this will hold the block id of the block and module that
178    /// contains this block.
179    block: Option<BlockInfo>,
180    pub root: ModuleId,
181    /// The modules and their data declared in this crate.
182    pub modules: ModulesMap,
183    /// The prelude module for this crate. This either comes from an import
184    /// marked with the `prelude_import` attribute, or (in the normal case) from
185    /// a dependency (`std` or `core`).
186    /// The prelude is empty for non-block DefMaps (unless `#[prelude_import]` was used,
187    /// but that attribute is nightly and when used in a block, it affects resolution globally
188    /// so we aren't handling this correctly anyways).
189    prelude: Option<(ModuleId, Option<UseId>)>,
190    /// `macro_use` prelude that contains macros from `#[macro_use]`'d external crates. Note that
191    /// this contains all kinds of macro, not just `macro_rules!` macro.
192    /// ExternCrateId being None implies it being imported from the general prelude import.
193    macro_use_prelude: ThinFxHashMap<Name, (MacroId, Option<ExternCrateId>)>,
194
195    /// Tracks which custom derives are in scope for an item, to allow resolution of derive helper
196    /// attributes.
197    // FIXME: Figure out a better way for the IDE layer to resolve these?
198    derive_helpers_in_scope: ThinFxHashMap<
199        AstId<ast::Item>,
200        Vec<(Name, MacroId, Either<MacroCallId, BuiltinDeriveImplId>)>,
201    >,
202    /// A mapping from [`hir_expand::MacroDefId`] to [`crate::MacroId`].
203    pub macro_def_to_macro_id: ThinFxHashMap<ErasedAstId, MacroId>,
204
205    /// The diagnostics that need to be emitted for this crate.
206    diagnostics: ThinVec<DefDiagnostic>,
207
208    /// The crate data that is shared between a crate's def map and all its block def maps.
209    data: Arc<DefMapCrateData>,
210}
211
212/// Data that belongs to a crate which is shared between a crate's def map and all its block def maps.
213#[derive(Clone, Debug, PartialEq, Eq)]
214struct DefMapCrateData {
215    /// Side table for resolving derive helpers.
216    exported_derives: FxHashMap<MacroId, Box<[Name]>>,
217    fn_proc_macro_mapping: FxHashMap<FunctionId, ProcMacroId>,
218    fn_proc_macro_mapping_back: FxHashMap<ProcMacroId, FunctionId>,
219
220    /// Custom tool modules registered with `#![register_tool]`.
221    registered_tools: Vec<Symbol>,
222    /// Unstable features of Rust enabled with `#![feature(A, B)]`.
223    unstable_features: UnstableFeatures,
224    /// `#[rustc_coherence_is_core]`
225    rustc_coherence_is_core: bool,
226    no_core: bool,
227    no_std: bool,
228
229    edition: Edition,
230    recursion_limit: Option<u32>,
231}
232
233impl DefMapCrateData {
234    fn new(edition: Edition) -> Self {
235        Self {
236            exported_derives: FxHashMap::default(),
237            fn_proc_macro_mapping: FxHashMap::default(),
238            fn_proc_macro_mapping_back: FxHashMap::default(),
239            registered_tools: PREDEFINED_TOOLS.iter().map(|it| Symbol::intern(it)).collect(),
240            unstable_features: UnstableFeatures::default(),
241            rustc_coherence_is_core: false,
242            no_core: false,
243            no_std: false,
244            edition,
245            recursion_limit: None,
246        }
247    }
248
249    fn shrink_to_fit(&mut self) {
250        let Self {
251            exported_derives,
252            fn_proc_macro_mapping,
253            fn_proc_macro_mapping_back,
254            registered_tools,
255            unstable_features,
256            rustc_coherence_is_core: _,
257            no_core: _,
258            no_std: _,
259            edition: _,
260            recursion_limit: _,
261        } = self;
262        exported_derives.shrink_to_fit();
263        fn_proc_macro_mapping.shrink_to_fit();
264        fn_proc_macro_mapping_back.shrink_to_fit();
265        registered_tools.shrink_to_fit();
266        unstable_features.shrink_to_fit();
267    }
268}
269
270/// For `DefMap`s computed for a block expression, this stores its location in the parent map.
271#[derive(Debug, PartialEq, Eq, Clone, Copy)]
272struct BlockInfo {
273    /// The `BlockId` this `DefMap` was created from.
274    block: BlockId,
275    /// The containing module.
276    parent: ModuleId,
277}
278
279impl std::ops::Index<ModuleIdLt<'_>> for DefMap {
280    type Output = ModuleData;
281
282    fn index(&self, id: ModuleIdLt<'_>) -> &ModuleData {
283        self.modules
284            .get(&unsafe { id.to_static() })
285            .unwrap_or_else(|| panic!("ModuleId not found in ModulesMap {:#?}: {id:#?}", self.root))
286    }
287}
288
289impl std::ops::IndexMut<ModuleId> for DefMap {
290    fn index_mut(&mut self, id: ModuleId) -> &mut ModuleData {
291        &mut self.modules[id]
292    }
293}
294
295#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
296pub enum ModuleOrigin {
297    CrateRoot {
298        definition: EditionedFileId,
299    },
300    /// Note that non-inline modules, by definition, live inside non-macro file.
301    File {
302        is_mod_rs: bool,
303        declaration: FileAstId<ast::Module>,
304        declaration_tree_id: TreeId,
305        definition: EditionedFileId,
306    },
307    Inline {
308        definition_tree_id: TreeId,
309        definition: FileAstId<ast::Module>,
310    },
311    /// Pseudo-module introduced by a block scope (contains only inner items).
312    BlockExpr {
313        id: BlockId,
314        block: AstId<ast::BlockExpr>,
315    },
316}
317
318impl ModuleOrigin {
319    pub fn declaration(&self) -> Option<AstId<ast::Module>> {
320        match self {
321            &ModuleOrigin::File { declaration, declaration_tree_id, .. } => {
322                Some(AstId::new(declaration_tree_id.file_id(), declaration))
323            }
324            &ModuleOrigin::Inline { definition, definition_tree_id } => {
325                Some(AstId::new(definition_tree_id.file_id(), definition))
326            }
327            ModuleOrigin::CrateRoot { .. } | ModuleOrigin::BlockExpr { .. } => None,
328        }
329    }
330
331    pub fn file_id(&self) -> Option<EditionedFileId> {
332        match self {
333            ModuleOrigin::File { definition, .. } | ModuleOrigin::CrateRoot { definition } => {
334                Some(*definition)
335            }
336            _ => None,
337        }
338    }
339
340    pub fn is_inline(&self) -> bool {
341        match self {
342            ModuleOrigin::Inline { .. } | ModuleOrigin::BlockExpr { .. } => true,
343            ModuleOrigin::CrateRoot { .. } | ModuleOrigin::File { .. } => false,
344        }
345    }
346
347    /// Returns a node which defines this module.
348    /// That is, a file or a `mod foo {}` with items.
349    pub fn definition_source(&self, db: &dyn SourceDatabase) -> InFile<ModuleSource> {
350        match self {
351            &ModuleOrigin::File { definition: editioned_file_id, .. }
352            | &ModuleOrigin::CrateRoot { definition: editioned_file_id } => {
353                let sf = editioned_file_id.parse(db).tree();
354                InFile::new(editioned_file_id.into(), ModuleSource::SourceFile(sf))
355            }
356            &ModuleOrigin::Inline { definition, definition_tree_id } => InFile::new(
357                definition_tree_id.file_id(),
358                ModuleSource::Module(
359                    AstId::new(definition_tree_id.file_id(), definition).to_node(db),
360                ),
361            ),
362            ModuleOrigin::BlockExpr { block, .. } => {
363                InFile::new(block.file_id, ModuleSource::BlockExpr(block.to_node(db)))
364            }
365        }
366    }
367}
368
369#[derive(Debug, PartialEq, Eq)]
370pub struct ModuleData {
371    /// Where does this module come from?
372    pub origin: ModuleOrigin,
373    /// Declared visibility of this module.
374    pub visibility: Visibility,
375    /// Parent module in the same `DefMap`.
376    ///
377    /// [`None`] for block modules because they are always its `DefMap`'s root.
378    pub parent: Option<ModuleId>,
379    pub children: ThinFxHashMap<Name, ModuleId>,
380    pub scope: ItemScope,
381}
382
383#[inline]
384pub fn crate_def_map(db: &dyn SourceDatabase, crate_id: Crate) -> &DefMap {
385    crate_local_def_map(db, crate_id).def_map(db)
386}
387
388#[salsa::tracked]
389pub(crate) struct DefMapPair<'db> {
390    #[tracked]
391    #[returns(ref)]
392    pub(crate) def_map: DefMap,
393    #[returns(ref)]
394    pub(crate) local: LocalDefMap,
395}
396
397#[salsa::tracked(returns(ref))]
398pub(crate) fn crate_local_def_map(db: &dyn SourceDatabase, crate_id: Crate) -> DefMapPair<'_> {
399    let krate = crate_id.data(db);
400    let _p = tracing::info_span!(
401        "crate_def_map_query",
402        name=?crate_id
403            .extra_data(db)
404            .display_name
405            .as_ref()
406            .map(|it| it.crate_name().to_smolstr())
407            .unwrap_or_default()
408    )
409    .entered();
410
411    let root_file_id = crate_id.root_file_id(db);
412    let module_data = ModuleData::new(
413        ModuleOrigin::CrateRoot { definition: root_file_id },
414        Visibility::Public,
415        None,
416    );
417
418    let def_map = DefMap::empty(
419        db,
420        crate_id,
421        Arc::new(DefMapCrateData::new(krate.edition)),
422        module_data,
423        None,
424    );
425    let (def_map, local_def_map) =
426        collector::collect_defs(db, def_map, TreeId::new(root_file_id.into(), None), None);
427
428    DefMapPair::new(db, def_map, local_def_map)
429}
430
431#[salsa::tracked(returns(ref))]
432pub fn block_def_map<'db>(db: &'db dyn SourceDatabase, block_id: BlockIdLt<'db>) -> DefMap {
433    let block_id = unsafe { block_id.to_static() };
434    let ast_id = block_id.ast_id(db);
435    let module = unsafe { block_id.module(db).to_static() };
436
437    let visibility = Visibility::Module(module, VisibilityExplicitness::Implicit);
438    let module_data =
439        ModuleData::new(ModuleOrigin::BlockExpr { block: ast_id, id: block_id }, visibility, None);
440
441    let krate = module.krate(db);
442    let local_def_map = crate_local_def_map(db, krate);
443    let def_map = DefMap::empty(
444        db,
445        krate,
446        local_def_map.def_map(db).data.clone(),
447        module_data,
448        Some(BlockInfo { block: block_id, parent: module }),
449    );
450
451    let (def_map, _) = collector::collect_defs(
452        db,
453        def_map,
454        TreeId::new(ast_id.file_id, Some(block_id)),
455        Some(local_def_map.local(db)),
456    );
457    def_map
458}
459
460impl DefMap {
461    pub fn edition(&self) -> Edition {
462        self.data.edition
463    }
464
465    fn empty(
466        db: &dyn SourceDatabase,
467        krate: Crate,
468        crate_data: Arc<DefMapCrateData>,
469        module_data: ModuleData,
470        block: Option<BlockInfo>,
471    ) -> DefMap {
472        let mut modules = ModulesMap::new();
473        let root = unsafe {
474            ModuleIdLt::new(
475                db,
476                krate,
477                block.map(|it| it.block),
478                None,
479                Name::new_symbol_root(sym::__empty),
480            )
481            .to_static()
482        };
483        modules.insert(root, module_data);
484
485        DefMap {
486            block,
487            root,
488            modules,
489            krate,
490            prelude: None,
491            macro_use_prelude: ThinFxHashMap::default(),
492            derive_helpers_in_scope: ThinFxHashMap::default(),
493            diagnostics: ThinVec::new(),
494            data: crate_data,
495            macro_def_to_macro_id: ThinFxHashMap::default(),
496        }
497    }
498    fn shrink_to_fit(&mut self) {
499        // Exhaustive match to require handling new fields.
500        let Self {
501            macro_use_prelude,
502            diagnostics,
503            modules,
504            derive_helpers_in_scope,
505            root: _,
506            block: _,
507            krate: _,
508            prelude: _,
509            data: _,
510            macro_def_to_macro_id,
511        } = self;
512
513        macro_def_to_macro_id.shrink_to_fit();
514        macro_use_prelude.shrink_to_fit();
515        diagnostics.shrink_to_fit();
516        modules.shrink_to_fit();
517        derive_helpers_in_scope.shrink_to_fit();
518        for (_, module) in modules.iter_mut() {
519            module.children.shrink_to_fit();
520            module.scope.shrink_to_fit();
521        }
522    }
523}
524
525impl DefMap {
526    /// Returns all modules in the crate that are associated with the given file.
527    pub fn modules_for_file<'a>(
528        &'a self,
529        db: &'a dyn SourceDatabase,
530        file_id: FileId,
531    ) -> impl Iterator<Item = ModuleId> + 'a {
532        self.modules
533            .iter()
534            .filter(move |(_, data)| {
535                data.origin.file_id().map(|file_id| file_id.file_id(db)) == Some(file_id)
536            })
537            .map(|(id, _)| id)
538    }
539
540    pub fn modules(&self) -> impl Iterator<Item = (ModuleId, &ModuleData)> + '_ {
541        self.modules.iter()
542    }
543
544    /// Returns all inline modules (mod name { ... }) in the crate that are associated with the given macro expansion.
545    pub fn inline_modules_for_macro_file(
546        &self,
547        file_id: MacroCallId,
548    ) -> impl Iterator<Item = ModuleId> + '_ {
549        self.modules
550            .iter()
551            .filter(move |(_, data)| {
552                matches!(
553                    data.origin,
554                    ModuleOrigin::Inline { definition_tree_id, .. }
555                    if definition_tree_id.file_id().macro_file() == Some(file_id)
556                )
557            })
558            .map(|(id, _)| id)
559    }
560
561    pub fn derive_helpers_in_scope(
562        &self,
563        id: AstId<ast::Adt>,
564    ) -> Option<&[(Name, MacroId, Either<MacroCallId, BuiltinDeriveImplId>)]> {
565        self.derive_helpers_in_scope.get(&id.map(|it| it.upcast())).map(Deref::deref)
566    }
567
568    pub fn registered_tools(&self) -> &[Symbol] {
569        &self.data.registered_tools
570    }
571
572    #[inline]
573    pub fn features(&self) -> &UnstableFeatures {
574        &self.data.unstable_features
575    }
576
577    pub fn is_rustc_coherence_is_core(&self) -> bool {
578        self.data.rustc_coherence_is_core
579    }
580
581    pub fn is_no_std(&self) -> bool {
582        self.data.no_std || self.data.no_core
583    }
584
585    pub fn is_no_core(&self) -> bool {
586        self.data.no_core
587    }
588
589    pub fn fn_as_proc_macro(&self, id: FunctionId) -> Option<ProcMacroId> {
590        self.data.fn_proc_macro_mapping.get(&id).copied()
591    }
592
593    pub fn proc_macro_as_fn(&self, id: ProcMacroId) -> Option<FunctionId> {
594        self.data.fn_proc_macro_mapping_back.get(&id).copied()
595    }
596
597    pub fn krate(&self) -> Crate {
598        self.krate
599    }
600
601    #[inline]
602    pub fn crate_root(&self, db: &dyn SourceDatabase) -> ModuleId {
603        match self.block {
604            Some(_) => crate_def_map(db, self.krate()).root,
605            None => self.root,
606        }
607    }
608
609    /// This is the same as [`Self::crate_root`] for crate def maps, but for block def maps, it
610    /// returns the root block module.
611    pub fn root_module_id(&self) -> ModuleId {
612        self.root
613    }
614
615    /// If this `DefMap` is for a block expression, returns the module containing the block (which
616    /// might again be a block, or a module inside a block).
617    pub fn parent(&self) -> Option<ModuleId> {
618        Some(self.block?.parent)
619    }
620
621    /// Returns the module containing `local_mod`, either the parent `mod`, or the module (or block) containing
622    /// the block, if `self` corresponds to a block expression.
623    pub fn containing_module(&self, local_mod: ModuleIdLt<'_>) -> Option<ModuleId> {
624        match self[local_mod].parent {
625            Some(parent) => Some(parent),
626            None => self.block.map(|BlockInfo { parent, .. }| parent),
627        }
628    }
629
630    /// Get a reference to the def map's diagnostics.
631    pub fn diagnostics(&self) -> &[DefDiagnostic] {
632        self.diagnostics.as_slice()
633    }
634
635    pub fn recursion_limit(&self) -> u32 {
636        // 128 is the default in rustc
637        self.data.recursion_limit.unwrap_or(128)
638    }
639
640    // FIXME: this can use some more human-readable format (ideally, an IR
641    // even), as this should be a great debugging aid.
642    pub fn dump(&self, db: &dyn SourceDatabase) -> String {
643        let mut buf = String::new();
644        let mut current_map = self;
645        while let Some(block) = current_map.block {
646            go(&mut buf, db, current_map, "(block scope)", current_map.root);
647            buf.push('\n');
648            current_map = block.parent.def_map(db);
649        }
650        go(&mut buf, db, current_map, "crate", current_map.root);
651        return buf;
652
653        fn go(
654            buf: &mut String,
655            db: &dyn SourceDatabase,
656            map: &DefMap,
657            path: &str,
658            module: ModuleId,
659        ) {
660            format_to!(buf, "{}\n", path);
661
662            map[module].scope.dump(db, buf);
663
664            for (name, child) in map[module].children.iter().sorted_by(|a, b| Ord::cmp(&a.0, &b.0))
665            {
666                let path = format!("{path}::{}", name.display(db, Edition::LATEST));
667                buf.push('\n');
668                go(buf, db, map, &path, *child);
669            }
670        }
671    }
672}
673
674impl DefMap {
675    pub(crate) fn block_id(&self) -> Option<BlockId> {
676        self.block.map(|block| block.block)
677    }
678
679    pub(crate) fn prelude(&self) -> Option<(ModuleId, Option<UseId>)> {
680        self.prelude
681    }
682
683    pub(crate) fn macro_use_prelude(
684        &self,
685    ) -> &ThinFxHashMap<Name, (MacroId, Option<ExternCrateId>)> {
686        &self.macro_use_prelude
687    }
688
689    pub(crate) fn resolve_path(
690        &self,
691        local_def_map: &LocalDefMap,
692        db: &dyn SourceDatabase,
693        original_module: ModuleId,
694        path: &ModPath,
695        shadow: BuiltinShadowMode,
696        expected_macro_subns: Option<MacroSubNs>,
697    ) -> (PerNs, Option<usize>) {
698        let res = self.resolve_path_fp_with_macro(
699            local_def_map,
700            db,
701            ResolveMode::Other,
702            original_module,
703            path,
704            shadow,
705            expected_macro_subns,
706        );
707        (res.resolved_def, res.segment_index)
708    }
709
710    /// The first `Option<usize>` points at the `Enum` segment in case of `Enum::Variant`, the second
711    /// points at the unresolved segments.
712    pub(crate) fn resolve_path_locally(
713        &self,
714        local_def_map: &LocalDefMap,
715        db: &dyn SourceDatabase,
716        original_module: ModuleId,
717        path: &ModPath,
718        shadow: BuiltinShadowMode,
719    ) -> (PerNs, Option<usize>, ResolvePathResultPrefixInfo) {
720        let res = self.resolve_path_fp_with_macro_single(
721            local_def_map,
722            db,
723            ResolveMode::Other,
724            original_module,
725            path,
726            shadow,
727            None, // Currently this function isn't used for macro resolution.
728        );
729        (res.resolved_def, res.segment_index, res.prefix_info)
730    }
731
732    /// Ascends the `DefMap` hierarchy and calls `f` with every `DefMap` and containing module.
733    ///
734    /// If `f` returns `Some(val)`, iteration is stopped and `Some(val)` is returned. If `f` returns
735    /// `None`, iteration continues.
736    pub(crate) fn with_ancestor_maps<'db, T>(
737        &self,
738        db: &'db dyn SourceDatabase,
739        local_mod: ModuleIdLt<'db>,
740        f: &mut dyn FnMut(&DefMap, ModuleIdLt<'db>) -> Option<T>,
741    ) -> Option<T> {
742        if let Some(it) = f(self, local_mod) {
743            return Some(it);
744        }
745        let mut block = self.block;
746        while let Some(block_info) = block {
747            let parent = block_info.parent.def_map(db);
748            if let Some(it) = f(parent, block_info.parent) {
749                return Some(it);
750            }
751            block = parent.block;
752        }
753
754        None
755    }
756}
757
758impl ModuleData {
759    pub(crate) fn new(
760        origin: ModuleOrigin,
761        visibility: Visibility,
762        parent: Option<ModuleId>,
763    ) -> Self {
764        ModuleData {
765            origin,
766            visibility,
767            parent,
768            children: Default::default(),
769            scope: ItemScope::default(),
770        }
771    }
772
773    /// Returns a node which defines this module. That is, a file or a `mod foo {}` with items.
774    pub fn definition_source(&self, db: &dyn SourceDatabase) -> InFile<ModuleSource> {
775        self.origin.definition_source(db)
776    }
777
778    /// Same as [`ModuleData::definition_source`] but only returns the file id to prevent parsing the ASt.
779    pub fn definition_source_file_id(&self) -> HirFileId {
780        match self.origin {
781            ModuleOrigin::File { definition, .. } | ModuleOrigin::CrateRoot { definition } => {
782                definition.into()
783            }
784            ModuleOrigin::Inline { definition_tree_id, .. } => definition_tree_id.file_id(),
785            ModuleOrigin::BlockExpr { block, .. } => block.file_id,
786        }
787    }
788
789    pub fn definition_source_range(&self, db: &dyn SourceDatabase) -> InFile<TextRange> {
790        match &self.origin {
791            &ModuleOrigin::File { definition, .. } | &ModuleOrigin::CrateRoot { definition } => {
792                InFile::new(
793                    definition.into(),
794                    ErasedAstId::new(definition.into(), ROOT_ERASED_FILE_AST_ID).to_range(db),
795                )
796            }
797            &ModuleOrigin::Inline { definition, definition_tree_id } => InFile::new(
798                definition_tree_id.file_id(),
799                AstId::new(definition_tree_id.file_id(), definition).to_range(db),
800            ),
801            ModuleOrigin::BlockExpr { block, .. } => InFile::new(block.file_id, block.to_range(db)),
802        }
803    }
804
805    /// Returns a node which declares this module, either a `mod foo;` or a `mod foo {}`.
806    /// `None` for the crate root or block.
807    pub fn declaration_source(&self, db: &dyn SourceDatabase) -> Option<InFile<ast::Module>> {
808        let decl = self.origin.declaration()?;
809        let value = decl.to_node(db);
810        Some(InFile { file_id: decl.file_id, value })
811    }
812
813    /// Returns the range which declares this module, either a `mod foo;` or a `mod foo {}`.
814    /// `None` for the crate root or block.
815    pub fn declaration_source_range(&self, db: &dyn SourceDatabase) -> Option<InFile<TextRange>> {
816        let decl = self.origin.declaration()?;
817        Some(InFile { file_id: decl.file_id, value: decl.to_range(db) })
818    }
819}
820
821#[derive(Debug, Clone, PartialEq, Eq)]
822pub enum ModuleSource {
823    SourceFile(ast::SourceFile),
824    Module(ast::Module),
825    BlockExpr(ast::BlockExpr),
826}
827
828impl ModuleSource {
829    pub fn node(&self) -> SyntaxNode {
830        match self {
831            ModuleSource::SourceFile(it) => it.syntax().clone(),
832            ModuleSource::Module(it) => it.syntax().clone(),
833            ModuleSource::BlockExpr(it) => it.syntax().clone(),
834        }
835    }
836}
837
838/// See `sub_namespace_match()`.
839#[derive(Clone, Copy, PartialEq, Eq)]
840pub enum MacroSubNs {
841    /// Function-like macros, suffixed with `!`.
842    Bang,
843    /// Macros inside attributes, i.e. attribute macros and derive macros.
844    Attr,
845}
846
847pub(crate) fn macro_styles_from_id(db: &dyn SourceDatabase, macro_id: MacroId) -> MacroCallStyles {
848    let expander = match macro_id {
849        MacroId::Macro2Id(it) => it.lookup(db).expander,
850        MacroId::MacroRulesId(it) => it.lookup(db).expander,
851        MacroId::ProcMacroId(it) => {
852            return match it.lookup(db).kind {
853                ProcMacroKind::CustomDerive => MacroCallStyles::DERIVE,
854                ProcMacroKind::Bang => MacroCallStyles::FN_LIKE,
855                ProcMacroKind::Attr => MacroCallStyles::ATTR,
856            };
857        }
858    };
859
860    match expander {
861        MacroExpander::Declarative { styles } => styles,
862        // Eager macros aren't *guaranteed* to be bang macros, but they *are* all bang macros currently.
863        MacroExpander::BuiltIn(_) | MacroExpander::BuiltInEager(_) => MacroCallStyles::FN_LIKE,
864        MacroExpander::BuiltInAttr(_) => MacroCallStyles::ATTR,
865        MacroExpander::BuiltInDerive(_) => MacroCallStyles::DERIVE,
866        MacroExpander::UnimplementedBuiltIn => MacroCallStyles::all(), // Unknown.
867    }
868}
869
870/// Quoted from [rustc]:
871/// Macro namespace is separated into two sub-namespaces, one for bang macros and
872/// one for attribute-like macros (attributes, derives).
873/// We ignore resolutions from one sub-namespace when searching names in scope for another.
874///
875/// [rustc]: https://github.com/rust-lang/rust/blob/1.69.0/compiler/rustc_resolve/src/macros.rs#L75
876fn sub_namespace_match(
877    db: &dyn SourceDatabase,
878    macro_id: MacroId,
879    expected: Option<MacroSubNs>,
880) -> bool {
881    let candidate = macro_styles_from_id(db, macro_id);
882    match expected {
883        Some(MacroSubNs::Bang) => candidate.contains(MacroCallStyles::FN_LIKE),
884        Some(MacroSubNs::Attr) => {
885            candidate.contains(MacroCallStyles::ATTR) || candidate.contains(MacroCallStyles::DERIVE)
886        }
887        // If we aren't expecting a specific sub-namespace
888        // (e.g. in `use` declarations), match any macro.
889        None => true,
890    }
891}
892
893/// A newtype wrapper around `ThinFxHashMap<ModuleId, ModuleData>` that implements `IndexMut`.
894#[derive(Debug, PartialEq, Eq)]
895pub struct ModulesMap {
896    inner: ThinFxHashMap<ModuleId, ModuleData>,
897}
898
899impl ModulesMap {
900    fn new() -> Self {
901        Self { inner: ThinFxHashMap::new() }
902    }
903
904    fn iter(&self) -> impl Iterator<Item = (ModuleId, &ModuleData)> + '_ {
905        self.inner.iter().map(|(&k, v)| (k, v))
906    }
907
908    fn iter_mut(&mut self) -> impl Iterator<Item = (ModuleId, &mut ModuleData)> + '_ {
909        self.inner.iter_mut().map(|(&k, v)| (k, v))
910    }
911}
912
913impl Deref for ModulesMap {
914    type Target = ThinFxHashMap<ModuleId, ModuleData>;
915
916    fn deref(&self) -> &Self::Target {
917        &self.inner
918    }
919}
920
921impl DerefMut for ModulesMap {
922    fn deref_mut(&mut self) -> &mut Self::Target {
923        &mut self.inner
924    }
925}
926
927impl Index<ModuleIdLt<'_>> for ModulesMap {
928    type Output = ModuleData;
929
930    fn index(&self, id: ModuleIdLt<'_>) -> &ModuleData {
931        self.inner
932            .get(&unsafe { id.to_static() })
933            .unwrap_or_else(|| panic!("ModuleId not found in ModulesMap: {id:#?}"))
934    }
935}
936
937impl IndexMut<ModuleId> for ModulesMap {
938    fn index_mut(&mut self, id: ModuleId) -> &mut ModuleData {
939        self.inner
940            .get_mut(&id)
941            .unwrap_or_else(|| panic!("ModuleId not found in ModulesMap: {id:#?}"))
942    }
943}