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