Skip to main content

wings_ir/validate/
mod.rs

1mod function;
2pub use function::operands;
3
4use super::*;
5
6impl Program {
7    pub fn validate(&self) -> Result<(), String> {
8        wings_abi::validate_records(&self.records)?;
9        if self.functions.iter().any(|procedure| std::iter::once(procedure.result)
10            .chain(procedure.parameters.iter().map(|(_, ty)| *ty))
11            .any(|ty| matches!(ty, ValueType::RecordRef(index) if usize::from(index) >= self.records.len()))) {
12            return Err("invalid named record function signature".into());
13        }
14        let functions = self
15            .functions
16            .iter()
17            .map(|procedure| &procedure.function)
18            .chain(self.handlers.iter().map(|handler| &handler.function))
19            .chain(std::iter::once(&self.initializer));
20        for function in functions {
21            for instruction in &function.instructions {
22                if matches!(instruction.ty, ValueType::RecordRef(index) if usize::from(index) >= self.records.len())
23                {
24                    return Err("invalid named record type index".into());
25                }
26                match &instruction.operation {
27                    Operation::RecordNew { schema, arguments } => {
28                        let record = self
29                            .records
30                            .get(usize::from(*schema))
31                            .ok_or("invalid record schema index")?;
32                        if instruction.ty != ValueType::RecordRef(*schema)
33                            || record.fields.len() != arguments.len()
34                            || record
35                                .fields
36                                .iter()
37                                .zip(arguments)
38                                .any(|((_, ty), register)| {
39                                    function.instructions.get(*register).map(|value| value.ty)
40                                        != Some(*ty)
41                                })
42                        {
43                            return Err("record constructor field type mismatch".into());
44                        }
45                    }
46                    Operation::RecordField { value, field } => {
47                        let Some(ValueType::RecordRef(schema)) =
48                            function.instructions.get(*value).map(|value| value.ty)
49                        else {
50                            return Err("record field requires named record".into());
51                        };
52                        if self
53                            .records
54                            .get(usize::from(schema))
55                            .and_then(|record| record.fields.get(*field))
56                            .map(|(_, ty)| *ty)
57                            != Some(instruction.ty)
58                        {
59                            return Err("invalid record field index or result type".into());
60                        }
61                    }
62                    _ => {}
63                }
64            }
65        }
66        if matches!(self.state, ValueType::RecordRef(index) if usize::from(index) >= self.records.len())
67            || self.handlers.iter().any(|handler| {
68                handler
69                    .parameters
70                    .iter()
71                    .any(|(_, ty)| matches!(ty, ValueType::RecordRef(_)))
72            })
73        {
74            return Err("named records cannot be message parameters".into());
75        }
76        if self.functions.len() > MAX_FUNCTIONS {
77            return Err("too many managed functions".into());
78        }
79        let total = self
80            .functions
81            .iter()
82            .map(|function| &function.function)
83            .chain(self.handlers.iter().map(|handler| &handler.function))
84            .chain(std::iter::once(&self.initializer))
85            .try_fold(0usize, |total, function| {
86                total.checked_add(function.instructions.len())
87            })
88            .ok_or("total IR operation count overflow")?;
89        if total > MAX_TOTAL_OPERATIONS {
90            return Err("program exceeds 65536 total IR operations".into());
91        }
92        self.functions
93            .iter()
94            .map(|function| &function.function)
95            .chain(self.handlers.iter().map(|handler| &handler.function))
96            .chain(std::iter::once(&self.initializer))
97            .flat_map(|function| &function.instructions)
98            .try_fold(0usize, |total, instruction| match &instruction.operation {
99                Operation::StringLiteral(value) => total.checked_add(value.len()),
100                Operation::FormatString { blob, .. } => total.checked_add(blob.len()),
101                Operation::BytesLiteral(value) => total.checked_add(value.len()),
102                _ => Some(total),
103            })
104            .filter(|total| *total <= MAX_LITERAL_BYTES)
105            .ok_or("program exceeds 1 MiB total string literal bytes")?;
106        if self.external_actors.len() > 32 {
107            return Err("external actor count exceeds 32".into());
108        }
109        for ext in &self.external_actors {
110            wings_abi::validate_records(&ext.records)?;
111            if ext.handlers.len() > MAX_HANDLERS {
112                return Err("external actor exceeds 128 handlers".into());
113            }
114            if ext
115                .handlers
116                .iter()
117                .any(|handler| handler.parameters.len() > MAX_PARAMETERS)
118            {
119                return Err("external actor handler exceeds 64 parameters".into());
120            }
121        }
122        let mut call_edges = Vec::with_capacity(self.functions.len());
123        let mut own_roots = Vec::with_capacity(self.functions.len());
124        for procedure in &self.functions {
125            if procedure.parameters.len() > MAX_PARAMETERS {
126                return Err("too many managed function parameters".into());
127            }
128            procedure.function.validate(
129                ValueType::Unit,
130                &procedure.parameters,
131                procedure.result,
132                false,
133                true,
134            )?;
135            if procedure
136                .function
137                .instructions
138                .iter()
139                .any(|instruction| instruction.operation.is_effect())
140            {
141                return Err("effects are not supported in managed functions".into());
142            }
143            call_edges.push(self.validate_call_signatures(&procedure.function)?);
144            own_roots.push(procedure.function.root_plan().capacity);
145        }
146        let acyclic_paths = compute_static_call_paths(&call_edges, &own_roots);
147        for (depth, path_roots) in &acyclic_paths {
148            if *depth > 32 {
149                return Err("function call chain exceeds 32".into());
150            }
151            if *path_roots > MAX_SHADOW_ROOTS {
152                return Err("managed call path exceeds 64 shadow roots".into());
153            }
154        }
155        if self.state == ValueType::RequestId
156            || self.handlers.iter().any(|handler| {
157                handler.reply == Some(ValueType::RequestId)
158                    || handler
159                        .parameters
160                        .iter()
161                        .any(|(_, ty)| *ty == ValueType::RequestId && !handler.is_completion())
162            })
163        {
164            return Err("RequestId is only supported as a local value".into());
165        }
166        if self.handlers.len() > MAX_HANDLERS {
167            return Err("too many handlers for the scalar prototype".into());
168        }
169        self.initializer
170            .validate(self.state, &[], ValueType::Unit, false, false)?;
171        self.validate_entry_calls(&self.initializer, &acyclic_paths)?;
172        if self
173            .initializer
174            .instructions
175            .iter()
176            .any(|instruction| instruction.operation.is_effect())
177        {
178            return Err("self-send is not supported in initializers".into());
179        }
180        for handler in &self.handlers {
181            if handler.parameters.len() > MAX_PARAMETERS {
182                return Err("too many parameters for the scalar prototype".into());
183            }
184            if let Some(ValueType::RecordRef(schema)) = handler.completion {
185                let expansion = wings_abi::expand_record_schema(&self.records, schema)?;
186                if handler.reply.is_some()
187                    || handler.parameters.len() != expansion.count + 2
188                    || handler.parameters[0].1 != ValueType::RequestId
189                    || handler.parameters[1].1 != ValueType::Int
190                    || handler.parameters[2..]
191                        .iter()
192                        .zip(&expansion.fields[..expansion.count])
193                        .any(|((_, actual), expected)| actual != expected)
194                {
195                    return Err("invalid named record completion signature".into());
196                }
197            } else if handler.completion.is_some() {
198                return Err("explicit completion metadata is reserved for named records".into());
199            }
200            if let Some(ValueType::RecordRef(schema)) = handler.reply {
201                wings_abi::expand_record_schema(&self.records, schema)?;
202            }
203            handler.function.validate(
204                self.state,
205                &handler.parameters,
206                handler.reply.unwrap_or(ValueType::Unit),
207                true,
208                true,
209            )?;
210            self.validate_entry_calls(&handler.function, &acyclic_paths)?;
211            for instruction in &handler.function.instructions {
212                if matches!(
213                    &instruction.operation,
214                    Operation::SpawnActor(actor) if *actor >= self.external_actors.len()
215                ) {
216                    return Err("invalid external actor spawn index".into());
217                }
218                if let Operation::SendActor {
219                    actor,
220                    handler: target,
221                    arguments,
222                    ..
223                }
224                | Operation::SendAfterActor {
225                    actor,
226                    handler: target,
227                    arguments,
228                    ..
229                } = &instruction.operation
230                {
231                    let ext = self
232                        .external_actors
233                        .get(*actor)
234                        .ok_or("invalid external actor index")?;
235                    let target = ext
236                        .handlers
237                        .get(*target)
238                        .ok_or("invalid external send handler")?;
239                    if target.reply.is_some()
240                        || target.parameters.len() != arguments.len()
241                        || arguments
242                            .iter()
243                            .zip(&target.parameters)
244                            .any(|(register, (_, ty))| {
245                                handler.function.instructions[*register].ty != *ty
246                            })
247                    {
248                        return Err(
249                            "external send requires matching one-way handler parameters".into()
250                        );
251                    }
252                }
253                if let Operation::Monitor {
254                    handler: target, ..
255                } = &instruction.operation
256                {
257                    let target = self
258                        .handlers
259                        .get(*target)
260                        .ok_or("invalid monitor handler")?;
261                    if target.reply.is_some()
262                        || target.is_completion()
263                        || target.parameters.len() != 2
264                        || target.parameters[0].1 != ValueType::Pid
265                        || target.parameters[1].1 != ValueType::Int
266                    {
267                        return Err("monitor requires a one-way (Pid, Int) handler".into());
268                    }
269                }
270                if let Operation::RequestActor {
271                    actor,
272                    handler: target,
273                    callback,
274                    arguments,
275                    ..
276                } = &instruction.operation
277                {
278                    let ext = self
279                        .external_actors
280                        .get(*actor)
281                        .ok_or("invalid external actor index")?;
282                    let target = ext
283                        .handlers
284                        .get(*target)
285                        .ok_or("invalid external request handler")?;
286                    let callback = self
287                        .handlers
288                        .get(*callback)
289                        .ok_or("invalid request completion")?;
290                    let compatible_reply = match (callback.completion_reply(), target.reply) {
291                        (Some(cb_ty), Some(tgt_ty)) => {
292                            wings_abi::equivalent_types(&self.records, cb_ty, &ext.records, tgt_ty)
293                        }
294                        _ => false,
295                    };
296                    if !target.reply.is_some_and(ValueType::is_supported_reply)
297                        || !compatible_reply
298                        || matches!(target.reply, Some(ValueType::RecordRef(index))
299                            if wings_abi::expand_record_schema(&ext.records, index).is_err())
300                        || target.parameters.len() != arguments.len()
301                        || arguments
302                            .iter()
303                            .zip(&target.parameters)
304                            .any(|(register, (_, ty))| {
305                                handler.function.instructions[*register].ty != *ty
306                            })
307                    {
308                        return Err(
309                            "external request requires a supported reply, matching completion event and matching parameters"
310                                .into(),
311                        );
312                    }
313                }
314                if let Operation::Request {
315                    handler: target,
316                    callback,
317                    arguments,
318                    ..
319                } = &instruction.operation
320                {
321                    let target = self
322                        .handlers
323                        .get(*target)
324                        .ok_or("invalid request handler")?;
325                    let callback = self
326                        .handlers
327                        .get(*callback)
328                        .ok_or("invalid request completion")?;
329                    if !target.reply.is_some_and(ValueType::is_supported_reply)
330                        || callback.completion_reply() != target.reply
331                        || matches!(target.reply, Some(ValueType::RecordRef(index))
332                            if wings_abi::expand_record_schema(&self.records, index).is_err())
333                        || target.parameters.len() != arguments.len()
334                        || arguments
335                            .iter()
336                            .zip(&target.parameters)
337                            .any(|(register, (_, ty))| {
338                                handler.function.instructions[*register].ty != *ty
339                            })
340                    {
341                        return Err(
342                            "request requires a supported reply, matching completion event and matching parameters"
343                                .into(),
344                        );
345                    }
346                }
347                if let Operation::SendSelf {
348                    handler: target,
349                    arguments,
350                }
351                | Operation::SendAfterSelf {
352                    handler: target,
353                    arguments,
354                    ..
355                }
356                | Operation::Send {
357                    handler: target,
358                    arguments,
359                    ..
360                }
361                | Operation::SendAfter {
362                    handler: target,
363                    arguments,
364                    ..
365                } = &instruction.operation
366                {
367                    let target = self
368                        .handlers
369                        .get(*target)
370                        .ok_or("invalid self-send handler")?;
371                    if target.reply.is_some()
372                        || target.is_completion()
373                        || target.parameters.len() != arguments.len()
374                        || arguments
375                            .iter()
376                            .zip(&target.parameters)
377                            .any(|(register, (_, ty))| {
378                                handler.function.instructions[*register].ty != *ty
379                            })
380                    {
381                        return Err("self-send requires matching one-way handler parameters".into());
382                    }
383                }
384            }
385        }
386        Ok(())
387    }
388
389    fn validate_call_signatures(&self, function: &Function) -> Result<Vec<usize>, String> {
390        let mut callees = Vec::new();
391        for instruction in &function.instructions {
392            if let Operation::Call {
393                function: target,
394                arguments,
395            } = &instruction.operation
396            {
397                let procedure = self
398                    .functions
399                    .get(*target)
400                    .ok_or("unknown managed function call")?;
401                if instruction.ty != procedure.result
402                    || arguments.len() != procedure.parameters.len()
403                    || arguments
404                        .iter()
405                        .zip(&procedure.parameters)
406                        .any(|(register, (_, ty))| function.instructions[*register].ty != *ty)
407                {
408                    return Err("managed function call signature mismatch".into());
409                }
410                callees.push(*target);
411            }
412        }
413        Ok(callees)
414    }
415
416    fn validate_entry_calls(
417        &self,
418        function: &Function,
419        acyclic_paths: &[(usize, usize)],
420    ) -> Result<(), String> {
421        let callees = self.validate_call_signatures(function)?;
422        let mut child_roots = 0usize;
423        for target in callees {
424            child_roots = child_roots.max(acyclic_paths[target].1);
425        }
426        if function.root_plan().capacity + child_roots > MAX_SHADOW_ROOTS {
427            return Err("managed call path exceeds 64 shadow roots".into());
428        }
429        Ok(())
430    }
431}
432
433fn compute_static_call_paths(edges: &[Vec<usize>], own_roots: &[usize]) -> Vec<(usize, usize)> {
434    // Both measures come from the SCC-condensed call DAG: edges inside a
435    // strongly connected component are recursion (bounded dynamically by the
436    // runtime step/stack/root budgets) and contribute a single entry, while
437    // edges between components accumulate exactly. Treating any chain that
438    // merely reaches recursion as unverifiable instead let an arbitrarily
439    // deep acyclic prefix skip both static limits.
440    let unit_weights = vec![1usize; edges.len()];
441    let depths = wings_analysis::calls::acyclic_chain_costs(edges, &unit_weights);
442    let roots = wings_analysis::calls::acyclic_chain_costs(edges, own_roots);
443    depths.into_iter().zip(roots).collect()
444}