cverif 0.0.4

Verifies that compiled machine code faithfully matches its C source
Documentation
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
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
//! Explanations of proof obligations that failed or were left undecided, and per-path
//! summaries of what the source and the machine code compute.
//!
//! While a path runs, the verifier only leaves cheap notes in a thread-local scratch area
//! (which instruction or statement made each branch decision, the two terms of the goal that
//! failed).  The owned, printable form is built from them only when a path fails or when
//! summaries were asked for, while the function's term store is still alive.

use super::{Dag, Importer, Names, Printer, Style, json_str, show_val};
use crate::c::ast::{Program, Type};
use crate::c::exec::CExec;
use crate::sym::{Ctx, R, Stop, WordLoc, arg_words};
use crate::term::{Env, Node, T};
use crate::thumb::exec::Machine;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::fmt::Write as _;

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Origin {
    None,
    Src(u32),
    Bin(u32),
}

type RawWrite = (T, u8, T);

#[derive(Default)]
struct RawCall {
    name: String,
    args: Vec<T>,
    ret: Option<T>,
    /// World memory at the call (binary side: since the previous call).
    writes: Vec<RawWrite>,
}

#[derive(Default)]
struct RawSide {
    calls: Vec<RawCall>,
    writes: Vec<RawWrite>,
    /// Volatile accesses: (write, address, size, value, number of calls before it).
    vol: Vec<(bool, T, u8, T, usize)>,
    ret: Vec<(String, T)>,
    returned: bool,
    cov: Vec<u32>,
    insns: Vec<(u32, u8)>,
}

struct Track {
    /// Path-condition entries [start, end) were added while `origin` executed.
    marks: Vec<(usize, usize, Origin)>,
    cur: Origin,
    cur_len: usize,
    pre_len: usize,
    last_src: Option<u32>,
    last_bin: Option<u32>,
    goal: Option<(T, T)>,
    addr: Option<T>,
    /// Most paths to summarise for the function being verified (0: none).
    dump: usize,
    src: Option<RawSide>,
    bin: Option<RawSide>,
    paths: Vec<PathDump>,
    skipped: usize,
}

impl Track {
    const fn new() -> Track {
        Track {
            marks: Vec::new(),
            cur: Origin::None,
            cur_len: 0,
            pre_len: 0,
            last_src: None,
            last_bin: None,
            goal: None,
            addr: None,
            dump: 0,
            src: None,
            bin: None,
            paths: Vec::new(),
            skipped: 0,
        }
    }

    #[inline]
    fn mark(&mut self, len: usize, o: Origin) {
        if len > self.cur_len {
            self.marks.push((self.cur_len, len, self.cur));
        }
        self.cur_len = len;
        self.cur = o;
    }

    fn origin(&self, i: usize) -> Origin {
        if i < self.pre_len {
            return Origin::None;
        }
        match self.marks.iter().find(|m| m.0 <= i && i < m.1) {
            Some(m) => m.2,
            None if i >= self.cur_len => self.cur,
            None => Origin::None,
        }
    }
}

thread_local! {
    static TRACK: RefCell<Track> = const { RefCell::new(Track::new()) };
}

/// A function is about to be verified on this thread; summarise up to `dump` of its paths.
pub(crate) fn begin_function(dump: usize) {
    TRACK.with(|t| {
        let mut t = t.borrow_mut();
        *t = Track::new();
        t.dump = dump;
    });
}

/// Exploration starts over (iterative deepening): forget the summaries of the last round.
pub(crate) fn begin_round() {
    TRACK.with(|t| {
        let mut t = t.borrow_mut();
        t.paths.clear();
        t.skipped = 0;
    });
}

/// A path starts with `pre_len` preconditions in the path condition.
pub(crate) fn begin_path(pre_len: usize) {
    TRACK.with(|t| {
        let mut t = t.borrow_mut();
        t.marks.clear();
        t.cur = Origin::None;
        t.cur_len = pre_len;
        t.pre_len = pre_len;
        t.last_src = None;
        t.last_bin = None;
        t.goal = None;
        t.addr = None;
        t.src = None;
        t.bin = None;
    });
}

/// The source side is about to execute the statement or branch of coverage point `cov`.
#[inline]
pub(crate) fn at_src(pc_len: usize, cov: u32) {
    TRACK.with(|t| {
        let mut t = t.borrow_mut();
        t.mark(pc_len, Origin::Src(cov));
        t.last_src = Some(cov);
    });
}

/// The machine is about to execute the instruction at `addr`.
#[inline]
pub(crate) fn at_bin(pc_len: usize, addr: u32) {
    TRACK.with(|t| {
        let mut t = t.borrow_mut();
        t.mark(pc_len, Origin::Bin(addr));
        t.last_bin = Some(addr);
    });
}

/// The memory location whose contents are compared next.
#[inline]
pub(crate) fn note_addr(addr: T) {
    TRACK.with(|t| t.borrow_mut().addr = Some(addr));
}

/// The equality `source == binary` could not be proved.
pub(crate) fn note_goal(source: T, binary: T) {
    TRACK.with(|t| t.borrow_mut().goal = Some((source, binary)));
}

#[inline]
pub(crate) fn dumping() -> bool {
    TRACK.with(|t| t.borrow().dump > 0)
}

