seq-runtime 5.4.0

Runtime library for the Seq programming language
Documentation
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
//! Arithmetic operations for Seq
//!
//! These functions are exported with C ABI for LLVM codegen to call.
//!
//! # Safety Contract
//!
//! **IMPORTANT:** These functions are designed to be called ONLY by compiler-generated code,
//! not by end users or arbitrary C code. The compiler's type checker is responsible for:
//!
//! - Ensuring stack has correct number of values
//! - Ensuring values are the correct types (Int for arithmetic, Int for comparisons)
//! - Preventing division by zero at compile time when possible
//!
//! # Overflow Behavior
//!
//! All arithmetic operations use **wrapping semantics** for predictable, defined behavior:
//! - `add`: i64::MAX + 1 wraps to i64::MIN
//! - `subtract`: i64::MIN - 1 wraps to i64::MAX
//! - `multiply`: overflow wraps around
//! - `divide`: i64::MIN / -1 wraps to i64::MIN (special case)
//!
//! This matches the behavior of Forth and Factor, providing consistency for low-level code.

use crate::stack::{Stack, peek, pop, pop_two, push};
use crate::value::Value;

/// Push an integer literal onto the stack (for compiler-generated code)
///
/// Stack effect: ( -- n )
///
/// # Safety
/// Always safe to call
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_push_int(stack: Stack, value: i64) -> Stack {
    unsafe { push(stack, Value::Int(value)) }
}

/// Push a boolean literal onto the stack (for compiler-generated code)
///
/// Stack effect: ( -- bool )
///
/// # Safety
/// Always safe to call
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_push_bool(stack: Stack, value: bool) -> Stack {
    unsafe { push(stack, Value::Bool(value)) }
}

/// Add two integers
///
/// Stack effect: ( a b -- a+b )
///
/// # Safety
/// Stack must have two Int values on top
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_add(stack: Stack) -> Stack {
    let (rest, a, b) = unsafe { pop_two(stack, "add") };
    match (a, b) {
        (Value::Int(a_val), Value::Int(b_val)) => unsafe {
            push(rest, Value::Int(a_val.wrapping_add(b_val)))
        },
        _ => panic!("add: expected two integers on stack"),
    }
}

/// Subtract two integers (a - b)
///
/// Stack effect: ( a b -- a-b )
///
/// # Safety
/// Stack must have two Int values on top
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_subtract(stack: Stack) -> Stack {
    let (rest, a, b) = unsafe { pop_two(stack, "subtract") };
    match (a, b) {
        (Value::Int(a_val), Value::Int(b_val)) => unsafe {
            push(rest, Value::Int(a_val.wrapping_sub(b_val)))
        },
        _ => panic!("subtract: expected two integers on stack"),
    }
}

/// Multiply two integers
///
/// Stack effect: ( a b -- a*b )
///
/// # Safety
/// Stack must have two Int values on top
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_multiply(stack: Stack) -> Stack {
    let (rest, a, b) = unsafe { pop_two(stack, "multiply") };
    match (a, b) {
        (Value::Int(a_val), Value::Int(b_val)) => unsafe {
            push(rest, Value::Int(a_val.wrapping_mul(b_val)))
        },
        _ => panic!("multiply: expected two integers on stack"),
    }
}

/// Divide two integers (a / b)
///
/// Stack effect: ( a b -- result success )
///
/// Returns the quotient and a Bool success flag.
/// On division by zero, returns (0, false).
/// On success, returns (a/b, true).
///
/// # Safety
/// Stack must have at least two values on top
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_divide(stack: Stack) -> Stack {
    let (rest, a, b) = unsafe { pop_two(stack, "divide") };
    match (a, b) {
        (Value::Int(_a_val), Value::Int(0)) => {
            // Division by zero - return 0 and false
            let stack = unsafe { push(rest, Value::Int(0)) };
            unsafe { push(stack, Value::Bool(false)) }
        }
        (Value::Int(a_val), Value::Int(b_val)) => {
            // Use wrapping_div to handle i64::MIN / -1 overflow edge case
            let stack = unsafe { push(rest, Value::Int(a_val.wrapping_div(b_val))) };
            unsafe { push(stack, Value::Bool(true)) }
        }
        _ => {
            // Type error - should not happen with type-checked code
            panic!("divide: expected two integers on stack");
        }
    }
}

