1use 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#[derive(Debug, Clone)]
13pub struct ConfigReport {
14 file: String,
15 source: String,
16 parse: ConfigParse,
17}
18
19#[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
29pub 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 #[must_use]
61 pub fn accepted(&self) -> bool {
62 self.parse.accepted()
63 }
64
65 #[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 #[must_use]
77 pub fn config(&self) -> Option<&ModelConfig> {
78 self.parse.config()
79 }
80
81 #[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 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 #[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}