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 
50 pub mod diagnostics;
51 mod collector;
52 mod mod_resolution;
53 mod path_resolution;
54 mod proc_macro;
55 
56 #[cfg(test)]
57 mod tests;
58 
59 use std::sync::Arc;
60 
61 use base_db::{CrateId, Edition, FileId};
62 use hir_expand::{name::Name, InFile, MacroDefId};
63 use la_arena::Arena;
64 use profile::Count;
65 use rustc_hash::FxHashMap;
66 use stdx::format_to;
67 use syntax::ast;
68 
69 use crate::{
70     db::DefDatabase,
71     item_scope::{BuiltinShadowMode, ItemScope},
72     item_tree::TreeId,
73     nameres::{diagnostics::DefDiagnostic, path_resolution::ResolveMode},
74     path::ModPath,
75     per_ns::PerNs,
76     visibility::Visibility,
77     AstId, BlockId, BlockLoc, LocalModuleId, ModuleDefId, ModuleId,
78 };
79 
80 use self::proc_macro::ProcMacroDef;
81 
82 /// Contains the results of (early) name resolution.
83 ///
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.
86 ///
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)]
92 pub struct DefMap {
93     _c: Count<Self>,
94     block: Option<BlockInfo>,
95     root: LocalModuleId,
96     modules: Arena<ModuleData>,
97     krate: CrateId,
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>,
103 
104     /// Side table with additional proc. macro info, for use by name resolution in downstream
105     /// crates.
106     ///
107     /// (the primary purpose is to resolve derive helpers and fetch a proc-macros name)
108     exported_proc_macros: FxHashMap<MacroDefId, ProcMacroDef>,
109 
110     edition: Edition,
111     diagnostics: Vec<DefDiagnostic>,
112 }
113 
114 /// For `DefMap`s computed for a block expression, this stores its location in the parent map.
115 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
116 struct BlockInfo {
117     /// The `BlockId` this `DefMap` was created from.
118     block: BlockId,
119     /// The containing module.
120     parent: ModuleId,
121 }
122 
123 impl std::ops::Index<LocalModuleId> for DefMap {
124     type Output = ModuleData;
index(&self, id: LocalModuleId) -> &ModuleData125     fn index(&self, id: LocalModuleId) -> &ModuleData {
126         &self.modules[id]
127     }
128 }
129 
130 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
131 pub enum ModuleOrigin {
132     CrateRoot {
133         definition: FileId,
134     },
135     /// Note that non-inline modules, by definition, live inside non-macro file.
136     File {
137         is_mod_rs: bool,
138         declaration: AstId<ast::Module>,
139         definition: FileId,
140     },
141     Inline {
142         definition: AstId<ast::Module>,
143     },
144     /// Pseudo-module introduced by a block scope (contains only inner items).
145     BlockExpr {
146         block: AstId<ast::BlockExpr>,
147     },
148 }
149 
150 impl ModuleOrigin {
declaration(&self) -> Option<AstId<ast::Module>>151     pub fn declaration(&self) -> Option<AstId<ast::Module>> {
152         match self {
153             ModuleOrigin::File { declaration: module, .. }
154             | ModuleOrigin::Inline { definition: module, .. } => Some(*module),
155             ModuleOrigin::CrateRoot { .. } | ModuleOrigin::BlockExpr { .. } => None,
156         }
157     }
158 
file_id(&self) -> Option<FileId>159     pub fn file_id(&self) -> Option<FileId> {
160         match self {
161             ModuleOrigin::File { definition, .. } | ModuleOrigin::CrateRoot { definition } => {
162                 Some(*definition)
163             }
164             _ => None,
165         }
166     }
167 
is_inline(&self) -> bool168     pub fn is_inline(&self) -> bool {
169         match self {
170             ModuleOrigin::Inline { .. } | ModuleOrigin::BlockExpr { .. } => true,
171             ModuleOrigin::CrateRoot { .. } | ModuleOrigin::File { .. } => false,
172         }
173     }
174 
175     /// Returns a node which defines this module.
176     /// That is, a file or a `mod foo {}` with items.
definition_source(&self, db: &dyn DefDatabase) -> InFile<ModuleSource>177     fn definition_source(&self, db: &dyn DefDatabase) -> InFile<ModuleSource> {
178         match self {
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))
183             }
184             ModuleOrigin::Inline { definition } => InFile::new(
185                 definition.file_id,
186                 ModuleSource::Module(definition.to_node(db.upcast())),
187             ),
188             ModuleOrigin::BlockExpr { block } => {
189                 InFile::new(block.file_id, ModuleSource::BlockExpr(block.to_node(db.upcast())))
190             }
191         }
192     }
193 }
194 
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,
201 
202     pub parent: Option<LocalModuleId>,
203     pub children: FxHashMap<Name, LocalModuleId>,
204     pub scope: ItemScope,
205 }
206 
207 impl DefMap {
crate_def_map_query(db: &dyn DefDatabase, krate: CrateId) -> Arc<DefMap>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()
211         });
212 
213         let crate_graph = db.crate_graph();
214 
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(
219             db,
220             def_map,
221             TreeId::new(crate_graph[krate].root_file_id.into(), None),
222         );
223 
224         Arc::new(def_map)
225     }
226 
block_def_map_query( db: &dyn DefDatabase, block_id: BlockId, ) -> Option<Arc<DefMap>>227     pub(crate) fn block_def_map_query(
228         db: &dyn DefDatabase,
229         block_id: BlockId,
230     ) -> Option<Arc<DefMap>> {
231         let block: BlockLoc = db.lookup_intern_block(block_id);
232 
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() {
236             return None;
237         }
238 
239         let block_info = BlockInfo { block: block_id, parent: block.module };
240 
241         let parent_map = block.module.def_map(db);
242         let mut def_map = DefMap::empty(
243             block.module.krate,
244             parent_map.edition,
245             ModuleOrigin::BlockExpr { block: block.ast_id },
246         );
247         def_map.block = Some(block_info);
248 
249         let def_map = collector::collect_defs(db, def_map, tree_id);
250         Some(Arc::new(def_map))
251     }
252 
empty(krate: CrateId, edition: Edition, root_module_origin: ModuleOrigin) -> DefMap253     fn empty(krate: CrateId, edition: Edition, root_module_origin: ModuleOrigin) -> DefMap {
254         let mut modules: Arena<ModuleData> = Arena::default();
255 
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);
263 
264         DefMap {
265             _c: Count::new(),
266             block: None,
267             krate,
268             edition,
269             extern_prelude: FxHashMap::default(),
270             exported_proc_macros: FxHashMap::default(),
271             prelude: None,
272             root,
273             modules,
274             diagnostics: Vec::new(),
275         }
276     }
277 
modules_for_file(&self, file_id: FileId) -> impl Iterator<Item = LocalModuleId> + '_278     pub fn modules_for_file(&self, file_id: FileId) -> impl Iterator<Item = LocalModuleId> + '_ {
279         self.modules
280             .iter()
281             .filter(move |(_id, data)| data.origin.file_id() == Some(file_id))
282             .map(|(id, _data)| id)
283     }
284 
modules(&self) -> impl Iterator<Item = (LocalModuleId, &ModuleData)> + '_285     pub fn modules(&self) -> impl Iterator<Item = (LocalModuleId, &ModuleData)> + '_ {
286         self.modules.iter()
287     }
exported_proc_macros(&self) -> impl Iterator<Item = (MacroDefId, Name)> + '_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()))
290     }
root(&self) -> LocalModuleId291     pub fn root(&self) -> LocalModuleId {
292         self.root
293     }
294 
krate(&self) -> CrateId295     pub(crate) fn krate(&self) -> CrateId {
296         self.krate
297     }
298 
block_id(&self) -> Option<BlockId>299     pub(crate) fn block_id(&self) -> Option<BlockId> {
300         self.block.as_ref().map(|block| block.block)
301     }
302 
prelude(&self) -> Option<ModuleId>303     pub(crate) fn prelude(&self) -> Option<ModuleId> {
304         self.prelude
305     }
306 
extern_prelude(&self) -> impl Iterator<Item = (&Name, &ModuleDefId)> + '_307     pub(crate) fn extern_prelude(&self) -> impl Iterator<Item = (&Name, &ModuleDefId)> + '_ {
308         self.extern_prelude.iter()
309     }
310 
module_id(&self, local_id: LocalModuleId) -> ModuleId311     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 }
314     }
315 
crate_root(&self, db: &dyn DefDatabase) -> ModuleId316     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))
320             } else {
321                 None
322             }
323         })
324         .expect("DefMap chain without root")
325     }
326 
resolve_path( &self, db: &dyn DefDatabase, original_module: LocalModuleId, path: &ModPath, shadow: BuiltinShadowMode, ) -> (PerNs, Option<usize>)327     pub(crate) fn resolve_path(
328         &self,
329         db: &dyn DefDatabase,
330         original_module: LocalModuleId,
331         path: &ModPath,
332         shadow: BuiltinShadowMode,
333     ) -> (PerNs, Option<usize>) {
334         let res =
335             self.resolve_path_fp_with_macro(db, ResolveMode::Other, original_module, path, shadow);
336         (res.resolved_def, res.segment_index)
337     }
338 
resolve_path_locally( &self, db: &dyn DefDatabase, original_module: LocalModuleId, path: &ModPath, shadow: BuiltinShadowMode, ) -> (PerNs, Option<usize>)339     pub(crate) fn resolve_path_locally(
340         &self,
341         db: &dyn DefDatabase,
342         original_module: LocalModuleId,
343         path: &ModPath,
344         shadow: BuiltinShadowMode,
345     ) -> (PerNs, Option<usize>) {
346         let res = self.resolve_path_fp_with_macro_single(
347             db,
348             ResolveMode::Other,
349             original_module,
350             path,
351             shadow,
352         );
353         (res.resolved_def, res.segment_index)
354     }
355 
356     /// Ascends the `DefMap` hierarchy and calls `f` with every `DefMap` and containing module.
357     ///
358     /// If `f` returns `Some(val)`, iteration is stopped and `Some(val)` is returned. If `f` returns
359     /// `None`, iteration continues.
with_ancestor_maps<T>( &self, db: &dyn DefDatabase, local_mod: LocalModuleId, f: &mut dyn FnMut(&DefMap, LocalModuleId) -> Option<T>, ) -> Option<T>360     pub fn with_ancestor_maps<T>(
361         &self,
362         db: &dyn DefDatabase,
363         local_mod: LocalModuleId,
364         f: &mut dyn FnMut(&DefMap, LocalModuleId) -> Option<T>,
365     ) -> Option<T> {
366         if let Some(it) = f(self, local_mod) {
367             return Some(it);
368         }
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) {
373                 return Some(it);
374             }
375             block = parent.block;
376         }
377 
378         None
379     }
380 
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).
parent(&self) -> Option<ModuleId>383     pub fn parent(&self) -> Option<ModuleId> {
384         Some(self.block?.parent)
385     }
386 
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.
containing_module(&self, local_mod: LocalModuleId) -> Option<ModuleId>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),
393         }
394     }
395 
396     // FIXME: this can use some more human-readable format (ideally, an IR
397     // even), as this should be a great debugging aid.
dump(&self, db: &dyn DefDatabase) -> String398     pub fn dump(&self, db: &dyn DefDatabase) -> String {
399         let mut buf = String::new();
400         let mut arc;
401         let mut current_map = self;
402         while let Some(block) = &current_map.block {
403             go(&mut buf, current_map, "block scope", current_map.root);
404             buf.push('\n');
405             arc = block.parent.def_map(db);
406             current_map = &*arc;
407         }
408         go(&mut buf, current_map, "crate", current_map.root);
409         return buf;
410 
411         fn go(buf: &mut String, map: &DefMap, path: &str, module: LocalModuleId) {
412             format_to!(buf, "{}\n", path);
413 
414             map.modules[module].scope.dump(buf);
415 
416             for (name, child) in map.modules[module].children.iter() {
417                 let path = format!("{}::{}", path, name);
418                 buf.push('\n');
419                 go(buf, map, &path, *child);
420             }
421         }
422     }
423 
dump_block_scopes(&self, db: &dyn DefDatabase) -> String424     pub fn dump_block_scopes(&self, db: &dyn DefDatabase) -> String {
425         let mut buf = String::new();
426         let mut arc;
427         let mut current_map = self;
428         while let Some(block) = &current_map.block {
429             format_to!(buf, "{:?} in {:?}\n", block.block, block.parent);
430             arc = block.parent.def_map(db);
431             current_map = &*arc;
432         }
433 
434         format_to!(buf, "crate scope\n");
435         buf
436     }
437 
shrink_to_fit(&mut self)438     fn shrink_to_fit(&mut self) {
439         // Exhaustive match to require handling new fields.
440         let Self {
441             _c: _,
442             exported_proc_macros,
443             extern_prelude,
444             diagnostics,
445             modules,
446             block: _,
447             edition: _,
448             krate: _,
449             prelude: _,
450             root: _,
451         } = self;
452 
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();
460         }
461     }
462 
463     /// Get a reference to the def map's diagnostics.
diagnostics(&self) -> &[DefDiagnostic]464     pub fn diagnostics(&self) -> &[DefDiagnostic] {
465         self.diagnostics.as_slice()
466     }
467 }
468 
469 impl ModuleData {
new(origin: ModuleOrigin, visibility: Visibility) -> Self470     pub(crate) fn new(origin: ModuleOrigin, visibility: Visibility) -> Self {
471         ModuleData {
472             origin,
473             visibility,
474             parent: None,
475             children: FxHashMap::default(),
476             scope: ItemScope::default(),
477         }
478     }
479 
480     /// Returns a node which defines this module. That is, a file or a `mod foo {}` with items.
definition_source(&self, db: &dyn DefDatabase) -> InFile<ModuleSource>481     pub fn definition_source(&self, db: &dyn DefDatabase) -> InFile<ModuleSource> {
482         self.origin.definition_source(db)
483     }
484 
485     /// Returns a node which declares this module, either a `mod foo;` or a `mod foo {}`.
486     /// `None` for the crate root or block.
declaration_source(&self, db: &dyn DefDatabase) -> Option<InFile<ast::Module>>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 })
491     }
492 }
493 
494 #[derive(Debug, Clone, PartialEq, Eq)]
495 pub enum ModuleSource {
496     SourceFile(ast::SourceFile),
497     Module(ast::Module),
498     BlockExpr(ast::BlockExpr),
499 }
500