fusevm 0.13.0

Language-agnostic bytecode VM with fused superinstructions and a 3-tier Cranelift JIT (linear/block/tracing)
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
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
//! Bytecode instruction set for fusevm.
//!
//! Universal ops that any language frontend can target.
//! Language-specific ops use `Extended(u16, u8)` which dispatches
//! through a handler table registered by the frontend.

use serde::{Deserialize, Serialize};
use std::hash::{Hash, Hasher};

/// Stack-based bytecode instruction set.
///
/// Operands: u16 for pool indices (64k names/constants), usize for jump targets.
/// Language-specific operations use `Extended` with a frontend-registered handler.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Op {
    /// No-op; consumed for cycle-counting and as a branch sentinel.
    Nop,

    // ── Constants ──
    /// Push int value onto the stack.
    LoadInt(i64),
    /// Push float value onto the stack.
    LoadFloat(f64),
    /// index into constant pool
    LoadConst(u16),
    /// Push true value onto the stack.
    LoadTrue,
    /// Push false value onto the stack.
    LoadFalse,
    /// Push undef value onto the stack.
    LoadUndef,

    // ── Stack ──
    /// Discard the top of the stack.
    Pop,
    /// Duplicate the top of the stack.
    Dup,
    /// Duplicate the top two values on the stack.
    Dup2,
    /// Swap the top two stack values.
    Swap,
    /// Rotate the top three stack values (a b c → b c a).
    Rot,

    // ── Variables (u16 = name pool index) ──
    /// Read var into the stack via name-pool index.
    GetVar(u16),
    /// Pop top of stack into var via name-pool index.
    SetVar(u16),
    /// Declare a fresh var binding in the current scope.
    DeclareVar(u16),
    /// Slot-indexed fast path (frame slot index, avoids name lookup)
    GetSlot(u16),
    /// Pop top of stack into slot via name-pool index.
    SetSlot(u16),
    /// Slot-based array index: stack: \[index\], slot contains array → value
    SlotArrayGet(u16),
    /// Slot-based array set: stack: \[value, index\], slot contains array
    SlotArraySet(u16),

    // ── Arrays ──
    /// Read array into the stack via name-pool index.
    GetArray(u16),
    /// Pop top of stack into array via name-pool index.
    SetArray(u16),
    /// Declare a fresh array binding in the current scope.
    DeclareArray(u16),
    /// stack: \[index\] → value
    ArrayGet(u16),
    /// stack: \[value, index\]
    ArraySet(u16),
    /// stack: \[value\]
    ArrayPush(u16),
    /// → popped value
    ArrayPop(u16),
    /// → shifted value
    ArrayShift(u16),
    /// → length
    ArrayLen(u16),
    /// pop N values, push as array
    MakeArray(u16),

    // ── Hashes ──
    /// Read hash into the stack via name-pool index.
    GetHash(u16),
    /// Pop top of stack into hash via name-pool index.
    SetHash(u16),
    /// Declare a fresh hash binding in the current scope.
    DeclareHash(u16),
    /// stack: \[key\] → value
    HashGet(u16),
    /// stack: \[value, key\]
    HashSet(u16),
    /// stack: \[key\] → deleted value
    HashDelete(u16),
    /// stack: \[key\] → bool
    HashExists(u16),
    /// → array of keys
    HashKeys(u16),
    /// → array of values
    HashValues(u16),
    /// pop N key-value pairs, push as hash
    MakeHash(u16),

    // ── Arithmetic ──
    /// Numeric `a + b` (pops 2, pushes sum).
    Add,
    /// Numeric `a - b` (pops 2, pushes difference).
    Sub,
    /// Numeric `a * b` (pops 2, pushes product).
    Mul,
    /// Numeric `a / b` (pops 2, pushes quotient).
    Div,
    /// Numeric `a % b` (pops 2, pushes remainder).
    Mod,
    /// Numeric `a ** b` (pops 2, pushes power).
    Pow,
    /// Numeric unary minus (`-x`).
    Negate,
    /// In-place += 1 on top-of-stack numeric.
    Inc,
    /// In-place -= 1 on top-of-stack numeric.
    Dec,

    // ── String ──
    /// String concatenation `a . b`.
    Concat,
    /// Repeat a string N times (`a x b` in Perl).
    StringRepeat,
    /// Length of top-of-stack string in bytes.
    StringLen,

    // ── Comparison (numeric) ──
    /// Numeric `eq` comparison.
    NumEq,
    /// Numeric `ne` comparison.
    NumNe,
    /// Numeric `lt` comparison.
    NumLt,
    /// Numeric `gt` comparison.
    NumGt,
    /// Numeric `le` comparison.
    NumLe,
    /// Numeric `ge` comparison.
    NumGe,
    /// <=> → -1, 0, 1
    Spaceship,

    // ── Comparison (string) ──
    /// String `eq` comparison.
    StrEq,
    /// String `ne` comparison.
    StrNe,
    /// String `lt` comparison.
    StrLt,
    /// String `gt` comparison.
    StrGt,
    /// String `le` comparison.
    StrLe,
    /// String `ge` comparison.
    StrGe,
    /// String `cmp` comparison.
    StrCmp,

    // ── Logical / Bitwise ──
    /// Boolean `!` (eager, evaluates both operands for binary forms).
    LogNot,
    /// differs from short-circuit jumps: evaluates both
    LogAnd,
    /// Boolean `||` (eager, evaluates both operands for binary forms).
    LogOr,
    /// Bitwise `and` operation.
    BitAnd,
    /// Bitwise `or` operation.
    BitOr,
    /// Bitwise `xor` operation.
    BitXor,
    /// Bitwise `not` operation.
    BitNot,
    /// Bit-shift left (`<<`/`>>`).
    Shl,
    /// Bit-shift right (`<<`/`>>`).
    Shr,

    // ── Control flow ──
    /// Unconditional jump to the given chunk offset.
    Jump(usize),
    /// Jump if top-of-stack is true; pops predicate.
    JumpIfTrue(usize),
    /// Jump if top-of-stack is false; pops predicate.
    JumpIfFalse(usize),
    /// short-circuit ||
    JumpIfTrueKeep(usize),
    /// short-circuit &&
    JumpIfFalseKeep(usize),

    // ── Functions ──
    /// Call: name_index, arg_count
    Call(u16, u8),
    /// Return from current function with no value (pushes Undef).
    Return,
    /// Return from current function using top-of-stack as the result.
    ReturnValue,

    // ── Scope ──
    /// Push a call frame on the frame stack.
    PushFrame,
    /// Pop a call frame on the frame stack.
    PopFrame,

    // ── I/O ──
    /// Print N values from stack to stdout
    Print(u8),
    /// Print N values + newline
    PrintLn(u8),
    /// Read line from stdin, push as string
    ReadLine,

    // ── Collections ──
    /// [from, to] → array
    Range,
    /// [from, to, step] → array
    RangeStep,

    // ── Higher-order (u16 = block index in chunk) ──
    /// Higher-order `map` over a slot-array using the block at the given chunk index.
    MapBlock(u16),
    /// Higher-order `grep` over a slot-array using the block at the given chunk index.
    GrepBlock(u16),
    /// Higher-order `sort` over a slot-array using the block at the given chunk index.
    SortBlock(u16),
    /// sort with default string comparison
    SortDefault,
    /// Higher-order `foreach` over a slot-array using the block at the given chunk index.
    ForEachBlock(u16),

    // ── Fused superinstructions ──
    // These are the performance secret sauce.
    // The compiler detects hot loop patterns and emits these
    // instead of multi-op sequences.
    /// Slot-indexed pre-increment (no stack traffic)
    PreIncSlot(u16),
    /// `if ($slot < INT) goto target` — fused compare + branch
    SlotLtIntJumpIfFalse(u16, i32, usize),
    /// `$slot += 1; if $slot < limit goto body` — fused loop backedge
    SlotIncLtIntJumpBack(u16, i32, usize),
    /// `while $i < limit { $sum += $i; $i += 1 }` — entire counted sum loop
    AccumSumLoop(u16, u16, i32),
    /// `while $i < limit { $s .= CONST; $i += 1 }` — fused string append loop
    ConcatConstLoop(u16, u16, u16, i32),
    /// `while $i < limit { push @a, $i; $i += 1 }` — fused array push loop
    PushIntRangeLoop(u16, u16, i32),
    /// Void-context slot add-assign: `$a += $b` (no stack push)
    AddAssignSlotVoid(u16, u16),
    /// Void-context pre-increment: `++$slot` (no stack push)
    PreIncSlotVoid(u16),

    // ── Builtins ──
    /// Call a registered builtin by ID: (builtin_id, arg_count)
    /// The builtin table is registered by the frontend at VM init.
    CallBuiltin(u16, u8),

    // ── Extension point ──
    /// Language-specific opcode dispatched through a frontend handler table.
    /// u16 = extension op ID, u8 = inline operand.
    /// Frontends register a `fn(&mut VM, u16, u8)` handler at init.
    Extended(u16, u8),
    /// Extended with usize payload (for jump targets, large indices)
    ExtendedWide(u16, usize),

    // ── Shell ops (registered via Extended, but defined here for type safety) ──
    // These are first-class because process control is universal enough
    // that multiple frontends need them (shell, scripting, build tools).
    /// Spawn external command: pop N args from stack, exec, push exit status
    Exec(u8),
    /// Spawn background: like Exec but don't wait
    ExecBg(u8),
    /// Set up N-stage pipeline
    PipelineBegin(u8),
    /// Wire next pipeline stage
    PipelineStage,
    /// Wait for pipeline, push last status
    PipelineEnd,
    /// Redirect fd: (source_fd, op_byte) — target on stack
    Redirect(u8, u8),
    /// Here-document: fd on stack, content from constant pool
    HereDoc(u16),
    /// Here-string: fd on stack, word on stack
    HereString,
    /// Command substitution: capture stdout of subprogram
    CmdSubst(u16), // u16 = bytecode range index
    /// Subshell: isolate scope
    SubshellBegin,
    /// Shell Ops (Registered Via Extended, But Defined Here For Type Safety) operation (`SubshellEnd`).
    SubshellEnd,
    /// Process substitution <(cmd) — push FIFO path
    ProcessSubIn(u16),
    /// Process substitution >(cmd) — push FIFO path
    ProcessSubOut(u16),
    /// Glob expand: pop pattern, push array of matches
    Glob,
    /// Recursive glob (parallel): pop pattern, push array
    GlobRecursive,
    /// File test: u8 encodes test type (-f=0, -d=1, -r=2, -w=3, -x=4, -e=5, -s=6, -L=7)
    TestFile(u8),
    /// Set last exit status ($?)
    SetStatus,
    /// Get last exit status
    GetStatus,
    /// Set trap handler: signal on stack, handler bytecode range
    TrapSet(u16),
    /// Check pending traps (inserted between ops by compiler)
    TrapCheck,
    /// Expand ${var:-default} family: u8 encodes modifier type
    ExpandParam(u8),
    /// Word split by IFS
    WordSplit,
    /// Brace expand {a,b} and {1..10}
    BraceExpand,
    /// Tilde expand ~ and ~user
    TildeExpand,
    /// Call user-defined shell function by name pool index with N args.
    /// Falls through to host.call_function() then host.exec() if not found.
    /// stack: \[arg_N, ..., arg_1\] → pushes Status
    CallFunction(u16, u8),
    /// Glob-pattern match: pop pattern, pop string, push Bool.
    /// Used by `[[ x = pat ]]` and `case` arm matching.
    StrMatch,
    /// Regex match: pop regex, pop string, push Bool. (`=~`)
    RegexMatch,
    /// Begin scoped redirection block: u8 = number of redirects already
    /// applied via prior Redirect ops. Saves fd state on the host's stack.
    /// Used for `cmd > out.txt` applied to compound commands and
    /// `func() { ... } > out.txt`.
    WithRedirectsBegin(u8),
    /// End scoped redirection block — restore fd state.
    WithRedirectsEnd,
}

