1#![allow(dead_code)] use std::fmt;
12
13use super::{joined, Expr, GlobalDecl, Instantiation, Param, ProcLocalDecl, TypeExpr};
14
15#[derive(Debug, Default)]
17pub struct Nta {
18 pub global_declarations: Vec<GlobalDecl>,
21 pub templates: Vec<Template>,
23 pub instances: Vec<Instantiation>,
25 pub system_processes: Vec<String>,
27}
28
29impl fmt::Display for Nta {
30 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#[derive(Debug)]
57pub struct Template {
58 pub name: String,
60 pub params: Vec<Param>,
62 pub declarations: Vec<ProcLocalDecl>,
69 pub locations: Vec<Location>,
71 pub init: String,
73 pub transitions: Vec<Transition>,
75}
76
77impl Template {
78 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 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#[derive(Debug)]
165pub struct Location {
166 pub id: String,
169 pub name: String,
171 pub invariant: Option<Expr>,
173 pub kind: LocationKind,
175}
176
177#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
180pub enum LocationKind {
181 #[default]
183 Normal,
184 Urgent,
186 Committed,
189}
190
191#[derive(Debug, Clone, PartialEq)]
193pub struct Select {
194 pub name: String,
196 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#[derive(Debug, Clone, PartialEq)]
208pub struct Sync {
209 pub chan: Expr,
211 pub dir: SyncDir,
213}
214
215keywords! {
216 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#[derive(Debug, Clone, Default, PartialEq)]
229pub struct System {
230 pub decls: Vec<GlobalDecl>,
232 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#[derive(Debug, Default)]
258pub struct Transition {
259 pub source: String,
261 pub target: String,
263 pub select: Option<String>,
265 pub guard: Option<String>,
267 pub sync: Option<String>,
269 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}