Skip to main content

dive_trace/
trace.rs

1//! A trace read against a model: states as values, in the model's variable
2//! order.
3
4use 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
13/// A state: the value of each of the model's variables, by
14/// [`dive_ir::VarId`]. Every entry is `Some`. Names must have the text and token
15/// of the model's interner; public typed inputs are checked before evaluation.
16pub type State = Arc<[Option<Value>]>;
17
18/// Checks public typed state values before any predicate can compare names.
19pub(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/// A counterexample (or behavior) read against a model.
29#[derive(Clone, Debug)]
30pub struct Trace {
31    /// The states.
32    pub states: Vec<State>,
33    /// The label of the step into each state (`labels[0]` is `None`).
34    pub labels: Vec<Option<Label>>,
35    /// What the trace claims.
36    pub ending: Ending,
37    /// The claimed number of states, if given.
38    pub length: Option<usize>,
39    /// All temporal properties claimed false on a periodic word.
40    pub properties: Vec<String>,
41}
42
43/// The model's variable names, by [`dive_ir::VarId`].
44#[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/// Why a document could not be read as a trace of the model: the state, and
55/// what is wrong.
56#[derive(Clone, Debug, PartialEq, Eq)]
57pub struct ShapeError {
58    /// The state (0-based), or `None` for the document as a whole.
59    pub state: Option<usize>,
60    /// What is wrong.
61    pub detail: String,
62}
63
64impl Trace {
65    /// Logical length, counting a separate partial terminal candidate.
66    #[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    /// Reads a [`Source::Dive`] document's values against `model`, checking
74    /// that every state assigns exactly the model's variables. A
75    /// [`Source::Tlc`] document is read by [`crate::tlc`] instead.
76    ///
77    /// # Errors
78    /// The first state that does not fit, or a missing ending.
79    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    /// The trace in dive's format.
111    ///
112    /// # Errors
113    /// If a value has no JSON form (an infinite set).
114    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
138/// Reads one state: exactly the variables `vars`, each value read by `read`.
139pub(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}