use crate::{
libs::core::{
core_lib_id::CoreLibId,
type_id::{CoreLibBaseTypeId, CoreLibTypeId, CoreLibVariantTypeId},
value_id::CoreLibValueId,
},
random::RandomState,
types::type_definition::callable::CallableTypeDefinition,
values::{
core_value::CoreValue,
core_values::{
callable::{CallableBody, error::CallableError},
map::Map,
},
value::Value,
value_container::ValueContainer,
},
};
pub mod core_lib_id;
pub mod type_id;
mod type_match;
pub mod value_id;
use crate::{
prelude::*,
types::{r#type::Type, type_definition::callable::CallableKind},
values::core_values::callable::CoreStub,
};
use indexmap::IndexMap;
use log::info;
use strum::IntoEnumIterator;
#[derive(Debug)]
pub struct CoreLibraryValues {
print: Value,
panic: Value,
}
impl Default for CoreLibraryValues {
fn default() -> Self {
CoreLibraryValues {
print: Value::callable(
Some("print".to_string()),
CallableTypeDefinition {
kind: CallableKind::Function,
parameter_types: vec![],
rest_parameter_type: Some((
Some("values".to_string()),
Box::new(Type::core(CoreLibBaseTypeId::Unknown)),
)),
return_type: None,
yeet_type: None,
},
CallableBody::Native(Self::print_impl),
),
panic: Value::callable(
Some("panic".to_string()),
CallableTypeDefinition {
kind: CallableKind::Function,
parameter_types: vec![],
rest_parameter_type: Some((
Some("values".to_string()),
Box::new(Type::core(CoreLibBaseTypeId::Unknown)),
)),
return_type: None,
yeet_type: None,
},
CallableBody::CoreStub(CoreStub::Panic),
),
}
}
}
impl CoreLibraryValues {
pub fn get_by_id(&self, id: &CoreLibValueId) -> &Value {
match id {
CoreLibValueId::Print => &self.print,
CoreLibValueId::Panic => &self.panic,
}
}
gen fn iterate(&self) -> (CoreLibValueId, &Value) {
for id in CoreLibValueId::iter() {
yield (id, self.get_by_id(&id));
}
}
pub fn panic_impl(
_args: &[ValueContainer],
) -> Result<Option<ValueContainer>, CallableError> {
unreachable!(
"Panic called from core library. This should be handled by the runtime."
);
}
fn print_impl(
mut args: &[ValueContainer],
) -> Result<Option<ValueContainer>, CallableError> {
let mut output = String::new();
if let Some(ValueContainer::Local(Value {
inner: CoreValue::Text(text),
..
})) = args.first()
{
output.push_str(&text.0);
args = &args[1..];
if !args.is_empty() {
output.push(' ');
}
}
#[cfg(feature = "decompiler")]
let args_string = args
.iter()
.map(|v| {
crate::decompiler::decompile_value(
v,
crate::decompiler::DecompileOptions::colorized(),
)
})
.collect::<Vec<_>>()
.join(" ");
#[cfg(not(feature = "decompiler"))]
let args_string = args
.iter()
.map(|v| v.to_string())
.collect::<Vec<_>>()
.join(" ");
output.push_str(&args_string);
#[cfg(feature = "std")]
println!("[PRINT] {}", output);
info!("[PRINT] {}", output);
Ok(None)
}
}
#[derive(Debug)]
pub struct CoreLibraryTypes(IndexMap<CoreLibTypeId, Value, RandomState>);
impl Default for CoreLibraryTypes {
fn default() -> Self {
Self(Self::core_lib_types().collect())
}
}
impl CoreLibraryTypes {
pub fn get_by_id(&self, id: &CoreLibTypeId) -> &Value {
self.0.get(id).expect("Core library type not found")
}
fn core_lib_types() -> impl Iterator<Item = (CoreLibTypeId, Value)> {
gen {
for id in CoreLibBaseTypeId::iter() {
yield Self::create_type(CoreLibTypeId::Base(id));
for variant_id in CoreLibVariantTypeId::variant_ids(&id) {
yield Self::create_type(CoreLibTypeId::Variant(variant_id));
}
}
}
}
gen fn iterate(&self) -> (CoreLibTypeId, &Value) {
for (id, value) in &self.0 {
yield (*id, value);
}
}
fn create_type(id: CoreLibTypeId) -> (CoreLibTypeId, Value) {
(id, Value::from(CoreValue::Type(Type::core(id))))
}
}
#[derive(Debug)]
pub struct CoreLibrary {
values: CoreLibraryValues,
types: CoreLibraryTypes,
map: Value,
}
impl Default for CoreLibrary {
fn default() -> Self {
let values = CoreLibraryValues::default();
let types = CoreLibraryTypes::default();
let entries = values
.iterate()
.map(|(id, value)| (CoreLibId::Value(id), value.clone()))
.chain(
types
.iterate()
.map(|(id, value)| (CoreLibId::Type(id), value.clone())),
)
.map(|(id, value)| (id.to_string(), ValueContainer::from(value)))
.collect::<Vec<_>>();
CoreLibrary {
map: Value::from(Map::from(entries)),
types,
values,
}
}
}
impl CoreLibrary {
pub fn value_or_type_by_id(&self, id: CoreLibId) -> &Value {
match id {
CoreLibId::Value(id) => self.values.get_by_id(&id),
CoreLibId::Type(id) => self.types.get_by_id(&id),
CoreLibId::CoreMap => &self.map,
}
}
pub fn map(&self) -> &Map {
self.map.try_as().unwrap()
}
pub fn value_by_id(&self, id: &CoreLibValueId) -> &Value {
self.values.get_by_id(id)
}
pub fn type_by_id(&self, id: &CoreLibTypeId) -> &Value {
self.types.get_by_id(id)
}
}
#[cfg(test)]
mod tests {
use crate::{
libs::core::core_lib_id::CoreLibIdIndex, shared_values::PointerAddress,
};
use super::*;
#[test]
fn debug() {
flexi_logger::init();
info!("{}", CoreLibrary::default().map());
}
#[test]
#[ignore]
#[cfg(feature = "std")]
fn create_core_type_ts_mapping() {
println!("export const CoreLibTypeId = {{");
for base_id in CoreLibBaseTypeId::iter() {
println!(" {}: {},", base_id, CoreLibIdIndex::from(base_id).0);
for variant_id in CoreLibVariantTypeId::variant_ids(&base_id) {
println!(
" {}_{}: {},",
base_id,
variant_id.variant_name(),
CoreLibIdIndex::from(variant_id).0
);
}
}
println!("}} as const;");
}
}