]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/nameres/collector.rs
Support the new `rustc_builtin_macro` syntax
[rust.git] / crates / hir_def / src / nameres / collector.rs
1 //! The core of the module-level name resolution algorithm.
2 //!
3 //! `DefCollector::collect` contains the fixed-point iteration loop which
4 //! resolves imports and expands macros.
5
6 use std::iter;
7
8 use base_db::{CrateId, Edition, FileId, ProcMacroId};
9 use cfg::{CfgExpr, CfgOptions};
10 use hir_expand::{
11     ast_id_map::FileAstId,
12     builtin_attr::find_builtin_attr,
13     builtin_derive::find_builtin_derive,
14     builtin_macro::find_builtin_macro,
15     name::{name, AsName, Name},
16     proc_macro::ProcMacroExpander,
17     ExpandTo, HirFileId, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind,
18 };
19 use hir_expand::{InFile, MacroCallLoc};
20 use itertools::Itertools;
21 use la_arena::Idx;
22 use limit::Limit;
23 use rustc_hash::{FxHashMap, FxHashSet};
24 use syntax::ast;
25
26 use crate::{
27     attr::{Attr, AttrId, AttrInput, Attrs},
28     attr_macro_as_call_id, builtin_attr,
29     db::DefDatabase,
30     derive_macro_as_call_id,
31     intern::Interned,
32     item_scope::{ImportType, PerNsGlobImports},
33     item_tree::{
34         self, Fields, FileItemTreeId, ImportKind, ItemTree, ItemTreeId, MacroCall, MacroDef,
35         MacroRules, Mod, ModItem, ModKind, TreeId,
36     },
37     macro_call_as_call_id,
38     nameres::{
39         diagnostics::DefDiagnostic,
40         mod_resolution::ModDir,
41         path_resolution::ReachedFixedPoint,
42         proc_macro::{ProcMacroDef, ProcMacroKind},
43         BuiltinShadowMode, DefMap, ModuleData, ModuleOrigin, ResolveMode,
44     },
45     path::{ImportAlias, ModPath, PathKind},
46     per_ns::PerNs,
47     visibility::{RawVisibility, Visibility},
48     AdtId, AstId, AstIdWithPath, ConstLoc, EnumLoc, EnumVariantId, FunctionLoc, ImplLoc, Intern,
49     LocalModuleId, ModuleDefId, StaticLoc, StructLoc, TraitLoc, TypeAliasLoc, UnionLoc,
50     UnresolvedMacro,
51 };
52
53 const GLOB_RECURSION_LIMIT: Limit = Limit::new(100);
54 const EXPANSION_DEPTH_LIMIT: Limit = Limit::new(128);
55 const FIXED_POINT_LIMIT: Limit = Limit::new(8192);
56
57 pub(super) fn collect_defs(
58     db: &dyn DefDatabase,
59     mut def_map: DefMap,
60     block: Option<AstId<ast::BlockExpr>>,
61 ) -> DefMap {
62     let crate_graph = db.crate_graph();
63
64     if block.is_none() {
65         // populate external prelude
66         for dep in &crate_graph[def_map.krate].dependencies {
67             tracing::debug!("crate dep {:?} -> {:?}", dep.name, dep.crate_id);
68             let dep_def_map = db.crate_def_map(dep.crate_id);
69             def_map
70                 .extern_prelude
71                 .insert(dep.as_name(), dep_def_map.module_id(dep_def_map.root).into());
72         }
73     }
74
75     let cfg_options = &crate_graph[def_map.krate].cfg_options;
76     let proc_macros = &crate_graph[def_map.krate].proc_macro;
77     let proc_macros = proc_macros
78         .iter()
79         .enumerate()
80         .map(|(idx, it)| {
81             // FIXME: a hacky way to create a Name from string.
82             let name = tt::Ident { text: it.name.clone(), id: tt::TokenId::unspecified() };
83             (name.as_name(), ProcMacroExpander::new(def_map.krate, ProcMacroId(idx as u32)))
84         })
85         .collect();
86
87     let mut collector = DefCollector {
88         db,
89         def_map,
90         glob_imports: FxHashMap::default(),
91         unresolved_imports: Vec::new(),
92         resolved_imports: Vec::new(),
93
94         unresolved_macros: Vec::new(),
95         mod_dirs: FxHashMap::default(),
96         cfg_options,
97         proc_macros,
98         exports_proc_macros: false,
99         from_glob_import: Default::default(),
100         skip_attrs: Default::default(),
101         derive_helpers_in_scope: Default::default(),
102         registered_attrs: Default::default(),
103         registered_tools: Default::default(),
104     };
105     match block {
106         Some(block) => {
107             collector.seed_with_inner(block);
108         }
109         None => {
110             collector.seed_with_top_level();
111         }
112     }
113     collector.collect();
114     let mut def_map = collector.finish();
115     def_map.shrink_to_fit();
116     def_map
117 }
118
119 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
120 enum PartialResolvedImport {
121     /// None of any namespaces is resolved
122     Unresolved,
123     /// One of namespaces is resolved
124     Indeterminate(PerNs),
125     /// All namespaces are resolved, OR it is came from other crate
126     Resolved(PerNs),
127 }
128
129 impl PartialResolvedImport {
130     fn namespaces(&self) -> PerNs {
131         match self {
132             PartialResolvedImport::Unresolved => PerNs::none(),
133             PartialResolvedImport::Indeterminate(ns) => *ns,
134             PartialResolvedImport::Resolved(ns) => *ns,
135         }
136     }
137 }
138
139 #[derive(Clone, Debug, Eq, PartialEq)]
140 enum ImportSource {
141     Import { id: ItemTreeId<item_tree::Import>, use_tree: Idx<ast::UseTree> },
142     ExternCrate(ItemTreeId<item_tree::ExternCrate>),
143 }
144
145 #[derive(Clone, Debug, Eq, PartialEq)]
146 struct Import {
147     path: Interned<ModPath>,
148     alias: Option<ImportAlias>,
149     visibility: RawVisibility,
150     kind: ImportKind,
151     is_prelude: bool,
152     is_extern_crate: bool,
153     is_macro_use: bool,
154     source: ImportSource,
155 }
156
157 impl Import {
158     fn from_use(
159         db: &dyn DefDatabase,
160         krate: CrateId,
161         tree: &ItemTree,
162         id: ItemTreeId<item_tree::Import>,
163     ) -> Vec<Self> {
164         let it = &tree[id.value];
165         let attrs = &tree.attrs(db, krate, ModItem::from(id.value).into());
166         let visibility = &tree[it.visibility];
167         let is_prelude = attrs.by_key("prelude_import").exists();
168
169         let mut res = Vec::new();
170         it.use_tree.expand(|idx, path, kind, alias| {
171             res.push(Self {
172                 path: Interned::new(path), // FIXME this makes little sense
173                 alias,
174                 visibility: visibility.clone(),
175                 kind,
176                 is_prelude,
177                 is_extern_crate: false,
178                 is_macro_use: false,
179                 source: ImportSource::Import { id, use_tree: idx },
180             });
181         });
182         res
183     }
184
185     fn from_extern_crate(
186         db: &dyn DefDatabase,
187         krate: CrateId,
188         tree: &ItemTree,
189         id: ItemTreeId<item_tree::ExternCrate>,
190     ) -> Self {
191         let it = &tree[id.value];
192         let attrs = &tree.attrs(db, krate, ModItem::from(id.value).into());
193         let visibility = &tree[it.visibility];
194         Self {
195             path: Interned::new(ModPath::from_segments(
196                 PathKind::Plain,
197                 iter::once(it.name.clone()),
198             )),
199             alias: it.alias.clone(),
200             visibility: visibility.clone(),
201             kind: ImportKind::Plain,
202             is_prelude: false,
203             is_extern_crate: true,
204             is_macro_use: attrs.by_key("macro_use").exists(),
205             source: ImportSource::ExternCrate(id),
206         }
207     }
208 }
209
210 #[derive(Clone, Debug, Eq, PartialEq)]
211 struct ImportDirective {
212     module_id: LocalModuleId,
213     import: Import,
214     status: PartialResolvedImport,
215 }
216
217 #[derive(Clone, Debug, Eq, PartialEq)]
218 struct MacroDirective {
219     module_id: LocalModuleId,
220     depth: usize,
221     kind: MacroDirectiveKind,
222 }
223
224 #[derive(Clone, Debug, Eq, PartialEq)]
225 enum MacroDirectiveKind {
226     FnLike { ast_id: AstIdWithPath<ast::MacroCall>, expand_to: ExpandTo },
227     Derive { ast_id: AstIdWithPath<ast::Item>, derive_attr: AttrId },
228     Attr { ast_id: AstIdWithPath<ast::Item>, attr: Attr, mod_item: ModItem },
229 }
230
231 struct DefData<'a> {
232     id: ModuleDefId,
233     name: &'a Name,
234     visibility: &'a RawVisibility,
235     has_constructor: bool,
236 }
237
238 /// Walks the tree of module recursively
239 struct DefCollector<'a> {
240     db: &'a dyn DefDatabase,
241     def_map: DefMap,
242     glob_imports: FxHashMap<LocalModuleId, Vec<(LocalModuleId, Visibility)>>,
243     unresolved_imports: Vec<ImportDirective>,
244     resolved_imports: Vec<ImportDirective>,
245     unresolved_macros: Vec<MacroDirective>,
246     mod_dirs: FxHashMap<LocalModuleId, ModDir>,
247     cfg_options: &'a CfgOptions,
248     /// List of procedural macros defined by this crate. This is read from the dynamic library
249     /// built by the build system, and is the list of proc. macros we can actually expand. It is
250     /// empty when proc. macro support is disabled (in which case we still do name resolution for
251     /// them).
252     proc_macros: Vec<(Name, ProcMacroExpander)>,
253     exports_proc_macros: bool,
254     from_glob_import: PerNsGlobImports,
255     /// If we fail to resolve an attribute on a `ModItem`, we fall back to ignoring the attribute.
256     /// This map is used to skip all attributes up to and including the one that failed to resolve,
257     /// in order to not expand them twice.
258     ///
259     /// This also stores the attributes to skip when we resolve derive helpers and non-macro
260     /// non-builtin attributes in general.
261     skip_attrs: FxHashMap<InFile<ModItem>, AttrId>,
262     /// Tracks which custom derives are in scope for an item, to allow resolution of derive helper
263     /// attributes.
264     derive_helpers_in_scope: FxHashMap<AstId<ast::Item>, Vec<Name>>,
265     /// Custom attributes registered with `#![register_attr]`.
266     registered_attrs: Vec<String>,
267     /// Custom tool modules registered with `#![register_tool]`.
268     registered_tools: Vec<String>,
269 }
270
271 impl DefCollector<'_> {
272     fn seed_with_top_level(&mut self) {
273         let file_id = self.db.crate_graph()[self.def_map.krate].root_file_id;
274         let item_tree = self.db.file_item_tree(file_id.into());
275         let module_id = self.def_map.root;
276
277         let attrs = item_tree.top_level_attrs(self.db, self.def_map.krate);
278         if attrs.cfg().map_or(true, |cfg| self.cfg_options.check(&cfg) != Some(false)) {
279             self.inject_prelude(&attrs);
280
281             // Process other crate-level attributes.
282             for attr in &*attrs {
283                 let attr_name = match attr.path.as_ident() {
284                     Some(name) => name,
285                     None => continue,
286                 };
287
288                 let registered_name = if *attr_name == hir_expand::name![register_attr]
289                     || *attr_name == hir_expand::name![register_tool]
290                 {
291                     match attr.input.as_deref() {
292                         Some(AttrInput::TokenTree(subtree, _)) => match &*subtree.token_trees {
293                             [tt::TokenTree::Leaf(tt::Leaf::Ident(name))] => name.as_name(),
294                             _ => continue,
295                         },
296                         _ => continue,
297                     }
298                 } else {
299                     continue;
300                 };
301
302                 if *attr_name == hir_expand::name![register_attr] {
303                     self.registered_attrs.push(registered_name.to_string());
304                     cov_mark::hit!(register_attr);
305                 } else {
306                     self.registered_tools.push(registered_name.to_string());
307                     cov_mark::hit!(register_tool);
308                 }
309             }
310
311             ModCollector {
312                 def_collector: &mut *self,
313                 macro_depth: 0,
314                 module_id,
315                 tree_id: TreeId::new(file_id.into(), None),
316                 item_tree: &item_tree,
317                 mod_dir: ModDir::root(),
318             }
319             .collect(item_tree.top_level_items());
320         }
321     }
322
323     fn seed_with_inner(&mut self, block: AstId<ast::BlockExpr>) {
324         let item_tree = self.db.file_item_tree(block.file_id);
325         let module_id = self.def_map.root;
326         if item_tree
327             .top_level_attrs(self.db, self.def_map.krate)
328             .cfg()
329             .map_or(true, |cfg| self.cfg_options.check(&cfg) != Some(false))
330         {
331             ModCollector {
332                 def_collector: &mut *self,
333                 macro_depth: 0,
334                 module_id,
335                 // FIXME: populate block once we have per-block ItemTrees
336                 tree_id: TreeId::new(block.file_id, None),
337                 item_tree: &item_tree,
338                 mod_dir: ModDir::root(),
339             }
340             .collect(item_tree.inner_items_of_block(block.value));
341         }
342     }
343
344     fn collect(&mut self) {
345         // main name resolution fixed-point loop.
346         let mut i = 0;
347         'outer: loop {
348             loop {
349                 self.db.unwind_if_cancelled();
350                 loop {
351                     if self.resolve_imports() == ReachedFixedPoint::Yes {
352                         break;
353                     }
354                 }
355                 if self.resolve_macros() == ReachedFixedPoint::Yes {
356                     break;
357                 }
358
359                 i += 1;
360                 if FIXED_POINT_LIMIT.check(i).is_err() {
361                     tracing::error!("name resolution is stuck");
362                     break 'outer;
363                 }
364             }
365
366             if self.reseed_with_unresolved_attribute() == ReachedFixedPoint::Yes {
367                 break;
368             }
369         }
370
371         // Resolve all indeterminate resolved imports again
372         // As some of the macros will expand newly import shadowing partial resolved imports
373         // FIXME: We maybe could skip this, if we handle the indeterminate imports in `resolve_imports`
374         // correctly
375         let partial_resolved = self.resolved_imports.iter().filter_map(|directive| {
376             if let PartialResolvedImport::Indeterminate(_) = directive.status {
377                 let mut directive = directive.clone();
378                 directive.status = PartialResolvedImport::Unresolved;
379                 Some(directive)
380             } else {
381                 None
382             }
383         });
384         self.unresolved_imports.extend(partial_resolved);
385         self.resolve_imports();
386
387         let unresolved_imports = std::mem::take(&mut self.unresolved_imports);
388         // show unresolved imports in completion, etc
389         for directive in &unresolved_imports {
390             self.record_resolved_import(directive)
391         }
392         self.unresolved_imports = unresolved_imports;
393
394         // FIXME: This condition should instead check if this is a `proc-macro` type crate.
395         if self.exports_proc_macros {
396             // A crate exporting procedural macros is not allowed to export anything else.
397             //
398             // Additionally, while the proc macro entry points must be `pub`, they are not publicly
399             // exported in type/value namespace. This function reduces the visibility of all items
400             // in the crate root that aren't proc macros.
401             let root = self.def_map.root;
402             let module_id = self.def_map.module_id(root);
403             let root = &mut self.def_map.modules[root];
404             root.scope.censor_non_proc_macros(module_id);
405         }
406     }
407
408     /// When the fixed-point loop reaches a stable state, we might still have some unresolved
409     /// attributes (or unexpanded attribute proc macros) left over. This takes one of them, and
410     /// feeds the item it's applied to back into name resolution.
411     ///
412     /// This effectively ignores the fact that the macro is there and just treats the items as
413     /// normal code.
414     ///
415     /// This improves UX when proc macros are turned off or don't work, and replicates the behavior
416     /// before we supported proc. attribute macros.
417     fn reseed_with_unresolved_attribute(&mut self) -> ReachedFixedPoint {
418         cov_mark::hit!(unresolved_attribute_fallback);
419
420         let mut unresolved_macros = std::mem::take(&mut self.unresolved_macros);
421         let pos = unresolved_macros.iter().position(|directive| {
422             if let MacroDirectiveKind::Attr { ast_id, mod_item, attr } = &directive.kind {
423                 self.skip_attrs.insert(ast_id.ast_id.with_value(*mod_item), attr.id);
424
425                 let file_id = ast_id.ast_id.file_id;
426                 let item_tree = self.db.file_item_tree(file_id);
427                 let mod_dir = self.mod_dirs[&directive.module_id].clone();
428                 ModCollector {
429                     def_collector: &mut *self,
430                     macro_depth: directive.depth,
431                     module_id: directive.module_id,
432                     tree_id: TreeId::new(file_id, None),
433                     item_tree: &item_tree,
434                     mod_dir,
435                 }
436                 .collect(&[*mod_item]);
437                 true
438             } else {
439                 false
440             }
441         });
442
443         if let Some(pos) = pos {
444             unresolved_macros.remove(pos);
445         }
446
447         // The collection above might add new unresolved macros (eg. derives), so merge the lists.
448         self.unresolved_macros.extend(unresolved_macros);
449
450         if pos.is_some() {
451             // Continue name resolution with the new data.
452             ReachedFixedPoint::No
453         } else {
454             ReachedFixedPoint::Yes
455         }
456     }
457
458     fn inject_prelude(&mut self, crate_attrs: &Attrs) {
459         // See compiler/rustc_builtin_macros/src/standard_library_imports.rs
460
461         if crate_attrs.by_key("no_core").exists() {
462             // libcore does not get a prelude.
463             return;
464         }
465
466         let krate = if crate_attrs.by_key("no_std").exists() {
467             name![core]
468         } else {
469             let std = name![std];
470             if self.def_map.extern_prelude().any(|(name, _)| *name == std) {
471                 std
472             } else {
473                 // If `std` does not exist for some reason, fall back to core. This mostly helps
474                 // keep r-a's own tests minimal.
475                 name![core]
476             }
477         };
478
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],
483         };
484
485         let path_kind = if self.def_map.edition == Edition::Edition2015 {
486             PathKind::Plain
487         } else {
488             PathKind::Abs
489         };
490         let path = ModPath::from_segments(
491             path_kind.clone(),
492             [krate.clone(), name![prelude], edition].iter().cloned(),
493         );
494         // Fall back to the older `std::prelude::v1` for compatibility with Rust <1.52.0
495         // FIXME remove this fallback
496         let fallback_path =
497             ModPath::from_segments(path_kind, [krate, name![prelude], name![v1]].iter().cloned());
498
499         for path in &[path, fallback_path] {
500             let (per_ns, _) = self.def_map.resolve_path(
501                 self.db,
502                 self.def_map.root,
503                 path,
504                 BuiltinShadowMode::Other,
505             );
506
507             match &per_ns.types {
508                 Some((ModuleDefId::ModuleId(m), _)) => {
509                     self.def_map.prelude = Some(*m);
510                     return;
511                 }
512                 _ => {
513                     tracing::debug!(
514                         "could not resolve prelude path `{}` to module (resolved to {:?})",
515                         path,
516                         per_ns.types
517                     );
518                 }
519             }
520         }
521     }
522
523     /// Adds a definition of procedural macro `name` to the root module.
524     ///
525     /// # Notes on procedural macro resolution
526     ///
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.
529     ///
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.
533     ///
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),
546                 local_inner: false,
547             },
548             None => MacroDefId {
549                 krate: self.def_map.krate,
550                 kind: MacroDefKind::ProcMacro(
551                     ProcMacroExpander::dummy(self.def_map.krate),
552                     kind,
553                     ast_id,
554                 ),
555                 local_inner: false,
556             },
557         };
558
559         self.define_proc_macro(def.name.clone(), macro_def);
560         self.def_map.exported_proc_macros.insert(macro_def, def);
561     }
562
563     /// Define a macro with `macro_rules`.
564     ///
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.
568     ///
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;
574     /// ```
575     ///
576     /// ```rust,compile_fail
577     /// macro_rules! foo { () => {} }
578     /// self::foo!();
579     /// crate::foo!();
580     /// ```
581     ///
582     /// Well, this code compiles, because the plain path `foo` in `use` is searched
583     /// in the legacy textual scope only.
584     /// ```rust
585     /// macro_rules! foo { () => {} }
586     /// use foo as bar;
587     /// ```
588     fn define_macro_rules(
589         &mut self,
590         module_id: LocalModuleId,
591         name: Name,
592         macro_: MacroDefId,
593         export: bool,
594     ) {
595         // Textual scoping
596         self.define_legacy_macro(module_id, name.clone(), macro_);
597
598         // Module scoping
599         // In Rust, `#[macro_export]` macros are unconditionally visible at the
600         // crate root, even if the parent modules is **not** visible.
601         if export {
602             self.update(
603                 self.def_map.root,
604                 &[(Some(name), PerNs::macros(macro_, Visibility::Public))],
605                 Visibility::Public,
606                 ImportType::Named,
607             );
608         }
609     }
610
611     /// Define a legacy textual scoped macro in module
612     ///
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) {
619         // Always shadowing
620         self.def_map.modules[module_id].scope.define_legacy_macro(name, mac);
621     }
622
623     /// Define a macro 2.0 macro
624     ///
625     /// The scoped of macro 2.0 macro is equal to normal function
626     fn define_macro_def(
627         &mut self,
628         module_id: LocalModuleId,
629         name: Name,
630         macro_: MacroDefId,
631         vis: &RawVisibility,
632     ) {
633         let vis =
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);
636     }
637
638     /// Define a proc macro
639     ///
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) {
643         self.update(
644             self.def_map.root,
645             &[(Some(name), PerNs::macros(macro_, Visibility::Public))],
646             Visibility::Public,
647             ImportType::Named,
648         );
649     }
650
651     /// Import macros from `#[macro_use] extern crate`.
652     fn import_macros_from_extern_crate(
653         &mut self,
654         current_module_id: LocalModuleId,
655         extern_crate: &item_tree::ExternCrate,
656     ) {
657         tracing::debug!(
658             "importing macros from extern crate: {:?} ({:?})",
659             extern_crate,
660             self.def_map.edition,
661         );
662
663         let res = self.def_map.resolve_name_in_extern_prelude(self.db, &extern_crate.name);
664
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);
668                 return;
669             }
670
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);
673         }
674     }
675
676     /// Import all exported macros from another crate
677     ///
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);
686         }
687     }
688
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
694             .into_iter()
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;
704                         None
705                     }
706                     PartialResolvedImport::Resolved(_) => {
707                         self.record_resolved_import(&directive);
708                         self.resolved_imports.push(directive);
709                         res = ReachedFixedPoint::No;
710                         None
711                     }
712                     PartialResolvedImport::Unresolved => Some(directive),
713                 }
714             })
715             .collect();
716         self.unresolved_imports = imports;
717         res
718     }
719
720     fn resolve_import(&self, module_id: LocalModuleId, import: &Import) -> PartialResolvedImport {
721         tracing::debug!("resolving import: {:?} ({:?})", import, self.def_map.edition);
722         if import.is_extern_crate {
723             let res = self.def_map.resolve_name_in_extern_prelude(
724                 self.db,
725                 import
726                     .path
727                     .as_ident()
728                     .expect("extern crate should have been desugared to one-element path"),
729             );
730             if res.is_none() {
731                 PartialResolvedImport::Unresolved
732             } else {
733                 PartialResolvedImport::Resolved(res)
734             }
735         } else {
736             let res = self.def_map.resolve_path_fp_with_macro(
737                 self.db,
738                 ResolveMode::Import,
739                 module_id,
740                 &import.path,
741                 BuiltinShadowMode::Module,
742             );
743
744             let def = res.resolved_def;
745             if res.reached_fixedpoint == ReachedFixedPoint::No || def.is_none() {
746                 return PartialResolvedImport::Unresolved;
747             }
748
749             if let Some(krate) = res.krate {
750                 if krate != self.def_map.krate {
751                     return PartialResolvedImport::Resolved(
752                         def.filter_visibility(|v| matches!(v, Visibility::Public)),
753                     );
754                 }
755             }
756
757             // Check whether all namespace is resolved
758             if def.take_types().is_some()
759                 && def.take_values().is_some()
760                 && def.take_macros().is_some()
761             {
762                 PartialResolvedImport::Resolved(def)
763             } else {
764                 PartialResolvedImport::Indeterminate(def)
765             }
766         }
767     }
768
769     fn record_resolved_import(&mut self, directive: &ImportDirective) {
770         let module_id = directive.module_id;
771         let import = &directive.import;
772         let mut def = directive.status.namespaces();
773         let vis = self
774             .def_map
775             .resolve_visibility(self.db, module_id, &directive.import.visibility)
776             .unwrap_or(Visibility::Public);
777
778         match import.kind {
779             ImportKind::Plain | ImportKind::TypeOnly => {
780                 let name = match &import.alias {
781                     Some(ImportAlias::Alias(name)) => Some(name.clone()),
782                     Some(ImportAlias::Underscore) => None,
783                     None => match import.path.segments().last() {
784                         Some(last_segment) => Some(last_segment.clone()),
785                         None => {
786                             cov_mark::hit!(bogus_paths);
787                             return;
788                         }
789                     },
790                 };
791
792                 if import.kind == ImportKind::TypeOnly {
793                     def.values = None;
794                     def.macros = None;
795                 }
796
797                 tracing::debug!("resolved import {:?} ({:?}) to {:?}", name, import, def);
798
799                 // extern crates in the crate root are special-cased to insert entries into the extern prelude: rust-lang/rust#54658
800                 if import.is_extern_crate && module_id == self.def_map.root {
801                     if let (Some(def), Some(name)) = (def.take_types(), name.as_ref()) {
802                         self.def_map.extern_prelude.insert(name.clone(), def);
803                     }
804                 }
805
806                 self.update(module_id, &[(name, def)], vis, ImportType::Named);
807             }
808             ImportKind::Glob => {
809                 tracing::debug!("glob import: {:?}", import);
810                 match def.take_types() {
811                     Some(ModuleDefId::ModuleId(m)) => {
812                         if import.is_prelude {
813                             // Note: This dodgily overrides the injected prelude. The rustc
814                             // implementation seems to work the same though.
815                             cov_mark::hit!(std_prelude);
816                             self.def_map.prelude = Some(m);
817                         } else if m.krate != self.def_map.krate {
818                             cov_mark::hit!(glob_across_crates);
819                             // glob import from other crate => we can just import everything once
820                             let item_map = m.def_map(self.db);
821                             let scope = &item_map[m.local_id].scope;
822
823                             // Module scoped macros is included
824                             let items = scope
825                                 .resolutions()
826                                 // only keep visible names...
827                                 .map(|(n, res)| {
828                                     (n, res.filter_visibility(|v| v.is_visible_from_other_crate()))
829                                 })
830                                 .filter(|(_, res)| !res.is_none())
831                                 .collect::<Vec<_>>();
832
833                             self.update(module_id, &items, vis, ImportType::Glob);
834                         } else {
835                             // glob import from same crate => we do an initial
836                             // import, and then need to propagate any further
837                             // additions
838                             let def_map;
839                             let scope = if m.block == self.def_map.block_id() {
840                                 &self.def_map[m.local_id].scope
841                             } else {
842                                 def_map = m.def_map(self.db);
843                                 &def_map[m.local_id].scope
844                             };
845
846                             // Module scoped macros is included
847                             let items = scope
848                                 .resolutions()
849                                 // only keep visible names...
850                                 .map(|(n, res)| {
851                                     (
852                                         n,
853                                         res.filter_visibility(|v| {
854                                             v.is_visible_from_def_map(
855                                                 self.db,
856                                                 &self.def_map,
857                                                 module_id,
858                                             )
859                                         }),
860                                     )
861                                 })
862                                 .filter(|(_, res)| !res.is_none())
863                                 .collect::<Vec<_>>();
864
865                             self.update(module_id, &items, vis, ImportType::Glob);
866                             // record the glob import in case we add further items
867                             let glob = self.glob_imports.entry(m.local_id).or_default();
868                             if !glob.iter().any(|(mid, _)| *mid == module_id) {
869                                 glob.push((module_id, vis));
870                             }
871                         }
872                     }
873                     Some(ModuleDefId::AdtId(AdtId::EnumId(e))) => {
874                         cov_mark::hit!(glob_enum);
875                         // glob import from enum => just import all the variants
876
877                         // XXX: urgh, so this works by accident! Here, we look at
878                         // the enum data, and, in theory, this might require us to
879                         // look back at the crate_def_map, creating a cycle. For
880                         // example, `enum E { crate::some_macro!(); }`. Luckily, the
881                         // only kind of macro that is allowed inside enum is a
882                         // `cfg_macro`, and we don't need to run name resolution for
883                         // it, but this is sheer luck!
884                         let enum_data = self.db.enum_data(e);
885                         let resolutions = enum_data
886                             .variants
887                             .iter()
888                             .map(|(local_id, variant_data)| {
889                                 let name = variant_data.name.clone();
890                                 let variant = EnumVariantId { parent: e, local_id };
891                                 let res = PerNs::both(variant.into(), variant.into(), vis);
892                                 (Some(name), res)
893                             })
894                             .collect::<Vec<_>>();
895                         self.update(module_id, &resolutions, vis, ImportType::Glob);
896                     }
897                     Some(d) => {
898                         tracing::debug!("glob import {:?} from non-module/enum {:?}", import, d);
899                     }
900                     None => {
901                         tracing::debug!("glob import {:?} didn't resolve as type", import);
902                     }
903                 }
904             }
905         }
906     }
907
908     fn update(
909         &mut self,
910         module_id: LocalModuleId,
911         resolutions: &[(Option<Name>, PerNs)],
912         vis: Visibility,
913         import_type: ImportType,
914     ) {
915         self.db.unwind_if_cancelled();
916         self.update_recursive(module_id, resolutions, vis, import_type, 0)
917     }
918
919     fn update_recursive(
920         &mut self,
921         module_id: LocalModuleId,
922         resolutions: &[(Option<Name>, PerNs)],
923         // All resolutions are imported with this visibility; the visibilities in
924         // the `PerNs` values are ignored and overwritten
925         vis: Visibility,
926         import_type: ImportType,
927         depth: usize,
928     ) {
929         if GLOB_RECURSION_LIMIT.check(depth).is_err() {
930             // prevent stack overflows (but this shouldn't be possible)
931             panic!("infinite recursion in glob imports!");
932         }
933         let mut changed = false;
934
935         for (name, res) in resolutions {
936             match name {
937                 Some(name) => {
938                     let scope = &mut self.def_map.modules[module_id].scope;
939                     changed |= scope.push_res_with_import(
940                         &mut self.from_glob_import,
941                         (module_id, name.clone()),
942                         res.with_visibility(vis),
943                         import_type,
944                     );
945                 }
946                 None => {
947                     let tr = match res.take_types() {
948                         Some(ModuleDefId::TraitId(tr)) => tr,
949                         Some(other) => {
950                             tracing::debug!("non-trait `_` import of {:?}", other);
951                             continue;
952                         }
953                         None => continue,
954                     };
955                     let old_vis = self.def_map.modules[module_id].scope.unnamed_trait_vis(tr);
956                     let should_update = match old_vis {
957                         None => true,
958                         Some(old_vis) => {
959                             let max_vis = old_vis.max(vis, &self.def_map).unwrap_or_else(|| {
960                                 panic!("`Tr as _` imports with unrelated visibilities {:?} and {:?} (trait {:?})", old_vis, vis, tr);
961                             });
962
963                             if max_vis == old_vis {
964                                 false
965                             } else {
966                                 cov_mark::hit!(upgrade_underscore_visibility);
967                                 true
968                             }
969                         }
970                     };
971
972                     if should_update {
973                         changed = true;
974                         self.def_map.modules[module_id].scope.push_unnamed_trait(tr, vis);
975                     }
976                 }
977             }
978         }
979
980         if !changed {
981             return;
982         }
983         let glob_imports = self
984             .glob_imports
985             .get(&module_id)
986             .into_iter()
987             .flat_map(|v| v.iter())
988             .filter(|(glob_importing_module, _)| {
989                 // we know all resolutions have the same visibility (`vis`), so we
990                 // just need to check that once
991                 vis.is_visible_from_def_map(self.db, &self.def_map, *glob_importing_module)
992             })
993             .cloned()
994             .collect::<Vec<_>>();
995
996         for (glob_importing_module, glob_import_vis) in glob_imports {
997             self.update_recursive(
998                 glob_importing_module,
999                 resolutions,
1000                 glob_import_vis,
1001                 ImportType::Glob,
1002                 depth + 1,
1003             );
1004         }
1005     }
1006
1007     fn resolve_macros(&mut self) -> ReachedFixedPoint {
1008         let mut macros = std::mem::take(&mut self.unresolved_macros);
1009         let mut resolved = Vec::new();
1010         let mut res = ReachedFixedPoint::Yes;
1011         macros.retain(|directive| {
1012             let resolver = |path| {
1013                 let resolved_res = self.def_map.resolve_path_fp_with_macro(
1014                     self.db,
1015                     ResolveMode::Other,
1016                     directive.module_id,
1017                     &path,
1018                     BuiltinShadowMode::Module,
1019                 );
1020                 resolved_res.resolved_def.take_macros()
1021             };
1022
1023             match &directive.kind {
1024                 MacroDirectiveKind::FnLike { ast_id, expand_to } => {
1025                     match macro_call_as_call_id(
1026                         ast_id,
1027                         *expand_to,
1028                         self.db,
1029                         self.def_map.krate,
1030                         &resolver,
1031                         &mut |_err| (),
1032                     ) {
1033                         Ok(Ok(call_id)) => {
1034                             resolved.push((directive.module_id, call_id, directive.depth));
1035                             res = ReachedFixedPoint::No;
1036                             return false;
1037                         }
1038                         Err(UnresolvedMacro { .. }) | Ok(Err(_)) => {}
1039                     }
1040                 }
1041                 MacroDirectiveKind::Derive { ast_id, derive_attr } => {
1042                     match derive_macro_as_call_id(
1043                         ast_id,
1044                         *derive_attr,
1045                         self.db,
1046                         self.def_map.krate,
1047                         &resolver,
1048                     ) {
1049                         Ok(call_id) => {
1050                             self.def_map.modules[directive.module_id].scope.add_derive_macro_invoc(
1051                                 ast_id.ast_id,
1052                                 call_id,
1053                                 *derive_attr,
1054                             );
1055
1056                             resolved.push((directive.module_id, call_id, directive.depth));
1057                             res = ReachedFixedPoint::No;
1058                             return false;
1059                         }
1060                         Err(UnresolvedMacro { .. }) => (),
1061                     }
1062                 }
1063                 MacroDirectiveKind::Attr { ast_id, mod_item, attr } => {
1064                     if let Some(ident) = ast_id.path.as_ident() {
1065                         if let Some(helpers) = self.derive_helpers_in_scope.get(&ast_id.ast_id) {
1066                             if helpers.contains(ident) {
1067                                 cov_mark::hit!(resolved_derive_helper);
1068
1069                                 // Resolved to derive helper. Collect the item's attributes again,
1070                                 // starting after the derive helper.
1071                                 let file_id = ast_id.ast_id.file_id;
1072                                 let item_tree = self.db.file_item_tree(file_id);
1073                                 let mod_dir = self.mod_dirs[&directive.module_id].clone();
1074                                 self.skip_attrs.insert(InFile::new(file_id, *mod_item), attr.id);
1075                                 ModCollector {
1076                                     def_collector: &mut *self,
1077                                     macro_depth: directive.depth,
1078                                     module_id: directive.module_id,
1079                                     tree_id: TreeId::new(file_id, None),
1080                                     item_tree: &item_tree,
1081                                     mod_dir,
1082                                 }
1083                                 .collect(&[*mod_item]);
1084
1085                                 // Remove the original directive since we resolved it.
1086                                 res = ReachedFixedPoint::No;
1087                                 return false;
1088                             }
1089                         }
1090                     }
1091
1092                     if !self.db.enable_proc_attr_macros() {
1093                         return true;
1094                     }
1095
1096                     // Not resolved to a derive helper, so try to resolve as a macro.
1097                     match attr_macro_as_call_id(
1098                         ast_id,
1099                         attr,
1100                         self.db,
1101                         self.def_map.krate,
1102                         &resolver,
1103                     ) {
1104                         Ok(call_id) => {
1105                             let loc: MacroCallLoc = self.db.lookup_intern_macro(call_id);
1106                             if let MacroDefKind::ProcMacro(exp, ..) = &loc.def.kind {
1107                                 if exp.is_dummy() {
1108                                     // Proc macros that cannot be expanded are treated as not
1109                                     // resolved, in order to fall back later.
1110                                     self.def_map.diagnostics.push(
1111                                         DefDiagnostic::unresolved_proc_macro(
1112                                             directive.module_id,
1113                                             loc.kind,
1114                                         ),
1115                                     );
1116
1117                                     let file_id = ast_id.ast_id.file_id;
1118                                     let item_tree = self.db.file_item_tree(file_id);
1119                                     let mod_dir = self.mod_dirs[&directive.module_id].clone();
1120                                     self.skip_attrs
1121                                         .insert(InFile::new(file_id, *mod_item), attr.id);
1122                                     ModCollector {
1123                                         def_collector: &mut *self,
1124                                         macro_depth: directive.depth,
1125                                         module_id: directive.module_id,
1126                                         tree_id: TreeId::new(file_id, None),
1127                                         item_tree: &item_tree,
1128                                         mod_dir,
1129                                     }
1130                                     .collect(&[*mod_item]);
1131
1132                                     // Remove the macro directive.
1133                                     return false;
1134                                 }
1135                             }
1136
1137                             self.def_map.modules[directive.module_id]
1138                                 .scope
1139                                 .add_attr_macro_invoc(ast_id.ast_id, call_id);
1140
1141                             resolved.push((directive.module_id, call_id, directive.depth));
1142                             res = ReachedFixedPoint::No;
1143                             return false;
1144                         }
1145                         Err(UnresolvedMacro { .. }) => (),
1146                     }
1147                 }
1148             }
1149
1150             true
1151         });
1152         // Attribute resolution can add unresolved macro invocations, so concatenate the lists.
1153         self.unresolved_macros.extend(macros);
1154
1155         for (module_id, macro_call_id, depth) in resolved {
1156             self.collect_macro_expansion(module_id, macro_call_id, depth);
1157         }
1158
1159         res
1160     }
1161
1162     fn collect_macro_expansion(
1163         &mut self,
1164         module_id: LocalModuleId,
1165         macro_call_id: MacroCallId,
1166         depth: usize,
1167     ) {
1168         if EXPANSION_DEPTH_LIMIT.check(depth).is_err() {
1169             cov_mark::hit!(macro_expansion_overflow);
1170             tracing::warn!("macro expansion is too deep");
1171             return;
1172         }
1173         let file_id = macro_call_id.as_file();
1174
1175         // First, fetch the raw expansion result for purposes of error reporting. This goes through
1176         // `macro_expand_error` to avoid depending on the full expansion result (to improve
1177         // incrementality).
1178         let loc: MacroCallLoc = self.db.lookup_intern_macro(macro_call_id);
1179         let err = self.db.macro_expand_error(macro_call_id);
1180         if let Some(err) = err {
1181             let diag = match err {
1182                 hir_expand::ExpandError::UnresolvedProcMacro => {
1183                     // Missing proc macros are non-fatal, so they are handled specially.
1184                     DefDiagnostic::unresolved_proc_macro(module_id, loc.kind.clone())
1185                 }
1186                 _ => DefDiagnostic::macro_error(module_id, loc.kind.clone(), err.to_string()),
1187             };
1188
1189             self.def_map.diagnostics.push(diag);
1190         }
1191
1192         // If we've just resolved a derive, record its helper attributes.
1193         if let MacroCallKind::Derive { ast_id, .. } = &loc.kind {
1194             if loc.def.krate != self.def_map.krate {
1195                 let def_map = self.db.crate_def_map(loc.def.krate);
1196                 if let Some(def) = def_map.exported_proc_macros.get(&loc.def) {
1197                     if let ProcMacroKind::CustomDerive { helpers } = &def.kind {
1198                         self.derive_helpers_in_scope
1199                             .entry(*ast_id)
1200                             .or_default()
1201                             .extend(helpers.iter().cloned());
1202                     }
1203                 }
1204             }
1205         }
1206
1207         // Then, fetch and process the item tree. This will reuse the expansion result from above.
1208         let item_tree = self.db.file_item_tree(file_id);
1209         let mod_dir = self.mod_dirs[&module_id].clone();
1210         ModCollector {
1211             def_collector: &mut *self,
1212             macro_depth: depth,
1213             tree_id: TreeId::new(file_id, None),
1214             module_id,
1215             item_tree: &item_tree,
1216             mod_dir,
1217         }
1218         .collect(item_tree.top_level_items());
1219     }
1220
1221     fn finish(mut self) -> DefMap {
1222         // Emit diagnostics for all remaining unexpanded macros.
1223
1224         for directive in &self.unresolved_macros {
1225             match &directive.kind {
1226                 MacroDirectiveKind::FnLike { ast_id, expand_to } => {
1227                     match macro_call_as_call_id(
1228                         ast_id,
1229                         *expand_to,
1230                         self.db,
1231                         self.def_map.krate,
1232                         |path| {
1233                             let resolved_res = self.def_map.resolve_path_fp_with_macro(
1234                                 self.db,
1235                                 ResolveMode::Other,
1236                                 directive.module_id,
1237                                 &path,
1238                                 BuiltinShadowMode::Module,
1239                             );
1240                             resolved_res.resolved_def.take_macros()
1241                         },
1242                         &mut |_| (),
1243                     ) {
1244                         Ok(_) => (),
1245                         Err(UnresolvedMacro { path }) => {
1246                             self.def_map.diagnostics.push(DefDiagnostic::unresolved_macro_call(
1247                                 directive.module_id,
1248                                 ast_id.ast_id,
1249                                 path,
1250                             ));
1251                         }
1252                     }
1253                 }
1254                 MacroDirectiveKind::Derive { .. } | MacroDirectiveKind::Attr { .. } => {
1255                     // FIXME: we might want to diagnose this too
1256                 }
1257             }
1258         }
1259
1260         // Emit diagnostics for all remaining unresolved imports.
1261
1262         // We'd like to avoid emitting a diagnostics avalanche when some `extern crate` doesn't
1263         // resolve. We first emit diagnostics for unresolved extern crates and collect the missing
1264         // crate names. Then we emit diagnostics for unresolved imports, but only if the import
1265         // doesn't start with an unresolved crate's name. Due to renaming and reexports, this is a
1266         // heuristic, but it works in practice.
1267         let mut diagnosed_extern_crates = FxHashSet::default();
1268         for directive in &self.unresolved_imports {
1269             if let ImportSource::ExternCrate(krate) = directive.import.source {
1270                 let item_tree = krate.item_tree(self.db);
1271                 let extern_crate = &item_tree[krate.value];
1272
1273                 diagnosed_extern_crates.insert(extern_crate.name.clone());
1274
1275                 self.def_map.diagnostics.push(DefDiagnostic::unresolved_extern_crate(
1276                     directive.module_id,
1277                     InFile::new(krate.file_id(), extern_crate.ast_id),
1278                 ));
1279             }
1280         }
1281
1282         for directive in &self.unresolved_imports {
1283             if let ImportSource::Import { id: import, use_tree } = &directive.import.source {
1284                 if let (Some(krate), PathKind::Plain | PathKind::Abs) =
1285                     (directive.import.path.segments().first(), &directive.import.path.kind)
1286                 {
1287                     if diagnosed_extern_crates.contains(krate) {
1288                         continue;
1289                     }
1290                 }
1291
1292                 self.def_map.diagnostics.push(DefDiagnostic::unresolved_import(
1293                     directive.module_id,
1294                     *import,
1295                     *use_tree,
1296                 ));
1297             }
1298         }
1299
1300         self.def_map
1301     }
1302 }
1303
1304 /// Walks a single module, populating defs, imports and macros
1305 struct ModCollector<'a, 'b> {
1306     def_collector: &'a mut DefCollector<'b>,
1307     macro_depth: usize,
1308     module_id: LocalModuleId,
1309     tree_id: TreeId,
1310     item_tree: &'a ItemTree,
1311     mod_dir: ModDir,
1312 }
1313
1314 impl ModCollector<'_, '_> {
1315     fn collect(&mut self, items: &[ModItem]) {
1316         let krate = self.def_collector.def_map.krate;
1317
1318         // Note: don't assert that inserted value is fresh: it's simply not true
1319         // for macros.
1320         self.def_collector.mod_dirs.insert(self.module_id, self.mod_dir.clone());
1321
1322         // Prelude module is always considered to be `#[macro_use]`.
1323         if let Some(prelude_module) = self.def_collector.def_map.prelude {
1324             if prelude_module.krate != krate {
1325                 cov_mark::hit!(prelude_is_macro_use);
1326                 self.def_collector.import_all_macros_exported(self.module_id, prelude_module.krate);
1327             }
1328         }
1329
1330         // This should be processed eagerly instead of deferred to resolving.
1331         // `#[macro_use] extern crate` is hoisted to imports macros before collecting
1332         // any other items.
1333         for item in items {
1334             let attrs = self.item_tree.attrs(self.def_collector.db, krate, (*item).into());
1335             if attrs.cfg().map_or(true, |cfg| self.is_cfg_enabled(&cfg)) {
1336                 if let ModItem::ExternCrate(id) = item {
1337                     let import = self.item_tree[*id].clone();
1338                     let attrs = self.item_tree.attrs(
1339                         self.def_collector.db,
1340                         krate,
1341                         ModItem::from(*id).into(),
1342                     );
1343                     if attrs.by_key("macro_use").exists() {
1344                         self.def_collector.import_macros_from_extern_crate(self.module_id, &import);
1345                     }
1346                 }
1347             }
1348         }
1349
1350         for &item in items {
1351             let attrs = self.item_tree.attrs(self.def_collector.db, krate, item.into());
1352             if let Some(cfg) = attrs.cfg() {
1353                 if !self.is_cfg_enabled(&cfg) {
1354                     self.emit_unconfigured_diagnostic(item, &cfg);
1355                     continue;
1356                 }
1357             }
1358
1359             if let Err(()) = self.resolve_attributes(&attrs, item) {
1360                 // Do not process the item. It has at least one non-builtin attribute, so the
1361                 // fixed-point algorithm is required to resolve the rest of them.
1362                 continue;
1363             }
1364
1365             let module = self.def_collector.def_map.module_id(self.module_id);
1366
1367             let mut def = None;
1368             match item {
1369                 ModItem::Mod(m) => self.collect_module(&self.item_tree[m], &attrs),
1370                 ModItem::Import(import_id) => {
1371                     let module_id = self.module_id;
1372                     let imports = Import::from_use(
1373                         self.def_collector.db,
1374                         krate,
1375                         self.item_tree,
1376                         ItemTreeId::new(self.tree_id, import_id),
1377                     );
1378                     self.def_collector.unresolved_imports.extend(imports.into_iter().map(
1379                         |import| ImportDirective {
1380                             module_id,
1381                             import,
1382                             status: PartialResolvedImport::Unresolved,
1383                         },
1384                     ));
1385                 }
1386                 ModItem::ExternCrate(import_id) => {
1387                     self.def_collector.unresolved_imports.push(ImportDirective {
1388                         module_id: self.module_id,
1389                         import: Import::from_extern_crate(
1390                             self.def_collector.db,
1391                             krate,
1392                             self.item_tree,
1393                             ItemTreeId::new(self.tree_id, import_id),
1394                         ),
1395                         status: PartialResolvedImport::Unresolved,
1396                     })
1397                 }
1398                 ModItem::ExternBlock(block) => self.collect(&self.item_tree[block].children),
1399                 ModItem::MacroCall(mac) => self.collect_macro_call(&self.item_tree[mac]),
1400                 ModItem::MacroRules(id) => self.collect_macro_rules(id),
1401                 ModItem::MacroDef(id) => self.collect_macro_def(id),
1402                 ModItem::Impl(imp) => {
1403                     let module = self.def_collector.def_map.module_id(self.module_id);
1404                     let impl_id =
1405                         ImplLoc { container: module, id: ItemTreeId::new(self.tree_id, imp) }
1406                             .intern(self.def_collector.db);
1407                     self.def_collector.def_map.modules[self.module_id].scope.define_impl(impl_id)
1408                 }
1409                 ModItem::Function(id) => {
1410                     let func = &self.item_tree[id];
1411
1412                     let ast_id = InFile::new(self.file_id(), func.ast_id);
1413                     self.collect_proc_macro_def(&func.name, ast_id, &attrs);
1414
1415                     def = Some(DefData {
1416                         id: FunctionLoc {
1417                             container: module.into(),
1418                             id: ItemTreeId::new(self.tree_id, id),
1419                         }
1420                         .intern(self.def_collector.db)
1421                         .into(),
1422                         name: &func.name,
1423                         visibility: &self.item_tree[func.visibility],
1424                         has_constructor: false,
1425                     });
1426                 }
1427                 ModItem::Struct(id) => {
1428                     let it = &self.item_tree[id];
1429
1430                     def = Some(DefData {
1431                         id: StructLoc { container: module, id: ItemTreeId::new(self.tree_id, id) }
1432                             .intern(self.def_collector.db)
1433                             .into(),
1434                         name: &it.name,
1435                         visibility: &self.item_tree[it.visibility],
1436                         has_constructor: !matches!(it.fields, Fields::Record(_)),
1437                     });
1438                 }
1439                 ModItem::Union(id) => {
1440                     let it = &self.item_tree[id];
1441
1442                     def = Some(DefData {
1443                         id: UnionLoc { container: module, id: ItemTreeId::new(self.tree_id, id) }
1444                             .intern(self.def_collector.db)
1445                             .into(),
1446                         name: &it.name,
1447                         visibility: &self.item_tree[it.visibility],
1448                         has_constructor: false,
1449                     });
1450                 }
1451                 ModItem::Enum(id) => {
1452                     let it = &self.item_tree[id];
1453
1454                     def = Some(DefData {
1455                         id: EnumLoc { container: module, id: ItemTreeId::new(self.tree_id, id) }
1456                             .intern(self.def_collector.db)
1457                             .into(),
1458                         name: &it.name,
1459                         visibility: &self.item_tree[it.visibility],
1460                         has_constructor: false,
1461                     });
1462                 }
1463                 ModItem::Const(id) => {
1464                     let it = &self.item_tree[id];
1465                     let const_id = ConstLoc {
1466                         container: module.into(),
1467                         id: ItemTreeId::new(self.tree_id, id),
1468                     }
1469                     .intern(self.def_collector.db);
1470
1471                     match &it.name {
1472                         Some(name) => {
1473                             def = Some(DefData {
1474                                 id: const_id.into(),
1475                                 name,
1476                                 visibility: &self.item_tree[it.visibility],
1477                                 has_constructor: false,
1478                             });
1479                         }
1480                         None => {
1481                             // const _: T = ...;
1482                             self.def_collector.def_map.modules[self.module_id]
1483                                 .scope
1484                                 .define_unnamed_const(const_id);
1485                         }
1486                     }
1487                 }
1488                 ModItem::Static(id) => {
1489                     let it = &self.item_tree[id];
1490
1491                     def = Some(DefData {
1492                         id: StaticLoc { container: module, id: ItemTreeId::new(self.tree_id, id) }
1493                             .intern(self.def_collector.db)
1494                             .into(),
1495                         name: &it.name,
1496                         visibility: &self.item_tree[it.visibility],
1497                         has_constructor: false,
1498                     });
1499                 }
1500                 ModItem::Trait(id) => {
1501                     let it = &self.item_tree[id];
1502
1503                     def = Some(DefData {
1504                         id: TraitLoc { container: module, id: ItemTreeId::new(self.tree_id, id) }
1505                             .intern(self.def_collector.db)
1506                             .into(),
1507                         name: &it.name,
1508                         visibility: &self.item_tree[it.visibility],
1509                         has_constructor: false,
1510                     });
1511                 }
1512                 ModItem::TypeAlias(id) => {
1513                     let it = &self.item_tree[id];
1514
1515                     def = Some(DefData {
1516                         id: TypeAliasLoc {
1517                             container: module.into(),
1518                             id: ItemTreeId::new(self.tree_id, id),
1519                         }
1520                         .intern(self.def_collector.db)
1521                         .into(),
1522                         name: &it.name,
1523                         visibility: &self.item_tree[it.visibility],
1524                         has_constructor: false,
1525                     });
1526                 }
1527             }
1528
1529             if let Some(DefData { id, name, visibility, has_constructor }) = def {
1530                 self.def_collector.def_map.modules[self.module_id].scope.declare(id);
1531                 let vis = self
1532                     .def_collector
1533                     .def_map
1534                     .resolve_visibility(self.def_collector.db, self.module_id, visibility)
1535                     .unwrap_or(Visibility::Public);
1536                 self.def_collector.update(
1537                     self.module_id,
1538                     &[(Some(name.clone()), PerNs::from_def(id, vis, has_constructor))],
1539                     vis,
1540                     ImportType::Named,
1541                 )
1542             }
1543         }
1544     }
1545
1546     fn collect_module(&mut self, module: &Mod, attrs: &Attrs) {
1547         let path_attr = attrs.by_key("path").string_value();
1548         let is_macro_use = attrs.by_key("macro_use").exists();
1549         match &module.kind {
1550             // inline module, just recurse
1551             ModKind::Inline { items } => {
1552                 let module_id = self.push_child_module(
1553                     module.name.clone(),
1554                     AstId::new(self.file_id(), module.ast_id),
1555                     None,
1556                     &self.item_tree[module.visibility],
1557                 );
1558
1559                 if let Some(mod_dir) = self.mod_dir.descend_into_definition(&module.name, path_attr)
1560                 {
1561                     ModCollector {
1562                         def_collector: &mut *self.def_collector,
1563                         macro_depth: self.macro_depth,
1564                         module_id,
1565                         tree_id: self.tree_id,
1566                         item_tree: self.item_tree,
1567                         mod_dir,
1568                     }
1569                     .collect(&*items);
1570                     if is_macro_use {
1571                         self.import_all_legacy_macros(module_id);
1572                     }
1573                 }
1574             }
1575             // out of line module, resolve, parse and recurse
1576             ModKind::Outline {} => {
1577                 let ast_id = AstId::new(self.tree_id.file_id(), module.ast_id);
1578                 let db = self.def_collector.db;
1579                 match self.mod_dir.resolve_declaration(db, self.file_id(), &module.name, path_attr)
1580                 {
1581                     Ok((file_id, is_mod_rs, mod_dir)) => {
1582                         let item_tree = db.file_item_tree(file_id.into());
1583                         let is_enabled = item_tree
1584                             .top_level_attrs(db, self.def_collector.def_map.krate)
1585                             .cfg()
1586                             .map_or(true, |cfg| {
1587                                 self.def_collector.cfg_options.check(&cfg) != Some(false)
1588                             });
1589                         if is_enabled {
1590                             let module_id = self.push_child_module(
1591                                 module.name.clone(),
1592                                 ast_id,
1593                                 Some((file_id, is_mod_rs)),
1594                                 &self.item_tree[module.visibility],
1595                             );
1596                             ModCollector {
1597                                 def_collector: &mut *self.def_collector,
1598                                 macro_depth: self.macro_depth,
1599                                 module_id,
1600                                 tree_id: TreeId::new(file_id.into(), None),
1601                                 item_tree: &item_tree,
1602                                 mod_dir,
1603                             }
1604                             .collect(item_tree.top_level_items());
1605                             if is_macro_use
1606                                 || item_tree
1607                                     .top_level_attrs(db, self.def_collector.def_map.krate)
1608                                     .by_key("macro_use")
1609                                     .exists()
1610                             {
1611                                 self.import_all_legacy_macros(module_id);
1612                             }
1613                         }
1614                     }
1615                     Err(candidate) => {
1616                         self.def_collector.def_map.diagnostics.push(
1617                             DefDiagnostic::unresolved_module(self.module_id, ast_id, candidate),
1618                         );
1619                     }
1620                 };
1621             }
1622         }
1623     }
1624
1625     fn push_child_module(
1626         &mut self,
1627         name: Name,
1628         declaration: AstId<ast::Module>,
1629         definition: Option<(FileId, bool)>,
1630         visibility: &crate::visibility::RawVisibility,
1631     ) -> LocalModuleId {
1632         let vis = self
1633             .def_collector
1634             .def_map
1635             .resolve_visibility(self.def_collector.db, self.module_id, visibility)
1636             .unwrap_or(Visibility::Public);
1637         let modules = &mut self.def_collector.def_map.modules;
1638         let origin = match definition {
1639             None => ModuleOrigin::Inline { definition: declaration },
1640             Some((definition, is_mod_rs)) => {
1641                 ModuleOrigin::File { declaration, definition, is_mod_rs }
1642             }
1643         };
1644         let res = modules.alloc(ModuleData::new(origin, vis));
1645         modules[res].parent = Some(self.module_id);
1646         for (name, mac) in modules[self.module_id].scope.collect_legacy_macros() {
1647             modules[res].scope.define_legacy_macro(name, mac)
1648         }
1649         modules[self.module_id].children.insert(name.clone(), res);
1650         let module = self.def_collector.def_map.module_id(res);
1651         let def: ModuleDefId = module.into();
1652         self.def_collector.def_map.modules[self.module_id].scope.declare(def);
1653         self.def_collector.update(
1654             self.module_id,
1655             &[(Some(name), PerNs::from_def(def, vis, false))],
1656             vis,
1657             ImportType::Named,
1658         );
1659         res
1660     }
1661
1662     /// Resolves attributes on an item.
1663     ///
1664     /// Returns `Err` when some attributes could not be resolved to builtins and have been
1665     /// registered as unresolved.
1666     ///
1667     /// If `ignore_up_to` is `Some`, attributes precending and including that attribute will be
1668     /// assumed to be resolved already.
1669     fn resolve_attributes(&mut self, attrs: &Attrs, mod_item: ModItem) -> Result<(), ()> {
1670         let mut ignore_up_to =
1671             self.def_collector.skip_attrs.get(&InFile::new(self.file_id(), mod_item)).copied();
1672         let iter = attrs
1673             .iter()
1674             .dedup_by(|a, b| {
1675                 // FIXME: this should not be required, all attributes on an item should have a
1676                 // unique ID!
1677                 // Still, this occurs because `#[cfg_attr]` can "expand" to multiple attributes:
1678                 //     #[cfg_attr(not(off), unresolved, unresolved)]
1679                 //     struct S;
1680                 // We should come up with a different way to ID attributes.
1681                 a.id == b.id
1682             })
1683             .skip_while(|attr| match ignore_up_to {
1684                 Some(id) if attr.id == id => {
1685                     ignore_up_to = None;
1686                     true
1687                 }
1688                 Some(_) => true,
1689                 None => false,
1690             });
1691
1692         for attr in iter {
1693             if attr.path.as_ident() == Some(&hir_expand::name![derive]) {
1694                 self.collect_derive(attr, mod_item);
1695             } else if self.is_builtin_or_registered_attr(&attr.path) {
1696                 continue;
1697             } else {
1698                 tracing::debug!("non-builtin attribute {}", attr.path);
1699
1700                 let ast_id = AstIdWithPath::new(
1701                     self.file_id(),
1702                     mod_item.ast_id(self.item_tree),
1703                     attr.path.as_ref().clone(),
1704                 );
1705                 self.def_collector.unresolved_macros.push(MacroDirective {
1706                     module_id: self.module_id,
1707                     depth: self.macro_depth + 1,
1708                     kind: MacroDirectiveKind::Attr { ast_id, attr: attr.clone(), mod_item },
1709                 });
1710
1711                 return Err(());
1712             }
1713         }
1714
1715         Ok(())
1716     }
1717
1718     fn is_builtin_or_registered_attr(&self, path: &ModPath) -> bool {
1719         if path.kind == PathKind::Plain {
1720             if let Some(tool_module) = path.segments().first() {
1721                 let tool_module = tool_module.to_string();
1722                 let is_tool = builtin_attr::TOOL_MODULES
1723                     .iter()
1724                     .copied()
1725                     .chain(self.def_collector.registered_tools.iter().map(AsRef::as_ref))
1726                     .any(|m| tool_module == *m);
1727                 if is_tool {
1728                     return true;
1729                 }
1730             }
1731
1732             if let Some(name) = path.as_ident() {
1733                 let name = name.to_string();
1734                 let is_inert = builtin_attr::INERT_ATTRIBUTES
1735                     .iter()
1736                     .chain(builtin_attr::EXTRA_ATTRIBUTES)
1737                     .copied()
1738                     .chain(self.def_collector.registered_attrs.iter().map(AsRef::as_ref))
1739                     .any(|attr| name == *attr);
1740                 return is_inert;
1741             }
1742         }
1743
1744         false
1745     }
1746
1747     fn collect_derive(&mut self, attr: &Attr, mod_item: ModItem) {
1748         let ast_id: FileAstId<ast::Item> = match mod_item {
1749             ModItem::Struct(it) => self.item_tree[it].ast_id.upcast(),
1750             ModItem::Union(it) => self.item_tree[it].ast_id.upcast(),
1751             ModItem::Enum(it) => self.item_tree[it].ast_id.upcast(),
1752             _ => {
1753                 // Cannot use derive on this item.
1754                 // FIXME: diagnose
1755                 return;
1756             }
1757         };
1758
1759         match attr.parse_derive() {
1760             Some(derive_macros) => {
1761                 for path in derive_macros {
1762                     let ast_id = AstIdWithPath::new(self.file_id(), ast_id, path);
1763                     self.def_collector.unresolved_macros.push(MacroDirective {
1764                         module_id: self.module_id,
1765                         depth: self.macro_depth + 1,
1766                         kind: MacroDirectiveKind::Derive { ast_id, derive_attr: attr.id },
1767                     });
1768                 }
1769             }
1770             None => {
1771                 // FIXME: diagnose
1772                 tracing::debug!("malformed derive: {:?}", attr);
1773             }
1774         }
1775     }
1776
1777     /// If `attrs` registers a procedural macro, collects its definition.
1778     fn collect_proc_macro_def(&mut self, func_name: &Name, ast_id: AstId<ast::Fn>, attrs: &Attrs) {
1779         // FIXME: this should only be done in the root module of `proc-macro` crates, not everywhere
1780         if let Some(proc_macro) = attrs.parse_proc_macro_decl(func_name) {
1781             self.def_collector.export_proc_macro(proc_macro, ast_id);
1782         }
1783     }
1784
1785     fn collect_macro_rules(&mut self, id: FileItemTreeId<MacroRules>) {
1786         let krate = self.def_collector.def_map.krate;
1787         let mac = &self.item_tree[id];
1788         let attrs = self.item_tree.attrs(self.def_collector.db, krate, ModItem::from(id).into());
1789         let ast_id = InFile::new(self.file_id(), mac.ast_id.upcast());
1790
1791         let export_attr = attrs.by_key("macro_export");
1792
1793         let is_export = export_attr.exists();
1794         let is_local_inner = if is_export {
1795             export_attr.tt_values().map(|it| &it.token_trees).flatten().any(|it| match it {
1796                 tt::TokenTree::Leaf(tt::Leaf::Ident(ident)) => {
1797                     ident.text.contains("local_inner_macros")
1798                 }
1799                 _ => false,
1800             })
1801         } else {
1802             false
1803         };
1804
1805         // Case 1: builtin macros
1806         if attrs.by_key("rustc_builtin_macro").exists() {
1807             // `#[rustc_builtin_macro = "builtin_name"]` overrides the `macro_rules!` name.
1808             let name;
1809             let name = match attrs.by_key("rustc_builtin_macro").string_value() {
1810                 Some(it) => {
1811                     // FIXME: a hacky way to create a Name from string.
1812                     name = tt::Ident { text: it.clone(), id: tt::TokenId::unspecified() }.as_name();
1813                     &name
1814                 }
1815                 None => {
1816                     match attrs.by_key("rustc_builtin_macro").tt_values().next().and_then(|tt| {
1817                         match tt.token_trees.first() {
1818                             Some(tt::TokenTree::Leaf(tt::Leaf::Ident(name))) => Some(name),
1819                             _ => None,
1820                         }
1821                     }) {
1822                         Some(ident) => {
1823                             name = ident.as_name();
1824                             &name
1825                         }
1826                         None => &mac.name,
1827                     }
1828                 }
1829             };
1830             let krate = self.def_collector.def_map.krate;
1831             match find_builtin_macro(name, krate, ast_id) {
1832                 Some(macro_id) => {
1833                     self.def_collector.define_macro_rules(
1834                         self.module_id,
1835                         mac.name.clone(),
1836                         macro_id,
1837                         is_export,
1838                     );
1839                     return;
1840                 }
1841                 None => {
1842                     self.def_collector
1843                         .def_map
1844                         .diagnostics
1845                         .push(DefDiagnostic::unimplemented_builtin_macro(self.module_id, ast_id));
1846                 }
1847             }
1848         }
1849
1850         // Case 2: normal `macro_rules!` macro
1851         let macro_id = MacroDefId {
1852             krate: self.def_collector.def_map.krate,
1853             kind: MacroDefKind::Declarative(ast_id),
1854             local_inner: is_local_inner,
1855         };
1856         self.def_collector.define_macro_rules(
1857             self.module_id,
1858             mac.name.clone(),
1859             macro_id,
1860             is_export,
1861         );
1862     }
1863
1864     fn collect_macro_def(&mut self, id: FileItemTreeId<MacroDef>) {
1865         let krate = self.def_collector.def_map.krate;
1866         let mac = &self.item_tree[id];
1867         let ast_id = InFile::new(self.file_id(), mac.ast_id.upcast());
1868
1869         // Case 1: bulitin macros
1870         let attrs = self.item_tree.attrs(self.def_collector.db, krate, ModItem::from(id).into());
1871         if attrs.by_key("rustc_builtin_macro").exists() {
1872             let macro_id = find_builtin_macro(&mac.name, krate, ast_id)
1873                 .or_else(|| find_builtin_derive(&mac.name, krate, ast_id))
1874                 .or_else(|| find_builtin_attr(&mac.name, krate, ast_id));
1875
1876             match macro_id {
1877                 Some(macro_id) => {
1878                     self.def_collector.define_macro_def(
1879                         self.module_id,
1880                         mac.name.clone(),
1881                         macro_id,
1882                         &self.item_tree[mac.visibility],
1883                     );
1884                     return;
1885                 }
1886                 None => {
1887                     self.def_collector
1888                         .def_map
1889                         .diagnostics
1890                         .push(DefDiagnostic::unimplemented_builtin_macro(self.module_id, ast_id));
1891                 }
1892             }
1893         }
1894
1895         // Case 2: normal `macro`
1896         let macro_id = MacroDefId {
1897             krate: self.def_collector.def_map.krate,
1898             kind: MacroDefKind::Declarative(ast_id),
1899             local_inner: false,
1900         };
1901
1902         self.def_collector.define_macro_def(
1903             self.module_id,
1904             mac.name.clone(),
1905             macro_id,
1906             &self.item_tree[mac.visibility],
1907         );
1908     }
1909
1910     fn collect_macro_call(&mut self, mac: &MacroCall) {
1911         let ast_id = AstIdWithPath::new(self.file_id(), mac.ast_id, (*mac.path).clone());
1912
1913         // Case 1: try to resolve in legacy scope and expand macro_rules
1914         let mut error = None;
1915         match macro_call_as_call_id(
1916             &ast_id,
1917             mac.expand_to,
1918             self.def_collector.db,
1919             self.def_collector.def_map.krate,
1920             |path| {
1921                 path.as_ident().and_then(|name| {
1922                     self.def_collector.def_map.with_ancestor_maps(
1923                         self.def_collector.db,
1924                         self.module_id,
1925                         &mut |map, module| map[module].scope.get_legacy_macro(name),
1926                     )
1927                 })
1928             },
1929             &mut |err| {
1930                 error.get_or_insert(err);
1931             },
1932         ) {
1933             Ok(Ok(macro_call_id)) => {
1934                 // Legacy macros need to be expanded immediately, so that any macros they produce
1935                 // are in scope.
1936                 self.def_collector.collect_macro_expansion(
1937                     self.module_id,
1938                     macro_call_id,
1939                     self.macro_depth + 1,
1940                 );
1941
1942                 return;
1943             }
1944             Ok(Err(_)) => {
1945                 // Built-in macro failed eager expansion.
1946
1947                 // FIXME: don't parse the file here
1948                 let macro_call = ast_id.ast_id.to_node(self.def_collector.db.upcast());
1949                 let expand_to = hir_expand::ExpandTo::from_call_site(&macro_call);
1950                 self.def_collector.def_map.diagnostics.push(DefDiagnostic::macro_error(
1951                     self.module_id,
1952                     MacroCallKind::FnLike { ast_id: ast_id.ast_id, expand_to },
1953                     error.unwrap().to_string(),
1954                 ));
1955                 return;
1956             }
1957             Err(UnresolvedMacro { .. }) => (),
1958         }
1959
1960         // Case 2: resolve in module scope, expand during name resolution.
1961         self.def_collector.unresolved_macros.push(MacroDirective {
1962             module_id: self.module_id,
1963             depth: self.macro_depth + 1,
1964             kind: MacroDirectiveKind::FnLike { ast_id, expand_to: mac.expand_to },
1965         });
1966     }
1967
1968     fn import_all_legacy_macros(&mut self, module_id: LocalModuleId) {
1969         let macros = self.def_collector.def_map[module_id].scope.collect_legacy_macros();
1970         for (name, macro_) in macros {
1971             self.def_collector.define_legacy_macro(self.module_id, name.clone(), macro_);
1972         }
1973     }
1974
1975     fn is_cfg_enabled(&self, cfg: &CfgExpr) -> bool {
1976         self.def_collector.cfg_options.check(cfg) != Some(false)
1977     }
1978
1979     fn emit_unconfigured_diagnostic(&mut self, item: ModItem, cfg: &CfgExpr) {
1980         let ast_id = item.ast_id(self.item_tree);
1981
1982         let ast_id = InFile::new(self.file_id(), ast_id);
1983         self.def_collector.def_map.diagnostics.push(DefDiagnostic::unconfigured_code(
1984             self.module_id,
1985             ast_id,
1986             cfg.clone(),
1987             self.def_collector.cfg_options.clone(),
1988         ));
1989     }
1990
1991     fn file_id(&self) -> HirFileId {
1992         self.tree_id.file_id()
1993     }
1994 }
1995
1996 #[cfg(test)]
1997 mod tests {
1998     use crate::{db::DefDatabase, test_db::TestDB};
1999     use base_db::{fixture::WithFixture, SourceDatabase};
2000
2001     use super::*;
2002
2003     fn do_collect_defs(db: &dyn DefDatabase, def_map: DefMap) -> DefMap {
2004         let mut collector = DefCollector {
2005             db,
2006             def_map,
2007             glob_imports: FxHashMap::default(),
2008             unresolved_imports: Vec::new(),
2009             resolved_imports: Vec::new(),
2010             unresolved_macros: Vec::new(),
2011             mod_dirs: FxHashMap::default(),
2012             cfg_options: &CfgOptions::default(),
2013             proc_macros: Default::default(),
2014             exports_proc_macros: false,
2015             from_glob_import: Default::default(),
2016             skip_attrs: Default::default(),
2017             derive_helpers_in_scope: Default::default(),
2018             registered_attrs: Default::default(),
2019             registered_tools: Default::default(),
2020         };
2021         collector.seed_with_top_level();
2022         collector.collect();
2023         collector.def_map
2024     }
2025
2026     fn do_resolve(not_ra_fixture: &str) -> DefMap {
2027         let (db, file_id) = TestDB::with_single_file(not_ra_fixture);
2028         let krate = db.test_crate();
2029
2030         let edition = db.crate_graph()[krate].edition;
2031         let module_origin = ModuleOrigin::CrateRoot { definition: file_id };
2032         let def_map = DefMap::empty(krate, edition, module_origin);
2033         do_collect_defs(&db, def_map)
2034     }
2035
2036     #[test]
2037     fn test_macro_expand_will_stop_1() {
2038         do_resolve(
2039             r#"
2040 macro_rules! foo {
2041     ($($ty:ty)*) => { foo!($($ty)*); }
2042 }
2043 foo!(KABOOM);
2044 "#,
2045         );
2046         do_resolve(
2047             r#"
2048 macro_rules! foo {
2049     ($($ty:ty)*) => { foo!(() $($ty)*); }
2050 }
2051 foo!(KABOOM);
2052 "#,
2053         );
2054     }
2055
2056     #[ignore]
2057     #[test]
2058     fn test_macro_expand_will_stop_2() {
2059         // FIXME: this test does succeed, but takes quite a while: 90 seconds in
2060         // the release mode. That's why the argument is not an ra_fixture --
2061         // otherwise injection highlighting gets stuck.
2062         //
2063         // We need to find a way to fail this faster.
2064         do_resolve(
2065             r#"
2066 macro_rules! foo {
2067     ($($ty:ty)*) => { foo!($($ty)* $($ty)*); }
2068 }
2069 foo!(KABOOM);
2070 "#,
2071         );
2072     }
2073 }