feat(verifier): add conservative type flow for PLN-0176 step 25

This commit is contained in:
2026-10-07 19:09:37 +01:00
parent 8d32fef65c
commit 01112da951
5 changed files with 1129 additions and 52 deletions
@@ -78,6 +78,7 @@ pub enum LoadReason {
UnknownClosureCallee,
NotClosure,
InvalidYield,
TypeMismatch,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(usize)]
@@ -214,3 +214,6 @@ mod heights;
// The executable v1 loader is the pending production consumer.
#[allow(unused_imports)]
pub(crate) use heights::validate_registry_stacks;
mod types;
#[allow(unused_imports)]
pub(crate) use types::validate_registry_types;
@@ -9,11 +9,11 @@ enum Fact {
NonClosure,
Closure(u32),
}
struct Block {
start: usize,
end: usize,
state: Option<Vec<Fact>>,
queued: bool,
pub(super) struct Block<F> {
pub start: usize,
pub end: usize,
pub state: Option<Vec<F>>,
pub queued: bool,
}
pub(crate) fn validate_registry_stacks(
@@ -65,45 +65,9 @@ fn analyze(
};
}
// A dense leader map is bounded by code bytes. States are retained at
// basic-block entries, so a long straight-line program needs one state,
// rather than one full frame snapshot per instruction.
let mut leaders = scratch::<u8>(body.len() + 1, budget)?;
budget.work(body.len() + 2)?;
leaders.resize(body.len() + 1, 0);
leaders[0] = 1;
let mut pc = 0;
while pc < body.len() {
*at_pc = pc;
let instruction = metered_decode(pc, body, budget)?;
let spec = instruction.opcode.spec();
if spec.is_branch {
budget.work(1)?;
leaders[instruction.imm_u32().unwrap() as usize] = 1;
}
if spec.is_branch || spec.is_terminator {
budget.work(1)?;
leaders[instruction.next_pc] = 1;
}
pc = instruction.next_pc;
}
budget.work(body.len())?;
let count = leaders[..body.len()].iter().filter(|&&mark| mark != 0).count();
let mut blocks = scratch::<Block>(count, budget)?;
budget.work(body.len())?;
for (pc, &mark) in leaders[..body.len()].iter().enumerate() {
if mark == 0 {
continue;
}
budget.work(2)?;
if let Some(previous) = blocks.last_mut() {
previous.end = pc;
}
blocks.push(Block { start: pc, end: body.len(), state: None, queued: false });
}
let leader_bytes = leaders.capacity() as u64;
drop(leaders);
budget.refund(Q::TemporaryBytes, leader_bytes);
let mut blocks = basic_blocks::<Fact>(body, budget, at_pc)?;
let count = blocks.len();
let mut pc;
let mut initial = scratch::<Fact>(locals, budget)?;
budget.work(locals)?;
@@ -270,6 +234,7 @@ fn analyze(
target,
&working[..locals + height],
locals,
Fact::Unknown,
&mut blocks,
&mut worklist,
budget,
@@ -288,6 +253,7 @@ fn analyze(
pc,
&working[..locals + height],
locals,
Fact::Unknown,
&mut blocks,
&mut worklist,
budget,
@@ -298,11 +264,12 @@ fn analyze(
Ok(())
}
fn propagate(
pub(super) fn propagate<F: Copy + Eq>(
target: usize,
incoming: &[Fact],
incoming: &[F],
locals: usize,
blocks: &mut [Block],
unknown: F,
blocks: &mut [Block<F>],
queue: &mut Vec<usize>,
budget: &mut LoadBudget,
) -> Result<(), E> {
@@ -332,14 +299,18 @@ fn propagate(
budget.work(incoming.len().checked_mul(3).ok_or_else(overflow)?)?;
let mut changed = false;
for (old, &new) in current.iter_mut().zip(incoming) {
if *old != new && *old != Fact::Unknown {
*old = Fact::Unknown;
changed = true;
if *old != new {
budget.work(1)?;
if *old != unknown {
budget.work(1)?;
*old = unknown;
changed = true;
}
}
}
changed
} else {
let mut state = scratch::<Fact>(incoming.len(), budget)?;
let mut state = scratch::<F>(incoming.len(), budget)?;
budget.work(incoming.len().checked_mul(2).ok_or_else(overflow)?)?;
state.extend_from_slice(incoming);
node.state = Some(state);
@@ -364,7 +335,7 @@ fn count_error(reason: R, actual: u64, expected: u64) -> E {
fn overflow() -> E {
E::new(C::ResourceLimit, R::Overflow)
}
fn scratch<T>(count: usize, budget: &mut LoadBudget) -> Result<Vec<T>, E> {
pub(super) fn scratch<T>(count: usize, budget: &mut LoadBudget) -> Result<Vec<T>, E> {
let bytes = count.checked_mul(size_of::<T>()).ok_or_else(overflow)? as u64;
budget.charge(Q::TemporaryBytes, bytes)?;
let mut values = Vec::new();
@@ -377,3 +348,48 @@ fn scratch<T>(count: usize, budget: &mut LoadBudget) -> Result<Vec<T>, E> {
budget.charge(Q::TemporaryBytes, actual - bytes)?;
Ok(values)
}
/// Metered CFG construction shared by the stack and semantic analyses.
pub(super) fn basic_blocks<F>(
body: &[u8],
budget: &mut LoadBudget,
at_pc: &mut usize,
) -> Result<Vec<Block<F>>, E> {
let mut leaders = scratch::<u8>(body.len() + 1, budget)?;
budget.work(body.len() + 2)?;
leaders.resize(body.len() + 1, 0);
leaders[0] = 1;
let mut pc = 0;
while pc < body.len() {
*at_pc = pc;
let instruction = metered_decode(pc, body, budget)?;
let spec = instruction.opcode.spec();
if spec.is_branch {
budget.work(1)?;
leaders[instruction.imm_u32().unwrap() as usize] = 1;
}
if spec.is_branch || spec.is_terminator {
budget.work(1)?;
leaders[instruction.next_pc] = 1;
}
pc = instruction.next_pc;
}
budget.work(body.len())?;
let count = leaders[..body.len()].iter().filter(|&&mark| mark != 0).count();
let mut blocks = scratch::<Block<F>>(count, budget)?;
budget.work(body.len())?;
for (pc, &mark) in leaders[..body.len()].iter().enumerate() {
if mark == 0 {
continue;
}
budget.work(2)?;
if let Some(previous) = blocks.last_mut() {
previous.end = pc;
}
blocks.push(Block { start: pc, end: body.len(), state: None, queued: false });
}
let bytes = leaders.capacity() as u64;
drop(leaders);
budget.refund(Q::TemporaryBytes, bytes);
Ok(blocks)
}
@@ -0,0 +1,748 @@
//! Finite conservative facts, with errors decided only after convergence.
//! This never removes runtime group, null, generation or bounds validation.
use super::heights::{basic_blocks, propagate, scratch};
use super::*;
use crate::builtins::{AbiType, BuiltinScalarType};
use prometeu_bytecode::model::ConstantPoolEntry as Constant;
use prometeu_bytecode::registry::{BuiltinId as B, TypeId, TypeKind};
const I32: u8 = 1;
const I64: u8 = 2;
const FLOAT: u8 = 4;
const BOOL: u8 = 8;
const STRING: u8 = 16;
const REFERENCE: u8 = 32;
const NULL: u8 = 64;
const ANY: u8 = 127;
const NUMERIC: u8 = I32 | I64 | FLOAT;
#[derive(Clone, Copy, PartialEq, Eq)]
enum Fact {
Unknown,
Null,
Carrier(u8),
Int64(i64),
Group { ty: TypeId, part: u32, origin: u64 },
Dynamic { part: u32, origin: u64 },
Closure(u32),
}
pub(crate) fn validate_registry_types(
code: &[u8],
registry: &Registry,
constants: &[Constant],
budget: &mut LoadBudget,
) -> Result<(), E> {
heights::validate_registry_stacks(code, registry, constants.len(), budget)?;
let before = budget.used(Q::TemporaryBytes);
let result = (|| {
for (id, function) in registry.declarations().functions.iter().enumerate() {
let phase_before = budget.used(Q::TemporaryBytes);
let start = function.code_offset as usize;
let body = &code[start..start + function.code_len as usize];
let mut pc = 0;
let result = analyze(body, registry, id as u32, constants, budget, &mut pc)
.map_err(|e| e.in_section(2).in_function(id as u32, Some((start + pc) as u32)));
budget.refund(Q::TemporaryBytes, budget.used(Q::TemporaryBytes) - phase_before);
result?;
}
Ok(())
})();
budget.refund(Q::TemporaryBytes, budget.used(Q::TemporaryBytes) - before);
result
}
fn analyze(
body: &[u8],
registry: &Registry,
id: u32,
constants: &[Constant],
budget: &mut LoadBudget,
at_pc: &mut usize,
) -> Result<(), E> {
let function = &registry.declarations().functions[id as usize];
let layout = registry.function_layout(FunctionId(id)).unwrap();
let locals = layout.parameter_slots as usize + function.local_slots as usize;
let mut blocks = basic_blocks::<Fact>(body, budget, at_pc)?;
let mut initial = scratch::<Fact>(locals, budget)?;
budget.work(locals)?;
initial.resize(locals, Fact::Null);
let mut offset = 0;
for (index, parameter) in function.signature.parameters.iter().enumerate() {
let width = group(
&mut initial[offset..],
registry,
parameter.type_id,
(1u64 << 63) | index as u64,
budget,
)?;
offset += width;
}
budget.work(2)?;
blocks[0].state = Some(initial);
blocks[0].queued = true;
let mut queue = scratch::<usize>(blocks.len(), budget)?;
queue.push(0);
let count = locals + function.max_stack_slots as usize;
let mut working = scratch::<Fact>(count, budget)?;
budget.work(count)?;
working.resize(count, Fact::Unknown);
// Phase one transfers and widens facts without reporting state-dependent
// mismatches. Calls use signatures, not interprocedural body inference.
while let Some(index) = queue.pop() {
*at_pc = blocks[index].start;
budget.work(3)?;
blocks[index].queued = false;
let input = blocks[index].state.as_ref().unwrap();
budget.work(input.len() * 2)?;
working[..input.len()].copy_from_slice(input);
let mut height = input.len() - locals;
let mut pc = blocks[index].start;
let end = blocks[index].end;
while pc < end {
*at_pc = pc;
let instruction = metered_decode(pc, body, budget)?;
transfer(&instruction, &mut working, locals, &mut height, registry, constants, budget)?;
let spec = instruction.opcode.spec();
if spec.is_branch {
let target = instruction.imm_u32().unwrap() as usize;
if target < body.len() {
propagate(
target,
&working[..locals + height],
locals,
Fact::Unknown,
&mut blocks,
&mut queue,
budget,
)?;
}
}
if spec.is_terminator {
break;
}
pc = instruction.next_pc;
if pc == end && pc < body.len() {
propagate(
pc,
&working[..locals + height],
locals,
Fact::Unknown,
&mut blocks,
&mut queue,
budget,
)?;
}
}
}
// Phase two deterministically replays only stabilized reachable states.
for block in &blocks {
*at_pc = block.start;
budget.work(1)?;
let Some(input) = &block.state else {
continue;
};
budget.work(input.len() * 2)?;
working[..input.len()].copy_from_slice(input);
let mut height = input.len() - locals;
let mut pc = block.start;
while pc < block.end {
*at_pc = pc;
let instruction = metered_decode(pc, body, budget)?;
check(&instruction, &working, locals, height, registry, id, budget)?;
transfer(&instruction, &mut working, locals, &mut height, registry, constants, budget)?;
if instruction.opcode.spec().is_terminator {
break;
}
pc = instruction.next_pc;
}
}
Ok(())
}
fn group(
out: &mut [Fact],
registry: &Registry,
ty: TypeId,
origin: u64,
budget: &mut LoadBudget,
) -> Result<usize, E> {
budget.work(1)?;
let width = registry.type_layout(ty).unwrap().storage.slots as usize;
budget.work(width)?;
for (part, fact) in out[..width].iter_mut().enumerate() {
*fact = Fact::Group { ty, part: part as u32, origin };
}
Ok(width)
}
fn component(registry: &Registry, ty: TypeId, part: u32, budget: &mut LoadBudget) -> Result<u8, E> {
budget.work(1)?;
Ok(match &registry.declarations().types[ty.0 as usize].kind {
TypeKind::Struct(_) | TypeKind::Array(_) => REFERENCE | NULL,
TypeKind::Trait(_) => {
if part == 0 {
REFERENCE | NULL
} else {
I64 | NULL
}
}
TypeKind::Builtin(B::INT32) => I32,
TypeKind::Builtin(B::INT64 | B::COLOR | B::PIXEL) => I64,
TypeKind::Builtin(B::FLOAT | B::VEC2) => FLOAT,
TypeKind::Builtin(B::BOOL) => BOOL,
TypeKind::Builtin(B::STRING) => STRING | NULL,
TypeKind::Builtin(B::DYNAMIC) => {
if part == 0 {
I64 | NULL
} else {
ANY
}
}
_ => unreachable!("Registry rejects unsupported BuiltinIds"),
})
}
fn mask(fact: Fact, registry: &Registry, budget: &mut LoadBudget) -> Result<u8, E> {
budget.work(1)?;
Ok(match fact {
Fact::Unknown => ANY,
Fact::Null => NULL,
Fact::Carrier(mask) => mask,
Fact::Int64(_) => I64,
Fact::Closure(_) => REFERENCE,
Fact::Group { ty, part, .. } => return component(registry, ty, part, budget),
Fact::Dynamic { part: 0, .. } => I64 | NULL,
Fact::Dynamic { .. } => ANY,
})
}
fn invalidate(
working: &mut [Fact],
ty: TypeId,
origin: u64,
registry: &Registry,
budget: &mut LoadBudget,
) -> Result<(), E> {
budget.work(1)?;
if registry.type_layout(ty).unwrap().storage.slots <= 1 {
return Ok(());
}
budget.work(working.len() * 2)?;
for fact in working {
if let Fact::Group { ty, part, origin: other } = *fact {
if origin == other {
let carrier = component(registry, ty, part, budget)?;
budget.work(1)?;
*fact = if carrier == ANY { Fact::Unknown } else { Fact::Carrier(carrier) };
}
}
}
Ok(())
}
fn transfer(
instruction: &prometeu_bytecode::DecodedInstr<'_>,
working: &mut [Fact],
locals: usize,
height: &mut usize,
registry: &Registry,
constants: &[Constant],
budget: &mut LoadBudget,
) -> Result<(), E> {
budget.work(1)?;
let opcode = instruction.opcode;
let spec = opcode.spec();
let (mut pops, mut pushes) = if opcode.requires_registry() {
budget.work(4)?;
let effect = instruction.registry_stack_effect(registry)?.unwrap();
(effect.pops as usize, effect.pushes as usize)
} else {
(spec.pops.unwrap() as usize, spec.pushes.unwrap() as usize)
};
let mut call = None;
let mut native = None;
match opcode {
Op::PopN => pops = instruction.imm_u32().unwrap() as usize,
Op::MakeClosure => pops = instruction.imm_u32x2().unwrap().1 as usize,
Op::Spawn => pops = instruction.imm_u32x2().unwrap().1 as usize,
Op::Call | Op::CallClosure => {
budget.work(1)?;
let target = if opcode == Op::Call {
instruction.imm_u32().unwrap()
} else {
let Fact::Closure(target) = working[locals + *height - 1] else {
return Err(E::new(C::InvalidCode, R::UnknownClosureCallee));
};
target
};
let layout = registry.function_layout(FunctionId(target)).unwrap();
pops = layout.parameter_slots as usize;
pushes = layout.result_slots as usize;
call = Some(target);
}
Op::Ret => {
// Stack analysis has already proved exact height; no continuation.
pops = *height;
pushes = 0;
}
Op::Syscall => {
budget.work(1)?;
let syscall =
prometeu_hal::syscalls::Syscall::from_u32(instruction.imm_u32().unwrap()).unwrap();
pops = syscall.args_count();
pushes = syscall.results_count();
}
Op::Intrinsic => {
let meta =
crate::builtins::metered_lookup_intrinsic(instruction.imm_u32().unwrap(), budget)?
.unwrap();
pops = meta.arg_slots();
pushes = meta.ret_slots();
native = Some(meta);
}
_ => {}
}
let base = locals + *height - pops;
let before = locals + *height;
// A partial pop destroys the group's relational proof, including copies.
// Every group has at most three components; do not do an unbounded search.
for index in base..before {
budget.work(1)?;
if let Fact::Group { ty, origin, part } = working[index] {
budget.work(1)?;
let width = registry.type_layout(ty).unwrap().storage.slots as usize;
if width > 1 {
let start = index.checked_sub(part as usize);
budget.work(width * 2)?;
let intact = start.is_some_and(|start| start >= base && start + width <= before)
&& (0..width).all(|part| {
working[start.unwrap() + part]
== Fact::Group { ty, origin, part: part as u32 }
});
if !intact {
invalidate(&mut working[..base], ty, origin, registry, budget)?;
}
}
}
if let Fact::Dynamic { origin, part } = working[index] {
budget.work(4)?;
let start = index.checked_sub(part as usize);
let intact = start.is_some_and(|start| start >= base && start + 2 <= before)
&& (0..2).all(|part| {
working[start.unwrap() + part] == Fact::Dynamic { part: part as u32, origin }
});
if !intact {
invalidate_dynamic(&mut working[..base], origin, budget)?;
}
}
}
match opcode {
Op::Dup => {
budget.work(3)?;
let fact = working[before - 1];
working[base] = fact;
working[base + 1] = fact;
}
Op::Swap => {
budget.work(4)?;
working.swap(base, base + 1);
}
Op::GetLocal => {
budget.work(2)?;
working[base] = working[instruction.imm_u32().unwrap() as usize];
}
Op::SetLocal => {
budget.work(3)?;
let slot = instruction.imm_u32().unwrap() as usize;
let source = working[base];
if let Fact::Group { ty, origin, .. } = working[slot] {
invalidate(&mut working[..before], ty, origin, registry, budget)?;
}
if let Fact::Dynamic { origin, .. } = working[slot] {
invalidate_dynamic(&mut working[..before], origin, budget)?;
}
working[slot] = source;
}
Op::PushI32 => {
budget.work(1)?;
working[base] = Fact::Carrier(I32);
}
Op::PushI64 => {
budget.work(1)?;
working[base] = Fact::Int64(i64::from_le_bytes(instruction.imm.try_into().unwrap()));
}
Op::PushF64 => {
budget.work(1)?;
working[base] = Fact::Carrier(FLOAT);
}
Op::PushBool => {
budget.work(1)?;
working[base] = Fact::Carrier(BOOL);
}
Op::PushConst => {
budget.work(2)?;
working[base] = match &constants[instruction.imm_u32().unwrap() as usize] {
Constant::Null => Fact::Null,
Constant::Int32(_) => Fact::Carrier(I32),
Constant::Int64(value) => Fact::Int64(*value),
Constant::Float64(_) => Fact::Carrier(FLOAT),
Constant::Boolean(_) => Fact::Carrier(BOOL),
Constant::String(_) => Fact::Carrier(STRING),
};
}
Op::MakeClosure => {
budget.work(1)?;
working[base] = Fact::Closure(instruction.imm_u32x2().unwrap().0);
}
Op::Call | Op::CallClosure => {
let signature = &registry.declarations().functions[call.unwrap() as usize].signature;
let mut offset = base;
for (index, ty) in signature.results.iter().enumerate() {
offset += group(
&mut working[offset..],
registry,
*ty,
(instruction.pc as u64) << 32 | index as u64,
budget,
)?;
}
}
Op::Intrinsic => {
for (offset, abi) in native.unwrap().ret_layout.iter().enumerate() {
budget.work(1)?;
working[base + offset] = Fact::Carrier(abi_mask(*abi));
}
}
Op::DynPack => {
budget.work(1)?;
let ty = TypeId(instruction.imm_u32().unwrap());
if !matches!(
registry.declarations().types[ty.0 as usize].kind,
TypeKind::Builtin(B::DYNAMIC)
) {
budget.work(2)?;
let origin = (1u64 << 62) | instruction.pc as u64;
working[base] = Fact::Dynamic { part: 0, origin };
working[base + 1] = Fact::Dynamic { part: 1, origin };
}
}
Op::DynUnpack => {
budget.work(1)?;
let ty = TypeId(instruction.imm_u32().unwrap());
if !matches!(
registry.declarations().types[ty.0 as usize].kind,
TypeKind::Builtin(B::DYNAMIC)
) {
group(&mut working[base..], registry, ty, (instruction.pc as u64) << 32, budget)?;
}
}
Op::RefCast | Op::RefToTrait => {
group(
&mut working[base..],
registry,
TypeId(instruction.imm_u32x2().unwrap().1),
(instruction.pc as u64) << 32,
budget,
)?;
}
Op::Eq
| Op::Neq
| Op::Lt
| Op::Gt
| Op::Lte
| Op::Gte
| Op::And
| Op::Or
| Op::Not
| Op::RefIsExact
| Op::RefImplements
| Op::DynCanUnpack => {
budget.work(1)?;
working[base] = Fact::Carrier(BOOL);
}
Op::Add
| Op::Sub
| Op::Mul
| Op::Div
| Op::Mod
| Op::BitAnd
| Op::BitOr
| Op::BitXor
| Op::Shl
| Op::Shr => {
let left = mask(working[base], registry, budget)?;
let right = mask(working[base + 1], registry, budget)?;
let out = if opcode == Op::Add && (left == STRING || right == STRING) {
STRING
} else if left & !NUMERIC == 0 && right & !NUMERIC == 0 {
if left == FLOAT || right == FLOAT {
FLOAT
} else if left == I64 || right == I64 {
I64
} else {
I32
}
} else {
ANY
};
budget.work(1)?;
working[base] = if out == ANY { Fact::Unknown } else { Fact::Carrier(out) };
}
Op::Neg => {
let carrier = mask(working[base], registry, budget)?;
budget.work(1)?;
working[base] = Fact::Carrier(carrier);
}
_ => {
budget.work(pushes)?;
working[base..base + pushes].fill(Fact::Unknown);
}
}
*height = *height - pops + pushes;
Ok(())
}
fn abi_mask(abi: AbiType) -> u8 {
match abi {
AbiType::Scalar(BuiltinScalarType::Int32) => I32,
AbiType::Scalar(BuiltinScalarType::Int64) => I64,
AbiType::Scalar(BuiltinScalarType::Float) => FLOAT,
AbiType::Scalar(BuiltinScalarType::Bool) => BOOL,
AbiType::Scalar(BuiltinScalarType::String) => STRING,
AbiType::Builtin(key) if key.name == "color" => I64,
AbiType::DynamicTag => I64 | NULL,
_ => ANY,
}
}
fn invalidate_dynamic(values: &mut [Fact], origin: u64, budget: &mut LoadBudget) -> Result<(), E> {
budget.work(values.len() * 2)?;
for value in values {
if let Fact::Dynamic { part, origin: other } = *value {
if origin == other {
budget.work(1)?;
*value = if part == 0 { Fact::Carrier(I64 | NULL) } else { Fact::Unknown };
}
}
}
Ok(())
}
fn mismatch(member: usize) -> E {
E::new(C::InvalidCode, R::TypeMismatch).member(member as u32)
}
fn require(
value: Fact,
allowed: u8,
member: usize,
registry: &Registry,
budget: &mut LoadBudget,
) -> Result<(), E> {
if mask(value, registry, budget)? & allowed == 0 { Err(mismatch(member)) } else { Ok(()) }
}
fn check_group(
values: &[Fact],
ty: TypeId,
registry: &Registry,
budget: &mut LoadBudget,
) -> Result<(), E> {
budget.work(2)?;
let kind = &registry.declarations().types[ty.0 as usize].kind;
let width = registry.type_layout(ty).unwrap().storage.slots as usize;
if matches!(values[0], Fact::Closure(_))
&& matches!(kind, TypeKind::Struct(_) | TypeKind::Array(_) | TypeKind::Trait(_))
{
return Err(mismatch(0).reference(IdDomain::Type, ty.0));
}
budget.work(1)?;
if let Fact::Group { ty: source, part: 0, origin } = values[0] {
budget.work(1)?;
if source != ty && registry.type_layout(source).unwrap().storage.slots as usize == width {
budget.work(width * 2)?;
if values[..width]
.iter()
.enumerate()
.all(|(part, &fact)| fact == Fact::Group { ty: source, part: part as u32, origin })
{
return Err(mismatch(0).reference(IdDomain::Type, ty.0));
}
}
}
if let [Fact::Dynamic { part: 0, origin: left }, Fact::Dynamic { part: 1, origin: right }] =
&values[..width]
{
budget.work(1)?;
if left == right && !matches!(kind, TypeKind::Builtin(B::DYNAMIC)) {
return Err(mismatch(0).reference(IdDomain::Type, ty.0));
}
}
for (part, &value) in values[..width].iter().enumerate() {
require(value, component(registry, ty, part as u32, budget)?, part, registry, budget)
.map_err(|e| e.reference(IdDomain::Type, ty.0))?;
}
// Known invalid pair/range facts are proof; uncertain relations retain the
// runtime whole-group check, even if their component carriers match.
if matches!(kind, TypeKind::Trait(_) | TypeKind::Builtin(B::DYNAMIC))
&& values[0] == Fact::Null
&& mask(values[1], registry, budget)? & NULL == 0
{
return Err(mismatch(1).reference(IdDomain::Type, ty.0));
}
let color = matches!(kind, TypeKind::Builtin(B::COLOR | B::PIXEL));
if color {
budget.work(1)?;
if let Fact::Int64(value) = values[width - 1] {
if u32::try_from(value).is_err() {
return Err(mismatch(width - 1).reference(IdDomain::Type, ty.0));
}
}
}
Ok(())
}
fn check(
instruction: &prometeu_bytecode::DecodedInstr<'_>,
working: &[Fact],
locals: usize,
height: usize,
registry: &Registry,
id: u32,
budget: &mut LoadBudget,
) -> Result<(), E> {
budget.work(1)?;
let end = locals + height;
match instruction.opcode {
Op::Call | Op::Spawn => {
let target = if instruction.opcode == Op::Call {
instruction.imm_u32().unwrap()
} else {
instruction.imm_u32x2().unwrap().0
};
budget.work(1)?;
let callee = registry.function_layout(FunctionId(target)).unwrap();
let mut base = end - callee.parameter_slots as usize;
for parameter in
&registry.declarations().functions[target as usize].signature.parameters
{
check_group(&working[base..], parameter.type_id, registry, budget)?;
budget.work(1)?;
base += registry.type_layout(parameter.type_id).unwrap().storage.slots as usize;
}
}
Op::Ret => {
let mut base = locals;
for ty in &registry.declarations().functions[id as usize].signature.results {
check_group(&working[base..], *ty, registry, budget)?;
budget.work(1)?;
base += registry.type_layout(*ty).unwrap().storage.slots as usize;
}
}
Op::CallClosure => {
budget.work(1)?;
let Fact::Closure(target) = working[end - 1] else {
return Err(E::new(C::InvalidCode, R::UnknownClosureCallee));
};
let parameters =
&registry.declarations().functions[target as usize].signature.parameters;
budget.work(1)?;
let receiver = parameters.first().unwrap();
if registry.type_layout(receiver.type_id).unwrap().storage.slots != 1 {
return Err(mismatch(0));
}
check_group(&working[end - 1..end], receiver.type_id, registry, budget)?;
let mut base = end - instruction.imm_u32().unwrap() as usize - 1;
for parameter in parameters.iter().skip(1) {
check_group(&working[base..], parameter.type_id, registry, budget)?;
budget.work(1)?;
base += registry.type_layout(parameter.type_id).unwrap().storage.slots as usize;
}
}
Op::DynPack => {
budget.work(1)?;
let ty = TypeId(instruction.imm_u32().unwrap());
let width = registry.type_layout(ty).unwrap().storage.slots as usize;
check_group(&working[end - width..], ty, registry, budget)?;
}
Op::DynUnpack | Op::DynCanUnpack => {
if let [
Fact::Group { ty, part: 0, origin: left },
Fact::Group { ty: other, part: 1, origin: right },
] = &working[end - 2..end]
{
budget.work(1)?;
if ty == other
&& left == right
&& !matches!(
registry.declarations().types[ty.0 as usize].kind,
TypeKind::Builtin(B::DYNAMIC)
)
{
return Err(mismatch(0));
}
}
require(working[end - 2], I64 | NULL, 0, registry, budget)?;
if working[end - 2] == Fact::Null
&& mask(working[end - 1], registry, budget)? & NULL == 0
{
return Err(mismatch(1));
}
}
Op::RefCast | Op::RefToTrait | Op::RefIsExact | Op::RefImplements => {
budget.work(1)?;
let ty = TypeId(instruction.imm_u32x2().unwrap().0);
let width = registry.type_layout(ty).unwrap().storage.slots as usize;
check_group(&working[end - width..], ty, registry, budget)?;
}
Op::Intrinsic => {
let native =
crate::builtins::metered_lookup_intrinsic(instruction.imm_u32().unwrap(), budget)?
.unwrap();
let base = end - native.arg_slots();
for (part, abi) in native.arg_layout.iter().enumerate() {
require(working[base + part], abi_mask(*abi), part, registry, budget)?;
}
}
Op::JmpIfTrue | Op::JmpIfFalse | Op::Not => {
require(working[end - 1], BOOL, 0, registry, budget)?
}
Op::And | Op::Or => {
require(working[end - 2], BOOL, 0, registry, budget)?;
require(working[end - 1], BOOL, 1, registry, budget)?;
}
Op::Neg => require(working[end - 1], NUMERIC, 0, registry, budget)?,
Op::Lt | Op::Gt | Op::Lte | Op::Gte => {
let left = mask(working[end - 2], registry, budget)?;
let right = mask(working[end - 1], registry, budget)?;
if !(left & NUMERIC != 0 && right & NUMERIC != 0
|| left & STRING != 0 && right & STRING != 0
|| left & BOOL != 0 && right & BOOL != 0)
{
return Err(mismatch(0));
}
}
Op::Add
| Op::Sub
| Op::Mul
| Op::Div
| Op::Mod
| Op::BitAnd
| Op::BitOr
| Op::BitXor
| Op::Shl
| Op::Shr => {
let left = mask(working[end - 2], registry, budget)?;
let right = mask(working[end - 1], registry, budget)?;
if instruction.opcode != Op::Add || (left & STRING == 0 && right & STRING == 0) {
let allowed = if matches!(
instruction.opcode,
Op::BitAnd | Op::BitOr | Op::BitXor | Op::Shl | Op::Shr
) {
I32 | I64
} else {
NUMERIC
};
require(working[end - 2], allowed, 0, registry, budget)?;
require(working[end - 1], allowed, 1, registry, budget)?;
}
}
_ => {}
}
Ok(())
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,309 @@
use super::*;
use prometeu_bytecode::load_limits::LoadLimits;
use prometeu_bytecode::registry::{
FunctionDecl, NamedType, RegistryDeclarations, Signature, TypeDecl,
};
fn op(code: &mut Vec<u8>, opcode: Op) {
code.extend_from_slice(&(opcode as u16).to_le_bytes());
}
fn arg(code: &mut Vec<u8>, opcode: Op, value: u32) {
op(code, opcode);
code.extend_from_slice(&value.to_le_bytes());
}
fn boolean(code: &mut Vec<u8>, value: bool) {
op(code, Op::PushBool);
code.push(u8::from(value));
}
fn int64(code: &mut Vec<u8>, value: i64) {
op(code, Op::PushI64);
code.extend_from_slice(&value.to_le_bytes());
}
fn float(code: &mut Vec<u8>, value: f64) {
op(code, Op::PushF64);
code.extend_from_slice(&value.to_le_bytes());
}
fn function(
offset: usize,
len: usize,
parameters: &[u32],
results: &[u32],
locals: u32,
max: u32,
) -> FunctionDecl {
FunctionDecl {
code_offset: offset as u32,
code_len: len as u32,
local_slots: locals,
max_stack_slots: max,
signature: Signature {
parameters: parameters
.iter()
.map(|&id| NamedType { name: None, type_id: TypeId(id) })
.collect(),
results: results.iter().copied().map(TypeId).collect(),
},
name: None,
}
}
fn registry(code: &[u8], functions: Vec<FunctionDecl>) -> Registry {
let kind = |kind| TypeDecl { name: None, kind };
Registry::resolve(
RegistryDeclarations {
types: vec![
kind(TypeKind::Builtin(B::INT32)),
kind(TypeKind::Builtin(B::INT64)),
kind(TypeKind::Builtin(B::FLOAT)),
kind(TypeKind::Builtin(B::BOOL)),
kind(TypeKind::Builtin(B::STRING)),
kind(TypeKind::Builtin(B::VEC2)),
kind(TypeKind::Builtin(B::COLOR)),
kind(TypeKind::Builtin(B::PIXEL)),
kind(TypeKind::Builtin(B::DYNAMIC)),
kind(TypeKind::Struct(vec![])),
kind(TypeKind::Struct(vec![])),
kind(TypeKind::Trait(vec![])),
],
functions,
implementations: vec![],
},
code.len(),
&mut LoadBudget::new(Default::default()),
)
.unwrap()
}
fn check(code: &[u8], r: &Registry, constants: &[Constant]) -> Result<(), E> {
validate_registry_types(code, r, constants, &mut LoadBudget::new(Default::default()))
}
#[test]
fn equal_height_mixed_type_joins_are_order_independent_and_require_runtime_checks() {
for reverse in [false, true] {
let mut code = vec![];
arg(&mut code, Op::GetLocal, 0);
let branch = code.len();
arg(&mut code, Op::JmpIfTrue, 0);
if reverse {
boolean(&mut code, true);
} else {
arg(&mut code, Op::PushI32, 1);
}
let jump = code.len();
arg(&mut code, Op::Jmp, 0);
let right = code.len();
if reverse {
arg(&mut code, Op::PushI32, 1);
} else {
boolean(&mut code, true);
}
let join = code.len();
arg(&mut code, Op::Call, 1);
op(&mut code, Op::Halt);
let main_end = code.len();
op(&mut code, Op::Ret);
code[branch + 2..branch + 6].copy_from_slice(&(right as u32).to_le_bytes());
code[jump + 2..jump + 6].copy_from_slice(&(join as u32).to_le_bytes());
let r = registry(
&code,
vec![function(0, main_end, &[3], &[], 0, 1), function(main_end, 2, &[0], &[], 0, 0)],
);
assert!(check(&code, &r, &[]).is_ok());
}
}
#[test]
fn loop_widening_happens_before_type_error_decisions() {
let mut code = vec![];
boolean(&mut code, false);
arg(&mut code, Op::SetLocal, 0);
let jump = code.len();
arg(&mut code, Op::Jmp, 0);
let header = code.len();
arg(&mut code, Op::GetLocal, 0);
arg(&mut code, Op::Call, 1);
arg(&mut code, Op::PushI32, 1);
arg(&mut code, Op::SetLocal, 0);
boolean(&mut code, true);
arg(&mut code, Op::JmpIfTrue, header as u32);
op(&mut code, Op::Halt);
let end = code.len();
op(&mut code, Op::Ret);
code[jump + 2..jump + 6].copy_from_slice(&(header as u32).to_le_bytes());
let r =
registry(&code, vec![function(0, end, &[], &[], 1, 1), function(end, 2, &[0], &[], 0, 0)]);
// No branch-condition inference: the stabilized call input is Unknown,
// so the runtime still discriminates the actual argument at consumption.
assert!(check(&code, &r, &[]).is_ok());
}
#[test]
fn proved_call_and_return_mismatches_preserve_exact_type_and_pc() {
let mut code = vec![];
boolean(&mut code, true);
let pc = code.len();
arg(&mut code, Op::Call, 1);
op(&mut code, Op::Halt);
let end = code.len();
op(&mut code, Op::Ret);
let r =
registry(&code, vec![function(0, end, &[], &[], 0, 1), function(end, 2, &[0], &[], 0, 0)]);
let e = check(&code, &r, &[]).unwrap_err();
assert_eq!(
(e.code, e.reason, e.function, e.pc, e.referenced_id),
(C::InvalidCode, R::TypeMismatch, Some(0), Some(pc as u32), Some(0))
);
let mut code = vec![];
boolean(&mut code, true);
op(&mut code, Op::Ret);
let r = registry(&code, vec![function(0, code.len(), &[], &[0], 0, 1)]);
assert_eq!(check(&code, &r, &[]).unwrap_err().pc, Some(3));
}
#[test]
fn generic_null_locals_are_nullable_but_never_numeric_defaults() {
for (result, accepted) in [(0, false), (4, true), (9, true)] {
let mut code = vec![];
arg(&mut code, Op::GetLocal, 0);
op(&mut code, Op::Ret);
let r = registry(&code, vec![function(0, code.len(), &[], &[result], 1, 1)]);
assert_eq!(check(&code, &r, &[]).is_ok(), accepted);
}
}
#[test]
fn exact_nominal_groups_need_an_explicit_reference_cast() {
for explicit in [false, true] {
let mut code = vec![];
arg(&mut code, Op::GetLocal, 0);
if explicit {
arg(&mut code, Op::RefCast, 9);
code.extend_from_slice(&10u32.to_le_bytes());
}
arg(&mut code, Op::Call, 1);
op(&mut code, Op::Halt);
let end = code.len();
op(&mut code, Op::Ret);
let r = registry(
&code,
vec![function(0, end, &[9], &[], 0, 1), function(end, 2, &[10], &[], 0, 0)],
);
assert_eq!(check(&code, &r, &[]).is_ok(), explicit);
}
}
#[test]
fn partial_multislot_writes_keep_carriers_but_drop_the_relational_proof() {
let mut code = vec![];
float(&mut code, 3.0);
arg(&mut code, Op::SetLocal, 1);
arg(&mut code, Op::GetLocal, 0);
arg(&mut code, Op::GetLocal, 1);
arg(&mut code, Op::Call, 1);
op(&mut code, Op::Halt);
let end = code.len();
op(&mut code, Op::Ret);
let r =
registry(&code, vec![function(0, end, &[5], &[], 0, 2), function(end, 2, &[5], &[], 0, 0)]);
assert!(check(&code, &r, &[]).is_ok());
// Reusing a scalar local does not impose its original parameter type.
let mut code = vec![];
boolean(&mut code, true);
arg(&mut code, Op::SetLocal, 0);
arg(&mut code, Op::GetLocal, 0);
op(&mut code, Op::Ret);
let r = registry(&code, vec![function(0, code.len(), &[0], &[3], 0, 1)]);
assert!(check(&code, &r, &[]).is_ok());
}
#[test]
fn invalid_trait_dynamic_pairs_and_color_ranges_are_proved_mismatches() {
for parameter in [8, 11] {
let mut code = vec![];
arg(&mut code, Op::PushConst, 0);
int64(&mut code, 0);
arg(&mut code, Op::Call, 1);
op(&mut code, Op::Halt);
let end = code.len();
op(&mut code, Op::Ret);
let r = registry(
&code,
vec![function(0, end, &[], &[], 0, 2), function(end, 2, &[parameter], &[], 0, 0)],
);
assert_eq!(check(&code, &r, &[Constant::Null]).unwrap_err().reason, R::TypeMismatch);
}
let mut code = vec![];
int64(&mut code, i64::from(u32::MAX) + 1);
arg(&mut code, Op::DynPack, 6);
op(&mut code, Op::Halt);
let r = registry(&code, vec![function(0, code.len(), &[], &[], 0, 2)]);
assert_eq!(check(&code, &r, &[]).unwrap_err().referenced_id, Some(6));
}
#[test]
fn arithmetic_promotions_do_not_promote_typed_boundaries() {
for (result, accepted) in [(0, false), (1, true)] {
let mut code = vec![];
arg(&mut code, Op::PushI32, 1);
int64(&mut code, 2);
op(&mut code, Op::Add);
op(&mut code, Op::Ret);
let r = registry(&code, vec![function(0, code.len(), &[], &[result], 0, 2)]);
assert_eq!(check(&code, &r, &[]).is_ok(), accepted);
}
}
#[test]
fn intrinsic_and_reference_operands_are_checked_after_convergence() {
let mut code = vec![];
for _ in 0..4 {
boolean(&mut code, true);
}
arg(&mut code, Op::Intrinsic, 0x1000);
op(&mut code, Op::Halt);
let r = registry(&code, vec![function(0, code.len(), &[], &[], 0, 4)]);
assert_eq!(check(&code, &r, &[]).unwrap_err().reason, R::TypeMismatch);
let mut code = vec![];
boolean(&mut code, true);
arg(&mut code, Op::RefIsExact, 9);
code.extend_from_slice(&9u32.to_le_bytes());
op(&mut code, Op::Halt);
let r = registry(&code, vec![function(0, code.len(), &[], &[], 0, 1)]);
assert_eq!(check(&code, &r, &[]).unwrap_err().reason, R::TypeMismatch);
}
#[test]
fn known_closure_receivers_are_not_faked_as_user_struct_types() {
let mut code = vec![];
arg(&mut code, Op::MakeClosure, 1);
code.extend_from_slice(&0u32.to_le_bytes());
arg(&mut code, Op::CallClosure, 0);
op(&mut code, Op::Halt);
let end = code.len();
op(&mut code, Op::Ret);
let r =
registry(&code, vec![function(0, end, &[], &[], 0, 1), function(end, 2, &[9], &[], 0, 0)]);
// No provisional callable descriptor: a Closure is never a guest Struct.
assert_eq!(check(&code, &r, &[]).unwrap_err().reason, R::TypeMismatch);
}
#[test]
fn type_analysis_is_metered_and_releases_scratch_on_success_and_failure() {
let mut code = vec![];
arg(&mut code, Op::PushI32, 0);
op(&mut code, Op::Ret);
let r = registry(&code, vec![function(0, code.len(), &[], &[0], 0, 1)]);
let mut full = LoadBudget::new(Default::default());
validate_registry_types(&code, &r, &[], &mut full).unwrap();
assert_eq!(full.used(Q::TemporaryBytes), 0);
let mut limits = LoadLimits::default();
limits.work = full.used(Q::Work) - 1;
let mut limited = LoadBudget::new(limits);
limited.charge(Q::TemporaryBytes, 7).unwrap();
let e = validate_registry_types(&code, &r, &[], &mut limited).unwrap_err();
assert_eq!(
(e.code, e.resource, e.function, e.pc),
(C::ResourceLimit, Some(Q::Work), Some(0), Some(6))
);
assert_eq!(limited.used(Q::TemporaryBytes), 7);
assert!(limited.used(Q::Work) <= limits.work);
}