]> git.lizzy.rs Git - rust.git/blob - crates/hir_def/src/item_scope.rs
37599371f61fee8f13a6ddae18172740f0061e39
[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;
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     derive_macros: FxHashMap<AstId<ast::Item>, SmallVec<[(AttrId, MacroCallId); 1]>>,
68 }
69
70 pub(crate) static BUILTIN_SCOPE: Lazy<FxHashMap<Name, PerNs>> = Lazy::new(|| {
71     BuiltinType::ALL
72         .iter()
73         .map(|(name, ty)| (name.clone(), PerNs::types((*ty).into(), Visibility::Public)))
74         .collect()
75 });
76
77 /// Shadow mode for builtin type which can be shadowed by module.
78 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
79 pub(crate) enum BuiltinShadowMode {
80     /// Prefer user-defined modules (or other types) over builtins.
81     Module,
82     /// Prefer builtins over user-defined modules (but not other types).
83     Other,
84 }
85
86 /// Legacy macros can only be accessed through special methods like `get_legacy_macros`.
87 /// Other methods will only resolve values, types and module scoped macros only.
88 impl ItemScope {
89     pub fn entries<'a>(&'a self) -> impl Iterator<Item = (&'a Name, PerNs)> + 'a {
90         // FIXME: shadowing
91         let keys: FxHashSet<_> = self
92             .types
93             .keys()
94             .chain(self.values.keys())
95             .chain(self.macros.keys())
96             .chain(self.unresolved.iter())
97             .collect();
98
99         keys.into_iter().map(move |name| (name, self.get(name)))
100     }
101
102     pub fn declarations(&self) -> impl Iterator<Item = ModuleDefId> + '_ {
103         self.declarations.iter().copied()
104     }
105
106     pub fn macro_declarations(&self) -> impl Iterator<Item = MacroDefId> + '_ {
107         self.macro_declarations.iter().copied()
108     }
109
110     pub fn impls(&self) -> impl Iterator<Item = ImplId> + ExactSizeIterator + '_ {
111         self.impls.iter().copied()
112     }
113
114     pub fn values(
115         &self,
116     ) -> impl Iterator<Item = (ModuleDefId, Visibility)> + ExactSizeIterator + '_ {
117         self.values.values().copied()
118     }
119
120     pub fn unnamed_consts(&self) -> impl Iterator<Item = ConstId> + '_ {
121         self.unnamed_consts.iter().copied()
122     }
123
124     /// Iterate over all module scoped macros
125     pub(crate) fn macros<'a>(&'a self) -> impl Iterator<Item = (&'a Name, MacroDefId)> + 'a {
126         self.entries().filter_map(|(name, def)| def.take_macros().map(|macro_| (name, macro_)))
127     }
128
129     /// Iterate over all legacy textual scoped macros visible at the end of the module
130     pub(crate) fn legacy_macros<'a>(&'a self) -> impl Iterator<Item = (&'a Name, MacroDefId)> + 'a {
131         self.legacy_macros.iter().map(|(name, def)| (name, *def))
132     }
133
134     /// Get a name from current module scope, legacy macros are not included
135     pub(crate) fn get(&self, name: &Name) -> PerNs {
136         PerNs {
137             types: self.types.get(name).copied(),
138             values: self.values.get(name).copied(),
139             macros: self.macros.get(name).copied(),
140         }
141     }
142
143     /// XXX: this is O(N) rather than O(1), try to not introduce new usages.
144     pub(crate) fn name_of(&self, item: ItemInNs) -> Option<(&Name, Visibility)> {
145         let (def, mut iter) = match item {
146             ItemInNs::Macros(def) => {
147                 return self
148                     .macros
149                     .iter()
150                     .find_map(|(name, &(other_def, vis))| (other_def == def).then(|| (name, vis)));
151             }
152             ItemInNs::Types(def) => (def, self.types.iter()),
153             ItemInNs::Values(def) => (def, self.values.iter()),
154         };
155         iter.find_map(|(name, &(other_def, vis))| (other_def == def).then(|| (name, vis)))
156     }
157
158     pub(crate) fn traits<'a>(&'a self) -> impl Iterator<Item = TraitId> + 'a {
159         self.types
160             .values()
161             .filter_map(|(def, _)| match def {
162                 ModuleDefId::TraitId(t) => Some(*t),
163                 _ => None,
164             })
165             .chain(self.unnamed_trait_imports.keys().copied())
166     }
167
168     pub(crate) fn declare(&mut self, def: ModuleDefId) {
169         self.declarations.push(def)
170     }
171
172     pub(crate) fn declare_macro(&mut self, def: MacroDefId) {
173         self.macro_declarations.push(def);
174     }
175
176     pub(crate) fn get_legacy_macro(&self, name: &Name) -> Option<MacroDefId> {
177         self.legacy_macros.get(name).copied()
178     }
179
180     pub(crate) fn define_impl(&mut self, imp: ImplId) {
181         self.impls.push(imp)
182     }
183
184     pub(crate) fn define_unnamed_const(&mut self, konst: ConstId) {
185         self.unnamed_consts.push(konst);
186     }
187
188     pub(crate) fn define_legacy_macro(&mut self, name: Name, mac: MacroDefId) {
189         self.legacy_macros.insert(name, mac);
190     }
191
192     pub(crate) fn add_attr_macro_invoc(&mut self, item: AstId<ast::Item>, call: MacroCallId) {
193         self.attr_macros.insert(item, call);
194     }
195
196     pub(crate) fn attr_macro_invocs(
197         &self,
198     ) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
199         self.attr_macros.iter().map(|(k, v)| (*k, *v))
200     }
201
202     pub(crate) fn add_derive_macro_invoc(
203         &mut self,
204         item: AstId<ast::Item>,
205         call: MacroCallId,
206         attr_id: AttrId,
207     ) {
208         self.derive_macros.entry(item).or_default().push((attr_id, call));
209     }
210
211     pub(crate) fn derive_macro_invocs(
212         &self,
213     ) -> impl Iterator<Item = (AstId<ast::Item>, &[(AttrId, MacroCallId)])> + '_ {
214         self.derive_macros.iter().map(|(k, v)| (*k, v.as_ref()))
215     }
216
217     pub(crate) fn unnamed_trait_vis(&self, tr: TraitId) -> Option<Visibility> {
218         self.unnamed_trait_imports.get(&tr).copied()
219     }
220
221     pub(crate) fn push_unnamed_trait(&mut self, tr: TraitId, vis: Visibility) {
222         self.unnamed_trait_imports.insert(tr, vis);
223     }
224
225     pub(crate) fn push_res_with_import(
226         &mut self,
227         glob_imports: &mut PerNsGlobImports,
228         lookup: (LocalModuleId, Name),
229         def: PerNs,
230         def_import_type: ImportType,
231     ) -> bool {
232         let mut changed = false;
233
234         macro_rules! check_changed {
235             (
236                 $changed:ident,
237                 ( $this:ident / $def:ident ) . $field:ident,
238                 $glob_imports:ident [ $lookup:ident ],
239                 $def_import_type:ident
240             ) => {{
241                 let existing = $this.$field.entry($lookup.1.clone());
242                 match (existing, $def.$field) {
243                     (Entry::Vacant(entry), Some(_)) => {
244                         match $def_import_type {
245                             ImportType::Glob => {
246                                 $glob_imports.$field.insert($lookup.clone());
247                             }
248                             ImportType::Named => {
249                                 $glob_imports.$field.remove(&$lookup);
250                             }
251                         }
252
253                         if let Some(fld) = $def.$field {
254                             entry.insert(fld);
255                         }
256                         $changed = true;
257                     }
258                     (Entry::Occupied(mut entry), Some(_))
259                         if $glob_imports.$field.contains(&$lookup)
260                             && matches!($def_import_type, ImportType::Named) =>
261                     {
262                         cov_mark::hit!(import_shadowed);
263                         $glob_imports.$field.remove(&$lookup);
264                         if let Some(fld) = $def.$field {
265                             entry.insert(fld);
266                         }
267                         $changed = true;
268                     }
269                     _ => {}
270                 }
271             }};
272         }
273
274         check_changed!(changed, (self / def).types, glob_imports[lookup], def_import_type);
275         check_changed!(changed, (self / def).values, glob_imports[lookup], def_import_type);
276         check_changed!(changed, (self / def).macros, glob_imports[lookup], def_import_type);
277
278         if def.is_none() && self.unresolved.insert(lookup.1) {
279             changed = true;
280         }
281
282         changed
283     }
284
285     pub(crate) fn resolutions<'a>(&'a self) -> impl Iterator<Item = (Option<Name>, PerNs)> + 'a {
286         self.entries().map(|(name, res)| (Some(name.clone()), res)).chain(
287             self.unnamed_trait_imports
288                 .iter()
289                 .map(|(tr, vis)| (None, PerNs::types(ModuleDefId::TraitId(*tr), *vis))),
290         )
291     }
292
293     pub(crate) fn collect_legacy_macros(&self) -> FxHashMap<Name, MacroDefId> {
294         self.legacy_macros.clone()
295     }
296
297     /// Marks everything that is not a procedural macro as private to `this_module`.
298     pub(crate) fn censor_non_proc_macros(&mut self, this_module: ModuleId) {
299         self.types
300             .values_mut()
301             .chain(self.values.values_mut())
302             .map(|(_, v)| v)
303             .chain(self.unnamed_trait_imports.values_mut())
304             .for_each(|vis| *vis = Visibility::Module(this_module));
305
306         for (mac, vis) in self.macros.values_mut() {
307             if let MacroDefKind::ProcMacro(..) = mac.kind {
308                 // FIXME: Technically this is insufficient since reexports of proc macros are also
309                 // forbidden. Practically nobody does that.
310                 continue;
311             }
312
313             *vis = Visibility::Module(this_module);
314         }
315     }
316
317     pub(crate) fn dump(&self, buf: &mut String) {
318         let mut entries: Vec<_> = self.resolutions().collect();
319         entries.sort_by_key(|(name, _)| name.clone());
320
321         for (name, def) in entries {
322             format_to!(buf, "{}:", name.map_or("_".to_string(), |name| name.to_string()));
323
324             if def.types.is_some() {
325                 buf.push_str(" t");
326             }
327             if def.values.is_some() {
328                 buf.push_str(" v");
329             }
330             if def.macros.is_some() {
331                 buf.push_str(" m");
332             }
333             if def.is_none() {
334                 buf.push_str(" _");
335             }
336
337             buf.push('\n');
338         }
339     }
340
341     pub(crate) fn shrink_to_fit(&mut self) {
342         // Exhaustive match to require handling new fields.
343         let Self {
344             _c: _,
345             types,
346             values,
347             macros,
348             unresolved,
349             declarations,
350             macro_declarations,
351             impls,
352             unnamed_consts,
353             unnamed_trait_imports,
354             legacy_macros,
355             attr_macros,
356             derive_macros,
357         } = self;
358         types.shrink_to_fit();
359         values.shrink_to_fit();
360         macros.shrink_to_fit();
361         unresolved.shrink_to_fit();
362         declarations.shrink_to_fit();
363         macro_declarations.shrink_to_fit();
364         impls.shrink_to_fit();
365         unnamed_consts.shrink_to_fit();
366         unnamed_trait_imports.shrink_to_fit();
367         legacy_macros.shrink_to_fit();
368         attr_macros.shrink_to_fit();
369         derive_macros.shrink_to_fit();
370     }
371 }
372
373 impl PerNs {
374     pub(crate) fn from_def(def: ModuleDefId, v: Visibility, has_constructor: bool) -> PerNs {
375         match def {
376             ModuleDefId::ModuleId(_) => PerNs::types(def, v),
377             ModuleDefId::FunctionId(_) => PerNs::values(def, v),
378             ModuleDefId::AdtId(adt) => match adt {
379                 AdtId::UnionId(_) => PerNs::types(def, v),
380                 AdtId::EnumId(_) => PerNs::types(def, v),
381                 AdtId::StructId(_) => {
382                     if has_constructor {
383                         PerNs::both(def, def, v)
384                     } else {
385                         PerNs::types(def, v)
386                     }
387                 }
388             },
389             ModuleDefId::EnumVariantId(_) => PerNs::both(def, def, v),
390             ModuleDefId::ConstId(_) | ModuleDefId::StaticId(_) => PerNs::values(def, v),
391             ModuleDefId::TraitId(_) => PerNs::types(def, v),
392             ModuleDefId::TypeAliasId(_) => PerNs::types(def, v),
393             ModuleDefId::BuiltinType(_) => PerNs::types(def, v),
394         }
395     }
396 }
397
398 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
399 pub enum ItemInNs {
400     Types(ModuleDefId),
401     Values(ModuleDefId),
402     Macros(MacroDefId),
403 }
404
405 impl ItemInNs {
406     pub fn as_module_def_id(self) -> Option<ModuleDefId> {
407         match self {
408             ItemInNs::Types(id) | ItemInNs::Values(id) => Some(id),
409             ItemInNs::Macros(_) => None,
410         }
411     }
412
413     /// Returns the crate defining this item (or `None` if `self` is built-in).
414     pub fn krate(&self, db: &dyn DefDatabase) -> Option<CrateId> {
415         match self {
416             ItemInNs::Types(did) | ItemInNs::Values(did) => did.module(db).map(|m| m.krate),
417             ItemInNs::Macros(id) => Some(id.krate),
418         }
419     }
420 }