/// The source side of the path has run.
pub(crate) fn note_source(cx: &CExec, ret: Option<T>, halted: bool) {
    if !dumping() {
        return;
    }
    let mut s = RawSide {
        returned: !halted,
        cov: cx.cov.clone(),
        ..Default::default()
    };
    for ev in &cx.events {
        s.calls.push(RawCall {
            name: ev.name.clone(),
            args: ev.args.iter().map(|a| a.0).collect(),
            ret: ev.ret.map(|r| r.0),
            writes: ev.writes.iter().map(|w| (w.addr, w.size, w.val)).collect(),
        });
        if ev.noreturn {
            s.returned = false;
        }
    }
    s.writes = cx.mem.world.iter().map(|w| (w.addr, w.size, w.val)).collect();
    s.vol = cx
        .volatile
        .iter()
        .map(|v| (v.write, v.addr, v.size, v.val, v.event))
        .collect();
    if let Some(r) = ret {
        s.ret.push(("return".into(), r));
    }
    TRACK.with(|t| t.borrow_mut().src = Some(s));
}

/// The machine code calls `name`; `nargs` is the number of arguments when known.
pub(crate) fn note_call(m: &Machine, name: &str, nargs: Option<usize>) {
    if !dumping() {
        return;
    }
    TRACK.with(|t| {
        let mut t = t.borrow_mut();
        let b = t.bin.get_or_insert_with(RawSide::default);
        b.calls.push(RawCall {
            name: name.to_string(),
            args: m.regs[..nargs.unwrap_or(4).min(4)].to_vec(),
            ret: None,
            writes: m.mem.world.iter().map(|w| (w.addr, w.size, w.val)).collect(),
        });
        b.insns = m.covered.clone();
    });
}

/// The machine code returns to its caller; the result has `width` bits (None: no result).
pub(crate) fn note_return(m: &Machine, width: Option<u8>) {
    if !dumping() {
        return;
    }
    TRACK.with(|t| {
        let mut t = t.borrow_mut();
        let b = t.bin.get_or_insert_with(RawSide::default);
        b.returned = true;
        match width {
            None => {}
            Some(64) => {
                b.ret.push(("r0".into(), m.regs[0]));
                b.ret.push(("r1".into(), m.regs[1]));
            }
            Some(_) => b.ret.push(("r0".into(), m.regs[0])),
        }
        b.writes = m.mem.world.iter().map(|w| (w.addr, w.size, w.val)).collect();
        b.insns = m.covered.clone();
    });
}

/// Which side of the comparison a path-condition entry comes from.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Side {
    /// Holds on entry (calling convention).
    Pre,
    Source,
    Binary,
    /// Added while the two sides were being compared.
    Compare,
}

impl Side {
    pub fn label(self) -> &'static str {
        match self {
            Side::Pre => "precondition",
            Side::Source => "source",
            Side::Binary => "binary",
            Side::Compare => "comparison",
        }
    }
}

/// One entry of a path condition.
#[derive(Clone, Debug)]
pub struct Decision {
    pub cond: u32,
    pub side: Side,
    /// Source statement that decided it.
    pub line: Option<(String, u32)>,
    /// Address of the instruction that decided it.
    pub addr: Option<u32>,
}

#[derive(Clone, Debug)]
pub struct Input {
    /// Display name (the parameter's name when the symbol is an argument register).
    pub label: String,
    /// The verifier's name of the symbol.
    pub name: String,
    pub value: u64,
    pub width: u8,
}

/// Why a function is not PROVED: the goal, the path, both terms, the counterexample.
#[derive(Clone, Debug, Default)]
pub struct Explanation {
    /// `mismatch`, `inconclusive` or `bounded`.
    pub outcome: String,
    /// Kind of the goal: `return_value`, `memory`, `argument`, `call_target`, `register`,
    /// `volatile`, `call_sequence`, `limit` or `other`.
    pub goal: String,
    /// What was compared, in words.
    pub what: String,
    /// Why it is not proved (the difference, or the name of the limit).
    pub reason: String,
    pub dag: Dag,
    pub source: Option<u32>,
    pub binary: Option<u32>,
    /// Address of the memory compared, for a `memory` goal.
    pub address: Option<u32>,
    pub path: Vec<Decision>,
    /// What the source's freedom from undefined behaviour lets the proof assume.
    pub assumptions: Vec<u32>,
    /// The counterexample: a value for every input the terms mention.
    pub inputs: Vec<Input>,
    /// Memory of the counterexample: (snapshot, address, bytes).
    pub memory: Vec<(u32, u32, Vec<u8>)>,
    pub has_model: bool,
    /// Where the two sides were when the goal failed.
    pub src_loc: Option<(String, u32)>,
    pub bin_addr: Option<u32>,
    /// For a BOUNDED result: whether a proof by induction over the loop was attempted.
    pub induction: Option<bool>,
}

/// What a path of one side does.
#[derive(Clone, Debug)]
pub enum Effect {
    Write {
        addr: u32,
        size: u8,
        val: u32,
    },
    Volatile {
        write: bool,
        addr: u32,
        size: u8,
        val: u32,
    },
    Call {
        index: usize,
        name: String,
        args: Vec<u32>,
        ret: Option<u32>,
    },
    Return(Vec<(String, u32)>),
    NoReturn,
}

#[derive(Clone, Debug, Default)]
pub struct SideDump {
    /// Source lines or address ranges the path goes through.
    pub trace: String,
    pub effects: Vec<Effect>,
}

/// One explored path: its condition and what each side computes on it.
#[derive(Clone, Debug, Default)]
pub struct PathDump {
    pub dag: Dag,
    pub outcome: String,
    pub conds: Vec<Decision>,
    pub assumptions: Vec<u32>,
    pub source: Option<SideDump>,
    pub binary: Option<SideDump>,
}

