Skip to main content

fic/xta_backend/
model.rs

1//! Fiducia → UPPAAL NTA transpilation.
2//!
3//! Three passes over `tast`, beside the Ccfg:
4//! 1. data-layer constants → global declarations;
5//! 2. channels → global declarations (async ones relayed by the
6//!    `ChannelAutogen` template, a bidirectional one as two unidirectional
7//!    ones);
8//! 3. each PD → one template: its `Orchestration` (one graph per entry
9//!    point) is printed by [`handler`]
10//!    under the platform's two rules — `init` once, committed (MK-Init), then
11//!    `notified`, its exit wired back to its head (MK-Restart). Interleaving
12//!    between PDs is UPPAAL's parallel composition, as it is the glts's.
13//!    Every `notified` location is urgent: the model does not count time, so
14//!    no PD waits while it can move. Progress, not fairness. A `protected`
15//!    graph is entered by a `Sync` channel's call, answers the waiting
16//!    caller, and goes back to where the callee was (`call`).
17//!
18//! The model is a slight over-approximation of the application, not a
19//! bisimulation of it: constructors run in any order rather than by
20//! priority, and PDs interleave freely, without the scheduler's priorities
21//! or run to completion. An invariant verified on it holds of the
22//! application; a counterexample may be one the platform cannot produce.
23//!
24//! Translation scheme summary:
25//! - A struct → a global `typedef struct { … } Name;` of the same fields,
26//!   after the structs its fields are of; a variable's type is `bool`,
27//!   the struct's name, or `int` (UPPAAL has no widths), an array's length
28//!   on its declarator, and a local's default fills every field
29//! - Unbuffered `Chan` → native UPPAAL `chan c;`; a `Sync` send is `c!`,
30//!   its value, if any, in `c_val`, then a wait for the callee's `ret_<pd>?`
31//! - Computation events → template-local functions; an edge firing the
32//!   event carries update label `name()`
33//! - Calls to contracted foreign functions (Viper or ACSL) → a declared
34//!   UPPAAL function per function a PD calls, `ffi_<name>`: `requires` as
35//!   `assert`s, never a guard, so the enabled edges are the Ccfg's;
36//!   `ensures retval == E` as its `return`. `x = io.f(a)` becomes
37//!   `x = ffi_f(a);`, a guard `[io.p(a)]` becomes `(ffi_p(a)) != (0)`, a
38//!   discarded value is still a call. An uncontracted call stays opaque (a
39//!   comment, or `0` in a guard).
40//! - Ccfg edge → transition: the guard printed as is, the event as
41//!   `(synchronisation, update)`; a silent edge is unlabelled and `hang`
42//!   is an unlabelled self-loop
43
44use std::collections::{BTreeSet, HashSet};
45
46use crate::ast::ProtectionDomainDecl;
47use crate::base::{BodyVarKind, ChanId, IdVec};
48use crate::ccfg::system::{Orchestration, System};
49use crate::ccfg::Ring;
50use crate::foreign::calls::call_sites;
51use crate::foreign::contract::ContractTable;
52use crate::tast::{ProgramView, Tast, TyEnv};
53
54use super::automaton::handler;
55use super::channel::{transpile_channel, transpile_channel_template};
56use super::contract::pancake_function;
57use super::func::Func;
58use super::types::{const_decl, struct_order, struct_typedef, typedef_name, var_decl};
59use super::xta::{
60    Expr, Instantiation, Nta, ProcLocalDecl, Template, Type, TypeExpr, VarDecl, KEYWORDS,
61};
62use super::{call, irq, queue};
63
64/// Transpile a typed Fiducia project and its graphs to a UPPAAL NTA.
65///
66/// `contracts` are declared as functions; an empty table leaves every
67/// foreign call opaque. No I/O.
68#[must_use]
69pub fn transpile(tast: &Tast, ccfg: &System, contracts: &ContractTable) -> Nta {
70    let tenv = &tast.tenv;
71    let mut nta = Nta::default();
72    let mut ch_template = transpile_channel_template();
73    let ch_instance = "ChannelAutogen".to_owned();
74
75    // Pass 0: structs → global typedefs, a struct after the ones its
76    // fields are of; then data-layer constants → global declarations,
77    // folded to their values (guard expressions reference them by name).
78    for id in struct_order(tenv) {
79        nta.global_declarations.push(struct_typedef(tenv, id));
80    }
81    for c in tenv.consts.iter() {
82        nta.global_declarations.push(const_decl(&c.name, &c.value));
83    }
84    nta.global_declarations
85        .extend(queue::decls(tenv, &ccfg.rings));
86    nta.global_declarations.extend(call::value_decls(tenv));
87    nta.global_declarations.extend(call::return_decls(tenv));
88    let irqs = irq::awaited(ccfg);
89    nta.global_declarations.extend(irq::decls(&irqs));
90
91    // Pass 1: channels → global declarations.
92    for ch in tenv.chans.iter() {
93        transpile_channel(&mut nta, tenv, ch, &mut ch_template);
94    }
95
96    // Pass 2: PDs → templates.
97    for (id, pd) in tenv.pds.iter_enumerated() {
98        let names = ProgramView::new(tast, id);
99        let template = transpile_pd(pd, names, &ccfg.programs[id], contracts, &ccfg.rings);
100        // Sanitize: avoid UPPAAL 5 reserved words as instance names.
101        let instance = uppaal_safe_name(&pd.name);
102        nta.instances.push(Instantiation {
103            name: instance.clone(),
104            params: Vec::new(),
105            template: template.name.clone(),
106            args: Vec::new(),
107        });
108        nta.system_processes.push(instance);
109        nta.templates.push(template);
110    }
111
112    nta.system_processes.push(ch_instance);
113    nta.templates.push(ch_template);
114    if let Some(environment) = irq::environment(&irqs) {
115        nta.instances.push(Instantiation {
116            name: "environment".to_owned(),
117            params: Vec::new(),
118            template: environment.name.clone(),
119            args: Vec::new(),
120        });
121        nta.system_processes.push("environment".to_owned());
122        nta.templates.push(environment);
123    }
124
125    nta
126}
127
128/// Transpile one Fiducia `ProtectionDomain` into a UPPAAL template: its
129/// declarations, then its `Orchestration` printed by [`handler`]. `program`
130/// is its program and that program's graphs, if it has processes.
131fn transpile_pd(
132    pd: &ProtectionDomainDecl,
133    names: ProgramView<'_>,
134    orchestration: &Orchestration,
135    contracts: &ContractTable,
136    rings: &IdVec<ChanId, Option<Ring>>,
137) -> Template {
138    let name = template_name(names.tenv, &pd.name);
139    let mut declarations = Vec::new();
140    let func = Func::new(contracts);
141
142    // Locals, then process `x: T;` declarations hoisted for the guards to read;
143    // the first declaration of a name wins.
144    let body = names.body();
145    let mut seen_vars: HashSet<&str> = HashSet::new();
146    let hoisted = body.processes.iter().flat_map(|p| {
147        p.body_vars
148            .iter()
149            .filter(|v| {
150                matches!(
151                    v.kind,
152                    BodyVarKind::Decl | BodyVarKind::Binder { .. } | BodyVarKind::Param
153                )
154            })
155            .map(|v| (&v.name, &v.ty))
156    });
157    let locals = names.locals().iter().map(|v| (&v.name, &v.ty));
158    for (var, ty) in locals.chain(hoisted) {
159        if seen_vars.insert(var) {
160            let decl = var_decl(names, ty, var, true);
161            declarations.push(ProcLocalDecl::Var(decl));
162        }
163    }
164
165    // One declared function per contracted function this PD calls, before
166    // the event functions that call them: `requires` become `assert`s, the
167    // deterministic `ensures` becomes the `return`.
168    let mut called = BTreeSet::new();
169    for site in call_sites(names.body()) {
170        called.insert(site.callee);
171    }
172    let mut declared: Vec<_> = called
173        .into_iter()
174        .filter_map(|f| contracts.contract(f))
175        .collect();
176    declared.sort_by(|a, b| a.name.cmp(&b.name));
177    for contract in declared {
178        declarations.push(ProcLocalDecl::Fn(pancake_function(contract)));
179    }
180
181    // Computation events as template-local functions, called from the
182    // update labels `transpile_event` writes.
183    for (id, _) in names.body().events.iter_enumerated() {
184        declarations.push(ProcLocalDecl::Fn(func.event_function(names, id)));
185    }
186
187    // `protected` receives only at its head, on `Sync` channels.
188    let buffered =
189        queue::Buffered::of(names, [&orchestration.init, &orchestration.notified], rings);
190    if !buffered.received.is_empty() {
191        declarations.push(queue::awake_decl());
192    }
193    if orchestration.protected.is_some() {
194        declarations.push(ProcLocalDecl::Var(VarDecl::single(
195            TypeExpr::plain(Type::Int),
196            call::FROM,
197            Some(Expr::Int(0)),
198        )));
199    }
200    let automaton = handler(&pd.name, orchestration, names, &func, &buffered);
201
202    Template {
203        name,
204        params: Vec::new(),
205        declarations,
206        locations: automaton.locations,
207        init: automaton.init,
208        transitions: automaton.transitions,
209    }
210}
211
212/// A PD's template name: `UpperCamelCase`, `Pd` appended when a struct's
213/// typedef has that name (PD `slot`, struct `Slot`), as the two share
214/// UPPAAL's global scope.
215fn template_name(tenv: &TyEnv, pd_name: &str) -> String {
216    let name = upper_camel(pd_name);
217    let taken = tenv
218        .structs
219        .iter_enumerated()
220        .any(|(id, _)| typedef_name(tenv, id) == name);
221    if taken {
222        format!("{name}Pd")
223    } else {
224        name
225    }
226}
227
228/// A UPPAAL-safe instance name for a PD: `_pd` appended when the raw name
229/// is one of UTAP's keywords (`simulate`, `system`, …).
230fn uppaal_safe_name(pd_name: &str) -> String {
231    if KEYWORDS.contains(&pd_name) {
232        format!("{pd_name}_pd")
233    } else {
234        pd_name.to_owned()
235    }
236}
237
238/// Map a `snake_case` identifier to `UpperCamelCase` for a UPPAAL
239/// template name (e.g. `eth_outer` → `EthOuter`, `phil0` → `Phil0`).
240pub(super) fn upper_camel(snake: &str) -> String {
241    let mut out = String::with_capacity(snake.len());
242    for segment in snake.split('_') {
243        let mut chars = segment.chars();
244        if let Some(first) = chars.next() {
245            out.extend(first.to_uppercase());
246            out.push_str(chars.as_str());
247        }
248    }
249    out
250}
251
252#[cfg(test)]
253mod tests {
254    use super::upper_camel;
255
256    #[test]
257    fn upper_camel_single_segment() {
258        assert_eq!(upper_camel("phil0"), "Phil0");
259    }
260
261    #[test]
262    fn upper_camel_multi_segment() {
263        assert_eq!(upper_camel("eth_outer"), "EthOuter");
264        assert_eq!(upper_camel("eth_outer_foo"), "EthOuterFoo");
265    }
266
267    #[test]
268    fn upper_camel_empty() {
269        assert_eq!(upper_camel(""), "");
270    }
271}