1use wings_abi::ValueType;
2
3pub const MAX_OPERATIONS: usize = 4096;
4pub const MAX_HANDLERS: usize = 128;
5pub const MAX_PARAMETERS: usize = 64;
6
7pub type Register = usize;
8
9#[derive(Clone, Copy, Debug)]
10pub enum Operator {
11 Add,
12 Subtract,
13 Multiply,
14 Divide,
15}
16
17#[derive(Clone, Debug)]
18pub enum Operation {
19 Constant(i64),
20 State,
21 Argument(usize),
22 Negate(Register),
23 Binary(Operator, Register, Register),
24}
25
26#[derive(Clone, Debug)]
27pub struct Instruction {
28 pub ty: ValueType,
29 pub operation: Operation,
30}
31
32#[derive(Clone, Debug)]
33pub struct Function {
34 pub instructions: Vec<Instruction>,
35 pub state: Register,
36 pub reply: Register,
37}
38
39#[derive(Clone, Debug)]
40pub struct Handler {
41 pub name: String,
42 pub parameters: Vec<(String, ValueType)>,
43 pub reply: Option<ValueType>,
44 pub function: Function,
45}
46
47#[derive(Clone, Debug)]
48pub struct Program {
49 pub name: String,
50 pub state: ValueType,
51 pub initializer: Function,
52 pub handlers: Vec<Handler>,
53}
54
55impl Program {
56 pub fn validate(&self) -> Result<(), String> {
57 if self.handlers.len() > MAX_HANDLERS {
58 return Err("too many handlers for the scalar prototype".into());
59 }
60 self.initializer
61 .validate(self.state, &[], ValueType::Unit, true)?;
62 for handler in &self.handlers {
63 if handler.parameters.len() > MAX_PARAMETERS {
64 return Err("too many parameters for the scalar prototype".into());
65 }
66 handler.function.validate(
67 self.state,
68 &handler.parameters,
69 handler.reply.unwrap_or(ValueType::Unit),
70 false,
71 )?;
72 }
73 Ok(())
74 }
75}
76
77impl Function {
78 fn validate(
79 &self,
80 state: ValueType,
81 parameters: &[(String, ValueType)],
82 reply: ValueType,
83 initializer: bool,
84 ) -> Result<(), String> {
85 if self.instructions.len() > MAX_OPERATIONS {
86 return Err("too many operations for the scalar prototype".into());
87 }
88 let mut types = Vec::new();
89 for instruction in &self.instructions {
90 let valid = match instruction.operation {
91 Operation::Constant(value) => instruction.ty.accepts(value),
92 Operation::State => !initializer && instruction.ty == state,
93 Operation::Argument(index) => parameters
94 .get(index)
95 .is_some_and(|parameter| parameter.1 == instruction.ty),
96 Operation::Negate(value) => {
97 instruction.ty == ValueType::Int && types.get(value) == Some(&ValueType::Int)
98 }
99 Operation::Binary(_, left, right) => {
100 instruction.ty == ValueType::Int
101 && types.get(left) == Some(&ValueType::Int)
102 && types.get(right) == Some(&ValueType::Int)
103 }
104 };
105 if !valid {
106 return Err("invalid scalar IR operand, type or forward reference".into());
107 }
108 types.push(instruction.ty);
109 }
110 if types.get(self.state) != Some(&state) || types.get(self.reply) != Some(&reply) {
111 return Err("invalid scalar IR state or reply register".into());
112 }
113 Ok(())
114 }
115}