/// Everything beyond the status that was recorded about one function.
#[derive(Clone, Debug, Default)]
pub struct FuncDetail {
    pub explanation: Option<Explanation>,
    pub paths: Vec<PathDump>,
    /// Paths explored but not summarised (over the limit).
    pub skipped_paths: usize,
}

/// Display names for the symbols of a function's inputs: its parameters' names for the
/// argument registers and stack words, the text of string literals.
fn aliases(prog: &Program, fid: u32) -> BTreeMap<String, String> {
    let mut m = BTreeMap::new();
    let f = &prog.funcs[fid as usize];
    let record = |t| matches!(prog.ty(t), Type::Record(_)) && prog.size_of(t).is_some_and(|s| s > 0);
    let first = (record(f.ty.ret) && prog.size_of(f.ty.ret).unwrap_or(0) > 4) as u8;
    let shapes: Vec<(u32, bool)> =
        f.ty.params
            .iter()
            .map(|&t| (prog.size_of(t).unwrap_or(4), prog.align_of(t) == 8))
            .collect();
    for (i, locs) in arg_words(&shapes, first).into_iter().enumerate() {
        let Some(l) = f.locals.get(i).filter(|_| i < f.nparams) else {
            continue;
        };
        let rec = record(f.ty.params[i]);
        if rec {
            m.insert(format!("&arg{i}"), format!("&{}", l.name));
        }
        for (j, loc) in locs.iter().enumerate() {
            let sym = match loc {
                WordLoc::Reg(n) => format!("r{n}"),
                WordLoc::Stack(off) => format!("stk{off}"),
            };
            let name = match (locs.len(), rec, j) {
                (1, false, _) => l.name.to_string(),
                (2, false, 0) => format!("{}.lo", l.name),
                (2, false, _) => format!("{}.hi", l.name),
                _ => format!("{}.word{j}", l.name),
            };
            // A narrow argument is a narrow symbol (`r0:8`) extended to the register.
            let ty = f.ty.params[i];
            let bits = prog.bits(ty);
            if locs.len() == 1 && !rec && bits < 32 {
                let vw = if ty == crate::c::ast::BOOL { 1 } else { bits };
                m.insert(format!("{sym}:{vw}"), name.clone());
            }
            m.insert(sym, name);
        }
    }
    for (s, bytes) in prog.strings.iter().enumerate() {
        m.insert(format!("&str#{s}"), string_label(bytes));
    }
    m
}

/// A string literal as C would write it, shortened.
pub(crate) fn string_label(bytes: &[u8]) -> String {
    let mut o = String::from("\"");
    let body = bytes.strip_suffix(&[0]).unwrap_or(bytes);
    for (i, &b) in body.iter().enumerate() {
        if i >= 24 {
            o.push('\u{2026}');
            break;
        }
        match b {
            b'"' => o.push_str("\\\""),
            b'\\' => o.push_str("\\\\"),
            b'\n' => o.push_str("\\n"),
            b'\t' => o.push_str("\\t"),
            0x20..=0x7e => o.push(b as char),
            _ => {
                let _ = write!(o, "\\x{b:02x}");
            }
        }
    }
    o.push('"');
    o
}

fn loc_of(prog: Option<&Program>, cov: u32) -> Option<(String, u32)> {
    let p = prog?;
    let (_, loc) = p.cov_info.get(cov as usize)?;
    Some((p.files.get(loc.file as usize).cloned().unwrap_or_default(), loc.line))
}

fn decisions(ctx: &Ctx, t: &Track, prog: Option<&Program>, dag: &mut Dag, imp: &mut Importer) -> Vec<Decision> {
    ctx.pc
        .iter()
        .enumerate()
        .map(|(i, &c)| {
            let cond = dag.import(imp, c);
            let (side, line, addr) = if i < t.pre_len {
                (Side::Pre, None, None)
            } else {
                match t.origin(i) {
                    Origin::Src(cov) => (Side::Source, loc_of(prog, cov), None),
                    Origin::Bin(a) => (Side::Binary, None, Some(a)),
                    Origin::None => (Side::Compare, None, None),
                }
            };
            Decision { cond, side, line, addr }
        })
        .collect()
}

/// The external calls a graph's symbols tell about: `ret0:name` is the result of call 1.
fn calls_from_syms(dag: &Dag) -> Vec<String> {
    let mut calls: Vec<String> = Vec::new();
    for s in &dag.syms {
        let Some(rest) = s.strip_prefix("ret") else { continue };
        let Some((k, name)) = rest.split_once(':') else {
            continue;
        };
        let Ok(k) = k.parse::<usize>() else { continue };
        if k < 4096 {
            if calls.len() <= k {
                calls.resize(k + 1, String::new());
            }
            calls[k] = name.to_string();
        }
    }
    // A call without a result leaves a gap; what comes after it is unnamed.
    if let Some(i) = calls.iter().position(|c| c.is_empty()) {
        calls.truncate(i);
    }
    calls
}

fn goal_kind(what: &str) -> &'static str {
    let w = what;
    if w.starts_with("return value") || w.contains("returned structure") {
        "return_value"
    } else if w.starts_with("memory") {
        "memory"
    } else if w.contains("argument") || w.contains("passed to") {
        "argument"
    } else if w.starts_with("target of call") {
        "call_target"
    } else if w.contains("register") || w.starts_with("stack pointer") {
        "register"
    } else if w.contains("volatile") {
        "volatile"
    } else if w.starts_with("binary ") {
        "call_sequence"
    } else {
        "other"
    }
}

