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.
package/src/runtime.rs ADDED
@@ -0,0 +1,829 @@
1
+ use crate::diagnostics::PolyError;
2
+ use crate::ir::{BuiltinId, FnId};
3
+ use rustc_hash::FxHashMap;
4
+ use std::fmt::Write as _;
5
+ use std::time::{SystemTime, UNIX_EPOCH};
6
+
7
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8
+ pub struct ObjHandle(pub u32);
9
+
10
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11
+ pub struct StrHandle(pub u32);
12
+
13
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14
+ pub struct ArrHandle(pub u32);
15
+
16
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
17
+ pub struct BufHandle(pub u32);
18
+
19
+ #[derive(Debug, Clone, Copy, PartialEq)]
20
+ pub enum Value {
21
+ Nil,
22
+ Bool(bool),
23
+ Int(i64),
24
+ Float(f64),
25
+ Str(StrHandle),
26
+ Array(ArrHandle),
27
+ Object(ObjHandle),
28
+ RawBuffer(BufHandle),
29
+ FunctionRef(FnId),
30
+ }
31
+
32
+ impl Value {
33
+ pub fn is_truthy(self, heap: &dyn MemoryHeap) -> bool {
34
+ match self {
35
+ Value::Nil => false,
36
+ Value::Bool(b) => b,
37
+ Value::Int(i) => i != 0,
38
+ Value::Float(f) => f != 0.0 && !f.is_nan(),
39
+ Value::Str(h) => heap.get_string(h).is_some_and(|s| !s.is_empty()),
40
+ Value::Array(h) => heap.get_array(h).is_some_and(|a| !a.is_empty()),
41
+ Value::Object(_) | Value::RawBuffer(_) | Value::FunctionRef(_) => true,
42
+ }
43
+ }
44
+
45
+ pub fn type_name(self) -> &'static str {
46
+ match self {
47
+ Value::Nil => "nil",
48
+ Value::Bool(_) => "bool",
49
+ Value::Int(_) => "int",
50
+ Value::Float(_) => "float",
51
+ Value::Str(_) => "string",
52
+ Value::Array(_) => "array",
53
+ Value::Object(_) => "object",
54
+ Value::RawBuffer(_) => "buffer",
55
+ Value::FunctionRef(_) => "function",
56
+ }
57
+ }
58
+
59
+ pub fn format(self, heap: &dyn MemoryHeap) -> String {
60
+ match self {
61
+ Value::Nil => "nil".to_string(),
62
+ Value::Bool(b) => b.to_string(),
63
+ Value::Int(i) => i.to_string(),
64
+ Value::Float(f) => {
65
+ if f.fract() == 0.0 && f.abs() < 1e15 {
66
+ format!("{f:.1}")
67
+ } else {
68
+ format!("{f}")
69
+ }
70
+ }
71
+ Value::Str(h) => heap.get_string(h).unwrap_or("<freed str>").to_string(),
72
+ Value::Array(h) => {
73
+ if let Some(items) = heap.get_array(h) {
74
+ let parts: Vec<String> = items.iter().map(|v| v.format(heap)).collect();
75
+ format!("[{}]", parts.join(", "))
76
+ } else {
77
+ "<freed array>".to_string()
78
+ }
79
+ }
80
+ Value::Object(h) => {
81
+ if let Some(obj) = heap.get_object(h) {
82
+ let parts: Vec<String> = obj
83
+ .fields
84
+ .iter()
85
+ .map(|(k, v)| format!("{k}: {}", v.format(heap)))
86
+ .collect();
87
+ format!("{} {{ {} }}", obj.class_name, parts.join(", "))
88
+ } else {
89
+ "<freed object>".to_string()
90
+ }
91
+ }
92
+ Value::RawBuffer(h) => {
93
+ let len = heap.buffer_len(h).unwrap_or(0);
94
+ format!("<buffer:{len}B>")
95
+ }
96
+ Value::FunctionRef(id) => format!("<fn#{}>", id.0),
97
+ }
98
+ }
99
+ }
100
+
101
+ #[derive(Debug, Clone)]
102
+ pub struct ClassInstance {
103
+ pub class_name: String,
104
+ pub fields: FxHashMap<String, Value>,
105
+ }
106
+
107
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
108
+ pub enum MemoryMode {
109
+ Arena,
110
+ TracingGc,
111
+ }
112
+
113
+ #[derive(Debug, Clone, Copy, Default)]
114
+ pub struct GcStats {
115
+ pub allocations: usize,
116
+ pub collections: usize,
117
+ pub freed_objects: usize,
118
+ pub live_objects: usize,
119
+ }
120
+
121
+ pub trait MemoryHeap: Send {
122
+ fn mode(&self) -> MemoryMode;
123
+ fn alloc_string(&mut self, s: String) -> StrHandle;
124
+ fn get_string(&self, h: StrHandle) -> Option<&str>;
125
+
126
+ fn alloc_array(&mut self, items: Vec<Value>) -> ArrHandle;
127
+ fn get_array(&self, h: ArrHandle) -> Option<&[Value]>;
128
+ fn get_array_mut(&mut self, h: ArrHandle) -> Option<&mut Vec<Value>>;
129
+
130
+ fn alloc_object(&mut self, instance: ClassInstance) -> ObjHandle;
131
+ fn get_object(&self, h: ObjHandle) -> Option<&ClassInstance>;
132
+ fn get_object_mut(&mut self, h: ObjHandle) -> Option<&mut ClassInstance>;
133
+
134
+ fn alloc_buffer(&mut self, size: usize) -> BufHandle;
135
+ fn buffer_len(&self, h: BufHandle) -> Option<usize>;
136
+ fn buffer_slice(&self, h: BufHandle) -> Option<&[u8]>;
137
+ fn buffer_slice_mut(&mut self, h: BufHandle) -> Option<&mut [u8]>;
138
+
139
+ fn maybe_collect(&mut self, roots: &[Value]) -> usize;
140
+ fn collect_garbage(&mut self, roots: &[Value]) -> usize;
141
+ fn stats(&self) -> GcStats;
142
+ }
143
+
144
+ /// Zero-GC bump/slab Arena allocator with string interning for ultra-fast C/Rust workloads.
145
+ #[derive(Default)]
146
+ pub struct ArenaHeap {
147
+ strings: Vec<String>,
148
+ string_intern: FxHashMap<String, StrHandle>,
149
+ arrays: Vec<Vec<Value>>,
150
+ objects: Vec<ClassInstance>,
151
+ buffers: Vec<Vec<u8>>,
152
+ allocations: usize,
153
+ }
154
+
155
+ impl MemoryHeap for ArenaHeap {
156
+ fn mode(&self) -> MemoryMode {
157
+ MemoryMode::Arena
158
+ }
159
+
160
+ fn alloc_string(&mut self, s: String) -> StrHandle {
161
+ if let Some(&h) = self.string_intern.get(&s) {
162
+ return h;
163
+ }
164
+ let h = StrHandle(self.strings.len() as u32);
165
+ self.string_intern.insert(s.clone(), h);
166
+ self.strings.push(s);
167
+ self.allocations += 1;
168
+ h
169
+ }
170
+
171
+ fn get_string(&self, h: StrHandle) -> Option<&str> {
172
+ self.strings.get(h.0 as usize).map(|s| s.as_str())
173
+ }
174
+
175
+ fn alloc_array(&mut self, items: Vec<Value>) -> ArrHandle {
176
+ let h = ArrHandle(self.arrays.len() as u32);
177
+ self.arrays.push(items);
178
+ self.allocations += 1;
179
+ h
180
+ }
181
+
182
+ fn get_array(&self, h: ArrHandle) -> Option<&[Value]> {
183
+ self.arrays.get(h.0 as usize).map(|v| v.as_slice())
184
+ }
185
+
186
+ fn get_array_mut(&mut self, h: ArrHandle) -> Option<&mut Vec<Value>> {
187
+ self.arrays.get_mut(h.0 as usize)
188
+ }
189
+
190
+ fn alloc_object(&mut self, instance: ClassInstance) -> ObjHandle {
191
+ let h = ObjHandle(self.objects.len() as u32);
192
+ self.objects.push(instance);
193
+ self.allocations += 1;
194
+ h
195
+ }
196
+
197
+ fn get_object(&self, h: ObjHandle) -> Option<&ClassInstance> {
198
+ self.objects.get(h.0 as usize)
199
+ }
200
+
201
+ fn get_object_mut(&mut self, h: ObjHandle) -> Option<&mut ClassInstance> {
202
+ self.objects.get_mut(h.0 as usize)
203
+ }
204
+
205
+ fn alloc_buffer(&mut self, size: usize) -> BufHandle {
206
+ let h = BufHandle(self.buffers.len() as u32);
207
+ self.buffers.push(vec![0u8; size]);
208
+ self.allocations += 1;
209
+ h
210
+ }
211
+
212
+ fn buffer_len(&self, h: BufHandle) -> Option<usize> {
213
+ self.buffers.get(h.0 as usize).map(|b| b.len())
214
+ }
215
+
216
+ fn buffer_slice(&self, h: BufHandle) -> Option<&[u8]> {
217
+ self.buffers.get(h.0 as usize).map(|b| b.as_slice())
218
+ }
219
+
220
+ fn buffer_slice_mut(&mut self, h: BufHandle) -> Option<&mut [u8]> {
221
+ self.buffers.get_mut(h.0 as usize).map(|b| b.as_mut_slice())
222
+ }
223
+
224
+ fn maybe_collect(&mut self, _roots: &[Value]) -> usize {
225
+ 0
226
+ }
227
+
228
+ fn collect_garbage(&mut self, _roots: &[Value]) -> usize {
229
+ 0
230
+ }
231
+
232
+ fn stats(&self) -> GcStats {
233
+ GcStats {
234
+ allocations: self.allocations,
235
+ collections: 0,
236
+ freed_objects: 0,
237
+ live_objects: self.strings.len()
238
+ + self.arrays.len()
239
+ + self.objects.len()
240
+ + self.buffers.len(),
241
+ }
242
+ }
243
+ }
244
+
245
+ struct GcSlot<T> {
246
+ marked: bool,
247
+ data: Option<T>,
248
+ }
249
+
250
+ /// Tracing Mark-and-Sweep GC heap that safely collects cyclic Python/JS object graphs.
251
+ pub struct MarkSweepHeap {
252
+ strings: Vec<GcSlot<String>>,
253
+ free_str: Vec<u32>,
254
+ arrays: Vec<GcSlot<Vec<Value>>>,
255
+ free_arr: Vec<u32>,
256
+ objects: Vec<GcSlot<ClassInstance>>,
257
+ free_obj: Vec<u32>,
258
+ buffers: Vec<GcSlot<Vec<u8>>>,
259
+ free_buf: Vec<u32>,
260
+ allocations: usize,
261
+ allocs_since_gc: usize,
262
+ gc_threshold: usize,
263
+ collections: usize,
264
+ freed_objects: usize,
265
+ }
266
+
267
+ impl Default for MarkSweepHeap {
268
+ fn default() -> Self {
269
+ Self {
270
+ strings: Vec::new(),
271
+ free_str: Vec::new(),
272
+ arrays: Vec::new(),
273
+ free_arr: Vec::new(),
274
+ objects: Vec::new(),
275
+ free_obj: Vec::new(),
276
+ buffers: Vec::new(),
277
+ free_buf: Vec::new(),
278
+ allocations: 0,
279
+ allocs_since_gc: 0,
280
+ gc_threshold: 4096,
281
+ collections: 0,
282
+ freed_objects: 0,
283
+ }
284
+ }
285
+ }
286
+
287
+ impl MarkSweepHeap {
288
+ fn alloc_in<T>(slots: &mut Vec<GcSlot<T>>, free: &mut Vec<u32>, val: T) -> u32 {
289
+ if let Some(idx) = free.pop() {
290
+ slots[idx as usize] = GcSlot {
291
+ marked: false,
292
+ data: Some(val),
293
+ };
294
+ idx
295
+ } else {
296
+ let idx = slots.len() as u32;
297
+ slots.push(GcSlot {
298
+ marked: false,
299
+ data: Some(val),
300
+ });
301
+ idx
302
+ }
303
+ }
304
+
305
+ fn mark_value(&mut self, val: Value, worklist: &mut Vec<Value>) {
306
+ match val {
307
+ Value::Str(h) => {
308
+ if let Some(slot) = self.strings.get_mut(h.0 as usize)
309
+ && slot.data.is_some()
310
+ && !slot.marked
311
+ {
312
+ slot.marked = true;
313
+ }
314
+ }
315
+ Value::RawBuffer(h) => {
316
+ if let Some(slot) = self.buffers.get_mut(h.0 as usize)
317
+ && slot.data.is_some()
318
+ && !slot.marked
319
+ {
320
+ slot.marked = true;
321
+ }
322
+ }
323
+ Value::Array(h) => {
324
+ if let Some(slot) = self.arrays.get_mut(h.0 as usize)
325
+ && !slot.marked
326
+ && let Some(items) = &slot.data
327
+ {
328
+ slot.marked = true;
329
+ worklist.extend(items.iter().copied());
330
+ }
331
+ }
332
+ Value::Object(h) => {
333
+ if let Some(slot) = self.objects.get_mut(h.0 as usize)
334
+ && !slot.marked
335
+ && let Some(inst) = &slot.data
336
+ {
337
+ slot.marked = true;
338
+ worklist.extend(inst.fields.values().copied());
339
+ }
340
+ }
341
+ Value::Nil | Value::Bool(_) | Value::Int(_) | Value::Float(_) | Value::FunctionRef(_) => {
342
+ }
343
+ }
344
+ }
345
+ }
346
+
347
+ impl MemoryHeap for MarkSweepHeap {
348
+ fn mode(&self) -> MemoryMode {
349
+ MemoryMode::TracingGc
350
+ }
351
+
352
+ fn alloc_string(&mut self, s: String) -> StrHandle {
353
+ self.allocations += 1;
354
+ self.allocs_since_gc += 1;
355
+ StrHandle(Self::alloc_in(&mut self.strings, &mut self.free_str, s))
356
+ }
357
+
358
+ fn get_string(&self, h: StrHandle) -> Option<&str> {
359
+ self.strings
360
+ .get(h.0 as usize)
361
+ .and_then(|s| s.data.as_deref())
362
+ }
363
+
364
+ fn alloc_array(&mut self, items: Vec<Value>) -> ArrHandle {
365
+ self.allocations += 1;
366
+ self.allocs_since_gc += 1;
367
+ ArrHandle(Self::alloc_in(&mut self.arrays, &mut self.free_arr, items))
368
+ }
369
+
370
+ fn get_array(&self, h: ArrHandle) -> Option<&[Value]> {
371
+ self.arrays
372
+ .get(h.0 as usize)
373
+ .and_then(|s| s.data.as_deref())
374
+ }
375
+
376
+ fn get_array_mut(&mut self, h: ArrHandle) -> Option<&mut Vec<Value>> {
377
+ self.arrays
378
+ .get_mut(h.0 as usize)
379
+ .and_then(|s| s.data.as_mut())
380
+ }
381
+
382
+ fn alloc_object(&mut self, instance: ClassInstance) -> ObjHandle {
383
+ self.allocations += 1;
384
+ self.allocs_since_gc += 1;
385
+ ObjHandle(Self::alloc_in(&mut self.objects, &mut self.free_obj, instance))
386
+ }
387
+
388
+ fn get_object(&self, h: ObjHandle) -> Option<&ClassInstance> {
389
+ self.objects
390
+ .get(h.0 as usize)
391
+ .and_then(|s| s.data.as_ref())
392
+ }
393
+
394
+ fn get_object_mut(&mut self, h: ObjHandle) -> Option<&mut ClassInstance> {
395
+ self.objects
396
+ .get_mut(h.0 as usize)
397
+ .and_then(|s| s.data.as_mut())
398
+ }
399
+
400
+ fn alloc_buffer(&mut self, size: usize) -> BufHandle {
401
+ self.allocations += 1;
402
+ self.allocs_since_gc += 1;
403
+ BufHandle(Self::alloc_in(
404
+ &mut self.buffers,
405
+ &mut self.free_buf,
406
+ vec![0u8; size],
407
+ ))
408
+ }
409
+
410
+ fn buffer_len(&self, h: BufHandle) -> Option<usize> {
411
+ self.buffers
412
+ .get(h.0 as usize)
413
+ .and_then(|s| s.data.as_ref())
414
+ .map(|b| b.len())
415
+ }
416
+
417
+ fn buffer_slice(&self, h: BufHandle) -> Option<&[u8]> {
418
+ self.buffers
419
+ .get(h.0 as usize)
420
+ .and_then(|s| s.data.as_deref())
421
+ }
422
+
423
+ fn buffer_slice_mut(&mut self, h: BufHandle) -> Option<&mut [u8]> {
424
+ self.buffers
425
+ .get_mut(h.0 as usize)
426
+ .and_then(|s| s.data.as_deref_mut())
427
+ }
428
+
429
+ fn maybe_collect(&mut self, roots: &[Value]) -> usize {
430
+ if self.allocs_since_gc >= self.gc_threshold {
431
+ self.collect_garbage(roots)
432
+ } else {
433
+ 0
434
+ }
435
+ }
436
+
437
+ fn collect_garbage(&mut self, roots: &[Value]) -> usize {
438
+ self.allocs_since_gc = 0;
439
+ self.collections += 1;
440
+ let mut worklist = roots.to_vec();
441
+ while let Some(v) = worklist.pop() {
442
+ self.mark_value(v, &mut worklist);
443
+ }
444
+
445
+ let mut freed = 0usize;
446
+ for (idx, slot) in self.strings.iter_mut().enumerate() {
447
+ if slot.data.is_some() {
448
+ if slot.marked {
449
+ slot.marked = false;
450
+ } else {
451
+ slot.data = None;
452
+ self.free_str.push(idx as u32);
453
+ freed += 1;
454
+ }
455
+ }
456
+ }
457
+ for (idx, slot) in self.arrays.iter_mut().enumerate() {
458
+ if slot.data.is_some() {
459
+ if slot.marked {
460
+ slot.marked = false;
461
+ } else {
462
+ slot.data = None;
463
+ self.free_arr.push(idx as u32);
464
+ freed += 1;
465
+ }
466
+ }
467
+ }
468
+ for (idx, slot) in self.objects.iter_mut().enumerate() {
469
+ if slot.data.is_some() {
470
+ if slot.marked {
471
+ slot.marked = false;
472
+ } else {
473
+ slot.data = None;
474
+ self.free_obj.push(idx as u32);
475
+ freed += 1;
476
+ }
477
+ }
478
+ }
479
+ for (idx, slot) in self.buffers.iter_mut().enumerate() {
480
+ if slot.data.is_some() {
481
+ if slot.marked {
482
+ slot.marked = false;
483
+ } else {
484
+ slot.data = None;
485
+ self.free_buf.push(idx as u32);
486
+ freed += 1;
487
+ }
488
+ }
489
+ }
490
+ self.freed_objects += freed;
491
+ freed
492
+ }
493
+
494
+ fn stats(&self) -> GcStats {
495
+ let live = self.strings.iter().filter(|s| s.data.is_some()).count()
496
+ + self.arrays.iter().filter(|s| s.data.is_some()).count()
497
+ + self.objects.iter().filter(|s| s.data.is_some()).count()
498
+ + self.buffers.iter().filter(|s| s.data.is_some()).count();
499
+ GcStats {
500
+ allocations: self.allocations,
501
+ collections: self.collections,
502
+ freed_objects: self.freed_objects,
503
+ live_objects: live,
504
+ }
505
+ }
506
+ }
507
+
508
+ pub fn make_heap(mode: MemoryMode) -> Box<dyn MemoryHeap> {
509
+ match mode {
510
+ MemoryMode::Arena => Box::new(ArenaHeap::default()),
511
+ MemoryMode::TracingGc => Box::new(MarkSweepHeap::default()),
512
+ }
513
+ }
514
+
515
+ pub fn eval_builtin(
516
+ builtin: BuiltinId,
517
+ args: &[Value],
518
+ heap: &mut dyn MemoryHeap,
519
+ stdout_sink: &mut Option<String>,
520
+ ) -> Result<Value, PolyError> {
521
+ match builtin {
522
+ BuiltinId::Print | BuiltinId::Println => {
523
+ let line: Vec<String> = args.iter().map(|v| v.format(heap)).collect();
524
+ let text = line.join(" ");
525
+ if let Some(sink) = stdout_sink {
526
+ if builtin == BuiltinId::Println {
527
+ let _ = writeln!(sink, "{text}");
528
+ } else {
529
+ let _ = write!(sink, "{text}");
530
+ }
531
+ } else if builtin == BuiltinId::Println {
532
+ println!("{text}");
533
+ } else {
534
+ print!("{text}");
535
+ }
536
+ Ok(Value::Nil)
537
+ }
538
+ BuiltinId::Printf => {
539
+ let fmt = args
540
+ .first()
541
+ .map(|v| match v {
542
+ Value::Str(h) => heap.get_string(*h).unwrap_or("").to_string(),
543
+ other => other.format(heap),
544
+ })
545
+ .unwrap_or_default();
546
+ let formatted = format_printf(&fmt, &args[1.min(args.len())..], heap);
547
+ if let Some(sink) = stdout_sink {
548
+ let _ = write!(sink, "{formatted}");
549
+ } else {
550
+ print!("{formatted}");
551
+ }
552
+ Ok(Value::Int(formatted.len() as i64))
553
+ }
554
+ BuiltinId::Len => {
555
+ let v = args
556
+ .first()
557
+ .copied()
558
+ .ok_or_else(|| PolyError::msg("E0401", "len() expects 1 argument"))?;
559
+ let len = match v {
560
+ Value::Str(h) => heap.get_string(h).map(|s| s.len()).unwrap_or(0),
561
+ Value::Array(h) => heap.get_array(h).map(|a| a.len()).unwrap_or(0),
562
+ Value::RawBuffer(h) => heap.buffer_len(h).unwrap_or(0),
563
+ Value::Object(h) => heap.get_object(h).map(|o| o.fields.len()).unwrap_or(0),
564
+ other => {
565
+ return Err(PolyError::msg(
566
+ "E0402",
567
+ format!("len() unsupported for type {}", other.type_name()),
568
+ ));
569
+ }
570
+ };
571
+ Ok(Value::Int(len as i64))
572
+ }
573
+ BuiltinId::Str => {
574
+ let s = args.first().copied().unwrap_or(Value::Nil).format(heap);
575
+ Ok(Value::Str(heap.alloc_string(s)))
576
+ }
577
+ BuiltinId::Int => {
578
+ let v = args.first().copied().unwrap_or(Value::Int(0));
579
+ let res = match v {
580
+ Value::Int(i) => i,
581
+ Value::Float(f) => f as i64,
582
+ Value::Bool(b) => i64::from(b),
583
+ Value::Str(h) => heap
584
+ .get_string(h)
585
+ .unwrap_or("0")
586
+ .trim()
587
+ .parse::<i64>()
588
+ .map_err(|_| PolyError::msg("E0403", "cannot parse string as int"))?,
589
+ other => {
590
+ return Err(PolyError::msg(
591
+ "E0403",
592
+ format!("cannot convert {} to int", other.type_name()),
593
+ ));
594
+ }
595
+ };
596
+ Ok(Value::Int(res))
597
+ }
598
+ BuiltinId::Float => {
599
+ let v = args.first().copied().unwrap_or(Value::Float(0.0));
600
+ let res = match v {
601
+ Value::Float(f) => f,
602
+ Value::Int(i) => i as f64,
603
+ Value::Bool(b) => {
604
+ if b {
605
+ 1.0
606
+ } else {
607
+ 0.0
608
+ }
609
+ }
610
+ Value::Str(h) => heap
611
+ .get_string(h)
612
+ .unwrap_or("0")
613
+ .trim()
614
+ .parse::<f64>()
615
+ .map_err(|_| PolyError::msg("E0403", "cannot parse string as float"))?,
616
+ other => {
617
+ return Err(PolyError::msg(
618
+ "E0403",
619
+ format!("cannot convert {} to float", other.type_name()),
620
+ ));
621
+ }
622
+ };
623
+ Ok(Value::Float(res))
624
+ }
625
+ BuiltinId::Bool => Ok(Value::Bool(
626
+ args.first().copied().unwrap_or(Value::Nil).is_truthy(heap),
627
+ )),
628
+ BuiltinId::Abs => {
629
+ let v = args.first().copied().unwrap_or(Value::Int(0));
630
+ match v {
631
+ Value::Int(i) => Ok(Value::Int(i.abs())),
632
+ Value::Float(f) => Ok(Value::Float(f.abs())),
633
+ other => Err(PolyError::msg(
634
+ "E0404",
635
+ format!("abs() expects number, got {}", other.type_name()),
636
+ )),
637
+ }
638
+ }
639
+ BuiltinId::Min => {
640
+ if args.len() < 2 {
641
+ return Err(PolyError::msg("E0401", "min() expects 2 arguments"));
642
+ }
643
+ match (args[0], args[1]) {
644
+ (Value::Int(a), Value::Int(b)) => Ok(Value::Int(a.min(b))),
645
+ (Value::Float(a), Value::Float(b)) => Ok(Value::Float(a.min(b))),
646
+ (Value::Int(a), Value::Float(b)) => Ok(Value::Float((a as f64).min(b))),
647
+ (Value::Float(a), Value::Int(b)) => Ok(Value::Float(a.min(b as f64))),
648
+ _ => Err(PolyError::msg("E0404", "min() expects numbers")),
649
+ }
650
+ }
651
+ BuiltinId::Max => {
652
+ if args.len() < 2 {
653
+ return Err(PolyError::msg("E0401", "max() expects 2 arguments"));
654
+ }
655
+ match (args[0], args[1]) {
656
+ (Value::Int(a), Value::Int(b)) => Ok(Value::Int(a.max(b))),
657
+ (Value::Float(a), Value::Float(b)) => Ok(Value::Float(a.max(b))),
658
+ (Value::Int(a), Value::Float(b)) => Ok(Value::Float((a as f64).max(b))),
659
+ (Value::Float(a), Value::Int(b)) => Ok(Value::Float(a.max(b as f64))),
660
+ _ => Err(PolyError::msg("E0404", "max() expects numbers")),
661
+ }
662
+ }
663
+ BuiltinId::Sqrt => {
664
+ let x = to_f64(args.first().copied().unwrap_or(Value::Float(0.0)))?;
665
+ Ok(Value::Float(x.sqrt()))
666
+ }
667
+ BuiltinId::Pow => {
668
+ let x = to_f64(args.first().copied().unwrap_or(Value::Float(0.0)))?;
669
+ let y = to_f64(args.get(1).copied().unwrap_or(Value::Float(1.0)))?;
670
+ Ok(Value::Float(x.powf(y)))
671
+ }
672
+ BuiltinId::Push => {
673
+ if args.len() < 2 {
674
+ return Err(PolyError::msg("E0401", "push() expects array and value"));
675
+ }
676
+ if let Value::Array(h) = args[0]
677
+ && let Some(arr) = heap.get_array_mut(h)
678
+ {
679
+ arr.push(args[1]);
680
+ return Ok(Value::Int(arr.len() as i64));
681
+ }
682
+ Err(PolyError::msg("E0404", "first argument to push() must be an array"))
683
+ }
684
+ BuiltinId::Pop => {
685
+ if let Some(Value::Array(h)) = args.first().copied()
686
+ && let Some(arr) = heap.get_array_mut(h)
687
+ {
688
+ return Ok(arr.pop().unwrap_or(Value::Nil));
689
+ }
690
+ Err(PolyError::msg("E0404", "pop() expects an array"))
691
+ }
692
+ BuiltinId::TypeOf => {
693
+ let t = args.first().copied().unwrap_or(Value::Nil).type_name();
694
+ Ok(Value::Str(heap.alloc_string(t.to_string())))
695
+ }
696
+ BuiltinId::AllocBuf => {
697
+ let size = match args.first().copied() {
698
+ Some(Value::Int(n)) if n >= 0 => n as usize,
699
+ _ => return Err(PolyError::msg("E0404", "alloc_buf() expects non-negative int")),
700
+ };
701
+ Ok(Value::RawBuffer(heap.alloc_buffer(size)))
702
+ }
703
+ BuiltinId::ReadU8 => {
704
+ let (Some(Value::RawBuffer(h)), Some(Value::Int(off))) =
705
+ (args.first().copied(), args.get(1).copied())
706
+ else {
707
+ return Err(PolyError::msg("E0404", "read_u8(buf, offset) invalid args"));
708
+ };
709
+ let slice = heap
710
+ .buffer_slice(h)
711
+ .ok_or_else(|| PolyError::msg("E0405", "dangling buffer handle"))?;
712
+ let idx = usize::try_from(off)
713
+ .ok()
714
+ .filter(|&i| i < slice.len())
715
+ .ok_or_else(|| PolyError::msg("E0406", "buffer read out of bounds"))?;
716
+ Ok(Value::Int(i64::from(slice[idx])))
717
+ }
718
+ BuiltinId::WriteU8 => {
719
+ let (Some(Value::RawBuffer(h)), Some(Value::Int(off)), Some(Value::Int(byte))) =
720
+ (args.first().copied(), args.get(1).copied(), args.get(2).copied())
721
+ else {
722
+ return Err(PolyError::msg(
723
+ "E0404",
724
+ "write_u8(buf, offset, val) invalid args",
725
+ ));
726
+ };
727
+ let slice = heap
728
+ .buffer_slice_mut(h)
729
+ .ok_or_else(|| PolyError::msg("E0405", "dangling buffer handle"))?;
730
+ let idx = usize::try_from(off)
731
+ .ok()
732
+ .filter(|&i| i < slice.len())
733
+ .ok_or_else(|| PolyError::msg("E0406", "buffer write out of bounds"))?;
734
+ slice[idx] = (byte & 0xff) as u8;
735
+ Ok(Value::Nil)
736
+ }
737
+ BuiltinId::BufLen => {
738
+ if let Some(Value::RawBuffer(h)) = args.first().copied() {
739
+ return Ok(Value::Int(heap.buffer_len(h).unwrap_or(0) as i64));
740
+ }
741
+ Err(PolyError::msg("E0404", "buf_len() expects a buffer"))
742
+ }
743
+ BuiltinId::ClockMs => {
744
+ let ms = SystemTime::now()
745
+ .duration_since(UNIX_EPOCH)
746
+ .map(|d| d.as_millis() as i64)
747
+ .unwrap_or(0);
748
+ Ok(Value::Int(ms))
749
+ }
750
+ BuiltinId::Assert => {
751
+ let ok = args.first().copied().unwrap_or(Value::Nil).is_truthy(heap);
752
+ if !ok {
753
+ let msg = args
754
+ .get(1)
755
+ .map(|v| v.format(heap))
756
+ .unwrap_or_else(|| "assertion failed".to_string());
757
+ return Err(PolyError::msg("E0407", msg));
758
+ }
759
+ Ok(Value::Bool(true))
760
+ }
761
+ }
762
+ }
763
+
764
+ fn to_f64(v: Value) -> Result<f64, PolyError> {
765
+ match v {
766
+ Value::Float(f) => Ok(f),
767
+ Value::Int(i) => Ok(i as f64),
768
+ other => Err(PolyError::msg(
769
+ "E0404",
770
+ format!("expected numeric value, got {}", other.type_name()),
771
+ )),
772
+ }
773
+ }
774
+
775
+ fn format_printf(fmt: &str, args: &[Value], heap: &dyn MemoryHeap) -> String {
776
+ let mut out = String::new();
777
+ let mut chars = fmt.chars().peekable();
778
+ let mut arg_idx = 0usize;
779
+
780
+ while let Some(ch) = chars.next() {
781
+ if ch == '%' {
782
+ if chars.peek() == Some(&'%') {
783
+ chars.next();
784
+ out.push('%');
785
+ continue;
786
+ }
787
+ // Parse optional precision like %.2f
788
+ let mut spec = String::new();
789
+ while let Some(&nc) = chars.peek() {
790
+ spec.push(nc);
791
+ chars.next();
792
+ if nc.is_ascii_alphabetic() {
793
+ break;
794
+ }
795
+ }
796
+ let val = args.get(arg_idx).copied().unwrap_or(Value::Nil);
797
+ arg_idx += 1;
798
+ if spec.ends_with('f') || spec.ends_with('g') {
799
+ let f = match val {
800
+ Value::Float(x) => x,
801
+ Value::Int(i) => i as f64,
802
+ _ => 0.0,
803
+ };
804
+ if let Some(prec) = spec
805
+ .strip_prefix('.')
806
+ .and_then(|s| s.strip_suffix('f'))
807
+ .and_then(|p| p.parse::<usize>().ok())
808
+ {
809
+ let _ = write!(out, "{f:.prec$}");
810
+ } else {
811
+ let _ = write!(out, "{f}");
812
+ }
813
+ } else if spec.ends_with('d') || spec.ends_with('i') {
814
+ let i = match val {
815
+ Value::Int(i) => i,
816
+ Value::Float(f) => f as i64,
817
+ Value::Bool(b) => i64::from(b),
818
+ _ => 0,
819
+ };
820
+ let _ = write!(out, "{i}");
821
+ } else {
822
+ out.push_str(&val.format(heap));
823
+ }
824
+ } else {
825
+ out.push(ch);
826
+ }
827
+ }
828
+ out
829
+ }