plotnik-bytecode 0.3.2

Bytecode format and runtime types for Plotnik
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
//! Bytecode instruction definitions.
//!
//! Instructions are runtime-friendly structs with `from_bytes`/`to_bytes`
//! methods for bytecode serialization.

use std::num::NonZeroU16;

use super::constants::{SECTION_ALIGN, STEP_SIZE};
use super::effects::EffectOp;
use super::nav::Nav;
use super::node_type_ir::NodeTypeIR;

/// Step address in bytecode (raw u16).
///
/// Used for layout addresses, entrypoint targets, bootstrap parameter, etc.
/// For decoded instruction successors (where 0 = terminal), use [`StepId`] instead.
pub type StepAddr = u16;

/// Successor step address in decoded instructions.
///
/// Uses NonZeroU16 because raw 0 means "terminal" (no successor).
/// This type is only for decoded instruction successors - use raw `u16`
/// for addresses in layout, entrypoints, and VM internals.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[repr(transparent)]
pub struct StepId(pub NonZeroU16);

impl StepId {
    /// Create a new StepId. Panics if n == 0.
    #[inline]
    pub fn new(n: u16) -> Self {
        Self(NonZeroU16::new(n).expect("StepId cannot be 0"))
    }

    /// Get the raw u16 value.
    #[inline]
    pub fn get(self) -> u16 {
        self.0.get()
    }
}

/// Instruction opcodes (4-bit).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(u8)]
pub enum Opcode {
    Match8 = 0x0,
    Match16 = 0x1,
    Match24 = 0x2,
    Match32 = 0x3,
    Match48 = 0x4,
    Match64 = 0x5,
    Call = 0x6,
    Return = 0x7,
    Trampoline = 0x8,
}

impl Opcode {
    pub fn from_u8(v: u8) -> Self {
        match v {
            0x0 => Self::Match8,
            0x1 => Self::Match16,
            0x2 => Self::Match24,
            0x3 => Self::Match32,
            0x4 => Self::Match48,
            0x5 => Self::Match64,
            0x6 => Self::Call,
            0x7 => Self::Return,
            0x8 => Self::Trampoline,
            _ => panic!("invalid opcode: {v}"),
        }
    }

    /// Instruction size in bytes.
    pub fn size(self) -> usize {
        match self {
            Self::Match8 => 8,
            Self::Match16 => 16,
            Self::Match24 => 24,
            Self::Match32 => 32,
            Self::Match48 => 48,
            Self::Match64 => 64,
            Self::Call => 8,
            Self::Return => 8,
            Self::Trampoline => 8,
        }
    }

    /// Number of steps this instruction occupies.
    pub fn step_count(self) -> u16 {
        (self.size() / STEP_SIZE) as u16
    }

    /// Whether this is a Match variant.
    pub fn is_match(self) -> bool {
        matches!(
            self,
            Self::Match8
                | Self::Match16
                | Self::Match24
                | Self::Match32
                | Self::Match48
                | Self::Match64
        )
    }

    /// Whether this is an extended Match (Match16-64).
    pub fn is_extended_match(self) -> bool {
        matches!(
            self,
            Self::Match16 | Self::Match24 | Self::Match32 | Self::Match48 | Self::Match64
        )
    }

    /// Payload capacity in u16 slots for extended Match variants.
    pub fn payload_slots(self) -> usize {
        match self {
            Self::Match16 => 4,
            Self::Match24 => 8,
            Self::Match32 => 12,
            Self::Match48 => 20,
            Self::Match64 => 28,
            _ => 0,
        }
    }
}

/// Match instruction decoded from bytecode.
///
/// Provides iterator-based access to effects and successors without allocating.
#[derive(Clone, Copy, Debug)]
pub struct Match<'a> {
    bytes: &'a [u8],
    /// Segment index (0-3, currently only 0 is used).
    pub segment: u8,
    /// Navigation command. `Epsilon` means no cursor movement or node check.
    pub nav: Nav,
    /// Node type constraint (Any = wildcard, Named/Anonymous for specific checks).
    pub node_type: NodeTypeIR,
    /// Field constraint (None = wildcard).
    pub node_field: Option<NonZeroU16>,
    /// Whether this is Match8 (no payload) or extended.
    is_match8: bool,
    /// For Match8: the single successor (0 = terminal).
    match8_next: u16,
    /// For extended: counts packed into single byte each.
    pre_count: u8,
    neg_count: u8,
    post_count: u8,
    succ_count: u8,
    /// Whether this instruction has a predicate (4-byte payload).
    has_predicate: bool,
}