/// Build the explanation of the path that just failed, from the notes it left and the state
/// of `ctx` (which still holds the path condition and the term store).
pub(crate) fn capture(
    ctx: &Ctx,
    prog: Option<&Program>,
    fid: u32,
    outcome: &str,
    why: &str,
    env: Option<&Env>,
) -> Explanation {
    TRACK.with(|t| {
        let t = t.borrow();
        let mut e = Explanation {
            outcome: outcome.to_string(),
            ..Default::default()
        };
        let (what, reason) = match outcome {
            "bounded" => ("", why),
            _ => match why.find(": source gives").or_else(|| why.find(": prover gave up")) {
                Some(i) => (&why[..i], &why[i + 2..]),
                None => (why, why),
            },
        };
        e.what = what.to_string();
        e.reason = reason.to_string();
        e.goal = if outcome == "bounded" { "limit" } else { goal_kind(what) }.to_string();
        if let Some(p) = prog {
            e.dag.alias = aliases(p, fid);
        }
        let mut imp = Importer::new(&ctx.tm, env);
        // The goal's terms first: they are what must survive the size limit.
        if let Some((c, b)) = t.goal.filter(|_| outcome != "bounded" || why.contains("limit")) {
            e.source = Some(e.dag.import(&mut imp, c));
            e.binary = Some(e.dag.import(&mut imp, b));
            if e.goal == "memory"
                && let Some(a) = t.addr
            {
                e.address = Some(e.dag.import(&mut imp, a));
            }
        }
        e.path = decisions(ctx, &t, prog, &mut e.dag, &mut imp);
        e.assumptions = ctx.ub.iter().map(|&u| e.dag.import(&mut imp, u)).collect();
        e.dag.calls = calls_from_syms(&e.dag);
        e.src_loc = t.last_src.and_then(|c| loc_of(prog, c));
        e.bin_addr = t.last_bin;
        if let Some(env) = env {
            e.has_model = true;
            let pr = Printer::new(&e.dag, &NO_NAMES, &[], Style::default());
            let mut seen = std::collections::HashSet::new();
            for (i, (n, w)) in e.dag.nodes.iter().enumerate() {
                let Node::Sym(s) = n else { continue };
                let name = &e.dag.syms[*s as usize];
                if name == super::ELIDED
                    || name.starts_with('&')
                    || matches!(name.as_str(), "SP0" | "LR0" | "RET0")
                    || !seen.insert(name.clone())
                {
                    continue;
                }
                e.inputs.push(Input {
                    label: pr.sym_label(name),
                    name: name.clone(),
                    value: e.dag.vals[i].unwrap_or(0),
                    width: *w,
                });
            }
            e.inputs
                .sort_by_key(|i| (!e.dag.alias.contains_key(&i.name), i.name.clone()));
            let mut cells: Vec<(u32, u32, u8)> = env.mem.iter().map(|(&(m, a), &v)| (m, a as u32, v)).collect();
            cells.sort();
            cells.truncate(512);
            for (m, a, v) in cells {
                match e.memory.last_mut() {
                    Some(run) if run.0 == m && run.1.wrapping_add(run.2.len() as u32) == a && run.2.len() < 8 => {
                        run.2.push(v)
                    }
                    _ => e.memory.push((m, a, vec![v])),
                }
            }
        }
        e
    })
}

static NO_NAMES: Names = Names { objs: Vec::new() };

/// An explanation that only names a limit.
pub(crate) fn limit_only(why: &str) -> Explanation {
    Explanation {
        outcome: "bounded".into(),
        goal: "limit".into(),
        reason: why.to_string(),
        ..Default::default()
    }
}

fn src_trace(prog: Option<&Program>, cov: &[u32]) -> String {
    let mut files: Vec<(String, Vec<u32>)> = Vec::new();
    for &c in cov {
        let Some((f, l)) = loc_of(prog, c) else { continue };
        match files.iter_mut().find(|x| x.0 == f) {
            Some(x) => x.1.push(l),
            None => files.push((f, vec![l])),
        }
    }
    let mut o = Vec::new();
    for (f, mut lines) in files {
        lines.sort();
        lines.dedup();
        let mut runs: Vec<(u32, u32)> = Vec::new();
        for l in lines {
            match runs.last_mut() {
                Some(r) if r.1 + 1 == l => r.1 = l,
                _ => runs.push((l, l)),
            }
        }
        let runs: Vec<String> = runs
            .iter()
            .map(|&(a, b)| if a == b { a.to_string() } else { format!("{a}-{b}") })
            .collect();
        let short = f.rsplit('/').next().unwrap_or(&f).to_string();
        o.push(format!("{short}:{}", runs.join(",")));
    }
    o.join(" ")
}

fn bin_trace(insns: &[(u32, u8)]) -> String {
    let mut v: Vec<(u32, u32)> = insns.iter().map(|&(a, n)| (a, a + n as u32)).collect();
    v.sort();
    let mut runs: Vec<(u32, u32)> = Vec::new();
    for (a, b) in v {
        match runs.last_mut() {
            Some(r) if r.1 >= a => r.1 = r.1.max(b),
            _ => runs.push((a, b)),
        }
    }
    let runs: Vec<String> = runs.iter().map(|&(a, b)| format!("{a:#x}-{b:#x}")).collect();
    runs.join(" ")
}