/// Modulo (remainder) of two integers (a % b)
///
/// Stack effect: ( a b -- result success )
///
/// Returns the remainder and a Bool success flag.
/// On division by zero, returns (0, false).
/// On success, returns (a%b, true).
///
/// # Safety
/// Stack must have at least two values on top
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_modulo(stack: Stack) -> Stack {
    let (rest, a, b) = unsafe { pop_two(stack, "modulo") };
    match (a, b) {
        (Value::Int(_a_val), Value::Int(0)) => {
            // Division by zero - return 0 and false
            let stack = unsafe { push(rest, Value::Int(0)) };
            unsafe { push(stack, Value::Bool(false)) }
        }
        (Value::Int(a_val), Value::Int(b_val)) => {
            // Use wrapping_rem to handle i64::MIN % -1 overflow edge case
            let stack = unsafe { push(rest, Value::Int(a_val.wrapping_rem(b_val))) };
            unsafe { push(stack, Value::Bool(true)) }
        }
        _ => {
            // Type error - should not happen with type-checked code
            panic!("modulo: expected two integers on stack");
        }
    }
}

/// Integer equality: =
///
/// Returns Bool (true if equal, false if not)
/// Stack effect: ( a b -- Bool )
///
/// # Safety
/// Stack must have two Int values on top
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_eq(stack: Stack) -> Stack {
    let (rest, a, b) = unsafe { pop_two(stack, "=") };
    match (a, b) {
        (Value::Int(a_val), Value::Int(b_val)) => unsafe {
            push(rest, Value::Bool(a_val == b_val))
        },
        _ => panic!("=: expected two integers on stack"),
    }
}

/// Less than: <
///
/// Returns Bool (true if a < b, false otherwise)
/// Stack effect: ( a b -- Bool )
///
/// # Safety
/// Stack must have two Int values on top
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_lt(stack: Stack) -> Stack {
    let (rest, a, b) = unsafe { pop_two(stack, "<") };
    match (a, b) {
        (Value::Int(a_val), Value::Int(b_val)) => unsafe { push(rest, Value::Bool(a_val < b_val)) },
        _ => panic!("<: expected two integers on stack"),
    }
}

/// Greater than: >
///
/// Returns Bool (true if a > b, false otherwise)
/// Stack effect: ( a b -- Bool )
///
/// # Safety
/// Stack must have two Int values on top
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_gt(stack: Stack) -> Stack {
    let (rest, a, b) = unsafe { pop_two(stack, ">") };
    match (a, b) {
        (Value::Int(a_val), Value::Int(b_val)) => unsafe { push(rest, Value::Bool(a_val > b_val)) },
        _ => panic!(">: expected two integers on stack"),
    }
}

/// Less than or equal: <=
///
/// Returns Bool (true if a <= b, false otherwise)
/// Stack effect: ( a b -- Bool )
///
/// # Safety
/// Stack must have two Int values on top
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_lte(stack: Stack) -> Stack {
    let (rest, a, b) = unsafe { pop_two(stack, "<=") };
    match (a, b) {
        (Value::Int(a_val), Value::Int(b_val)) => unsafe {
            push(rest, Value::Bool(a_val <= b_val))
        },
        _ => panic!("<=: expected two integers on stack"),
    }
}

/// Greater than or equal: >=
///
/// Returns Bool (true if a >= b, false otherwise)
/// Stack effect: ( a b -- Bool )
///
/// # Safety
/// Stack must have two Int values on top
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_gte(stack: Stack) -> Stack {
    let (rest, a, b) = unsafe { pop_two(stack, ">=") };
    match (a, b) {
        (Value::Int(a_val), Value::Int(b_val)) => unsafe {
            push(rest, Value::Bool(a_val >= b_val))
        },
        _ => panic!(">=: expected two integers on stack"),
    }
}

/// Not equal: <>
///
/// Returns Bool (true if a != b, false otherwise)
/// Stack effect: ( a b -- Bool )
///
/// # Safety
/// Stack must have two Int values on top
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_neq(stack: Stack) -> Stack {
    let (rest, a, b) = unsafe { pop_two(stack, "<>") };
    match (a, b) {
        (Value::Int(a_val), Value::Int(b_val)) => unsafe {
            push(rest, Value::Bool(a_val != b_val))
        },
        _ => panic!("<>: expected two integers on stack"),
    }
}

