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