xqvm 0.1.0

X-Quadratic Virtual Machine — bytecode interpreter for the XQuad Toolchain
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
// Copyright (C) 2026 Postquant Labs Incorporated
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

use core::fmt;

use super::Opcode;
use super::RegisterEffect;

// ---------------------------------------------------------------------------
// Macro-generated Instruction enum
// ---------------------------------------------------------------------------

macro_rules! impl_instruction {
    (
        $( ($code:literal, $variant:ident, $mnem:literal, $doc:literal, {$($fname:ident: $ftype:ty),*}) ),*
        $(,)?
    ) => {
        /// A fully decoded XQVM instruction with its operands.
        ///
        /// All variants use named struct syntax. Unit-like instructions (no
        /// operands) use an empty field list (`Nop {}`). This uniform
        /// representation allows the entire enum to be generated from the
        /// [`opcodes!`](crate::opcodes) x-macro without any special-casing.
        ///
        /// Use [`Instruction::opcode`] to recover the corresponding
        /// [`Opcode`], or [`Instruction::mnemonic`] for the assembly string.
        ///
        /// # Examples
        ///
        /// ```rust
        /// use xqvm::{Instruction, Opcode, Register};
        ///
        /// let instr = Instruction::Pop {};
        /// assert_eq!(instr.opcode(), Opcode::Pop);
        /// assert_eq!(instr.mnemonic(), "POP");
        ///
        /// let instr = Instruction::Energy {
        ///     model:  Register(0),
        ///     sample: Register(1),
        /// };
        /// assert_eq!(instr.opcode(), Opcode::Energy);
        /// ```
        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
        pub enum Instruction {
            $(
                #[doc = $doc]
                $variant {
                    $(
                        #[expect(missing_docs, reason = "macro-generated enum variant fields don't warrant individual doc comments")]
                        $fname: $ftype,
                    )*
                },
            )*
        }

        impl Instruction {
            /// Return the [`Opcode`] corresponding to this instruction.
            ///
            /// # Examples
            ///
            /// ```rust
            /// use xqvm::{Instruction, Opcode, Register};
            ///
            /// assert_eq!(Instruction::Add {}.opcode(), Opcode::Add);
            /// assert_eq!(Instruction::Stow { reg: Register(7) }.opcode(), Opcode::Stow);
            /// ```
            pub fn opcode(&self) -> Opcode {
                match self {
                    $( Self::$variant { .. } => Opcode::$variant, )*
                }
            }

            /// Return the uppercase assembly mnemonic for this instruction.
            ///
            /// Delegates to [`Opcode::mnemonic`].
            ///
            /// # Examples
            ///
            /// ```rust
            /// use xqvm::Instruction;
            ///
            /// assert_eq!(Instruction::Halt {}.mnemonic(), "HALT");
            /// ```
            pub fn mnemonic(&self) -> &'static str {
                self.opcode().mnemonic()
            }
        }
    };
}

opcodes!(impl_instruction);

// ---------------------------------------------------------------------------
// Register introspection
// ---------------------------------------------------------------------------