/// Logical AND operation (Forth-style: multiply for boolean values)
///
/// Stack effect: ( a b -- result )
/// where 0 is false, non-zero is true
/// Returns 1 if both are true (non-zero), 0 otherwise
///
/// # Safety
/// Stack must have at least two Int values
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_and(stack: Stack) -> Stack {
    let (rest, a, b) = unsafe { pop_two(stack, "and") };
    match (a, b) {
        (Value::Int(a_val), Value::Int(b_val)) => unsafe {
            push(
                rest,
                Value::Int(if a_val != 0 && b_val != 0 { 1 } else { 0 }),
            )
        },
        _ => panic!("and: expected two integers on stack"),
    }
}

/// Logical OR operation (Forth-style)
///
/// Stack effect: ( a b -- result )
/// where 0 is false, non-zero is true
/// Returns 1 if either is true (non-zero), 0 otherwise
///
/// # Safety
/// Stack must have at least two Int values
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_or(stack: Stack) -> Stack {
    let (rest, a, b) = unsafe { pop_two(stack, "or") };
    match (a, b) {
        (Value::Int(a_val), Value::Int(b_val)) => unsafe {
            push(
                rest,
                Value::Int(if a_val != 0 || b_val != 0 { 1 } else { 0 }),
            )
        },
        _ => panic!("or: expected two integers on stack"),
    }
}

/// Logical NOT operation
///
/// Stack effect: ( a -- result )
/// where 0 is false, non-zero is true
/// Returns 1 if false (0), 0 otherwise
///
/// # Safety
/// Stack must have at least one Int value
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_not(stack: Stack) -> Stack {
    assert!(!stack.is_null(), "not: stack is empty");
    let (rest, a) = unsafe { pop(stack) };

    match a {
        Value::Int(a_val) => unsafe { push(rest, Value::Int(if a_val == 0 { 1 } else { 0 })) },
        _ => panic!("not: expected integer on stack"),
    }
}

// ============================================================================
// Bitwise Operations
// ============================================================================

/// Bitwise AND
///
/// Stack effect: ( a b -- a&b )
///
/// # Safety
/// Stack must have two Int values on top
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_band(stack: Stack) -> Stack {
    let (rest, a, b) = unsafe { pop_two(stack, "band") };
    match (a, b) {
        (Value::Int(a_val), Value::Int(b_val)) => unsafe { push(rest, Value::Int(a_val & b_val)) },
        _ => panic!("band: expected two integers on stack"),
    }
}

/// Bitwise OR
///
/// Stack effect: ( a b -- a|b )
///
/// # Safety
/// Stack must have two Int values on top
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_bor(stack: Stack) -> Stack {
    let (rest, a, b) = unsafe { pop_two(stack, "bor") };
    match (a, b) {
        (Value::Int(a_val), Value::Int(b_val)) => unsafe { push(rest, Value::Int(a_val | b_val)) },
        _ => panic!("bor: expected two integers on stack"),
    }
}

/// Bitwise XOR
///
/// Stack effect: ( a b -- a^b )
///
/// # Safety
/// Stack must have two Int values on top
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_bxor(stack: Stack) -> Stack {
    let (rest, a, b) = unsafe { pop_two(stack, "bxor") };
    match (a, b) {
        (Value::Int(a_val), Value::Int(b_val)) => unsafe { push(rest, Value::Int(a_val ^ b_val)) },
        _ => panic!("bxor: expected two integers on stack"),
    }
}

/// Bitwise NOT (one's complement)
///
/// Stack effect: ( a -- !a )
///
/// # Safety
/// Stack must have one Int value on top
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_bnot(stack: Stack) -> Stack {
    assert!(!stack.is_null(), "bnot: stack is empty");
    let (rest, a) = unsafe { pop(stack) };
    match a {
        Value::Int(a_val) => unsafe { push(rest, Value::Int(!a_val)) },
        _ => panic!("bnot: expected integer on stack"),
    }
}

/// Shift left
///
/// Stack effect: ( value count -- result )
/// Shifts value left by count bits. Negative count or count >= 64 returns 0.
///
/// # Safety
/// Stack must have two Int values on top
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_shl(stack: Stack) -> Stack {
    let (rest, value, count) = unsafe { pop_two(stack, "shl") };
    match (value, count) {
        (Value::Int(v), Value::Int(c)) => {
            // Use checked_shl to avoid undefined behavior for out-of-range shifts
            // Negative counts become large u32 values, which correctly return None
            let result = if c < 0 {
                0
            } else {
                v.checked_shl(c as u32).unwrap_or(0)
            };
            unsafe { push(rest, Value::Int(result)) }
        }
        _ => panic!("shl: expected two integers on stack"),
    }
}

