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 #[serde(default, skip_serializing_if = "Option::is_none")]
78 pub cost: Option<u64>,
79}
80
81#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
83#[serde(rename_all = "camelCase")]
84pub struct TypeInfo {
85 pub raw: Vec<u8>,
87}
88
89#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
106#[serde(rename_all = "camelCase")]
107pub struct Instruction {
108 pub header: u32,
110 pub opcode: Opcode,
112 pub a: u8,
114 pub b: u8,
116 pub c: u8,
118 pub d: i16,
120 pub e: i32,
122 #[serde(with = "aux_serde")]
125 pub aux: Option<u32>,
126}
127
128mod aux_serde {
131 use serde::{Deserialize, Deserializer, Serialize, Serializer};
132
133 pub fn serialize<S: Serializer>(aux: &Option<u32>, serializer: S) -> Result<S::Ok, S::Error> {
134 let words: &[u32] = match aux {
135 Some(word) => std::slice::from_ref(word),
136 None => &[],
137 };
138 words.serialize(serializer)
139 }
140
141 pub fn deserialize<'de, D: Deserializer<'de>>(
142 deserializer: D,
143 ) -> Result<Option<u32>, D::Error> {
144 let words = Vec::<u32>::deserialize(deserializer)?;
145 match words.as_slice() {
146 [] => Ok(None),
147 [word] => Ok(Some(*word)),
148 _ => Err(serde::de::Error::custom(
149 "an instruction has at most one AUX word",
150 )),
151 }
152 }
153}
154
155impl Instruction {
156 #[must_use]
158 pub fn from_words(header: u32, aux: Option<u32>) -> Option<Self> {
159 let opcode = Opcode::from_byte((header & 0xff) as u8)?;
160 Some(Self {
161 header,
162 opcode,
163 a: ((header >> 8) & 0xff) as u8,
164 b: ((header >> 16) & 0xff) as u8,
165 c: ((header >> 24) & 0xff) as u8,
166 d: (header >> 16) as u16 as i16,
167 e: (header as i32) >> 8,
168 aux,
169 })
170 }
171
172 #[must_use]
174 pub fn abc(opcode: Opcode, a: u8, b: u8, c: u8) -> Self {
175 let header =
176 opcode.byte() as u32 | ((a as u32) << 8) | ((b as u32) << 16) | ((c as u32) << 24);
177 Self::from_words(header, None).expect("opcode bytes from the Opcode enum always decode")
178 }
179
180 #[must_use]
182 pub fn abc_with_aux(opcode: Opcode, a: u8, b: u8, c: u8, aux: Option<u32>) -> Self {
183 let header =
184 opcode.byte() as u32 | ((a as u32) << 8) | ((b as u32) << 16) | ((c as u32) << 24);
185 Self::from_words(header, aux).expect("opcode bytes from the Opcode enum always decode")
186 }
187
188 #[must_use]
190 pub fn ad(opcode: Opcode, a: u8, d: i16) -> Self {
191 let header = opcode.byte() as u32 | ((a as u32) << 8) | ((d as u16 as u32) << 16);
192 Self::from_words(header, None).expect("opcode bytes from the Opcode enum always decode")
193 }
194
195 #[must_use]
202 pub fn jump_offset_words(&self) -> Option<i32> {
203 match self.opcode {
204 Opcode::Jump
205 | Opcode::JumpBack
206 | Opcode::JumpIf
207 | Opcode::JumpIfNot
208 | Opcode::JumpIfEq
209 | Opcode::JumpIfLe
210 | Opcode::JumpIfLt
211 | Opcode::JumpIfNotEq
212 | Opcode::JumpIfNotLe
213 | Opcode::JumpIfNotLt
214 | Opcode::ForNPrep
215 | Opcode::ForNLoop
216 | Opcode::ForGLoop
217 | Opcode::ForGPrepInext
218 | Opcode::ForGPrepNext
219 | Opcode::ForGPrep
220 | Opcode::JumpXEqKNil
221 | Opcode::JumpXEqKB
222 | Opcode::JumpXEqKN
223 | Opcode::JumpXEqKS
224 | Opcode::CmpProto => Some(i32::from(self.d)),
225 Opcode::JumpX => Some(self.e),
226 Opcode::LoadB
227 | Opcode::FastCall
228 | Opcode::FastCall1
229 | Opcode::FastCall2
230 | Opcode::FastCall2K
231 | Opcode::FastCall3 => Some(i32::from(self.c)),
232 _ => None,
233 }
234 }
235
236 #[must_use]
238 pub fn jump_target_word(&self, instruction_word: u32) -> Option<i32> {
239 Some(instruction_word as i32 + 1 + self.jump_offset_words()?)
240 }
241
242 #[must_use]
244 pub fn capture_type(&self) -> Option<CaptureType> {
245 if self.opcode == Opcode::Capture {
246 CaptureType::from_byte(self.a)
247 } else {
248 None
249 }
250 }
251
252 #[must_use]
254 pub fn capture_source(&self) -> Option<u8> {
255 self.capture_type().map(|_| self.b)
256 }
257
258 #[must_use]
261 pub fn word_len(&self) -> u32 {
262 1 + u32::from(self.aux.is_some())
263 }
264
265 #[must_use]
269 pub fn is_header_consistent(&self) -> bool {
270 Self::from_words(self.header, self.aux).is_some_and(|decoded| decoded == *self)
271 }
272}
273
274#[must_use]
276pub fn code_word_count(code: &[Instruction]) -> u32 {
277 code.iter().map(Instruction::word_len).sum()
278}
279
280#[must_use]
282pub fn instruction_word_offsets(code: &[Instruction]) -> Vec<u32> {
283 let mut next = 0u32;
284 code.iter()
285 .map(|instruction| {
286 let current = next;
287 next += instruction.word_len();
288 current
289 })
290 .collect()
291}
292
293#[must_use]
295pub fn jump_target_instruction_index(
296 code: &[Instruction],
297 instruction_index: usize,
298) -> Option<usize> {
299 let offsets = instruction_word_offsets(code);
300 let instruction = code.get(instruction_index)?;
301 let source_word = *offsets.get(instruction_index)?;
302 let target = instruction.jump_target_word(source_word)?;
303 offsets.iter().position(|word| *word as i32 == target)
304}
305
306#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
308#[serde(tag = "kind", rename_all = "camelCase")]
309pub enum Constant {
310 Nil,
312 Boolean {
314 value: bool,
316 },
317 Number {
319 bits: u64,
321 },
322 String {
324 string: u32,
326 },
327 Import {
329 import_id: u32,
331 },
332 Table {
334 keys: Vec<u32>,
336 },
337 Closure {
339 proto: u32,
341 },
342 Vector {
344 bits: [u32; 4],
346 },
347 VectorDouble {
349 bits: [u64; 4],
351 },
352 TableWithConstants {
354 entries: Vec<TableEntry>,
356 },
357 Integer {
359 value: i64,
361 },
362 ClassShape {
364 shape: ClassShape,
366 },
367}
368
369#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
371#[serde(rename_all = "camelCase")]
372pub struct TableEntry {
373 pub key: u32,
375 pub value: i32,
377}
378
379#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
381#[serde(rename_all = "camelCase")]
382pub struct ClassShape {
383 pub class_name: u32,
385 pub property_names: Vec<u32>,
387 pub method_names: Vec<u32>,
389}
390
391#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
393#[serde(rename_all = "camelCase")]
394pub struct LineInfo {
395 pub log2_span: u8,
397 pub delta_bytes: Vec<u8>,
399 pub baseline_deltas: Vec<i32>,
401}
402
403impl LineInfo {
404 #[must_use]
406 pub(crate) fn from_line_numbers(lines: &[i32]) -> Option<Self> {
407 if lines.is_empty() {
408 return None;
409 }
410
411 let mut span = 1usize << 24;
412 let mut offset = 0usize;
413 while offset < lines.len() {
414 let mut next = offset;
415 let mut min = lines[offset];
416 let mut max = lines[offset];
417
418 while next < lines.len() && next < offset + span {
419 min = min.min(lines[next]);
420 max = max.max(lines[next]);
421 if max - min > 255 {
422 break;
423 }
424 next += 1;
425 }
426
427 if next < lines.len() && next - offset < span {
428 span = 1usize << line_info_log2(next - offset);
429 }
430
431 offset += span;
432 }
433
434 let log2_span = line_info_log2(span) as u8;
435 let baseline_size = (lines.len() - 1) / span + 1;
436 let mut baselines = Vec::with_capacity(baseline_size);
437 for chunk in lines.chunks(span) {
438 baselines.push(*chunk.iter().min().expect("non-empty chunk"));
439 }
440
441 let mut delta_bytes = Vec::with_capacity(lines.len());
442 let mut last_offset = 0u8;
443 for (index, line) in lines.iter().enumerate() {
444 let baseline = baselines[index >> usize::from(log2_span)];
445 let delta = *line - baseline;
446 debug_assert!((0..=255).contains(&delta));
447 let delta = delta as u8;
448 delta_bytes.push(delta.wrapping_sub(last_offset));
449 last_offset = delta;
450 }
451
452 let mut baseline_deltas = Vec::with_capacity(baseline_size);
453 let mut last_line = 0;
454 for baseline in baselines {
455 baseline_deltas.push(baseline - last_line);
456 last_line = baseline;
457 }
458
459 Some(Self {
460 log2_span,
461 delta_bytes,
462 baseline_deltas,
463 })
464 }
465
466 #[must_use]
468 pub fn to_line_numbers(&self) -> Option<Vec<i32>> {
469 let mut baselines = Vec::with_capacity(self.baseline_deltas.len());
470 let mut baseline = 0i32;
471 for delta in &self.baseline_deltas {
472 baseline = baseline.wrapping_add(*delta);
474 baselines.push(baseline);
475 }
476
477 let mut lines = Vec::with_capacity(self.delta_bytes.len());
478 let mut last_offset = 0u8;
479 for (index, byte) in self.delta_bytes.iter().enumerate() {
480 let baseline = *baselines.get(index >> usize::from(self.log2_span))?;
481 let offset = last_offset.wrapping_add(*byte);
482 lines.push(baseline.wrapping_add(i32::from(offset)));
483 last_offset = offset;
484 }
485
486 Some(lines)
487 }
488}
489
490fn line_info_log2(value: usize) -> usize {
491 debug_assert!(value > 0);
492
493 let mut result = 0;
494 while value >= (2usize << result) {
495 result += 1;
496 }
497 result
498}
499
500#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
502#[serde(rename_all = "camelCase")]
503pub struct DebugInfo {
504 pub locals: Vec<DebugLocal>,
506 pub upvalues: Vec<u32>,
508}
509
510#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
512#[serde(rename_all = "camelCase")]
513pub struct DebugLocal {
514 pub name: u32,
516 pub start_pc: u32,
518 pub end_pc: u32,
520 pub register: u8,
522}
523
524#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
526#[serde(rename_all = "camelCase")]
527pub struct FeedbackSlot {
528 pub kind: FeedbackType,
530 pub pc: u32,
532}
533
534#[cfg(test)]
535mod tests {
536 use super::{
537 CaptureType, Instruction, LineInfo, Opcode, instruction_word_offsets,
538 jump_target_instruction_index,
539 };
540
541 #[test]
542 fn jump_targets_are_word_relative() {
543 let jump_next = Instruction::ad(Opcode::Jump, 0, 0);
544 assert_eq!(jump_next.jump_offset_words(), Some(0));
545 assert_eq!(jump_next.jump_target_word(10), Some(11));
546
547 let jump_back = Instruction::ad(Opcode::JumpBack, 0, -3);
548 assert_eq!(jump_back.jump_target_word(10), Some(8));
549
550 let jump_x = Instruction::from_words(
551 Opcode::JumpX.byte() as u32 | ((-5_i32 as u32 & 0x00ff_ffff) << 8),
552 None,
553 )
554 .expect("jumpx");
555 assert_eq!(jump_x.jump_offset_words(), Some(-5));
556 assert_eq!(jump_x.jump_target_word(10), Some(6));
557 }
558
559 #[test]
560 fn jump_targets_count_aux_words() {
561 let compare = Instruction::abc_with_aux(Opcode::JumpIfEq, 0, 1, 0, Some(0));
562 assert_eq!(compare.jump_offset_words(), Some(1));
563 assert_eq!(compare.jump_target_word(4), Some(6));
564
565 let code = vec![
566 Instruction::ad(Opcode::LoadN, 0, 1),
567 compare,
568 Instruction::ad(Opcode::LoadN, 1, 2),
569 Instruction::abc(Opcode::Return, 0, 1, 0),
570 ];
571 assert_eq!(instruction_word_offsets(&code), vec![0, 1, 3, 4]);
572 assert_eq!(jump_target_instruction_index(&code, 1), Some(2));
573
574 let compare_to_return = Instruction::abc_with_aux(Opcode::JumpIfEq, 0, 2, 0, Some(0));
575 let code = vec![
576 Instruction::ad(Opcode::LoadN, 0, 1),
577 compare_to_return,
578 Instruction::ad(Opcode::LoadN, 1, 2),
579 Instruction::abc(Opcode::Return, 0, 1, 0),
580 ];
581 assert_eq!(jump_target_instruction_index(&code, 1), Some(3));
582 }
583
584 #[test]
585 fn short_jump_operands_are_exposed() {
586 let loadb = Instruction::abc(Opcode::LoadB, 0, 1, 2);
587 assert_eq!(loadb.jump_offset_words(), Some(2));
588 assert_eq!(loadb.jump_target_word(7), Some(10));
589
590 let fastcall = Instruction::abc(Opcode::FastCall2K, 18, 1, 3);
591 assert_eq!(fastcall.jump_offset_words(), Some(3));
592 assert_eq!(fastcall.jump_target_word(7), Some(11));
593
594 let not_a_jump = Instruction::ad(Opcode::LoadN, 0, 5);
595 assert_eq!(not_a_jump.jump_offset_words(), None);
596 assert_eq!(not_a_jump.jump_target_word(0), None);
597 }
598
599 #[test]
600 fn capture_operands_are_exposed() {
601 let by_value = Instruction::abc(Opcode::Capture, CaptureType::Val as u8, 3, 0);
602 assert_eq!(by_value.capture_type(), Some(CaptureType::Val));
603 assert_eq!(by_value.capture_source(), Some(3));
604
605 let by_reference = Instruction::abc(Opcode::Capture, CaptureType::Ref as u8, 4, 0);
606 assert_eq!(by_reference.capture_type(), Some(CaptureType::Ref));
607 assert_eq!(by_reference.capture_source(), Some(4));
608
609 let upvalue = Instruction::abc(Opcode::Capture, CaptureType::Upval as u8, 1, 0);
610 assert_eq!(upvalue.capture_type(), Some(CaptureType::Upval));
611 assert_eq!(upvalue.capture_source(), Some(1));
612
613 let invalid = Instruction::abc(Opcode::Capture, 99, 1, 0);
614 assert_eq!(invalid.capture_type(), None);
615 assert_eq!(invalid.capture_source(), None);
616
617 let not_capture = Instruction::ad(Opcode::LoadN, 0, 5);
618 assert_eq!(not_capture.capture_type(), None);
619 assert_eq!(not_capture.capture_source(), None);
620 }
621
622 #[test]
623 fn line_info_uses_large_span_when_deltas_fit() {
624 let line_info = LineInfo::from_line_numbers(&[10, 10, 20]).expect("line info");
625 assert_eq!(line_info.log2_span, 24);
626 assert_eq!(line_info.delta_bytes, vec![0, 0, 10]);
627 assert_eq!(line_info.baseline_deltas, vec![10]);
628 assert_eq!(
629 line_info.to_line_numbers().expect("line numbers"),
630 vec![10, 10, 20]
631 );
632 }
633
634 #[test]
635 fn line_info_shrinks_span_before_8_bit_delta_overflows() {
636 let lines = [1, 2, 300, 301, 302];
637 let line_info = LineInfo::from_line_numbers(&lines).expect("line info");
638
639 assert_eq!(line_info.log2_span, 1);
640 assert_eq!(line_info.delta_bytes, vec![0, 1, 255, 1, 255]);
641 assert_eq!(line_info.baseline_deltas, vec![1, 299, 2]);
642 assert_eq!(line_info.to_line_numbers().expect("line numbers"), lines);
643 }
644}