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.
package/src/runtime.rs CHANGED
@@ -1,5 +1,6 @@
1
1
  use crate::diagnostics::PolyError;
2
2
  use crate::ir::{BuiltinId, FnId};
3
+ use regex::{Regex, RegexBuilder};
3
4
  use rustc_hash::FxHashMap;
4
5
  use std::fmt::Write as _;
5
6
  use std::time::{SystemTime, UNIX_EPOCH};
@@ -10,6 +11,9 @@ pub struct ObjHandle(pub u32);
10
11
  #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11
12
  pub struct StrHandle(pub u32);
12
13
 
14
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15
+ pub struct RegHandle(pub u32);
16
+
13
17
  #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14
18
  pub struct ArrHandle(pub u32);
15
19
 
@@ -23,6 +27,7 @@ pub enum Value {
23
27
  Int(i64),
24
28
  Float(f64),
25
29
  Str(StrHandle),
30
+ Regex(RegHandle),
26
31
  Array(ArrHandle),
27
32
  Object(ObjHandle),
28
33
  RawBuffer(BufHandle),
@@ -38,7 +43,7 @@ impl Value {
38
43
  Value::Float(f) => f != 0.0 && !f.is_nan(),
39
44
  Value::Str(h) => heap.get_string(h).is_some_and(|s| !s.is_empty()),
40
45
  Value::Array(h) => heap.get_array(h).is_some_and(|a| !a.is_empty()),
41
- Value::Object(_) | Value::RawBuffer(_) | Value::FunctionRef(_) => true,
46
+ Value::Regex(_) | Value::Object(_) | Value::RawBuffer(_) | Value::FunctionRef(_) => true,
42
47
  }
43
48
  }
44
49
 
@@ -49,6 +54,7 @@ impl Value {
49
54
  Value::Int(_) => "int",
50
55
  Value::Float(_) => "float",
51
56
  Value::Str(_) => "string",
57
+ Value::Regex(_) => "regex",
52
58
  Value::Array(_) => "array",
53
59
  Value::Object(_) => "object",
54
60
  Value::RawBuffer(_) => "buffer",
@@ -69,6 +75,13 @@ impl Value {
69
75
  }
70
76
  }