impl<'a> Match<'a> {
    /// Parse a Match instruction from bytecode without allocating.
    ///
    /// The slice must start at the instruction and contain at least
    /// the full instruction size (determined by opcode).
    ///
    /// Header byte layout: `segment(2) | node_kind(2) | opcode(4)`
    #[inline]
    pub fn from_bytes(bytes: &'a [u8]) -> Self {
        debug_assert!(bytes.len() >= 8, "Match instruction too short");

        let type_id_byte = bytes[0];
        // Header byte: segment(2) | node_kind(2) | opcode(4)
        let segment = (type_id_byte >> 6) & 0x3;
        let node_kind = (type_id_byte >> 4) & 0x3;
        let opcode = Opcode::from_u8(type_id_byte & 0xF);
        debug_assert!(segment == 0, "non-zero segment not yet supported");
        debug_assert!(opcode.is_match(), "expected Match opcode");

        let nav = Nav::from_byte(bytes[1]);
        let node_type_val = u16::from_le_bytes([bytes[2], bytes[3]]);
        let node_type = NodeTypeIR::from_bytes(node_kind, node_type_val);
        let node_field = NonZeroU16::new(u16::from_le_bytes([bytes[4], bytes[5]]));

        let (is_match8, match8_next, pre_count, neg_count, post_count, succ_count, has_predicate) =
            if opcode == Opcode::Match8 {
                let next = u16::from_le_bytes([bytes[6], bytes[7]]);
                (true, next, 0, 0, 0, if next == 0 { 0 } else { 1 }, false)
            } else {
                // counts field layout (16 bits):
                // bits 15-13: pre_count (3)
                // bits 12-10: neg_count (3)
                // bits  9-7:  post_count (3)
                // bits  6-2:  succ_count (5, max 31)
                // bit   1:    has_predicate
                // bit   0:    reserved
                let counts = u16::from_le_bytes([bytes[6], bytes[7]]);
                (
                    false,
                    0,
                    ((counts >> 13) & 0x7) as u8,
                    ((counts >> 10) & 0x7) as u8,
                    ((counts >> 7) & 0x7) as u8,
                    ((counts >> 2) & 0x1F) as u8,
                    (counts >> 1) & 0x1 != 0,
                )
            };

        Self {
            bytes,
            segment,
            nav,
            node_type,
            node_field,
            is_match8,
            match8_next,
            pre_count,
            neg_count,
            post_count,
            succ_count,
            has_predicate,
        }
    }

    /// Check if this is a terminal (accept) state.
    #[inline]
    pub fn is_terminal(&self) -> bool {
        self.succ_count == 0
    }

    /// Check if this is an epsilon transition (no node interaction).
    #[inline]
    pub fn is_epsilon(&self) -> bool {
        self.nav == Nav::Epsilon
    }

    /// Check if this is a Match8 (8-byte fast-path instruction).
    #[inline]
    pub fn is_match8(&self) -> bool {
        self.is_match8
    }

    /// Number of successors.
    #[inline]
    pub fn succ_count(&self) -> usize {
        self.succ_count as usize
    }

    /// Get a successor by index.
    #[inline]
    pub fn successor(&self, idx: usize) -> StepId {
        debug_assert!(
            idx < self.succ_count as usize,
            "successor index out of bounds"
        );
        if self.is_match8 {
            debug_assert!(idx == 0);
            debug_assert!(self.match8_next != 0, "terminal has no successors");
            StepId::new(self.match8_next)
        } else {
            let offset = self.succ_offset() + idx * 2;
            StepId::new(u16::from_le_bytes([
                self.bytes[offset],
                self.bytes[offset + 1],
            ]))
        }
    }

