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