Skip to main content

fic/xta_backend/
func.rs

1//! A PD's own code as XTA: its event bodies as template-local functions,
2//! and the expressions of its guards and updates. A call into a contracted
3//! import calls its declared function (`contract`); any other is opaque.
4
5use std::cell::RefCell;
6use std::iter::once;
7
8use crate::ast::{BinaryOp, Lit, UnaryOp};
9use crate::base::{BodyVarId, EventId, FfnId, IdVec, ProcId};
10use crate::foreign::contract::ContractTable;
11use crate::tast::{self, BodyVar, EventBody, ProgramView, Ty};
12
13use super::contract::{chosen, ffi_name, term_args, term_with, Choice};
14use super::types::var_decl;
15use super::xta::{
16    AssignOp, BinOp, BlockLocalDecl, Expr, FnDecl, Param, Stmt, Type, TypeExpr, UnOp,
17};
18
19/// Expression context. UPPAAL wants booleans in guards and as operands of
20/// `&&`/`||`/`!`, and integers elsewhere; a call in boolean position
21/// becomes `(call) != 0` (see [`Func::call`]), the declared function
22/// returning `int`.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24enum Cx {
25    Bool,
26    Int,
27}
28
29/// Renders expressions and event bodies, calling the declared function
30/// (see `contract::pancake_function`) for every call into a contracted import.
31pub(super) struct Func<'a> {
32    pub(super) contracts: &'a ContractTable,
33    /// While an event's function is printed: the ranged calls met so far,
34    /// each a parameter the firing edge chooses.
35    chosen: RefCell<Option<Vec<FfnId>>>,
36}
37
38impl<'a> Func<'a> {
39    pub(super) fn new(contracts: &'a ContractTable) -> Self {
40        Self {
41            contracts,
42            chosen: RefCell::new(None),
43        }
44    }
45
46    /// One `evt` declaration as a template-local UPPAAL function; a ranged
47    /// call in it is a parameter, `fic_r<k>`, which the firing edge chooses
48    /// ([`Self::choices`]).
49    pub(super) fn event_function(&self, names: ProgramView<'_>, id: EventId) -> FnDecl {
50        self.event(names, id).0
51    }
52
53    /// The results the edge firing event `id` chooses, in parameter order.
54    pub(super) fn choices(&self, names: ProgramView<'_>, id: EventId) -> Vec<Choice> {
55        self.event(names, id)
56            .1
57            .iter()
58            .enumerate()
59            .map(|(k, callee)| {
60                let contract = self.contracts.contract(*callee).expect("ranged");
61                let name = chosen(k);
62                Choice {
63                    range: contract.result_range().expect("ranged"),
64                    guard: contract
65                        .ensures
66                        .iter()
67                        .filter(|c| c.mentions_retval())
68                        .map(|c| term_with(c, &name).to_string())
69                        .collect(),
70                    name,
71                }
72            })
73            .collect()
74    }
75
76    /// The event's function, and the ranged calls it chooses.
77    fn event(&self, names: ProgramView<'_>, id: EventId) -> (FnDecl, Vec<FfnId>) {
78        let evt = &names.body().events[id];
79        *self.chosen.borrow_mut() = Some(Vec::new());
80        let body = evt
81            .body
82            .iter()
83            .filter_map(|s| self.stmt(names, evt, s))
84            .collect();
85        let calls = self.chosen.borrow_mut().take().unwrap_or_default();
86        // The carriers, in order, then one `int` per ranged call it chooses.
87        let carriers = evt.body_vars.iter().take(evt.sig.carriers.len()).map(|v| {
88            let decl = var_decl(names, &v.ty, &v.name, false);
89            Param {
90                ty: decl.ty,
91                by_ref: false,
92                decl: decl.ids[0].decl.clone(),
93            }
94        });
95        let params = carriers
96            .chain((0..calls.len()).map(|k| Param::value(TypeExpr::plain(Type::Int), chosen(k))))
97            .collect();
98        let function = FnDecl {
99            ret: TypeExpr::plain(Type::Void),
100            name: evt.sig.name.clone(),
101            params,
102            body_vars: Vec::new(),
103            body,
104        };
105        (function, calls)
106    }
107
108    /// One Fiducia statement as a UPPAAL statement: a contracted call stays
109    /// a call, for its `assert`s; an opaque one is a comment; a `dbg` is
110    /// none.
111    fn stmt(&self, names: ProgramView<'_>, evt: &EventBody, s: &tast::Stmt) -> Option<Stmt> {
112        let body_vars = &evt.body_vars;
113        Some(match s {
114            tast::Stmt::Decl(id) => {
115                let local = &body_vars[*id];
116                Stmt::Decl(BlockLocalDecl::Var(var_decl(
117                    names,
118                    &local.ty,
119                    &local.name,
120                    false,
121                )))
122            }
123            // An opaque struct or array has no value to give: the target is
124            // left as it was, but for the fields its contract fixes.
125            tast::Stmt::Assign { target, rhs, .. } if self.opaque_aggregate(rhs) => {
126                let tast::ExprKind::Call(call) = &rhs.kind else {
127                    unreachable!("opaque_aggregate holds of a call")
128                };
129                let target = names.var_in(body_vars, *target);
130                let note = Stmt::Comment(format!(
131                    "{target} = {}(): opaque, left unchanged but for its contract's fields",
132                    names.tenv.ffis[call.callee].name
133                ));
134                let Some(contract) = self.contracts.contract(call.callee) else {
135                    return Some(note);
136                };
137                if contract.fields.is_empty() {
138                    return Some(note);
139                }
140                let args: Vec<(&str, Expr)> = contract
141                    .params
142                    .iter()
143                    .map(String::as_str)
144                    .zip(
145                        call.args
146                            .iter()
147                            .map(|a| self.expr(names, body_vars, a, Cx::Int)),
148                    )
149                    .collect();
150                let body = once(note)
151                    .chain(contract.fields.iter().map(|(field, value)| {
152                        Stmt::Expr(Expr::assign(
153                            Expr::Field {
154                                base: Box::new(Expr::ident(target)),
155                                name: field.clone(),
156                            },
157                            AssignOp::Assign,
158                            term_args(value, &args),
159                        ))
160                    }))
161                    .collect();
162                Stmt::Block {
163                    decls: Vec::new(),
164                    body,
165                }
166            }
167            tast::Stmt::Assign { target, rhs, .. } => Stmt::Expr(Expr::assign(
168                Expr::ident(names.var_in(body_vars, *target)),
169                AssignOp::Assign,
170                self.expr(names, body_vars, rhs, Cx::Int),
171            )),
172            tast::Stmt::Call(call) => {
173                let name = &names.tenv.ffis[call.callee].name;
174                match self.contracts.contract(call.callee) {
175                    Some(_) => Stmt::Expr(Expr::Call {
176                        name: ffi_name(name),
177                        args: call
178                            .args
179                            .iter()
180                            .map(|a| self.expr(names, body_vars, a, Cx::Int))
181                            .collect(),
182                    }),
183                    None => Stmt::Comment(format!("{name}();")),
184                }
185            }
186            tast::Stmt::Dbg { .. } => return None,
187        })
188    }
189
190    /// `e` is a call the model does not know, of a struct or array type.
191    fn opaque_aggregate(&self, e: &tast::Expr) -> bool {
192        let tast::ExprKind::Call(call) = &e.kind else {
193            return false;
194        };
195        let known = self
196            .contracts
197            .contract(call.callee)
198            .is_some_and(|c| c.retval.is_some());
199        !known && matches!(e.ty, Ty::Struct(_) | Ty::Array { .. })
200    }
201
202    /// A value written in `process`, as label text.
203    pub(super) fn value(&self, names: ProgramView<'_>, process: ProcId, e: &tast::Expr) -> String {
204        let body_vars = &names.body().processes[process].body_vars;
205        self.expr(names, body_vars, e, Cx::Int).to_string()
206    }
207
208    /// A guard written in `process`, as label text.
209    pub(super) fn guard(&self, names: ProgramView<'_>, process: ProcId, e: &tast::Expr) -> String {
210        let body_vars = &names.body().processes[process].body_vars;
211        self.expr(names, body_vars, e, Cx::Bool).to_string()
212    }
213
214    /// An expression in a body whose variables are `body_vars`.
215    fn expr(
216        &self,
217        names: ProgramView<'_>,
218        body_vars: &IdVec<BodyVarId, BodyVar>,
219        e: &tast::Expr,
220        cx: Cx,
221    ) -> Expr {
222        let sub = |e: &tast::Expr, cx| self.expr(names, body_vars, e, cx);
223        match &e.kind {
224            tast::ExprKind::Lit(Lit::Bool(b)) => Expr::Bool(*b),
225            tast::ExprKind::Lit(Lit::Int(n)) => Expr::Int(i128::from(*n)),
226            // UPPAAL reads decimal only.
227            tast::ExprKind::Lit(Lit::Hex(n)) => Expr::Int(i128::from(*n)),
228            tast::ExprKind::Var(v) => Expr::ident(names.var_in(body_vars, *v)),
229            // The address the layout chose; UPPAAL has no mapping to name.
230            tast::ExprKind::Vaddr(m) => Expr::Int(i128::from(names.tenv.mappings[*m].vaddr)),
231            // Patched in at load time; opaque to the model, like an
232            // uncontracted call.
233            tast::ExprKind::Paddr(m) => {
234                Expr::Verbatim(format!("/* {}.paddr */ 0", names.tenv.mappings[*m].name))
235            }
236            tast::ExprKind::Call(call) => self.call(
237                names,
238                call.callee,
239                || call.args.iter().map(|a| sub(a, Cx::Int)).collect(),
240                cx,
241            ),
242            tast::ExprKind::Sizeof { .. } => Expr::Verbatim("/* sizeof */ 0".to_string()),
243            // The model's integers are one unbounded int: a cast is its operand.
244            tast::ExprKind::Cast { expr, .. } => sub(expr, Cx::Int),
245            tast::ExprKind::Unary { op, operand } => match op {
246                UnaryOp::Neg => Expr::unary(UnOp::Neg, sub(operand, Cx::Int)),
247                UnaryOp::Not => Expr::unary(UnOp::Not, sub(operand, Cx::Bool)),
248                // UPPAAL has no `~`: the complement as `-x - 1`.
249                UnaryOp::BitNot => Expr::binary(
250                    BinOp::Sub,
251                    Expr::unary(UnOp::Neg, sub(operand, Cx::Int)),
252                    Expr::Int(1),
253                ),
254            },
255            tast::ExprKind::Field { base, field, .. } => Expr::Field {
256                base: Box::new(sub(base, Cx::Int)),
257                name: names.field(&base.ty, *field).name.clone(),
258            },
259            tast::ExprKind::Binary { op, lhs, rhs } => {
260                let cx = operand_cx(*op);
261                Expr::binary((*op).into(), sub(lhs, cx), sub(rhs, cx))
262            }
263        }
264    }
265
266    /// A call in expression position: a contracted function's
267    /// declared function (see `contract::pancake_function`), else opaque (`0`).
268    fn call(
269        &self,
270        names: ProgramView<'_>,
271        callee: FfnId,
272        args: impl FnOnce() -> Vec<Expr>,
273        cx: Cx,
274    ) -> Expr {
275        let name = &names.tenv.ffis[callee].name;
276        let Some(contract) = self.contracts.contract(callee) else {
277            return Expr::Verbatim(format!("/* {name}() */ 0"));
278        };
279        if contract.result_range().is_some() {
280            if let Some(calls) = self.chosen.borrow_mut().as_mut() {
281                calls.push(callee);
282                return Expr::ident(chosen(calls.len() - 1));
283            }
284        }
285        if contract.retval.is_none() {
286            return Expr::Verbatim(format!("/* {name}(): no deterministic contract */ 0"));
287        }
288        let call = Expr::Call {
289            name: ffi_name(name),
290            args: args(),
291        };
292        match cx {
293            Cx::Bool => Expr::binary(BinOp::Ne, call, Expr::Int(0)),
294            Cx::Int => call,
295        }
296    }
297}
298
299/// The context the operands of `op` are read in: boolean for the logical
300/// operators, integer for every other.
301fn operand_cx(op: BinaryOp) -> Cx {
302    match op {
303        BinaryOp::And | BinaryOp::Or => Cx::Bool,
304        _ => Cx::Int,
305    }
306}
307
308impl From<BinaryOp> for BinOp {
309    fn from(op: BinaryOp) -> Self {
310        match op {
311            BinaryOp::Add => BinOp::Add,
312            BinaryOp::Sub => BinOp::Sub,
313            BinaryOp::Mul => BinOp::Mul,
314            BinaryOp::Div => BinOp::Div,
315            BinaryOp::Mod => BinOp::Mod,
316            BinaryOp::Eq => BinOp::Eq,
317            BinaryOp::Ne => BinOp::Ne,
318            BinaryOp::Lt => BinOp::Lt,
319            BinaryOp::Le => BinOp::Le,
320            BinaryOp::Gt => BinOp::Gt,
321            BinaryOp::Ge => BinOp::Ge,
322            BinaryOp::And => BinOp::And,
323            BinaryOp::Or => BinOp::Or,
324            BinaryOp::BitAnd => BinOp::BitAnd,
325            BinaryOp::BitOr => BinOp::BitOr,
326            BinaryOp::BitXor => BinOp::BitXor,
327            BinaryOp::Shl => BinOp::Shl,
328            BinaryOp::Shr => BinOp::Shr,
329        }
330    }
331}
332
333#[cfg(test)]
334mod tests {
335    use super::Func;
336    use crate::base::{EventId, Idx, PdId};
337    use crate::foreign::contract::ContractTable;
338    use crate::tast::env::built;
339    use crate::tast::ProgramView;
340
341    /// The event function reads a mapping's laid-out vaddr; its paddr is
342    /// opaque.
343    #[test]
344    fn a_mapping_vaddr_is_its_laid_out_address() {
345        let fis = "MemoryRegion mr(0x1000);\nProtectionDomain pd(100);";
346        let fi = "Mapping m(mr, \"rw\");\n\
347                  x: Address;\n\
348                  evt a: x = m.vaddr;";
349        let (tast, _) = built(fis, &[("pd", fi)]).expect("builds");
350        let names = ProgramView::new(&tast, PdId::new(0));
351        let no_contracts = ContractTable::default();
352        let func = Func::new(&no_contracts);
353        let body = func.event_function(names, EventId::new(0)).to_string();
354        let vaddr = tast.tenv.mappings.iter().next().expect("one mapping").vaddr;
355        assert!(body.contains(&format!("x = {vaddr};")), "{body}");
356        assert!(!body.contains(".vaddr"), "{body}");
357    }
358
359    #[test]
360    fn a_mapping_paddr_is_opaque_to_the_model() {
361        let fis = "MemoryRegion mr(0x1000);\nProtectionDomain pd(100);";
362        let fi = "Mapping m(mr, \"rw\");\n\
363                  x: Address;\n\
364                  evt a: x = m.paddr;";
365        let (tast, _) = built(fis, &[("pd", fi)]).expect("builds");
366        let names = ProgramView::new(&tast, PdId::new(0));
367        let no_contracts = ContractTable::default();
368        let func = Func::new(&no_contracts);
369        let body = func.event_function(names, EventId::new(0)).to_string();
370        assert!(body.contains("x = /* m.paddr */ 0;"), "{body}");
371    }
372}