polycomp 0.0.0-stage → 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.
package/src/runtime.rs ADDED
@@ -0,0 +1,1104 @@
1
+ use crate::diagnostics::PolyError;
2
+ use crate::ir::{BuiltinId, FnId};
3
+ use regex::{Regex, RegexBuilder};
4
+ use rustc_hash::FxHashMap;
5
+ use std::fmt::Write as _;
6
+ use std::time::{SystemTime, UNIX_EPOCH};
7
+
8
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9
+ pub struct ObjHandle(pub u32);
10
+
11
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12
+ pub struct StrHandle(pub u32);
13
+
14
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15
+ pub struct RegHandle(pub u32);
16
+
17
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
18
+ pub struct ArrHandle(pub u32);
19
+
20
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21
+ pub struct BufHandle(pub u32);
22
+
23
+ #[derive(Debug, Clone, Copy, PartialEq)]
24
+ pub enum Value {
25
+ Nil,
26
+ Bool(bool),
27
+ Int(i64),
28
+ Float(f64),
29
+ Str(StrHandle),
30
+ Regex(RegHandle),
31
+ Array(ArrHandle),
32
+ Object(ObjHandle),
33
+ RawBuffer(BufHandle),
34
+ FunctionRef(FnId),
35
+ }
36
+
37
+ impl Value {
38
+ pub fn is_truthy(self, heap: &dyn MemoryHeap) -> bool {
39
+ match self {
40
+ Value::Nil => false,
41
+ Value::Bool(b) => b,
42
+ Value::Int(i) => i != 0,
43
+ Value::Float(f) => f != 0.0 && !f.is_nan(),
44
+ Value::Str(h) => heap.get_string(h).is_some_and(|s| !s.is_empty()),
45
+ Value::Array(h) => heap.get_array(h).is_some_and(|a| !a.is_empty()),
46
+ Value::Regex(_) | Value::Object(_) | Value::RawBuffer(_) | Value::FunctionRef(_) => true,
47
+ }
48
+ }
49
+
50
+ pub fn type_name(self) -> &'static str {
51
+ match self {
52
+ Value::Nil => "nil",
53
+ Value::Bool(_) => "bool",
54
+ Value::Int(_) => "int",
55
+ Value::Float(_) => "float",
56
+ Value::Str(_) => "string",
57
+ Value::Regex(_) => "regex",
58
+ Value::Array(_) => "array",
59
+ Value::Object(_) => "object",
60
+ Value::RawBuffer(_) => "buffer",
61
+ Value::FunctionRef(_) => "function",
62
+ }
63
+ }
64
+
65
+ pub fn format(self, heap: &dyn MemoryHeap) -> String {
66
+ match self {
67
+ Value::Nil => "nil".to_string(),
68
+ Value::Bool(b) => b.to_string(),
69
+ Value::Int(i) => i.to_string(),
70
+ Value::Float(f) => {
71
+ if f.fract() == 0.0 && f.abs() < 1e15 {
72
+ format!("{f:.1}")
73
+ } else {
74
+ format!("{f}")
75
+ }
76
+ }
77
+ Value::Str(h) => heap.get_string(h).unwrap_or("<freed str>").to_string(),
78
+ Value::Regex(h) => {
79
+ if let Some(r) = heap.get_regex(h) {
80
+ format!("/{}/", r.as_str())
81
+ } else {
82
+ "<freed regex>".to_string()
83
+ }
84
+ }
85
+ Value::Array(h) => {
86
+ if let Some(items) = heap.get_array(h) {
87
+ let parts: Vec<String> = items.iter().map(|v| v.format(heap)).collect();
88
+ format!("[{}]", parts.join(", "))
89
+ } else {
90
+ "<freed array>".to_string()
91
+ }
92
+ }
93
+ Value::Object(h) => {
94
+ if let Some(obj) = heap.get_object(h) {
95
+ let parts: Vec<String> = obj
96
+ .fields
97
+ .iter()
98
+ .map(|(k, v)| format!("{k}: {}", v.format(heap)))
99
+ .collect();
100
+ format!("{} {{ {} }}", obj.class_name, parts.join(", "))
101
+ } else {
102
+ "<freed object>".to_string()
103
+ }
104
+ }
105
+ Value::RawBuffer(h) => {
106
+ let len = heap.buffer_len(h).unwrap_or(0);
107
+ format!("<buffer:{len}B>")
108
+ }
109
+ Value::FunctionRef(id) => format!("<fn#{}>", id.0),
110
+ }
111
+ }
112
+ }
113
+
114
+ #[derive(Debug, Clone)]
115
+ pub struct ClassInstance {
116
+ pub class_name: String,
117
+ pub fields: FxHashMap<String, Value>,
118
+ }
119
+
120
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
121
+ pub enum MemoryMode {
122
+ Arena,
123
+ TracingGc,
124
+ }
125
+
126
+ #[derive(Debug, Clone, Copy, Default)]
127
+ pub struct GcStats {
128
+ pub allocations: usize,
129
+ pub collections: usize,
130
+ pub freed_objects: usize,
131
+ pub live_objects: usize,
132
+ }
133
+
134
+ pub trait MemoryHeap: Send {
135
+ fn mode(&self) -> MemoryMode;
136
+ fn alloc_string(&mut self, s: String) -> StrHandle;
137
+ fn get_string(&self, h: StrHandle) -> Option<&str>;
138
+
139
+ fn alloc_regex(&mut self, pattern: &str, flags: &str) -> Result<RegHandle, PolyError>;
140
+ fn get_regex(&self, h: RegHandle) -> Option<&Regex>;
141
+
142
+ fn alloc_array(&mut self, items: Vec<Value>) -> ArrHandle;
143
+ fn get_array(&self, h: ArrHandle) -> Option<&[Value]>;
144
+ fn get_array_mut(&mut self, h: ArrHandle) -> Option<&mut Vec<Value>>;
145
+
146
+ fn alloc_object(&mut self, instance: ClassInstance) -> ObjHandle;
147
+ fn get_object(&self, h: ObjHandle) -> Option<&ClassInstance>;
148
+ fn get_object_mut(&mut self, h: ObjHandle) -> Option<&mut ClassInstance>;
149
+
150
+ fn alloc_buffer(&mut self, size: usize) -> BufHandle;
151
+ fn buffer_len(&self, h: BufHandle) -> Option<usize>;
152
+ fn buffer_slice(&self, h: BufHandle) -> Option<&[u8]>;
153
+ fn buffer_slice_mut(&mut self, h: BufHandle) -> Option<&mut [u8]>;
154
+
155
+ fn maybe_collect(&mut self, roots: &[Value]) -> usize;
156
+ fn collect_garbage(&mut self, roots: &[Value]) -> usize;
157
+ fn stats(&self) -> GcStats;
158
+ }
159
+
160
+ #[derive(Default)]
161
+ pub struct ArenaHeap {
162
+ strings: Vec<String>,
163
+ string_intern: FxHashMap<String, StrHandle>,
164
+ regexes: Vec<Regex>,
165
+ regex_intern: FxHashMap<(String, String), RegHandle>,
166
+ arrays: Vec<Vec<Value>>,
167
+ objects: Vec<ClassInstance>,
168
+ buffers: Vec<Vec<u8>>,
169
+ allocations: usize,
170
+ }
171
+
172
+ impl MemoryHeap for ArenaHeap {
173
+ fn mode(&self) -> MemoryMode {
174
+ MemoryMode::Arena
175
+ }
176
+
177
+ fn alloc_string(&mut self, s: String) -> StrHandle {
178
+ if let Some(&h) = self.string_intern.get(&s) {
179
+ return h;
180
+ }
181
+ let h = StrHandle(self.strings.len() as u32);
182
+ self.string_intern.insert(s.clone(), h);
183
+ self.strings.push(s);
184
+ self.allocations += 1;
185
+ h
186
+ }
187
+
188
+ fn get_string(&self, h: StrHandle) -> Option<&str> {
189
+ self.strings.get(h.0 as usize).map(|s| s.as_str())
190
+ }
191
+
192
+ fn alloc_regex(&mut self, pattern: &str, flags: &str) -> Result<RegHandle, PolyError> {
193
+ let key = (pattern.to_string(), flags.to_string());
194
+ if let Some(&h) = self.regex_intern.get(&key) {
195
+ return Ok(h);
196
+ }
197
+ let mut builder = RegexBuilder::new(pattern);
198
+ builder.case_insensitive(flags.contains('i'));
199
+ builder.multi_line(flags.contains('m'));
200
+ builder.dot_matches_new_line(flags.contains('s'));
201
+ let re = builder
202
+ .build()
203
+ .map_err(|e| PolyError::msg("E0410", format!("invalid regex '/{pattern}/': {e}")))?;
204
+ let h = RegHandle(self.regexes.len() as u32);
205
+ self.regex_intern.insert(key, h);
206
+ self.regexes.push(re);
207
+ self.allocations += 1;
208
+ Ok(h)
209
+ }
210
+
211
+ fn get_regex(&self, h: RegHandle) -> Option<&Regex> {
212
+ self.regexes.get(h.0 as usize)
213
+ }
214
+
215
+ fn alloc_array(&mut self, items: Vec<Value>) -> ArrHandle {
216
+ let h = ArrHandle(self.arrays.len() as u32);
217
+ self.arrays.push(items);
218
+ self.allocations += 1;
219
+ h
220
+ }
221
+
222
+ fn get_array(&self, h: ArrHandle) -> Option<&[Value]> {
223
+ self.arrays.get(h.0 as usize).map(|v| v.as_slice())
224
+ }
225
+
226
+ fn get_array_mut(&mut self, h: ArrHandle) -> Option<&mut Vec<Value>> {
227
+ self.arrays.get_mut(h.0 as usize)
228
+ }
229
+
230
+ fn alloc_object(&mut self, instance: ClassInstance) -> ObjHandle {
231
+ let h = ObjHandle(self.objects.len() as u32);
232
+ self.objects.push(instance);
233
+ self.allocations += 1;
234
+ h
235
+ }
236
+
237
+ fn get_object(&self, h: ObjHandle) -> Option<&ClassInstance> {
238
+ self.objects.get(h.0 as usize)
239
+ }
240
+
241
+ fn get_object_mut(&mut self, h: ObjHandle) -> Option<&mut ClassInstance> {
242
+ self.objects.get_mut(h.0 as usize)
243
+ }
244
+
245
+ fn alloc_buffer(&mut self, size: usize) -> BufHandle {
246
+ let h = BufHandle(self.buffers.len() as u32);
247
+ self.buffers.push(vec![0u8; size]);
248
+ self.allocations += 1;
249
+ h
250
+ }
251
+
252
+ fn buffer_len(&self, h: BufHandle) -> Option<usize> {
253
+ self.buffers.get(h.0 as usize).map(|b| b.len())
254
+ }
255
+
256
+ fn buffer_slice(&self, h: BufHandle) -> Option<&[u8]> {
257
+ self.buffers.get(h.0 as usize).map(|b| b.as_slice())
258
+ }
259
+
260
+ fn buffer_slice_mut(&mut self, h: BufHandle) -> Option<&mut [u8]> {
261
+ self.buffers.get_mut(h.0 as usize).map(|b| b.as_mut_slice())
262
+ }
263
+
264
+ fn maybe_collect(&mut self, _roots: &[Value]) -> usize {
265
+ 0
266
+ }
267
+
268
+ fn collect_garbage(&mut self, _roots: &[Value]) -> usize {
269
+ 0
270
+ }
271
+
272
+ fn stats(&self) -> GcStats {
273
+ GcStats {
274
+ allocations: self.allocations,
275
+ collections: 0,
276
+ freed_objects: 0,
277
+ live_objects: self.strings.len()
278
+ + self.regexes.len()
279
+ + self.arrays.len()
280
+ + self.objects.len()
281
+ + self.buffers.len(),
282
+ }
283
+ }
284
+ }
285
+
286
+ struct GcSlot<T> {
287
+ marked: bool,
288
+ data: Option<T>,
289
+ }
290
+
291
+ pub struct MarkSweepHeap {
292
+ strings: Vec<GcSlot<String>>,
293
+ free_str: Vec<u32>,
294
+ regexes: Vec<GcSlot<Regex>>,
295
+ free_reg: Vec<u32>,
296
+ arrays: Vec<GcSlot<Vec<Value>>>,
297
+ free_arr: Vec<u32>,
298
+ objects: Vec<GcSlot<ClassInstance>>,
299
+ free_obj: Vec<u32>,
300
+ buffers: Vec<GcSlot<Vec<u8>>>,
301
+ free_buf: Vec<u32>,
302
+ allocations: usize,
303
+ allocs_since_gc: usize,
304
+ gc_threshold: usize,
305
+ collections: usize,
306
+ freed_objects: usize,
307
+ }
308
+
309
+ impl Default for MarkSweepHeap {
310
+ fn default() -> Self {
311
+ Self {
312
+ strings: Vec::new(),
313
+ free_str: Vec::new(),
314
+ regexes: Vec::new(),
315
+ free_reg: Vec::new(),
316
+ arrays: Vec::new(),
317
+ free_arr: Vec::new(),
318
+ objects: Vec::new(),
319
+ free_obj: Vec::new(),
320
+ buffers: Vec::new(),
321
+ free_buf: Vec::new(),
322
+ allocations: 0,
323
+ allocs_since_gc: 0,
324
+ gc_threshold: 4096,
325
+ collections: 0,
326
+ freed_objects: 0,
327
+ }
328
+ }
329
+ }
330
+
331
+ impl MarkSweepHeap {
332
+ fn alloc_in<T>(slots: &mut Vec<GcSlot<T>>, free: &mut Vec<u32>, val: T) -> u32 {
333
+ if let Some(idx) = free.pop() {
334
+ slots[idx as usize] = GcSlot {
335
+ marked: false,
336
+ data: Some(val),
337
+ };
338
+ idx
339
+ } else {
340
+ let idx = slots.len() as u32;
341
+ slots.push(GcSlot {
342
+ marked: false,
343
+ data: Some(val),
344
+ });
345
+ idx
346
+ }
347
+ }
348
+
349
+ fn mark_value(&mut self, val: Value, worklist: &mut Vec<Value>) {
350
+ match val {
351
+ Value::Str(h) => {
352
+ if let Some(slot) = self.strings.get_mut(h.0 as usize)
353
+ && slot.data.is_some()
354
+ && !slot.marked
355
+ {
356
+ slot.marked = true;
357
+ }
358
+ }
359
+ Value::Regex(h) => {
360
+ if let Some(slot) = self.regexes.get_mut(h.0 as usize)
361
+ && slot.data.is_some()
362
+ && !slot.marked
363
+ {
364
+ slot.marked = true;
365
+ }
366
+ }
367
+ Value::RawBuffer(h) => {
368
+ if let Some(slot) = self.buffers.get_mut(h.0 as usize)
369
+ && slot.data.is_some()
370
+ && !slot.marked
371
+ {
372
+ slot.marked = true;
373
+ }
374
+ }
375
+ Value::Array(h) => {
376
+ if let Some(slot) = self.arrays.get_mut(h.0 as usize)
377
+ && !slot.marked
378
+ && let Some(items) = &slot.data
379
+ {
380
+ slot.marked = true;
381
+ worklist.extend(items.iter().copied());
382
+ }
383
+ }
384
+ Value::Object(h) => {
385
+ if let Some(slot) = self.objects.get_mut(h.0 as usize)
386
+ && !slot.marked
387
+ && let Some(inst) = &slot.data
388
+ {
389
+ slot.marked = true;
390
+ worklist.extend(inst.fields.values().copied());
391
+ }
392
+ }
393
+ Value::Nil | Value::Bool(_) | Value::Int(_) | Value::Float(_) | Value::FunctionRef(_) => {
394
+ }
395
+ }
396
+ }
397
+ }
398
+
399
+ impl MemoryHeap for MarkSweepHeap {
400
+ fn mode(&self) -> MemoryMode {
401
+ MemoryMode::TracingGc
402
+ }
403
+
404
+ fn alloc_string(&mut self, s: String) -> StrHandle {
405
+ self.allocations += 1;
406
+ self.allocs_since_gc += 1;
407
+ StrHandle(Self::alloc_in(&mut self.strings, &mut self.free_str, s))
408
+ }
409
+
410
+ fn get_string(&self, h: StrHandle) -> Option<&str> {
411
+ self.strings
412
+ .get(h.0 as usize)
413
+ .and_then(|s| s.data.as_deref())
414
+ }
415
+
416
+ fn alloc_regex(&mut self, pattern: &str, flags: &str) -> Result<RegHandle, PolyError> {
417
+ let mut builder = RegexBuilder::new(pattern);
418
+ builder.case_insensitive(flags.contains('i'));
419
+ builder.multi_line(flags.contains('m'));
420
+ builder.dot_matches_new_line(flags.contains('s'));
421
+ let re = builder
422
+ .build()
423
+ .map_err(|e| PolyError::msg("E0410", format!("invalid regex '/{pattern}/': {e}")))?;
424
+ self.allocations += 1;
425
+ self.allocs_since_gc += 1;
426
+ Ok(RegHandle(Self::alloc_in(
427
+ &mut self.regexes,
428
+ &mut self.free_reg,
429
+ re,
430
+ )))
431
+ }
432
+
433
+ fn get_regex(&self, h: RegHandle) -> Option<&Regex> {
434
+ self.regexes.get(h.0 as usize).and_then(|r| r.data.as_ref())
435
+ }
436
+
437
+ fn alloc_array(&mut self, items: Vec<Value>) -> ArrHandle {
438
+ self.allocations += 1;
439
+ self.allocs_since_gc += 1;
440
+ ArrHandle(Self::alloc_in(&mut self.arrays, &mut self.free_arr, items))
441
+ }
442
+
443
+ fn get_array(&self, h: ArrHandle) -> Option<&[Value]> {
444
+ self.arrays
445
+ .get(h.0 as usize)
446
+ .and_then(|s| s.data.as_deref())
447
+ }
448
+
449
+ fn get_array_mut(&mut self, h: ArrHandle) -> Option<&mut Vec<Value>> {
450
+ self.arrays
451
+ .get_mut(h.0 as usize)
452
+ .and_then(|s| s.data.as_mut())
453
+ }
454
+
455
+ fn alloc_object(&mut self, instance: ClassInstance) -> ObjHandle {
456
+ self.allocations += 1;
457
+ self.allocs_since_gc += 1;
458
+ ObjHandle(Self::alloc_in(&mut self.objects, &mut self.free_obj, instance))
459
+ }
460
+
461
+ fn get_object(&self, h: ObjHandle) -> Option<&ClassInstance> {
462
+ self.objects
463
+ .get(h.0 as usize)
464
+ .and_then(|s| s.data.as_ref())
465
+ }
466
+
467
+ fn get_object_mut(&mut self, h: ObjHandle) -> Option<&mut ClassInstance> {
468
+ self.objects
469
+ .get_mut(h.0 as usize)
470
+ .and_then(|s| s.data.as_mut())
471
+ }
472
+
473
+ fn alloc_buffer(&mut self, size: usize) -> BufHandle {
474
+ self.allocations += 1;
475
+ self.allocs_since_gc += 1;
476
+ BufHandle(Self::alloc_in(
477
+ &mut self.buffers,
478
+ &mut self.free_buf,
479
+ vec![0u8; size],
480
+ ))
481
+ }
482
+
483
+ fn buffer_len(&self, h: BufHandle) -> Option<usize> {
484
+ self.buffers
485
+ .get(h.0 as usize)
486
+ .and_then(|s| s.data.as_ref())
487
+ .map(|b| b.len())
488
+ }
489
+
490
+ fn buffer_slice(&self, h: BufHandle) -> Option<&[u8]> {
491
+ self.buffers
492
+ .get(h.0 as usize)
493
+ .and_then(|s| s.data.as_deref())
494
+ }
495
+
496
+ fn buffer_slice_mut(&mut self, h: BufHandle) -> Option<&mut [u8]> {
497
+ self.buffers
498
+ .get_mut(h.0 as usize)
499
+ .and_then(|s| s.data.as_deref_mut())
500
+ }
501
+
502
+ fn maybe_collect(&mut self, roots: &[Value]) -> usize {
503
+ if self.allocs_since_gc >= self.gc_threshold {
504
+ self.collect_garbage(roots)
505
+ } else {
506
+ 0
507
+ }
508
+ }
509
+
510
+ fn collect_garbage(&mut self, roots: &[Value]) -> usize {
511
+ self.allocs_since_gc = 0;
512
+ self.collections += 1;
513
+ let mut worklist = roots.to_vec();
514
+ while let Some(v) = worklist.pop() {
515
+ self.mark_value(v, &mut worklist);
516
+ }
517
+
518
+ let mut freed = 0usize;
519
+ for (idx, slot) in self.strings.iter_mut().enumerate() {
520
+ if slot.data.is_some() {
521
+ if slot.marked {
522
+ slot.marked = false;
523
+ } else {
524
+ slot.data = None;
525
+ self.free_str.push(idx as u32);
526
+ freed += 1;
527
+ }
528
+ }
529
+ }
530
+ for (idx, slot) in self.regexes.iter_mut().enumerate() {
531
+ if slot.data.is_some() {
532
+ if slot.marked {
533
+ slot.marked = false;
534
+ } else {
535
+ slot.data = None;
536
+ self.free_reg.push(idx as u32);
537
+ freed += 1;
538
+ }
539
+ }
540
+ }
541
+ for (idx, slot) in self.arrays.iter_mut().enumerate() {
542
+ if slot.data.is_some() {
543
+ if slot.marked {
544
+ slot.marked = false;
545
+ } else {
546
+ slot.data = None;
547
+ self.free_arr.push(idx as u32);
548
+ freed += 1;
549
+ }
550
+ }
551
+ }
552
+ for (idx, slot) in self.objects.iter_mut().enumerate() {
553
+ if slot.data.is_some() {
554
+ if slot.marked {
555
+ slot.marked = false;
556
+ } else {
557
+ slot.data = None;
558
+ self.free_obj.push(idx as u32);
559
+ freed += 1;
560
+ }
561
+ }
562
+ }
563
+ for (idx, slot) in self.buffers.iter_mut().enumerate() {
564
+ if slot.data.is_some() {
565
+ if slot.marked {
566
+ slot.marked = false;
567
+ } else {
568
+ slot.data = None;
569
+ self.free_buf.push(idx as u32);
570
+ freed += 1;
571
+ }
572
+ }
573
+ }
574
+ self.freed_objects += freed;
575
+ freed
576
+ }
577
+
578
+ fn stats(&self) -> GcStats {
579
+ let live = self.strings.iter().filter(|s| s.data.is_some()).count()
580
+ + self.regexes.iter().filter(|s| s.data.is_some()).count()
581
+ + self.arrays.iter().filter(|s| s.data.is_some()).count()
582
+ + self.objects.iter().filter(|s| s.data.is_some()).count()
583
+ + self.buffers.iter().filter(|s| s.data.is_some()).count();
584
+ GcStats {
585
+ allocations: self.allocations,
586
+ collections: self.collections,
587
+ freed_objects: self.freed_objects,
588
+ live_objects: live,
589
+ }
590
+ }
591
+ }
592
+
593
+ pub fn make_heap(mode: MemoryMode) -> Box<dyn MemoryHeap> {
594
+ match mode {
595
+ MemoryMode::Arena => Box::new(ArenaHeap::default()),
596
+ MemoryMode::TracingGc => Box::new(MarkSweepHeap::default()),
597
+ }
598
+ }
599
+
600
+ pub fn eval_builtin(
601
+ builtin: BuiltinId,
602
+ args: &[Value],
603
+ heap: &mut dyn MemoryHeap,
604
+ stdout_sink: &mut Option<String>,
605
+ ) -> Result<Value, PolyError> {
606
+ match builtin {
607
+ BuiltinId::Print | BuiltinId::Println => {
608
+ let line: Vec<String> = args.iter().map(|v| v.format(heap)).collect();
609
+ let text = line.join(" ");
610
+ if let Some(sink) = stdout_sink {
611
+ if builtin == BuiltinId::Println {
612
+ let _ = writeln!(sink, "{text}");
613
+ } else {
614
+ let _ = write!(sink, "{text}");
615
+ }
616
+ } else if builtin == BuiltinId::Println {
617
+ println!("{text}");
618
+ } else {
619
+ print!("{text}");
620
+ }
621
+ Ok(Value::Nil)
622
+ }
623
+ BuiltinId::Printf => {
624
+ let fmt = args
625
+ .first()
626
+ .map(|v| match v {
627
+ Value::Str(h) => heap.get_string(*h).unwrap_or("").to_string(),
628
+ other => other.format(heap),
629
+ })
630
+ .unwrap_or_default();
631
+ let formatted = format_printf(&fmt, &args[1.min(args.len())..], heap);
632
+ if let Some(sink) = stdout_sink {
633
+ let _ = write!(sink, "{formatted}");
634
+ } else {
635
+ print!("{formatted}");
636
+ }
637
+ Ok(Value::Int(formatted.len() as i64))
638
+ }
639
+ BuiltinId::Sprintf => {
640
+ let fmt = args
641
+ .first()
642
+ .map(|v| match v {
643
+ Value::Str(h) => heap.get_string(*h).unwrap_or("").to_string(),
644
+ other => other.format(heap),
645
+ })
646
+ .unwrap_or_default();
647
+ let formatted = format_printf(&fmt, &args[1.min(args.len())..], heap);
648
+ Ok(Value::Str(heap.alloc_string(formatted)))
649
+ }
650
+ BuiltinId::Len => {
651
+ let v = args
652
+ .first()
653
+ .copied()
654
+ .ok_or_else(|| PolyError::msg("E0401", "len() expects 1 argument"))?;
655
+ let len = match v {
656
+ Value::Str(h) => heap.get_string(h).map(|s| s.len()).unwrap_or(0),
657
+ Value::Array(h) => heap.get_array(h).map(|a| a.len()).unwrap_or(0),
658
+ Value::RawBuffer(h) => heap.buffer_len(h).unwrap_or(0),
659
+ Value::Object(h) => heap.get_object(h).map(|o| o.fields.len()).unwrap_or(0),
660
+ other => {
661
+ return Err(PolyError::msg(
662
+ "E0402",
663
+ format!("len() unsupported for type {}", other.type_name()),
664
+ ));
665
+ }
666
+ };
667
+ Ok(Value::Int(len as i64))
668
+ }
669
+ BuiltinId::Str => {
670
+ let s = args.first().copied().unwrap_or(Value::Nil).format(heap);
671
+ Ok(Value::Str(heap.alloc_string(s)))
672
+ }
673
+ BuiltinId::Int => {
674
+ let v = args.first().copied().unwrap_or(Value::Int(0));
675
+ let res = match v {
676
+ Value::Int(i) => i,
677
+ Value::Float(f) => f as i64,
678
+ Value::Bool(b) => i64::from(b),
679
+ Value::Str(h) => heap
680
+ .get_string(h)
681
+ .unwrap_or("0")
682
+ .trim()
683
+ .parse::<i64>()
684
+ .map_err(|_| PolyError::msg("E0403", "cannot parse string as int"))?,
685
+ other => {
686
+ return Err(PolyError::msg(
687
+ "E0403",
688
+ format!("cannot convert {} to int", other.type_name()),
689
+ ));
690
+ }
691
+ };
692
+ Ok(Value::Int(res))
693
+ }
694
+ BuiltinId::Float => {
695
+ let v = args.first().copied().unwrap_or(Value::Float(0.0));
696
+ let res = match v {
697
+ Value::Float(f) => f,
698
+ Value::Int(i) => i as f64,
699
+ Value::Bool(b) => {
700
+ if b {
701
+ 1.0
702
+ } else {
703
+ 0.0
704
+ }
705
+ }
706
+ Value::Str(h) => heap
707
+ .get_string(h)
708
+ .unwrap_or("0")
709
+ .trim()
710
+ .parse::<f64>()
711
+ .map_err(|_| PolyError::msg("E0403", "cannot parse string as float"))?,
712
+ other => {
713
+ return Err(PolyError::msg(
714
+ "E0403",
715
+ format!("cannot convert {} to float", other.type_name()),
716
+ ));
717
+ }
718
+ };
719
+ Ok(Value::Float(res))
720
+ }
721
+ BuiltinId::Bool => Ok(Value::Bool(
722
+ args.first().copied().unwrap_or(Value::Nil).is_truthy(heap),
723
+ )),
724
+ BuiltinId::Abs => {
725
+ let v = args.first().copied().unwrap_or(Value::Int(0));
726
+ match v {
727
+ Value::Int(i) => Ok(Value::Int(i.abs())),
728
+ Value::Float(f) => Ok(Value::Float(f.abs())),
729
+ other => Err(PolyError::msg(
730
+ "E0404",
731
+ format!("abs() expects number, got {}", other.type_name()),
732
+ )),
733
+ }
734
+ }
735
+ BuiltinId::Min => {
736
+ if args.len() < 2 {
737
+ return Err(PolyError::msg("E0401", "min() expects 2 arguments"));
738
+ }
739
+ match (args[0], args[1]) {
740
+ (Value::Int(a), Value::Int(b)) => Ok(Value::Int(a.min(b))),
741
+ (Value::Float(a), Value::Float(b)) => Ok(Value::Float(a.min(b))),
742
+ (Value::Int(a), Value::Float(b)) => Ok(Value::Float((a as f64).min(b))),
743
+ (Value::Float(a), Value::Int(b)) => Ok(Value::Float(a.min(b as f64))),
744
+ _ => Err(PolyError::msg("E0404", "min() expects numbers")),
745
+ }
746
+ }
747
+ BuiltinId::Max => {
748
+ if args.len() < 2 {
749
+ return Err(PolyError::msg("E0401", "max() expects 2 arguments"));
750
+ }
751
+ match (args[0], args[1]) {
752
+ (Value::Int(a), Value::Int(b)) => Ok(Value::Int(a.max(b))),
753
+ (Value::Float(a), Value::Float(b)) => Ok(Value::Float(a.max(b))),
754
+ (Value::Int(a), Value::Float(b)) => Ok(Value::Float((a as f64).max(b))),
755
+ (Value::Float(a), Value::Int(b)) => Ok(Value::Float(a.max(b as f64))),
756
+ _ => Err(PolyError::msg("E0404", "max() expects numbers")),
757
+ }
758
+ }
759
+ BuiltinId::Sqrt => {
760
+ let x = to_f64(args.first().copied().unwrap_or(Value::Float(0.0)))?;
761
+ Ok(Value::Float(x.sqrt()))
762
+ }
763
+ BuiltinId::Pow => {
764
+ let x = to_f64(args.first().copied().unwrap_or(Value::Float(0.0)))?;
765
+ let y = to_f64(args.get(1).copied().unwrap_or(Value::Float(1.0)))?;
766
+ Ok(Value::Float(x.powf(y)))
767
+ }
768
+ BuiltinId::Floor => {
769
+ let x = to_f64(args.first().copied().unwrap_or(Value::Float(0.0)))?;
770
+ Ok(Value::Float(x.floor()))
771
+ }
772
+ BuiltinId::Ceil => {
773
+ let x = to_f64(args.first().copied().unwrap_or(Value::Float(0.0)))?;
774
+ Ok(Value::Float(x.ceil()))
775
+ }
776
+ BuiltinId::Round => {
777
+ let x = to_f64(args.first().copied().unwrap_or(Value::Float(0.0)))?;
778
+ Ok(Value::Float(x.round()))
779
+ }
780
+ BuiltinId::Sin => {
781
+ let x = to_f64(args.first().copied().unwrap_or(Value::Float(0.0)))?;
782
+ Ok(Value::Float(x.sin()))
783
+ }
784
+ BuiltinId::Cos => {
785
+ let x = to_f64(args.first().copied().unwrap_or(Value::Float(0.0)))?;
786
+ Ok(Value::Float(x.cos()))
787
+ }
788
+ BuiltinId::Log => {
789
+ let x = to_f64(args.first().copied().unwrap_or(Value::Float(0.0)))?;
790
+ Ok(Value::Float(x.ln()))
791
+ }
792
+ BuiltinId::Push => {
793
+ if args.len() < 2 {
794
+ return Err(PolyError::msg("E0401", "push() expects array and value"));
795
+ }
796
+ if let Value::Array(h) = args[0]
797
+ && let Some(arr) = heap.get_array_mut(h)
798
+ {
799
+ arr.push(args[1]);
800
+ return Ok(Value::Int(arr.len() as i64));
801
+ }
802
+ Err(PolyError::msg("E0404", "first argument to push() must be array"))
803
+ }
804
+ BuiltinId::Pop => {
805
+ if let Some(Value::Array(h)) = args.first().copied()
806
+ && let Some(arr) = heap.get_array_mut(h)
807
+ {
808
+ return Ok(arr.pop().unwrap_or(Value::Nil));
809
+ }
810
+ Err(PolyError::msg("E0404", "pop() expects an array"))
811
+ }
812
+ BuiltinId::TypeOf => {
813
+ let t = args.first().copied().unwrap_or(Value::Nil).type_name();
814
+ Ok(Value::Str(heap.alloc_string(t.to_string())))
815
+ }
816
+ BuiltinId::AllocBuf => {
817
+ let size = match args.first().copied() {
818
+ Some(Value::Int(n)) if n >= 0 => n as usize,
819
+ _ => return Err(PolyError::msg("E0404", "alloc_buf() expects non-negative int")),
820
+ };
821
+ Ok(Value::RawBuffer(heap.alloc_buffer(size)))
822
+ }
823
+ BuiltinId::ReadU8 => {
824
+ let (Some(Value::RawBuffer(h)), Some(Value::Int(off))) =
825
+ (args.first().copied(), args.get(1).copied())
826
+ else {
827
+ return Err(PolyError::msg("E0404", "read_u8(buf, offset) invalid args"));
828
+ };
829
+ let slice = heap
830
+ .buffer_slice(h)
831
+ .ok_or_else(|| PolyError::msg("E0405", "dangling buffer handle"))?;
832
+ let idx = usize::try_from(off)
833
+ .ok()
834
+ .filter(|&i| i < slice.len())
835
+ .ok_or_else(|| PolyError::msg("E0406", "buffer read out of bounds"))?;
836
+ Ok(Value::Int(i64::from(slice[idx])))
837
+ }
838
+ BuiltinId::WriteU8 => {
839
+ let (Some(Value::RawBuffer(h)), Some(Value::Int(off)), Some(Value::Int(byte))) =
840
+ (args.first().copied(), args.get(1).copied(), args.get(2).copied())
841
+ else {
842
+ return Err(PolyError::msg(
843
+ "E0404",
844
+ "write_u8(buf, offset, val) invalid args",
845
+ ));
846
+ };
847
+ let slice = heap
848
+ .buffer_slice_mut(h)
849
+ .ok_or_else(|| PolyError::msg("E0405", "dangling buffer handle"))?;
850
+ let idx = usize::try_from(off)
851
+ .ok()
852
+ .filter(|&i| i < slice.len())
853
+ .ok_or_else(|| PolyError::msg("E0406", "buffer write out of bounds"))?;
854
+ slice[idx] = (byte & 0xff) as u8;
855
+ Ok(Value::Nil)
856
+ }
857
+ BuiltinId::BufLen => {
858
+ if let Some(Value::RawBuffer(h)) = args.first().copied() {
859
+ return Ok(Value::Int(heap.buffer_len(h).unwrap_or(0) as i64));
860
+ }
861
+ Err(PolyError::msg("E0404", "buf_len() expects a buffer"))
862
+ }
863
+ BuiltinId::ClockMs => {
864
+ let ms = SystemTime::now()
865
+ .duration_since(UNIX_EPOCH)
866
+ .map(|d| d.as_millis() as i64)
867
+ .unwrap_or(0);
868
+ Ok(Value::Int(ms))
869
+ }
870
+ BuiltinId::Assert => {
871
+ let ok = args.first().copied().unwrap_or(Value::Nil).is_truthy(heap);
872
+ if !ok {
873
+ let msg = args
874
+ .get(1)
875
+ .map(|v| v.format(heap))
876
+ .unwrap_or_else(|| "assertion failed".to_string());
877
+ return Err(PolyError::msg("E0407", msg));
878
+ }
879
+ Ok(Value::Bool(true))
880
+ }
881
+ BuiltinId::Range => {
882
+ let (start, end, step) = match args.len() {
883
+ 1 => (0i64, to_i64(args[0])?, 1i64),
884
+ 2 => (to_i64(args[0])?, to_i64(args[1])?, 1i64),
885
+ 3.. => (to_i64(args[0])?, to_i64(args[1])?, to_i64(args[2])?),
886
+ _ => (0, 0, 1),
887
+ };
888
+ if step == 0 {
889
+ return Err(PolyError::msg("E0408", "range() step cannot be zero"));
890
+ }
891
+ let mut items = Vec::new();
892
+ let mut curr = start;
893
+ if step > 0 {
894
+ while curr < end {
895
+ items.push(Value::Int(curr));
896
+ curr += step;
897
+ }
898
+ } else {
899
+ while curr > end {
900
+ items.push(Value::Int(curr));
901
+ curr += step;
902
+ }
903
+ }
904
+ Ok(Value::Array(heap.alloc_array(items)))
905
+ }
906
+
907
+ // ====================================================================
908
+ // Regex & String Built-in Operations
909
+ // ====================================================================
910
+ BuiltinId::RegexNew => {
911
+ let pat = match args.first().copied() {
912
+ Some(Value::Str(h)) => heap.get_string(h).unwrap_or("").to_string(),
913
+ _ => "".to_string(),
914
+ };
915
+ let flags = match args.get(1).copied() {
916
+ Some(Value::Str(h)) => heap.get_string(h).unwrap_or("").to_string(),
917
+ _ => "".to_string(),
918
+ };
919
+ let h = heap.alloc_regex(&pat, &flags)?;
920
+ Ok(Value::Regex(h))
921
+ }
922
+ BuiltinId::RegexTest => {
923
+ let (re, text) = extract_re_and_text(args, heap)?;
924
+ Ok(Value::Bool(re.is_match(&text)))
925
+ }
926
+ BuiltinId::RegexMatch => {
927
+ let (re, text) = extract_re_and_text(args, heap)?;
928
+ if let Some(m) = re.find(&text) {
929
+ Ok(Value::Str(heap.alloc_string(m.as_str().to_string())))
930
+ } else {
931
+ Ok(Value::Nil)
932
+ }
933
+ }
934
+ BuiltinId::RegexFindAll => {
935
+ let (re, text) = extract_re_and_text(args, heap)?;
936
+ let matches: Vec<Value> = re
937
+ .find_iter(&text)
938
+ .map(|m| Value::Str(heap.alloc_string(m.as_str().to_string())))
939
+ .collect();
940
+ Ok(Value::Array(heap.alloc_array(matches)))
941
+ }
942
+ BuiltinId::RegexReplace => {
943
+ let (re, text) = extract_re_and_text(args, heap)?;
944
+ let repl = match args.get(2).copied() {
945
+ Some(Value::Str(h)) => heap.get_string(h).unwrap_or("").to_string(),
946
+ Some(v) => v.format(heap),
947
+ None => "".to_string(),
948
+ };
949
+ let replaced = re.replace_all(&text, repl.as_str()).to_string();
950
+ Ok(Value::Str(heap.alloc_string(replaced)))
951
+ }
952
+ BuiltinId::RegexSplit => {
953
+ let (re, text) = extract_re_and_text(args, heap)?;
954
+ let parts: Vec<Value> = re
955
+ .split(&text)
956
+ .map(|s| Value::Str(heap.alloc_string(s.to_string())))
957
+ .collect();
958
+ Ok(Value::Array(heap.alloc_array(parts)))
959
+ }
960
+ BuiltinId::StrContains => {
961
+ let s1 = args.first().copied().unwrap_or(Value::Nil).format(heap);
962
+ let s2 = args.get(1).copied().unwrap_or(Value::Nil).format(heap);
963
+ Ok(Value::Bool(s1.contains(&s2)))
964
+ }
965
+ BuiltinId::StrSplit => {
966
+ let s1 = args.first().copied().unwrap_or(Value::Nil).format(heap);
967
+ let sep = args.get(1).copied().unwrap_or(Value::Nil).format(heap);
968
+ let parts: Vec<Value> = if sep.is_empty() {
969
+ s1.chars()
970
+ .map(|c| Value::Str(heap.alloc_string(c.to_string())))
971
+ .collect()
972
+ } else {
973
+ s1.split(&sep)
974
+ .map(|s| Value::Str(heap.alloc_string(s.to_string())))
975
+ .collect()
976
+ };
977
+ Ok(Value::Array(heap.alloc_array(parts)))
978
+ }
979
+ BuiltinId::StrTrim => {
980
+ let s = args.first().copied().unwrap_or(Value::Nil).format(heap);
981
+ Ok(Value::Str(heap.alloc_string(s.trim().to_string())))
982
+ }
983
+ BuiltinId::StrUpper => {
984
+ let s = args.first().copied().unwrap_or(Value::Nil).format(heap);
985
+ Ok(Value::Str(heap.alloc_string(s.to_uppercase())))
986
+ }
987
+ BuiltinId::StrLower => {
988
+ let s = args.first().copied().unwrap_or(Value::Nil).format(heap);
989
+ Ok(Value::Str(heap.alloc_string(s.to_lowercase())))
990
+ }
991
+ BuiltinId::StrReplace => {
992
+ let s = args.first().copied().unwrap_or(Value::Nil).format(heap);
993
+ let from = args.get(1).copied().unwrap_or(Value::Nil).format(heap);
994
+ let to = args.get(2).copied().unwrap_or(Value::Nil).format(heap);
995
+ Ok(Value::Str(heap.alloc_string(s.replace(&from, &to))))
996
+ }
997
+ }
998
+ }
999
+
1000
+ fn extract_re_and_text(
1001
+ args: &[Value],
1002
+ heap: &mut dyn MemoryHeap,
1003
+ ) -> Result<(Regex, String), PolyError> {
1004
+ if args.len() < 2 {
1005
+ return Err(PolyError::msg("E0401", "regex operation expects 2 arguments"));
1006
+ }
1007
+ let (re_val, text_val) = (args[0], args[1]);
1008
+ let re = match re_val {
1009
+ Value::Regex(h) => heap
1010
+ .get_regex(h)
1011
+ .cloned()
1012
+ .ok_or_else(|| PolyError::msg("E0405", "dangling regex handle"))?,
1013
+ Value::Str(h) => {
1014
+ let pat = heap.get_string(h).unwrap_or("");
1015
+ Regex::new(pat).map_err(|e| PolyError::msg("E0410", format!("invalid regex: {e}")))?
1016
+ }
1017
+ other => {
1018
+ let pat = other.format(heap);
1019
+ Regex::new(&pat).map_err(|e| PolyError::msg("E0410", format!("invalid regex: {e}")))?
1020
+ }
1021
+ };
1022
+ let text = match text_val {
1023
+ Value::Str(h) => heap.get_string(h).unwrap_or("").to_string(),
1024
+ other => other.format(heap),
1025
+ };
1026
+ Ok((re, text))
1027
+ }
1028
+
1029
+ fn to_f64(v: Value) -> Result<f64, PolyError> {
1030
+ match v {
1031
+ Value::Float(f) => Ok(f),
1032
+ Value::Int(i) => Ok(i as f64),
1033
+ other => Err(PolyError::msg(
1034
+ "E0404",
1035
+ format!("expected numeric value, got {}", other.type_name()),
1036
+ )),
1037
+ }
1038
+ }
1039
+
1040
+ fn to_i64(v: Value) -> Result<i64, PolyError> {
1041
+ match v {
1042
+ Value::Int(i) => Ok(i),
1043
+ Value::Float(f) => Ok(f as i64),
1044
+ other => Err(PolyError::msg(
1045
+ "E0404",
1046
+ format!("expected integer value, got {}", other.type_name()),
1047
+ )),
1048
+ }
1049
+ }
1050
+
1051
+ fn format_printf(fmt: &str, args: &[Value], heap: &dyn MemoryHeap) -> String {
1052
+ let mut out = String::new();
1053
+ let mut chars = fmt.chars().peekable();
1054
+ let mut arg_idx = 0usize;
1055
+
1056
+ while let Some(ch) = chars.next() {
1057
+ if ch == '%' {
1058
+ if chars.peek() == Some(&'%') {
1059
+ chars.next();
1060
+ out.push('%');
1061
+ continue;
1062
+ }
1063
+ let mut spec = String::new();
1064
+ while let Some(&nc) = chars.peek() {
1065
+ spec.push(nc);
1066
+ chars.next();
1067
+ if nc.is_ascii_alphabetic() {
1068
+ break;
1069
+ }
1070
+ }
1071
+ let val = args.get(arg_idx).copied().unwrap_or(Value::Nil);
1072
+ arg_idx += 1;
1073
+ if spec.ends_with('f') || spec.ends_with('g') {
1074
+ let f = match val {
1075
+ Value::Float(x) => x,
1076
+ Value::Int(i) => i as f64,
1077
+ _ => 0.0,
1078
+ };
1079
+ if let Some(prec) = spec
1080
+ .strip_prefix('.')
1081
+ .and_then(|s| s.strip_suffix('f'))
1082
+ .and_then(|p| p.parse::<usize>().ok())
1083
+ {
1084
+ let _ = write!(out, "{f:.prec$}");
1085
+ } else {
1086
+ let _ = write!(out, "{f}");
1087
+ }
1088
+ } else if spec.ends_with('d') || spec.ends_with('i') {
1089
+ let i = match val {
1090
+ Value::Int(i) => i,
1091
+ Value::Float(f) => f as i64,
1092
+ Value::Bool(b) => i64::from(b),
1093
+ _ => 0,
1094
+ };
1095
+ let _ = write!(out, "{i}");
1096
+ } else {
1097
+ out.push_str(&val.format(heap));
1098
+ }
1099
+ } else {
1100
+ out.push(ch);
1101
+ }
1102
+ }
1103
+ out
1104
+ }