/// Logical shift right (zero-fill)
///
/// Stack effect: ( value count -- result )
/// Shifts value right by count bits, filling with zeros.
/// Negative count or count >= 64 returns 0.
///
/// # Safety
/// Stack must have two Int values on top
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_shr(stack: Stack) -> Stack {
    let (rest, value, count) = unsafe { pop_two(stack, "shr") };
    match (value, count) {
        (Value::Int(v), Value::Int(c)) => {
            // Use checked_shr to avoid undefined behavior for out-of-range shifts
            // Cast to u64 for logical (zero-fill) shift behavior
            let result = if c < 0 {
                0
            } else {
                (v as u64).checked_shr(c as u32).unwrap_or(0) as i64
            };
            unsafe { push(rest, Value::Int(result)) }
        }
        _ => panic!("shr: expected two integers on stack"),
    }
}

/// Population count (count number of 1 bits)
///
/// Stack effect: ( n -- count )
///
/// # Safety
/// Stack must have one Int value on top
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_popcount(stack: Stack) -> Stack {
    assert!(!stack.is_null(), "popcount: stack is empty");
    let (rest, a) = unsafe { pop(stack) };
    match a {
        Value::Int(v) => unsafe { push(rest, Value::Int(v.count_ones() as i64)) },
        _ => panic!("popcount: expected integer on stack"),
    }
}

/// Count leading zeros
///
/// Stack effect: ( n -- count )
///
/// # Safety
/// Stack must have one Int value on top
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_clz(stack: Stack) -> Stack {
    assert!(!stack.is_null(), "clz: stack is empty");
    let (rest, a) = unsafe { pop(stack) };
    match a {
        Value::Int(v) => unsafe { push(rest, Value::Int(v.leading_zeros() as i64)) },
        _ => panic!("clz: expected integer on stack"),
    }
}

/// Count trailing zeros
///
/// Stack effect: ( n -- count )
///
/// # Safety
/// Stack must have one Int value on top
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_ctz(stack: Stack) -> Stack {
    assert!(!stack.is_null(), "ctz: stack is empty");
    let (rest, a) = unsafe { pop(stack) };
    match a {
        Value::Int(v) => unsafe { push(rest, Value::Int(v.trailing_zeros() as i64)) },
        _ => panic!("ctz: expected integer on stack"),
    }
}

/// Push the bit width of Int (64)
///
/// Stack effect: ( -- 64 )
///
/// # Safety
/// Always safe to call
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_int_bits(stack: Stack) -> Stack {
    unsafe { push(stack, Value::Int(64)) }
}

/// Helper for peeking at the top integer value without popping
///
/// Returns the integer value on top of the stack without modifying the stack.
/// Used in conjunction with pop_stack for conditional branching.
///
/// **Why separate peek and pop?**
/// In LLVM IR for conditionals, we need to:
/// 1. Extract the integer value to test it (peek_int_value)
/// 2. Branch based on that value (icmp + br)
/// 3. Free the stack node in both branches (pop_stack)
///
/// A combined pop_int_value would leak memory since we'd need the value
/// before branching but couldn't return the updated stack pointer through
/// both branches. Separating these operations prevents memory leaks.
///
/// Stack effect: ( n -- n ) returns n
///
/// # Safety
/// Stack must have an Int value on top
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_peek_int_value(stack: Stack) -> i64 {
    assert!(!stack.is_null(), "peek_int_value: stack is empty");

    // Peek and extract — use pop/push-free path via peek()
    let val = unsafe { peek(stack) };
    match val {
        Value::Int(i) => i,
        other => panic!("peek_int_value: expected Int on stack, got {:?}", other),
    }
}

/// Peek at a bool value on top of stack without popping (for pattern matching)
///
/// # Safety
/// Stack must have a Bool value on top
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_peek_bool_value(stack: Stack) -> bool {
    assert!(!stack.is_null(), "peek_bool_value: stack is empty");

    let val = unsafe { peek(stack) };
    match val {
        Value::Bool(b) => b,
        other => panic!("peek_bool_value: expected Bool on stack, got {:?}", other),
    }
}

/// Helper for popping without extracting the value (for conditionals)
///
/// Pops the top stack node and returns the updated stack pointer.
/// Used after peek_int_value to free the condition value's stack node.
///
/// Stack effect: ( n -- )
///
/// # Safety
/// Stack must not be empty
#[unsafe(no_mangle)]
pub unsafe extern "C" fn patch_seq_pop_stack(stack: Stack) -> Stack {
    assert!(!stack.is_null(), "pop_stack: stack is empty");
    let (rest, _value) = unsafe { pop(stack) };
    rest
}