impl Instruction {
    /// Register indices this instruction reads from.
    ///
    /// Returns the set of register slots whose current values are consumed
    /// by this instruction. Stack-only and control-flow-only instructions
    /// return an empty set.
    pub fn read_registers(&self) -> RegisterEffect {
        match self {
            // -- No register reads --
            // Control flow
            Self::Nop { .. }
            | Self::Target { .. }
            | Self::Jump1 { .. }
            | Self::Jump2 { .. }
            | Self::JumpI1 { .. }
            | Self::JumpI2 { .. }
            | Self::Next { .. }
            | Self::Range { .. }
            | Self::Halt { .. }
            // Stack manipulation
            | Self::Pop { .. }
            | Self::Push1 { .. }
            | Self::Push2 { .. }
            | Self::Push3 { .. }
            | Self::Push4 { .. }
            | Self::Push5 { .. }
            | Self::Push6 { .. }
            | Self::Push7 { .. }
            | Self::Push8 { .. }
            | Self::Sclr { .. }
            | Self::Swap { .. }
            | Self::Copy { .. }
            // Arithmetic
            | Self::Add { .. }
            | Self::Sub { .. }
            | Self::Mul { .. }
            | Self::Div { .. }
            | Self::Modulo { .. }
            | Self::Sqr { .. }
            | Self::Abs { .. }
            | Self::Neg { .. }
            | Self::Min { .. }
            | Self::Max { .. }
            | Self::Inc { .. }
            | Self::Dec { .. }
            // Comparison
            | Self::Eq { .. }
            | Self::Lt { .. }
            | Self::Gt { .. }
            | Self::Lte { .. }
            | Self::Gte { .. }
            // Logical
            | Self::Not { .. }
            | Self::And { .. }
            | Self::Or { .. }
            | Self::Xor { .. }
            // Bitwise
            | Self::BAnd { .. }
            | Self::BOr { .. }
            | Self::BXor { .. }
            | Self::BNot { .. }
            | Self::Shl { .. }
            | Self::Shr { .. }
            // Index math
            | Self::IdxGrid { .. }
            | Self::IdxTriu { .. }
            // Write-only: allocators + stores
            | Self::Stow { .. }
            | Self::Drop { .. }
            | Self::Input { .. }
            | Self::Lidx { .. }
            | Self::LVal { .. }
            | Self::Bqmx { .. }
            | Self::Sqmx { .. }
            | Self::Xqmx { .. }
            | Self::Bsmx { .. }
            | Self::Ssmx { .. }
            | Self::Xsmx { .. }
            | Self::Vec { .. }
            | Self::VecI { .. }
            | Self::VecX { .. } => RegisterEffect::EMPTY,

            // -- Single register reads --
            Self::Load { reg }
            | Self::Output { reg }
            | Self::Iter { reg }
            | Self::VecGet { reg }
            | Self::VecLen { reg }
            | Self::GetLine { reg }
            | Self::GetQuad { reg }
            | Self::RowFind { reg }
            | Self::ColFind { reg }
            | Self::RowSum { reg }
            | Self::ColSum { reg }
            // Read+write
            | Self::VecPush { reg }
            | Self::VecSet { reg }
            | Self::SetLine { reg }
            | Self::AddLine { reg }
            | Self::SetQuad { reg }
            | Self::AddQuad { reg }
            | Self::Resize { reg }
            | Self::OneHotR { reg }
            | Self::OneHotC { reg }
            | Self::Exclude { reg }
            | Self::Implies { reg } => RegisterEffect::one(reg.slot()),

            // -- Two register reads --
            Self::Energy { model, sample } => {
                RegisterEffect::two(model.slot(), sample.slot())
            }
        }
    }

    /// Register indices this instruction writes to.
    ///
    /// Returns the set of register slots whose values are modified by this
    /// instruction. Stack-only, control-flow-only, and read-only register
    /// instructions return an empty set.
    pub fn written_registers(&self) -> RegisterEffect {
        match self {
            // -- No register writes --
            // Control flow
            Self::Nop { .. }
            | Self::Target { .. }
            | Self::Jump1 { .. }
            | Self::Jump2 { .. }
            | Self::JumpI1 { .. }
            | Self::JumpI2 { .. }
            | Self::Next { .. }
            | Self::Range { .. }
            | Self::Halt { .. }
            // Stack manipulation
            | Self::Pop { .. }
            | Self::Push1 { .. }
            | Self::Push2 { .. }
            | Self::Push3 { .. }
            | Self::Push4 { .. }
            | Self::Push5 { .. }
            | Self::Push6 { .. }
            | Self::Push7 { .. }
            | Self::Push8 { .. }
            | Self::Sclr { .. }
            | Self::Swap { .. }
            | Self::Copy { .. }
            // Arithmetic
            | Self::Add { .. }
            | Self::Sub { .. }
            | Self::Mul { .. }
            | Self::Div { .. }
            | Self::Modulo { .. }
            | Self::Sqr { .. }
            | Self::Abs { .. }
            | Self::Neg { .. }
            | Self::Min { .. }
            | Self::Max { .. }
            | Self::Inc { .. }
            | Self::Dec { .. }
            // Comparison
            | Self::Eq { .. }
            | Self::Lt { .. }
            | Self::Gt { .. }
            | Self::Lte { .. }
            | Self::Gte { .. }
            // Logical
            | Self::Not { .. }
            | Self::And { .. }
            | Self::Or { .. }
            | Self::Xor { .. }
            // Bitwise
            | Self::BAnd { .. }
            | Self::BOr { .. }
            | Self::BXor { .. }
            | Self::BNot { .. }
            | Self::Shl { .. }
            | Self::Shr { .. }
            // Index math
            | Self::IdxGrid { .. }
            | Self::IdxTriu { .. }
            // Read-only register ops
            | Self::Load { .. }
            | Self::Output { .. }
            | Self::Iter { .. }
            | Self::VecGet { .. }
            | Self::VecLen { .. }
            | Self::GetLine { .. }
            | Self::GetQuad { .. }
            | Self::RowFind { .. }
            | Self::ColFind { .. }
            | Self::RowSum { .. }
            | Self::ColSum { .. }
            // Energy reads two, writes none
            | Self::Energy { .. } => RegisterEffect::EMPTY,

            // -- Single register writes --
            // Write-only
            Self::Stow { reg }
            | Self::Drop { reg }
            | Self::Input { reg }
            | Self::Lidx { reg }
            | Self::LVal { reg }
            | Self::Bqmx { reg }
            | Self::Sqmx { reg }
            | Self::Xqmx { reg }
            | Self::Bsmx { reg }
            | Self::Ssmx { reg }
            | Self::Xsmx { reg }
            | Self::Vec { reg }
            | Self::VecI { reg }
            | Self::VecX { reg }
            // Read+write
            | Self::VecPush { reg }
            | Self::VecSet { reg }
            | Self::SetLine { reg }
            | Self::AddLine { reg }
            | Self::SetQuad { reg }
            | Self::AddQuad { reg }
            | Self::Resize { reg }
            | Self::OneHotR { reg }
            | Self::OneHotC { reg }
            | Self::Exclude { reg }
            | Self::Implies { reg } => RegisterEffect::one(reg.slot()),
        }
    }
}

