use crate::error::{ErrParam, VmError, VmResult, code};
use crate::value::{INVALID_PROP, ObjId, PropId};
macro_rules! metaclasses {
($( $variant:ident $name:literal $version:literal $parent:ident; )*) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[allow(missing_docs)]
pub enum MetaKind {
$( $variant, )*
}
impl MetaKind {
pub const ALL: &'static [MetaKind] = &[ $( MetaKind::$variant, )* ];
pub const fn name(self) -> &'static str {
match self {
$( Self::$variant => $name, )*
}
}
pub const fn version(self) -> &'static str {
match self {
$( Self::$variant => $version, )*
}
}
#[allow(unreachable_patterns)]
pub const fn parent(self) -> Option<MetaKind> {
match self {
Self::Root => None,
$( Self::$variant => Some(MetaKind::$parent), )*
}
}
}
};
}
metaclasses! {
Root "root-object" "030004" Root;
ProgramObject "hexicon-object" "030005" Root;
IntClassMod "int-class-mod" "030000" Root;
BuiltinClass "intrinsic-class" "030001" Root;
String "string" "030008" Root;
Collection "collection" "030000" Root;
List "list" "030008" Collection;
Vector "vector" "030005" Collection;
Map "lookuptable" "030003" Collection;
WeakMap "weakreflookuptable" "030001" Map;
Iterator "iterator" "030001" Root;
IndexedIterator "indexed-iterator" "030000" Iterator;
MapIterator "lookuptable-iterator" "030000" Iterator;
Function "anon-func-ptr" "030000" Vector;
Decimal "bignumber" "030001" Root;
ByteArray "bytearray" "030002" Root;
CharacterSet "character-set" "030001" Root;
Date "date" "030000" Root;
Dictionary "dictionary2" "030001" Root;
CompiledCode "dynamic-func" "030000" Root;
FileName "filename" "030000" Root;
File "file" "030003" Root;
StackFrame "stack-frame-desc" "030000" Root;
StackFrameRef "stack-frame-ref" "030000" Root;
GrammarRule "grammar-production" "030002" Root;
HttpRequest "http-request" "030001" Root;
HttpServer "http-server" "030000" Root;
Regex "regex-pattern" "030000" Root;
StringBuilder "stringbuffer" "030000" Root;
StringComparator "string-comparator" "030000" Root;
TemporaryFile "tempfile" "030000" Root;
TimeZone "timezone" "030000" Root;
}
impl MetaKind {
pub fn from_name(name: &str) -> Option<Self> {
Self::ALL.iter().copied().find(|kind| kind.name() == name)
}
}
#[derive(Debug, Clone)]
pub struct MetaEntry {
pub kind: MetaKind,
#[allow(dead_code)]
pub image_name: String,
pub method_props: Vec<PropId>,
pub class_obj: ObjId,
min_prop: PropId,
by_prop: Vec<u16>,
}
impl MetaEntry {
fn new(kind: MetaKind, image_name: String, method_props: Vec<PropId>) -> Self {
let used = method_props.iter().copied().filter(|&p| p != INVALID_PROP);
let min_prop = used.clone().min().unwrap_or(INVALID_PROP);
let max_prop = used.max().unwrap_or(INVALID_PROP);
let mut by_prop = Vec::new();
if min_prop != INVALID_PROP {
by_prop = vec![0; (max_prop - min_prop) as usize + 1];
for (index, &prop) in method_props.iter().enumerate() {
if prop != INVALID_PROP {
by_prop[(prop - min_prop) as usize] = index as u16 + 1;
}
}
}
Self {
kind,
image_name,
method_props,
class_obj: ObjId::INVALID,
min_prop,
by_prop,
}
}
pub fn prop_range(&self) -> (PropId, usize) {
(self.min_prop, self.by_prop.len())
}
pub fn method_index(&self, prop: PropId) -> u16 {
if prop < self.min_prop {
return 0;
}
self.by_prop
.get((prop - self.min_prop) as usize)
.copied()
.unwrap_or(0)
}
pub fn method_prop(&self, method: u16) -> PropId {
match method {
0 => INVALID_PROP,
n => self
.method_props
.get(n as usize - 1)
.copied()
.unwrap_or(INVALID_PROP),
}
}
}
#[derive(Debug, Clone, Default)]
pub struct MetaTable {
entries: Vec<MetaEntry>,
by_kind: Vec<u16>,
}
fn split_version(id: &str) -> (&str, &str) {
id.split_once('/').unwrap_or((id, "000000"))
}
impl MetaTable {
pub fn new() -> Self {
Self {
entries: Vec::new(),
by_kind: vec![u16::MAX; MetaKind::ALL.len()],
}
}
pub fn add(&mut self, image_name: &str, method_props: Vec<PropId>) -> VmResult<()> {
let (name, version) = split_version(image_name);
let Some(kind) = MetaKind::from_name(name) else {
return Err(VmError::with(
code::UNKNOWN_METACLASS,
vec![ErrParam::Str(image_name.to_owned())],
));
};
if version > kind.version() {
return Err(VmError::with(
code::METACLASS_TOO_OLD,
vec![
ErrParam::Str(image_name.to_owned()),
ErrParam::Str(kind.version().to_owned()),
],
));
}
self.push(kind, image_name.to_owned(), method_props);
Ok(())
}
pub fn add_if_new(&mut self, kind: MetaKind) {
if self.index_of(kind).is_none() {
let name = format!("{}/{}", kind.name(), kind.version());
self.push(kind, name, Vec::new());
}
}
fn push(&mut self, kind: MetaKind, image_name: String, method_props: Vec<PropId>) {
if self.by_kind[kind as usize] == u16::MAX {
self.by_kind[kind as usize] = self.entries.len() as u16;
}
self.entries
.push(MetaEntry::new(kind, image_name, method_props));
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn get(&self, index: usize) -> Option<&MetaEntry> {
self.entries.get(index)
}
pub fn get_mut(&mut self, index: usize) -> Option<&mut MetaEntry> {
self.entries.get_mut(index)
}
pub fn index_of(&self, kind: MetaKind) -> Option<usize> {
match self.by_kind[kind as usize] {
u16::MAX => None,
index => Some(index as usize),
}
}
pub fn entry(&self, kind: MetaKind) -> Option<&MetaEntry> {
self.index_of(kind).map(|index| &self.entries[index])
}
pub fn method_index(&self, kind: MetaKind, prop: PropId) -> u16 {
self.entry(kind).map_or(0, |entry| entry.method_index(prop))
}
pub fn class_obj(&self, kind: MetaKind) -> ObjId {
self.entry(kind).map_or(ObjId::INVALID, |e| e.class_obj)
}
}