Skip to main content

ruau_bytecode/
types.rs

1//! Structured representation of one serialized Luau bytecode chunk.
2
3use serde::{Deserialize, Serialize};
4
5use crate::opcodes::{CaptureType, FeedbackType, Opcode};
6
7/// One decoded bytecode blob.
8#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
9#[serde(tag = "kind", rename_all = "camelCase")]
10pub enum BytecodeChunk {
11    /// Valid bytecode chunk.
12    Valid {
13        /// Serialized bytecode version.
14        bytecode_version: u8,
15        /// Serialized type-encoding version.
16        type_version: u8,
17        /// String table in wire order. Entry ids are one-based; id zero is empty.
18        strings: Vec<Vec<u8>>,
19        /// Userdata type-name mappings in wire order.
20        userdata_type_mappings: Vec<UserdataTypeMapping>,
21        /// Protos in wire order.
22        protos: Vec<Proto>,
23        /// Main proto id.
24        main_proto: u32,
25    },
26    /// Non-throwing upstream compile error bytecode.
27    Error {
28        /// Raw error message bytes after the leading zero marker.
29        message: Vec<u8>,
30    },
31}
32
33/// Userdata type-name remapping entry.
34#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
35#[serde(rename_all = "camelCase")]
36pub struct UserdataTypeMapping {
37    /// Type tag index.
38    pub type_index: u8,
39    /// One-based string-table id.
40    pub name: u32,
41}
42
43/// One decoded proto.
44#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
45#[serde(rename_all = "camelCase")]
46pub struct Proto {
47    /// Maximum stack size.
48    pub max_stack_size: u8,
49    /// Fixed parameter count.
50    pub num_params: u8,
51    /// Upvalue count.
52    pub num_upvalues: u8,
53    /// Vararg flag.
54    pub is_vararg: u8,
55    /// Proto flags.
56    pub flags: u8,
57    /// Type-info section.
58    pub type_info: TypeInfo,
59    /// Decoded instructions in word order.
60    pub code: Vec<Instruction>,
61    /// Constant table.
62    pub constants: Vec<Constant>,
63    /// Child proto ids.
64    pub child_protos: Vec<u32>,
65    /// Source line where this proto is defined.
66    pub line_defined: u32,
67    /// One-based string-table id of debug name, or zero.
68    pub debug_name: u32,
69    /// Encoded line-info block.
70    pub line_info: Option<LineInfo>,
71    /// Local and upvalue debug info.
72    pub debug_info: Option<DebugInfo>,
73    /// Feedback slots, present in version 11 and extended-layout chunks.
74    #[serde(default, skip_serializing_if = "Vec::is_empty")]
75    pub feedback_slots: Vec<FeedbackSlot>,
76    /// Estimated execution cost for an inlinable extended-layout proto.
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub cost: Option<u64>,
79}
80
81/// Raw type-info payload with decoded counts.
82#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
83#[serde(rename_all = "camelCase")]
84pub struct TypeInfo {
85    /// Encoded type-info payload bytes.
86    pub raw: Vec<u8>,
87}
88
89/// One instruction header and its optional static AUX word.
90///
91/// Plain-old-data on purpose: the dispatch loop fetches instructions by copy,
92/// so the type must never grow a heap allocation. Every aux-bearing Luau
93/// opcode carries exactly one AUX word (`Opcode::instruction_len`).
94///
95/// # Invariant
96///
97/// `opcode`, `a`, `b`, `c`, `d`, and `e` are pre-decoded views of `header`;
98/// every constructor ([`Instruction::from_words`], [`Instruction::abc`],
99/// [`Instruction::abc_with_aux`], [`Instruction::ad`]) derives them together
100/// so they always agree. The fields stay public (and mutable) for the VM
101/// dispatch loop, so direct mutation of one side can break the invariant —
102/// but never silently: [`crate::validate_chunk`] reports the mismatch and
103/// [`crate::encode_chunk`] refuses to encode it. To change an instruction,
104/// build a replacement through a constructor instead of mutating fields.
105#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
106#[serde(rename_all = "camelCase")]
107pub struct Instruction {
108    /// Header word.
109    pub header: u32,
110    /// Decoded opcode.
111    pub opcode: Opcode,
112    /// ABC A operand.
113    pub a: u8,
114    /// ABC B operand.
115    pub b: u8,
116    /// ABC C operand.
117    pub c: u8,
118    /// AD D operand.
119    pub d: i16,
120    /// E operand.
121    pub e: i32,
122    /// The static AUX word following the header, when the opcode has one.
123    /// Serialized as a 0/1-element array to keep the committed fixture shape.
124    #[serde(with = "aux_serde")]
125    pub aux: Option<u32>,
126}
127
128/// Serializes the optional AUX word as the 0/1-element array the committed
129/// fixture corpus already uses.
130mod aux_serde {
131    use serde::{Deserialize, Deserializer, Serialize, Serializer};
132
133    pub fn serialize<S: Serializer>(aux: &Option<u32>, serializer: S) -> Result<S::Ok, S::Error> {
134        let words: &[u32] = match aux {
135            Some(word) => std::slice::from_ref(word),
136            None => &[],
137        };
138        words.serialize(serializer)
139    }
140
141    pub fn deserialize<'de, D: Deserializer<'de>>(
142        deserializer: D,
143    ) -> Result<Option<u32>, D::Error> {
144        let words = Vec::<u32>::deserialize(deserializer)?;
145        match words.as_slice() {
146            [] => Ok(None),
147            [word] => Ok(Some(*word)),
148            _ => Err(serde::de::Error::custom(
149                "an instruction has at most one AUX word",
150            )),
151        }
152    }
153}
154
155impl Instruction {
156    /// Creates an instruction from its raw words.
157    #[must_use]
158    pub fn from_words(header: u32, aux: Option<u32>) -> Option<Self> {
159        let opcode = Opcode::from_byte((header & 0xff) as u8)?;
160        Some(Self {
161            header,
162            opcode,
163            a: ((header >> 8) & 0xff) as u8,
164            b: ((header >> 16) & 0xff) as u8,
165            c: ((header >> 24) & 0xff) as u8,
166            d: (header >> 16) as u16 as i16,
167            e: (header as i32) >> 8,
168            aux,
169        })
170    }
171
172    /// Encodes ABC instruction fields.
173    #[must_use]
174    pub fn abc(opcode: Opcode, a: u8, b: u8, c: u8) -> Self {
175        let header =
176            opcode.byte() as u32 | ((a as u32) << 8) | ((b as u32) << 16) | ((c as u32) << 24);
177        Self::from_words(header, None).expect("opcode bytes from the Opcode enum always decode")
178    }
179
180    /// Encodes ABC instruction fields followed by an optional static AUX word.
181    #[must_use]
182    pub fn abc_with_aux(opcode: Opcode, a: u8, b: u8, c: u8, aux: Option<u32>) -> Self {
183        let header =
184            opcode.byte() as u32 | ((a as u32) << 8) | ((b as u32) << 16) | ((c as u32) << 24);
185        Self::from_words(header, aux).expect("opcode bytes from the Opcode enum always decode")
186    }
187
188    /// Encodes AD instruction fields.
189    #[must_use]
190    pub fn ad(opcode: Opcode, a: u8, d: i16) -> Self {
191        let header = opcode.byte() as u32 | ((a as u32) << 8) | ((d as u16 as u32) << 16);
192        Self::from_words(header, None).expect("opcode bytes from the Opcode enum always decode")
193    }
194
195    /// Returns the encoded jump offset in instruction words, if this opcode jumps.
196    ///
197    /// Luau jump offsets are relative to the word after the instruction header.
198    /// For instructions with AUX words, the AUX words are part of the encoded
199    /// offset span; for example, comparison jumps use `D = 1` for the next
200    /// decoded instruction because their AUX word occupies the intervening word.
201    #[must_use]
202    pub fn jump_offset_words(&self) -> Option<i32> {
203        match self.opcode {
204            Opcode::Jump
205            | Opcode::JumpBack
206            | Opcode::JumpIf
207            | Opcode::JumpIfNot
208            | Opcode::JumpIfEq
209            | Opcode::JumpIfLe
210            | Opcode::JumpIfLt
211            | Opcode::JumpIfNotEq
212            | Opcode::JumpIfNotLe
213            | Opcode::JumpIfNotLt
214            | Opcode::ForNPrep
215            | Opcode::ForNLoop
216            | Opcode::ForGLoop
217            | Opcode::ForGPrepInext
218            | Opcode::ForGPrepNext
219            | Opcode::ForGPrep
220            | Opcode::JumpXEqKNil
221            | Opcode::JumpXEqKB
222            | Opcode::JumpXEqKN
223            | Opcode::JumpXEqKS
224            | Opcode::CmpProto => Some(i32::from(self.d)),
225            Opcode::JumpX => Some(self.e),
226            Opcode::LoadB
227            | Opcode::FastCall
228            | Opcode::FastCall1
229            | Opcode::FastCall2
230            | Opcode::FastCall2K
231            | Opcode::FastCall3 => Some(i32::from(self.c)),
232            _ => None,
233        }
234    }
235
236    /// Resolves this instruction's jump target as an absolute instruction-word offset.
237    #[must_use]
238    pub fn jump_target_word(&self, instruction_word: u32) -> Option<i32> {
239        Some(instruction_word as i32 + 1 + self.jump_offset_words()?)
240    }
241
242    /// Returns the `CAPTURE` operand kind, if this is a valid capture instruction.
243    #[must_use]
244    pub fn capture_type(&self) -> Option<CaptureType> {
245        if self.opcode == Opcode::Capture {
246            CaptureType::from_byte(self.a)
247        } else {
248            None
249        }
250    }
251
252    /// Returns the `CAPTURE` source register or upvalue index.
253    #[must_use]
254    pub fn capture_source(&self) -> Option<u8> {
255        self.capture_type().map(|_| self.b)
256    }
257
258    /// Returns the number of instruction words this instruction occupies,
259    /// counting its header word plus any AUX words.
260    #[must_use]
261    pub fn word_len(&self) -> u32 {
262        1 + u32::from(self.aux.is_some())
263    }
264
265    /// Returns `true` when the pre-decoded operand fields match a fresh
266    /// re-decode of `header`, i.e. the instruction upholds the type's
267    /// header/field invariant.
268    #[must_use]
269    pub fn is_header_consistent(&self) -> bool {
270        Self::from_words(self.header, self.aux).is_some_and(|decoded| decoded == *self)
271    }
272}
273
274/// Returns the total number of instruction words spanned by `code`.
275#[must_use]
276pub fn code_word_count(code: &[Instruction]) -> u32 {
277    code.iter().map(Instruction::word_len).sum()
278}
279
280/// Returns the absolute instruction-word offset for each decoded instruction.
281#[must_use]
282pub fn instruction_word_offsets(code: &[Instruction]) -> Vec<u32> {
283    let mut next = 0u32;
284    code.iter()
285        .map(|instruction| {
286            let current = next;
287            next += instruction.word_len();
288            current
289        })
290        .collect()
291}
292
293/// Resolves one decoded instruction's jump target to another decoded instruction index.
294#[must_use]
295pub fn jump_target_instruction_index(
296    code: &[Instruction],
297    instruction_index: usize,
298) -> Option<usize> {
299    let offsets = instruction_word_offsets(code);
300    let instruction = code.get(instruction_index)?;
301    let source_word = *offsets.get(instruction_index)?;
302    let target = instruction.jump_target_word(source_word)?;
303    offsets.iter().position(|word| *word as i32 == target)
304}
305
306/// Constant table entry.
307#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
308#[serde(tag = "kind", rename_all = "camelCase")]
309pub enum Constant {
310    /// Nil.
311    Nil,
312    /// Boolean.
313    Boolean {
314        /// Boolean value.
315        value: bool,
316    },
317    /// Floating-point number, stored by exact bits.
318    Number {
319        /// Little-endian f64 bit pattern interpreted numerically by upstream.
320        bits: u64,
321    },
322    /// One-based string-table id.
323    String {
324        /// String table id.
325        string: u32,
326    },
327    /// Packed import id.
328    Import {
329        /// Import id.
330        import_id: u32,
331    },
332    /// Table shape.
333    Table {
334        /// Constant ids used as keys.
335        keys: Vec<u32>,
336    },
337    /// Closure proto reference.
338    Closure {
339        /// Proto id.
340        proto: u32,
341    },
342    /// Vector, stored by exact f32 bits.
343    Vector {
344        /// Four f32 bit patterns.
345        bits: [u32; 4],
346    },
347    /// Double-precision vector, stored by exact f64 bits.
348    VectorDouble {
349        /// Four f64 bit patterns.
350        bits: [u64; 4],
351    },
352    /// Table shape with constant payloads.
353    TableWithConstants {
354        /// Key/value entries.
355        entries: Vec<TableEntry>,
356    },
357    /// 64-bit integer.
358    Integer {
359        /// Integer value.
360        value: i64,
361    },
362    /// Class shape.
363    ClassShape {
364        /// Shape payload.
365        shape: ClassShape,
366    },
367}
368
369/// One table shape entry with a pre-filled constant.
370#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
371#[serde(rename_all = "camelCase")]
372pub struct TableEntry {
373    /// Key constant id.
374    pub key: u32,
375    /// Value constant id, or -1 sentinel.
376    pub value: i32,
377}
378
379/// Class-shape constant payload.
380#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
381#[serde(rename_all = "camelCase")]
382pub struct ClassShape {
383    /// Class-name string id.
384    pub class_name: u32,
385    /// Property-name string ids.
386    pub property_names: Vec<u32>,
387    /// Method-name string ids.
388    pub method_names: Vec<u32>,
389}
390
391/// Wire-preserving line info.
392#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
393#[serde(rename_all = "camelCase")]
394pub struct LineInfo {
395    /// Log2 of encoded line span.
396    pub log2_span: u8,
397    /// Per-instruction unsigned delta differences.
398    pub delta_bytes: Vec<u8>,
399    /// Per-span signed baseline differences.
400    pub baseline_deltas: Vec<i32>,
401}
402
403impl LineInfo {
404    /// Encodes absolute source lines using upstream's line-info span packing.
405    #[must_use]
406    pub(crate) fn from_line_numbers(lines: &[i32]) -> Option<Self> {
407        if lines.is_empty() {
408            return None;
409        }
410
411        let mut span = 1usize << 24;
412        let mut offset = 0usize;
413        while offset < lines.len() {
414            let mut next = offset;
415            let mut min = lines[offset];
416            let mut max = lines[offset];
417
418            while next < lines.len() && next < offset + span {
419                min = min.min(lines[next]);
420                max = max.max(lines[next]);
421                if max - min > 255 {
422                    break;
423                }
424                next += 1;
425            }
426
427            if next < lines.len() && next - offset < span {
428                span = 1usize << line_info_log2(next - offset);
429            }
430
431            offset += span;
432        }
433
434        let log2_span = line_info_log2(span) as u8;
435        let baseline_size = (lines.len() - 1) / span + 1;
436        let mut baselines = Vec::with_capacity(baseline_size);
437        for chunk in lines.chunks(span) {
438            baselines.push(*chunk.iter().min().expect("non-empty chunk"));
439        }
440
441        let mut delta_bytes = Vec::with_capacity(lines.len());
442        let mut last_offset = 0u8;
443        for (index, line) in lines.iter().enumerate() {
444            let baseline = baselines[index >> usize::from(log2_span)];
445            let delta = *line - baseline;
446            debug_assert!((0..=255).contains(&delta));
447            let delta = delta as u8;
448            delta_bytes.push(delta.wrapping_sub(last_offset));
449            last_offset = delta;
450        }
451
452        let mut baseline_deltas = Vec::with_capacity(baseline_size);
453        let mut last_line = 0;
454        for baseline in baselines {
455            baseline_deltas.push(baseline - last_line);
456            last_line = baseline;
457        }
458
459        Some(Self {
460            log2_span,
461            delta_bytes,
462            baseline_deltas,
463        })
464    }
465
466    /// Decodes wire line-info payloads into absolute source lines.
467    #[must_use]
468    pub fn to_line_numbers(&self) -> Option<Vec<i32>> {
469        let mut baselines = Vec::with_capacity(self.baseline_deltas.len());
470        let mut baseline = 0i32;
471        for delta in &self.baseline_deltas {
472            // Line numbers wrap rather than panic on a hostile delta stream.
473            baseline = baseline.wrapping_add(*delta);
474            baselines.push(baseline);
475        }
476
477        let mut lines = Vec::with_capacity(self.delta_bytes.len());
478        let mut last_offset = 0u8;
479        for (index, byte) in self.delta_bytes.iter().enumerate() {
480            let baseline = *baselines.get(index >> usize::from(self.log2_span))?;
481            let offset = last_offset.wrapping_add(*byte);
482            lines.push(baseline.wrapping_add(i32::from(offset)));
483            last_offset = offset;
484        }
485
486        Some(lines)
487    }
488}
489
490fn line_info_log2(value: usize) -> usize {
491    debug_assert!(value > 0);
492
493    let mut result = 0;
494    while value >= (2usize << result) {
495        result += 1;
496    }
497    result
498}
499
500/// Debug local and upvalue names.
501#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
502#[serde(rename_all = "camelCase")]
503pub struct DebugInfo {
504    /// Local debug entries.
505    pub locals: Vec<DebugLocal>,
506    /// One-based string-table ids for upvalue names.
507    pub upvalues: Vec<u32>,
508}
509
510/// One local debug-info entry.
511#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
512#[serde(rename_all = "camelCase")]
513pub struct DebugLocal {
514    /// One-based string-table id.
515    pub name: u32,
516    /// Inclusive start pc.
517    pub start_pc: u32,
518    /// Exclusive end pc.
519    pub end_pc: u32,
520    /// Register.
521    pub register: u8,
522}
523
524/// Feedback slot metadata.
525#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
526#[serde(rename_all = "camelCase")]
527pub struct FeedbackSlot {
528    /// Slot type.
529    pub kind: FeedbackType,
530    /// Instruction pc associated with the slot.
531    pub pc: u32,
532}
533
534#[cfg(test)]
535mod tests {
536    use super::{
537        CaptureType, Instruction, LineInfo, Opcode, instruction_word_offsets,
538        jump_target_instruction_index,
539    };
540
541    #[test]
542    fn jump_targets_are_word_relative() {
543        let jump_next = Instruction::ad(Opcode::Jump, 0, 0);
544        assert_eq!(jump_next.jump_offset_words(), Some(0));
545        assert_eq!(jump_next.jump_target_word(10), Some(11));
546
547        let jump_back = Instruction::ad(Opcode::JumpBack, 0, -3);
548        assert_eq!(jump_back.jump_target_word(10), Some(8));
549
550        let jump_x = Instruction::from_words(
551            Opcode::JumpX.byte() as u32 | ((-5_i32 as u32 & 0x00ff_ffff) << 8),
552            None,
553        )
554        .expect("jumpx");
555        assert_eq!(jump_x.jump_offset_words(), Some(-5));
556        assert_eq!(jump_x.jump_target_word(10), Some(6));
557    }
558
559    #[test]
560    fn jump_targets_count_aux_words() {
561        let compare = Instruction::abc_with_aux(Opcode::JumpIfEq, 0, 1, 0, Some(0));
562        assert_eq!(compare.jump_offset_words(), Some(1));
563        assert_eq!(compare.jump_target_word(4), Some(6));
564
565        let code = vec![
566            Instruction::ad(Opcode::LoadN, 0, 1),
567            compare,
568            Instruction::ad(Opcode::LoadN, 1, 2),
569            Instruction::abc(Opcode::Return, 0, 1, 0),
570        ];
571        assert_eq!(instruction_word_offsets(&code), vec![0, 1, 3, 4]);
572        assert_eq!(jump_target_instruction_index(&code, 1), Some(2));
573
574        let compare_to_return = Instruction::abc_with_aux(Opcode::JumpIfEq, 0, 2, 0, Some(0));
575        let code = vec![
576            Instruction::ad(Opcode::LoadN, 0, 1),
577            compare_to_return,
578            Instruction::ad(Opcode::LoadN, 1, 2),
579            Instruction::abc(Opcode::Return, 0, 1, 0),
580        ];
581        assert_eq!(jump_target_instruction_index(&code, 1), Some(3));
582    }
583
584    #[test]
585    fn short_jump_operands_are_exposed() {
586        let loadb = Instruction::abc(Opcode::LoadB, 0, 1, 2);
587        assert_eq!(loadb.jump_offset_words(), Some(2));
588        assert_eq!(loadb.jump_target_word(7), Some(10));
589
590        let fastcall = Instruction::abc(Opcode::FastCall2K, 18, 1, 3);
591        assert_eq!(fastcall.jump_offset_words(), Some(3));
592        assert_eq!(fastcall.jump_target_word(7), Some(11));
593
594        let not_a_jump = Instruction::ad(Opcode::LoadN, 0, 5);
595        assert_eq!(not_a_jump.jump_offset_words(), None);
596        assert_eq!(not_a_jump.jump_target_word(0), None);
597    }
598
599    #[test]
600    fn capture_operands_are_exposed() {
601        let by_value = Instruction::abc(Opcode::Capture, CaptureType::Val as u8, 3, 0);
602        assert_eq!(by_value.capture_type(), Some(CaptureType::Val));
603        assert_eq!(by_value.capture_source(), Some(3));
604
605        let by_reference = Instruction::abc(Opcode::Capture, CaptureType::Ref as u8, 4, 0);
606        assert_eq!(by_reference.capture_type(), Some(CaptureType::Ref));
607        assert_eq!(by_reference.capture_source(), Some(4));
608
609        let upvalue = Instruction::abc(Opcode::Capture, CaptureType::Upval as u8, 1, 0);
610        assert_eq!(upvalue.capture_type(), Some(CaptureType::Upval));
611        assert_eq!(upvalue.capture_source(), Some(1));
612
613        let invalid = Instruction::abc(Opcode::Capture, 99, 1, 0);
614        assert_eq!(invalid.capture_type(), None);
615        assert_eq!(invalid.capture_source(), None);
616
617        let not_capture = Instruction::ad(Opcode::LoadN, 0, 5);
618        assert_eq!(not_capture.capture_type(), None);
619        assert_eq!(not_capture.capture_source(), None);
620    }
621
622    #[test]
623    fn line_info_uses_large_span_when_deltas_fit() {
624        let line_info = LineInfo::from_line_numbers(&[10, 10, 20]).expect("line info");
625        assert_eq!(line_info.log2_span, 24);
626        assert_eq!(line_info.delta_bytes, vec![0, 0, 10]);
627        assert_eq!(line_info.baseline_deltas, vec![10]);
628        assert_eq!(
629            line_info.to_line_numbers().expect("line numbers"),
630            vec![10, 10, 20]
631        );
632    }
633
634    #[test]
635    fn line_info_shrinks_span_before_8_bit_delta_overflows() {
636        let lines = [1, 2, 300, 301, 302];
637        let line_info = LineInfo::from_line_numbers(&lines).expect("line info");
638
639        assert_eq!(line_info.log2_span, 1);
640        assert_eq!(line_info.delta_bytes, vec![0, 1, 255, 1, 255]);
641        assert_eq!(line_info.baseline_deltas, vec![1, 299, 2]);
642        assert_eq!(line_info.to_line_numbers().expect("line numbers"), lines);
643    }
644}