1use super::*;
2use crate::ast::Type;
3use crate::config::LustConfig;
4use alloc::rc::Rc;
5use alloc::string::String;
6use alloc::vec::Vec;
7use core::result::Result as CoreResult;
8use core::{array, mem};
9
10#[derive(Debug, Clone)]
11pub struct NativeExportParam {
12 name: String,
13 ty: String,
14}
15
16impl NativeExportParam {
17 pub fn new(name: impl Into<String>, ty: impl Into<String>) -> Self {
18 Self {
19 name: name.into(),
20 ty: ty.into(),
21 }
22 }
23
24 pub fn name(&self) -> &str {
25 &self.name
26 }
27
28 pub fn ty(&self) -> &str {
29 &self.ty
30 }
31}
32
33#[derive(Debug, Clone)]
34pub struct NativeExport {
35 name: String,
36 params: Vec<NativeExportParam>,
37 return_type: String,
38 doc: Option<String>,
39}
40
41impl NativeExport {
42 pub fn new(
43 name: impl Into<String>,
44 params: Vec<NativeExportParam>,
45 return_type: impl Into<String>,
46 ) -> Self {
47 Self {
48 name: name.into(),
49 params,
50 return_type: return_type.into(),
51 doc: None,
52 }
53 }
54
55 pub fn with_doc(mut self, doc: impl Into<String>) -> Self {
56 self.doc = Some(doc.into());
57 self
58 }
59
60 pub fn name(&self) -> &str {
61 &self.name
62 }
63
64 pub fn params(&self) -> &[NativeExportParam] {
65 &self.params
66 }
67
68 pub fn return_type(&self) -> &str {
69 &self.return_type
70 }
71
72 pub fn doc(&self) -> Option<&str> {
73 self.doc.as_deref()
74 }
75}
76impl VM {
77 pub fn new() -> Self {
78 Self::with_config(&LustConfig::default())
79 }
80
81 pub fn with_config(config: &LustConfig) -> Self {
82 let mut vm = Self {
83 functions: Vec::new(),
84 natives: HashMap::new(),
85 globals: HashMap::new(),
86 call_stack: Vec::new(),
87 max_stack_depth: 1000,
88 pending_return_value: None,
89 pending_return_dest: None,
90 jit: JitState::new(),
91 trace_recorder: None,
92 side_trace_context: None,
93 skip_next_trace_record: false,
94 trait_impls: HashMap::new(),
95 struct_tostring_cache: HashMap::new(),
96 struct_metadata: HashMap::new(),
97 call_until_depth: None,
98 task_manager: TaskManager::new(),
99 current_task: None,
100 pending_task_signal: None,
101 last_task_signal: None,
102 cycle_collector: cycle::CycleCollector::new(),
103 exported_natives: Vec::new(),
104 export_prefix_stack: Vec::new(),
105 };
106 vm.jit.enabled = vm.jit.enabled && config.jit_enabled();
107 vm.trait_impls
108 .insert(("int".to_string(), "ToString".to_string()), true);
109 vm.trait_impls
110 .insert(("float".to_string(), "ToString".to_string()), true);
111 vm.trait_impls
112 .insert(("string".to_string(), "ToString".to_string()), true);
113 vm.trait_impls
114 .insert(("bool".to_string(), "ToString".to_string()), true);
115 vm.trait_impls
116 .insert(("int".to_string(), "Hashable".to_string()), true);
117 vm.trait_impls
118 .insert(("float".to_string(), "Hashable".to_string()), true);
119 vm.trait_impls
120 .insert(("string".to_string(), "Hashable".to_string()), true);
121 vm.trait_impls
122 .insert(("bool".to_string(), "Hashable".to_string()), true);
123 super::corelib::install_core_builtins(&mut vm);
124 #[cfg(feature = "std")]
125 for (name, func) in super::stdlib::create_stdlib(config) {
126 vm.register_native(name, func);
127 }
128
129 vm
130 }
131
132 pub(super) fn observe_value(&mut self, value: &Value) {
133 self.cycle_collector.register_value(value);
134 }
135
136 pub(super) fn maybe_collect_cycles(&mut self) {
137 let mut collector = mem::take(&mut self.cycle_collector);
138 collector.maybe_collect(self);
139 self.cycle_collector = collector;
140 }
141
142 pub fn with_current<F, R>(f: F) -> CoreResult<R, String>
143 where
144 F: FnOnce(&mut VM) -> CoreResult<R, String>,
145 {
146 let ptr_opt = super::with_vm_stack(|stack| stack.last().copied());
147 if let Some(ptr) = ptr_opt {
148 let vm = unsafe { &mut *ptr };
149 f(vm)
150 } else {
151 Err("task API requires a running VM".to_string())
152 }
153 }
154
155 pub fn load_functions(&mut self, functions: Vec<Function>) {
156 self.functions = functions;
157 }
158
159 pub fn register_structs(&mut self, defs: &HashMap<String, StructDef>) {
160 for (name, def) in defs {
161 let field_names: Vec<Rc<String>> = def
162 .fields
163 .iter()
164 .map(|field| Rc::new(field.name.clone()))
165 .collect();
166 let field_storage: Vec<FieldStorage> = def
167 .fields
168 .iter()
169 .map(|field| match field.ownership {
170 FieldOwnership::Weak => FieldStorage::Weak,
171 FieldOwnership::Strong => FieldStorage::Strong,
172 })
173 .collect();
174 let field_types: Vec<Type> = def.fields.iter().map(|field| field.ty.clone()).collect();
175 let weak_targets: Vec<Option<Type>> = def
176 .fields
177 .iter()
178 .map(|field| field.weak_target.clone())
179 .collect();
180 let layout = Rc::new(StructLayout::new(
181 def.name.clone(),
182 field_names,
183 field_storage,
184 field_types,
185 weak_targets,
186 ));
187 self.struct_metadata.insert(
188 name.clone(),
189 RuntimeStructInfo {
190 layout: layout.clone(),
191 },
192 );
193 if let Some(simple) = name.rsplit('.').next() {
194 self.struct_metadata.insert(
195 simple.to_string(),
196 RuntimeStructInfo {
197 layout: layout.clone(),
198 },
199 );
200 }
201 }
202 }
203
204 pub fn instantiate_struct(
205 &self,
206 struct_name: &str,
207 fields: Vec<(Rc<String>, Value)>,
208 ) -> Result<Value> {
209 let info =
210 self.struct_metadata
211 .get(struct_name)
212 .ok_or_else(|| LustError::RuntimeError {
213 message: format!("Unknown struct '{}'", struct_name),
214 })?;
215 Self::build_struct_value(struct_name, info, fields)
216 }
217
218 fn build_struct_value(
219 struct_name: &str,
220 info: &RuntimeStructInfo,
221 mut fields: Vec<(Rc<String>, Value)>,
222 ) -> Result<Value> {
223 let layout = info.layout.clone();
224 let field_count = layout.field_names().len();
225 let mut ordered = vec![Value::Nil; field_count];
226 let mut filled = vec![false; field_count];
227 for (field_name, field_value) in fields.drain(..) {
228 let index_opt = layout
229 .index_of_rc(&field_name)
230 .or_else(|| layout.index_of_str(field_name.as_str()));
231 let index = match index_opt {
232 Some(i) => i,
233 None => {
234 return Err(LustError::RuntimeError {
235 message: format!("Struct '{}' has no field '{}'", struct_name, field_name),
236 })
237 }
238 };
239 let canonical = layout
240 .canonicalize_field_value(index, field_value)
241 .map_err(|msg| LustError::RuntimeError { message: msg })?;
242 ordered[index] = canonical;
243 filled[index] = true;
244 }
245
246 if filled.iter().any(|slot| !*slot) {
247 let missing: Vec<String> = layout
248 .field_names()
249 .iter()
250 .enumerate()
251 .filter_map(|(idx, name)| (!filled[idx]).then(|| (**name).clone()))
252 .collect();
253 return Err(LustError::RuntimeError {
254 message: format!(
255 "Struct '{}' is missing required field(s): {}",
256 struct_name,
257 missing.join(", ")
258 ),
259 });
260 }
261
262 Ok(Value::Struct {
263 name: struct_name.to_string(),
264 layout,
265 fields: Rc::new(RefCell::new(ordered)),
266 })
267 }
268
269 pub fn register_trait_impl(&mut self, type_name: String, trait_name: String) {
270 self.trait_impls.insert((type_name, trait_name), true);
271 }
272
273 pub fn register_native(&mut self, name: impl Into<String>, value: Value) {
274 let name = name.into();
275 match value {
276 Value::NativeFunction(_) => {
277 let cloned = value.clone();
278 self.natives.insert(name.clone(), value);
279 self.globals.insert(name, cloned);
280 }
281
282 other => {
283 self.globals.insert(name, other);
284 }
285 }
286 }
287
288 pub(crate) fn push_export_prefix(&mut self, crate_name: &str) {
289 let sanitized = crate_name.replace('-', "_");
290 let prefix = format!("externs.{sanitized}");
291 self.export_prefix_stack.push(prefix);
292 }
293
294 pub(crate) fn pop_export_prefix(&mut self) {
295 self.export_prefix_stack.pop();
296 }
297
298 fn current_export_prefix(&self) -> Option<&str> {
299 self.export_prefix_stack.last().map(|s| s.as_str())
300 }
301
302 pub fn register_exported_native<F>(&mut self, export: NativeExport, func: F)
303 where
304 F: Fn(&[Value]) -> CoreResult<NativeCallResult, String> + 'static,
305 {
306 let mut export = export;
307 if let Some(prefix) = self.current_export_prefix() {
308 if !export.name.starts_with("externs.") {
309 let name = if export.name.is_empty() {
310 prefix.to_string()
311 } else {
312 format!("{prefix}.{}", export.name)
313 };
314 export.name = name;
315 }
316 }
317 let name = export.name.clone();
318 self.exported_natives.push(export);
319 let native = Value::NativeFunction(Rc::new(func));
320 self.register_native(name, native);
321 }
322
323 pub fn exported_natives(&self) -> &[NativeExport] {
324 &self.exported_natives
325 }
326
327 pub fn take_exported_natives(&mut self) -> Vec<NativeExport> {
328 mem::take(&mut self.exported_natives)
329 }
330
331 pub fn clear_native_functions(&mut self) {
332 self.natives.clear();
333 }
334
335 pub fn get_global(&self, name: &str) -> Option<Value> {
336 if let Some(value) = self.globals.get(name) {
337 Some(value.clone())
338 } else {
339 self.natives.get(name).cloned()
340 }
341 }
342
343 pub fn global_names(&self) -> Vec<String> {
344 self.globals.keys().cloned().collect()
345 }
346
347 pub fn globals_snapshot(&self) -> Vec<(String, Value)> {
348 self.globals
349 .iter()
350 .map(|(name, value)| (name.clone(), value.clone()))
351 .collect()
352 }
353
354 pub fn set_global(&mut self, name: impl Into<String>, value: Value) {
355 let name = name.into();
356 self.observe_value(&value);
357 self.globals.insert(name.clone(), value);
358 self.natives.remove(&name);
359 self.maybe_collect_cycles();
360 }
361
362 pub fn call(&mut self, function_name: &str, args: Vec<Value>) -> Result<Value> {
363 let func_idx = self
364 .functions
365 .iter()
366 .position(|f| f.name == function_name)
367 .ok_or_else(|| LustError::RuntimeError {
368 message: format!("Function not found: {}", function_name),
369 })?;
370 let mut frame = CallFrame {
371 function_idx: func_idx,
372 ip: 0,
373 registers: array::from_fn(|_| Value::Nil),
374 base_register: 0,
375 return_dest: None,
376 upvalues: Vec::new(),
377 };
378 let func = &self.functions[func_idx];
379 if args.len() != func.param_count as usize {
380 return Err(LustError::RuntimeError {
381 message: format!(
382 "Function {} expects {} arguments, got {}",
383 function_name,
384 func.param_count,
385 args.len()
386 ),
387 });
388 }
389
390 for (i, arg) in args.into_iter().enumerate() {
391 frame.registers[i] = arg;
392 }
393
394 self.call_stack.push(frame);
395 match self.run() {
396 Ok(v) => Ok(v),
397 Err(e) => Err(self.annotate_runtime_error(e)),
398 }
399 }
400
401 pub fn function_value(&self, function_name: &str) -> Option<Value> {
402 let canonical = if function_name.contains("::") {
403 function_name.replace("::", ".")
404 } else {
405 function_name.to_string()
406 };
407 self.functions
408 .iter()
409 .position(|f| f.name == canonical)
410 .map(Value::Function)
411 }
412
413 pub fn function_name(&self, index: usize) -> Option<&str> {
414 self.functions.get(index).map(|f| f.name.as_str())
415 }
416
417 pub fn fail_task_handle(&mut self, handle: TaskHandle, error: LustError) -> Result<()> {
418 let task_id = self.task_id_from_handle(handle)?;
419 let mut task =
420 self.task_manager
421 .detach(task_id)
422 .ok_or_else(|| LustError::RuntimeError {
423 message: format!("Invalid task handle {}", handle.id()),
424 })?;
425 task.state = TaskState::Failed;
426 task.error = Some(error.clone());
427 task.last_yield = None;
428 task.last_result = None;
429 task.yield_dest = None;
430 task.call_stack.clear();
431 task.pending_return_value = None;
432 task.pending_return_dest = None;
433 self.task_manager.attach(task);
434 Err(error)
435 }
436}