use prometeu_bytecode::{ Value, registry::{BuiltinId, StorageLayout}, }; use prometeu_hal::{HostContext, color::Color}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct BuiltinTypeKey { pub name: &'static str, pub version: u16, } impl BuiltinTypeKey { pub const fn new(name: &'static str, version: u16) -> Self { Self { name, version } } pub const fn key(self) -> (&'static str, u16) { (self.name, self.version) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct BuiltinConstKey { pub target: &'static str, pub name: &'static str, pub version: u16, } impl BuiltinConstKey { pub const fn new(target: &'static str, name: &'static str, version: u16) -> Self { Self { target, name, version } } pub const fn key(self) -> (&'static str, &'static str, u16) { (self.target, self.name, self.version) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct IntrinsicKey { pub owner: &'static str, pub name: &'static str, pub version: u16, } impl IntrinsicKey { pub const fn new(owner: &'static str, name: &'static str, version: u16) -> Self { Self { owner, name, version } } pub const fn key(self) -> (&'static str, &'static str, u16) { (self.owner, self.name, self.version) } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum BuiltinScalarType { Int32, Int64, Float, Bool, String, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum AbiType { /// Internal group components; neither can establish a valid Dynamic alone. DynamicTag, DynamicPayload, Scalar(BuiltinScalarType), Builtin(BuiltinTypeKey), } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum BuiltinLayoutType { Scalar(BuiltinScalarType), Builtin(BuiltinTypeKey), } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum BuiltinTypeShape { Scalar, Aggregate, Dynamic, Reference, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct BuiltinFieldMeta { pub name: &'static str, pub start_slot: u16, pub field_type: BuiltinLayoutType, pub flat_slot_width: u16, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct BuiltinTypeMeta { pub id: u32, pub name: &'static str, pub version: u16, pub shape: BuiltinTypeShape, pub fields: &'static [BuiltinFieldMeta], pub flat_slot_layout: &'static [AbiType], pub flat_slot_width: u16, } impl BuiltinTypeMeta { pub const fn key(&self) -> BuiltinTypeKey { BuiltinTypeKey::new(self.name, self.version) } pub fn field(&self, name: &str) -> Option<&'static BuiltinFieldMeta> { self.fields.iter().find(|field| field.name == name) } pub fn flatten_layout(&self) -> Vec { let mut out = Vec::with_capacity(self.flat_slot_width as usize); self.flatten_into(&mut out); out } pub fn storage_layout( &self, ) -> Result { BuiltinId(self.id).layout() } pub fn validate_flat_values(&self, values: &[Value]) -> Result<(), BuiltinValueError> { if self.shape == BuiltinTypeShape::Dynamic { if values.len() != 2 { return Err(BuiltinValueError::ArityMismatch { expected: 2, got: values.len() }); } if matches!(values, [Value::Null, Value::Null]) { return Ok(()); } // A non-null tag is a program TypeId, and its payload may be a box. // This context-free catalogue must never claim to validate it. return Err(BuiltinValueError::RegistryRequired); } if self.shape == BuiltinTypeShape::Reference { if values.len() != 1 { return Err(BuiltinValueError::ArityMismatch { expected: 1, got: values.len() }); } return if matches!(values, [Value::Null]) { Ok(()) } else { Err(BuiltinValueError::RegistryRequired) }; } let layout = self.flatten_layout(); validate_values_against_layout(values, &layout) } fn flatten_into(&self, out: &mut Vec) { match self.shape { BuiltinTypeShape::Scalar | BuiltinTypeShape::Dynamic | BuiltinTypeShape::Reference => { out.extend_from_slice(self.flat_slot_layout) } BuiltinTypeShape::Aggregate => { for field in self.fields { flatten_layout_type(field.field_type, out); } } } } } #[derive(Debug, Clone, Copy, PartialEq)] pub enum BuiltinConstSlotValue { Int32(i32), Int64(i64), Float(f64), Bool(bool), NominalBuiltin { builtin: BuiltinTypeKey, carrier: u32 }, } pub type BuiltinConstHook = fn() -> Vec; #[derive(Debug, Clone, Copy)] pub enum BuiltinConstMaterializer { Direct(&'static [BuiltinConstSlotValue]), Hook(BuiltinConstHook), } #[derive(Debug, Clone, Copy)] pub struct BuiltinConstMeta { pub key: BuiltinConstKey, pub flat_slot_layout: &'static [AbiType], pub flat_slot_width: u16, pub materializer: BuiltinConstMaterializer, } impl BuiltinConstMeta { pub fn direct_slots(&self) -> Option<&'static [BuiltinConstSlotValue]> { match self.materializer { BuiltinConstMaterializer::Direct(slots) => Some(slots), BuiltinConstMaterializer::Hook(_) => None, } } pub fn materialize(&self) -> Result, BuiltinValueError> { let values = match self.materializer { BuiltinConstMaterializer::Direct(slots) => { slots.iter().copied().map(BuiltinConstSlotValue::into_value).collect() } BuiltinConstMaterializer::Hook(hook) => hook(), }; validate_values_against_layout(&values, self.flat_slot_layout)?; Ok(values) } } #[derive(Debug, Clone, PartialEq, Eq)] pub enum IntrinsicExecutionError { ArityMismatch { expected: usize, got: usize }, TypeMismatch { index: usize, expected: AbiType }, HardwareUnavailable, Numeric(crate::numeric::NumericError), } #[derive(Debug, Clone, PartialEq, Eq)] pub enum BuiltinValueError { RegistryRequired, ArityMismatch { expected: usize, got: usize }, TypeMismatch { index: usize, expected: AbiType }, } pub type IntrinsicHostImplementation = fn(&[Value], &mut HostContext<'_>) -> Result, IntrinsicExecutionError>; /// VM-owned operations cannot be invoked through a HostContext callback. #[derive(Debug, Clone, Copy)] pub enum IntrinsicImplementation { Host(IntrinsicHostImplementation), VmOwned, BorrowedInline(crate::IntrinsicInlineImplementation), } impl IntrinsicImplementation { pub fn host_callback(self) -> Option { match self { Self::Host(f) => Some(f), Self::VmOwned | Self::BorrowedInline(_) => None, } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum IntrinsicCostModel { Fixed, RandomRejectionV1, ArgumentUtf8BytesV1, } impl IntrinsicCostModel { pub const fn name(self) -> &'static str { match self { Self::Fixed => "fixed", Self::RandomRejectionV1 => "random_rejection_v1", Self::ArgumentUtf8BytesV1 => "argument_utf8_bytes_v1", } } } #[derive(Debug, Clone, Copy)] pub struct IntrinsicMeta { pub id: u32, pub owner: &'static str, pub name: &'static str, pub version: u16, pub arg_layout: &'static [AbiType], pub arg_nullable: &'static [bool], pub ret_layout: &'static [AbiType], pub parameter_names: &'static [&'static str], /// Full fixed cost, or base cost for a variable model. pub cost_cycles: u64, pub cost_model: IntrinsicCostModel, pub cost_arg_index: Option, pub cost_per_byte: u64, pub attempt_cost_cycles: u64, pub max_attempts: u32, pub mutates_guest_state: bool, pub deterministic: bool, pub may_allocate: bool, pub implementation: IntrinsicImplementation, } impl IntrinsicMeta { pub const fn key(&self) -> IntrinsicKey { IntrinsicKey::new(self.owner, self.name, self.version) } pub fn arg_slots(&self) -> usize { self.arg_layout.len() } pub fn ret_slots(&self) -> usize { self.ret_layout.len() } pub fn validate_result_values(&self, values: &[Value]) -> Result<(), IntrinsicExecutionError> { Self::validate_values(values, self.ret_layout) } pub fn validate_argument_values( &self, values: &[Value], ) -> Result<(), IntrinsicExecutionError> { Self::validate_values(values, self.arg_layout)?; for (index, (value, nullable)) in values.iter().zip(self.arg_nullable).enumerate() { if matches!(value, Value::Null) && !nullable { return Err(IntrinsicExecutionError::TypeMismatch { index, expected: self.arg_layout[index], }); } } Ok(()) } fn validate_values( values: &[Value], layout: &[AbiType], ) -> Result<(), IntrinsicExecutionError> { if values.len() != layout.len() { return Err(IntrinsicExecutionError::ArityMismatch { expected: layout.len(), got: values.len(), }); } for (index, (value, expected)) in values.iter().zip(layout.iter()).enumerate() { if !value_matches_abi_type(value, *expected) { return Err(IntrinsicExecutionError::TypeMismatch { index, expected: *expected }); } } Ok(()) } } impl BuiltinConstSlotValue { pub fn into_value(self) -> Value { match self { BuiltinConstSlotValue::Int32(value) => Value::Int32(value), BuiltinConstSlotValue::Int64(value) => Value::Int64(value), BuiltinConstSlotValue::Float(value) => Value::Float(value), BuiltinConstSlotValue::Bool(value) => Value::Boolean(value), BuiltinConstSlotValue::NominalBuiltin { carrier, .. } => { Value::Int64(i64::from(carrier)) } } } } const COLOR: BuiltinTypeKey = BuiltinTypeKey::new("color", 1); const VEC2: BuiltinTypeKey = BuiltinTypeKey::new("vec2", 1); const PIXEL: BuiltinTypeKey = BuiltinTypeKey::new("pixel", 1); const COLOR_LAYOUT: [AbiType; 1] = [AbiType::Builtin(COLOR)]; const VEC2_LAYOUT: [AbiType; 2] = [AbiType::Scalar(BuiltinScalarType::Float), AbiType::Scalar(BuiltinScalarType::Float)]; const PIXEL_LAYOUT: [AbiType; 3] = [ AbiType::Scalar(BuiltinScalarType::Int64), AbiType::Scalar(BuiltinScalarType::Int64), AbiType::Builtin(COLOR), ]; const VEC2_FIELDS: [BuiltinFieldMeta; 2] = [ BuiltinFieldMeta { name: "x", start_slot: 0, field_type: BuiltinLayoutType::Scalar(BuiltinScalarType::Float), flat_slot_width: 1, }, BuiltinFieldMeta { name: "y", start_slot: 1, field_type: BuiltinLayoutType::Scalar(BuiltinScalarType::Float), flat_slot_width: 1, }, ]; const PIXEL_FIELDS: [BuiltinFieldMeta; 3] = [ BuiltinFieldMeta { name: "x", start_slot: 0, field_type: BuiltinLayoutType::Scalar(BuiltinScalarType::Int64), flat_slot_width: 1, }, BuiltinFieldMeta { name: "y", start_slot: 1, field_type: BuiltinLayoutType::Scalar(BuiltinScalarType::Int64), flat_slot_width: 1, }, BuiltinFieldMeta { name: "color", start_slot: 2, field_type: BuiltinLayoutType::Builtin(COLOR), flat_slot_width: 1, }, ]; const BUILTIN_TYPES: [BuiltinTypeMeta; 10] = [ BuiltinTypeMeta { id: 0x0001, name: COLOR.name, version: COLOR.version, shape: BuiltinTypeShape::Scalar, fields: &[], flat_slot_layout: &COLOR_LAYOUT, flat_slot_width: 1, }, BuiltinTypeMeta { id: 0x0002, name: VEC2.name, version: VEC2.version, shape: BuiltinTypeShape::Aggregate, fields: &VEC2_FIELDS, flat_slot_layout: &VEC2_LAYOUT, flat_slot_width: 2, }, BuiltinTypeMeta { id: 0x0003, name: PIXEL.name, version: PIXEL.version, shape: BuiltinTypeShape::Aggregate, fields: &PIXEL_FIELDS, flat_slot_layout: &PIXEL_LAYOUT, flat_slot_width: 3, }, BuiltinTypeMeta { id: 0x16, name: "Random", version: 1, shape: BuiltinTypeShape::Reference, fields: &[], flat_slot_layout: &[AbiType::Builtin(BuiltinTypeKey::new("Random", 1))], flat_slot_width: 1, }, scalar_meta(0x10, "Int32", &[AbiType::Scalar(BuiltinScalarType::Int32)]), scalar_meta(0x11, "Int64", &[AbiType::Scalar(BuiltinScalarType::Int64)]), scalar_meta(0x12, "Float", &[AbiType::Scalar(BuiltinScalarType::Float)]), scalar_meta(0x13, "Bool", &[AbiType::Scalar(BuiltinScalarType::Bool)]), scalar_meta(0x14, "String", &[AbiType::Scalar(BuiltinScalarType::String)]), BuiltinTypeMeta { id: 0x15, name: "Dynamic", version: 1, shape: BuiltinTypeShape::Dynamic, fields: &[], flat_slot_layout: &[AbiType::DynamicTag, AbiType::DynamicPayload], flat_slot_width: 2, }, ]; const fn scalar_meta(id: u32, name: &'static str, layout: &'static [AbiType]) -> BuiltinTypeMeta { BuiltinTypeMeta { id, name, version: 1, shape: BuiltinTypeShape::Scalar, fields: &[], flat_slot_layout: layout, flat_slot_width: 1, } } const VEC2_ZERO_LAYOUT: [AbiType; 2] = [AbiType::Scalar(BuiltinScalarType::Float), AbiType::Scalar(BuiltinScalarType::Float)]; const VEC2_ZERO_SLOTS: [BuiltinConstSlotValue; 2] = [BuiltinConstSlotValue::Float(0.0), BuiltinConstSlotValue::Float(0.0)]; const COLOR_BLACK_SLOTS: [BuiltinConstSlotValue; 1] = [BuiltinConstSlotValue::Int64(Color::BLACK.raw() as i64)]; const COLOR_WHITE_SLOTS: [BuiltinConstSlotValue; 1] = [BuiltinConstSlotValue::Int64(Color::WHITE.raw() as i64)]; const COLOR_RED_SLOTS: [BuiltinConstSlotValue; 1] = [BuiltinConstSlotValue::Int64(Color::RED.raw() as i64)]; const COLOR_GREEN_SLOTS: [BuiltinConstSlotValue; 1] = [BuiltinConstSlotValue::Int64(Color::GREEN.raw() as i64)]; const COLOR_BLUE_SLOTS: [BuiltinConstSlotValue; 1] = [BuiltinConstSlotValue::Int64(Color::BLUE.raw() as i64)]; const COLOR_YELLOW_SLOTS: [BuiltinConstSlotValue; 1] = [BuiltinConstSlotValue::Int64(Color::YELLOW.raw() as i64)]; const COLOR_ORANGE_SLOTS: [BuiltinConstSlotValue; 1] = [BuiltinConstSlotValue::Int64(Color::ORANGE.raw() as i64)]; const COLOR_INDIGO_SLOTS: [BuiltinConstSlotValue; 1] = [BuiltinConstSlotValue::Int64(Color::INDIGO.raw() as i64)]; const COLOR_GRAY_SLOTS: [BuiltinConstSlotValue; 1] = [BuiltinConstSlotValue::Int64(Color::GRAY.raw() as i64)]; const COLOR_CYAN_SLOTS: [BuiltinConstSlotValue; 1] = [BuiltinConstSlotValue::Int64(Color::CYAN.raw() as i64)]; const COLOR_MAGENTA_SLOTS: [BuiltinConstSlotValue; 1] = [BuiltinConstSlotValue::Int64(Color::MAGENTA.raw() as i64)]; const COLOR_TRANSPARENT_SLOTS: [BuiltinConstSlotValue; 1] = [BuiltinConstSlotValue::Int64(Color::TRANSPARENT.raw() as i64)]; 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, flat_slot_width: 2, materializer: BuiltinConstMaterializer::Direct(&VEC2_ZERO_SLOTS), }, color_const_meta("black", &COLOR_BLACK_SLOTS), color_const_meta("white", &COLOR_WHITE_SLOTS), color_const_meta("red", &COLOR_RED_SLOTS), color_const_meta("green", &COLOR_GREEN_SLOTS), color_const_meta("blue", &COLOR_BLUE_SLOTS), color_const_meta("yellow", &COLOR_YELLOW_SLOTS), color_const_meta("orange", &COLOR_ORANGE_SLOTS), color_const_meta("indigo", &COLOR_INDIGO_SLOTS), color_const_meta("gray", &COLOR_GRAY_SLOTS), color_const_meta("cyan", &COLOR_CYAN_SLOTS), color_const_meta("magenta", &COLOR_MAGENTA_SLOTS), color_const_meta("transparent", &COLOR_TRANSPARENT_SLOTS), ]; const fn color_const_meta( name: &'static str, slots: &'static [BuiltinConstSlotValue], ) -> BuiltinConstMeta { BuiltinConstMeta { key: BuiltinConstKey::new("color", name, 1), flat_slot_layout: &COLOR_LAYOUT, flat_slot_width: 1, materializer: BuiltinConstMaterializer::Direct(slots), } } const VEC2_DOT_ARGS: [AbiType; 4] = [ AbiType::Scalar(BuiltinScalarType::Float), AbiType::Scalar(BuiltinScalarType::Float), AbiType::Scalar(BuiltinScalarType::Float), AbiType::Scalar(BuiltinScalarType::Float), ]; const SINGLE_FLOAT_RET: [AbiType; 1] = [AbiType::Scalar(BuiltinScalarType::Float)]; const VEC2_LENGTH_ARGS: [AbiType; 2] = [AbiType::Scalar(BuiltinScalarType::Float), AbiType::Scalar(BuiltinScalarType::Float)]; const NO_ARGS: [AbiType; 0] = []; const COLOR_ARGS: [AbiType; 1] = [AbiType::Builtin(COLOR)]; const COLOR_RET: [AbiType; 1] = [AbiType::Builtin(COLOR)]; const COLOR_RGB_ARGS: [AbiType; 3] = [ AbiType::Scalar(BuiltinScalarType::Int64), AbiType::Scalar(BuiltinScalarType::Int64), AbiType::Scalar(BuiltinScalarType::Int64), ]; const COLOR_RGBA_ARGS: [AbiType; 4] = [ AbiType::Scalar(BuiltinScalarType::Int64), AbiType::Scalar(BuiltinScalarType::Int64), AbiType::Scalar(BuiltinScalarType::Int64), AbiType::Scalar(BuiltinScalarType::Int64), ]; const COLOR_HTML_RGBA_ARGS: [AbiType; 1] = [AbiType::Scalar(BuiltinScalarType::String)]; const INT_RET: [AbiType; 1] = [AbiType::Scalar(BuiltinScalarType::Int64)]; const INTRINSICS: [IntrinsicMeta; 21] = [ IntrinsicMeta { id: 0x1000, owner: "vec2", name: "dot", version: 1, arg_layout: &VEC2_DOT_ARGS, arg_nullable: &[false; VEC2_DOT_ARGS.len()], ret_layout: &SINGLE_FLOAT_RET, parameter_names: &["ax", "ay", "bx", "by"], cost_cycles: 10, cost_model: crate::IntrinsicCostModel::Fixed, cost_arg_index: None, cost_per_byte: 0, attempt_cost_cycles: 0, max_attempts: 0, mutates_guest_state: false, deterministic: true, may_allocate: false, implementation: crate::IntrinsicImplementation::Host(vec2_dot), }, IntrinsicMeta { id: 0x1001, owner: "vec2", name: "length", version: 1, arg_layout: &VEC2_LENGTH_ARGS, arg_nullable: &[false; VEC2_LENGTH_ARGS.len()], ret_layout: &SINGLE_FLOAT_RET, parameter_names: &["x", "y"], cost_cycles: 40, cost_model: crate::IntrinsicCostModel::Fixed, cost_arg_index: None, cost_per_byte: 0, attempt_cost_cycles: 0, max_attempts: 0, mutates_guest_state: false, deterministic: true, may_allocate: false, implementation: crate::IntrinsicImplementation::Host(vec2_length), }, IntrinsicMeta { id: 0x1100, owner: "color", name: "from_raw", version: 1, arg_layout: &INT_RET, arg_nullable: &[false; INT_RET.len()], ret_layout: &COLOR_RET, parameter_names: &["raw"], cost_cycles: 1, cost_model: crate::IntrinsicCostModel::Fixed, cost_arg_index: None, cost_per_byte: 0, attempt_cost_cycles: 0, max_attempts: 0, mutates_guest_state: false, deterministic: true, may_allocate: false, implementation: crate::IntrinsicImplementation::Host(color_from_raw), }, IntrinsicMeta { id: 0x1101, owner: "color", name: "rgb", version: 1, arg_layout: &COLOR_RGB_ARGS, arg_nullable: &[false; COLOR_RGB_ARGS.len()], ret_layout: &COLOR_RET, parameter_names: &["r", "g", "b"], cost_cycles: 1, cost_model: crate::IntrinsicCostModel::Fixed, cost_arg_index: None, cost_per_byte: 0, attempt_cost_cycles: 0, max_attempts: 0, mutates_guest_state: false, deterministic: true, may_allocate: false, implementation: crate::IntrinsicImplementation::Host(color_rgb), }, IntrinsicMeta { id: 0x1102, owner: "color", name: "rgba", version: 1, arg_layout: &COLOR_RGBA_ARGS, arg_nullable: &[false; COLOR_RGBA_ARGS.len()], ret_layout: &COLOR_RET, parameter_names: &["r", "g", "b", "a"], cost_cycles: 1, cost_model: crate::IntrinsicCostModel::Fixed, cost_arg_index: None, cost_per_byte: 0, attempt_cost_cycles: 0, max_attempts: 0, mutates_guest_state: false, deterministic: true, may_allocate: false, implementation: crate::IntrinsicImplementation::Host(color_rgba), }, IntrinsicMeta { id: 0x1103, owner: "color", name: "html_rgba", version: 1, arg_layout: &COLOR_HTML_RGBA_ARGS, arg_nullable: &[false; COLOR_HTML_RGBA_ARGS.len()], ret_layout: &COLOR_RET, parameter_names: &["value"], cost_cycles: 1, cost_model: crate::IntrinsicCostModel::Fixed, cost_arg_index: None, cost_per_byte: 0, attempt_cost_cycles: 0, max_attempts: 0, mutates_guest_state: false, deterministic: true, may_allocate: false, implementation: crate::IntrinsicImplementation::Host(color_html_rgba), }, IntrinsicMeta { id: 0x1104, owner: "color", name: "gray_scale", version: 1, arg_layout: &INT_RET, arg_nullable: &[false; INT_RET.len()], ret_layout: &COLOR_RET, parameter_names: &["value"], cost_cycles: 1, cost_model: crate::IntrinsicCostModel::Fixed, cost_arg_index: None, cost_per_byte: 0, attempt_cost_cycles: 0, max_attempts: 0, mutates_guest_state: false, deterministic: true, may_allocate: false, implementation: crate::IntrinsicImplementation::Host(color_gray_scale), }, IntrinsicMeta { id: 0x1105, owner: "color", name: "hex", version: 1, arg_layout: &COLOR_ARGS, arg_nullable: &[false; COLOR_ARGS.len()], ret_layout: &INT_RET, parameter_names: &["color"], cost_cycles: 1, cost_model: crate::IntrinsicCostModel::Fixed, cost_arg_index: None, cost_per_byte: 0, attempt_cost_cycles: 0, max_attempts: 0, mutates_guest_state: false, deterministic: true, may_allocate: false, implementation: crate::IntrinsicImplementation::Host(color_hex), }, IntrinsicMeta { id: 0x1106, owner: "color", name: "alpha", version: 1, arg_layout: &COLOR_ARGS, arg_nullable: &[false; COLOR_ARGS.len()], ret_layout: &INT_RET, parameter_names: &["color"], cost_cycles: 1, cost_model: crate::IntrinsicCostModel::Fixed, cost_arg_index: None, cost_per_byte: 0, attempt_cost_cycles: 0, max_attempts: 0, mutates_guest_state: false, deterministic: true, may_allocate: false, implementation: crate::IntrinsicImplementation::Host(color_alpha), }, IntrinsicMeta { id: 0x1120, owner: "color", name: "black", version: 1, arg_layout: &NO_ARGS, arg_nullable: &[false; NO_ARGS.len()], ret_layout: &COLOR_RET, parameter_names: &[], cost_cycles: 1, cost_model: crate::IntrinsicCostModel::Fixed, cost_arg_index: None, cost_per_byte: 0, attempt_cost_cycles: 0, max_attempts: 0, mutates_guest_state: false, deterministic: true, may_allocate: false, implementation: crate::IntrinsicImplementation::Host(color_black), }, IntrinsicMeta { id: 0x1121, owner: "color", name: "white", version: 1, arg_layout: &NO_ARGS, arg_nullable: &[false; NO_ARGS.len()], ret_layout: &COLOR_RET, parameter_names: &[], cost_cycles: 1, cost_model: crate::IntrinsicCostModel::Fixed, cost_arg_index: None, cost_per_byte: 0, attempt_cost_cycles: 0, max_attempts: 0, mutates_guest_state: false, deterministic: true, may_allocate: false, implementation: crate::IntrinsicImplementation::Host(color_white), }, IntrinsicMeta { id: 0x1122, owner: "color", name: "red", version: 1, arg_layout: &NO_ARGS, arg_nullable: &[false; NO_ARGS.len()], ret_layout: &COLOR_RET, parameter_names: &[], cost_cycles: 1, cost_model: crate::IntrinsicCostModel::Fixed, cost_arg_index: None, cost_per_byte: 0, attempt_cost_cycles: 0, max_attempts: 0, mutates_guest_state: false, deterministic: true, may_allocate: false, implementation: crate::IntrinsicImplementation::Host(color_red), }, IntrinsicMeta { id: 0x1123, owner: "color", name: "green", version: 1, arg_layout: &NO_ARGS, arg_nullable: &[false; NO_ARGS.len()], ret_layout: &COLOR_RET, parameter_names: &[], cost_cycles: 1, cost_model: crate::IntrinsicCostModel::Fixed, cost_arg_index: None, cost_per_byte: 0, attempt_cost_cycles: 0, max_attempts: 0, mutates_guest_state: false, deterministic: true, may_allocate: false, implementation: crate::IntrinsicImplementation::Host(color_green), }, IntrinsicMeta { id: 0x1124, owner: "color", name: "blue", version: 1, arg_layout: &NO_ARGS, arg_nullable: &[false; NO_ARGS.len()], ret_layout: &COLOR_RET, parameter_names: &[], cost_cycles: 1, cost_model: crate::IntrinsicCostModel::Fixed, cost_arg_index: None, cost_per_byte: 0, attempt_cost_cycles: 0, max_attempts: 0, mutates_guest_state: false, deterministic: true, may_allocate: false, implementation: crate::IntrinsicImplementation::Host(color_blue), }, IntrinsicMeta { id: 0x1125, owner: "color", name: "yellow", version: 1, arg_layout: &NO_ARGS, arg_nullable: &[false; NO_ARGS.len()], ret_layout: &COLOR_RET, parameter_names: &[], cost_cycles: 1, cost_model: crate::IntrinsicCostModel::Fixed, cost_arg_index: None, cost_per_byte: 0, attempt_cost_cycles: 0, max_attempts: 0, mutates_guest_state: false, deterministic: true, may_allocate: false, implementation: crate::IntrinsicImplementation::Host(color_yellow), }, IntrinsicMeta { id: 0x1126, owner: "color", name: "orange", version: 1, arg_layout: &NO_ARGS, arg_nullable: &[false; NO_ARGS.len()], ret_layout: &COLOR_RET, parameter_names: &[], cost_cycles: 1, cost_model: crate::IntrinsicCostModel::Fixed, cost_arg_index: None, cost_per_byte: 0, attempt_cost_cycles: 0, max_attempts: 0, mutates_guest_state: false, deterministic: true, may_allocate: false, implementation: crate::IntrinsicImplementation::Host(color_orange), }, IntrinsicMeta { id: 0x1127, owner: "color", name: "indigo", version: 1, arg_layout: &NO_ARGS, arg_nullable: &[false; NO_ARGS.len()], ret_layout: &COLOR_RET, parameter_names: &[], cost_cycles: 1, cost_model: crate::IntrinsicCostModel::Fixed, cost_arg_index: None, cost_per_byte: 0, attempt_cost_cycles: 0, max_attempts: 0, mutates_guest_state: false, deterministic: true, may_allocate: false, implementation: crate::IntrinsicImplementation::Host(color_indigo), }, IntrinsicMeta { id: 0x1128, owner: "color", name: "gray", version: 1, arg_layout: &NO_ARGS, arg_nullable: &[false; NO_ARGS.len()], ret_layout: &COLOR_RET, parameter_names: &[], cost_cycles: 1, cost_model: crate::IntrinsicCostModel::Fixed, cost_arg_index: None, cost_per_byte: 0, attempt_cost_cycles: 0, max_attempts: 0, mutates_guest_state: false, deterministic: true, may_allocate: false, implementation: crate::IntrinsicImplementation::Host(color_gray), }, IntrinsicMeta { id: 0x1129, owner: "color", name: "cyan", version: 1, arg_layout: &NO_ARGS, arg_nullable: &[false; NO_ARGS.len()], ret_layout: &COLOR_RET, parameter_names: &[], cost_cycles: 1, cost_model: crate::IntrinsicCostModel::Fixed, cost_arg_index: None, cost_per_byte: 0, attempt_cost_cycles: 0, max_attempts: 0, mutates_guest_state: false, deterministic: true, may_allocate: false, implementation: crate::IntrinsicImplementation::Host(color_cyan), }, IntrinsicMeta { id: 0x112A, owner: "color", name: "magenta", version: 1, arg_layout: &NO_ARGS, arg_nullable: &[false; NO_ARGS.len()], ret_layout: &COLOR_RET, parameter_names: &[], cost_cycles: 1, cost_model: crate::IntrinsicCostModel::Fixed, cost_arg_index: None, cost_per_byte: 0, attempt_cost_cycles: 0, max_attempts: 0, mutates_guest_state: false, deterministic: true, may_allocate: false, implementation: crate::IntrinsicImplementation::Host(color_magenta), }, IntrinsicMeta { id: 0x112B, owner: "color", name: "transparent", version: 1, arg_layout: &NO_ARGS, arg_nullable: &[false; NO_ARGS.len()], ret_layout: &COLOR_RET, parameter_names: &[], cost_cycles: 1, cost_model: crate::IntrinsicCostModel::Fixed, cost_arg_index: None, cost_per_byte: 0, attempt_cost_cycles: 0, max_attempts: 0, mutates_guest_state: false, deterministic: true, may_allocate: false, implementation: crate::IntrinsicImplementation::Host(color_transparent), }, ]; pub fn lookup_builtin_type(name: &str, version: u16) -> Option<&'static BuiltinTypeMeta> { BUILTIN_TYPES.iter().find(|meta| meta.name == name && meta.version == version) } pub fn lookup_builtin_constant( target: &str, name: &str, version: u16, ) -> Option<&'static BuiltinConstMeta> { BUILTIN_CONSTS.iter().find(|meta| { meta.key.target == target && meta.key.name == name && meta.key.version == version }) } pub fn materialize_builtin_constant( target: &str, name: &str, version: u16, ) -> Result>, BuiltinValueError> { lookup_builtin_constant(target, name, version).map(BuiltinConstMeta::materialize).transpose() } pub fn lookup_intrinsic(owner: &str, name: &str, version: u16) -> Option<&'static IntrinsicMeta> { INTRINSICS .iter() .chain(crate::input_intrinsics::INPUT_INTRINSICS.iter()) .chain(crate::math_intrinsics::MATH_INTRINSICS.iter()) .chain(crate::random_intrinsics::RANDOM_INTRINSICS.iter()) .chain(crate::hash_intrinsics::HASH_INTRINSICS.iter()) .find(|meta| meta.owner == owner && meta.name == name && meta.version == version) } 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()) .chain(crate::random_intrinsics::RANDOM_INTRINSICS.iter()) .chain(crate::hash_intrinsics::HASH_INTRINSICS.iter()) .find(|meta| meta.id == id) } fn flatten_layout_type(layout_type: BuiltinLayoutType, out: &mut Vec) { match layout_type { BuiltinLayoutType::Scalar(scalar) => out.push(AbiType::Scalar(scalar)), BuiltinLayoutType::Builtin(key) => { let meta = lookup_builtin_type(key.name, key.version).unwrap_or_else(|| { panic!("missing builtin metadata for {}@{}", key.name, key.version) }); meta.flatten_into(out); } } } fn expect_float_arg(args: &[Value], index: usize) -> Result { let value = args .get(index) .ok_or(IntrinsicExecutionError::ArityMismatch { expected: index + 1, got: args.len() })?; match value { Value::Float(value) => Ok(*value), _ => Err(IntrinsicExecutionError::TypeMismatch { index, expected: AbiType::Scalar(BuiltinScalarType::Float), }), } } fn expect_int_arg(args: &[Value], index: usize) -> Result { let value = args .get(index) .ok_or(IntrinsicExecutionError::ArityMismatch { expected: index + 1, got: args.len() })?; match value { Value::Int64(value) => Ok(*value), _ => Err(IntrinsicExecutionError::TypeMismatch { index, expected: AbiType::Scalar(BuiltinScalarType::Int64), }), } } fn expect_string_arg(args: &[Value], index: usize) -> Result<&str, IntrinsicExecutionError> { let value = args .get(index) .ok_or(IntrinsicExecutionError::ArityMismatch { expected: index + 1, got: args.len() })?; match value { Value::String(value) => Ok(value.as_ref()), _ => Err(IntrinsicExecutionError::TypeMismatch { index, expected: AbiType::Scalar(BuiltinScalarType::String), }), } } fn value_matches_abi_type(value: &Value, expected: AbiType) -> bool { match expected { AbiType::Scalar(BuiltinScalarType::Int32) => matches!(value, Value::Int32(_)), AbiType::Scalar(BuiltinScalarType::Int64) => matches!(value, Value::Int64(_)), AbiType::Scalar(BuiltinScalarType::Float) => matches!(value, Value::Float(_)), AbiType::Scalar(BuiltinScalarType::Bool) => matches!(value, Value::Boolean(_)), AbiType::Scalar(BuiltinScalarType::String) => { matches!(value, Value::String(_) | Value::Null) } AbiType::Builtin(key) if key.name == "Random" && key.version == 1 => { matches!(value, Value::HeapRef(_) | Value::Null) } AbiType::Builtin(key) if key == COLOR => { matches!(value, Value::Int64(raw) if u32::try_from(*raw).is_ok()) } AbiType::Builtin(_) | AbiType::DynamicTag | AbiType::DynamicPayload => false, } } fn validate_values_against_layout( values: &[Value], layout: &[AbiType], ) -> Result<(), BuiltinValueError> { if values.len() != layout.len() { return Err(BuiltinValueError::ArityMismatch { expected: layout.len(), got: values.len() }); } for (index, (value, expected)) in values.iter().zip(layout.iter()).enumerate() { if !value_matches_abi_type(value, *expected) { return Err(BuiltinValueError::TypeMismatch { index, expected: *expected }); } } Ok(()) } fn vec2_dot( args: &[Value], _ctx: &mut HostContext<'_>, ) -> Result, IntrinsicExecutionError> { lookup_intrinsic_by_id(0x1000).unwrap().validate_argument_values(args)?; if args.len() != 4 { return Err(IntrinsicExecutionError::ArityMismatch { expected: 4, got: args.len() }); } let ax = expect_float_arg(args, 0)?; 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(crate::numeric::dot([ax, ay, bx, by])?)]) } fn vec2_length( args: &[Value], _ctx: &mut HostContext<'_>, ) -> Result, IntrinsicExecutionError> { 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(crate::numeric::length(x, y)?)]) } fn color_value(color: Color) -> Vec { vec![Value::Int64(color.raw() as i64)] } fn expect_color_arg(args: &[Value], index: usize) -> Result { let raw = u32::try_from(expect_int_arg(args, index)?).map_err(|_| { IntrinsicExecutionError::TypeMismatch { index, expected: AbiType::Builtin(COLOR) } })?; Ok(Color::from_raw(raw)) } fn expect_channel(args: &[Value], index: usize) -> Result { let value = expect_int_arg(args, index)?; u8::try_from(value).map_err(|_| IntrinsicExecutionError::TypeMismatch { index, expected: AbiType::Scalar(BuiltinScalarType::Int64), }) } fn parse_html_rgba(value: &str) -> Option { let hex = value.strip_prefix('#').unwrap_or(value); if hex.len() != 8 || !hex.as_bytes().iter().all(u8::is_ascii_hexdigit) { return None; } Some(Color::from_raw(u32::from_str_radix(hex, 16).ok()?)) } fn color_from_raw( args: &[Value], _ctx: &mut HostContext<'_>, ) -> Result, IntrinsicExecutionError> { let raw = u32::try_from(expect_int_arg(args, 0)?).map_err(|_| { IntrinsicExecutionError::TypeMismatch { index: 0, expected: AbiType::Scalar(BuiltinScalarType::Int64), } })?; Ok(color_value(Color::from_raw(raw))) } fn color_rgb( args: &[Value], _ctx: &mut HostContext<'_>, ) -> Result, IntrinsicExecutionError> { Ok(color_value(Color::rgb( expect_channel(args, 0)?, expect_channel(args, 1)?, expect_channel(args, 2)?, ))) } fn color_rgba( args: &[Value], _ctx: &mut HostContext<'_>, ) -> Result, IntrinsicExecutionError> { Ok(color_value(Color::rgba( expect_channel(args, 0)?, expect_channel(args, 1)?, expect_channel(args, 2)?, expect_channel(args, 3)?, ))) } fn color_html_rgba( args: &[Value], _ctx: &mut HostContext<'_>, ) -> Result, IntrinsicExecutionError> { let color = parse_html_rgba(expect_string_arg(args, 0)?).ok_or({ IntrinsicExecutionError::TypeMismatch { index: 0, expected: AbiType::Scalar(BuiltinScalarType::String), } })?; Ok(color_value(color)) } fn color_gray_scale( args: &[Value], _ctx: &mut HostContext<'_>, ) -> Result, IntrinsicExecutionError> { Ok(color_value(Color::gray_scale(expect_channel(args, 0)?))) } fn color_hex( args: &[Value], _ctx: &mut HostContext<'_>, ) -> Result, IntrinsicExecutionError> { Ok(vec![Value::Int64(expect_color_arg(args, 0)?.hex() as i64)]) } fn color_alpha( args: &[Value], _ctx: &mut HostContext<'_>, ) -> Result, IntrinsicExecutionError> { Ok(vec![Value::Int64(expect_color_arg(args, 0)?.alpha() as i64)]) } fn color_const(color: Color) -> Result, IntrinsicExecutionError> { Ok(color_value(color)) } fn color_black( _: &[Value], _: &mut HostContext<'_>, ) -> Result, IntrinsicExecutionError> { color_const(Color::BLACK) } fn color_white( _: &[Value], _: &mut HostContext<'_>, ) -> Result, IntrinsicExecutionError> { color_const(Color::WHITE) } fn color_red(_: &[Value], _: &mut HostContext<'_>) -> Result, IntrinsicExecutionError> { color_const(Color::RED) } fn color_green( _: &[Value], _: &mut HostContext<'_>, ) -> Result, IntrinsicExecutionError> { color_const(Color::GREEN) } fn color_blue(_: &[Value], _: &mut HostContext<'_>) -> Result, IntrinsicExecutionError> { color_const(Color::BLUE) } fn color_yellow( _: &[Value], _: &mut HostContext<'_>, ) -> Result, IntrinsicExecutionError> { color_const(Color::YELLOW) } fn color_orange( _: &[Value], _: &mut HostContext<'_>, ) -> Result, IntrinsicExecutionError> { color_const(Color::ORANGE) } fn color_indigo( _: &[Value], _: &mut HostContext<'_>, ) -> Result, IntrinsicExecutionError> { color_const(Color::INDIGO) } fn color_gray(_: &[Value], _: &mut HostContext<'_>) -> Result, IntrinsicExecutionError> { color_const(Color::GRAY) } fn color_cyan(_: &[Value], _: &mut HostContext<'_>) -> Result, IntrinsicExecutionError> { color_const(Color::CYAN) } fn color_magenta( _: &[Value], _: &mut HostContext<'_>, ) -> Result, IntrinsicExecutionError> { color_const(Color::MAGENTA) } fn color_transparent( _: &[Value], _: &mut HostContext<'_>, ) -> Result, IntrinsicExecutionError> { color_const(Color::TRANSPARENT) } /// Loader-side lookup charges each catalogue record before examining it. pub(crate) fn metered_lookup_intrinsic( id: u32, budget: &mut prometeu_bytecode::load_limits::LoadBudget, ) -> Result, prometeu_bytecode::load_limits::LoadFailure> { for meta in INTRINSICS .iter() .chain(crate::input_intrinsics::INPUT_INTRINSICS.iter()) .chain(crate::math_intrinsics::MATH_INTRINSICS.iter()) .chain(crate::random_intrinsics::RANDOM_INTRINSICS.iter()) .chain(crate::hash_intrinsics::HASH_INTRINSICS.iter()) { budget.work(1)?; if meta.id == id { budget.work(meta.arg_slots() + 1)?; meta.validate_descriptor().map_err(|_| { prometeu_bytecode::load_limits::LoadFailure::new( prometeu_bytecode::load_limits::LoadCode::InvalidCode, prometeu_bytecode::load_limits::LoadReason::NativeId, ) })?; return Ok(Some(meta)); } } Ok(None) } /// Runtime-owned catalogue, including input and scalar math. pub fn intrinsic_catalog() -> impl Iterator { INTRINSICS .iter() .chain(crate::input_intrinsics::INPUT_INTRINSICS.iter()) .chain(crate::math_intrinsics::MATH_INTRINSICS.iter()) .chain(crate::random_intrinsics::RANDOM_INTRINSICS.iter()) .chain(crate::hash_intrinsics::HASH_INTRINSICS.iter()) } pub fn builtin_constant_catalog() -> impl Iterator { BUILTIN_CONSTS.iter() } #[cfg(test)] mod tests { use super::*; #[test] fn builtin_lookup_uses_canonical_identity() { let color = lookup_builtin_type("color", 1).expect("color builtin must exist"); assert_eq!(color.key(), COLOR); assert!(lookup_builtin_type("Color", 1).is_none()); assert!(lookup_builtin_type("color", 2).is_none()); } #[test] fn builtin_layout_flattening_matches_expected_widths() { let color = lookup_builtin_type("color", 1).expect("color builtin must exist"); assert_eq!(color.flatten_layout(), vec![AbiType::Builtin(COLOR)]); assert_eq!(color.flat_slot_width, 1); let vec2 = lookup_builtin_type("vec2", 1).expect("vec2 builtin must exist"); assert_eq!(vec2.flatten_layout(), vec![AbiType::Scalar(BuiltinScalarType::Float); 2]); assert_eq!(vec2.flat_slot_width, 2); let pixel = lookup_builtin_type("pixel", 1).expect("pixel builtin must exist"); assert_eq!( pixel.flatten_layout(), vec![ AbiType::Scalar(BuiltinScalarType::Int64), AbiType::Scalar(BuiltinScalarType::Int64), AbiType::Builtin(COLOR), ] ); assert_eq!(pixel.flat_slot_width, 3); } #[test] fn builtin_field_offsets_are_stable() { let vec2 = lookup_builtin_type("vec2", 1).expect("vec2 builtin must exist"); assert_eq!(vec2.field("x").map(|field| field.start_slot), Some(0)); assert_eq!(vec2.field("y").map(|field| field.start_slot), Some(1)); let pixel = lookup_builtin_type("pixel", 1).expect("pixel builtin must exist"); let color_field = pixel.field("color").expect("pixel.color must exist"); assert_eq!(color_field.start_slot, 2); assert_eq!(color_field.flat_slot_width, 1); } #[test] fn builtin_constant_registry_is_separate_from_intrinsics() { let zero = lookup_builtin_constant("vec2", "zero", 1).expect("vec2.zero must exist"); assert_eq!(zero.key, BuiltinConstKey::new("vec2", "zero", 1)); assert_eq!(zero.flat_slot_width, 2); assert_eq!(zero.flat_slot_layout, &VEC2_ZERO_LAYOUT); assert_eq!(zero.direct_slots(), Some(&VEC2_ZERO_SLOTS[..])); assert!(lookup_intrinsic("vec2", "zero", 1).is_none()); } #[test] fn builtin_constant_materializes_vec2_zero() { let zero = lookup_builtin_constant("vec2", "zero", 1).expect("vec2.zero must exist"); let materialized = zero.materialize().expect("vec2.zero must materialize"); assert_eq!(materialized, vec![Value::Float(0.0), Value::Float(0.0)]); let looked_up = materialize_builtin_constant("vec2", "zero", 1) .expect("materialization lookup must succeed") .expect("constant must exist"); assert_eq!(looked_up, materialized); } #[test] fn builtin_constant_materializes_color_values() { let red = materialize_builtin_constant("color", "red", 1) .expect("materialization lookup must succeed") .expect("constant must exist"); assert_eq!(red, vec![Value::Int64(Color::RED.raw() as i64)]); let transparent = materialize_builtin_constant("color", "transparent", 1) .expect("materialization lookup must succeed") .expect("constant must exist"); assert_eq!(transparent, vec![Value::Int64(Color::TRANSPARENT.raw() as i64)]); } #[test] fn intrinsic_metadata_exposes_arg_and_return_layouts() { let dot = lookup_intrinsic("vec2", "dot", 1).expect("vec2.dot must exist"); assert_eq!(dot.arg_layout.len(), 4); assert_eq!(dot.ret_layout.len(), 1); assert!(dot.deterministic); assert!(!dot.may_allocate); let length = lookup_intrinsic("vec2", "length", 1).expect("vec2.length must exist"); assert_eq!(length.arg_layout.len(), 2); assert_eq!(length.ret_layout.len(), 1); assert_eq!(lookup_intrinsic_by_id(length.id).map(|meta| meta.key()), Some(length.key())); let hold = lookup_intrinsic("input.pad.up", "hold", 1).expect("input.pad.up.hold must exist"); assert_eq!(hold.arg_layout.len(), 0); assert_eq!(hold.ret_layout.len(), 1); assert!(hold.deterministic); assert!(!hold.may_allocate); } #[test] fn intrinsic_implementations_are_registered_without_syscalls() { let dot = lookup_intrinsic("vec2", "dot", 1).expect("vec2.dot must exist"); let mut ctx = HostContext::new(None); let result = (dot.implementation.host_callback().expect("host intrinsic"))( &[Value::Float(1.0), Value::Float(2.0), Value::Float(3.0), Value::Float(4.0)], &mut ctx, ) .expect("dot implementation must execute"); assert_eq!(result, vec![Value::Float(11.0)]); let length = lookup_intrinsic("vec2", "length", 1).expect("vec2.length must exist"); let result = (length.implementation.host_callback().expect("host intrinsic"))( &[Value::Float(3.0), Value::Float(4.0)], &mut ctx, ) .expect("length implementation must execute"); assert_eq!(result, vec![Value::Float(5.0)]); } #[test] fn color_intrinsics_construct_and_project_rgba8888() { let mut ctx = HostContext::new(None); let rgba = lookup_intrinsic("color", "rgba", 1).expect("color.rgba must exist"); let result = (rgba.implementation.host_callback().expect("host intrinsic"))( &[Value::Int64(0x11), Value::Int64(0x22), Value::Int64(0x33), Value::Int64(0x44)], &mut ctx, ) .expect("rgba implementation must execute"); assert_eq!(result, vec![Value::Int64(0x11223344)]); let html = lookup_intrinsic("color", "html_rgba", 1).expect("color.html_rgba must exist"); let result = (html.implementation.host_callback().expect("host intrinsic"))( &[Value::String("#AABBCCDD".into())], &mut ctx, ) .expect("html_rgba implementation must execute"); assert_eq!(result, vec![Value::Int64(0xAABBCCDD)]); let alpha = lookup_intrinsic("color", "alpha", 1).expect("color.alpha must exist"); let result = (alpha.implementation.host_callback().expect("host intrinsic"))( &[Value::Int64(0xAABBCCDD)], &mut ctx, ) .expect("alpha implementation must execute"); assert_eq!(result, vec![Value::Int64(0xDD)]); } #[test] fn input_intrinsic_requires_hardware_context() { let mut ctx = HostContext::new(None); let touch_x = lookup_intrinsic("input.touch", "x", 1).expect("input.touch.x must exist"); let err = (touch_x.implementation.host_callback().expect("host intrinsic"))(&[], &mut ctx) .expect_err("touch.x must fail without hardware context"); assert_eq!(err, IntrinsicExecutionError::HardwareUnavailable); } #[test] fn pixel_flat_values_validate_with_color_carrier_slot() { let pixel = lookup_builtin_type("pixel", 1).expect("pixel builtin must exist"); let values = vec![Value::Int64(1), Value::Int64(2), Value::Int64(0xF800)]; pixel.validate_flat_values(&values).expect("pixel flat values must validate"); assert_eq!(pixel.flat_slot_width, 3); assert_eq!(pixel.field("color").map(|field| field.start_slot), Some(2)); } }