forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime.rs
More file actions
1752 lines (1611 loc) · 65 KB
/
Copy pathruntime.rs
File metadata and controls
1752 lines (1611 loc) · 65 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
//! Runtime helper functions callable from JIT-compiled code.
use crate::bytecode::Constant;
use crate::value_layout::{
is_float_raw, sext48, tag_int, PAYLOAD_MASK, TAG_CLOSURE, TAG_INT, TAG_MASK, TAG_PTR,
TAG_STRING,
};
use crate::vm::Value;
use std::cell::{Cell, UnsafeCell};
use std::ffi::CStr;
// is_float_raw is now imported from crate::value_layout (integer bitmask, no FPU).
/// Coerce a raw Nulang value to its string representation: the string content
/// if it IS a string (constant-pool or heap), otherwise `Value::to_string_repr`
/// (matching the interpreter's IAdd string fallback, so `"n=" + 42 == "n=42"`).
fn coerce_string(raw: u64) -> String {
match resolve_string_coerce(raw) {
Some(s) => s,
None => Value::from_raw(raw).to_string_repr(),
}
}
/// Is the value ACTUALLY a string (a TAG_STRING constant or a TAG_PTR heap
/// string), as opposed to merely coercible to one? `resolve_string_coerce`
/// returns Some for ints/floats/bools too, so it can't gate the concat path.
fn raw_is_string(raw: u64) -> bool {
let val = Value::from_raw(raw);
if val.is_string() {
return true;
}
if (raw & TAG_MASK) == TAG_PTR {
let ptr = (raw & PAYLOAD_MASK) as *mut u8;
if ptr.is_null() {
return false;
}
unsafe {
let header = &*ActorHeap::header_of(ptr);
header.type_tag == HeapTypeTag::String
}
} else {
false
}
}
/// Allocate a heap string holding `s` and return its tagged pointer value.
fn alloc_string_value(s: String) -> u64 {
let bytes = s.into_bytes();
unsafe {
if let Some(ptr) = alloc_obj(bytes.len() + 1, HeapTypeTag::String) {
std::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr, bytes.len());
*ptr.add(bytes.len()) = 0;
Value::ptr(ptr).as_raw()
} else {
Value::nil().as_raw()
}
}
}
#[no_mangle]
pub extern "C" fn nulang_iadd(a: u64, b: u64) -> u64 {
// String concatenation fallback (mirrors the interpreter's IAdd): when the
// compiler couldn't determine operand types at compile time (e.g. a string
// added to an int), coerce both operands to strings and concatenate.
if raw_is_string(a) || raw_is_string(b) {
let result = format!("{}{}", coerce_string(a), coerce_string(b));
return alloc_string_value(result);
}
if is_float_raw(a) && is_float_raw(b) {
Value::float(f64::from_bits(a) + f64::from_bits(b)).as_raw()
} else {
tag_int(as_int_or_zero(a) + as_int_or_zero(b))
}
}
#[no_mangle]
pub extern "C" fn nulang_isub(a: u64, b: u64) -> u64 {
if is_float_raw(a) && is_float_raw(b) {
Value::float(f64::from_bits(a) - f64::from_bits(b)).as_raw()
} else {
tag_int(as_int_or_zero(a) - as_int_or_zero(b))
}
}
#[no_mangle]
pub extern "C" fn nulang_imul(a: u64, b: u64) -> u64 {
if is_float_raw(a) && is_float_raw(b) {
Value::float(f64::from_bits(a) * f64::from_bits(b)).as_raw()
} else {
tag_int(as_int_or_zero(a).wrapping_mul(as_int_or_zero(b)))
}
}
#[no_mangle]
pub extern "C" fn nulang_idiv(a: u64, b: u64) -> u64 {
if is_float_raw(a) && is_float_raw(b) {
let bv = f64::from_bits(b);
if bv == 0.0 {
return Value::nil().as_raw();
}
return Value::float(f64::from_bits(a) / bv).as_raw();
}
let bv = as_int_or_one(b);
if bv == 0 {
return Value::nil().as_raw();
}
tag_int(as_int_or_zero(a) / bv)
}
#[no_mangle]
pub extern "C" fn nulang_imod(a: u64, b: u64) -> u64 {
if is_float_raw(a) && is_float_raw(b) {
let bv = f64::from_bits(b);
if bv == 0.0 {
return Value::nil().as_raw();
}
return Value::float(f64::from_bits(a) % bv).as_raw();
}
let bv = as_int_or_one(b);
if bv == 0 {
return Value::nil().as_raw();
}
tag_int(as_int_or_zero(a) % bv)
}
/// Denominator for div/mod, matching the interpreter's `as_int().unwrap_or(1)`:
/// a non-int-tagged denominator is 1 (no div-by-zero), while a tagged int 0
/// still yields div-by-zero → nil.
pub(crate) fn as_int_or_one(v: u64) -> i64 {
if (v & TAG_MASK) == TAG_INT {
sext48(v & PAYLOAD_MASK)
} else {
1
}
}
/// Extract the integer payload like the interpreter's `as_int().unwrap_or(0)`:
/// non-int-tagged values contribute 0.
pub(crate) fn as_int_or_zero(v: u64) -> i64 {
if (v & TAG_MASK) == TAG_INT {
sext48(v & PAYLOAD_MASK)
} else {
0
}
}
/// Extract the raw payload pointer from a NaN-boxed value, or null.
fn val_ptr(v: u64) -> *mut u8 {
if (v & TAG_MASK) == TAG_PTR {
(v & PAYLOAD_MASK) as *mut u8
} else {
std::ptr::null_mut()
}
}
#[no_mangle]
pub extern "C" fn nulang_xor(a: u64, b: u64) -> u64 {
tag_int(as_int_or_zero(a) ^ as_int_or_zero(b))
}
#[no_mangle]
pub extern "C" fn nulang_shl(a: u64, b: u64) -> u64 {
let shift = (as_int_or_zero(b) as u64) & 0x3f;
tag_int(as_int_or_zero(a) << shift)
}
#[no_mangle]
pub extern "C" fn nulang_shr(a: u64, b: u64) -> u64 {
let shift = (as_int_or_zero(b) as u64) & 0x3f;
tag_int(as_int_or_zero(a) >> shift)
}
#[no_mangle]
pub extern "C" fn nulang_bitand(a: u64, b: u64) -> u64 {
tag_int(as_int_or_zero(a) & as_int_or_zero(b))
}
#[no_mangle]
pub extern "C" fn nulang_bitor(a: u64, b: u64) -> u64 {
tag_int(as_int_or_zero(a) | as_int_or_zero(b))
}
#[no_mangle]
pub extern "C" fn nulang_ineg(a: u64) -> u64 {
if is_float_raw(a) {
Value::float(-f64::from_bits(a)).as_raw()
} else {
tag_int(-as_int_or_zero(a))
}
}
#[no_mangle]
pub extern "C" fn nulang_iinc(a: u64) -> u64 {
// IInc/IDec read the raw 48-bit payload as a signed value (tag ignored),
// matching step_iinc — NOT as_int_or_zero (which would zero non-int tags).
tag_int(sext48(a & PAYLOAD_MASK) + 1)
}
#[no_mangle]
pub extern "C" fn nulang_idec(a: u64) -> u64 {
tag_int(sext48(a & PAYLOAD_MASK) - 1)
}
#[no_mangle]
pub extern "C" fn nulang_icmp_eq(a: u64, b: u64) -> u64 {
if is_float_raw(a) && is_float_raw(b) {
Value::bool((f64::from_bits(a) - f64::from_bits(b)).abs() < f64::EPSILON).as_raw()
} else if (a & TAG_MASK) == TAG_INT && (b & TAG_MASK) == TAG_INT {
Value::bool(sext48(a & PAYLOAD_MASK) == sext48(b & PAYLOAD_MASK)).as_raw()
} else if is_float_raw(a) && (b & TAG_MASK) == TAG_INT {
let bf = sext48(b & PAYLOAD_MASK) as f64;
Value::bool((f64::from_bits(a) - bf).abs() < f64::EPSILON).as_raw()
} else if (a & TAG_MASK) == TAG_INT && is_float_raw(b) {
let af = sext48(a & PAYLOAD_MASK) as f64;
Value::bool((af - f64::from_bits(b)).abs() < f64::EPSILON).as_raw()
} else if (a & TAG_MASK) == TAG_STRING
|| (a & TAG_MASK) == TAG_PTR
|| (b & TAG_MASK) == TAG_STRING
|| (b & TAG_MASK) == TAG_PTR
{
// String equality must compare content, not raw bits.
// Only when BOTH resolve to strings do we compare text.
let eq = match (resolve_jit_string(a), resolve_jit_string(b)) {
(Some(sa), Some(sb)) => sa == sb,
_ => false,
};
Value::bool(eq).as_raw()
} else {
Value::bool(a == b).as_raw()
}
}
#[no_mangle]
pub extern "C" fn nulang_icmp_lt(a: u64, b: u64) -> u64 {
if is_float_raw(a) && is_float_raw(b) {
Value::bool(f64::from_bits(a) < f64::from_bits(b)).as_raw()
} else if (a & TAG_MASK) == TAG_INT && (b & TAG_MASK) == TAG_INT {
Value::bool(sext48(a & PAYLOAD_MASK) < sext48(b & PAYLOAD_MASK)).as_raw()
} else if is_float_raw(a) && (b & TAG_MASK) == TAG_INT {
Value::bool(f64::from_bits(a) < sext48(b & PAYLOAD_MASK) as f64).as_raw()
} else if (a & TAG_MASK) == TAG_INT && is_float_raw(b) {
Value::bool((sext48(a & PAYLOAD_MASK) as f64) < f64::from_bits(b)).as_raw()
} else {
Value::bool(a < b).as_raw()
}
}
#[no_mangle]
pub extern "C" fn nulang_icmp_gt(a: u64, b: u64) -> u64 {
if is_float_raw(a) && is_float_raw(b) {
Value::bool(f64::from_bits(a) > f64::from_bits(b)).as_raw()
} else if (a & TAG_MASK) == TAG_INT && (b & TAG_MASK) == TAG_INT {
Value::bool(sext48(a & PAYLOAD_MASK) > sext48(b & PAYLOAD_MASK)).as_raw()
} else if is_float_raw(a) && (b & TAG_MASK) == TAG_INT {
Value::bool(f64::from_bits(a) > sext48(b & PAYLOAD_MASK) as f64).as_raw()
} else if (a & TAG_MASK) == TAG_INT && is_float_raw(b) {
Value::bool((sext48(a & PAYLOAD_MASK) as f64) > f64::from_bits(b)).as_raw()
} else {
Value::bool(a > b).as_raw()
}
}
#[no_mangle]
pub extern "C" fn nulang_icmp_le(a: u64, b: u64) -> u64 {
if is_float_raw(a) && is_float_raw(b) {
Value::bool(f64::from_bits(a) <= f64::from_bits(b)).as_raw()
} else if (a & TAG_MASK) == TAG_INT && (b & TAG_MASK) == TAG_INT {
Value::bool(sext48(a & PAYLOAD_MASK) <= sext48(b & PAYLOAD_MASK)).as_raw()
} else if is_float_raw(a) && (b & TAG_MASK) == TAG_INT {
Value::bool(f64::from_bits(a) <= sext48(b & PAYLOAD_MASK) as f64).as_raw()
} else if (a & TAG_MASK) == TAG_INT && is_float_raw(b) {
Value::bool((sext48(a & PAYLOAD_MASK) as f64) <= f64::from_bits(b)).as_raw()
} else {
Value::bool(a <= b).as_raw()
}
}
#[no_mangle]
pub extern "C" fn nulang_icmp_ge(a: u64, b: u64) -> u64 {
if is_float_raw(a) && is_float_raw(b) {
Value::bool(f64::from_bits(a) >= f64::from_bits(b)).as_raw()
} else if (a & TAG_MASK) == TAG_INT && (b & TAG_MASK) == TAG_INT {
Value::bool(sext48(a & PAYLOAD_MASK) >= sext48(b & PAYLOAD_MASK)).as_raw()
} else if is_float_raw(a) && (b & TAG_MASK) == TAG_INT {
Value::bool(f64::from_bits(a) >= sext48(b & PAYLOAD_MASK) as f64).as_raw()
} else if (a & TAG_MASK) == TAG_INT && is_float_raw(b) {
Value::bool((sext48(a & PAYLOAD_MASK) as f64) >= f64::from_bits(b)).as_raw()
} else {
Value::bool(a >= b).as_raw()
}
}
#[no_mangle]
pub extern "C" fn nulang_fadd(a: u64, b: u64) -> u64 {
Value::float(f64::from_bits(a) + f64::from_bits(b)).as_raw()
}
#[no_mangle]
pub extern "C" fn nulang_fsub(a: u64, b: u64) -> u64 {
Value::float(f64::from_bits(a) - f64::from_bits(b)).as_raw()
}
#[no_mangle]
pub extern "C" fn nulang_fmul(a: u64, b: u64) -> u64 {
Value::float(f64::from_bits(a) * f64::from_bits(b)).as_raw()
}
#[no_mangle]
pub extern "C" fn nulang_fdiv(a: u64, b: u64) -> u64 {
let bv = f64::from_bits(b);
if bv == 0.0 {
return Value::nil().as_raw();
}
Value::float(f64::from_bits(a) / bv).as_raw()
}
#[no_mangle]
pub extern "C" fn nulang_fcmp_eq(a: u64, b: u64) -> u64 {
Value::bool((f64::from_bits(a) - f64::from_bits(b)).abs() < f64::EPSILON).as_raw()
}
#[no_mangle]
pub extern "C" fn nulang_fcmp_lt(a: u64, b: u64) -> u64 {
Value::bool(f64::from_bits(a) < f64::from_bits(b)).as_raw()
}
#[no_mangle]
pub extern "C" fn nulang_fcmp_gt(a: u64, b: u64) -> u64 {
Value::bool(f64::from_bits(a) > f64::from_bits(b)).as_raw()
}
fn is_truthy(v: u64) -> bool {
v != Value::nil().as_raw() && v != Value::bool(false).as_raw() && v != Value::int(0).as_raw()
}
#[no_mangle]
pub extern "C" fn nulang_not(a: u64) -> u64 {
Value::bool(is_truthy(a) == false).as_raw()
}
#[no_mangle]
pub extern "C" fn nulang_and(a: u64, b: u64) -> u64 {
Value::bool(is_truthy(a) && is_truthy(b)).as_raw()
}
#[no_mangle]
pub extern "C" fn nulang_or(a: u64, b: u64) -> u64 {
Value::bool(is_truthy(a) || is_truthy(b)).as_raw()
}
#[no_mangle]
pub extern "C" fn nulang_itof(a: u64) -> u64 {
Value::float(sext48(a & PAYLOAD_MASK) as f64).as_raw()
}
#[no_mangle]
pub extern "C" fn nulang_ftoi(a: u64) -> u64 {
Value::int(f64::from_bits(a) as i64).as_raw()
}
/// Float negate, matching the interpreter's `as_float().unwrap_or(0.0)`:
/// any NaN bit pattern (i.e. any tagged value) negates to -0.0.
#[no_mangle]
pub extern "C" fn nulang_fneg(a: u64) -> u64 {
let f = f64::from_bits(a);
let v = if f.is_nan() { 0.0 } else { f };
Value::float(-v).as_raw()
}
// -----------------------------------------------------------------------
// Actor callback thread-local for JIT runtime helpers
// -----------------------------------------------------------------------
/// Raw pair representing a `*mut dyn ActorVmCallbacks` fat pointer.
/// Stored as two usize values to avoid zero-initialization UB.
#[derive(Clone, Copy)]
struct CbPair(usize, usize);
impl CbPair {
const NULL: Self = CbPair(0, 0);
/// # Safety
/// Transmutes `*mut dyn ActorVmCallbacks` (a fat pointer: data ptr +
/// vtable ptr) to `(usize, usize)`. Relies on the de-facto fat pointer
/// layout used by all Tier-1 Rust targets (x86_64, aarch64).
fn from_ptr(ptr: *mut dyn crate::vm::ActorVmCallbacks) -> Self {
unsafe { std::mem::transmute(ptr) }
}
/// # Safety
/// Reconstructs the fat pointer. The caller must ensure the original
/// `&mut dyn ActorVmCallbacks` is alive and `&mut` provenance restored.
fn to_ptr(self) -> *mut dyn crate::vm::ActorVmCallbacks {
unsafe { std::mem::transmute(self) }
}
fn is_null(self) -> bool {
self.0 == 0 && self.1 == 0
}
}
thread_local! {
static JIT_CALLBACKS: UnsafeCell<CbPair> = UnsafeCell::new(CbPair::NULL);
}
pub unsafe fn set_jit_callbacks(cb: *mut dyn crate::vm::ActorVmCallbacks) {
JIT_CALLBACKS.with(|cell| {
*cell.get() = CbPair::from_ptr(cb);
});
}
pub fn clear_jit_callbacks() {
JIT_CALLBACKS.with(|cell| unsafe {
*cell.get() = CbPair::NULL;
});
}
// ---------------------------------------------------------------------------
// Constant-pool thread-local for JIT runtime helpers (string comparison)
// ---------------------------------------------------------------------------
/// Pointer-length pair for the current module's constant pool, stored as
/// two usize values to avoid zero-initialization UB in the thread-local.
#[derive(Clone, Copy)]
struct ConstantsPtr(*const Constant, usize);
impl ConstantsPtr {
const NULL: Self = ConstantsPtr(std::ptr::null(), 0);
/// # Safety
/// The slice must be valid for the duration of the JIT execution.
unsafe fn as_slice(self) -> &'static [Constant] {
if self.0.is_null() {
&[]
} else {
std::slice::from_raw_parts(self.0, self.1)
}
}
}
thread_local! {
static JIT_CONSTANTS: UnsafeCell<ConstantsPtr> = UnsafeCell::new(ConstantsPtr::NULL);
}
/// Set the current module's constant pool for JIT runtime helpers.
///
/// # Safety
/// The slice must remain valid until `clear_jit_constants` is called.
pub unsafe fn set_jit_constants(constants: &[Constant]) {
JIT_CONSTANTS.with(|cell| {
*cell.get() = ConstantsPtr(constants.as_ptr(), constants.len());
});
}
pub fn clear_jit_constants() {
JIT_CONSTANTS.with(|cell| unsafe {
*cell.get() = ConstantsPtr::NULL;
});
}
/// Resolve a raw u64 value to its string content (for comparison).
/// Returns None for non-string values or when the constant pool is unavailable.
fn resolve_jit_string(raw: u64) -> Option<String> {
if (raw & TAG_MASK) == TAG_STRING {
// Interned string: look up in the thread-local constant pool.
let id = (raw & PAYLOAD_MASK) as u32;
JIT_CONSTANTS.with(|cell| unsafe {
let cp = (*cell.get()).as_slice();
match cp.get(id as usize) {
Some(Constant::String(s)) => Some(s.clone()),
_ => None,
}
})
} else if (raw & TAG_MASK) == TAG_PTR {
let ptr = (raw & PAYLOAD_MASK) as *mut u8;
if ptr.is_null() {
return None;
}
// SAFETY: ptr is a valid ActorHeap allocation with a header.
// We check the type tag to ensure it's a string.
unsafe {
let header = &*ActorHeap::header_of(ptr);
if header.type_tag != HeapTypeTag::String {
return None;
}
Some(
CStr::from_ptr(ptr as *const std::ffi::c_char)
.to_string_lossy()
.into_owned(),
)
}
} else {
None
}
}
// ---------------------------------------------------------------------------
// JIT Safepoint: reduction-count preemption for long-running JIT regions
// ---------------------------------------------------------------------------
/// How many JIT region entries a behavior may execute before yielding
/// back to the scheduler. Reset at each behavior invocation.
pub const JIT_SAFEPOINT_BUDGET: u64 = 1000;
// JIT code can execute concurrently on different runtime worker threads. The
// status slots and safepoint target therefore must be thread-local: process-
// global slots let one VM consume another VM's branch exit or yield marker.
thread_local! {
static JIT_SAFEPOINT_PTR: Cell<*mut u64> = const { Cell::new(std::ptr::null_mut()) };
static JIT_YIELD_PC: Cell<u64> = const { Cell::new(u64::MAX) };
static JIT_BRANCH_EXIT_PC: Cell<u64> = const { Cell::new(u64::MAX) };
}
pub fn set_jit_safepoint_ptr(ptr: *mut u64) {
JIT_SAFEPOINT_PTR.with(|cell| cell.set(ptr));
}
pub fn clear_jit_safepoint_ptr() {
JIT_SAFEPOINT_PTR.with(|cell| cell.set(std::ptr::null_mut()));
}
/// Check and decrement the current thread's actor reduction budget.
/// Returns 1 when the compiled region must yield, otherwise 0.
#[no_mangle]
pub extern "C" fn nulang_jit_safepoint_check(_unused: u64) -> u64 {
JIT_SAFEPOINT_PTR.with(|cell| {
let ptr = cell.get();
if ptr.is_null() {
return 0;
}
// SAFETY: the runtime installs a pointer to the active actor's
// scheduler-confined counter for the duration of this JIT call.
unsafe {
let next = (*ptr).wrapping_sub(1);
*ptr = next;
u64::from((next as i64) <= 0)
}
})
}
/// Store a relative bytecode offset for a safepoint/effect fallback.
#[no_mangle]
pub extern "C" fn nulang_jit_set_yield_pc(offset: u64) -> u64 {
JIT_YIELD_PC.with(|slot| slot.set(offset));
0
}
/// Store a relative bytecode offset for a compiled branch exit.
#[no_mangle]
pub extern "C" fn nulang_jit_set_branch_exit_pc(offset: u64) -> u64 {
JIT_BRANCH_EXIT_PC.with(|slot| slot.set(offset));
0
}
/// Bytecode offset where the JIT yielded, or `u64::MAX` if no yield is
/// pending. Thread-local because multiple runtime workers can execute JIT
/// code concurrently.
pub fn take_jit_yield_pc() -> Option<usize> {
JIT_YIELD_PC.with(|slot| {
let old = slot.replace(u64::MAX);
(old != u64::MAX).then_some(old as usize)
})
}
/// Bytecode offset where a compiled region exited via a branch to a target
/// outside the region. Thread-local for the same reason as the yield slot.
pub fn take_jit_branch_exit_pc() -> Option<usize> {
JIT_BRANCH_EXIT_PC.with(|slot| {
let old = slot.replace(u64::MAX);
(old != u64::MAX).then_some(old as usize)
})
}
/// Called from JIT-compiled code when the safepoint budget is exhausted.
#[no_mangle]
pub unsafe extern "C" fn nulang_safepoint_yield(resume_offset: u64) -> u64 {
nulang_jit_set_yield_pc(resume_offset)
}
unsafe fn with_callbacks<R>(f: impl FnOnce(&mut dyn crate::vm::ActorVmCallbacks) -> R) -> R {
JIT_CALLBACKS.with(|cell| {
let pair = *cell.get();
assert!(!pair.is_null(), "JIT_CALLBACKS not set");
f(&mut *pair.to_ptr())
})
}
use crate::runtime::heap::{ActorHeap, TypeTag as HeapTypeTag};
// ---------------------------------------------------------------------------
// AOT standalone execution context
// ---------------------------------------------------------------------------
thread_local! {
/// Standalone heap for AOT execution when no actor runtime is active.
static AOT_HEAP: std::cell::RefCell<Option<crate::runtime::heap::ActorHeap>> =
std::cell::RefCell::new(None);
/// Standalone constant pool for AOT execution.
static AOT_CONSTANTS: std::cell::RefCell<Option<Vec<crate::bytecode::Constant>>> =
std::cell::RefCell::new(None);
}
/// Set up a standalone heap for AOT execution.
pub fn aot_set_heap(heap: crate::runtime::heap::ActorHeap) {
AOT_HEAP.with(|cell| {
*cell.borrow_mut() = Some(heap);
});
}
/// Take the standalone heap, returning it to the caller.
pub fn aot_take_heap() -> Option<crate::runtime::heap::ActorHeap> {
AOT_HEAP.with(|cell| cell.borrow_mut().take())
}
/// Set standalone constants for AOT execution.
///
/// # Safety
/// The slice must remain valid until `aot_clear_constants` is called.
pub unsafe fn aot_set_constants(constants: &[crate::bytecode::Constant]) {
AOT_CONSTANTS.with(|cell| {
*cell.borrow_mut() = Some(constants.to_vec());
});
}
/// Clear standalone constants.
pub fn aot_clear_constants() {
AOT_CONSTANTS.with(|cell| {
*cell.borrow_mut() = None;
});
}
/// Allocate via callbacks or fall back to standalone AOT heap.
/// Check if JIT callbacks are set, and if so, use them.
pub(crate) unsafe fn try_with_callbacks<R>(
f: impl FnOnce(&mut dyn crate::vm::ActorVmCallbacks) -> R,
) -> Option<R> {
JIT_CALLBACKS.with(|cell| {
let pair = *cell.get();
if pair.is_null() {
None
} else {
Some(f(&mut *pair.to_ptr()))
}
})
}
/// Allocate via callbacks or fall back to standalone AOT heap.
unsafe fn alloc_obj(size: usize, type_tag: HeapTypeTag) -> Option<*mut u8> {
if let Some(ptr) = try_with_callbacks(|cb| cb.alloc(size, type_tag)) {
return ptr;
}
AOT_HEAP.with(|cell| {
cell.borrow_mut()
.as_mut()
.and_then(|heap| heap.alloc(size, type_tag))
})
}
/// Retain a reference via callbacks or AOT heap directly.
unsafe fn retain_obj(ptr: *mut u8) {
if try_with_callbacks(|cb| {
cb.retain_ref(ptr);
true
})
.is_some()
{
return;
}
if !ptr.is_null() {
let header = &mut *ActorHeap::header_of(ptr);
header.ref_count += 1;
}
}
/// Drop a reference via callbacks or AOT heap directly.
unsafe fn drop_obj(ptr: *mut u8) {
if try_with_callbacks(|cb| {
cb.drop_ref(ptr);
true
})
.is_some()
{
return;
}
if !ptr.is_null() {
let header = &mut *ActorHeap::header_of(ptr);
if header.ref_count > 0 {
header.ref_count -= 1;
}
if header.ref_count == 0 {
AOT_HEAP.with(|cell| {
if let Some(ref mut heap) = *cell.borrow_mut() {
heap.free(ptr);
}
});
}
}
}
// ---------------------------------------------------------------------------
// AOT value-based runtime helpers
// ---------------------------------------------------------------------------
/// Allocate a heap object with `slot_count` slots of type `type_tag`.
/// Returns tagged pointer or nil.
#[no_mangle]
pub unsafe extern "C" fn nulang_alloc_obj(slot_count: u64, type_tag_raw: u32) -> u64 {
let count = slot_count as usize;
let tag: HeapTypeTag = match type_tag_raw {
1 => HeapTypeTag::Array,
3 => HeapTypeTag::Record,
6 => HeapTypeTag::Tuple,
2 => HeapTypeTag::String,
_ => return Value::nil().as_raw(),
};
let size = count.checked_mul(std::mem::size_of::<Value>()).unwrap_or(0);
if let Some(ptr) = alloc_obj(size, tag) {
let slots = std::slice::from_raw_parts_mut(ptr as *mut Value, count);
for slot in slots.iter_mut() {
*slot = Value::nil();
}
Value::ptr(ptr).as_raw()
} else {
Value::nil().as_raw()
}
}
/// Read slot `idx` from a heap object (record, tuple, or array).
/// Returns nil if the object is not a valid heap object or idx is out of range.
#[no_mangle]
pub unsafe extern "C" fn nulang_obj_get(obj: u64, idx: u64) -> u64 {
let obj_ptr = val_ptr(obj);
if obj_ptr.is_null() {
return Value::nil().as_raw();
}
let header = &*ActorHeap::header_of(obj_ptr);
let payload_size = header.size.saturating_sub(ActorHeap::HEADER_SIZE);
let len = payload_size / std::mem::size_of::<Value>();
// idx may be a raw slot index (records/tuples, unboxed arrays) or a tagged
// Int (boxed arrays) — mask off any tag bits to get the slot position.
let i = (idx & PAYLOAD_MASK) as usize;
if i < len {
(*((obj_ptr as *const Value).add(i))).as_raw()
} else {
Value::nil().as_raw()
}
}
/// Write `val` into slot `idx` of a heap object, with proper refcounting.
#[no_mangle]
pub unsafe extern "C" fn nulang_obj_set(obj: u64, idx: u64, val: u64) {
let obj_ptr = val_ptr(obj);
if obj_ptr.is_null() {
return;
}
let val = Value::from_raw(val);
let header = &*ActorHeap::header_of(obj_ptr);
let payload_size = header.size.saturating_sub(ActorHeap::HEADER_SIZE);
let len = payload_size / std::mem::size_of::<Value>();
// idx may be a raw slot index (records/tuples, unboxed arrays) or a tagged
// Int (boxed arrays) — mask off any tag bits to get the slot position.
let i = (idx & PAYLOAD_MASK) as usize;
if i < len {
if let Some(ptr) = val.as_ptr() {
retain_obj(ptr);
}
let slot = (obj_ptr as *mut Value).add(i);
let old = *slot;
*slot = val;
if let Some(old_ptr) = old.as_ptr() {
drop_obj(old_ptr);
}
}
}
/// Get element count of a heap object (record, tuple, or array).
/// Returns tagged int.
#[no_mangle]
pub unsafe extern "C" fn nulang_obj_len(obj: u64) -> u64 {
let obj_ptr = val_ptr(obj);
if obj_ptr.is_null() {
return Value::int(0).as_raw();
}
let header = &*ActorHeap::header_of(obj_ptr);
let payload_size = header.size.saturating_sub(ActorHeap::HEADER_SIZE);
let len = payload_size / std::mem::size_of::<Value>();
Value::int(len as i64).as_raw()
}
/// Shallow copy a record (copies all slots, retains each).
/// Returns tagged pointer or nil.
#[no_mangle]
pub unsafe extern "C" fn nulang_rec_copy(obj: u64) -> u64 {
let src_ptr = val_ptr(obj);
if src_ptr.is_null() {
return Value::nil().as_raw();
}
let header = &*ActorHeap::header_of(src_ptr);
if header.type_tag != HeapTypeTag::Record {
return Value::nil().as_raw();
}
let payload_size = header.size.saturating_sub(ActorHeap::HEADER_SIZE);
let slot_count = payload_size / std::mem::size_of::<Value>();
if let Some(dst_ptr) = alloc_obj(payload_size, HeapTypeTag::Record) {
let src_slots = std::slice::from_raw_parts(src_ptr as *const Value, slot_count);
let dst_slots = std::slice::from_raw_parts_mut(dst_ptr as *mut Value, slot_count);
for i in 0..slot_count {
let val = src_slots[i];
if let Some(ptr) = val.as_ptr() {
retain_obj(ptr);
}
dst_slots[i] = val;
}
Value::ptr(dst_ptr).as_raw()
} else {
Value::nil().as_raw()
}
}
/// String equality: compare two Nulang values as strings.
/// Returns tagged bool.
#[no_mangle]
pub unsafe extern "C" fn nulang_str_eq(a: u64, b: u64) -> u64 {
let sa = resolve_string_coerce(a);
let sb = resolve_string_coerce(b);
let eq = match (sa, sb) {
(Some(sa), Some(sb)) => sa == sb,
_ => false,
};
Value::bool(eq).as_raw()
}
/// String concatenation: allocate a new heap string.
/// Returns tagged pointer or nil.
#[no_mangle]
pub fn resolve_string_coerce(raw: u64) -> Option<String> {
let val = crate::vm::Value::from_raw(raw);
if val.is_int() {
return Some(val.as_int().unwrap().to_string());
}
if val.is_float() {
return Some(val.as_float().unwrap().to_string());
}
if val.is_bool() {
return Some(val.as_bool().unwrap().to_string());
}
if (raw & TAG_MASK) == TAG_STRING {
// String constant from the module pool: content lives in the JIT or
// AOT constant pool, keyed by the payload index.
let id = (raw & PAYLOAD_MASK) as u32;
let from_jit = JIT_CONSTANTS.with(|cell| unsafe {
let cp = (*cell.get()).as_slice();
cp.get(id as usize).and_then(|c| match c {
crate::bytecode::Constant::String(s) => Some(s.clone()),
_ => None,
})
});
if from_jit.is_some() {
return from_jit;
}
return AOT_CONSTANTS.with(|cell| {
let guard = cell.borrow();
if let Some(ref constants) = *guard {
constants.get(id as usize).and_then(|c| match c {
crate::bytecode::Constant::String(s) => Some(s.clone()),
_ => None,
})
} else {
None
}
});
}
if (raw & TAG_MASK) == TAG_PTR {
let ptr = (raw & PAYLOAD_MASK) as *mut u8;
if ptr.is_null() {
return None;
}
unsafe {
let header = &*ActorHeap::header_of(ptr);
if header.type_tag != HeapTypeTag::String {
return None;
}
return Some(
std::ffi::CStr::from_ptr(ptr as *const std::ffi::c_char)
.to_string_lossy()
.into_owned(),
);
}
}
None
}
#[no_mangle]
pub unsafe extern "C" fn nulang_str_concat(a: u64, b: u64) -> u64 {
let result = format!("{}{}", coerce_string(a), coerce_string(b));
alloc_string_value(result)
}
/// Power operation: float pow when both operands are floats, else int pow.
/// Int overflow wraps (wrapping_mul, matching the interpreter); a negative
/// int exponent returns nil.
#[no_mangle]
pub extern "C" fn nulang_pow(a: u64, b: u64) -> u64 {
// Match the interpreter's step_ipow: both floats → powf; else int pow
// with wrapping_mul (negative exponent → nil).
if is_float_raw(a) && is_float_raw(b) {
let af = f64::from_bits(a);
let bf = f64::from_bits(b);
return Value::float(af.powf(bf)).as_raw();
}
let base = as_int_or_zero(a);
let exp = as_int_or_zero(b);
if exp < 0 {
return Value::nil().as_raw();
}
// Binary exponentiation with wrapping_mul, matching the interpreter (so
// overflow wraps instead of nil — e.g. 1000000000 ** 1000000000 == 0).
let mut result: i64 = 1;
let mut base = base;
let mut exp = exp;
while exp > 0 {
if exp & 1 != 0 {
result = result.wrapping_mul(base);
}
exp >>= 1;
if exp > 0 {
base = base.wrapping_mul(base);
}
}
Value::int(result).as_raw()
}
/// # Safety
/// `regs` must point to a valid `[u64; 256]` array. Called only from
/// JIT-compiled code that follows the `regs_ptr` ABI contract.
#[no_mangle]
pub unsafe extern "C" fn nulang_arr_store(
regs: *mut u64,
arr_reg: u32,
idx_reg: u32,
src_reg: u32,
) {
let arr_ptr_val = *regs.add(arr_reg as usize);
let idx_val = *regs.add(idx_reg as usize);
let val = Value::from_raw(*regs.add(src_reg as usize));
let arr_ptr = val_ptr(arr_ptr_val);
if arr_ptr.is_null() {
return;
}
let idx = as_int_or_zero(idx_val) as usize;
with_callbacks(|cb| {
if let Some(len) = cb.array_len(arr_ptr) {
if idx < len {
if let Some(ptr) = val.as_ptr() {
cb.retain_ref(ptr);
}
let slot = (arr_ptr as *mut Value).add(idx);
let old = *slot;
*slot = val;
if let Some(old_ptr) = old.as_ptr() {
cb.drop_ref(old_ptr);
}
}
}
});
}
/// # Safety
/// `regs` must point to a valid `[u64; 256]` array.
#[no_mangle]
pub unsafe extern "C" fn nulang_arr_len(regs: *mut u64, arr_reg: u32, dst_reg: u32) {
let arr_ptr_val = *regs.add(arr_reg as usize);
let arr_ptr = val_ptr(arr_ptr_val);
let len = if !arr_ptr.is_null() {
let header = &*ActorHeap::header_of(arr_ptr);
if header.type_tag == HeapTypeTag::Array {
header.size.saturating_sub(ActorHeap::HEADER_SIZE) / std::mem::size_of::<Value>()
} else {
0
}
} else {
0
};
*regs.add(dst_reg as usize) = tag_int(len as i64);
}
/// # Safety
/// `regs` must point to a valid `[u64; 256]` array.
#[no_mangle]
pub unsafe extern "C" fn nulang_field_load(regs: *mut u64, obj_reg: u32, idx: u32, dst_reg: u32) {
let obj_ptr_val = *regs.add(obj_reg as usize);
let obj_ptr = val_ptr(obj_ptr_val);
let val = if !obj_ptr.is_null() {
let header = &*ActorHeap::header_of(obj_ptr);
if header.type_tag == HeapTypeTag::Tuple {
let payload_size = header.size.saturating_sub(ActorHeap::HEADER_SIZE);
let len = payload_size / std::mem::size_of::<Value>();
if (idx as usize) < len {
*((obj_ptr as *const Value).add(idx as usize))
} else {