1 //! This module implements import-resolution/macro expansion algorithm.
3 //! The result of this module is `DefMap`: a data structure which contains:
5 //! * a tree of modules for the crate
6 //! * for each module, a set of items visible in the module (directly declared
9 //! Note that `DefMap` contains fully macro expanded code.
11 //! Computing `DefMap` can be partitioned into several logically
12 //! independent "phases". The phases are mutually recursive though, there's no
15 //! ## Collecting RawItems
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>,
22 //! ## Collecting Modules
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.
29 //! While we walk tree of modules, we also record macro_rules definitions and
30 //! expand calls to macro_rules defined macros.
32 //! ## Resolving Imports
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.
39 //! ## Resolving Macros
41 //! macro_rules from the same crate use a global mutable namespace. We expand
42 //! them immediately, when we collect modules.
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
61 use base_db::{CrateId, Edition, FileId};
62 use hir_expand::{name::Name, InFile, MacroDefId};
65 use rustc_hash::FxHashMap;
71 item_scope::{BuiltinShadowMode, ItemScope},
73 nameres::{diagnostics::DefDiagnostic, path_resolution::ResolveMode},
76 visibility::Visibility,
77 AstId, BlockId, BlockLoc, LocalModuleId, ModuleDefId, ModuleId,
80 use self::proc_macro::ProcMacroDef;
82 /// Contains the results of (early) name resolution.
84 /// A `DefMap` stores the module tree and the definitions that are in scope in every module after
85 /// item-level macros have been expanded.
87 /// Every crate has a primary `DefMap` whose root is the crate's main file (`main.rs`/`lib.rs`),
88 /// computed by the `crate_def_map` query. Additionally, every block expression introduces the
89 /// opportunity to write arbitrary item and module hierarchies, and thus gets its own `DefMap` that
90 /// is computed by the `block_def_map` query.
91 #[derive(Debug, PartialEq, Eq)]
94 block: Option<BlockInfo>,
96 modules: Arena<ModuleData>,
98 /// The prelude module for this crate. This either comes from an import
99 /// marked with the `prelude_import` attribute, or (in the normal case) from
100 /// a dependency (`std` or `core`).
101 prelude: Option<ModuleId>,
102 extern_prelude: FxHashMap<Name, ModuleDefId>,
104 /// Side table with additional proc. macro info, for use by name resolution in downstream
107 /// (the primary purpose is to resolve derive helpers and fetch a proc-macros name)
108 exported_proc_macros: FxHashMap<MacroDefId, ProcMacroDef>,
111 diagnostics: Vec<DefDiagnostic>,
114 /// For `DefMap`s computed for a block expression, this stores its location in the parent map.
115 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
117 /// The `BlockId` this `DefMap` was created from.
119 /// The containing module.
123 impl std::ops::Index<LocalModuleId> for DefMap {
124 type Output = ModuleData;
125 fn index(&self, id: LocalModuleId) -> &ModuleData {
130 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
131 pub enum ModuleOrigin {
135 /// Note that non-inline modules, by definition, live inside non-macro file.
138 declaration: AstId<ast::Module>,
142 definition: AstId<ast::Module>,
144 /// Pseudo-module introduced by a block scope (contains only inner items).
146 block: AstId<ast::BlockExpr>,
151 fn declaration(&self) -> Option<AstId<ast::Module>> {
153 ModuleOrigin::File { declaration: module, .. }
154 | ModuleOrigin::Inline { definition: module, .. } => Some(*module),
155 ModuleOrigin::CrateRoot { .. } | ModuleOrigin::BlockExpr { .. } => None,
159 pub fn file_id(&self) -> Option<FileId> {
161 ModuleOrigin::File { definition, .. } | ModuleOrigin::CrateRoot { definition } => {
168 pub fn is_inline(&self) -> bool {
170 ModuleOrigin::Inline { .. } | ModuleOrigin::BlockExpr { .. } => true,
171 ModuleOrigin::CrateRoot { .. } | ModuleOrigin::File { .. } => false,
175 /// Returns a node which defines this module.
176 /// That is, a file or a `mod foo {}` with items.
177 fn definition_source(&self, db: &dyn DefDatabase) -> InFile<ModuleSource> {
179 ModuleOrigin::File { definition, .. } | ModuleOrigin::CrateRoot { definition } => {
180 let file_id = *definition;
181 let sf = db.parse(file_id).tree();
182 InFile::new(file_id.into(), ModuleSource::SourceFile(sf))
184 ModuleOrigin::Inline { definition } => InFile::new(
186 ModuleSource::Module(definition.to_node(db.upcast())),
188 ModuleOrigin::BlockExpr { block } => {
189 InFile::new(block.file_id, ModuleSource::BlockExpr(block.to_node(db.upcast())))
195 #[derive(Debug, PartialEq, Eq)]
196 pub struct ModuleData {
197 /// Where does this module come from?
198 pub origin: ModuleOrigin,
199 /// Declared visibility of this module.
200 pub visibility: Visibility,
202 pub parent: Option<LocalModuleId>,
203 pub children: FxHashMap<Name, LocalModuleId>,
204 pub scope: ItemScope,
208 pub(crate) fn crate_def_map_query(db: &dyn DefDatabase, krate: CrateId) -> Arc<DefMap> {
209 let _p = profile::span("crate_def_map_query").detail(|| {
210 db.crate_graph()[krate].display_name.as_deref().unwrap_or_default().to_string()
213 let crate_graph = db.crate_graph();
215 let edition = crate_graph[krate].edition;
216 let origin = ModuleOrigin::CrateRoot { definition: crate_graph[krate].root_file_id };
217 let def_map = DefMap::empty(krate, edition, origin);
218 let def_map = collector::collect_defs(
221 TreeId::new(crate_graph[krate].root_file_id.into(), None),
227 pub(crate) fn block_def_map_query(
228 db: &dyn DefDatabase,
230 ) -> Option<Arc<DefMap>> {
231 let block: BlockLoc = db.lookup_intern_block(block_id);
233 let tree_id = TreeId::new(block.ast_id.file_id, Some(block_id));
234 let item_tree = tree_id.item_tree(db);
235 if item_tree.top_level_items().is_empty() {
239 let block_info = BlockInfo { block: block_id, parent: block.module };
241 let parent_map = block.module.def_map(db);
242 let mut def_map = DefMap::empty(
245 ModuleOrigin::BlockExpr { block: block.ast_id },
247 def_map.block = Some(block_info);
249 let def_map = collector::collect_defs(db, def_map, tree_id);
250 Some(Arc::new(def_map))
253 fn empty(krate: CrateId, edition: Edition, root_module_origin: ModuleOrigin) -> DefMap {
254 let mut modules: Arena<ModuleData> = Arena::default();
256 let local_id = LocalModuleId::from_raw(la_arena::RawIdx::from(0));
257 // NB: we use `None` as block here, which would be wrong for implicit
258 // modules declared by blocks with items. At the moment, we don't use
259 // this visibility for anything outside IDE, so that's probably OK.
260 let visibility = Visibility::Module(ModuleId { krate, local_id, block: None });
261 let root = modules.alloc(ModuleData::new(root_module_origin, visibility));
262 assert_eq!(local_id, root);
269 extern_prelude: FxHashMap::default(),
270 exported_proc_macros: FxHashMap::default(),
274 diagnostics: Vec::new(),
278 pub fn modules_for_file(&self, file_id: FileId) -> impl Iterator<Item = LocalModuleId> + '_ {
281 .filter(move |(_id, data)| data.origin.file_id() == Some(file_id))
282 .map(|(id, _data)| id)
285 pub fn modules(&self) -> impl Iterator<Item = (LocalModuleId, &ModuleData)> + '_ {
288 pub fn exported_proc_macros(&self) -> impl Iterator<Item = (MacroDefId, Name)> + '_ {
289 self.exported_proc_macros.iter().map(|(id, def)| (*id, def.name.clone()))
291 pub fn root(&self) -> LocalModuleId {
295 pub(crate) fn krate(&self) -> CrateId {
299 pub(crate) fn block_id(&self) -> Option<BlockId> {
300 self.block.as_ref().map(|block| block.block)
303 pub(crate) fn prelude(&self) -> Option<ModuleId> {
307 pub(crate) fn extern_prelude(&self) -> impl Iterator<Item = (&Name, &ModuleDefId)> + '_ {
308 self.extern_prelude.iter()
311 pub fn module_id(&self, local_id: LocalModuleId) -> ModuleId {
312 let block = self.block.as_ref().map(|b| b.block);
313 ModuleId { krate: self.krate, local_id, block }
316 pub(crate) fn crate_root(&self, db: &dyn DefDatabase) -> ModuleId {
317 self.with_ancestor_maps(db, self.root, &mut |def_map, _module| {
318 if def_map.block.is_none() {
319 Some(def_map.module_id(def_map.root))
324 .expect("DefMap chain without root")
327 pub(crate) fn resolve_path(
329 db: &dyn DefDatabase,
330 original_module: LocalModuleId,
332 shadow: BuiltinShadowMode,
333 ) -> (PerNs, Option<usize>) {
335 self.resolve_path_fp_with_macro(db, ResolveMode::Other, original_module, path, shadow);
336 (res.resolved_def, res.segment_index)
339 pub(crate) fn resolve_path_locally(
341 db: &dyn DefDatabase,
342 original_module: LocalModuleId,
344 shadow: BuiltinShadowMode,
345 ) -> (PerNs, Option<usize>) {
346 let res = self.resolve_path_fp_with_macro_single(
353 (res.resolved_def, res.segment_index)
356 /// Ascends the `DefMap` hierarchy and calls `f` with every `DefMap` and containing module.
358 /// If `f` returns `Some(val)`, iteration is stopped and `Some(val)` is returned. If `f` returns
359 /// `None`, iteration continues.
360 pub fn with_ancestor_maps<T>(
362 db: &dyn DefDatabase,
363 local_mod: LocalModuleId,
364 f: &mut dyn FnMut(&DefMap, LocalModuleId) -> Option<T>,
366 if let Some(it) = f(self, local_mod) {
369 let mut block = self.block;
370 while let Some(block_info) = block {
371 let parent = block_info.parent.def_map(db);
372 if let Some(it) = f(&parent, block_info.parent.local_id) {
375 block = parent.block;
381 /// If this `DefMap` is for a block expression, returns the module containing the block (which
382 /// might again be a block, or a module inside a block).
383 pub fn parent(&self) -> Option<ModuleId> {
384 Some(self.block?.parent)
387 /// Returns the module containing `local_mod`, either the parent `mod`, or the module containing
388 /// the block, if `self` corresponds to a block expression.
389 pub fn containing_module(&self, local_mod: LocalModuleId) -> Option<ModuleId> {
390 match &self[local_mod].parent {
391 Some(parent) => Some(self.module_id(*parent)),
392 None => self.block.as_ref().map(|block| block.parent),
396 // FIXME: this can use some more human-readable format (ideally, an IR
397 // even), as this should be a great debugging aid.
398 pub fn dump(&self, db: &dyn DefDatabase) -> String {
399 let mut buf = String::new();
401 let mut current_map = self;
402 while let Some(block) = ¤t_map.block {
403 go(&mut buf, current_map, "block scope", current_map.root);
405 arc = block.parent.def_map(db);
408 go(&mut buf, current_map, "crate", current_map.root);
411 fn go(buf: &mut String, map: &DefMap, path: &str, module: LocalModuleId) {
412 format_to!(buf, "{}\n", path);
414 map.modules[module].scope.dump(buf);
416 for (name, child) in map.modules[module].children.iter() {
417 let path = format!("{}::{}", path, name);
419 go(buf, map, &path, *child);
424 pub fn dump_block_scopes(&self, db: &dyn DefDatabase) -> String {
425 let mut buf = String::new();
427 let mut current_map = self;
428 while let Some(block) = ¤t_map.block {
429 format_to!(buf, "{:?} in {:?}\n", block.block, block.parent);
430 arc = block.parent.def_map(db);
434 format_to!(buf, "crate scope\n");
438 fn shrink_to_fit(&mut self) {
439 // Exhaustive match to require handling new fields.
442 exported_proc_macros,
453 extern_prelude.shrink_to_fit();
454 exported_proc_macros.shrink_to_fit();
455 diagnostics.shrink_to_fit();
456 modules.shrink_to_fit();
457 for (_, module) in modules.iter_mut() {
458 module.children.shrink_to_fit();
459 module.scope.shrink_to_fit();
463 /// Get a reference to the def map's diagnostics.
464 pub fn diagnostics(&self) -> &[DefDiagnostic] {
465 self.diagnostics.as_slice()
470 pub(crate) fn new(origin: ModuleOrigin, visibility: Visibility) -> Self {
475 children: FxHashMap::default(),
476 scope: ItemScope::default(),
480 /// Returns a node which defines this module. That is, a file or a `mod foo {}` with items.
481 pub fn definition_source(&self, db: &dyn DefDatabase) -> InFile<ModuleSource> {
482 self.origin.definition_source(db)
485 /// Returns a node which declares this module, either a `mod foo;` or a `mod foo {}`.
486 /// `None` for the crate root or block.
487 pub fn declaration_source(&self, db: &dyn DefDatabase) -> Option<InFile<ast::Module>> {
488 let decl = self.origin.declaration()?;
489 let value = decl.to_node(db.upcast());
490 Some(InFile { file_id: decl.file_id, value })
494 #[derive(Debug, Clone, PartialEq, Eq)]
495 pub enum ModuleSource {
496 SourceFile(ast::SourceFile),
498 BlockExpr(ast::BlockExpr),