Skip to main content

fic/xta_backend/xta/
nta.rs

1//! The network (UTAP's `Document`): a typed mirror of the flat-system-1.5
2//! schema that `transpile` fills and that prints itself as text — [`Nta`] → [`Template`] →
3//! [`Location`], [`Transition`] — with the label forms the XML reader parses
4//! with their own start symbols ([`Select`] for `SelectList`, [`Sync`] for
5//! `SyncExpr`) and the `<system>` section ([`System`], the `XTA` start
6//! symbol). The text inside every element is written in the language the
7//! sibling files define.
8
9#![allow(dead_code)] // the transition labels are still strings in `transpile`
10
11use std::fmt;
12
13use super::{joined, Expr, GlobalDecl, Instantiation, Param, ProcLocalDecl, TypeExpr};
14
15/// A complete UPPAAL Network of Timed Automata.
16#[derive(Debug, Default)]
17pub struct Nta {
18    /// Top-level (`<nta><declaration>`) global declarations: chans,
19    /// shared variables, capacity constants.
20    pub global_declarations: Vec<GlobalDecl>,
21    /// One template per Fiducia `ProtectionDomain`.
22    pub templates: Vec<Template>,
23    /// `<system>` instantiations, e.g. `phil0_inst = Phil0();`.
24    pub instances: Vec<Instantiation>,
25    /// Names of instances composed under `system ...;`.
26    pub system_processes: Vec<String>,
27}
28
29impl fmt::Display for Nta {
30    /// The model in UPPAAL's textual form (`.xta`, UTAP's `XTA` start
31    /// symbol): the global declarations, each template as a process
32    /// declaration, the instantiations, then the `system` line.
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        for decl in &self.global_declarations {
35            writeln!(f, "{decl}")?;
36        }
37        for template in &self.templates {
38            write!(f, "\n{template}")?;
39        }
40        if !self.instances.is_empty() || !self.system_processes.is_empty() {
41            writeln!(f)?;
42        }
43        for instance in &self.instances {
44            writeln!(f, "{instance}")?;
45        }
46        if !self.system_processes.is_empty() {
47            f.write_str("system ")?;
48            joined(f, &self.system_processes, ", ")?;
49            writeln!(f, ";")?;
50        }
51        Ok(())
52    }
53}
54
55/// A UPPAAL template — the per-PD timed automaton.
56#[derive(Debug)]
57pub struct Template {
58    /// Template name (`UpperCamelCase`).
59    pub name: String,
60    /// Formal parameters (`<parameter>`, a `ParameterList`).
61    pub params: Vec<Param>,
62    /// Template-local declarations: bool/int variables and the
63    /// auto-generated event functions (one per Fiducia event).
64    ///
65    /// [`ProcLocalDecl`], not [`GlobalDecl`]: UTAP admits only variables,
66    /// typedefs and functions inside a template (`ProcLocalDeclList`,
67    /// parser.y:786), so the scope rule is carried by the type.
68    pub declarations: Vec<ProcLocalDecl>,
69    /// All locations in the template.
70    pub locations: Vec<Location>,
71    /// ID of the initial location (must reference one of `locations`).
72    pub init: String,
73    /// Edges between locations.
74    pub transitions: Vec<Transition>,
75}
76
77impl Template {
78    /// The name of the location `id` refers to, the identifier the textual
79    /// form uses.
80    fn location_name<'a>(&'a self, id: &'a str) -> &'a str {
81        self.locations
82            .iter()
83            .find(|l| l.id == id)
84            .map_or(id, |l| l.name.as_str())
85    }
86
87    fn write_kind(
88        &self,
89        f: &mut fmt::Formatter<'_>,
90        keyword: &str,
91        kind: LocationKind,
92    ) -> fmt::Result {
93        let names: Vec<&str> = self
94            .locations
95            .iter()
96            .filter(|l| l.kind == kind)
97            .map(|l| l.name.as_str())
98            .collect();
99        if names.is_empty() {
100            return Ok(());
101        }
102        write!(f, "{keyword} ")?;
103        joined(f, &names, ", ")?;
104        writeln!(f, ";")
105    }
106}
107
108impl fmt::Display for Template {
109    /// A process declaration (`ProcDecl`, parser.y): the declarations, the
110    /// locations as `state` with their invariants, the committed and urgent
111    /// ones, `init`, and the transitions with their labels.
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        write!(f, "process {}(", self.name)?;
114        joined(f, &self.params, ", ")?;
115        writeln!(f, ") {{")?;
116        for decl in &self.declarations {
117            writeln!(f, "{decl}")?;
118        }
119        f.write_str("state ")?;
120        for (i, loc) in self.locations.iter().enumerate() {
121            if i > 0 {
122                f.write_str(", ")?;
123            }
124            f.write_str(&loc.name)?;
125            if let Some(inv) = &loc.invariant {
126                write!(f, " {{ {inv} }}")?;
127            }
128        }
129        writeln!(f, ";")?;
130        self.write_kind(f, "commit", LocationKind::Committed)?;
131        self.write_kind(f, "urgent", LocationKind::Urgent)?;
132        writeln!(f, "init {};", self.location_name(&self.init))?;
133        if !self.transitions.is_empty() {
134            writeln!(f, "trans")?;
135            for (i, t) in self.transitions.iter().enumerate() {
136                if i > 0 {
137                    writeln!(f, ",")?;
138                }
139                write!(
140                    f,
141                    "    {} -> {} {{",
142                    self.location_name(&t.source),
143                    self.location_name(&t.target)
144                )?;
145                for (keyword, label) in [
146                    ("select", &t.select),
147                    ("guard", &t.guard),
148                    ("sync", &t.sync),
149                    ("assign", &t.update),
150                ] {
151                    if let Some(label) = label {
152                        write!(f, " {keyword} {label};")?;
153                    }
154                }
155                f.write_str(" }")?;
156            }
157            writeln!(f, ";")?;
158        }
159        writeln!(f, "}}")
160    }
161}
162
163/// A UPPAAL location (state).
164#[derive(Debug)]
165pub struct Location {
166    /// Stable identifier — referenced by `init` and by transition
167    /// `source` / `target`.
168    pub id: String,
169    /// Display name shown in the UPPAAL GUI.
170    pub name: String,
171    /// The `invariant` label.
172    pub invariant: Option<Expr>,
173    /// Normal, urgent or committed.
174    pub kind: LocationKind,
175}
176
177/// What may happen at a location: UTAP marks a location urgent or
178/// committed, never both.
179#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
180pub enum LocationKind {
181    /// Time may pass.
182    #[default]
183    Normal,
184    /// No time passes here.
185    Urgent,
186    /// No time passes, and the network's next transition leaves a
187    /// committed location.
188    Committed,
189}
190
191/// One `select` binding: `name : type` (`SelectList`).
192#[derive(Debug, Clone, PartialEq)]
193pub struct Select {
194    /// The bound name.
195    pub name: String,
196    /// Its range, a bounded int or a scalar set.
197    pub ty: TypeExpr,
198}
199
200impl fmt::Display for Select {
201    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
202        write!(f, "{} : {}", self.name, self.ty)
203    }
204}
205
206/// A synchronisation label (`SyncExpr`): `chan!` or `chan?`.
207#[derive(Debug, Clone, PartialEq)]
208pub struct Sync {
209    /// The channel, possibly indexed (`ball[i]`).
210    pub chan: Expr,
211    /// Send or receive.
212    pub dir: SyncDir,
213}
214
215keywords! {
216    /// The direction of a [`Sync`].
217    pub enum SyncDir { Send => "!", Recv => "?" }
218}
219
220impl fmt::Display for Sync {
221    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
222        write!(f, "{}{}", self.chan, self.dir)
223    }
224}
225
226/// The `<system>` section (UTAP's `XTA` start symbol): declarations, most
227/// often instantiations, then the `system` line.
228#[derive(Debug, Clone, Default, PartialEq)]
229pub struct System {
230    /// Declarations before the `system` line (`P1 = Worker(c, 1);`, …).
231    pub decls: Vec<GlobalDecl>,
232    /// The composed processes, by priority group, lowest first:
233    /// `[[a, b], [c]]` is `system a, b < c;` (`ProcessList`).
234    pub processes: Vec<Vec<String>>,
235}
236
237impl fmt::Display for System {
238    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
239        for decl in &self.decls {
240            writeln!(f, "{decl}")?;
241        }
242        if !self.processes.is_empty() {
243            f.write_str("system ")?;
244            for (i, group) in self.processes.iter().enumerate() {
245                if i > 0 {
246                    f.write_str(" < ")?;
247                }
248                joined(f, group, ", ")?;
249            }
250            f.write_str(";\n")?;
251        }
252        Ok(())
253    }
254}
255
256/// A directed edge between two locations.
257#[derive(Debug, Default)]
258pub struct Transition {
259    /// Source location id.
260    pub source: String,
261    /// Target location id.
262    pub target: String,
263    /// Optional select label, values the edge chooses: `r : int[0, 1]`.
264    pub select: Option<String>,
265    /// Optional guard label (UPPAAL boolean expression).
266    pub guard: Option<String>,
267    /// Optional synchronisation label, e.g. `c!` or `c?`.
268    pub sync: Option<String>,
269    /// Optional update label, e.g. `c_buf++` or `think();`.
270    pub update: Option<String>,
271}
272
273#[cfg(test)]
274mod tests {
275    use crate::xta_backend::xta::*;
276
277    #[test]
278    fn select_and_sync_labels() {
279        let sel = Select {
280            name: "i".to_string(),
281            ty: TypeExpr::plain(Type::BoundedInt {
282                lo: Expr::Int(0),
283                hi: Expr::Int(3),
284            }),
285        };
286        assert_eq!(sel.to_string(), "i : int[0, 3]");
287        let chan = Expr::Index {
288            base: Box::new(Expr::ident("ball")),
289            index: Box::new(Expr::ident("i")),
290        };
291        let send = Sync {
292            chan: chan.clone(),
293            dir: SyncDir::Send,
294        };
295        let recv = Sync {
296            chan,
297            dir: SyncDir::Recv,
298        };
299        assert_eq!(send.to_string(), "ball[i]!");
300        assert_eq!(recv.to_string(), "ball[i]?");
301    }
302
303    #[test]
304    fn system_line_with_priority_groups() {
305        let system = System {
306            decls: vec![GlobalDecl::Instantiation(Instantiation {
307                name: "ping".to_string(),
308                params: Vec::new(),
309                template: "Ping".to_string(),
310                args: vec![Expr::Int(1)],
311            })],
312            processes: vec![
313                vec!["ping".to_string(), "pong".to_string()],
314                vec!["monitor".to_string()],
315            ],
316        };
317        assert_eq!(
318            system.to_string(),
319            "ping = Ping(1);\nsystem ping, pong < monitor;\n"
320        );
321        assert_eq!(System::default().to_string(), "");
322    }
323}