]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/item_scope.rs
Expand derive macros under cursor in `Expand Macro Recursively`
[rust.git] / crates / hir_def / src / item_scope.rs
1 //! Describes items defined or visible (ie, imported) in a certain scope.
2 //! This is shared between modules and blocks.
3
4 use std::collections::hash_map::Entry;
5
6 use base_db::CrateId;
7 use hir_expand::{name::Name, AstId, MacroCallId, MacroDefKind};
8 use once_cell::sync::Lazy;
9 use profile::Count;
10 use rustc_hash::{FxHashMap, FxHashSet};
11 use stdx::format_to;
12 use syntax::ast;
13
14 use crate::{
15     attr::AttrId, db::DefDatabase, per_ns::PerNs, visibility::Visibility, AdtId, BuiltinType,
16     ConstId, ImplId, LocalModuleId, MacroDefId, ModuleDefId, ModuleId, TraitId,
17 };
18
19 #[derive(Copy, Clone)]
20 pub(crate) enum ImportType {
21     Glob,
22     Named,
23 }
24
25 #[derive(Debug, Default)]
26 pub struct PerNsGlobImports {
27     types: FxHashSet<(LocalModuleId, Name)>,
28     values: FxHashSet<(LocalModuleId, Name)>,
29     macros: FxHashSet<(LocalModuleId, Name)>,
30 }
31
32 #[derive(Debug, Default, PartialEq, Eq)]
33 pub struct ItemScope {
34     _c: Count<Self>,
35
36     /// Defs visible in this scope. This includes `declarations`, but also
37     /// imports.
38     types: FxHashMap<Name, (ModuleDefId, Visibility)>,
39     values: FxHashMap<Name, (ModuleDefId, Visibility)>,
40     macros: FxHashMap<Name, (MacroDefId, Visibility)>,
41     unresolved: FxHashSet<Name>,
42
43     /// The defs declared in this scope. Each def has a single scope where it is
44     /// declared.
45     declarations: Vec<ModuleDefId>,
46     impls: Vec<ImplId>,
47     unnamed_consts: Vec<ConstId>,
48     /// Traits imported via `use Trait as _;`.
49     unnamed_trait_imports: FxHashMap<TraitId, Visibility>,
50     /// Macros visible in current module in legacy textual scope
51     ///
52     /// For macros invoked by an unqualified identifier like `bar!()`, `legacy_macros` will be searched in first.
53     /// If it yields no result, then it turns to module scoped `macros`.
54     /// It macros with name qualified with a path like `crate::foo::bar!()`, `legacy_macros` will be skipped,
55     /// and only normal scoped `macros` will be searched in.
56     ///
57     /// Note that this automatically inherit macros defined textually before the definition of module itself.
58     ///
59     /// Module scoped macros will be inserted into `items` instead of here.
60     // FIXME: Macro shadowing in one module is not properly handled. Non-item place macros will
61     // be all resolved to the last one defined if shadowing happens.
62     legacy_macros: FxHashMap<Name, MacroDefId>,
63     attr_macros: FxHashMap<AstId<ast::Item>, MacroCallId>,
64     derive_macros: FxHashMap<AstId<ast::Item>, (AttrId, MacroCallId)>,
65 }
66
67 pub(crate) static BUILTIN_SCOPE: Lazy<FxHashMap<Name, PerNs>> = Lazy::new(|| {
68     BuiltinType::ALL
69         .iter()
70         .map(|(name, ty)| (name.clone(), PerNs::types((*ty).into(), Visibility::Public)))
71         .collect()
72 });
73
74 /// Shadow mode for builtin type which can be shadowed by module.
75 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
76 pub(crate) enum BuiltinShadowMode {
77     /// Prefer user-defined modules (or other types) over builtins.
78     Module,
79     /// Prefer builtins over user-defined modules (but not other types).
80     Other,
81 }
82
83 /// Legacy macros can only be accessed through special methods like `get_legacy_macros`.
84 /// Other methods will only resolve values, types and module scoped macros only.
85 impl ItemScope {
86     pub fn entries<'a>(&'a self) -> impl Iterator<Item = (&'a Name, PerNs)> + 'a {
87         // FIXME: shadowing
88         let keys: FxHashSet<_> = self
89             .types
90             .keys()
91             .chain(self.values.keys())
92             .chain(self.macros.keys())
93             .chain(self.unresolved.iter())
94             .collect();
95
96         keys.into_iter().map(move |name| (name, self.get(name)))
97     }
98
99     pub fn declarations(&self) -> impl Iterator<Item = ModuleDefId> + '_ {
100         self.declarations.iter().copied()
101     }
102
103     pub fn impls(&self) -> impl Iterator<Item = ImplId> + ExactSizeIterator + '_ {
104         self.impls.iter().copied()
105     }
106
107     pub fn values(
108         &self,
109     ) -> impl Iterator<Item = (ModuleDefId, Visibility)> + ExactSizeIterator + '_ {
110         self.values.values().copied()
111     }
112
113     pub fn unnamed_consts(&self) -> impl Iterator<Item = ConstId> + '_ {
114         self.unnamed_consts.iter().copied()
115     }
116
117     /// Iterate over all module scoped macros
118     pub(crate) fn macros<'a>(&'a self) -> impl Iterator<Item = (&'a Name, MacroDefId)> + 'a {
119         self.entries().filter_map(|(name, def)| def.take_macros().map(|macro_| (name, macro_)))
120     }
121
122     /// Iterate over all legacy textual scoped macros visible at the end of the module
123     pub(crate) fn legacy_macros<'a>(&'a self) -> impl Iterator<Item = (&'a Name, MacroDefId)> + 'a {
124         self.legacy_macros.iter().map(|(name, def)| (name, *def))
125     }
126
127     /// Get a name from current module scope, legacy macros are not included
128     pub(crate) fn get(&self, name: &Name) -> PerNs {
129         PerNs {
130             types: self.types.get(name).copied(),
131             values: self.values.get(name).copied(),
132             macros: self.macros.get(name).copied(),
133         }
134     }
135
136     /// XXX: this is O(N) rather than O(1), try to not introduce new usages.
137     pub(crate) fn name_of(&self, item: ItemInNs) -> Option<(&Name, Visibility)> {
138         for (name, per_ns) in self.entries() {
139             if let Some(vis) = item.match_with(per_ns) {
140                 return Some((name, vis));
141             }
142         }
143         None
144     }
145
146     pub(crate) fn traits<'a>(&'a self) -> impl Iterator<Item = TraitId> + 'a {
147         self.types
148             .values()
149             .filter_map(|(def, _)| match def {
150                 ModuleDefId::TraitId(t) => Some(*t),
151                 _ => None,
152             })
153             .chain(self.unnamed_trait_imports.keys().copied())
154     }
155
156     pub(crate) fn declare(&mut self, def: ModuleDefId) {
157         self.declarations.push(def)
158     }
159
160     pub(crate) fn get_legacy_macro(&self, name: &Name) -> Option<MacroDefId> {
161         self.legacy_macros.get(name).copied()
162     }
163
164     pub(crate) fn define_impl(&mut self, imp: ImplId) {
165         self.impls.push(imp)
166     }
167
168     pub(crate) fn define_unnamed_const(&mut self, konst: ConstId) {
169         self.unnamed_consts.push(konst);
170     }
171
172     pub(crate) fn define_legacy_macro(&mut self, name: Name, mac: MacroDefId) {
173         self.legacy_macros.insert(name, mac);
174     }
175
176     pub(crate) fn add_attr_macro_invoc(&mut self, item: AstId<ast::Item>, call: MacroCallId) {
177         self.attr_macros.insert(item, call);
178     }
179
180     pub(crate) fn attr_macro_invocs(
181         &self,
182     ) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
183         self.attr_macros.iter().map(|(k, v)| (*k, *v))
184     }
185
186     pub(crate) fn add_derive_macro_invoc(
187         &mut self,
188         item: AstId<ast::Item>,
189         call: MacroCallId,
190         attr_id: AttrId,
191     ) {
192         self.derive_macros.insert(item, (attr_id, call));
193     }
194
195     pub(crate) fn derive_macro_invocs(
196         &self,
197     ) -> impl Iterator<Item = (AstId<ast::Item>, (AttrId, MacroCallId))> + '_ {
198         self.derive_macros.iter().map(|(k, v)| (*k, *v))
199     }
200
201     pub(crate) fn unnamed_trait_vis(&self, tr: TraitId) -> Option<Visibility> {
202         self.unnamed_trait_imports.get(&tr).copied()
203     }
204
205     pub(crate) fn push_unnamed_trait(&mut self, tr: TraitId, vis: Visibility) {
206         self.unnamed_trait_imports.insert(tr, vis);
207     }
208
209     pub(crate) fn push_res_with_import(
210         &mut self,
211         glob_imports: &mut PerNsGlobImports,
212         lookup: (LocalModuleId, Name),
213         def: PerNs,
214         def_import_type: ImportType,
215     ) -> bool {
216         let mut changed = false;
217
218         macro_rules! check_changed {
219             (
220                 $changed:ident,
221                 ( $this:ident / $def:ident ) . $field:ident,
222                 $glob_imports:ident [ $lookup:ident ],
223                 $def_import_type:ident
224             ) => {{
225                 let existing = $this.$field.entry($lookup.1.clone());
226                 match (existing, $def.$field) {
227                     (Entry::Vacant(entry), Some(_)) => {
228                         match $def_import_type {
229                             ImportType::Glob => {
230                                 $glob_imports.$field.insert($lookup.clone());
231                             }
232                             ImportType::Named => {
233                                 $glob_imports.$field.remove(&$lookup);
234                             }
235                         }
236
237                         if let Some(fld) = $def.$field {
238                             entry.insert(fld);
239                         }
240                         $changed = true;
241                     }
242                     (Entry::Occupied(mut entry), Some(_))
243                         if $glob_imports.$field.contains(&$lookup)
244                             && matches!($def_import_type, ImportType::Named) =>
245                     {
246                         cov_mark::hit!(import_shadowed);
247                         $glob_imports.$field.remove(&$lookup);
248                         if let Some(fld) = $def.$field {
249                             entry.insert(fld);
250                         }
251                         $changed = true;
252                     }
253                     _ => {}
254                 }
255             }};
256         }
257
258         check_changed!(changed, (self / def).types, glob_imports[lookup], def_import_type);
259         check_changed!(changed, (self / def).values, glob_imports[lookup], def_import_type);
260         check_changed!(changed, (self / def).macros, glob_imports[lookup], def_import_type);
261
262         if def.is_none() && self.unresolved.insert(lookup.1) {
263             changed = true;
264         }
265
266         changed
267     }
268
269     pub(crate) fn resolutions<'a>(&'a self) -> impl Iterator<Item = (Option<Name>, PerNs)> + 'a {
270         self.entries().map(|(name, res)| (Some(name.clone()), res)).chain(
271             self.unnamed_trait_imports
272                 .iter()
273                 .map(|(tr, vis)| (None, PerNs::types(ModuleDefId::TraitId(*tr), *vis))),
274         )
275     }
276
277     pub(crate) fn collect_legacy_macros(&self) -> FxHashMap<Name, MacroDefId> {
278         self.legacy_macros.clone()
279     }
280
281     /// Marks everything that is not a procedural macro as private to `this_module`.
282     pub(crate) fn censor_non_proc_macros(&mut self, this_module: ModuleId) {
283         self.types
284             .values_mut()
285             .chain(self.values.values_mut())
286             .map(|(_, v)| v)
287             .chain(self.unnamed_trait_imports.values_mut())
288             .for_each(|vis| *vis = Visibility::Module(this_module));
289
290         for (mac, vis) in self.macros.values_mut() {
291             if let MacroDefKind::ProcMacro(..) = mac.kind {
292                 // FIXME: Technically this is insufficient since reexports of proc macros are also
293                 // forbidden. Practically nobody does that.
294                 continue;
295             }
296
297             *vis = Visibility::Module(this_module);
298         }
299     }
300
301     pub(crate) fn dump(&self, buf: &mut String) {
302         let mut entries: Vec<_> = self.resolutions().collect();
303         entries.sort_by_key(|(name, _)| name.clone());
304
305         for (name, def) in entries {
306             format_to!(buf, "{}:", name.map_or("_".to_string(), |name| name.to_string()));
307
308             if def.types.is_some() {
309                 buf.push_str(" t");
310             }
311             if def.values.is_some() {
312                 buf.push_str(" v");
313             }
314             if def.macros.is_some() {
315                 buf.push_str(" m");
316             }
317             if def.is_none() {
318                 buf.push_str(" _");
319             }
320
321             buf.push('\n');
322         }
323     }
324
325     pub(crate) fn shrink_to_fit(&mut self) {
326         // Exhaustive match to require handling new fields.
327         let Self {
328             _c: _,
329             types,
330             values,
331             macros,
332             unresolved,
333             declarations: defs,
334             impls,
335             unnamed_consts,
336             unnamed_trait_imports,
337             legacy_macros,
338             attr_macros,
339             derive_macros,
340         } = self;
341         types.shrink_to_fit();
342         values.shrink_to_fit();
343         macros.shrink_to_fit();
344         unresolved.shrink_to_fit();
345         defs.shrink_to_fit();
346         impls.shrink_to_fit();
347         unnamed_consts.shrink_to_fit();
348         unnamed_trait_imports.shrink_to_fit();
349         legacy_macros.shrink_to_fit();
350         attr_macros.shrink_to_fit();
351         derive_macros.shrink_to_fit();
352     }
353 }
354
355 impl PerNs {
356     pub(crate) fn from_def(def: ModuleDefId, v: Visibility, has_constructor: bool) -> PerNs {
357         match def {
358             ModuleDefId::ModuleId(_) => PerNs::types(def, v),
359             ModuleDefId::FunctionId(_) => PerNs::values(def, v),
360             ModuleDefId::AdtId(adt) => match adt {
361                 AdtId::UnionId(_) => PerNs::types(def, v),
362                 AdtId::EnumId(_) => PerNs::types(def, v),
363                 AdtId::StructId(_) => {
364                     if has_constructor {
365                         PerNs::both(def, def, v)
366                     } else {
367                         PerNs::types(def, v)
368                     }
369                 }
370             },
371             ModuleDefId::EnumVariantId(_) => PerNs::both(def, def, v),
372             ModuleDefId::ConstId(_) | ModuleDefId::StaticId(_) => PerNs::values(def, v),
373             ModuleDefId::TraitId(_) => PerNs::types(def, v),
374             ModuleDefId::TypeAliasId(_) => PerNs::types(def, v),
375             ModuleDefId::BuiltinType(_) => PerNs::types(def, v),
376         }
377     }
378 }
379
380 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
381 pub enum ItemInNs {
382     Types(ModuleDefId),
383     Values(ModuleDefId),
384     Macros(MacroDefId),
385 }
386
387 impl ItemInNs {
388     fn match_with(self, per_ns: PerNs) -> Option<Visibility> {
389         match self {
390             ItemInNs::Types(def) => {
391                 per_ns.types.filter(|(other_def, _)| *other_def == def).map(|(_, vis)| vis)
392             }
393             ItemInNs::Values(def) => {
394                 per_ns.values.filter(|(other_def, _)| *other_def == def).map(|(_, vis)| vis)
395             }
396             ItemInNs::Macros(def) => {
397                 per_ns.macros.filter(|(other_def, _)| *other_def == def).map(|(_, vis)| vis)
398             }
399         }
400     }
401
402     pub fn as_module_def_id(self) -> Option<ModuleDefId> {
403         match self {
404             ItemInNs::Types(id) | ItemInNs::Values(id) => Some(id),
405             ItemInNs::Macros(_) => None,
406         }
407     }
408
409     /// Returns the crate defining this item (or `None` if `self` is built-in).
410     pub fn krate(&self, db: &dyn DefDatabase) -> Option<CrateId> {
411         match self {
412             ItemInNs::Types(did) | ItemInNs::Values(did) => did.module(db).map(|m| m.krate),
413             ItemInNs::Macros(id) => Some(id.krate),
414         }
415     }
416 }