/// File test opcodes for `TestFile(u8)`
pub mod file_test {
    /// Regular file (`-f`).
    pub const IS_FILE: u8 = 0;
    /// Directory (`-d`).
    pub const IS_DIR: u8 = 1;
    /// Readable to current uid (`-r`).
    pub const IS_READABLE: u8 = 2;
    /// Writable to current uid (`-w`).
    pub const IS_WRITABLE: u8 = 3;
    /// Executable (`-x`).
    pub const IS_EXECUTABLE: u8 = 4;
    /// Exists (any type, `-e`).
    pub const EXISTS: u8 = 5;
    /// Exists and size > 0 (`-s`).
    pub const IS_NONEMPTY: u8 = 6;
    /// Symbolic link (`-L` / `-h`).
    pub const IS_SYMLINK: u8 = 7;
    /// Unix-domain socket (`-S`).
    pub const IS_SOCKET: u8 = 8;
    /// Named pipe / FIFO (`-p`).
    pub const IS_FIFO: u8 = 9;
    /// Block device (`-b`).
    pub const IS_BLOCK_DEV: u8 = 10;
    /// Character device (`-c`).
    pub const IS_CHAR_DEV: u8 = 11;
}

/// Redirect op types for `Redirect(fd, op)`
pub mod redirect_op {
    /// `> file` — truncate-then-write.
    pub const WRITE: u8 = 0;
    /// `>> file` — open for append.
    pub const APPEND: u8 = 1;
    /// `< file` — open for read.
    pub const READ: u8 = 2;
    /// `<> file` — open for read+write.
    pub const READ_WRITE: u8 = 3;
    /// `>| file` — forced truncate even under `noclobber`.
    pub const CLOBBER: u8 = 4;
    /// `<& N` — duplicate input fd N.
    pub const DUP_READ: u8 = 5;
    /// `>& N` — duplicate output fd N.
    pub const DUP_WRITE: u8 = 6;
    /// `&> file` — redirect both stdout and stderr (truncate).
    pub const WRITE_BOTH: u8 = 7;
    /// `&>> file` — redirect both stdout and stderr (append).
    pub const APPEND_BOTH: u8 = 8;
}