fn side_dump(raw: &RawSide, source: bool, trace: String, dag: &mut Dag, imp: &mut Importer) -> SideDump {
    let mut d = SideDump {
        trace,
        effects: Vec::new(),
    };
    let mut shown: std::collections::HashSet<RawWrite> = std::collections::HashSet::new();
    let mut writes = |ws: &[RawWrite], d: &mut SideDump, dag: &mut Dag, imp: &mut Importer| {
        // The log is in program order; a later store to the same place replaces the earlier.
        let mut last: Vec<RawWrite> = Vec::new();
        for &w in ws {
            if source && !shown.insert(w) {
                continue;
            }
            last.retain(|x| !(x.0 == w.0 && x.1 == w.1));
            last.push(w);
        }
        for (a, size, v) in last {
            let (addr, val) = (dag.import(imp, a), dag.import(imp, v));
            d.effects.push(Effect::Write { addr, size, val });
        }
    };
    let vols = |k: usize, d: &mut SideDump, dag: &mut Dag, imp: &mut Importer| {
        for &(write, a, size, v, ev) in &raw.vol {
            if ev == k {
                let (addr, val) = (dag.import(imp, a), dag.import(imp, v));
                d.effects.push(Effect::Volatile { write, addr, size, val });
            }
        }
    };
    for (k, c) in raw.calls.iter().enumerate() {
        writes(&c.writes, &mut d, dag, imp);
        vols(k, &mut d, dag, imp);
        let args = c.args.iter().map(|&a| dag.import(imp, a)).collect();
        let ret = c.ret.map(|r| dag.import(imp, r));
        d.effects.push(Effect::Call {
            index: k + 1,
            name: c.name.clone(),
            args,
            ret,
        });
    }
    if raw.returned {
        writes(&raw.writes, &mut d, dag, imp);
        vols(raw.calls.len(), &mut d, dag, imp);
        let ret = raw.ret.iter().map(|(l, t)| (l.clone(), dag.import(imp, *t))).collect();
        d.effects.push(Effect::Return(ret));
    } else {
        d.effects.push(Effect::NoReturn);
    }
    d
}

/// A path has ended with `res`: turn the notes it left into a summary.
pub(crate) fn end_path<V>(ctx: &Ctx, prog: Option<&Program>, fid: u32, res: &R<V>) {
    if !dumping() {
        return;
    }
    let outcome = match res {
        Ok(_) => "proved".to_string(),
        Err(Stop::Undefined) => "the source has undefined behaviour here (nothing to prove)".into(),
        Err(Stop::Halt) => "does not return".into(),
        Err(Stop::Truncated(w)) => format!("not explored to the end: {w}"),
        Err(Stop::Mismatch(w, _)) => format!("MISMATCH: {w}"),
        Err(Stop::Inconclusive(w)) => format!("inconclusive: {w}"),
        Err(Stop::Unsupported(w)) => format!("unsupported: {w}"),
    };
    end_path_as(ctx, prog, fid, outcome);
}

pub(crate) fn end_path_as(ctx: &Ctx, prog: Option<&Program>, fid: u32, outcome: String) {
    TRACK.with(|t| {
        let mut t = t.borrow_mut();
        if t.paths.len() >= t.dump {
            t.skipped += 1;
            return;
        }
        let mut p = PathDump {
            outcome,
            ..Default::default()
        };
        if let Some(pg) = prog {
            p.dag.alias = aliases(pg, fid);
        }
        let mut imp = Importer::new(&ctx.tm, None);
        p.conds = decisions(ctx, &t, prog, &mut p.dag, &mut imp);
        p.assumptions = ctx.ub.iter().map(|&u| p.dag.import(&mut imp, u)).collect();
        if let Some(s) = &t.src {
            p.dag.calls = s.calls.iter().map(|c| c.name.clone()).collect();
            p.source = Some(side_dump(s, true, src_trace(prog, &s.cov), &mut p.dag, &mut imp));
        }
        if let Some(b) = &t.bin {
            if p.dag.calls.is_empty() {
                p.dag.calls = b.calls.iter().map(|c| c.name.clone()).collect();
            }
            p.binary = Some(side_dump(b, false, bin_trace(&b.insns), &mut p.dag, &mut imp));
        }
        t.paths.push(p);
    });
}

/// The summaries collected for the function: (paths, number left out).
pub(crate) fn take_paths() -> (Vec<PathDump>, usize) {
    TRACK.with(|t| {
        let mut t = t.borrow_mut();
        let skipped = t.skipped;
        (std::mem::take(&mut t.paths), skipped)
    })
}

// ----- rendering --------------------------------------------------------------

/// The named sub-terms that `body` (or another one that is used) mentions.
fn used_lets(lets: Vec<super::Let>, body: &str) -> Vec<super::Let> {
    let mentions = |text: &str, name: &str| {
        text.match_indices(name).any(|(i, _)| {
            !text[i + name.len()..].starts_with(|c: char| c.is_ascii_digit())
                && !text[..i].ends_with(|c: char| c.is_alphanumeric() || c == '_')
        })
    };
    let mut keep = vec![false; lets.len()];
    for i in (0..lets.len()).rev() {
        keep[i] = mentions(body, &lets[i].name)
            || (i + 1..lets.len()).any(|j| keep[j] && mentions(&lets[j].text, &lets[i].name));
    }
    lets.into_iter().zip(keep).filter(|x| x.1).map(|x| x.0).collect()
}

fn pad(s: &str, w: usize) -> String {
    let n = s.chars().count();
    if n >= w {
        s.to_string()
    } else {
        format!("{s}{}", " ".repeat(w - n))
    }
}

fn decision_origin(d: &Decision, names: &Names) -> String {
    match (&d.line, d.addr) {
        (Some((f, l)), _) => format!("source {}:{l}", f.rsplit('/').next().unwrap_or(f)),
        (None, Some(a)) => match names.locate(a) {
            Some(s) => format!("binary {a:#x} <{s}>"),
            None => format!("binary {a:#x}"),
        },
        _ => d.side.label().to_string(),
    }
}

