spock-cli 0.9.0

A modern, statically typed, natively compiled model checking and proof language
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
//! 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;
use spock_smt::{
    CtiReachability, DecodedState, Failure, ObligationKind, ProveOutcome, ProveReport,
    SymbolicOutcome, SymbolicReport, UnknownObligation,
};

/// Action, field, and stutter coverage observed on a conforming trace.
#[derive(Debug, Clone, Serialize)]
pub struct TraceCoverage {
    pub actions: Vec<String>,
    pub leaf_actions: Vec<String>,
    pub missing_actions: Vec<String>,
    pub observed_fields: Vec<String>,
    pub spec_fields: Vec<String>,
    pub missing_fields: Vec<String>,
    pub stutters: usize,
}

/// 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 step of a trace, and the action that reached it.
struct Step<'a> {
    program: &'a Program,
    state: &'a State,
}

fn decoded_state(s: &DecodedState) -> State {
    State { action: s.action, args: s.args.clone(), fields: s.fields.clone() }
}

/// The report of `spock check --symbolic --json`.
pub fn symbolic_report(
    spec: &str,
    program: &Program,
    report: &SymbolicReport,
    location: Option<Location>,
) -> String {
    #[derive(Serialize)]
    #[serde(tag = "kind", rename_all = "snake_case")]
    enum SymKind<'a> {
        Ok,
        Assumption { name: &'a str },
        Invariant { name: &'a str },
        StepProperty { name: &'a str },
        Unknown { depth: usize, reason: &'a str },
        Error { message: &'a str, location: Option<Location> },
    }
    #[derive(Serialize)]
    struct SymJson<'a> {
        version: u32,
        mode: &'static str,
        spec: &'a str,
        model: &'a str,
        outcome: SymKind<'a>,
        depth_checked: usize,
        seconds: f64,
        unchecked: Vec<String>,
        trace: Vec<Step<'a>>,
    }
    let (outcome, states): (SymKind<'_>, Vec<State>) = match &report.outcome {
        SymbolicOutcome::Ok => (SymKind::Ok, Vec::new()),
        SymbolicOutcome::AssumptionViolated { name } => (SymKind::Assumption { name }, Vec::new()),
        SymbolicOutcome::InvariantViolated { name, trace } => {
            (SymKind::Invariant { name }, trace.iter().map(decoded_state).collect())
        }
        SymbolicOutcome::PropertyViolated { name, trace } => {
            (SymKind::StepProperty { name }, trace.iter().map(decoded_state).collect())
        }
        SymbolicOutcome::Unknown { depth, reason } => {
            (SymKind::Unknown { depth: *depth, reason }, Vec::new())
        }
        SymbolicOutcome::Error { message, trace, .. } => {
            (SymKind::Error { message, location }, trace.iter().map(decoded_state).collect())
        }
    };
    let trace = states.iter().map(|state| Step { program, state }).collect();
    to_string(&SymJson {
        version: 1,
        mode: "symbolic",
        spec,
        model: &program.model.name,
        outcome,
        depth_checked: report.depth_checked,
        seconds: report.elapsed.as_secs_f64(),
        unchecked: spock_report::smt_unchecked(program),
        trace,
    })
}

#[derive(Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum ProveKind<'a> {
    Proved,
    Failed,
    Unknown,
    Error { message: &'a str, location: Option<Location> },
}

#[derive(Serialize)]
struct ProveJson<'a> {
    version: u32,
    spec: &'a str,
    model: Option<&'a str>,
    outcome: ProveKind<'a>,
    obligations: usize,
    proved: usize,
    failed: usize,
    unknown: usize,
    seconds: f64,
    unchecked: Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    failures: Vec<JsonFailure<'a>>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    unknowns: Vec<JsonUnknown<'a>>,
}

#[derive(Serialize)]
struct JsonFailure<'a> {
    kind: &'static str,
    label: &'a str,
    action: Option<&'a str>,
    target: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pre: Option<OwnedStep<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    post: Option<OwnedStep<'a>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    reachability: Option<JsonReachability<'a>>,
}

#[derive(Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum JsonReachability<'a> {
    Reachable { steps: usize, witness: Vec<OwnedStep<'a>> },
    Unreachable { depth: usize },
}

#[derive(Serialize)]
struct JsonUnknown<'a> {
    kind: &'static str,
    label: &'a str,
    reason: &'a str,
}

struct OwnedStep<'a> {
    program: &'a Program,
    state: State,
}

impl Serialize for OwnedStep<'_> {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        Step { program: self.program, state: &self.state }.serialize(s)
    }
}

