use crate::{
libs::core::{
core_lib_id::CoreLibId,
type_id::{CoreLibBaseTypeId, CoreLibTypeId, CoreLibVariantTypeId},
value_id::CoreLibValueId,
},
prelude::*,
random::RandomState,
types::type_definition::callable::CallableTypeDefinition,
values::{
core_value::CoreValue,
core_value_with_classification::CoreValueWithClassification,
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::{
libs::core::type_id::TOTAL_CORE_LIB_TYPE_COUNT,
runtime::Runtime,
traits::apply::{ApplyArgument, get_borrowed_apply_argument_values},
types::{r#type::Type, type_definition::callable::CallableKind},
utils::logger::log_info_with_tag,
values::core_values::{callable::CoreStub, endpoint::Endpoint},
};
use indexmap::IndexMap;
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,
requires_async: false,
parameters: vec![],
rest_parameter: Some((
Some("values".to_string()),
Box::new(Type::core(CoreLibBaseTypeId::Any)),
)),
return_type: None,
yeet_type: None,
},
CallableBody::native_sync(Self::print_impl),
Endpoint::LOCAL,
),
panic: Value::callable(
Some("panic".to_string()),
CallableTypeDefinition {
kind: CallableKind::Function,
requires_async: false,
parameters: vec![],
rest_parameter: Some((
Some("values".to_string()),
Box::new(Type::core(CoreLibBaseTypeId::Any)),
)),
return_type: None,
yeet_type: None,
},
CallableBody::CoreStub(CoreStub::Panic),
Endpoint::LOCAL,
),
}
}
}
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: Vec<ApplyArgument>,
_runtime: &Runtime,
) -> Result<(Option<ValueContainer>, Vec<ValueContainer>), CallableError>
{
let mut output = String::new();
if let Some(ValueContainer::Local(Value::Core(
CoreValueWithClassification {
inner: CoreValue::Text(text),
..
},
))) = args.first().map(|v| &v.value)
{
output.push_str(text.as_str());
if args.len() > 1 {
output.push(' ');
};
args.remove(0);
}
#[cfg(feature = "decompiler")]
let args_string = args
.iter()
.map(|v| {
crate::decompiler::ast_to_source_code::value_to_source_code(
&v.value,
crate::decompiler::DecompileOptions::colorized(),
)
})
.collect::<Vec<_>>()
.join(" ");
#[cfg(not(feature = "decompiler"))]
let args_string = args
.iter()
.map(|v| v.value.to_string())
.collect::<Vec<_>>()
.join(" ");
output.push_str(&args_string);
log_info_with_tag!("PRINT", "{}", output);
Ok((None, get_borrowed_apply_argument_values(args)))
}
}
#[derive(Debug)]
pub struct CoreLibraryTypes(IndexMap<CoreLibTypeId, Value, RandomState>);
impl Default for CoreLibraryTypes {
fn default() -> Self {
let mut map = IndexMap::with_capacity_and_hasher(
TOTAL_CORE_LIB_TYPE_COUNT as usize,
RandomState::default(),
);
map.extend(Self::core_lib_types());
Self(map)
}
}
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)));
CoreLibrary {
map: Value::from(Map::from_iter(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 super::*;
#[test]
fn debug() {
flexi_logger::init();
log::info!("{}", CoreLibrary::default().map());
}
#[test]
#[ignore]
#[cfg(feature = "std")]
fn create_core_type_ts_mapping() {
println!("export const CoreLibTypeId = {{");
use crate::libs::core::core_lib_id::CoreLibIdIndex;
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;");
}
}