1 //! Describes items defined or visible (ie, imported) in a certain scope.
2 //! This is shared between modules and blocks.
4 use std::collections::hash_map::Entry;
7 use hir_expand::{name::Name, AstId, MacroCallId, MacroDefKind};
8 use once_cell::sync::Lazy;
10 use rustc_hash::{FxHashMap, FxHashSet};
11 use smallvec::SmallVec;
16 attr::AttrId, db::DefDatabase, per_ns::PerNs, visibility::Visibility, AdtId, BuiltinType,
17 ConstId, ImplId, LocalModuleId, MacroDefId, ModuleDefId, ModuleId, TraitId,
20 #[derive(Copy, Clone)]
21 pub(crate) enum ImportType {
26 #[derive(Debug, Default)]
27 pub struct PerNsGlobImports {
28 types: FxHashSet<(LocalModuleId, Name)>,
29 values: FxHashSet<(LocalModuleId, Name)>,
30 macros: FxHashSet<(LocalModuleId, Name)>,
33 #[derive(Debug, Default, PartialEq, Eq)]
34 pub struct ItemScope {
37 /// Defs visible in this scope. This includes `declarations`, but also
39 types: FxHashMap<Name, (ModuleDefId, Visibility)>,
40 values: FxHashMap<Name, (ModuleDefId, Visibility)>,
41 macros: FxHashMap<Name, (MacroDefId, Visibility)>,
42 unresolved: FxHashSet<Name>,
44 /// The defs declared in this scope. Each def has a single scope where it is
46 declarations: Vec<ModuleDefId>,
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
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.
58 /// Note that this automatically inherit macros defined textually before the definition of module itself.
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]>>,
68 pub(crate) static BUILTIN_SCOPE: Lazy<FxHashMap<Name, PerNs>> = Lazy::new(|| {
71 .map(|(name, ty)| (name.clone(), PerNs::types((*ty).into(), Visibility::Public)))
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.
80 /// Prefer builtins over user-defined modules (but not other types).
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.
87 pub fn entries<'a>(&'a self) -> impl Iterator<Item = (&'a Name, PerNs)> + 'a {
89 let keys: FxHashSet<_> = self
92 .chain(self.values.keys())
93 .chain(self.macros.keys())
94 .chain(self.unresolved.iter())
97 keys.into_iter().map(move |name| (name, self.get(name)))
100 pub fn declarations(&self) -> impl Iterator<Item = ModuleDefId> + '_ {
101 self.declarations.iter().copied()
104 pub fn impls(&self) -> impl Iterator<Item = ImplId> + ExactSizeIterator + '_ {
105 self.impls.iter().copied()
110 ) -> impl Iterator<Item = (ModuleDefId, Visibility)> + ExactSizeIterator + '_ {
111 self.values.values().copied()
114 pub fn unnamed_consts(&self) -> impl Iterator<Item = ConstId> + '_ {
115 self.unnamed_consts.iter().copied()
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_)))
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))
128 /// Get a name from current module scope, legacy macros are not included
129 pub(crate) fn get(&self, name: &Name) -> PerNs {
131 types: self.types.get(name).copied(),
132 values: self.values.get(name).copied(),
133 macros: self.macros.get(name).copied(),
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 for (name, per_ns) in self.entries() {
140 if let Some(vis) = item.match_with(per_ns) {
141 return Some((name, vis));
147 pub(crate) fn traits<'a>(&'a self) -> impl Iterator<Item = TraitId> + 'a {
150 .filter_map(|(def, _)| match def {
151 ModuleDefId::TraitId(t) => Some(*t),
154 .chain(self.unnamed_trait_imports.keys().copied())
157 pub(crate) fn declare(&mut self, def: ModuleDefId) {
158 self.declarations.push(def)
161 pub(crate) fn get_legacy_macro(&self, name: &Name) -> Option<MacroDefId> {
162 self.legacy_macros.get(name).copied()
165 pub(crate) fn define_impl(&mut self, imp: ImplId) {
169 pub(crate) fn define_unnamed_const(&mut self, konst: ConstId) {
170 self.unnamed_consts.push(konst);
173 pub(crate) fn define_legacy_macro(&mut self, name: Name, mac: MacroDefId) {
174 self.legacy_macros.insert(name, mac);
177 pub(crate) fn add_attr_macro_invoc(&mut self, item: AstId<ast::Item>, call: MacroCallId) {
178 self.attr_macros.insert(item, call);
181 pub(crate) fn attr_macro_invocs(
183 ) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
184 self.attr_macros.iter().map(|(k, v)| (*k, *v))
187 pub(crate) fn add_derive_macro_invoc(
189 item: AstId<ast::Item>,
193 self.derive_macros.entry(item).or_default().push((attr_id, call));
196 pub(crate) fn derive_macro_invocs(
198 ) -> impl Iterator<Item = (AstId<ast::Item>, &[(AttrId, MacroCallId)])> + '_ {
199 self.derive_macros.iter().map(|(k, v)| (*k, v.as_ref()))
202 pub(crate) fn unnamed_trait_vis(&self, tr: TraitId) -> Option<Visibility> {
203 self.unnamed_trait_imports.get(&tr).copied()
206 pub(crate) fn push_unnamed_trait(&mut self, tr: TraitId, vis: Visibility) {
207 self.unnamed_trait_imports.insert(tr, vis);
210 pub(crate) fn push_res_with_import(
212 glob_imports: &mut PerNsGlobImports,
213 lookup: (LocalModuleId, Name),
215 def_import_type: ImportType,
217 let mut changed = false;
219 macro_rules! check_changed {
222 ( $this:ident / $def:ident ) . $field:ident,
223 $glob_imports:ident [ $lookup:ident ],
224 $def_import_type:ident
226 let existing = $this.$field.entry($lookup.1.clone());
227 match (existing, $def.$field) {
228 (Entry::Vacant(entry), Some(_)) => {
229 match $def_import_type {
230 ImportType::Glob => {
231 $glob_imports.$field.insert($lookup.clone());
233 ImportType::Named => {
234 $glob_imports.$field.remove(&$lookup);
238 if let Some(fld) = $def.$field {
243 (Entry::Occupied(mut entry), Some(_))
244 if $glob_imports.$field.contains(&$lookup)
245 && matches!($def_import_type, ImportType::Named) =>
247 cov_mark::hit!(import_shadowed);
248 $glob_imports.$field.remove(&$lookup);
249 if let Some(fld) = $def.$field {
259 check_changed!(changed, (self / def).types, glob_imports[lookup], def_import_type);
260 check_changed!(changed, (self / def).values, glob_imports[lookup], def_import_type);
261 check_changed!(changed, (self / def).macros, glob_imports[lookup], def_import_type);
263 if def.is_none() && self.unresolved.insert(lookup.1) {
270 pub(crate) fn resolutions<'a>(&'a self) -> impl Iterator<Item = (Option<Name>, PerNs)> + 'a {
271 self.entries().map(|(name, res)| (Some(name.clone()), res)).chain(
272 self.unnamed_trait_imports
274 .map(|(tr, vis)| (None, PerNs::types(ModuleDefId::TraitId(*tr), *vis))),
278 pub(crate) fn collect_legacy_macros(&self) -> FxHashMap<Name, MacroDefId> {
279 self.legacy_macros.clone()
282 /// Marks everything that is not a procedural macro as private to `this_module`.
283 pub(crate) fn censor_non_proc_macros(&mut self, this_module: ModuleId) {
286 .chain(self.values.values_mut())
288 .chain(self.unnamed_trait_imports.values_mut())
289 .for_each(|vis| *vis = Visibility::Module(this_module));
291 for (mac, vis) in self.macros.values_mut() {
292 if let MacroDefKind::ProcMacro(..) = mac.kind {
293 // FIXME: Technically this is insufficient since reexports of proc macros are also
294 // forbidden. Practically nobody does that.
298 *vis = Visibility::Module(this_module);
302 pub(crate) fn dump(&self, buf: &mut String) {
303 let mut entries: Vec<_> = self.resolutions().collect();
304 entries.sort_by_key(|(name, _)| name.clone());
306 for (name, def) in entries {
307 format_to!(buf, "{}:", name.map_or("_".to_string(), |name| name.to_string()));
309 if def.types.is_some() {
312 if def.values.is_some() {
315 if def.macros.is_some() {
326 pub(crate) fn shrink_to_fit(&mut self) {
327 // Exhaustive match to require handling new fields.
337 unnamed_trait_imports,
342 types.shrink_to_fit();
343 values.shrink_to_fit();
344 macros.shrink_to_fit();
345 unresolved.shrink_to_fit();
346 defs.shrink_to_fit();
347 impls.shrink_to_fit();
348 unnamed_consts.shrink_to_fit();
349 unnamed_trait_imports.shrink_to_fit();
350 legacy_macros.shrink_to_fit();
351 attr_macros.shrink_to_fit();
352 derive_macros.shrink_to_fit();
357 pub(crate) fn from_def(def: ModuleDefId, v: Visibility, has_constructor: bool) -> PerNs {
359 ModuleDefId::ModuleId(_) => PerNs::types(def, v),
360 ModuleDefId::FunctionId(_) => PerNs::values(def, v),
361 ModuleDefId::AdtId(adt) => match adt {
362 AdtId::UnionId(_) => PerNs::types(def, v),
363 AdtId::EnumId(_) => PerNs::types(def, v),
364 AdtId::StructId(_) => {
366 PerNs::both(def, def, v)
372 ModuleDefId::EnumVariantId(_) => PerNs::both(def, def, v),
373 ModuleDefId::ConstId(_) | ModuleDefId::StaticId(_) => PerNs::values(def, v),
374 ModuleDefId::TraitId(_) => PerNs::types(def, v),
375 ModuleDefId::TypeAliasId(_) => PerNs::types(def, v),
376 ModuleDefId::BuiltinType(_) => PerNs::types(def, v),
381 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
389 fn match_with(self, per_ns: PerNs) -> Option<Visibility> {
391 ItemInNs::Types(def) => {
392 per_ns.types.filter(|(other_def, _)| *other_def == def).map(|(_, vis)| vis)
394 ItemInNs::Values(def) => {
395 per_ns.values.filter(|(other_def, _)| *other_def == def).map(|(_, vis)| vis)
397 ItemInNs::Macros(def) => {
398 per_ns.macros.filter(|(other_def, _)| *other_def == def).map(|(_, vis)| vis)
403 pub fn as_module_def_id(self) -> Option<ModuleDefId> {
405 ItemInNs::Types(id) | ItemInNs::Values(id) => Some(id),
406 ItemInNs::Macros(_) => None,
410 /// Returns the crate defining this item (or `None` if `self` is built-in).
411 pub fn krate(&self, db: &dyn DefDatabase) -> Option<CrateId> {
413 ItemInNs::Types(did) | ItemInNs::Values(did) => did.module(db).map(|m| m.krate),
414 ItemInNs::Macros(id) => Some(id.krate),