use serde::{Serialize, Serializer, ser::SerializeMap as _};
use spock_engine::{
Ending, Outcome, Report, State, Value,
trace::{self, Difference, Matched, Miss, Why},
};
use spock_ir::{Field, Program, TypeDefKind, positional};
use spock_report::show;
use spock_smt::{
DecodedState, Failure, ObligationKind, ProveOutcome, ProveReport, SymbolicOutcome,
SymbolicReport, UnknownObligation,
};
#[derive(Serialize)]
pub struct Location {
pub file: String,
pub line: usize,
pub column: usize,
}
#[derive(Serialize)]
struct Json<'a> {
version: u32,
spec: &'a str,
model: Option<&'a str>,
outcome: Kind<'a>,
distinct: u64,
generated: u64,
depth: u32,
seconds: f64,
unchecked: &'a [String],
trace: Vec<Step<'a>>,
#[serde(skip_serializing_if = "Option::is_none")]
back_to: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
back_step: Option<BackStep<'a>>,
}
#[derive(Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum Kind<'a> {
Ok,
Assumption {
name: &'a str,
},
Invariant {
name: &'a str,
},
StepProperty {
name: &'a str,
},
Property {
name: &'a str,
},
Deadlock,
Error {
message: &'a str,
location: Option<Location>,
},
}
pub fn report(
spec: &str,
program: &Program,
report: &Report,
location: Option<Location>,
) -> String {
let outcome = match &report.outcome {
Outcome::Ok => Kind::Ok,
Outcome::AssumptionViolated { name } => Kind::Assumption { name },
Outcome::InvariantViolated { name, .. } => Kind::Invariant { name },
Outcome::PropertyViolated { name, .. } => Kind::StepProperty { name },
Outcome::TemporalViolated { name, .. } => Kind::Property { name },
Outcome::Deadlock { .. } => Kind::Deadlock,
Outcome::Error { message, .. } => Kind::Error { message, location },
};
let (back_to, back_step) = match &report.outcome {
Outcome::TemporalViolated { trace, ending, .. } => {
let step = match ending {
Ending::Back { step, .. } => Some(BackStep { program, state: step }),
Ending::Prefix | Ending::Stutters => None,
};
(ending.back_to(trace.len()), step)
}
_ => (None, None),
};
let json = Json {
version: 1,
spec,
model: Some(&program.model.name),
outcome,
distinct: report.distinct,
generated: report.generated,
depth: report.depth,
seconds: report.elapsed.as_secs_f64(),
unchecked: &report.unchecked,
trace: report.outcome.trace().iter().map(|state| Step { program, state }).collect(),
back_to,
back_step,
};
to_string(&json)
}
fn to_string(json: &impl Serialize) -> String {
use std::io::IsTerminal as _;
let text = if std::io::stdout().is_terminal() {
serde_json::to_string_pretty(json)
} else {
serde_json::to_string(json)
};
text.expect("a report is JSON")
}
pub fn spec_error(
spec: &str,
model: Option<&str>,
message: &str,
location: Option<Location>,
) -> String {
let json = Json {
version: 1,
spec,
model,
outcome: Kind::Error { message, location },
distinct: 0,
generated: 0,
depth: 0,
seconds: 0.0,
unchecked: &[],
trace: Vec::new(),
back_to: None,
back_step: None,
};
to_string(&json)
}
struct BackStep<'a> {
program: &'a Program,
state: &'a State,
}
impl Serialize for BackStep<'_> {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
let program = self.program;
let action = self.state.action.map(|id| program.actions[id.index()].name.as_str());
let args: Vec<JsonValue> = each(program, &self.state.args).collect();
let mut map = s.serialize_map(Some(2))?;
map.serialize_entry("action", &action)?;
map.serialize_entry("args", &args)?;
map.end()
}
}
struct Step<'a> {
program: &'a Program,
state: &'a State,
}
fn decoded_state(s: &DecodedState) -> State {
State { action: s.action, args: s.args.clone(), fields: s.fields.clone() }
}
pub fn symbolic_report(
spec: &str,
program: &Program,
report: &SymbolicReport,
location: Option<Location>,
) -> String {
#[derive(Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum SymKind<'a> {
Ok,
Assumption { name: &'a str },
Invariant { name: &'a str },
StepProperty { name: &'a str },
Unknown { depth: usize, reason: &'a str },
Error { message: &'a str, location: Option<Location> },
}
#[derive(Serialize)]
struct SymJson<'a> {
version: u32,
mode: &'static str,
spec: &'a str,
model: &'a str,
outcome: SymKind<'a>,
depth_checked: usize,
seconds: f64,
unchecked: Vec<String>,
trace: Vec<Step<'a>>,
}
let (outcome, states): (SymKind<'_>, Vec<State>) = match &report.outcome {
SymbolicOutcome::Ok => (SymKind::Ok, Vec::new()),
SymbolicOutcome::AssumptionViolated { name } => (SymKind::Assumption { name }, Vec::new()),
SymbolicOutcome::InvariantViolated { name, trace } => {
(SymKind::Invariant { name }, trace.iter().map(decoded_state).collect())
}
SymbolicOutcome::PropertyViolated { name, trace } => {
(SymKind::StepProperty { name }, trace.iter().map(decoded_state).collect())
}
SymbolicOutcome::Unknown { depth, reason } => {
(SymKind::Unknown { depth: *depth, reason }, Vec::new())
}
SymbolicOutcome::Error { message, trace, .. } => {
(SymKind::Error { message, location }, trace.iter().map(decoded_state).collect())
}
};
let trace = states.iter().map(|state| Step { program, state }).collect();
to_string(&SymJson {
version: 1,
mode: "symbolic",
spec,
model: &program.model.name,
outcome,
depth_checked: report.depth_checked,
seconds: report.elapsed.as_secs_f64(),
unchecked: spock_report::smt_unchecked(program),
trace,
})
}
#[derive(Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum ProveKind<'a> {
Proved,
Failed,
Unknown,
Error { message: &'a str, location: Option<Location> },
}
#[derive(Serialize)]
struct ProveJson<'a> {
version: u32,
spec: &'a str,
model: Option<&'a str>,
outcome: ProveKind<'a>,
obligations: usize,
proved: usize,
failed: usize,
unknown: usize,
seconds: f64,
unchecked: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
failures: Vec<JsonFailure<'a>>,
#[serde(skip_serializing_if = "Vec::is_empty")]
unknowns: Vec<JsonUnknown<'a>>,
}
#[derive(Serialize)]
struct JsonFailure<'a> {
kind: &'static str,
label: &'a str,
action: Option<&'a str>,
target: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
pre: Option<OwnedStep<'a>>,
#[serde(skip_serializing_if = "Option::is_none")]
post: Option<OwnedStep<'a>>,
}
#[derive(Serialize)]
struct JsonUnknown<'a> {
kind: &'static str,
label: &'a str,
reason: &'a str,
}
struct OwnedStep<'a> {
program: &'a Program,
state: State,
}
impl Serialize for OwnedStep<'_> {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
Step { program: self.program, state: &self.state }.serialize(s)
}
}
fn obligation_kind(k: ObligationKind) -> &'static str {
match k {
ObligationKind::Vacuity => "vacuity",
ObligationKind::InitType => "init_type",
ObligationKind::InitInductive => "init_inductive",
ObligationKind::InitProperty => "init_property",
ObligationKind::StepType => "step_type",
ObligationKind::StepInductive => "step_inductive",
ObligationKind::SafetyInvariant => "safety_invariant",
ObligationKind::StepProperty => "step_property",
}
}
pub fn prove_error(
spec: &str,
model: Option<&str>,
message: &str,
location: Option<Location>,
) -> String {
to_string(&ProveJson {
version: 1,
spec,
model,
outcome: ProveKind::Error { message, location },
obligations: 0,
proved: 0,
failed: 0,
unknown: 0,
seconds: 0.0,
unchecked: Vec::new(),
failures: Vec::new(),
unknowns: Vec::new(),
})
}
pub fn prove_report(
spec: &str,
program: &Program,
report: &ProveReport,
location: Option<Location>,
) -> String {
fn map_unknowns(us: &[UnknownObligation]) -> Vec<JsonUnknown<'_>> {
us.iter()
.map(|u| JsonUnknown {
kind: obligation_kind(u.kind),
label: &u.label,
reason: &u.reason,
})
.collect()
}
let mut failures = Vec::new();
let mut unknowns = map_unknowns(&report.unknowns);
let outcome = match &report.outcome {
ProveOutcome::Proved => ProveKind::Proved,
ProveOutcome::Failed { failures: fs } => {
failures = fs
.iter()
.map(|f: &Failure| JsonFailure {
kind: obligation_kind(f.kind),
label: &f.label,
action: f.action.map(|id| program.actions[id.index()].name.as_str()),
target: &f.target,
pre: f.cti.pre.as_ref().map(|s| OwnedStep { program, state: decoded_state(s) }),
post: f
.cti
.post
.as_ref()
.map(|s| OwnedStep { program, state: decoded_state(s) }),
})
.collect();
ProveKind::Failed
}
ProveOutcome::Unknown { unknowns: us } => {
if unknowns.is_empty() {
unknowns = map_unknowns(us);
}
ProveKind::Unknown
}
ProveOutcome::Error { message, .. } => ProveKind::Error { message, location },
};
to_string(&ProveJson {
version: 1,
spec,
model: Some(&program.model.name),
outcome,
obligations: report.obligations,
proved: report.proved,
failed: report.failed,
unknown: report.unknown,
seconds: report.elapsed.as_secs_f64(),
unchecked: spock_report::smt_unchecked(program),
failures,
unknowns,
})
}
impl Serialize for Step<'_> {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
let mut map = s.serialize_map(Some(3))?;
step_entries::<S>(&mut map, self.program, self.state)?;
map.end()
}
}
fn step_entries<S: Serializer>(
map: &mut S::SerializeMap,
program: &Program,
state: &State,
) -> Result<(), S::Error> {
let action = state.action.map(|id| program.actions[id.index()].name.as_str());
let args: Vec<JsonValue> = each(program, &state.args).collect();
map.serialize_entry("action", &action)?;
map.serialize_entry("args", &args)?;
let fields = Fields { program, fields: program.state_fields(), values: &state.fields };
map.serialize_entry("state", &fields)
}
struct Fields<'a> {
program: &'a Program,
fields: &'a [Field],
values: &'a [Value],
}
impl Serialize for Fields<'_> {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
let mut map = s.serialize_map(Some(self.values.len()))?;
for (f, v) in self.fields.iter().zip(self.values) {
map.serialize_entry(&f.name, &JsonValue { program: self.program, value: v })?;
}
map.end()
}
}
struct JsonValue<'a> {
program: &'a Program,
value: &'a Value,
}
impl Serialize for JsonValue<'_> {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
let program = self.program;
match self.value {
Value::Bool(b) => s.serialize_bool(*b),
Value::Int(n) => s.serialize_i64(*n),
Value::Atom(ty, index) => {
let def = program.def(*ty);
match &def.kind {
TypeDefKind::Atoms(atoms) => s.serialize_str(&atoms[*index as usize]),
TypeDefKind::Abstract => {
s.serialize_str(&spock_ir::abstract_atom(&def.name, *index))
}
_ => s.serialize_u32(*index),
}
}
Value::Struct(ty, values) => match &program.def(*ty).kind {
TypeDefKind::Struct(fields) => Fields { program, fields, values }.serialize(s),
_ => s.collect_seq(each(program, values)),
},
Value::Ctor(ty, index, values) => {
let TypeDefKind::Variant(ctors) = &program.def(*ty).kind else {
return s.collect_seq(each(program, values));
};
let ctor = &ctors[*index as usize];
if values.is_empty() {
return s.serialize_str(&ctor.name);
}
let mut map = s.serialize_map(Some(1))?;
match values.as_slice() {
[value] if positional(&ctor.fields) => {
map.serialize_entry(&ctor.name, &JsonValue { program, value })?
}
_ if positional(&ctor.fields) => {
map.serialize_entry(&ctor.name, &each(program, values).collect::<Vec<_>>())?
}
_ => map.serialize_entry(
&ctor.name,
&Fields { program, fields: &ctor.fields, values },
)?,
}
map.end()
}
Value::Tuple(items) | Value::Set(items) | Value::Seq(items) => {
s.collect_seq(each(program, items))
}
Value::Map(pairs) => {
s.collect_seq(pairs.iter().map(|(k, v)| {
(JsonValue { program, value: k }, JsonValue { program, value: v })
}))
}
}
}
}
fn each<'a>(program: &'a Program, values: &'a [Value]) -> impl Iterator<Item = JsonValue<'a>> {
values.iter().map(move |value| JsonValue { program, value })
}
#[derive(Serialize)]
struct TraceJson<'a> {
version: u32,
spec: &'a str,
model: Option<&'a str>,
trace: &'a str,
outcome: TraceKind<'a>,
states: usize,
matched: usize,
most: usize,
generated: u64,
seconds: f64,
behavior: Vec<MatchedStep<'a>>,
}
#[derive(Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum TraceKind<'a> {
Matches,
Invariant {
name: &'a str,
line: u32,
},
StepProperty {
name: &'a str,
line: u32,
},
Diverges {
line: u32,
misses: Vec<MissJson<'a>>,
},
Error {
message: &'a str,
location: Option<Location>,
line: Option<u32>,
},
}
pub fn trace_report(
spec: &str,
path: &str,
program: &Program,
lines: &[u32],
report: &trace::Report,
location: Option<Location>,
) -> String {
let line = |event: usize| lines[event];
let (outcome, behavior) = match &report.outcome {
trace::Outcome::Matches { behavior } => (TraceKind::Matches, behavior),
trace::Outcome::InvariantViolated { name, at, behavior } => {
(TraceKind::Invariant { name, line: line(*at) }, behavior)
}
trace::Outcome::PropertyViolated { name, at, behavior } => {
(TraceKind::StepProperty { name, line: line(*at) }, behavior)
}
trace::Outcome::Diverges { at, behavior, misses } => {
let misses = misses.iter().map(|miss| MissJson { program, miss }).collect();
(TraceKind::Diverges { line: line(*at), misses }, behavior)
}
trace::Outcome::Error { message, at, behavior, .. } => {
(TraceKind::Error { message, location, line: at.map(line) }, behavior)
}
};
let json = TraceJson {
version: 1,
spec,
model: Some(&program.model.name),
trace: path,
outcome,
states: lines.len(),
matched: report.matched,
most: report.most,
generated: report.generated,
seconds: report.elapsed.as_secs_f64(),
behavior: behavior
.iter()
.map(|matched| MatchedStep { program, line: matched.event.map(line), matched })
.collect(),
};
to_string(&json)
}
pub fn trace_error(
spec: &str,
model: Option<&str>,
path: &str,
message: &str,
location: Option<Location>,
) -> String {
let json = TraceJson {
version: 1,
spec,
model,
trace: path,
outcome: TraceKind::Error { message, location, line: None },
states: 0,
matched: 0,
most: 0,
generated: 0,
seconds: 0.0,
behavior: Vec::new(),
};
to_string(&json)
}
struct MatchedStep<'a> {
program: &'a Program,
line: Option<u32>,
matched: &'a Matched,
}
impl Serialize for MatchedStep<'_> {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
let mut map = s.serialize_map(Some(4))?;
map.serialize_entry("line", &self.line)?;
step_entries::<S>(&mut map, self.program, &self.matched.state)?;
map.end()
}
}
struct MissJson<'a> {
program: &'a Program,
miss: &'a Miss,
}
impl Serialize for MissJson<'_> {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
let program = self.program;
let mut map = s.serialize_map(Some(2))?;
let from = self.miss.from.as_ref().map(|state| Step { program, state });
map.serialize_entry("from", &from)?;
map.serialize_entry("why", &WhyJson { program, why: &self.miss.why })?;
map.end()
}
}
struct WhyJson<'a> {
program: &'a Program,
why: &'a Why,
}
impl Serialize for WhyJson<'_> {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
let program = self.program;
let mut map = s.serialize_map(None)?;
match self.why {
Why::NotEnabled => map.serialize_entry("kind", "not_enabled")?,
Why::Arguments(lists) => {
map.serialize_entry("kind", "arguments")?;
let lists: Vec<Vec<JsonValue>> =
lists.iter().map(|args| each(program, args).collect()).collect();
map.serialize_entry("arguments", &lists)?;
}
Why::Differs { step, differences } => {
map.serialize_entry("kind", "differs")?;
map.serialize_entry("step", &step.as_ref().map(|state| Step { program, state }))?;
let differences: Vec<DifferenceJson> = differences
.iter()
.map(|difference| DifferenceJson { program, difference })
.collect();
map.serialize_entry("differences", &differences)?;
}
}
map.end()
}
}
struct DifferenceJson<'a> {
program: &'a Program,
difference: &'a Difference,
}
impl Serialize for DifferenceJson<'_> {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
let (program, difference) = (self.program, self.difference);
let mut map = s.serialize_map(Some(3))?;
map.serialize_entry("path", &show::path(program, &difference.path))?;
let seen = difference.seen.as_ref().map(|value| JsonValue { program, value });
let spec = difference.spec.as_ref().map(|value| JsonValue { program, value });
map.serialize_entry("seen", &seen)?;
map.serialize_entry("spec", &spec)?;
map.end()
}
}