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;
#[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,
}
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) => match &program.def(*ty).kind {
TypeDefKind::Atoms(atoms) => s.serialize_str(&atoms[*index as usize]),
_ => 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()
}
}