fn mem_label(names: &Names, snapshot: u32, addr: u32, calls: &[String]) -> String {
    let mut s = match names.locate(addr) {
        Some(n) => format!("{n} ({addr:#x})"),
        None => format!("{addr:#x}"),
    };
    if snapshot & super::UNINIT != 0 {
        s.push_str(" {never written}");
    } else if snapshot > 0 {
        match calls.get(snapshot as usize - 1) {
            Some(c) => {
                let _ = write!(s, " {{after call #{snapshot} to {c}}}");
            }
            None => {
                let _ = write!(s, " {{after call #{snapshot}}}");
            }
        }
    }
    s
}

impl Explanation {
    fn roots(&self) -> Vec<u32> {
        let mut r: Vec<u32> = self.source.into_iter().chain(self.binary).chain(self.address).collect();
        r.extend(self.path.iter().filter(|d| d.side != Side::Pre).map(|d| d.cond));
        r.extend(self.assumptions.iter().copied());
        r
    }

    /// The explanation as indented text.
    pub fn text(&self, names: &Names, style: Style) -> String {
        let mut roots = self.roots();
        if style.full {
            roots.extend(self.path.iter().filter(|d| d.side == Side::Pre).map(|d| d.cond));
        }
        let pr = Printer::new(&self.dag, names, &roots, style);
        let mut o = String::new();
        let val = |n: u32| match self.dag.val(n) {
            Some(v) => format!("  = {}", show_val(v, self.dag.width(n))),
            None => String::new(),
        };
        match self.outcome.as_str() {
            "bounded" => {
                let _ = writeln!(o, "  limit:     {}", self.reason);
                match self.induction {
                    Some(true) => {
                        let _ = writeln!(
                            o,
                            "  induction: attempted, no proof found (no loop invariant strong enough within half the budget)"
                        );
                    }
                    Some(false) => {
                        let _ = writeln!(o, "  induction: not attempted (the limit was hit first)");
                    }
                    None => {}
                }
                if !self.what.is_empty() {
                    let _ = writeln!(o, "  undecided: {}", self.what);
                }
            }
            _ => {
                let _ = writeln!(o, "  compared:  {}", self.what);
                if let Some(a) = self.address {
                    let _ = writeln!(o, "  address:   {}", pr.addr(a));
                }
                if self.reason != self.what {
                    let _ = writeln!(o, "  result:    {}", self.reason);
                }
            }
        }
        let mut at = Vec::new();
        if let Some((f, l)) = &self.src_loc {
            at.push(format!("source {f}:{l}"));
        }
        if let Some(a) = self.bin_addr {
            at.push(match names.locate(a) {
                Some(s) => format!("binary {a:#x} <{s}>"),
                None => format!("binary {a:#x}"),
            });
        }
        if !at.is_empty() {
            let _ = writeln!(o, "  at:        {}", at.join(", "));
        }
        let shown: Vec<&Decision> = self.path.iter().filter(|d| style.full || d.side != Side::Pre).collect();
        let pre = self.path.len() - self.path.iter().filter(|d| d.side != Side::Pre).count();
        if self.path.is_empty() {
            // Nothing was recorded about a path (a limit on the whole function).
        } else if shown.is_empty() {
            let _ = writeln!(o, "  path:      every input (no branch decision)");
        } else {
            let _ = writeln!(o, "  path:      taken when");
            let texts: Vec<String> = shown.iter().map(|d| pr.expr(d.cond)).collect();
            let w = texts.iter().map(|t| t.chars().count()).max().unwrap_or(0).min(48);
            for (i, (d, t)) in shown.iter().zip(&texts).enumerate() {
                let _ = writeln!(o, "    {:>2}. {}  [{}]", i + 1, pad(t, w), decision_origin(d, names));
            }
        }
        if pre > 0 && !style.full {
            let _ = writeln!(
                o,
                "             (+ {pre} calling-convention preconditions; --full lists them)"
            );
        }
        if !self.assumptions.is_empty() {
            let _ = writeln!(o, "  assuming:  the source has no undefined behaviour, that is");
            for &a in &self.assumptions {
                let _ = writeln!(o, "    - {}", pr.expr(a));
            }
        }
        let mut tail = String::new();
        if let (Some(s), Some(b)) = (self.source, self.binary) {
            let (st, bt) = (pr.expr(s), pr.expr(b));
            let w = st.chars().count().max(bt.chars().count()).min(60);
            let _ = writeln!(tail, "{}", format!("  source:    {}{}", pad(&st, w), val(s)).trim_end());
            let _ = writeln!(tail, "{}", format!("  binary:    {}{}", pad(&bt, w), val(b)).trim_end());
            let d = pr.diff(s, b);
            if !(d.holes.len() == 1 && d.skeleton == d.holes[0].label) {
                let _ = writeln!(tail, "  differ in: {}", d.skeleton);
                for h in &d.holes {
                    let w = h.source.chars().count().max(h.binary.chars().count()).min(60);
                    let v = |v: Option<u64>| match v {
                        Some(v) => format!("  = {}", show_val(v, h.width)),
                        None => String::new(),
                    };
                    let _ = writeln!(tail, "    {} source: {}{}", h.label, pad(&h.source, w), v(h.source_val));
                    let _ = writeln!(tail, "        binary: {}{}", pad(&h.binary, w), v(h.binary_val));
                }
            }
        }
        let lets = used_lets(pr.lets(), &format!("{o}{tail}"));
        if !lets.is_empty() {
            let _ = writeln!(o, "  where:");
            for l in &lets {
                let v = match l.value {
                    Some(v) => format!("  = {}", show_val(v, l.width)),
                    None => String::new(),
                };
                let _ = writeln!(o, "    {} = {}{v}", l.name, l.text);
            }
        }
        o.push_str(&tail);
        if self.has_model {
            if self.inputs.is_empty() && self.memory.is_empty() {
                let _ = writeln!(o, "  counterexample: any input");
            } else {
                let _ = writeln!(o, "  counterexample:");
            }
            let w = self.inputs.iter().map(|i| i.label.chars().count()).max().unwrap_or(0);
            for i in &self.inputs {
                let raw = if i.label == i.name {
                    String::new()
                } else {
                    format!("  ({})", i.name)
                };
                let _ = writeln!(o, "    {} = {}{raw}", pad(&i.label, w), show_val(i.value, i.width));
            }
            let limit = if style.full { usize::MAX } else { 16 };
            for (m, a, bytes) in self.memory.iter().take(limit) {
                let hex: Vec<String> = bytes.iter().map(|b| format!("{b:02x}")).collect();
                let _ = writeln!(
                    o,
                    "    memory at {}: {}",
                    mem_label(names, *m, *a, &self.dag.calls),
                    hex.join(" ")
                );
            }
            if self.memory.len() > limit {
                let _ = writeln!(o, "    ... {} more memory cells (--full)", self.memory.len() - limit);
            }
        }
        o
    }

