wings-ir 0.0.4

Validated managed execution IR and CFG root analysis for Wings VM
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
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)> {
    // Both measures come from the SCC-condensed call DAG: edges inside a
    // strongly connected component are recursion (bounded dynamically by the
    // runtime step/stack/root budgets) and contribute a single entry, while
    // edges between components accumulate exactly. Treating any chain that
    // merely reaches recursion as unverifiable instead let an arbitrarily
    // deep acyclic prefix skip both static limits.
    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()
}