71
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
+ }
72
85
  Value::Array(h) => {
73
86
  if let Some(items) = heap.get_array(h) {
74
87
  let parts: Vec<String> = items.iter().map(|v| v.format(heap)).collect();
@@ -123,6 +136,9 @@ pub trait MemoryHeap: Send {
123
136
  fn alloc_string(&mut self, s: String) -> StrHandle;
124
137
  fn get_string(&self, h: StrHandle) -> Option<&str>;
125
138
 
139
+ fn alloc_regex(&mut self, pattern: &str, flags: &str) -> Result<RegHandle, PolyError>;
140
+ fn get_regex(&self, h: RegHandle) -> Option<&Regex>;
141
+
126
142
  fn alloc_array(&mut self, items: Vec<Value>) -> ArrHandle;
127
143
  fn get_array(&self, h: ArrHandle) -> Option<&[Value]>;
128
144
  fn get_array_mut(&mut self, h: ArrHandle) -> Option<&mut Vec<Value>>;
@@ -141,11 +157,12 @@ pub trait MemoryHeap: Send {
141
157
  fn stats(&self) -> GcStats;
142
158
  }
143
159
 
144
- /// Zero-GC bump/slab Arena allocator with string interning for ultra-fast C/Rust workloads.
145
160
  #[derive(Default)]
146
161
  pub struct ArenaHeap {
147
162
  strings: Vec<String>,
148
163
  string_intern: FxHashMap<String, StrHandle>,
164
+ regexes: Vec<Regex>,
165
+ regex_intern: FxHashMap<(String, String), RegHandle>,
149
166
  arrays: Vec<Vec<Value>>,
150
167
  objects: Vec<ClassInstance>,
151
168
  buffers: Vec<Vec<u8>>,
@@ -172,6 +189,29 @@ impl MemoryHeap for ArenaHeap {
172
189
  self.strings.get(h.0 as usize).map(|s| s.as_str())
173
190
  }
174
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
+
175
215
  fn alloc_array(&mut self, items: Vec<Value>) -> ArrHandle {
176
216
  let h = ArrHandle(self.arrays.len() as u32);
177
217
  self.arrays.push(items);
@@ -235,6 +275,7 @@ impl MemoryHeap for ArenaHeap {
235
275
  collections: 0,
236
276
  freed_objects: 0,
237
277
  live_objects: self.strings.len()
278
+ + self.regexes.len()
238
279
  + self.arrays.len()
239
280
  + self.objects.len()
240
281
  + self.buffers.len(),
@@ -247,10 +288,11 @@ struct GcSlot<T> {
247
288
  data: Option<T>,
248
289
  }
249
290
 
250
- /// Tracing Mark-and-Sweep GC heap that safely collects cyclic Python/JS object graphs.
251
291
  pub struct MarkSweepHeap {
252
292
  strings: Vec<GcSlot<String>>,
253
293
  free_str: Vec<u32>,
294
+ regexes: Vec<GcSlot<Regex>>,
295
+ free_reg: Vec<u32>,
254
296
  arrays: Vec<GcSlot<Vec<Value>>>,
255
297
  free_arr: Vec<u32>,
256
298
  objects: Vec<GcSlot<ClassInstance>>,
@@ -269,6 +311,8 @@ impl Default for MarkSweepHeap {
269
311
  Self {
270
312
  strings: Vec::new(),
271
313
  free_str: Vec::new(),
314
+ regexes: Vec::new(),
315
+ free_reg: Vec::new(),
272
316
  arrays: Vec::new(),
273
317
  free_arr: Vec::new(),
274
318
  objects: Vec::new(),
@@ -312,6 +356,14 @@ impl MarkSweepHeap {
312
356
  slot.marked = true;
313
357
  }
314
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
+ }
315
367
  Value::RawBuffer(h) => {
316
368
  if let Some(slot) = self.buffers.get_mut(h.0 as usize)
317
369
  && slot.data.is_some()
@@ -361,6 +413,27 @@ impl MemoryHeap for MarkSweepHeap {
361
413
  .and_then(|s| s.data.as_deref())
362
414
  }
363
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
+
364
437
  fn alloc_array(&mut self, items: Vec<Value>) -> ArrHandle {
365
438
  self.allocations += 1;
366
439
  self.allocs_since_gc += 1;
@@ -454,6 +527,17 @@ impl MemoryHeap for MarkSweepHeap {
454
527
  }
455
528
  }
456
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
+ }
457
541
  for (idx, slot) in self.arrays.iter_mut().enumerate() {
458
542
  if slot.data.is_some() {
459
543
  if slot.marked {
@@ -493,6 +577,7 @@ impl MemoryHeap for MarkSweepHeap {
493
577
 
494
578
  fn stats(&self) -> GcStats {
495
579
  let live = self.strings.iter().filter(|s| s.data.is_some()).count()
580
+ + self.regexes.iter().filter(|s| s.data.is_some()).count()
496
581
  + self.arrays.iter().filter(|s| s.data.is_some()).count()
497
582
  + self.objects.iter().filter(|s| s.data.is_some()).count()
498
583
  + self.buffers.iter().filter(|s| s.data.is_some()).count();
@@ -551,6 +636,17 @@ pub fn eval_builtin(
551
636
  }
552
637
  Ok(Value::Int(formatted.len() as i64))
553
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
+ }
554
650
  BuiltinId::Len => {
555
651
  let v = args
556
652
  .first()
@@ -669,6 +765,30 @@ pub fn eval_builtin(
669
765
  let y = to_f64(args.get(1).copied().unwrap_or(Value::Float(1.0)))?;
670
766
  Ok(Value::Float(x.powf(y)))
671
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
+ }
672
792
  BuiltinId::Push => {
673
793
  if args.len() < 2 {
674
794
  return Err(PolyError::msg("E0401", "push() expects array and value"));
@@ -679,7 +799,7 @@ pub fn eval_builtin(
679
799
  arr.push(args[1]);
680
800
  return Ok(Value::Int(arr.len() as i64));
681
801
  }
682
- Err(PolyError::msg("E0404", "first argument to push() must be an array"))
802
+ Err(PolyError::msg("E0404", "first argument to push() must be array"))
683
803
  }
684
804
  BuiltinId::Pop => {
685
805
  if let Some(Value::Array(h)) = args.first().copied()
@@ -758,7 +878,152 @@ pub fn eval_builtin(
758
878
  }
759
879
  Ok(Value::Bool(true))
760
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"));
761
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))
762
1027
  }
763
1028
 
764
1029
  fn to_f64(v: Value) -> Result<f64, PolyError> {
@@ -772,6 +1037,17 @@ fn to_f64(v: Value) -> Result<f64, PolyError> {
772
1037
  }
773
1038
  }
774
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
+
775
1051
  fn format_printf(fmt: &str, args: &[Value], heap: &dyn MemoryHeap) -> String {
776
1052
  let mut out = String::new();
777
1053
  let mut chars = fmt.chars().peekable();
@@ -784,7 +1060,6 @@ fn format_printf(fmt: &str, args: &[Value], heap: &dyn MemoryHeap) -> String {
784
1060
  out.push('%');
785
1061
  continue;
786
1062
  }
787
- // Parse optional precision like %.2f
788
1063
  let mut spec = String::new();
789
1064
  while let Some(&nc) = chars.peek() {
790
1065
  spec.push(nc);