Skip to main content

fic/wfcheck/
chan_cycle.rs

1//! **Wf2** (`WellFormed.lean`'s `dependsOn`): the channel dependency graph is
2//! acyclic, as [`check_wf2`].
3//!
4//! An edge `r → s` means PD `r` receives from PD `s`, so waits for it; a cycle
5//! is a circular wait, a deadlock by construction. A unidirectional channel
6//! gives one edge, receiver → sender; `AsyncBi` gives both, so every
7//! bidirectional channel fails Wf2. Parallel channels between one ordered pair
8//! are one edge: dependency is a relation.
9//!
10//! Each cycle is found once, by a DFS from its least PD that enters only
11//! greater PDs: O(n · (n + E)), ample at embedded scale; Johnson's algorithm
12//! if graphs grow.
13
14use std::collections::BTreeMap;
15
16use crate::ast::ChannelKind;
17use crate::base::{ChanId, Idx};
18use crate::error::{Diagnostic, Diagnostics};
19use crate::tast::TyEnv;
20
21/// A dependency cycle: its PDs from the least, and the channel of each edge.
22type Cycle = (Vec<usize>, Vec<ChanId>);
23
24/// Check WF2: the channel dependency graph is acyclic.
25///
26/// # Errors
27///
28/// One diagnostic per cycle, naming its PDs and channels, at its first channel.
29///
30/// # Examples
31///
32/// ```
33/// use fic::ast::RawAst;
34/// use fic::foreign::ForeignModules;
35/// use fic::parser::parse_system;
36/// use fic::wfcheck::check_wf2;
37///
38/// // The check reads the typed tree; the system's declarations type it,
39/// // whatever the programs do.
40/// let wf2 = |src: &str| {
41///     let system = parse_system(src).unwrap();
42///     // One program per protection domain, by position; empty `.fi`s here.
43///     let programs = system.protection_domains.iter()
44///         .map(|_| fic::parser::parse_program("").unwrap())
45///         .collect();
46///     let rawast = RawAst { system, programs };
47///     let (env, tenv) = fic::frontend::data_layer(&rawast).unwrap();
48///     let (rast, _) = fic::rast::build(&rawast, env, &mut ForeignModules::new()).unwrap();
49///     let (tast, _) = fic::tast::build(rast, tenv).unwrap();
50///     check_wf2(&tast.tenv)
51/// };
52/// assert!(wf2("ProtectionDomain A(10); ProtectionDomain B(20); Chan ab = A --> B;").is_ok());
53/// assert!(wf2("ProtectionDomain A(10); ProtectionDomain B(20); Chan ab = A <-> B;").is_err());
54/// ```
55pub fn check_wf2(tenv: &TyEnv) -> Result<(), Diagnostics> {
56    // `adj[r][s]`: the first channel on which `r` receives from `s`.
57    let mut adj: Vec<BTreeMap<usize, ChanId>> = vec![BTreeMap::new(); tenv.pds.len()];
58    for (id, ch) in tenv.chans.iter_enumerated() {
59        let (s, r) = (ch.sender.pd.index(), ch.receiver.pd.index());
60        adj[r].entry(s).or_insert(id);
61        if ch.kind == ChannelKind::AsyncBi {
62            adj[s].entry(r).or_insert(id);
63        }
64    }
65
66    let mut cycles = Vec::new();
67    for start in 0..adj.len() {
68        cycles_from(&adj, &mut vec![start], &mut Vec::new(), &mut cycles);
69    }
70
71    let pd = |i: usize| tenv.pds[Idx::new(i)].name.as_str();
72    let errors = cycles
73        .iter()
74        .map(|(pds, chans)| {
75            let path: Vec<&str> = pds.iter().map(|&i| pd(i)).collect();
76            let names: Vec<&str> = chans.iter().map(|&c| tenv.chans[c].name.as_str()).collect();
77            // TODO: highlight every channel once `Diagnostic` has secondary spans.
78            Diagnostic::at(
79                format!(
80                    "WF2 violation: channel dependency graph contains a cycle: {} → {} (via channel{}: {})",
81                    path.join(" → "),
82                    pd(pds[0]),
83                    if chans.len() == 1 { "" } else { "s" },
84                    names.join(", "),
85                ),
86                tenv.chans[chans[0]].span.clone(),
87                tenv.file.clone(),
88            )
89        })
90        .collect();
91    Diagnostics::finish(errors, ())
92}
93
94/// Extend `path` from its last PD, recording every edge back to `path[0]`
95/// and entering only PDs greater than it.
96fn cycles_from(
97    adj: &[BTreeMap<usize, ChanId>],
98    path: &mut Vec<usize>,
99    chans: &mut Vec<ChanId>,
100    cycles: &mut Vec<Cycle>,
101) {
102    let (start, current) = (path[0], path[path.len() - 1]);
103    for (&next, &chan) in &adj[current] {
104        if next == start {
105            let mut closed = chans.clone();
106            closed.push(chan);
107            cycles.push((path.clone(), closed));
108        } else if next > start && !path.contains(&next) {
109            path.push(next);
110            chans.push(chan);
111            cycles_from(adj, path, chans, cycles);
112            path.pop();
113            chans.pop();
114        }
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121    use crate::tast::env::built;
122
123    fn wf2(src: &str) -> Result<(), Diagnostics> {
124        let (tast, _) = built(src, &[]).expect("builds");
125        check_wf2(&tast.tenv)
126    }
127
128    #[test]
129    fn wf2_accepts_acyclic_graphs() {
130        for src in [
131            "ProtectionDomain A(10);",
132            "ProtectionDomain A(10); ProtectionDomain B(20);",
133            "ProtectionDomain A(10); ProtectionDomain B(20); ProtectionDomain C(30);
134             Chan ab = A --> B; Chan bc = B --> C;",
135            // D is isolated.
136            "ProtectionDomain A(10); ProtectionDomain B(20);
137             ProtectionDomain C(30); ProtectionDomain D(40);
138             Chan ab = A --> B; Chan bc = B --> C;",
139            "ProtectionDomain A(10); ProtectionDomain B(20); ProtectionDomain C(30);
140             Chan ab = A --> B; Chan ac = A --> C;",
141            "ProtectionDomain A(10); ProtectionDomain B(20); Sync Chan ab = A --> B;",
142            // Parallel channels are one edge.
143            "ProtectionDomain A(10); ProtectionDomain B(20);
144             Chan c1 = A --> B; Chan c2 = A --> B;",
145        ] {
146            assert!(wf2(src).is_ok(), "{src}");
147        }
148    }
149
150    #[test]
151    fn wf2_rejects_cycles() {
152        for src in [
153            "ProtectionDomain A(10); ProtectionDomain B(20); Chan ab = A <-> B;",
154            "ProtectionDomain A(10); ProtectionDomain B(20);
155             Chan ab = A --> B; Chan ba = B --> A;",
156            "ProtectionDomain A(10); ProtectionDomain B(20); ProtectionDomain C(30);
157             Chan ab = A --> B; Chan bc = B --> C; Chan ca = C --> A;",
158            // Mixed kinds; A outranks B so `resolve` accepts the sync channel.
159            "ProtectionDomain A(30); ProtectionDomain B(20);
160             Chan async_ab = A --> B; Sync Chan sync_ba = B --> A;",
161        ] {
162            assert!(wf2(src).is_err(), "{src}");
163        }
164    }
165
166    #[test]
167    fn error_message_names_pds_and_channel() {
168        let err = wf2("ProtectionDomain A(10); ProtectionDomain B(20);
169             Chan my_chan = A <-> B;")
170        .unwrap_err();
171        let msg = format!("{err}");
172        assert!(msg.contains('A'), "expected PD 'A' in message: {msg}");
173        assert!(msg.contains('B'), "expected PD 'B' in message: {msg}");
174        assert!(
175            msg.contains("my_chan"),
176            "expected channel name in message: {msg}"
177        );
178    }
179}