refactor: extract core objects into a standalone package
Verify databases and deploy Aster VM / verify-and-deploy (push) Successful in 7m34s

This commit is contained in:
2026-10-19 13:33:24 +08:00
parent 78fc859825
commit f77b8370ea
40 changed files with 631 additions and 202 deletions
+246
View File
@@ -0,0 +1,246 @@
use crate::{CompareOp, VmError};
/// Endor wordcode, following CPython's opcode/oparg code-unit design.
/// Numeric opcode IDs are Endor's own, not a CPython bytecode ABI.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum Opcode {
Nop = 0,
LoadConst = 1,
LoadFast = 2,
StoreFast = 3,
DeleteFast = 4,
LoadGlobal = 5,
StoreGlobal = 6,
DeleteGlobal = 7,
PopTop = 8,
Copy = 9,
Swap = 10,
PushNull = 11,
Call = 12,
ReturnValue = 13,
JumpForward = 14,
JumpBackward = 15,
PopJumpIfFalse = 16,
PopJumpIfTrue = 17,
ToBool = 18,
UnaryNot = 19,
CompareOp = 20,
LoadDeref = 21,
StoreDeref = 22,
DeleteDeref = 23,
LoadClosure = 24,
LoadAttr = 25,
StoreAttr = 26,
BuildMap = 27,
MakeFunction = 28,
ExtendedArg = 255,
}
impl Opcode {
fn decode(byte: u8) -> Option<Self> {
Some(match byte {
0 => Self::Nop,
1 => Self::LoadConst,
2 => Self::LoadFast,
3 => Self::StoreFast,
4 => Self::DeleteFast,
5 => Self::LoadGlobal,
6 => Self::StoreGlobal,
7 => Self::DeleteGlobal,
8 => Self::PopTop,
9 => Self::Copy,
10 => Self::Swap,
11 => Self::PushNull,
12 => Self::Call,
13 => Self::ReturnValue,
14 => Self::JumpForward,
15 => Self::JumpBackward,
16 => Self::PopJumpIfFalse,
17 => Self::PopJumpIfTrue,
18 => Self::ToBool,
19 => Self::UnaryNot,
20 => Self::CompareOp,
21 => Self::LoadDeref,
22 => Self::StoreDeref,
23 => Self::DeleteDeref,
24 => Self::LoadClosure,
25 => Self::LoadAttr,
26 => Self::StoreAttr,
27 => Self::BuildMap,
28 => Self::MakeFunction,
255 => Self::ExtendedArg,
_ => return None,
})
}
pub(crate) fn takes_argument(self) -> bool {
!matches!(
self,
Self::Nop
| Self::PopTop
| Self::PushNull
| Self::ReturnValue
| Self::ToBool
| Self::UnaryNot
)
}
}
/// A decoded logical instruction; EXTENDED_ARG is handled by the codec.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Instruction {
pub opcode: Opcode,
pub argument: u32,
}
impl Instruction {
pub const fn new(opcode: Opcode, argument: u32) -> Self {
Self { opcode, argument }
}
pub const fn simple(opcode: Opcode) -> Self {
Self::new(opcode, 0)
}
/// Build a function from [defaults..., closure cells..., code] on the stack.
/// The low 16 operand bits count trailing positional defaults; the high
/// 16 bits count cells in the code's free-variable order. No tuples or
/// subsequent mutation of the function object are required.
pub const fn make_function(defaults: u16, closure: u16) -> Self {
Self::new(
Opcode::MakeFunction,
(defaults as u32) | ((closure as u32) << 16),
)
}
pub const fn compare(operation: CompareOp) -> Self {
Self::new(
Opcode::CompareOp,
match operation {
CompareOp::Lt => 0,
CompareOp::Le => 1,
CompareOp::Eq => 2,
CompareOp::Ne => 3,
CompareOp::Gt => 4,
CompareOp::Ge => 5,
},
)
}
/// Decode a comparison operand; None denotes an invalid operand.
pub fn compare_operation(argument: u32) -> Option<CompareOp> {
compare_operation(argument)
}
/// Decode the default-value and closure-cell counts of MAKE_FUNCTION.
pub fn function_counts(argument: u32) -> (usize, usize) {
function_counts(argument)
}
/// Encodes 8-bit operands directly and prefixes up to three EXTENDED_ARG
/// code units for larger operands. Each code unit is [opcode, operand].
pub fn encode_all(instructions: &[Self]) -> Result<Vec<u8>, VmError> {
let mut bytes = Vec::new();
for instruction in instructions {
if instruction.opcode == Opcode::ExtendedArg {
return Err(invalid(0, "EXTENDED_ARG is emitted by the encoder"));
}
if !instruction.opcode.takes_argument() && instruction.argument != 0 {
return Err(invalid(bytes.len() / 2, "unexpected instruction operand"));
}
let parts = instruction.argument.to_be_bytes();
let first = parts.iter().position(|part| *part != 0).unwrap_or(3);
for part in &parts[first..3] {
bytes.extend([Opcode::ExtendedArg as u8, *part]);
}
bytes.extend([instruction.opcode as u8, parts[3]]);
}
Ok(bytes)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DecodedInstruction {
/// Offsets count two-byte code units, including EXTENDED_ARG prefixes.
pub offset: usize,
pub next_offset: usize,
pub instruction: Instruction,
}
impl DecodedInstruction {
/// Resolve a jump relative to the end of this logical instruction.
pub fn jump_target(self) -> Result<usize, VmError> {
if !matches!(
self.instruction.opcode,
Opcode::JumpForward
| Opcode::JumpBackward
| Opcode::PopJumpIfFalse
| Opcode::PopJumpIfTrue
) {
return Err(invalid(self.offset, "instruction is not a jump"));
}
crate::code::jump_target(self)
}
}
pub(crate) fn decode(bytes: &[u8]) -> Result<Vec<DecodedInstruction>, VmError> {
if bytes.is_empty() || !bytes.len().is_multiple_of(2) {
return Err(invalid(
0,
"wordcode must contain complete two-byte code units",
));
}
let mut instructions = Vec::new();
let mut cursor = 0;
while cursor < bytes.len() {
let start = cursor / 2;
let mut argument = 0_u32;
let mut prefixes = 0;
loop {
if cursor >= bytes.len() {
return Err(invalid(start, "dangling EXTENDED_ARG"));
}
let opcode = Opcode::decode(bytes[cursor])
.ok_or_else(|| invalid(cursor / 2, "unknown opcode"))?;
argument = (argument << 8) | u32::from(bytes[cursor + 1]);
cursor += 2;
if opcode == Opcode::ExtendedArg {
prefixes += 1;
if prefixes > 3 {
return Err(invalid(start, "too many EXTENDED_ARG prefixes"));
}
continue;
}
if !opcode.takes_argument() && (argument != 0 || prefixes != 0) {
return Err(invalid(start, "unexpected instruction operand"));
}
instructions.push(DecodedInstruction {
offset: start,
next_offset: cursor / 2,
instruction: Instruction::new(opcode, argument),
});
break;
}
}
Ok(instructions)
}
pub(crate) fn compare_operation(argument: u32) -> Option<CompareOp> {
Some(match argument {
0 => CompareOp::Lt,
1 => CompareOp::Le,
2 => CompareOp::Eq,
3 => CompareOp::Ne,
4 => CompareOp::Gt,
5 => CompareOp::Ge,
_ => return None,
})
}
pub(crate) fn function_counts(argument: u32) -> (usize, usize) {
((argument & 0xffff) as usize, (argument >> 16) as usize)
}
pub(crate) fn invalid(offset: usize, reason: &'static str) -> VmError {
VmError::InvalidBytecode { offset, reason }
}