1 //! The core of the module-level name resolution algorithm.
3 //! `DefCollector::collect` contains the fixed-point iteration loop which
4 //! resolves imports and expands macros.
8 use base_db::{CrateId, Edition, FileId, ProcMacroId};
9 use cfg::{CfgExpr, CfgOptions};
11 builtin_attr_macro::find_builtin_attr,
12 builtin_derive_macro::find_builtin_derive,
13 builtin_fn_macro::find_builtin_macro,
14 name::{name, AsName, Name},
15 proc_macro::ProcMacroExpander,
16 ExpandTo, HirFileId, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind,
18 use hir_expand::{InFile, MacroCallLoc};
19 use itertools::Itertools;
22 use rustc_hash::{FxHashMap, FxHashSet};
23 use syntax::{ast, SmolStr};
26 attr::{Attr, AttrId, AttrInput, Attrs},
27 attr_macro_as_call_id, builtin_attr,
29 derive_macro_as_call_id,
31 item_scope::{ImportType, PerNsGlobImports},
33 self, Fields, FileItemTreeId, ImportKind, ItemTree, ItemTreeId, MacroCall, MacroDef,
34 MacroRules, Mod, ModItem, ModKind, TreeId,
36 macro_call_as_call_id,
38 diagnostics::DefDiagnostic,
39 mod_resolution::ModDir,
40 path_resolution::ReachedFixedPoint,
41 proc_macro::{ProcMacroDef, ProcMacroKind},
42 BuiltinShadowMode, DefMap, ModuleData, ModuleOrigin, ResolveMode,
44 path::{ImportAlias, ModPath, PathKind},
46 visibility::{RawVisibility, Visibility},
47 AdtId, AstId, AstIdWithPath, ConstLoc, EnumLoc, EnumVariantId, FunctionLoc, ImplLoc, Intern,
48 LocalModuleId, ModuleDefId, StaticLoc, StructLoc, TraitLoc, TypeAliasLoc, UnionLoc,
52 static GLOB_RECURSION_LIMIT: Limit = Limit::new(100);
53 static EXPANSION_DEPTH_LIMIT: Limit = Limit::new(128);
54 static FIXED_POINT_LIMIT: Limit = Limit::new(8192);
56 pub(super) fn collect_defs(db: &dyn DefDatabase, mut def_map: DefMap, tree_id: TreeId) -> DefMap {
57 let crate_graph = db.crate_graph();
59 let mut deps = FxHashMap::default();
60 // populate external prelude and dependency list
61 for dep in &crate_graph[def_map.krate].dependencies {
62 tracing::debug!("crate dep {:?} -> {:?}", dep.name, dep.crate_id);
63 let dep_def_map = db.crate_def_map(dep.crate_id);
64 let dep_root = dep_def_map.module_id(dep_def_map.root);
66 deps.insert(dep.as_name(), dep_root.into());
68 if dep.is_prelude() && !tree_id.is_block() {
69 def_map.extern_prelude.insert(dep.as_name(), dep_root.into());
73 let cfg_options = &crate_graph[def_map.krate].cfg_options;
74 let proc_macros = &crate_graph[def_map.krate].proc_macro;
75 let proc_macros = proc_macros
79 // FIXME: a hacky way to create a Name from string.
80 let name = tt::Ident { text: it.name.clone(), id: tt::TokenId::unspecified() };
81 (name.as_name(), ProcMacroExpander::new(def_map.krate, ProcMacroId(idx as u32)))
85 let mut collector = DefCollector {
89 glob_imports: FxHashMap::default(),
90 unresolved_imports: Vec::new(),
91 resolved_imports: Vec::new(),
92 unresolved_macros: Vec::new(),
93 mod_dirs: FxHashMap::default(),
96 exports_proc_macros: false,
97 from_glob_import: Default::default(),
98 skip_attrs: Default::default(),
99 derive_helpers_in_scope: Default::default(),
100 registered_attrs: Default::default(),
101 registered_tools: Default::default(),
103 if tree_id.is_block() {
104 collector.seed_with_inner(tree_id);
106 collector.seed_with_top_level();
109 let mut def_map = collector.finish();
110 def_map.shrink_to_fit();
114 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
115 enum PartialResolvedImport {
116 /// None of any namespaces is resolved
118 /// One of namespaces is resolved
119 Indeterminate(PerNs),
120 /// All namespaces are resolved, OR it comes from other crate
124 impl PartialResolvedImport {
125 fn namespaces(self) -> PerNs {
127 PartialResolvedImport::Unresolved => PerNs::none(),
128 PartialResolvedImport::Indeterminate(ns) | PartialResolvedImport::Resolved(ns) => ns,
133 #[derive(Clone, Debug, Eq, PartialEq)]
135 Import { id: ItemTreeId<item_tree::Import>, use_tree: Idx<ast::UseTree> },
136 ExternCrate(ItemTreeId<item_tree::ExternCrate>),
139 #[derive(Clone, Debug, Eq, PartialEq)]
141 path: Interned<ModPath>,
142 alias: Option<ImportAlias>,
143 visibility: RawVisibility,
146 is_extern_crate: bool,
148 source: ImportSource,
153 db: &dyn DefDatabase,
156 id: ItemTreeId<item_tree::Import>,
158 let it = &tree[id.value];
159 let attrs = &tree.attrs(db, krate, ModItem::from(id.value).into());
160 let visibility = &tree[it.visibility];
161 let is_prelude = attrs.by_key("prelude_import").exists();
163 let mut res = Vec::new();
164 it.use_tree.expand(|idx, path, kind, alias| {
166 path: Interned::new(path), // FIXME this makes little sense
168 visibility: visibility.clone(),
171 is_extern_crate: false,
173 source: ImportSource::Import { id, use_tree: idx },
179 fn from_extern_crate(
180 db: &dyn DefDatabase,
183 id: ItemTreeId<item_tree::ExternCrate>,
185 let it = &tree[id.value];
186 let attrs = &tree.attrs(db, krate, ModItem::from(id.value).into());
187 let visibility = &tree[it.visibility];
189 path: Interned::new(ModPath::from_segments(
191 iter::once(it.name.clone()),
193 alias: it.alias.clone(),
194 visibility: visibility.clone(),
195 kind: ImportKind::Plain,
197 is_extern_crate: true,
198 is_macro_use: attrs.by_key("macro_use").exists(),
199 source: ImportSource::ExternCrate(id),
204 #[derive(Clone, Debug, Eq, PartialEq)]
205 struct ImportDirective {
206 module_id: LocalModuleId,
208 status: PartialResolvedImport,
211 #[derive(Clone, Debug, Eq, PartialEq)]
212 struct MacroDirective {
213 module_id: LocalModuleId,
215 kind: MacroDirectiveKind,
218 #[derive(Clone, Debug, Eq, PartialEq)]
219 enum MacroDirectiveKind {
220 FnLike { ast_id: AstIdWithPath<ast::MacroCall>, expand_to: ExpandTo },
221 Derive { ast_id: AstIdWithPath<ast::Item>, derive_attr: AttrId },
222 Attr { ast_id: AstIdWithPath<ast::Item>, attr: Attr, mod_item: ModItem, tree: TreeId },
225 /// Walks the tree of module recursively
226 struct DefCollector<'a> {
227 db: &'a dyn DefDatabase,
229 deps: FxHashMap<Name, ModuleDefId>,
230 glob_imports: FxHashMap<LocalModuleId, Vec<(LocalModuleId, Visibility)>>,
231 unresolved_imports: Vec<ImportDirective>,
232 resolved_imports: Vec<ImportDirective>,
233 unresolved_macros: Vec<MacroDirective>,
234 mod_dirs: FxHashMap<LocalModuleId, ModDir>,
235 cfg_options: &'a CfgOptions,
236 /// List of procedural macros defined by this crate. This is read from the dynamic library
237 /// built by the build system, and is the list of proc. macros we can actually expand. It is
238 /// empty when proc. macro support is disabled (in which case we still do name resolution for
240 proc_macros: Vec<(Name, ProcMacroExpander)>,
241 exports_proc_macros: bool,
242 from_glob_import: PerNsGlobImports,
243 /// If we fail to resolve an attribute on a `ModItem`, we fall back to ignoring the attribute.
244 /// This map is used to skip all attributes up to and including the one that failed to resolve,
245 /// in order to not expand them twice.
247 /// This also stores the attributes to skip when we resolve derive helpers and non-macro
248 /// non-builtin attributes in general.
249 skip_attrs: FxHashMap<InFile<ModItem>, AttrId>,
250 /// Tracks which custom derives are in scope for an item, to allow resolution of derive helper
252 derive_helpers_in_scope: FxHashMap<AstId<ast::Item>, Vec<Name>>,
253 /// Custom attributes registered with `#![register_attr]`.
254 registered_attrs: Vec<SmolStr>,
255 /// Custom tool modules registered with `#![register_tool]`.
256 registered_tools: Vec<SmolStr>,
259 impl DefCollector<'_> {
260 fn seed_with_top_level(&mut self) {
261 let _p = profile::span("seed_with_top_level");
263 let file_id = self.db.crate_graph()[self.def_map.krate].root_file_id;
264 let item_tree = self.db.file_item_tree(file_id.into());
265 let module_id = self.def_map.root;
267 let attrs = item_tree.top_level_attrs(self.db, self.def_map.krate);
268 if attrs.cfg().map_or(true, |cfg| self.cfg_options.check(&cfg) != Some(false)) {
269 self.inject_prelude(&attrs);
271 // Process other crate-level attributes.
272 for attr in &*attrs {
273 let attr_name = match attr.path.as_ident() {
278 let attr_is_register_like = *attr_name == hir_expand::name![register_attr]
279 || *attr_name == hir_expand::name![register_tool];
280 if !attr_is_register_like {
284 let registered_name = match attr.input.as_deref() {
285 Some(AttrInput::TokenTree(subtree, _)) => match &*subtree.token_trees {
286 [tt::TokenTree::Leaf(tt::Leaf::Ident(name))] => name.as_name(),
292 if *attr_name == hir_expand::name![register_attr] {
293 self.registered_attrs.push(registered_name.to_smol_str());
294 cov_mark::hit!(register_attr);
296 self.registered_tools.push(registered_name.to_smol_str());
297 cov_mark::hit!(register_tool);
305 tree_id: TreeId::new(file_id.into(), None),
306 item_tree: &item_tree,
307 mod_dir: ModDir::root(),
309 .collect(item_tree.top_level_items());
313 fn seed_with_inner(&mut self, tree_id: TreeId) {
314 let item_tree = tree_id.item_tree(self.db);
315 let module_id = self.def_map.root;
317 let is_cfg_enabled = item_tree
318 .top_level_attrs(self.db, self.def_map.krate)
320 .map_or(true, |cfg| self.cfg_options.check(&cfg) != Some(false));
327 item_tree: &item_tree,
328 mod_dir: ModDir::root(),
330 .collect(item_tree.top_level_items());
334 fn resolution_loop(&mut self) {
335 let _p = profile::span("DefCollector::resolution_loop");
337 // main name resolution fixed-point loop.
341 self.db.unwind_if_cancelled();
343 let _p = profile::span("resolve_imports loop");
345 if self.resolve_imports() == ReachedFixedPoint::Yes {
350 if self.resolve_macros() == ReachedFixedPoint::Yes {
355 if FIXED_POINT_LIMIT.check(i).is_err() {
356 tracing::error!("name resolution is stuck");
361 if self.reseed_with_unresolved_attribute() == ReachedFixedPoint::Yes {
367 fn collect(&mut self) {
368 let _p = profile::span("DefCollector::collect");
370 self.resolution_loop();
372 // Resolve all indeterminate resolved imports again
373 // As some of the macros will expand newly import shadowing partial resolved imports
374 // FIXME: We maybe could skip this, if we handle the indeterminate imports in `resolve_imports`
376 let partial_resolved = self.resolved_imports.iter().filter_map(|directive| {
377 if let PartialResolvedImport::Indeterminate(_) = directive.status {
378 let mut directive = directive.clone();
379 directive.status = PartialResolvedImport::Unresolved;
385 self.unresolved_imports.extend(partial_resolved);
386 self.resolve_imports();
388 let unresolved_imports = std::mem::take(&mut self.unresolved_imports);
389 // show unresolved imports in completion, etc
390 for directive in &unresolved_imports {
391 self.record_resolved_import(directive)
393 self.unresolved_imports = unresolved_imports;
395 // FIXME: This condition should instead check if this is a `proc-macro` type crate.
396 if self.exports_proc_macros {
397 // A crate exporting procedural macros is not allowed to export anything else.
399 // Additionally, while the proc macro entry points must be `pub`, they are not publicly
400 // exported in type/value namespace. This function reduces the visibility of all items
401 // in the crate root that aren't proc macros.
402 let root = self.def_map.root;
403 let module_id = self.def_map.module_id(root);
404 let root = &mut self.def_map.modules[root];
405 root.scope.censor_non_proc_macros(module_id);
409 /// When the fixed-point loop reaches a stable state, we might still have some unresolved
410 /// attributes (or unexpanded attribute proc macros) left over. This takes one of them, and
411 /// feeds the item it's applied to back into name resolution.
413 /// This effectively ignores the fact that the macro is there and just treats the items as
416 /// This improves UX when proc macros are turned off or don't work, and replicates the behavior
417 /// before we supported proc. attribute macros.
418 fn reseed_with_unresolved_attribute(&mut self) -> ReachedFixedPoint {
419 cov_mark::hit!(unresolved_attribute_fallback);
421 let mut unresolved_macros = std::mem::take(&mut self.unresolved_macros);
422 let pos = unresolved_macros.iter().position(|directive| {
423 if let MacroDirectiveKind::Attr { ast_id, mod_item, attr, tree } = &directive.kind {
424 self.skip_attrs.insert(ast_id.ast_id.with_value(*mod_item), attr.id);
426 let item_tree = tree.item_tree(self.db);
427 let mod_dir = self.mod_dirs[&directive.module_id].clone();
430 macro_depth: directive.depth,
431 module_id: directive.module_id,
433 item_tree: &item_tree,
436 .collect(&[*mod_item]);
443 if let Some(pos) = pos {
444 unresolved_macros.remove(pos);
447 // The collection above might add new unresolved macros (eg. derives), so merge the lists.
448 self.unresolved_macros.extend(unresolved_macros);
451 // Continue name resolution with the new data.
452 ReachedFixedPoint::No
454 ReachedFixedPoint::Yes
458 fn inject_prelude(&mut self, crate_attrs: &Attrs) {
459 // See compiler/rustc_builtin_macros/src/standard_library_imports.rs
461 if crate_attrs.by_key("no_core").exists() {
462 // libcore does not get a prelude.
466 let krate = if crate_attrs.by_key("no_std").exists() {
469 let std = name![std];
470 if self.def_map.extern_prelude().any(|(name, _)| *name == std) {
473 // If `std` does not exist for some reason, fall back to core. This mostly helps
474 // keep r-a's own tests minimal.
479 let edition = match self.def_map.edition {
480 Edition::Edition2015 => name![rust_2015],
481 Edition::Edition2018 => name![rust_2018],
482 Edition::Edition2021 => name![rust_2021],
485 let path_kind = if self.def_map.edition == Edition::Edition2015 {
490 let path = ModPath::from_segments(
492 [krate.clone(), name![prelude], edition].into_iter(),
494 // Fall back to the older `std::prelude::v1` for compatibility with Rust <1.52.0
495 // FIXME remove this fallback
497 ModPath::from_segments(path_kind, [krate, name![prelude], name![v1]].into_iter());
499 for path in &[path, fallback_path] {
500 let (per_ns, _) = self.def_map.resolve_path(
504 BuiltinShadowMode::Other,
508 Some((ModuleDefId::ModuleId(m), _)) => {
509 self.def_map.prelude = Some(m);
514 "could not resolve prelude path `{}` to module (resolved to {:?})",
523 /// Adds a definition of procedural macro `name` to the root module.
525 /// # Notes on procedural macro resolution
527 /// Procedural macro functionality is provided by the build system: It has to build the proc
528 /// macro and pass the resulting dynamic library to rust-analyzer.
530 /// When procedural macro support is enabled, the list of proc macros exported by a crate is
531 /// known before we resolve names in the crate. This list is stored in `self.proc_macros` and is
532 /// derived from the dynamic library.
534 /// However, we *also* would like to be able to at least *resolve* macros on our own, without
535 /// help by the build system. So, when the macro isn't found in `self.proc_macros`, we instead
536 /// use a dummy expander that always errors. This comes with the drawback of macros potentially
537 /// going out of sync with what the build system sees (since we resolve using VFS state, but
538 /// Cargo builds only on-disk files). We could and probably should add diagnostics for that.
539 fn export_proc_macro(&mut self, def: ProcMacroDef, ast_id: AstId<ast::Fn>) {
540 let kind = def.kind.to_basedb_kind();
541 self.exports_proc_macros = true;
542 let macro_def = match self.proc_macros.iter().find(|(n, _)| n == &def.name) {
543 Some(&(_, expander)) => MacroDefId {
544 krate: self.def_map.krate,
545 kind: MacroDefKind::ProcMacro(expander, kind, ast_id),
549 krate: self.def_map.krate,
550 kind: MacroDefKind::ProcMacro(
551 ProcMacroExpander::dummy(self.def_map.krate),
559 self.define_proc_macro(def.name.clone(), macro_def);
560 self.def_map.exported_proc_macros.insert(macro_def, def);
563 /// Define a macro with `macro_rules`.
565 /// It will define the macro in legacy textual scope, and if it has `#[macro_export]`,
566 /// then it is also defined in the root module scope.
567 /// You can `use` or invoke it by `crate::macro_name` anywhere, before or after the definition.
569 /// It is surprising that the macro will never be in the current module scope.
570 /// These code fails with "unresolved import/macro",
571 /// ```rust,compile_fail
572 /// mod m { macro_rules! foo { () => {} } }
573 /// use m::foo as bar;
576 /// ```rust,compile_fail
577 /// macro_rules! foo { () => {} }
582 /// Well, this code compiles, because the plain path `foo` in `use` is searched
583 /// in the legacy textual scope only.
585 /// macro_rules! foo { () => {} }
588 fn define_macro_rules(
590 module_id: LocalModuleId,
596 self.define_legacy_macro(module_id, name.clone(), macro_);
599 // In Rust, `#[macro_export]` macros are unconditionally visible at the
600 // crate root, even if the parent modules is **not** visible.
604 &[(Some(name), PerNs::macros(macro_, Visibility::Public))],
611 /// Define a legacy textual scoped macro in module
613 /// We use a map `legacy_macros` to store all legacy textual scoped macros visible per module.
614 /// It will clone all macros from parent legacy scope, whose definition is prior to
615 /// the definition of current module.
616 /// And also, `macro_use` on a module will import all legacy macros visible inside to
617 /// current legacy scope, with possible shadowing.
618 fn define_legacy_macro(&mut self, module_id: LocalModuleId, name: Name, mac: MacroDefId) {
620 self.def_map.modules[module_id].scope.define_legacy_macro(name, mac);
623 /// Define a macro 2.0 macro
625 /// The scoped of macro 2.0 macro is equal to normal function
628 module_id: LocalModuleId,
634 self.def_map.resolve_visibility(self.db, module_id, vis).unwrap_or(Visibility::Public);
635 self.update(module_id, &[(Some(name), PerNs::macros(macro_, vis))], vis, ImportType::Named);
638 /// Define a proc macro
640 /// A proc macro is similar to normal macro scope, but it would not visible in legacy textual scoped.
641 /// And unconditionally exported.
642 fn define_proc_macro(&mut self, name: Name, macro_: MacroDefId) {
645 &[(Some(name), PerNs::macros(macro_, Visibility::Public))],
651 /// Import macros from `#[macro_use] extern crate`.
652 fn import_macros_from_extern_crate(
654 current_module_id: LocalModuleId,
655 extern_crate: &item_tree::ExternCrate,
658 "importing macros from extern crate: {:?} ({:?})",
660 self.def_map.edition,
663 let res = self.resolve_extern_crate(&extern_crate.name);
665 if let Some(ModuleDefId::ModuleId(m)) = res.take_types() {
666 if m == self.def_map.module_id(current_module_id) {
667 cov_mark::hit!(ignore_macro_use_extern_crate_self);
671 cov_mark::hit!(macro_rules_from_other_crates_are_visible_with_macro_use);
672 self.import_all_macros_exported(current_module_id, m.krate);
676 /// Import all exported macros from another crate
678 /// Exported macros are just all macros in the root module scope.
679 /// Note that it contains not only all `#[macro_export]` macros, but also all aliases
680 /// created by `use` in the root module, ignoring the visibility of `use`.
681 fn import_all_macros_exported(&mut self, current_module_id: LocalModuleId, krate: CrateId) {
682 let def_map = self.db.crate_def_map(krate);
683 for (name, def) in def_map[def_map.root].scope.macros() {
684 // `macro_use` only bring things into legacy scope.
685 self.define_legacy_macro(current_module_id, name.clone(), def);
689 /// Tries to resolve every currently unresolved import.
690 fn resolve_imports(&mut self) -> ReachedFixedPoint {
691 let mut res = ReachedFixedPoint::Yes;
692 let imports = std::mem::take(&mut self.unresolved_imports);
693 let imports = imports
695 .filter_map(|mut directive| {
696 directive.status = self.resolve_import(directive.module_id, &directive.import);
697 match directive.status {
698 PartialResolvedImport::Indeterminate(_) => {
699 self.record_resolved_import(&directive);
700 // FIXME: For avoid performance regression,
701 // we consider an imported resolved if it is indeterminate (i.e not all namespace resolved)
702 self.resolved_imports.push(directive);
703 res = ReachedFixedPoint::No;
706 PartialResolvedImport::Resolved(_) => {
707 self.record_resolved_import(&directive);
708 self.resolved_imports.push(directive);
709 res = ReachedFixedPoint::No;
712 PartialResolvedImport::Unresolved => Some(directive),
716 self.unresolved_imports = imports;
720 fn resolve_import(&self, module_id: LocalModuleId, import: &Import) -> PartialResolvedImport {
721 let _p = profile::span("resolve_import").detail(|| format!("{}", import.path));
722 tracing::debug!("resolving import: {:?} ({:?})", import, self.def_map.edition);
723 if import.is_extern_crate {
727 .expect("extern crate should have been desugared to one-element path");
729 let res = self.resolve_extern_crate(name);
732 PartialResolvedImport::Unresolved
734 PartialResolvedImport::Resolved(res)
737 let res = self.def_map.resolve_path_fp_with_macro(
742 BuiltinShadowMode::Module,
745 let def = res.resolved_def;
746 if res.reached_fixedpoint == ReachedFixedPoint::No || def.is_none() {
747 return PartialResolvedImport::Unresolved;
750 if let Some(krate) = res.krate {
751 if krate != self.def_map.krate {
752 return PartialResolvedImport::Resolved(
753 def.filter_visibility(|v| matches!(v, Visibility::Public)),
758 // Check whether all namespace is resolved
759 if def.take_types().is_some()
760 && def.take_values().is_some()
761 && def.take_macros().is_some()
763 PartialResolvedImport::Resolved(def)
765 PartialResolvedImport::Indeterminate(def)
770 fn resolve_extern_crate(&self, name: &Name) -> PerNs {
771 if *name == name!(self) {
772 cov_mark::hit!(extern_crate_self_as);
773 let root = match self.def_map.block {
775 let def_map = self.def_map.crate_root(self.db).def_map(self.db);
776 def_map.module_id(def_map.root())
778 None => self.def_map.module_id(self.def_map.root()),
780 PerNs::types(root.into(), Visibility::Public)
782 self.deps.get(name).map_or(PerNs::none(), |&it| PerNs::types(it, Visibility::Public))
786 fn record_resolved_import(&mut self, directive: &ImportDirective) {
787 let _p = profile::span("record_resolved_import");
789 let module_id = directive.module_id;
790 let import = &directive.import;
791 let mut def = directive.status.namespaces();
794 .resolve_visibility(self.db, module_id, &directive.import.visibility)
795 .unwrap_or(Visibility::Public);
798 ImportKind::Plain | ImportKind::TypeOnly => {
799 let name = match &import.alias {
800 Some(ImportAlias::Alias(name)) => Some(name),
801 Some(ImportAlias::Underscore) => None,
802 None => match import.path.segments().last() {
803 Some(last_segment) => Some(last_segment),
805 cov_mark::hit!(bogus_paths);
811 if import.kind == ImportKind::TypeOnly {
816 tracing::debug!("resolved import {:?} ({:?}) to {:?}", name, import, def);
818 // extern crates in the crate root are special-cased to insert entries into the extern prelude: rust-lang/rust#54658
819 if import.is_extern_crate && module_id == self.def_map.root {
820 if let (Some(def), Some(name)) = (def.take_types(), name) {
821 self.def_map.extern_prelude.insert(name.clone(), def);
825 self.update(module_id, &[(name.cloned(), def)], vis, ImportType::Named);
827 ImportKind::Glob => {
828 tracing::debug!("glob import: {:?}", import);
829 match def.take_types() {
830 Some(ModuleDefId::ModuleId(m)) => {
831 if import.is_prelude {
832 // Note: This dodgily overrides the injected prelude. The rustc
833 // implementation seems to work the same though.
834 cov_mark::hit!(std_prelude);
835 self.def_map.prelude = Some(m);
836 } else if m.krate != self.def_map.krate {
837 cov_mark::hit!(glob_across_crates);
838 // glob import from other crate => we can just import everything once
839 let item_map = m.def_map(self.db);
840 let scope = &item_map[m.local_id].scope;
842 // Module scoped macros is included
845 // only keep visible names...
847 (n, res.filter_visibility(|v| v.is_visible_from_other_crate()))
849 .filter(|(_, res)| !res.is_none())
850 .collect::<Vec<_>>();
852 self.update(module_id, &items, vis, ImportType::Glob);
854 // glob import from same crate => we do an initial
855 // import, and then need to propagate any further
858 let scope = if m.block == self.def_map.block_id() {
859 &self.def_map[m.local_id].scope
861 def_map = m.def_map(self.db);
862 &def_map[m.local_id].scope
865 // Module scoped macros is included
868 // only keep visible names...
872 res.filter_visibility(|v| {
873 v.is_visible_from_def_map(
881 .filter(|(_, res)| !res.is_none())
882 .collect::<Vec<_>>();
884 self.update(module_id, &items, vis, ImportType::Glob);
885 // record the glob import in case we add further items
886 let glob = self.glob_imports.entry(m.local_id).or_default();
887 if !glob.iter().any(|(mid, _)| *mid == module_id) {
888 glob.push((module_id, vis));
892 Some(ModuleDefId::AdtId(AdtId::EnumId(e))) => {
893 cov_mark::hit!(glob_enum);
894 // glob import from enum => just import all the variants
896 // XXX: urgh, so this works by accident! Here, we look at
897 // the enum data, and, in theory, this might require us to
898 // look back at the crate_def_map, creating a cycle. For
899 // example, `enum E { crate::some_macro!(); }`. Luckily, the
900 // only kind of macro that is allowed inside enum is a
901 // `cfg_macro`, and we don't need to run name resolution for
902 // it, but this is sheer luck!
903 let enum_data = self.db.enum_data(e);
904 let resolutions = enum_data
907 .map(|(local_id, variant_data)| {
908 let name = variant_data.name.clone();
909 let variant = EnumVariantId { parent: e, local_id };
910 let res = PerNs::both(variant.into(), variant.into(), vis);
913 .collect::<Vec<_>>();
914 self.update(module_id, &resolutions, vis, ImportType::Glob);
917 tracing::debug!("glob import {:?} from non-module/enum {:?}", import, d);
920 tracing::debug!("glob import {:?} didn't resolve as type", import);
929 module_id: LocalModuleId,
930 resolutions: &[(Option<Name>, PerNs)],
932 import_type: ImportType,
934 self.db.unwind_if_cancelled();
935 self.update_recursive(module_id, resolutions, vis, import_type, 0)
940 module_id: LocalModuleId,
941 resolutions: &[(Option<Name>, PerNs)],
942 // All resolutions are imported with this visibility; the visibilities in
943 // the `PerNs` values are ignored and overwritten
945 import_type: ImportType,
948 if GLOB_RECURSION_LIMIT.check(depth).is_err() {
949 // prevent stack overflows (but this shouldn't be possible)
950 panic!("infinite recursion in glob imports!");
952 let mut changed = false;
954 for (name, res) in resolutions {
957 let scope = &mut self.def_map.modules[module_id].scope;
958 changed |= scope.push_res_with_import(
959 &mut self.from_glob_import,
960 (module_id, name.clone()),
961 res.with_visibility(vis),
966 let tr = match res.take_types() {
967 Some(ModuleDefId::TraitId(tr)) => tr,
969 tracing::debug!("non-trait `_` import of {:?}", other);
974 let old_vis = self.def_map.modules[module_id].scope.unnamed_trait_vis(tr);
975 let should_update = match old_vis {
978 let max_vis = old_vis.max(vis, &self.def_map).unwrap_or_else(|| {
979 panic!("`Tr as _` imports with unrelated visibilities {:?} and {:?} (trait {:?})", old_vis, vis, tr);
982 if max_vis == old_vis {
985 cov_mark::hit!(upgrade_underscore_visibility);
993 self.def_map.modules[module_id].scope.push_unnamed_trait(tr, vis);
1002 let glob_imports = self
1006 .flat_map(|v| v.iter())
1007 .filter(|(glob_importing_module, _)| {
1008 // we know all resolutions have the same visibility (`vis`), so we
1009 // just need to check that once
1010 vis.is_visible_from_def_map(self.db, &self.def_map, *glob_importing_module)
1013 .collect::<Vec<_>>();
1015 for (glob_importing_module, glob_import_vis) in glob_imports {
1016 self.update_recursive(
1017 glob_importing_module,
1026 fn resolve_macros(&mut self) -> ReachedFixedPoint {
1027 let mut macros = std::mem::take(&mut self.unresolved_macros);
1028 let mut resolved = Vec::new();
1029 let mut res = ReachedFixedPoint::Yes;
1030 macros.retain(|directive| {
1031 let resolver = |path| {
1032 let resolved_res = self.def_map.resolve_path_fp_with_macro(
1035 directive.module_id,
1037 BuiltinShadowMode::Module,
1039 resolved_res.resolved_def.take_macros()
1042 match &directive.kind {
1043 MacroDirectiveKind::FnLike { ast_id, expand_to } => {
1044 let call_id = macro_call_as_call_id(
1052 if let Ok(Ok(call_id)) = call_id {
1053 resolved.push((directive.module_id, call_id, directive.depth));
1054 res = ReachedFixedPoint::No;
1058 MacroDirectiveKind::Derive { ast_id, derive_attr } => {
1059 let call_id = derive_macro_as_call_id(
1066 if let Ok(call_id) = call_id {
1067 self.def_map.modules[directive.module_id].scope.add_derive_macro_invoc(
1073 resolved.push((directive.module_id, call_id, directive.depth));
1074 res = ReachedFixedPoint::No;
1078 MacroDirectiveKind::Attr { ast_id: file_ast_id, mod_item, attr, tree } => {
1079 let &AstIdWithPath { ast_id, ref path } = file_ast_id;
1080 let file_id = ast_id.file_id;
1082 let mut recollect_without = |collector: &mut Self| {
1083 // Remove the original directive since we resolved it.
1084 let mod_dir = collector.mod_dirs[&directive.module_id].clone();
1085 collector.skip_attrs.insert(InFile::new(file_id, *mod_item), attr.id);
1087 let item_tree = tree.item_tree(self.db);
1089 def_collector: collector,
1090 macro_depth: directive.depth,
1091 module_id: directive.module_id,
1093 item_tree: &item_tree,
1096 .collect(&[*mod_item]);
1097 res = ReachedFixedPoint::No;
1101 if let Some(ident) = path.as_ident() {
1102 if let Some(helpers) = self.derive_helpers_in_scope.get(&ast_id) {
1103 if helpers.contains(ident) {
1104 cov_mark::hit!(resolved_derive_helper);
1105 // Resolved to derive helper. Collect the item's attributes again,
1106 // starting after the derive helper.
1107 return recollect_without(self);
1112 let def = resolver(path.clone()).filter(MacroDefId::is_attribute);
1115 Some(MacroDefId { kind:MacroDefKind::BuiltInAttr(expander, _),.. })
1116 if expander.is_derive()
1118 // Resolved to `#[derive]`
1121 ModItem::Struct(_) | ModItem::Union(_) | ModItem::Enum(_) => (),
1123 let diag = DefDiagnostic::invalid_derive_target(
1124 directive.module_id,
1128 self.def_map.diagnostics.push(diag);
1129 return recollect_without(self);
1133 match attr.parse_derive() {
1134 Some(derive_macros) => {
1135 for path in derive_macros {
1136 let ast_id = AstIdWithPath::new(file_id, ast_id.value, path);
1137 self.unresolved_macros.push(MacroDirective {
1138 module_id: directive.module_id,
1139 depth: directive.depth + 1,
1140 kind: MacroDirectiveKind::Derive {
1142 derive_attr: attr.id,
1148 let diag = DefDiagnostic::malformed_derive(
1149 directive.module_id,
1153 self.def_map.diagnostics.push(diag);
1157 return recollect_without(self);
1160 if !self.db.enable_proc_attr_macros() {
1164 // Not resolved to a derive helper or the derive attribute, so try to resolve as a normal attribute.
1165 match attr_macro_as_call_id(file_ast_id, attr, self.db, self.def_map.krate, def)
1168 let loc: MacroCallLoc = self.db.lookup_intern_macro_call(call_id);
1170 // Skip #[test]/#[bench] expansion, which would merely result in more memory usage
1171 // due to duplicating functions into macro expansions
1174 MacroDefKind::BuiltInAttr(expander, _)
1175 if expander.is_test() || expander.is_bench()
1177 return recollect_without(self);
1180 if let MacroDefKind::ProcMacro(exp, ..) = loc.def.kind {
1182 // Proc macros that cannot be expanded are treated as not
1183 // resolved, in order to fall back later.
1184 self.def_map.diagnostics.push(
1185 DefDiagnostic::unresolved_proc_macro(
1186 directive.module_id,
1191 return recollect_without(self);
1195 self.def_map.modules[directive.module_id]
1197 .add_attr_macro_invoc(ast_id, call_id);
1199 resolved.push((directive.module_id, call_id, directive.depth));
1200 res = ReachedFixedPoint::No;
1203 Err(UnresolvedMacro { .. }) => (),
1210 // Attribute resolution can add unresolved macro invocations, so concatenate the lists.
1211 self.unresolved_macros.extend(macros);
1213 for (module_id, macro_call_id, depth) in resolved {
1214 self.collect_macro_expansion(module_id, macro_call_id, depth);
1220 fn collect_macro_expansion(
1222 module_id: LocalModuleId,
1223 macro_call_id: MacroCallId,
1226 if EXPANSION_DEPTH_LIMIT.check(depth).is_err() {
1227 cov_mark::hit!(macro_expansion_overflow);
1228 tracing::warn!("macro expansion is too deep");
1231 let file_id = macro_call_id.as_file();
1233 // First, fetch the raw expansion result for purposes of error reporting. This goes through
1234 // `macro_expand_error` to avoid depending on the full expansion result (to improve
1236 let loc: MacroCallLoc = self.db.lookup_intern_macro_call(macro_call_id);
1237 let err = self.db.macro_expand_error(macro_call_id);
1238 if let Some(err) = err {
1239 let diag = match err {
1240 hir_expand::ExpandError::UnresolvedProcMacro => {
1241 // Missing proc macros are non-fatal, so they are handled specially.
1242 DefDiagnostic::unresolved_proc_macro(module_id, loc.kind.clone())
1244 _ => DefDiagnostic::macro_error(module_id, loc.kind.clone(), err.to_string()),
1247 self.def_map.diagnostics.push(diag);
1250 // If we've just resolved a derive, record its helper attributes.
1251 if let MacroCallKind::Derive { ast_id, .. } = &loc.kind {
1252 if loc.def.krate != self.def_map.krate {
1253 let def_map = self.db.crate_def_map(loc.def.krate);
1254 if let Some(def) = def_map.exported_proc_macros.get(&loc.def) {
1255 if let ProcMacroKind::CustomDerive { helpers } = &def.kind {
1256 self.derive_helpers_in_scope
1259 .extend(helpers.iter().cloned());
1265 // Then, fetch and process the item tree. This will reuse the expansion result from above.
1266 let item_tree = self.db.file_item_tree(file_id);
1267 let mod_dir = self.mod_dirs[&module_id].clone();
1269 def_collector: &mut *self,
1271 tree_id: TreeId::new(file_id, None),
1273 item_tree: &item_tree,
1276 .collect(item_tree.top_level_items());
1279 fn finish(mut self) -> DefMap {
1280 // Emit diagnostics for all remaining unexpanded macros.
1282 let _p = profile::span("DefCollector::finish");
1284 for directive in &self.unresolved_macros {
1285 match &directive.kind {
1286 MacroDirectiveKind::FnLike { ast_id, expand_to } => {
1287 let macro_call_as_call_id = macro_call_as_call_id(
1293 let resolved_res = self.def_map.resolve_path_fp_with_macro(
1296 directive.module_id,
1298 BuiltinShadowMode::Module,
1300 resolved_res.resolved_def.take_macros()
1304 if let Err(UnresolvedMacro { path }) = macro_call_as_call_id {
1305 self.def_map.diagnostics.push(DefDiagnostic::unresolved_macro_call(
1306 directive.module_id,
1312 MacroDirectiveKind::Derive { .. } | MacroDirectiveKind::Attr { .. } => {
1313 // FIXME: we might want to diagnose this too
1318 // Emit diagnostics for all remaining unresolved imports.
1320 // We'd like to avoid emitting a diagnostics avalanche when some `extern crate` doesn't
1321 // resolve. We first emit diagnostics for unresolved extern crates and collect the missing
1322 // crate names. Then we emit diagnostics for unresolved imports, but only if the import
1323 // doesn't start with an unresolved crate's name. Due to renaming and reexports, this is a
1324 // heuristic, but it works in practice.
1325 let mut diagnosed_extern_crates = FxHashSet::default();
1326 for directive in &self.unresolved_imports {
1327 if let ImportSource::ExternCrate(krate) = directive.import.source {
1328 let item_tree = krate.item_tree(self.db);
1329 let extern_crate = &item_tree[krate.value];
1331 diagnosed_extern_crates.insert(extern_crate.name.clone());
1333 self.def_map.diagnostics.push(DefDiagnostic::unresolved_extern_crate(
1334 directive.module_id,
1335 InFile::new(krate.file_id(), extern_crate.ast_id),
1340 for directive in &self.unresolved_imports {
1341 if let ImportSource::Import { id: import, use_tree } = directive.import.source {
1343 (directive.import.path.segments().first(), &directive.import.path.kind),
1344 (Some(krate), PathKind::Plain | PathKind::Abs) if diagnosed_extern_crates.contains(krate)
1349 self.def_map.diagnostics.push(DefDiagnostic::unresolved_import(
1350 directive.module_id,
1361 /// Walks a single module, populating defs, imports and macros
1362 struct ModCollector<'a, 'b> {
1363 def_collector: &'a mut DefCollector<'b>,
1365 module_id: LocalModuleId,
1367 item_tree: &'a ItemTree,
1371 impl ModCollector<'_, '_> {
1372 fn collect(&mut self, items: &[ModItem]) {
1373 struct DefData<'a> {
1376 visibility: &'a RawVisibility,
1377 has_constructor: bool,
1380 let krate = self.def_collector.def_map.krate;
1382 // Note: don't assert that inserted value is fresh: it's simply not true
1384 self.def_collector.mod_dirs.insert(self.module_id, self.mod_dir.clone());
1386 // Prelude module is always considered to be `#[macro_use]`.
1387 if let Some(prelude_module) = self.def_collector.def_map.prelude {
1388 if prelude_module.krate != krate {
1389 cov_mark::hit!(prelude_is_macro_use);
1390 self.def_collector.import_all_macros_exported(self.module_id, prelude_module.krate);
1394 // This should be processed eagerly instead of deferred to resolving.
1395 // `#[macro_use] extern crate` is hoisted to imports macros before collecting
1397 for &item in items {
1398 let attrs = self.item_tree.attrs(self.def_collector.db, krate, item.into());
1399 if attrs.cfg().map_or(true, |cfg| self.is_cfg_enabled(&cfg)) {
1400 if let ModItem::ExternCrate(id) = item {
1401 let import = &self.item_tree[id];
1402 let attrs = self.item_tree.attrs(
1403 self.def_collector.db,
1405 ModItem::from(id).into(),
1407 if attrs.by_key("macro_use").exists() {
1408 self.def_collector.import_macros_from_extern_crate(self.module_id, import);
1414 for &item in items {
1415 let attrs = self.item_tree.attrs(self.def_collector.db, krate, item.into());
1416 if let Some(cfg) = attrs.cfg() {
1417 if !self.is_cfg_enabled(&cfg) {
1418 self.emit_unconfigured_diagnostic(item, &cfg);
1423 if let Err(()) = self.resolve_attributes(&attrs, item) {
1424 // Do not process the item. It has at least one non-builtin attribute, so the
1425 // fixed-point algorithm is required to resolve the rest of them.
1429 let module = self.def_collector.def_map.module_id(self.module_id);
1433 ModItem::Mod(m) => self.collect_module(&self.item_tree[m], &attrs),
1434 ModItem::Import(import_id) => {
1435 let module_id = self.module_id;
1436 let imports = Import::from_use(
1437 self.def_collector.db,
1440 ItemTreeId::new(self.tree_id, import_id),
1442 self.def_collector.unresolved_imports.extend(imports.into_iter().map(
1443 |import| ImportDirective {
1446 status: PartialResolvedImport::Unresolved,
1450 ModItem::ExternCrate(import_id) => {
1451 self.def_collector.unresolved_imports.push(ImportDirective {
1452 module_id: self.module_id,
1453 import: Import::from_extern_crate(
1454 self.def_collector.db,
1457 ItemTreeId::new(self.tree_id, import_id),
1459 status: PartialResolvedImport::Unresolved,
1462 ModItem::ExternBlock(block) => self.collect(&self.item_tree[block].children),
1463 ModItem::MacroCall(mac) => self.collect_macro_call(&self.item_tree[mac]),
1464 ModItem::MacroRules(id) => self.collect_macro_rules(id),
1465 ModItem::MacroDef(id) => self.collect_macro_def(id),
1466 ModItem::Impl(imp) => {
1467 let module = self.def_collector.def_map.module_id(self.module_id);
1469 ImplLoc { container: module, id: ItemTreeId::new(self.tree_id, imp) }
1470 .intern(self.def_collector.db);
1471 self.def_collector.def_map.modules[self.module_id].scope.define_impl(impl_id)
1473 ModItem::Function(id) => {
1474 let func = &self.item_tree[id];
1476 let ast_id = InFile::new(self.file_id(), func.ast_id);
1477 self.collect_proc_macro_def(&func.name, ast_id, &attrs);
1479 def = Some(DefData {
1481 container: module.into(),
1482 id: ItemTreeId::new(self.tree_id, id),
1484 .intern(self.def_collector.db)
1487 visibility: &self.item_tree[func.visibility],
1488 has_constructor: false,
1491 ModItem::Struct(id) => {
1492 let it = &self.item_tree[id];
1494 def = Some(DefData {
1495 id: StructLoc { container: module, id: ItemTreeId::new(self.tree_id, id) }
1496 .intern(self.def_collector.db)
1499 visibility: &self.item_tree[it.visibility],
1500 has_constructor: !matches!(it.fields, Fields::Record(_)),
1503 ModItem::Union(id) => {
1504 let it = &self.item_tree[id];
1506 def = Some(DefData {
1507 id: UnionLoc { container: module, id: ItemTreeId::new(self.tree_id, id) }
1508 .intern(self.def_collector.db)
1511 visibility: &self.item_tree[it.visibility],
1512 has_constructor: false,
1515 ModItem::Enum(id) => {
1516 let it = &self.item_tree[id];
1518 def = Some(DefData {
1519 id: EnumLoc { container: module, id: ItemTreeId::new(self.tree_id, id) }
1520 .intern(self.def_collector.db)
1523 visibility: &self.item_tree[it.visibility],
1524 has_constructor: false,
1527 ModItem::Const(id) => {
1528 let it = &self.item_tree[id];
1529 let const_id = ConstLoc {
1530 container: module.into(),
1531 id: ItemTreeId::new(self.tree_id, id),
1533 .intern(self.def_collector.db);
1537 def = Some(DefData {
1538 id: const_id.into(),
1540 visibility: &self.item_tree[it.visibility],
1541 has_constructor: false,
1545 // const _: T = ...;
1546 self.def_collector.def_map.modules[self.module_id]
1548 .define_unnamed_const(const_id);
1552 ModItem::Static(id) => {
1553 let it = &self.item_tree[id];
1555 def = Some(DefData {
1556 id: StaticLoc { container: module, id: ItemTreeId::new(self.tree_id, id) }
1557 .intern(self.def_collector.db)
1560 visibility: &self.item_tree[it.visibility],
1561 has_constructor: false,
1564 ModItem::Trait(id) => {
1565 let it = &self.item_tree[id];
1567 def = Some(DefData {
1568 id: TraitLoc { container: module, id: ItemTreeId::new(self.tree_id, id) }
1569 .intern(self.def_collector.db)
1572 visibility: &self.item_tree[it.visibility],
1573 has_constructor: false,
1576 ModItem::TypeAlias(id) => {
1577 let it = &self.item_tree[id];
1579 def = Some(DefData {
1581 container: module.into(),
1582 id: ItemTreeId::new(self.tree_id, id),
1584 .intern(self.def_collector.db)
1587 visibility: &self.item_tree[it.visibility],
1588 has_constructor: false,
1593 if let Some(DefData { id, name, visibility, has_constructor }) = def {
1594 self.def_collector.def_map.modules[self.module_id].scope.declare(id);
1598 .resolve_visibility(self.def_collector.db, self.module_id, visibility)
1599 .unwrap_or(Visibility::Public);
1600 self.def_collector.update(
1602 &[(Some(name.clone()), PerNs::from_def(id, vis, has_constructor))],
1610 fn collect_module(&mut self, module: &Mod, attrs: &Attrs) {
1611 let path_attr = attrs.by_key("path").string_value();
1612 let is_macro_use = attrs.by_key("macro_use").exists();
1613 match &module.kind {
1614 // inline module, just recurse
1615 ModKind::Inline { items } => {
1616 let module_id = self.push_child_module(
1617 module.name.clone(),
1618 AstId::new(self.file_id(), module.ast_id),
1620 &self.item_tree[module.visibility],
1623 if let Some(mod_dir) = self.mod_dir.descend_into_definition(&module.name, path_attr)
1626 def_collector: &mut *self.def_collector,
1627 macro_depth: self.macro_depth,
1629 tree_id: self.tree_id,
1630 item_tree: self.item_tree,
1635 self.import_all_legacy_macros(module_id);
1639 // out of line module, resolve, parse and recurse
1640 ModKind::Outline {} => {
1641 let ast_id = AstId::new(self.tree_id.file_id(), module.ast_id);
1642 let db = self.def_collector.db;
1643 match self.mod_dir.resolve_declaration(db, self.file_id(), &module.name, path_attr)
1645 Ok((file_id, is_mod_rs, mod_dir)) => {
1646 let item_tree = db.file_item_tree(file_id.into());
1647 let is_enabled = item_tree
1648 .top_level_attrs(db, self.def_collector.def_map.krate)
1650 .map_or(true, |cfg| self.is_cfg_enabled(&cfg));
1652 let module_id = self.push_child_module(
1653 module.name.clone(),
1655 Some((file_id, is_mod_rs)),
1656 &self.item_tree[module.visibility],
1659 def_collector: &mut *self.def_collector,
1660 macro_depth: self.macro_depth,
1662 tree_id: TreeId::new(file_id.into(), None),
1663 item_tree: &item_tree,
1666 .collect(item_tree.top_level_items());
1667 let is_macro_use = is_macro_use
1669 .top_level_attrs(db, self.def_collector.def_map.krate)
1670 .by_key("macro_use")
1673 self.import_all_legacy_macros(module_id);
1678 self.def_collector.def_map.diagnostics.push(
1679 DefDiagnostic::unresolved_module(self.module_id, ast_id, candidate),
1687 fn push_child_module(
1690 declaration: AstId<ast::Module>,
1691 definition: Option<(FileId, bool)>,
1692 visibility: &crate::visibility::RawVisibility,
1693 ) -> LocalModuleId {
1697 .resolve_visibility(self.def_collector.db, self.module_id, visibility)
1698 .unwrap_or(Visibility::Public);
1699 let modules = &mut self.def_collector.def_map.modules;
1700 let origin = match definition {
1701 None => ModuleOrigin::Inline { definition: declaration },
1702 Some((definition, is_mod_rs)) => {
1703 ModuleOrigin::File { declaration, definition, is_mod_rs }
1707 let res = modules.alloc(ModuleData::new(origin, vis));
1708 modules[res].parent = Some(self.module_id);
1709 for (name, mac) in modules[self.module_id].scope.collect_legacy_macros() {
1710 modules[res].scope.define_legacy_macro(name, mac)
1712 modules[self.module_id].children.insert(name.clone(), res);
1714 let module = self.def_collector.def_map.module_id(res);
1715 let def = ModuleDefId::from(module);
1717 self.def_collector.def_map.modules[self.module_id].scope.declare(def);
1718 self.def_collector.update(
1720 &[(Some(name), PerNs::from_def(def, vis, false))],
1727 /// Resolves attributes on an item.
1729 /// Returns `Err` when some attributes could not be resolved to builtins and have been
1730 /// registered as unresolved.
1732 /// If `ignore_up_to` is `Some`, attributes preceding and including that attribute will be
1733 /// assumed to be resolved already.
1734 fn resolve_attributes(&mut self, attrs: &Attrs, mod_item: ModItem) -> Result<(), ()> {
1735 let mut ignore_up_to =
1736 self.def_collector.skip_attrs.get(&InFile::new(self.file_id(), mod_item)).copied();
1740 // FIXME: this should not be required, all attributes on an item should have a
1742 // Still, this occurs because `#[cfg_attr]` can "expand" to multiple attributes:
1743 // #[cfg_attr(not(off), unresolved, unresolved)]
1745 // We should come up with a different way to ID attributes.
1748 .skip_while(|attr| match ignore_up_to {
1749 Some(id) if attr.id == id => {
1750 ignore_up_to = None;
1758 if self.is_builtin_or_registered_attr(&attr.path) {
1761 tracing::debug!("non-builtin attribute {}", attr.path);
1763 let ast_id = AstIdWithPath::new(
1765 mod_item.ast_id(self.item_tree),
1766 attr.path.as_ref().clone(),
1768 self.def_collector.unresolved_macros.push(MacroDirective {
1769 module_id: self.module_id,
1770 depth: self.macro_depth + 1,
1771 kind: MacroDirectiveKind::Attr {
1785 fn is_builtin_or_registered_attr(&self, path: &ModPath) -> bool {
1786 if path.kind != PathKind::Plain {
1790 let segments = path.segments();
1792 if let Some(name) = segments.first() {
1793 let name = name.to_smol_str();
1794 let pred = |n: &_| *n == name;
1796 let registered = self.def_collector.registered_tools.iter().map(SmolStr::as_str);
1797 let is_tool = builtin_attr::TOOL_MODULES.iter().copied().chain(registered).any(pred);
1802 if segments.len() == 1 {
1803 let registered = self.def_collector.registered_attrs.iter().map(SmolStr::as_str);
1805 builtin_attr::INERT_ATTRIBUTES.iter().copied().chain(registered).any(pred);
1812 /// If `attrs` registers a procedural macro, collects its definition.
1813 fn collect_proc_macro_def(&mut self, func_name: &Name, ast_id: AstId<ast::Fn>, attrs: &Attrs) {
1814 // FIXME: this should only be done in the root module of `proc-macro` crates, not everywhere
1815 if let Some(proc_macro) = attrs.parse_proc_macro_decl(func_name) {
1816 self.def_collector.export_proc_macro(proc_macro, ast_id);
1820 fn collect_macro_rules(&mut self, id: FileItemTreeId<MacroRules>) {
1821 let krate = self.def_collector.def_map.krate;
1822 let mac = &self.item_tree[id];
1823 let attrs = self.item_tree.attrs(self.def_collector.db, krate, ModItem::from(id).into());
1824 let ast_id = InFile::new(self.file_id(), mac.ast_id.upcast());
1826 let export_attr = attrs.by_key("macro_export");
1828 let is_export = export_attr.exists();
1829 let is_local_inner = if is_export {
1830 export_attr.tt_values().flat_map(|it| &it.token_trees).any(|it| match it {
1831 tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) => {
1832 ident.text.contains("local_inner_macros")
1840 // Case 1: builtin macros
1841 if attrs.by_key("rustc_builtin_macro").exists() {
1842 // `#[rustc_builtin_macro = "builtin_name"]` overrides the `macro_rules!` name.
1844 let name = match attrs.by_key("rustc_builtin_macro").string_value() {
1846 // FIXME: a hacky way to create a Name from string.
1847 name = tt::Ident { text: it.clone(), id: tt::TokenId::unspecified() }.as_name();
1852 attrs.by_key("rustc_builtin_macro").tt_values().next().and_then(|tt| {
1853 match tt.token_trees.first() {
1854 Some(tt::TokenTree::Leaf(tt::Leaf::Ident(name))) => Some(name),
1858 match explicit_name {
1860 name = ident.as_name();
1867 let krate = self.def_collector.def_map.krate;
1868 match find_builtin_macro(name, krate, ast_id) {
1870 self.def_collector.define_macro_rules(
1882 .push(DefDiagnostic::unimplemented_builtin_macro(self.module_id, ast_id));
1887 // Case 2: normal `macro_rules!` macro
1888 let macro_id = MacroDefId {
1889 krate: self.def_collector.def_map.krate,
1890 kind: MacroDefKind::Declarative(ast_id),
1891 local_inner: is_local_inner,
1893 self.def_collector.define_macro_rules(
1901 fn collect_macro_def(&mut self, id: FileItemTreeId<MacroDef>) {
1902 let krate = self.def_collector.def_map.krate;
1903 let mac = &self.item_tree[id];
1904 let ast_id = InFile::new(self.file_id(), mac.ast_id.upcast());
1906 // Case 1: builtin macros
1907 let attrs = self.item_tree.attrs(self.def_collector.db, krate, ModItem::from(id).into());
1908 if attrs.by_key("rustc_builtin_macro").exists() {
1909 let macro_id = find_builtin_macro(&mac.name, krate, ast_id)
1910 .or_else(|| find_builtin_derive(&mac.name, krate, ast_id))
1911 .or_else(|| find_builtin_attr(&mac.name, krate, ast_id));
1915 self.def_collector.define_macro_def(
1919 &self.item_tree[mac.visibility],
1927 .push(DefDiagnostic::unimplemented_builtin_macro(self.module_id, ast_id));
1932 // Case 2: normal `macro`
1933 let macro_id = MacroDefId {
1934 krate: self.def_collector.def_map.krate,
1935 kind: MacroDefKind::Declarative(ast_id),
1939 self.def_collector.define_macro_def(
1943 &self.item_tree[mac.visibility],
1947 fn collect_macro_call(&mut self, mac: &MacroCall) {
1948 let ast_id = AstIdWithPath::new(self.file_id(), mac.ast_id, ModPath::clone(&mac.path));
1950 // Case 1: try to resolve in legacy scope and expand macro_rules
1951 let mut error = None;
1952 match macro_call_as_call_id(
1955 self.def_collector.db,
1956 self.def_collector.def_map.krate,
1958 path.as_ident().and_then(|name| {
1959 self.def_collector.def_map.with_ancestor_maps(
1960 self.def_collector.db,
1962 &mut |map, module| map[module].scope.get_legacy_macro(name),
1967 error.get_or_insert(err);
1970 Ok(Ok(macro_call_id)) => {
1971 // Legacy macros need to be expanded immediately, so that any macros they produce
1973 self.def_collector.collect_macro_expansion(
1976 self.macro_depth + 1,
1979 if let Some(err) = error {
1980 self.def_collector.def_map.diagnostics.push(DefDiagnostic::macro_error(
1982 MacroCallKind::FnLike { ast_id: ast_id.ast_id, expand_to: mac.expand_to },
1990 // Built-in macro failed eager expansion.
1992 self.def_collector.def_map.diagnostics.push(DefDiagnostic::macro_error(
1994 MacroCallKind::FnLike { ast_id: ast_id.ast_id, expand_to: mac.expand_to },
1995 error.unwrap().to_string(),
1999 Err(UnresolvedMacro { .. }) => (),
2002 // Case 2: resolve in module scope, expand during name resolution.
2003 self.def_collector.unresolved_macros.push(MacroDirective {
2004 module_id: self.module_id,
2005 depth: self.macro_depth + 1,
2006 kind: MacroDirectiveKind::FnLike { ast_id, expand_to: mac.expand_to },
2010 fn import_all_legacy_macros(&mut self, module_id: LocalModuleId) {
2011 let macros = self.def_collector.def_map[module_id].scope.collect_legacy_macros();
2012 for (name, macro_) in macros {
2013 self.def_collector.define_legacy_macro(self.module_id, name.clone(), macro_);
2017 fn is_cfg_enabled(&self, cfg: &CfgExpr) -> bool {
2018 self.def_collector.cfg_options.check(cfg) != Some(false)
2021 fn emit_unconfigured_diagnostic(&mut self, item: ModItem, cfg: &CfgExpr) {
2022 let ast_id = item.ast_id(self.item_tree);
2024 let ast_id = InFile::new(self.file_id(), ast_id);
2025 self.def_collector.def_map.diagnostics.push(DefDiagnostic::unconfigured_code(
2029 self.def_collector.cfg_options.clone(),
2033 fn file_id(&self) -> HirFileId {
2034 self.tree_id.file_id()
2040 use crate::{db::DefDatabase, test_db::TestDB};
2041 use base_db::{fixture::WithFixture, SourceDatabase};
2045 fn do_collect_defs(db: &dyn DefDatabase, def_map: DefMap) -> DefMap {
2046 let mut collector = DefCollector {
2049 deps: FxHashMap::default(),
2050 glob_imports: FxHashMap::default(),
2051 unresolved_imports: Vec::new(),
2052 resolved_imports: Vec::new(),
2053 unresolved_macros: Vec::new(),
2054 mod_dirs: FxHashMap::default(),
2055 cfg_options: &CfgOptions::default(),
2056 proc_macros: Default::default(),
2057 exports_proc_macros: false,
2058 from_glob_import: Default::default(),
2059 skip_attrs: Default::default(),
2060 derive_helpers_in_scope: Default::default(),
2061 registered_attrs: Default::default(),
2062 registered_tools: Default::default(),
2064 collector.seed_with_top_level();
2065 collector.collect();
2069 fn do_resolve(not_ra_fixture: &str) -> DefMap {
2070 let (db, file_id) = TestDB::with_single_file(not_ra_fixture);
2071 let krate = db.test_crate();
2073 let edition = db.crate_graph()[krate].edition;
2074 let module_origin = ModuleOrigin::CrateRoot { definition: file_id };
2075 let def_map = DefMap::empty(krate, edition, module_origin);
2076 do_collect_defs(&db, def_map)
2080 fn test_macro_expand_will_stop_1() {
2084 ($($ty:ty)*) => { foo!($($ty)*); }
2092 ($($ty:ty)*) => { foo!(() $($ty)*); }
2101 fn test_macro_expand_will_stop_2() {
2102 // FIXME: this test does succeed, but takes quite a while: 90 seconds in
2103 // the release mode. That's why the argument is not an ra_fixture --
2104 // otherwise injection highlighting gets stuck.
2106 // We need to find a way to fail this faster.
2110 ($($ty:ty)*) => { foo!($($ty)* $($ty)*); }