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