/// Parameter expansion modifier types for `ExpandParam(u8)`
pub mod param_mod {
    /// `${var:-default}` — substitute default if unset/empty.
    pub const DEFAULT: u8 = 0;
    /// `${var:=default}` — assign default if unset/empty.
    pub const ASSIGN: u8 = 1;
    /// `${var:?error}` — error if unset/empty.
    pub const ERROR: u8 = 2;
    /// `${var:+alternate}` — substitute alternate when set.
    pub const ALTERNATE: u8 = 3;
    /// `${#var}` — string length.
    pub const LENGTH: u8 = 4;
    /// `${var#pat}` — strip shortest matching prefix.
    pub const STRIP_SHORT: u8 = 5;
    /// `${var##pat}` — strip longest matching prefix.
    pub const STRIP_LONG: u8 = 6;
    /// `${var%pat}` — strip shortest matching suffix.
    pub const RSTRIP_SHORT: u8 = 7;
    /// `${var%%pat}` — strip longest matching suffix.
    pub const RSTRIP_LONG: u8 = 8;
    /// `${var/pat/rep}` — substitute first match.
    pub const SUBST_FIRST: u8 = 9;
    /// `${var//pat/rep}` — substitute every match.
    pub const SUBST_ALL: u8 = 10;
    /// `${var^^}` — uppercase every char.
    pub const UPPER: u8 = 11;
    /// `${var,,}` — lowercase every char.
    pub const LOWER: u8 = 12;
    /// `${var^}` — uppercase first char.
    pub const UPPER_FIRST: u8 = 13;
    /// `${var,}` — lowercase first char.
    pub const LOWER_FIRST: u8 = 14;
    /// `${!var}` — indirect expand (use value of `var` as name).
    pub const INDIRECT: u8 = 15;
    /// `${!arr[@]}` — array key/index list.
    pub const KEYS: u8 = 16;
    /// `${var:off:len}` — substring slice.
    pub const SLICE: u8 = 17;
}

