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;
60 use std::{cmp::Ord, ops::Deref, sync::Arc};
62 use base_db::{CrateId, Edition, FileId};
63 use hir_expand::{name::Name, InFile, MacroCallId, MacroDefId};
64 use itertools::Itertools;
67 use rustc_hash::FxHashMap;
69 use syntax::{ast, SmolStr};
73 item_scope::{BuiltinShadowMode, ItemScope},
74 item_tree::{ItemTreeId, Mod, TreeId},
75 nameres::{diagnostics::DefDiagnostic, path_resolution::ResolveMode},
78 visibility::Visibility,
79 AstId, BlockId, BlockLoc, FunctionId, LocalModuleId, MacroId, ModuleId, ProcMacroId,
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, ModuleId>,
104 /// Side table for resolving derive helpers.
105 exported_derives: FxHashMap<MacroDefId, Box<[Name]>>,
106 fn_proc_macro_mapping: FxHashMap<FunctionId, ProcMacroId>,
107 /// The error that occurred when failing to load the proc-macro dll.
108 proc_macro_loading_error: Option<Box<str>>,
109 /// Tracks which custom derives are in scope for an item, to allow resolution of derive helper
111 derive_helpers_in_scope: FxHashMap<AstId<ast::Item>, Vec<(Name, MacroId, MacroCallId)>>,
113 /// Custom attributes registered with `#![register_attr]`.
114 registered_attrs: Vec<SmolStr>,
115 /// Custom tool modules registered with `#![register_tool]`.
116 registered_tools: Vec<SmolStr>,
119 recursion_limit: Option<u32>,
120 diagnostics: Vec<DefDiagnostic>,
123 /// For `DefMap`s computed for a block expression, this stores its location in the parent map.
124 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
126 /// The `BlockId` this `DefMap` was created from.
128 /// The containing module.
132 impl std::ops::Index<LocalModuleId> for DefMap {
133 type Output = ModuleData;
134 fn index(&self, id: LocalModuleId) -> &ModuleData {
139 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
140 pub enum ModuleOrigin {
144 /// Note that non-inline modules, by definition, live inside non-macro file.
147 declaration: AstId<ast::Module>,
148 declaration_tree_id: ItemTreeId<Mod>,
152 definition_tree_id: ItemTreeId<Mod>,
153 definition: AstId<ast::Module>,
155 /// Pseudo-module introduced by a block scope (contains only inner items).
157 block: AstId<ast::BlockExpr>,
162 pub fn declaration(&self) -> Option<AstId<ast::Module>> {
164 ModuleOrigin::File { declaration: module, .. }
165 | ModuleOrigin::Inline { definition: module, .. } => Some(*module),
166 ModuleOrigin::CrateRoot { .. } | ModuleOrigin::BlockExpr { .. } => None,
170 pub fn file_id(&self) -> Option<FileId> {
172 ModuleOrigin::File { definition, .. } | ModuleOrigin::CrateRoot { definition } => {
179 pub fn is_inline(&self) -> bool {
181 ModuleOrigin::Inline { .. } | ModuleOrigin::BlockExpr { .. } => true,
182 ModuleOrigin::CrateRoot { .. } | ModuleOrigin::File { .. } => false,
186 /// Returns a node which defines this module.
187 /// That is, a file or a `mod foo {}` with items.
188 fn definition_source(&self, db: &dyn DefDatabase) -> InFile<ModuleSource> {
190 ModuleOrigin::File { definition, .. } | ModuleOrigin::CrateRoot { definition } => {
191 let file_id = *definition;
192 let sf = db.parse(file_id).tree();
193 InFile::new(file_id.into(), ModuleSource::SourceFile(sf))
195 ModuleOrigin::Inline { definition, .. } => InFile::new(
197 ModuleSource::Module(definition.to_node(db.upcast())),
199 ModuleOrigin::BlockExpr { block } => {
200 InFile::new(block.file_id, ModuleSource::BlockExpr(block.to_node(db.upcast())))
206 #[derive(Debug, PartialEq, Eq)]
207 pub struct ModuleData {
208 /// Where does this module come from?
209 pub origin: ModuleOrigin,
210 /// Declared visibility of this module.
211 pub visibility: Visibility,
213 pub parent: Option<LocalModuleId>,
214 pub children: FxHashMap<Name, LocalModuleId>,
215 pub scope: ItemScope,
219 pub(crate) fn crate_def_map_query(db: &dyn DefDatabase, krate: CrateId) -> Arc<DefMap> {
220 let _p = profile::span("crate_def_map_query").detail(|| {
221 db.crate_graph()[krate].display_name.as_deref().unwrap_or_default().to_string()
224 let crate_graph = db.crate_graph();
226 let edition = crate_graph[krate].edition;
227 let origin = ModuleOrigin::CrateRoot { definition: crate_graph[krate].root_file_id };
228 let def_map = DefMap::empty(krate, edition, ModuleData::new(origin, Visibility::Public));
229 let def_map = collector::collect_defs(
232 TreeId::new(crate_graph[krate].root_file_id.into(), None),
238 pub(crate) fn block_def_map_query(
239 db: &dyn DefDatabase,
241 ) -> Option<Arc<DefMap>> {
242 let block: BlockLoc = db.lookup_intern_block(block_id);
244 let tree_id = TreeId::new(block.ast_id.file_id, Some(block_id));
245 let item_tree = tree_id.item_tree(db);
246 if item_tree.top_level_items().is_empty() {
250 let parent_map = block.module.def_map(db);
251 let krate = block.module.krate;
252 let local_id = LocalModuleId::from_raw(la_arena::RawIdx::from(0));
253 // NB: we use `None` as block here, which would be wrong for implicit
254 // modules declared by blocks with items. At the moment, we don't use
255 // this visibility for anything outside IDE, so that's probably OK.
256 let visibility = Visibility::Module(ModuleId { krate, local_id, block: None });
258 ModuleData::new(ModuleOrigin::BlockExpr { block: block.ast_id }, visibility);
260 let mut def_map = DefMap::empty(krate, parent_map.edition, module_data);
261 def_map.block = Some(BlockInfo { block: block_id, parent: block.module });
263 let def_map = collector::collect_defs(db, def_map, tree_id);
264 Some(Arc::new(def_map))
267 fn empty(krate: CrateId, edition: Edition, module_data: ModuleData) -> DefMap {
268 let mut modules: Arena<ModuleData> = Arena::default();
269 let root = modules.alloc(module_data);
276 recursion_limit: None,
277 extern_prelude: FxHashMap::default(),
278 exported_derives: FxHashMap::default(),
279 fn_proc_macro_mapping: FxHashMap::default(),
280 proc_macro_loading_error: None,
281 derive_helpers_in_scope: FxHashMap::default(),
285 registered_attrs: Vec::new(),
286 registered_tools: Vec::new(),
287 diagnostics: Vec::new(),
291 pub fn modules_for_file(&self, file_id: FileId) -> impl Iterator<Item = LocalModuleId> + '_ {
294 .filter(move |(_id, data)| data.origin.file_id() == Some(file_id))
295 .map(|(id, _data)| id)
298 pub fn modules(&self) -> impl Iterator<Item = (LocalModuleId, &ModuleData)> + '_ {
302 pub fn derive_helpers_in_scope(
305 ) -> Option<&[(Name, MacroId, MacroCallId)]> {
306 self.derive_helpers_in_scope.get(&id.map(|it| it.upcast())).map(Deref::deref)
309 pub fn registered_tools(&self) -> &[SmolStr] {
310 &self.registered_tools
313 pub fn registered_attrs(&self) -> &[SmolStr] {
314 &self.registered_attrs
317 pub fn root(&self) -> LocalModuleId {
321 pub fn fn_as_proc_macro(&self, id: FunctionId) -> Option<ProcMacroId> {
322 self.fn_proc_macro_mapping.get(&id).copied()
325 pub fn proc_macro_loading_error(&self) -> Option<&str> {
326 self.proc_macro_loading_error.as_deref()
329 pub(crate) fn krate(&self) -> CrateId {
333 pub(crate) fn block_id(&self) -> Option<BlockId> {
334 self.block.as_ref().map(|block| block.block)
337 pub(crate) fn prelude(&self) -> Option<ModuleId> {
341 pub(crate) fn extern_prelude(&self) -> impl Iterator<Item = (&Name, &ModuleId)> + '_ {
342 self.extern_prelude.iter()
345 pub fn module_id(&self, local_id: LocalModuleId) -> ModuleId {
346 let block = self.block.as_ref().map(|b| b.block);
347 ModuleId { krate: self.krate, local_id, block }
350 pub(crate) fn crate_root(&self, db: &dyn DefDatabase) -> ModuleId {
351 self.with_ancestor_maps(db, self.root, &mut |def_map, _module| {
352 if def_map.block.is_none() { Some(def_map.module_id(def_map.root)) } else { None }
354 .expect("DefMap chain without root")
357 pub(crate) fn resolve_path(
359 db: &dyn DefDatabase,
360 original_module: LocalModuleId,
362 shadow: BuiltinShadowMode,
363 ) -> (PerNs, Option<usize>) {
365 self.resolve_path_fp_with_macro(db, ResolveMode::Other, original_module, path, shadow);
366 (res.resolved_def, res.segment_index)
369 pub(crate) fn resolve_path_locally(
371 db: &dyn DefDatabase,
372 original_module: LocalModuleId,
374 shadow: BuiltinShadowMode,
375 ) -> (PerNs, Option<usize>) {
376 let res = self.resolve_path_fp_with_macro_single(
383 (res.resolved_def, res.segment_index)
386 /// Ascends the `DefMap` hierarchy and calls `f` with every `DefMap` and containing module.
388 /// If `f` returns `Some(val)`, iteration is stopped and `Some(val)` is returned. If `f` returns
389 /// `None`, iteration continues.
390 pub fn with_ancestor_maps<T>(
392 db: &dyn DefDatabase,
393 local_mod: LocalModuleId,
394 f: &mut dyn FnMut(&DefMap, LocalModuleId) -> Option<T>,
396 if let Some(it) = f(self, local_mod) {
399 let mut block = self.block;
400 while let Some(block_info) = block {
401 let parent = block_info.parent.def_map(db);
402 if let Some(it) = f(&parent, block_info.parent.local_id) {
405 block = parent.block;
411 /// If this `DefMap` is for a block expression, returns the module containing the block (which
412 /// might again be a block, or a module inside a block).
413 pub fn parent(&self) -> Option<ModuleId> {
414 Some(self.block?.parent)
417 /// Returns the module containing `local_mod`, either the parent `mod`, or the module containing
418 /// the block, if `self` corresponds to a block expression.
419 pub fn containing_module(&self, local_mod: LocalModuleId) -> Option<ModuleId> {
420 match &self[local_mod].parent {
421 Some(parent) => Some(self.module_id(*parent)),
422 None => self.block.as_ref().map(|block| block.parent),
426 // FIXME: this can use some more human-readable format (ideally, an IR
427 // even), as this should be a great debugging aid.
428 pub fn dump(&self, db: &dyn DefDatabase) -> String {
429 let mut buf = String::new();
431 let mut current_map = self;
432 while let Some(block) = ¤t_map.block {
433 go(&mut buf, current_map, "block scope", current_map.root);
435 arc = block.parent.def_map(db);
438 go(&mut buf, current_map, "crate", current_map.root);
441 fn go(buf: &mut String, map: &DefMap, path: &str, module: LocalModuleId) {
442 format_to!(buf, "{}\n", path);
444 map.modules[module].scope.dump(buf);
447 map.modules[module].children.iter().sorted_by(|a, b| Ord::cmp(&a.0, &b.0))
449 let path = format!("{}::{}", path, name);
451 go(buf, map, &path, *child);
456 pub fn dump_block_scopes(&self, db: &dyn DefDatabase) -> String {
457 let mut buf = String::new();
459 let mut current_map = self;
460 while let Some(block) = ¤t_map.block {
461 format_to!(buf, "{:?} in {:?}\n", block.block, block.parent);
462 arc = block.parent.def_map(db);
466 format_to!(buf, "crate scope\n");
470 fn shrink_to_fit(&mut self) {
471 // Exhaustive match to require handling new fields.
480 fn_proc_macro_mapping,
481 derive_helpers_in_scope,
482 proc_macro_loading_error: _,
491 extern_prelude.shrink_to_fit();
492 exported_derives.shrink_to_fit();
493 diagnostics.shrink_to_fit();
494 modules.shrink_to_fit();
495 registered_attrs.shrink_to_fit();
496 registered_tools.shrink_to_fit();
497 fn_proc_macro_mapping.shrink_to_fit();
498 derive_helpers_in_scope.shrink_to_fit();
499 for (_, module) in modules.iter_mut() {
500 module.children.shrink_to_fit();
501 module.scope.shrink_to_fit();
505 /// Get a reference to the def map's diagnostics.
506 pub fn diagnostics(&self) -> &[DefDiagnostic] {
507 self.diagnostics.as_slice()
510 pub fn recursion_limit(&self) -> Option<u32> {
516 pub(crate) fn new(origin: ModuleOrigin, visibility: Visibility) -> Self {
521 children: FxHashMap::default(),
522 scope: ItemScope::default(),
526 /// Returns a node which defines this module. That is, a file or a `mod foo {}` with items.
527 pub fn definition_source(&self, db: &dyn DefDatabase) -> InFile<ModuleSource> {
528 self.origin.definition_source(db)
531 /// Returns a node which declares this module, either a `mod foo;` or a `mod foo {}`.
532 /// `None` for the crate root or block.
533 pub fn declaration_source(&self, db: &dyn DefDatabase) -> Option<InFile<ast::Module>> {
534 let decl = self.origin.declaration()?;
535 let value = decl.to_node(db.upcast());
536 Some(InFile { file_id: decl.file_id, value })
540 #[derive(Debug, Clone, PartialEq, Eq)]
541 pub enum ModuleSource {
542 SourceFile(ast::SourceFile),
544 BlockExpr(ast::BlockExpr),