use std::sync::Arc;
use dive_model::Model;
use dive_value::Value;
use serde_json::{Map, Value as J};
use crate::format::{Ending, Label, Source, TraceDoc};
use crate::value_json;
pub type State = Arc<[Option<Value>]>;
pub(crate) fn validate_state_names(model: &Model, state: &State) -> Result<(), String> {
for value in state.iter().flatten() {
value
.validate_names_in(&model.names, model.evaluator.options().ctx.order)
.map_err(|error| error.to_string())?;
}
Ok(())
}
#[derive(Clone, Debug)]
pub struct Trace {
pub states: Vec<State>,
pub labels: Vec<Option<Label>>,
pub ending: Ending,
pub length: Option<usize>,
pub properties: Vec<String>,
}
#[must_use]
pub fn variables(model: &Model) -> Vec<String> {
model
.ir
.vars()
.iter()
.map(|&d| model.ir.decl(d).name.clone())
.collect()
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ShapeError {
pub state: Option<usize>,
pub detail: String,
}
impl Trace {
#[must_use]
pub fn logical_length(&self) -> usize {
self.states.len().saturating_add(usize::from(matches!(
self.ending,
Ending::PartialNext { .. } | Ending::PartialInit { .. }
)))
}
pub fn decode(model: &Model, doc: &TraceDoc) -> Result<Self, ShapeError> {
if doc.source == Source::Tlc {
return Err(ShapeError {
state: None,
detail: "TLC's lossy JSON values must be read with dive_trace::tlc".to_owned(),
});
}
let ending = doc.ending.clone().ok_or_else(|| ShapeError {
state: None,
detail: "the trace does not say how it ends (no `ending`)".to_owned(),
})?;
let ctx = model.evaluator.options().ctx;
let vars = variables(model);
let mut states = Vec::with_capacity(doc.states.len());
for (k, s) in doc.states.iter().enumerate() {
let state = decode_state(&vars, s, |_, j| value_json::from_json(j, &model.names, ctx))
.map_err(|detail| ShapeError {
state: Some(k),
detail,
})?;
states.push(state);
}
Ok(Self {
states,
labels: doc.labels.clone(),
ending,
length: doc.length,
properties: doc.properties.clone(),
})
}
pub fn to_doc(&self, model: &Model) -> Result<TraceDoc, String> {
let ctx = model.evaluator.options().ctx;
let vars = variables(model);
let mut states = Vec::with_capacity(self.states.len());
for s in &self.states {
let mut m = Map::new();
for (name, v) in vars.iter().zip(s.iter()) {
let v = v.as_ref().ok_or("a state has an unassigned variable")?;
m.insert(name.clone(), value_json::to_json(v, ctx)?);
}
states.push(m);
}
Ok(TraceDoc {
variables: vars,
states,
labels: self.labels.clone(),
ending: Some(self.ending.clone()),
length: self.length,
source: Source::Dive,
properties: self.properties.clone(),
})
}
}
pub(crate) fn decode_state(
vars: &[String],
s: &Map<String, J>,
mut read: impl FnMut(&str, &J) -> Result<Value, String>,
) -> Result<State, String> {
if let Some(extra) = s.keys().find(|k| !vars.contains(k)) {
return Err(format!("`{extra}` is not a variable of the specification"));
}
let mut out = Vec::with_capacity(vars.len());
for v in vars {
let j = s
.get(v)
.ok_or_else(|| format!("variable `{v}` is not assigned"))?;
out.push(Some(
read(v, j).map_err(|e| format!("variable `{v}`: {e}"))?,
));
}
Ok(out.into())
}