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