polycomp 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1214 @@
1
+ use crate::diagnostics::PolyError;
2
+ use crate::ir::*;
3
+ use crate::jit::{JitAbiVal, JitCallbacks, JitEngine, is_jit_eligible};
4
+ use crate::lowering::{lower_function, lower_top_level};
5
+ use crate::optimizer::optimize_function;
6
+ use crate::resolver::{ModuleResolver, StaticCheckReport};
7
+ use crate::runtime::{
8
+ ClassInstance, GcStats, MemoryHeap, MemoryMode, StrHandle, Value, eval_builtin, make_heap,
9
+ };
10
+ use crate::bundle::IrBundle;
11
+ use rustc_hash::{FxHashMap, FxHashSet};
12
+ use std::path::{Path, PathBuf};
13
+
14
+ #[derive(Debug, Clone)]
15
+ pub struct RunConfig {
16
+ pub memory_mode: MemoryMode,
17
+ pub enable_jit: bool,
18
+ pub jit_threshold: u32,
19
+ pub trace_imports: bool,
20
+ pub capture_stdout: bool,
21
+ }
22
+
23
+ impl Default for RunConfig {
24
+ fn default() -> Self {
25
+ Self {
26
+ memory_mode: MemoryMode::TracingGc,
27
+ enable_jit: true,
28
+ jit_threshold: 1,
29
+ trace_imports: false,
30
+ capture_stdout: false,
31
+ }
32
+ }
33
+ }
34
+
35
+ #[derive(Debug, Clone, Default)]
36
+ pub struct RunStats {
37
+ pub modules_parsed: usize,
38
+ pub parsed_paths: Vec<PathBuf>,
39
+ pub functions_lowered: usize,
40
+ pub functions_jit_compiled: usize,
41
+ pub jit_invocations: usize,
42
+ pub vm_invocations: usize,
43
+ pub call_sites_resolved: usize,
44
+ pub gc_stats: GcStats,
45
+ }
46
+
47
+ pub struct RunOutcome {
48
+ pub return_value: Value,
49
+ pub formatted_return: String,
50
+ pub stdout: String,
51
+ pub stats: RunStats,
52
+ }
53
+
54
+ pub struct VmEngine {
55
+ pub resolver: ModuleResolver,
56
+ pub heap: Box<dyn MemoryHeap>,
57
+ pub jit: Option<JitEngine>,
58
+ pub config: RunConfig,
59
+ pub functions: Vec<IrFunction>,
60
+ pub fn_map: FxHashMap<(usize, String), FnId>,
61
+ pub call_sites: Vec<CallSite>,
62
+ pub call_counts: Vec<u32>,
63
+ pub top_level_ran: FxHashSet<usize>,
64
+ pub active_roots: Vec<Vec<Value>>,
65
+ pub stdout_sink: Option<String>,
66
+ pub stats: RunStats,
67
+ pub last_error: Option<PolyError>,
68
+ pub last_trap_code: Option<u32>,
69
+ }
70
+
71
+ impl VmEngine {
72
+ pub fn new(config: RunConfig) -> Result<Self, PolyError> {
73
+ let heap = make_heap(config.memory_mode);
74
+ let jit = if config.enable_jit {
75
+ Some(JitEngine::new(JitCallbacks {
76
+ call_site: rt_call_site,
77
+ call_fn: rt_call_fn,
78
+ call_builtin: rt_call_builtin,
79
+ set_trap: rt_set_trap,
80
+ })?)
81
+ } else {
82
+ None
83
+ };
84
+ let stdout_sink = if config.capture_stdout {
85
+ Some(String::new())
86
+ } else {
87
+ None
88
+ };
89
+ Ok(Self {
90
+ resolver: ModuleResolver::new(config.trace_imports),
91
+ heap,
92
+ jit,
93
+ config,
94
+ functions: Vec::new(),
95
+ fn_map: FxHashMap::default(),
96
+ call_sites: Vec::new(),
97
+ call_counts: Vec::new(),
98
+ top_level_ran: FxHashSet::default(),
99
+ active_roots: Vec::new(),
100
+ stdout_sink,
101
+ stats: RunStats::default(),
102
+ last_error: None,
103
+ last_trap_code: None,
104
+ })
105
+ }
106
+
107
+ pub fn run_entry(
108
+ &mut self,
109
+ entry_path: &Path,
110
+ entry_fn: &str,
111
+ args: &[Value],
112
+ ) -> Result<RunOutcome, PolyError> {
113
+ let entry_mod_id = self.resolver.load_module(entry_path)?;
114
+ self.run_module_top_level_if_needed(entry_mod_id)?;
115
+
116
+ let fn_id = self.ensure_function_compiled(entry_mod_id, entry_fn)?;
117
+ let ret = self.invoke_fn(fn_id, args)?;
118
+
119
+ self.stats.modules_parsed = self.resolver.stats.modules_parsed;
120
+ self.stats.parsed_paths = self.resolver.stats.parsed_paths.clone();
121
+ self.stats.gc_stats = self.heap.stats();
122
+
123
+ let formatted_return = ret.format(&*self.heap);
124
+ let stdout = self.stdout_sink.take().unwrap_or_default();
125
+
126
+ Ok(RunOutcome {
127
+ return_value: ret,
128
+ formatted_return,
129
+ stdout,
130
+ stats: self.stats.clone(),
131
+ })
132
+ }
133
+
134
+ pub fn dump_reachable_ir(
135
+ &mut self,
136
+ entry_path: &Path,
137
+ entry_fn: &str,
138
+ ) -> Result<Vec<IrFunction>, PolyError> {
139
+ let entry_mod_id = self.resolver.load_module(entry_path)?;
140
+ let reachable = self
141
+ .resolver
142
+ .check_reachable_from_entry(entry_mod_id, entry_fn)?;
143
+ let mut out = Vec::new();
144
+ for (mod_id, fname) in reachable {
145
+ let fn_id = self.ensure_function_compiled(mod_id, &fname)?;
146
+ out.push(self.functions[fn_id.0 as usize].clone());
147
+ }
148
+ Ok(out)
149
+ }
150
+ /// Compiles and optimizes all reachable functions into a standalone, zero-source `IrBundle`.
151
+ pub fn run_inline_source(
152
+ &mut self,
153
+ virtual_path: &Path,
154
+ lang: crate::ast::Language,
155
+ source: String,
156
+ entry_fn: &str,
157
+ args: &[Value],
158
+ ) -> Result<RunOutcome, PolyError> {
159
+ let entry_mod_id = self
160
+ .resolver
161
+ .load_source_in_memory(virtual_path, lang, source)?;
162
+ self.run_module_top_level_if_needed(entry_mod_id)?;
163
+ let fn_id = self.ensure_function_compiled(entry_mod_id, entry_fn)?;
164
+ let ret = self.invoke_fn(fn_id, args)?;
165
+
166
+ self.stats.modules_parsed = self.resolver.stats.modules_parsed;
167
+ self.stats.parsed_paths = self.resolver.stats.parsed_paths.clone();
168
+ self.stats.gc_stats = self.heap.stats();
169
+
170
+ let formatted_return = ret.format(&*self.heap);
171
+ let stdout = self.stdout_sink.take().unwrap_or_default();
172
+ Ok(RunOutcome {
173
+ return_value: ret,
174
+ formatted_return,
175
+ stdout,
176
+ stats: self.stats.clone(),
177
+ })
178
+ }
179
+ /// Compiles and optimizes all reachable functions into a standalone, zero-source `IrBundle`.
180
+ pub fn compile_to_bundle(
181
+ &mut self,
182
+ entry_path: &Path,
183
+ entry_fn: &str,
184
+ ) -> Result<IrBundle, PolyError> {
185
+ let entry_mod_id = self.resolver.load_module(entry_path)?;
186
+ self.compile_loaded_module(entry_mod_id, entry_fn)
187
+ }
188
+
189
+ pub fn compile_inline_to_bundle(
190
+ &mut self,
191
+ virtual_path: &Path,
192
+ lang: crate::ast::Language,
193
+ source: String,
194
+ entry_fn: &str,
195
+ ) -> Result<IrBundle, PolyError> {
196
+ let entry_mod_id = self
197
+ .resolver
198
+ .load_source_in_memory(virtual_path, lang, source)?;
199
+ self.compile_loaded_module(entry_mod_id, entry_fn)
200
+ }
201
+
202
+ fn compile_loaded_module(
203
+ &mut self,
204
+ entry_mod_id: usize,
205
+ entry_fn: &str,
206
+ ) -> Result<IrBundle, PolyError> {
207
+ let reachable = self
208
+ .resolver
209
+ .check_reachable_from_entry(entry_mod_id, entry_fn)?;
210
+
211
+ let mut init_fns = Vec::new();
212
+ let mut seen_mods = FxHashSet::default();
213
+ for &(mod_id, _) in &reachable {
214
+ if seen_mods.insert(mod_id) {
215
+ let m = self.resolver.get_module(mod_id);
216
+ if !m.ast.top_level.is_empty() {
217
+ let stmts = m.ast.top_level.clone();
218
+ let bindings = m.bindings.clone();
219
+ let fn_idx_map = m.function_index.clone();
220
+ let mod_name = m
221
+ .path
222
+ .file_stem()
223
+ .and_then(|s| s.to_str())
224
+ .unwrap_or("module")
225
+ .to_string();
226
+ let fn_id = FnId(self.functions.len() as u32);
227
+ let mut ir_fn = lower_top_level(
228
+ fn_id,
229
+ mod_id,
230
+ format!("{mod_name}::__top_level"),
231
+ &stmts,
232
+ &bindings,
233
+ &fn_idx_map,
234
+ &mut self.call_sites,
235
+ )?;
236
+ optimize_function(&mut ir_fn);
237
+ self.functions.push(ir_fn);
238
+ self.call_counts.push(0);
239
+ self.stats.functions_lowered += 1;
240
+ init_fns.push(fn_id);
241
+ }
242
+ }
243
+ }
244
+
245
+ let mut exports = Vec::new();
246
+ for (mod_id, fname) in &reachable {
247
+ let fn_id = self.ensure_function_compiled(*mod_id, fname)?;
248
+ let mod_stem = self
249
+ .resolver
250
+ .get_module(*mod_id)
251
+ .path
252
+ .file_stem()
253
+ .and_then(|s| s.to_str())
254
+ .unwrap_or("module")
255
+ .to_string();
256
+ exports.push((format!("{mod_stem}::{fname}"), fn_id));
257
+ if *mod_id == entry_mod_id {
258
+ exports.push((fname.clone(), fn_id));
259
+ }
260
+ }
261
+
262
+ let entry_fn_id = self.ensure_function_compiled(entry_mod_id, entry_fn)?;
263
+
264
+ let mut idx = 0usize;
265
+ while idx < self.functions.len() {
266
+ let block_count = self.functions[idx].blocks.len();
267
+ for b in 0..block_count {
268
+ let instr_count = self.functions[idx].blocks[b].instructions.len();
269
+ for j in 0..instr_count {
270
+ let instr = self.functions[idx].blocks[b].instructions[j].clone();
271
+ match instr {
272
+ IrInstruction::CallLazy(dst, site_id, args) => {
273
+ let target_id = self.resolve_call_site(site_id)?;
274
+ self.functions[idx].blocks[b].instructions[j] =
275
+ IrInstruction::CallFn(dst, target_id, args);
276
+ }
277
+ IrInstruction::ResolveFn(dst, site_id) => {
278
+ let target_id = self.resolve_call_site(site_id)?;
279
+ self.functions[idx].blocks[b].instructions[j] =
280
+ IrInstruction::LoadFnRef(dst, target_id);
281
+ }
282
+ _ => {}
283
+ }
284
+ }
285
+ }
286
+ optimize_function(&mut self.functions[idx]);
287
+ idx += 1;
288
+ }
289
+
290
+ Ok(IrBundle {
291
+ entry_fn: entry_fn_id,
292
+ entry_name: entry_fn.to_string(),
293
+ init_fns,
294
+ exports,
295
+ functions: self.functions.clone(),
296
+ })
297
+ }
298
+ /// Executes a pre-compiled `IrBundle` directly, completely skipping parsing/lowering/optimization.
299
+ pub fn run_bundle(
300
+ &mut self,
301
+ bundle: IrBundle,
302
+ entry_override: Option<&str>,
303
+ args: &[Value],
304
+ ) -> Result<RunOutcome, PolyError> {
305
+ self.functions = bundle.functions;
306
+ self.call_counts = vec![0; self.functions.len()];
307
+ self.fn_map.clear();
308
+ self.call_sites.clear();
309
+
310
+ for init_id in bundle.init_fns {
311
+ let _ = self.invoke_fn(init_id, &[])?;
312
+ }
313
+
314
+ let target_fn_id = if let Some(name) = entry_override {
315
+ if name == bundle.entry_name {
316
+ bundle.entry_fn
317
+ } else if let Some((_, id)) = bundle.exports.iter().find(|(n, _)| n == name) {
318
+ *id
319
+ } else {
320
+ return Err(PolyError::msg(
321
+ "E0501",
322
+ format!("function '{name}' not found in IR bundle"),
323
+ ));
324
+ }
325
+ } else {
326
+ bundle.entry_fn
327
+ };
328
+
329
+ let ret = self.invoke_fn(target_fn_id, args)?;
330
+ self.stats.modules_parsed = 0;
331
+ self.stats.gc_stats = self.heap.stats();
332
+
333
+ let formatted_return = ret.format(&*self.heap);
334
+ let stdout = self.stdout_sink.take().unwrap_or_default();
335
+
336
+ Ok(RunOutcome {
337
+ return_value: ret,
338
+ formatted_return,
339
+ stdout,
340
+ stats: self.stats.clone(),
341
+ })
342
+ }
343
+ fn run_module_top_level_if_needed(&mut self, module_id: usize) -> Result<(), PolyError> {
344
+ if !self.top_level_ran.insert(module_id) {
345
+ return Ok(());
346
+ }
347
+ let m = self.resolver.get_module(module_id);
348
+ if m.ast.top_level.is_empty() {
349
+ return Ok(());
350
+ }
351
+ let stmts = m.ast.top_level.clone();
352
+ let bindings = m.bindings.clone();
353
+ let fn_idx_map = m.function_index.clone();
354
+ let mod_name = m
355
+ .path
356
+ .file_stem()
357
+ .and_then(|s| s.to_str())
358
+ .unwrap_or("module")
359
+ .to_string();
360
+
361
+ let fn_id = FnId(self.functions.len() as u32);
362
+ let mut ir_fn = lower_top_level(
363
+ fn_id,
364
+ module_id,
365
+ format!("{mod_name}::__top_level"),
366
+ &stmts,
367
+ &bindings,
368
+ &fn_idx_map,
369
+ &mut self.call_sites,
370
+ )?;
371
+ optimize_function(&mut ir_fn);
372
+ self.functions.push(ir_fn);
373
+ self.call_counts.push(0);
374
+ self.stats.functions_lowered += 1;
375
+ let _ = self.invoke_fn(fn_id, &[])?;
376
+ Ok(())
377
+ }
378
+
379
+ /// Lowers & optimizes ONLY the requested function (demand-driven).
380
+ pub fn ensure_function_compiled(
381
+ &mut self,
382
+ module_id: usize,
383
+ fn_name: &str,
384
+ ) -> Result<FnId, PolyError> {
385
+ if let Some(&id) = self.fn_map.get(&(module_id, fn_name.to_string())) {
386
+ return Ok(id);
387
+ }
388
+
389
+ let m = self.resolver.get_module(module_id);
390
+ let decl_idx = *m.function_index.get(fn_name).ok_or_else(|| {
391
+ PolyError::msg(
392
+ "E0501",
393
+ format!(
394
+ "function '{}' not found in '{}'",
395
+ fn_name,
396
+ m.path.display()
397
+ ),
398
+ )
399
+ })?;
400
+ let decl = m.ast.functions[decl_idx].clone();
401
+ let bindings = m.bindings.clone();
402
+ let local_fn_names = m.function_index.clone();
403
+ let mod_stem = m
404
+ .path
405
+ .file_stem()
406
+ .and_then(|s| s.to_str())
407
+ .unwrap_or("module")
408
+ .to_string();
409
+
410
+ let fn_id = FnId(self.functions.len() as u32);
411
+ let mut ir_fn = lower_function(
412
+ fn_id,
413
+ module_id,
414
+ format!("{mod_stem}::{fn_name}"),
415
+ &decl,
416
+ &bindings,
417
+ &local_fn_names,
418
+ &mut self.call_sites,
419
+ )?;
420
+ optimize_function(&mut ir_fn);
421
+
422
+ self.functions.push(ir_fn);
423
+ self.call_counts.push(0);
424
+ self.fn_map.insert((module_id, fn_name.to_string()), fn_id);
425
+ self.stats.functions_lowered += 1;
426
+ Ok(fn_id)
427
+ }
428
+
429
+ pub fn resolve_call_site(&mut self, site_id: CallSiteId) -> Result<FnId, PolyError> {
430
+ if let Some(id) = self.call_sites[site_id.0 as usize].resolved_fn {
431
+ return Ok(id);
432
+ }
433
+
434
+ let site = self.call_sites[site_id.0 as usize].clone();
435
+ let (target_mod, target_fn) = match site.target {
436
+ LazyTarget::SelfModule { module_id, symbol } => (module_id, symbol),
437
+ LazyTarget::ModuleMember { module_id, member } => (module_id, member),
438
+ LazyTarget::Direct {
439
+ from_module,
440
+ symbol,
441
+ } => {
442
+ if let Some((ns, member)) = symbol.split_once("::") {
443
+ self.resolver
444
+ .resolve_member_function_lazy(from_module, ns, member, site.span)?
445
+ } else {
446
+ self.resolver
447
+ .resolve_symbol_lazy(from_module, &symbol, site.span)?
448
+ }
449
+ }
450
+ };
451
+
452
+ self.run_module_top_level_if_needed(target_mod)?;
453
+ let fn_id = self.ensure_function_compiled(target_mod, &target_fn)?;
454
+ self.call_sites[site_id.0 as usize].resolved_fn = Some(fn_id);
455
+ self.stats.call_sites_resolved += 1;
456
+ Ok(fn_id)
457
+ }
458
+
459
+ pub fn invoke_fn(&mut self, fn_id: FnId, args: &[Value]) -> Result<Value, PolyError> {
460
+ let idx = fn_id.0 as usize;
461
+ self.call_counts[idx] += 1;
462
+ let count = self.call_counts[idx];
463
+
464
+ if self.config.enable_jit && count >= self.config.jit_threshold {
465
+ let already_compiled = self.jit.as_ref().and_then(|j| j.get(fn_id)).is_some();
466
+ if !already_compiled && is_jit_eligible(&self.functions[idx]) {
467
+ let ir_clone = self.functions[idx].clone();
468
+ let heap_ptr: *mut dyn MemoryHeap = &mut *self.heap;
469
+ if let Some(jit) = self.jit.as_mut() {
470
+ let compiled = jit.compile_function(&ir_clone, |s| {
471
+ // Safe: `jit` does not touch `heap` except via this closure
472
+ let h = unsafe { &mut *heap_ptr };
473
+ h.alloc_string(s.to_string()).0
474
+ });
475
+ match compiled {
476
+ Ok(_) => self.stats.functions_jit_compiled += 1,
477
+ Err(e) if self.config.trace_imports => {
478
+ eprintln!("[polycomp:jit] skip {}: {e}", ir_clone.qualified_name);
479
+ }
480
+ Err(_) => {}
481
+ }
482
+ }
483
+ }
484
+
485
+ if let Some(entry) = self.jit.as_ref().and_then(|j| j.get(fn_id)).cloned() {
486
+ return self.invoke_jit(&entry, args);
487
+ }
488
+ }
489
+
490
+ self.invoke_vm(fn_id, args)
491
+ }
492
+
493
+ fn invoke_jit(
494
+ &mut self,
495
+ entry: &crate::jit::JitEntry,
496
+ args: &[Value],
497
+ ) -> Result<Value, PolyError> {
498
+ self.stats.jit_invocations += 1;
499
+ let expected = entry.param_types.len();
500
+ if args.len() != expected {
501
+ return Err(PolyError::msg(
502
+ "E0502",
503
+ format!("expected {expected} arguments, got {}", args.len()),
504
+ ));
505
+ }
506
+
507
+ let mut raw_args = Vec::with_capacity(expected);
508
+ for (i, &pty) in entry.param_types.iter().enumerate() {
509
+ let raw = match (pty, args[i]) {
510
+ (IrType::I64, Value::Int(v)) => v as u64,
511
+ (IrType::I64, Value::Float(f)) => (f as i64) as u64,
512
+ (IrType::I64, Value::Bool(b)) => u64::from(b),
513
+ (IrType::F64, Value::Float(f)) => f.to_bits(),
514
+ (IrType::F64, Value::Int(v)) => (v as f64).to_bits(),
515
+ (IrType::Bool, v) => u64::from(v.is_truthy(&*self.heap)),
516
+ (IrType::Str, Value::Str(h)) => u64::from(h.0),
517
+ _ => {
518
+ return Err(PolyError::msg(
519
+ "E0503",
520
+ format!(
521
+ "incompatible argument #{} type '{}' for JIT function expecting {:?}",
522
+ i + 1,
523
+ args[i].type_name(),
524
+ pty
525
+ ),
526
+ ));
527
+ }
528
+ };
529
+ raw_args.push(raw);
530
+ }
531
+
532
+ let mut raw_out: u64 = 0;
533
+ let tramp = entry.trampoline;
534
+ let ret_ty = entry.return_type;
535
+ let vm_ptr = self as *mut VmEngine as *mut u8;
536
+ let status = unsafe { tramp(vm_ptr, raw_args.as_ptr(), &mut raw_out) };
537
+
538
+ if status != 0 {
539
+ if let Some(err) = self.last_error.take() {
540
+ return Err(err);
541
+ }
542
+ if let Some(code) = self.last_trap_code.take()
543
+ && code == 1
544
+ {
545
+ return Err(PolyError::msg("E0504", "division or modulo by zero"));
546
+ }
547
+ return Err(PolyError::msg("E0505", "JIT runtime trap"));
548
+ }
549
+
550
+ let val = match ret_ty {
551
+ IrType::Void => Value::Nil,
552
+ IrType::I64 => Value::Int(raw_out as i64),
553
+ IrType::F64 => Value::Float(f64::from_bits(raw_out)),
554
+ IrType::Bool => Value::Bool(raw_out != 0),
555
+ IrType::Str => Value::Str(StrHandle(raw_out as u32)),
556
+ IrType::Dynamic => Value::Nil,
557
+ };
558
+ Ok(val)
559
+ }
560
+
561
+ fn invoke_vm(&mut self, fn_id: FnId, args: &[Value]) -> Result<Value, PolyError> {
562
+ self.stats.vm_invocations += 1;
563
+ let func = self.functions[fn_id.0 as usize].clone();
564
+
565
+ if args.len() != func.params.len() {
566
+ return Err(PolyError::msg(
567
+ "E0502",
568
+ format!(
569
+ "function '{}' expects {} arguments, got {}",
570
+ func.qualified_name,
571
+ func.params.len(),
572
+ args.len()
573
+ ),
574
+ ));
575
+ }
576
+
577
+ let frame_idx = self.active_roots.len();
578
+ let mut regs = vec![Value::Nil; func.register_types.len()];
579
+ for (i, (reg, pty)) in func.params.iter().enumerate() {
580
+ regs[reg.0] = cast_value(args[i], *pty, &mut *self.heap)?;
581
+ }
582
+ self.active_roots.push(regs);
583
+
584
+ let result = self.exec_blocks(&func, frame_idx);
585
+ self.active_roots.pop();
586
+
587
+ // Trigger GC periodically if in TracingGc mode
588
+ if self.heap.mode() == MemoryMode::TracingGc {
589
+ let mut roots = Vec::new();
590
+ for frame in &self.active_roots {
591
+ roots.extend(frame.iter().copied());
592
+ }
593
+ if let Ok(ret_v) = &result {
594
+ roots.push(*ret_v);
595
+ }
596
+ self.heap.maybe_collect(&roots);
597
+ }
598
+
599
+ result
600
+ }
601
+
602
+ fn exec_blocks(&mut self, func: &IrFunction, frame: usize) -> Result<Value, PolyError> {
603
+ let mut bb_idx = 0usize;
604
+ let mut ip = 0usize;
605
+
606
+ while bb_idx < func.blocks.len() {
607
+ let bb = &func.blocks[bb_idx];
608
+ if ip >= bb.instructions.len() {
609
+ break;
610
+ }
611
+ match &bb.instructions[ip] {
612
+ IrInstruction::LoadConst(dst, c) => {
613
+ let v = match c {
614
+ Constant::Nil => Value::Nil,
615
+ Constant::Bool(b) => Value::Bool(*b),
616
+ Constant::Int(i) => Value::Int(*i),
617
+ Constant::Float(f) => Value::Float(*f),
618
+ Constant::String(s) => Value::Str(self.heap.alloc_string(s.clone())),
619
+ };
620
+ self.active_roots[frame][dst.0] = v;
621
+ ip += 1;
622
+ }
623
+ IrInstruction::Move(dst, src) => {
624
+ let v = self.active_roots[frame][src.0];
625
+ self.active_roots[frame][dst.0] = v;
626
+ ip += 1;
627
+ }
628
+ IrInstruction::Cast(dst, ty, src) => {
629
+ let v = self.active_roots[frame][src.0];
630
+ let cv = cast_value(v, *ty, &mut *self.heap)?;
631
+ self.active_roots[frame][dst.0] = cv;
632
+ ip += 1;
633
+ }
634
+ IrInstruction::UnaryOp(op, dst, src) => {
635
+ let v = self.active_roots[frame][src.0];
636
+ let res = eval_unary(*op, v, &*self.heap)?;
637
+ self.active_roots[frame][dst.0] = res;
638
+ ip += 1;
639
+ }
640
+ IrInstruction::BinOp(op, dst, l, r) => {
641
+ let lv = self.active_roots[frame][l.0];
642
+ let rv = self.active_roots[frame][r.0];
643
+ let res = eval_binop(*op, lv, rv, &mut *self.heap)?;
644
+ self.active_roots[frame][dst.0] = res;
645
+ ip += 1;
646
+ }
647
+ IrInstruction::CallLazy(dst, site_id, arg_regs) => {
648
+ let args: Vec<Value> = arg_regs
649
+ .iter()
650
+ .map(|r| self.active_roots[frame][r.0])
651
+ .collect();
652
+ let target_id = self.resolve_call_site(*site_id)?;
653
+ let ret = self.invoke_fn(target_id, &args)?;
654
+ self.active_roots[frame][dst.0] = ret;
655
+ ip += 1;
656
+ }
657
+ IrInstruction::CallFn(dst, target_id, arg_regs) => {
658
+ let args: Vec<Value> = arg_regs
659
+ .iter()
660
+ .map(|r| self.active_roots[frame][r.0])
661
+ .collect();
662
+ let ret = self.invoke_fn(*target_id, &args)?;
663
+ self.active_roots[frame][dst.0] = ret;
664
+ ip += 1;
665
+ }
666
+ IrInstruction::CallIndirect(dst, fn_reg, arg_regs) => {
667
+ let callee = self.active_roots[frame][fn_reg.0];
668
+ let Value::FunctionRef(target_id) = callee else {
669
+ return Err(PolyError::msg(
670
+ "E0506",
671
+ format!("attempted to call non-function value of type {}", callee.type_name()),
672
+ ));
673
+ };
674
+ let args: Vec<Value> = arg_regs
675
+ .iter()
676
+ .map(|r| self.active_roots[frame][r.0])
677
+ .collect();
678
+ let ret = self.invoke_fn(target_id, &args)?;
679
+ self.active_roots[frame][dst.0] = ret;
680
+ ip += 1;
681
+ }
682
+ IrInstruction::CallBuiltin(dst, builtin, arg_regs) => {
683
+ let args: Vec<Value> = arg_regs
684
+ .iter()
685
+ .map(|r| self.active_roots[frame][r.0])
686
+ .collect();
687
+ let ret = eval_builtin(*builtin, &args, &mut *self.heap, &mut self.stdout_sink)?;
688
+ self.active_roots[frame][dst.0] = ret;
689
+ ip += 1;
690
+ }
691
+ IrInstruction::ResolveFn(dst, site_id) => {
692
+ let target_id = self.resolve_call_site(*site_id)?;
693
+ self.active_roots[frame][dst.0] = Value::FunctionRef(target_id);
694
+ ip += 1;
695
+ }
696
+ IrInstruction::LoadFnRef(dst, fn_id) => {
697
+ self.active_roots[frame][dst.0] = Value::FunctionRef(*fn_id);
698
+ ip += 1;
699
+ }
700
+ IrInstruction::Return(opt_r) => {
701
+ let val = opt_r
702
+ .map(|r| self.active_roots[frame][r.0])
703
+ .unwrap_or(Value::Nil);
704
+ return Ok(val);
705
+ }
706
+ IrInstruction::BranchIf(cond, t_bb, f_bb) => {
707
+ let cv = self.active_roots[frame][cond.0];
708
+ bb_idx = if cv.is_truthy(&*self.heap) {
709
+ t_bb.0
710
+ } else {
711
+ f_bb.0
712
+ };
713
+ ip = 0;
714
+ }
715
+ IrInstruction::Jump(target) => {
716
+ bb_idx = target.0;
717
+ ip = 0;
718
+ }
719
+ IrInstruction::CreateArray(dst, item_regs) => {
720
+ let items: Vec<Value> = item_regs
721
+ .iter()
722
+ .map(|r| self.active_roots[frame][r.0])
723
+ .collect();
724
+ let h = self.heap.alloc_array(items);
725
+ self.active_roots[frame][dst.0] = Value::Array(h);
726
+ ip += 1;
727
+ }
728
+ IrInstruction::GetIndex(dst, obj_reg, idx_reg) => {
729
+ let obj = self.active_roots[frame][obj_reg.0];
730
+ let idx_val = self.active_roots[frame][idx_reg.0];
731
+ let Value::Int(idx_i) = idx_val else {
732
+ return Err(PolyError::msg("E0507", "index must be an integer"));
733
+ };
734
+ let val = match obj {
735
+ Value::Array(h) => {
736
+ let arr = self
737
+ .heap
738
+ .get_array(h)
739
+ .ok_or_else(|| PolyError::msg("E0508", "dangling array handle"))?;
740
+ let i = usize::try_from(idx_i)
741
+ .ok()
742
+ .filter(|&i| i < arr.len())
743
+ .ok_or_else(|| {
744
+ PolyError::msg(
745
+ "E0509",
746
+ format!("array index {idx_i} out of bounds (len {})", arr.len()),
747
+ )
748
+ })?;
749
+ arr[i]
750
+ }
751
+ Value::RawBuffer(h) => {
752
+ let buf = self
753
+ .heap
754
+ .buffer_slice(h)
755
+ .ok_or_else(|| PolyError::msg("E0508", "dangling buffer handle"))?;
756
+ let i = usize::try_from(idx_i)
757
+ .ok()
758
+ .filter(|&i| i < buf.len())
759
+ .ok_or_else(|| {
760
+ PolyError::msg("E0509", "buffer index out of bounds")
761
+ })?;
762
+ Value::Int(i64::from(buf[i]))
763
+ }
764
+ Value::Str(h) => {
765
+ let s = self
766
+ .heap
767
+ .get_string(h)
768
+ .ok_or_else(|| PolyError::msg("E0508", "dangling string handle"))?;
769
+ let ch = usize::try_from(idx_i)
770
+ .ok()
771
+ .and_then(|i| s.chars().nth(i))
772
+ .ok_or_else(|| {
773
+ PolyError::msg("E0509", "string index out of bounds")
774
+ })?;
775
+ Value::Str(self.heap.alloc_string(ch.to_string()))
776
+ }
777
+ other => {
778
+ return Err(PolyError::msg(
779
+ "E0510",
780
+ format!("cannot index type {}", other.type_name()),
781
+ ));
782
+ }
783
+ };
784
+ self.active_roots[frame][dst.0] = val;
785
+ ip += 1;
786
+ }
787
+ IrInstruction::SetIndex(obj_reg, idx_reg, val_reg) => {
788
+ let obj = self.active_roots[frame][obj_reg.0];
789
+ let idx_val = self.active_roots[frame][idx_reg.0];
790
+ let val = self.active_roots[frame][val_reg.0];
791
+ let Value::Int(idx_i) = idx_val else {
792
+ return Err(PolyError::msg("E0507", "index must be an integer"));
793
+ };
794
+ match obj {
795
+ Value::Array(h) => {
796
+ let arr = self
797
+ .heap
798
+ .get_array_mut(h)
799
+ .ok_or_else(|| PolyError::msg("E0508", "dangling array handle"))?;
800
+ let i = usize::try_from(idx_i)
801
+ .ok()
802
+ .filter(|&i| i < arr.len())
803
+ .ok_or_else(|| {
804
+ PolyError::msg("E0509", "array index out of bounds")
805
+ })?;
806
+ arr[i] = val;
807
+ }
808
+ Value::RawBuffer(h) => {
809
+ let Value::Int(byte) = val else {
810
+ return Err(PolyError::msg(
811
+ "E0510",
812
+ "buffer element must be an integer byte",
813
+ ));
814
+ };
815
+ let buf = self
816
+ .heap
817
+ .buffer_slice_mut(h)
818
+ .ok_or_else(|| PolyError::msg("E0508", "dangling buffer handle"))?;
819
+ let i = usize::try_from(idx_i)
820
+ .ok()
821
+ .filter(|&i| i < buf.len())
822
+ .ok_or_else(|| {
823
+ PolyError::msg("E0509", "buffer index out of bounds")
824
+ })?;
825
+ buf[i] = (byte & 0xff) as u8;
826
+ }
827
+ other => {
828
+ return Err(PolyError::msg(
829
+ "E0510",
830
+ format!("cannot index-assign type {}", other.type_name()),
831
+ ));
832
+ }
833
+ }
834
+ ip += 1;
835
+ }
836
+ IrInstruction::CreateObject(dst, class_name) => {
837
+ let h = self.heap.alloc_object(ClassInstance {
838
+ class_name: class_name.clone(),
839
+ fields: FxHashMap::default(),
840
+ });
841
+ self.active_roots[frame][dst.0] = Value::Object(h);
842
+ ip += 1;
843
+ }
844
+ IrInstruction::SetField(obj_reg, field, val_reg) => {
845
+ let obj = self.active_roots[frame][obj_reg.0];
846
+ let val = self.active_roots[frame][val_reg.0];
847
+ let Value::Object(h) = obj else {
848
+ return Err(PolyError::msg(
849
+ "E0511",
850
+ format!("cannot set field '{field}' on {}", obj.type_name()),
851
+ ));
852
+ };
853
+ let inst = self
854
+ .heap
855
+ .get_object_mut(h)
856
+ .ok_or_else(|| PolyError::msg("E0508", "dangling object handle"))?;
857
+ inst.fields.insert(field.clone(), val);
858
+ ip += 1;
859
+ }
860
+ IrInstruction::GetField(dst, obj_reg, field) => {
861
+ let obj = self.active_roots[frame][obj_reg.0];
862
+ let Value::Object(h) = obj else {
863
+ return Err(PolyError::msg(
864
+ "E0511",
865
+ format!("cannot get field '{field}' on {}", obj.type_name()),
866
+ ));
867
+ };
868
+ let inst = self
869
+ .heap
870
+ .get_object(h)
871
+ .ok_or_else(|| PolyError::msg("E0508", "dangling object handle"))?;
872
+ let val = inst.fields.get(field).copied().unwrap_or(Value::Nil);
873
+ self.active_roots[frame][dst.0] = val;
874
+ ip += 1;
875
+ }
876
+ IrInstruction::AllocBuffer(dst, size_reg) => {
877
+ let Value::Int(sz) = self.active_roots[frame][size_reg.0] else {
878
+ return Err(PolyError::msg("E0512", "buffer size must be integer"));
879
+ };
880
+ if sz < 0 {
881
+ return Err(PolyError::msg("E0512", "negative buffer size"));
882
+ }
883
+ let h = self.heap.alloc_buffer(sz as usize);
884
+ self.active_roots[frame][dst.0] = Value::RawBuffer(h);
885
+ ip += 1;
886
+ }
887
+ IrInstruction::StoreByte(buf_r, off_r, val_r) => {
888
+ let _ = eval_builtin(
889
+ BuiltinId::WriteU8,
890
+ &[
891
+ self.active_roots[frame][buf_r.0],
892
+ self.active_roots[frame][off_r.0],
893
+ self.active_roots[frame][val_r.0],
894
+ ],
895
+ &mut *self.heap,
896
+ &mut self.stdout_sink,
897
+ )?;
898
+ ip += 1;
899
+ }
900
+ IrInstruction::LoadByte(dst, buf_r, off_r) => {
901
+ let v = eval_builtin(
902
+ BuiltinId::ReadU8,
903
+ &[
904
+ self.active_roots[frame][buf_r.0],
905
+ self.active_roots[frame][off_r.0],
906
+ ],
907
+ &mut *self.heap,
908
+ &mut self.stdout_sink,
909
+ )?;
910
+ self.active_roots[frame][dst.0] = v;
911
+ ip += 1;
912
+ }
913
+ }
914
+ }
915
+
916
+ Ok(Value::Nil)
917
+ }
918
+ }
919
+
920
+ pub fn check_project(entry_path: &Path, entry_fn: &str, trace_imports: bool) -> Result<StaticCheckReport, PolyError> {
921
+ let mut resolver = ModuleResolver::new(trace_imports);
922
+ let entry_mod = resolver.load_module(entry_path)?;
923
+ let reachable = resolver.check_reachable_from_entry(entry_mod, entry_fn)?;
924
+ Ok(StaticCheckReport {
925
+ modules_parsed: resolver.stats.modules_parsed,
926
+ reachable_functions: reachable.len(),
927
+ parsed_paths: resolver.stats.parsed_paths,
928
+ })
929
+ }
930
+
931
+ fn cast_value(val: Value, ty: IrType, heap: &mut dyn MemoryHeap) -> Result<Value, PolyError> {
932
+ match ty {
933
+ IrType::Dynamic | IrType::Void => Ok(val),
934
+ IrType::Bool => Ok(Value::Bool(val.is_truthy(heap))),
935
+ IrType::I64 => match val {
936
+ Value::Int(i) => Ok(Value::Int(i)),
937
+ Value::Float(f) => Ok(Value::Int(f as i64)),
938
+ Value::Bool(b) => Ok(Value::Int(i64::from(b))),
939
+ other => Err(PolyError::msg(
940
+ "E0513",
941
+ format!("cannot cast {} to int", other.type_name()),
942
+ )),
943
+ },
944
+ IrType::F64 => match val {
945
+ Value::Float(f) => Ok(Value::Float(f)),
946
+ Value::Int(i) => Ok(Value::Float(i as f64)),
947
+ Value::Bool(b) => Ok(Value::Float(if b { 1.0 } else { 0.0 })),
948
+ other => Err(PolyError::msg(
949
+ "E0513",
950
+ format!("cannot cast {} to float", other.type_name()),
951
+ )),
952
+ },
953
+ IrType::Str => match val {
954
+ Value::Str(h) => Ok(Value::Str(h)),
955
+ other => Ok(Value::Str(heap.alloc_string(other.format(heap)))),
956
+ },
957
+ }
958
+ }
959
+
960
+ fn eval_unary(op: IrUnaryOp, v: Value, heap: &dyn MemoryHeap) -> Result<Value, PolyError> {
961
+ match op {
962
+ IrUnaryOp::Not => Ok(Value::Bool(!v.is_truthy(heap))),
963
+ IrUnaryOp::Neg => match v {
964
+ Value::Int(i) => Ok(Value::Int(i.wrapping_neg())),
965
+ Value::Float(f) => Ok(Value::Float(-f)),
966
+ other => Err(PolyError::msg(
967
+ "E0514",
968
+ format!("cannot negate {}", other.type_name()),
969
+ )),
970
+ },
971
+ IrUnaryOp::BitsToF64 => match v {
972
+ Value::Int(i) => Ok(Value::Float(f64::from_bits(i as u64))),
973
+ other => Err(PolyError::msg(
974
+ "E0514",
975
+ format!("cannot bitcast {} to float", other.type_name()),
976
+ )),
977
+ },
978
+ IrUnaryOp::BitNot => match v {
979
+ Value::Int(i) => Ok(Value::Int(!i)),
980
+ other => Err(PolyError::msg(
981
+ "E0514",
982
+ format!("cannot bitwise-not {}", other.type_name()),
983
+ )),
984
+ },
985
+ }
986
+ }
987
+
988
+ fn eval_binop(
989
+ op: IrBinOp,
990
+ l: Value,
991
+ r: Value,
992
+ heap: &mut dyn MemoryHeap,
993
+ ) -> Result<Value, PolyError> {
994
+ if op == IrBinOp::Add && (matches!(l, Value::Str(_)) || matches!(r, Value::Str(_))) {
995
+ let ls = l.format(heap);
996
+ let rs = r.format(heap);
997
+ return Ok(Value::Str(heap.alloc_string(format!("{ls}{rs}"))));
998
+ }
999
+
1000
+ match (l, r) {
1001
+ (Value::Int(a), Value::Int(b)) => match op {
1002
+ IrBinOp::Add => Ok(Value::Int(a.wrapping_add(b))),
1003
+ IrBinOp::Sub => Ok(Value::Int(a.wrapping_sub(b))),
1004
+ IrBinOp::Mul => Ok(Value::Int(a.wrapping_mul(b))),
1005
+ IrBinOp::Div => {
1006
+ if b == 0 {
1007
+ return Err(PolyError::msg("E0504", "division by zero"));
1008
+ }
1009
+ Ok(Value::Int(a.wrapping_div(b)))
1010
+ }
1011
+ IrBinOp::FloorDiv => {
1012
+ if b == 0 {
1013
+ return Err(PolyError::msg("E0504", "division by zero"));
1014
+ }
1015
+ let mut q = a.wrapping_div(b);
1016
+ let rem = a.wrapping_rem(b);
1017
+ if rem != 0 && (a ^ b) < 0 {
1018
+ q = q.wrapping_sub(1);
1019
+ }
1020
+ Ok(Value::Int(q))
1021
+ }
1022
+ IrBinOp::Mod => {
1023
+ if b == 0 {
1024
+ return Err(PolyError::msg("E0504", "modulo by zero"));
1025
+ }
1026
+ Ok(Value::Int(a.wrapping_rem(b)))
1027
+ }
1028
+ IrBinOp::Eq => Ok(Value::Bool(a == b)),
1029
+ IrBinOp::Ne => Ok(Value::Bool(a != b)),
1030
+ IrBinOp::Lt => Ok(Value::Bool(a < b)),
1031
+ IrBinOp::Le => Ok(Value::Bool(a <= b)),
1032
+ IrBinOp::Gt => Ok(Value::Bool(a > b)),
1033
+ IrBinOp::Ge => Ok(Value::Bool(a >= b)),
1034
+ IrBinOp::BitAnd => Ok(Value::Int(a & b)),
1035
+ IrBinOp::BitOr => Ok(Value::Int(a | b)),
1036
+ IrBinOp::BitXor => Ok(Value::Int(a ^ b)),
1037
+ IrBinOp::Shl => Ok(Value::Int(a.wrapping_shl(b as u32))),
1038
+ IrBinOp::Shr => Ok(Value::Int(a.wrapping_shr(b as u32))),
1039
+ IrBinOp::And => Ok(Value::Bool(a != 0 && b != 0)),
1040
+ IrBinOp::Or => Ok(Value::Bool(a != 0 || b != 0)),
1041
+ },
1042
+ (Value::Float(a), Value::Float(b)) => eval_float_op(op, a, b),
1043
+ (Value::Int(a), Value::Float(b)) => eval_float_op(op, a as f64, b),
1044
+ (Value::Float(a), Value::Int(b)) => eval_float_op(op, a, b as f64),
1045
+ (Value::Bool(a), Value::Bool(b)) => match op {
1046
+ IrBinOp::Eq => Ok(Value::Bool(a == b)),
1047
+ IrBinOp::Ne => Ok(Value::Bool(a != b)),
1048
+ IrBinOp::And => Ok(Value::Bool(a && b)),
1049
+ IrBinOp::Or => Ok(Value::Bool(a || b)),
1050
+ _ => Err(PolyError::msg("E0515", "unsupported boolean binary operation")),
1051
+ },
1052
+ (Value::Str(a), Value::Str(b)) => {
1053
+ let sa = heap.get_string(a).unwrap_or("");
1054
+ let sb = heap.get_string(b).unwrap_or("");
1055
+ match op {
1056
+ IrBinOp::Eq => Ok(Value::Bool(sa == sb)),
1057
+ IrBinOp::Ne => Ok(Value::Bool(sa != sb)),
1058
+ IrBinOp::Lt => Ok(Value::Bool(sa < sb)),
1059
+ IrBinOp::Le => Ok(Value::Bool(sa <= sb)),
1060
+ IrBinOp::Gt => Ok(Value::Bool(sa > sb)),
1061
+ IrBinOp::Ge => Ok(Value::Bool(sa >= sb)),
1062
+ _ => Err(PolyError::msg("E0515", "unsupported string binary operation")),
1063
+ }
1064
+ }
1065
+ (Value::Nil, Value::Nil) => match op {
1066
+ IrBinOp::Eq => Ok(Value::Bool(true)),
1067
+ IrBinOp::Ne => Ok(Value::Bool(false)),
1068
+ _ => Err(PolyError::msg("E0515", "unsupported nil binary operation")),
1069
+ },
1070
+ (a, b) => match op {
1071
+ IrBinOp::Eq => Ok(Value::Bool(a == b)),
1072
+ IrBinOp::Ne => Ok(Value::Bool(a != b)),
1073
+ _ => Err(PolyError::msg(
1074
+ "E0515",
1075
+ format!(
1076
+ "unsupported binary operation {:?} between {} and {}",
1077
+ op,
1078
+ a.type_name(),
1079
+ b.type_name()
1080
+ ),
1081
+ )),
1082
+ },
1083
+ }
1084
+ }
1085
+
1086
+ fn eval_float_op(op: IrBinOp, a: f64, b: f64) -> Result<Value, PolyError> {
1087
+ match op {
1088
+ IrBinOp::Add => Ok(Value::Float(a + b)),
1089
+ IrBinOp::Sub => Ok(Value::Float(a - b)),
1090
+ IrBinOp::Mul => Ok(Value::Float(a * b)),
1091
+ IrBinOp::Div => Ok(Value::Float(a / b)),
1092
+ IrBinOp::FloorDiv => Ok(Value::Float((a / b).floor())),
1093
+ IrBinOp::Mod => Ok(Value::Float(a % b)),
1094
+ IrBinOp::Eq => Ok(Value::Bool(a == b)),
1095
+ IrBinOp::Ne => Ok(Value::Bool(a != b)),
1096
+ IrBinOp::Lt => Ok(Value::Bool(a < b)),
1097
+ IrBinOp::Le => Ok(Value::Bool(a <= b)),
1098
+ IrBinOp::Gt => Ok(Value::Bool(a > b)),
1099
+ IrBinOp::Ge => Ok(Value::Bool(a >= b)),
1100
+ IrBinOp::And => Ok(Value::Bool(a != 0.0 && b != 0.0)),
1101
+ IrBinOp::Or => Ok(Value::Bool(a != 0.0 || b != 0.0)),
1102
+ _ => Err(PolyError::msg("E0515", "unsupported float binary operation")),
1103
+ }
1104
+ }
1105
+
1106
+ // ============================================================================
1107
+ // Runtime callbacks invoked synchronously from Cranelift JITted machine code
1108
+ // ============================================================================
1109
+
1110
+ unsafe extern "C" fn rt_call_site(
1111
+ rt_ctx: *mut u8,
1112
+ site_id: u32,
1113
+ args_ptr: *const JitAbiVal,
1114
+ args_len: usize,
1115
+ out_ptr: *mut JitAbiVal,
1116
+ ) -> u8 {
1117
+ let vm = unsafe { &mut *(rt_ctx as *mut VmEngine) };
1118
+ let args = decode_abi_args(args_ptr, args_len);
1119
+ let res = vm
1120
+ .resolve_call_site(CallSiteId(site_id))
1121
+ .and_then(|fn_id| vm.invoke_fn(fn_id, &args));
1122
+ finish_abi_call(vm, res, out_ptr)
1123
+ }
1124
+
1125
+ unsafe extern "C" fn rt_call_fn(
1126
+ rt_ctx: *mut u8,
1127
+ fn_id: u32,
1128
+ args_ptr: *const JitAbiVal,
1129
+ args_len: usize,
1130
+ out_ptr: *mut JitAbiVal,
1131
+ ) -> u8 {
1132
+ let vm = unsafe { &mut *(rt_ctx as *mut VmEngine) };
1133
+ let args = decode_abi_args(args_ptr, args_len);
1134
+ let res = vm.invoke_fn(FnId(fn_id), &args);
1135
+ finish_abi_call(vm, res, out_ptr)
1136
+ }
1137
+
1138
+ unsafe extern "C" fn rt_call_builtin(
1139
+ rt_ctx: *mut u8,
1140
+ builtin_discriminant: u32,
1141
+ args_ptr: *const JitAbiVal,
1142
+ args_len: usize,
1143
+ out_ptr: *mut JitAbiVal,
1144
+ ) -> u8 {
1145
+ let vm = unsafe { &mut *(rt_ctx as *mut VmEngine) };
1146
+ let args = decode_abi_args(args_ptr, args_len);
1147
+ let res = match builtin_from_u32(builtin_discriminant) {
1148
+ Some(b) => eval_builtin(b, &args, &mut *vm.heap, &mut vm.stdout_sink),
1149
+ None => Err(PolyError::msg("E0516", "invalid builtin id from JIT")),
1150
+ };
1151
+ finish_abi_call(vm, res, out_ptr)
1152
+ }
1153
+
1154
+ unsafe extern "C" fn rt_set_trap(rt_ctx: *mut u8, code: u32) {
1155
+ let vm = unsafe { &mut *(rt_ctx as *mut VmEngine) };
1156
+ vm.last_trap_code = Some(code);
1157
+ }
1158
+
1159
+ fn decode_abi_args(ptr: *const JitAbiVal, len: usize) -> Vec<Value> {
1160
+ if len == 0 || ptr.is_null() {
1161
+ return Vec::new();
1162
+ }
1163
+ let slice = unsafe { std::slice::from_raw_parts(ptr, len) };
1164
+ slice.iter().map(|a| a.to_value()).collect()
1165
+ }
1166
+
1167
+ fn finish_abi_call(
1168
+ vm: &mut VmEngine,
1169
+ res: Result<Value, PolyError>,
1170
+ out_ptr: *mut JitAbiVal,
1171
+ ) -> u8 {
1172
+ match res {
1173
+ Ok(val) => {
1174
+ if !out_ptr.is_null() {
1175
+ unsafe {
1176
+ *out_ptr = JitAbiVal::from_value(val);
1177
+ }
1178
+ }
1179
+ 0
1180
+ }
1181
+ Err(err) => {
1182
+ vm.last_error = Some(err);
1183
+ 1
1184
+ }
1185
+ }
1186
+ }
1187
+
1188
+ fn builtin_from_u32(v: u32) -> Option<BuiltinId> {
1189
+ match v {
1190
+ x if x == BuiltinId::Print as u32 => Some(BuiltinId::Print),
1191
+ x if x == BuiltinId::Println as u32 => Some(BuiltinId::Println),
1192
+ x if x == BuiltinId::Printf as u32 => Some(BuiltinId::Printf),
1193
+ x if x == BuiltinId::Len as u32 => Some(BuiltinId::Len),
1194
+ x if x == BuiltinId::Str as u32 => Some(BuiltinId::Str),
1195
+ x if x == BuiltinId::Int as u32 => Some(BuiltinId::Int),
1196
+ x if x == BuiltinId::Float as u32 => Some(BuiltinId::Float),
1197
+ x if x == BuiltinId::Bool as u32 => Some(BuiltinId::Bool),
1198
+ x if x == BuiltinId::Abs as u32 => Some(BuiltinId::Abs),
1199
+ x if x == BuiltinId::Min as u32 => Some(BuiltinId::Min),
1200
+ x if x == BuiltinId::Max as u32 => Some(BuiltinId::Max),
1201
+ x if x == BuiltinId::Sqrt as u32 => Some(BuiltinId::Sqrt),
1202
+ x if x == BuiltinId::Pow as u32 => Some(BuiltinId::Pow),
1203
+ x if x == BuiltinId::Push as u32 => Some(BuiltinId::Push),
1204
+ x if x == BuiltinId::Pop as u32 => Some(BuiltinId::Pop),
1205
+ x if x == BuiltinId::TypeOf as u32 => Some(BuiltinId::TypeOf),
1206
+ x if x == BuiltinId::AllocBuf as u32 => Some(BuiltinId::AllocBuf),
1207
+ x if x == BuiltinId::ReadU8 as u32 => Some(BuiltinId::ReadU8),
1208
+ x if x == BuiltinId::WriteU8 as u32 => Some(BuiltinId::WriteU8),
1209
+ x if x == BuiltinId::BufLen as u32 => Some(BuiltinId::BufLen),
1210
+ x if x == BuiltinId::ClockMs as u32 => Some(BuiltinId::ClockMs),
1211
+ x if x == BuiltinId::Assert as u32 => Some(BuiltinId::Assert),
1212
+ _ => None,
1213
+ }
1214
+ }