spock-cli 0.4.0

A model checker for specs that read like Rust: TLA's logic of actions, checked on every core in machine code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
//! The reports `spock check --json` and `spock trace --json` print (RFD0003, The report).
//! Objects keep declared order: a state's fields are in the order the state struct declares
//! them.

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;

/// Where an error is: a file, and a 1-based line and column.
#[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>>,
    /// For a temporal property's violation by a behavior: the index in `trace` of the state
    /// the last state steps back to forever.
    #[serde(skip_serializing_if = "Option::is_none")]
    back_to: Option<usize>,
    /// The action and arguments of that step, unless it is a stutter.
    #[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,
    /// TLA+'s `ASSUME`.
    Assumption {
        name: &'a str,
    },
    Invariant {
        name: &'a str,
    },
    StepProperty {
        name: &'a str,
    },
    /// A temporal property.
    Property {
        name: &'a str,
    },
    Deadlock,
    Error {
        message: &'a str,
        location: Option<Location>,
    },
}

/// The report of a check that ran.
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)
}

/// One line, or indented for a terminal.
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")
}

/// The report of a check that couldn't run, since the spec has an error.
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)
}

/// The step back of a behavior that loops: its action and arguments.
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()
    }
}

/// A state of a trace, and the action that reached it.
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()
    }
}

/// A step's `action`, `args` and `state`.
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()
    }
}

/// A value as serde writes the Rust type it would be: a struct is an object, a tuple, a set or
/// a sequence an array, a map an array of `[key, value]`, an atom or a constructor without
/// fields its name, and a constructor with fields `{ "Name": payload }`.
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 })
}

/// The report of `spock trace`: whether a behavior of the model matches the trace.
#[derive(Serialize)]
struct TraceJson<'a> {
    version: u32,
    spec: &'a str,
    model: Option<&'a str>,
    trace: &'a str,
    outcome: TraceKind<'a>,
    /// The trace's states.
    states: usize,
    /// How many of them, from the first, a behavior matches.
    matched: usize,
    /// The most states the run could have been in at one of them.
    most: usize,
    generated: u64,
    seconds: f64,
    /// A behavior that matches the trace, or the states `matched` of it.
    behavior: Vec<MatchedStep<'a>>,
}

#[derive(Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum TraceKind<'a> {
    Matches,
    /// No behavior matches the trace's state at `line`.
    Diverges {
        line: u32,
        misses: Vec<MissJson<'a>>,
    },
    Error {
        message: &'a str,
        location: Option<Location>,
        /// The line of the trace the check had got to.
        line: Option<u32>,
    },
}

/// What `spock trace` reports of a check that ran. `lines` are the lines of the trace's states.
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::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)
}

/// What `spock trace` reports when it can't check: the spec or the trace has an error.
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)
}

/// A state of a behavior that matches a trace: the trace's line it matches, or null after a
/// hidden step, then the step as `--json`'s traces write it.
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()
    }
}

/// Why the step fails from one of the states the run could be in: `from` it, null at the
/// first line, and `why`.
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()
    }
}

/// `{"kind": "not_enabled"}`, `{"kind": "arguments", "arguments": [[..], ..]}`, or
/// `{"kind": "differs", "step": .., "differences": [..]}`, whose step is null for a stutter.
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()
    }
}

/// `{"path": "pc[a]", "seen": .., "spec": ..}`: the path as a trace's key writes it, what the
/// line saw there (null when it saw only parts), and what the spec has (null when its map or
/// sequence has nothing there).
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()
    }
}