    /// Iterate over pre-effects (executed before match attempt).
    #[inline]
    pub fn pre_effects(&self) -> impl Iterator<Item = EffectOp> + '_ {
        let start = 8; // payload starts at byte 8
        (0..self.pre_count as usize).map(move |i| {
            let offset = start + i * 2;
            EffectOp::from_bytes([self.bytes[offset], self.bytes[offset + 1]])
        })
    }

    /// Iterate over negated fields (must NOT be present on matched node).
    #[inline]
    pub fn neg_fields(&self) -> impl Iterator<Item = u16> + '_ {
        let start = 8 + (self.pre_count as usize) * 2;
        (0..self.neg_count as usize).map(move |i| {
            let offset = start + i * 2;
            u16::from_le_bytes([self.bytes[offset], self.bytes[offset + 1]])
        })
    }

    /// Iterate over post-effects (executed after successful match).
    #[inline]
    pub fn post_effects(&self) -> impl Iterator<Item = EffectOp> + '_ {
        let start = 8 + (self.pre_count as usize + self.neg_count as usize) * 2;
        (0..self.post_count as usize).map(move |i| {
            let offset = start + i * 2;
            EffectOp::from_bytes([self.bytes[offset], self.bytes[offset + 1]])
        })
    }

    /// Iterate over successors.
    #[inline]
    pub fn successors(&self) -> impl Iterator<Item = StepId> + '_ {
        (0..self.succ_count as usize).map(move |i| self.successor(i))
    }

    /// Whether this instruction has a predicate (text filter).
    #[inline]
    pub fn has_predicate(&self) -> bool {
        self.has_predicate
    }

    /// Get predicate data if present: (op, is_regex, value_ref).
    ///
    /// - `op`: operator (0=Eq, 1=Ne, 2=StartsWith, 3=EndsWith, 4=Contains, 5=RegexMatch, 6=RegexNoMatch)
    /// - `is_regex`: true if value_ref is a RegexTable index, false if StringTable index
    /// - `value_ref`: index into the appropriate table
    pub fn predicate(&self) -> Option<(u8, bool, u16)> {
        if !self.has_predicate {
            return None;
        }

        let effects_size =
            (self.pre_count as usize + self.neg_count as usize + self.post_count as usize) * 2;
        let offset = 8 + effects_size;

        let op_and_flags = u16::from_le_bytes([self.bytes[offset], self.bytes[offset + 1]]);
        let op = (op_and_flags & 0xFF) as u8;
        let is_regex = (op_and_flags >> 8) & 0x1 != 0;
        let value_ref = u16::from_le_bytes([self.bytes[offset + 2], self.bytes[offset + 3]]);

        Some((op, is_regex, value_ref))
    }

    /// Byte offset where successors start in the payload.
    /// Accounts for predicate (4 bytes) if present.
    #[inline]
    fn succ_offset(&self) -> usize {
        let effects_size =
            (self.pre_count as usize + self.neg_count as usize + self.post_count as usize) * 2;
        let predicate_size = if self.has_predicate { 4 } else { 0 };
        8 + effects_size + predicate_size
    }
}

/// Call instruction for invoking definitions (recursion).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Call {
    /// Segment index (0-3).
    pub segment: u8,
    /// Navigation to apply before jumping to target.
    pub nav: Nav,
    /// Field constraint (None = no constraint).
    pub node_field: Option<NonZeroU16>,
    /// Return address (current segment).
    pub next: StepId,
    /// Callee entry point (target segment from type_id).
    pub target: StepId,
}

impl Call {
    /// Create a new Call instruction.
    pub fn new(nav: Nav, node_field: Option<NonZeroU16>, next: StepId, target: StepId) -> Self {
        Self {
            segment: 0,
            nav,
            node_field,
            next,
            target,
        }
    }

    /// Decode from 8-byte bytecode.
    ///
    /// Header byte layout: `segment(2) | node_kind(2) | opcode(4)`
    /// For Call, node_kind bits are ignored (always 0).
    pub(crate) fn from_bytes(bytes: [u8; 8]) -> Self {
        let type_id_byte = bytes[0];
        let segment = (type_id_byte >> 6) & 0x3;
        let opcode = Opcode::from_u8(type_id_byte & 0xF);
        assert!(
            segment == 0,
            "non-zero segment not yet supported: {segment}"
        );
        assert_eq!(opcode, Opcode::Call, "expected Call opcode");

        Self {
            segment,
            nav: Nav::from_byte(bytes[1]),
            node_field: NonZeroU16::new(u16::from_le_bytes([bytes[2], bytes[3]])),
            next: StepId::new(u16::from_le_bytes([bytes[4], bytes[5]])),
            target: StepId::new(u16::from_le_bytes([bytes[6], bytes[7]])),
        }
    }

    /// Encode to 8-byte bytecode.
    ///
    /// Header byte layout: `segment(2) | node_kind(2) | opcode(4)`
    pub fn to_bytes(&self) -> [u8; 8] {
        let mut bytes = [0u8; 8];
        // node_kind = 0 for Call
        bytes[0] = (self.segment << 6) | (Opcode::Call as u8);
        bytes[1] = self.nav.to_byte();
        bytes[2..4].copy_from_slice(&self.node_field.map_or(0, |v| v.get()).to_le_bytes());
        bytes[4..6].copy_from_slice(&self.next.get().to_le_bytes());
        bytes[6..8].copy_from_slice(&self.target.get().to_le_bytes());
        bytes
    }

