1use serde::{Deserialize, Serialize};
4
5use crate::opcodes::{CaptureType, FeedbackType, Opcode};
6
7#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
9#[serde(tag = "kind", rename_all = "camelCase")]
10pub enum BytecodeChunk {
11 Valid {
13 bytecode_version: u8,
15 type_version: u8,
17 strings: Vec<Vec<u8>>,
19 userdata_type_mappings: Vec<UserdataTypeMapping>,
21 protos: Vec<Proto>,
23 main_proto: u32,
25 },
26 Error {
28 message: Vec<u8>,
30 },
31}
32
33#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
35#[serde(rename_all = "camelCase")]
36pub struct UserdataTypeMapping {
37 pub type_index: u8,
39 pub name: u32,
41}
42
43#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
45#[serde(rename_all = "camelCase")]
46pub struct Proto {
47 pub max_stack_size: u8,
49 pub num_params: u8,
51 pub num_upvalues: u8,
53 pub is_vararg: u8,
55 pub flags: u8,
57 pub type_info: TypeInfo,
59 pub code: Vec<Instruction>,
61 pub constants: Vec<Constant>,
63 pub child_protos: Vec<u32>,
65 pub line_defined: u32,
67 pub debug_name: u32,
69 pub line_info: Option<LineInfo>,
71 pub debug_info: Option<DebugInfo>,
73 #[serde(default, skip_serializing_if = "Vec::is_empty")]
75 pub feedback_slots: Vec<FeedbackSlot>,
76}
77
78#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
80#[serde(rename_all = "camelCase")]
81pub struct TypeInfo {
82 pub raw: Vec<u8>,
84}
85
86#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
103#[serde(rename_all = "camelCase")]
104pub struct Instruction {
105 pub header: u32,
107 pub opcode: Opcode,
109 pub a: u8,
111 pub b: u8,
113 pub c: u8,
115 pub d: i16,
117 pub e: i32,
119 #[serde(with = "aux_serde")]
122 pub aux: Option<u32>,
123}
124
125mod 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[must_use]
251 pub fn capture_source(&self) -> Option<u8> {
252 self.capture_type().map(|_| self.b)
253 }
254
255 #[must_use]
258 pub fn word_len(&self) -> u32 {
259 1 + u32::from(self.aux.is_some())
260 }
261
262 #[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#[must_use]
273pub fn code_word_count(code: &[Instruction]) -> u32 {
274 code.iter().map(Instruction::word_len).sum()
275}
276
277#[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#[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#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
305#[serde(tag = "kind", rename_all = "camelCase")]
306pub enum Constant {
307 Nil,
309 Boolean {
311 value: bool,
313 },
314 Number {
316 bits: u64,
318 },
319 String {
321 string: u32,
323 },
324 Import {
326 import_id: u32,
328 },
329 Table {
331 keys: Vec<u32>,
333 },
334 Closure {
336 proto: u32,
338 },
339 Vector {
341 bits: [u32; 4],
343 },
344 TableWithConstants {
346 entries: Vec<TableEntry>,
348 },
349 Integer {
351 value: i64,
353 },
354 ClassShape {
356 shape: ClassShape,
358 },
359}
360
361#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
363#[serde(rename_all = "camelCase")]
364pub struct TableEntry {
365 pub key: u32,
367 pub value: i32,
369}
370
371#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
373#[serde(rename_all = "camelCase")]
374pub struct ClassShape {
375 pub class_name: u32,
377 pub property_names: Vec<u32>,
379 pub method_names: Vec<u32>,
381}
382
383#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
385#[serde(rename_all = "camelCase")]
386pub struct LineInfo {
387 pub log2_span: u8,
389 pub delta_bytes: Vec<u8>,
391 pub baseline_deltas: Vec<i32>,
393}
394
395impl LineInfo {
396 #[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 #[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 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#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
494#[serde(rename_all = "camelCase")]
495pub struct DebugInfo {
496 pub locals: Vec<DebugLocal>,
498 pub upvalues: Vec<u32>,
500}
501
502#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
504#[serde(rename_all = "camelCase")]
505pub struct DebugLocal {
506 pub name: u32,
508 pub start_pc: u32,
510 pub end_pc: u32,
512 pub register: u8,
514}
515
516#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
518#[serde(rename_all = "camelCase")]
519pub struct FeedbackSlot {
520 pub kind: FeedbackType,
522 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}