Skip to main content

ruau_bytecode/
builder.rs

1//! Small order-preserving chunk builder used by the first compiler slice.
2
3use std::collections::HashMap;
4
5use foldhash::fast::FixedState;
6
7use crate::{
8    BytecodeChunk, ClassShape, Constant, DebugInfo, DebugLocal, Instruction, LineInfo, Proto,
9    TableEntry, TypeInfo, codec::write_varint, instruction_word_offsets, opcodes::Opcode,
10};
11
12/// Version emitted by the pinned upstream compiler without bytecode flags.
13pub const DEFAULT_VERSION: u8 = 9;
14/// Highest bytecode version accepted only by repository-owned fixture tooling.
15#[doc(hidden)]
16pub const FIXTURE_TOOLING_MAX_VERSION: u8 = 13;
17/// Work-in-progress class bytecode version accepted only by fixture tooling.
18#[doc(hidden)]
19pub const FIXTURE_TOOLING_CLASS_VERSION: u8 = 100;
20/// Type encoding version emitted by the pinned upstream compiler.
21pub const DEFAULT_TYPE_VERSION: u8 = 3;
22
23#[derive(Clone, Copy)]
24struct TypedLocal {
25    type_tag: u8,
26    reg: u8,
27    startpc: u32,
28    endpc: u32,
29}
30
31#[derive(Default)]
32pub struct ProtoWork {
33    child_protos: Vec<u32>,
34    constants: Vec<Constant>,
35    constant_ids: HashMap<Constant, u32, FixedState>,
36    code: Vec<Instruction>,
37    code_word_offsets: Vec<u32>,
38    next_code_word_offset: u32,
39    code_lines: Vec<i32>,
40    feedback_slots: Vec<crate::FeedbackSlot>,
41    max_stack_size: u8,
42    current_line: i32,
43    implicit_return_line_delta: u8,
44    implicit_return_line_base: Option<i32>,
45    proto_flags: u8,
46    implicit_prepvarargs: bool,
47    function_type_info: Vec<u8>,
48    typed_upvalues: Vec<u8>,
49    typed_locals: Vec<TypedLocal>,
50    debug_locals: Vec<DebugLocal>,
51    debug_upvalues: Vec<u32>,
52}
53
54pub struct ProtoMetadata {
55    pub(crate) num_params: u8,
56    pub(crate) num_upvalues: u8,
57    pub(crate) is_vararg: bool,
58    pub(crate) flags: u8,
59    pub(crate) line_defined: u32,
60    pub(crate) debug_name: u32,
61    pub(crate) debug_level: u8,
62}
63
64impl ProtoWork {
65    fn new() -> Self {
66        Self {
67            current_line: 1,
68            proto_flags: 2,
69            implicit_prepvarargs: true,
70            ..Self::default()
71        }
72    }
73
74    fn new_function() -> Self {
75        Self {
76            current_line: 1,
77            proto_flags: 2,
78            ..Self::default()
79        }
80    }
81
82    pub(crate) fn fold_jumps(&mut self) {
83        let offsets = instruction_word_offsets(&self.code);
84
85        for index in 0..self.code.len() {
86            if !is_foldable_jump_d(self.code[index].opcode) {
87                continue;
88            }
89
90            let source_word = offsets[index];
91            let Some(mut target_word) = self.code[index].jump_target_word(source_word) else {
92                continue;
93            };
94            if target_word < 0 {
95                continue;
96            }
97
98            let Some(mut target_index) = instruction_index_for_word(&offsets, target_word as u32)
99            else {
100                continue;
101            };
102
103            while self.code[target_index].opcode == Opcode::Jump && self.code[target_index].d >= 0 {
104                let Some(next_target) =
105                    self.code[target_index].jump_target_word(offsets[target_index])
106                else {
107                    break;
108                };
109                if next_target < 0 {
110                    break;
111                }
112                let Some(next_index) = instruction_index_for_word(&offsets, next_target as u32)
113                else {
114                    break;
115                };
116                target_word = next_target;
117                target_index = next_index;
118            }
119            if self.code[index].opcode != Opcode::Jump
120                && self.code[target_index].opcode == Opcode::Return
121            {
122                while target_index + 1 < self.code.len()
123                    && self.code[target_index + 1] == self.code[target_index]
124                {
125                    target_index += 1;
126                    target_word = offsets[target_index] as i32;
127                }
128            }
129
130            let offset = target_word - source_word as i32 - 1;
131            if self.code[index].opcode == Opcode::Jump
132                && self.code[target_index].opcode == Opcode::Return
133            {
134                self.code[index] = self.code[target_index];
135            } else if let Ok(offset) = i16::try_from(offset) {
136                patch_jump_d_instruction(&mut self.code[index], offset);
137            }
138        }
139    }
140
141    pub(crate) fn into_proto(self, metadata: &ProtoMetadata) -> Proto {
142        let line_info = if metadata.debug_level >= 1 {
143            LineInfo::from_line_numbers(&self.code_lines)
144        } else {
145            None
146        };
147        let debug_info = (metadata.debug_level >= 2
148            && (!self.debug_locals.is_empty() || !self.debug_upvalues.is_empty()))
149        .then_some(DebugInfo {
150            locals: self.debug_locals,
151            upvalues: self.debug_upvalues,
152        });
153
154        Proto {
155            max_stack_size: self.max_stack_size,
156            num_params: metadata.num_params,
157            num_upvalues: metadata.num_upvalues,
158            is_vararg: u8::from(metadata.is_vararg),
159            flags: metadata.flags,
160            type_info: TypeInfo {
161                raw: type_info_payload(
162                    &self.function_type_info,
163                    &self.typed_upvalues,
164                    &self.typed_locals,
165                ),
166            },
167            code: self.code,
168            constants: self.constants,
169            child_protos: self.child_protos,
170            line_defined: metadata.line_defined,
171            debug_name: metadata.debug_name,
172            line_info,
173            debug_info,
174            feedback_slots: self.feedback_slots,
175            cost: None,
176        }
177    }
178}
179
180pub struct ChunkBuilder {
181    strings: Vec<Vec<u8>>,
182    string_ids: HashMap<Vec<u8>, u32, FixedState>,
183    protos: Vec<Proto>,
184    current: ProtoWork,
185    bytecode_version: u8,
186}
187
188impl ChunkBuilder {
189    pub(crate) fn new() -> Self {
190        Self {
191            bytecode_version: DEFAULT_VERSION,
192            current: ProtoWork::new(),
193            strings: Vec::new(),
194            string_ids: HashMap::with_hasher(FixedState::default()),
195            protos: Vec::new(),
196        }
197    }
198
199    pub(crate) fn begin_proto(&mut self) -> ProtoWork {
200        std::mem::replace(&mut self.current, ProtoWork::new_function())
201    }
202
203    pub(crate) fn end_proto(&mut self, previous: ProtoWork) -> ProtoWork {
204        std::mem::replace(&mut self.current, previous)
205    }
206
207    pub(crate) fn set_bytecode_version(&mut self, version: u8) {
208        self.bytecode_version = version;
209    }
210
211    pub(crate) fn set_max_stack_size(&mut self, value: u8) {
212        self.current.max_stack_size = self.current.max_stack_size.max(value);
213    }
214
215    pub(crate) fn set_proto_flags(&mut self, value: u8) {
216        self.current.proto_flags = value;
217    }
218
219    pub(crate) fn set_implicit_return_line_delta(&mut self, value: u8) {
220        self.current.implicit_return_line_delta = value;
221    }
222
223    pub(crate) fn set_implicit_return_line_base(&mut self, line: u32) {
224        self.current.implicit_return_line_base = Some(line as i32);
225    }
226
227    pub(crate) fn set_debug_line(&mut self, line: u32) {
228        self.current.current_line = line as i32;
229    }
230
231    pub(crate) fn add_number(&mut self, value: f64) -> u32 {
232        let bits = value.to_bits();
233        self.add_constant(Constant::Number { bits })
234    }
235
236    pub(crate) fn add_string(&mut self, value: &str) -> u32 {
237        let bytes = decode_ast_string_bytes(value);
238        if let Some(index) = self.string_ids.get(bytes.as_slice()) {
239            return *index;
240        }
241        self.strings.push(bytes);
242        let index = self.strings.len() as u32;
243        self.string_ids.insert(
244            self.strings.last().expect("string was just pushed").clone(),
245            index,
246        );
247        index
248    }
249
250    pub(crate) fn add_string_constant(&mut self, value: &str) -> u32 {
251        let string = self.add_string(value);
252        self.add_constant(Constant::String { string })
253    }
254
255    pub(crate) fn add_nil(&mut self) -> u32 {
256        self.add_constant(Constant::Nil)
257    }
258
259    pub(crate) fn add_boolean(&mut self, value: bool) -> u32 {
260        self.add_constant(Constant::Boolean { value })
261    }
262
263    pub(crate) fn add_vector_bits(&mut self, bits: [u32; 4]) -> u32 {
264        self.add_constant(Constant::Vector { bits })
265    }
266
267    pub(crate) fn add_integer(&mut self, value: i64) -> u32 {
268        self.add_constant(Constant::Integer { value })
269    }
270
271    pub(crate) fn add_import(&mut self, import_id: u32) -> u32 {
272        self.add_constant(Constant::Import { import_id })
273    }
274
275    pub(crate) fn add_table_shape(&mut self, keys: Vec<u32>) -> u32 {
276        self.add_constant(Constant::Table { keys })
277    }
278
279    pub(crate) fn add_table_with_constants(&mut self, entries: Vec<TableEntry>) -> u32 {
280        self.add_constant(Constant::TableWithConstants { entries })
281    }
282
283    pub(crate) fn add_class_shape(&mut self, shape: ClassShape) -> u32 {
284        self.add_constant(Constant::ClassShape { shape })
285    }
286
287    pub(crate) fn add_closure(&mut self, proto: u32) -> u32 {
288        self.add_constant(Constant::Closure { proto })
289    }
290
291    pub(crate) fn add_child_proto(&mut self, proto: u32) -> i16 {
292        if let Some(index) = self
293            .current
294            .child_protos
295            .iter()
296            .position(|existing| *existing == proto)
297        {
298            return index as i16;
299        }
300        let index = self.current.child_protos.len();
301        self.current.child_protos.push(proto);
302        index as i16
303    }
304
305    pub(crate) fn add_proto(&mut self, proto: Proto) -> u32 {
306        let id = self.protos.len() as u32;
307        self.protos.push(proto);
308        id
309    }
310
311    pub(crate) fn emit(&mut self, instruction: Instruction) -> usize {
312        let line = self.current.current_line;
313        self.emit_at_line(instruction, line)
314    }
315
316    pub(crate) fn emit_implicit_return(&mut self) -> usize {
317        self.emit_at_line(
318            Instruction::abc(Opcode::Return, 0, 1, 0),
319            self.implicit_return_line(),
320        )
321    }
322
323    pub(crate) fn patch_ad(&mut self, index: usize, opcode: Opcode, a: u8, d: i16) {
324        self.current.code[index] = Instruction::ad(opcode, a, d);
325    }
326
327    pub(crate) fn patch_ad_with_aux(
328        &mut self,
329        index: usize,
330        opcode: Opcode,
331        a: u8,
332        d: i16,
333        aux: Option<u32>,
334    ) {
335        let b = (d as u16 & 0xff) as u8;
336        let c = ((d as u16 >> 8) & 0xff) as u8;
337        self.current.code[index] = Instruction::abc_with_aux(opcode, a, b, c, aux);
338    }
339
340    pub(crate) fn patch_skip_c_to_current(&mut self, index: usize) -> bool {
341        let source = self.instruction_word_offset(index);
342        let target = self.current_word_offset();
343        let Some(offset) = target.checked_sub(source + 1) else {
344            return false;
345        };
346        let Ok(offset) = u8::try_from(offset) else {
347            return false;
348        };
349        let instruction = &self.current.code[index];
350        debug_assert!(matches!(
351            instruction.opcode,
352            Opcode::FastCall
353                | Opcode::FastCall1
354                | Opcode::FastCall2
355                | Opcode::FastCall2K
356                | Opcode::FastCall3
357        ));
358        self.current.code[index] = Instruction::abc_with_aux(
359            instruction.opcode,
360            instruction.a,
361            instruction.b,
362            offset,
363            instruction.aux,
364        );
365        true
366    }
367
368    pub(crate) fn current_word_offset(&self) -> u32 {
369        self.current.next_code_word_offset
370    }
371
372    pub(crate) fn current_type_info_pc(&self) -> u32 {
373        self.current_word_offset()
374            + u32::from(self.current.implicit_prepvarargs && self.needs_implicit_prepvarargs())
375    }
376
377    pub(crate) fn instruction_word_offset(&self, index: usize) -> u32 {
378        self.current.code_word_offsets[index]
379    }
380
381    pub(crate) fn push_local_type_info(&mut self, type_tag: u8, reg: u8, startpc: u32, endpc: u32) {
382        self.current.typed_locals.push(TypedLocal {
383            type_tag,
384            reg,
385            startpc,
386            endpc,
387        });
388    }
389
390    pub(crate) fn set_function_type_info(&mut self, type_info: Vec<u8>) {
391        self.current.function_type_info = type_info;
392    }
393
394    pub(crate) fn push_upvalue_type_info(&mut self, type_tag: u8) {
395        self.current.typed_upvalues.push(type_tag);
396    }
397
398    pub(crate) fn push_debug_local(&mut self, name: u32, start_pc: u32, end_pc: u32, register: u8) {
399        self.current.debug_locals.push(DebugLocal {
400            name,
401            start_pc,
402            end_pc,
403            register,
404        });
405    }
406
407    pub(crate) fn push_debug_upvalue(&mut self, name: u32) {
408        self.current.debug_upvalues.push(name);
409    }
410
411    pub(crate) fn current_code(&self) -> &[Instruction] {
412        &self.current.code
413    }
414
415    pub(crate) fn push_feedback_slot(&mut self, slot: crate::FeedbackSlot) -> u32 {
416        let index = self.current.feedback_slots.len() as u32;
417        self.current.feedback_slots.push(slot);
418        index
419    }
420
421    pub(crate) fn proto_flags(&self) -> u8 {
422        self.current.proto_flags
423    }
424
425    pub(crate) fn max_stack_size(&self) -> u8 {
426        self.current.max_stack_size
427    }
428
429    fn emit_at_line(&mut self, instruction: Instruction, line: i32) -> usize {
430        self.current
431            .code_lines
432            .extend(std::iter::repeat_n(line, instruction.word_len() as usize));
433        let index = self.current.code.len();
434        self.current
435            .code_word_offsets
436            .push(self.current.next_code_word_offset);
437        self.current.next_code_word_offset += instruction.word_len();
438        self.current.code.push(instruction);
439        index
440    }
441
442    fn implicit_return_line(&self) -> i32 {
443        self.current
444            .implicit_return_line_base
445            .or_else(|| self.current.code_lines.last().copied())
446            .unwrap_or(1)
447            .saturating_add(i32::from(self.current.implicit_return_line_delta))
448    }
449
450    fn needs_implicit_prepvarargs(&self) -> bool {
451        if !self.current.implicit_prepvarargs {
452            return false;
453        }
454        self.current
455            .code
456            .first()
457            .is_none_or(|instruction| instruction.opcode != Opcode::PrepVarargs)
458    }
459
460    pub(crate) fn finish(mut self, debug_level: u8, fold_jumps: bool) -> BytecodeChunk {
461        if self.needs_implicit_prepvarargs() {
462            self.current
463                .code
464                .insert(0, Instruction::abc(Opcode::PrepVarargs, 0, 0, 0));
465            self.current.code_lines.insert(0, 1);
466            for offset in &mut self.current.code_word_offsets {
467                *offset += 1;
468            }
469            self.current.code_word_offsets.insert(0, 0);
470            self.current.next_code_word_offset += 1;
471        }
472        let inserted_implicit_return = self.current.code.is_empty()
473            || self
474                .current
475                .code
476                .last()
477                .is_some_and(|instruction| instruction.opcode != Opcode::Return);
478        if inserted_implicit_return {
479            self.emit_implicit_return();
480        }
481        if fold_jumps {
482            self.current.fold_jumps();
483        }
484        let flags = self.current.proto_flags;
485        let current = std::mem::replace(&mut self.current, ProtoWork::new());
486        let proto = current.into_proto(&ProtoMetadata {
487            num_params: 0,
488            num_upvalues: 0,
489            is_vararg: true,
490            flags,
491            line_defined: 1,
492            debug_name: 0,
493            debug_level,
494        });
495        let main_proto = self.protos.len() as u32;
496        self.protos.push(proto);
497        BytecodeChunk::Valid {
498            bytecode_version: self.bytecode_version,
499            type_version: DEFAULT_TYPE_VERSION,
500            strings: std::mem::take(&mut self.strings),
501            userdata_type_mappings: Vec::new(),
502            protos: self.protos,
503            main_proto,
504        }
505    }
506
507    fn add_constant(&mut self, constant: Constant) -> u32 {
508        if let Some(index) = self.current.constant_ids.get(&constant) {
509            return *index;
510        }
511        let index = self.current.constants.len() as u32;
512        self.current.constants.push(constant.clone());
513        self.current.constant_ids.insert(constant, index);
514        index
515    }
516}
517
518fn instruction_index_for_word(offsets: &[u32], word: u32) -> Option<usize> {
519    offsets.binary_search(&word).ok()
520}
521
522fn is_foldable_jump_d(opcode: Opcode) -> bool {
523    matches!(
524        opcode,
525        Opcode::Jump
526            | Opcode::JumpBack
527            | Opcode::JumpIf
528            | Opcode::JumpIfNot
529            | Opcode::JumpIfEq
530            | Opcode::JumpIfLe
531            | Opcode::JumpIfLt
532            | Opcode::JumpIfNotEq
533            | Opcode::JumpIfNotLe
534            | Opcode::JumpIfNotLt
535            | Opcode::ForNPrep
536            | Opcode::ForNLoop
537            | Opcode::ForGLoop
538            | Opcode::ForGPrepInext
539            | Opcode::ForGPrepNext
540            | Opcode::ForGPrep
541            | Opcode::JumpXEqKNil
542            | Opcode::JumpXEqKB
543            | Opcode::JumpXEqKN
544            | Opcode::JumpXEqKS
545            | Opcode::CmpProto
546    )
547}
548
549fn patch_jump_d_instruction(instruction: &mut Instruction, offset: i16) {
550    if instruction.aux.is_none() {
551        *instruction = Instruction::ad(instruction.opcode, instruction.a, offset);
552    } else {
553        *instruction = Instruction::abc_with_aux(
554            instruction.opcode,
555            instruction.a,
556            (offset as u16 & 0xff) as u8,
557            ((offset as u16 >> 8) & 0xff) as u8,
558            instruction.aux,
559        );
560    }
561}
562
563fn type_info_payload(
564    function_type_info: &[u8],
565    typed_upvalues: &[u8],
566    typed_locals: &[TypedLocal],
567) -> Vec<u8> {
568    if function_type_info.is_empty() && typed_upvalues.is_empty() && typed_locals.is_empty() {
569        return Vec::new();
570    }
571
572    let mut bytes = Vec::new();
573    write_varint(&mut bytes, function_type_info.len() as u64);
574    write_varint(&mut bytes, typed_upvalues.len() as u64);
575    write_varint(&mut bytes, typed_locals.len() as u64);
576    bytes.extend_from_slice(function_type_info);
577    bytes.extend_from_slice(typed_upvalues);
578    for local in typed_locals {
579        bytes.push(local.type_tag);
580        bytes.push(local.reg);
581        write_varint(&mut bytes, u64::from(local.startpc));
582        write_varint(
583            &mut bytes,
584            u64::from(local.endpc.saturating_sub(local.startpc)),
585        );
586    }
587    bytes
588}
589
590/// Decodes the AST's byte-preserving string encoding back to the raw Luau string bytes a
591/// constant must hold. Luau strings are byte strings, but the AST stores them in a Rust `String`
592/// (ruau-syntax `ast_string_from_bytes`): valid UTF-8 stays intact, while each invalid byte is the
593/// marker `U+FFFF` followed by `"ff"` and the byte's two hex digits. Storing `value.as_bytes()`
594/// directly would leak that marker form into the constant pool — e.g. `"\255"` became the seven
595/// bytes of `U+FFFF` plus `"ffff"` instead of the single byte `0xFF`.
596fn decode_ast_string_bytes(value: &str) -> Vec<u8> {
597    let mut bytes = Vec::with_capacity(value.len());
598    let mut chars = value.chars();
599    while let Some(ch) = chars.next() {
600        if ch == '\u{ffff}' {
601            // An exact marker is followed by "ff" then the original byte's two hex digits.
602            // A genuine U+FFFF without that suffix remains ordinary UTF-8.
603            let tail: String = chars.clone().take(4).collect();
604            if let Some(byte) = tail
605                .strip_prefix("ff")
606                .filter(|hex| hex.len() == 2)
607                .and_then(|hex| u8::from_str_radix(hex, 16).ok())
608            {
609                chars.by_ref().take(4).for_each(drop);
610                bytes.push(byte);
611                continue;
612            }
613        }
614        let mut encoded = [0; 4];
615        bytes.extend_from_slice(ch.encode_utf8(&mut encoded).as_bytes());
616    }
617    bytes
618}
619
620#[cfg(test)]
621mod tests {
622    use super::{ChunkBuilder, ProtoWork, decode_ast_string_bytes};
623    use crate::{BytecodeChunk, Constant, Instruction, TableEntry, opcodes::Opcode};
624
625    #[test]
626    fn preserves_constant_and_child_proto_insertion_order() {
627        let mut builder = ChunkBuilder::new();
628
629        let string = builder.add_string_constant("key");
630        assert_eq!(builder.add_string_constant("key"), string);
631
632        let import = builder.add_import(0x0102_0304);
633        assert_eq!(builder.add_import(0x0102_0304), import);
634
635        let table = builder.add_table_shape(vec![string]);
636        assert_eq!(builder.add_table_shape(vec![string]), table);
637
638        let table_with_constants = builder.add_table_with_constants(vec![TableEntry {
639            key: string,
640            value: import as i32,
641        }]);
642        assert_eq!(
643            builder.add_table_with_constants(vec![TableEntry {
644                key: string,
645                value: import as i32
646            }]),
647            table_with_constants
648        );
649
650        let closure = builder.add_closure(7);
651        assert_eq!(builder.add_closure(7), closure);
652
653        assert_eq!(builder.add_child_proto(7), 0);
654        assert_eq!(builder.add_child_proto(7), 0);
655        assert_eq!(builder.add_child_proto(9), 1);
656        builder.emit(Instruction::abc(Opcode::Return, 0, 1, 0));
657
658        let BytecodeChunk::Valid {
659            strings, protos, ..
660        } = builder.finish(0, false)
661        else {
662            panic!("expected valid chunk");
663        };
664
665        assert_eq!(strings, vec![b"key".to_vec()]);
666        assert_eq!(
667            protos[0].constants,
668            vec![
669                Constant::String { string: 1 },
670                Constant::Import {
671                    import_id: 0x0102_0304
672                },
673                Constant::Table { keys: vec![string] },
674                Constant::TableWithConstants {
675                    entries: vec![TableEntry {
676                        key: string,
677                        value: import as i32
678                    }],
679                },
680                Constant::Closure { proto: 7 },
681            ]
682        );
683        assert_eq!(protos[0].child_protos, vec![7, 9]);
684    }
685
686    #[test]
687    fn decodes_valid_utf8_and_invalid_byte_markers() {
688        assert_eq!(decode_ast_string_bytes("eĆ©šŸ˜€"), "eĆ©šŸ˜€".as_bytes());
689        assert_eq!(
690            decode_ast_string_bytes("\u{ffff}\u{10000}"),
691            "\u{ffff}\u{10000}".as_bytes()
692        );
693        assert_eq!(decode_ast_string_bytes("a\u{ffff}ffc8b"), b"a\xc8b");
694    }
695
696    #[test]
697    fn patches_fastcall_skip_c_by_instruction_word_offset() {
698        let mut builder = ChunkBuilder::new();
699
700        let fastcall = builder.emit(Instruction::abc_with_aux(
701            Opcode::FastCall2,
702            29,
703            1,
704            0,
705            Some(2),
706        ));
707        builder.emit(Instruction::abc(Opcode::Move, 3, 1, 0));
708        builder.emit(Instruction::abc_with_aux(
709            Opcode::GetImport,
710            2,
711            4,
712            0,
713            Some(0x4000_0000),
714        ));
715
716        assert!(builder.patch_skip_c_to_current(fastcall));
717        assert_eq!(builder.current_code()[fastcall].c, 4);
718    }
719
720    #[test]
721    fn records_instruction_word_offsets_as_code_is_emitted() {
722        let mut builder = ChunkBuilder::new();
723        let first = builder.emit(Instruction::abc_with_aux(
724            Opcode::GetImport,
725            0,
726            0,
727            0,
728            Some(0),
729        ));
730        let second = builder.emit(Instruction::abc(Opcode::Move, 1, 0, 0));
731
732        assert_eq!(builder.instruction_word_offset(first), 0);
733        assert_eq!(builder.instruction_word_offset(second), 2);
734        assert_eq!(builder.current_word_offset(), 3);
735    }
736
737    #[test]
738    fn folds_forward_jump_chains_and_jumps_to_return() {
739        let mut proto = ProtoWork::new();
740        proto.code = vec![
741            Instruction::ad(Opcode::JumpIfNot, 1, 2),
742            Instruction::abc(Opcode::LoadN, 0, 1, 0),
743            Instruction::ad(Opcode::Jump, 0, 0),
744            Instruction::ad(Opcode::Jump, 0, 1),
745            Instruction::abc(Opcode::LoadN, 0, 0, 0),
746            Instruction::abc(Opcode::Return, 0, 2, 0),
747        ];
748
749        proto.fold_jumps();
750
751        assert_eq!(proto.code[0].d, 4);
752        assert_eq!(proto.code[2], Instruction::abc(Opcode::Return, 0, 2, 0));
753        assert_eq!(proto.code[3], Instruction::abc(Opcode::Return, 0, 2, 0));
754    }
755}