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