Skip to main content

model_core/
relation.rs

1use serde::{Deserialize, Serialize};
2
3/// Kind of a relation. Containment is not a relation: it is the entity's
4/// parent.
5#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
6#[serde(rename_all = "snake_case")]
7pub enum RelationKind {
8    Calls,
9    /// Any other use of a symbol (type in a signature, field access...).
10    References,
11    /// Subclassing (`extends`, superclass).
12    Inherits,
13    Implements,
14    Imports,
15    /// Typed entity (field, parameter, local, method return) to its declared
16    /// type.
17    DeclaredType,
18    /// Read or write of a variable (field, parameter, local); the site flags
19    /// say which ([`SiteFlags`]).
20    Accesses,
21    /// Method to an exception type it declares in its `throws` clause.
22    Throws,
23    /// Method to the method it overrides or implements.
24    Overrides,
25    /// Defined by an analysis or a plugin (`http`, `rpc`...).
26    #[serde(untagged)]
27    Other(String),
28}
29
30/// One byte per occurrence site, stored beside the range. Bits combine
31/// (`READ | WRITE` for `x += 1`); unknown bits are preserved.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
33pub struct SiteFlags(pub u8);
34
35impl SiteFlags {
36    pub const NONE: SiteFlags = SiteFlags(0);
37    /// The site reads the target (`accesses`).
38    pub const READ: SiteFlags = SiteFlags(1);
39    /// The site writes the target (`accesses`).
40    pub const WRITE: SiteFlags = SiteFlags(2);
41    /// The target is a receiver: `x` in `x.f()` or `x.f`, `this`, `super`.
42    pub const RECEIVER: SiteFlags = SiteFlags(4);
43
44    pub const fn contains(self, other: SiteFlags) -> bool {
45        self.0 & other.0 == other.0
46    }
47
48    pub const fn is_empty(self) -> bool {
49        self.0 == 0
50    }
51}
52
53impl std::ops::BitOr for SiteFlags {
54    type Output = SiteFlags;
55    fn bitor(self, o: SiteFlags) -> SiteFlags {
56        SiteFlags(self.0 | o.0)
57    }
58}
59
60impl std::ops::BitOrAssign for SiteFlags {
61    fn bitor_assign(&mut self, o: SiteFlags) {
62        self.0 |= o.0;
63    }
64}
65
66const FLAG_NAMES: [(SiteFlags, &str); 3] = [
67    (SiteFlags::READ, "read"),
68    (SiteFlags::WRITE, "write"),
69    (SiteFlags::RECEIVER, "receiver"),
70];
71
72impl SiteFlags {
73    /// Names of the set bits, in bit order (`read`, `write`, `receiver`).
74    pub fn names(self) -> impl Iterator<Item = &'static str> {
75        FLAG_NAMES
76            .into_iter()
77            .filter(move |(f, _)| self.contains(*f))
78            .map(|(_, n)| n)
79    }
80
81    /// Inverse of [`Self::names`]; `None` for an unknown name.
82    pub fn from_names<'a>(names: impl IntoIterator<Item = &'a str>) -> Option<SiteFlags> {
83        let mut out = SiteFlags::NONE;
84        for n in names {
85            out |= FLAG_NAMES.iter().find(|(_, x)| *x == n)?.0;
86        }
87        Some(out)
88    }
89}
90
91/// Who asserted a fact: lets analyses weigh syntactic guesses against
92/// compiler-grade SCIP data.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
94#[serde(rename_all = "snake_case")]
95pub enum Provenance {
96    /// Syntax only (tree-sitter); names may be unresolved.
97    TreeSitter,
98    /// Resolved by a SCIP indexer.
99    Scip,
100    /// A language-specific frontend (hand-written resolution).
101    Frontend,
102    /// Computed from the model by an analysis.
103    Derived,
104}
105
106/// Index of a relation in its [`crate::Model`].
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
108pub struct RelationId(pub(crate) u32);
109
110impl RelationId {
111    pub fn index(self) -> usize {
112        self.0 as usize
113    }
114
115    /// See [`crate::EntityId::from_index`].
116    pub fn from_index(index: u32) -> RelationId {
117        RelationId(index)
118    }
119}
120
121impl RelationKind {
122    /// Serialised name: `calls`, `references`..., or the custom name.
123    pub fn as_str(&self) -> &str {
124        match self {
125            RelationKind::Calls => "calls",
126            RelationKind::References => "references",
127            RelationKind::Inherits => "inherits",
128            RelationKind::Implements => "implements",
129            RelationKind::Imports => "imports",
130            RelationKind::DeclaredType => "declared_type",
131            RelationKind::Accesses => "accesses",
132            RelationKind::Throws => "throws",
133            RelationKind::Overrides => "overrides",
134            RelationKind::Other(s) => s,
135        }
136    }
137
138    /// Inverse of [`Self::as_str`].
139    pub fn from_name(name: &str) -> RelationKind {
140        match name {
141            "calls" => RelationKind::Calls,
142            "references" => RelationKind::References,
143            "inherits" => RelationKind::Inherits,
144            "implements" => RelationKind::Implements,
145            "imports" => RelationKind::Imports,
146            "declared_type" => RelationKind::DeclaredType,
147            "accesses" => RelationKind::Accesses,
148            "throws" => RelationKind::Throws,
149            "overrides" => RelationKind::Overrides,
150            other => RelationKind::Other(other.to_string()),
151        }
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use super::RelationKind;
158
159    #[test]
160    fn names_round_trip_as_in_json() {
161        for k in [
162            RelationKind::Calls,
163            RelationKind::References,
164            RelationKind::Inherits,
165            RelationKind::Implements,
166            RelationKind::Imports,
167            RelationKind::DeclaredType,
168            RelationKind::Accesses,
169            RelationKind::Throws,
170            RelationKind::Overrides,
171            RelationKind::Other("http".into()),
172        ] {
173            assert_eq!(RelationKind::from_name(k.as_str()), k);
174            let json = serde_json::to_string(&k).unwrap();
175            assert_eq!(json, format!("\"{}\"", k.as_str()));
176        }
177    }
178}