// Public re-exports with short names for internal use
pub use patch_seq_add as add;
pub use patch_seq_and as and;
pub use patch_seq_band as band;
pub use patch_seq_bnot as bnot;
pub use patch_seq_bor as bor;
pub use patch_seq_bxor as bxor;
pub use patch_seq_clz as clz;
pub use patch_seq_ctz as ctz;
pub use patch_seq_divide as divide;
pub use patch_seq_eq as eq;
pub use patch_seq_gt as gt;
pub use patch_seq_gte as gte;
pub use patch_seq_int_bits as int_bits;
pub use patch_seq_lt as lt;
pub use patch_seq_lte as lte;
pub use patch_seq_multiply as multiply;
pub use patch_seq_neq as neq;
pub use patch_seq_not as not;
pub use patch_seq_or as or;
pub use patch_seq_popcount as popcount;
pub use patch_seq_push_bool as push_bool;
pub use patch_seq_push_int as push_int;
pub use patch_seq_shl as shl;
pub use patch_seq_shr as shr;
pub use patch_seq_subtract as subtract;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_add() {
        unsafe {
            let stack = crate::stack::alloc_test_stack();
            let stack = push_int(stack, 5);
            let stack = push_int(stack, 3);
            let stack = add(stack);

            let (_stack, result) = pop(stack);
            assert_eq!(result, Value::Int(8));
        }
    }

    #[test]
    fn test_subtract() {
        unsafe {
            let stack = crate::stack::alloc_test_stack();
            let stack = push_int(stack, 10);
            let stack = push_int(stack, 3);
            let stack = subtract(stack);

            let (_stack, result) = pop(stack);
            assert_eq!(result, Value::Int(7));
        }
    }

    #[test]
    fn test_multiply() {
        unsafe {
            let stack = crate::stack::alloc_test_stack();
            let stack = push_int(stack, 4);
            let stack = push_int(stack, 5);
            let stack = multiply(stack);

            let (_stack, result) = pop(stack);
            assert_eq!(result, Value::Int(20));
        }
    }

    #[test]
    fn test_divide() {
        unsafe {
            let stack = crate::stack::alloc_test_stack();
            let stack = push_int(stack, 20);
            let stack = push_int(stack, 4);
            let stack = divide(stack);

            // Division now returns (result, success_bool)
            let (stack, success) = pop(stack);
            assert_eq!(success, Value::Bool(true));
            let (_stack, result) = pop(stack);
            assert_eq!(result, Value::Int(5));
        }
    }

    #[test]
    fn test_comparisons() {
        unsafe {
            // Test eq (returns true/false Bool)
            let stack = crate::stack::alloc_test_stack();
            let stack = push_int(stack, 5);
            let stack = push_int(stack, 5);
            let stack = eq(stack);
            let (_stack, result) = pop(stack);
            assert_eq!(result, Value::Bool(true));

            // Test lt
            let stack = push_int(stack, 3);
            let stack = push_int(stack, 5);
            let stack = lt(stack);
            let (_stack, result) = pop(stack);
            assert_eq!(result, Value::Bool(true));

            // Test gt
            let stack = push_int(stack, 7);
            let stack = push_int(stack, 5);
            let stack = gt(stack);
            let (_stack, result) = pop(stack);
            assert_eq!(result, Value::Bool(true));
        }
    }

    #[test]
    fn test_63bit_overflow_wrapping() {
        // Verify that arithmetic at the 63-bit boundary wraps correctly.
        // tag_int silently overflows for values outside -(2^62) to (2^62-1),
        // so wrapping arithmetic at the boundary is defined but the tagged
        // representation wraps within 63 bits.
        unsafe {
            let int63_max = (1i64 << 62) - 1; // 4611686018427387903

            // max + 1 wraps within the tagged representation
            let stack = crate::stack::alloc_test_stack();
            let stack = push(stack, Value::Int(int63_max));
            let stack = push(stack, Value::Int(1));
            let stack = add(stack);
            let (_stack, result) = pop(stack);
            // The result wraps — it should be a valid Int (not crash)
            assert!(matches!(result, Value::Int(_)));
        }
    }

    #[test]
    fn test_negative_division() {
        unsafe {
            // Test negative dividend
            let stack = crate::stack::alloc_test_stack();
            let stack = push_int(stack, -10);
            let stack = push_int(stack, 3);
            let stack = divide(stack);
            let (stack, success) = pop(stack);
            assert_eq!(success, Value::Bool(true));
            let (_stack, result) = pop(stack);
            assert_eq!(result, Value::Int(-3)); // Truncates toward zero

            // Test negative divisor
            let stack = push_int(stack, 10);
            let stack = push_int(stack, -3);
            let stack = divide(stack);
            let (stack, success) = pop(stack);
            assert_eq!(success, Value::Bool(true));
            let (_stack, result) = pop(stack);
            assert_eq!(result, Value::Int(-3));

            // Test both negative
            let stack = push_int(stack, -10);
            let stack = push_int(stack, -3);
            let stack = divide(stack);
            let (stack, success) = pop(stack);
            assert_eq!(success, Value::Bool(true));
            let (_stack, result) = pop(stack);
            assert_eq!(result, Value::Int(3));
        }
    }

    #[test]
    fn test_and_true_true() {
        unsafe {
            let stack = crate::stack::alloc_test_stack();
            let stack = push_int(stack, 1);
            let stack = push_int(stack, 1);
            let stack = and(stack);
            let (_stack, result) = pop(stack);
            assert_eq!(result, Value::Int(1));
        }
    }

    #[test]
    fn test_and_true_false() {
        unsafe {
            let stack = crate::stack::alloc_test_stack();
            let stack = push_int(stack, 1);
            let stack = push_int(stack, 0);
            let stack = and(stack);
            let (_stack, result) = pop(stack);
            assert_eq!(result, Value::Int(0));
        }
    }

    #[test]
    fn test_and_false_false() {
        unsafe {
            let stack = crate::stack::alloc_test_stack();
            let stack = push_int(stack, 0);
            let stack = push_int(stack, 0);
            let stack = and(stack);
            let (_stack, result) = pop(stack);
            assert_eq!(result, Value::Int(0));
        }
    }

    #[test]
    fn test_or_true_true() {
        unsafe {
            let stack = crate::stack::alloc_test_stack();
            let stack = push_int(stack, 1);
            let stack = push_int(stack, 1);
            let stack = or(stack);
            let (_stack, result) = pop(stack);
            assert_eq!(result, Value::Int(1));
        }
    }

    #[test]
    fn test_or_true_false() {
        unsafe {
            let stack = crate::stack::alloc_test_stack();
            let stack = push_int(stack, 1);
            let stack = push_int(stack, 0);
            let stack = or(stack);
            let (_stack, result) = pop(stack);
            assert_eq!(result, Value::Int(1));
        }
    }

    #[test]
    fn test_or_false_false() {
        unsafe {
            let stack = crate::stack::alloc_test_stack();
            let stack = push_int(stack, 0);
            let stack = push_int(stack, 0);
            let stack = or(stack);
            let (_stack, result) = pop(stack);
            assert_eq!(result, Value::Int(0));
        }
    }

    #[test]
    fn test_not_true() {
        unsafe {
            let stack = crate::stack::alloc_test_stack();
            let stack = push_int(stack, 1);
            let stack = not(stack);
            let (_stack, result) = pop(stack);
            assert_eq!(result, Value::Int(0));
        }
    }

    #[test]
    fn test_not_false() {
        unsafe {
            let stack = crate::stack::alloc_test_stack();
            let stack = push_int(stack, 0);
            let stack = not(stack);
            let (_stack, result) = pop(stack);
            assert_eq!(result, Value::Int(1));
        }
    }

    #[test]
    fn test_and_nonzero_values() {
        // Forth-style: any non-zero is true
        unsafe {
            let stack = crate::stack::alloc_test_stack();
            let stack = push_int(stack, 42);
            let stack = push_int(stack, -5);
            let stack = and(stack);
            let (_stack, result) = pop(stack);
            assert_eq!(result, Value::Int(1));
        }
    }

    #[test]
    fn test_divide_by_zero_returns_false() {
        unsafe {
            let stack = crate::stack::alloc_test_stack();
            let stack = push_int(stack, 42);
            let stack = push_int(stack, 0);
            let stack = divide(stack);

            // Division by zero now returns (0, false) instead of setting runtime error
            let (stack, success) = pop(stack);
            assert_eq!(success, Value::Bool(false));

            // Should have pushed 0 as result
            let (_stack, result) = pop(stack);
            assert_eq!(result, Value::Int(0));
        }
    }
}