fn obligation_kind(k: ObligationKind) -> &'static str {
    match k {
        ObligationKind::Vacuity => "vacuity",
        ObligationKind::InitType => "init_type",
        ObligationKind::InitInductive => "init_inductive",
        ObligationKind::InitProperty => "init_property",
        ObligationKind::StepType => "step_type",
        ObligationKind::StepInductive => "step_inductive",
        ObligationKind::SafetyInvariant => "safety_invariant",
        ObligationKind::StepProperty => "step_property",
        ObligationKind::WellDefined => "well_defined",
    }
}

/// The report of `spock prove --json` when the spec failed to load.
pub fn prove_error(
    spec: &str,
    model: Option<&str>,
    message: &str,
    location: Option<Location>,
) -> String {
    to_string(&ProveJson {
        version: 1,
        spec,
        model,
        outcome: ProveKind::Error { message, location },
        obligations: 0,
        proved: 0,
        failed: 0,
        unknown: 0,
        seconds: 0.0,
        unchecked: Vec::new(),
        failures: Vec::new(),
        unknowns: Vec::new(),
    })
}

/// The report of `spock prove --json`.
pub fn prove_report(
    spec: &str,
    program: &Program,
    report: &ProveReport,
    triage: &[Option<CtiReachability>],
    location: Option<Location>,
) -> String {
    fn map_unknowns(us: &[UnknownObligation]) -> Vec<JsonUnknown<'_>> {
        us.iter()
            .map(|u| JsonUnknown {
                kind: obligation_kind(u.kind),
                label: &u.label,
                reason: &u.reason,
            })
            .collect()
    }
    let mut failures = Vec::new();
    let mut unknowns = map_unknowns(&report.unknowns);
    let outcome = match &report.outcome {
        ProveOutcome::Proved => ProveKind::Proved,
        ProveOutcome::Failed { failures: fs } => {
            failures = fs
                .iter()
                .enumerate()
                .map(|(i, f): (usize, &Failure)| {
                    let reachability = triage.get(i).and_then(Option::as_ref).map(|r| match r {
                        CtiReachability::Reachable { witness } => JsonReachability::Reachable {
                            steps: witness.len().saturating_sub(1),
                            witness: witness
                                .iter()
                                .map(|s| OwnedStep { program, state: decoded_state(s) })
                                .collect(),
                        },
                        CtiReachability::Unreachable { depth } => {
                            JsonReachability::Unreachable { depth: *depth }
                        }
                    });
                    JsonFailure {
                        kind: obligation_kind(f.kind),
                        label: &f.label,
                        action: f.action.map(|id| program.actions[id.index()].name.as_str()),
                        target: &f.target,
                        pre: f
                            .cti
                            .pre
                            .as_ref()
                            .map(|s| OwnedStep { program, state: decoded_state(s) }),
                        post: f
                            .cti
                            .post
                            .as_ref()
                            .map(|s| OwnedStep { program, state: decoded_state(s) }),
                        reachability,
                    }
                })
                .collect();
            ProveKind::Failed
        }
        ProveOutcome::Unknown { unknowns: us } => {
            if unknowns.is_empty() {
                unknowns = map_unknowns(us);
            }
            ProveKind::Unknown
        }
        ProveOutcome::Error { message, .. } => ProveKind::Error { message, location },
    };
    to_string(&ProveJson {
        version: 1,
        spec,
        model: Some(&program.model.name),
        outcome,
        obligations: report.obligations,
        proved: report.proved,
        failed: report.failed,
        unknown: report.unknown,
        seconds: report.elapsed.as_secs_f64(),
        unchecked: spock_report::smt_unchecked(program),
        failures,
        unknowns,
    })
}

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) => {
                let def = program.def(*ty);
                match &def.kind {
                    TypeDefKind::Atoms(atoms) => s.serialize_str(&atoms[*index as usize]),
                    TypeDefKind::Abstract => {
                        s.serialize_str(&spock_ir::abstract_atom(&def.name, *index))
                    }
                    _ => 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>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    coverage: Option<&'a TraceCoverage>,
}

#[derive(Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum TraceKind<'a> {
    Matches,
    Coverage {
        errors: &'a [String],
    },
    Invariant {
        name: &'a str,
        line: u32,
    },
    StepProperty {
        name: &'a str,
        line: u32,
    },
    /// 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.
#[allow(clippy::too_many_arguments)]
pub fn trace_report(
    spec: &str,
    path: &str,
    program: &Program,
    lines: &[u32],
    report: &trace::Report,
    location: Option<Location>,
    coverage: Option<&TraceCoverage>,
    coverage_errors: &[String],
) -> String {
    let line = |event: usize| lines[event];
    let (outcome, behavior) = match &report.outcome {
        trace::Outcome::Matches { behavior } if !coverage_errors.is_empty() => {
            (TraceKind::Coverage { errors: coverage_errors }, behavior)
        }
        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(),
        coverage,
    };
    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(),
        coverage: None,
    };
    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()
    }
}