feat(vm)!: implement typed callables and single-context execution
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good

Add structural Fn signatures, typed capture environments, indirect calls and Trait dispatch while preserving logical parameter and result groups, ownership and budgets.

Remove guest coroutine execution and legacy loading. Activate bounded sealed PBX v1 with mandatory capture metadata, preserve frame continuations and root return results, and migrate producers and shipped cartridges.

Publish coordinated specs, handoffs and the completed runtime lesson. Validation: 880 workspace tests passed, 9 existing tests ignored; both cartridges completed six production-host frames.
This commit is contained in:
2026-10-09 05:47:24 +01:00
parent 86bade3e1f
commit ec84a6bba5
96 changed files with 3656 additions and 6075 deletions
@@ -139,7 +139,49 @@ fn intrinsic_boundaries_reject_implicit_carrier_conversions_in_execution() {
"PUSH_I64 1\nPUSH_F64 f64:0x4000000000000000\nINTRINSIC 0x1001", // Float/Float required
"PUSH_I64 -1\nINTRINSIC 0x1106", // out-of-range color
] {
let mut vm = VirtualMachine::new(assemble(source).unwrap(), vec![]);
let bytes = prometeu_test_support::program::TestProgram::single(
assemble(&(source.to_string() + "\nHALT")).unwrap(),
Default::default(),
0,
8,
)
.serialize();
let known = prometeu_vm::ValidatedProgramImage::load(
&bytes,
&mut prometeu_bytecode::load_limits::LoadBudget::new(Default::default()),
0,
);
if let Err(error) = known {
assert!(
matches!(error,prometeu_vm::VmInitError::RegistryLoadFailed(e) if e.code==prometeu_bytecode::load_limits::LoadCode::InvalidCode && e.reason==prometeu_bytecode::load_limits::LoadReason::TypeMismatch)
);
}
// Globals deliberately hide the concrete carrier from static facts;
// the same rejected values must still fault at the runtime boundary.
let lines: Vec<_> = source.lines().collect();
let mut unknown = String::new();
for (i, line) in lines[..lines.len() - 1].iter().enumerate() {
unknown.push_str(&format!("{line}\nSET_GLOBAL {i}\n"));
}
for i in 0..lines.len() - 1 {
unknown.push_str(&format!("GET_GLOBAL {i}\n"));
}
unknown.push_str(lines.last().unwrap());
unknown.push_str("\nHALT");
let bytes = prometeu_test_support::program::TestProgram::single(
assemble(&unknown).unwrap(),
Default::default(),
0,
8,
)
.serialize();
let image = prometeu_vm::ValidatedProgramImage::load(
&bytes,
&mut prometeu_bytecode::load_limits::LoadBudget::new(Default::default()),
0,
)
.unwrap();
let mut vm = VirtualMachine::from_image(image, Default::default());
vm.prepare_call("0").expect("prepare entry call");
let report = vm.run_budget(100, &mut NoSyscalls, &mut HostContext::new(None)).unwrap();
assert!(
@@ -45,6 +45,7 @@ fn named_arguments_preserve_source_effect_order_and_call_in_signature_order_with
vec![]
};
functions.push(FunctionDecl {
captures: vec![],
name: Some(["main", "effectX", "effectY", "combine"][index].into()),
signature: Signature {
parameters,
@@ -6,18 +6,19 @@ use prometeu_vm::{
resource_budget::{RuntimeLimits, RuntimeResource},
};
// Independent executable oracle: 32-byte header, seven directory entries,
// payload at 116, one Bool import, one zero-slot HALT function; total 173.
// Independent executable oracle: 32-byte header, eight directory entries,
// payload at 128, one Bool import, one zero-slot HALT function; total 193.
fn minimal() -> Vec<u8> {
"50 42 58 00 01 00 00 00 07 00 00 00
"50 42 58 00 01 00 00 00 08 00 00 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 74 00 00 00 04 00 00 00
01 00 00 00 78 00 00 00 1d 00 00 00
02 00 00 00 95 00 00 00 02 00 00 00
04 00 00 00 97 00 00 00 04 00 00 00
05 00 00 00 9b 00 00 00 04 00 00 00
06 00 00 00 9f 00 00 00 0a 00 00 00
07 00 00 00 a9 00 00 00 04 00 00 00
00 00 00 00 80 00 00 00 04 00 00 00
01 00 00 00 84 00 00 00 1d 00 00 00
02 00 00 00 a1 00 00 00 02 00 00 00
04 00 00 00 a3 00 00 00 04 00 00 00
05 00 00 00 a7 00 00 00 04 00 00 00
06 00 00 00 ab 00 00 00 0a 00 00 00
07 00 00 00 b5 00 00 00 04 00 00 00
08 00 00 00 b9 00 00 00 08 00 00 00
00 00 00 00
01 00 00 00 00 00 00 00 00 00 00 00 00
00 00 00 00 02 00 00 00 00 00 00 00 00 00 00 00
@@ -25,7 +26,8 @@ fn minimal() -> Vec<u8> {
00 00 00 00
00 00 00 00
01 00 00 00 00 00 13 00 00 00
00 00 00 00"
00 00 00 00
01 00 00 00 00 00 00 00"
.split_whitespace()
.map(|byte| u8::from_str_radix(byte, 16).unwrap())
.collect()
@@ -46,7 +48,7 @@ impl NativeInterface for Native {
#[test]
fn independent_v1_bytes_load_publish_and_execute_through_the_public_sealed_boundary() {
let bytes = minimal();
assert_eq!(bytes.len(), 173);
assert_eq!(bytes.len(), 193);
let mut load = LoadBudget::new(Default::default());
let image = ValidatedProgramImage::load(&bytes, &mut load, caps::NONE).unwrap();
assert_eq!(load.used(LoadResource::TemporaryBytes), 0);
@@ -63,9 +65,9 @@ fn independent_v1_bytes_load_publish_and_execute_through_the_public_sealed_bound
fn single_violation_oracles_reject_before_image_publication_with_typed_context() {
for (offset, replacement, code, reason, pc) in [
(4, 0, LoadCode::UnsupportedFormat, LoadReason::Version, None),
(165, 0, LoadCode::UnsupportedFormat, LoadReason::Builtin, None),
(149, 0xff, LoadCode::InvalidCode, LoadReason::UnknownOpcode, Some(0)),
(149, 0x11, LoadCode::InvalidCode, LoadReason::StackUnderflow, Some(0)),
(177, 0, LoadCode::UnsupportedFormat, LoadReason::Builtin, None),
(161, 0xff, LoadCode::InvalidCode, LoadReason::UnknownOpcode, Some(0)),
(161, 0x11, LoadCode::InvalidCode, LoadReason::StackUnderflow, Some(0)),
] {
let mut bytes = minimal();
bytes[offset] = replacement;
+2 -2
View File
@@ -10,10 +10,10 @@ use prometeu_vm::VirtualMachine;
#[test]
fn vm_instantiation_is_stable() {
// Create a VM with empty ROM and empty constant pool.
let vm = VirtualMachine::new(vec![], vec![]);
let vm = VirtualMachine::default();
// Basic invariant checks that should remain stable across refactors.
assert_eq!(vm.pc(), 0);
assert!(!vm.is_halted());
assert!(vm.is_halted());
}
#[test]
@@ -0,0 +1,127 @@
use prometeu_bytecode::Value;
use prometeu_bytecode::assembler::assemble;
use prometeu_bytecode::load_limits::LoadBudget;
use prometeu_bytecode::registry::*;
use prometeu_bytecode::registry_codec::PbxModule;
use prometeu_hal::syscalls::caps;
use prometeu_hal::vm_fault::VmFault;
use prometeu_hal::{HostContext, HostReturn, NativeInterface};
use prometeu_vm::resource_budget::RuntimeLimits;
use prometeu_vm::{ValidatedProgramImage, VirtualMachine, VmInitError};
pub struct Native;
impl NativeInterface for Native {
fn syscall(
&mut self,
_: u32,
_: &[Value],
_: &mut HostReturn,
_: &mut HostContext,
) -> Result<(), VmFault> {
panic!("no syscall in callable fixtures")
}
}
pub fn param(id: u32) -> NamedType {
NamedType { type_id: TypeId(id), name: None }
}
pub fn sig(parameters: &[u32], results: &[u32]) -> Signature {
Signature {
parameters: parameters.iter().map(|&i| param(i)).collect(),
results: results.iter().map(|&i| TypeId(i)).collect(),
}
}
pub fn types() -> Vec<TypeDecl> {
vec![
TypeKind::Builtin(BuiltinId::INT32),
TypeKind::Builtin(BuiltinId::FLOAT),
TypeKind::Builtin(BuiltinId::VEC2),
TypeKind::Builtin(BuiltinId::STRING),
TypeKind::Fn(sig(&[], &[0])),
TypeKind::Struct(vec![param(0)]),
TypeKind::Fn(sig(&[], &[4, 4])),
TypeKind::Trait(vec![MethodDecl { name: None, signature: sig(&[], &[0]) }]),
TypeKind::Struct(vec![param(0)]),
TypeKind::Fn(sig(&[], &[])),
TypeKind::Array(TypeId(4)),
TypeKind::Builtin(BuiltinId::DYNAMIC),
TypeKind::Fn(sig(&[2], &[2])),
TypeKind::Fn(sig(&[], &[2])),
TypeKind::Fn(sig(&[], &[1, 1])),
TypeKind::Struct(vec![param(4)]),
TypeKind::Fn(sig(&[], &[3])),
TypeKind::Fn(sig(&[], &[7, 11, 3, 2])),
TypeKind::Fn(sig(&[4], &[4])),
]
.into_iter()
.map(|kind| TypeDecl { name: None, kind })
.collect()
}
pub fn image(
bodies: &[(&str, Signature, Vec<TypeId>)],
implementations: Vec<ImplementationDecl>,
) -> Result<std::sync::Arc<ValidatedProgramImage>, VmInitError> {
image_constants(bodies, implementations, &[])
}
pub fn image_constants(
bodies: &[(&str, Signature, Vec<TypeId>)],
implementations: Vec<ImplementationDecl>,
constants: &[prometeu_bytecode::model::ConstantPoolEntry],
) -> Result<std::sync::Arc<ValidatedProgramImage>, VmInitError> {
let bytes = bytes(bodies, implementations, constants)?;
ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(Default::default()), caps::NONE)
}
pub fn bytes(
bodies: &[(&str, Signature, Vec<TypeId>)],
implementations: Vec<ImplementationDecl>,
constants: &[prometeu_bytecode::model::ConstantPoolEntry],
) -> Result<Vec<u8>, prometeu_bytecode::load_limits::LoadFailure> {
bytes_with_syscalls(bodies, implementations, constants, &[])
}
pub fn bytes_with_syscalls(
bodies: &[(&str, Signature, Vec<TypeId>)],
implementations: Vec<ImplementationDecl>,
constants: &[prometeu_bytecode::model::ConstantPoolEntry],
syscalls: &[prometeu_bytecode::model::SyscallDecl],
) -> Result<Vec<u8>, prometeu_bytecode::load_limits::LoadFailure> {
let mut code = vec![];
let mut functions = vec![];
for (source, signature, captures) in bodies {
let body = assemble(source).unwrap();
functions.push(FunctionDecl {
signature: signature.clone(),
captures: captures.clone(),
code_offset: code.len() as u32,
code_len: body.len() as u32,
local_slots: 4,
max_stack_slots: 32,
..Default::default()
});
code.extend(body);
}
let mut budget = LoadBudget::new(Default::default());
let registry = Registry::resolve(
RegistryDeclarations { types: types(), functions, implementations },
code.len(),
&mut budget,
)?;
let bytes = PbxModule {
registry: &registry,
constants,
code: &code,
debug: None,
exports: &[],
syscalls,
}
.serialize(&mut budget)?;
Ok(bytes)
}
pub fn vm(bodies: &[(&str, Signature, Vec<TypeId>)]) -> VirtualMachine {
let mut vm =
VirtualMachine::from_image(image(bodies, vec![]).unwrap(), RuntimeLimits::default());
vm.prepare_boot_call().unwrap();
vm
}
pub fn run(vm: &mut VirtualMachine, budget: u64) -> prometeu_vm::BudgetReport {
vm.run_budget(budget, &mut Native, &mut HostContext::new(None)).unwrap()
}
@@ -1,45 +1,21 @@
//! Regression test: input is no longer exposed through the syscall registry.
use prometeu_bytecode::isa::core::CoreOpCode as OpCode;
use prometeu_hal::vm_fault::VmFault;
use prometeu_vm::{HostContext, HostReturn, NativeInterface, VirtualMachine};
fn enc_op(op: OpCode) -> [u8; 2] {
(op as u16).to_le_bytes()
}
//! Removed native IDs cannot enter the sealed execution path.
use prometeu_bytecode::assemble;
use prometeu_test_support::program::{TestProgram, int64_signature};
use prometeu_vm::{LoaderPatchError, ValidatedProgramImage, VmInitError};
#[test]
fn vm_rejects_legacy_input_syscall_id() {
// Legacy input syscall id (PadGetUp) must now be rejected as unknown syscall.
let mut rom = Vec::new();
rom.extend_from_slice(&enc_op(OpCode::Syscall));
rom.extend_from_slice(&0x2200u32.to_le_bytes());
rom.extend_from_slice(&enc_op(OpCode::Halt));
struct NoopNative;
impl NativeInterface for NoopNative {
fn syscall(
&mut self,
_id: u32,
_args: &[prometeu_bytecode::Value],
_ret: &mut HostReturn,
_ctx: &mut HostContext,
) -> Result<(), VmFault> {
Ok(())
}
}
let mut vm = VirtualMachine::new(rom, vec![]);
let mut native = NoopNative;
let mut ctx = HostContext::new(None);
vm.prepare_call("0").expect("prepare entry call");
vm.set_capabilities(prometeu_hal::syscalls::caps::ALL);
let report = vm.run_budget(100, &mut native, &mut ctx).expect("VM run failed");
match report.reason {
prometeu_vm::LogicalFrameEndingReason::Trap(trap) => {
assert_eq!(trap.code, prometeu_bytecode::TRAP_INVALID_SYSCALL);
assert!(trap.message.contains("Unknown syscall"));
}
other => panic!("Expected invalid syscall trap, got {:?}", other),
}
fn loader_rejects_legacy_input_syscall_id() {
let bytes =
TestProgram::single(assemble("SYSCALL 0x2200\nHALT").unwrap(), int64_signature(0, 0), 0, 4)
.serialize();
assert!(matches!(
ValidatedProgramImage::load(
&bytes,
&mut prometeu_bytecode::load_limits::LoadBudget::new(Default::default()),
0
),
Err(VmInitError::LoaderPatchFailed(LoaderPatchError::RawSyscallInPreloadArtifact {
syscall_id: 0x2200,
..
}))
));
}
@@ -0,0 +1,246 @@
mod support {
pub mod callables;
}
use prometeu_bytecode::{
Value,
load_limits::{LoadCode, LoadReason},
registry::*,
};
use prometeu_vm::{
LogicalFrameEndingReason, VirtualMachine, VmInitError,
resource_budget::{RuntimeLimits, RuntimeResource},
};
use support::callables::*;
#[test]
fn captures_are_not_public_parameters_and_survive_creator_return() {
let mut vm = vm(&[
("CALL 1\nSET_GLOBAL 0\nGET_GLOBAL 0\nCALL_CLOSURE 4\nRET", sig(&[], &[0]), vec![]),
("PUSH_I32 42\nMAKE_CLOSURE fn=2,type=4\nRET", sig(&[], &[4]), vec![]),
("GET_CAPTURE 0\nRET", sig(&[], &[0]), vec![TypeId(0)]),
]);
assert_eq!(run(&mut vm, 1000).reason, LogicalFrameEndingReason::EndOfRom);
assert_eq!(vm.operand_stack_top(1).to_vec(), vec![Value::Int32(42)]);
}
#[test]
fn factory_returns_two_callbacks_sharing_a_mutable_cell() {
let factory = "STRUCT_NEW 5\nSET_LOCAL 0\nGET_LOCAL 0\nMAKE_CLOSURE fn=2,type=4\nGET_LOCAL 0\nMAKE_CLOSURE fn=3,type=4\nRET";
let increment = "GET_CAPTURE 0\nDUP\nSTRUCT_GET type=5,field=0\nPUSH_I32 1\nADD\nSTRUCT_SET type=5,field=0\nGET_CAPTURE 0\nSTRUCT_GET type=5,field=0\nRET";
let mut vm = vm(&[
(
"CALL 1\nSET_GLOBAL 1\nSET_GLOBAL 0\nGET_GLOBAL 0\nCALL_CLOSURE 4\nPOP\nGET_GLOBAL 0\nCALL_CLOSURE 4\nPOP\nGET_GLOBAL 1\nCALL_CLOSURE 4\nRET",
sig(&[], &[0]),
vec![],
),
(factory, sig(&[], &[4, 4]), vec![]),
(increment, sig(&[], &[0]), vec![TypeId(5)]),
("GET_CAPTURE 0\nSTRUCT_GET type=5,field=0\nRET", sig(&[], &[0]), vec![TypeId(5)]),
]);
assert_eq!(run(&mut vm, 10000).reason, LogicalFrameEndingReason::EndOfRom);
assert_eq!(vm.operand_stack_top(1).to_vec(), vec![Value::Int32(2)]);
}
#[test]
fn independent_factories_do_not_share_mutable_cells() {
let factory = "STRUCT_NEW 5\nSET_LOCAL 0\nGET_LOCAL 0\nMAKE_CLOSURE fn=2,type=4\nGET_LOCAL 0\nMAKE_CLOSURE fn=3,type=4\nRET";
let increment = "GET_CAPTURE 0\nDUP\nSTRUCT_GET type=5,field=0\nPUSH_I32 1\nADD\nSTRUCT_SET type=5,field=0\nGET_CAPTURE 0\nSTRUCT_GET type=5,field=0\nRET";
let root = "CALL 1\nSET_GLOBAL 1\nSET_GLOBAL 0\nCALL 1\nSET_GLOBAL 3\nSET_GLOBAL 2\nGET_GLOBAL 0\nCALL_CLOSURE 4\nPOP\nGET_GLOBAL 1\nCALL_CLOSURE 4\nGET_GLOBAL 3\nCALL_CLOSURE 4\nRET";
let mut v = vm(&[
(root, sig(&[], &[0, 0]), vec![]),
(factory, sig(&[], &[4, 4]), vec![]),
(increment, sig(&[], &[0]), vec![TypeId(5)]),
("GET_CAPTURE 0\nSTRUCT_GET type=5,field=0\nRET", sig(&[], &[0]), vec![TypeId(5)]),
]);
assert_eq!(run(&mut v, 1000).reason, LogicalFrameEndingReason::EndOfRom);
assert_eq!(v.operand_stack_top(2), vec![Value::Int32(0), Value::Int32(1)]);
}
#[test]
fn captured_direct_calls_and_invalid_capture_indices_reject_at_load() {
for (root, body, captures, reason) in [
("CALL 1\nRET", "GET_CAPTURE 0\nRET", vec![TypeId(0)], LoadReason::CapturedDirectCall),
(
"PUSH_I32 1\nMAKE_CLOSURE fn=1,type=4\nCALL_CLOSURE 4\nRET",
"GET_CAPTURE 1\nRET",
vec![TypeId(0)],
LoadReason::CaptureIndex,
),
] {
assert!(
matches!(image(&[(root,sig(&[],&[0]),vec![]),(body,sig(&[],&[0]),captures)],vec![]),Err(VmInitError::RegistryLoadFailed(e)) if e.reason==reason)
);
}
}
#[test]
fn host_cannot_prepare_a_capturing_body_or_capturant_trait_implementation() {
let image = image(
&[("RET", sig(&[], &[]), vec![]), ("GET_CAPTURE 0\nRET", sig(&[], &[0]), vec![TypeId(0)])],
vec![],
)
.unwrap();
let mut v = VirtualMachine::from_image(image, Default::default());
assert!(
matches!(v.prepare_call("1"),Err(VmInitError::RegistryLoadFailed(e)) if e.code==LoadCode::InvalidEntrypoint && e.reason==LoadReason::CapturedDirectCall)
);
let result = support::callables::image(
&[("RET", sig(&[], &[]), vec![]), ("GET_CAPTURE 0\nRET", sig(&[5], &[0]), vec![TypeId(0)])],
vec![ImplementationDecl {
owner: TypeId(5),
trait_id: TypeId(7),
methods: vec![FunctionId(1)],
}],
);
assert!(
matches!(result,Err(VmInitError::RegistryLoadFailed(e)) if e.code==LoadCode::InvalidRegistry && e.reason==LoadReason::CapturedDirectCall)
);
}
#[test]
fn sync_and_gc_retain_active_frame_environment_after_fn_operand_is_consumed() {
let mut body = "MAKE_CLOSURE fn=2,type=4\nPOP\n".repeat(1030);
body.push_str("FRAME_SYNC\nGET_CAPTURE 0\nRET");
let mut vm = vm(&[
("PUSH_I32 73\nMAKE_CLOSURE fn=1,type=4\nCALL_CLOSURE 4\nRET", sig(&[], &[0]), vec![]),
(&body, sig(&[], &[0]), vec![TypeId(0)]),
("PUSH_I32 1\nRET", sig(&[], &[0]), vec![]),
]);
assert_eq!(run(&mut vm, 100000).reason, LogicalFrameEndingReason::FrameSync);
assert_eq!(vm.heap().len(), 1);
assert!(!vm.call_stack_is_empty());
assert_eq!(run(&mut vm, 1000).reason, LogicalFrameEndingReason::EndOfRom);
assert_eq!(vm.operand_stack_top(1).to_vec(), vec![Value::Int32(73)]);
}
#[test]
fn recurring_roots_use_no_heap_execution_objects_or_handle_quota() {
let image = image(&[("RET", sig(&[], &[]), vec![])], vec![]).unwrap();
let limits = RuntimeLimits::default().lowered(RuntimeResource::HandleSlots, 0).unwrap();
let mut vm = VirtualMachine::from_image(image, limits);
for _ in 0..3000 {
vm.prepare_boot_call().unwrap();
assert_eq!(run(&mut vm, 20).reason, LogicalFrameEndingReason::EndOfRom);
}
assert_eq!(vm.heap().allocation_count(), 0);
assert_eq!(vm.heap().len(), 0);
}
#[test]
fn logical_result_groups_distinguish_equal_width_signatures_at_load() {
let result = image(
&[
("MAKE_CLOSURE fn=1,type=14\nPOP\nRET", sig(&[], &[]), vec![]),
(
"PUSH_F64 f64:0x3ff0000000000000\nPUSH_F64 f64:0x4000000000000000\nRET",
sig(&[], &[2]),
vec![],
),
],
vec![],
);
assert!(
matches!(result,Err(VmInitError::RegistryLoadFailed(e)) if e.code==LoadCode::InvalidCode && e.reason==LoadReason::Signature)
);
}
#[test]
fn trait_dispatch_selects_exact_receiver_first_implementation() {
let bodies = [
(
"STRUCT_NEW 5\nREF_TO_TRAIT source=5,target=7\nCALL_TRAIT type=7,method=0\nSTRUCT_NEW 8\nREF_TO_TRAIT source=8,target=7\nCALL_TRAIT type=7,method=0\nADD\nRET",
sig(&[], &[0]),
vec![],
),
("PUSH_I32 10\nRET", sig(&[5], &[0]), vec![]),
("PUSH_I32 20\nRET", sig(&[8], &[0]), vec![]),
];
let impls = vec![
ImplementationDecl { owner: TypeId(5), trait_id: TypeId(7), methods: vec![FunctionId(1)] },
ImplementationDecl { owner: TypeId(8), trait_id: TypeId(7), methods: vec![FunctionId(2)] },
];
let mut vm =
VirtualMachine::from_image(image(&bodies, impls).unwrap(), RuntimeLimits::default());
vm.prepare_boot_call().unwrap();
assert_eq!(run(&mut vm, 1000).reason, LogicalFrameEndingReason::EndOfRom);
assert_eq!(vm.operand_stack_top(1).to_vec(), vec![Value::Int32(30)]);
}
#[test]
fn fn_survives_struct_array_dynamic_storage_and_pass_return() {
let source = "STRUCT_NEW 15\nSET_LOCAL 0\nGET_LOCAL 0\nMAKE_CLOSURE fn=2,type=4\nSTRUCT_SET type=15,field=0\nPUSH_I64 1\nARRAY_NEW 10\nSET_LOCAL 1\nGET_LOCAL 1\nPUSH_I64 0\nGET_LOCAL 0\nSTRUCT_GET type=15,field=0\nARRAY_SET 10\nGET_LOCAL 1\nPUSH_I64 0\nARRAY_GET 10\nDYN_PACK 4\nDYN_UNPACK 4\nCALL 1\nCALL_CLOSURE 4\nRET";
let mut v = vm(&[
(source, sig(&[], &[0]), vec![]),
("GET_LOCAL 0\nRET", sig(&[4], &[4]), vec![]),
("PUSH_I32 81\nRET", sig(&[], &[0]), vec![]),
]);
assert_eq!(run(&mut v, 1000).reason, LogicalFrameEndingReason::EndOfRom);
assert_eq!(v.operand_stack_top(1), vec![Value::Int32(81)]);
}
#[test]
fn branch_selects_unknown_concrete_target_under_one_signature() {
for selected in [false, true] {
let mut code = prometeu_bytecode::assemble(&format!(
"PUSH_BOOL {}\nJMP_IF_FALSE 0\nMAKE_CLOSURE fn=1,type=4\nJMP 0",
u8::from(selected)
))
.unwrap();
let otherwise = code.len() as u32;
code.extend(prometeu_bytecode::assemble("MAKE_CLOSURE fn=2,type=4").unwrap());
let join = code.len() as u32;
code.extend(prometeu_bytecode::assemble("CALL_CLOSURE 4\nRET").unwrap());
code[5..9].copy_from_slice(&otherwise.to_le_bytes());
code[21..25].copy_from_slice(&join.to_le_bytes());
let source = prometeu_bytecode::disassemble(&code).unwrap();
let mut v = vm(&[
(&source, sig(&[], &[0]), vec![]),
("PUSH_I32 12\nRET", sig(&[], &[0]), vec![]),
("PUSH_I32 34\nRET", sig(&[], &[0]), vec![]),
]);
assert_eq!(run(&mut v, 1000).reason, LogicalFrameEndingReason::EndOfRom);
assert_eq!(v.operand_stack_top(1), vec![Value::Int32(if selected { 12 } else { 34 })]);
}
}
#[test]
fn bound_trait_receiver_adapter_keeps_view_in_capture_environment() {
let bodies = [
(
"STRUCT_NEW 5\nREF_TO_TRAIT source=5,target=7\nMAKE_CLOSURE fn=2,type=4\nCALL_CLOSURE 4\nRET",
sig(&[], &[0]),
vec![],
),
("PUSH_I32 91\nRET", sig(&[5], &[0]), vec![]),
("GET_CAPTURE 0\nCALL_TRAIT type=7,method=0\nRET", sig(&[], &[0]), vec![TypeId(7)]),
];
let implementation =
ImplementationDecl { owner: TypeId(5), trait_id: TypeId(7), methods: vec![FunctionId(1)] };
let mut v = VirtualMachine::from_image(
image(&bodies, vec![implementation]).unwrap(),
Default::default(),
);
v.prepare_boot_call().unwrap();
assert_eq!(run(&mut v, 1000).reason, LogicalFrameEndingReason::EndOfRom);
assert_eq!(v.operand_stack_top(1), vec![Value::Int32(91)]);
}
#[test]
fn native_string_capture_survives_factory_return() {
let bodies = [
("CALL 1\nCALL_CLOSURE 16\nRET", sig(&[], &[3]), vec![]),
("PUSH_CONST 0\nMAKE_CLOSURE fn=2,type=16\nRET", sig(&[], &[16]), vec![]),
("GET_CAPTURE 0\nRET", sig(&[], &[3]), vec![TypeId(3)]),
];
let mut v = VirtualMachine::from_image(
image_constants(
&bodies,
vec![],
&[prometeu_bytecode::model::ConstantPoolEntry::String("escaped owner".into())],
)
.unwrap(),
Default::default(),
);
v.prepare_boot_call().unwrap();
assert_eq!(run(&mut v, 1000).reason, LogicalFrameEndingReason::EndOfRom);
assert_eq!(v.operand_stack_top(1), vec![Value::string("escaped owner")]);
}