1use std::sync::Arc;
5
6use dive_model::Model;
7use dive_value::Value;
8use serde_json::{Map, Value as J};
9
10use crate::format::{Ending, Label, Source, TraceDoc};
11use crate::value_json;
12
13pub type State = Arc<[Option<Value>]>;
17
18pub(crate) fn validate_state_names(model: &Model, state: &State) -> Result<(), String> {
20 for value in state.iter().flatten() {
21 value
22 .validate_names_in(&model.names, model.evaluator.options().ctx.order)
23 .map_err(|error| error.to_string())?;
24 }
25 Ok(())
26}
27
28#[derive(Clone, Debug)]
30pub struct Trace {
31 pub states: Vec<State>,
33 pub labels: Vec<Option<Label>>,
35 pub ending: Ending,
37 pub length: Option<usize>,
39 pub properties: Vec<String>,
41}
42
43#[must_use]
45pub fn variables(model: &Model) -> Vec<String> {
46 model
47 .ir
48 .vars()
49 .iter()
50 .map(|&d| model.ir.decl(d).name.clone())
51 .collect()
52}
53
54#[derive(Clone, Debug, PartialEq, Eq)]
57pub struct ShapeError {
58 pub state: Option<usize>,
60 pub detail: String,
62}
63
64impl Trace {
65 #[must_use]
67 pub fn logical_length(&self) -> usize {
68 self.states.len().saturating_add(usize::from(matches!(
69 self.ending,
70 Ending::PartialNext { .. } | Ending::PartialInit { .. }
71 )))
72 }
73 pub fn decode(model: &Model, doc: &TraceDoc) -> Result<Self, ShapeError> {
80 if doc.source == Source::Tlc {
81 return Err(ShapeError {
82 state: None,
83 detail: "TLC's lossy JSON values must be read with dive_trace::tlc".to_owned(),
84 });
85 }
86 let ending = doc.ending.clone().ok_or_else(|| ShapeError {
87 state: None,
88 detail: "the trace does not say how it ends (no `ending`)".to_owned(),
89 })?;
90 let ctx = model.evaluator.options().ctx;
91 let vars = variables(model);
92 let mut states = Vec::with_capacity(doc.states.len());
93 for (k, s) in doc.states.iter().enumerate() {
94 let state = decode_state(&vars, s, |_, j| value_json::from_json(j, &model.names, ctx))
95 .map_err(|detail| ShapeError {
96 state: Some(k),
97 detail,
98 })?;
99 states.push(state);
100 }
101 Ok(Self {
102 states,
103 labels: doc.labels.clone(),
104 ending,
105 length: doc.length,
106 properties: doc.properties.clone(),
107 })
108 }
109
110 pub fn to_doc(&self, model: &Model) -> Result<TraceDoc, String> {
115 let ctx = model.evaluator.options().ctx;
116 let vars = variables(model);
117 let mut states = Vec::with_capacity(self.states.len());
118 for s in &self.states {
119 let mut m = Map::new();
120 for (name, v) in vars.iter().zip(s.iter()) {
121 let v = v.as_ref().ok_or("a state has an unassigned variable")?;
122 m.insert(name.clone(), value_json::to_json(v, ctx)?);
123 }
124 states.push(m);
125 }
126 Ok(TraceDoc {
127 variables: vars,
128 states,
129 labels: self.labels.clone(),
130 ending: Some(self.ending.clone()),
131 length: self.length,
132 source: Source::Dive,
133 properties: self.properties.clone(),
134 })
135 }
136}
137
138pub(crate) fn decode_state(
140 vars: &[String],
141 s: &Map<String, J>,
142 mut read: impl FnMut(&str, &J) -> Result<Value, String>,
143) -> Result<State, String> {
144 if let Some(extra) = s.keys().find(|k| !vars.contains(k)) {
145 return Err(format!("`{extra}` is not a variable of the specification"));
146 }
147 let mut out = Vec::with_capacity(vars.len());
148 for v in vars {
149 let j = s
150 .get(v)
151 .ok_or_else(|| format!("variable `{v}` is not assigned"))?;
152 out.push(Some(
153 read(v, j).map_err(|e| format!("variable `{v}`: {e}"))?,
154 ));
155 }
156 Ok(out.into())
157}