1use crate::{
3 libs::core::{
4 core_lib_id::CoreLibId,
5 type_id::{CoreLibBaseTypeId, CoreLibTypeId, CoreLibVariantTypeId},
6 value_id::CoreLibValueId,
7 },
8 random::RandomState,
9 types::type_definition::callable::CallableTypeDefinition,
10 values::{
11 core_value::CoreValue,
12 core_values::{
13 callable::{CallableBody, error::CallableError},
14 map::Map,
15 },
16 value::Value,
17 value_container::ValueContainer,
18 },
19};
20
21pub mod core_lib_id;
22pub mod type_id;
23mod type_match;
24pub mod value_id;
25
26use crate::{
27 prelude::*,
28 types::{r#type::Type, type_definition::callable::CallableKind},
29 values::core_values::callable::CoreStub,
30};
31use indexmap::IndexMap;
32use log::info;
33use strum::IntoEnumIterator;
34
35#[derive(Debug)]
36pub struct CoreLibraryValues {
37 print: Value,
38 panic: Value,
39}
40
41impl Default for CoreLibraryValues {
42 fn default() -> Self {
43 CoreLibraryValues {
44 print: Value::callable(
45 Some("print".to_string()),
46 CallableTypeDefinition {
47 kind: CallableKind::Function,
48 parameter_types: vec![],
49 rest_parameter_type: Some((
50 Some("values".to_string()),
51 Box::new(Type::core(CoreLibBaseTypeId::Unknown)),
52 )),
53 return_type: None,
54 yeet_type: None,
55 },
56 CallableBody::Native(Self::print_impl),
57 ),
58 panic: Value::callable(
59 Some("panic".to_string()),
60 CallableTypeDefinition {
61 kind: CallableKind::Function,
62 parameter_types: vec![],
63 rest_parameter_type: Some((
64 Some("values".to_string()),
65 Box::new(Type::core(CoreLibBaseTypeId::Unknown)),
66 )),
67 return_type: None,
68 yeet_type: None,
69 },
70 CallableBody::CoreStub(CoreStub::Panic),
71 ),
72 }
73 }
74}
75
76impl CoreLibraryValues {
77 pub fn get_by_id(&self, id: &CoreLibValueId) -> &Value {
79 match id {
80 CoreLibValueId::Print => &self.print,
81 CoreLibValueId::Panic => &self.panic,
82 }
83 }
84
85 gen fn iterate(&self) -> (CoreLibValueId, &Value) {
87 for id in CoreLibValueId::iter() {
88 yield (id, self.get_by_id(&id));
89 }
90 }
91
92 pub fn panic_impl(
93 _args: &[ValueContainer],
94 ) -> Result<Option<ValueContainer>, CallableError> {
95 unreachable!(
96 "Panic called from core library. This should be handled by the runtime."
97 );
98 }
99
100 fn print_impl(
101 mut args: &[ValueContainer],
102 ) -> Result<Option<ValueContainer>, CallableError> {
103 let mut output = String::new();
106
107 if let Some(ValueContainer::Local(Value {
109 inner: CoreValue::Text(text),
110 ..
111 })) = args.first()
112 {
113 output.push_str(&text.0);
114 args = &args[1..];
116 if !args.is_empty() {
118 output.push(' ');
119 }
120 }
121
122 #[cfg(feature = "decompiler")]
123 let args_string = args
124 .iter()
125 .map(|v| {
126 crate::decompiler::decompile_value(
127 v,
128 crate::decompiler::DecompileOptions::colorized(),
129 )
130 })
131 .collect::<Vec<_>>()
132 .join(" ");
133 #[cfg(not(feature = "decompiler"))]
134 let args_string = args
135 .iter()
136 .map(|v| v.to_string())
137 .collect::<Vec<_>>()
138 .join(" ");
139 output.push_str(&args_string);
140
141 #[cfg(feature = "std")]
142 println!("[PRINT] {}", output);
143 info!("[PRINT] {}", output);
144 Ok(None)
145 }
146}
147
148#[derive(Debug)]
149pub struct CoreLibraryTypes(IndexMap<CoreLibTypeId, Value, RandomState>);
150
151impl Default for CoreLibraryTypes {
152 fn default() -> Self {
153 Self(Self::core_lib_types().collect())
154 }
155}
156
157impl CoreLibraryTypes {
158 pub fn get_by_id(&self, id: &CoreLibTypeId) -> &Value {
160 self.0.get(id).expect("Core library type not found")
161 }
162
163 fn core_lib_types() -> impl Iterator<Item = (CoreLibTypeId, Value)> {
165 gen {
166 for id in CoreLibBaseTypeId::iter() {
167 yield Self::create_type(CoreLibTypeId::Base(id));
168 for variant_id in CoreLibVariantTypeId::variant_ids(&id) {
169 yield Self::create_type(CoreLibTypeId::Variant(variant_id));
170 }
171 }
172 }
173 }
174
175 gen fn iterate(&self) -> (CoreLibTypeId, &Value) {
177 for (id, value) in &self.0 {
178 yield (*id, value);
179 }
180 }
181
182 fn create_type(id: CoreLibTypeId) -> (CoreLibTypeId, Value) {
184 (id, Value::from(CoreValue::Type(Type::core(id))))
185 }
186}
187
188#[derive(Debug)]
189pub struct CoreLibrary {
190 values: CoreLibraryValues,
191 types: CoreLibraryTypes,
192 map: Value,
193}
194
195impl Default for CoreLibrary {
196 fn default() -> Self {
197 let values = CoreLibraryValues::default();
198 let types = CoreLibraryTypes::default();
199 let entries = values
200 .iterate()
201 .map(|(id, value)| (CoreLibId::Value(id), value.clone()))
202 .chain(
203 types
204 .iterate()
205 .map(|(id, value)| (CoreLibId::Type(id), value.clone())),
206 )
207 .map(|(id, value)| (id.to_string(), ValueContainer::from(value)))
208 .collect::<Vec<_>>();
209
210 CoreLibrary {
211 map: Value::from(Map::from(entries)),
212 types,
213 values,
214 }
215 }
216}
217
218impl CoreLibrary {
219 pub fn value_or_type_by_id(&self, id: CoreLibId) -> &Value {
221 match id {
222 CoreLibId::Value(id) => self.values.get_by_id(&id),
223 CoreLibId::Type(id) => self.types.get_by_id(&id),
224 CoreLibId::CoreMap => &self.map,
225 }
226 }
227
228 pub fn map(&self) -> &Map {
230 self.map.try_as().unwrap()
231 }
232
233 pub fn value_by_id(&self, id: &CoreLibValueId) -> &Value {
235 self.values.get_by_id(id)
236 }
237
238 pub fn type_by_id(&self, id: &CoreLibTypeId) -> &Value {
240 self.types.get_by_id(id)
241 }
242}
243
244#[cfg(test)]
245mod tests {
246 use crate::{
247 libs::core::core_lib_id::CoreLibIdIndex, shared_values::PointerAddress,
248 };
249
250 use super::*;
251
252 #[test]
253 fn debug() {
254 flexi_logger::init();
255 info!("{}", CoreLibrary::default().map());
256 }
257
258 #[test]
259 #[ignore]
260 #[cfg(feature = "std")]
261 fn create_core_type_ts_mapping() {
266 println!("export const CoreLibTypeId = {{");
267
268 for base_id in CoreLibBaseTypeId::iter() {
269 println!(" {}: {},", base_id, CoreLibIdIndex::from(base_id).0);
270 for variant_id in CoreLibVariantTypeId::variant_ids(&base_id) {
271 println!(
272 " {}_{}: {},",
273 base_id,
274 variant_id.variant_name(),
275 CoreLibIdIndex::from(variant_id).0
276 );
277 }
278 }
279
280 println!("}} as const;");
281 }
282}