Skip to main content

fic/foreign/
calls.rs

1//! Call sites of imported functions in a `.fi` program, with how each
2//! call's value is used — the information both the C backend (prototypes)
3//! and the contract checks need.
4
5use crate::base::FfnId;
6use crate::tast::{Body, Call, Comm, Event, Expr, ExprKind, Proc, Stmt};
7
8/// How a call's return value is consumed.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum Usage {
11    /// Statement position in an event body: the value is discarded.
12    Statement,
13    /// Part of an expression whose value is used (assignment right-hand side,
14    /// send payload, argument of another call).
15    Value,
16    /// Inside a process guard: used as (part of) a boolean condition.
17    Guard,
18}
19
20/// One call site.
21#[derive(Debug, Clone, Copy)]
22pub struct Site {
23    /// What is called.
24    pub callee: FfnId,
25    /// How the result is used.
26    pub usage: Usage,
27}
28
29/// Every call site in a program: event bodies (statements, assignments,
30/// nested arguments), then send payloads and process guards.
31pub fn call_sites(body: &Body) -> Vec<Site> {
32    let mut out = Vec::new();
33    for evt in body.events.iter() {
34        for stmt in &evt.body {
35            match stmt {
36                Stmt::Call(call) => sites_in_call(call, Usage::Statement, &mut out),
37                Stmt::Assign { rhs, .. } => sites_in_expr(rhs, Usage::Value, &mut out),
38                Stmt::Decl(_) | Stmt::Dbg { .. } => {}
39            }
40        }
41    }
42    for decl in body.processes.iter() {
43        sites_in_proc(&decl.body, &mut out);
44    }
45    out
46}
47
48/// The call, then the calls in its arguments, whose values it uses.
49fn sites_in_call(call: &Call, usage: Usage, out: &mut Vec<Site>) {
50    out.push(Site {
51        callee: call.callee,
52        usage,
53    });
54    let inner = if usage == Usage::Guard {
55        Usage::Guard
56    } else {
57        Usage::Value
58    };
59    for arg in &call.args {
60        sites_in_expr(arg, inner, out);
61    }
62}
63
64fn sites_in_expr(e: &Expr, usage: Usage, out: &mut Vec<Site>) {
65    match &e.kind {
66        ExprKind::Call(call) => sites_in_call(call, usage, out),
67        ExprKind::Unary { operand, .. } | ExprKind::Cast { expr: operand, .. } => {
68            sites_in_expr(operand, usage, out);
69        }
70        ExprKind::Field { base, .. } => sites_in_expr(base, usage, out),
71        ExprKind::Binary { lhs, rhs, .. } => {
72            sites_in_expr(lhs, usage, out);
73            sites_in_expr(rhs, usage, out);
74        }
75        ExprKind::Lit(_)
76        | ExprKind::Var(_)
77        | ExprKind::Vaddr(_)
78        | ExprKind::Paddr(_)
79        | ExprKind::Sizeof { .. } => {}
80    }
81}
82
83fn sites_in_proc(p: &Proc, out: &mut Vec<Site>) {
84    match p {
85        Proc::Prefix(event, rest) => {
86            if let Event::Comm(Comm::Send {
87                expr: Some(expr), ..
88            }) = event
89            {
90                sites_in_expr(expr, Usage::Value, out);
91            }
92            sites_in_proc(rest, out);
93        }
94        Proc::Guard(expr, inner) => {
95            sites_in_expr(expr, Usage::Guard, out);
96            sites_in_proc(inner, out);
97        }
98        Proc::Seq(parts) => {
99            for part in parts {
100                sites_in_proc(part, out);
101            }
102        }
103        Proc::Choice(branches) => {
104            for b in branches {
105                sites_in_proc(b, out);
106            }
107        }
108        Proc::Skip | Proc::Div | Proc::Ref { .. } | Proc::Decl(_) => {}
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115    use crate::base::{Idx, PdId};
116    use crate::tast::env::built_with;
117
118    /// `pingpong.pnk`: the exports in the order `EXPECTED` indexes them.
119    const PNK: &str = "\
120export fun 1 say_ping() { return 0; }
121export fun 1 tally(1 r) { return r + 1; }
122export fun 1 log(1 v) { return 0; }
123export fun 1 peek(1 n) { return n; }
124export fun 1 first() { return 0; }
125export fun 1 keep_playing(1 r) { return r < 5; }
126export fun 1 done() { return 0; }
127";
128
129    const PROGRAM: &str = r#"
130import "pingpong.pnk" as io;
131rounds: uint;
132evt say_ping: io.say_ping();
133evt tally:    rounds = io.tally(rounds);
134evt nested:   io.log(io.peek(1) + 1);
135@bind(microkit.init)
136proc Init() { ball!(io.first() as uint8) -> Skip; }
137@bind(microkit.notified)
138proc Notified() {
139    back?x -> say_ping -> tally -> Skip;
140    [io.keep_playing(rounds) != 0 && io.done() == 0] ball!0 -> Notified()
141 default Skip;
142}
143"#;
144
145    /// Each call's function, by name, and how its value is used. The guard's
146    /// calls come twice: the desugared `default` negates that guard, as the
147    /// Ccfg always evaluated it.
148    const EXPECTED: [(&str, Usage); 9] = [
149        ("say_ping", Usage::Statement),
150        ("tally", Usage::Value),
151        ("log", Usage::Statement),
152        ("peek", Usage::Value),
153        ("first", Usage::Value),
154        ("keep_playing", Usage::Guard),
155        ("done", Usage::Guard),
156        ("keep_playing", Usage::Guard),
157        ("done", Usage::Guard),
158    ];
159
160    #[test]
161    fn finds_calls_with_their_usage() {
162        let fis = "MemoryRegion court(0x1000);\nMemoryRegion back_court(0x1000);\n\
163                   ProtectionDomain ping(100); ProtectionDomain pong(101);\n\
164                   Chan ball = ping --> pong via court<uint8>;\n\
165                   Chan back = pong --> ping via back_court<uint8>;";
166        let (tast, _) = built_with(fis, &[("ping", PROGRAM)], "pingpong.pnk", PNK).expect("builds");
167        let body = &tast.bodies[PdId::new(0)];
168        let summary: Vec<(&str, Usage)> = call_sites(body)
169            .iter()
170            .map(|s| (tast.tenv.ffis[s.callee].name.as_str(), s.usage))
171            .collect();
172        assert_eq!(summary, EXPECTED);
173    }
174}