]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/nameres.rs
Merge #9003
[rust.git] / crates / hir_def / src / nameres.rs
1 //! This module implements import-resolution/macro expansion algorithm.
2 //!
3 //! The result of this module is `CrateDefMap`: 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 `CrateDefMap` contains fully macro expanded code.
10 //!
11 //! Computing `CrateDefMap` 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     nameres::{diagnostics::DefDiagnostic, path_resolution::ResolveMode},
73     path::ModPath,
74     per_ns::PerNs,
75     AstId, BlockId, BlockLoc, LocalModuleId, ModuleDefId, ModuleId,
76 };
77
78 use self::proc_macro::ProcMacroDef;
79
80 /// Contains the results of (early) name resolution.
81 ///
82 /// A `DefMap` stores the module tree and the definitions that are in scope in every module after
83 /// item-level macros have been expanded.
84 ///
85 /// Every crate has a primary `DefMap` whose root is the crate's main file (`main.rs`/`lib.rs`),
86 /// computed by the `crate_def_map` query. Additionally, every block expression introduces the
87 /// opportunity to write arbitrary item and module hierarchies, and thus gets its own `DefMap` that
88 /// is computed by the `block_def_map` query.
89 #[derive(Debug, PartialEq, Eq)]
90 pub struct DefMap {
91     _c: Count<Self>,
92     block: Option<BlockInfo>,
93     root: LocalModuleId,
94     modules: Arena<ModuleData>,
95     krate: CrateId,
96     /// The prelude module for this crate. This either comes from an import
97     /// marked with the `prelude_import` attribute, or (in the normal case) from
98     /// a dependency (`std` or `core`).
99     prelude: Option<ModuleId>,
100     extern_prelude: FxHashMap<Name, ModuleDefId>,
101
102     /// Side table with additional proc. macro info, for use by name resolution in downstream
103     /// crates.
104     ///
105     /// (the primary purpose is to resolve derive helpers)
106     exported_proc_macros: FxHashMap<MacroDefId, ProcMacroDef>,
107
108     edition: Edition,
109     diagnostics: Vec<DefDiagnostic>,
110 }
111
112 /// For `DefMap`s computed for a block expression, this stores its location in the parent map.
113 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
114 struct BlockInfo {
115     /// The `BlockId` this `DefMap` was created from.
116     block: BlockId,
117     /// The containing module.
118     parent: ModuleId,
119 }
120
121 impl std::ops::Index<LocalModuleId> for DefMap {
122     type Output = ModuleData;
123     fn index(&self, id: LocalModuleId) -> &ModuleData {
124         &self.modules[id]
125     }
126 }
127
128 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
129 pub enum ModuleOrigin {
130     CrateRoot {
131         definition: FileId,
132     },
133     /// Note that non-inline modules, by definition, live inside non-macro file.
134     File {
135         is_mod_rs: bool,
136         declaration: AstId<ast::Module>,
137         definition: FileId,
138     },
139     Inline {
140         definition: AstId<ast::Module>,
141     },
142     /// Pseudo-module introduced by a block scope (contains only inner items).
143     BlockExpr {
144         block: AstId<ast::BlockExpr>,
145     },
146 }
147
148 impl Default for ModuleOrigin {
149     fn default() -> Self {
150         ModuleOrigin::CrateRoot { definition: FileId(0) }
151     }
152 }
153
154 impl ModuleOrigin {
155     fn declaration(&self) -> Option<AstId<ast::Module>> {
156         match self {
157             ModuleOrigin::File { declaration: module, .. }
158             | ModuleOrigin::Inline { definition: module, .. } => Some(*module),
159             ModuleOrigin::CrateRoot { .. } | ModuleOrigin::BlockExpr { .. } => None,
160         }
161     }
162
163     pub fn file_id(&self) -> Option<FileId> {
164         match self {
165             ModuleOrigin::File { definition, .. } | ModuleOrigin::CrateRoot { definition } => {
166                 Some(*definition)
167             }
168             _ => None,
169         }
170     }
171
172     pub fn is_inline(&self) -> bool {
173         match self {
174             ModuleOrigin::Inline { .. } | ModuleOrigin::BlockExpr { .. } => true,
175             ModuleOrigin::CrateRoot { .. } | ModuleOrigin::File { .. } => false,
176         }
177     }
178
179     /// Returns a node which defines this module.
180     /// That is, a file or a `mod foo {}` with items.
181     fn definition_source(&self, db: &dyn DefDatabase) -> InFile<ModuleSource> {
182         match self {
183             ModuleOrigin::File { definition, .. } | ModuleOrigin::CrateRoot { definition } => {
184                 let file_id = *definition;
185                 let sf = db.parse(file_id).tree();
186                 InFile::new(file_id.into(), ModuleSource::SourceFile(sf))
187             }
188             ModuleOrigin::Inline { definition } => InFile::new(
189                 definition.file_id,
190                 ModuleSource::Module(definition.to_node(db.upcast())),
191             ),
192             ModuleOrigin::BlockExpr { block } => {
193                 InFile::new(block.file_id, ModuleSource::BlockExpr(block.to_node(db.upcast())))
194             }
195         }
196     }
197 }
198
199 #[derive(Default, Debug, PartialEq, Eq)]
200 pub struct ModuleData {
201     pub parent: Option<LocalModuleId>,
202     pub children: FxHashMap<Name, LocalModuleId>,
203     pub scope: ItemScope,
204
205     /// Where does this module come from?
206     pub origin: ModuleOrigin,
207 }
208
209 impl DefMap {
210     pub(crate) fn crate_def_map_query(db: &dyn DefDatabase, krate: CrateId) -> Arc<DefMap> {
211         let _p = profile::span("crate_def_map_query").detail(|| {
212             db.crate_graph()[krate].display_name.as_deref().unwrap_or_default().to_string()
213         });
214         let edition = db.crate_graph()[krate].edition;
215         let def_map = DefMap::empty(krate, edition);
216         let def_map = collector::collect_defs(db, def_map, None);
217         Arc::new(def_map)
218     }
219
220     pub(crate) fn block_def_map_query(
221         db: &dyn DefDatabase,
222         block_id: BlockId,
223     ) -> Option<Arc<DefMap>> {
224         let block: BlockLoc = db.lookup_intern_block(block_id);
225
226         let item_tree = db.file_item_tree(block.ast_id.file_id);
227         if item_tree.inner_items_of_block(block.ast_id.value).is_empty() {
228             return None;
229         }
230
231         let block_info = BlockInfo { block: block_id, parent: block.module };
232
233         let parent_map = block.module.def_map(db);
234         let mut def_map = DefMap::empty(block.module.krate, parent_map.edition);
235         def_map.block = Some(block_info);
236
237         let def_map = collector::collect_defs(db, def_map, Some(block.ast_id));
238         Some(Arc::new(def_map))
239     }
240
241     fn empty(krate: CrateId, edition: Edition) -> DefMap {
242         let mut modules: Arena<ModuleData> = Arena::default();
243         let root = modules.alloc(ModuleData::default());
244         DefMap {
245             _c: Count::new(),
246             block: None,
247             krate,
248             edition,
249             extern_prelude: FxHashMap::default(),
250             exported_proc_macros: FxHashMap::default(),
251             prelude: None,
252             root,
253             modules,
254             diagnostics: Vec::new(),
255         }
256     }
257
258     pub fn modules_for_file(&self, file_id: FileId) -> impl Iterator<Item = LocalModuleId> + '_ {
259         self.modules
260             .iter()
261             .filter(move |(_id, data)| data.origin.file_id() == Some(file_id))
262             .map(|(id, _data)| id)
263     }
264
265     pub fn modules(&self) -> impl Iterator<Item = (LocalModuleId, &ModuleData)> + '_ {
266         self.modules.iter()
267     }
268
269     pub fn root(&self) -> LocalModuleId {
270         self.root
271     }
272
273     pub(crate) fn krate(&self) -> CrateId {
274         self.krate
275     }
276
277     pub(crate) fn block_id(&self) -> Option<BlockId> {
278         self.block.as_ref().map(|block| block.block)
279     }
280
281     pub(crate) fn prelude(&self) -> Option<ModuleId> {
282         self.prelude
283     }
284
285     pub(crate) fn extern_prelude(&self) -> impl Iterator<Item = (&Name, &ModuleDefId)> + '_ {
286         self.extern_prelude.iter()
287     }
288
289     pub fn module_id(&self, local_id: LocalModuleId) -> ModuleId {
290         let block = self.block.as_ref().map(|b| b.block);
291         ModuleId { krate: self.krate, local_id, block }
292     }
293
294     pub(crate) fn crate_root(&self, db: &dyn DefDatabase) -> ModuleId {
295         self.with_ancestor_maps(db, self.root, &mut |def_map, _module| {
296             if def_map.block.is_none() {
297                 Some(def_map.module_id(def_map.root))
298             } else {
299                 None
300             }
301         })
302         .expect("DefMap chain without root")
303     }
304
305     pub(crate) fn resolve_path(
306         &self,
307         db: &dyn DefDatabase,
308         original_module: LocalModuleId,
309         path: &ModPath,
310         shadow: BuiltinShadowMode,
311     ) -> (PerNs, Option<usize>) {
312         let res =
313             self.resolve_path_fp_with_macro(db, ResolveMode::Other, original_module, path, shadow);
314         (res.resolved_def, res.segment_index)
315     }
316
317     pub(crate) fn resolve_path_locally(
318         &self,
319         db: &dyn DefDatabase,
320         original_module: LocalModuleId,
321         path: &ModPath,
322         shadow: BuiltinShadowMode,
323     ) -> (PerNs, Option<usize>) {
324         let res = self.resolve_path_fp_with_macro_single(
325             db,
326             ResolveMode::Other,
327             original_module,
328             path,
329             shadow,
330         );
331         (res.resolved_def, res.segment_index)
332     }
333
334     /// Ascends the `DefMap` hierarchy and calls `f` with every `DefMap` and containing module.
335     ///
336     /// If `f` returns `Some(val)`, iteration is stopped and `Some(val)` is returned. If `f` returns
337     /// `None`, iteration continues.
338     pub fn with_ancestor_maps<T>(
339         &self,
340         db: &dyn DefDatabase,
341         local_mod: LocalModuleId,
342         f: &mut dyn FnMut(&DefMap, LocalModuleId) -> Option<T>,
343     ) -> Option<T> {
344         if let Some(it) = f(self, local_mod) {
345             return Some(it);
346         }
347         let mut block = self.block;
348         while let Some(block_info) = block {
349             let parent = block_info.parent.def_map(db);
350             if let Some(it) = f(&parent, block_info.parent.local_id) {
351                 return Some(it);
352             }
353             block = parent.block;
354         }
355
356         None
357     }
358
359     /// If this `DefMap` is for a block expression, returns the module containing the block (which
360     /// might again be a block, or a module inside a block).
361     pub fn parent(&self) -> Option<ModuleId> {
362         Some(self.block?.parent)
363     }
364
365     /// Returns the module containing `local_mod`, either the parent `mod`, or the module containing
366     /// the block, if `self` corresponds to a block expression.
367     pub fn containing_module(&self, local_mod: LocalModuleId) -> Option<ModuleId> {
368         match &self[local_mod].parent {
369             Some(parent) => Some(self.module_id(*parent)),
370             None => match &self.block {
371                 Some(block) => Some(block.parent),
372                 None => None,
373             },
374         }
375     }
376
377     // FIXME: this can use some more human-readable format (ideally, an IR
378     // even), as this should be a great debugging aid.
379     pub fn dump(&self, db: &dyn DefDatabase) -> String {
380         let mut buf = String::new();
381         let mut arc;
382         let mut current_map = self;
383         while let Some(block) = &current_map.block {
384             go(&mut buf, current_map, "block scope", current_map.root);
385             buf.push('\n');
386             arc = block.parent.def_map(db);
387             current_map = &*arc;
388         }
389         go(&mut buf, current_map, "crate", current_map.root);
390         return buf;
391
392         fn go(buf: &mut String, map: &DefMap, path: &str, module: LocalModuleId) {
393             format_to!(buf, "{}\n", path);
394
395             map.modules[module].scope.dump(buf);
396
397             for (name, child) in map.modules[module].children.iter() {
398                 let path = format!("{}::{}", path, name);
399                 buf.push('\n');
400                 go(buf, map, &path, *child);
401             }
402         }
403     }
404
405     pub fn dump_block_scopes(&self, db: &dyn DefDatabase) -> String {
406         let mut buf = String::new();
407         let mut arc;
408         let mut current_map = self;
409         while let Some(block) = &current_map.block {
410             format_to!(buf, "{:?} in {:?}\n", block.block, block.parent);
411             arc = block.parent.def_map(db);
412             current_map = &*arc;
413         }
414
415         format_to!(buf, "crate scope\n");
416         buf
417     }
418
419     fn shrink_to_fit(&mut self) {
420         // Exhaustive match to require handling new fields.
421         let Self {
422             _c: _,
423             exported_proc_macros,
424             extern_prelude,
425             diagnostics,
426             modules,
427             block: _,
428             edition: _,
429             krate: _,
430             prelude: _,
431             root: _,
432         } = self;
433
434         extern_prelude.shrink_to_fit();
435         exported_proc_macros.shrink_to_fit();
436         diagnostics.shrink_to_fit();
437         modules.shrink_to_fit();
438         for (_, module) in modules.iter_mut() {
439             module.children.shrink_to_fit();
440             module.scope.shrink_to_fit();
441         }
442     }
443
444     /// Get a reference to the def map's diagnostics.
445     pub fn diagnostics(&self) -> &[DefDiagnostic] {
446         self.diagnostics.as_slice()
447     }
448 }
449
450 impl ModuleData {
451     /// Returns a node which defines this module. That is, a file or a `mod foo {}` with items.
452     pub fn definition_source(&self, db: &dyn DefDatabase) -> InFile<ModuleSource> {
453         self.origin.definition_source(db)
454     }
455
456     /// Returns a node which declares this module, either a `mod foo;` or a `mod foo {}`.
457     /// `None` for the crate root or block.
458     pub fn declaration_source(&self, db: &dyn DefDatabase) -> Option<InFile<ast::Module>> {
459         let decl = self.origin.declaration()?;
460         let value = decl.to_node(db.upcast());
461         Some(InFile { file_id: decl.file_id, value })
462     }
463 }
464
465 #[derive(Debug, Clone, PartialEq, Eq)]
466 pub enum ModuleSource {
467     SourceFile(ast::SourceFile),
468     Module(ast::Module),
469     BlockExpr(ast::BlockExpr),
470 }