feat(vm): add deterministic gameplay math and domain coverage gates
Intrepid/Prometeu/Runtime/pipeline/pr-master There was a failure building this commit

This commit is contained in:
2026-10-09 10:25:11 +01:00
parent 2e041266f1
commit 9318cf7cd3
47 changed files with 8825 additions and 281 deletions
+85 -4
View File
@@ -206,6 +206,7 @@ pub enum IntrinsicExecutionError {
ArityMismatch { expected: usize, got: usize },
TypeMismatch { index: usize, expected: AbiType },
HardwareUnavailable,
Numeric(crate::numeric::NumericError),
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -226,6 +227,9 @@ pub struct IntrinsicMeta {
pub version: u16,
pub arg_layout: &'static [AbiType],
pub ret_layout: &'static [AbiType],
pub parameter_names: &'static [&'static str],
/// Total virtual call cost; math attempts are charged before checks.
pub cost_cycles: u64,
pub deterministic: bool,
pub may_allocate: bool,
pub implementation: IntrinsicImplementation,
@@ -424,7 +428,23 @@ const COLOR_MAGENTA_SLOTS: [BuiltinConstSlotValue; 1] =
const COLOR_TRANSPARENT_SLOTS: [BuiltinConstSlotValue; 1] =
[BuiltinConstSlotValue::Int64(Color::TRANSPARENT.raw() as i64)];
const BUILTIN_CONSTS: [BuiltinConstMeta; 13] = [
const BUILTIN_CONSTS: [BuiltinConstMeta; 15] = [
BuiltinConstMeta {
key: BuiltinConstKey::new("mathf", "pi", 1),
flat_slot_layout: &SINGLE_FLOAT_RET,
flat_slot_width: 1,
materializer: BuiltinConstMaterializer::Direct(&[BuiltinConstSlotValue::Float(
f64::from_bits(crate::numeric::PI_BITS),
)]),
},
BuiltinConstMeta {
key: BuiltinConstKey::new("mathf", "tau", 1),
flat_slot_layout: &SINGLE_FLOAT_RET,
flat_slot_width: 1,
materializer: BuiltinConstMaterializer::Direct(&[BuiltinConstSlotValue::Float(
f64::from_bits(crate::numeric::TAU_BITS),
)]),
},
BuiltinConstMeta {
key: BuiltinConstKey::new("vec2", "zero", 1),
flat_slot_layout: &VEC2_ZERO_LAYOUT,
@@ -491,6 +511,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &VEC2_DOT_ARGS,
ret_layout: &SINGLE_FLOAT_RET,
parameter_names: &["ax", "ay", "bx", "by"],
cost_cycles: 10,
deterministic: true,
may_allocate: false,
implementation: vec2_dot,
@@ -502,6 +524,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &VEC2_LENGTH_ARGS,
ret_layout: &SINGLE_FLOAT_RET,
parameter_names: &["x", "y"],
cost_cycles: 40,
deterministic: true,
may_allocate: false,
implementation: vec2_length,
@@ -513,6 +537,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &INT_RET,
ret_layout: &COLOR_RET,
parameter_names: &["raw"],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_from_raw,
@@ -524,6 +550,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &COLOR_RGB_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &["r", "g", "b"],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_rgb,
@@ -535,6 +563,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &COLOR_RGBA_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &["r", "g", "b", "a"],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_rgba,
@@ -546,6 +576,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &COLOR_HTML_RGBA_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &["value"],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_html_rgba,
@@ -557,6 +589,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &INT_RET,
ret_layout: &COLOR_RET,
parameter_names: &["value"],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_gray_scale,
@@ -568,6 +602,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &COLOR_ARGS,
ret_layout: &INT_RET,
parameter_names: &["color"],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_hex,
@@ -579,6 +615,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &COLOR_ARGS,
ret_layout: &INT_RET,
parameter_names: &["color"],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_alpha,
@@ -590,6 +628,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_black,
@@ -601,6 +641,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_white,
@@ -612,6 +654,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_red,
@@ -623,6 +667,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_green,
@@ -634,6 +680,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_blue,
@@ -645,6 +693,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_yellow,
@@ -656,6 +706,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_orange,
@@ -667,6 +719,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_indigo,
@@ -678,6 +732,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_gray,
@@ -689,6 +745,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_cyan,
@@ -700,6 +758,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_magenta,
@@ -711,6 +771,8 @@ const INTRINSICS: [IntrinsicMeta; 21] = [
version: 1,
arg_layout: &NO_ARGS,
ret_layout: &COLOR_RET,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation: color_transparent,
@@ -743,6 +805,7 @@ pub fn lookup_intrinsic(owner: &str, name: &str, version: u16) -> Option<&'stati
INTRINSICS
.iter()
.chain(crate::input_intrinsics::INPUT_INTRINSICS.iter())
.chain(crate::math_intrinsics::MATH_INTRINSICS.iter())
.find(|meta| meta.owner == owner && meta.name == name && meta.version == version)
}
@@ -750,6 +813,7 @@ pub fn lookup_intrinsic_by_id(id: u32) -> Option<&'static IntrinsicMeta> {
INTRINSICS
.iter()
.chain(crate::input_intrinsics::INPUT_INTRINSICS.iter())
.chain(crate::math_intrinsics::MATH_INTRINSICS.iter())
.find(|meta| meta.id == id)
}
@@ -841,6 +905,7 @@ fn vec2_dot(
args: &[Value],
_ctx: &mut HostContext<'_>,
) -> Result<Vec<Value>, IntrinsicExecutionError> {
lookup_intrinsic_by_id(0x1000).unwrap().validate_argument_values(args)?;
if args.len() != 4 {
return Err(IntrinsicExecutionError::ArityMismatch { expected: 4, got: args.len() });
}
@@ -848,7 +913,7 @@ fn vec2_dot(
let ay = expect_float_arg(args, 1)?;
let bx = expect_float_arg(args, 2)?;
let by = expect_float_arg(args, 3)?;
Ok(vec![Value::Float((ax * bx) + (ay * by))])
Ok(vec![Value::Float(crate::numeric::dot([ax, ay, bx, by])?)])
}
fn vec2_length(
@@ -858,9 +923,10 @@ fn vec2_length(
if args.len() != 2 {
return Err(IntrinsicExecutionError::ArityMismatch { expected: 2, got: args.len() });
}
lookup_intrinsic_by_id(0x1001).unwrap().validate_argument_values(args)?;
let x = expect_float_arg(args, 0)?;
let y = expect_float_arg(args, 1)?;
Ok(vec![Value::Float((x * x + y * y).sqrt())])
Ok(vec![Value::Float(crate::numeric::length(x, y)?)])
}
fn color_value(color: Color) -> Vec<Value> {
@@ -1041,7 +1107,11 @@ pub(crate) fn metered_lookup_intrinsic(
id: u32,
budget: &mut prometeu_bytecode::load_limits::LoadBudget,
) -> Result<Option<&'static IntrinsicMeta>, prometeu_bytecode::load_limits::LoadFailure> {
for meta in INTRINSICS.iter().chain(crate::input_intrinsics::INPUT_INTRINSICS.iter()) {
for meta in INTRINSICS
.iter()
.chain(crate::input_intrinsics::INPUT_INTRINSICS.iter())
.chain(crate::math_intrinsics::MATH_INTRINSICS.iter())
{
budget.work(1)?;
if meta.id == id {
return Ok(Some(meta));
@@ -1210,3 +1280,14 @@ mod tests {
assert_eq!(pixel.field("color").map(|field| field.start_slot), Some(2));
}
}
/// Runtime-owned catalogue, including input and scalar math.
pub fn intrinsic_catalog() -> impl Iterator<Item = &'static IntrinsicMeta> {
INTRINSICS
.iter()
.chain(crate::input_intrinsics::INPUT_INTRINSICS.iter())
.chain(crate::math_intrinsics::MATH_INTRINSICS.iter())
}
pub fn builtin_constant_catalog() -> impl Iterator<Item = &'static BuiltinConstMeta> {
BUILTIN_CONSTS.iter()
}
+69
View File
@@ -0,0 +1,69 @@
//! Exported handoff artifacts are generated from runtime metadata.
use crate::{AbiType, BuiltinScalarType, builtin_constant_catalog, intrinsic_catalog};
use prometeu_bytecode::Value;
use std::fmt::Write;
fn atom(t: AbiType) -> String {
match t {
AbiType::Scalar(BuiltinScalarType::Int32) => "Int32".into(),
AbiType::Scalar(BuiltinScalarType::Int64) => "Int64".into(),
AbiType::Scalar(BuiltinScalarType::Float) => "Float".into(),
AbiType::Scalar(BuiltinScalarType::Bool) => "Bool".into(),
AbiType::Scalar(BuiltinScalarType::String) => "String".into(),
AbiType::Builtin(k) => format!("builtin:{}", k.name),
AbiType::DynamicTag => "DynamicTag".into(),
AbiType::DynamicPayload => "DynamicPayload".into(),
}
}
pub fn intrinsic_catalog_csv() -> String {
let mut out = String::from(
"final_id_hex,final_id_dec,canonical_name,canonical_version,owner,name,arg_slots,ret_slots,arg_layout,ret_layout,deterministic,may_allocate,parameter_names,cost_cycles\n",
);
let mut entries: Vec<_> = intrinsic_catalog().collect();
entries.sort_by_key(|m| m.id);
for m in entries {
writeln!(
&mut out,
"0x{:04X},{},{}.{},{},{},{},{},{},{},{},{},{},{},{}",
m.id,
m.id,
m.owner,
m.name,
m.version,
m.owner,
m.name,
m.arg_slots(),
m.ret_slots(),
m.arg_layout.iter().copied().map(atom).collect::<Vec<_>>().join("|"),
m.ret_layout.iter().copied().map(atom).collect::<Vec<_>>().join("|"),
m.deterministic,
m.may_allocate,
m.parameter_names.join("|"),
m.cost_cycles
)
.unwrap();
}
out
}
pub fn builtin_constant_catalog_csv() -> String {
let mut out = String::from("target,name,version,slot,carrier,bits_or_value\n");
let mut entries: Vec<_> = builtin_constant_catalog().collect();
entries.sort_by_key(|m| m.key.key());
for m in entries {
for (slot, v) in m.materialize().expect("canonical constant").iter().enumerate() {
let (carrier, value) = match v {
Value::Float(v) => ("Float", format!("0x{:016X}", v.to_bits())),
Value::Int32(v) => ("Int32", v.to_string()),
Value::Int64(v) => ("Int64", v.to_string()),
Value::Boolean(v) => ("Bool", v.to_string()),
_ => unreachable!("canonical constant carrier"),
};
writeln!(
&mut out,
"{},{},{},{},{},{}",
m.key.target, m.key.name, m.key.version, slot, carrier, value
)
.unwrap();
}
}
out
}
@@ -21,6 +21,8 @@ const fn query(
version: 1,
arg_layout: &[],
ret_layout,
parameter_names: &[],
cost_cycles: 1,
deterministic: true,
may_allocate: false,
implementation,
+8 -2
View File
@@ -1,8 +1,13 @@
#[cfg(test)]
extern crate self as prometeu_vm;
mod builtins;
mod catalog;
pub use catalog::{builtin_constant_catalog_csv, intrinsic_catalog_csv};
mod call_frame;
mod input_intrinsics;
mod math_intrinsics;
mod numeric;
pub use numeric::NumericError;
mod local_addressing;
// Keep the verifier internal in production builds, but expose it for integration tests
// so the golden verifier suite can exercise it without widening the public API in releases.
@@ -34,8 +39,9 @@ pub use builtins::{
AbiType, BuiltinConstKey, BuiltinConstMaterializer, BuiltinConstMeta, BuiltinConstSlotValue,
BuiltinFieldMeta, BuiltinLayoutType, BuiltinScalarType, BuiltinTypeKey, BuiltinTypeMeta,
BuiltinTypeShape, BuiltinValueError, IntrinsicExecutionError, IntrinsicImplementation,
IntrinsicKey, IntrinsicMeta, lookup_builtin_constant, lookup_builtin_type, lookup_intrinsic,
lookup_intrinsic_by_id, materialize_builtin_constant,
IntrinsicKey, IntrinsicMeta, builtin_constant_catalog, intrinsic_catalog,
lookup_builtin_constant, lookup_builtin_type, lookup_intrinsic, lookup_intrinsic_by_id,
materialize_builtin_constant,
};
pub use prometeu_hal::{HostContext, HostReturn, NativeInterface, SyscallId};
pub use virtual_machine::{BudgetReport, LogicalFrameEndingReason, VirtualMachine};
@@ -0,0 +1,149 @@
//! Exact scalar identities. Public math overloads are a consumer projection.
use crate::builtins::{AbiType, BuiltinScalarType, IntrinsicExecutionError as E, IntrinsicMeta};
use crate::numeric::{self, NumericError};
use prometeu_bytecode::{TRAP_NUMERIC_DOMAIN, TRAP_NUMERIC_RANGE, Value};
use prometeu_hal::HostContext;
const I32: AbiType = AbiType::Scalar(BuiltinScalarType::Int32);
const I64: AbiType = AbiType::Scalar(BuiltinScalarType::Int64);
const FLOAT: AbiType = AbiType::Scalar(BuiltinScalarType::Float);
const fn entry<const ID: u32>(
owner: &'static str,
name: &'static str,
arg_layout: &'static [AbiType],
ret_layout: &'static [AbiType],
parameter_names: &'static [&'static str],
cost_cycles: u64,
) -> IntrinsicMeta {
IntrinsicMeta {
id: ID,
owner,
name,
version: 1,
arg_layout,
ret_layout,
parameter_names,
cost_cycles,
deterministic: true,
may_allocate: false,
implementation: execute::<ID>,
}
}
pub(crate) const MATH_INTRINSICS: [IntrinsicMeta; 26] = [
entry::<0x3000>("math.i32", "min", &[I32, I32], &[I32], &["a", "b"], 2),
entry::<0x3001>("math.i32", "max", &[I32, I32], &[I32], &["a", "b"], 2),
entry::<0x3002>("math.i32", "clamp", &[I32, I32, I32], &[I32], &["value", "min", "max"], 4),
entry::<0x3003>("math.i32", "abs", &[I32], &[I32], &["value"], 2),
entry::<0x3004>("math.i64", "min", &[I64, I64], &[I64], &["a", "b"], 2),
entry::<0x3005>("math.i64", "max", &[I64, I64], &[I64], &["a", "b"], 2),
entry::<0x3006>("math.i64", "clamp", &[I64, I64, I64], &[I64], &["value", "min", "max"], 4),
entry::<0x3007>("math.i64", "abs", &[I64], &[I64], &["value"], 2),
entry::<0x3008>("mathf", "min", &[FLOAT, FLOAT], &[FLOAT], &["a", "b"], 2),
entry::<0x3009>("mathf", "max", &[FLOAT, FLOAT], &[FLOAT], &["a", "b"], 2),
entry::<0x300a>(
"mathf",
"clamp",
&[FLOAT, FLOAT, FLOAT],
&[FLOAT],
&["value", "min", "max"],
4,
),
entry::<0x300b>("mathf", "abs", &[FLOAT], &[FLOAT], &["value"], 2),
entry::<0x300c>("mathf", "floor", &[FLOAT], &[FLOAT], &["value"], 4),
entry::<0x300d>("mathf", "ceil", &[FLOAT], &[FLOAT], &["value"], 4),
entry::<0x300e>("mathf", "trunc", &[FLOAT], &[FLOAT], &["value"], 4),
entry::<0x300f>("mathf", "round", &[FLOAT], &[FLOAT], &["value"], 4),
entry::<0x3010>("mathf", "sqrt", &[FLOAT], &[FLOAT], &["value"], 16),
entry::<0x3011>("mathf", "sin", &[FLOAT], &[FLOAT], &["angle"], 32),
entry::<0x3012>("mathf", "cos", &[FLOAT], &[FLOAT], &["angle"], 32),
entry::<0x3013>("mathf", "atan2", &[FLOAT, FLOAT], &[FLOAT], &["y", "x"], 48),
entry::<0x3014>("math.i32", "to_i64", &[I32], &[I64], &["value"], 2),
entry::<0x3015>("math.i64", "to_i32", &[I64], &[I32], &["value"], 2),
entry::<0x3016>("math.i32", "to_float", &[I32], &[FLOAT], &["value"], 2),
entry::<0x3017>("math.i64", "to_float", &[I64], &[FLOAT], &["value"], 2),
entry::<0x3018>("mathf", "to_i32", &[FLOAT], &[I32], &["value"], 2),
entry::<0x3019>("mathf", "to_i64", &[FLOAT], &[I64], &["value"], 2),
];
impl From<NumericError> for E {
fn from(error: NumericError) -> Self {
Self::Numeric(error)
}
}
fn integer(args: &[Value], offset: u32, narrow: bool) -> Result<Value, E> {
let mut a = [0i64; 3];
for (i, value) in args.iter().enumerate() {
a[i] = match value {
Value::Int32(v) => i64::from(*v),
Value::Int64(v) => *v,
_ => unreachable!("validated exact integer carrier"),
};
}
let result = match offset {
0 => a[0].min(a[1]),
1 => a[0].max(a[1]),
2 => {
if a[1] > a[2] {
return Err(NumericError::new(TRAP_NUMERIC_DOMAIN).into());
}
a[0].clamp(a[1], a[2])
}
3 => {
if (narrow && a[0] == i64::from(i32::MIN)) || a[0] == i64::MIN {
return Err(NumericError::new(TRAP_NUMERIC_RANGE).into());
}
a[0].abs()
}
_ => unreachable!("private integer operation"),
};
Ok(if narrow { Value::Int32(result as i32) } else { Value::Int64(result) })
}
fn execute<const ID: u32>(args: &[Value], _: &mut HostContext<'_>) -> Result<Vec<Value>, E> {
let meta = crate::lookup_intrinsic_by_id(ID).expect("static scalar identity");
meta.validate_argument_values(args)?;
if ID < 0x3008 {
return Ok(vec![integer(args, (ID - 0x3000) % 4, ID < 0x3004)?]);
}
let mut floats = [0.0; 3];
for (i, value) in args.iter().enumerate() {
if let Value::Float(v) = value {
floats[i] = *v;
}
}
if (0x3008..=0x3013).contains(&ID) || ID >= 0x3018 {
numeric::check_inputs(&floats[..args.len()])?;
}
let x = floats[0];
let value = match ID {
0x3008 => Value::Float(numeric::min(x, floats[1])),
0x3009 => Value::Float(numeric::max(x, floats[1])),
0x300a => Value::Float(numeric::clamp(x, floats[1], floats[2])?),
0x300b => Value::Float(numeric::abs(x)),
0x300c => Value::Float(numeric::floor(x)?),
0x300d => Value::Float(numeric::ceil(x)?),
0x300e => Value::Float(numeric::trunc(x)?),
0x300f => Value::Float(numeric::round(x)?),
0x3010 => Value::Float(numeric::sqrt(x)?),
0x3011 => Value::Float(numeric::sin(x)?),
0x3012 => Value::Float(numeric::cos(x)?),
0x3013 => Value::Float(numeric::atan2(x, floats[1])?),
0x3014 => {
let Value::Int32(v) = args[0] else { unreachable!() };
Value::Int64(i64::from(v))
}
0x3015 => {
let Value::Int64(v) = args[0] else { unreachable!() };
Value::Int32(i32::try_from(v).map_err(|_| NumericError::new(TRAP_NUMERIC_RANGE))?)
}
0x3016 => {
let Value::Int32(v) = args[0] else { unreachable!() };
Value::Float(numeric::from_i64(i64::from(v)))
}
0x3017 => {
let Value::Int64(v) = args[0] else { unreachable!() };
Value::Float(numeric::from_i64(v))
}
0x3018 => Value::Int32(numeric::to_i64(x, 32)? as i32),
0x3019 => Value::Int64(numeric::to_i64(x, 64)?),
_ => unreachable!("static scalar identity"),
};
Ok(vec![value])
}
+324
View File
@@ -0,0 +1,324 @@
//! Canonical binary64 adapter. Host f64 is a bit carrier only; arithmetic and
//! comparisons use SoftF64. Integer conversions and ties-even rounding use bits.
use fpmath::SoftF64 as F;
use prometeu_bytecode::{TRAP_DIV_ZERO, TRAP_NON_FINITE, TRAP_NUMERIC_DOMAIN, TRAP_NUMERIC_RANGE};
pub(crate) const PI_BITS: u64 = 0x4009_21fb_5444_2d18;
pub(crate) const TAU_BITS: u64 = 0x4019_21fb_5444_2d18;
const PI_2_BITS: u64 = 0x3ff9_21fb_5444_2d18;
const SIGN: u64 = 1 << 63;
const MAG: u64 = !SIGN;
const EXP: u64 = 0x7ff0_0000_0000_0000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NumericError {
pub code: u32,
pub argument: Option<usize>,
}
impl NumericError {
pub(crate) fn new(code: u32) -> Self {
Self { code, argument: None }
}
}
pub(crate) type Result<T> = std::result::Result<T, NumericError>;
pub(crate) fn finite(x: f64) -> bool {
x.to_bits() & EXP != EXP
}
pub(crate) fn check_inputs(values: &[f64]) -> Result<()> {
for (argument, &value) in values.iter().enumerate() {
if !finite(value) {
return Err(NumericError { code: TRAP_NON_FINITE, argument: Some(argument) });
}
}
Ok(())
}
fn soft(x: f64) -> F {
F::from_bits(x.to_bits())
}
fn output(x: F) -> Result<f64> {
let bits = x.to_bits();
if bits & EXP == EXP {
Err(NumericError::new(TRAP_NUMERIC_RANGE))
} else {
Ok(f64::from_bits(bits))
}
}
pub(crate) fn zero(x: f64) -> bool {
x.to_bits() & MAG == 0
}
pub(crate) fn cmp(a: f64, b: f64) -> std::cmp::Ordering {
// All callers check finitude first. Both zeros compare equal.
soft(a).partial_cmp(&soft(b)).expect("finite binary64 comparison")
}
pub(crate) fn abs(x: f64) -> f64 {
f64::from_bits(x.to_bits() & MAG)
}
pub(crate) fn neg(x: f64) -> Result<f64> {
check_inputs(&[x])?;
Ok(f64::from_bits(x.to_bits() ^ SIGN))
}
pub(crate) fn min(a: f64, b: f64) -> f64 {
if zero(a) && zero(b) {
f64::from_bits(a.to_bits() | b.to_bits())
} else if cmp(a, b).is_gt() {
b
} else {
a
}
}
pub(crate) fn max(a: f64, b: f64) -> f64 {
if zero(a) && zero(b) {
f64::from_bits(a.to_bits() & b.to_bits())
} else if cmp(a, b).is_lt() {
b
} else {
a
}
}
pub(crate) fn clamp(value: f64, lo: f64, hi: f64) -> Result<f64> {
check_inputs(&[value, lo, hi])?;
if cmp(lo, hi).is_gt() {
return Err(NumericError::new(TRAP_NUMERIC_DOMAIN));
}
Ok(min(max(value, lo), hi))
}
pub(crate) fn add(a: f64, b: f64) -> Result<f64> {
check_inputs(&[a, b])?;
output(soft(a) + soft(b))
}
pub(crate) fn sub(a: f64, b: f64) -> Result<f64> {
check_inputs(&[a, b])?;
output(soft(a) - soft(b))
}
pub(crate) fn mul(a: f64, b: f64) -> Result<f64> {
check_inputs(&[a, b])?;
output(soft(a) * soft(b))
}
pub(crate) fn div(a: f64, b: f64) -> Result<f64> {
check_inputs(&[a, b])?;
if zero(b) {
return Err(NumericError::new(TRAP_DIV_ZERO));
}
output(soft(a) / soft(b))
}
pub(crate) fn sqrt(x: f64) -> Result<f64> {
check_inputs(&[x])?;
if !zero(x) && x.to_bits() & SIGN != 0 {
return Err(NumericError::new(TRAP_NUMERIC_DOMAIN));
}
output(fpmath::sqrt(soft(x)))
}
pub(crate) fn sin(x: f64) -> Result<f64> {
check_inputs(&[x])?;
output(fpmath::sin(soft(x)))
}
pub(crate) fn cos(x: f64) -> Result<f64> {
check_inputs(&[x])?;
output(fpmath::cos(soft(x)))
}
pub(crate) fn atan2(y: f64, x: f64) -> Result<f64> {
check_inputs(&[y, x])?;
let sign_y = y.to_bits() & SIGN;
if zero(y) {
if zero(x) {
return Err(NumericError::new(TRAP_NUMERIC_DOMAIN));
}
return Ok(f64::from_bits(sign_y | if x.to_bits() & SIGN != 0 { PI_BITS } else { 0 }));
}
if zero(x) {
return Ok(f64::from_bits(sign_y | PI_2_BITS));
}
output(fpmath::atan2(soft(y), soft(x)))
}
pub(crate) fn floor(x: f64) -> Result<f64> {
check_inputs(&[x])?;
output(fpmath::floor(soft(x)))
}
pub(crate) fn ceil(x: f64) -> Result<f64> {
check_inputs(&[x])?;
output(fpmath::ceil(soft(x)))
}
pub(crate) fn trunc(x: f64) -> Result<f64> {
check_inputs(&[x])?;
output(fpmath::trunc(soft(x)))
}
pub(crate) fn round(x: f64) -> Result<f64> {
check_inputs(&[x])?;
let bits = x.to_bits();
let sign = bits & SIGN;
let magnitude = bits & MAG;
let exponent = ((magnitude >> 52) as i32) - 1023;
let rounded = if exponent >= 52 {
magnitude
} else if exponent < -1 {
0
} else if exponent == -1 {
// Exactly +/-0.5 ties to signed zero, all larger magnitudes to +/-1.
if magnitude == 0x3fe0_0000_0000_0000 { 0 } else { 0x3ff0_0000_0000_0000 }
} else {
let shift = 52 - exponent;
let unit = 1u64 << shift;
let remainder = magnitude & (unit - 1);
let half = unit >> 1;
let integral = magnitude & !(unit - 1);
integral
+ if remainder > half || (remainder == half && integral & unit != 0) { unit } else { 0 }
};
Ok(f64::from_bits(sign | rounded))
}
pub(crate) fn from_i64(value: i64) -> f64 {
let magnitude = value.unsigned_abs();
if magnitude == 0 {
return f64::from_bits(0);
}
let sign = if value < 0 { SIGN } else { 0 };
let mut exponent = 63 - magnitude.leading_zeros();
let mut significand = if exponent <= 52 {
magnitude << (52 - exponent)
} else {
let shift = exponent - 52;
let unit = 1u64 << shift;
let mut sig = magnitude >> shift;
let rem = magnitude & (unit - 1);
if rem > unit / 2 || (rem == unit / 2 && sig & 1 != 0) {
sig += 1;
}
sig
};
if significand == 1u64 << 53 {
significand >>= 1;
exponent += 1;
}
f64::from_bits(sign | (u64::from(exponent + 1023) << 52) | (significand & ((1 << 52) - 1)))
}
pub(crate) fn to_i64(x: f64, width: u32) -> Result<i64> {
check_inputs(&[x])?;
let bits = x.to_bits();
let exponent = ((bits & EXP) >> 52) as i32 - 1023;
if exponent < 0 {
return Ok(0);
}
if exponent > 63 {
return Err(NumericError::new(TRAP_NUMERIC_RANGE));
}
let significand = (bits & ((1 << 52) - 1)) | (1 << 52);
let magnitude = if exponent >= 52 {
significand << (exponent - 52)
} else {
significand >> (52 - exponent)
};
let negative = bits & SIGN != 0;
let limit = 1u64 << (width - 1);
if magnitude > limit || (magnitude == limit && !negative) {
return Err(NumericError::new(TRAP_NUMERIC_RANGE));
}
// unsigned magnitude handles exactly -2^63 without an intermediate overflow.
Ok(if negative { magnitude.wrapping_neg() as i64 } else { magnitude as i64 })
}
pub(crate) fn dot(a: [f64; 4]) -> Result<f64> {
check_inputs(&a)?;
let p1 = mul(a[0], a[2])?;
let p2 = mul(a[1], a[3])?;
add(p1, p2)
}
pub(crate) fn length(x: f64, y: f64) -> Result<f64> {
check_inputs(&[x, y])?;
let ax = abs(x);
let ay = abs(y);
let m = max(ax, ay);
let n = min(ax, ay);
if zero(m) {
return Ok(f64::from_bits(0));
}
let r = div(n, m)?;
let q = mul(r, r)?;
let s = add(f64::from_bits(0x3ff0_0000_0000_0000), q)?;
let t = sqrt(s)?;
mul(m, t)
}
fn promoted(value: &prometeu_bytecode::Value) -> Option<f64> {
use prometeu_bytecode::Value;
match value {
Value::Int32(v) => Some(from_i64(i64::from(*v))),
Value::Int64(v) => Some(from_i64(*v)),
Value::Float(v) => Some(*v),
_ => None,
}
}
pub(crate) fn opcode_binary(
op: prometeu_bytecode::isa::core::CoreOpCode,
a: &prometeu_bytecode::Value,
b: &prometeu_bytecode::Value,
) -> Result<prometeu_bytecode::Value> {
use prometeu_bytecode::isa::core::CoreOpCode as Op;
use prometeu_bytecode::{TRAP_TYPE, Value};
if matches!(a, Value::Float(_)) || matches!(b, Value::Float(_)) {
let (Some(a), Some(b)) = (promoted(a), promoted(b)) else {
return Err(NumericError::new(TRAP_TYPE));
};
return Ok(Value::Float(match op {
Op::Add => add(a, b)?,
Op::Sub => sub(a, b)?,
Op::Mul => mul(a, b)?,
Op::Div => div(a, b)?,
_ => unreachable!(),
}));
}
let (a, b, narrow) = match (a, b) {
(Value::Int32(a), Value::Int32(b)) => (i64::from(*a), i64::from(*b), true),
(Value::Int32(a), Value::Int64(b)) => (i64::from(*a), *b, false),
(Value::Int64(a), Value::Int32(b)) => (*a, i64::from(*b), false),
(Value::Int64(a), Value::Int64(b)) => (*a, *b, false),
_ => return Err(NumericError::new(TRAP_TYPE)),
};
if op == Op::Div && b == 0 {
return Err(NumericError::new(TRAP_DIV_ZERO));
}
if narrow {
let (a, b) = (a as i32, b as i32);
return Ok(Value::Int32(match op {
Op::Add => a.wrapping_add(b),
Op::Sub => a.wrapping_sub(b),
Op::Mul => a.wrapping_mul(b),
Op::Div => a.wrapping_div(b),
_ => unreachable!(),
}));
}
Ok(Value::Int64(match op {
Op::Add => a.wrapping_add(b),
Op::Sub => a.wrapping_sub(b),
Op::Mul => a.wrapping_mul(b),
Op::Div => a.wrapping_div(b),
_ => unreachable!(),
}))
}
pub(crate) fn compare_values(
a: &prometeu_bytecode::Value,
b: &prometeu_bytecode::Value,
) -> Result<Option<std::cmp::Ordering>> {
use prometeu_bytecode::Value;
if matches!(a, Value::Float(_)) || matches!(b, Value::Float(_)) {
let (Some(a), Some(b)) = (promoted(a), promoted(b)) else {
return Ok(None);
};
check_inputs(&[a, b])?;
Ok(Some(cmp(a, b)))
} else {
Ok(a.partial_cmp(b))
}
}
pub(crate) fn equal_values(
a: &prometeu_bytecode::Value,
b: &prometeu_bytecode::Value,
) -> Result<bool> {
use prometeu_bytecode::Value;
if matches!(a, Value::Float(_)) || matches!(b, Value::Float(_)) {
Ok(compare_values(a, b)? == Some(std::cmp::Ordering::Equal))
} else {
Ok(a == b)
}
}
@@ -70,7 +70,7 @@ fn publication_shares_owners_and_preserves_payload_bits_and_names() {
K::Null,
K::String("é猫".into()),
K::String(String::new()),
K::Float64(f64::from_bits(0x7ff8000000000042)),
K::Float64(f64::from_bits(0x0008000000000042)),
K::Float64(-0.0),
];
let bytes = fixture(&[1, 0], 0, &constants, Some(&debug), &[]);
@@ -85,7 +85,7 @@ fn publication_shares_owners_and_preserves_payload_bits_and_names() {
assert!(image.lease_constant(0).is_none());
let Value::Float(nan) = image.constants()[3] else { panic!() };
let Value::Float(zero) = image.constants()[4] else { panic!() };
assert_eq!(nan.to_bits(), 0x7ff8000000000042);
assert_eq!(nan.to_bits(), 0x0008000000000042);
assert_eq!(zero.to_bits(), (-0.0f64).to_bits());
let projection = image.execution.clone();
assert!(Arc::ptr_eq(&projection.rom, &image.execution.rom));
@@ -111,6 +111,13 @@ fn validate_inner(
Op::PushBool if instruction.imm_u8().unwrap() > 1 => {
return Err(fail(R::BooleanImmediate));
}
Op::PushF64 => {
if instruction.imm_f64().unwrap().to_bits() & 0x7ff0_0000_0000_0000
== 0x7ff0_0000_0000_0000
{
return Err(fail(R::NonFiniteValue).at(2, start + pc));
}
}
Op::PushConst => {
let id = instruction.imm_u32().unwrap();
if id as usize >= constants {
@@ -165,7 +172,7 @@ fn validate_inner(
Op::Intrinsic => {
let id = instruction.imm_u32().unwrap();
if crate::builtins::metered_lookup_intrinsic(id, budget)?.is_none() {
return Err(with_id(reference_error(fail(R::NativeId)), id));
return Err(with_id(fail(R::NativeId), id));
}
}
_ => {}
@@ -445,7 +445,11 @@ fn unreachable_function_constant_boolean_and_native_operands_are_checked() {
assert_eq!((e.reason, e.pc, e.referenced_id), (reason, Some(2), Some(id)));
assert_eq!(
e.code,
if operation == Op::Hostcall { C::InvalidCode } else { C::InvalidReference }
if matches!(operation, Op::Hostcall | Op::Intrinsic) {
C::InvalidCode
} else {
C::InvalidReference
}
);
}
let code = [
@@ -7,6 +7,7 @@ use prometeu_bytecode::{HeapRef, Value};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ValueError {
Type,
NonFinite,
InvalidHandle,
NullReference,
Bounds,
+86 -120
View File
@@ -1,3 +1,4 @@
use crate::numeric;
use crate::resource_budget::BudgetVec;
mod callable;
mod collections;
@@ -65,6 +66,12 @@ pub(crate) enum OpError {
Trap(u32, String),
}
impl From<crate::numeric::NumericError> for OpError {
fn from(error: crate::numeric::NumericError) -> Self {
Self::Trap(error.code, format!("Numeric operation failed: {error:?}"))
}
}
impl From<TrapInfo> for LogicalFrameEndingReason {
fn from(info: TrapInfo) -> Self {
LogicalFrameEndingReason::Trap(info)
@@ -276,6 +283,15 @@ impl VirtualMachine {
self.cycles += opcode.cycles();
}
let charged_math = if opcode == OpCode::Intrinsic {
lookup_intrinsic_by_id(instr.imm_u32().unwrap())
.filter(|m| m.owner == "vec2" || m.owner == "mathf" || m.owner.starts_with("math."))
} else {
None
};
if let Some(meta) = charged_math {
self.cycles += meta.cost_cycles;
}
// Execute
match opcode {
OpCode::Nop => {}
@@ -436,117 +452,40 @@ impl VirtualMachine {
{
self.execute_string_add(opcode, start_pc as u32)?;
} else {
self.binary_op(opcode, start_pc as u32, |a, b| match (&a, &b) {
(Value::Int32(a), Value::Int32(b)) => Ok(Value::Int32(a.wrapping_add(*b))),
(Value::Int64(a), Value::Int64(b)) => Ok(Value::Int64(a.wrapping_add(*b))),
(Value::Int32(a), Value::Int64(b)) => {
Ok(Value::Int64((*a as i64).wrapping_add(*b)))
}
(Value::Int64(a), Value::Int32(b)) => {
Ok(Value::Int64(a.wrapping_add(*b as i64)))
}
(Value::Float(a), Value::Float(b)) => Ok(Value::Float(a + b)),
(Value::Int32(a), Value::Float(b)) => Ok(Value::Float(*a as f64 + b)),
(Value::Float(a), Value::Int32(b)) => Ok(Value::Float(a + *b as f64)),
(Value::Int64(a), Value::Float(b)) => Ok(Value::Float(*a as f64 + b)),
(Value::Float(a), Value::Int64(b)) => Ok(Value::Float(a + *b as f64)),
_ => Err(OpError::Trap(TRAP_TYPE, "Invalid types for ADD".into())),
self.binary_op(opcode, start_pc as u32, |a, b| {
numeric::opcode_binary(opcode, &a, &b).map_err(|e| {
if e.code == TRAP_TYPE {
OpError::Trap(
TRAP_TYPE,
format!(
"Invalid types for {}",
format!("{opcode:?}").to_uppercase()
),
)
} else {
OpError::from(e)
}
})
})?;
}
}
OpCode::Sub => self.binary_op(opcode, start_pc as u32, |a, b| match (a, b) {
(Value::Int32(a), Value::Int32(b)) => Ok(Value::Int32(a.wrapping_sub(b))),
(Value::Int64(a), Value::Int64(b)) => Ok(Value::Int64(a.wrapping_sub(b))),
(Value::Int32(a), Value::Int64(b)) => Ok(Value::Int64((a as i64).wrapping_sub(b))),
(Value::Int64(a), Value::Int32(b)) => Ok(Value::Int64(a.wrapping_sub(b as i64))),
(Value::Float(a), Value::Float(b)) => Ok(Value::Float(a - b)),
(Value::Int32(a), Value::Float(b)) => Ok(Value::Float(a as f64 - b)),
(Value::Float(a), Value::Int32(b)) => Ok(Value::Float(a - b as f64)),
(Value::Int64(a), Value::Float(b)) => Ok(Value::Float(a as f64 - b)),
(Value::Float(a), Value::Int64(b)) => Ok(Value::Float(a - b as f64)),
_ => Err(OpError::Trap(TRAP_TYPE, "Invalid types for SUB".into())),
})?,
OpCode::Mul => self.binary_op(opcode, start_pc as u32, |a, b| match (a, b) {
(Value::Int32(a), Value::Int32(b)) => Ok(Value::Int32(a.wrapping_mul(b))),
(Value::Int64(a), Value::Int64(b)) => Ok(Value::Int64(a.wrapping_mul(b))),
(Value::Int32(a), Value::Int64(b)) => Ok(Value::Int64((a as i64).wrapping_mul(b))),
(Value::Int64(a), Value::Int32(b)) => Ok(Value::Int64(a.wrapping_mul(b as i64))),
(Value::Float(a), Value::Float(b)) => Ok(Value::Float(a * b)),
(Value::Int32(a), Value::Float(b)) => Ok(Value::Float(a as f64 * b)),
(Value::Float(a), Value::Int32(b)) => Ok(Value::Float(a * b as f64)),
(Value::Int64(a), Value::Float(b)) => Ok(Value::Float(a as f64 * b)),
(Value::Float(a), Value::Int64(b)) => Ok(Value::Float(a * b as f64)),
_ => Err(OpError::Trap(TRAP_TYPE, "Invalid types for MUL".into())),
})?,
OpCode::Div => self.binary_op(opcode, start_pc as u32, |a, b| match (a, b) {
(Value::Int32(a), Value::Int32(b)) => {
if b == 0 {
return Err(OpError::Trap(
TRAP_DIV_ZERO,
"Integer division by zero".into(),
));
}
Ok(Value::Int32(a.wrapping_div(b)))
}
(Value::Int64(a), Value::Int64(b)) => {
if b == 0 {
return Err(OpError::Trap(
TRAP_DIV_ZERO,
"Integer division by zero".into(),
));
}
Ok(Value::Int64(a.wrapping_div(b)))
}
(Value::Int32(a), Value::Int64(b)) => {
if b == 0 {
return Err(OpError::Trap(
TRAP_DIV_ZERO,
"Integer division by zero".into(),
));
}
Ok(Value::Int64((a as i64).wrapping_div(b)))
}
(Value::Int64(a), Value::Int32(b)) => {
if b == 0 {
return Err(OpError::Trap(
TRAP_DIV_ZERO,
"Integer division by zero".into(),
));
}
Ok(Value::Int64(a.wrapping_div(b as i64)))
}
(Value::Float(a), Value::Float(b)) => {
if b == 0.0 {
return Err(OpError::Trap(TRAP_DIV_ZERO, "Float division by zero".into()));
}
Ok(Value::Float(a / b))
}
(Value::Int32(a), Value::Float(b)) => {
if b == 0.0 {
return Err(OpError::Trap(TRAP_DIV_ZERO, "Float division by zero".into()));
}
Ok(Value::Float(a as f64 / b))
}
(Value::Float(a), Value::Int32(b)) => {
if b == 0 {
return Err(OpError::Trap(TRAP_DIV_ZERO, "Float division by zero".into()));
}
Ok(Value::Float(a / b as f64))
}
(Value::Int64(a), Value::Float(b)) => {
if b == 0.0 {
return Err(OpError::Trap(TRAP_DIV_ZERO, "Float division by zero".into()));
}
Ok(Value::Float(a as f64 / b))
}
(Value::Float(a), Value::Int64(b)) => {
if b == 0 {
return Err(OpError::Trap(TRAP_DIV_ZERO, "Float division by zero".into()));
}
Ok(Value::Float(a / b as f64))
}
_ => Err(OpError::Trap(TRAP_TYPE, "Invalid types for DIV".into())),
})?,
OpCode::Sub | OpCode::Mul | OpCode::Div => {
self.binary_op(opcode, start_pc as u32, |a, b| {
numeric::opcode_binary(opcode, &a, &b).map_err(|e| {
if e.code == TRAP_TYPE {
OpError::Trap(
TRAP_TYPE,
format!(
"Invalid types for {}",
format!("{opcode:?}").to_uppercase()
),
)
} else {
OpError::from(e)
}
})
})?
}
OpCode::Mod => self.binary_op(opcode, start_pc as u32, |a, b| match (a, b) {
(Value::Int32(a), Value::Int32(b)) => {
if b == 0 {
@@ -562,29 +501,33 @@ impl VirtualMachine {
}
_ => Err(OpError::Trap(TRAP_TYPE, "Invalid types for MOD".into())),
})?,
OpCode::Eq => {
self.binary_op(opcode, start_pc as u32, |a, b| Ok(Value::Boolean(a == b)))?
}
OpCode::Neq => {
self.binary_op(opcode, start_pc as u32, |a, b| Ok(Value::Boolean(a != b)))?
}
OpCode::Eq => self.binary_op(opcode, start_pc as u32, |a, b| {
numeric::equal_values(&a, &b).map(Value::Boolean).map_err(OpError::from)
})?,
OpCode::Neq => self.binary_op(opcode, start_pc as u32, |a, b| {
numeric::equal_values(&a, &b).map(|v| Value::Boolean(!v)).map_err(OpError::from)
})?,
OpCode::Lt => self.binary_op(opcode, start_pc as u32, |a, b| {
a.partial_cmp(&b)
numeric::compare_values(&a, &b)
.map_err(OpError::from)?
.map(|o| Value::Boolean(o == std::cmp::Ordering::Less))
.ok_or_else(|| OpError::Trap(TRAP_TYPE, "Invalid types for LT".into()))
})?,
OpCode::Gt => self.binary_op(opcode, start_pc as u32, |a, b| {
a.partial_cmp(&b)
numeric::compare_values(&a, &b)
.map_err(OpError::from)?
.map(|o| Value::Boolean(o == std::cmp::Ordering::Greater))
.ok_or_else(|| OpError::Trap(TRAP_TYPE, "Invalid types for GT".into()))
})?,
OpCode::Lte => self.binary_op(opcode, start_pc as u32, |a, b| {
a.partial_cmp(&b)
numeric::compare_values(&a, &b)
.map_err(OpError::from)?
.map(|o| Value::Boolean(o != std::cmp::Ordering::Greater))
.ok_or_else(|| OpError::Trap(TRAP_TYPE, "Invalid types for LTE".into()))
})?,
OpCode::Gte => self.binary_op(opcode, start_pc as u32, |a, b| {
a.partial_cmp(&b)
numeric::compare_values(&a, &b)
.map_err(OpError::from)?
.map(|o| Value::Boolean(o != std::cmp::Ordering::Less))
.ok_or_else(|| OpError::Trap(TRAP_TYPE, "Invalid types for GTE".into()))
})?,
@@ -657,7 +600,12 @@ impl VirtualMachine {
Value::Int64(a) => {
self.push_trap(Value::Int64(a.wrapping_neg()), opcode, start_pc as u32)?
}
Value::Float(a) => self.push_trap(Value::Float(-a), opcode, start_pc as u32)?,
Value::Float(a) => {
let result = numeric::neg(a).map_err(|e| {
self.trap(e.code, opcode as u16, format!("NEG: {e:?}"), start_pc as u32)
})?;
self.push_trap(Value::Float(result), opcode, start_pc as u32)?;
}
_ => {
return Err(self.trap(
TRAP_TYPE,
@@ -997,6 +945,15 @@ impl VirtualMachine {
),
pc_at_intrinsic,
),
crate::IntrinsicExecutionError::Numeric(error) => self.trap(
error.code,
opcode as u16,
format!(
"Intrinsic {}.{}: {:?}",
intrinsic.owner, intrinsic.name, error
),
pc_at_intrinsic,
),
crate::IntrinsicExecutionError::HardwareUnavailable => self.trap(
TRAP_UNAVAILABLE,
OpCode::Intrinsic as u16,
@@ -1027,6 +984,15 @@ impl VirtualMachine {
),
pc_at_intrinsic,
),
crate::IntrinsicExecutionError::Numeric(error) => self.trap(
error.code,
opcode as u16,
format!(
"Intrinsic {}.{} result: {:?}",
intrinsic.owner, intrinsic.name, error
),
pc_at_intrinsic,
),
crate::IntrinsicExecutionError::HardwareUnavailable => self.trap(
TRAP_UNAVAILABLE,
OpCode::Intrinsic as u16,
@@ -1073,7 +1039,7 @@ impl VirtualMachine {
}
// Control attempts were already charged before validation.
if !charged_control {
if !charged_control && charged_math.is_none() {
self.cycles += opcode.cycles();
}
Ok(())
@@ -34,11 +34,17 @@ impl VirtualMachine {
LogicalFrameEndingReason::Trap(self.program.create_trap(code, opcode, message, pc))
}
pub fn push(&mut self, val: Value) -> Result<(), ResourceFailure> {
let growth = self.operand_stack.prepare_growth(1)?;
let val = self.import_string_value(&val)?;
pub fn push(&mut self, val: Value) -> Result<(), VmFault> {
if matches!(&val,Value::Float(x) if !crate::numeric::finite(*x)) {
return Err(VmFault::Trap(
prometeu_bytecode::TRAP_NON_FINITE,
"Native stack import contains a non-finite Float".into(),
));
}
let growth = self.operand_stack.prepare_growth(1).map_err(VmFault::ResourceLimit)?;
let val = self.import_string_value(&val).map_err(VmFault::ResourceLimit)?;
self.operand_stack.commit_growth(growth);
self.operand_stack.push(val)
self.operand_stack.push(val).map_err(VmFault::ResourceLimit)
}
pub(super) fn push_trap(
@@ -20,6 +20,7 @@ impl VirtualMachine {
pub(super) fn value_error_code(error: ValueError) -> u32 {
match error {
ValueError::Type => TRAP_TYPE,
ValueError::NonFinite => prometeu_bytecode::TRAP_NON_FINITE,
ValueError::InvalidHandle => TRAP_INVALID_HANDLE,
ValueError::NullReference => TRAP_NULL_REFERENCE,
ValueError::Bounds => TRAP_OOB,
@@ -74,6 +75,12 @@ impl VirtualMachine {
if values.len() != slot {
return Err((slot, ValueError::Type));
}
// Validate the complete signature before classifying numeric content.
if let Some(slot) =
values.iter().position(|v| matches!(v,Value::Float(x) if !crate::numeric::finite(*x)))
{
return Err((slot, ValueError::NonFinite));
}
Ok(())
}
}