// ---------------------------------------------------------------------------
// Display
// ---------------------------------------------------------------------------

/// Sign-extend a big-endian byte slice (1..=8 bytes) to `i64`.
#[expect(
    clippy::cast_possible_truncation,
    reason = "bytes.len() <= 8 per debug_assert; 8 * 8 = 64 always fits in u32"
)]
fn sign_extend_be(bytes: &[u8]) -> i64 {
    debug_assert!(!bytes.is_empty() && bytes.len() <= 8);
    let mut v = 0i64;
    for &b in bytes {
        v = (v << 8) | i64::from(b);
    }
    let shift = 64u32 - (bytes.len() * 8) as u32;
    (v << shift) >> shift
}

impl fmt::Display for Instruction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            // Push variants: show decoded integer value.
            Self::Push1 { val } => write!(f, "PUSH1 {}", sign_extend_be(val)),
            Self::Push2 { val } => write!(f, "PUSH2 {}", sign_extend_be(val)),
            Self::Push3 { val } => write!(f, "PUSH3 {}", sign_extend_be(val)),
            Self::Push4 { val } => write!(f, "PUSH4 {}", sign_extend_be(val)),
            Self::Push5 { val } => write!(f, "PUSH5 {}", sign_extend_be(val)),
            Self::Push6 { val } => write!(f, "PUSH6 {}", sign_extend_be(val)),
            Self::Push7 { val } => write!(f, "PUSH7 {}", sign_extend_be(val)),
            Self::Push8 { val } => write!(f, "PUSH8 {}", sign_extend_be(val)),

            // Jump variants: show label index with dot prefix.
            Self::Jump1 { label } => write!(f, "JUMP1 .{label}"),
            Self::Jump2 { label } => write!(f, "JUMP2 .{label}"),
            Self::JumpI1 { label } => write!(f, "JUMPI1 .{label}"),
            Self::JumpI2 { label } => write!(f, "JUMPI2 .{label}"),

            // Energy: two register operands.
            Self::Energy { model, sample } => {
                write!(f, "ENERGY r{} r{}", model.slot(), sample.slot())
            }

            // All other single-register variants.
            Self::Load { reg }
            | Self::Stow { reg }
            | Self::Drop { reg }
            | Self::Input { reg }
            | Self::Output { reg }
            | Self::Lidx { reg }
            | Self::LVal { reg }
            | Self::Iter { reg }
            | Self::Bqmx { reg }
            | Self::Sqmx { reg }
            | Self::Xqmx { reg }
            | Self::Bsmx { reg }
            | Self::Ssmx { reg }
            | Self::Xsmx { reg }
            | Self::Vec { reg }
            | Self::VecI { reg }
            | Self::VecX { reg }
            | Self::VecPush { reg }
            | Self::VecGet { reg }
            | Self::VecSet { reg }
            | Self::VecLen { reg }
            | Self::GetLine { reg }
            | Self::SetLine { reg }
            | Self::AddLine { reg }
            | Self::GetQuad { reg }
            | Self::SetQuad { reg }
            | Self::AddQuad { reg }
            | Self::Resize { reg }
            | Self::RowFind { reg }
            | Self::ColFind { reg }
            | Self::RowSum { reg }
            | Self::ColSum { reg }
            | Self::OneHotR { reg }
            | Self::OneHotC { reg }
            | Self::Exclude { reg }
            | Self::Implies { reg } => {
                write!(f, "{} r{}", self.mnemonic(), reg.slot())
            }

            // No-operand variants: just the mnemonic.
            _ => write!(f, "{}", self.mnemonic()),
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bytecode::types::Register;

    // Build a flat array of (Instruction, expected_opcode, mnemonic) triples
    // from the x-macro table so every variant is covered automatically.
    // Each operand is zero-initialised: Register(0), 0i16, 0i64.
    macro_rules! all_instruction_opcode_pairs {
        (
            $( ($code:literal, $variant:ident, $mnem:literal, $doc:literal, {$($fname:ident: $ftype:ty),*}) ),*
            $(,)?
        ) => {
            [
                $(
                    (
                        Instruction::$variant {
                            $( $fname: <$ftype as Default>::default(), )*
                        },
                        Opcode::$variant,
                        $mnem,
                    )
                ),*
            ]
        };
    }

    #[test]
    fn opcode_method_covers_all_variants() {
        for (instr, expected, _) in opcodes!(all_instruction_opcode_pairs) {
            assert_eq!(instr.opcode(), expected, "opcode mismatch for {instr:?}");
        }
    }

    #[test]
    fn mnemonic_method_covers_all_variants() {
        for (instr, _, expected_mnem) in opcodes!(all_instruction_opcode_pairs) {
            assert_eq!(
                instr.mnemonic(),
                expected_mnem,
                "mnemonic mismatch for {instr:?}"
            );
        }
    }

    #[test]
    fn instruction_count_is_87() {
        assert_eq!(opcodes!(all_instruction_opcode_pairs).len(), 87);
    }

    #[test]
    fn energy_named_fields() {
        let e = Instruction::Energy {
            model: Register(0),
            sample: Register(1),
        };
        assert_eq!(e.opcode(), Opcode::Energy);
        if let Instruction::Energy { model, sample } = e {
            assert_eq!(model.slot(), 0);
            assert_eq!(sample.slot(), 1);
        } else {
            panic!("pattern match failed");
        }
    }

    #[test]
    fn read_registers_stack_only() {
        let add = Instruction::Add {};
        assert!(add.read_registers().is_empty());
        assert!(add.written_registers().is_empty());
    }

    #[test]
    fn read_registers_load() {
        let load = Instruction::Load { reg: Register(5) };
        assert_eq!(load.read_registers().as_slice(), &[5]);
        assert!(load.written_registers().is_empty());
    }

    #[test]
    fn written_registers_stow() {
        let stow = Instruction::Stow { reg: Register(3) };
        assert!(stow.read_registers().is_empty());
        assert_eq!(stow.written_registers().as_slice(), &[3]);
    }

    #[test]
    fn read_write_registers_vec_push() {
        let vp = Instruction::VecPush { reg: Register(0) };
        assert_eq!(vp.read_registers().as_slice(), &[0]);
        assert_eq!(vp.written_registers().as_slice(), &[0]);
    }

    #[test]
    fn read_registers_energy() {
        let e = Instruction::Energy {
            model: Register(1),
            sample: Register(2),
        };
        assert_eq!(e.read_registers().as_slice(), &[1, 2]);
        assert!(e.written_registers().is_empty());
    }

    #[test]
    fn all_variants_covered_by_read_and_written() {
        for (instr, _, _) in opcodes!(all_instruction_opcode_pairs) {
            let _ = instr.read_registers();
            let _ = instr.written_registers();
        }
    }

    #[cfg(not(feature = "std"))]
    use alloc::format;

    #[test]
    fn display_no_operands() {
        assert_eq!(format!("{}", Instruction::Add {}), "ADD");
        assert_eq!(format!("{}", Instruction::Halt {}), "HALT");
        assert_eq!(format!("{}", Instruction::Nop {}), "NOP");
    }

    #[test]
    fn display_register_operand() {
        assert_eq!(
            format!("{}", Instruction::Load { reg: Register(5) }),
            "LOAD r5",
        );
        assert_eq!(
            format!("{}", Instruction::Stow { reg: Register(0) }),
            "STOW r0",
        );
    }

    #[test]
    fn display_push() {
        assert_eq!(
            format!(
                "{}",
                Instruction::Push8 {
                    val: 42i64.to_be_bytes()
                }
            ),
            "PUSH8 42",
        );
        assert_eq!(
            format!("{}", Instruction::Push1 { val: [0xFF] }),
            "PUSH1 -1",
        );
    }

    #[test]
    fn display_jump() {
        assert_eq!(format!("{}", Instruction::Jump1 { label: 3 }), "JUMP1 .3");
        assert_eq!(
            format!("{}", Instruction::Jump2 { label: 300 }),
            "JUMP2 .300",
        );
        assert_eq!(format!("{}", Instruction::JumpI1 { label: 3 }), "JUMPI1 .3");
        assert_eq!(
            format!("{}", Instruction::JumpI2 { label: 300 }),
            "JUMPI2 .300",
        );
    }

    #[test]
    fn display_energy() {
        assert_eq!(
            format!(
                "{}",
                Instruction::Energy {
                    model: Register(0),
                    sample: Register(1)
                }
            ),
            "ENERGY r0 r1",
        );
    }
}