Files
prometeu-runtime/crates/console/prometeu-bytecode/src/registry.rs
T
bquarkz 6c2a07e579
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good
feat(runtime): implement shared transactional memcard with async saves
2026-10-13 15:24:01 +01:00

834 lines
31 KiB
Rust

//! Typed PBX declarations and bounded immutable Registry resolution.
//! These declarations do not authorize execution: code and bindings still require verification.
use crate::load_limits::IdDomain;
use crate::load_limits::{
LoadBudget, LoadCode as C, LoadFailure as E, LoadReason as R, LoadResource as Q,
};
use crate::Value;
use std::sync::Arc;
macro_rules! id {
($name:ident) => {
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct $name(pub u32);
};
}
id!(TypeId);
id!(FunctionId);
id!(ImplementationId);
id!(BuiltinId);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NamedType {
pub type_id: TypeId,
pub name: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Signature {
pub parameters: Vec<NamedType>,
pub results: Vec<TypeId>,
}
impl Signature {
pub fn same_types(&self, other: &Self) -> bool {
self.parameters.len() == other.parameters.len()
&& self
.parameters
.iter()
.map(|p| p.type_id)
.eq(other.parameters.iter().map(|p| p.type_id))
&& self.results == other.results
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MethodDecl {
pub name: Option<String>,
pub signature: Signature,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TypeKind {
Builtin(BuiltinId),
Struct(Vec<NamedType>),
Array(TypeId),
Trait(Vec<MethodDecl>),
Fn(Signature),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TypeDecl {
pub name: Option<String>,
pub kind: TypeKind,
}
/// Runtime-owned roles; frontend names and FunctionIds are independent.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[repr(u8)]
pub enum LifecycleRole {
#[default]
None = 0,
BeforePause = 1,
BeforeResume = 2,
MemcardBoot = 3,
}
impl TryFrom<u8> for LifecycleRole {
type Error = E;
fn try_from(value: u8) -> Result<Self, E> {
match value {
0 => Ok(Self::None),
1 => Ok(Self::BeforePause),
2 => Ok(Self::BeforeResume),
3 => Ok(Self::MemcardBoot),
_ => Err(E::new(C::InvalidRegistry, R::LifecycleRole)),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FunctionDecl {
pub lifecycle_role: LifecycleRole,
pub name: Option<String>,
pub signature: Signature,
pub code_offset: u32,
pub code_len: u32,
pub local_slots: u32,
pub max_stack_slots: u32,
/// Ordered logical capture groups, encoded in the separate PBX section 8.
pub captures: Vec<TypeId>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImplementationDecl {
pub owner: TypeId,
pub trait_id: TypeId,
pub methods: Vec<FunctionId>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RegistryDeclarations {
pub types: Vec<TypeDecl>,
pub functions: Vec<FunctionDecl>,
pub implementations: Vec<ImplementationDecl>,
}
pub type StringSlot = Option<Arc<str>>;
#[derive(Debug, Clone)]
pub struct DynamicSlot {
pub type_id: Option<TypeId>,
pub payload: Value,
}
impl Default for DynamicSlot {
fn default() -> Self {
Self { type_id: None, payload: Value::Null }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DefaultKind {
Int32,
Int64,
Float,
Bool,
Null,
Vec2,
Pixel,
Trait,
Dynamic,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Ownership {
Plain,
GuestReference,
NativeString,
TraitReceiver,
Dynamic,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StorageLayout {
pub size: usize,
pub alignment: usize,
pub slots: u32,
pub ownership: Ownership,
pub default: DefaultKind,
}
impl StorageLayout {
fn new(
size: usize,
alignment: usize,
slots: u32,
ownership: Ownership,
default: DefaultKind,
) -> Self {
Self { size, alignment, slots, ownership, default }
}
pub fn nullable(self) -> bool {
!matches!(self.ownership, Ownership::Plain)
}
/// Canonical stack-side defaults, with no allocation or source constructor.
/// Native typed storage still requires its own initialized-slot construction.
pub fn default_values(self) -> &'static [Value] {
match self.default {
DefaultKind::Int32 => &[Value::Int32(0)],
DefaultKind::Int64 => &[Value::Int64(0)],
DefaultKind::Float => &[Value::Float(0.0)],
DefaultKind::Bool => &[Value::Boolean(false)],
DefaultKind::Null => &[Value::Null],
DefaultKind::Vec2 => &[Value::Float(0.0), Value::Float(0.0)],
DefaultKind::Pixel => &[Value::Int64(0), Value::Int64(0), Value::Int64(0)],
DefaultKind::Trait | DefaultKind::Dynamic => &[Value::Null, Value::Null],
}
}
}
impl BuiltinId {
pub const COLOR: Self = Self(1);
pub const VEC2: Self = Self(2);
pub const PIXEL: Self = Self(3);
pub const INT32: Self = Self(0x10);
pub const INT64: Self = Self(0x11);
pub const FLOAT: Self = Self(0x12);
pub const BOOL: Self = Self(0x13);
pub const STRING: Self = Self(0x14);
pub const DYNAMIC: Self = Self(0x15);
pub const RANDOM: Self = Self(0x16);
pub fn layout(self) -> Result<StorageLayout, E> {
use DefaultKind as D;
use Ownership as O;
let (size, alignment, slots, ownership, default) = match self {
Self::COLOR => (4, 4, 1, O::Plain, D::Int64),
Self::VEC2 => (16, 8, 2, O::Plain, D::Vec2),
Self::PIXEL => (24, 8, 3, O::Plain, D::Pixel),
Self::INT32 => (4, 4, 1, O::Plain, D::Int32),
Self::INT64 => (8, 8, 1, O::Plain, D::Int64),
Self::FLOAT => (8, 8, 1, O::Plain, D::Float),
Self::BOOL => (1, 1, 1, O::Plain, D::Bool),
Self::RANDOM => (8, 8, 1, O::GuestReference, D::Null),
Self::STRING => {
(size_of::<StringSlot>(), align_of::<StringSlot>(), 1, O::NativeString, D::Null)
}
Self::DYNAMIC => {
(size_of::<DynamicSlot>(), align_of::<DynamicSlot>(), 2, O::Dynamic, D::Dynamic)
}
_ => return Err(E::new(C::UnsupportedFormat, R::Builtin)),
};
Ok(StorageLayout::new(size, alignment, slots, ownership, default))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FieldLayout {
pub type_id: TypeId,
pub offset: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OwnedField {
pub offset: usize,
pub ownership: Ownership,
}
#[derive(Debug, PartialEq, Eq)]
pub struct StructLayout {
/// Sum of execution-slot widths, resolved once for deterministic NEW charging.
pub initialization_slots: u64,
pub size: usize,
pub alignment: usize,
pub fields: Vec<FieldLayout>,
/// Sorted offsets for fields requiring guest tracing or native ownership handling.
pub owned_fields: Vec<OwnedField>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ArrayLayout {
pub element_type_id: TypeId,
pub stride: usize,
pub element_alignment: usize,
}
#[derive(Debug, PartialEq, Eq)]
pub struct TypeLayout {
pub storage: StorageLayout,
pub instance: Option<StructLayout>,
pub array: Option<ArrayLayout>,
pub callable: Option<FunctionLayout>,
pub methods: Vec<FunctionLayout>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CaptureLayout {
pub type_id: TypeId,
pub slot_offset: u32,
pub slots: u32,
}
#[derive(Debug, PartialEq, Eq)]
pub struct FunctionLayout {
pub parameter_slots: u32,
pub result_slots: u32,
pub capture_slots: u32,
pub captures: Vec<CaptureLayout>,
}
#[derive(Debug)]
pub struct Registry {
lifecycle_hooks: [Option<FunctionId>; 3],
declarations: RegistryDeclarations,
layouts: Vec<TypeLayout>,
functions: Vec<FunctionLayout>,
// Sorted by owner/trait; original implementation IDs are never remapped.
implementations: Vec<(TypeId, TypeId, ImplementationId)>,
}
impl Registry {
pub fn lifecycle_hook(&self, role: LifecycleRole) -> Option<FunctionId> {
match role {
LifecycleRole::None => None,
LifecycleRole::BeforePause => self.lifecycle_hooks[0],
LifecycleRole::BeforeResume => self.lifecycle_hooks[1],
LifecycleRole::MemcardBoot => self.lifecycle_hooks[2],
}
}
pub fn declarations(&self) -> &RegistryDeclarations {
&self.declarations
}
pub fn type_layout(&self, id: TypeId) -> Option<&TypeLayout> {
self.layouts.get(id.0 as usize)
}
pub fn function_layout(&self, id: FunctionId) -> Option<&FunctionLayout> {
self.functions.get(id.0 as usize)
}
pub fn implementation(&self, owner: TypeId, trait_id: TypeId) -> Option<ImplementationId> {
self.implementations
.binary_search_by_key(&(owner, trait_id), |&(a, b, _)| (a, b))
.ok()
.map(|i| self.implementations[i].2)
}
/// Resolves declarations, not code/bindings. The caller must still verify before publication.
/// Declaration allocations are retained and charged here, even for non-PBX producers.
pub fn resolve(
declarations: RegistryDeclarations,
code_len: usize,
budget: &mut LoadBudget,
) -> Result<Self, E> {
budget.transaction(|budget| Self::resolve_inner(declarations, code_len, budget))
}
fn resolve_inner(
d: RegistryDeclarations,
code_len: usize,
b: &mut LoadBudget,
) -> Result<Self, E> {
b.check(Q::Types, d.types.len() as u64)?;
b.check(Q::Functions, d.functions.len() as u64)?;
b.check(Q::Implementations, d.implementations.len() as u64)?;
b.check(Q::CodeBytes, code_len as u64)?;
charge_declarations(&d, b)?;
validate_declarations(&d, b)?;
let mut layouts = b.vector(d.types.len(), Q::RegistryBytes)?;
for (i, t) in d.types.iter().enumerate() {
b.work(1)?;
let storage = match t.kind {
TypeKind::Builtin(id) => id.layout().map_err(|e| e.record(i as u32))?,
TypeKind::Trait(_) => {
StorageLayout::new(16, 8, 2, Ownership::TraitReceiver, DefaultKind::Trait)
}
_ => StorageLayout::new(8, 8, 1, Ownership::GuestReference, DefaultKind::Null),
};
layouts.push(TypeLayout {
storage,
instance: None,
array: None,
callable: None,
methods: Vec::new(),
});
}
for (i, t) in d.types.iter().enumerate() {
b.work(1)?;
if let TypeKind::Fn(s) = &t.kind {
layouts[i].callable = Some(resolve_signature(s, &layouts, b)?);
}
if let TypeKind::Trait(methods) = &t.kind {
let mut resolved = b.vector(methods.len(), Q::RegistryBytes)?;
for method in methods {
b.work(1)?;
resolved.push(resolve_signature(&method.signature, &layouts, b)?);
}
layouts[i].methods = resolved;
}
if let TypeKind::Array(element_type_id) = t.kind {
let element = layouts[element_type_id.0 as usize].storage;
layouts[i].array = Some(ArrayLayout {
element_type_id,
stride: align(element.size, element.alignment)?,
element_alignment: element.alignment,
});
}
if let TypeKind::Struct(fields) = &t.kind {
let mut offsets = b.vector(fields.len(), Q::RegistryBytes)?;
b.work(fields.len())?;
let owned_count = fields
.iter()
.filter(|f| layouts[f.type_id.0 as usize].storage.ownership != Ownership::Plain)
.count();
let mut owned = b.vector(owned_count, Q::RegistryBytes)?;
let (mut size, mut alignment) = (0, 1);
let mut initialization_slots = 0u64;
for field in fields {
b.work(1)?;
let layout = layouts[field.type_id.0 as usize].storage;
initialization_slots = initialization_slots
.checked_add(u64::from(layout.slots))
.ok_or_else(overflow)?;
size = align(size, layout.alignment)?;
offsets.push(FieldLayout { type_id: field.type_id, offset: size });
if layout.ownership != Ownership::Plain {
owned.push(OwnedField { offset: size, ownership: layout.ownership });
}
size = size.checked_add(layout.size).ok_or_else(overflow)?;
alignment = alignment.max(layout.alignment);
}
layouts[i].instance = Some(StructLayout {
initialization_slots,
size: align(size, alignment)?,
alignment,
fields: offsets,
owned_fields: owned,
});
}
}
let mut lifecycle_hooks = [None; 3];
let mut functions = b.vector(d.functions.len(), Q::RegistryBytes)?;
let mut ranges = b.vector(d.functions.len(), Q::TemporaryBytes)?;
for (i, f) in d.functions.iter().enumerate() {
b.work(1)?;
if f.lifecycle_role != LifecycleRole::None {
let signature_valid = if f.lifecycle_role == LifecycleRole::MemcardBoot {
f.signature.parameters.len() == 1
&& f.signature.results.len() == 1
&& d.types
.get(f.signature.parameters[0].type_id.0 as usize)
.is_some_and(|t| t.kind == TypeKind::Builtin(BuiltinId::INT64))
&& d.types
.get(f.signature.results[0].0 as usize)
.is_some_and(|t| t.kind == TypeKind::Builtin(BuiltinId::INT32))
} else {
f.signature.parameters.is_empty() && f.signature.results.is_empty()
};
let invalid = i == 0 || !signature_valid || !f.captures.is_empty();
if invalid {
return Err(E::new(C::InvalidEntrypoint, R::LifecycleSignature)
.in_section(1)
.record(i as u32)
.in_function(i as u32, None));
}
let slot = &mut lifecycle_hooks[f.lifecycle_role as usize - 1];
if slot.replace(FunctionId(i as u32)).is_some() {
return Err(E::new(C::InvalidRegistry, R::DuplicateLifecycleRole)
.in_section(1)
.record(i as u32)
.in_function(i as u32, None));
}
}
let params = width(f.signature.parameters.iter().map(|p| p.type_id), &layouts, b)?;
let results = width(f.signature.results.iter().copied(), &layouts, b)?;
let frame = u64::from(params) + u64::from(f.local_slots) + u64::from(f.max_stack_slots);
if frame > b.frame_limit() {
return Err(E::new(C::InvalidCode, R::FrameSlots)
.in_section(1)
.record(i as u32)
.in_function(i as u32, None));
}
if u64::from(results) > b.result_limit() {
return Err(E::new(C::InvalidCode, R::ReturnSlots)
.in_section(1)
.record(i as u32)
.in_function(i as u32, None));
}
let end = f.code_offset.checked_add(f.code_len).ok_or_else(|| {
E::new(C::InvalidCode, R::CodeRange)
.in_section(1)
.record(i as u32)
.in_function(i as u32, Some(f.code_offset))
})?;
if end as usize > code_len || f.code_len == 0 {
return Err(E::new(C::InvalidCode, R::CodeRange)
.in_section(1)
.record(i as u32)
.in_function(i as u32, Some(f.code_offset)));
}
ranges.push((f.code_offset, end, i as u32));
let mut captures = b.vector(f.captures.len(), Q::RegistryBytes)?;
let mut capture_slots = 0u32;
for &type_id in &f.captures {
b.work(1)?;
let slots = layouts[type_id.0 as usize].storage.slots;
captures.push(CaptureLayout { type_id, slot_offset: capture_slots, slots });
capture_slots = capture_slots.checked_add(slots).ok_or_else(overflow)?;
}
functions.push(FunctionLayout {
parameter_slots: params,
result_slots: results,
capture_slots,
captures,
});
}
sort_work(ranges.len(), b)?;
ranges.sort_unstable();
for pair in ranges.windows(2) {
b.work(1)?;
if pair[0].1 > pair[1].0 {
return Err(E::new(C::InvalidCode, R::CodeRange).record(pair[1].2));
}
}
b.refund(Q::TemporaryBytes, (ranges.capacity() * size_of::<(u32, u32, u32)>()) as u64);
drop(ranges);
let mut implementations = b.vector(d.implementations.len(), Q::RegistryBytes)?;
for (i, imp) in d.implementations.iter().enumerate() {
b.work(1)?;
if !matches!(d.types[imp.owner.0 as usize].kind, TypeKind::Struct(_)) {
return Err(E::new(C::InvalidReference, R::OwnerCategory)
.in_section(7)
.record(i as u32)
.reference(IdDomain::Type, imp.owner.0));
}
let TypeKind::Trait(methods) = &d.types[imp.trait_id.0 as usize].kind else {
return Err(E::new(C::InvalidReference, R::TraitCategory)
.in_section(7)
.record(i as u32)
.reference(IdDomain::Type, imp.trait_id.0));
};
if methods.len() != imp.methods.len() {
return Err(E::new(C::InvalidRegistry, R::MethodCount)
.in_section(7)
.record(i as u32));
}
for (j, (method, id)) in methods.iter().zip(&imp.methods).enumerate() {
let signature = &d.functions[id.0 as usize].signature;
if !d.functions[id.0 as usize].captures.is_empty() {
return Err(E::new(C::InvalidRegistry, R::CapturedDirectCall)
.in_section(7)
.record(i as u32)
.member(j as u32));
}
b.work(signature.parameters.len() + signature.results.len() + 1)?;
if signature.parameters.first().map(|p| p.type_id) != Some(imp.owner)
|| signature.parameters.len() != method.signature.parameters.len() + 1
|| !signature.parameters.iter().skip(1).map(|p| p.type_id).eq(method
.signature
.parameters
.iter()
.map(|p| p.type_id))
|| signature.results != method.signature.results
{
return Err(E::new(C::InvalidRegistry, R::Signature)
.in_section(7)
.record(i as u32)
.member(j as u32));
}
}
implementations.push((imp.owner, imp.trait_id, ImplementationId(i as u32)));
}
sort_work(implementations.len(), b)?;
implementations.sort_unstable();
for pair in implementations.windows(2) {
b.work(1)?;
if (pair[0].0, pair[0].1) == (pair[1].0, pair[1].1) {
return Err(E::new(C::InvalidRegistry, R::DuplicateImplementation)
.in_section(7)
.record(pair[1].2 .0));
}
}
Ok(Self { lifecycle_hooks, declarations: d, layouts, functions, implementations })
}
}
fn overflow() -> E {
E::new(C::ResourceLimit, R::Overflow)
}
fn resolve_signature(
s: &Signature,
layouts: &[TypeLayout],
b: &mut LoadBudget,
) -> Result<FunctionLayout, E> {
let parameter_slots = width(s.parameters.iter().map(|p| p.type_id), layouts, b)?;
let result_slots = width(s.results.iter().copied(), layouts, b)?;
if u64::from(parameter_slots) > b.frame_limit() {
return Err(E::new(C::InvalidRegistry, R::FrameSlots));
}
if u64::from(result_slots) > b.result_limit() {
return Err(E::new(C::InvalidRegistry, R::ReturnSlots));
}
Ok(FunctionLayout { parameter_slots, result_slots, capture_slots: 0, captures: Vec::new() })
}
fn align(n: usize, a: usize) -> Result<usize, E> {
n.checked_add(a - 1).map(|v| v & !(a - 1)).ok_or_else(overflow)
}
fn width(
ids: impl Iterator<Item = TypeId>,
layouts: &[TypeLayout],
b: &mut LoadBudget,
) -> Result<u32, E> {
let mut sum = 0u32;
for id in ids {
b.work(1)?;
sum = sum.checked_add(layouts[id.0 as usize].storage.slots).ok_or_else(overflow)?;
}
Ok(sum)
}
fn sort_work(n: usize, b: &mut LoadBudget) -> Result<(), E> {
let bits = usize::BITS - n.leading_zeros();
b.work(n.checked_mul(bits as usize + 1).ok_or_else(overflow)?)
}
fn type_ref(id: TypeId, d: &RegistryDeclarations) -> Result<(), E> {
if (id.0 as usize) < d.types.len() {
Ok(())
} else {
Err(E::new(C::InvalidReference, R::TypeId).reference(IdDomain::Type, id.0))
}
}
fn name(name: &Option<String>, b: &mut LoadBudget) -> Result<(), E> {
if let Some(name) = name {
if name.len() as u64 > b.individual_name_limit() {
return Err(E::resource(Q::NameBytes, name.len() as u64, b.individual_name_limit()));
}
b.charge(Q::NameBytes, name.len() as u64)?;
b.work(name.len())?;
}
Ok(())
}
fn named(items: &[NamedType], d: &RegistryDeclarations, b: &mut LoadBudget) -> Result<(), E> {
b.charge(Q::NestedRecords, items.len() as u64)?;
for (i, item) in items.iter().enumerate() {
b.work(1)?;
type_ref(item.type_id, d).map_err(|e| e.member(i as u32))?;
name(&item.name, b)?;
}
Ok(())
}
fn signature(s: &Signature, d: &RegistryDeclarations, b: &mut LoadBudget) -> Result<(), E> {
named(&s.parameters, d, b)?;
b.charge(Q::NestedRecords, s.results.len() as u64)?;
for (i, id) in s.results.iter().enumerate() {
b.work(1)?;
type_ref(*id, d).map_err(|e| e.member(i as u32))?;
}
Ok(())
}
fn signature_order(
a: &Signature,
b: &Signature,
budget: &mut LoadBudget,
) -> Result<std::cmp::Ordering, E> {
use std::cmp::Ordering;
for (a, b) in a.parameters.iter().zip(&b.parameters) {
budget.work(1)?;
let order = a.type_id.cmp(&b.type_id);
if order != Ordering::Equal {
return Ok(order);
}
}
budget.work(1)?;
let order = a.parameters.len().cmp(&b.parameters.len());
if order != Ordering::Equal {
return Ok(order);
}
for (a, b) in a.results.iter().zip(&b.results) {
budget.work(1)?;
let order = a.cmp(b);
if order != Ordering::Equal {
return Ok(order);
}
}
budget.work(1)?;
Ok(a.results.len().cmp(&b.results.len()))
}
/// Validate all edges before indexed layout resolution; IDs remain table positions.
pub(crate) fn validate_declarations(d: &RegistryDeclarations, b: &mut LoadBudget) -> Result<(), E> {
b.charge(Q::Types, d.types.len() as u64)?;
b.charge(Q::Functions, d.functions.len() as u64)?;
b.charge(Q::Implementations, d.implementations.len() as u64)?;
let mut constructors = b.vector(d.types.len(), Q::TemporaryBytes)?;
for (i, t) in d.types.iter().enumerate() {
b.work(1)?;
name(&t.name, b).map_err(|e| e.in_section(6).record(i as u32))?;
let result = (|| match &t.kind {
TypeKind::Builtin(id) => {
id.layout()?;
constructors.push((0, id.0, i as u32));
Ok(())
}
TypeKind::Array(id) => {
type_ref(*id, d)?;
constructors.push((1, id.0, i as u32));
Ok(())
}
TypeKind::Struct(fields) => named(fields, d, b),
TypeKind::Fn(s) => signature(s, d, b),
TypeKind::Trait(methods) => {
b.charge(Q::NestedRecords, methods.len() as u64)?;
for m in methods {
b.work(1)?;
name(&m.name, b)?;
signature(&m.signature, d, b)?;
}
Ok(())
}
})();
result.map_err(|e| e.in_section(6).record(i as u32))?;
}
sort_work(constructors.len(), b)?;
constructors.sort_unstable();
for pair in constructors.windows(2) {
b.work(1)?;
if (pair[0].0, pair[0].1) == (pair[1].0, pair[1].1) {
return Err(E::new(
C::InvalidRegistry,
if pair[1].0 == 0 { R::DuplicateBuiltin } else { R::DuplicateArray },
)
.record(pair[1].2));
}
}
b.refund(Q::TemporaryBytes, (constructors.capacity() * size_of::<(i32, u32, u32)>()) as u64);
drop(constructors);
// Sorted Fn indices use fallible, metered comparisons; names are never keys.
let mut fns = b.vector::<usize>(d.types.len(), Q::TemporaryBytes)?;
for (id, t) in d.types.iter().enumerate() {
b.work(1)?;
let TypeKind::Fn(key) = &t.kind else { continue };
let (mut lo, mut hi) = (0, fns.len());
while lo < hi {
let mid = lo + (hi - lo) / 2;
let TypeKind::Fn(other) = &d.types[fns[mid]].kind else { unreachable!() };
match signature_order(key, other, b)? {
std::cmp::Ordering::Equal => {
return Err(E::new(C::InvalidRegistry, R::DuplicateFn)
.in_section(6)
.record(id as u32))
}
std::cmp::Ordering::Less => hi = mid,
std::cmp::Ordering::Greater => lo = mid + 1,
}
}
b.work(fns.len() - lo + 1)?;
fns.insert(lo, id);
}
b.refund(Q::TemporaryBytes, (fns.capacity() * size_of::<usize>()) as u64);
drop(fns);
// Iterative DFS processes each structural edge once; nominal nodes are leaves.
let mut colors = b.vector::<u8>(d.types.len(), Q::TemporaryBytes)?;
b.work(d.types.len())?;
colors.resize(d.types.len(), 0);
let mut walk = b.vector::<(usize, usize)>(d.types.len(), Q::TemporaryBytes)?;
for start in 0..d.types.len() {
b.work(1)?;
if colors[start] != 0 {
continue;
}
colors[start] = 1;
walk.push((start, 0));
while let Some((node, edge)) = walk.last_mut() {
b.work(1)?;
let next = match &d.types[*node].kind {
TypeKind::Array(id) if *edge == 0 => Some(*id),
TypeKind::Fn(s) => s.parameters.get(*edge).map(|p| p.type_id).or_else(|| {
edge.checked_sub(s.parameters.len()).and_then(|e| s.results.get(e)).copied()
}),
_ => None,
};
*edge += 1;
if let Some(id) = next {
let id = id.0 as usize;
if colors[id] == 1 {
b.work(walk.len())?;
let reason =
if walk.iter().any(|(n, _)| matches!(d.types[*n].kind, TypeKind::Fn(_))) {
R::StructuralTypeCycle
} else {
R::ArrayCycle
};
return Err(E::new(C::InvalidRegistry, reason).in_section(6).record(id as u32));
}
if colors[id] == 0 {
colors[id] = 1;
walk.push((id, 0));
}
} else {
colors[*node] = 2;
walk.pop();
}
}
}
b.refund(Q::TemporaryBytes, colors.capacity() as u64);
b.refund(Q::TemporaryBytes, (walk.capacity() * size_of::<(usize, usize)>()) as u64);
drop(colors);
drop(walk);
for (i, f) in d.functions.iter().enumerate() {
b.work(1)?;
name(&f.name, b).map_err(|e| e.in_section(1).record(i as u32))?;
signature(&f.signature, d, b).map_err(|e| e.in_section(1).record(i as u32))?;
b.charge(Q::NestedRecords, f.captures.len() as u64)?;
for (j, &id) in f.captures.iter().enumerate() {
b.work(1)?;
type_ref(id, d).map_err(|e| e.in_section(8).record(i as u32).member(j as u32))?;
}
}
for (i, imp) in d.implementations.iter().enumerate() {
b.work(1)?;
type_ref(imp.owner, d).map_err(|e| e.in_section(7).record(i as u32))?;
type_ref(imp.trait_id, d).map_err(|e| e.in_section(7).record(i as u32))?;
b.charge(Q::NestedRecords, imp.methods.len() as u64)?;
for (j, id) in imp.methods.iter().enumerate() {
b.work(1)?;
if id.0 as usize >= d.functions.len() {
return Err(E::new(C::InvalidReference, R::FunctionId)
.in_section(7)
.reference(IdDomain::Function, id.0)
.record(i as u32)
.member(j as u32));
}
}
}
Ok(())
}
fn charge_vec<T>(v: &Vec<T>, b: &mut LoadBudget) -> Result<(), E> {
b.charge(
Q::RegistryBytes,
(v.capacity() as u64).checked_mul(size_of::<T>() as u64).ok_or_else(overflow)?,
)
}
fn charge_name(n: &Option<String>, b: &mut LoadBudget) -> Result<(), E> {
if let Some(n) = n {
b.charge(Q::RegistryBytes, n.capacity() as u64)?;
}
Ok(())
}
fn charge_named(v: &Vec<NamedType>, b: &mut LoadBudget) -> Result<(), E> {
charge_vec(v, b)?;
for p in v {
b.work(1)?;
charge_name(&p.name, b)?;
}
Ok(())
}
fn charge_signature(s: &Signature, b: &mut LoadBudget) -> Result<(), E> {
charge_named(&s.parameters, b)?;
charge_vec(&s.results, b)
}
fn charge_declarations(d: &RegistryDeclarations, b: &mut LoadBudget) -> Result<(), E> {
b.charge(Q::RegistryBytes, size_of::<Registry>() as u64)?;
charge_vec(&d.types, b)?;
charge_vec(&d.functions, b)?;
charge_vec(&d.implementations, b)?;
for t in &d.types {
b.work(1)?;
charge_name(&t.name, b)?;
match &t.kind {
TypeKind::Struct(fields) => charge_named(fields, b)?,
TypeKind::Fn(s) => charge_signature(s, b)?,
TypeKind::Trait(methods) => {
charge_vec(methods, b)?;
for m in methods {
b.work(1)?;
charge_name(&m.name, b)?;
charge_signature(&m.signature, b)?;
}
}
_ => {}
}
}
for f in &d.functions {
b.work(1)?;
charge_name(&f.name, b)?;
charge_signature(&f.signature, b)?;
charge_vec(&f.captures, b)?;
}
for imp in &d.implementations {
b.work(1)?;
charge_vec(&imp.methods, b)?;
}
Ok(())
}