forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvm.rs
More file actions
7565 lines (7141 loc) · 306 KB
/
Copy pathvm.rs
File metadata and controls
7565 lines (7141 loc) · 306 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Nulang Virtual Machine: register-based bytecode interpreter.
//!
//! ## Architecture
//!
//! - **256 general-purpose registers** per activation frame
//! - **NaN-boxing** for efficient tagged values (int/float/bool/nil/actor_ref)
//! - **Bytecode modules** with constant pools and function tables
//! - **Algebraic effects** via handler stack (Perform/Resume/Unwind/Handle)
//!
//! ## Effect System
//!
//! The VM implements algebraic effects via four opcodes:
//! - `Handle`: Push a handler frame onto the handler stack
//! - `Perform`: Invoke an effect operation (captures continuation)
//! - `Resume`: Restore the captured continuation with a value
//! - `Unwind`: Pop the handler frame (normal completion)
//!
//! Handler frames stay on the stack until `Unwind`, allowing multiple
//! effects in the same handle block to be handled by the same handler.
//!
//! ## Value Representation
//!
//! Uses NaN boxing: all non-float values are encoded in the quiet-NaN
//! payload of an f64. This gives us 51 bits of payload space for
//! pointers, integers, and type tags.
use std::ffi::{c_char, CStr, CString};
use crate::backends::{create_default_jit, JitBackend, TieredAction};
use crate::bytecode::{CodeModule, Constant, Instruction, OpCode};
use crate::ffi::{call_native, CType, Signature, FFI_REGISTRY};
use crate::runtime::heap::{ActorHeap, TypeTag as HeapTypeTag};
use crate::types::{NuError, NuResult, Span, VmSuspension};
// ---------------------------------------------------------------------------
// Distributed runtime callbacks for VM opcode integration.
//
// The VM does not depend on the actor runtime directly (that would create a
// circular crate dependency). Instead, a lightweight callback trait can be
// installed when the VM is used inside a distributed actor context.
// ---------------------------------------------------------------------------
/// Callback interface that supplies real distributed behavior for the VM's
/// `NodeId`, `Migrate`, `RAsk`, and `Gossip` opcodes.
///
/// A default no-op implementation is provided so the standalone VM remains
/// usable without any distributed runtime attached.
pub trait DistributedVmCallbacks: std::any::Any + std::fmt::Debug {
/// Return the local node ID.
fn node_id(&self) -> u64 {
0
}
/// Record an actor migration request.
fn migrate(&mut self, _actor_id: u64, _target_node_id: u64) {}
/// Perform a synchronous remote ask.
///
/// Returns the response value, or `Value::nil()` on timeout / failure.
fn remote_ask(
&mut self,
_target_actor: u64,
_behavior: &str,
_args: &[Value],
_timeout_ms: u64,
) -> Value {
Value::nil()
}
/// Perform a fire-and-forget remote send.
///
/// The VM calls this for the `RSend` opcode. The implementation should
/// serialize the message and deliver it to the target node.
fn remote_send(
&mut self,
_target_actor: u64,
_target_node: u64,
_behavior: &str,
_args: &[Value],
) {
}
/// Send a gossip-style message to a subset of known nodes.
///
/// Returns `Value::unit()`.
fn gossip(&mut self, _message: &str) -> Value {
Value::unit()
}
fn remote_spawn(
&mut self,
_target_node: u64,
_behavior: &str,
_init: &[(String, Value)],
) -> Value {
Value::actor_ref(0)
}
}
// ---------------------------------------------------------------------------
// Actor runtime callbacks for VM opcode integration.
//
// The VM is designed to run standalone, but when embedded in the actor
// runtime these callbacks wire Spawn to real actors and route heap
// allocations through the current actor's heap.
// ---------------------------------------------------------------------------
/// Result of querying whether a workflow signal has been received.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SignalWaitResult {
/// The signal has been received; resume with this value.
Ready(Value),
/// The signal has not been received; the runtime should suspend the step.
NotReady,
}
/// Result of a generic async effect operation from the `PerformAsync` opcode.
#[derive(Debug, Clone, PartialEq)]
pub enum PerformAsyncResult {
/// The effect completed synchronously; `Some(content)` is the string
/// result (interned into the module's constant pool by the VM), `None`
/// means nil.
Ready(Option<String>),
/// The effect was dispatched to a background worker; the VM suspends the
/// current behavior and re-executes the `PerformAsync` instruction on resume.
Pending,
}
/// Callback interface that supplies real actor-runtime behavior for the VM's
/// `Spawn`, `ArrAlloc`, `SConcat`, `SRead`, and `Drop` opcodes.
pub trait ActorVmCallbacks: std::any::Any + std::fmt::Debug {
/// Return the ID of the actor currently executing in the VM, if any.
fn current_actor_id(&self) -> Option<u64> {
None
}
/// Allocate `size` bytes on the current actor's heap.
///
/// `type_tag` tells the heap what kind of object is being allocated.
/// Returns a pointer to the payload region, or `None` if allocation fails.
fn alloc(&mut self, size: usize, type_tag: HeapTypeTag) -> Option<*mut u8>;
/// Drop a local reference to a heap object.
///
/// For standalone heaps this frees immediately; for actor heaps it should
/// decrement the local reference count and reclaim when possible.
fn drop_ref(&mut self, ptr: *mut u8);
/// Create an additional local reference to a heap object.
///
/// Called when a value that owns a heap pointer is captured into a
/// closure environment, so the object cannot be freed by a `Drop` of the
/// original binding while the closure still holds it. Mirrors `drop_ref`
/// (increment vs. decrement of the same reference count).
fn retain_ref(&mut self, ptr: *mut u8);
/// Return the number of elements in an array allocated on the actor heap.
fn array_len(&self, ptr: *mut u8) -> Option<usize>;
/// Spawn a real actor from `module.actor_metadata`.
///
/// `behavior_idx` is the behavior table index embedded in the `Spawn`
/// instruction. The callback should find the matching `ActorMeta`, apply
/// its persistence defaults, and return an actor reference value.
fn spawn_actor(
&mut self,
module: &CodeModule,
behavior_idx: usize,
init: Vec<(String, Value)>,
) -> Value;
/// Send a message to an actor by behavior table index.
fn send_message(&mut self, target: Value, behavior_id: u16, args: &[Value]);
/// Synchronously ask an actor and return its response.
/// Default implementation sends the message and returns nil.
fn ask_actor(&mut self, target: Value, behavior_id: u16, args: &[Value]) -> Value {
let _ = (target, behavior_id, args);
Value::nil()
}
/// Read a field from the current actor's state. Default returns nil.
fn get_state_field(&self, _field: &str) -> Value {
Value::nil()
}
/// Write a field on the current actor's state. Default is a no-op.
fn set_state_field(&mut self, _field: &str, _value: Value) {}
/// Emit an event in the current actor. Default is a no-op.
fn emit_event(&mut self, _event: &str, _args: &[Value]) {}
/// Handle a built-in effect performed without an explicit handler.
///
/// The callback receives the effect name and the current frame registers
/// (args are placed in r0..rn by the compiler). If it returns `Some`, the
/// VM resumes with that value; otherwise the effect is unhandled and the
/// VM errors.
fn perform_effect(&mut self, _effect_name: &str, _regs: &[Value]) -> Option<Value> {
None
}
/// Handle a built-in effect performed without an explicit handler,
/// given the operation name (e.g. `print` in `perform IO.print`) and
/// the performing module's constant pool for resolving string-id
/// arguments.
///
/// The default ignores the extra context and delegates to
/// `perform_effect`, preserving the historic callback contract for
/// runtime-backed implementations (e.g. workflow `Timer.sleep`).
fn perform_builtin_effect(
&mut self,
effect_name: &str,
op_name: Option<&str>,
constants: &[Constant],
regs: &[Value],
) -> Option<Value> {
let _ = (op_name, constants);
self.perform_effect(effect_name, regs)
}
/// Handle a built-in effect performed without an explicit handler,
/// given the operation name and the whole performing module — both its
/// constant pool (string-id arguments) and its actor metadata (needed
/// by effects that resolve actor types by name, e.g. `Otp.set_template`).
///
/// The default delegates to `perform_builtin_effect` with the module's
/// constant pool, preserving that callback's contract.
fn perform_builtin_effect_in_module(
&mut self,
effect_name: &str,
op_name: Option<&str>,
module: &CodeModule,
regs: &[Value],
) -> Option<Value> {
self.perform_builtin_effect(effect_name, op_name, &module.constants, regs)
}
/// Check whether a workflow signal has been received.
/// Default returns `Ready(unit)` so un-wired signal waits do not block.
fn wait_signal(&mut self, _name: &str) -> SignalWaitResult {
SignalWaitResult::Ready(Value::unit())
}
/// Suspend the current workflow step waiting for a signal.
/// The callback receives the captured VM state so it can store it on the
/// actor and resume execution when the signal arrives.
fn suspend_for_signal(&mut self, _name: &str, _vm_state: Option<SuspendedVmState>) {}
/// Execute an LLM request synchronously and return the response content.
///
/// The VM extracts the prompt as a string and passes it to the callback
/// along with the model constant from the `LlmAsk` instruction. If no
/// client is configured, return `None` and the VM will leave the result
/// register as `nil`.
fn complete_llm(&mut self, _model: &str, _prompt: &str) -> Option<String> {
None
}
/// Execute an LLM request, possibly asynchronously.
///
/// The default implementation preserves blocking behavior by delegating
/// to `complete_llm`. Runtime-backed callbacks may override this to
/// return `Pending` and deliver the response on a later resume, in which
/// case the VM suspends the behavior with an `LlmAsk:suspend` sentinel
/// error (same pattern as `SignalWait`).
fn llm_ask(&mut self, model: &str, prompt: &str) -> PerformAsyncResult {
PerformAsyncResult::Ready(self.complete_llm(model, prompt))
}
/// Execute a generic async effect, possibly asynchronously.
///
/// `effect_op` is the fully-qualified effect-and-operation name (e.g.
/// `"Inference.ask"`). `args` are the staged argument values from
/// registers r0..rN; `constants` is the performing module's constant
/// pool for resolving string-id arguments. Returns `Ready(content)` when
/// the effect completed synchronously (the VM interns the content string
/// into its module's constant pool), or `Pending` when the call was
/// dispatched to a background worker — the VM then suspends the current
/// behavior with a `PerformAsync` sentinel and re-executes the
/// instruction on resume.
///
/// The default implementation returns `Ready(None)` so the standalone VM
/// always gets a nil result for any async effect.
fn perform_async(
&mut self,
_effect_op: &str,
_constants: &[Constant],
_args: &[Value],
) -> PerformAsyncResult {
PerformAsyncResult::Ready(None)
}
/// Try to receive a message from the current actor's mailbox.
/// Returns `Some((behavior_id, value))` if a message is available,
/// or `None` if the mailbox is empty. Default returns `None`.
fn try_receive(&mut self) -> Option<(u16, Value)> {
None
}
/// Selective receive: scan the current actor's mailbox in FIFO order
/// for the first message whose behavior id appears in `behavior_ids`.
/// Non-matching messages stay in the mailbox. Returns
/// `Some((arm_index, payload))` — `arm_index` is the position of the
/// matched id within `behavior_ids` — or `None` when nothing matches
/// (or there is no current actor). Default returns `None`.
fn try_receive_match(&mut self, _behavior_ids: &[u16]) -> Option<(usize, Vec<Value>)> {
None
}
/// Timed selective receive (`receive { ... } after ms => body`): the
/// mailbox scan found no matching message. Return `true` to suspend the
/// current actor — the VM re-executes the `ReceiveWait` instruction when
/// the runtime resumes it (matching message arrived or timeout fired).
/// Return `false` to resolve the wait now with the no-match sentinel:
/// a non-positive timeout, no actor context, or an already-fired
/// timeout marker (which the implementation must consume so the next
/// wait is not poisoned). Default returns `false`, so standalone
/// execution is always non-blocking.
fn receive_wait_suspend(&mut self, _timeout_ms: i64) -> bool {
false
}
/// Timed selective receive resolved with a mailbox match: cancel any
/// pending receive-wait timeout state for the current actor so a stale
/// timer cannot fire into a later wait. Default is a no-op.
fn receive_wait_matched(&mut self) {}
/// Commit a selective receive: remove the matched ("tried") message from
/// the skip-buffer and clear remaining "tried" flags. Called after a
/// pattern+guard check succeeds. Default is a no-op (standalone VM has no
/// skip-buffer).
fn commit_receive_match(&mut self) {}
/// Reset "tried" flags in the skip-buffer. Called when
/// `try_receive_match` returns `None`, preparing the buffer for the next
/// receive expression. Default is a no-op.
fn reset_receive_match(&mut self) {}
}
/// Standalone callbacks used when the VM runs without an actor runtime.
///
/// Allocations go through a private `ActorHeap` so that `Drop` actually
/// reclaims memory instead of leaking.
#[derive(Debug)]
pub(crate) struct StandaloneVmCallbacks {
heap: ActorHeap,
gc: crate::runtime::OrcaGc,
/// Test hook: when set, `IO.print` output is recorded here instead of
/// written to stdout.
io_output: Option<std::rc::Rc<std::cell::RefCell<Vec<String>>>>,
}
impl StandaloneVmCallbacks {
pub(crate) fn new() -> Self {
let mut heap = ActorHeap::new(1024 * 1024);
heap.set_actor_id(0);
Self {
heap,
gc: crate::runtime::OrcaGc::new(0),
io_output: None,
}
}
}
/// Resolve a value to display text using a module constant pool.
///
/// String-id values index the constant pool; pointer values are read as
/// null-terminated UTF-8; everything else falls back to `to_string_repr`.
pub fn resolve_value_string(constants: &[Constant], value: Value) -> String {
if let Some(id) = value.as_string_id() {
match constants.get(id as usize) {
Some(Constant::String(s)) => s.clone(),
_ => String::new(),
}
} else if let Some(ptr) = value.as_ptr() {
if ptr.is_null() {
String::new()
} else {
// SAFETY: heap string payloads are null-terminated
// (allocate_string and the standalone IO.read path both write
// a trailing zero byte).
unsafe {
CStr::from_ptr(ptr as *const c_char)
.to_string_lossy()
.into_owned()
}
}
} else {
value.to_string_repr()
}
}
impl ActorVmCallbacks for StandaloneVmCallbacks {
fn alloc(&mut self, size: usize, type_tag: HeapTypeTag) -> Option<*mut u8> {
self.heap.alloc(size, type_tag)
}
fn drop_ref(&mut self, ptr: *mut u8) {
// SAFETY: `ptr` is a valid heap pointer previously allocated by this
// actor's heap. The caller (VM ArrStore/FieldS write barrier) guarantees
// ptr is non-null and points to an OrcaHeader-managed allocation.
unsafe {
self.gc.drop_local_ref(&mut self.heap, ptr);
}
}
fn retain_ref(&mut self, ptr: *mut u8) {
// SAFETY: `ptr` is a valid, non-null heap pointer to an
// OrcaHeader-managed object. The GC only reads the header.
unsafe {
self.gc.local_ref(&self.heap, ptr);
}
}
fn array_len(&self, ptr: *mut u8) -> Option<usize> {
// SAFETY: `ptr` is a valid heap pointer from a prior Array allocation.
// `ActorHeap::header_of` computes the OrcaHeader immediately preceding
// the payload — this is sound when ptr was returned by heap.alloc().
unsafe {
let header = &*ActorHeap::header_of(ptr);
if header.type_tag == HeapTypeTag::Array {
let payload_size = header.size.saturating_sub(ActorHeap::HEADER_SIZE);
Some(payload_size / std::mem::size_of::<Value>())
} else {
None
}
}
}
fn spawn_actor(
&mut self,
_module: &CodeModule,
_behavior_idx: usize,
_init: Vec<(String, Value)>,
) -> Value {
Value::actor_ref(0)
}
fn send_message(&mut self, _target: Value, _behavior_id: u16, _args: &[Value]) {}
/// Built-in effects for actor-free scripts: `IO.print` writes the
/// first staged argument to stdout, `IO.read` reads one stdin line
/// into a heap string. String-id arguments resolve against the
/// performing module's constant pool. `Actor.*` and `Otp.*` effects
/// need the actor runtime, so they are nil no-ops here (matching the
/// runtime's outside-an-actor contract).
fn perform_builtin_effect(
&mut self,
effect_name: &str,
op_name: Option<&str>,
constants: &[Constant],
regs: &[Value],
) -> Option<Value> {
if effect_name == "Actor" || effect_name == "Otp" {
return Some(Value::nil());
}
if effect_name == "DB" {
// DB.query requires a runtime with a configured database.
// Standalone VM returns nil.
return Some(Value::nil());
}
if effect_name == "Timer" {
return Some(Value::unit());
}
if effect_name == "Int" && op_name == Some("to_string") {
let n = regs.first().and_then(|v| v.as_int()).unwrap_or(0);
let s = format!("{}", n);
let bytes = s.into_bytes();
match self.heap.alloc(bytes.len() + 1, HeapTypeTag::String) {
Some(ptr) => {
unsafe {
std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, bytes.len());
*ptr.add(bytes.len()) = 0;
}
return Some(Value::ptr(ptr));
}
None => return Some(Value::nil()),
}
}
if effect_name == "Int" && op_name == Some("to_float") {
let n = regs.first().and_then(|v| v.as_int()).unwrap_or(0);
return Some(Value::float(n as f64));
}
if effect_name == "Int" && op_name == Some("to_hex") {
let n = regs.first().and_then(|v| v.as_int()).unwrap_or(0);
let s = format!("{:x}", n);
let bytes = s.into_bytes();
match self.heap.alloc(bytes.len() + 1, HeapTypeTag::String) {
Some(ptr) => {
unsafe {
std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, bytes.len());
*ptr.add(bytes.len()) = 0;
}
return Some(Value::ptr(ptr));
}
None => return Some(Value::nil()),
}
}
if effect_name == "Int" && op_name == Some("to_binary") {
let n = regs.first().and_then(|v| v.as_int()).unwrap_or(0);
let s = format!("{:b}", n);
let bytes = s.into_bytes();
match self.heap.alloc(bytes.len() + 1, HeapTypeTag::String) {
Some(ptr) => {
unsafe {
std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, bytes.len());
*ptr.add(bytes.len()) = 0;
}
return Some(Value::ptr(ptr));
}
None => return Some(Value::nil()),
}
}
if effect_name == "Float" && op_name == Some("to_int") {
let x = regs.first().and_then(|v| v.as_float()).unwrap_or(0.0);
return Some(Value::int(x as i64));
}
if effect_name == "Float" && op_name == Some("to_string") {
let x = regs.first().and_then(|v| v.as_float()).unwrap_or(0.0);
let s = format!("{}", x);
let bytes = s.into_bytes();
match self.heap.alloc(bytes.len() + 1, HeapTypeTag::String) {
Some(ptr) => {
unsafe {
std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, bytes.len());
*ptr.add(bytes.len()) = 0;
}
return Some(Value::ptr(ptr));
}
None => return Some(Value::nil()),
}
}
if effect_name == "Float" && op_name == Some("sin") {
let x = regs.first().and_then(|v| v.as_float()).unwrap_or(0.0);
return Some(Value::float(f64::sin(x)));
}
if effect_name == "Float" && op_name == Some("cos") {
let x = regs.first().and_then(|v| v.as_float()).unwrap_or(0.0);
return Some(Value::float(f64::cos(x)));
}
if effect_name == "Float" && op_name == Some("sqrt") {
let x = regs.first().and_then(|v| v.as_float()).unwrap_or(0.0);
if x < 0.0 {
return Some(Value::nil());
}
return Some(Value::float(f64::sqrt(x)));
}
if effect_name == "Float" && op_name == Some("tan") {
let x = regs.first().and_then(|v| v.as_float()).unwrap_or(0.0);
return Some(Value::float(f64::tan(x)));
}
if effect_name == "Float" && op_name == Some("log") {
let x = regs.first().and_then(|v| v.as_float()).unwrap_or(0.0);
if x <= 0.0 {
return Some(Value::nil());
}
return Some(Value::float(f64::ln(x)));
}
if effect_name == "Float" && op_name == Some("exp") {
let x = regs.first().and_then(|v| v.as_float()).unwrap_or(0.0);
return Some(Value::float(f64::exp(x)));
}
if effect_name == "Float" && op_name == Some("log2") {
let x = regs.first().and_then(|v| v.as_float()).unwrap_or(0.0);
if x <= 0.0 {
return Some(Value::nil());
}
return Some(Value::float(f64::log2(x)));
}
if effect_name == "Float" && op_name == Some("log10") {
let x = regs.first().and_then(|v| v.as_float()).unwrap_or(0.0);
if x <= 0.0 {
return Some(Value::nil());
}
return Some(Value::float(f64::log10(x)));
}
if effect_name == "Float" && op_name == Some("pow") {
let base = regs.first().and_then(|v| v.as_float()).unwrap_or(0.0);
let exp = regs.get(1).and_then(|v| v.as_float()).unwrap_or(0.0);
return Some(Value::float(f64::powf(base, exp)));
}
if effect_name == "String" && op_name == Some("to_int") {
let s = resolve_value_string(constants, *regs.first().unwrap_or(&Value::nil()));
let n: i64 = s.parse().unwrap_or(0);
return Some(Value::int(n));
}
if effect_name == "String" && op_name == Some("to_float") {
let s = resolve_value_string(constants, *regs.first().unwrap_or(&Value::nil()));
let f: f64 = s.parse().unwrap_or(0.0);
return Some(Value::float(f));
}
if effect_name == "String" && op_name == Some("length") {
let s = resolve_value_string(constants, *regs.first().unwrap_or(&Value::nil()));
return Some(Value::int(s.len() as i64));
}
if effect_name == "String" && op_name == Some("charAt") {
let s = resolve_value_string(constants, *regs.first().unwrap_or(&Value::nil()));
let idx = regs.get(1).and_then(|v| v.as_int()).unwrap_or(-1);
if idx < 0 || idx as usize >= s.len() {
return Some(Value::int(-1));
}
return Some(Value::int(s.as_bytes()[idx as usize] as i64));
}
if effect_name == "String" && op_name == Some("from_char") {
let code = regs.first().and_then(|v| v.as_int()).unwrap_or(-1);
if code < 0 {
return Some(Value::nil());
}
let c = match char::from_u32(code as u32) {
Some(c) => c,
None => return Some(Value::nil()),
};
let s: String = c.to_string();
let bytes = s.into_bytes();
match self.heap.alloc(bytes.len() + 1, HeapTypeTag::String) {
Some(ptr) => {
unsafe {
std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, bytes.len());
*ptr.add(bytes.len()) = 0;
}
return Some(Value::ptr(ptr));
}
None => return Some(Value::nil()),
}
}
if effect_name == "String" && op_name == Some("concat") {
let a = resolve_value_string(constants, *regs.first().unwrap_or(&Value::nil()));
let b = resolve_value_string(constants, *regs.get(1).unwrap_or(&Value::nil()));
let combined = a + &b;
let bytes = combined.into_bytes();
match self.heap.alloc(bytes.len() + 1, HeapTypeTag::String) {
Some(ptr) => {
unsafe {
std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, bytes.len());
*ptr.add(bytes.len()) = 0;
}
return Some(Value::ptr(ptr));
}
None => return Some(Value::nil()),
}
}
if effect_name == "String" && op_name == Some("substring") {
let s = resolve_value_string(constants, *regs.first().unwrap_or(&Value::nil()));
let start = regs.get(1).and_then(|v| v.as_int()).unwrap_or(0);
let len = regs.get(2).and_then(|v| v.as_int()).unwrap_or(0);
if start < 0 || len < 0 || start as usize > s.len() {
return Some(Value::nil());
}
let end = ((start + len) as usize).min(s.len());
let sub = &s[start as usize..end];
let bytes = sub.as_bytes().to_vec();
match self.heap.alloc(bytes.len() + 1, HeapTypeTag::String) {
Some(ptr) => {
unsafe {
std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, bytes.len());
*ptr.add(bytes.len()) = 0;
}
return Some(Value::ptr(ptr));
}
None => return Some(Value::nil()),
}
}
if effect_name == "Debug" && op_name == Some("inspect") {
let label = regs
.first()
.map(|v| resolve_value_string(constants, *v))
.unwrap_or_default();
let val = regs.get(1).copied().unwrap_or(Value::nil());
let file = crate::types::source_map_file().unwrap_or_else(|| "<unknown>".to_string());
eprintln!("[{}] {} = {}", file, label, val.to_string_repr());
return Some(val);
}
if effect_name == "FS" {
match op_name {
Some("read") => {
let path = regs
.first()
.map(|v| resolve_value_string(constants, *v))
.unwrap_or_default();
match std::fs::read_to_string(&path) {
Ok(content) => {
let bytes = content.into_bytes();
match self.heap.alloc(bytes.len() + 1, HeapTypeTag::String) {
Some(ptr) => {
unsafe {
std::ptr::copy_nonoverlapping(
bytes.as_ptr(),
ptr,
bytes.len(),
);
*ptr.add(bytes.len()) = 0;
}
return Some(Value::ptr(ptr));
}
None => return Some(Value::nil()),
}
}
Err(_) => return Some(Value::nil()),
}
}
Some("write") => {
let path = regs
.first()
.map(|v| resolve_value_string(constants, *v))
.unwrap_or_default();
let content = regs
.get(1)
.map(|v| resolve_value_string(constants, *v))
.unwrap_or_default();
if std::fs::write(&path, &content).is_err() {
return Some(Value::nil());
}
return Some(Value::unit());
}
Some("append") => {
let path = regs
.first()
.map(|v| resolve_value_string(constants, *v))
.unwrap_or_default();
let content = regs
.get(1)
.map(|v| resolve_value_string(constants, *v))
.unwrap_or_default();
use std::io::Write;
let mut file = match std::fs::OpenOptions::new()
.append(true)
.create(true)
.open(&path)
{
Ok(f) => f,
Err(_) => return Some(Value::nil()),
};
if file.write_all(content.as_bytes()).is_err() {
return Some(Value::nil());
}
return Some(Value::unit());
}
Some("exists") => {
let path = regs
.first()
.map(|v| resolve_value_string(constants, *v))
.unwrap_or_default();
let exists = std::path::Path::new(&path).exists();
return Some(Value::bool(exists));
}
_ => return None,
}
}
if effect_name == "Array" {
match op_name {
Some("length") => {
let arr_ptr = regs
.first()
.and_then(|v| v.as_ptr())
.unwrap_or(std::ptr::null_mut());
let len = if !arr_ptr.is_null() {
self.array_len(arr_ptr).unwrap_or(0) as i64
} else {
0
};
return Some(Value::int(len));
}
Some("push") => {
let arr_ptr = regs
.first()
.and_then(|v| v.as_ptr())
.unwrap_or(std::ptr::null_mut());
let elem = regs.get(1).copied().unwrap_or(Value::nil());
let len = if !arr_ptr.is_null() {
self.array_len(arr_ptr).unwrap_or(0)
} else {
0
};
let new_len = len + 1;
let size = new_len
.checked_mul(std::mem::size_of::<Value>())
.unwrap_or(0);
if let Some(new_ptr) = self.heap.alloc(size, HeapTypeTag::Array) {
unsafe {
let new_slots =
std::slice::from_raw_parts_mut(new_ptr as *mut Value, new_len);
// Copy existing elements, retaining heap refs.
if !arr_ptr.is_null() {
let old_slots =
std::slice::from_raw_parts(arr_ptr as *const Value, len);
for (i, slot) in old_slots.iter().enumerate() {
new_slots[i] = *slot;
if let Some(ptr) = slot.as_ptr() {
self.gc.local_ref(&self.heap, ptr);
}
}
}
// Store new element, retaining if heap value.
new_slots[len] = elem;
if let Some(ptr) = elem.as_ptr() {
self.gc.local_ref(&self.heap, ptr);
}
}
return Some(Value::ptr(new_ptr));
}
return Some(Value::nil());
}
Some("new") => {
let n = regs.first().and_then(|v| v.as_int()).unwrap_or(0);
if n < 0 {
return Some(Value::nil());
}
let n = n as usize;
let init = regs.get(1).copied().unwrap_or(Value::nil());
let size = n.checked_mul(std::mem::size_of::<Value>()).unwrap_or(0);
if let Some(new_ptr) = self.heap.alloc(size, HeapTypeTag::Array) {
unsafe {
let slots = std::slice::from_raw_parts_mut(new_ptr as *mut Value, n);
for slot in slots.iter_mut() {
*slot = init;
if let Some(ptr) = init.as_ptr() {
self.gc.local_ref(&self.heap, ptr);
}
}
}
return Some(Value::ptr(new_ptr));
}
return Some(Value::nil());
}
Some("set") => {
let arr_ptr = regs
.first()
.and_then(|v| v.as_ptr())
.unwrap_or(std::ptr::null_mut());
let idx = regs.get(1).and_then(|v| v.as_int()).unwrap_or(-1);
let val = regs.get(2).copied().unwrap_or(Value::nil());
if arr_ptr.is_null() || idx < 0 {
return Some(Value::nil());
}
let idx = idx as usize;
let len = self.array_len(arr_ptr).unwrap_or(0);
if idx >= len {
return Some(Value::nil());
}
let size = len.checked_mul(std::mem::size_of::<Value>()).unwrap_or(0);
if let Some(new_ptr) = self.heap.alloc(size, HeapTypeTag::Array) {
unsafe {
let new_slots =
std::slice::from_raw_parts_mut(new_ptr as *mut Value, len);
let old_slots =
std::slice::from_raw_parts(arr_ptr as *const Value, len);
for i in 0..len {
let src = if i == idx { val } else { old_slots[i] };
new_slots[i] = src;
if let Some(ptr) = src.as_ptr() {
self.gc.local_ref(&self.heap, ptr);
}
}
}
return Some(Value::ptr(new_ptr));
}
return Some(Value::nil());
}
Some("slice") => {
let arr_ptr = regs
.first()
.and_then(|v| v.as_ptr())
.unwrap_or(std::ptr::null_mut());
let start = regs.get(1).and_then(|v| v.as_int()).unwrap_or(0);
let end = regs.get(2).and_then(|v| v.as_int()).unwrap_or(-1);
let len = if !arr_ptr.is_null() {
self.array_len(arr_ptr).unwrap_or(0)
} else {
0
};
let start = start.max(0) as usize;
let end = if end < 0 || end as usize > len {
len
} else {
end as usize
};
if start > end {
return Some(Value::nil());
}
let new_len = end - start;
let size = new_len
.checked_mul(std::mem::size_of::<Value>())
.unwrap_or(0);
if let Some(new_ptr) = self.heap.alloc(size, HeapTypeTag::Array) {
unsafe {
let new_slots =
std::slice::from_raw_parts_mut(new_ptr as *mut Value, new_len);
let old_slots =
std::slice::from_raw_parts(arr_ptr as *const Value, len);
for i in 0..new_len {
let src = old_slots[start + i];
new_slots[i] = src;
if let Some(ptr) = src.as_ptr() {
self.gc.local_ref(&self.heap, ptr);
}
}
}
return Some(Value::ptr(new_ptr));
}
return Some(Value::nil());
}
Some("range") => {
let start = regs.first().and_then(|v| v.as_int()).unwrap_or(0);
let end = regs.get(1).and_then(|v| v.as_int()).unwrap_or(0);
let len = if end > start {
(end - start) as usize
} else {
0
};
let size = len.checked_mul(std::mem::size_of::<Value>()).unwrap_or(0);
if let Some(new_ptr) = self.heap.alloc(size, HeapTypeTag::Array) {
unsafe {
let slots = std::slice::from_raw_parts_mut(new_ptr as *mut Value, len);
for i in 0..len {
slots[i] = Value::int(start + i as i64);
}
}
return Some(Value::ptr(new_ptr));
}
return Some(Value::nil());
}
_ => return None,
}
}
if effect_name == "Http" {
match op_name {
Some("get") => {
let url = regs
.first()
.map(|v| resolve_value_string(constants, *v))
.unwrap_or_default();
match ureq::get(&url).call() {
Ok(response) => match response.into_string() {
Ok(body) => {
let bytes = body.into_bytes();
match self.heap.alloc(bytes.len() + 1, HeapTypeTag::String) {
Some(ptr) => {
unsafe {
std::ptr::copy_nonoverlapping(
bytes.as_ptr(),
ptr,
bytes.len(),
);
*ptr.add(bytes.len()) = 0;
}
return Some(Value::ptr(ptr));
}
None => return Some(Value::nil()),
}
}
Err(_) => return Some(Value::nil()),
},
Err(_) => return Some(Value::nil()),
}
}
Some("post") => {
let url = regs
.first()
.map(|v| resolve_value_string(constants, *v))
.unwrap_or_default();
let body = regs
.get(1)
.map(|v| resolve_value_string(constants, *v))
.unwrap_or_default();
match ureq::post(&url).send_string(&body) {
Ok(response) => match response.into_string() {
Ok(body) => {
let bytes = body.into_bytes();
match self.heap.alloc(bytes.len() + 1, HeapTypeTag::String) {
Some(ptr) => {
unsafe {
std::ptr::copy_nonoverlapping(
bytes.as_ptr(),
ptr,
bytes.len(),
);
*ptr.add(bytes.len()) = 0;
}
return Some(Value::ptr(ptr));
}
None => return Some(Value::nil()),
}
}
Err(_) => return Some(Value::nil()),
},
Err(_) => return Some(Value::nil()),
}
}
_ => return None,
}
}
if effect_name == "Time" && op_name == Some("now") {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs() as i64;
return Some(Value::int(now));
}
if effect_name == "Process" && op_name == Some("run") {