aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir_def/src/per_ns.rs
blob: 6e435c8c12a7c28e1352389dc8d9c4149c7e3ebc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//! In rust, it is possible to have a value, a type and a macro with the same
//! name without conflicts.
//!
//! `PerNs` (per namespace) captures this.

use hir_expand::MacroDefId;

use crate::{visibility::Visibility, ModuleDefId};

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct PerNs {
    pub types: Option<(ModuleDefId, Visibility)>,
    pub values: Option<(ModuleDefId, Visibility)>,
    pub macros: Option<(MacroDefId, Visibility)>,
}

impl Default for PerNs {
    fn default() -> Self {
        PerNs { types: None, values: None, macros: None }
    }
}

impl PerNs {
    pub fn none() -> PerNs {
        PerNs { types: None, values: None, macros: None }
    }

    pub fn values(t: ModuleDefId, v: Visibility) -> PerNs {
        PerNs { types: None, values: Some((t, v)), macros: None }
    }

    pub fn types(t: ModuleDefId, v: Visibility) -> PerNs {
        PerNs { types: Some((t, v)), values: None, macros: None }
    }

    pub fn both(types: ModuleDefId, values: ModuleDefId, v: Visibility) -> PerNs {
        PerNs { types: Some((types, v)), values: Some((values, v)), macros: None }
    }

    pub fn macros(macro_: MacroDefId, v: Visibility) -> PerNs {
        PerNs { types: None, values: None, macros: Some((macro_, v)) }
    }

    pub fn is_none(&self) -> bool {
        self.types.is_none() && self.values.is_none() && self.macros.is_none()
    }

    pub fn take_types(self) -> Option<ModuleDefId> {
        self.types.map(|it| it.0)
    }

    pub fn take_types_vis(self) -> Option<(ModuleDefId, Visibility)> {
        self.types
    }

    pub fn take_values(self) -> Option<ModuleDefId> {
        self.values.map(|it| it.0)
    }

    pub fn take_macros(self) -> Option<MacroDefId> {
        self.macros.map(|it| it.0)
    }

    pub fn filter_visibility(self, mut f: impl FnMut(Visibility) -> bool) -> PerNs {
        PerNs {
            types: self.types.filter(|(_, v)| f(*v)),
            values: self.values.filter(|(_, v)| f(*v)),
            macros: self.macros.filter(|(_, v)| f(*v)),
        }
    }

    pub fn with_visibility(self, vis: Visibility) -> PerNs {
        PerNs {
            types: self.types.map(|(it, _)| (it, vis)),
            values: self.values.map(|(it, _)| (it, vis)),
            macros: self.macros.map(|(it, _)| (it, vis)),
        }
    }

    pub fn or(self, other: PerNs) -> PerNs {
        PerNs {
            types: self.types.or(other.types),
            values: self.values.or(other.values),
            macros: self.macros.or(other.macros),
        }
    }
}