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
50 pub mod attr_resolution;
62 use base_db::{CrateId, Edition, FileId};
63 use hir_expand::{name::Name, InFile, MacroDefId};
66 use rustc_hash::FxHashMap;
68 use syntax::{ast, SmolStr};
72 item_scope::{BuiltinShadowMode, ItemScope},
74 nameres::{diagnostics::DefDiagnostic, path_resolution::ResolveMode},
77 visibility::Visibility,
78 AstId, BlockId, BlockLoc, LocalModuleId, ModuleDefId, ModuleId,
81 use self::proc_macro::ProcMacroDef;
83 /// Contains the results of (early) name resolution.
85 /// A `DefMap` stores the module tree and the definitions that are in scope in every module after
86 /// item-level macros have been expanded.
88 /// Every crate has a primary `DefMap` whose root is the crate's main file (`main.rs`/`lib.rs`),
89 /// computed by the `crate_def_map` query. Additionally, every block expression introduces the
90 /// opportunity to write arbitrary item and module hierarchies, and thus gets its own `DefMap` that
91 /// is computed by the `block_def_map` query.
92 #[derive(Debug, PartialEq, Eq)]
95 block: Option<BlockInfo>,
97 modules: Arena<ModuleData>,
99 /// The prelude module for this crate. This either comes from an import
100 /// marked with the `prelude_import` attribute, or (in the normal case) from
101 /// a dependency (`std` or `core`).
102 prelude: Option<ModuleId>,
103 extern_prelude: FxHashMap<Name, ModuleDefId>,
105 /// Side table with additional proc. macro info, for use by name resolution in downstream
108 /// (the primary purpose is to resolve derive helpers and fetch a proc-macros name)
109 exported_proc_macros: FxHashMap<MacroDefId, ProcMacroDef>,
111 /// Custom attributes registered with `#![register_attr]`.
112 registered_attrs: Vec<SmolStr>,
113 /// Custom tool modules registered with `#![register_tool]`.
114 registered_tools: Vec<SmolStr>,
117 diagnostics: Vec<DefDiagnostic>,
120 /// For `DefMap`s computed for a block expression, this stores its location in the parent map.
121 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
123 /// The `BlockId` this `DefMap` was created from.
125 /// The containing module.
129 impl std::ops::Index<LocalModuleId> for DefMap {
130 type Output = ModuleData;
131 fn index(&self, id: LocalModuleId) -> &ModuleData {
136 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
137 pub enum ModuleOrigin {
141 /// Note that non-inline modules, by definition, live inside non-macro file.
144 declaration: AstId<ast::Module>,
148 definition: AstId<ast::Module>,
150 /// Pseudo-module introduced by a block scope (contains only inner items).
152 block: AstId<ast::BlockExpr>,
157 pub fn declaration(&self) -> Option<AstId<ast::Module>> {
159 ModuleOrigin::File { declaration: module, .. }
160 | ModuleOrigin::Inline { definition: module, .. } => Some(*module),
161 ModuleOrigin::CrateRoot { .. } | ModuleOrigin::BlockExpr { .. } => None,
165 pub fn file_id(&self) -> Option<FileId> {
167 ModuleOrigin::File { definition, .. } | ModuleOrigin::CrateRoot { definition } => {
174 pub fn is_inline(&self) -> bool {
176 ModuleOrigin::Inline { .. } | ModuleOrigin::BlockExpr { .. } => true,
177 ModuleOrigin::CrateRoot { .. } | ModuleOrigin::File { .. } => false,
181 /// Returns a node which defines this module.
182 /// That is, a file or a `mod foo {}` with items.
183 fn definition_source(&self, db: &dyn DefDatabase) -> InFile<ModuleSource> {
185 ModuleOrigin::File { definition, .. } | ModuleOrigin::CrateRoot { definition } => {
186 let file_id = *definition;
187 let sf = db.parse(file_id).tree();
188 InFile::new(file_id.into(), ModuleSource::SourceFile(sf))
190 ModuleOrigin::Inline { definition } => InFile::new(
192 ModuleSource::Module(definition.to_node(db.upcast())),
194 ModuleOrigin::BlockExpr { block } => {
195 InFile::new(block.file_id, ModuleSource::BlockExpr(block.to_node(db.upcast())))
201 #[derive(Debug, PartialEq, Eq)]
202 pub struct ModuleData {
203 /// Where does this module come from?
204 pub origin: ModuleOrigin,
205 /// Declared visibility of this module.
206 pub visibility: Visibility,
208 pub parent: Option<LocalModuleId>,
209 pub children: FxHashMap<Name, LocalModuleId>,
210 pub scope: ItemScope,
214 pub(crate) fn crate_def_map_query(db: &dyn DefDatabase, krate: CrateId) -> Arc<DefMap> {
215 let _p = profile::span("crate_def_map_query").detail(|| {
216 db.crate_graph()[krate].display_name.as_deref().unwrap_or_default().to_string()
219 let crate_graph = db.crate_graph();
221 let edition = crate_graph[krate].edition;
222 let origin = ModuleOrigin::CrateRoot { definition: crate_graph[krate].root_file_id };
223 let def_map = DefMap::empty(krate, edition, origin);
224 let def_map = collector::collect_defs(
227 TreeId::new(crate_graph[krate].root_file_id.into(), None),
233 pub(crate) fn block_def_map_query(
234 db: &dyn DefDatabase,
236 ) -> Option<Arc<DefMap>> {
237 let block: BlockLoc = db.lookup_intern_block(block_id);
239 let tree_id = TreeId::new(block.ast_id.file_id, Some(block_id));
240 let item_tree = tree_id.item_tree(db);
241 if item_tree.top_level_items().is_empty() {
245 let block_info = BlockInfo { block: block_id, parent: block.module };
247 let parent_map = block.module.def_map(db);
248 let mut def_map = DefMap::empty(
251 ModuleOrigin::BlockExpr { block: block.ast_id },
253 def_map.block = Some(block_info);
255 let def_map = collector::collect_defs(db, def_map, tree_id);
256 Some(Arc::new(def_map))
259 fn empty(krate: CrateId, edition: Edition, root_module_origin: ModuleOrigin) -> DefMap {
260 let mut modules: Arena<ModuleData> = Arena::default();
262 let local_id = LocalModuleId::from_raw(la_arena::RawIdx::from(0));
263 // NB: we use `None` as block here, which would be wrong for implicit
264 // modules declared by blocks with items. At the moment, we don't use
265 // this visibility for anything outside IDE, so that's probably OK.
266 let visibility = Visibility::Module(ModuleId { krate, local_id, block: None });
267 let root = modules.alloc(ModuleData::new(root_module_origin, visibility));
268 assert_eq!(local_id, root);
275 extern_prelude: FxHashMap::default(),
276 exported_proc_macros: FxHashMap::default(),
280 registered_attrs: Vec::new(),
281 registered_tools: Vec::new(),
282 diagnostics: Vec::new(),
286 pub fn modules_for_file(&self, file_id: FileId) -> impl Iterator<Item = LocalModuleId> + '_ {
289 .filter(move |(_id, data)| data.origin.file_id() == Some(file_id))
290 .map(|(id, _data)| id)
293 pub fn modules(&self) -> impl Iterator<Item = (LocalModuleId, &ModuleData)> + '_ {
296 pub fn exported_proc_macros(&self) -> impl Iterator<Item = (MacroDefId, Name)> + '_ {
297 self.exported_proc_macros.iter().map(|(id, def)| (*id, def.name.clone()))
299 pub fn root(&self) -> LocalModuleId {
303 pub(crate) fn krate(&self) -> CrateId {
307 pub(crate) fn block_id(&self) -> Option<BlockId> {
308 self.block.as_ref().map(|block| block.block)
311 pub(crate) fn prelude(&self) -> Option<ModuleId> {
315 pub(crate) fn extern_prelude(&self) -> impl Iterator<Item = (&Name, &ModuleDefId)> + '_ {
316 self.extern_prelude.iter()
319 pub fn module_id(&self, local_id: LocalModuleId) -> ModuleId {
320 let block = self.block.as_ref().map(|b| b.block);
321 ModuleId { krate: self.krate, local_id, block }
324 pub(crate) fn crate_root(&self, db: &dyn DefDatabase) -> ModuleId {
325 self.with_ancestor_maps(db, self.root, &mut |def_map, _module| {
326 if def_map.block.is_none() {
327 Some(def_map.module_id(def_map.root))
332 .expect("DefMap chain without root")
335 pub(crate) fn resolve_path(
337 db: &dyn DefDatabase,
338 original_module: LocalModuleId,
340 shadow: BuiltinShadowMode,
341 ) -> (PerNs, Option<usize>) {
343 self.resolve_path_fp_with_macro(db, ResolveMode::Other, original_module, path, shadow);
344 (res.resolved_def, res.segment_index)
347 pub(crate) fn resolve_path_locally(
349 db: &dyn DefDatabase,
350 original_module: LocalModuleId,
352 shadow: BuiltinShadowMode,
353 ) -> (PerNs, Option<usize>) {
354 let res = self.resolve_path_fp_with_macro_single(
361 (res.resolved_def, res.segment_index)
364 /// Ascends the `DefMap` hierarchy and calls `f` with every `DefMap` and containing module.
366 /// If `f` returns `Some(val)`, iteration is stopped and `Some(val)` is returned. If `f` returns
367 /// `None`, iteration continues.
368 pub fn with_ancestor_maps<T>(
370 db: &dyn DefDatabase,
371 local_mod: LocalModuleId,
372 f: &mut dyn FnMut(&DefMap, LocalModuleId) -> Option<T>,
374 if let Some(it) = f(self, local_mod) {
377 let mut block = self.block;
378 while let Some(block_info) = block {
379 let parent = block_info.parent.def_map(db);
380 if let Some(it) = f(&parent, block_info.parent.local_id) {
383 block = parent.block;
389 /// If this `DefMap` is for a block expression, returns the module containing the block (which
390 /// might again be a block, or a module inside a block).
391 pub fn parent(&self) -> Option<ModuleId> {
392 Some(self.block?.parent)
395 /// Returns the module containing `local_mod`, either the parent `mod`, or the module containing
396 /// the block, if `self` corresponds to a block expression.
397 pub fn containing_module(&self, local_mod: LocalModuleId) -> Option<ModuleId> {
398 match &self[local_mod].parent {
399 Some(parent) => Some(self.module_id(*parent)),
400 None => self.block.as_ref().map(|block| block.parent),
404 // FIXME: this can use some more human-readable format (ideally, an IR
405 // even), as this should be a great debugging aid.
406 pub fn dump(&self, db: &dyn DefDatabase) -> String {
407 let mut buf = String::new();
409 let mut current_map = self;
410 while let Some(block) = ¤t_map.block {
411 go(&mut buf, current_map, "block scope", current_map.root);
413 arc = block.parent.def_map(db);
416 go(&mut buf, current_map, "crate", current_map.root);
419 fn go(buf: &mut String, map: &DefMap, path: &str, module: LocalModuleId) {
420 format_to!(buf, "{}\n", path);
422 map.modules[module].scope.dump(buf);
424 for (name, child) in map.modules[module].children.iter() {
425 let path = format!("{}::{}", path, name);
427 go(buf, map, &path, *child);
432 pub fn dump_block_scopes(&self, db: &dyn DefDatabase) -> String {
433 let mut buf = String::new();
435 let mut current_map = self;
436 while let Some(block) = ¤t_map.block {
437 format_to!(buf, "{:?} in {:?}\n", block.block, block.parent);
438 arc = block.parent.def_map(db);
442 format_to!(buf, "crate scope\n");
446 fn shrink_to_fit(&mut self) {
447 // Exhaustive match to require handling new fields.
450 exported_proc_macros,
463 extern_prelude.shrink_to_fit();
464 exported_proc_macros.shrink_to_fit();
465 diagnostics.shrink_to_fit();
466 modules.shrink_to_fit();
467 registered_attrs.shrink_to_fit();
468 registered_tools.shrink_to_fit();
469 for (_, module) in modules.iter_mut() {
470 module.children.shrink_to_fit();
471 module.scope.shrink_to_fit();
475 /// Get a reference to the def map's diagnostics.
476 pub fn diagnostics(&self) -> &[DefDiagnostic] {
477 self.diagnostics.as_slice()
482 pub(crate) fn new(origin: ModuleOrigin, visibility: Visibility) -> Self {
487 children: FxHashMap::default(),
488 scope: ItemScope::default(),
492 /// Returns a node which defines this module. That is, a file or a `mod foo {}` with items.
493 pub fn definition_source(&self, db: &dyn DefDatabase) -> InFile<ModuleSource> {
494 self.origin.definition_source(db)
497 /// Returns a node which declares this module, either a `mod foo;` or a `mod foo {}`.
498 /// `None` for the crate root or block.
499 pub fn declaration_source(&self, db: &dyn DefDatabase) -> Option<InFile<ast::Module>> {
500 let decl = self.origin.declaration()?;
501 let value = decl.to_node(db.upcast());
502 Some(InFile { file_id: decl.file_id, value })
506 #[derive(Debug, Clone, PartialEq, Eq)]
507 pub enum ModuleSource {
508 SourceFile(ast::SourceFile),
510 BlockExpr(ast::BlockExpr),