polycomp 0.2.0 → 0.3.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.
@@ -1,13 +1,15 @@
1
+ use crate::ast::Language;
2
+ use crate::bundle::IrBundle;
1
3
  use crate::diagnostics::PolyError;
2
4
  use crate::ir::*;
3
- use crate::jit::{JitAbiVal, JitCallbacks, JitEngine, is_jit_eligible};
5
+ use crate::jit::{is_jit_eligible, JitAbiVal, JitCallbacks, JitEngine};
4
6
  use crate::lowering::{lower_function, lower_top_level};
5
7
  use crate::optimizer::optimize_function;
6
8
  use crate::resolver::{ModuleResolver, StaticCheckReport};
7
9
  use crate::runtime::{
8
- ClassInstance, GcStats, MemoryHeap, MemoryMode, StrHandle, Value, eval_builtin, make_heap,
10
+ eval_builtin, make_heap, ClassInstance, GcStats, MemoryHeap, MemoryMode, StrHandle,
11
+ Value,
9
12
  };
10
- use crate::bundle::IrBundle;
11
13
  use rustc_hash::{FxHashMap, FxHashSet};
12
14
  use std::path::{Path, PathBuf};
13
15
 
@@ -51,6 +53,12 @@ pub struct RunOutcome {
51
53
  pub stats: RunStats,
52
54
  }
53
55
 
56
+ #[derive(Debug, Clone, Copy)]
57
+ struct ExceptionHandler {
58
+ catch_bb: BasicBlockId,
59
+ err_reg: Register,
60
+ }
61
+
54
62
  pub struct VmEngine {
55
63
  pub resolver: ModuleResolver,
56
64
  pub heap: Box<dyn MemoryHeap>,
@@ -113,7 +121,12 @@ impl VmEngine {
113
121
  let entry_mod_id = self.resolver.load_module(entry_path)?;
114
122
  self.run_module_top_level_if_needed(entry_mod_id)?;
115
123
 
116
- let fn_id = self.ensure_function_compiled(entry_mod_id, entry_fn)?;
124
+ let actual_entry = self
125
+ .resolver
126
+ .resolve_entry_fn_name(entry_mod_id, entry_fn)
127
+ .unwrap_or_else(|| entry_fn.to_string());
128
+
129
+ let fn_id = self.ensure_function_compiled(entry_mod_id, &actual_entry)?;
117
130
  let ret = self.invoke_fn(fn_id, args)?;
118
131
 
119
132
  self.stats.modules_parsed = self.resolver.stats.modules_parsed;
@@ -131,27 +144,10 @@ impl VmEngine {
131
144
  })
132
145
  }
