use crate::entity::EntityKind;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct KindId(pub(crate) u8);
impl KindId {
pub fn index(self) -> usize {
self.0 as usize
}
pub fn of(archetype: EntityKind) -> KindId {
KindId(archetype as u8)
}
}
impl From<EntityKind> for KindId {
fn from(archetype: EntityKind) -> Self {
KindId::of(archetype)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct TraitMask(pub u64);
impl TraitMask {
pub const EMPTY: TraitMask = TraitMask(0);
pub fn contains(self, other: TraitMask) -> bool {
self.0 & other.0 == other.0
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KindInfo {
pub name: String,
pub archetype: EntityKind,
pub traits: TraitMask,
pub fm3: Option<String>,
pub graphql_type: Option<String>,
pub graphql_root: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Metamodel {
kinds: Vec<KindInfo>,
}
impl Default for Metamodel {
fn default() -> Self {
Metamodel {
kinds: EntityKind::ALL
.iter()
.map(|&a| KindInfo {
name: a.as_str().to_string(),
archetype: a,
traits: TraitMask::EMPTY,
fm3: None,
graphql_type: None,
graphql_root: None,
})
.collect(),
}
}
}
impl Metamodel {
pub fn define(
&mut self,
name: &str,
archetype: EntityKind,
traits: TraitMask,
fm3: Option<&str>,
) -> KindId {
if let Some(id) = self.find(name) {
return id;
}
match u8::try_from(self.kinds.len()) {
Ok(i) => {
self.kinds.push(KindInfo {
name: name.to_string(),
archetype,
traits,
fm3: fm3.map(str::to_string),
graphql_type: None,
graphql_root: None,
});
KindId(i)
}
Err(_) => KindId::of(archetype),
}
}
pub fn set_traits(&mut self, id: KindId, traits: TraitMask) -> bool {
match self.kinds.get_mut(id.index()) {
Some(k) => {
k.traits = traits;
true
}
None => false,
}
}
pub fn set_concept(
&mut self,
id: KindId,
graphql_type: Option<&str>,
graphql_root: Option<&str>,
) -> bool {
if id.index() < EntityKind::ALL.len() {
return false;
}
match self.kinds.get_mut(id.index()) {
Some(k) => {
k.graphql_type = graphql_type.map(str::to_string);
k.graphql_root = graphql_root.map(str::to_string);
true
}
None => false,
}
}
pub fn find(&self, name: &str) -> Option<KindId> {
self.kinds
.iter()
.position(|k| k.name == name)
.map(|i| KindId(i as u8))
}
pub fn get(&self, id: KindId) -> Option<&KindInfo> {
self.kinds.get(id.index())
}
pub fn archetype(&self, id: KindId) -> EntityKind {
self.get(id).map_or(EntityKind::Variable, |k| k.archetype)
}
pub fn len(&self) -> usize {
self.kinds.len()
}
pub fn is_empty(&self) -> bool {
self.kinds.is_empty()
}
pub fn iter(&self) -> impl ExactSizeIterator<Item = (KindId, &KindInfo)> {
self.kinds
.iter()
.enumerate()
.map(|(i, k)| (KindId(i as u8), k))
}
pub(crate) fn custom(&self) -> impl Iterator<Item = &KindInfo> {
self.kinds.iter().skip(EntityKind::ALL.len())
}
}