Skip to main content

wings_ir/
lib.rs

1use wings_abi::{MAX_SHADOW_ROOTS, ValueType};
2
3mod root_plan;
4
5pub const MAX_OPERATIONS: usize = 4096;
6pub const MAX_HANDLERS: usize = 128;
7pub const MAX_PARAMETERS: usize = 64;
8pub const MAX_FUNCTIONS: usize = 64;
9pub const MAX_TOTAL_OPERATIONS: usize = 65536;
10pub const MAX_LITERAL_BYTES: usize = 1 << 20;
11
12pub type Register = usize;
13
14#[derive(Clone, Copy, Debug)]
15pub enum Operator {
16    Add,
17    Subtract,
18    Multiply,
19    Divide,
20    Remainder,
21}
22
23#[derive(Clone, Copy, Debug)]
24pub enum Comparison {
25    Equal,
26    NotEqual,
27    Less,
28    LessEqual,
29    Greater,
30    GreaterEqual,
31}
32
33#[derive(Clone, Debug)]
34pub enum Operation {
35    Constant(i64),
36    StringLiteral(String),
37    BytesLiteral(Vec<u8>),
38    IntToString(Register),
39    BoolToString(Register),
40    RecordNew {
41        schema: u16,
42        arguments: Vec<Register>,
43    },
44    RecordField {
45        value: Register,
46        field: usize,
47    },
48    State,
49    Argument(usize),
50    Negate(Register),
51    Binary(Operator, Register, Register),
52    Compare(Comparison, Register, Register),
53    Collect,
54    EmptyInts,
55    PrependInt(Register, Register),
56    HeadInt(Register),
57    TailInts(Register),
58    IsEmptyInts(Register),
59    FillBytes(Register, Register),
60    BytesLen(Register),
61    ByteAt(Register, Register),
62    ReplaceByte([Register; 3]),
63    ReadI64Be(Register, Register),
64    ReplaceI64Be([Register; 3]),
65    StringFromBytes(Register),
66    StringBytes(Register),
67    StringLen(Register),
68    StringAt(Register, Register),
69    StringSlice([Register; 3]),
70    ConcatStrings(Register, Register),
71    EqualStrings(Register, Register),
72    SendSelf {
73        handler: usize,
74        arguments: Vec<Register>,
75    },
76    SendAfterSelf {
77        handler: usize,
78        delay: Register,
79        arguments: Vec<Register>,
80    },
81    NullPid,
82    SelfPid,
83    SpawnSelf,
84    SpawnActor(usize),
85    Send {
86        target: Register,
87        handler: usize,
88        arguments: Vec<Register>,
89    },
90    SendActor {
91        target: Register,
92        actor: usize,
93        handler: usize,
94        arguments: Vec<Register>,
95    },
96    SendAfter {
97        target: Register,
98        handler: usize,
99        delay: Register,
100        arguments: Vec<Register>,
101    },
102    SendAfterActor {
103        target: Register,
104        actor: usize,
105        handler: usize,
106        delay: Register,
107        arguments: Vec<Register>,
108    },
109    Monitor {
110        target: Register,
111        handler: usize,
112    },
113    Request {
114        target: Register,
115        handler: usize,
116        callback: usize,
117        timeout: Register,
118        arguments: Vec<Register>,
119    },
120    RequestActor {
121        target: Register,
122        actor: usize,
123        handler: usize,
124        callback: usize,
125        timeout: Register,
126        arguments: Vec<Register>,
127    },
128    CancelRequest(Register),
129    Call {
130        function: usize,
131        arguments: Vec<Register>,
132    },
133    If(Register),
134    Else(Vec<Register>),
135    EndIf(Vec<Register>),
136    Loop(Vec<Register>),
137    While(Register),
138    EndLoop(Vec<Register>),
139    PhiValue(usize),
140}
141
142#[derive(Clone, Debug)]
143pub struct Instruction {
144    pub ty: ValueType,
145    pub operation: Operation,
146}
147
148#[derive(Clone, Debug)]
149pub struct Function {
150    pub instructions: Vec<Instruction>,
151    pub state: Register,
152    pub reply: Register,
153}
154
155#[derive(Clone, Debug)]
156pub struct Handler {
157    pub name: String,
158    pub parameters: Vec<(String, ValueType)>,
159    pub reply: Option<ValueType>,
160    pub completion: Option<ValueType>,
161    pub function: Function,
162}
163
164impl Handler {
165    pub fn is_completion(&self) -> bool {
166        self.completion_reply().is_some()
167    }
168
169    pub fn completion_reply(&self) -> Option<ValueType> {
170        self.completion
171            .or(match (self.reply, self.parameters.as_slice()) {
172                (
173                    None,
174                    [
175                        (_, ValueType::RequestId),
176                        (_, ValueType::Int),
177                        (
178                            _,
179                            ty @ (ValueType::Int
180                            | ValueType::Bool
181                            | ValueType::Unit
182                            | ValueType::ListRef
183                            | ValueType::BytesRef
184                            | ValueType::StringRef
185                            | ValueType::Pid),
186                        ),
187                    ],
188                ) => Some(*ty),
189                _ => None,
190            })
191    }
192}
193
194#[derive(Clone, Debug)]
195pub struct ExternalHandler {
196    pub name: String,
197    pub parameters: Vec<(String, ValueType)>,
198    pub reply: Option<ValueType>,
199}
200
201#[derive(Clone, Debug)]
202pub struct ExternalActor {
203    pub name: String,
204    pub records: Vec<wings_abi::RecordSchema>,
205    pub handlers: Vec<ExternalHandler>,
206}
207
208#[derive(Clone, Debug)]
209pub struct Program {
210    pub name: String,
211    pub records: Vec<wings_abi::RecordSchema>,
212    pub external_actors: Vec<ExternalActor>,
213    pub state: ValueType,
214    pub initializer: Function,
215    pub functions: Vec<Procedure>,
216    pub handlers: Vec<Handler>,
217}
218
219#[derive(Clone, Debug)]
220pub struct Procedure {
221    pub name: String,
222    pub parameters: Vec<(String, ValueType)>,
223    pub result: ValueType,
224    pub function: Function,
225}
226
227enum Region {
228    Branch(usize, Option<Vec<ValueType>>),
229    Loop(usize, Vec<ValueType>, bool),
230}
231
232impl Program {
233    pub fn validate(&self) -> Result<(), String> {
234        wings_abi::validate_records(&self.records)?;
235        if self.functions.iter().any(|procedure| std::iter::once(procedure.result)
236            .chain(procedure.parameters.iter().map(|(_, ty)| *ty))
237            .any(|ty| matches!(ty, ValueType::RecordRef(index) if usize::from(index) >= self.records.len()))) {
238            return Err("invalid named record function signature".into());
239        }
240        let functions = self
241            .functions
242            .iter()
243            .map(|procedure| &procedure.function)
244            .chain(self.handlers.iter().map(|handler| &handler.function))
245            .chain(std::iter::once(&self.initializer));
246        for function in functions {
247            for instruction in &function.instructions {
248                if matches!(instruction.ty, ValueType::RecordRef(index) if usize::from(index) >= self.records.len())
249                {
250                    return Err("invalid named record type index".into());
251                }
252                match &instruction.operation {
253                    Operation::RecordNew { schema, arguments } => {
254                        let record = self
255                            .records
256                            .get(usize::from(*schema))
257                            .ok_or("invalid record schema index")?;
258                        if instruction.ty != ValueType::RecordRef(*schema)
259                            || record.fields.len() != arguments.len()
260                            || record
261                                .fields
262                                .iter()
263                                .zip(arguments)
264                                .any(|((_, ty), register)| {
265                                    function.instructions.get(*register).map(|value| value.ty)
266                                        != Some(*ty)
267                                })
268                        {
269                            return Err("record constructor field type mismatch".into());
270                        }
271                    }
272                    Operation::RecordField { value, field } => {
273                        let Some(ValueType::RecordRef(schema)) =
274                            function.instructions.get(*value).map(|value| value.ty)
275                        else {
276                            return Err("record field requires named record".into());
277                        };
278                        if self
279                            .records
280                            .get(usize::from(schema))
281                            .and_then(|record| record.fields.get(*field))
282                            .map(|(_, ty)| *ty)
283                            != Some(instruction.ty)
284                        {
285                            return Err("invalid record field index or result type".into());
286                        }
287                    }
288                    _ => {}
289                }
290            }
291        }
292        if matches!(self.state, ValueType::RecordRef(index) if usize::from(index) >= self.records.len())
293            || self.handlers.iter().any(|handler| {
294                handler
295                    .parameters
296                    .iter()
297                    .any(|(_, ty)| matches!(ty, ValueType::RecordRef(_)))
298            })
299        {
300            return Err("named records cannot be message parameters".into());
301        }
302        if self.functions.len() > MAX_FUNCTIONS {
303            return Err("too many managed functions".into());
304        }
305        let total = self
306            .functions
307            .iter()
308            .map(|function| &function.function)
309            .chain(self.handlers.iter().map(|handler| &handler.function))
310            .chain(std::iter::once(&self.initializer))
311            .try_fold(0usize, |total, function| {
312                total.checked_add(function.instructions.len())
313            })
314            .ok_or("total IR operation count overflow")?;
315        if total > MAX_TOTAL_OPERATIONS {
316            return Err("program exceeds 65536 total IR operations".into());
317        }
318        self.functions
319            .iter()
320            .map(|function| &function.function)
321            .chain(self.handlers.iter().map(|handler| &handler.function))
322            .chain(std::iter::once(&self.initializer))
323            .flat_map(|function| &function.instructions)
324            .try_fold(0usize, |total, instruction| match &instruction.operation {
325                Operation::StringLiteral(value) => total.checked_add(value.len()),
326                Operation::BytesLiteral(value) => total.checked_add(value.len()),
327                _ => Some(total),
328            })
329            .filter(|total| *total <= MAX_LITERAL_BYTES)
330            .ok_or("program exceeds 1 MiB total string literal bytes")?;
331        if self.external_actors.len() > 32 {
332            return Err("external actor count exceeds 32".into());
333        }
334        for ext in &self.external_actors {
335            wings_abi::validate_records(&ext.records)?;
336            if ext.handlers.len() > MAX_HANDLERS {
337                return Err("external actor exceeds 128 handlers".into());
338            }
339        }
340        let mut call_edges = Vec::with_capacity(self.functions.len());
341        let mut own_roots = Vec::with_capacity(self.functions.len());
342        for procedure in &self.functions {
343            if procedure.parameters.len() > MAX_PARAMETERS {
344                return Err("too many managed function parameters".into());
345            }
346            procedure.function.validate(
347                ValueType::Unit,
348                &procedure.parameters,
349                procedure.result,
350                false,
351                true,
352            )?;
353            if procedure
354                .function
355                .instructions
356                .iter()
357                .any(|instruction| is_effect(&instruction.operation))
358            {
359                return Err("effects are not supported in managed functions".into());
360            }
361            call_edges.push(self.validate_call_signatures(&procedure.function)?);
362            own_roots.push(procedure.function.root_plan().capacity);
363        }
364        let acyclic_paths = compute_acyclic_call_paths(&call_edges, &own_roots);
365        for path in acyclic_paths.iter().flatten() {
366            if path.0 > 32 {
367                return Err("function call chain exceeds 32".into());
368            }
369            if path.1 > MAX_SHADOW_ROOTS {
370                return Err("managed call path exceeds 64 shadow roots".into());
371            }
372        }
373        if self.state == ValueType::RequestId
374            || self.handlers.iter().any(|handler| {
375                handler.reply == Some(ValueType::RequestId)
376                    || handler
377                        .parameters
378                        .iter()
379                        .any(|(_, ty)| *ty == ValueType::RequestId && !handler.is_completion())
380            })
381        {
382            return Err("RequestId is only supported as a local value".into());
383        }
384        if self.handlers.len() > MAX_HANDLERS {
385            return Err("too many handlers for the scalar prototype".into());
386        }
387        self.initializer
388            .validate(self.state, &[], ValueType::Unit, false, false)?;
389        self.validate_entry_calls(&self.initializer, &acyclic_paths)?;
390        if self
391            .initializer
392            .instructions
393            .iter()
394            .any(|instruction| is_effect(&instruction.operation))
395        {
396            return Err("self-send is not supported in initializers".into());
397        }
398        for handler in &self.handlers {
399            if handler.parameters.len() > MAX_PARAMETERS {
400                return Err("too many parameters for the scalar prototype".into());
401            }
402            if let Some(ValueType::RecordRef(schema)) = handler.completion {
403                let expansion = wings_abi::expand_record_schema(&self.records, schema)?;
404                if handler.reply.is_some()
405                    || handler.parameters.len() != expansion.count + 2
406                    || handler.parameters[0].1 != ValueType::RequestId
407                    || handler.parameters[1].1 != ValueType::Int
408                    || handler.parameters[2..]
409                        .iter()
410                        .zip(&expansion.fields[..expansion.count])
411                        .any(|((_, actual), expected)| actual != expected)
412                {
413                    return Err("invalid named record completion signature".into());
414                }
415            } else if handler.completion.is_some() {
416                return Err("explicit completion metadata is reserved for named records".into());
417            }
418            if let Some(ValueType::RecordRef(schema)) = handler.reply {
419                wings_abi::expand_record_schema(&self.records, schema)?;
420            }
421            handler.function.validate(
422                self.state,
423                &handler.parameters,
424                handler.reply.unwrap_or(ValueType::Unit),
425                true,
426                true,
427            )?;
428            self.validate_entry_calls(&handler.function, &acyclic_paths)?;
429            for instruction in &handler.function.instructions {
430                if matches!(
431                    &instruction.operation,
432                    Operation::SpawnActor(actor) if *actor >= self.external_actors.len()
433                ) {
434                    return Err("invalid external actor spawn index".into());
435                }
436                if let Operation::SendActor {
437                    actor,
438                    handler: target,
439                    arguments,
440                    ..
441                }
442                | Operation::SendAfterActor {
443                    actor,
444                    handler: target,
445                    arguments,
446                    ..
447                } = &instruction.operation
448                {
449                    let ext = self
450                        .external_actors
451                        .get(*actor)
452                        .ok_or("invalid external actor index")?;
453                    let target = ext
454                        .handlers
455                        .get(*target)
456                        .ok_or("invalid external send handler")?;
457                    if target.reply.is_some()
458                        || target.parameters.len() != arguments.len()
459                        || arguments
460                            .iter()
461                            .zip(&target.parameters)
462                            .any(|(register, (_, ty))| {
463                                handler.function.instructions[*register].ty != *ty
464                            })
465                    {
466                        return Err(
467                            "external send requires matching one-way handler parameters".into()
468                        );
469                    }
470                }
471                if let Operation::Monitor {
472                    handler: target, ..
473                } = &instruction.operation
474                {
475                    let target = self
476                        .handlers
477                        .get(*target)
478                        .ok_or("invalid monitor handler")?;
479                    if target.reply.is_some()
480                        || target.is_completion()
481                        || target.parameters.len() != 2
482                        || target.parameters[0].1 != ValueType::Pid
483                        || target.parameters[1].1 != ValueType::Int
484                    {
485                        return Err("monitor requires a one-way (Pid, Int) handler".into());
486                    }
487                }
488                if let Operation::RequestActor {
489                    actor,
490                    handler: target,
491                    callback,
492                    arguments,
493                    ..
494                } = &instruction.operation
495                {
496                    let ext = self
497                        .external_actors
498                        .get(*actor)
499                        .ok_or("invalid external actor index")?;
500                    let target = ext
501                        .handlers
502                        .get(*target)
503                        .ok_or("invalid external request handler")?;
504                    let callback = self
505                        .handlers
506                        .get(*callback)
507                        .ok_or("invalid request completion")?;
508                    let compatible_reply = match (callback.completion_reply(), target.reply) {
509                        (Some(cb_ty), Some(tgt_ty)) => {
510                            wings_abi::equivalent_types(&self.records, cb_ty, &ext.records, tgt_ty)
511                        }
512                        _ => false,
513                    };
514                    if !matches!(
515                        target.reply,
516                        Some(
517                            ValueType::Int
518                                | ValueType::Bool
519                                | ValueType::Unit
520                                | ValueType::ListRef
521                                | ValueType::BytesRef
522                                | ValueType::StringRef
523                                | ValueType::RecordRef(_)
524                                | ValueType::Pid
525                        )
526                    ) || !compatible_reply
527                        || matches!(target.reply, Some(ValueType::RecordRef(index))
528                            if wings_abi::expand_record_schema(&ext.records, index).is_err())
529                        || target.parameters.len() != arguments.len()
530                        || arguments
531                            .iter()
532                            .zip(&target.parameters)
533                            .any(|(register, (_, ty))| {
534                                handler.function.instructions[*register].ty != *ty
535                            })
536                    {
537                        return Err(
538                            "external request requires a supported reply, matching completion event and matching parameters"
539                                .into(),
540                        );
541                    }
542                }
543                if let Operation::Request {
544                    handler: target,
545                    callback,
546                    arguments,
547                    ..
548                } = &instruction.operation
549                {
550                    let target = self
551                        .handlers
552                        .get(*target)
553                        .ok_or("invalid request handler")?;
554                    let callback = self
555                        .handlers
556                        .get(*callback)
557                        .ok_or("invalid request completion")?;
558                    if !matches!(
559                        target.reply,
560                        Some(
561                            ValueType::Int
562                                | ValueType::Bool
563                                | ValueType::Unit
564                                | ValueType::ListRef
565                                | ValueType::BytesRef
566                                | ValueType::StringRef
567                                | ValueType::RecordRef(_)
568                                | ValueType::Pid
569                        )
570                    ) || callback.completion_reply() != target.reply
571                        || matches!(target.reply, Some(ValueType::RecordRef(index))
572                            if wings_abi::expand_record_schema(&self.records, index).is_err())
573                        || target.parameters.len() != arguments.len()
574                        || arguments
575                            .iter()
576                            .zip(&target.parameters)
577                            .any(|(register, (_, ty))| {
578                                handler.function.instructions[*register].ty != *ty
579                            })
580                    {
581                        return Err(
582                            "request requires a supported reply, matching completion event and matching parameters"
583                                .into(),
584                        );
585                    }
586                }
587                if let Operation::SendSelf {
588                    handler: target,
589                    arguments,
590                }
591                | Operation::SendAfterSelf {
592                    handler: target,
593                    arguments,
594                    ..
595                }
596                | Operation::Send {
597                    handler: target,
598                    arguments,
599                    ..
600                }
601                | Operation::SendAfter {
602                    handler: target,
603                    arguments,
604                    ..
605                } = &instruction.operation
606                {
607                    let target = self
608                        .handlers
609                        .get(*target)
610                        .ok_or("invalid self-send handler")?;
611                    if target.reply.is_some()
612                        || target.is_completion()
613                        || target.parameters.len() != arguments.len()
614                        || arguments
615                            .iter()
616                            .zip(&target.parameters)
617                            .any(|(register, (_, ty))| {
618                                handler.function.instructions[*register].ty != *ty
619                            })
620                    {
621                        return Err("self-send requires matching one-way handler parameters".into());
622                    }
623                }
624            }
625        }
626        Ok(())
627    }
628
629    fn validate_call_signatures(&self, function: &Function) -> Result<Vec<usize>, String> {
630        let mut callees = Vec::new();
631        for instruction in &function.instructions {
632            if let Operation::Call {
633                function: target,
634                arguments,
635            } = &instruction.operation
636            {
637                let procedure = self
638                    .functions
639                    .get(*target)
640                    .ok_or("unknown managed function call")?;
641                if instruction.ty != procedure.result
642                    || arguments.len() != procedure.parameters.len()
643                    || arguments
644                        .iter()
645                        .zip(&procedure.parameters)
646                        .any(|(register, (_, ty))| function.instructions[*register].ty != *ty)
647                {
648                    return Err("managed function call signature mismatch".into());
649                }
650                callees.push(*target);
651            }
652        }
653        Ok(callees)
654    }
655
656    fn validate_entry_calls(
657        &self,
658        function: &Function,
659        acyclic_paths: &[Option<(usize, usize)>],
660    ) -> Result<(), String> {
661        let callees = self.validate_call_signatures(function)?;
662        let mut child_roots = 0usize;
663        let mut reaches_cycle = false;
664        for target in callees {
665            match acyclic_paths[target] {
666                Some((_, roots)) => child_roots = child_roots.max(roots),
667                None => reaches_cycle = true,
668            }
669        }
670        if !reaches_cycle && function.root_plan().capacity + child_roots > MAX_SHADOW_ROOTS {
671            return Err("managed call path exceeds 64 shadow roots".into());
672        }
673        Ok(())
674    }
675}
676
677fn compute_acyclic_call_paths(
678    edges: &[Vec<usize>],
679    own_roots: &[usize],
680) -> Vec<Option<(usize, usize)>> {
681    let n = edges.len();
682    let mut state = vec![0u8; n];
683    let mut memo: Vec<Option<(usize, usize)>> = vec![None; n];
684
685    fn dfs(
686        u: usize,
687        edges: &[Vec<usize>],
688        own_roots: &[usize],
689        state: &mut [u8],
690        memo: &mut [Option<(usize, usize)>],
691    ) -> Option<(usize, usize)> {
692        if state[u] == 1 {
693            return None;
694        }
695        if state[u] == 2 {
696            return memo[u];
697        }
698        state[u] = 1;
699        let mut depth = 1usize;
700        let mut child_roots = 0usize;
701        let mut reaches_cycle = false;
702        for &v in &edges[u] {
703            match dfs(v, edges, own_roots, state, memo) {
704                Some((d, r)) => {
705                    depth = depth.max(1 + d);
706                    child_roots = child_roots.max(r);
707                }
708                None => reaches_cycle = true,
709            }
710        }
711        state[u] = 2;
712        memo[u] = (!reaches_cycle).then_some((depth, own_roots[u] + child_roots));
713        memo[u]
714    }
715
716    for i in 0..n {
717        if state[i] == 0 {
718            dfs(i, edges, own_roots, &mut state, &mut memo);
719        }
720    }
721    memo
722}
723
724fn is_effect(operation: &Operation) -> bool {
725    matches!(
726        operation,
727        Operation::SendSelf { .. }
728            | Operation::SendAfterSelf { .. }
729            | Operation::Send { .. }
730            | Operation::SendActor { .. }
731            | Operation::SendAfter { .. }
732            | Operation::SendAfterActor { .. }
733            | Operation::Monitor { .. }
734            | Operation::SelfPid
735            | Operation::SpawnSelf
736            | Operation::SpawnActor(_)
737            | Operation::Request { .. }
738            | Operation::RequestActor { .. }
739            | Operation::CancelRequest(_)
740    )
741}
742
743impl Function {
744    fn validate(
745        &self,
746        state: ValueType,
747        parameters: &[(String, ValueType)],
748        reply: ValueType,
749        allow_state: bool,
750        allow_loops: bool,
751    ) -> Result<(), String> {
752        if self.instructions.len() > MAX_OPERATIONS {
753            return Err("too many operations for the scalar prototype".into());
754        }
755        let mut types = Vec::new();
756        let mut available = Vec::new();
757        let mut branches = Vec::new();
758        let mut expected_phis: std::collections::VecDeque<(usize, ValueType)> =
759            std::collections::VecDeque::new();
760        for instruction in &self.instructions {
761            if let Some((expected_index, expected_ty)) = expected_phis.pop_front() {
762                if !matches!(instruction.operation, Operation::PhiValue(actual) if actual == expected_index)
763                    || instruction.ty != expected_ty
764                {
765                    return Err("invalid or missing phi result instruction".into());
766                }
767                types.push(instruction.ty);
768                available.push(true);
769                continue;
770            }
771            if matches!(instruction.operation, Operation::PhiValue(_)) {
772                return Err("unexpected phi result instruction".into());
773            }
774            let operands = operands(&instruction.operation);
775            if operands
776                .into_iter()
777                .any(|register| available.get(register) != Some(&true))
778            {
779                return Err(
780                    "invalid scalar IR operand, type or forward reference, or branch scope".into(),
781                );
782            }
783            let valid = match instruction.operation {
784                Operation::Constant(value) => instruction.ty.accepts(value),
785                Operation::StringLiteral(ref value) => {
786                    instruction.ty == ValueType::StringRef && value.len() <= 65536
787                }
788                Operation::BytesLiteral(ref value) => {
789                    instruction.ty == ValueType::BytesRef && value.len() <= 65536
790                }
791                Operation::IntToString(value) => {
792                    instruction.ty == ValueType::StringRef
793                        && types.get(value) == Some(&ValueType::Int)
794                }
795                Operation::BoolToString(value) => {
796                    instruction.ty == ValueType::StringRef
797                        && types.get(value) == Some(&ValueType::Bool)
798                }
799                Operation::RecordNew { .. } | Operation::RecordField { .. } => true,
800                Operation::State => allow_state && instruction.ty == state,
801                Operation::Argument(index) => parameters
802                    .get(index)
803                    .is_some_and(|parameter| parameter.1 == instruction.ty),
804                Operation::Negate(value) => {
805                    instruction.ty == ValueType::Int && types.get(value) == Some(&ValueType::Int)
806                }
807                Operation::Binary(_, left, right) => {
808                    instruction.ty == ValueType::Int
809                        && types.get(left) == Some(&ValueType::Int)
810                        && types.get(right) == Some(&ValueType::Int)
811                }
812                Operation::Compare(comparison, left, right) => {
813                    instruction.ty == ValueType::Bool
814                        && types.get(left) == types.get(right)
815                        && match comparison {
816                            Comparison::Equal | Comparison::NotEqual => matches!(
817                                types.get(left),
818                                Some(
819                                    ValueType::Int
820                                        | ValueType::Bool
821                                        | ValueType::Unit
822                                        | ValueType::Pid
823                                )
824                            ),
825                            _ => types.get(left) == Some(&ValueType::Int),
826                        }
827                }
828                Operation::Collect => instruction.ty == ValueType::Unit,
829                Operation::EmptyInts => instruction.ty == ValueType::ListRef,
830                Operation::PrependInt(value, tail) => {
831                    instruction.ty == ValueType::ListRef
832                        && types.get(value) == Some(&ValueType::Int)
833                        && types.get(tail) == Some(&ValueType::ListRef)
834                }
835                Operation::HeadInt(value) => {
836                    instruction.ty == ValueType::Int
837                        && types.get(value) == Some(&ValueType::ListRef)
838                }
839                Operation::TailInts(value) => {
840                    instruction.ty == ValueType::ListRef
841                        && types.get(value) == Some(&ValueType::ListRef)
842                }
843                Operation::IsEmptyInts(value) => {
844                    instruction.ty == ValueType::Bool
845                        && types.get(value) == Some(&ValueType::ListRef)
846                }
847                Operation::FillBytes(length, value) => {
848                    instruction.ty == ValueType::BytesRef
849                        && types.get(length) == Some(&ValueType::Int)
850                        && types.get(value) == Some(&ValueType::Int)
851                }
852                Operation::BytesLen(value) => {
853                    instruction.ty == ValueType::Int
854                        && types.get(value) == Some(&ValueType::BytesRef)
855                }
856                Operation::StringFromBytes(value) => {
857                    instruction.ty == ValueType::StringRef
858                        && types.get(value) == Some(&ValueType::BytesRef)
859                }
860                Operation::StringBytes(value) => {
861                    instruction.ty == ValueType::BytesRef
862                        && types.get(value) == Some(&ValueType::StringRef)
863                }
864                Operation::StringLen(value) => {
865                    instruction.ty == ValueType::Int
866                        && types.get(value) == Some(&ValueType::StringRef)
867                }
868                Operation::StringAt(value, index) => {
869                    instruction.ty == ValueType::Int
870                        && types.get(value) == Some(&ValueType::StringRef)
871                        && types.get(index) == Some(&ValueType::Int)
872                }
873                Operation::StringSlice([value, start, length]) => {
874                    instruction.ty == ValueType::StringRef
875                        && types.get(value) == Some(&ValueType::StringRef)
876                        && types.get(start) == Some(&ValueType::Int)
877                        && types.get(length) == Some(&ValueType::Int)
878                }
879                Operation::ConcatStrings(left, right) => {
880                    instruction.ty == ValueType::StringRef
881                        && types.get(left) == Some(&ValueType::StringRef)
882                        && types.get(right) == Some(&ValueType::StringRef)
883                }
884                Operation::EqualStrings(left, right) => {
885                    instruction.ty == ValueType::Bool
886                        && types.get(left) == Some(&ValueType::StringRef)
887                        && types.get(right) == Some(&ValueType::StringRef)
888                }
889                Operation::ByteAt(value, index) | Operation::ReadI64Be(value, index) => {
890                    instruction.ty == ValueType::Int
891                        && types.get(value) == Some(&ValueType::BytesRef)
892                        && types.get(index) == Some(&ValueType::Int)
893                }
894                Operation::ReplaceByte([value, index, byte])
895                | Operation::ReplaceI64Be([value, index, byte]) => {
896                    instruction.ty == ValueType::BytesRef
897                        && types.get(value) == Some(&ValueType::BytesRef)
898                        && types.get(index) == Some(&ValueType::Int)
899                        && types.get(byte) == Some(&ValueType::Int)
900                }
901                Operation::SendSelf { ref arguments, .. } => {
902                    instruction.ty == ValueType::Unit
903                        && arguments.len() <= MAX_PARAMETERS
904                        && arguments.iter().all(|register| {
905                            types.get(*register).is_some_and(|ty| {
906                                matches!(
907                                    ty,
908                                    ValueType::Int
909                                        | ValueType::Bool
910                                        | ValueType::Unit
911                                        | ValueType::ListRef
912                                        | ValueType::BytesRef
913                                        | ValueType::StringRef
914                                        | ValueType::Pid
915                                )
916                            })
917                        })
918                }
919                Operation::SendAfterSelf {
920                    delay,
921                    ref arguments,
922                    ..
923                } => {
924                    instruction.ty == ValueType::Unit
925                        && types.get(delay) == Some(&ValueType::Int)
926                        && arguments.len() <= MAX_PARAMETERS
927                        && arguments.iter().all(|register| {
928                            types.get(*register).is_some_and(|ty| {
929                                matches!(
930                                    ty,
931                                    ValueType::Int
932                                        | ValueType::Bool
933                                        | ValueType::Unit
934                                        | ValueType::ListRef
935                                        | ValueType::BytesRef
936                                        | ValueType::StringRef
937                                        | ValueType::Pid
938                                )
939                            })
940                        })
941                }
942                Operation::NullPid
943                | Operation::SelfPid
944                | Operation::SpawnSelf
945                | Operation::SpawnActor(_) => instruction.ty == ValueType::Pid,
946                Operation::Monitor { target, .. } => {
947                    instruction.ty == ValueType::Unit && types.get(target) == Some(&ValueType::Pid)
948                }
949                Operation::Request {
950                    target,
951                    timeout,
952                    ref arguments,
953                    ..
954                }
955                | Operation::RequestActor {
956                    target,
957                    timeout,
958                    ref arguments,
959                    ..
960                } => {
961                    instruction.ty == ValueType::RequestId
962                        && types.get(target) == Some(&ValueType::Pid)
963                        && types.get(timeout) == Some(&ValueType::Int)
964                        && arguments.len() <= MAX_PARAMETERS
965                        && arguments.iter().all(|register| {
966                            types.get(*register).is_some_and(|ty| {
967                                matches!(
968                                    ty,
969                                    ValueType::Int
970                                        | ValueType::Bool
971                                        | ValueType::Unit
972                                        | ValueType::ListRef
973                                        | ValueType::BytesRef
974                                        | ValueType::StringRef
975                                        | ValueType::Pid
976                                )
977                            })
978                        })
979                }
980                Operation::CancelRequest(value) => {
981                    instruction.ty == ValueType::Unit
982                        && types.get(value) == Some(&ValueType::RequestId)
983                }
984                Operation::Call { ref arguments, .. } => arguments.len() <= MAX_PARAMETERS,
985                Operation::Send {
986                    target,
987                    ref arguments,
988                    ..
989                }
990                | Operation::SendActor {
991                    target,
992                    ref arguments,
993                    ..
994                } => {
995                    instruction.ty == ValueType::Unit
996                        && types.get(target) == Some(&ValueType::Pid)
997                        && arguments.len() <= MAX_PARAMETERS
998                        && arguments.iter().all(|register| {
999                            types.get(*register).is_some_and(|ty| {
1000                                matches!(
1001                                    ty,
1002                                    ValueType::Int
1003                                        | ValueType::Bool
1004                                        | ValueType::Unit
1005                                        | ValueType::ListRef
1006                                        | ValueType::BytesRef
1007                                        | ValueType::StringRef
1008                                        | ValueType::Pid
1009                                )
1010                            })
1011                        })
1012                }
1013                Operation::SendAfter {
1014                    target,
1015                    delay,
1016                    ref arguments,
1017                    ..
1018                }
1019                | Operation::SendAfterActor {
1020                    target,
1021                    delay,
1022                    ref arguments,
1023                    ..
1024                } => {
1025                    instruction.ty == ValueType::Unit
1026                        && types.get(target) == Some(&ValueType::Pid)
1027                        && types.get(delay) == Some(&ValueType::Int)
1028                        && arguments.len() <= MAX_PARAMETERS
1029                        && arguments.iter().all(|register| {
1030                            types.get(*register).is_some_and(|ty| {
1031                                matches!(
1032                                    ty,
1033                                    ValueType::Int
1034                                        | ValueType::Bool
1035                                        | ValueType::Unit
1036                                        | ValueType::ListRef
1037                                        | ValueType::BytesRef
1038                                        | ValueType::StringRef
1039                                        | ValueType::Pid
1040                                )
1041                            })
1042                        })
1043                }
1044                Operation::If(condition) => {
1045                    if branches.len() == 64 {
1046                        return Err("conditional nesting exceeds 64 branches".into());
1047                    }
1048                    branches.push(Region::Branch(types.len(), None));
1049                    instruction.ty == ValueType::Unit
1050                        && types.get(condition) == Some(&ValueType::Bool)
1051                }
1052                Operation::Else(ref values) => {
1053                    let Some(Region::Branch(start, arm)) = branches.last_mut() else {
1054                        return Err("else without matching if".into());
1055                    };
1056                    if arm.is_some() {
1057                        return Err("duplicate else in conditional".into());
1058                    }
1059                    if values.is_empty() || values.len() > MAX_PARAMETERS {
1060                        return Err("invalid branch arity".into());
1061                    }
1062                    let then_types: Vec<ValueType> = values.iter().map(|&reg| types[reg]).collect();
1063                    *arm = Some(then_types);
1064                    available[start.saturating_add(1)..].fill(false);
1065                    instruction.ty == ValueType::Unit
1066                }
1067                Operation::EndIf(ref values) => {
1068                    let Some(Region::Branch(start, Some(then_types))) = branches.pop() else {
1069                        return Err("end-if without matching if/else".into());
1070                    };
1071                    available[start.saturating_add(1)..].fill(false);
1072                    let valid = values.len() == then_types.len()
1073                        && instruction.ty == then_types[0]
1074                        && values
1075                            .iter()
1076                            .zip(&then_types)
1077                            .all(|(&reg, &ty)| types.get(reg) == Some(&ty));
1078                    for (idx, &ty) in then_types.iter().enumerate().skip(1) {
1079                        expected_phis.push_back((idx, ty));
1080                    }
1081                    valid
1082                }
1083                Operation::Loop(ref initials) => {
1084                    if branches.len() == 64 {
1085                        return Err("control nesting exceeds 64 regions".into());
1086                    }
1087                    if !allow_loops || initials.is_empty() || initials.len() > MAX_PARAMETERS {
1088                        false
1089                    } else {
1090                        let phi_types: Vec<ValueType> =
1091                            initials.iter().map(|&reg| types[reg]).collect();
1092                        let valid = instruction.ty == phi_types[0];
1093                        for (idx, &ty) in phi_types.iter().enumerate().skip(1) {
1094                            expected_phis.push_back((idx, ty));
1095                        }
1096                        branches.push(Region::Loop(types.len(), phi_types, false));
1097                        valid
1098                    }
1099                }
1100                Operation::While(condition) => {
1101                    let Some(Region::Loop(_, _, tested)) = branches.last_mut() else {
1102                        return Err("while without matching loop".into());
1103                    };
1104                    if *tested {
1105                        return Err("duplicate while in loop".into());
1106                    }
1107                    *tested = true;
1108                    instruction.ty == ValueType::Unit
1109                        && types.get(condition) == Some(&ValueType::Bool)
1110                }
1111                Operation::EndLoop(ref values) => {
1112                    let Some(Region::Loop(start, phi_types, true)) = branches.pop() else {
1113                        return Err("end-loop without matching loop/while".into());
1114                    };
1115                    available[start..].fill(false);
1116                    let valid = values.len() == phi_types.len()
1117                        && instruction.ty == phi_types[0]
1118                        && values
1119                            .iter()
1120                            .zip(&phi_types)
1121                            .all(|(&reg, &ty)| types.get(reg) == Some(&ty));
1122                    for (idx, &ty) in phi_types.iter().enumerate().skip(1) {
1123                        expected_phis.push_back((idx, ty));
1124                    }
1125                    valid
1126                }
1127                Operation::PhiValue(_) => false,
1128            };
1129            if !valid {
1130                return Err("invalid scalar IR operand, type or forward reference".into());
1131            }
1132            types.push(instruction.ty);
1133            available.push(!matches!(
1134                instruction.operation,
1135                Operation::If(_) | Operation::Else(_) | Operation::While(_)
1136            ));
1137        }
1138        if !expected_phis.is_empty() {
1139            return Err("missing phi result instruction".into());
1140        }
1141        if !branches.is_empty() {
1142            return Err("unterminated conditional in scalar IR".into());
1143        }
1144        if types.get(self.state) != Some(&state)
1145            || types.get(self.reply) != Some(&reply)
1146            || available.get(self.state) != Some(&true)
1147            || available.get(self.reply) != Some(&true)
1148        {
1149            return Err("invalid scalar IR state or reply register".into());
1150        }
1151        if self.root_plan().capacity > MAX_SHADOW_ROOTS {
1152            return Err("AOT function exceeds 64 simultaneously live reference roots".into());
1153        }
1154        Ok(())
1155    }
1156
1157    pub fn root_plan(&self) -> RootPlan {
1158        root_plan::build(self)
1159    }
1160}
1161
1162fn operands(operation: &Operation) -> impl Iterator<Item = Register> + '_ {
1163    let (fixed, extra): (_, &[Register]) = match *operation {
1164        Operation::Negate(value) | Operation::If(value) | Operation::While(value) => {
1165            ([Some(value), None], &[])
1166        }
1167        Operation::HeadInt(value)
1168        | Operation::TailInts(value)
1169        | Operation::IsEmptyInts(value)
1170        | Operation::BytesLen(value)
1171        | Operation::StringFromBytes(value)
1172        | Operation::StringBytes(value)
1173        | Operation::StringLen(value)
1174        | Operation::IntToString(value)
1175        | Operation::BoolToString(value) => ([Some(value), None], &[]),
1176        Operation::StringAt(value, index) => ([Some(value), Some(index)], &[]),
1177        Operation::Else(ref values)
1178        | Operation::EndIf(ref values)
1179        | Operation::Loop(ref values)
1180        | Operation::EndLoop(ref values) => ([None, None], values.as_slice()),
1181        Operation::Binary(_, left, right)
1182        | Operation::Compare(_, left, right)
1183        | Operation::FillBytes(left, right)
1184        | Operation::ConcatStrings(left, right)
1185        | Operation::EqualStrings(left, right)
1186        | Operation::ByteAt(left, right)
1187        | Operation::ReadI64Be(left, right)
1188        | Operation::PrependInt(left, right) => ([Some(left), Some(right)], &[]),
1189        Operation::ReplaceByte(ref arguments) | Operation::ReplaceI64Be(ref arguments) => {
1190            ([None, None], arguments.as_slice())
1191        }
1192        Operation::StringSlice(ref arguments) => ([None, None], arguments.as_slice()),
1193        Operation::SendSelf { ref arguments, .. } => ([None, None], arguments),
1194        Operation::SendAfterSelf {
1195            delay,
1196            ref arguments,
1197            ..
1198        } => ([Some(delay), None], arguments),
1199        Operation::Call { ref arguments, .. } => ([None, None], arguments),
1200        Operation::RecordNew { ref arguments, .. } => ([None, None], arguments),
1201        Operation::RecordField { value, .. } => ([Some(value), None], &[]),
1202        Operation::Send {
1203            target,
1204            ref arguments,
1205            ..
1206        }
1207        | Operation::SendActor {
1208            target,
1209            ref arguments,
1210            ..
1211        } => ([Some(target), None], arguments),
1212        Operation::SendAfter {
1213            target,
1214            delay,
1215            ref arguments,
1216            ..
1217        }
1218        | Operation::SendAfterActor {
1219            target,
1220            delay,
1221            ref arguments,
1222            ..
1223        } => ([Some(target), Some(delay)], arguments),
1224        Operation::Monitor { target, .. } => ([Some(target), None], &[]),
1225        Operation::Request {
1226            target,
1227            timeout,
1228            ref arguments,
1229            ..
1230        }
1231        | Operation::RequestActor {
1232            target,
1233            timeout,
1234            ref arguments,
1235            ..
1236        } => ([Some(target), Some(timeout)], arguments),
1237        Operation::CancelRequest(value) => ([Some(value), None], &[]),
1238        _ => ([None, None], &[]),
1239    };
1240    fixed.into_iter().flatten().chain(extra.iter().copied())
1241}
1242
1243pub struct RootPlan {
1244    pub capacity: usize,
1245    pub at: Vec<Vec<Register>>,
1246}