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