    /// The explanation as a JSON object (see the README for the schema).
    pub fn json(&self, names: &Names) -> String {
        let mut roots = self.roots();
        roots.extend(self.path.iter().filter(|d| d.side == Side::Pre).map(|d| d.cond));
        let pr = Printer::new(&self.dag, names, &roots, Style::default());
        let hex = |v: u64| format!("\"{v:#x}\"");
        let term = |n: u32| {
            let mut s = format!("{{\"text\":{},\"node\":{n}", json_str(&pr.expr(n)));
            if let Some(v) = self.dag.val(n) {
                let _ = write!(s, ",\"value\":{}", hex(v));
            }
            s.push('}');
            s
        };
        let mut o = format!(
            "{{\"outcome\":{},\"goal\":{},\"what\":{},\"reason\":{}",
            json_str(&self.outcome),
            json_str(&self.goal),
            json_str(&self.what),
            json_str(&self.reason)
        );
        if let Some(i) = self.induction {
            let _ = write!(o, ",\"induction_attempted\":{i}");
        }
        o.push_str(",\"location\":{");
        let mut loc = Vec::new();
        if let Some((f, l)) = &self.src_loc {
            loc.push(format!("\"file\":{},\"line\":{l}", json_str(f)));
        }
        if let Some(a) = self.bin_addr {
            loc.push(format!("\"address\":{a}"));
        }
        o.push_str(&loc.join(","));
        o.push('}');
        if let Some(a) = self.address {
            let _ = write!(o, ",\"address\":{}", term(a));
        }
        o.push_str(",\"path\":[");
        for (i, d) in self.path.iter().enumerate() {
            let _ = write!(
                o,
                "{}{{\"side\":{},\"condition\":{},\"node\":{}",
                if i > 0 { "," } else { "" },
                json_str(d.side.label()),
                json_str(&pr.expr(d.cond)),
                d.cond
            );
            if let Some((f, l)) = &d.line {
                let _ = write!(o, ",\"file\":{},\"line\":{l}", json_str(f));
            }
            if let Some(a) = d.addr {
                let _ = write!(o, ",\"address\":{a}");
            }
            o.push('}');
        }
        o.push_str("],\"assumptions\":[");
        for (i, &a) in self.assumptions.iter().enumerate() {
            let _ = write!(o, "{}{}", if i > 0 { "," } else { "" }, term(a));
        }
        o.push(']');
        if let (Some(s), Some(b)) = (self.source, self.binary) {
            let _ = write!(o, ",\"source\":{},\"binary\":{}", term(s), term(b));
            let d = pr.diff(s, b);
            let _ = write!(o, ",\"diff\":{{\"skeleton\":{},\"holes\":[", json_str(&d.skeleton));
            for (i, h) in d.holes.iter().enumerate() {
                let _ = write!(
                    o,
                    "{}{{\"label\":{},\"source\":{},\"binary\":{}",
                    if i > 0 { "," } else { "" },
                    json_str(&h.label),
                    json_str(&h.source),
                    json_str(&h.binary)
                );
                if let (Some(sv), Some(bv)) = (h.source_val, h.binary_val) {
                    let _ = write!(o, ",\"source_value\":{},\"binary_value\":{}", hex(sv), hex(bv));
                }
                o.push('}');
            }
            o.push_str("]}");
        }
        o.push_str(",\"lets\":[");
        for (i, l) in pr.lets().iter().enumerate() {
            let _ = write!(
                o,
                "{}{{\"name\":{},\"text\":{},\"node\":{}",
                if i > 0 { "," } else { "" },
                json_str(&l.name),
                json_str(&l.text),
                l.node
            );
            if let Some(v) = l.value {
                let _ = write!(o, ",\"value\":{}", hex(v));
            }
            o.push('}');
        }
        o.push(']');
        if self.has_model {
            o.push_str(",\"counterexample\":{\"inputs\":[");
            for (i, inp) in self.inputs.iter().enumerate() {
                let _ = write!(
                    o,
                    "{}{{\"name\":{},\"symbol\":{},\"value\":{},\"width\":{}}}",
                    if i > 0 { "," } else { "" },
                    json_str(&inp.label),
                    json_str(&inp.name),
                    hex(inp.value),
                    inp.width
                );
            }
            o.push_str("],\"memory\":[");
            for (i, (m, a, bytes)) in self.memory.iter().enumerate() {
                let list: Vec<String> = bytes.iter().map(|b| b.to_string()).collect();
                let _ = write!(
                    o,
                    "{}{{\"snapshot\":{m},\"address\":{a},\"bytes\":[{}]",
                    if i > 0 { "," } else { "" },
                    list.join(",")
                );
                if let Some(s) = names.locate(*a) {
                    let _ = write!(o, ",\"symbol\":{}", json_str(&s));
                }
                o.push('}');
            }
            o.push_str("]}");
        }
        let _ = write!(o, ",\"nodes\":{}}}", self.dag.json(&roots, names));
        o
    }
}

