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 userdata_mapping_terminator: u8,
23 protos: Vec<Proto>,
25 main_proto: u32,
27 },
28 Error {
30 message: Vec<u8>,
32 },
33}
34
35#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
37#[serde(rename_all = "camelCase")]
38pub struct UserdataTypeMapping {
39 pub type_index: u8,
41 pub name: u32,
43}
44
45#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
47#[serde(rename_all = "camelCase")]
48pub struct Proto {
49 pub max_stack_size: u8,
51 pub num_params: u8,
53 pub num_upvalues: u8,
55 pub is_vararg: u8,
57 pub flags: u8,
59 pub type_info: TypeInfo,
61 pub code: Vec<Instruction>,
63 pub constants: Vec<Constant>,
65 pub child_protos: Vec<u32>,
67 pub line_defined: u32,
69 pub debug_name: u32,
71 pub line_info: Option<LineInfo>,
73 pub debug_info: Option<DebugInfo>,
75 #[serde(default, skip_serializing_if = "Vec::is_empty")]
77 pub feedback_slots: Vec<FeedbackSlot>,
78}
79
80#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
82#[serde(rename_all = "camelCase")]
83pub struct TypeInfo {
84 pub raw: Vec<u8>,
86}
87
88#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
94#[serde(rename_all = "camelCase")]
95pub struct Instruction {
96 pub header: u32,
98 pub opcode: Opcode,
100 pub a: u8,
102 pub b: u8,
104 pub c: u8,
106 pub d: i16,
108 pub e: i32,
110 #[serde(with = "aux_serde")]
113 pub aux: Option<u32>,
114}
115
116mod aux_serde {
119 use serde::{Deserialize, Deserializer, Serialize, Serializer};
120
121 pub fn serialize<S: Serializer>(aux: &Option<u32>, serializer: S) -> Result<S::Ok, S::Error> {
122 let words: &[u32] = match aux {
123 Some(word) => std::slice::from_ref(word),
124 None => &[],
125 };
126 words.serialize(serializer)
127 }
128
129 pub fn deserialize<'de, D: Deserializer<'de>>(
130 deserializer: D,
131 ) -> Result<Option<u32>, D::Error> {
132 let words = Vec::<u32>::deserialize(deserializer)?;
133 match words.as_slice() {
134 [] => Ok(None),
135 [word] => Ok(Some(*word)),
136 _ => Err(serde::de::Error::custom(
137 "an instruction has at most one AUX word",
138 )),
139 }
140 }
141}
142
143impl Instruction {
144 #[must_use]
146 pub fn from_words(header: u32, aux: Option<u32>) -> Option<Self> {
147 let opcode = Opcode::from_byte((header & 0xff) as u8)?;
148 Some(Self {
149 header,
150 opcode,
151 a: ((header >> 8) & 0xff) as u8,
152 b: ((header >> 16) & 0xff) as u8,
153 c: ((header >> 24) & 0xff) as u8,
154 d: (header >> 16) as u16 as i16,
155 e: (header as i32) >> 8,
156 aux,
157 })
158 }
159
160 #[must_use]
162 pub fn abc(opcode: Opcode, a: u8, b: u8, c: u8) -> Self {
163 let header =
164 opcode.byte() as u32 | ((a as u32) << 8) | ((b as u32) << 16) | ((c as u32) << 24);
165 Self::from_words(header, None).expect("opcode bytes from the Opcode enum always decode")
166 }
167
168 #[must_use]
170 pub fn abc_with_aux(opcode: Opcode, a: u8, b: u8, c: u8, aux: Option<u32>) -> Self {
171 let header =
172 opcode.byte() as u32 | ((a as u32) << 8) | ((b as u32) << 16) | ((c as u32) << 24);
173 Self::from_words(header, aux).expect("opcode bytes from the Opcode enum always decode")
174 }
175
176 #[must_use]
178 pub fn ad(opcode: Opcode, a: u8, d: i16) -> Self {
179 let header = opcode.byte() as u32 | ((a as u32) << 8) | ((d as u16 as u32) << 16);
180 Self::from_words(header, None).expect("opcode bytes from the Opcode enum always decode")
181 }
182
183 #[must_use]
190 pub fn jump_offset_words(&self) -> Option<i32> {
191 match self.opcode {
192 Opcode::Jump
193 | Opcode::JumpBack
194 | Opcode::JumpIf
195 | Opcode::JumpIfNot
196 | Opcode::JumpIfEq
197 | Opcode::JumpIfLe
198 | Opcode::JumpIfLt
199 | Opcode::JumpIfNotEq
200 | Opcode::JumpIfNotLe
201 | Opcode::JumpIfNotLt
202 | Opcode::ForNPrep
203 | Opcode::ForNLoop
204 | Opcode::ForGLoop
205 | Opcode::ForGPrepInext
206 | Opcode::ForGPrepNext
207 | Opcode::ForGPrep
208 | Opcode::JumpXEqKNil
209 | Opcode::JumpXEqKB
210 | Opcode::JumpXEqKN
211 | Opcode::JumpXEqKS
212 | Opcode::CmpProto => Some(i32::from(self.d)),
213 Opcode::JumpX => Some(self.e),
214 Opcode::LoadB
215 | Opcode::FastCall
216 | Opcode::FastCall1
217 | Opcode::FastCall2
218 | Opcode::FastCall2K
219 | Opcode::FastCall3 => Some(i32::from(self.c)),
220 _ => None,
221 }
222 }
223
224 #[must_use]
226 pub fn jump_target_word(&self, instruction_word: u32) -> Option<i32> {
227 Some(instruction_word as i32 + 1 + self.jump_offset_words()?)
228 }
229
230 #[must_use]
232 pub fn capture_type(&self) -> Option<CaptureType> {
233 if self.opcode == Opcode::Capture {
234 CaptureType::from_byte(self.a)
235 } else {
236 None
237 }
238 }
239
240 #[must_use]
242 pub fn capture_source(&self) -> Option<u8> {
243 self.capture_type().map(|_| self.b)
244 }
245
246 #[must_use]
249 pub fn word_len(&self) -> u32 {
250 1 + u32::from(self.aux.is_some())
251 }
252}
253
254#[must_use]
256pub fn code_word_count(code: &[Instruction]) -> u32 {
257 code.iter().map(Instruction::word_len).sum()
258}
259
260#[must_use]
262pub fn instruction_word_offsets(code: &[Instruction]) -> Vec<u32> {
263 let mut next = 0u32;
264 code.iter()
265 .map(|instruction| {
266 let current = next;
267 next += instruction.word_len();
268 current
269 })
270 .collect()
271}
272
273#[must_use]
275pub fn jump_target_instruction_index(
276 code: &[Instruction],
277 instruction_index: usize,
278) -> Option<usize> {
279 let offsets = instruction_word_offsets(code);
280 let instruction = code.get(instruction_index)?;
281 let source_word = *offsets.get(instruction_index)?;
282 let target = instruction.jump_target_word(source_word)?;
283 offsets.iter().position(|word| *word as i32 == target)
284}
285
286#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
288#[serde(tag = "kind", rename_all = "camelCase")]
289pub enum Constant {
290 Nil,
292 Boolean {
294 value: bool,
296 },
297 Number {
299 bits: u64,
301 },
302 String {
304 string: u32,
306 },
307 Import {
309 import_id: u32,
311 },
312 Table {
314 keys: Vec<u32>,
316 },
317 Closure {
319 proto: u32,
321 },
322 Vector {
324 bits: [u32; 4],
326 },
327 TableWithConstants {
329 entries: Vec<TableEntry>,
331 },
332 Integer {
334 value: i64,
336 },
337 ClassShape {
339 shape: ClassShape,
341 },
342}
343
344#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
346#[serde(rename_all = "camelCase")]
347pub struct TableEntry {
348 pub key: u32,
350 pub value: i32,
352}
353
354#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
356#[serde(rename_all = "camelCase")]
357pub struct ClassShape {
358 pub class_name: u32,
360 pub property_names: Vec<u32>,
362 pub method_names: Vec<u32>,
364}
365
366#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
368#[serde(rename_all = "camelCase")]
369pub struct LineInfo {
370 pub log2_span: u8,
372 pub delta_bytes: Vec<u8>,
374 pub baseline_deltas: Vec<i32>,
376}
377
378impl LineInfo {
379 #[must_use]
381 pub(crate) fn from_line_numbers(lines: &[i32]) -> Option<Self> {
382 if lines.is_empty() {
383 return None;
384 }
385
386 let mut span = 1usize << 24;
387 let mut offset = 0usize;
388 while offset < lines.len() {
389 let mut next = offset;
390 let mut min = lines[offset];
391 let mut max = lines[offset];
392
393 while next < lines.len() && next < offset + span {
394 min = min.min(lines[next]);
395 max = max.max(lines[next]);
396 if max - min > 255 {
397 break;
398 }
399 next += 1;
400 }
401
402 if next < lines.len() && next - offset < span {
403 span = 1usize << line_info_log2(next - offset);
404 }
405
406 offset += span;
407 }
408
409 let log2_span = line_info_log2(span) as u8;
410 let baseline_size = (lines.len() - 1) / span + 1;
411 let mut baselines = Vec::with_capacity(baseline_size);
412 for chunk in lines.chunks(span) {
413 baselines.push(*chunk.iter().min().expect("non-empty chunk"));
414 }
415
416 let mut delta_bytes = Vec::with_capacity(lines.len());
417 let mut last_offset = 0u8;
418 for (index, line) in lines.iter().enumerate() {
419 let baseline = baselines[index >> usize::from(log2_span)];
420 let delta = *line - baseline;
421 debug_assert!((0..=255).contains(&delta));
422 let delta = delta as u8;
423 delta_bytes.push(delta.wrapping_sub(last_offset));
424 last_offset = delta;
425 }
426
427 let mut baseline_deltas = Vec::with_capacity(baseline_size);
428 let mut last_line = 0;
429 for baseline in baselines {
430 baseline_deltas.push(baseline - last_line);
431 last_line = baseline;
432 }
433
434 Some(Self {
435 log2_span,
436 delta_bytes,
437 baseline_deltas,
438 })
439 }
440
441 #[must_use]
443 pub fn to_line_numbers(&self) -> Option<Vec<i32>> {
444 let mut baselines = Vec::with_capacity(self.baseline_deltas.len());
445 let mut baseline = 0i32;
446 for delta in &self.baseline_deltas {
447 baseline = baseline.wrapping_add(*delta);
449 baselines.push(baseline);
450 }
451
452 let mut lines = Vec::with_capacity(self.delta_bytes.len());
453 let mut last_offset = 0u8;
454 for (index, byte) in self.delta_bytes.iter().enumerate() {
455 let baseline = *baselines.get(index >> usize::from(self.log2_span))?;
456 let offset = last_offset.wrapping_add(*byte);
457 lines.push(baseline.wrapping_add(i32::from(offset)));
458 last_offset = offset;
459 }
460
461 Some(lines)
462 }
463}
464
465fn line_info_log2(value: usize) -> usize {
466 debug_assert!(value > 0);
467
468 let mut result = 0;
469 while value >= (2usize << result) {
470 result += 1;
471 }
472 result
473}
474
475#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
477#[serde(rename_all = "camelCase")]
478pub struct DebugInfo {
479 pub locals: Vec<DebugLocal>,
481 pub upvalues: Vec<u32>,
483}
484
485#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
487#[serde(rename_all = "camelCase")]
488pub struct DebugLocal {
489 pub name: u32,
491 pub start_pc: u32,
493 pub end_pc: u32,
495 pub register: u8,
497}
498
499#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
501#[serde(rename_all = "camelCase")]
502pub struct FeedbackSlot {
503 pub kind: FeedbackType,
505 pub pc: u32,
507}
508
509#[cfg(test)]
510mod tests {
511 use super::{
512 CaptureType, Instruction, LineInfo, Opcode, instruction_word_offsets,
513 jump_target_instruction_index,
514 };
515
516 #[test]
517 fn jump_targets_are_word_relative() {
518 let jump_next = Instruction::ad(Opcode::Jump, 0, 0);
519 assert_eq!(jump_next.jump_offset_words(), Some(0));
520 assert_eq!(jump_next.jump_target_word(10), Some(11));
521
522 let jump_back = Instruction::ad(Opcode::JumpBack, 0, -3);
523 assert_eq!(jump_back.jump_target_word(10), Some(8));
524
525 let jump_x = Instruction::from_words(
526 Opcode::JumpX.byte() as u32 | ((-5_i32 as u32 & 0x00ff_ffff) << 8),
527 None,
528 )
529 .expect("jumpx");
530 assert_eq!(jump_x.jump_offset_words(), Some(-5));
531 assert_eq!(jump_x.jump_target_word(10), Some(6));
532 }
533
534 #[test]
535 fn jump_targets_count_aux_words() {
536 let compare = Instruction::abc_with_aux(Opcode::JumpIfEq, 0, 1, 0, Some(0));
537 assert_eq!(compare.jump_offset_words(), Some(1));
538 assert_eq!(compare.jump_target_word(4), Some(6));
539
540 let code = vec![
541 Instruction::ad(Opcode::LoadN, 0, 1),
542 compare,
543 Instruction::ad(Opcode::LoadN, 1, 2),
544 Instruction::abc(Opcode::Return, 0, 1, 0),
545 ];
546 assert_eq!(instruction_word_offsets(&code), vec![0, 1, 3, 4]);
547 assert_eq!(jump_target_instruction_index(&code, 1), Some(2));
548
549 let compare_to_return = Instruction::abc_with_aux(Opcode::JumpIfEq, 0, 2, 0, Some(0));
550 let code = vec![
551 Instruction::ad(Opcode::LoadN, 0, 1),
552 compare_to_return,
553 Instruction::ad(Opcode::LoadN, 1, 2),
554 Instruction::abc(Opcode::Return, 0, 1, 0),
555 ];
556 assert_eq!(jump_target_instruction_index(&code, 1), Some(3));
557 }
558
559 #[test]
560 fn short_jump_operands_are_exposed() {
561 let loadb = Instruction::abc(Opcode::LoadB, 0, 1, 2);
562 assert_eq!(loadb.jump_offset_words(), Some(2));
563 assert_eq!(loadb.jump_target_word(7), Some(10));
564
565 let fastcall = Instruction::abc(Opcode::FastCall2K, 18, 1, 3);
566 assert_eq!(fastcall.jump_offset_words(), Some(3));
567 assert_eq!(fastcall.jump_target_word(7), Some(11));
568
569 let not_a_jump = Instruction::ad(Opcode::LoadN, 0, 5);
570 assert_eq!(not_a_jump.jump_offset_words(), None);
571 assert_eq!(not_a_jump.jump_target_word(0), None);
572 }
573
574 #[test]
575 fn capture_operands_are_exposed() {
576 let by_value = Instruction::abc(Opcode::Capture, CaptureType::Val as u8, 3, 0);
577 assert_eq!(by_value.capture_type(), Some(CaptureType::Val));
578 assert_eq!(by_value.capture_source(), Some(3));
579
580 let by_reference = Instruction::abc(Opcode::Capture, CaptureType::Ref as u8, 4, 0);
581 assert_eq!(by_reference.capture_type(), Some(CaptureType::Ref));
582 assert_eq!(by_reference.capture_source(), Some(4));
583
584 let upvalue = Instruction::abc(Opcode::Capture, CaptureType::Upval as u8, 1, 0);
585 assert_eq!(upvalue.capture_type(), Some(CaptureType::Upval));
586 assert_eq!(upvalue.capture_source(), Some(1));
587
588 let invalid = Instruction::abc(Opcode::Capture, 99, 1, 0);
589 assert_eq!(invalid.capture_type(), None);
590 assert_eq!(invalid.capture_source(), None);
591
592 let not_capture = Instruction::ad(Opcode::LoadN, 0, 5);
593 assert_eq!(not_capture.capture_type(), None);
594 assert_eq!(not_capture.capture_source(), None);
595 }
596
597 #[test]
598 fn line_info_uses_large_span_when_deltas_fit() {
599 let line_info = LineInfo::from_line_numbers(&[10, 10, 20]).expect("line info");
600 assert_eq!(line_info.log2_span, 24);
601 assert_eq!(line_info.delta_bytes, vec![0, 0, 10]);
602 assert_eq!(line_info.baseline_deltas, vec![10]);
603 assert_eq!(
604 line_info.to_line_numbers().expect("line numbers"),
605 vec![10, 10, 20]
606 );
607 }
608
609 #[test]
610 fn line_info_shrinks_span_before_8_bit_delta_overflows() {
611 let lines = [1, 2, 300, 301, 302];
612 let line_info = LineInfo::from_line_numbers(&lines).expect("line info");
613
614 assert_eq!(line_info.log2_span, 1);
615 assert_eq!(line_info.delta_bytes, vec![0, 1, 255, 1, 255]);
616 assert_eq!(line_info.baseline_deltas, vec![1, 299, 2]);
617 assert_eq!(line_info.to_line_numbers().expect("line numbers"), lines);
618 }
619}