feat(vm): add reference identity and deterministic value hashing

This commit is contained in:
2026-10-23 14:29:00 +01:00
parent 57992cf214
commit 69ad1931de
41 changed files with 2521 additions and 121 deletions
@@ -379,18 +379,26 @@ pub fn assemble(src: &str) -> Result<Vec<u8>, AsmError> {
emit_u16(op as u16, &mut out);
emit_u32(parse_u32_any(ops)?, &mut out);
}
"DYN_PACK" | "DYN_UNPACK" | "DYN_CAN_UNPACK" => {
"DYN_PACK" | "DYN_UNPACK" | "DYN_CAN_UNPACK" | "REF_IDENTITY_HASH" => {
if ops.is_empty() {
return Err(AsmError::MissingOperand(line.into()));
}
let opcode = match mn {
"DYN_PACK" => CoreOpCode::DynPack,
"DYN_UNPACK" => CoreOpCode::DynUnpack,
"REF_IDENTITY_HASH" => CoreOpCode::RefIdentityHash,
_ => CoreOpCode::DynCanUnpack,
};
emit_u16(opcode as u16, &mut out);
emit_u32(parse_u32_any(ops)?, &mut out);
}
"REF_IDENTITY_EQ" => {
let (a, b) = parse_keyvals(ops)?;
let (left, right) = parse_pair(a, "left", b, "right")?;
emit_u16(CoreOpCode::RefIdentityEq as u16, &mut out);
emit_u32(left, &mut out);
emit_u32(right, &mut out);
}
"REF_IS_EXACT" | "REF_IMPLEMENTS" | "REF_TO_TRAIT" | "REF_CAST" => {
if ops.is_empty() {
return Err(AsmError::MissingOperand(line.into()));
@@ -21,9 +21,9 @@
//! - Floats use exact bit-pattern format to prevent locale/rounding differences.
//! - Ordering is the canonical decode order; no address prefixes are emitted.
use crate::DecodeError;
use crate::decode_next;
use crate::isa::core::{CoreOpCode, CoreOpCodeSpecExt};
use crate::DecodeError;
fn fmt_f64_bits(bits: u64) -> String {
// Fixed-width 16 hex digits, lowercase.
@@ -65,6 +65,7 @@ fn format_operand(op: CoreOpCode, imm: &[u8]) -> String {
| CoreOpCode::Hostcall
| CoreOpCode::DynPack
| CoreOpCode::DynUnpack
| CoreOpCode::RefIdentityHash
| CoreOpCode::DynCanUnpack
| CoreOpCode::StructNew
| CoreOpCode::ArrayNew
@@ -88,6 +89,11 @@ fn format_operand(op: CoreOpCode, imm: &[u8]) -> String {
let field = u32::from_le_bytes(imm[4..].try_into().unwrap());
format!("type={}, field={}", ty, field)
}
CoreOpCode::RefIdentityEq => {
let left = u32::from_le_bytes(imm[..4].try_into().unwrap());
let right = u32::from_le_bytes(imm[4..].try_into().unwrap());
format!("left={}, right={}", left, right)
}
CoreOpCode::RefIsExact
| CoreOpCode::RefImplements
| CoreOpCode::RefToTrait
@@ -192,6 +192,10 @@ pub enum OpCode {
RefToTrait = 0x95,
/// REF_CAST: source:TypeId, target:TypeId; requires validated Registry metadata.
RefCast = 0x96,
/// Query a complete typed reference identity; source TypeId.
RefIdentityHash = 0x97,
/// Compare two complete typed references; left/right TypeIds.
RefIdentityEq = 0x98,
// Registry-backed collection operations. cycles() is their base component.
StructNew = 0xA0,
@@ -278,6 +282,8 @@ impl TryFrom<u16> for OpCode {
0x94 => Ok(OpCode::RefImplements),
0x95 => Ok(OpCode::RefToTrait),
0x96 => Ok(OpCode::RefCast),
0x97 => Ok(OpCode::RefIdentityHash),
0x98 => Ok(OpCode::RefIdentityEq),
0xA0 => Ok(OpCode::StructNew),
0xA1 => Ok(OpCode::StructGet),
0xA2 => Ok(OpCode::StructSet),
@@ -360,6 +366,8 @@ impl OpCode {
OpCode::RefImplements => 4,
OpCode::RefToTrait => 5,
OpCode::RefCast => 4,
OpCode::RefIdentityHash => 8,
OpCode::RefIdentityEq => 4,
OpCode::StructNew => 8,
OpCode::StructGet => 3,
OpCode::StructSet => 4,
@@ -596,6 +596,26 @@ impl OpCodeSpecExt for OpCode {
may_trap: true,
is_safepoint: false,
},
OpCode::RefIdentityHash => OpcodeSpec {
name: "REF_IDENTITY_HASH",
imm_bytes: 4,
pops: None,
pushes: None,
is_branch: false,
is_terminator: false,
may_trap: true,
is_safepoint: false,
},
OpCode::RefIdentityEq => OpcodeSpec {
name: "REF_IDENTITY_EQ",
imm_bytes: 8,
pops: None,
pushes: None,
is_branch: false,
is_terminator: false,
may_trap: true,
is_safepoint: false,
},
OpCode::StructNew => OpcodeSpec {
name: "STRUCT_NEW",
imm_bytes: 4,
@@ -52,6 +52,19 @@ pub enum TypeKind {
Trait(Vec<MethodDecl>),
Fn(Signature),
}
impl TypeKind {
/// Categories supported by identity queries, not by legacy REF_* conversions.
pub fn is_identity_reference(&self) -> bool {
matches!(
self,
Self::Struct(_)
| Self::Array(_)
| Self::Fn(_)
| Self::Trait(_)
| Self::Builtin(BuiltinId::RANDOM)
)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TypeDecl {
pub name: Option<String>,
@@ -133,6 +133,23 @@ impl DecodedInstr<'_> {
};
(source_layout.storage.slots, pushes)
}
Op::RefIdentityHash | Op::RefIdentityEq => {
let (left, right) = if self.opcode == Op::RefIdentityHash {
(self.imm_u32().map_err(|_| malformed())?, None)
} else {
let (a, b) = self.imm_u32x2().map_err(|_| malformed())?;
(a, Some(b))
};
let mut pops = 0;
for id in std::iter::once(left).chain(right) {
let (decl, layout) = type_info(id)?;
if !decl.kind.is_identity_reference() {
return Err(bad_category(id));
}
pops += layout.storage.slots;
}
(pops, 1)
}
Op::FieldsPublish => {
let schema = self.imm_u32().map_err(|_| malformed())?;
let (decl, _) = type_info(schema)?;
@@ -210,7 +227,11 @@ impl DecodedInstr<'_> {
.get(field as usize)
.ok_or_else(|| bad_category(id).member(field))?;
let w = registry.type_layout(f.type_id).unwrap().storage.slots;
if op == Op::StructGet { (1, w) } else { (1 + w, 0) }
if op == Op::StructGet {
(1, w)
} else {
(1 + w, 0)
}
}
}
} else {
@@ -34,6 +34,8 @@ fn all_typed_instructions_match_independent_bytes_and_costs() {
("REF_IMPLEMENTS source=16909060, target=84281096", &[0x94, 0, 4, 3, 2, 1, 8, 7, 6, 5], 4),
("REF_TO_TRAIT source=16909060, target=84281096", &[0x95, 0, 4, 3, 2, 1, 8, 7, 6, 5], 5),
("REF_CAST source=16909060, target=84281096", &[0x96, 0, 4, 3, 2, 1, 8, 7, 6, 5], 4),
("REF_IDENTITY_HASH 16909060", &[0x97, 0, 4, 3, 2, 1], 8),
("REF_IDENTITY_EQ left=16909060, right=84281096", &[0x98, 0, 4, 3, 2, 1, 8, 7, 6, 5], 4),
];
for &(text, bytes, cycles) in cases {
assert_eq!(assemble(text).unwrap(), bytes);
@@ -49,8 +51,8 @@ fn all_typed_instructions_match_independent_bytes_and_costs() {
}
}
assert!(matches!(
decode_next(0, &[0x97, 0]),
Err(DecodeError::UnknownOpcode { opcode: 0x97, .. })
decode_next(0, &[0x99, 0]),
Err(DecodeError::UnknownOpcode { opcode: 0x99, .. })
));
}
#[test]
@@ -68,6 +70,8 @@ fn slot_effects_resolve_semantic_widths_and_reference_categories() {
("REF_TO_TRAIT source=4, target=6", 1, 2),
("REF_TO_TRAIT source=6, target=6", 2, 2),
("REF_CAST source=6, target=4", 2, 1),
("REF_IDENTITY_HASH 6", 2, 1),
("REF_IDENTITY_EQ left=6, right=4", 3, 1),
] {
let bytes = assemble(text).unwrap();
assert_eq!(
@@ -94,6 +98,9 @@ fn invalid_type_immediates_are_contextual_load_errors() {
"REF_IS_EXACT source=4, target=6",
"REF_TO_TRAIT source=4, target=0",
"REF_IMPLEMENTS source=0, target=6",
"REF_IDENTITY_HASH 0",
"REF_IDENTITY_HASH 3",
"REF_IDENTITY_EQ left=4, right=1",
] {
let bytes = assemble(text).unwrap();
let e = decode_next(0, &bytes).unwrap().registry_stack_effect(&registry).unwrap_err();
@@ -114,6 +121,10 @@ fn assembler_rejects_missing_overflowing_or_ambiguous_type_ids() {
"REF_CAST source=4",
"REF_CAST source=4, target=5, target=6",
"REF_CAST source=4, trait=6",
"REF_IDENTITY_HASH",
"REF_IDENTITY_HASH -1",
"REF_IDENTITY_EQ left=4",
"REF_IDENTITY_EQ left=4, target=5",
] {
assert!(assemble(text).is_err(), "{text}");
}