impl PathDump {
    fn roots(&self) -> Vec<u32> {
        let mut r: Vec<u32> = self
            .conds
            .iter()
            .filter(|d| d.side != Side::Pre)
            .map(|d| d.cond)
            .collect();
        for s in self.source.iter().chain(&self.binary) {
            for e in &s.effects {
                match e {
                    Effect::Write { addr, val, .. } | Effect::Volatile { addr, val, .. } => r.extend([*addr, *val]),
                    Effect::Call { args, ret, .. } => {
                        r.extend(args.iter().copied());
                        r.extend(*ret);
                    }
                    Effect::Return(v) => r.extend(v.iter().map(|x| x.1)),
                    Effect::NoReturn => {}
                }
            }
        }
        r
    }

    /// The path as indented text; `index` and `total` number it among the function's paths.
    pub fn text(&self, names: &Names, style: Style, index: usize, total: usize) -> String {
        let pr = Printer::new(&self.dag, names, &self.roots(), style);
        let mut o = String::new();
        let _ = writeln!(o, "  path {index} of {total}: {}", self.outcome);
        let conds: Vec<&Decision> = self.conds.iter().filter(|d| d.side != Side::Pre).collect();
        if conds.is_empty() {
            let _ = writeln!(o, "    when:   always");
        }
        let texts: Vec<String> = conds.iter().map(|d| pr.expr(d.cond)).collect();
        let w = texts.iter().map(|t| t.chars().count()).max().unwrap_or(0).min(48);
        for (i, (d, t)) in conds.iter().zip(&texts).enumerate() {
            let _ = writeln!(
                o,
                "    {}  {}  [{}]",
                if i == 0 { "when: " } else { "  and:" },
                pad(t, w),
                decision_origin(d, names)
            );
        }
        if !self.assumptions.is_empty() && style.full {
            for &a in &self.assumptions {
                let _ = writeln!(o, "    assuming (no undefined behaviour): {}", pr.expr(a));
            }
        }
        for (label, side) in [("source", &self.source), ("binary", &self.binary)] {
            let Some(s) = side else { continue };
            let _ = writeln!(o, "    {label}: {}", s.trace);
            for e in &s.effects {
                match e {
                    Effect::Write { addr, size, val } => {
                        let _ = writeln!(
                            o,
                            "      store   {} \u{2190} {}",
                            pr.lvalue(*addr, *size),
                            pr.expr(*val)
                        );
                    }
                    Effect::Volatile { write, addr, size, val } => {
                        if *write {
                            let _ = writeln!(
                                o,
                                "      volatile write  {} \u{2190} {}",
                                pr.lvalue(*addr, *size),
                                pr.expr(*val)
                            );
                        } else {
                            let _ = writeln!(
                                o,
                                "      volatile read   {} \u{2192} {}",
                                pr.lvalue(*addr, *size),
                                pr.expr(*val)
                            );
                        }
                    }
                    Effect::Call { index, name, args, ret } => {
                        let list: Vec<String> = if label == "binary" {
                            args.iter()
                                .enumerate()
                                .map(|(i, &a)| format!("r{i} = {}", pr.expr(a)))
                                .collect()
                        } else {
                            args.iter().map(|&a| pr.expr(a)).collect()
                        };
                        let r = match ret {
                            Some(r) => format!(" \u{2192} {}", pr.expr(*r)),
                            None => String::new(),
                        };
                        let _ = writeln!(o, "      call #{index} {name}({}){r}", list.join(", "));
                    }
                    Effect::Return(v) => {
                        let list: Vec<String> = v
                            .iter()
                            .map(|(l, t)| {
                                if l == "return" {
                                    pr.expr(*t)
                                } else {
                                    format!("{l} = {}", pr.expr(*t))
                                }
                            })
                            .collect();
                        let _ = writeln!(o, "      {}", format!("return  {}", list.join(", ")).trim_end());
                    }
                    Effect::NoReturn => {
                        let _ = writeln!(o, "      (does not return on this path)");
                    }
                }
            }
        }
        let lets = used_lets(pr.lets(), &o);
        if !lets.is_empty() {
            let _ = writeln!(o, "    where:");
            for l in &lets {
                let _ = writeln!(o, "      {} = {}", l.name, l.text);
            }
        }
        o
    }
}

impl FuncDetail {
    /// The path summaries of a function as text.
    pub fn dump_text(&self, names: &Names, style: Style) -> String {
        let mut o = String::new();
        let total = self.paths.len() + self.skipped_paths;
        for (i, p) in self.paths.iter().enumerate() {
            o.push_str(&p.text(names, style, i + 1, total));
        }
        if self.skipped_paths > 0 {
            let _ = writeln!(
                o,
                "  ... {} more paths not shown (--full shows every path)",
                self.skipped_paths
            );
        }
        o
    }
}