    pub fn nav(&self) -> Nav {
        self.nav
    }
    pub fn node_field(&self) -> Option<NonZeroU16> {
        self.node_field
    }
    pub fn next(&self) -> StepId {
        self.next
    }
    pub fn target(&self) -> StepId {
        self.target
    }
}

/// Return instruction for returning from definitions.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Return {
    /// Segment index (0-3).
    pub segment: u8,
}

impl Return {
    /// Create a new Return instruction.
    pub fn new() -> Self {
        Self { segment: 0 }
    }

    /// Decode from 8-byte bytecode.
    ///
    /// Header byte layout: `segment(2) | node_kind(2) | opcode(4)`
    /// For Return, node_kind bits are ignored (always 0).
    pub(crate) fn from_bytes(bytes: [u8; 8]) -> Self {
        let type_id_byte = bytes[0];
        let segment = (type_id_byte >> 6) & 0x3;
        let opcode = Opcode::from_u8(type_id_byte & 0xF);
        assert!(
            segment == 0,
            "non-zero segment not yet supported: {segment}"
        );
        assert_eq!(opcode, Opcode::Return, "expected Return opcode");

        Self { segment }
    }

    /// Encode to 8-byte bytecode.
    ///
    /// Header byte layout: `segment(2) | node_kind(2) | opcode(4)`
    pub fn to_bytes(&self) -> [u8; 8] {
        let mut bytes = [0u8; 8];
        // node_kind = 0 for Return
        bytes[0] = (self.segment << 6) | (Opcode::Return as u8);
        // bytes[1..8] are reserved/padding
        bytes
    }
}

impl Default for Return {
    fn default() -> Self {
        Self::new()
    }
}

/// Trampoline instruction for universal entry.
///
/// Like Call, but the target comes from VM context (external parameter)
/// rather than being encoded in the instruction. Used at address 0 for
/// the entry preamble: `Obj → Trampoline → EndObj → Accept`.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Trampoline {
    /// Segment index (0-3).
    pub segment: u8,
    /// Return address (where to continue after entrypoint returns).
    pub next: StepId,
}

impl Trampoline {
    /// Create a new Trampoline instruction.
    pub fn new(next: StepId) -> Self {
        Self { segment: 0, next }
    }

    /// Decode from 8-byte bytecode.
    ///
    /// Header byte layout: `segment(2) | node_kind(2) | opcode(4)`
    /// For Trampoline, node_kind bits are ignored (always 0).
    pub(crate) fn from_bytes(bytes: [u8; 8]) -> Self {
        let type_id_byte = bytes[0];
        let segment = (type_id_byte >> 6) & 0x3;
        let opcode = Opcode::from_u8(type_id_byte & 0xF);
        assert!(
            segment == 0,
            "non-zero segment not yet supported: {segment}"
        );
        assert_eq!(opcode, Opcode::Trampoline, "expected Trampoline opcode");

        Self {
            segment,
            next: StepId::new(u16::from_le_bytes([bytes[2], bytes[3]])),
        }
    }

    /// Encode to 8-byte bytecode.
    ///
    /// Header byte layout: `segment(2) | node_kind(2) | opcode(4)`
    pub fn to_bytes(&self) -> [u8; 8] {
        let mut bytes = [0u8; 8];
        // node_kind = 0 for Trampoline
        bytes[0] = (self.segment << 6) | (Opcode::Trampoline as u8);
        // bytes[1] is padding
        bytes[2..4].copy_from_slice(&self.next.get().to_le_bytes());
        // bytes[4..8] are reserved/padding
        bytes
    }

    pub fn next(&self) -> StepId {
        self.next
    }
}

/// Select the smallest Match variant that fits the given payload.
pub fn select_match_opcode(slots_needed: usize) -> Option<Opcode> {
    if slots_needed == 0 {
        return Some(Opcode::Match8);
    }
    match slots_needed {
        1..=4 => Some(Opcode::Match16),
        5..=8 => Some(Opcode::Match24),
        9..=12 => Some(Opcode::Match32),
        13..=20 => Some(Opcode::Match48),
        21..=28 => Some(Opcode::Match64),
        _ => None, // Too large, must split
    }
}

/// Pad a size to the next multiple of SECTION_ALIGN (64 bytes).
#[inline]
pub fn align_to_section(size: usize) -> usize {
    (size + SECTION_ALIGN - 1) & !(SECTION_ALIGN - 1)
}