Skip to main content

dive_api/
config.rs

1//! Reading TLC model configuration (`.cfg`) files.
2
3use crate::ApiError;
4use dive_config::{
5    ConfigParse, ConfigValue, ConstantEntry, Diagnostic, ModelConfig, Name, Severity, Spanned,
6};
7use dive_syntax::diagnostics::line_col;
8use serde_json::{Map, Value, json};
9use std::path::Path;
10
11/// The outcome of reading one cfg file.
12#[derive(Debug, Clone)]
13pub struct ConfigReport {
14    file: String,
15    source: String,
16    parse: ConfigParse,
17}
18
19/// Reads cfg text. `file` names it in reports.
20#[must_use]
21pub fn parse_config_source(file: &str, source: &str) -> ConfigReport {
22    ConfigReport {
23        file: file.to_owned(),
24        source: source.to_owned(),
25        parse: dive_config::parse(source),
26    }
27}
28
29/// Reads and parses a cfg file, as TLC's `-config` does.
30///
31/// Malformed UTF-8 is read as U+FFFD, like TLC's reader, with a
32/// `DIVE-C0004` warning.
33///
34/// # Errors
35///
36/// [`ApiError::Io`] if the file cannot be read, and
37/// [`ApiError::Unsupported`] for a configuration embedded in a `.tla` file
38/// (TLC reads those through `MonolithSpecExtractor`; dive does not yet).
39pub fn parse_config_file(path: &Path) -> Result<ConfigReport, ApiError> {
40    let shown = path.display().to_string();
41    if path.extension().is_some_and(|e| e == "tla") {
42        return Err(ApiError::Unsupported {
43            feature: "configurations embedded in a .tla file (MonolithSpecExtractor)".to_owned(),
44        });
45    }
46    let bytes = std::fs::read(path).map_err(|error| ApiError::Io {
47        path: shown.clone(),
48        error,
49    })?;
50    let (source, parse) = dive_config::parse_bytes(&bytes);
51    Ok(ConfigReport {
52        file: shown,
53        source,
54        parse,
55    })
56}
57
58impl ConfigReport {
59    /// Whether TLC's cfg reader accepts the file.
60    #[must_use]
61    pub fn accepted(&self) -> bool {
62        self.parse.accepted()
63    }
64
65    /// The parse result.
66    #[must_use]
67    pub fn parse(&self) -> &ConfigParse {
68        &self.parse
69    }
70
71    pub(crate) fn source_bytes(&self) -> &[u8] {
72        self.source.as_bytes()
73    }
74
75    /// The configuration, if accepted.
76    #[must_use]
77    pub fn config(&self) -> Option<&ModelConfig> {
78        self.parse.config()
79    }
80
81    /// Diagnostics, one per line, like `file:3:7: error[DIVE-C0013]: message`,
82    /// with TLC's equivalent report after each error.
83    #[must_use]
84    pub fn render_human(&self) -> String {
85        use std::fmt::Write as _;
86        let mut s = String::new();
87        for d in self.parse.diagnostics() {
88            let (line, col) = line_col(&self.source, d.range.start());
89            let sev = match d.severity {
90                Severity::Error => "error",
91                Severity::Warning => "warning",
92            };
93            // Writing to a String cannot fail.
94            let _ = writeln!(
95                s,
96                "{}:{line}:{col}: {sev}[{}]: {}",
97                self.file, d.code, d.message
98            );
99            if let Some(h) = &d.help {
100                let _ = writeln!(s, "  help: {h}");
101            }
102            if let Some(t) = d.tlc {
103                let _ = writeln!(
104                    s,
105                    "  tlc: {} ({}), exit {}{}",
106                    t.name,
107                    t.code,
108                    t.exit_code,
109                    t.line.map(|l| format!(", line {l}")).unwrap_or_default()
110                );
111            }
112        }
113        s
114    }
115
116    /// The report as JSON (the `config` object of `dive parse --output json`).
117    ///
118    /// ```text
119    /// { "file", "accepted",
120    ///   "diagnostics": [ { "code", "severity", "message", "help", "span",
121    ///                      "tlc": { "code", "name", "exit_code", "line", "detail" } | null } ],
122    ///   "model": { "init", "next", "specification", "view", "symmetry", "alias",
123    ///              "periodic", "rl_reward",            // name objects or null
124    ///              "check_deadlock": bool | null, "checks_deadlock": bool,
125    ///              "invariants", "properties", "constraints", "action_constraints",
126    ///              "postconditions", "possible",       // arrays of name objects
127    ///              "constants": [ { "kind": "assignment", "name", "module", "args", "value" }
128    ///                           | { "kind": "substitution", "name", "module", "target" } ],
129    ///              "model_values": [ "..." ] } | null }
130    /// ```
131    ///
132    /// A name object is `{ "text", "span" }`; a value is `{ "int" }`,
133    /// `{ "string" }`, `{ "bool" }`, `{ "model_value" }` or `{ "set": [...] }`,
134    /// each with a `span`.
135    /// This is a nested configuration fragment. Its wire contract inherits
136    /// the enclosing `parse` or `check` report's version; it is not an
137    /// independently versioned operation envelope.
138    #[must_use]
139    pub fn to_json(&self) -> Value {
140        let diagnostics: Vec<Value> = self
141            .parse
142            .diagnostics()
143            .iter()
144            .map(|d| self.diagnostic_json(d))
145            .collect();
146        json!({
147            "file": self.file,
148            "accepted": self.accepted(),
149            "diagnostics": diagnostics,
150            "model": self.parse.config().map(|c| self.model_json(c)),
151        })
152    }
153
154    fn span(&self, r: dive_config::TextRange) -> Value {
155        let (line, column) = line_col(&self.source, r.start());
156        let (end_line, end_column) = line_col(&self.source, r.end());
157        json!({
158            "start": u32::from(r.start()),
159            "end": u32::from(r.end()),
160            "line": line,
161            "column": column,
162            "end_line": end_line,
163            "end_column": end_column,
164        })
165    }
166
167    fn diagnostic_json(&self, d: &Diagnostic) -> Value {
168        json!({
169            "code": d.code.as_str(),
170            "severity": match d.severity {
171                Severity::Error => "error",
172                Severity::Warning => "warning",
173            },
174            "message": d.message,
175            "help": d.help,
176            "span": self.span(d.range),
177            "tlc": d.tlc.map(|t| json!({
178                "code": t.code,
179                "name": t.name,
180                "exit_code": t.exit_code,
181                "line": t.line,
182                "detail": t.detail,
183            })),
184        })
185    }
186
187    fn name_json(&self, n: &Name) -> Value {
188        json!({ "text": n.text, "span": self.span(n.span) })
189    }
190
191    fn value_json(&self, v: &Spanned<ConfigValue>) -> Value {
192        let mut m = Map::new();
193        match &v.value {
194            ConfigValue::Int(i) => m.insert("int".to_owned(), json!(i)),
195            ConfigValue::String(s) => m.insert("string".to_owned(), json!(s)),
196            ConfigValue::Bool(b) => m.insert("bool".to_owned(), json!(b)),
197            ConfigValue::ModelValue(s) => m.insert("model_value".to_owned(), json!(s)),
198            ConfigValue::Set(items) => m.insert(
199                "set".to_owned(),
200                Value::Array(items.iter().map(|i| self.value_json(i)).collect()),
201            ),
202        };
203        m.insert("span".to_owned(), self.span(v.span));
204        Value::Object(m)
205    }
206
207    fn model_json(&self, c: &ModelConfig) -> Value {
208        let one = |n: &Option<Name>| n.as_ref().map(|n| self.name_json(n));
209        let list = |l: &[Name]| l.iter().map(|n| self.name_json(n)).collect::<Vec<_>>();
210        let constants: Vec<Value> = c
211            .constants
212            .iter()
213            .map(|e| match e {
214                ConstantEntry::Assignment {
215                    name,
216                    args,
217                    module,
218                    value,
219                } => json!({
220                    "kind": "assignment",
221                    "name": self.name_json(name),
222                    "module": module.as_ref().map(|m| self.name_json(m)),
223                    "args": args.iter().map(|a| self.value_json(a)).collect::<Vec<_>>(),
224                    "value": self.value_json(value),
225                }),
226                ConstantEntry::Substitution {
227                    name,
228                    module,
229                    target,
230                } => json!({
231                    "kind": "substitution",
232                    "name": self.name_json(name),
233                    "module": module.as_ref().map(|m| self.name_json(m)),
234                    "target": self.name_json(target),
235                }),
236            })
237            .collect();
238        json!({
239            "init": one(&c.init),
240            "next": one(&c.next),
241            "specification": one(&c.specification),
242            "view": one(&c.view),
243            "symmetry": one(&c.symmetry),
244            "alias": one(&c.alias),
245            "periodic": one(&c.periodic),
246            "rl_reward": one(&c.rl_reward),
247            "check_deadlock": c.check_deadlock.as_ref().map(|d| d.value),
248            "checks_deadlock": c.checks_deadlock(),
249            "invariants": list(&c.invariants),
250            "properties": list(&c.properties),
251            "constraints": list(&c.constraints),
252            "action_constraints": list(&c.action_constraints),
253            "postconditions": list(&c.postconditions),
254            "possible": list(&c.possible),
255            "constants": constants,
256            "model_values": c.model_values,
257        })
258    }
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264
265    #[test]
266    fn accepted_config_json() {
267        let r = parse_config_source(
268            "M.cfg",
269            "CONSTANT N = 3 S = {a, b}\nT <- [Mod] U\nINIT Init\nNEXT Next\nINVARIANT Inv\n",
270        );
271        assert!(r.accepted());
272        let v = r.to_json();
273        assert_eq!(v["model"]["init"]["text"], "Init");
274        assert_eq!(v["model"]["invariants"][0]["text"], "Inv");
275        assert_eq!(v["model"]["checks_deadlock"], true);
276        assert_eq!(
277            v["model"]["constants"][1]["value"]["set"][1]["model_value"],
278            "b"
279        );
280        assert_eq!(v["model"]["constants"][2]["module"]["text"], "Mod");
281        assert_eq!(v["model"]["model_values"], json!(["a", "b"]));
282    }
283
284    #[test]
285    fn rejected_config_reports_tlc_equivalent() {
286        let r = parse_config_source("M.cfg", "INIT Init\nINVARIANT Inv ;\n");
287        assert!(!r.accepted());
288        let v = r.to_json();
289        assert_eq!(v["model"], Value::Null);
290        assert_eq!(v["diagnostics"][0]["code"], "DIVE-C0001");
291        assert_eq!(v["diagnostics"][0]["tlc"]["code"], 5007);
292        assert_eq!(v["diagnostics"][0]["tlc"]["exit_code"], 151);
293        assert_eq!(v["diagnostics"][0]["span"]["line"], 2);
294        assert!(
295            r.render_human()
296                .contains("CFG_LEXICAL_ERROR (5007), exit 151, line 2")
297        );
298    }
299
300    #[test]
301    fn tla_configs_are_unsupported() {
302        let e = parse_config_file(Path::new("Spec.tla"));
303        assert!(matches!(e, Err(ApiError::Unsupported { .. })));
304    }
305}