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