Skip to main content

fic/xta_backend/
contract.rs

1//! The contracts of the foreign functions a PD calls, as XTA: each
2//! contracted function a declared UPPAAL function, `requires` as `assert`s
3//! and the deterministic `ensures` as its `return`, and a ranged result a
4//! choice of the firing edge. The one place a contract becomes XTA.
5
6use crate::foreign::contract::{BinOp as TermBinOp, FnContract, Term, UnaryOp as TermUnOp};
7
8use super::xta::{BinOp, Expr, FnDecl, Param, Stmt, Type, TypeExpr, UnOp};
9
10/// One template-local UPPAAL function for a contracted export: each `requires`
11/// clause an `assert` (one each, so a violation's `file:line` names the
12/// clause), then the deterministic `ensures` as the `return`; `void` when
13/// there is none and the function is called only for its `assert`s. A
14/// `Term::Param` prints as its own name, which is the function's formal
15/// parameter — no call-site substitution. It is named [`ffi_name`].
16pub(super) fn pancake_function(contract: &FnContract) -> FnDecl {
17    let params = contract
18        .params
19        .iter()
20        .map(|p| Param::value(TypeExpr::plain(Type::Int), p))
21        .collect();
22    let mut body: Vec<Stmt> = contract
23        .requires
24        .iter()
25        .map(|clause| Stmt::Assert(term(clause)))
26        .collect();
27    let ret = match &contract.retval {
28        Some(e) => {
29            body.push(Stmt::Return(Some(term(e))));
30            Type::Int
31        }
32        None => Type::Void,
33    };
34    FnDecl {
35        ret: TypeExpr::plain(ret),
36        name: ffi_name(&contract.name),
37        params,
38        body_vars: Vec::new(),
39        body,
40    }
41}
42
43/// The model's name for the foreign function `name`: `ffi_<name>`, apart
44/// from the event functions, which take their events' names.
45pub(super) fn ffi_name(name: &str) -> String {
46    format!("ffi_{name}")
47}
48
49/// A contract term as an XTA expression — the one place a contract becomes
50/// UPPAAL syntax.
51fn term(t: &Term) -> Expr {
52    term_with(t, "retval")
53}
54
55/// [`term`], the return value named `result`.
56pub(super) fn term_with(t: &Term, result: &str) -> Expr {
57    let sub = |t| term_with(t, result);
58    match t {
59        Term::Int(n) => Expr::Int(*n),
60        Term::Bool(b) => Expr::Bool(*b),
61        Term::Param(name) => Expr::ident(name),
62        Term::RetVal => Expr::ident(result),
63        Term::Field { base, name } => Expr::Field {
64            base: Box::new(sub(base)),
65            name: name.clone(),
66        },
67        Term::Old(inner) => sub(inner),
68        Term::Unary { op, operand } => Expr::unary((*op).into(), sub(operand)),
69        Term::Binary { op, lhs, rhs } => Expr::binary((*op).into(), sub(lhs), sub(rhs)),
70        Term::Ternary { cond, then, els } => Expr::Ternary {
71            cond: Box::new(sub(cond)),
72            then: Box::new(sub(then)),
73            els: Box::new(sub(els)),
74        },
75    }
76}
77
78/// `t` at a call: each parameter its argument.
79pub(super) fn term_args(t: &Term, args: &[(&str, Expr)]) -> Expr {
80    let sub = |t| term_args(t, args);
81    match t {
82        Term::Param(name) => args
83            .iter()
84            .find(|(p, _)| p == name)
85            .map_or_else(|| Expr::ident(name), |(_, a)| a.clone()),
86        Term::Old(inner) => sub(inner),
87        Term::Unary { op, operand } => Expr::unary((*op).into(), sub(operand)),
88        Term::Binary { op, lhs, rhs } => Expr::binary((*op).into(), sub(lhs), sub(rhs)),
89        Term::Ternary { cond, then, els } => Expr::Ternary {
90            cond: Box::new(sub(cond)),
91            then: Box::new(sub(then)),
92            els: Box::new(sub(els)),
93        },
94        t => term(t),
95    }
96}
97
98/// The `k`-th result an event's edge chooses: its function's parameter.
99pub(super) fn chosen(k: usize) -> String {
100    format!("fic_r{k}")
101}
102
103/// A result the edge firing an event chooses, for a call whose contract
104/// bounds its return to an interval: `name : int[lo, hi]`, constrained by
105/// the `ensures`.
106pub(super) struct Choice {
107    /// The edge's `select` binding, and the event function's parameter.
108    pub(super) name: String,
109    /// The interval.
110    pub(super) range: (i128, i128),
111    /// The `ensures` over the return value, `name` for it.
112    pub(super) guard: Vec<String>,
113}
114
115impl From<TermUnOp> for UnOp {
116    fn from(op: TermUnOp) -> Self {
117        match op {
118            TermUnOp::Not => UnOp::Not,
119            TermUnOp::Neg => UnOp::Neg,
120        }
121    }
122}
123
124impl From<TermBinOp> for BinOp {
125    fn from(op: TermBinOp) -> Self {
126        match op {
127            TermBinOp::Add => BinOp::Add,
128            TermBinOp::Sub => BinOp::Sub,
129            TermBinOp::Mul => BinOp::Mul,
130            TermBinOp::Div => BinOp::Div,
131            TermBinOp::Mod => BinOp::Mod,
132            TermBinOp::Eq => BinOp::Eq,
133            TermBinOp::Ne => BinOp::Ne,
134            TermBinOp::Lt => BinOp::Lt,
135            TermBinOp::Le => BinOp::Le,
136            TermBinOp::Gt => BinOp::Gt,
137            TermBinOp::Ge => BinOp::Ge,
138            TermBinOp::And => BinOp::And,
139            TermBinOp::Or => BinOp::Or,
140        }
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use std::path::{Path, PathBuf};
147
148    use crate::ast::RawAst;
149    use crate::ccfg::build as build_ccfg;
150    use crate::foreign::contract::ContractTable;
151    use crate::foreign::extract;
152    use crate::foreign::{ForeignLang, ForeignModules};
153    use crate::frontend::{data_layer, front_end};
154    use crate::parser::parse_foreign;
155    use crate::rast::env::ast_of;
156    use crate::xta_backend::model::transpile;
157    use crate::xta_backend::xta::ProcLocalDecl;
158    use crate::xta_backend::xta::Template;
159
160    /// A system with one written program, that of `pd`; the other
161    /// protection domains run nothing.
162    fn project(fis: &str, pd: &str, fi: &str) -> RawAst {
163        ast_of(fis, &[(pd, fi)])
164    }
165
166    /// A template's declarations as one block of text, for assertions to match
167    /// against.
168    fn decl_text(decls: &[ProcLocalDecl]) -> String {
169        decls
170            .iter()
171            .map(ToString::to_string)
172            .collect::<Vec<_>>()
173            .join("\n")
174    }
175
176    /// The demo's Pancake module, with its contracts.
177    const SOURCE: &str = "\
178export fun 1 say_ping() { @dbg(0, 0, 0, 1); return 0; }
179export fun 1 tally(1 r) {
180    /@ requires 0 <= r && r < ROUNDS @/
181    /@ ensures retval == r + 1 @/
182    return r + 1;
183}
184export fun 1 keep_playing(1 r) {
185    /@ requires 0 <= r @/
186    /@ ensures retval == (r < ROUNDS ? 1 : 0) @/
187    return r < ROUNDS;
188}
189";
190
191    /// The store holding `pingpong.pnk`, read by the Pancake reader.
192    fn pancake_module() -> ForeignModules {
193        let mut foreign = ForeignModules::new();
194        foreign.insert(
195            parse_foreign(
196                SOURCE,
197                Path::new("pingpong.pnk"),
198                PathBuf::from("pingpong.pnk"),
199                ForeignLang::Pancake,
200                &[],
201            )
202            .unwrap(),
203        );
204        foreign
205    }
206
207    const PING_FIS: &str = "
208        const ROUNDS: int = 5;
209        ProtectionDomain ping(100);
210        ProtectionDomain pong(101);
211        Chan ball = ping <-> pong;
212        System = ping ||| pong;
213    ";
214
215    /// The `Ping` template of a program importing `pingpong.pnk`, transpiled
216    /// with its contracts or with none.
217    fn ping_template(fi: &str, with_contracts: bool) -> Template {
218        let rawast = project(PING_FIS, "ping", fi);
219        let mut foreign = pancake_module();
220        foreign.bind(&rawast);
221        let (env, tenv) = data_layer(&rawast).expect("data layer");
222        let front = front_end(&rawast, &mut foreign, env, tenv).expect("front end");
223        let contracts = if with_contracts {
224            extract(&front, &foreign).unwrap()
225        } else {
226            ContractTable::default()
227        };
228        let ccfg = build_ccfg(&front).expect("builds the ccfg");
229        let nta = transpile(&front, &ccfg, &contracts);
230        nta.templates
231            .into_iter()
232            .find(|t| t.name == "Ping")
233            .unwrap()
234    }
235
236    #[test]
237    fn pancake_contracts_become_declared_functions() {
238        const FI: &str = r#"
239import "pingpong.pnk" as io;
240rounds: uint;
241evt say_ping: io.say_ping();
242evt tally:    rounds = io.tally(rounds);
243@bind(microkit.init)
244proc Init() { ball! -> Skip; }
245@bind(microkit.notified)
246proc Notified() {
247    ball? -> say_ping -> tally -> Skip;
248    [io.keep_playing(rounds) != 0] ball! -> Notified()
249 default Skip;
250}
251"#;
252        let ping = ping_template(FI, true);
253        let decls = decl_text(&ping.declarations);
254        // The declared function: requires as assert(s), ensures as the return.
255        assert!(
256            decls.contains("int ffi_tally(int r) {\n    assert(((0) <= (r)) && ((r) < (ROUNDS)));\n    return (r) + (1);\n}"),
257            "{decls}"
258        );
259        // The event calls it, real arguments, no textual substitution.
260        assert!(decls.contains("rounds = ffi_tally(rounds);"), "{decls}");
261        assert!(
262            decls.contains("void say_ping() {\n    ffi_say_ping();\n}"),
263            "{decls}"
264        );
265        let guards: Vec<&str> = ping
266            .transitions
267            .iter()
268            .filter_map(|t| t.guard.as_deref())
269            .collect();
270        // The predicate's condition guards the send, `!= 0` since the
271        // declared function returns a word; the Ccfg's negated default guard
272        // (`default Skip`) is its complement, in the Lean shape
273        // `!((b₁ && true) || false)`.
274        assert!(
275            guards.contains(&"(ffi_keep_playing(rounds)) != (0)"),
276            "{guards:?}"
277        );
278        assert!(
279            guards
280                .iter()
281                .any(|g| g.starts_with("!(") && g.contains("(ffi_keep_playing(rounds)) != (0)")),
282            "{guards:?}"
283        );
284
285        // Without contracts the same calls are opaque, as for C imports.
286        let ping = ping_template(FI, false);
287        assert!(decl_text(&ping.declarations).contains("rounds = /* tally() */ 0;"));
288    }
289
290    /// A contracted call whose value is discarded still runs, for its
291    /// `assert`s, and is not repeated as a comment.
292    #[test]
293    fn effect_only_contracted_call_is_still_a_call() {
294        let ping = ping_template(
295            r#"
296import "pingpong.pnk" as io;
297evt bump: io.tally(1);
298@bind(microkit.init)
299proc Init() { Skip; }
300@bind(microkit.notified)
301proc Notified() { ball? -> bump -> Skip; }
302"#,
303            true,
304        );
305        let decls = decl_text(&ping.declarations);
306        // The literal `1` is passed, not a substituted term.
307        assert!(
308            decls.contains("void bump() {\n    ffi_tally(1);\n}"),
309            "{decls}"
310        );
311        assert!(!decls.contains("// tally"), "{decls}");
312    }
313
314    /// The model has no output: an event keeps only its work.
315    #[test]
316    fn dbg_is_erased() {
317        let ping = ping_template(
318            r#"
319import "pingpong.pnk" as io;
320rounds: uint;
321evt tally: { dbg("ping ", rounds); rounds = io.tally(rounds); }
322@bind(microkit.init)
323proc Init() { Skip; }
324@bind(microkit.notified)
325proc Notified() { ball? -> tally -> Skip; }
326"#,
327            true,
328        );
329        let decls = decl_text(&ping.declarations);
330        assert!(
331            decls.contains("void tally() {\n    rounds = ffi_tally(rounds);\n}"),
332            "{decls}"
333        );
334    }
335}