1use std::{fmt, sync::LazyLock};
5
6use base_db::Crate;
7use hir_expand::{AstId, MacroCallId, attrs::AttrId, name::Name};
8use indexmap::map::Entry;
9use itertools::Itertools;
10use la_arena::Idx;
11use rustc_hash::{FxHashMap, FxHashSet};
12use smallvec::{SmallVec, smallvec};
13use span::Edition;
14use stdx::format_to;
15use syntax::ast;
16use thin_vec::ThinVec;
17
18use crate::{
19 AdtId, BuiltinType, ConstId, ExternBlockId, ExternCrateId, FxIndexMap, HasModule, ImplId,
20 Lookup, MacroCallStyles, MacroId, ModuleDefId, ModuleId, TraitId, UseId,
21 db::DefDatabase,
22 per_ns::{Item, MacrosItem, PerNs, TypesItem, ValuesItem},
23 visibility::Visibility,
24};
25
26#[derive(Debug, Default)]
27pub struct PerNsGlobImports {
28 types: FxHashSet<(ModuleId, Name)>,
29 values: FxHashSet<(ModuleId, Name)>,
30 macros: FxHashSet<(ModuleId, Name)>,
31}
32
33#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
34pub enum ImportOrExternCrate {
35 Glob(GlobId),
36 Import(ImportId),
37 ExternCrate(ExternCrateId),
38}
39
40impl From<ImportOrGlob> for ImportOrExternCrate {
41 fn from(value: ImportOrGlob) -> Self {
42 match value {
43 ImportOrGlob::Glob(it) => ImportOrExternCrate::Glob(it),
44 ImportOrGlob::Import(it) => ImportOrExternCrate::Import(it),
45 }
46 }
47}
48
49impl ImportOrExternCrate {
50 pub fn import_or_glob(self) -> Option<ImportOrGlob> {
51 match self {
52 ImportOrExternCrate::Import(it) => Some(ImportOrGlob::Import(it)),
53 ImportOrExternCrate::Glob(it) => Some(ImportOrGlob::Glob(it)),
54 _ => None,
55 }
56 }
57
58 pub fn import(self) -> Option<ImportId> {
59 match self {
60 ImportOrExternCrate::Import(it) => Some(it),
61 _ => None,
62 }
63 }
64
65 pub fn glob(self) -> Option<GlobId> {
66 match self {
67 ImportOrExternCrate::Glob(id) => Some(id),
68 _ => None,
69 }
70 }
71
72 pub fn use_(self) -> Option<UseId> {
73 match self {
74 ImportOrExternCrate::Glob(id) => Some(id.use_),
75 ImportOrExternCrate::Import(id) => Some(id.use_),
76 _ => None,
77 }
78 }
79}
80
81#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
82pub enum ImportOrGlob {
83 Glob(GlobId),
84 Import(ImportId),
85}
86
87impl ImportOrGlob {
88 pub fn into_import(self) -> Option<ImportId> {
89 match self {
90 ImportOrGlob::Import(it) => Some(it),
91 _ => None,
92 }
93 }
94}
95
96#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
97pub enum ImportOrDef {
98 Import(ImportId),
99 Glob(GlobId),
100 ExternCrate(ExternCrateId),
101 Def(ModuleDefId),
102}
103
104impl From<ImportOrExternCrate> for ImportOrDef {
105 fn from(value: ImportOrExternCrate) -> Self {
106 match value {
107 ImportOrExternCrate::Import(it) => ImportOrDef::Import(it),
108 ImportOrExternCrate::Glob(it) => ImportOrDef::Glob(it),
109 ImportOrExternCrate::ExternCrate(it) => ImportOrDef::ExternCrate(it),
110 }
111 }
112}
113
114impl From<ImportOrGlob> for ImportOrDef {
115 fn from(value: ImportOrGlob) -> Self {
116 match value {
117 ImportOrGlob::Import(it) => ImportOrDef::Import(it),
118 ImportOrGlob::Glob(it) => ImportOrDef::Glob(it),
119 }
120 }
121}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
124pub struct ImportId {
125 pub use_: UseId,
126 pub idx: Idx<ast::UseTree>,
127}
128
129#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
130pub struct GlobId {
131 pub use_: UseId,
132 pub idx: Idx<ast::UseTree>,
133}
134
135impl PerNsGlobImports {
136 pub(crate) fn contains_type(&self, module_id: ModuleId, name: Name) -> bool {
137 self.types.contains(&(module_id, name))
138 }
139 pub(crate) fn contains_value(&self, module_id: ModuleId, name: Name) -> bool {
140 self.values.contains(&(module_id, name))
141 }
142 pub(crate) fn contains_macro(&self, module_id: ModuleId, name: Name) -> bool {
143 self.macros.contains(&(module_id, name))
144 }
145}
146
147#[derive(Debug, Default, PartialEq, Eq)]
148pub struct ItemScope {
149 types: FxIndexMap<Name, TypesItem>,
153 values: FxIndexMap<Name, ValuesItem>,
154 macros: FxIndexMap<Name, MacrosItem>,
155 unresolved: FxHashSet<Name>,
156
157 declarations: ThinVec<ModuleDefId>,
160
161 impls: ThinVec<ImplId>,
162 extern_blocks: ThinVec<ExternBlockId>,
163 unnamed_consts: ThinVec<ConstId>,
164 unnamed_trait_imports: ThinVec<(TraitId, Item<()>)>,
166
167 use_imports_types: FxHashMap<ImportOrExternCrate, ImportOrDef>,
169 use_imports_values: FxHashMap<ImportOrGlob, ImportOrDef>,
170 use_imports_macros: FxHashMap<ImportOrExternCrate, ImportOrDef>,
171
172 use_decls: ThinVec<UseId>,
173 extern_crate_decls: ThinVec<ExternCrateId>,
174 legacy_macros: FxHashMap<Name, SmallVec<[MacroId; 2]>>,
187 attr_macros: FxHashMap<AstId<ast::Item>, MacroCallId>,
189 macro_invocations: FxHashMap<AstId<ast::MacroCall>, MacroCallId>,
191 derive_macros: FxHashMap<AstId<ast::Adt>, SmallVec<[DeriveMacroInvocation; 1]>>,
194}
195
196#[derive(Debug, PartialEq, Eq)]
197struct DeriveMacroInvocation {
198 attr_id: AttrId,
199 attr_call_id: MacroCallId,
201 derive_call_ids: SmallVec<[Option<MacroCallId>; 4]>,
202}
203
204pub(crate) static BUILTIN_SCOPE: LazyLock<FxIndexMap<Name, PerNs>> = LazyLock::new(|| {
205 BuiltinType::all_builtin_types()
206 .iter()
207 .map(|(name, ty)| (name.clone(), PerNs::types((*ty).into(), Visibility::Public, None)))
208 .collect()
209});
210
211#[derive(Debug, Copy, Clone, PartialEq, Eq)]
213pub(crate) enum BuiltinShadowMode {
214 Module,
216 Other,
218}
219
220impl ItemScope {
223 pub fn entries(&self) -> impl Iterator<Item = (&Name, PerNs)> + '_ {
224 self.types
226 .keys()
227 .chain(self.values.keys())
228 .chain(self.macros.keys())
229 .chain(self.unresolved.iter())
230 .sorted()
231 .dedup()
232 .map(move |name| (name, self.get(name)))
233 }
234
235 pub fn values(&self) -> impl Iterator<Item = (&Name, Item<ModuleDefId, ImportOrGlob>)> + '_ {
236 self.values.iter().map(|(n, &i)| (n, i))
237 }
238
239 pub fn types(
240 &self,
241 ) -> impl Iterator<Item = (&Name, Item<ModuleDefId, ImportOrExternCrate>)> + '_ {
242 self.types.iter().map(|(n, &i)| (n, i))
243 }
244
245 pub fn macros(&self) -> impl Iterator<Item = (&Name, Item<MacroId, ImportOrExternCrate>)> + '_ {
246 self.macros.iter().map(|(n, &i)| (n, i))
247 }
248
249 pub fn imports(&self) -> impl Iterator<Item = ImportId> + '_ {
250 self.use_imports_types
251 .keys()
252 .copied()
253 .chain(self.use_imports_macros.keys().copied())
254 .filter_map(ImportOrExternCrate::import_or_glob)
255 .chain(self.use_imports_values.keys().copied())
256 .filter_map(ImportOrGlob::into_import)
257 .sorted()
258 .dedup()
259 }
260
261 pub fn fully_resolve_import(&self, db: &dyn DefDatabase, mut import: ImportId) -> PerNs {
262 let mut res = PerNs::none();
263
264 let mut scope = self;
265 while let Some(&m) = scope.use_imports_macros.get(&ImportOrExternCrate::Import(import)) {
266 match m {
267 ImportOrDef::Import(i) => {
268 let module_id = i.use_.lookup(db).container;
269 scope = &module_id.def_map(db)[module_id].scope;
270 import = i;
271 }
272 ImportOrDef::Def(ModuleDefId::MacroId(def)) => {
273 res.macros = Some(Item { def, vis: Visibility::Public, import: None });
274 break;
275 }
276 _ => break,
277 }
278 }
279 let mut scope = self;
280 while let Some(&m) = scope.use_imports_types.get(&ImportOrExternCrate::Import(import)) {
281 match m {
282 ImportOrDef::Import(i) => {
283 let module_id = i.use_.lookup(db).container;
284 scope = &module_id.def_map(db)[module_id].scope;
285 import = i;
286 }
287 ImportOrDef::Def(def) => {
288 res.types = Some(Item { def, vis: Visibility::Public, import: None });
289 break;
290 }
291 _ => break,
292 }
293 }
294 let mut scope = self;
295 while let Some(&m) = scope.use_imports_values.get(&ImportOrGlob::Import(import)) {
296 match m {
297 ImportOrDef::Import(i) => {
298 let module_id = i.use_.lookup(db).container;
299 scope = &module_id.def_map(db)[module_id].scope;
300 import = i;
301 }
302 ImportOrDef::Def(def) => {
303 res.values = Some(Item { def, vis: Visibility::Public, import: None });
304 break;
305 }
306 _ => break,
307 }
308 }
309 res
310 }
311
312 pub fn declarations(&self) -> impl Iterator<Item = ModuleDefId> + '_ {
313 self.declarations.iter().copied()
314 }
315
316 pub fn extern_crate_decls(&self) -> impl ExactSizeIterator<Item = ExternCrateId> + '_ {
317 self.extern_crate_decls.iter().copied()
318 }
319
320 pub fn extern_blocks(&self) -> impl Iterator<Item = ExternBlockId> + '_ {
321 self.extern_blocks.iter().copied()
322 }
323
324 pub fn use_decls(&self) -> impl ExactSizeIterator<Item = UseId> + '_ {
325 self.use_decls.iter().copied()
326 }
327
328 pub fn impls(&self) -> impl ExactSizeIterator<Item = ImplId> + '_ {
329 self.impls.iter().copied()
330 }
331
332 pub fn all_macro_calls(&self) -> impl Iterator<Item = MacroCallId> + '_ {
333 self.macro_invocations.values().copied().chain(self.attr_macros.values().copied()).chain(
334 self.derive_macros.values().flat_map(|it| {
335 it.iter().flat_map(|it| it.derive_call_ids.iter().copied().flatten())
336 }),
337 )
338 }
339
340 pub(crate) fn modules_in_scope(&self) -> impl Iterator<Item = (ModuleId, Visibility)> + '_ {
341 self.types.values().filter_map(|ns| match ns.def {
342 ModuleDefId::ModuleId(module) => Some((module, ns.vis)),
343 _ => None,
344 })
345 }
346
347 pub fn unnamed_consts(&self) -> impl Iterator<Item = ConstId> + '_ {
348 self.unnamed_consts.iter().copied()
349 }
350
351 pub fn legacy_macros(&self) -> impl Iterator<Item = (&Name, &[MacroId])> + '_ {
353 self.legacy_macros.iter().map(|(name, def)| (name, &**def))
354 }
355
356 pub fn get(&self, name: &Name) -> PerNs {
358 PerNs {
359 types: self.types.get(name).copied(),
360 values: self.values.get(name).copied(),
361 macros: self.macros.get(name).copied(),
362 }
363 }
364
365 pub(crate) fn type_(&self, name: &Name) -> Option<(ModuleDefId, Visibility)> {
366 self.types.get(name).map(|item| (item.def, item.vis))
367 }
368
369 pub(crate) fn name_of(&self, item: ItemInNs) -> Option<(&Name, Visibility, bool)> {
371 match item {
372 ItemInNs::Macros(def) => self.macros.iter().find_map(|(name, other_def)| {
373 (other_def.def == def).then_some((name, other_def.vis, other_def.import.is_none()))
374 }),
375 ItemInNs::Types(def) => self.types.iter().find_map(|(name, other_def)| {
376 (other_def.def == def).then_some((name, other_def.vis, other_def.import.is_none()))
377 }),
378 ItemInNs::Values(def) => self.values.iter().find_map(|(name, other_def)| {
379 (other_def.def == def).then_some((name, other_def.vis, other_def.import.is_none()))
380 }),
381 }
382 }
383
384 pub(crate) fn names_of<T>(
386 &self,
387 item: ItemInNs,
388 mut cb: impl FnMut(&Name, Visibility, bool) -> Option<T>,
389 ) -> Option<T> {
390 match item {
391 ItemInNs::Macros(def) => self
392 .macros
393 .iter()
394 .filter_map(|(name, other_def)| {
395 (other_def.def == def).then_some((
396 name,
397 other_def.vis,
398 other_def.import.is_none(),
399 ))
400 })
401 .find_map(|(a, b, c)| cb(a, b, c)),
402 ItemInNs::Types(def) => self
403 .types
404 .iter()
405 .filter_map(|(name, other_def)| {
406 (other_def.def == def).then_some((
407 name,
408 other_def.vis,
409 other_def.import.is_none(),
410 ))
411 })
412 .find_map(|(a, b, c)| cb(a, b, c)),
413 ItemInNs::Values(def) => self
414 .values
415 .iter()
416 .filter_map(|(name, other_def)| {
417 (other_def.def == def).then_some((
418 name,
419 other_def.vis,
420 other_def.import.is_none(),
421 ))
422 })
423 .find_map(|(a, b, c)| cb(a, b, c)),
424 }
425 }
426
427 pub(crate) fn traits(&self) -> impl Iterator<Item = TraitId> + '_ {
428 self.types
429 .values()
430 .filter_map(|def| match def.def {
431 ModuleDefId::TraitId(t) => Some(t),
432 _ => None,
433 })
434 .chain(self.unnamed_trait_imports.iter().map(|&(t, _)| t))
435 }
436
437 pub(crate) fn resolutions(&self) -> impl Iterator<Item = (Option<Name>, PerNs)> + '_ {
438 self.entries().map(|(name, res)| (Some(name.clone()), res)).chain(
439 self.unnamed_trait_imports.iter().map(|(tr, trait_)| {
440 (
441 None,
442 PerNs::types(
443 ModuleDefId::TraitId(*tr),
444 trait_.vis,
445 trait_.import.map(ImportOrExternCrate::Import),
446 ),
447 )
448 }),
449 )
450 }
451
452 pub fn macro_invoc(&self, call: AstId<ast::MacroCall>) -> Option<MacroCallId> {
453 self.macro_invocations.get(&call).copied()
454 }
455
456 pub fn iter_macro_invoc(&self) -> impl Iterator<Item = (&AstId<ast::MacroCall>, &MacroCallId)> {
457 self.macro_invocations.iter()
458 }
459}
460
461impl ItemScope {
462 pub(crate) fn declare(&mut self, def: ModuleDefId) {
463 self.declarations.push(def)
464 }
465
466 pub(crate) fn get_legacy_macro(&self, name: &Name) -> Option<&[MacroId]> {
467 self.legacy_macros.get(name).map(|it| &**it)
468 }
469
470 pub(crate) fn define_impl(&mut self, imp: ImplId) {
471 self.impls.push(imp);
472 }
473
474 pub(crate) fn define_extern_block(&mut self, extern_block: ExternBlockId) {
475 self.extern_blocks.push(extern_block);
476 }
477
478 pub(crate) fn define_extern_crate_decl(&mut self, extern_crate: ExternCrateId) {
479 self.extern_crate_decls.push(extern_crate);
480 }
481
482 pub(crate) fn define_unnamed_const(&mut self, konst: ConstId) {
483 self.unnamed_consts.push(konst);
484 }
485
486 pub(crate) fn define_legacy_macro(&mut self, name: Name, mac: MacroId) {
487 self.legacy_macros.entry(name).or_default().push(mac);
488 }
489
490 pub(crate) fn add_attr_macro_invoc(&mut self, item: AstId<ast::Item>, call: MacroCallId) {
491 self.attr_macros.insert(item, call);
492 }
493
494 pub(crate) fn add_macro_invoc(&mut self, call: AstId<ast::MacroCall>, call_id: MacroCallId) {
495 self.macro_invocations.insert(call, call_id);
496 }
497
498 pub fn attr_macro_invocs(&self) -> impl Iterator<Item = (AstId<ast::Item>, MacroCallId)> + '_ {
499 self.attr_macros.iter().map(|(k, v)| (*k, *v))
500 }
501
502 pub(crate) fn set_derive_macro_invoc(
503 &mut self,
504 adt: AstId<ast::Adt>,
505 call: MacroCallId,
506 id: AttrId,
507 idx: usize,
508 ) {
509 if let Some(derives) = self.derive_macros.get_mut(&adt)
510 && let Some(DeriveMacroInvocation { derive_call_ids, .. }) =
511 derives.iter_mut().find(|&&mut DeriveMacroInvocation { attr_id, .. }| id == attr_id)
512 {
513 derive_call_ids[idx] = Some(call);
514 }
515 }
516
517 pub(crate) fn init_derive_attribute(
521 &mut self,
522 adt: AstId<ast::Adt>,
523 attr_id: AttrId,
524 attr_call_id: MacroCallId,
525 len: usize,
526 ) {
527 self.derive_macros.entry(adt).or_default().push(DeriveMacroInvocation {
528 attr_id,
529 attr_call_id,
530 derive_call_ids: smallvec![None; len],
531 });
532 }
533
534 pub fn derive_macro_invocs(
535 &self,
536 ) -> impl Iterator<
537 Item = (
538 AstId<ast::Adt>,
539 impl Iterator<Item = (AttrId, MacroCallId, &[Option<MacroCallId>])>,
540 ),
541 > + '_ {
542 self.derive_macros.iter().map(|(k, v)| {
543 (
544 *k,
545 v.iter().map(|DeriveMacroInvocation { attr_id, attr_call_id, derive_call_ids }| {
546 (*attr_id, *attr_call_id, &**derive_call_ids)
547 }),
548 )
549 })
550 }
551
552 pub fn derive_macro_invoc(
553 &self,
554 ast_id: AstId<ast::Adt>,
555 attr_id: AttrId,
556 ) -> Option<MacroCallId> {
557 Some(self.derive_macros.get(&ast_id)?.iter().find(|it| it.attr_id == attr_id)?.attr_call_id)
558 }
559
560 pub(crate) fn unnamed_trait_vis(&self, tr: TraitId) -> Option<Visibility> {
562 self.unnamed_trait_imports.iter().find(|&&(t, _)| t == tr).map(|(_, trait_)| trait_.vis)
563 }
564
565 pub(crate) fn push_unnamed_trait(
566 &mut self,
567 tr: TraitId,
568 vis: Visibility,
569 import: Option<ImportId>,
570 ) {
571 self.unnamed_trait_imports.push((tr, Item { def: (), vis, import }));
572 }
573
574 pub(crate) fn push_res_with_import(
575 &mut self,
576 glob_imports: &mut PerNsGlobImports,
577 lookup: (ModuleId, Name),
578 def: PerNs,
579 import: Option<ImportOrExternCrate>,
580 ) -> bool {
581 let mut changed = false;
582
583 if let Some(mut fld) = def.types {
586 let existing = self.types.entry(lookup.1.clone());
587 match existing {
588 Entry::Vacant(entry) => {
589 match import {
590 Some(ImportOrExternCrate::Glob(_)) => {
591 glob_imports.types.insert(lookup.clone());
592 }
593 _ => _ = glob_imports.types.remove(&lookup),
594 }
595 let prev = std::mem::replace(&mut fld.import, import);
596 if let Some(import) = import {
597 self.use_imports_types
598 .insert(import, prev.map_or(ImportOrDef::Def(fld.def), Into::into));
599 }
600 entry.insert(fld);
601 changed = true;
602 }
603 Entry::Occupied(mut entry) => {
604 match import {
605 Some(ImportOrExternCrate::Glob(..)) => {
606 }
612 _ => {
613 if glob_imports.types.remove(&lookup) {
614 let prev = std::mem::replace(&mut fld.import, import);
615 if let Some(import) = import {
616 self.use_imports_types.insert(
617 import,
618 prev.map_or(ImportOrDef::Def(fld.def), Into::into),
619 );
620 }
621 cov_mark::hit!(import_shadowed);
622 entry.insert(fld);
623 changed = true;
624 }
625 }
626 }
627 }
628 }
629 }
630
631 if let Some(mut fld) = def.values {
632 let existing = self.values.entry(lookup.1.clone());
633 match existing {
634 Entry::Vacant(entry) => {
635 match import {
636 Some(ImportOrExternCrate::Glob(_)) => {
637 glob_imports.values.insert(lookup.clone());
638 }
639 _ => _ = glob_imports.values.remove(&lookup),
640 }
641 let import = import.and_then(ImportOrExternCrate::import_or_glob);
642 let prev = std::mem::replace(&mut fld.import, import);
643 if let Some(import) = import {
644 self.use_imports_values
645 .insert(import, prev.map_or(ImportOrDef::Def(fld.def), Into::into));
646 }
647 entry.insert(fld);
648 changed = true;
649 }
650 Entry::Occupied(mut entry)
651 if !matches!(import, Some(ImportOrExternCrate::Glob(..))) =>
652 {
653 if glob_imports.values.remove(&lookup) {
654 cov_mark::hit!(import_shadowed);
655
656 let import = import.and_then(ImportOrExternCrate::import_or_glob);
657 let prev = std::mem::replace(&mut fld.import, import);
658 if let Some(import) = import {
659 self.use_imports_values
660 .insert(import, prev.map_or(ImportOrDef::Def(fld.def), Into::into));
661 }
662 entry.insert(fld);
663 changed = true;
664 }
665 }
666 _ => {}
667 }
668 }
669
670 if let Some(mut fld) = def.macros {
671 let existing = self.macros.entry(lookup.1.clone());
672 match existing {
673 Entry::Vacant(entry) => {
674 match import {
675 Some(ImportOrExternCrate::Glob(_)) => {
676 glob_imports.macros.insert(lookup.clone());
677 }
678 _ => _ = glob_imports.macros.remove(&lookup),
679 }
680 let prev = std::mem::replace(&mut fld.import, import);
681 if let Some(import) = import {
682 self.use_imports_macros.insert(
683 import,
684 prev.map_or_else(|| ImportOrDef::Def(fld.def.into()), Into::into),
685 );
686 }
687 entry.insert(fld);
688 changed = true;
689 }
690 Entry::Occupied(mut entry)
691 if !matches!(import, Some(ImportOrExternCrate::Glob(..))) =>
692 {
693 if glob_imports.macros.remove(&lookup) {
694 cov_mark::hit!(import_shadowed);
695 let prev = std::mem::replace(&mut fld.import, import);
696 if let Some(import) = import {
697 self.use_imports_macros.insert(
698 import,
699 prev.map_or_else(|| ImportOrDef::Def(fld.def.into()), Into::into),
700 );
701 }
702 entry.insert(fld);
703 changed = true;
704 }
705 }
706 _ => {}
707 }
708 }
709
710 if def.is_none() && self.unresolved.insert(lookup.1) {
711 changed = true;
712 }
713
714 changed
715 }
716
717 pub(crate) fn censor_non_proc_macros(&mut self, krate: Crate) {
719 self.types
720 .values_mut()
721 .map(|def| &mut def.vis)
722 .chain(self.values.values_mut().map(|def| &mut def.vis))
723 .chain(self.unnamed_trait_imports.iter_mut().map(|(_, def)| &mut def.vis))
724 .for_each(|vis| *vis = Visibility::PubCrate(krate));
725
726 for mac in self.macros.values_mut() {
727 if matches!(mac.def, MacroId::ProcMacroId(_) if mac.import.is_none()) {
728 continue;
729 }
730 mac.vis = Visibility::PubCrate(krate)
731 }
732 }
733
734 pub(crate) fn dump(&self, db: &dyn DefDatabase, buf: &mut String) {
735 let mut entries: Vec<_> = self.resolutions().collect();
736 entries.sort_by_key(|(name, _)| name.clone());
737
738 let print_macro_sub_ns = |buf: &mut String, macro_id: MacroId| {
739 let styles = crate::nameres::macro_styles_from_id(db, macro_id);
740 if styles.contains(MacroCallStyles::FN_LIKE) {
741 buf.push('!');
742 }
743 if styles.contains(MacroCallStyles::ATTR) || styles.contains(MacroCallStyles::DERIVE) {
744 buf.push('#');
745 }
746 };
747
748 for (name, def) in entries {
749 let display_name: &dyn fmt::Display = match &name {
750 Some(name) => &name.display(db, Edition::LATEST),
751 None => &"_",
752 };
753 format_to!(buf, "- {display_name} :");
754
755 if let Some(Item { import, .. }) = def.types {
756 buf.push_str(" type");
757 match import {
758 Some(ImportOrExternCrate::Import(_)) => buf.push_str(" (import)"),
759 Some(ImportOrExternCrate::Glob(_)) => buf.push_str(" (glob)"),
760 Some(ImportOrExternCrate::ExternCrate(_)) => buf.push_str(" (extern)"),
761 None => (),
762 }
763 }
764 if let Some(Item { import, .. }) = def.values {
765 buf.push_str(" value");
766 match import {
767 Some(ImportOrGlob::Import(_)) => buf.push_str(" (import)"),
768 Some(ImportOrGlob::Glob(_)) => buf.push_str(" (glob)"),
769 None => (),
770 }
771 }
772 if let Some(Item { def: macro_id, import, .. }) = def.macros {
773 buf.push_str(" macro");
774 print_macro_sub_ns(buf, macro_id);
775 match import {
776 Some(ImportOrExternCrate::Import(_)) => buf.push_str(" (import)"),
777 Some(ImportOrExternCrate::Glob(_)) => buf.push_str(" (glob)"),
778 Some(ImportOrExternCrate::ExternCrate(_)) => buf.push_str(" (extern)"),
779 None => (),
780 }
781 }
782 if def.is_none() {
783 buf.push_str(" _");
784 }
785
786 buf.push('\n');
787 }
788
789 let mut legacy_macros = self.legacy_macros().collect::<Vec<_>>();
794 legacy_macros.sort_by(|(a, _), (b, _)| Ord::cmp(a, b));
795 for (name, macros) in legacy_macros {
796 format_to!(buf, "- (legacy) {} :", name.display(db, Edition::LATEST));
797 for ¯o_id in macros {
798 buf.push_str(" macro");
799 print_macro_sub_ns(buf, macro_id);
800 }
801 buf.push('\n');
802 }
803 }
804
805 pub(crate) fn shrink_to_fit(&mut self) {
806 let Self {
808 types,
809 values,
810 macros,
811 unresolved,
812 declarations,
813 impls,
814 unnamed_consts,
815 unnamed_trait_imports,
816 legacy_macros,
817 attr_macros,
818 derive_macros,
819 extern_crate_decls,
820 use_decls,
821 use_imports_values,
822 use_imports_types,
823 use_imports_macros,
824 macro_invocations,
825 extern_blocks,
826 } = self;
827 extern_blocks.shrink_to_fit();
828 types.shrink_to_fit();
829 values.shrink_to_fit();
830 macros.shrink_to_fit();
831 use_imports_types.shrink_to_fit();
832 use_imports_values.shrink_to_fit();
833 use_imports_macros.shrink_to_fit();
834 unresolved.shrink_to_fit();
835 declarations.shrink_to_fit();
836 impls.shrink_to_fit();
837 unnamed_consts.shrink_to_fit();
838 unnamed_trait_imports.shrink_to_fit();
839 legacy_macros.shrink_to_fit();
840 attr_macros.shrink_to_fit();
841 derive_macros.shrink_to_fit();
842 extern_crate_decls.shrink_to_fit();
843 use_decls.shrink_to_fit();
844 macro_invocations.shrink_to_fit();
845 }
846}
847
848impl ItemScope {
850 pub(crate) fn update_visibility_types(&mut self, name: &Name, vis: Visibility) {
851 let res =
852 self.types.get_mut(name).expect("tried to update visibility of non-existent type");
853 res.vis = vis;
854 }
855
856 pub(crate) fn update_visibility_values(&mut self, name: &Name, vis: Visibility) {
857 let res =
858 self.values.get_mut(name).expect("tried to update visibility of non-existent value");
859 res.vis = vis;
860 }
861
862 pub(crate) fn update_visibility_macros(&mut self, name: &Name, vis: Visibility) {
863 let res =
864 self.macros.get_mut(name).expect("tried to update visibility of non-existent macro");
865 res.vis = vis;
866 }
867}
868
869impl PerNs {
870 pub(crate) fn from_def(
871 def: ModuleDefId,
872 v: Visibility,
873 has_constructor: bool,
874 import: Option<ImportOrExternCrate>,
875 ) -> PerNs {
876 match def {
877 ModuleDefId::ModuleId(_) => PerNs::types(def, v, import),
878 ModuleDefId::FunctionId(_) => {
879 PerNs::values(def, v, import.and_then(ImportOrExternCrate::import_or_glob))
880 }
881 ModuleDefId::AdtId(adt) => match adt {
882 AdtId::UnionId(_) => PerNs::types(def, v, import),
883 AdtId::EnumId(_) => PerNs::types(def, v, import),
884 AdtId::StructId(_) => {
885 if has_constructor {
886 PerNs::both(def, def, v, import)
887 } else {
888 PerNs::types(def, v, import)
889 }
890 }
891 },
892 ModuleDefId::EnumVariantId(_) => PerNs::both(def, def, v, import),
893 ModuleDefId::ConstId(_) | ModuleDefId::StaticId(_) => {
894 PerNs::values(def, v, import.and_then(ImportOrExternCrate::import_or_glob))
895 }
896 ModuleDefId::TraitId(_) => PerNs::types(def, v, import),
897 ModuleDefId::TypeAliasId(_) => PerNs::types(def, v, import),
898 ModuleDefId::BuiltinType(_) => PerNs::types(def, v, import),
899 ModuleDefId::MacroId(mac) => PerNs::macros(mac, v, import),
900 }
901 }
902}
903
904#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
905pub enum ItemInNs {
906 Types(ModuleDefId),
907 Values(ModuleDefId),
908 Macros(MacroId),
909}
910
911impl ItemInNs {
912 pub fn as_module_def_id(self) -> Option<ModuleDefId> {
913 match self {
914 ItemInNs::Types(id) | ItemInNs::Values(id) => Some(id),
915 ItemInNs::Macros(_) => None,
916 }
917 }
918
919 pub fn krate(&self, db: &dyn DefDatabase) -> Option<Crate> {
921 self.module(db).map(|module_id| module_id.krate(db))
922 }
923
924 pub fn module(&self, db: &dyn DefDatabase) -> Option<ModuleId> {
925 match self {
926 ItemInNs::Types(id) | ItemInNs::Values(id) => id.module(db),
927 ItemInNs::Macros(id) => Some(id.module(db)),
928 }
929 }
930}