1 //! This module implements import-resolution/macro expansion algorithm.
3 //! The result of this module is `CrateDefMap`: a data structure which contains:
5 //! * a tree of modules for the crate
6 //! * for each module, a set of items visible in the module (directly declared
9 //! Note that `CrateDefMap` contains fully macro expanded code.
11 //! Computing `CrateDefMap` can be partitioned into several logically
12 //! independent "phases". The phases are mutually recursive though, there's no
15 //! ## Collecting RawItems
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>,
22 //! ## Collecting Modules
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.
29 //! While we walk tree of modules, we also record macro_rules definitions and
30 //! expand calls to macro_rules defined macros.
32 //! ## Resolving Imports
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.
39 //! ## Resolving Macros
41 //! macro_rules from the same crate use a global mutable namespace. We expand
42 //! them immediately, when we collect modules.
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
59 use base_db::{CrateId, Edition, FileId};
60 use hir_expand::{diagnostics::DiagnosticSink, name::Name, InFile};
63 use rustc_hash::FxHashMap;
65 use syntax::{ast, AstNode};
69 item_scope::{BuiltinShadowMode, ItemScope},
70 nameres::{diagnostics::DefDiagnostic, path_resolution::ResolveMode},
73 AstId, LocalModuleId, ModuleDefId, ModuleId,
76 /// Contains all top-level defs from a macro-expanded crate
77 #[derive(Debug, PartialEq, Eq)]
80 parent: Option<Arc<DefMap>>,
82 modules: Arena<ModuleData>,
84 /// The prelude module for this crate. This either comes from an import
85 /// marked with the `prelude_import` attribute, or (in the normal case) from
86 /// a dependency (`std` or `core`).
87 prelude: Option<ModuleId>,
88 extern_prelude: FxHashMap<Name, ModuleDefId>,
91 diagnostics: Vec<DefDiagnostic>,
94 impl std::ops::Index<LocalModuleId> for DefMap {
95 type Output = ModuleData;
96 fn index(&self, id: LocalModuleId) -> &ModuleData {
101 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
102 pub enum ModuleOrigin {
106 /// Note that non-inline modules, by definition, live inside non-macro file.
109 declaration: AstId<ast::Module>,
113 definition: AstId<ast::Module>,
115 /// Pseudo-module introduced by a block scope (contains only inner items).
117 block: AstId<ast::BlockExpr>,
121 impl Default for ModuleOrigin {
122 fn default() -> Self {
123 ModuleOrigin::CrateRoot { definition: FileId(0) }
128 fn declaration(&self) -> Option<AstId<ast::Module>> {
130 ModuleOrigin::File { declaration: module, .. }
131 | ModuleOrigin::Inline { definition: module, .. } => Some(*module),
132 ModuleOrigin::CrateRoot { .. } | ModuleOrigin::BlockExpr { .. } => None,
136 pub fn file_id(&self) -> Option<FileId> {
138 ModuleOrigin::File { definition, .. } | ModuleOrigin::CrateRoot { definition } => {
145 pub fn is_inline(&self) -> bool {
147 ModuleOrigin::Inline { .. } | ModuleOrigin::BlockExpr { .. } => true,
148 ModuleOrigin::CrateRoot { .. } | ModuleOrigin::File { .. } => false,
152 /// Returns a node which defines this module.
153 /// That is, a file or a `mod foo {}` with items.
154 fn definition_source(&self, db: &dyn DefDatabase) -> InFile<ModuleSource> {
156 ModuleOrigin::File { definition, .. } | ModuleOrigin::CrateRoot { definition } => {
157 let file_id = *definition;
158 let sf = db.parse(file_id).tree();
159 InFile::new(file_id.into(), ModuleSource::SourceFile(sf))
161 ModuleOrigin::Inline { definition } => InFile::new(
163 ModuleSource::Module(definition.to_node(db.upcast())),
165 ModuleOrigin::BlockExpr { block } => {
166 InFile::new(block.file_id, ModuleSource::BlockExpr(block.to_node(db.upcast())))
172 #[derive(Default, Debug, PartialEq, Eq)]
173 pub struct ModuleData {
174 pub parent: Option<LocalModuleId>,
175 pub children: FxHashMap<Name, LocalModuleId>,
176 pub scope: ItemScope,
178 /// Where does this module come from?
179 pub origin: ModuleOrigin,
183 pub(crate) fn crate_def_map_query(db: &dyn DefDatabase, krate: CrateId) -> Arc<DefMap> {
184 let _p = profile::span("crate_def_map_query").detail(|| {
185 db.crate_graph()[krate].display_name.as_deref().unwrap_or_default().to_string()
187 let edition = db.crate_graph()[krate].edition;
188 let def_map = DefMap::empty(krate, edition);
189 let def_map = collector::collect_defs(db, def_map, None);
193 pub(crate) fn block_def_map_query(
194 db: &dyn DefDatabase,
196 block: AstId<ast::BlockExpr>,
198 let item_tree = db.item_tree(block.file_id);
199 let block_items = item_tree.inner_items_of_block(block.value);
201 let parent = parent_def_map(db, krate, block);
203 if block_items.is_empty() {
204 // If there are no inner items, nothing new is brought into scope, so we can just return
205 // the parent DefMap. This keeps DefMap parent chains short.
209 let mut def_map = DefMap::empty(krate, parent.edition);
210 def_map.parent = Some(parent);
212 let def_map = collector::collect_defs(db, def_map, Some(block.value));
216 fn empty(krate: CrateId, edition: Edition) -> DefMap {
217 let mut modules: Arena<ModuleData> = Arena::default();
218 let root = modules.alloc(ModuleData::default());
224 extern_prelude: FxHashMap::default(),
228 diagnostics: Vec::new(),
232 pub fn add_diagnostics(
234 db: &dyn DefDatabase,
235 module: LocalModuleId,
236 sink: &mut DiagnosticSink,
238 self.diagnostics.iter().for_each(|it| it.add_to(db, module, sink))
241 pub fn modules_for_file(&self, file_id: FileId) -> impl Iterator<Item = LocalModuleId> + '_ {
244 .filter(move |(_id, data)| data.origin.file_id() == Some(file_id))
245 .map(|(id, _data)| id)
248 pub fn modules(&self) -> impl Iterator<Item = (LocalModuleId, &ModuleData)> + '_ {
252 pub fn root(&self) -> LocalModuleId {
256 pub(crate) fn krate(&self) -> CrateId {
260 pub(crate) fn prelude(&self) -> Option<ModuleId> {
264 pub(crate) fn extern_prelude(&self) -> impl Iterator<Item = (&Name, &ModuleDefId)> + '_ {
265 self.extern_prelude.iter()
268 pub(crate) fn resolve_path(
270 db: &dyn DefDatabase,
271 original_module: LocalModuleId,
273 shadow: BuiltinShadowMode,
274 ) -> (PerNs, Option<usize>) {
276 self.resolve_path_fp_with_macro(db, ResolveMode::Other, original_module, path, shadow);
277 (res.resolved_def, res.segment_index)
280 // FIXME: this can use some more human-readable format (ideally, an IR
281 // even), as this should be a great debugging aid.
282 pub fn dump(&self) -> String {
283 let mut buf = String::new();
284 let mut current_map = self;
285 while let Some(parent) = ¤t_map.parent {
286 go(&mut buf, current_map, "block scope", current_map.root);
287 current_map = &**parent;
289 go(&mut buf, current_map, "crate", current_map.root);
292 fn go(buf: &mut String, map: &DefMap, path: &str, module: LocalModuleId) {
293 format_to!(buf, "{}\n", path);
295 let mut entries: Vec<_> = map.modules[module].scope.resolutions().collect();
296 entries.sort_by_key(|(name, _)| name.clone());
298 for (name, def) in entries {
299 format_to!(buf, "{}:", name.map_or("_".to_string(), |name| name.to_string()));
301 if def.types.is_some() {
304 if def.values.is_some() {
307 if def.macros.is_some() {
317 for (name, child) in map.modules[module].children.iter() {
318 let path = format!("{}::{}", path, name);
320 go(buf, map, &path, *child);
327 /// Returns a node which defines this module. That is, a file or a `mod foo {}` with items.
328 pub fn definition_source(&self, db: &dyn DefDatabase) -> InFile<ModuleSource> {
329 self.origin.definition_source(db)
332 /// Returns a node which declares this module, either a `mod foo;` or a `mod foo {}`.
333 /// `None` for the crate root or block.
334 pub fn declaration_source(&self, db: &dyn DefDatabase) -> Option<InFile<ast::Module>> {
335 let decl = self.origin.declaration()?;
336 let value = decl.to_node(db.upcast());
337 Some(InFile { file_id: decl.file_id, value })
342 db: &dyn DefDatabase,
344 block: AstId<ast::BlockExpr>,
346 // FIXME: store this info in the item tree instead of reparsing here
347 let ast_id_map = db.ast_id_map(block.file_id);
348 let block_ptr = ast_id_map.get(block.value);
349 let root = match db.parse_or_expand(block.file_id) {
352 return Arc::new(DefMap::empty(krate, Edition::Edition2018));
355 let ast = block_ptr.to_node(&root);
357 for ancestor in ast.syntax().ancestors().skip(1) {
358 if let Some(block_expr) = ast::BlockExpr::cast(ancestor) {
359 let ancestor_id = ast_id_map.ast_id(&block_expr);
360 let ast_id = InFile::new(block.file_id, ancestor_id);
361 let parent_map = db.block_def_map(krate, ast_id);
366 // No enclosing block scope, so the parent is the crate-level DefMap.
367 db.crate_def_map(krate)
370 #[derive(Debug, Clone, PartialEq, Eq)]
371 pub enum ModuleSource {
372 SourceFile(ast::SourceFile),
374 BlockExpr(ast::BlockExpr),
378 use cfg::{CfgExpr, CfgOptions};
379 use hir_expand::diagnostics::DiagnosticSink;
380 use hir_expand::hygiene::Hygiene;
381 use hir_expand::{InFile, MacroCallKind};
382 use syntax::ast::AttrsOwner;
383 use syntax::{ast, AstNode, AstPtr, SyntaxKind, SyntaxNodePtr};
385 use crate::path::ModPath;
386 use crate::{db::DefDatabase, diagnostics::*, nameres::LocalModuleId, AstId};
388 #[derive(Debug, PartialEq, Eq)]
389 enum DiagnosticKind {
390 UnresolvedModule { declaration: AstId<ast::Module>, candidate: String },
392 UnresolvedExternCrate { ast: AstId<ast::ExternCrate> },
394 UnresolvedImport { ast: AstId<ast::Use>, index: usize },
396 UnconfiguredCode { ast: AstId<ast::Item>, cfg: CfgExpr, opts: CfgOptions },
398 UnresolvedProcMacro { ast: MacroCallKind },
400 MacroError { ast: MacroCallKind, message: String },
403 #[derive(Debug, PartialEq, Eq)]
404 pub(super) struct DefDiagnostic {
405 in_module: LocalModuleId,
406 kind: DiagnosticKind,
410 pub(super) fn unresolved_module(
411 container: LocalModuleId,
412 declaration: AstId<ast::Module>,
416 in_module: container,
417 kind: DiagnosticKind::UnresolvedModule { declaration, candidate },
421 pub(super) fn unresolved_extern_crate(
422 container: LocalModuleId,
423 declaration: AstId<ast::ExternCrate>,
426 in_module: container,
427 kind: DiagnosticKind::UnresolvedExternCrate { ast: declaration },
431 pub(super) fn unresolved_import(
432 container: LocalModuleId,
433 ast: AstId<ast::Use>,
436 Self { in_module: container, kind: DiagnosticKind::UnresolvedImport { ast, index } }
439 pub(super) fn unconfigured_code(
440 container: LocalModuleId,
441 ast: AstId<ast::Item>,
445 Self { in_module: container, kind: DiagnosticKind::UnconfiguredCode { ast, cfg, opts } }
448 pub(super) fn unresolved_proc_macro(container: LocalModuleId, ast: MacroCallKind) -> Self {
449 Self { in_module: container, kind: DiagnosticKind::UnresolvedProcMacro { ast } }
452 pub(super) fn macro_error(
453 container: LocalModuleId,
457 Self { in_module: container, kind: DiagnosticKind::MacroError { ast, message } }
460 pub(super) fn add_to(
462 db: &dyn DefDatabase,
463 target_module: LocalModuleId,
464 sink: &mut DiagnosticSink,
466 if self.in_module != target_module {
471 DiagnosticKind::UnresolvedModule { declaration, candidate } => {
472 let decl = declaration.to_node(db.upcast());
473 sink.push(UnresolvedModule {
474 file: declaration.file_id,
475 decl: AstPtr::new(&decl),
476 candidate: candidate.clone(),
480 DiagnosticKind::UnresolvedExternCrate { ast } => {
481 let item = ast.to_node(db.upcast());
482 sink.push(UnresolvedExternCrate {
484 item: AstPtr::new(&item),
488 DiagnosticKind::UnresolvedImport { ast, index } => {
489 let use_item = ast.to_node(db.upcast());
490 let hygiene = Hygiene::new(db.upcast(), ast.file_id);
493 ModPath::expand_use_item(
494 InFile::new(ast.file_id, use_item),
496 |_mod_path, use_tree, _is_glob, _alias| {
498 tree = Some(use_tree.clone());
505 if let Some(tree) = tree {
506 sink.push(UnresolvedImport { file: ast.file_id, node: AstPtr::new(&tree) });
510 DiagnosticKind::UnconfiguredCode { ast, cfg, opts } => {
511 let item = ast.to_node(db.upcast());
512 sink.push(InactiveCode {
514 node: AstPtr::new(&item).into(),
520 DiagnosticKind::UnresolvedProcMacro { ast } => {
521 let mut precise_location = None;
522 let (file, ast, name) = match ast {
523 MacroCallKind::FnLike(ast) => {
524 let node = ast.to_node(db.upcast());
525 (ast.file_id, SyntaxNodePtr::from(AstPtr::new(&node)), None)
527 MacroCallKind::Attr(ast, name) => {
528 let node = ast.to_node(db.upcast());
530 // Compute the precise location of the macro name's token in the derive
532 // FIXME: This does not handle paths to the macro, but neither does the
535 node.attrs().filter_map(|attr| match attr.as_simple_call() {
536 Some((name, args)) if name == "derive" => Some(args),
539 'outer: for attr in derive_attrs {
541 attr.syntax().children_with_tokens().filter_map(|elem| {
543 syntax::NodeOrToken::Node(_) => None,
544 syntax::NodeOrToken::Token(tok) => Some(tok),
547 for token in tokens {
548 if token.kind() == SyntaxKind::IDENT
549 && token.text() == name.as_str()
551 precise_location = Some(token.text_range());
559 SyntaxNodePtr::from(AstPtr::new(&node)),
564 sink.push(UnresolvedProcMacro {
572 DiagnosticKind::MacroError { ast, message } => {
573 let (file, ast) = match ast {
574 MacroCallKind::FnLike(ast) => {
575 let node = ast.to_node(db.upcast());
576 (ast.file_id, SyntaxNodePtr::from(AstPtr::new(&node)))
578 MacroCallKind::Attr(ast, _) => {
579 let node = ast.to_node(db.upcast());
580 (ast.file_id, SyntaxNodePtr::from(AstPtr::new(&node)))
583 sink.push(MacroError { file, node: ast, message: message.clone() });