1#![forbid(unsafe_code)]
37
38mod config;
39pub mod host_inputs;
40pub use dive_model::SymmetryLiveness;
42pub use host_inputs::HostAccess;
43mod publication;
44pub use publication::{
45 OriginalAstWriteReport, TranslationPublication, prepare_translation_file,
46 write_original_ast_file, write_translation_file,
47};
48mod rewrite;
49pub use rewrite::{
50 ChecksumPolicy, RewriteOptions, RewriteReport, RewriteRequest, rewrite_file, rewrite_source,
51};
52mod original_ast;
53mod translate;
54pub use dive_pluscal::FairnessOption as TranslationFairness;
56pub use original_ast::{OriginalAstReport, original_ast_file, original_ast_source};
57pub use translate::{
58 TRANSLATE_SCHEMA_VERSION, TranslationReport, TranslationRequest, translate_file,
59 translate_source,
60};
61
62pub mod debug;
63pub mod diagnostics;
64pub mod temporal;
65pub mod trace;
66
67pub use config::{ConfigReport, parse_config_file, parse_config_source};
68
69mod analyze;
70mod check;
71mod core_checkpoint;
72mod core_worker;
73pub use core_worker::{CoreWorker, prepare_core_worker};
74pub use dive_explore::distributed::{
76 Options as DistributedOptions, Usage as DistributedUsage, WorkerInfo,
77};
78mod core_ending;
79mod core_engine;
80#[cfg(test)]
81mod core_graph;
82mod core_modes;
83mod core_native_atoms;
84mod core_native_graph;
85mod core_native_values;
86mod core_random;
87mod core_sample;
88mod core_temporal;
89mod mode_budget;
90pub mod checkpoint {
92 pub use dive_runtime::checkpoint::{
93 Action, Counters, MAX_COUNTER, MAX_LEVEL, MAX_PAYLOAD_BYTES, MAX_STATE_BYTES, MAX_STATES,
94 Receipt, Request, Result, config_source_hash, owned_identity, owned_identity_seed_fp,
95 read_payload, write_payload,
96 };
97}
98mod dfid;
99mod dfid_admission;
100pub use dfid::{DFID_SCHEMA_VERSION, DfidReport, DfidRequest, dfid_file};
101mod simulate;
102pub use simulate::{SIMULATE_SCHEMA_VERSION, SimulateReport, SimulateRequest, simulate_file};
103
104pub use check::{
105 BudgetSetting, CHECK_SCHEMA_VERSION, CheckReport, CheckRequest, ExitConvention,
106 PeriodicSchedule, Store, TEMPORAL_CHECK_SCHEMA_VERSION, TemporalMode, check_file,
107 check_file_checkpoint, check_file_core_opts, check_file_tlc_inputs, exit,
108};
109pub use dive_stdlib::random::parse_seed;
111
112pub use analyze::{
113 ANALYZE_SCHEMA_VERSION, AnalyzeOptions, AnalyzeReport, analyze_file, analyze_source,
114};
115
116use dive_syntax::ast::Unit;
117use dive_syntax::diagnostics::line_col;
118use dive_syntax::{Diagnostic, Parse, Severity, SyntaxElement, SyntaxNode};
119use serde_json::{Value, json};
120use std::path::Path;
121
122pub const REPORT_SCHEMA_VERSION: u32 = 3;
135
136pub const PARSE_SCHEMA_VERSION: u32 = REPORT_SCHEMA_VERSION;
140
141#[derive(Debug, Clone)]
143pub struct ParseReport {
144 file: String,
145 source: String,
146 parse: Parse,
147 diagnostics: Vec<Diagnostic>,
148}
149
150#[derive(Debug)]
152#[non_exhaustive]
153pub enum ApiError {
154 BudgetStartup(dive_runtime::budget::StartError),
156 BudgetMeasurement(dive_runtime::budget::MeasurementError),
158 Io {
160 path: String,
162 error: std::io::Error,
164 },
165 Unsupported {
168 feature: String,
170 },
171 Rejected {
174 message: String,
176 },
177}
178
179impl std::fmt::Display for ApiError {
180 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
181 match self {
182 Self::BudgetStartup(error) => error.fmt(f),
183 Self::BudgetMeasurement(error) => error.fmt(f),
184 Self::Io { path, error } => write!(f, "cannot read {path}: {error}"),
185 Self::Unsupported { feature } => write!(f, "unsupported: {feature}"),
186 Self::Rejected { message } => f.write_str(message),
187 }
188 }
189}
190
191impl std::error::Error for ApiError {}
192
193#[must_use]
196pub fn parse_source(file: &str, source: &str) -> ParseReport {
197 let parse = dive_syntax::parse_module(source);
198 let mut diagnostics = parse.diagnostics().to_vec();
199 let base = Path::new(file)
200 .file_name()
201 .and_then(|n| n.to_str())
202 .unwrap_or(file);
203 diagnostics.extend(parse.check_file_name(base));
204 for diagnostic in &mut diagnostics {
205 diagnostic.help.get_or_insert_with(|| {
206 diagnostics::syntax_explanation(diagnostic.code)
207 .remediation
208 .to_owned()
209 });
210 }
211 ParseReport {
212 file: file.to_owned(),
213 source: source.to_owned(),
214 parse,
215 diagnostics,
216 }
217}
218
219pub fn parse_file(path: &Path) -> Result<ParseReport, ApiError> {
230 let shown = path.display().to_string();
231 let bytes = std::fs::read(path).map_err(|error| ApiError::Io {
232 path: shown.clone(),
233 error,
234 })?;
235 match String::from_utf8(bytes) {
236 Ok(source) => Ok(parse_source(&shown, &source)),
237 Err(e) => {
238 let valid_up_to = e.utf8_error().valid_up_to();
239 let source = String::from_utf8_lossy(e.as_bytes()).into_owned();
240 let mut report = parse_source(&shown, &source);
241 let at = dive_syntax::TextSize::try_from(valid_up_to).unwrap_or_default();
242 report.diagnostics.insert(
243 0,
244 Diagnostic {
245 code: dive_syntax::Code::InvalidUtf8,
246 severity: Severity::Warning,
247 message: "the file is not valid UTF-8; invalid bytes were read as U+FFFD"
248 .to_owned(),
249 range: dive_syntax::TextRange::empty(at),
250 help: Some("save the file as UTF-8".to_owned()),
251 },
252 );
253 Ok(report)
254 }
255 }
256}
257
258impl ParseReport {
259 #[must_use]
261 pub fn accepted(&self) -> bool {
262 !self.diagnostics.iter().any(Diagnostic::is_error)
263 }
264
265 #[must_use]
267 pub fn parse(&self) -> &Parse {
268 &self.parse
269 }
270
271 #[must_use]
273 pub fn diagnostics(&self) -> &[Diagnostic] {
274 &self.diagnostics
275 }
276
277 #[must_use]
279 pub fn modules(&self) -> Vec<String> {
280 let mut out = Vec::new();
281 let mut stack: Vec<dive_syntax::ast::Module> = self.parse.module().into_iter().collect();
282 while let Some(m) = stack.pop() {
283 out.extend(m.name());
284 let mut nested: Vec<_> = m
285 .units()
286 .filter_map(|u| match u {
287 Unit::Module(n) => Some(n),
288 _ => None,
289 })
290 .collect();
291 nested.reverse();
292 stack.extend(nested);
293 }
294 out
295 }
296
297 #[must_use]
300 pub fn render_human(&self) -> String {
301 use std::fmt::Write as _;
302 let mut s = String::new();
303 for d in &self.diagnostics {
304 let (line, col) = line_col(&self.source, d.range.start());
305 let sev = match d.severity {
306 Severity::Error => "error",
307 Severity::Warning => "warning",
308 };
309 let _ = writeln!(
311 s,
312 "{}:{line}:{col}: {sev}[{}]: {}",
313 self.file, d.code, d.message
314 );
315 if let Some(h) = &d.help {
316 let _ = writeln!(s, " help: {h}");
317 }
318 }
319 s
320 }
321
322 #[must_use]
340 pub fn to_json(&self, cst: bool) -> Value {
341 let diagnostics: Vec<Value> = self
342 .diagnostics
343 .iter()
344 .map(|d| {
345 let (line, column) = line_col(&self.source, d.range.start());
346 let (end_line, end_column) = line_col(&self.source, d.range.end());
347 json!({
348 "code": d.code.as_str(),
349 "severity": match d.severity {
350 Severity::Error => "error",
351 Severity::Warning => "warning",
352 },
353 "message": d.message,
354 "help": d.help,
355 "span": {
356 "start": u32::from(d.range.start()),
357 "end": u32::from(d.range.end()),
358 "line": line,
359 "column": column,
360 "end_line": end_line,
361 "end_column": end_column,
362 },
363 })
364 })
365 .collect();
366 let modules = self.modules();
367 let mut v = json!({
368 "schema_version": PARSE_SCHEMA_VERSION,
369 "command": "parse",
370 "file": self.file,
371 "accepted": self.accepted(),
372 "module": modules.first(),
373 "modules": modules,
374 "diagnostics": diagnostics,
375 });
376 if cst && let Some(obj) = v.as_object_mut() {
377 obj.insert("cst".to_owned(), cst_json(&self.parse.syntax()));
378 }
379 v
380 }
381}
382
383fn cst_json(root: &SyntaxNode) -> Value {
385 enum Frame {
387 Open(SyntaxNode, Vec<Value>, std::vec::IntoIter<SyntaxElement>),
388 }
389 let element = |kind: &str, r: dive_syntax::TextRange| -> serde_json::Map<String, Value> {
390 let mut m = serde_json::Map::new();
391 m.insert("kind".to_owned(), Value::from(kind));
392 m.insert("start".to_owned(), Value::from(u32::from(r.start())));
393 m.insert("end".to_owned(), Value::from(u32::from(r.end())));
394 m
395 };
396 let children_of = |n: &SyntaxNode| n.children_with_tokens().collect::<Vec<_>>().into_iter();
397 let mut stack = vec![Frame::Open(root.clone(), Vec::new(), children_of(root))];
398 loop {
399 let Some(Frame::Open(node, mut done, mut rest)) = stack.pop() else {
400 return Value::Null;
401 };
402 match rest.next() {
403 Some(SyntaxElement::Token(t)) => {
404 let mut m = element(t.kind().name(), t.text_range());
405 m.insert("text".to_owned(), Value::from(t.text()));
406 done.push(Value::Object(m));
407 stack.push(Frame::Open(node, done, rest));
408 }
409 Some(SyntaxElement::Node(n)) => {
410 let it = children_of(&n);
411 stack.push(Frame::Open(node, done, rest));
412 stack.push(Frame::Open(n, Vec::new(), it));
413 }
414 None => {
415 let mut m = element(node.kind().name(), node.text_range());
416 m.insert("children".to_owned(), Value::Array(done));
417 let v = Value::Object(m);
418 match stack.last_mut() {
419 Some(Frame::Open(_, parent_done, _)) => parent_done.push(v),
420 None => return v,
421 }
422 }
423 }
424 }
425}
426
427pub use dive_syntax;
429
430pub use dive_sema;
432
433pub use dive_eval::ActionComposition;
435pub use dive_runtime::SeenOptions;
437pub use dive_store::seen::Limits as SeenLimits;
439
440#[cfg(test)]
441mod tests {
442 use super::*;
443
444 #[test]
445 fn nested_modules_are_listed() {
446 let r = parse_source(
447 "A.tla",
448 "---- MODULE A ----\n---- MODULE B ----\n====\n---- MODULE C ----\n====\n====\n",
449 );
450 assert!(r.accepted());
451 assert_eq!(r.modules(), ["A", "B", "C"]);
452 }
453
454 #[test]
455 fn file_name_mismatch_is_an_error() {
456 let r = parse_source("dir/B.tla", "---- MODULE A ----\n====\n");
457 assert!(!r.accepted());
458 assert_eq!(r.diagnostics()[0].code.as_str(), "DIVE-S0006");
459 }
460
461 #[test]
462 fn invalid_utf8_is_read_like_sany() {
463 let dir = std::env::temp_dir().join(format!("dive-api-utf8-{}", std::process::id()));
464 let _ = std::fs::create_dir_all(&dir);
465 let path = dir.join("Latin.tla");
466 let bytes = b"---- MODULE Latin ----\n(* caf\xe9 *)\nx == 1\n====\n";
468 if let Err(e) = std::fs::write(&path, bytes) {
469 unreachable!("cannot write {}: {e}", path.display());
470 }
471 let r = match parse_file(&path) {
472 Ok(r) => r,
473 Err(e) => unreachable!("{e}"),
474 };
475 assert!(r.accepted());
476 assert_eq!(r.diagnostics()[0].code.as_str(), "DIVE-S0007");
477 assert!(!r.diagnostics()[0].is_error());
478 }
479
480 #[test]
481 fn json_has_schema_version_and_cst() {
482 let r = parse_source("M.tla", "---- MODULE M ----\nx == 1 + \n====\n");
483 let v = r.to_json(true);
484 assert_eq!(v["schema_version"], PARSE_SCHEMA_VERSION);
485 assert_eq!(v["accepted"], false);
486 assert_eq!(v["diagnostics"][0]["span"]["line"], 3);
487 assert_eq!(v["cst"]["kind"], "SOURCE_FILE");
488 assert!(r.render_human().contains("error[DIVE-S"));
489 }
490}