Skip to main content

model_core/
metamodel.rs

1//! Fine-grained kinds. [`EntityKind`] stays the 15-way *archetype* every
2//! analysis understands; a [`KindId`] says which finer kind an entity is
3//! (`record`, `annotation_type`, `enum_constant`...). The [`Metamodel`]
4//! table, carried by the model, maps each kind to its archetype, a trait
5//! mask and, optionally, the name of the FM3 class it corresponds to.
6
7use crate::entity::EntityKind;
8
9/// Index of a kind in its [`Metamodel`]; one byte in the entity row, so a
10/// model holds at most 256 kinds.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
12pub struct KindId(pub(crate) u8);
13
14impl KindId {
15    pub fn index(self) -> usize {
16        self.0 as usize
17    }
18
19    /// Default kind of an archetype: its own, unrefined kind.
20    pub fn of(archetype: EntityKind) -> KindId {
21        KindId(archetype as u8)
22    }
23}
24
25impl From<EntityKind> for KindId {
26    fn from(archetype: EntityKind) -> Self {
27        KindId::of(archetype)
28    }
29}
30
31/// Bit set of traits (composable capabilities); bit meanings belong to
32/// whoever defines the traits, not to this crate.
33#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
34pub struct TraitMask(pub u64);
35
36impl TraitMask {
37    pub const EMPTY: TraitMask = TraitMask(0);
38
39    pub fn contains(self, other: TraitMask) -> bool {
40        self.0 & other.0 == other.0
41    }
42}
43
44/// What the metamodel knows about one kind.
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct KindInfo {
47    pub name: String,
48    pub archetype: EntityKind,
49    pub traits: TraitMask,
50    /// FM3 class this kind maps to (`Famix-Java-Entities.Record`...), if any.
51    pub fm3: Option<String>,
52    /// Name of the GraphQL concept (object type) of this kind (`Parameter`,
53    /// `TsInterface`...), if its language declares one. Data, not code: the
54    /// GraphQL server builds one type per named concept.
55    pub graphql_type: Option<String>,
56    /// Name of the root field listing this kind (`parameters`); the lookup by
57    /// key is `<singular>ByKey`, derived by the server from `graphql_type`.
58    pub graphql_root: Option<String>,
59}
60
61/// Kinds of a model. Ids `0..15` are the archetypes' default kinds
62/// (`KindId::of`); finer kinds are defined after them, by name.
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct Metamodel {
65    kinds: Vec<KindInfo>,
66}
67
68impl Default for Metamodel {
69    fn default() -> Self {
70        Metamodel {
71            kinds: EntityKind::ALL
72                .iter()
73                .map(|&a| KindInfo {
74                    name: a.as_str().to_string(),
75                    archetype: a,
76                    traits: TraitMask::EMPTY,
77                    fm3: None,
78                    graphql_type: None,
79                    graphql_root: None,
80                })
81                .collect(),
82        }
83    }
84}
85
86impl Metamodel {
87    /// Kind named `name`, defined with `archetype` if absent (an existing
88    /// kind is left as is). A full table (256 kinds) falls back to the
89    /// archetype's default kind, so extraction never fails on it.
90    pub fn define(
91        &mut self,
92        name: &str,
93        archetype: EntityKind,
94        traits: TraitMask,
95        fm3: Option<&str>,
96    ) -> KindId {
97        if let Some(id) = self.find(name) {
98            return id;
99        }
100        match u8::try_from(self.kinds.len()) {
101            Ok(i) => {
102                self.kinds.push(KindInfo {
103                    name: name.to_string(),
104                    archetype,
105                    traits,
106                    fm3: fm3.map(str::to_string),
107                    graphql_type: None,
108                    graphql_root: None,
109                });
110                KindId(i)
111            }
112            Err(_) => KindId::of(archetype),
113        }
114    }
115
116    /// Sets the trait mask of an existing kind (how a frontend gives the
117    /// default archetype kinds their traits). Returns false for an unknown id.
118    pub fn set_traits(&mut self, id: KindId, traits: TraitMask) -> bool {
119        match self.kinds.get_mut(id.index()) {
120            Some(k) => {
121                k.traits = traits;
122                true
123            }
124            None => false,
125        }
126    }
127
128    /// Declares the GraphQL concept name and root field of a kind defined
129    /// beyond the archetypes' defaults (those keep the archetype types).
130    /// Returns false for an archetype default or an unknown id.
131    pub fn set_concept(
132        &mut self,
133        id: KindId,
134        graphql_type: Option<&str>,
135        graphql_root: Option<&str>,
136    ) -> bool {
137        if id.index() < EntityKind::ALL.len() {
138            return false;
139        }
140        match self.kinds.get_mut(id.index()) {
141            Some(k) => {
142                k.graphql_type = graphql_type.map(str::to_string);
143                k.graphql_root = graphql_root.map(str::to_string);
144                true
145            }
146            None => false,
147        }
148    }
149
150    pub fn find(&self, name: &str) -> Option<KindId> {
151        self.kinds
152            .iter()
153            .position(|k| k.name == name)
154            .map(|i| KindId(i as u8))
155    }
156
157    pub fn get(&self, id: KindId) -> Option<&KindInfo> {
158        self.kinds.get(id.index())
159    }
160
161    /// Archetype of `id`; kinds of another model fall back to `Variable`.
162    pub fn archetype(&self, id: KindId) -> EntityKind {
163        self.get(id).map_or(EntityKind::Variable, |k| k.archetype)
164    }
165
166    pub fn len(&self) -> usize {
167        self.kinds.len()
168    }
169
170    pub fn is_empty(&self) -> bool {
171        self.kinds.is_empty()
172    }
173
174    /// Every kind with its id, archetype defaults first.
175    pub fn iter(&self) -> impl ExactSizeIterator<Item = (KindId, &KindInfo)> {
176        self.kinds
177            .iter()
178            .enumerate()
179            .map(|(i, k)| (KindId(i as u8), k))
180    }
181
182    /// Kinds defined beyond the archetypes' defaults.
183    pub(crate) fn custom(&self) -> impl Iterator<Item = &KindInfo> {
184        self.kinds.iter().skip(EntityKind::ALL.len())
185    }
186}