]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/hir-def/src/nameres.rs
Rollup merge of #101049 - JeanCASPAR:remove-span_fatal-from-ast_lowering, r=davidtwco
[rust.git] / src / tools / rust-analyzer / 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 proc_macro;
52 pub mod diagnostics;
53 mod collector;
54 mod mod_resolution;
55 mod path_resolution;
56
57 #[cfg(test)]
58 mod tests;
59
60 use std::{cmp::Ord, ops::Deref, sync::Arc};
61
62 use base_db::{CrateId, Edition, FileId};
63 use hir_expand::{name::Name, InFile, MacroCallId, MacroDefId};
64 use itertools::Itertools;
65 use la_arena::Arena;
66 use profile::Count;
67 use rustc_hash::FxHashMap;
68 use stdx::format_to;
69 use syntax::{ast, SmolStr};
70
71 use crate::{
72     db::DefDatabase,
73     item_scope::{BuiltinShadowMode, ItemScope},
74     item_tree::{ItemTreeId, Mod, TreeId},
75     nameres::{diagnostics::DefDiagnostic, path_resolution::ResolveMode},
76     path::ModPath,
77     per_ns::PerNs,
78     visibility::Visibility,
79     AstId, BlockId, BlockLoc, FunctionId, LocalModuleId, MacroId, ModuleId, ProcMacroId,
80 };
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, ModuleId>,
103
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
110     /// attributes.
111     derive_helpers_in_scope: FxHashMap<AstId<ast::Item>, Vec<(Name, MacroId, MacroCallId)>>,
112
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>,
117
118     edition: Edition,
119     recursion_limit: Option<u32>,
120     diagnostics: Vec<DefDiagnostic>,
121 }
122
123 /// For `DefMap`s computed for a block expression, this stores its location in the parent map.
124 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
125 struct BlockInfo {
126     /// The `BlockId` this `DefMap` was created from.
127     block: BlockId,
128     /// The containing module.
129     parent: ModuleId,
130 }
131
132 impl std::ops::Index<LocalModuleId> for DefMap {
133     type Output = ModuleData;
134     fn index(&self, id: LocalModuleId) -> &ModuleData {
135         &self.modules[id]
136     }
137 }
138
139 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
140 pub enum ModuleOrigin {
141     CrateRoot {
142         definition: FileId,
143     },
144     /// Note that non-inline modules, by definition, live inside non-macro file.
145     File {
146         is_mod_rs: bool,
147         declaration: AstId<ast::Module>,
148         declaration_tree_id: ItemTreeId<Mod>,
149         definition: FileId,
150     },
151     Inline {
152         definition_tree_id: ItemTreeId<Mod>,
153         definition: AstId<ast::Module>,
154     },
155     /// Pseudo-module introduced by a block scope (contains only inner items).
156     BlockExpr {
157         block: AstId<ast::BlockExpr>,
158     },
159 }
160
161 impl ModuleOrigin {
162     pub fn declaration(&self) -> Option<AstId<ast::Module>> {
163         match self {
164             ModuleOrigin::File { declaration: module, .. }
165             | ModuleOrigin::Inline { definition: module, .. } => Some(*module),
166             ModuleOrigin::CrateRoot { .. } | ModuleOrigin::BlockExpr { .. } => None,
167         }
168     }
169
170     pub fn file_id(&self) -> Option<FileId> {
171         match self {
172             ModuleOrigin::File { definition, .. } | ModuleOrigin::CrateRoot { definition } => {
173                 Some(*definition)
174             }
175             _ => None,
176         }
177     }
178
179     pub fn is_inline(&self) -> bool {
180         match self {
181             ModuleOrigin::Inline { .. } | ModuleOrigin::BlockExpr { .. } => true,
182             ModuleOrigin::CrateRoot { .. } | ModuleOrigin::File { .. } => false,
183         }
184     }
185
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> {
189         match self {
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))
194             }
195             ModuleOrigin::Inline { definition, .. } => InFile::new(
196                 definition.file_id,
197                 ModuleSource::Module(definition.to_node(db.upcast())),
198             ),
199             ModuleOrigin::BlockExpr { block } => {
200                 InFile::new(block.file_id, ModuleSource::BlockExpr(block.to_node(db.upcast())))
201             }
202         }
203     }
204 }
205
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,
212
213     pub parent: Option<LocalModuleId>,
214     pub children: FxHashMap<Name, LocalModuleId>,
215     pub scope: ItemScope,
216 }
217
218 impl DefMap {
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()
222         });
223
224         let crate_graph = db.crate_graph();
225
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(
230             db,
231             def_map,
232             TreeId::new(crate_graph[krate].root_file_id.into(), None),
233         );
234
235         Arc::new(def_map)
236     }
237
238     pub(crate) fn block_def_map_query(
239         db: &dyn DefDatabase,
240         block_id: BlockId,
241     ) -> Option<Arc<DefMap>> {
242         let block: BlockLoc = db.lookup_intern_block(block_id);
243
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() {
247             return None;
248         }
249
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 });
257         let module_data =
258             ModuleData::new(ModuleOrigin::BlockExpr { block: block.ast_id }, visibility);
259
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 });
262
263         let def_map = collector::collect_defs(db, def_map, tree_id);
264         Some(Arc::new(def_map))
265     }
266
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);
270
271         DefMap {
272             _c: Count::new(),
273             block: None,
274             krate,
275             edition,
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(),
282             prelude: None,
283             root,
284             modules,
285             registered_attrs: Vec::new(),
286             registered_tools: Vec::new(),
287             diagnostics: Vec::new(),
288         }
289     }
290
291     pub fn modules_for_file(&self, file_id: FileId) -> impl Iterator<Item = LocalModuleId> + '_ {
292         self.modules
293             .iter()
294             .filter(move |(_id, data)| data.origin.file_id() == Some(file_id))
295             .map(|(id, _data)| id)
296     }
297
298     pub fn modules(&self) -> impl Iterator<Item = (LocalModuleId, &ModuleData)> + '_ {
299         self.modules.iter()
300     }
301
302     pub fn derive_helpers_in_scope(
303         &self,
304         id: AstId<ast::Adt>,
305     ) -> Option<&[(Name, MacroId, MacroCallId)]> {
306         self.derive_helpers_in_scope.get(&id.map(|it| it.upcast())).map(Deref::deref)
307     }
308
309     pub fn registered_tools(&self) -> &[SmolStr] {
310         &self.registered_tools
311     }
312
313     pub fn registered_attrs(&self) -> &[SmolStr] {
314         &self.registered_attrs
315     }
316
317     pub fn root(&self) -> LocalModuleId {
318         self.root
319     }
320
321     pub fn fn_as_proc_macro(&self, id: FunctionId) -> Option<ProcMacroId> {
322         self.fn_proc_macro_mapping.get(&id).copied()
323     }
324
325     pub fn proc_macro_loading_error(&self) -> Option<&str> {
326         self.proc_macro_loading_error.as_deref()
327     }
328
329     pub(crate) fn krate(&self) -> CrateId {
330         self.krate
331     }
332
333     pub(crate) fn block_id(&self) -> Option<BlockId> {
334         self.block.as_ref().map(|block| block.block)
335     }
336
337     pub(crate) fn prelude(&self) -> Option<ModuleId> {
338         self.prelude
339     }
340
341     pub(crate) fn extern_prelude(&self) -> impl Iterator<Item = (&Name, &ModuleId)> + '_ {
342         self.extern_prelude.iter()
343     }
344
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 }
348     }
349
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 }
353         })
354         .expect("DefMap chain without root")
355     }
356
357     pub(crate) fn resolve_path(
358         &self,
359         db: &dyn DefDatabase,
360         original_module: LocalModuleId,
361         path: &ModPath,
362         shadow: BuiltinShadowMode,
363     ) -> (PerNs, Option<usize>) {
364         let res =
365             self.resolve_path_fp_with_macro(db, ResolveMode::Other, original_module, path, shadow);
366         (res.resolved_def, res.segment_index)
367     }
368
369     pub(crate) fn resolve_path_locally(
370         &self,
371         db: &dyn DefDatabase,
372         original_module: LocalModuleId,
373         path: &ModPath,
374         shadow: BuiltinShadowMode,
375     ) -> (PerNs, Option<usize>) {
376         let res = self.resolve_path_fp_with_macro_single(
377             db,
378             ResolveMode::Other,
379             original_module,
380             path,
381             shadow,
382         );
383         (res.resolved_def, res.segment_index)
384     }
385
386     /// Ascends the `DefMap` hierarchy and calls `f` with every `DefMap` and containing module.
387     ///
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>(
391         &self,
392         db: &dyn DefDatabase,
393         local_mod: LocalModuleId,
394         f: &mut dyn FnMut(&DefMap, LocalModuleId) -> Option<T>,
395     ) -> Option<T> {
396         if let Some(it) = f(self, local_mod) {
397             return Some(it);
398         }
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) {
403                 return Some(it);
404             }
405             block = parent.block;
406         }
407
408         None
409     }
410
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)
415     }
416
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),
423         }
424     }
425
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();
430         let mut arc;
431         let mut current_map = self;
432         while let Some(block) = &current_map.block {
433             go(&mut buf, current_map, "block scope", current_map.root);
434             buf.push('\n');
435             arc = block.parent.def_map(db);
436             current_map = &*arc;
437         }
438         go(&mut buf, current_map, "crate", current_map.root);
439         return buf;
440
441         fn go(buf: &mut String, map: &DefMap, path: &str, module: LocalModuleId) {
442             format_to!(buf, "{}\n", path);
443
444             map.modules[module].scope.dump(buf);
445
446             for (name, child) in
447                 map.modules[module].children.iter().sorted_by(|a, b| Ord::cmp(&a.0, &b.0))
448             {
449                 let path = format!("{}::{}", path, name);
450                 buf.push('\n');
451                 go(buf, map, &path, *child);
452             }
453         }
454     }
455
456     pub fn dump_block_scopes(&self, db: &dyn DefDatabase) -> String {
457         let mut buf = String::new();
458         let mut arc;
459         let mut current_map = self;
460         while let Some(block) = &current_map.block {
461             format_to!(buf, "{:?} in {:?}\n", block.block, block.parent);
462             arc = block.parent.def_map(db);
463             current_map = &*arc;
464         }
465
466         format_to!(buf, "crate scope\n");
467         buf
468     }
469
470     fn shrink_to_fit(&mut self) {
471         // Exhaustive match to require handling new fields.
472         let Self {
473             _c: _,
474             exported_derives,
475             extern_prelude,
476             diagnostics,
477             modules,
478             registered_attrs,
479             registered_tools,
480             fn_proc_macro_mapping,
481             derive_helpers_in_scope,
482             proc_macro_loading_error: _,
483             block: _,
484             edition: _,
485             recursion_limit: _,
486             krate: _,
487             prelude: _,
488             root: _,
489         } = self;
490
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();
502         }
503     }
504
505     /// Get a reference to the def map's diagnostics.
506     pub fn diagnostics(&self) -> &[DefDiagnostic] {
507         self.diagnostics.as_slice()
508     }
509
510     pub fn recursion_limit(&self) -> Option<u32> {
511         self.recursion_limit
512     }
513 }
514
515 impl ModuleData {
516     pub(crate) fn new(origin: ModuleOrigin, visibility: Visibility) -> Self {
517         ModuleData {
518             origin,
519             visibility,
520             parent: None,
521             children: FxHashMap::default(),
522             scope: ItemScope::default(),
523         }
524     }
525
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)
529     }
530
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 })
537     }
538 }
539
540 #[derive(Debug, Clone, PartialEq, Eq)]
541 pub enum ModuleSource {
542     SourceFile(ast::SourceFile),
543     Module(ast::Module),
544     BlockExpr(ast::BlockExpr),
545 }