Skip to main content

fic/emit/
xta.rs

1//! `--emit=xta`: the UPPAAL model, as the text verifyta reads or, with
2//! `--pretty`, pretty-printed as the flat-system-1.5 XML the GUI opens.
3//!
4//! The text is what the model prints of itself; the XML is the one
5//! container that carries coordinates.
6
7use std::collections::{HashMap, HashSet, VecDeque};
8use std::fmt::{self, Write as _};
9use std::fs;
10use std::io;
11use std::path::Path;
12
13use anyhow::{Context, Result};
14use quick_xml::events::{BytesDecl, BytesText, Event};
15use quick_xml::writer::ElementWriter;
16use quick_xml::Writer;
17
18use crate::xta_backend::xta::{Location, LocationKind, Nta, Template, Transition};
19
20/// Write the model to `path`: textual XTA, or the pretty-printed XML.
21pub fn write(nta: &Nta, path: &Path, pretty: bool) -> Result<()> {
22    let text = if pretty { pprint(nta) } else { nta.to_string() };
23    if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) {
24        fs::create_dir_all(dir).with_context(|| format!("Failed to create {}", dir.display()))?;
25    }
26    fs::write(path, text).with_context(|| format!("Failed to write {}", path.display()))
27}
28
29/// The model pretty-printed as flat-system-1.5 XML.
30pub fn pprint(nta: &Nta) -> String {
31    let mut w = Writer::new_with_indent(Vec::new(), b' ', 2);
32    network(&mut w, nta).expect("writing to a Vec cannot fail");
33    let mut xml = String::from_utf8(w.into_inner()).expect("quick-xml writes UTF-8");
34    xml.push('\n');
35    xml
36}
37
38/// Horizontal distance between depths at least, vertical between branches.
39const DX: i32 = 180;
40const DY: i32 = 120;
41/// What the GUI's label font takes per character, and per line.
42const CHAR_W: i32 = 7;
43const LINE_H: i32 = 16;
44/// Clear space kept on both sides of a label.
45const MARGIN: i32 = 60;
46/// How far a self-loop reaches up, and how far apart the loops of one
47/// location sit side by side: wide enough for their labels.
48const LOOP_H: i32 = 70;
49const LOOP_W: i32 = 220;
50/// Where the first location sits.
51const ORIGIN: (i32, i32) = (100, 100);
52
53/// The width the labels of a transition take.
54fn label_width(t: &Transition) -> i32 {
55    [&t.guard, &t.sync, &t.update]
56        .into_iter()
57        .flatten()
58        .map(|l| CHAR_W * i32::try_from(l.chars().count()).unwrap_or(i32::MAX / CHAR_W))
59        .max()
60        .unwrap_or(0)
61}
62
63/// How many labels a transition carries.
64fn label_count(t: &Transition) -> i32 {
65    [&t.guard, &t.sync, &t.update]
66        .into_iter()
67        .flatten()
68        .count()
69        .try_into()
70        .unwrap_or(0)
71}
72
73/// Where each location of a template sits: x by depth from the initial
74/// location, breadth first over the transitions, y by the order of
75/// discovery within a depth; what no transition reaches sits past the
76/// last depth. A depth is as far from the next as its widest label
77/// needs, so the labels of one row never meet.
78struct Placement<'a> {
79    at: HashMap<&'a str, (i32, i32)>,
80    depth: HashMap<&'a str, usize>,
81    /// The locations with a self-loop, whose name moves out of its way.
82    looped: HashSet<&'a str>,
83}
84
85impl<'a> Placement<'a> {
86    fn of(template: &'a Template) -> Self {
87        let mut out: HashMap<&str, Vec<&str>> = HashMap::new();
88        for t in &template.transitions {
89            out.entry(&t.source).or_default().push(&t.target);
90        }
91        let mut depth: HashMap<&str, usize> = HashMap::new();
92        let mut order: Vec<&str> = Vec::new();
93        let mut queue = VecDeque::new();
94        if template.locations.iter().any(|l| l.id == template.init) {
95            depth.insert(&template.init, 0);
96            queue.push_back(template.init.as_str());
97        }
98        while let Some(id) = queue.pop_front() {
99            order.push(id);
100            for next in out.get(id).into_iter().flatten() {
101                if !depth.contains_key(next) {
102                    depth.insert(next, depth[id] + 1);
103                    queue.push_back(next);
104                }
105            }
106        }
107        let beyond = depth.values().max().map_or(0, |d| d + 1);
108        for loc in &template.locations {
109            if !depth.contains_key(loc.id.as_str()) {
110                depth.insert(&loc.id, beyond);
111                order.push(&loc.id);
112            }
113        }
114        // The loops above the first row need room to hang, and to the
115        // left of the first column to fan out.
116        let mut loops: HashMap<&str, i32> = HashMap::new();
117        for t in template.transitions.iter().filter(|t| t.source == t.target) {
118            *loops.entry(&t.source).or_default() += 1;
119        }
120        let widest = loops.values().max().copied().unwrap_or(0);
121        let top = ORIGIN.1 + if widest > 0 { 80 } else { 0 };
122        let mut gap = vec![DX; beyond + 1];
123        for t in &template.transitions {
124            let (Some(&from), Some(&to)) =
125                (depth.get(t.source.as_str()), depth.get(t.target.as_str()))
126            else {
127                continue;
128            };
129            if to > from {
130                gap[from] = gap[from].max(label_width(t) + 2 * MARGIN);
131            }
132        }
133        let left = ORIGIN.0 + (widest - 1).max(0) * LOOP_W / 2;
134        let mut column = vec![left; beyond + 1];
135        for d in 1..column.len() {
136            column[d] = column[d - 1] + gap[d - 1];
137        }
138        let mut rows: HashMap<usize, i32> = HashMap::new();
139        let mut at = HashMap::new();
140        for id in order {
141            let d = depth[id];
142            let row = rows.entry(d).or_insert(0);
143            at.insert(id, (column[d], top + DY * *row));
144            *row += 1;
145        }
146        let looped = loops.keys().copied().collect();
147        Placement { at, depth, looped }
148    }
149
150    fn at(&self, id: &str) -> (i32, i32) {
151        self.at.get(id).copied().unwrap_or(ORIGIN)
152    }
153
154    /// A transition to the same or a shallower depth.
155    fn backward(&self, t: &Transition) -> bool {
156        self.depth.get(t.target.as_str()) <= self.depth.get(t.source.as_str())
157    }
158
159    /// How many depths a backward transition climbs back.
160    fn span(&self, t: &Transition) -> i32 {
161        let of = |id: &str| self.depth.get(id).copied().unwrap_or(0);
162        i32::try_from(of(&t.source).saturating_sub(of(&t.target))).unwrap_or(0)
163    }
164}
165
166/// Where a transition runs: the nails it bends through, and where its
167/// labels go (the nail or midpoint, and whether they hang below it).
168struct Route {
169    nails: Vec<(i32, i32)>,
170    anchor: (i32, i32),
171    below: bool,
172}
173
174type Xml = Writer<Vec<u8>>;
175
176const DOCTYPE: &str = "nta PUBLIC '-//Uppaal Team//DTD Flat System 1.5//EN' \
177    'http://www.it.uu.se/research/group/darts/uppaal/flat-1_5.dtd'";
178
179/// The network: global declarations, templates, system.
180fn network(w: &mut Xml, nta: &Nta) -> io::Result<()> {
181    w.write_event(Event::Decl(BytesDecl::new("1.0", Some("utf-8"), None)))?;
182    w.write_event(Event::DocType(BytesText::from_escaped(DOCTYPE)))?;
183    w.create_element("nta").write_inner_content(|w| {
184        text(w, "declaration", &lines(&nta.global_declarations))?;
185        for t in &nta.templates {
186            template(w, t)?;
187        }
188        let mut system = lines(&nta.instances);
189        if !nta.system_processes.is_empty() {
190            let _ = writeln!(system, "\nsystem {};", nta.system_processes.join(", "));
191        }
192        text(w, "system", &system)
193    })?;
194    Ok(())
195}
196
197fn template(w: &mut Xml, t: &Template) -> io::Result<()> {
198    let placement = Placement::of(t);
199    w.create_element("template").write_inner_content(|w| {
200        text(w, "name", &t.name)?;
201        if !t.params.is_empty() {
202            let params: Vec<String> = t.params.iter().map(ToString::to_string).collect();
203            text(w, "parameter", &params.join(", "))?;
204        }
205        if !t.declarations.is_empty() {
206            text(w, "declaration", &lines(&t.declarations))?;
207        }
208        for loc in &t.locations {
209            location(w, loc, &placement)?;
210        }
211        w.create_element("init")
212            .with_attribute(("ref", t.init.as_str()))
213            .write_empty()?;
214        let mut seen: HashMap<(&str, &str), usize> = HashMap::new();
215        let mut group: HashMap<(&str, &str), usize> = HashMap::new();
216        for tr in &t.transitions {
217            *group.entry((&tr.source, &tr.target)).or_default() += 1;
218        }
219        for tr in &t.transitions {
220            let key = (tr.source.as_str(), tr.target.as_str());
221            let nth = seen.entry(key).or_default();
222            transition(w, tr, &placement, (*nth, group[&key]))?;
223            *nth += 1;
224        }
225        Ok(())
226    })?;
227    Ok(())
228}
229
230fn location(w: &mut Xml, loc: &Location, placement: &Placement<'_>) -> io::Result<()> {
231    let (x, y) = placement.at(&loc.id);
232    let name = if placement.looped.contains(loc.id.as_str()) {
233        (x - 10, y + 36)
234    } else {
235        (x - 10, y - 34)
236    };
237    placed(w, "location", &[("id", &loc.id)], (x, y)).write_inner_content(|w| {
238        placed(w, "name", &[], name).write_text_content(BytesText::new(&loc.name))?;
239        if let Some(inv) = &loc.invariant {
240            placed(w, "label", &[("kind", "invariant")], (x - 10, y + 18))
241                .write_text_content(BytesText::new(&inv.to_string()))?;
242        }
243        match loc.kind {
244            LocationKind::Normal => {}
245            LocationKind::Urgent => _ = w.create_element("urgent").write_empty()?,
246            LocationKind::Committed => _ = w.create_element("committed").write_empty()?,
247        }
248        Ok(())
249    })?;
250    Ok(())
251}
252
253/// Route one transition, the `nth` of the `of` that share its ends. Each
254/// of them gets a nail of its own, or they would be one line with the
255/// labels written over each other.
256fn route(t: &Transition, placement: &Placement<'_>, nth: usize, of: usize) -> Route {
257    let (sx, sy) = placement.at(&t.source);
258    let (tx, ty) = placement.at(&t.target);
259    let (mx, my) = (i32::midpoint(sx, tx), i32::midpoint(sy, ty));
260    let rank = i32::try_from(nth).unwrap_or(0);
261    let fan = i32::try_from(of).unwrap_or(1) - 1;
262    if t.source == t.target {
263        // The loops of a location fan out above it, side by side.
264        let cx = sx + (2 * rank - fan) * LOOP_W / 2;
265        let far = sy - LOOP_H;
266        Route {
267            nails: vec![(cx - 30, far), (cx + 30, far)],
268            anchor: (cx, far),
269            below: false,
270        }
271    } else if placement.backward(t) {
272        // Down, across beneath the row, up: it never crosses the edges
273        // of the row, and nests outward the further it climbs back.
274        let low = sy.max(ty) + 50 + 30 * placement.span(t) + 60 * rank;
275        Route {
276            nails: vec![(sx, low), (tx, low)],
277            anchor: (mx, low),
278            below: true,
279        }
280    } else if fan == 0 {
281        Route {
282            nails: Vec::new(),
283            anchor: (mx, my),
284            below: false,
285        }
286    } else {
287        // Fan out around the straight line: the first above, the last below.
288        let off = (2 * rank - fan) * 35;
289        Route {
290            nails: vec![(mx, my + off)],
291            anchor: (mx, my + off),
292            below: off > 0,
293        }
294    }
295}
296
297fn transition(
298    w: &mut Xml,
299    t: &Transition,
300    placement: &Placement<'_>,
301    (nth, of): (usize, usize),
302) -> io::Result<()> {
303    let route = route(t, placement, nth, of);
304    let width = label_width(t);
305    let height = LINE_H * label_count(t);
306    // Labels are centred on the anchor, above it or below.
307    let lx = route.anchor.0 - width / 2;
308    let top = if route.below {
309        route.anchor.1 + 6
310    } else {
311        route.anchor.1 - 6 - height
312    };
313    w.create_element("transition").write_inner_content(|w| {
314        w.create_element("source")
315            .with_attribute(("ref", t.source.as_str()))
316            .write_empty()?;
317        w.create_element("target")
318            .with_attribute(("ref", t.target.as_str()))
319            .write_empty()?;
320        let labels = [
321            ("select", &t.select),
322            ("guard", &t.guard),
323            ("synchronisation", &t.sync),
324            ("assignment", &t.update),
325        ];
326        let mut line = 0;
327        for (kind, label) in labels {
328            if let Some(label) = label {
329                placed(w, "label", &[("kind", kind)], (lx, top + LINE_H * line))
330                    .write_text_content(BytesText::new(label))?;
331                line += 1;
332            }
333        }
334        for nail in route.nails {
335            placed(w, "nail", &[], nail).write_empty()?;
336        }
337        Ok(())
338    })?;
339    Ok(())
340}
341
342/// `<tag>text</tag>`.
343fn text(w: &mut Xml, tag: &str, content: &str) -> io::Result<()> {
344    w.create_element(tag)
345        .write_text_content(BytesText::new(content))?;
346    Ok(())
347}
348
349/// An element the GUI places: its attributes, then `x` and `y`.
350fn placed<'a>(
351    w: &'a mut Xml,
352    tag: &'a str,
353    attrs: &[(&str, &str)],
354    (x, y): (i32, i32),
355) -> ElementWriter<'a, Vec<u8>> {
356    w.create_element(tag)
357        .with_attributes(attrs.iter().copied())
358        .with_attribute(("x", x.to_string().as_str()))
359        .with_attribute(("y", y.to_string().as_str()))
360}
361
362/// A text block, one item per line.
363fn lines<T: fmt::Display>(items: &[T]) -> String {
364    let mut s = String::new();
365    for item in items {
366        let _ = write!(s, "\n{item}");
367    }
368    if !s.is_empty() {
369        s.push('\n');
370    }
371    s
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377    use crate::xta_backend::xta::{BinOp, Declarator, Expr, Param, Type, TypeExpr};
378
379    fn location(id: &str, name: &str, kind: LocationKind) -> Location {
380        Location {
381            id: id.to_string(),
382            name: name.to_string(),
383            invariant: None,
384            kind,
385        }
386    }
387
388    fn edge(source: &str, target: &str) -> Transition {
389        Transition {
390            source: source.to_string(),
391            target: target.to_string(),
392            ..Transition::default()
393        }
394    }
395
396    /// `Init -> A -> B -> Exit`, with a branch `A -> C` and the exit
397    /// rejoining `A`: a chain, one branch below it, one backward edge.
398    fn handler() -> Template {
399        Template {
400            name: "Pd".to_string(),
401            params: Vec::new(),
402            declarations: Vec::new(),
403            locations: vec![
404                location("init", "Init", LocationKind::Committed),
405                location("a", "A", LocationKind::Normal),
406                location("b", "B", LocationKind::Normal),
407                location("c", "C", LocationKind::Normal),
408                location("exit", "Exit", LocationKind::Normal),
409            ],
410            init: "init".to_string(),
411            transitions: vec![
412                edge("init", "a"),
413                edge("a", "b"),
414                edge("a", "c"),
415                edge("b", "exit"),
416                edge("exit", "a"),
417            ],
418        }
419    }
420
421    #[test]
422    fn depth_gives_x_and_branches_give_y() {
423        let template = handler();
424        let p = Placement::of(&template);
425        assert_eq!(p.at("init"), (100, 100));
426        assert_eq!(p.at("a"), (280, 100));
427        assert_eq!(p.at("b"), (460, 100));
428        assert_eq!(p.at("c"), (460, 220));
429        assert_eq!(p.at("exit"), (640, 100));
430        assert!(p.backward(&edge("exit", "a")));
431        assert!(!p.backward(&edge("a", "b")));
432    }
433
434    #[test]
435    fn unreached_locations_sit_past_the_end() {
436        let mut template = handler();
437        template
438            .locations
439            .push(location("lost", "Lost", LocationKind::Normal));
440        let p = Placement::of(&template);
441        assert_eq!(p.at("lost"), (820, 100));
442    }
443
444    #[test]
445    fn backward_edges_bend_through_a_nail_and_self_loops_through_two() {
446        let mut template = handler();
447        template.transitions.push(Transition {
448            source: "b".to_string(),
449            target: "b".to_string(),
450            update: Some("tick()".to_string()),
451            ..Transition::default()
452        });
453        let xml = pprint(&Nta {
454            templates: vec![template],
455            ..Nta::default()
456        });
457        assert!(
458            xml.contains(
459                "<source ref=\"exit\"/>\n      <target ref=\"a\"/>\n      <nail x=\"640\" y=\"290\"/>\n      <nail x=\"280\" y=\"290\"/>"
460            ),
461            "{xml}"
462        );
463        assert!(
464            xml.contains("<nail x=\"430\" y=\"110\"/>\n      <nail x=\"490\" y=\"110\"/>"),
465            "{xml}"
466        );
467        assert!(
468            xml.contains("<label kind=\"assignment\" x=\"439\" y=\"88\">tick()</label>"),
469            "{xml}"
470        );
471    }
472
473    #[test]
474    fn parallel_edges_and_loops_each_get_a_route_of_their_own() {
475        let mut template = handler();
476        let guarded = |guard: &str| Transition {
477            guard: Some(guard.to_string()),
478            ..edge("b", "exit")
479        };
480        template.transitions.push(guarded("x < 1"));
481        template.transitions.push(Transition {
482            sync: Some("tick!".to_string()),
483            ..edge("c", "c")
484        });
485        template.transitions.push(Transition {
486            sync: Some("tock!".to_string()),
487            ..edge("c", "c")
488        });
489        let xml = pprint(&Nta {
490            templates: vec![template],
491            ..Nta::default()
492        });
493        // b -> exit twice: one nail above the straight line, one below.
494        assert_eq!(
495            xml.matches("<nail x=\"660\" y=\"145\"/>").count(),
496            1,
497            "{xml}"
498        );
499        assert_eq!(
500            xml.matches("<nail x=\"660\" y=\"215\"/>").count(),
501            1,
502            "{xml}"
503        );
504        // The two loops at c sit side by side, not on top of each other.
505        assert!(xml.contains("<nail x=\"430\" y=\"230\"/>"), "{xml}");
506        assert!(xml.contains("<nail x=\"710\" y=\"230\"/>"), "{xml}");
507    }
508
509    #[test]
510    fn a_wide_label_pushes_the_next_depth_out() {
511        let mut template = handler();
512        template.transitions[1].guard = Some("g".repeat(40));
513        let p = Placement::of(&template);
514        // 40 characters, a margin each side: 280 + 60 + 60 > 180.
515        assert_eq!(p.at("b"), (100 + 180 + 400, 100));
516    }
517
518    #[test]
519    fn every_location_and_name_carries_coordinates() {
520        let xml = pprint(&Nta {
521            templates: vec![handler()],
522            ..Nta::default()
523        });
524        assert!(xml.contains("<location id=\"init\" x=\"100\" y=\"100\">\n      <name x=\"90\" y=\"66\">Init</name>\n      <committed/>\n    </location>"), "{xml}");
525        assert_eq!(xml.matches("<location id=").count(), 5);
526        assert_eq!(xml.matches("<name x=").count(), 5);
527    }
528
529    #[test]
530    fn empty_nta_is_valid() {
531        let xml = pprint(&Nta::default());
532        assert!(xml.contains("<nta>"));
533        assert!(xml.contains("</nta>"));
534        assert!(xml.contains("<declaration></declaration>"));
535        assert!(xml.contains("<system>"));
536    }
537
538    #[test]
539    fn parameters_invariant_and_urgency_reach_the_xml() {
540        let mut nta = Nta::default();
541        nta.templates.push(Template {
542            name: "Worker".to_string(),
543            params: vec![
544                Param {
545                    ty: TypeExpr::plain(Type::Int),
546                    by_ref: true,
547                    decl: Declarator::scalar("count"),
548                },
549                Param {
550                    ty: TypeExpr::constant(Type::Int),
551                    by_ref: false,
552                    decl: Declarator::scalar("id"),
553                },
554            ],
555            declarations: Vec::new(),
556            locations: vec![Location {
557                id: "w_0".to_string(),
558                name: "Busy".to_string(),
559                invariant: Some(Expr::binary(BinOp::Lt, Expr::ident("count"), Expr::Int(3))),
560                kind: LocationKind::Urgent,
561            }],
562            init: "w_0".to_string(),
563            transitions: Vec::new(),
564        });
565        let xml = pprint(&nta);
566        assert!(
567            xml.contains("<parameter>int &amp;count, const int id</parameter>"),
568            "{xml}"
569        );
570        assert!(
571            xml.contains("<label kind=\"invariant\" x=\"90\" y=\"118\">(count) &lt; (3)</label>\n      <urgent/>\n    </location>"),
572            "{xml}"
573        );
574    }
575
576    #[test]
577    fn xml_text_is_escaped() {
578        let mut nta = Nta::default();
579        nta.templates.push(Template {
580            name: "T".to_string(),
581            params: Vec::new(),
582            declarations: Vec::new(),
583            locations: vec![location("t0", "S", LocationKind::Normal)],
584            init: "t0".to_string(),
585            transitions: vec![Transition {
586                source: "t0".to_string(),
587                target: "t0".to_string(),
588                guard: Some("a < b && c > d".to_string()),
589                ..Transition::default()
590            }],
591        });
592        let xml = pprint(&nta);
593        assert!(xml.contains("a &lt; b &amp;&amp; c &gt; d"), "{xml}");
594    }
595}