mod function;
pub use function::operands;
use super::*;
impl Program {
pub fn validate(&self) -> Result<(), String> {
wings_abi::validate_records(&self.records)?;
if self.functions.iter().any(|procedure| std::iter::once(procedure.result)
.chain(procedure.parameters.iter().map(|(_, ty)| *ty))
.any(|ty| matches!(ty, ValueType::RecordRef(index) if usize::from(index) >= self.records.len()))) {
return Err("invalid named record function signature".into());
}
let functions = self
.functions
.iter()
.map(|procedure| &procedure.function)
.chain(self.handlers.iter().map(|handler| &handler.function))
.chain(std::iter::once(&self.initializer));
for function in functions {
for instruction in &function.instructions {
if matches!(instruction.ty, ValueType::RecordRef(index) if usize::from(index) >= self.records.len())
{
return Err("invalid named record type index".into());
}
match &instruction.operation {
Operation::RecordNew { schema, arguments } => {
let record = self
.records
.get(usize::from(*schema))
.ok_or("invalid record schema index")?;
if instruction.ty != ValueType::RecordRef(*schema)
|| record.fields.len() != arguments.len()
|| record
.fields
.iter()
.zip(arguments)
.any(|((_, ty), register)| {
function.instructions.get(*register).map(|value| value.ty)
!= Some(*ty)
})
{
return Err("record constructor field type mismatch".into());
}
}
Operation::RecordField { value, field } => {
let Some(ValueType::RecordRef(schema)) =
function.instructions.get(*value).map(|value| value.ty)
else {
return Err("record field requires named record".into());
};
if self
.records
.get(usize::from(schema))
.and_then(|record| record.fields.get(*field))
.map(|(_, ty)| *ty)
!= Some(instruction.ty)
{
return Err("invalid record field index or result type".into());
}
}
_ => {}
}
}
}
if matches!(self.state, ValueType::RecordRef(index) if usize::from(index) >= self.records.len())
|| self.handlers.iter().any(|handler| {
handler
.parameters
.iter()
.any(|(_, ty)| matches!(ty, ValueType::RecordRef(_)))
})
{
return Err("named records cannot be message parameters".into());
}
if self.functions.len() > MAX_FUNCTIONS {
return Err("too many managed functions".into());
}
let total = self
.functions
.iter()
.map(|function| &function.function)
.chain(self.handlers.iter().map(|handler| &handler.function))
.chain(std::iter::once(&self.initializer))
.try_fold(0usize, |total, function| {
total.checked_add(function.instructions.len())
})
.ok_or("total IR operation count overflow")?;
if total > MAX_TOTAL_OPERATIONS {
return Err("program exceeds 65536 total IR operations".into());
}
self.functions
.iter()
.map(|function| &function.function)
.chain(self.handlers.iter().map(|handler| &handler.function))
.chain(std::iter::once(&self.initializer))
.flat_map(|function| &function.instructions)
.try_fold(0usize, |total, instruction| match &instruction.operation {
Operation::StringLiteral(value) => total.checked_add(value.len()),
Operation::FormatString { blob, .. } => total.checked_add(blob.len()),
Operation::BytesLiteral(value) => total.checked_add(value.len()),
_ => Some(total),
})
.filter(|total| *total <= MAX_LITERAL_BYTES)
.ok_or("program exceeds 1 MiB total string literal bytes")?;
if self.external_actors.len() > 32 {
return Err("external actor count exceeds 32".into());
}
for ext in &self.external_actors {
wings_abi::validate_records(&ext.records)?;
if ext.handlers.len() > MAX_HANDLERS {
return Err("external actor exceeds 128 handlers".into());
}
if ext
.handlers
.iter()
.any(|handler| handler.parameters.len() > MAX_PARAMETERS)
{
return Err("external actor handler exceeds 64 parameters".into());
}
}
let mut call_edges = Vec::with_capacity(self.functions.len());
let mut own_roots = Vec::with_capacity(self.functions.len());
for procedure in &self.functions {
if procedure.parameters.len() > MAX_PARAMETERS {
return Err("too many managed function parameters".into());
}
procedure.function.validate(
ValueType::Unit,
&procedure.parameters,
procedure.result,
false,
true,
)?;
if procedure
.function
.instructions
.iter()
.any(|instruction| instruction.operation.is_effect())
{
return Err("effects are not supported in managed functions".into());
}
call_edges.push(self.validate_call_signatures(&procedure.function)?);
own_roots.push(procedure.function.root_plan().capacity);
}
let acyclic_paths = compute_static_call_paths(&call_edges, &own_roots);
for (depth, path_roots) in &acyclic_paths {
if *depth > 32 {
return Err("function call chain exceeds 32".into());
}
if *path_roots > MAX_SHADOW_ROOTS {
return Err("managed call path exceeds 64 shadow roots".into());
}
}
if self.state == ValueType::RequestId
|| self.handlers.iter().any(|handler| {
handler.reply == Some(ValueType::RequestId)
|| handler
.parameters
.iter()
.any(|(_, ty)| *ty == ValueType::RequestId && !handler.is_completion())
})
{
return Err("RequestId is only supported as a local value".into());
}
if self.handlers.len() > MAX_HANDLERS {
return Err("too many handlers for the scalar prototype".into());
}
self.initializer
.validate(self.state, &[], ValueType::Unit, false, false)?;
self.validate_entry_calls(&self.initializer, &acyclic_paths)?;
if self
.initializer
.instructions
.iter()
.any(|instruction| instruction.operation.is_effect())
{
return Err("self-send is not supported in initializers".into());
}
for handler in &self.handlers {
if handler.parameters.len() > MAX_PARAMETERS {
return Err("too many parameters for the scalar prototype".into());
}
if let Some(ValueType::RecordRef(schema)) = handler.completion {
let expansion = wings_abi::expand_record_schema(&self.records, schema)?;
if handler.reply.is_some()
|| handler.parameters.len() != expansion.count + 2
|| handler.parameters[0].1 != ValueType::RequestId
|| handler.parameters[1].1 != ValueType::Int
|| handler.parameters[2..]
.iter()
.zip(&expansion.fields[..expansion.count])
.any(|((_, actual), expected)| actual != expected)
{
return Err("invalid named record completion signature".into());
}
} else if handler.completion.is_some() {
return Err("explicit completion metadata is reserved for named records".into());
}
if let Some(ValueType::RecordRef(schema)) = handler.reply {
wings_abi::expand_record_schema(&self.records, schema)?;
}
handler.function.validate(
self.state,
&handler.parameters,
handler.reply.unwrap_or(ValueType::Unit),
true,
true,
)?;
self.validate_entry_calls(&handler.function, &acyclic_paths)?;
for instruction in &handler.function.instructions {
if matches!(
&instruction.operation,
Operation::SpawnActor(actor) if *actor >= self.external_actors.len()
) {
return Err("invalid external actor spawn index".into());
}
if let Operation::SendActor {
actor,
handler: target,
arguments,
..
}
| Operation::SendAfterActor {
actor,
handler: target,
arguments,
..
} = &instruction.operation
{
let ext = self
.external_actors
.get(*actor)
.ok_or("invalid external actor index")?;
let target = ext
.handlers
.get(*target)
.ok_or("invalid external send handler")?;
if target.reply.is_some()
|| target.parameters.len() != arguments.len()
|| arguments
.iter()
.zip(&target.parameters)
.any(|(register, (_, ty))| {
handler.function.instructions[*register].ty != *ty
})
{
return Err(
"external send requires matching one-way handler parameters".into()
);
}
}
if let Operation::Monitor {
handler: target, ..
} = &instruction.operation
{
let target = self
.handlers
.get(*target)
.ok_or("invalid monitor handler")?;
if target.reply.is_some()
|| target.is_completion()
|| target.parameters.len() != 2
|| target.parameters[0].1 != ValueType::Pid
|| target.parameters[1].1 != ValueType::Int
{
return Err("monitor requires a one-way (Pid, Int) handler".into());
}
}
if let Operation::RequestActor {
actor,
handler: target,
callback,
arguments,
..
} = &instruction.operation
{
let ext = self
.external_actors
.get(*actor)
.ok_or("invalid external actor index")?;
let target = ext
.handlers
.get(*target)
.ok_or("invalid external request handler")?;
let callback = self
.handlers
.get(*callback)
.ok_or("invalid request completion")?;
let compatible_reply = match (callback.completion_reply(), target.reply) {
(Some(cb_ty), Some(tgt_ty)) => {
wings_abi::equivalent_types(&self.records, cb_ty, &ext.records, tgt_ty)
}
_ => false,
};
if !target.reply.is_some_and(ValueType::is_supported_reply)
|| !compatible_reply
|| matches!(target.reply, Some(ValueType::RecordRef(index))
if wings_abi::expand_record_schema(&ext.records, index).is_err())
|| target.parameters.len() != arguments.len()
|| arguments
.iter()
.zip(&target.parameters)
.any(|(register, (_, ty))| {
handler.function.instructions[*register].ty != *ty
})
{
return Err(
"external request requires a supported reply, matching completion event and matching parameters"
.into(),
);
}
}
if let Operation::Request {
handler: target,
callback,
arguments,
..
} = &instruction.operation
{
let target = self
.handlers
.get(*target)
.ok_or("invalid request handler")?;
let callback = self
.handlers
.get(*callback)
.ok_or("invalid request completion")?;
if !target.reply.is_some_and(ValueType::is_supported_reply)
|| callback.completion_reply() != target.reply
|| matches!(target.reply, Some(ValueType::RecordRef(index))
if wings_abi::expand_record_schema(&self.records, index).is_err())
|| target.parameters.len() != arguments.len()
|| arguments
.iter()
.zip(&target.parameters)
.any(|(register, (_, ty))| {
handler.function.instructions[*register].ty != *ty
})
{
return Err(
"request requires a supported reply, matching completion event and matching parameters"
.into(),
);
}
}
if let Operation::SendSelf {
handler: target,
arguments,
}
| Operation::SendAfterSelf {
handler: target,
arguments,
..
}
| Operation::Send {
handler: target,
arguments,
..
}
| Operation::SendAfter {
handler: target,
arguments,
..
} = &instruction.operation
{
let target = self
.handlers
.get(*target)
.ok_or("invalid self-send handler")?;
if target.reply.is_some()
|| target.is_completion()
|| target.parameters.len() != arguments.len()
|| arguments
.iter()
.zip(&target.parameters)
.any(|(register, (_, ty))| {
handler.function.instructions[*register].ty != *ty
})
{
return Err("self-send requires matching one-way handler parameters".into());
}
}
}
}
Ok(())
}
fn validate_call_signatures(&self, function: &Function) -> Result<Vec<usize>, String> {
let mut callees = Vec::new();
for instruction in &function.instructions {
if let Operation::Call {
function: target,
arguments,
} = &instruction.operation
{
let procedure = self
.functions
.get(*target)
.ok_or("unknown managed function call")?;
if instruction.ty != procedure.result
|| arguments.len() != procedure.parameters.len()
|| arguments
.iter()
.zip(&procedure.parameters)
.any(|(register, (_, ty))| function.instructions[*register].ty != *ty)
{
return Err("managed function call signature mismatch".into());
}
callees.push(*target);
}
}
Ok(callees)
}
fn validate_entry_calls(
&self,
function: &Function,
acyclic_paths: &[(usize, usize)],
) -> Result<(), String> {
let callees = self.validate_call_signatures(function)?;
let mut child_roots = 0usize;
for target in callees {
child_roots = child_roots.max(acyclic_paths[target].1);
}
if function.root_plan().capacity + child_roots > MAX_SHADOW_ROOTS {
return Err("managed call path exceeds 64 shadow roots".into());
}
Ok(())
}
}
fn compute_static_call_paths(edges: &[Vec<usize>], own_roots: &[usize]) -> Vec<(usize, usize)> {
let unit_weights = vec![1usize; edges.len()];
let depths = wings_analysis::calls::acyclic_chain_costs(edges, &unit_weights);
let roots = wings_analysis::calls::acyclic_chain_costs(edges, own_roots);
depths.into_iter().zip(roots).collect()
}