impl Hash for Op {
    fn hash<H: Hasher>(&self, state: &mut H) {
        std::mem::discriminant(self).hash(state);
        match self {
            Op::LoadInt(n) => n.hash(state),
            Op::LoadFloat(f) => f.to_bits().hash(state),
            Op::LoadConst(idx) => idx.hash(state),
            Op::GetVar(idx)
            | Op::SetVar(idx)
            | Op::DeclareVar(idx)
            | Op::GetSlot(idx)
            | Op::SetSlot(idx)
            | Op::SlotArrayGet(idx)
            | Op::SlotArraySet(idx)
            | Op::GetArray(idx)
            | Op::SetArray(idx)
            | Op::DeclareArray(idx)
            | Op::ArrayGet(idx)
            | Op::ArraySet(idx)
            | Op::ArrayPush(idx)
            | Op::ArrayPop(idx)
            | Op::ArrayShift(idx)
            | Op::ArrayLen(idx)
            | Op::MakeArray(idx)
            | Op::GetHash(idx)
            | Op::SetHash(idx)
            | Op::DeclareHash(idx)
            | Op::HashGet(idx)
            | Op::HashSet(idx)
            | Op::HashDelete(idx)
            | Op::HashExists(idx)
            | Op::HashKeys(idx)
            | Op::HashValues(idx)
            | Op::MakeHash(idx)
            | Op::PreIncSlot(idx)
            | Op::PreIncSlotVoid(idx)
            | Op::HereDoc(idx)
            | Op::CmdSubst(idx)
            | Op::ProcessSubIn(idx)
            | Op::ProcessSubOut(idx)
            | Op::TrapSet(idx)
            | Op::MapBlock(idx)
            | Op::GrepBlock(idx)
            | Op::SortBlock(idx)
            | Op::ForEachBlock(idx) => idx.hash(state),
            Op::Jump(t)
            | Op::JumpIfTrue(t)
            | Op::JumpIfFalse(t)
            | Op::JumpIfTrueKeep(t)
            | Op::JumpIfFalseKeep(t) => t.hash(state),
            Op::Call(name, argc) => {
                name.hash(state);
                argc.hash(state);
            }
            Op::CallBuiltin(id, argc) => {
                id.hash(state);
                argc.hash(state);
            }
            Op::CallFunction(name, argc) => {
                name.hash(state);
                argc.hash(state);
            }
            Op::WithRedirectsBegin(n) => n.hash(state),
            Op::Extended(id, arg) => {
                id.hash(state);
                arg.hash(state);
            }
            Op::ExtendedWide(id, payload) => {
                id.hash(state);
                payload.hash(state);
            }
            Op::Print(n) | Op::PrintLn(n) | Op::Exec(n) | Op::ExecBg(n) | Op::PipelineBegin(n) => {
                n.hash(state)
            }
            Op::Redirect(fd, op) => {
                fd.hash(state);
                op.hash(state);
            }
            Op::TestFile(t) | Op::ExpandParam(t) => t.hash(state),
            Op::SlotLtIntJumpIfFalse(slot, limit, target) => {
                slot.hash(state);
                limit.hash(state);
                target.hash(state);
            }
            Op::SlotIncLtIntJumpBack(slot, limit, target) => {
                slot.hash(state);
                limit.hash(state);
                target.hash(state);
            }
            Op::AccumSumLoop(sum, i, limit) => {
                sum.hash(state);
                i.hash(state);
                limit.hash(state);
            }
            Op::ConcatConstLoop(c, s, i, limit) => {
                c.hash(state);
                s.hash(state);
                i.hash(state);
                limit.hash(state);
            }
            Op::PushIntRangeLoop(arr, i, limit) => {
                arr.hash(state);
                i.hash(state);
                limit.hash(state);
            }
            Op::AddAssignSlotVoid(a, b) => {
                a.hash(state);
                b.hash(state);
            }
            // Nullary ops — discriminant alone is sufficient
            Op::Nop
            | Op::LoadTrue
            | Op::LoadFalse
            | Op::LoadUndef
            | Op::Pop
            | Op::Dup
            | Op::Dup2
            | Op::Swap
            | Op::Rot
            | Op::Add
            | Op::Sub
            | Op::Mul
            | Op::Div
            | Op::Mod
            | Op::Pow
            | Op::Negate
            | Op::Inc
            | Op::Dec
            | Op::Concat
            | Op::StringRepeat
            | Op::StringLen
            | Op::NumEq
            | Op::NumNe
            | Op::NumLt
            | Op::NumGt
            | Op::NumLe
            | Op::NumGe
            | Op::Spaceship
            | Op::StrEq
            | Op::StrNe
            | Op::StrLt
            | Op::StrGt
            | Op::StrLe
            | Op::StrGe
            | Op::StrCmp
            | Op::LogNot
            | Op::LogAnd
            | Op::LogOr
            | Op::BitAnd
            | Op::BitOr
            | Op::BitXor
            | Op::BitNot
            | Op::Shl
            | Op::Shr
            | Op::Return
            | Op::ReturnValue
            | Op::PushFrame
            | Op::PopFrame
            | Op::ReadLine
            | Op::Range
            | Op::RangeStep
            | Op::SortDefault
            | Op::SetStatus
            | Op::GetStatus
            | Op::PipelineStage
            | Op::PipelineEnd
            | Op::HereString
            | Op::SubshellBegin
            | Op::SubshellEnd
            | Op::Glob
            | Op::GlobRecursive
            | Op::TrapCheck
            | Op::WordSplit
            | Op::BraceExpand
            | Op::TildeExpand
            | Op::StrMatch
            | Op::RegexMatch
            | Op::WithRedirectsEnd => {}
        }
    }
}

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

    #[test]
    fn test_op_size() {
        // Ops should be reasonably small for cache-friendly dispatch
        assert!(
            std::mem::size_of::<Op>() <= 24,
            "Op too large: {} bytes",
            std::mem::size_of::<Op>()
        );
    }

    #[test]
    fn equal_ops_hash_equal() {
        use std::collections::hash_map::DefaultHasher;
        let h = |op: &Op| {
            let mut hs = DefaultHasher::new();
            op.hash(&mut hs);
            hs.finish()
        };
        assert_eq!(h(&Op::LoadInt(42)), h(&Op::LoadInt(42)));
        assert_eq!(h(&Op::Jump(7)), h(&Op::Jump(7)));
        assert_eq!(h(&Op::Add), h(&Op::Add));
    }

    #[test]
    fn different_ops_typically_hash_differently() {
        use std::collections::hash_map::DefaultHasher;
        let h = |op: &Op| {
            let mut hs = DefaultHasher::new();
            op.hash(&mut hs);
            hs.finish()
        };
        assert_ne!(h(&Op::LoadInt(1)), h(&Op::LoadInt(2)));
        assert_ne!(h(&Op::Add), h(&Op::Sub));
        assert_ne!(h(&Op::Jump(0)), h(&Op::JumpIfTrue(0)));
    }

    #[test]
    fn float_load_hash_uses_bit_pattern() {
        // f64 must hash via bits — NaN, -0.0 etc. need to be hashable.
        use std::collections::hash_map::DefaultHasher;
        let h = |op: &Op| {
            let mut hs = DefaultHasher::new();
            op.hash(&mut hs);
            hs.finish()
        };
        let a = Op::LoadFloat(f64::NAN);
        let b = Op::LoadFloat(f64::NAN);
        // Same bit pattern → equal hash.
        assert_eq!(h(&a), h(&b));
        // +0.0 and -0.0 are == under PartialEq but have different bits;
        // their hashes will differ — verify the impl is bit-based.
        assert_ne!(h(&Op::LoadFloat(0.0)), h(&Op::LoadFloat(-0.0)));
    }

    #[test]
    fn partialeq_works_for_payloaded_ops() {
        assert_eq!(Op::LoadInt(1), Op::LoadInt(1));
        assert_ne!(Op::LoadInt(1), Op::LoadInt(2));
        assert_eq!(Op::Jump(5), Op::Jump(5));
        assert_ne!(Op::Jump(5), Op::Jump(6));
    }

    #[test]
    fn op_clone_is_value_equal() {
        let a = Op::LoadInt(123);
        let b = a.clone();
        assert_eq!(a, b);
    }

    #[test]
    fn op_serde_roundtrip() {
        // Verify a representative selection of ops survive serde JSON roundtrip.
        let cases = vec![
            Op::Nop,
            Op::LoadInt(-5),
            Op::LoadFloat(1.5),
            Op::Add,
            Op::Jump(42),
            Op::GetSlot(7),
        ];
        for op in cases {
            let s = serde_json::to_string(&op).unwrap();
            let back: Op = serde_json::from_str(&s).unwrap();
            assert_eq!(op, back);
        }
    }

    use std::collections::hash_map::DefaultHasher;

    fn hash_of(op: &Op) -> u64 {
        let mut h = DefaultHasher::new();
        op.hash(&mut h);
        h.finish()
    }

    // ─── Hash impl coverage: every variant arm must produce consistent
    //     hashes and equal-ops-hash-equal regardless of payload class ──

    #[test]
    fn nullary_arithmetic_ops_hash_consistently() {
        for op in [Op::Add, Op::Sub, Op::Mul, Op::Div, Op::Mod, Op::Pow] {
            assert_eq!(hash_of(&op), hash_of(&op.clone()));
        }
    }

    #[test]
    fn distinct_nullary_ops_hash_differently() {
        // Discriminant alone differentiates these. Collisions are theoretically
        // allowed by Hash but DefaultHasher is unlikely to collide on so few.
        let h_add = hash_of(&Op::Add);
        let h_sub = hash_of(&Op::Sub);
        let h_mul = hash_of(&Op::Mul);
        assert_ne!(h_add, h_sub);
        assert_ne!(h_add, h_mul);
        assert_ne!(h_sub, h_mul);
    }

    #[test]
    fn same_idx_in_different_u16_arms_does_not_collide_on_discriminant() {
        // GetVar(5) and SetVar(5) share the payload value but differ in
        // discriminant — must hash differently.
        let h_get = hash_of(&Op::GetVar(5));
        let h_set = hash_of(&Op::SetVar(5));
        assert_ne!(h_get, h_set);
    }

    #[test]
    fn jump_targets_hash_independent_of_call_targets() {
        // Jump(7) and Call(7, 0) share the literal value 7 but should never
        // collide because discriminants differ.
        let h_jump = hash_of(&Op::Jump(7));
        let h_call = hash_of(&Op::Call(7, 0));
        assert_ne!(h_jump, h_call);
    }

    #[test]
    fn call_argc_changes_hash() {
        let h_zero_arg = hash_of(&Op::Call(10, 0));
        let h_two_args = hash_of(&Op::Call(10, 2));
        assert_ne!(h_zero_arg, h_two_args);
    }

    #[test]
    fn float_load_distinct_values_hash_differently() {
        // f64 → to_bits → hash. 1.0 and 2.0 have distinct bit patterns.
        let h_one = hash_of(&Op::LoadFloat(1.0));
        let h_two = hash_of(&Op::LoadFloat(2.0));
        assert_ne!(h_one, h_two);
    }

    #[test]
    fn float_load_neg_zero_and_pos_zero_hash_differently() {
        // 0.0 and -0.0 are == under PartialEq but have different bit patterns,
        // so the bit-based Hash impl produces different hashes. This is consistent
        // with serde_json roundtrip semantics for the constant pool.
        let h_pos = hash_of(&Op::LoadFloat(0.0));
        let h_neg = hash_of(&Op::LoadFloat(-0.0));
        assert_ne!(h_pos, h_neg, "+0.0 and -0.0 have distinct bit patterns");
    }

    #[test]
    fn redirect_op_uses_both_fd_and_op_in_hash() {
        let a = Op::Redirect(0, 1);
        let b = Op::Redirect(0, 2);
        let c = Op::Redirect(1, 1);
        assert_ne!(hash_of(&a), hash_of(&b), "second field changes hash");
        assert_ne!(hash_of(&a), hash_of(&c), "first field changes hash");
    }

    #[test]
    fn extended_uses_both_id_and_arg_in_hash() {
        let a = Op::Extended(1, 2);
        let b = Op::Extended(1, 3);
        let c = Op::Extended(2, 2);
        assert_ne!(hash_of(&a), hash_of(&b));
        assert_ne!(hash_of(&a), hash_of(&c));
    }

    #[test]
    fn three_field_loop_ops_use_all_fields() {
        let base = Op::SlotLtIntJumpIfFalse(1, 10, 100);
        let diff_slot = Op::SlotLtIntJumpIfFalse(2, 10, 100);
        let diff_limit = Op::SlotLtIntJumpIfFalse(1, 99, 100);
        let diff_target = Op::SlotLtIntJumpIfFalse(1, 10, 200);
        assert_ne!(hash_of(&base), hash_of(&diff_slot));
        assert_ne!(hash_of(&base), hash_of(&diff_limit));
        assert_ne!(hash_of(&base), hash_of(&diff_target));
    }

    #[test]
    fn equal_loadint_payloads_hash_equal() {
        // Same payload → same hash, no matter how the value was constructed.
        let a = Op::LoadInt(-42);
        let b = Op::LoadInt(-42);
        assert_eq!(hash_of(&a), hash_of(&b));
    }

    #[test]
    fn pop_dup_swap_rot_are_each_unique() {
        // Common stack ops — discriminant alone differentiates.
        let pop = hash_of(&Op::Pop);
        let dup = hash_of(&Op::Dup);
        let swap = hash_of(&Op::Swap);
        let rot = hash_of(&Op::Rot);
        let set: std::collections::HashSet<_> = [pop, dup, swap, rot].iter().copied().collect();
        assert_eq!(set.len(), 4, "all four nullary stack ops are distinct");
    }

    // ─── Serde round-trip extension: more payload-carrying ops ────────

    #[test]
    fn serde_roundtrip_payload_ops() {
        let cases = vec![
            Op::Call(100, 3),
            Op::CallBuiltin(0, 1),
            Op::Redirect(2, 5),
            Op::Extended(7, 9),
            Op::SlotLtIntJumpIfFalse(1, 10, 200),
        ];
        for op in cases {
            let s = serde_json::to_string(&op).expect("serialize");
            let back: Op = serde_json::from_str(&s).expect("deserialize");
            assert_eq!(op, back);
        }
    }

    #[test]
    fn serde_roundtrip_float_special_values() {
        // Special-case floats: NaN doesn't round-trip via PartialEq, so
        // only check finite ones.
        for f in [0.0, -0.0, 1.5, -1.5, f64::MIN, f64::MAX] {
            let op = Op::LoadFloat(f);
            let s = serde_json::to_string(&op).expect("ser");
            let back: Op = serde_json::from_str(&s).expect("de");
            assert_eq!(op, back, "roundtrip {f}");
        }
    }

    // ─── tests for the `block` constants module ───────────────────────

    #[test]
    fn param_mod_constants_are_unique_and_within_u8() {
        // Each ExpandParam modifier maps to a distinct u8 op-code; verify no
        // collisions on the 18-value table.
        let names = [
            param_mod::DEFAULT,
            param_mod::ASSIGN,
            param_mod::ERROR,
            param_mod::ALTERNATE,
            param_mod::LENGTH,
            param_mod::STRIP_SHORT,
            param_mod::STRIP_LONG,
            param_mod::RSTRIP_SHORT,
            param_mod::RSTRIP_LONG,
            param_mod::SUBST_FIRST,
            param_mod::SUBST_ALL,
            param_mod::UPPER,
            param_mod::LOWER,
            param_mod::UPPER_FIRST,
            param_mod::LOWER_FIRST,
            param_mod::INDIRECT,
            param_mod::KEYS,
            param_mod::SLICE,
        ];
        let set: std::collections::HashSet<_> = names.iter().copied().collect();
        assert_eq!(set.len(), names.len(), "param_mod constants must be unique");
    }
}