lust/vm/
api.rs

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            exported_type_stubs: Vec::new(),
106        };
107        vm.jit.enabled = vm.jit.enabled && config.jit_enabled();
108        vm.trait_impls
109            .insert(("int".to_string(), "ToString".to_string()), true);
110        vm.trait_impls
111            .insert(("float".to_string(), "ToString".to_string()), true);
112        vm.trait_impls
113            .insert(("string".to_string(), "ToString".to_string()), true);
114        vm.trait_impls
115            .insert(("bool".to_string(), "ToString".to_string()), true);
116        vm.trait_impls
117            .insert(("int".to_string(), "Hashable".to_string()), true);
118        vm.trait_impls
119            .insert(("float".to_string(), "Hashable".to_string()), true);
120        vm.trait_impls
121            .insert(("string".to_string(), "Hashable".to_string()), true);
122        vm.trait_impls
123            .insert(("bool".to_string(), "Hashable".to_string()), true);
124        super::corelib::install_core_builtins(&mut vm);
125        #[cfg(feature = "std")]
126        for (name, func) in super::stdlib::create_stdlib(config) {
127            vm.register_native(name, func);
128        }
129
130        vm
131    }
132
133    pub(super) fn observe_value(&mut self, value: &Value) {
134        self.cycle_collector.register_value(value);
135    }
136
137    pub(super) fn maybe_collect_cycles(&mut self) {
138        let mut collector = mem::take(&mut self.cycle_collector);
139        collector.maybe_collect(self);
140        self.cycle_collector = collector;
141    }
142
143    pub fn with_current<F, R>(f: F) -> CoreResult<R, String>
144    where
145        F: FnOnce(&mut VM) -> CoreResult<R, String>,
146    {
147        let ptr_opt = super::with_vm_stack(|stack| stack.last().copied());
148        if let Some(ptr) = ptr_opt {
149            let vm = unsafe { &mut *ptr };
150            f(vm)
151        } else {
152            Err("task API requires a running VM".to_string())
153        }
154    }
155
156    pub fn load_functions(&mut self, functions: Vec<Function>) {
157        self.functions = functions;
158    }
159
160    pub fn register_structs(&mut self, defs: &HashMap<String, StructDef>) {
161        for (name, def) in defs {
162            let field_names: Vec<Rc<String>> = def
163                .fields
164                .iter()
165                .map(|field| Rc::new(field.name.clone()))
166                .collect();
167            let field_storage: Vec<FieldStorage> = def
168                .fields
169                .iter()
170                .map(|field| match field.ownership {
171                    FieldOwnership::Weak => FieldStorage::Weak,
172                    FieldOwnership::Strong => FieldStorage::Strong,
173                })
174                .collect();
175            let field_types: Vec<Type> = def.fields.iter().map(|field| field.ty.clone()).collect();
176            let weak_targets: Vec<Option<Type>> = def
177                .fields
178                .iter()
179                .map(|field| field.weak_target.clone())
180                .collect();
181            let layout = Rc::new(StructLayout::new(
182                def.name.clone(),
183                field_names,
184                field_storage,
185                field_types,
186                weak_targets,
187            ));
188            self.struct_metadata.insert(
189                name.clone(),
190                RuntimeStructInfo {
191                    layout: layout.clone(),
192                },
193            );
194            if let Some(simple) = name.rsplit('.').next() {
195                self.struct_metadata.insert(
196                    simple.to_string(),
197                    RuntimeStructInfo {
198                        layout: layout.clone(),
199                    },
200                );
201            }
202        }
203    }
204
205    pub fn instantiate_struct(
206        &self,
207        struct_name: &str,
208        fields: Vec<(Rc<String>, Value)>,
209    ) -> Result<Value> {
210        let info =
211            self.struct_metadata
212                .get(struct_name)
213                .ok_or_else(|| LustError::RuntimeError {
214                    message: format!("Unknown struct '{}'", struct_name),
215                })?;
216        Self::build_struct_value(struct_name, info, fields)
217    }
218
219    fn build_struct_value(
220        struct_name: &str,
221        info: &RuntimeStructInfo,
222        mut fields: Vec<(Rc<String>, Value)>,
223    ) -> Result<Value> {
224        let layout = info.layout.clone();
225        let field_count = layout.field_names().len();
226        let mut ordered = vec![Value::Nil; field_count];
227        let mut filled = vec![false; field_count];
228        for (field_name, field_value) in fields.drain(..) {
229            let index_opt = layout
230                .index_of_rc(&field_name)
231                .or_else(|| layout.index_of_str(field_name.as_str()));
232            let index = match index_opt {
233                Some(i) => i,
234                None => {
235                    return Err(LustError::RuntimeError {
236                        message: format!("Struct '{}' has no field '{}'", struct_name, field_name),
237                    })
238                }
239            };
240            let canonical = layout
241                .canonicalize_field_value(index, field_value)
242                .map_err(|msg| LustError::RuntimeError { message: msg })?;
243            ordered[index] = canonical;
244            filled[index] = true;
245        }
246
247        if filled.iter().any(|slot| !*slot) {
248            let missing: Vec<String> = layout
249                .field_names()
250                .iter()
251                .enumerate()
252                .filter_map(|(idx, name)| (!filled[idx]).then(|| (**name).clone()))
253                .collect();
254            return Err(LustError::RuntimeError {
255                message: format!(
256                    "Struct '{}' is missing required field(s): {}",
257                    struct_name,
258                    missing.join(", ")
259                ),
260            });
261        }
262
263        Ok(Value::Struct {
264            name: struct_name.to_string(),
265            layout,
266            fields: Rc::new(RefCell::new(ordered)),
267        })
268    }
269
270    pub fn register_trait_impl(&mut self, type_name: String, trait_name: String) {
271        self.trait_impls.insert((type_name, trait_name), true);
272    }
273
274    pub fn register_native(&mut self, name: impl Into<String>, value: Value) {
275        let name = name.into();
276        match value {
277            Value::NativeFunction(_) => {
278                let cloned = value.clone();
279                self.natives.insert(name.clone(), value);
280                self.globals.insert(name, cloned);
281            }
282
283            other => {
284                self.globals.insert(name, other);
285            }
286        }
287    }
288
289    pub(crate) fn push_export_prefix(&mut self, crate_name: &str, include_extern_namespace: bool) {
290        let sanitized = crate_name.replace('-', "_");
291        let prefix = if include_extern_namespace {
292            format!("externs.{sanitized}")
293        } else {
294            sanitized
295        };
296        self.export_prefix_stack.push(prefix);
297    }
298
299    pub(crate) fn pop_export_prefix(&mut self) {
300        self.export_prefix_stack.pop();
301    }
302
303    fn current_export_prefix(&self) -> Option<&str> {
304        self.export_prefix_stack.last().map(|s| s.as_str())
305    }
306
307    pub fn export_prefix(&self) -> Option<String> {
308        self.current_export_prefix().map(|s| s.to_string())
309    }
310
311    pub fn register_exported_native<F>(&mut self, export: NativeExport, func: F)
312    where
313        F: Fn(&[Value]) -> CoreResult<NativeCallResult, String> + 'static,
314    {
315        let mut export = export;
316        if let Some(prefix) = self.current_export_prefix() {
317            if !export.name.starts_with("externs.") {
318                let name = if export.name.is_empty() {
319                    prefix.to_string()
320                } else {
321                    format!("{prefix}.{}", export.name)
322                };
323                export.name = name;
324            }
325        }
326        let name = export.name.clone();
327        self.exported_natives.push(export);
328        let native = Value::NativeFunction(Rc::new(func));
329        self.register_native(name, native);
330    }
331
332    pub fn register_type_stubs(&mut self, stubs: Vec<ModuleStub>) {
333        if stubs.is_empty() {
334            return;
335        }
336        self.exported_type_stubs.extend(stubs);
337    }
338
339    pub fn take_type_stubs(&mut self) -> Vec<ModuleStub> {
340        mem::take(&mut self.exported_type_stubs)
341    }
342
343    pub fn exported_natives(&self) -> &[NativeExport] {
344        &self.exported_natives
345    }
346
347    pub fn take_exported_natives(&mut self) -> Vec<NativeExport> {
348        mem::take(&mut self.exported_natives)
349    }
350
351    pub fn clear_native_functions(&mut self) {
352        self.natives.clear();
353        self.exported_type_stubs.clear();
354    }
355
356    pub fn get_global(&self, name: &str) -> Option<Value> {
357        if let Some(value) = self.globals.get(name) {
358            Some(value.clone())
359        } else {
360            self.natives.get(name).cloned()
361        }
362    }
363
364    pub fn global_names(&self) -> Vec<String> {
365        self.globals.keys().cloned().collect()
366    }
367
368    pub fn globals_snapshot(&self) -> Vec<(String, Value)> {
369        self.globals
370            .iter()
371            .map(|(name, value)| (name.clone(), value.clone()))
372            .collect()
373    }
374
375    pub fn set_global(&mut self, name: impl Into<String>, value: Value) {
376        let name = name.into();
377        self.observe_value(&value);
378        self.globals.insert(name.clone(), value);
379        self.natives.remove(&name);
380        self.maybe_collect_cycles();
381    }
382
383    pub fn call(&mut self, function_name: &str, args: Vec<Value>) -> Result<Value> {
384        let func_idx = self
385            .functions
386            .iter()
387            .position(|f| f.name == function_name)
388            .ok_or_else(|| LustError::RuntimeError {
389                message: format!("Function not found: {}", function_name),
390            })?;
391        let mut frame = CallFrame {
392            function_idx: func_idx,
393            ip: 0,
394            registers: array::from_fn(|_| Value::Nil),
395            base_register: 0,
396            return_dest: None,
397            upvalues: Vec::new(),
398        };
399        let func = &self.functions[func_idx];
400        if args.len() != func.param_count as usize {
401            return Err(LustError::RuntimeError {
402                message: format!(
403                    "Function {} expects {} arguments, got {}",
404                    function_name,
405                    func.param_count,
406                    args.len()
407                ),
408            });
409        }
410
411        for (i, arg) in args.into_iter().enumerate() {
412            frame.registers[i] = arg;
413        }
414
415        self.call_stack.push(frame);
416        match self.run() {
417            Ok(v) => Ok(v),
418            Err(e) => Err(self.annotate_runtime_error(e)),
419        }
420    }
421
422    pub fn function_value(&self, function_name: &str) -> Option<Value> {
423        let canonical = if function_name.contains("::") {
424            function_name.replace("::", ".")
425        } else {
426            function_name.to_string()
427        };
428        self.functions
429            .iter()
430            .position(|f| f.name == canonical)
431            .map(Value::Function)
432    }
433
434    pub fn function_name(&self, index: usize) -> Option<&str> {
435        self.functions.get(index).map(|f| f.name.as_str())
436    }
437
438    pub fn fail_task_handle(&mut self, handle: TaskHandle, error: LustError) -> Result<()> {
439        let task_id = self.task_id_from_handle(handle)?;
440        let mut task =
441            self.task_manager
442                .detach(task_id)
443                .ok_or_else(|| LustError::RuntimeError {
444                    message: format!("Invalid task handle {}", handle.id()),
445                })?;
446        task.state = TaskState::Failed;
447        task.error = Some(error.clone());
448        task.last_yield = None;
449        task.last_result = None;
450        task.yield_dest = None;
451        task.call_stack.clear();
452        task.pending_return_value = None;
453        task.pending_return_dest = None;
454        self.task_manager.attach(task);
455        Err(error)
456    }
457}