#![forbid(unsafe_code)]
mod config;
pub mod host_inputs;
pub use dive_model::SymmetryLiveness;
pub use host_inputs::HostAccess;
mod publication;
pub use publication::{
OriginalAstWriteReport, TranslationPublication, prepare_translation_file,
write_original_ast_file, write_translation_file,
};
mod rewrite;
pub use rewrite::{
ChecksumPolicy, RewriteOptions, RewriteReport, RewriteRequest, rewrite_file, rewrite_source,
};
mod original_ast;
mod translate;
pub use dive_pluscal::FairnessOption as TranslationFairness;
pub use original_ast::{OriginalAstReport, original_ast_file, original_ast_source};
pub use translate::{
TRANSLATE_SCHEMA_VERSION, TranslationReport, TranslationRequest, translate_file,
translate_source,
};
pub mod debug;
pub mod diagnostics;
pub mod temporal;
pub mod trace;
pub use config::{ConfigReport, parse_config_file, parse_config_source};
mod analyze;
mod check;
mod core_checkpoint;
mod core_worker;
pub use core_worker::{CoreWorker, prepare_core_worker};
pub use dive_explore::distributed::{
Options as DistributedOptions, Usage as DistributedUsage, WorkerInfo,
};
mod core_ending;
mod core_engine;
#[cfg(test)]
mod core_graph;
mod core_modes;
mod core_native_atoms;
mod core_native_graph;
mod core_native_values;
mod core_random;
mod core_sample;
mod core_temporal;
mod mode_budget;
pub mod checkpoint {
pub use dive_runtime::checkpoint::{
Action, Counters, MAX_COUNTER, MAX_LEVEL, MAX_PAYLOAD_BYTES, MAX_STATE_BYTES, MAX_STATES,
Receipt, Request, Result, config_source_hash, owned_identity, owned_identity_seed_fp,
read_payload, write_payload,
};
}
mod dfid;
mod dfid_admission;
pub use dfid::{DFID_SCHEMA_VERSION, DfidReport, DfidRequest, dfid_file};
mod simulate;
pub use simulate::{SIMULATE_SCHEMA_VERSION, SimulateReport, SimulateRequest, simulate_file};
pub use check::{
BudgetSetting, CHECK_SCHEMA_VERSION, CheckReport, CheckRequest, ExitConvention,
PeriodicSchedule, Store, TEMPORAL_CHECK_SCHEMA_VERSION, TemporalMode, check_file,
check_file_checkpoint, check_file_core_opts, check_file_tlc_inputs, exit,
};
pub use dive_stdlib::random::parse_seed;
pub use analyze::{
ANALYZE_SCHEMA_VERSION, AnalyzeOptions, AnalyzeReport, analyze_file, analyze_source,
};
use dive_syntax::ast::Unit;
use dive_syntax::diagnostics::line_col;
use dive_syntax::{Diagnostic, Parse, Severity, SyntaxElement, SyntaxNode};
use serde_json::{Value, json};
use std::path::Path;
pub const REPORT_SCHEMA_VERSION: u32 = 3;
pub const PARSE_SCHEMA_VERSION: u32 = REPORT_SCHEMA_VERSION;
#[derive(Debug, Clone)]
pub struct ParseReport {
file: String,
source: String,
parse: Parse,
diagnostics: Vec<Diagnostic>,
}
#[derive(Debug)]
#[non_exhaustive]
pub enum ApiError {
BudgetStartup(dive_runtime::budget::StartError),
BudgetMeasurement(dive_runtime::budget::MeasurementError),
Io {
path: String,
error: std::io::Error,
},
Unsupported {
feature: String,
},
Rejected {
message: String,
},
}
impl std::fmt::Display for ApiError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::BudgetStartup(error) => error.fmt(f),
Self::BudgetMeasurement(error) => error.fmt(f),
Self::Io { path, error } => write!(f, "cannot read {path}: {error}"),
Self::Unsupported { feature } => write!(f, "unsupported: {feature}"),
Self::Rejected { message } => f.write_str(message),
}
}
}
impl std::error::Error for ApiError {}
#[must_use]
pub fn parse_source(file: &str, source: &str) -> ParseReport {
let parse = dive_syntax::parse_module(source);
let mut diagnostics = parse.diagnostics().to_vec();
let base = Path::new(file)
.file_name()
.and_then(|n| n.to_str())
.unwrap_or(file);
diagnostics.extend(parse.check_file_name(base));
for diagnostic in &mut diagnostics {
diagnostic.help.get_or_insert_with(|| {
diagnostics::syntax_explanation(diagnostic.code)
.remediation
.to_owned()
});
}
ParseReport {
file: file.to_owned(),
source: source.to_owned(),
parse,
diagnostics,
}
}
pub fn parse_file(path: &Path) -> Result<ParseReport, ApiError> {
let shown = path.display().to_string();
let bytes = std::fs::read(path).map_err(|error| ApiError::Io {
path: shown.clone(),
error,
})?;
match String::from_utf8(bytes) {
Ok(source) => Ok(parse_source(&shown, &source)),
Err(e) => {
let valid_up_to = e.utf8_error().valid_up_to();
let source = String::from_utf8_lossy(e.as_bytes()).into_owned();
let mut report = parse_source(&shown, &source);
let at = dive_syntax::TextSize::try_from(valid_up_to).unwrap_or_default();
report.diagnostics.insert(
0,
Diagnostic {
code: dive_syntax::Code::InvalidUtf8,
severity: Severity::Warning,
message: "the file is not valid UTF-8; invalid bytes were read as U+FFFD"
.to_owned(),
range: dive_syntax::TextRange::empty(at),
help: Some("save the file as UTF-8".to_owned()),
},
);
Ok(report)
}
}
}
impl ParseReport {
#[must_use]
pub fn accepted(&self) -> bool {
!self.diagnostics.iter().any(Diagnostic::is_error)
}
#[must_use]
pub fn parse(&self) -> &Parse {
&self.parse
}
#[must_use]
pub fn diagnostics(&self) -> &[Diagnostic] {
&self.diagnostics
}
#[must_use]
pub fn modules(&self) -> Vec<String> {
let mut out = Vec::new();
let mut stack: Vec<dive_syntax::ast::Module> = self.parse.module().into_iter().collect();
while let Some(m) = stack.pop() {
out.extend(m.name());
let mut nested: Vec<_> = m
.units()
.filter_map(|u| match u {
Unit::Module(n) => Some(n),
_ => None,
})
.collect();
nested.reverse();
stack.extend(nested);
}
out
}
#[must_use]
pub fn render_human(&self) -> String {
use std::fmt::Write as _;
let mut s = String::new();
for d in &self.diagnostics {
let (line, col) = line_col(&self.source, d.range.start());
let sev = match d.severity {
Severity::Error => "error",
Severity::Warning => "warning",
};
let _ = writeln!(
s,
"{}:{line}:{col}: {sev}[{}]: {}",
self.file, d.code, d.message
);
if let Some(h) = &d.help {
let _ = writeln!(s, " help: {h}");
}
}
s
}
#[must_use]
pub fn to_json(&self, cst: bool) -> Value {
let diagnostics: Vec<Value> = self
.diagnostics
.iter()
.map(|d| {
let (line, column) = line_col(&self.source, d.range.start());
let (end_line, end_column) = line_col(&self.source, d.range.end());
json!({
"code": d.code.as_str(),
"severity": match d.severity {
Severity::Error => "error",
Severity::Warning => "warning",
},
"message": d.message,
"help": d.help,
"span": {
"start": u32::from(d.range.start()),
"end": u32::from(d.range.end()),
"line": line,
"column": column,
"end_line": end_line,
"end_column": end_column,
},
})
})
.collect();
let modules = self.modules();
let mut v = json!({
"schema_version": PARSE_SCHEMA_VERSION,
"command": "parse",
"file": self.file,
"accepted": self.accepted(),
"module": modules.first(),
"modules": modules,
"diagnostics": diagnostics,
});
if cst && let Some(obj) = v.as_object_mut() {
obj.insert("cst".to_owned(), cst_json(&self.parse.syntax()));
}
v
}
}
fn cst_json(root: &SyntaxNode) -> Value {
enum Frame {
Open(SyntaxNode, Vec<Value>, std::vec::IntoIter<SyntaxElement>),
}
let element = |kind: &str, r: dive_syntax::TextRange| -> serde_json::Map<String, Value> {
let mut m = serde_json::Map::new();
m.insert("kind".to_owned(), Value::from(kind));
m.insert("start".to_owned(), Value::from(u32::from(r.start())));
m.insert("end".to_owned(), Value::from(u32::from(r.end())));
m
};
let children_of = |n: &SyntaxNode| n.children_with_tokens().collect::<Vec<_>>().into_iter();
let mut stack = vec![Frame::Open(root.clone(), Vec::new(), children_of(root))];
loop {
let Some(Frame::Open(node, mut done, mut rest)) = stack.pop() else {
return Value::Null;
};
match rest.next() {
Some(SyntaxElement::Token(t)) => {
let mut m = element(t.kind().name(), t.text_range());
m.insert("text".to_owned(), Value::from(t.text()));
done.push(Value::Object(m));
stack.push(Frame::Open(node, done, rest));
}
Some(SyntaxElement::Node(n)) => {
let it = children_of(&n);
stack.push(Frame::Open(node, done, rest));
stack.push(Frame::Open(n, Vec::new(), it));
}
None => {
let mut m = element(node.kind().name(), node.text_range());
m.insert("children".to_owned(), Value::Array(done));
let v = Value::Object(m);
match stack.last_mut() {
Some(Frame::Open(_, parent_done, _)) => parent_done.push(v),
None => return v,
}
}
}
}
}
pub use dive_syntax;
pub use dive_sema;
pub use dive_eval::ActionComposition;
pub use dive_runtime::SeenOptions;
pub use dive_store::seen::Limits as SeenLimits;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn nested_modules_are_listed() {
let r = parse_source(
"A.tla",
"---- MODULE A ----\n---- MODULE B ----\n====\n---- MODULE C ----\n====\n====\n",
);
assert!(r.accepted());
assert_eq!(r.modules(), ["A", "B", "C"]);
}
#[test]
fn file_name_mismatch_is_an_error() {
let r = parse_source("dir/B.tla", "---- MODULE A ----\n====\n");
assert!(!r.accepted());
assert_eq!(r.diagnostics()[0].code.as_str(), "DIVE-S0006");
}
#[test]
fn invalid_utf8_is_read_like_sany() {
let dir = std::env::temp_dir().join(format!("dive-api-utf8-{}", std::process::id()));
let _ = std::fs::create_dir_all(&dir);
let path = dir.join("Latin.tla");
let bytes = b"---- MODULE Latin ----\n(* caf\xe9 *)\nx == 1\n====\n";
if let Err(e) = std::fs::write(&path, bytes) {
unreachable!("cannot write {}: {e}", path.display());
}
let r = match parse_file(&path) {
Ok(r) => r,
Err(e) => unreachable!("{e}"),
};
assert!(r.accepted());
assert_eq!(r.diagnostics()[0].code.as_str(), "DIVE-S0007");
assert!(!r.diagnostics()[0].is_error());
}
#[test]
fn json_has_schema_version_and_cst() {
let r = parse_source("M.tla", "---- MODULE M ----\nx == 1 + \n====\n");
let v = r.to_json(true);
assert_eq!(v["schema_version"], PARSE_SCHEMA_VERSION);
assert_eq!(v["accepted"], false);
assert_eq!(v["diagnostics"][0]["span"]["line"], 3);
assert_eq!(v["cst"]["kind"], "SOURCE_FILE");
assert!(r.render_human().contains("error[DIVE-S"));
}
}