Skip to main content

fic/foreign/pnk/
annotation.rs

1//! Pancake contracts: pancake2viper's annotation IR, lifted to the contract IR.
2//!
3//! The `pancake2viper` crate parses each `/@ … @/` annotation — the same
4//! parser the verifier runs, at the revision `Cargo.toml` and
5//! `nix/pancake2viper.nix` share. This module is `foreign::c::acsl`'s
6//! counterpart for Viper: the `ir::Expr` of each `requires`/`ensures`
7//! becomes a [`Term`] of [`crate::foreign::contract`].
8//!
9//! The subset matches C's: integer and boolean literals, parameters,
10//! `retval`, `old(…)`, `+ - * / %`, the signed comparisons (`<+` and friends
11//! are unsigned), `==`/`!=`, `! && ||` and `c ? a : b`. Permissions,
12//! quantifiers, the heap, implication, calls, bit operators and shifts are
13//! rejected by name. Any other annotation (`trusted`, an invariant) is the
14//! verifier's and is not read.
15
16use std::collections::HashMap;
17
18use anyhow::{anyhow, bail, Result};
19use pancake2viper::annotation::parse_annot;
20use pancake2viper::ir::{AnnotationType, BinOpType, Expr, Quantifier, UnOpType};
21
22use super::Pancake;
23use crate::base::FfnId;
24use crate::foreign::contract::{FnContract, Term, UnaryOp};
25use crate::foreign::{ForeignContract, ForeignFn, ForeignLang, ForeignModule, Lift};
26
27impl Lift for Pancake {
28    fn notation(&self) -> &'static str {
29        "Pancake"
30    }
31
32    fn lift(
33        &self,
34        module: &ForeignModule,
35        functions: &[(FfnId, &str)],
36        consts: &[&str],
37    ) -> Result<HashMap<FfnId, FnContract>> {
38        let mut out = HashMap::new();
39        for &(id, name) in functions {
40            let f = module.export(name).expect("a called function is exported");
41            if let Some(found) = module.contracts.get(name) {
42                out.insert(id, from_foreign(f, found, consts)?);
43            }
44        }
45        Ok(out)
46    }
47}
48
49/// The contract of a Pancake function from its `requires`/`ensures`
50/// annotations; any other annotation is the verifier's and is not read.
51/// `consts` are the `.fis` constants a clause may name besides the
52/// parameters.
53///
54/// # Errors
55///
56/// A clause pancake2viper cannot parse, or outside the subset; an identifier
57/// that is neither a parameter nor a constant (Pancake globals and the heap
58/// are not modelled); or a contract [`FnContract::from_clauses`] rejects.
59pub fn from_foreign(
60    func: &ForeignFn,
61    found: &ForeignContract,
62    consts: &[&str],
63) -> Result<FnContract> {
64    let annotations = &found.contracts;
65    let params: Vec<String> = func
66        .params
67        .iter()
68        .map(|p| p.name.clone().unwrap_or_default())
69        .collect();
70    let mut requires = Vec::new();
71    let mut ensures = Vec::new();
72
73    for annotation in annotations {
74        let text = annotation.text.trim();
75        let parsed = parse(text).map_err(|e| anyhow!("function `{}`: {e}", func.name))?;
76        let clauses = match parsed.typ {
77            AnnotationType::Precondition => &mut requires,
78            AnnotationType::Postcondition => &mut ensures,
79            _ => continue,
80        };
81        let t = lift(&parsed.expr)
82            .map_err(|e| anyhow!("function `{}`: contract clause `{text}` {e}", func.name))?;
83        check_identifiers(&func.name, text, &t, &params, consts)?;
84        clauses.push(t);
85    }
86
87    FnContract::from_clauses(
88        ForeignLang::Pancake,
89        func.name.clone(),
90        params,
91        requires,
92        ensures,
93        found.impurity.clone(),
94    )
95}
96
97/// One annotation, as pancake2viper parses it. `true`: the whole text must
98/// parse (the other rule stops at the first unreadable token).
99fn parse(text: &str) -> Result<pancake2viper::ir::Annotation> {
100    parse_annot(text, true).map_err(|e| anyhow!("cannot parse contract clause `{text}`:\n{e}"))
101}
102
103/// A pancake2viper expression as a [`Term`].
104fn lift(e: &Expr) -> Result<Term> {
105    Ok(match e {
106        Expr::Const(n) => Term::Int(i128::from(*n)),
107        Expr::BoolLit(b) => Term::Bool(*b),
108        Expr::Var(v) if v.name == "retval" => Term::RetVal,
109        Expr::Var(v) => Term::Param(v.name.clone()),
110        Expr::Old(old) => Term::Old(Box::new(lift(&old.expr)?)),
111        Expr::UnOp(u) => Term::Unary {
112            op: match u.optype {
113                UnOpType::Neg => UnaryOp::Not,
114                UnOpType::Minus => UnaryOp::Neg,
115            },
116            operand: Box::new(lift(&u.right)?),
117        },
118        Expr::BinOp(b) => {
119            let op = match b.optype {
120                BinOpType::Add => "+",
121                BinOpType::Sub => "-",
122                BinOpType::Mul => "*",
123                BinOpType::Div => "/",
124                BinOpType::Modulo => "%",
125                BinOpType::PancakeEqual => "==",
126                BinOpType::PancakeNotEqual => "!=",
127                BinOpType::SignedLt => "<",
128                BinOpType::SignedLte => "<=",
129                BinOpType::SignedGt => ">",
130                BinOpType::SignedGte => ">=",
131                BinOpType::BoolAnd => "&&",
132                BinOpType::BoolOr => "||",
133                BinOpType::Lt => return Err(outside("the unsigned comparison `<+`")),
134                BinOpType::Lte => return Err(outside("the unsigned comparison `<=+`")),
135                BinOpType::Gt => return Err(outside("the unsigned comparison `>+`")),
136                BinOpType::Gte => return Err(outside("the unsigned comparison `>=+`")),
137                BinOpType::Imp => return Err(outside("implication `==>`")),
138                BinOpType::Iff => return Err(outside("equivalence `<==>`")),
139                BinOpType::ViperEqual => return Err(outside("Viper equality `===`")),
140                BinOpType::ViperNotEqual => return Err(outside("Viper inequality `!==`")),
141                BinOpType::BitAnd => return Err(outside("the bit operator `&`")),
142                BinOpType::BitOr => return Err(outside("the bit operator `|`")),
143                BinOpType::BitXor => return Err(outside("the bit operator `^`")),
144            };
145            Term::binary(op, lift(&b.left)?, lift(&b.right)?)
146        }
147        Expr::Ternary(t) => Term::Ternary {
148            cond: Box::new(lift(&t.cond)?),
149            then: Box::new(lift(&t.left)?),
150            els: Box::new(lift(&t.right)?),
151        },
152        Expr::Quantified(q) => {
153            return Err(outside(match q.quantifier {
154                Quantifier::Forall => "the quantifier `forall`",
155                Quantifier::Exists => "the quantifier `exists`",
156            }))
157        }
158        Expr::AccessPredicate(_) | Expr::AccessSlice(_) | Expr::UnfoldingIn(_) => {
159            return Err(outside(
160                "`acc` (permissions and predicates are not modelled)",
161            ))
162        }
163        Expr::Load(_) | Expr::LoadBits(_) | Expr::BaseAddr | Expr::BytesInWord => {
164            return Err(outside("the heap"))
165        }
166        Expr::FunctionCall(c) => return Err(outside(&format!("a call to `{}(…)`", c.fname))),
167        Expr::MethodCall(c) => return Err(outside(&format!("a call to `{}(…)`", c.fname))),
168        Expr::Shift(_) => return Err(outside("a shift")),
169        other => return Err(outside(&format!("`{other}`"))),
170    })
171}
172
173fn outside(what: &str) -> anyhow::Error {
174    anyhow!(
175        "uses {what}, which is outside fic's contract subset \
176         (arithmetic, comparisons, `! && ||`, `? :`, `old(…)`, `retval`, parameters)"
177    )
178}
179
180fn check_identifiers(
181    fn_name: &str,
182    text: &str,
183    t: &Term,
184    params: &[String],
185    consts: &[&str],
186) -> Result<()> {
187    for id in t.identifiers() {
188        if !params.iter().any(|p| p == id) && !consts.contains(&id) {
189            bail!(
190                "function `{fn_name}`: clause `{}` refers to `{id}`, which is neither a parameter \
191                 nor a `.fis` constant (Pancake globals and the heap are outside fic's contract subset)",
192                text.trim()
193            );
194        }
195    }
196    Ok(())
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202    use crate::foreign::{Annotation, ForeignParam, ForeignType};
203
204    /// A Pancake export with its annotations, lifted.
205    fn build_with(name: &str, params: &[&str], annotations: &[&str]) -> Result<FnContract> {
206        let func = ForeignFn {
207            name: name.to_string(),
208            params: params
209                .iter()
210                .map(|p| ForeignParam {
211                    name: Some((*p).to_string()),
212                    ty: ForeignType::Word,
213                })
214                .collect(),
215            ret: ForeignType::Word,
216            variadic: false,
217            span: 0..0,
218        };
219        let found = ForeignContract {
220            contracts: annotations
221                .iter()
222                .map(|t| Annotation {
223                    text: (*t).to_string(),
224                    span: 0..0,
225                })
226                .collect(),
227            impurity: None,
228        };
229        from_foreign(&func, &found, &[])
230    }
231
232    /// A Pancake export with its `requires`/`ensures`, lifted.
233    fn build(
234        name: &str,
235        params: &[&str],
236        requires: &[&str],
237        ensures: &[&str],
238    ) -> Result<FnContract> {
239        let annotations: Vec<String> = requires
240            .iter()
241            .map(|t| format!("requires {t}"))
242            .chain(ensures.iter().map(|t| format!("ensures {t}")))
243            .collect();
244        let refs: Vec<&str> = annotations.iter().map(String::as_str).collect();
245        build_with(name, params, &refs)
246    }
247
248    /// One clause's expression, lifted.
249    fn lower_text(text: &str) -> Result<Term> {
250        lift(&parse(text)?.expr)
251    }
252
253    /// A term as a fully parenthesised string, so the precedence
254    /// assertions stay readable.
255    fn shape(t: &Term) -> String {
256        match t {
257            Term::Int(n) => n.to_string(),
258            Term::Bool(b) => b.to_string(),
259            Term::Param(name) => name.clone(),
260            Term::RetVal => "retval".to_string(),
261            Term::Field { base, name } => format!("{}.{name}", shape(base)),
262            Term::Old(inner) => shape(inner),
263            Term::Unary { op, operand } => {
264                let sym = match op {
265                    UnaryOp::Not => "!",
266                    UnaryOp::Neg => "-",
267                };
268                format!("{sym}({})", shape(operand))
269            }
270            Term::Binary { op, lhs, rhs } => {
271                format!("({}) {} ({})", shape(lhs), op.symbol(), shape(rhs))
272            }
273            Term::Ternary { cond, then, els } => {
274                format!("({}) ? ({}) : ({})", shape(cond), shape(then), shape(els))
275            }
276        }
277    }
278
279    #[test]
280    fn precedence_is_pancake2vipers() {
281        let t = lower_text("requires 1 + 2 * 3").unwrap();
282        assert_eq!(shape(&t), "(1) + ((2) * (3))");
283        let t = lower_text("requires 0 <= r && r < 5").unwrap();
284        assert_eq!(shape(&t), "((0) <= (r)) && ((r) < (5))");
285        let t = lower_text("requires a - b - c").unwrap();
286        assert_eq!(shape(&t), "((a) - (b)) - (c)");
287        let t = lower_text("requires !(x == 1) || y >= 2").unwrap();
288        assert_eq!(shape(&t), "(!((x) == (1))) || ((y) >= (2))");
289        let t = lower_text("requires -x + 0x10").unwrap();
290        assert_eq!(shape(&t), "(-(x)) + (16)");
291        let t = lower_text(" ensures old(r) + 1 == retval ").unwrap();
292        assert_eq!(shape(&t), "((r) + (1)) == (retval)");
293        let t = lower_text("ensures c ? true : false").unwrap();
294        assert_eq!(shape(&t), "(c) ? (true) : (false)");
295    }
296
297    #[test]
298    fn a_clause_may_span_lines() {
299        let t = lower_text("requires 0 <= r &&\n     r < 10").unwrap();
300        assert_eq!(shape(&t), "((0) <= (r)) && ((r) < (10))");
301    }
302
303    #[test]
304    fn constructs_outside_the_subset_are_named() {
305        let err = |text: &str| lower_text(text).unwrap_err().to_string();
306        assert!(err("requires forall i: Int :: i >= 0").contains("quantifier `forall`"));
307        assert!(err("requires acc(heap[0])").contains("`acc`"));
308        assert!(err("requires x ==> y").contains("implication"));
309        assert!(err("requires f(x) == 1").contains("call to `f(…)`"));
310        assert!(err("requires x & 1").contains("bit operator `&`"));
311        assert!(err("requires x <+ y").contains("unsigned comparison `<+`"));
312        assert!(err("requires x === y").contains("Viper equality"));
313        // Syntax errors are pancake2viper's; `1 +` is not `1`.
314        assert!(err("requires 1 +").contains("cannot parse"));
315        assert!(err("requires (1").contains("cannot parse"));
316        assert!(
317            err("assumes x").contains("cannot parse"),
318            "not an annotation keyword"
319        );
320    }
321
322    #[test]
323    fn retval_is_the_unique_ensures_equation() {
324        let c = build("tally", &["r"], &["0 <= r && r < 5"], &["retval == r + 1"]).unwrap();
325        assert_eq!(shape(c.retval.as_ref().unwrap()), "(r) + (1)");
326        assert_eq!(c.requires.len(), 1);
327
328        // Flipped equation and old() are fine.
329        let c = build("f", &["r"], &[], &["old(r) * 2 == retval"]).unwrap();
330        assert_eq!(shape(&c.retval.unwrap()), "(r) * (2)");
331
332        // A range alone gives no deterministic retval.
333        let c = build("poll", &[], &[], &["0 <= retval && retval <= 1"]).unwrap();
334        assert!(c.retval.is_none());
335
336        // Two equations are ambiguous.
337        let err = build("f", &["r"], &[], &["retval == r", "retval == r + 0"])
338            .unwrap_err()
339            .to_string();
340        assert!(err.contains("two `ensures retval == …`"), "{err}");
341    }
342
343    #[test]
344    fn identifiers_must_be_parameters_and_retval_only_in_ensures() {
345        let err = build("f", &["r"], &[], &["retval == r + g"])
346            .unwrap_err()
347            .to_string();
348        assert!(err.contains("`g`, which is neither a parameter"), "{err}");
349        let err = build("f", &["r"], &["retval > 0"], &[])
350            .unwrap_err()
351            .to_string();
352        assert!(err.contains("only exists after the call"), "{err}");
353    }
354
355    #[test]
356    fn other_annotations_are_the_verifiers() {
357        let c = build_with("f", &["r"], &["trusted", "ensures retval == r"]).unwrap();
358        assert_eq!(shape(c.retval.as_ref().unwrap()), "r");
359        assert!(c.requires.is_empty(), "{:?}", c.requires);
360    }
361}