133
146
 
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(
147
+ pub fn run_inline_source(
152
148
  &mut self,
153
149
  virtual_path: &Path,
154
- lang: crate::ast::Language,
150
+ lang: Language,
155
151
  source: String,
156
152
  entry_fn: &str,
157
153
  args: &[Value],
@@ -160,7 +156,13 @@ pub fn run_inline_source(
160
156
  .resolver
161
157
  .load_source_in_memory(virtual_path, lang, source)?;
162
158
  self.run_module_top_level_if_needed(entry_mod_id)?;
163
- let fn_id = self.ensure_function_compiled(entry_mod_id, entry_fn)?;
159
+
160
+ let actual_entry = self
161
+ .resolver
162
+ .resolve_entry_fn_name(entry_mod_id, entry_fn)
163
+ .unwrap_or_else(|| entry_fn.to_string());
164
+
165
+ let fn_id = self.ensure_function_compiled(entry_mod_id, &actual_entry)?;
164
166
  let ret = self.invoke_fn(fn_id, args)?;
165
167
 
166
168
  self.stats.modules_parsed = self.resolver.stats.modules_parsed;
@@ -169,6 +171,7 @@ pub fn run_inline_source(
169
171
 
170
172
  let formatted_return = ret.format(&*self.heap);
171
173
  let stdout = self.stdout_sink.take().unwrap_or_default();
174
+
172
175
  Ok(RunOutcome {
173
176
  return_value: ret,
174
177
  formatted_return,
@@ -176,7 +179,24 @@ pub fn run_inline_source(
176
179
  stats: self.stats.clone(),
177
180
  })
178
181
  }
179
- /// Compiles and optimizes all reachable functions into a standalone, zero-source `IrBundle`.
182
+
183
+ pub fn dump_reachable_ir(
184
+ &mut self,
185
+ entry_path: &Path,
186
+ entry_fn: &str,
187
+ ) -> Result<Vec<IrFunction>, PolyError> {
188
+ let entry_mod_id = self.resolver.load_module(entry_path)?;
189
+ let reachable = self
190
+ .resolver
191
+ .check_reachable_from_entry(entry_mod_id, entry_fn)?;
192
+ let mut out = Vec::new();
193
+ for (mod_id, fname) in reachable {
194
+ let fn_id = self.ensure_function_compiled(mod_id, &fname)?;
195
+ out.push(self.functions[fn_id.0 as usize].clone());
196
+ }
197
+ Ok(out)
198
+ }
199
+
180
200
  pub fn compile_to_bundle(
181
201
  &mut self,
182
202
  entry_path: &Path,
@@ -189,7 +209,7 @@ pub fn run_inline_source(
189
209
  pub fn compile_inline_to_bundle(
190
210
  &mut self,
191
211
  virtual_path: &Path,
192
- lang: crate::ast::Language,
212
+ lang: Language,
193
213
  source: String,
194
214
  entry_fn: &str,
195
215
  ) -> Result<IrBundle, PolyError> {
@@ -259,7 +279,11 @@ pub fn run_inline_source(
259
279
  }
260
280
  }
261
281
 
262
- let entry_fn_id = self.ensure_function_compiled(entry_mod_id, entry_fn)?;
282
+ let actual_entry = self
283
+ .resolver
284
+ .resolve_entry_fn_name(entry_mod_id, entry_fn)
285
+ .unwrap_or_else(|| entry_fn.to_string());
286
+ let entry_fn_id = self.ensure_function_compiled(entry_mod_id, &actual_entry)?;
263
287
 
264
288
  let mut idx = 0usize;
265
289
  while idx < self.functions.len() {
@@ -295,51 +319,52 @@ pub fn run_inline_source(
295
319
  functions: self.functions.clone(),
296
320
  })
297
321
  }
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
- }
322
+
323
+ pub fn run_bundle(
324
+ &mut self,
325
+ bundle: IrBundle,
326
+ entry_override: Option<&str>,
327
+ args: &[Value],
328
+ ) -> Result<RunOutcome, PolyError> {
329
+ self.functions = bundle.functions;
330
+ self.call_counts = vec![0; self.functions.len()];
331
+ self.fn_map.clear();
332
+ self.call_sites.clear();
333
+
334
+ for init_id in bundle.init_fns {
335
+ let _ = self.invoke_fn(init_id, &[])?;
336
+ }
337
+
338
+ let target_fn_id = if let Some(name) = entry_override {
339
+ if name == bundle.entry_name {
340
+ bundle.entry_fn
341
+ } else if let Some((_, id)) = bundle.exports.iter().find(|(n, _)| n == name) {
342
+ *id
343
+ } else {
344
+ return Err(PolyError::msg(
345
+ "E0501",
346
+ format!("function '{name}' not found in IR bundle"),
347
+ ));
348
+ }
349
+ } else {
350
+ bundle.entry_fn
351
+ };
352
+
353
+ let ret = self.invoke_fn(target_fn_id, args)?;
354
+ self.stats.modules_parsed = 0;
355
+ self.stats.gc_stats = self.heap.stats();
356
+
357
+ let formatted_return = ret.format(&*self.heap);
358
+ let stdout = self.stdout_sink.take().unwrap_or_default();
359
+
360
+ Ok(RunOutcome {
361
+ return_value: ret,
362
+ formatted_return,
363
+ stdout,
364
+ stats: self.stats.clone(),
365
+ })
366
+ }
367
+
343
368
  fn run_module_top_level_if_needed(&mut self, module_id: usize) -> Result<(), PolyError> {
344
369
  if !self.top_level_ran.insert(module_id) {
345
370
  return Ok(());
@@ -376,7 +401,6 @@ pub fn run_inline_source(
376
401
  Ok(())
377
402
  }
378
403
 
379
- /// Lowers & optimizes ONLY the requested function (demand-driven).
380
404
  pub fn ensure_function_compiled(
381
405
  &mut self,
382
406
  module_id: usize,
@@ -468,7 +492,6 @@ pub fn run_inline_source(
468
492
  let heap_ptr: *mut dyn MemoryHeap = &mut *self.heap;
469
493
  if let Some(jit) = self.jit.as_mut() {
470
494
  let compiled = jit.compile_function(&ir_clone, |s| {
471
- // Safe: `jit` does not touch `heap` except via this closure
472
495
  let h = unsafe { &mut *heap_ptr };
473
496
  h.alloc_string(s.to_string()).0
474
497
  });
@@ -584,7 +607,6 @@ pub fn run_inline_source(
584
607
  let result = self.exec_blocks(&func, frame_idx);
585
608
  self.active_roots.pop();
586
609
 
587
- // Trigger GC periodically if in TracingGc mode
588
610
  if self.heap.mode() == MemoryMode::TracingGc {
589
611
  let mut roots = Vec::new();
590
612
  for frame in &self.active_roots {
@@ -602,6 +624,7 @@ pub fn run_inline_source(
602
624
  fn exec_blocks(&mut self, func: &IrFunction, frame: usize) -> Result<Value, PolyError> {
603
625
  let mut bb_idx = 0usize;
604
626
  let mut ip = 0usize;
627
+ let mut try_stack: Vec<ExceptionHandler> = Vec::new();
605
628
 
606
629
  while bb_idx < func.blocks.len() {
607
630
  let bb = &func.blocks[bb_idx];
@@ -616,6 +639,10 @@ pub fn run_inline_source(
616
639
  Constant::Int(i) => Value::Int(*i),
617
640
  Constant::Float(f) => Value::Float(*f),
618
641
  Constant::String(s) => Value::Str(self.heap.alloc_string(s.clone())),
642
+ Constant::Regex { pattern, flags } => {
643
+ let h = self.heap.alloc_regex(pattern, flags)?;
644
+ Value::Regex(h)
645
+ }
619
646
  };
620
647
  self.active_roots[frame][dst.0] = v;
621
648
  ip += 1;
@@ -640,9 +667,22 @@ pub fn run_inline_source(
640
667
  IrInstruction::BinOp(op, dst, l, r) => {
641
668
  let lv = self.active_roots[frame][l.0];
642
669
  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;
670
+ match eval_binop(*op, lv, rv, &mut *self.heap) {
671
+ Ok(res) => {
672
+ self.active_roots[frame][dst.0] = res;
673
+ ip += 1;
674
+ }
675
+ Err(e) => {
676
+ if let Some(h) = try_stack.pop() {
677
+ let s = self.heap.alloc_string(e.to_string());
678
+ self.active_roots[frame][h.err_reg.0] = Value::Str(s);
679
+ bb_idx = h.catch_bb.0;
680
+ ip = 0;
681
+ } else {
682
+ return Err(e);
683
+ }
684
+ }
685
+ }
646
686
  }
647
687
  IrInstruction::CallLazy(dst, site_id, arg_regs) => {
648
688
  let args: Vec<Value> = arg_regs
@@ -650,32 +690,84 @@ pub fn run_inline_source(
650
690
  .map(|r| self.active_roots[frame][r.0])
651
691
  .collect();
652
692
  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;
693
+ match self.invoke_fn(target_id, &args) {
694
+ Ok(ret) => {
695
+ self.active_roots[frame][dst.0] = ret;
696
+ ip += 1;
697
+ }
698
+ Err(e) => {
699
+ if let Some(h) = try_stack.pop() {
700
+ let s = self.heap.alloc_string(e.to_string());
701
+ self.active_roots[frame][h.err_reg.0] = Value::Str(s);
702
+ bb_idx = h.catch_bb.0;
703
+ ip = 0;
704
+ } else {
705
+ return Err(e);
706
+ }
707
+ }
708
+ }
656
709
  }
657
710
  IrInstruction::CallFn(dst, target_id, arg_regs) => {
658
711
  let args: Vec<Value> = arg_regs
659
712
  .iter()
660
713
  .map(|r| self.active_roots[frame][r.0])
661
714
  .collect();
662
- let ret = self.invoke_fn(*target_id, &args)?;
663
- self.active_roots[frame][dst.0] = ret;
664
- ip += 1;
715
+ match self.invoke_fn(*target_id, &args) {
716
+ Ok(ret) => {
717
+ self.active_roots[frame][dst.0] = ret;
718
+ ip += 1;
719
+ }
720
+ Err(e) => {
721
+ if let Some(h) = try_stack.pop() {
722
+ let s = self.heap.alloc_string(e.to_string());
723
+ self.active_roots[frame][h.err_reg.0] = Value::Str(s);
724
+ bb_idx = h.catch_bb.0;
725
+ ip = 0;
726
+ } else {
727
+ return Err(e);
728
+ }
729
+ }
730
+ }
665
731
  }
666
732
  IrInstruction::CallIndirect(dst, fn_reg, arg_regs) => {
667
733
  let callee = self.active_roots[frame][fn_reg.0];
668
734
  let Value::FunctionRef(target_id) = callee else {
669
735
  return Err(PolyError::msg(
670
736
  "E0506",
671
- format!("attempted to call non-function value of type {}", callee.type_name()),
737
+ format!(
738
+ "attempted to call non-function value of type {}",
739
+ callee.type_name()
740
+ ),
672
741
  ));
673
742
  };
674
743
  let args: Vec<Value> = arg_regs
675
744
  .iter()
676
745
  .map(|r| self.active_roots[frame][r.0])
677
746
  .collect();
678
- let ret = self.invoke_fn(target_id, &args)?;
747
+ match self.invoke_fn(target_id, &args) {
748
+ Ok(ret) => {
749
+ self.active_roots[frame][dst.0] = ret;
750
+ ip += 1;
751
+ }
752
+ Err(e) => {
753
+ if let Some(h) = try_stack.pop() {
754
+ let s = self.heap.alloc_string(e.to_string());
755
+ self.active_roots[frame][h.err_reg.0] = Value::Str(s);
756
+ bb_idx = h.catch_bb.0;
757
+ ip = 0;
758
+ } else {
759
+ return Err(e);
760
+ }
761
+ }
762
+ }
763
+ }
764
+ IrInstruction::CallMethod(dst, obj_reg, method_name, arg_regs) => {
765
+ let obj = self.active_roots[frame][obj_reg.0];
766
+ let args: Vec<Value> = arg_regs
767
+ .iter()
768
+ .map(|r| self.active_roots[frame][r.0])
769
+ .collect();
770
+ let ret = self.eval_method_call(obj, method_name, &args)?;
679
771
  self.active_roots[frame][dst.0] = ret;
680
772
  ip += 1;
681
773
  }
@@ -684,9 +776,22 @@ pub fn run_inline_source(
684
776
  .iter()
685
777
  .map(|r| self.active_roots[frame][r.0])
686
778
  .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;
779
+ match eval_builtin(*builtin, &args, &mut *self.heap, &mut self.stdout_sink) {
780
+ Ok(ret) => {
781
+ self.active_roots[frame][dst.0] = ret;
782
+ ip += 1;
783
+ }
784
+ Err(e) => {
785
+ if let Some(h) = try_stack.pop() {
786
+ let s = self.heap.alloc_string(e.to_string());
787
+ self.active_roots[frame][h.err_reg.0] = Value::Str(s);
788
+ bb_idx = h.catch_bb.0;
789
+ ip = 0;
790
+ } else {
791
+ return Err(e);
792
+ }
793
+ }
794
+ }
690
795
  }
691
796
  IrInstruction::ResolveFn(dst, site_id) => {
692
797
  let target_id = self.resolve_call_site(*site_id)?;
@@ -716,6 +821,28 @@ pub fn run_inline_source(
716
821
  bb_idx = target.0;
717
822
  ip = 0;
718
823
  }
824
+ IrInstruction::TryBegin(catch_bb, err_reg) => {
825
+ try_stack.push(ExceptionHandler {
826
+ catch_bb: *catch_bb,
827
+ err_reg: *err_reg,
828
+ });
829
+ ip += 1;
830
+ }
831
+ IrInstruction::TryEnd => {
832
+ let _ = try_stack.pop();
833
+ ip += 1;
834
+ }
835
+ IrInstruction::Throw(r) => {
836
+ let err_val = self.active_roots[frame][r.0];
837
+ if let Some(h) = try_stack.pop() {
838
+ self.active_roots[frame][h.err_reg.0] = err_val;
839
+ bb_idx = h.catch_bb.0;
840
+ ip = 0;
841
+ } else {
842
+ let msg = err_val.format(&*self.heap);
843
+ return Err(PolyError::msg("E0520", format!("uncaught exception: {msg}")));
844
+ }
845
+ }
719
846
  IrInstruction::CreateArray(dst, item_regs) => {
720
847
  let items: Vec<Value> = item_regs
721
848
  .iter()
@@ -743,7 +870,10 @@ pub fn run_inline_source(
743
870
  .ok_or_else(|| {
744
871
  PolyError::msg(
745
872
  "E0509",
746
- format!("array index {idx_i} out of bounds (len {})", arr.len()),
873
+ format!(
874
+ "array index {idx_i} out of bounds (len {})",
875
+ arr.len()
876
+ ),
747
877
  )
748
878
  })?;
749
879
  arr[i]
@@ -859,17 +989,32 @@ pub fn run_inline_source(
859
989
  }
860
990
  IrInstruction::GetField(dst, obj_reg, field) => {
861
991
  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
- ));
992
+ let val = match obj {
993
+ Value::Object(h) => {
994
+ let inst = self
995
+ .heap
996
+ .get_object(h)
997
+ .ok_or_else(|| PolyError::msg("E0508", "dangling object handle"))?;
998
+ inst.fields.get(field).copied().unwrap_or(Value::Nil)
999
+ }
1000
+ Value::Str(h) => {
1001
+ let s = self.heap.get_string(h).unwrap_or("");
1002
+ if field == "length" || field == "Length" {
1003
+ Value::Int(s.len() as i64)
1004
+ } else {
1005
+ Value::Nil
1006
+ }
1007
+ }
1008
+ Value::Array(h) => {
1009
+ let a = self.heap.get_array(h).unwrap_or(&[]);
1010
+ if field == "length" || field == "Length" || field == "Count" {
1011
+ Value::Int(a.len() as i64)
1012
+ } else {
1013
+ Value::Nil
1014
+ }
1015
+ }
1016
+ _ => Value::Nil,
867
1017
  };
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
1018
  self.active_roots[frame][dst.0] = val;
874
1019
  ip += 1;
875
1020
  }
@@ -915,9 +1060,191 @@ pub fn run_inline_source(
915
1060
 
916
1061
  Ok(Value::Nil)
917
1062
  }
1063
+
1064
+ fn eval_method_call(
1065
+ &mut self,
1066
+ obj: Value,
1067
+ method: &str,
1068
+ args: &[Value],
1069
+ ) -> Result<Value, PolyError> {
1070
+ match obj {
1071
+ Value::Regex(h) => match method {
1072
+ "test" | "Match" | "IsMatch" => {
1073
+ let mut b_args = vec![Value::Regex(h)];
1074
+ b_args.extend_from_slice(args);
1075
+ eval_builtin(
1076
+ BuiltinId::RegexTest,
1077
+ &b_args,
1078
+ &mut *self.heap,
1079
+ &mut self.stdout_sink,
1080
+ )
1081
+ }
1082
+ "exec" | "match" => {
1083
+ let mut b_args = vec![Value::Regex(h)];
1084
+ b_args.extend_from_slice(args);
1085
+ eval_builtin(
1086
+ BuiltinId::RegexMatch,
1087
+ &b_args,
1088
+ &mut *self.heap,
1089
+ &mut self.stdout_sink,
1090
+ )
1091
+ }
1092
+ "replace" | "Replace" | "ReplaceAll" => {
1093
+ let mut b_args = vec![Value::Regex(h)];
1094
+ b_args.extend_from_slice(args);
1095
+ eval_builtin(
1096
+ BuiltinId::RegexReplace,
1097
+ &b_args,
1098
+ &mut *self.heap,
1099
+ &mut self.stdout_sink,
1100
+ )
1101
+ }
1102
+ "split" | "Split" => {
1103
+ let mut b_args = vec![Value::Regex(h)];
1104
+ b_args.extend_from_slice(args);
1105
+ eval_builtin(
1106
+ BuiltinId::RegexSplit,
1107
+ &b_args,
1108
+ &mut *self.heap,
1109
+ &mut self.stdout_sink,
1110
+ )
1111
+ }
1112
+ _ => Err(PolyError::msg(
1113
+ "E0521",
1114
+ format!("unknown regex method '{method}'"),
1115
+ )),
1116
+ },
1117
+ Value::Str(h) => match method {
1118
+ "contains" | "Contains" | "includes" => {
1119
+ let mut b_args = vec![Value::Str(h)];
1120
+ b_args.extend_from_slice(args);
1121
+ eval_builtin(
1122
+ BuiltinId::StrContains,
1123
+ &b_args,
1124
+ &mut *self.heap,
1125
+ &mut self.stdout_sink,
1126
+ )
1127
+ }
1128
+ "split" | "Split" => {
1129
+ let mut b_args = vec![Value::Str(h)];
1130
+ b_args.extend_from_slice(args);
1131
+ eval_builtin(
1132
+ BuiltinId::StrSplit,
1133
+ &b_args,
1134
+ &mut *self.heap,
1135
+ &mut self.stdout_sink,
1136
+ )
1137
+ }
1138
+ "trim" | "Trim" | "TrimSpace" => eval_builtin(
1139
+ BuiltinId::StrTrim,
1140
+ &[Value::Str(h)],
1141
+ &mut *self.heap,
1142
+ &mut self.stdout_sink,
1143
+ ),
1144
+ "toUpperCase" | "ToUpper" | "upper" => eval_builtin(
1145
+ BuiltinId::StrUpper,
1146
+ &[Value::Str(h)],
1147
+ &mut *self.heap,
1148
+ &mut self.stdout_sink,
1149
+ ),
1150
+ "toLowerCase" | "ToLower" | "lower" => eval_builtin(
1151
+ BuiltinId::StrLower,
1152
+ &[Value::Str(h)],
1153
+ &mut *self.heap,
1154
+ &mut self.stdout_sink,
1155
+ ),
1156
+ "replace" | "Replace" | "replaceAll" | "ReplaceAll" => {
1157
+ if let Some(Value::Regex(_)) = args.first() {
1158
+ let mut b_args = vec![args[0], Value::Str(h)];
1159
+ if let Some(repl) = args.get(1) {
1160
+ b_args.push(*repl);
1161
+ }
1162
+ eval_builtin(
1163
+ BuiltinId::RegexReplace,
1164
+ &b_args,
1165
+ &mut *self.heap,
1166
+ &mut self.stdout_sink,
1167
+ )
1168
+ } else {
1169
+ let mut b_args = vec![Value::Str(h)];
1170
+ b_args.extend_from_slice(args);
1171
+ eval_builtin(
1172
+ BuiltinId::StrReplace,
1173
+ &b_args,
1174
+ &mut *self.heap,
1175
+ &mut self.stdout_sink,
1176
+ )
1177
+ }
1178
+ }
1179
+ _ => Err(PolyError::msg(
1180
+ "E0521",
1181
+ format!("unknown string method '{method}'"),
1182
+ )),
1183
+ },
1184
+ Value::Array(h) => match method {
1185
+ "push" | "append" | "Add" => {
1186
+ let mut b_args = vec![Value::Array(h)];
1187
+ b_args.extend_from_slice(args);
1188
+ eval_builtin(
1189
+ BuiltinId::Push,
1190
+ &b_args,
1191
+ &mut *self.heap,
1192
+ &mut self.stdout_sink,
1193
+ )
1194
+ }
1195
+ "pop" => eval_builtin(
1196
+ BuiltinId::Pop,
1197
+ &[Value::Array(h)],
1198
+ &mut *self.heap,
1199
+ &mut self.stdout_sink,
1200
+ ),
1201
+ _ => Err(PolyError::msg(
1202
+ "E0521",
1203
+ format!("unknown array method '{method}'"),
1204
+ )),
1205
+ },
1206
+ Value::Object(h) => {
1207
+ let inst = self
1208
+ .heap
1209
+ .get_object(h)
1210
+ .ok_or_else(|| PolyError::msg("E0508", "dangling object handle"))?;
1211
+ if let Some(&field_val) = inst.fields.get(method) {
1212
+ if let Value::FunctionRef(target_id) = field_val {
1213
+ let mut call_args = vec![obj];
1214
+ call_args.extend_from_slice(args);
1215
+ return self.invoke_fn(target_id, &call_args);
1216
+ }
1217
+ return Ok(field_val);
1218
+ }
1219
+ let scoped_name = format!("{}::{method}", inst.class_name);
1220
+ for (&(_, ref name), &target_id) in &self.fn_map {
1221
+ if name == &scoped_name {
1222
+ let mut call_args = vec![obj];
1223
+ call_args.extend_from_slice(args);
1224
+ return self.invoke_fn(target_id, &call_args);
1225
+ }
1226
+ }
1227
+ Err(PolyError::msg(
1228
+ "E0521",
1229
+ format!(
1230
+ "object of class '{}' has no method '{method}'",
1231
+ inst.class_name
1232
+ ),
1233
+ ))
1234
+ }
1235
+ other => Err(PolyError::msg(
1236
+ "E0521",
1237
+ format!("cannot call method '{method}' on {}", other.type_name()),
1238
+ )),
1239
+ }
1240
+ }
918
1241
  }
919
1242
 
920
- pub fn check_project(entry_path: &Path, entry_fn: &str, trace_imports: bool) -> Result<StaticCheckReport, PolyError> {
1243
+ pub fn check_project(
1244
+ entry_path: &Path,
1245
+ entry_fn: &str,
1246
+ trace_imports: bool,
1247
+ ) -> Result<StaticCheckReport, PolyError> {
921
1248
  let mut resolver = ModuleResolver::new(trace_imports);
922
1249
  let entry_mod = resolver.load_module(entry_path)?;
923
1250
  let reachable = resolver.check_reachable_from_entry(entry_mod, entry_fn)?;
@@ -968,18 +1295,18 @@ fn eval_unary(op: IrUnaryOp, v: Value, heap: &dyn MemoryHeap) -> Result<Value, P
968
1295
  format!("cannot negate {}", other.type_name()),
969
1296
  )),
970
1297
  },
971
- IrUnaryOp::BitsToF64 => match v {
972
- Value::Int(i) => Ok(Value::Float(f64::from_bits(i as u64))),
1298
+ IrUnaryOp::BitNot => match v {
1299
+ Value::Int(i) => Ok(Value::Int(!i)),
973
1300
  other => Err(PolyError::msg(
974
1301
  "E0514",
975
- format!("cannot bitcast {} to float", other.type_name()),
1302
+ format!("cannot bitwise-not {}", other.type_name()),
976
1303
  )),
977
1304
  },
978
- IrUnaryOp::BitNot => match v {
979
- Value::Int(i) => Ok(Value::Int(!i)),
1305
+ IrUnaryOp::BitsToF64 => match v {
1306
+ Value::Int(i) => Ok(Value::Float(f64::from_bits(i as u64))),
980
1307
  other => Err(PolyError::msg(
981
1308
  "E0514",
982
- format!("cannot bitwise-not {}", other.type_name()),
1309
+ format!("cannot bitcast {} to float", other.type_name()),
983
1310
  )),
984
1311
  },
985
1312
  }
@@ -1025,6 +1352,13 @@ fn eval_binop(
1025
1352
  }
1026
1353
  Ok(Value::Int(a.wrapping_rem(b)))
1027
1354
  }
1355
+ IrBinOp::Pow => {
1356
+ if b >= 0 && b <= u32::MAX as i64 {
1357
+ Ok(Value::Int(a.wrapping_pow(b as u32)))
1358
+ } else {
1359
+ Ok(Value::Float((a as f64).powf(b as f64)))
1360
+ }
1361
+ }
1028
1362
  IrBinOp::Eq => Ok(Value::Bool(a == b)),
1029
1363
  IrBinOp::Ne => Ok(Value::Bool(a != b)),
1030
1364
  IrBinOp::Lt => Ok(Value::Bool(a < b)),
@@ -1047,7 +1381,7 @@ fn eval_binop(
1047
1381
  IrBinOp::Ne => Ok(Value::Bool(a != b)),
1048
1382
  IrBinOp::And => Ok(Value::Bool(a && b)),
1049
1383
  IrBinOp::Or => Ok(Value::Bool(a || b)),
1050
- _ => Err(PolyError::msg("E0515", "unsupported boolean binary operation")),
1384
+ _ => Err(PolyError::msg("E0515", "unsupported boolean operation")),
1051
1385
  },
1052
1386
  (Value::Str(a), Value::Str(b)) => {
1053
1387
  let sa = heap.get_string(a).unwrap_or("");
@@ -1059,13 +1393,13 @@ fn eval_binop(
1059
1393
  IrBinOp::Le => Ok(Value::Bool(sa <= sb)),
1060
1394
  IrBinOp::Gt => Ok(Value::Bool(sa > sb)),
1061
1395
  IrBinOp::Ge => Ok(Value::Bool(sa >= sb)),
1062
- _ => Err(PolyError::msg("E0515", "unsupported string binary operation")),
1396
+ _ => Err(PolyError::msg("E0515", "unsupported string operation")),
1063
1397
  }
1064
1398
  }
1065
1399
  (Value::Nil, Value::Nil) => match op {
1066
1400
  IrBinOp::Eq => Ok(Value::Bool(true)),
1067
1401
  IrBinOp::Ne => Ok(Value::Bool(false)),
1068
- _ => Err(PolyError::msg("E0515", "unsupported nil binary operation")),
1402
+ _ => Err(PolyError::msg("E0515", "unsupported nil operation")),
1069
1403
  },
1070
1404
  (a, b) => match op {
1071
1405
  IrBinOp::Eq => Ok(Value::Bool(a == b)),
@@ -1091,6 +1425,7 @@ fn eval_float_op(op: IrBinOp, a: f64, b: f64) -> Result<Value, PolyError> {
1091
1425
  IrBinOp::Div => Ok(Value::Float(a / b)),
1092
1426
  IrBinOp::FloorDiv => Ok(Value::Float((a / b).floor())),
1093
1427
  IrBinOp::Mod => Ok(Value::Float(a % b)),
1428
+ IrBinOp::Pow => Ok(Value::Float(a.powf(b))),
1094
1429
  IrBinOp::Eq => Ok(Value::Bool(a == b)),
1095
1430
  IrBinOp::Ne => Ok(Value::Bool(a != b)),
1096
1431
  IrBinOp::Lt => Ok(Value::Bool(a < b)),
@@ -1099,14 +1434,10 @@ fn eval_float_op(op: IrBinOp, a: f64, b: f64) -> Result<Value, PolyError> {
1099
1434
  IrBinOp::Ge => Ok(Value::Bool(a >= b)),
1100
1435
  IrBinOp::And => Ok(Value::Bool(a != 0.0 && b != 0.0)),
1101
1436
  IrBinOp::Or => Ok(Value::Bool(a != 0.0 || b != 0.0)),
1102
- _ => Err(PolyError::msg("E0515", "unsupported float binary operation")),
1437
+ _ => Err(PolyError::msg("E0515", "unsupported float operation")),
1103
1438
  }
1104
1439
  }
1105
1440
 
1106
- // ============================================================================
1107
- // Runtime callbacks invoked synchronously from Cranelift JITted machine code
1108
- // ============================================================================
1109
-
1110
1441
  unsafe extern "C" fn rt_call_site(
1111
1442
  rt_ctx: *mut u8,
1112
1443
  site_id: u32,
@@ -1190,6 +1521,7 @@ fn builtin_from_u32(v: u32) -> Option<BuiltinId> {
1190
1521
  x if x == BuiltinId::Print as u32 => Some(BuiltinId::Print),
1191
1522
  x if x == BuiltinId::Println as u32 => Some(BuiltinId::Println),
1192
1523
  x if x == BuiltinId::Printf as u32 => Some(BuiltinId::Printf),
1524
+ x if x == BuiltinId::Sprintf as u32 => Some(BuiltinId::Sprintf),
1193
1525
  x if x == BuiltinId::Len as u32 => Some(BuiltinId::Len),
1194
1526
  x if x == BuiltinId::Str as u32 => Some(BuiltinId::Str),
1195
1527
  x if x == BuiltinId::Int as u32 => Some(BuiltinId::Int),
@@ -1200,6 +1532,12 @@ fn builtin_from_u32(v: u32) -> Option<BuiltinId> {
1200
1532
  x if x == BuiltinId::Max as u32 => Some(BuiltinId::Max),
1201
1533
  x if x == BuiltinId::Sqrt as u32 => Some(BuiltinId::Sqrt),
1202
1534
  x if x == BuiltinId::Pow as u32 => Some(BuiltinId::Pow),
1535
+ x if x == BuiltinId::Floor as u32 => Some(BuiltinId::Floor),
1536
+ x if x == BuiltinId::Ceil as u32 => Some(BuiltinId::Ceil),
1537
+ x if x == BuiltinId::Round as u32 => Some(BuiltinId::Round),
1538
+ x if x == BuiltinId::Sin as u32 => Some(BuiltinId::Sin),
1539
+ x if x == BuiltinId::Cos as u32 => Some(BuiltinId::Cos),
1540
+ x if x == BuiltinId::Log as u32 => Some(BuiltinId::Log),
1203
1541
  x if x == BuiltinId::Push as u32 => Some(BuiltinId::Push),
1204
1542
  x if x == BuiltinId::Pop as u32 => Some(BuiltinId::Pop),
1205
1543
  x if x == BuiltinId::TypeOf as u32 => Some(BuiltinId::TypeOf),
@@ -1209,6 +1547,19 @@ fn builtin_from_u32(v: u32) -> Option<BuiltinId> {
1209
1547
  x if x == BuiltinId::BufLen as u32 => Some(BuiltinId::BufLen),
1210
1548
  x if x == BuiltinId::ClockMs as u32 => Some(BuiltinId::ClockMs),
1211
1549
  x if x == BuiltinId::Assert as u32 => Some(BuiltinId::Assert),
1550
+ x if x == BuiltinId::Range as u32 => Some(BuiltinId::Range),
1551
+ x if x == BuiltinId::RegexNew as u32 => Some(BuiltinId::RegexNew),
1552
+ x if x == BuiltinId::RegexTest as u32 => Some(BuiltinId::RegexTest),
1553
+ x if x == BuiltinId::RegexMatch as u32 => Some(BuiltinId::RegexMatch),
1554
+ x if x == BuiltinId::RegexFindAll as u32 => Some(BuiltinId::RegexFindAll),
1555
+ x if x == BuiltinId::RegexReplace as u32 => Some(BuiltinId::RegexReplace),
1556
+ x if x == BuiltinId::RegexSplit as u32 => Some(BuiltinId::RegexSplit),
1557
+ x if x == BuiltinId::StrContains as u32 => Some(BuiltinId::StrContains),
1558
+ x if x == BuiltinId::StrSplit as u32 => Some(BuiltinId::StrSplit),
1559
+ x if x == BuiltinId::StrTrim as u32 => Some(BuiltinId::StrTrim),
1560
+ x if x == BuiltinId::StrUpper as u32 => Some(BuiltinId::StrUpper),
1561
+ x if x == BuiltinId::StrLower as u32 => Some(BuiltinId::StrLower),
1562
+ x if x == BuiltinId::StrReplace as u32 => Some(BuiltinId::StrReplace),
1212
1563
  _ => None,
1213
1564
  }
1214
1565
  }