Skip to main content

dive_api/
lib.rs

1//! `dive-api`: the embeddable library API and `cargo test` integration.
2//!
3//! It exposes everything the `dive` command line does as plain Rust calls,
4//! each returning a typed report with a versioned JSON form
5//! ([`REPORT_SCHEMA_VERSION`]):
6//!
7//! - **Parsing** TLA+ source ([`parse_source`], [`parse_file`]) into a lossless
8//!   syntax tree, with SANY's syntax errors.
9//! - **Model configurations** in TLC's `.cfg` format ([`parse_config_file`],
10//!   [`parse_config_source`]).
11//! - **Semantic analysis** equivalent to SANY ([`analyze_file`],
12//!   [`analyze_source`]).
13//! - **PlusCal** translation and checksum rewriting ([`translate_file`],
14//!   [`translate_source`], [`rewrite_file`]).
15//! - **Model checking** of safety and temporal properties ([`check_file`] with a
16//!   [`CheckRequest`], returning a [`CheckReport`]), including run budgets,
17//!   checkpoints ([`checkpoint`]) and several workers.
18//! - **Simulation** with a seed ([`simulate_file`]) and depth-first iterative
19//!   deepening ([`dfid_file`]).
20//! - **Trace validation**: checking a counterexample against the
21//!   specification with the independent validator ([`trace`]), and temporal
22//!   checking on its own ([`temporal`]).
23//!
24//! Anything dive does not implement exactly is reported as
25//! [`ApiError::Unsupported`], naming the feature, rather than approximated.
26//!
27//! # Example
28//!
29//! ```
30//! let report = dive_api::parse_source("Spec.tla", "---- MODULE Spec ----\nx == 1\n====\n");
31//! assert!(report.accepted());
32//! assert_eq!(report.modules(), ["Spec"]);
33//! let json = report.to_json(false);
34//! assert_eq!(json["schema_version"], dive_api::PARSE_SCHEMA_VERSION);
35//! ```
36#![forbid(unsafe_code)]
37
38mod config;
39pub mod host_inputs;
40/// Shared whole-run policy for symmetry combined with temporal properties.
41pub 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;
54/// Native PlusCal fairness selection, including pinned translator option spellings.
55pub 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};
74/// Authenticated native distributed pure-safety options and actual work facts.
75pub 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;
90/// Native safety checkpoint request and format API.
91pub 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};
109/// Parses a seed as TLC's `-seed` does (`dive check --seed`).
110pub 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
122/// Version of every public operation's JSON report.
123///
124/// Reports use `command` to identify the operation; check reports also carry
125/// `check_kind` to distinguish safety and temporal report families. Neither
126/// discriminator establishes execution or proof. The native `dive-trace`
127/// payload has its own independent format version.
128///
129/// Incompatible field, type or outcome changes require a new version, a
130/// CHANGELOG entry and advance notice to known consumers. Optional fields and
131/// diagnostic codes may be added; readers must reject unknown outcomes and
132/// versions. The compatibility policy is in the
133/// [reports and errors guide](https://github.com/Chelis-Lang/dive/blob/main/docs/user/reports-and-errors.md).
134pub const REPORT_SCHEMA_VERSION: u32 = 3;
135
136/// Version of the JSON document produced by [`ParseReport::to_json`].
137///
138/// Bump it on any incompatible change to the document's shape.
139pub const PARSE_SCHEMA_VERSION: u32 = REPORT_SCHEMA_VERSION;
140
141/// The outcome of parsing one file.
142#[derive(Debug, Clone)]
143pub struct ParseReport {
144    file: String,
145    source: String,
146    parse: Parse,
147    diagnostics: Vec<Diagnostic>,
148}
149
150/// Errors from the API that are not diagnostics about the source.
151#[derive(Debug)]
152#[non_exhaustive]
153pub enum ApiError {
154    /// A requested run budget could not be enforced; no check ran.
155    BudgetStartup(dive_runtime::budget::StartError),
156    /// Required memory observation failed; no verdict is produced.
157    BudgetMeasurement(dive_runtime::budget::MeasurementError),
158    /// The file could not be read.
159    Io {
160        /// The file.
161        path: String,
162        /// The underlying error.
163        error: std::io::Error,
164    },
165    /// The request needs a feature dive does not implement yet. No result
166    /// is produced (soundness contract rule 3).
167    Unsupported {
168        /// The feature, named for the user.
169        feature: String,
170    },
171    /// The input is rejected: the specification or configuration has
172    /// errors, or the model cannot be bound (TLC's error).
173    Rejected {
174        /// What is wrong.
175        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/// Parses TLA+ source text. `file` names the source in reports and is used
194/// for SANY's check that the module name matches the file name.
195#[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
219/// Reads and parses a TLA+ file.
220///
221/// Like SANY, which reads files as UTF-8 and replaces malformed bytes, a file
222/// that is not valid UTF-8 is decoded with U+FFFD replacement characters and
223/// parsed anyway, with a `DIVE-S0007` warning. The CST is then lossless with
224/// respect to the decoded text.
225///
226/// # Errors
227///
228/// [`ApiError`] if the file cannot be read.
229pub 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    /// Whether SANY would accept the file (no error diagnostics).
260    #[must_use]
261    pub fn accepted(&self) -> bool {
262        !self.diagnostics.iter().any(Diagnostic::is_error)
263    }
264
265    /// The parse result.
266    #[must_use]
267    pub fn parse(&self) -> &Parse {
268        &self.parse
269    }
270
271    /// All diagnostics, including the file-name check.
272    #[must_use]
273    pub fn diagnostics(&self) -> &[Diagnostic] {
274        &self.diagnostics
275    }
276
277    /// Names of the top-level module and every nested module, in order.
278    #[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    /// The diagnostics in a human-readable form, one per line, like
298    /// `file:3:7: error[DIVE-S0012]: message`.
299    #[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            // Writing to a String cannot fail.
310            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    /// The versioned JSON report. With `cst`, the whole concrete syntax tree
323    /// is included under `"cst"`.
324    ///
325    /// Shape (schema version 3):
326    ///
327    /// ```text
328    /// { "schema_version": 3, "command": "parse", "file": "...",
329    ///   "accepted": bool, "module": "Name" | null, "modules": ["Name", ...],
330    ///   "diagnostics": [ { "code", "severity", "message", "help",
331    ///                      "span": { "start", "end", "line", "column",
332    ///                                "end_line", "end_column" } } ],
333    ///   "cst": { "kind", "start", "end", "children" | "text" }   // optional
334    /// }
335    /// ```
336    ///
337    /// Offsets are bytes; lines and columns are 1-based, columns count
338    /// Unicode scalar values.
339    #[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
383/// The CST as JSON: nodes have `children`, tokens have `text`.
384fn cst_json(root: &SyntaxNode) -> Value {
385    // Iterative, so deep trees cannot overflow the stack.
386    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
427/// Re-exported so API users can work with the tree directly.
428pub use dive_syntax;
429
430/// Re-exported so API users can work with the semantic model directly.
431pub use dive_sema;
432
433/// Action composition modes (`--action-composition`).
434pub use dive_eval::ActionComposition;
435/// Bounded transient disk seen-state safety options.
436pub use dive_runtime::SeenOptions;
437/// Limits for full disk keys, entries, probes and collision summaries.
438pub 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        // `\xe9` (Latin-1 e-acute) inside a comment: SANY reads it as U+FFFD.
467        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}