use serde::{Deserialize, Serialize};
use crate::opcodes::{CaptureType, FeedbackType, Opcode};
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum BytecodeChunk {
Valid {
bytecode_version: u8,
type_version: u8,
strings: Vec<Vec<u8>>,
userdata_type_mappings: Vec<UserdataTypeMapping>,
userdata_mapping_terminator: u8,
protos: Vec<Proto>,
main_proto: u32,
},
Error {
message: Vec<u8>,
},
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UserdataTypeMapping {
pub type_index: u8,
pub name: u32,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Proto {
pub max_stack_size: u8,
pub num_params: u8,
pub num_upvalues: u8,
pub is_vararg: u8,
pub flags: u8,
pub type_info: TypeInfo,
pub code: Vec<Instruction>,
pub constants: Vec<Constant>,
pub child_protos: Vec<u32>,
pub line_defined: u32,
pub debug_name: u32,
pub line_info: Option<LineInfo>,
pub debug_info: Option<DebugInfo>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub feedback_slots: Vec<FeedbackSlot>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TypeInfo {
pub raw: Vec<u8>,
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Instruction {
pub header: u32,
pub opcode: Opcode,
pub a: u8,
pub b: u8,
pub c: u8,
pub d: i16,
pub e: i32,
#[serde(with = "aux_serde")]
pub aux: Option<u32>,
}
mod aux_serde {
use serde::{Deserialize, Deserializer, Serialize, Serializer};
pub fn serialize<S: Serializer>(aux: &Option<u32>, serializer: S) -> Result<S::Ok, S::Error> {
let words: &[u32] = match aux {
Some(word) => std::slice::from_ref(word),
None => &[],
};
words.serialize(serializer)
}
pub fn deserialize<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<Option<u32>, D::Error> {
let words = Vec::<u32>::deserialize(deserializer)?;
match words.as_slice() {
[] => Ok(None),
[word] => Ok(Some(*word)),
_ => Err(serde::de::Error::custom(
"an instruction has at most one AUX word",
)),
}
}
}
impl Instruction {
#[must_use]
pub fn from_words(header: u32, aux: Option<u32>) -> Option<Self> {
let opcode = Opcode::from_byte((header & 0xff) as u8)?;
Some(Self {
header,
opcode,
a: ((header >> 8) & 0xff) as u8,
b: ((header >> 16) & 0xff) as u8,
c: ((header >> 24) & 0xff) as u8,
d: (header >> 16) as u16 as i16,
e: (header as i32) >> 8,
aux,
})
}
#[must_use]
pub fn abc(opcode: Opcode, a: u8, b: u8, c: u8) -> Self {
let header =
opcode.byte() as u32 | ((a as u32) << 8) | ((b as u32) << 16) | ((c as u32) << 24);
Self::from_words(header, None).expect("opcode bytes from the Opcode enum always decode")
}
#[must_use]
pub fn abc_with_aux(opcode: Opcode, a: u8, b: u8, c: u8, aux: Option<u32>) -> Self {
let header =
opcode.byte() as u32 | ((a as u32) << 8) | ((b as u32) << 16) | ((c as u32) << 24);
Self::from_words(header, aux).expect("opcode bytes from the Opcode enum always decode")
}
#[must_use]
pub fn ad(opcode: Opcode, a: u8, d: i16) -> Self {
let header = opcode.byte() as u32 | ((a as u32) << 8) | ((d as u16 as u32) << 16);
Self::from_words(header, None).expect("opcode bytes from the Opcode enum always decode")
}
#[must_use]
pub fn jump_offset_words(&self) -> Option<i32> {
match self.opcode {
Opcode::Jump
| Opcode::JumpBack
| Opcode::JumpIf
| Opcode::JumpIfNot
| Opcode::JumpIfEq
| Opcode::JumpIfLe
| Opcode::JumpIfLt
| Opcode::JumpIfNotEq
| Opcode::JumpIfNotLe
| Opcode::JumpIfNotLt
| Opcode::ForNPrep
| Opcode::ForNLoop
| Opcode::ForGLoop
| Opcode::ForGPrepInext
| Opcode::ForGPrepNext
| Opcode::ForGPrep
| Opcode::JumpXEqKNil
| Opcode::JumpXEqKB
| Opcode::JumpXEqKN
| Opcode::JumpXEqKS
| Opcode::CmpProto => Some(i32::from(self.d)),
Opcode::JumpX => Some(self.e),
Opcode::LoadB
| Opcode::FastCall
| Opcode::FastCall1
| Opcode::FastCall2
| Opcode::FastCall2K
| Opcode::FastCall3 => Some(i32::from(self.c)),
_ => None,
}
}
#[must_use]
pub fn jump_target_word(&self, instruction_word: u32) -> Option<i32> {
Some(instruction_word as i32 + 1 + self.jump_offset_words()?)
}
#[must_use]
pub fn capture_type(&self) -> Option<CaptureType> {
if self.opcode == Opcode::Capture {
CaptureType::from_byte(self.a)
} else {
None
}
}
#[must_use]
pub fn capture_source(&self) -> Option<u8> {
self.capture_type().map(|_| self.b)
}
#[must_use]
pub fn word_len(&self) -> u32 {
1 + u32::from(self.aux.is_some())
}
}
#[must_use]
pub fn code_word_count(code: &[Instruction]) -> u32 {
code.iter().map(Instruction::word_len).sum()
}
#[must_use]
pub fn instruction_word_offsets(code: &[Instruction]) -> Vec<u32> {
let mut next = 0u32;
code.iter()
.map(|instruction| {
let current = next;
next += instruction.word_len();
current
})
.collect()
}
#[must_use]
pub fn jump_target_instruction_index(
code: &[Instruction],
instruction_index: usize,
) -> Option<usize> {
let offsets = instruction_word_offsets(code);
let instruction = code.get(instruction_index)?;
let source_word = *offsets.get(instruction_index)?;
let target = instruction.jump_target_word(source_word)?;
offsets.iter().position(|word| *word as i32 == target)
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(tag = "kind", rename_all = "camelCase")]
pub enum Constant {
Nil,
Boolean {
value: bool,
},
Number {
bits: u64,
},
String {
string: u32,
},
Import {
import_id: u32,
},
Table {
keys: Vec<u32>,
},
Closure {
proto: u32,
},
Vector {
bits: [u32; 4],
},
TableWithConstants {
entries: Vec<TableEntry>,
},
Integer {
value: i64,
},
ClassShape {
shape: ClassShape,
},
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TableEntry {
pub key: u32,
pub value: i32,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ClassShape {
pub class_name: u32,
pub property_names: Vec<u32>,
pub method_names: Vec<u32>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LineInfo {
pub log2_span: u8,
pub delta_bytes: Vec<u8>,
pub baseline_deltas: Vec<i32>,
}
impl LineInfo {
#[must_use]
pub(crate) fn from_line_numbers(lines: &[i32]) -> Option<Self> {
if lines.is_empty() {
return None;
}
let mut span = 1usize << 24;
let mut offset = 0usize;
while offset < lines.len() {
let mut next = offset;
let mut min = lines[offset];
let mut max = lines[offset];
while next < lines.len() && next < offset + span {
min = min.min(lines[next]);
max = max.max(lines[next]);
if max - min > 255 {
break;
}
next += 1;
}
if next < lines.len() && next - offset < span {
span = 1usize << line_info_log2(next - offset);
}
offset += span;
}
let log2_span = line_info_log2(span) as u8;
let baseline_size = (lines.len() - 1) / span + 1;
let mut baselines = Vec::with_capacity(baseline_size);
for chunk in lines.chunks(span) {
baselines.push(*chunk.iter().min().expect("non-empty chunk"));
}
let mut delta_bytes = Vec::with_capacity(lines.len());
let mut last_offset = 0u8;
for (index, line) in lines.iter().enumerate() {
let baseline = baselines[index >> usize::from(log2_span)];
let delta = *line - baseline;
debug_assert!((0..=255).contains(&delta));
let delta = delta as u8;
delta_bytes.push(delta.wrapping_sub(last_offset));
last_offset = delta;
}
let mut baseline_deltas = Vec::with_capacity(baseline_size);
let mut last_line = 0;
for baseline in baselines {
baseline_deltas.push(baseline - last_line);
last_line = baseline;
}
Some(Self {
log2_span,
delta_bytes,
baseline_deltas,
})
}
#[must_use]
pub fn to_line_numbers(&self) -> Option<Vec<i32>> {
let mut baselines = Vec::with_capacity(self.baseline_deltas.len());
let mut baseline = 0i32;
for delta in &self.baseline_deltas {
baseline = baseline.wrapping_add(*delta);
baselines.push(baseline);
}
let mut lines = Vec::with_capacity(self.delta_bytes.len());
let mut last_offset = 0u8;
for (index, byte) in self.delta_bytes.iter().enumerate() {
let baseline = *baselines.get(index >> usize::from(self.log2_span))?;
let offset = last_offset.wrapping_add(*byte);
lines.push(baseline.wrapping_add(i32::from(offset)));
last_offset = offset;
}
Some(lines)
}
}
fn line_info_log2(value: usize) -> usize {
debug_assert!(value > 0);
let mut result = 0;
while value >= (2usize << result) {
result += 1;
}
result
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DebugInfo {
pub locals: Vec<DebugLocal>,
pub upvalues: Vec<u32>,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DebugLocal {
pub name: u32,
pub start_pc: u32,
pub end_pc: u32,
pub register: u8,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FeedbackSlot {
pub kind: FeedbackType,
pub pc: u32,
}
#[cfg(test)]
mod tests {
use super::{
CaptureType, Instruction, LineInfo, Opcode, instruction_word_offsets,
jump_target_instruction_index,
};
#[test]
fn jump_targets_are_word_relative() {
let jump_next = Instruction::ad(Opcode::Jump, 0, 0);
assert_eq!(jump_next.jump_offset_words(), Some(0));
assert_eq!(jump_next.jump_target_word(10), Some(11));
let jump_back = Instruction::ad(Opcode::JumpBack, 0, -3);
assert_eq!(jump_back.jump_target_word(10), Some(8));
let jump_x = Instruction::from_words(
Opcode::JumpX.byte() as u32 | ((-5_i32 as u32 & 0x00ff_ffff) << 8),
None,
)
.expect("jumpx");
assert_eq!(jump_x.jump_offset_words(), Some(-5));
assert_eq!(jump_x.jump_target_word(10), Some(6));
}
#[test]
fn jump_targets_count_aux_words() {
let compare = Instruction::abc_with_aux(Opcode::JumpIfEq, 0, 1, 0, Some(0));
assert_eq!(compare.jump_offset_words(), Some(1));
assert_eq!(compare.jump_target_word(4), Some(6));
let code = vec![
Instruction::ad(Opcode::LoadN, 0, 1),
compare,
Instruction::ad(Opcode::LoadN, 1, 2),
Instruction::abc(Opcode::Return, 0, 1, 0),
];
assert_eq!(instruction_word_offsets(&code), vec![0, 1, 3, 4]);
assert_eq!(jump_target_instruction_index(&code, 1), Some(2));
let compare_to_return = Instruction::abc_with_aux(Opcode::JumpIfEq, 0, 2, 0, Some(0));
let code = vec![
Instruction::ad(Opcode::LoadN, 0, 1),
compare_to_return,
Instruction::ad(Opcode::LoadN, 1, 2),
Instruction::abc(Opcode::Return, 0, 1, 0),
];
assert_eq!(jump_target_instruction_index(&code, 1), Some(3));
}
#[test]
fn short_jump_operands_are_exposed() {
let loadb = Instruction::abc(Opcode::LoadB, 0, 1, 2);
assert_eq!(loadb.jump_offset_words(), Some(2));
assert_eq!(loadb.jump_target_word(7), Some(10));
let fastcall = Instruction::abc(Opcode::FastCall2K, 18, 1, 3);
assert_eq!(fastcall.jump_offset_words(), Some(3));
assert_eq!(fastcall.jump_target_word(7), Some(11));
let not_a_jump = Instruction::ad(Opcode::LoadN, 0, 5);
assert_eq!(not_a_jump.jump_offset_words(), None);
assert_eq!(not_a_jump.jump_target_word(0), None);
}
#[test]
fn capture_operands_are_exposed() {
let by_value = Instruction::abc(Opcode::Capture, CaptureType::Val as u8, 3, 0);
assert_eq!(by_value.capture_type(), Some(CaptureType::Val));
assert_eq!(by_value.capture_source(), Some(3));
let by_reference = Instruction::abc(Opcode::Capture, CaptureType::Ref as u8, 4, 0);
assert_eq!(by_reference.capture_type(), Some(CaptureType::Ref));
assert_eq!(by_reference.capture_source(), Some(4));
let upvalue = Instruction::abc(Opcode::Capture, CaptureType::Upval as u8, 1, 0);
assert_eq!(upvalue.capture_type(), Some(CaptureType::Upval));
assert_eq!(upvalue.capture_source(), Some(1));
let invalid = Instruction::abc(Opcode::Capture, 99, 1, 0);
assert_eq!(invalid.capture_type(), None);
assert_eq!(invalid.capture_source(), None);
let not_capture = Instruction::ad(Opcode::LoadN, 0, 5);
assert_eq!(not_capture.capture_type(), None);
assert_eq!(not_capture.capture_source(), None);
}
#[test]
fn line_info_uses_large_span_when_deltas_fit() {
let line_info = LineInfo::from_line_numbers(&[10, 10, 20]).expect("line info");
assert_eq!(line_info.log2_span, 24);
assert_eq!(line_info.delta_bytes, vec![0, 0, 10]);
assert_eq!(line_info.baseline_deltas, vec![10]);
assert_eq!(
line_info.to_line_numbers().expect("line numbers"),
vec![10, 10, 20]
);
}
#[test]
fn line_info_shrinks_span_before_8_bit_delta_overflows() {
let lines = [1, 2, 300, 301, 302];
let line_info = LineInfo::from_line_numbers(&lines).expect("line info");
assert_eq!(line_info.log2_span, 1);
assert_eq!(line_info.delta_bytes, vec![0, 1, 255, 1, 255]);
assert_eq!(line_info.baseline_deltas, vec![1, 299, 2]);
assert_eq!(line_info.to_line_numbers().expect("line numbers"), lines);
}
}