use super::*;
impl Function {
pub(super) fn validate(
&self,
state: ValueType,
parameters: &[(String, ValueType)],
reply: ValueType,
allow_state: bool,
allow_loops: bool,
) -> Result<(), String> {
if self.instructions.len() > MAX_OPERATIONS {
return Err("too many operations for the scalar prototype".into());
}
let mut types = Vec::new();
let mut available = Vec::new();
let mut branches = Vec::new();
let mut expected_phis: std::collections::VecDeque<(usize, ValueType)> =
std::collections::VecDeque::new();
let mut seen_proc_gc_point = false;
for instruction in &self.instructions {
if let Some((expected_index, expected_ty)) = expected_phis.pop_front() {
if !matches!(instruction.operation, Operation::PhiValue(actual) if actual == expected_index)
|| instruction.ty != expected_ty
{
return Err("invalid or missing phi result instruction".into());
}
types.push(instruction.ty);
available.push(true);
continue;
}
if matches!(instruction.operation, Operation::PhiValue(_)) {
return Err("unexpected phi result instruction".into());
}
let operands = operands(&instruction.operation);
if operands
.into_iter()
.any(|register| available.get(register) != Some(&true))
{
return Err(
"invalid scalar IR operand, type or forward reference, or branch scope".into(),
);
}
let valid = match instruction.operation {
Operation::Constant(value) => instruction.ty.accepts(value),
Operation::StringLiteral(ref value) => {
instruction.ty == ValueType::StringRef && value.len() <= 65536
}
Operation::FormatString {
ref blob,
ref pieces,
ref arguments,
} => {
instruction.ty == ValueType::StringRef
&& !pieces.is_empty()
&& pieces.len() <= wings_abi::MAX_FORMAT_PIECES
&& arguments.len() <= pieces.len()
&& blob.len() <= 65536
&& pieces.iter().all(|piece| match *piece {
FormatPiece::Literal { offset, len } => (offset as usize)
.checked_add(len as usize)
.is_some_and(|end| {
end <= blob.len()
&& blob.is_char_boundary(offset as usize)
&& blob.is_char_boundary(end)
}),
FormatPiece::String(idx) => {
arguments.get(idx).and_then(|&r| types.get(r))
== Some(&ValueType::StringRef)
}
FormatPiece::Int(idx) => {
arguments.get(idx).and_then(|&r| types.get(r))
== Some(&ValueType::Int)
}
FormatPiece::Bool(idx) => {
arguments.get(idx).and_then(|&r| types.get(r))
== Some(&ValueType::Bool)
}
})
}
Operation::BytesLiteral(ref value) => {
instruction.ty == ValueType::BytesRef && value.len() <= 65536
}
Operation::IntToString(value) => {
instruction.ty == ValueType::StringRef
&& types.get(value) == Some(&ValueType::Int)
}
Operation::BoolToString(value) => {
instruction.ty == ValueType::StringRef
&& types.get(value) == Some(&ValueType::Bool)
}
Operation::RecordNew { .. } | Operation::RecordField { .. } => true,
Operation::State => allow_state && instruction.ty == state,
Operation::Argument(index) => {
(!instruction.ty.is_reference() || allow_state || !seen_proc_gc_point)
&& parameters
.get(index)
.is_some_and(|parameter| parameter.1 == instruction.ty)
}
Operation::Negate(value) => {
instruction.ty == ValueType::Int && types.get(value) == Some(&ValueType::Int)
}
Operation::Binary(_, left, right) => {
instruction.ty == ValueType::Int
&& types.get(left) == Some(&ValueType::Int)
&& types.get(right) == Some(&ValueType::Int)
}
Operation::Compare(comparison, left, right) => {
instruction.ty == ValueType::Bool
&& types.get(left) == types.get(right)
&& match comparison {
Comparison::Equal | Comparison::NotEqual => matches!(
types.get(left),
Some(
ValueType::Int
| ValueType::Bool
| ValueType::Unit
| ValueType::Pid
)
),
_ => types.get(left) == Some(&ValueType::Int),
}
}
Operation::Collect => instruction.ty == ValueType::Unit,
Operation::EmptyInts => instruction.ty == ValueType::ListRef,
Operation::PrependInt(value, tail) => {
instruction.ty == ValueType::ListRef
&& types.get(value) == Some(&ValueType::Int)
&& types.get(tail) == Some(&ValueType::ListRef)
}
Operation::HeadInt(value) => {
instruction.ty == ValueType::Int
&& types.get(value) == Some(&ValueType::ListRef)
}
Operation::TailInts(value) => {
instruction.ty == ValueType::ListRef
&& types.get(value) == Some(&ValueType::ListRef)
}
Operation::IsEmptyInts(value) => {
instruction.ty == ValueType::Bool
&& types.get(value) == Some(&ValueType::ListRef)
}
Operation::FillBytes(length, value) => {
instruction.ty == ValueType::BytesRef
&& types.get(length) == Some(&ValueType::Int)
&& types.get(value) == Some(&ValueType::Int)
}
Operation::BytesLen(value) => {
instruction.ty == ValueType::Int
&& types.get(value) == Some(&ValueType::BytesRef)
}
Operation::StringFromBytes(value) => {
instruction.ty == ValueType::StringRef
&& types.get(value) == Some(&ValueType::BytesRef)
}
Operation::StringBytes(value) => {
instruction.ty == ValueType::BytesRef
&& types.get(value) == Some(&ValueType::StringRef)
}
Operation::StringLen(value) => {
instruction.ty == ValueType::Int
&& types.get(value) == Some(&ValueType::StringRef)
}
Operation::StringAt(value, index) => {
instruction.ty == ValueType::Int
&& types.get(value) == Some(&ValueType::StringRef)
&& types.get(index) == Some(&ValueType::Int)
}
Operation::StringSlice([value, start, length]) => {
instruction.ty == ValueType::StringRef
&& types.get(value) == Some(&ValueType::StringRef)
&& types.get(start) == Some(&ValueType::Int)
&& types.get(length) == Some(&ValueType::Int)
}
Operation::ConcatStrings(left, right) => {
instruction.ty == ValueType::StringRef
&& types.get(left) == Some(&ValueType::StringRef)
&& types.get(right) == Some(&ValueType::StringRef)
}
Operation::EqualStrings(left, right) => {
instruction.ty == ValueType::Bool
&& types.get(left) == Some(&ValueType::StringRef)
&& types.get(right) == Some(&ValueType::StringRef)
}
Operation::ByteAt(value, index) | Operation::ReadI64Be(value, index) => {
instruction.ty == ValueType::Int
&& types.get(value) == Some(&ValueType::BytesRef)
&& types.get(index) == Some(&ValueType::Int)
}
Operation::ReplaceByte([value, index, byte])
| Operation::ReplaceI64Be([value, index, byte]) => {
instruction.ty == ValueType::BytesRef
&& types.get(value) == Some(&ValueType::BytesRef)
&& types.get(index) == Some(&ValueType::Int)
&& types.get(byte) == Some(&ValueType::Int)
}
Operation::SendSelf { ref arguments, .. } => {
instruction.ty == ValueType::Unit
&& arguments.len() <= MAX_PARAMETERS
&& arguments.iter().all(|register| {
types.get(*register).is_some_and(|ty| {
matches!(
ty,
ValueType::Int
| ValueType::Bool
| ValueType::Unit
| ValueType::ListRef
| ValueType::BytesRef
| ValueType::StringRef
| ValueType::Pid
)
})
})
}
Operation::SendAfterSelf {
delay,
ref arguments,
..
} => {
instruction.ty == ValueType::Unit
&& types.get(delay) == Some(&ValueType::Int)
&& arguments.len() <= MAX_PARAMETERS
&& arguments.iter().all(|register| {
types.get(*register).is_some_and(|ty| {
matches!(
ty,
ValueType::Int
| ValueType::Bool
| ValueType::Unit
| ValueType::ListRef
| ValueType::BytesRef
| ValueType::StringRef
| ValueType::Pid
)
})
})
}
Operation::NullPid
| Operation::SelfPid
| Operation::SpawnSelf
| Operation::SpawnActor(_) => instruction.ty == ValueType::Pid,
Operation::Monitor { target, .. } => {
instruction.ty == ValueType::Unit && types.get(target) == Some(&ValueType::Pid)
}
Operation::Hostcall {
timeout,
ref arguments,
} => {
instruction.ty == ValueType::BytesRef
&& types.get(timeout) == Some(&ValueType::Int)
&& arguments.len() == 2
&& types.get(arguments[0]) == Some(&ValueType::StringRef)
&& types.get(arguments[1]) == Some(&ValueType::BytesRef)
}
Operation::Request {
target,
timeout,
ref arguments,
..
}
| Operation::RequestActor {
target,
timeout,
ref arguments,
..
} => {
instruction.ty == ValueType::RequestId
&& types.get(target) == Some(&ValueType::Pid)
&& types.get(timeout) == Some(&ValueType::Int)
&& arguments.len() <= MAX_PARAMETERS
&& arguments.iter().all(|register| {
types.get(*register).is_some_and(|ty| {
matches!(
ty,
ValueType::Int
| ValueType::Bool
| ValueType::Unit
| ValueType::ListRef
| ValueType::BytesRef
| ValueType::StringRef
| ValueType::Pid
)
})
})
}
Operation::CancelRequest(value) => {
instruction.ty == ValueType::Unit
&& types.get(value) == Some(&ValueType::RequestId)
}
Operation::Call { ref arguments, .. } => arguments.len() <= MAX_PARAMETERS,
Operation::Send {
target,
ref arguments,
..
}
| Operation::SendActor {
target,
ref arguments,
..
} => {
instruction.ty == ValueType::Unit
&& types.get(target) == Some(&ValueType::Pid)
&& arguments.len() <= MAX_PARAMETERS
&& arguments.iter().all(|register| {
types.get(*register).is_some_and(|ty| {
matches!(
ty,
ValueType::Int
| ValueType::Bool
| ValueType::Unit
| ValueType::ListRef
| ValueType::BytesRef
| ValueType::StringRef
| ValueType::Pid
)
})
})
}
Operation::SendAfter {
target,
delay,
ref arguments,
..
}
| Operation::SendAfterActor {
target,
delay,
ref arguments,
..
} => {
instruction.ty == ValueType::Unit
&& types.get(target) == Some(&ValueType::Pid)
&& types.get(delay) == Some(&ValueType::Int)
&& arguments.len() <= MAX_PARAMETERS
&& arguments.iter().all(|register| {
types.get(*register).is_some_and(|ty| {
matches!(
ty,
ValueType::Int
| ValueType::Bool
| ValueType::Unit
| ValueType::ListRef
| ValueType::BytesRef
| ValueType::StringRef
| ValueType::Pid
)
})
})
}
Operation::If(condition) => {
if branches.len() == 64 {
return Err("conditional nesting exceeds 64 branches".into());
}
branches.push(Region::Branch(types.len(), None));
instruction.ty == ValueType::Unit
&& types.get(condition) == Some(&ValueType::Bool)
}
Operation::Else(ref values) => {
let Some(Region::Branch(start, arm)) = branches.last_mut() else {
return Err("else without matching if".into());
};
if arm.is_some() {
return Err("duplicate else in conditional".into());
}
if values.is_empty() || values.len() > MAX_PARAMETERS {
return Err("invalid branch arity".into());
}
let then_types: Vec<ValueType> = values.iter().map(|®| types[reg]).collect();
*arm = Some(then_types);
available[start.saturating_add(1)..].fill(false);
instruction.ty == ValueType::Unit
}
Operation::EndIf(ref values) => {
let Some(Region::Branch(start, Some(then_types))) = branches.pop() else {
return Err("end-if without matching if/else".into());
};
available[start.saturating_add(1)..].fill(false);
let valid = values.len() == then_types.len()
&& instruction.ty == then_types[0]
&& values
.iter()
.zip(&then_types)
.all(|(®, &ty)| types.get(reg) == Some(&ty));
for (idx, &ty) in then_types.iter().enumerate().skip(1) {
expected_phis.push_back((idx, ty));
}
valid
}
Operation::Loop(ref initials) => {
if branches.len() == 64 {
return Err("control nesting exceeds 64 regions".into());
}
if !allow_loops || initials.is_empty() || initials.len() > MAX_PARAMETERS {
false
} else {
let phi_types: Vec<ValueType> =
initials.iter().map(|®| types[reg]).collect();
let valid = instruction.ty == phi_types[0];
for (idx, &ty) in phi_types.iter().enumerate().skip(1) {
expected_phis.push_back((idx, ty));
}
branches.push(Region::Loop(types.len(), phi_types, false));
valid
}
}
Operation::While(condition, ref exit_values) => {
let Some(Region::Loop(_, phi_types, tested)) = branches.last_mut() else {
return Err("while without matching loop".into());
};
if *tested {
return Err("duplicate while in loop".into());
}
*tested = true;
instruction.ty == ValueType::Unit
&& types.get(condition) == Some(&ValueType::Bool)
&& exit_values.len() == phi_types.len()
&& exit_values
.iter()
.zip(phi_types.iter())
.all(|(®, &ty)| types.get(reg) == Some(&ty))
}
Operation::EndLoop(ref values) => {
let Some(Region::Loop(start, phi_types, true)) = branches.pop() else {
return Err("end-loop without matching loop/while".into());
};
available[start..].fill(false);
let valid = values.len() == phi_types.len()
&& instruction.ty == phi_types[0]
&& values
.iter()
.zip(&phi_types)
.all(|(®, &ty)| types.get(reg) == Some(&ty));
for (idx, &ty) in phi_types.iter().enumerate().skip(1) {
expected_phis.push_back((idx, ty));
}
valid
}
Operation::PhiValue(_) => false,
};
if !valid {
return Err("invalid scalar IR operand, type or forward reference".into());
}
if !allow_state
&& !matches!(
instruction.operation,
Operation::Constant(_)
| Operation::NullPid
| Operation::Argument(_)
| Operation::Negate(_)
| Operation::Binary(_, _, _)
| Operation::Compare(_, _, _)
| Operation::PhiValue(_)
| Operation::RecordField { .. }
| Operation::HeadInt(_)
| Operation::TailInts(_)
| Operation::IsEmptyInts(_)
| Operation::BytesLen(_)
| Operation::StringLen(_)
| Operation::ByteAt(_, _)
| Operation::ReadI64Be(_, _)
)
{
seen_proc_gc_point = true;
}
types.push(instruction.ty);
available.push(!matches!(
instruction.operation,
Operation::If(_) | Operation::Else(_) | Operation::While(_, _)
));
}
if !expected_phis.is_empty() {
return Err("missing phi result instruction".into());
}
if !branches.is_empty() {
return Err("unterminated conditional in scalar IR".into());
}
if types.get(self.state) != Some(&state)
|| types.get(self.reply) != Some(&reply)
|| available.get(self.state) != Some(&true)
|| available.get(self.reply) != Some(&true)
{
return Err("invalid scalar IR state or reply register".into());
}
if self.root_plan().capacity > MAX_SHADOW_ROOTS {
return Err("AOT function exceeds 64 simultaneously live reference roots".into());
}
Ok(())
}
pub fn root_plan(&self) -> RootPlan {
root_plan::build(self)
}
}
pub fn operands(operation: &Operation) -> impl Iterator<Item = Register> + '_ {
let (fixed, extra): (_, &[Register]) = match *operation {
Operation::Negate(value) | Operation::If(value) => ([Some(value), None], &[]),
Operation::While(value, ref exit_values) => ([Some(value), None], exit_values.as_slice()),
Operation::HeadInt(value)
| Operation::TailInts(value)
| Operation::IsEmptyInts(value)
| Operation::BytesLen(value)
| Operation::StringFromBytes(value)
| Operation::StringBytes(value)
| Operation::StringLen(value)
| Operation::IntToString(value)
| Operation::BoolToString(value) => ([Some(value), None], &[]),
Operation::StringAt(value, index) => ([Some(value), Some(index)], &[]),
Operation::Else(ref values)
| Operation::EndIf(ref values)
| Operation::Loop(ref values)
| Operation::EndLoop(ref values) => ([None, None], values.as_slice()),
Operation::Binary(_, left, right)
| Operation::Compare(_, left, right)
| Operation::FillBytes(left, right)
| Operation::ConcatStrings(left, right)
| Operation::EqualStrings(left, right)
| Operation::ByteAt(left, right)
| Operation::ReadI64Be(left, right)
| Operation::PrependInt(left, right) => ([Some(left), Some(right)], &[]),
Operation::ReplaceByte(ref arguments) | Operation::ReplaceI64Be(ref arguments) => {
([None, None], arguments.as_slice())
}
Operation::StringSlice(ref arguments) => ([None, None], arguments.as_slice()),
Operation::SendSelf { ref arguments, .. } => ([None, None], arguments),
Operation::SendAfterSelf {
delay,
ref arguments,
..
} => ([Some(delay), None], arguments),
Operation::Call { ref arguments, .. } => ([None, None], arguments),
Operation::FormatString { ref arguments, .. } => ([None, None], arguments),
Operation::RecordNew { ref arguments, .. } => ([None, None], arguments),
Operation::RecordField { value, .. } => ([Some(value), None], &[]),
Operation::Send {
target,
ref arguments,
..
}
| Operation::SendActor {
target,
ref arguments,
..
} => ([Some(target), None], arguments),
Operation::SendAfter {
target,
delay,
ref arguments,
..
}
| Operation::SendAfterActor {
target,
delay,
ref arguments,
..
} => ([Some(target), Some(delay)], arguments),
Operation::Monitor { target, .. } => ([Some(target), None], &[]),
Operation::Hostcall {
timeout,
ref arguments,
} => ([Some(timeout), None], arguments),
Operation::Request {
target,
timeout,
ref arguments,
..
}
| Operation::RequestActor {
target,
timeout,
ref arguments,
..
} => ([Some(target), Some(timeout)], arguments),
Operation::CancelRequest(value) => ([Some(value), None], &[]),
_ => ([None, None], &[]),
};
fixed.into_iter().flatten().chain(extra.iter().copied())
}