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