Skip to main content

fic/foreign/
extract.rs

1//! Contract extraction: every called foreign function's contract, lifted
2//! into [`FnContract`] by its language's [`Lift`] and collected by function
3//! into one [`ContractTable`], each file lifted once. The verifiers (`frama-c
4//! -wp`, `pancake2viper`) prove the contracts against the code.
5//!
6//! Then the call sites are checked against what the model needs: a call
7//! whose value is used has a deterministic return value (a unique `ensures
8//! retval == E`), and a call in a guard is pure. Pancake contracts only.
9
10use std::collections::HashMap;
11
12use anyhow::{anyhow, bail, Result};
13
14use crate::base::{FfnId, ModuleId};
15use crate::tast::{Body, Tast, TyEnv};
16
17use super::calls::{call_sites, Usage};
18use super::contract::{ContractTable, FnContract};
19use super::{c, pnk, ForeignLang, ForeignModule, ForeignModules};
20
21/// One foreign language's contract lifting.
22pub trait Lift {
23    /// What a lifting error calls the contract's notation.
24    fn notation(&self) -> &'static str;
25
26    /// The contracts of `functions`, called functions of `module` by name,
27    /// in the neutral IR, by function. `consts` are the `.fis` constants a
28    /// clause may name.
29    ///
30    /// # Errors
31    ///
32    /// A clause outside fic's subset, or an identifier that is neither a
33    /// parameter nor a constant.
34    fn lift(
35        &self,
36        module: &ForeignModule,
37        functions: &[(FfnId, &str)],
38        consts: &[&str],
39    ) -> Result<HashMap<FfnId, FnContract>>;
40}
41
42/// The lifting for `lang`.
43fn lifting(lang: ForeignLang) -> &'static dyn Lift {
44    match lang {
45        ForeignLang::C => &c::C,
46        ForeignLang::Pancake => &pnk::Pancake,
47    }
48}
49
50/// The contract of every foreign function a program calls, each file
51/// lifted once, and the call-site checks.
52///
53/// # Errors
54///
55/// A contract outside fic's subset, or a call site that fails a check.
56pub fn extract(tast: &Tast, foreign: &ForeignModules) -> Result<ContractTable> {
57    let Tast { tenv, bodies } = tast;
58    let consts: Vec<&str> = tenv.consts.iter().map(|c| c.name.as_str()).collect();
59    let mut out = ContractTable::default();
60    let mut modules: Vec<ModuleId> = Vec::new();
61    for f in foreign.ffis.iter() {
62        if !modules.contains(&f.module) {
63            modules.push(f.module);
64        }
65    }
66    for id in modules {
67        let module = &foreign.modules[id];
68        let functions: Vec<(FfnId, &str)> = foreign
69            .ffis
70            .iter_enumerated()
71            .filter(|(_, at)| at.module == id)
72            .map(|(f, at)| (f, module.exports[at.index as usize].name.as_str()))
73            .collect();
74        // Reported in the first program importing the file.
75        let file = foreign
76            .links
77            .iter_enumerated()
78            .find(|(_, files)| files.iter().any(|f| f.module == id))
79            .map_or_else(String::new, |(pd, _)| tenv.pds[pd].fi.display().to_string());
80        let lift = lifting(module.lang());
81        let contracts = lift.lift(module, &functions, &consts).map_err(|e| {
82            anyhow!(
83                "{file}: {} contract error in \"{}\": {e}",
84                lift.notation(),
85                module.path.display()
86            )
87        })?;
88        for (f, contract) in contracts {
89            out.insert(f, contract);
90        }
91    }
92    for (pd, body) in bodies.iter_enumerated() {
93        let file = tenv.pds[pd].fi.display().to_string();
94        check_calls(tenv, body, &file, &out)?;
95    }
96    Ok(out)
97}
98
99/// A deterministic retval where a call's value is used, purity where the
100/// call guards; Pancake contracts only.
101fn check_calls(tenv: &TyEnv, body: &Body, file: &str, contracts: &ContractTable) -> Result<()> {
102    for site in call_sites(body) {
103        let function = site.callee;
104        let Some(contract) = contracts.contract(function) else {
105            continue;
106        };
107        if contract.lang != ForeignLang::Pancake {
108            continue;
109        }
110        let name = &tenv.ffis[function].name;
111        match site.usage {
112            Usage::Statement => {}
113            Usage::Value | Usage::Guard => {
114                if contract.retval.is_none() {
115                    bail!(
116                        "{file}: the value of `{name}(…)` is used, but `{name}` has no \
117                         deterministic `ensures retval == …` clause; fic cannot extract its \
118                         return value for the UPPAAL model (non-deterministic contracts are future work)"
119                    );
120                }
121            }
122        }
123        if site.usage == Usage::Guard {
124            if let Some(why) = &contract.impurity {
125                bail!(
126                    "{file}: `{name}` is used in a guard but {why}; guard functions must be \
127                     side-effect free (the generated C may evaluate a guard more than once)"
128                );
129            }
130        }
131    }
132    Ok(())
133}
134
135#[cfg(test)]
136mod tests {
137    use std::path::{Path, PathBuf};
138
139    use super::*;
140    use crate::foreign::contract::Term;
141    use crate::foreign::{ForeignLang, ForeignModules};
142    use crate::frontend::data_layer;
143    use crate::parser::parse_foreign;
144    use crate::rast::build;
145    use crate::rast::env::ast_of;
146    use crate::tast::build as build_tast;
147
148    const SOURCE: &str = "\
149export fun 1 say_ping() { @dbg(0, 0, 0, 1); return 0; }
150export fun 1 tally(1 r) {
151    /@ requires 0 <= r && r < ROUNDS @/
152    /@ ensures retval == r + 1 @/
153    return r + 1;
154}
155export fun 1 keep_playing(1 r) {
156    /@ requires 0 <= r @/
157    /@ ensures retval == (r < ROUNDS ? 1 : 0) @/
158    return r < ROUNDS;
159}
160export fun 1 poll() {
161    /@ ensures 0 <= retval && retval <= 1 @/
162    return 0;
163}
164export fun 1 logged(1 r) {
165    /@ ensures retval == r @/
166    @dbg(0, 0, 0, r);
167    return r;
168}
169fun 1 hidden(1 r) { return r; }
170";
171
172    /// A project with one program and one Pancake module, `pingpong.pnk`:
173    /// its contracts, and the resolved AST naming its functions.
174    fn table_for(fi: &str, pnk: &str) -> Result<(ContractTable, TyEnv)> {
175        let rawast = ast_of(
176            "const ROUNDS: int = 5;\nProtectionDomain ping(100);\nProtectionDomain pong(101);\n\
177             Chan ball = ping <-> pong;\nChan c = pong --> ping;",
178            &[("ping", fi)],
179        );
180        let mut foreign = ForeignModules::new();
181        foreign.insert(
182            parse_foreign(
183                pnk,
184                Path::new("pingpong.pnk"),
185                PathBuf::from("pingpong.pnk"),
186                ForeignLang::Pancake,
187                &[],
188            )
189            .unwrap(),
190        );
191        foreign.bind(&rawast);
192        let (env, tenv) = data_layer(&rawast).expect("data layer");
193        let (rast, _) = build(&rawast, env, &mut foreign).expect("builds");
194        let (tast, _) = build_tast(rast, tenv).expect("types");
195        Ok((extract(&tast, &foreign)?, tast.tenv))
196    }
197
198    fn load(fi: &str) -> Result<(ContractTable, TyEnv)> {
199        table_for(fi, SOURCE)
200    }
201
202    /// `pingpong.pnk`'s function `name`.
203    fn named(tenv: &TyEnv, name: &str) -> FfnId {
204        let (id, _) = tenv
205            .ffis
206            .iter_enumerated()
207            .find(|(_, f)| f.name == name)
208            .expect("called");
209        id
210    }
211
212    #[test]
213    fn no_pancake_imports_means_an_empty_table() {
214        let (table, _) = load("rounds: uint;").unwrap();
215        assert!(table.is_empty());
216    }
217
218    #[test]
219    fn contracts_come_from_the_module_and_constants_stay_symbolic() {
220        let (table, tenv) = load(
221            r#"
222import "pingpong.pnk" as io;
223rounds: uint;
224evt say_ping: io.say_ping();
225evt tally:    rounds = io.tally(rounds);
226@bind(microkit.init)
227proc Init() { ball! -> Skip; }
228@bind(microkit.notified)
229proc Notified() {
230    ball? -> say_ping -> tally -> Skip;
231    [io.keep_playing(rounds) != 0] ball! -> Notified()
232 default Skip;
233}
234"#,
235        )
236        .unwrap();
237        assert_eq!(table.function_count(), 3, "the called functions only");
238
239        let tally = table.contract(named(&tenv, "tally")).unwrap();
240        assert_eq!(
241            tally.retval,
242            Some(Term::binary("+", Term::Param("r".into()), Term::Int(1)))
243        );
244        let keep = table.contract(named(&tenv, "keep_playing")).unwrap();
245        assert_eq!(
246            keep.retval,
247            Some(Term::Ternary {
248                cond: Box::new(Term::binary(
249                    "<",
250                    Term::Param("r".into()),
251                    Term::Param("ROUNDS".into())
252                )),
253                then: Box::new(Term::Int(1)),
254                els: Box::new(Term::Int(0)),
255            })
256        );
257        assert!(table
258            .contract(named(&tenv, "say_ping"))
259            .unwrap()
260            .retval
261            .is_none());
262    }
263
264    #[test]
265    fn value_uses_need_a_retval_and_guards_need_purity() {
266        // poll's range contract has no deterministic retval.
267        let err = load(r#"import "pingpong.pnk" as io; x: uint; evt e: x = io.poll();"#)
268            .unwrap_err()
269            .to_string();
270        assert!(
271            err.contains("no deterministic `ensures retval == …`"),
272            "{err}"
273        );
274        // …but calling it for effect is fine.
275        load(r#"import "pingpong.pnk" as io; evt e: io.poll();"#).unwrap();
276
277        // say_ping has no retval: rejected in a guard.
278        let err = load(
279            r#"import "pingpong.pnk" as io;
280@bind(microkit.init) proc Init() { Skip; }
281@bind(microkit.notified) proc N() { [io.say_ping() != 0] ball! -> Skip default Skip; }"#,
282        )
283        .unwrap_err()
284        .to_string();
285        assert!(err.contains("no deterministic"), "{err}");
286
287        // logged has a retval but calls the FFI: rejected in a guard, fine as a value.
288        let err = load(
289            r#"import "pingpong.pnk" as io; r: uint;
290@bind(microkit.init) proc Init() { Skip; }
291@bind(microkit.notified) proc N() { [io.logged(r) != 0] ball! -> Skip default Skip; }"#,
292        )
293        .unwrap_err()
294        .to_string();
295        assert!(
296            err.contains("used in a guard but calls the foreign function `@dbg`"),
297            "{err}"
298        );
299        load(r#"import "pingpong.pnk" as io; r: uint; evt e: r = io.logged(r);"#).unwrap();
300
301        // A pure predicate in a guard is accepted.
302        load(
303            r#"import "pingpong.pnk" as io; r: uint;
304@bind(microkit.init) proc Init() { Skip; }
305@bind(microkit.notified) proc N() { [io.keep_playing(r) != 0] ball! -> Skip default Skip; }"#,
306        )
307        .unwrap();
308    }
309
310    #[test]
311    fn a_clause_outside_the_subset_names_the_file() {
312        let err = table_for(
313            r#"import "pingpong.pnk" as io; evt e: io.f();"#,
314            "export fun 1 f() {\n    /@ ensures forall i: Int :: i >= 0 @/\n    return 0;\n}\n",
315        )
316        .unwrap_err()
317        .to_string();
318        assert!(
319            err.contains("ping.fi: Pancake contract error in \"pingpong.pnk\""),
320            "{err}"
321        );
322        assert!(err.contains("quantifier `forall`"), "{err}");
323    }
324
325    #[test]
326    fn a_clause_may_name_a_system_constant_but_nothing_else() {
327        let err = table_for(
328            r#"import "pingpong.pnk" as io; evt e: io.f();"#,
329            "export fun 1 f() {\n    /@ ensures retval == LIMIT @/\n    return 0;\n}\n",
330        )
331        .unwrap_err()
332        .to_string();
333        assert!(
334            err.contains("`LIMIT`, which is neither a parameter nor a `.fis` constant"),
335            "{err}"
336        );
337        table_for(
338            r#"import "pingpong.pnk" as io; evt e: io.f();"#,
339            "export fun 1 f() {\n    /@ ensures retval == ROUNDS @/\n    return 0;\n}\n",
340        )
341        .unwrap();
342    }
343}