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
60 use hir_expand::{diagnostics::DiagnosticSink, name::Name, InFile, MacroDefId};
61 use once_cell::sync::Lazy;
63 use ra_db::{CrateId, Edition, FileId, FilePosition};
69 use rustc_hash::FxHashMap;
72 builtin_type::BuiltinType,
74 nameres::{diagnostics::DefDiagnostic, path_resolution::ResolveMode},
77 AstId, ImplId, LocalImportId, LocalModuleId, ModuleDefId, ModuleId, TraitId,
80 /// Contains all top-level defs from a macro-expanded crate
81 #[derive(Debug, PartialEq, Eq)]
82 pub struct CrateDefMap {
83 pub root: LocalModuleId,
84 pub modules: Arena<LocalModuleId, ModuleData>,
85 pub(crate) krate: CrateId,
86 /// The prelude module for this crate. This either comes from an import
87 /// marked with the `prelude_import` attribute, or (in the normal case) from
88 /// a dependency (`std` or `core`).
89 pub(crate) prelude: Option<ModuleId>,
90 pub(crate) extern_prelude: FxHashMap<Name, ModuleDefId>,
93 diagnostics: Vec<DefDiagnostic>,
96 impl std::ops::Index<LocalModuleId> for CrateDefMap {
97 type Output = ModuleData;
98 fn index(&self, id: LocalModuleId) -> &ModuleData {
103 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
104 pub enum ModuleOrigin {
108 /// Note that non-inline modules, by definition, live inside non-macro file.
110 declaration: AstId<ast::Module>,
114 definition: AstId<ast::Module>,
118 impl Default for ModuleOrigin {
119 fn default() -> Self {
120 ModuleOrigin::CrateRoot { definition: FileId(0) }
125 pub(crate) fn not_sure_file(file: Option<FileId>, declaration: AstId<ast::Module>) -> Self {
127 None => ModuleOrigin::Inline { definition: declaration },
128 Some(definition) => ModuleOrigin::File { declaration, definition },
132 fn declaration(&self) -> Option<AstId<ast::Module>> {
134 ModuleOrigin::File { declaration: module, .. }
135 | ModuleOrigin::Inline { definition: module, .. } => Some(*module),
136 ModuleOrigin::CrateRoot { .. } => None,
140 pub fn file_id(&self) -> Option<FileId> {
142 ModuleOrigin::File { definition, .. } | ModuleOrigin::CrateRoot { definition } => {
149 /// Returns a node which defines this module.
150 /// That is, a file or a `mod foo {}` with items.
151 fn definition_source(&self, db: &impl DefDatabase) -> InFile<ModuleSource> {
153 ModuleOrigin::File { definition, .. } | ModuleOrigin::CrateRoot { definition } => {
154 let file_id = *definition;
155 let sf = db.parse(file_id).tree();
156 return InFile::new(file_id.into(), ModuleSource::SourceFile(sf));
158 ModuleOrigin::Inline { definition } => {
159 InFile::new(definition.file_id, ModuleSource::Module(definition.to_node(db)))
165 #[derive(Default, Debug, PartialEq, Eq)]
166 pub struct ModuleData {
167 pub parent: Option<LocalModuleId>,
168 pub children: FxHashMap<Name, LocalModuleId>,
169 pub scope: ModuleScope,
171 /// Where does this module come from?
172 pub origin: ModuleOrigin,
174 pub impls: Vec<ImplId>,
177 #[derive(Debug, Default, PartialEq, Eq)]
178 pub struct ModuleScope {
179 items: FxHashMap<Name, Resolution>,
180 /// Macros visable in current module in legacy textual scope
182 /// For macros invoked by an unquatified identifier like `bar!()`, `legacy_macros` will be searched in first.
183 /// If it yields no result, then it turns to module scoped `macros`.
184 /// It macros with name quatified with a path like `crate::foo::bar!()`, `legacy_macros` will be skipped,
185 /// and only normal scoped `macros` will be searched in.
187 /// Note that this automatically inherit macros defined textually before the definition of module itself.
189 /// Module scoped macros will be inserted into `items` instead of here.
190 // FIXME: Macro shadowing in one module is not properly handled. Non-item place macros will
191 // be all resolved to the last one defined if shadowing happens.
192 legacy_macros: FxHashMap<Name, MacroDefId>,
195 static BUILTIN_SCOPE: Lazy<FxHashMap<Name, Resolution>> = Lazy::new(|| {
199 (name.clone(), Resolution { def: PerNs::types(ty.clone().into()), import: None })
204 /// Shadow mode for builtin type which can be shadowed by module.
205 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
206 pub enum BuiltinShadowMode {
209 // Prefer Other Types
213 /// Legacy macros can only be accessed through special methods like `get_legacy_macros`.
214 /// Other methods will only resolve values, types and module scoped macros only.
216 pub fn entries<'a>(&'a self) -> impl Iterator<Item = (&'a Name, &'a Resolution)> + 'a {
218 self.items.iter().chain(BUILTIN_SCOPE.iter())
221 pub fn declarations(&self) -> impl Iterator<Item = ModuleDefId> + '_ {
223 .filter_map(|(_name, res)| if res.import.is_none() { Some(res.def) } else { None })
225 per_ns.take_types().into_iter().chain(per_ns.take_values().into_iter())
229 /// Iterate over all module scoped macros
230 pub fn macros<'a>(&'a self) -> impl Iterator<Item = (&'a Name, MacroDefId)> + 'a {
233 .filter_map(|(name, res)| res.def.take_macros().map(|macro_| (name, macro_)))
236 /// Iterate over all legacy textual scoped macros visable at the end of the module
237 pub fn legacy_macros<'a>(&'a self) -> impl Iterator<Item = (&'a Name, MacroDefId)> + 'a {
238 self.legacy_macros.iter().map(|(name, def)| (name, *def))
241 /// Get a name from current module scope, legacy macros are not included
242 pub fn get(&self, name: &Name, shadow: BuiltinShadowMode) -> Option<&Resolution> {
244 BuiltinShadowMode::Module => self.items.get(name).or_else(|| BUILTIN_SCOPE.get(name)),
245 BuiltinShadowMode::Other => {
246 let item = self.items.get(name);
247 if let Some(res) = item {
248 if let Some(ModuleDefId::ModuleId(_)) = res.def.take_types() {
249 return BUILTIN_SCOPE.get(name).or(item);
253 item.or_else(|| BUILTIN_SCOPE.get(name))
258 pub fn traits<'a>(&'a self) -> impl Iterator<Item = TraitId> + 'a {
259 self.items.values().filter_map(|r| match r.def.take_types() {
260 Some(ModuleDefId::TraitId(t)) => Some(t),
265 fn get_legacy_macro(&self, name: &Name) -> Option<MacroDefId> {
266 self.legacy_macros.get(name).copied()
270 #[derive(Debug, Clone, PartialEq, Eq, Default)]
271 pub struct Resolution {
272 /// None for unresolved
274 /// ident by which this is imported into local scope.
275 pub import: Option<LocalImportId>,
279 pub(crate) fn crate_def_map_query(
280 // Note that this doesn't have `+ AstDatabase`!
281 // This gurantess that `CrateDefMap` is stable across reparses.
282 db: &impl DefDatabase,
284 ) -> Arc<CrateDefMap> {
285 let _p = profile("crate_def_map_query");
287 let crate_graph = db.crate_graph();
288 let edition = crate_graph.edition(krate);
289 let mut modules: Arena<LocalModuleId, ModuleData> = Arena::default();
290 let root = modules.alloc(ModuleData::default());
294 extern_prelude: FxHashMap::default(),
298 diagnostics: Vec::new(),
301 let def_map = collector::collect_defs(db, def_map);
305 pub fn add_diagnostics(
307 db: &impl DefDatabase,
308 module: LocalModuleId,
309 sink: &mut DiagnosticSink,
311 self.diagnostics.iter().for_each(|it| it.add_to(db, module, sink))
314 pub fn modules_for_file(&self, file_id: FileId) -> impl Iterator<Item = LocalModuleId> + '_ {
317 .filter(move |(_id, data)| data.origin.file_id() == Some(file_id))
318 .map(|(id, _data)| id)
321 pub(crate) fn resolve_path(
323 db: &impl DefDatabase,
324 original_module: LocalModuleId,
326 shadow: BuiltinShadowMode,
327 ) -> (PerNs, Option<usize>) {
329 self.resolve_path_fp_with_macro(db, ResolveMode::Other, original_module, path, shadow);
330 (res.resolved_def, res.segment_index)
335 /// Returns a node which defines this module. That is, a file or a `mod foo {}` with items.
336 pub fn definition_source(&self, db: &impl DefDatabase) -> InFile<ModuleSource> {
337 self.origin.definition_source(db)
340 /// Returns a node which declares this module, either a `mod foo;` or a `mod foo {}`.
341 /// `None` for the crate root or block.
342 pub fn declaration_source(&self, db: &impl DefDatabase) -> Option<InFile<ast::Module>> {
343 let decl = self.origin.declaration()?;
344 let value = decl.to_node(db);
345 Some(InFile { file_id: decl.file_id, value })
349 #[derive(Debug, Clone, PartialEq, Eq)]
350 pub enum ModuleSource {
351 SourceFile(ast::SourceFile),
356 // FIXME: this methods do not belong here
357 pub fn from_position(db: &impl DefDatabase, position: FilePosition) -> ModuleSource {
358 let parse = db.parse(position.file_id);
359 match &ra_syntax::algo::find_node_at_offset::<ast::Module>(
360 parse.tree().syntax(),
363 Some(m) if !m.has_semi() => ModuleSource::Module(m.clone()),
365 let source_file = parse.tree();
366 ModuleSource::SourceFile(source_file)
371 pub fn from_child_node(db: &impl DefDatabase, child: InFile<&SyntaxNode>) -> ModuleSource {
373 child.value.ancestors().filter_map(ast::Module::cast).find(|it| !it.has_semi())
375 ModuleSource::Module(m)
377 let file_id = child.file_id.original_file(db);
378 let source_file = db.parse(file_id).tree();
379 ModuleSource::SourceFile(source_file)
385 use hir_expand::diagnostics::DiagnosticSink;
386 use ra_db::RelativePathBuf;
387 use ra_syntax::{ast, AstPtr};
389 use crate::{db::DefDatabase, diagnostics::UnresolvedModule, nameres::LocalModuleId, AstId};
391 #[derive(Debug, PartialEq, Eq)]
392 pub(super) enum DefDiagnostic {
394 module: LocalModuleId,
395 declaration: AstId<ast::Module>,
396 candidate: RelativePathBuf,
401 pub(super) fn add_to(
403 db: &impl DefDatabase,
404 target_module: LocalModuleId,
405 sink: &mut DiagnosticSink,
408 DefDiagnostic::UnresolvedModule { module, declaration, candidate } => {
409 if *module != target_module {
412 let decl = declaration.to_node(db);
413 sink.push(UnresolvedModule {
414 file: declaration.file_id,
415 decl: AstPtr::new(&decl),
416 candidate: candidate.clone(),