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
6021 lines (5638 loc) · 237 KB
/
Copy pathvm.rs
File metadata and controls
6021 lines (5638 loc) · 237 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::{JitBackend, TieredAction};
use crate::bytecode::{CodeModule, Constant, Instruction, OpCode};
use crate::ffi::{call_native, CType, Signature, FFI_REGISTRY};
use crate::jit::JitSession;
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()
}
}
// ---------------------------------------------------------------------------
// 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)]
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 {
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(crate) 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 == "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("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 != "IO" {
return None;
}
match op_name {
Some("print") | Some("println") => {
let message = regs
.first()
.map(|v| resolve_value_string(constants, *v))
.unwrap_or_default();
if let Some(sink) = &self.io_output {
sink.borrow_mut().push(message);
} else {
println!("{}", message);
}
Some(Value::unit())
}
Some("log") => {
let level = regs
.first()
.map(|v| resolve_value_string(constants, *v))
.unwrap_or_default();
let message = regs
.get(1)
.map(|v| resolve_value_string(constants, *v))
.unwrap_or_default();
eprintln!("[{}] {}", level.to_uppercase(), message);
Some(Value::unit())
}
Some("log_error") => {
let message = regs
.first()
.map(|v| resolve_value_string(constants, *v))
.unwrap_or_default();
eprintln!("ERROR: {}", message);
Some(Value::unit())
}
Some("read") => {
let mut input = String::new();
if std::io::stdin().read_line(&mut input).is_err() {
return Some(Value::nil());
}
while input.ends_with(|c| c == '\n' || c == '\r') {
input.pop();
}
let bytes = input.into_bytes();
match self.heap.alloc(bytes.len() + 1, HeapTypeTag::String) {
Some(ptr) => {
// SAFETY: `ptr` points to bytes.len()+1 freshly
// allocated bytes on the standalone heap.
unsafe {
std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, bytes.len());
*ptr.add(bytes.len()) = 0;
}
Some(Value::ptr(ptr))
}
None => Some(Value::nil()),
}
}
_ => None,
}
}
}
// ---------------------------------------------------------------------------
// Value: NaN-boxed tagged value
// ---------------------------------------------------------------------------
/// Tagged value using NaN boxing.
///
/// All non-float values are encoded in the quiet-NaN payload of an f64.
/// The high 16 bits hold the type tag; the low 48 bits hold the payload.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Value {
raw: u64,
}
use crate::value_layout::{
is_float_raw, sext48, PAYLOAD_MASK, TAG_ACTOR, TAG_BOOL, TAG_CLOSURE, TAG_INT, TAG_MASK,
TAG_NIL, TAG_PTR, TAG_STRING, TAG_UNIT,
};
impl Value {
/// Create a nil value.
pub fn nil() -> Self {
Value { raw: TAG_NIL }
}
/// Create an integer value.
pub fn int(n: i64) -> Self {
// Store directly in the 48-bit payload.
let payload = (n as u64) & PAYLOAD_MASK;
Value {
raw: TAG_INT | payload,
}
}
/// Create a float value.
pub fn float(f: f64) -> Self {
Value { raw: f.to_bits() }
}
/// Create a boolean value.
pub fn bool(b: bool) -> Self {
Value {
raw: TAG_BOOL | (b as u64),
}
}
/// Create a unit value.
pub fn unit() -> Self {
Value { raw: TAG_UNIT }
}
/// Create an actor reference.
pub fn actor_ref(id: u64) -> Self {
Value {
raw: TAG_ACTOR | (id & PAYLOAD_MASK),
}
}
/// Create a closure reference.
pub fn closure(id: u64) -> Self {
Value {
raw: TAG_CLOSURE | (id & PAYLOAD_MASK),
}
}
/// Create a pointer value (for strings, lists, etc.).
pub fn ptr(p: *mut u8) -> Self {
Value {
raw: TAG_PTR | (p as u64 & PAYLOAD_MASK),
}
}
/// Create a string reference (index into string pool).
pub fn string(id: u32) -> Self {
Value {
raw: TAG_STRING | (id as u64),
}
}
// -- Type checks --
pub fn is_nil(&self) -> bool {
self.raw == TAG_NIL
}
pub fn is_unit(&self) -> bool {
self.raw == TAG_UNIT
}
pub fn is_int(&self) -> bool {
(self.raw & TAG_MASK) == TAG_INT
}
#[inline]
pub fn is_float(&self) -> bool {
is_float_raw(self.raw)
}
pub fn is_bool(&self) -> bool {
(self.raw & TAG_MASK) == TAG_BOOL
}
pub fn is_actor_ref(&self) -> bool {
(self.raw & TAG_MASK) == TAG_ACTOR
}
// -- Extractors --
pub fn as_int(&self) -> Option<i64> {
if (self.raw & TAG_MASK) == TAG_INT {
Some(sext48(self.raw & PAYLOAD_MASK))
} else {
None
}
}
#[inline]
pub fn as_float(&self) -> Option<f64> {
if is_float_raw(self.raw) {
Some(f64::from_bits(self.raw))
} else {
None
}
}
pub fn as_bool(&self) -> Option<bool> {
if (self.raw & TAG_MASK) == TAG_BOOL {
Some((self.raw & 1) != 0)
} else {
None
}
}
pub fn as_actor_id(&self) -> Option<u64> {
if (self.raw & TAG_MASK) == TAG_ACTOR {
Some(self.raw & PAYLOAD_MASK)
} else {
None
}
}
pub fn as_ptr(&self) -> Option<*mut u8> {
if (self.raw & TAG_MASK) == TAG_PTR {
Some((self.raw & PAYLOAD_MASK) as *mut u8)
} else {
None
}
}
pub fn is_ptr(&self) -> bool {
(self.raw & TAG_MASK) == TAG_PTR
}
pub fn is_string(&self) -> bool {
(self.raw & TAG_MASK) == TAG_STRING
}
pub fn is_closure(&self) -> bool {
(self.raw & TAG_MASK) == TAG_CLOSURE
}
pub fn as_string_id(&self) -> Option<u32> {
if self.is_string() {
Some((self.raw & PAYLOAD_MASK) as u32)
} else {
None
}
}
/// Return the raw NaN-boxed bits.
pub fn as_raw(&self) -> u64 {
self.raw
}
/// Construct a Value from raw NaN-boxed bits.
///
/// # Safety
/// The caller must ensure the bits form a valid tagged value.
pub fn from_raw(raw: u64) -> Self {
Value { raw }
}
/// Return the raw NaN-boxed bits (opaque bit pattern).
pub fn to_bits(self) -> u64 {
self.raw
}
/// Construct a Value from raw NaN-boxed bits.
pub fn from_bits(raw: u64) -> Self {
Value { raw }
}
pub fn to_string_repr(&self) -> String {
if self.is_nil() {
"nil".to_string()
} else if self.is_unit() {
"()".to_string()
} else if let Some(n) = self.as_int() {
n.to_string()
} else if let Some(f) = self.as_float() {
f.to_string()
} else if let Some(b) = self.as_bool() {
b.to_string()
} else if self.is_actor_ref() {
format!("#Actor:{}", self.as_actor_id().unwrap())
} else {
format!("#Value({:x})", self.raw)
}
}
}
/// Convert a bytecode constant into a runtime value.
pub(crate) fn constant_to_value(c: &Constant) -> Value {
match c {
Constant::Int(i) => Value::int(*i),
Constant::Float(f) => Value::float(*f),
Constant::String(_) => Value::nil(), // strings are heap-allocated on demand
Constant::Bool(b) => Value::bool(*b),
Constant::Nil => Value::nil(),
Constant::Unit => Value::unit(),
Constant::FunctionRef(_) | Constant::BehaviorRef(_) | Constant::TypeDescriptor(_) => {
Value::nil()
}
}
}
/// Convert a bytecode constant pool to raw NaN-boxed bits for the JIT.
///
/// String constants must encode their constant-pool index exactly like the
/// interpreter's `ConstU` (`Value::string(idx)`); encoding them as nil makes
/// every tiered-up string load silently produce nil.
fn constants_to_jit_bits(constants: &[Constant]) -> Vec<u64> {
constants
.iter()
.enumerate()
.map(|(idx, c)| match c {
Constant::Int(i) => Value::int(*i).to_bits(),
Constant::Float(f) => Value::float(*f).to_bits(),
Constant::String(_) => Value::string(idx as u32).to_bits(),
Constant::Bool(b) => Value::bool(*b).to_bits(),
Constant::Nil => Value::nil().to_bits(),
Constant::Unit => Value::unit().to_bits(),
Constant::FunctionRef(_) | Constant::BehaviorRef(_) | Constant::TypeDescriptor(_) => {
Value::nil().to_bits()
}
})
.collect()
}
/// Parse a `ReceiveMatch` spec constant of the form
/// `"max_params:id1,id2,..."` into (max_params, behavior ids).
/// Malformed specs degrade to "no arms, no payload registers", which the
/// VM treats as an unconditional no-match.
fn parse_receive_spec(spec: &str) -> (usize, Vec<u16>) {
let Some((head, rest)) = spec.split_once(':') else {
return (0, Vec::new());
};
let max_params = head.parse::<usize>().unwrap_or(0);
let ids = rest
.split(',')
.filter_map(|s| s.parse::<u16>().ok())
.collect();
(max_params, ids)
}
// ---------------------------------------------------------------------------
// Frame: activation frame
// ---------------------------------------------------------------------------
#[derive(Clone)]
/// Activation frame: 256 registers + spill slots + metadata.
pub struct Frame {
/// 256 general-purpose registers (r0..r255).
pub regs: [Value; 256],
/// Spill slots for functions whose local count exceeds the register file.
/// Indexed by spill slot index (u16). Empty for functions that fit entirely
/// in registers.
pub spilled: Vec<Value>,
/// Program counter (bytecode index).
pub pc: usize,
/// Module index in VM.modules.
pub module_idx: usize,
/// Return destination register.
pub return_dst: u8,
/// Index of the caller frame in the VM's flat frame stack.
/// None for the top-level frame.
pub caller_idx: Option<usize>,
/// Closure environment (None if not a closure).
pub closure_env: Option<Value>,
}
impl Frame {
/// Create a new frame with all registers initialized to nil.
pub fn new(caller_idx: Option<usize>, module_idx: usize) -> Self {
Frame {
regs: [Value::nil(); 256],
spilled: Vec::new(),
pc: 0,
module_idx,
return_dst: 0,
caller_idx,
closure_env: None,
}
}
}
impl std::fmt::Debug for Frame {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// Show only first 8 registers and key metadata to avoid
// overwhelming output (all 256 regs is too much).
f.debug_struct("Frame")
.field("pc", &self.pc)
.field("module_idx", &self.module_idx)
.field("return_dst", &self.return_dst)
.field("regs[0..8]", &&self.regs[0..8])
.field("caller_idx", &self.caller_idx)
.field("closure_env", &self.closure_env)
.finish()
}
}
// ---------------------------------------------------------------------------
// HandlerFrame: handler stack entry for algebraic effects
// ---------------------------------------------------------------------------
/// A handler frame tracks a single `handle` block's context.
///
/// Created by `Handle` opcode, popped by `Unwind`.
/// When `Perform` finds this handler, it captures a `Continuation`
/// and stores it here for `Resume` to use. For single-shot handlers
/// the lightweight `SingleShotState` is used instead — no heap allocation.
#[derive(Debug, Clone)]
pub struct HandlerFrame {
/// Index into the module's handler_tables.
pub handler_table_idx: usize,
/// Module index (so we can look up handler_tables).
pub module_idx: usize,
/// PC to resume at after the handle block completes normally.
pub resume_pc: usize,
/// Destination register for the handle block's result.
pub resume_dst: u8,
/// Captured continuation (set by Perform, consumed by Resume).
pub captured_continuation: Option<Continuation>,
/// Lightweight continuation state for single-shot handlers.
/// When `Some`, `captured_continuation` is `None` and `Resume`
/// restores from this inline state without a heap allocation.
pub single_shot_state: Option<SingleShotState>,
}
/// Inline continuation state for single-shot effect handlers.
///
/// A single-shot handler resumes the continuation at most once.
/// Instead of deep-cloning every frame into a heap-allocated
/// `Continuation`, we snapshot only the current frame's registers
/// and restore them on `Resume`. This avoids a `Vec<Frame>`
/// allocation (~few hundred bytes + per-frame metadata).
#[derive(Debug, Clone)]
pub struct SingleShotState {
/// PC after the `PerformDirect` instruction (the continuation point).
pub resume_pc: usize,
/// Destination register for the resume value.
pub resume_dst: u8,
/// Step count at capture time.
pub step_count: usize,
/// Snapshot of the current frame's registers at the perform site.
pub regs: [Value; 256],
}
impl HandlerFrame {
pub fn new(
handler_table_idx: usize,
module_idx: usize,
resume_pc: usize,
resume_dst: u8,
) -> Self {
HandlerFrame {
handler_table_idx,
module_idx,
resume_pc,
resume_dst,
captured_continuation: None,
single_shot_state: None,
}
}
}
// ---------------------------------------------------------------------------
// Continuation: captured execution state for algebraic effects
// ---------------------------------------------------------------------------
/// A captured continuation — a deep snapshot of the VM's execution state
/// at the point of a `perform` call. Restored by `resume` to continue
/// the suspended computation with a value.
#[derive(Debug, Clone)]
pub struct Continuation {
pub frames: Vec<Frame>,
/// Index of the active frame within `frames`.
pub current_frame_idx: usize,
/// Program counter at the point of capture (points past Perform).
pub resume_pc: usize,
/// Destination register for the resume value.
pub resume_dst: u8,
/// Step count at capture time.
pub step_count: usize,
/// Snapshot of the handler stack at capture time.
/// Only populated during serialization, empty during normal capture.
pub handler_stack_snapshot: Vec<HandlerFrame>,
}
impl Continuation {
/// Capture a continuation from the current VM state.
pub(crate) fn capture(vm: &VM, resume_dst: u8) -> Option<Self> {
let current_idx = vm.current_frame_idx?;
Some(Continuation {
frames: vm