everystate 0.4.6

A lightning-fast TLA+ model checker (TLC-compatible, no Java needed)
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
1253
//! Command-line driver (port of main.ts). Accepts TLC's flags and prints TLC-compatible output,
//! including `-tool` framing, `-dump`, the XMLExporter emulation and the `java` command-line shim.
use crate::cfg::parse_config;
use crate::checker::*;
use crate::eval::StateRef;
use crate::host::{timestamp, HostRef};
use crate::intern::*;
use crate::liveness::model_check;
use crate::model::*;
use crate::modules::{def_level, Loader, SourceResolver, Sym};
use crate::pprint::ppr;
use crate::stdlib::{build_stdlib, global_defs};
use crate::value::fmt;
use std::cell::RefCell;
use std::rc::Rc;

pub const VERSION: &str = env!("CARGO_PKG_VERSION");

// ---- path helpers (pure string operations: no file-system access) ----
/// On Windows, backslashes are separators too; everything is handled with forward slashes, which
/// Windows file APIs accept.
fn norm(p: &str) -> String {
    if cfg!(windows) { p.replace('\\', "/") } else { p.to_string() }
}
/// A Windows drive prefix such as `C:` at the start of a path.
fn drive(p: &str) -> Option<&str> {
    let b = p.as_bytes();
    if cfg!(windows) && b.len() >= 2 && b[1] == b':' && b[0].is_ascii_alphabetic() { Some(&p[..2]) } else { None }
}
pub fn path_join(a: &str, b: &str) -> String {
    let (a, b) = (norm(a), norm(b));
    if b.starts_with('/') || drive(&b).is_some() || a.is_empty() {
        return b;
    }
    if a.ends_with('/') { format!("{}{}", a, b) } else { format!("{}/{}", a, b) }
}
pub fn path_resolve(cwd: &str, p: &str) -> String {
    let full = path_join(cwd, p);
    let (prefix, rest) = match drive(&full) {
        Some(d) => (d.to_string(), &full[2..]),
        None => (String::new(), &full[..]),
    };
    let mut parts: Vec<&str> = vec![];
    for seg in rest.split('/') {
        match seg {
            "" | "." => {}
            ".." => {
                parts.pop();
            }
            s => parts.push(s),
        }
    }
    format!("{}/{}", prefix, parts.join("/"))
}
fn last_sep(p: &str) -> Option<usize> {
    if cfg!(windows) { p.rfind(|c| c == '/' || c == '\\') } else { p.rfind('/') }
}
pub fn dirname(p: &str) -> String {
    match last_sep(p) {
        Some(0) => "/".to_string(),
        Some(i) => p[..i].to_string(),
        None => ".".to_string(),
    }
}
pub fn basename<'a>(p: &'a str, ext: &str) -> &'a str {
    let b = match last_sep(p) {
        Some(i) => &p[i + 1..],
        None => p,
    };
    if !ext.is_empty() && b.ends_with(ext) && b.len() > ext.len() { &b[..b.len() - ext.len()] } else { b }
}

fn commas(n: f64) -> String {
    let s = format!("{}", n.round() as i64);
    let (neg, digits) = match s.strip_prefix('-') {
        Some(d) => (true, d.to_string()),
        None => (false, s),
    };
    let mut out = String::new();
    for (i, c) in digits.chars().enumerate() {
        if i > 0 && (digits.len() - i) % 3 == 0 {
            out.push(',');
        }
        out.push(c);
    }
    if neg { format!("-{}", out) } else { out }
}

/// The value of a variable in TLC syntax; `null` for a variable the state leaves unassigned (only the
/// last state of a simulation trace that an action did not completely specify has such variables).
pub(crate) fn var_text(s: &StateRef, i: usize) -> String {
    if s.is_undef(i) { "null".to_string() } else { fmt(&s.get(i)) }
}
pub fn state_text(model: &Model, s: &StateRef) -> String {
    let vars = &model.vars;
    if vars.len() == 1 {
        return format!("{} = {}\n", vars[0].name, ppr(&var_text(s, 0)));
    }
    let mut out = String::new();
    for (i, v) in vars.iter().enumerate() {
        out += &format!("/\\ {} = {}\n", v.name, ppr(&var_text(s, i)));
    }
    out
}
/// The Java stand-in announces itself as TLC 2.19 (the tla2tools 1.7.4 release), which names a step after
/// the operator alone: `Run`. TLC since 1.8.0, which the `everystate` command follows, adds the arguments:
/// `Run(TRUE)`. Either way the error trace and the edges of `-dump dot,actionlabels` use the same name.
pub static TLC_2_19_NAMES: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
fn action_args(a: &Action) -> &str {
    if TLC_2_19_NAMES.load(std::sync::atomic::Ordering::Relaxed) {
        ""
    } else {
        &a.params
    }
}
pub fn action_label(a: Option<&Action>) -> String {
    match a {
        None => "<Initial predicate>".to_string(),
        Some(a) => format!("<{}{} line {}, col {} to line {}, col {} of module {}>", a.name, action_args(a), a.loc[0], a.loc[1], a.loc[2], a.loc[3], a.module),
    }
}

pub(crate) struct Reporter {
    pub(crate) tool: bool,
    pub(crate) host: HostRef,
    /// Simulation mode only: the label of the first state of a trace (TLC names the initial predicate
    /// there instead of printing `<Initial predicate>`).
    pub(crate) init_label: RefCell<Option<String>>,
}
impl Reporter {
    // cls: 0 none, 1 error, 2 bug, 3 warning, 4 state
    pub(crate) fn msg(&self, code: u32, cls: u32, text: &str) {
        if self.tool {
            self.host.print(&format!("@!@!@STARTMSG {}:{} @!@!@\n{}\n@!@!@ENDMSG {} @!@!@\n", code, cls, text, code));
        } else {
            let prefix = match cls {
                1 => "Error: ",
                3 => "Warning: ",
                4 => "State ",
                _ => "",
            };
            self.host.print(&format!("{}{}\n", prefix, text));
        }
    }
    fn plain(&self, text: &str) {
        self.host.print(&format!("{}\n", text));
    }
    pub(crate) fn now(&self) -> String {
        timestamp(self.host.now_ms())
    }
}

pub(crate) fn exit_code(status: &str) -> i32 {
    match status {
        "ok" => 0,
        "assumption" => 10,
        "deadlock" => 11,
        "invariant" | "invariant-init" => 12,
        "action-property" | "implied-init" | "liveness" => 13,
        "incomplete" => 75,
        _ => 255,
    }
}

/// TLC's exit status for the result of a run (EC.errorConstantToExitStatus).
pub(crate) fn exit_of(res: &CheckResult) -> i32 {
    if res.call_stack.is_some() {
        return 75;
    }
    match res.code {
        Some(2111) => 76,
        // an assumption or postcondition that is false or cannot be evaluated
        Some(2105 | 2404 | 2405 | 2780) => 10,
        // TLC: a temporal counterexample completed during the search ends the run like an invariant violation
        _ if res.finite => 12,
        _ => exit_code(res.status),
    }
}

fn arity1(a: &str) -> bool {
    matches!(
        a,
        "-workers" | "-fp" | "-metadir" | "-seed" | "-depth" | "-fpmem" | "-coverage" | "-checkpoint" | "-maxSetSize" | "-fpbits" | "-userFile" | "-recover" | "-aril"
            | "-dfid" | "-suppressMessages" | "-messagesAsErrors" | "-inv" | "-invlevel" | "-postCondition" | "-teSpecOutDir"
    )
}

fn json_str(s: &str, o: &mut String) {
    o.push('"');
    for c in s.chars() {
        match c {
            '"' => o.push_str("\\\""),
            '\\' => o.push_str("\\\\"),
            '\n' => o.push_str("\\n"),
            '\r' => o.push_str("\\r"),
            '\t' => o.push_str("\\t"),
            '\x08' => o.push_str("\\b"),
            '\x0c' => o.push_str("\\f"),
            c if (c as u32) < 0x20 => o.push_str(&format!("\\u{:04x}", c as u32)),
            c => o.push(c),
        }
    }
    o.push('"');
}

/// The `-json` result line (also what the WebAssembly API returns).
pub fn result_json(model: &Model, res: &CheckResult, extended: bool) -> String {
    let counts = format!(",\"generated\":{},\"distinct\":{},\"queue\":{},\"depth\":{}", res.generated, res.distinct, res.queue, res.depth);
    result_json_with(model, res, extended, &counts)
}

/// `result_json` with the given text for the state counts (simulation mode reports its own).
pub fn result_json_with(model: &Model, res: &CheckResult, extended: bool, counts: &str) -> String {
    let mut o = String::with_capacity(256);
    o.push_str("{\"status\":");
    json_str(res.status, &mut o);
    if let Some(n) = &res.name {
        o.push_str(",\"name\":");
        json_str(n, &mut o);
    }
    if let Some(m) = &res.message {
        o.push_str(",\"message\":");
        json_str(m, &mut o);
    }
    o.push_str(counts);
    if let Some(l) = res.loop_to {
        o.push_str(&format!(",\"loopTo\":{}", l));
    }
    if extended {
        if res.status == "liveness" {
            o.push_str(",\"loopAction\":");
            match res.loop_action {
                Some(a) => json_str(&model.actions[a].name, &mut o),
                None => o.push_str("null"),
            }
        }
        if let Some(c) = res.code {
            o.push_str(&format!(",\"code\":{}", c));
        }
        o.push_str(",\"vars\":[");
        for (j, v) in model.vars.iter().enumerate() {
            if j > 0 {
                o.push(',');
            }
            json_str(&v.name.to_string(), &mut o);
        }
        o.push(']');
    }
    if let Some(tr) = &res.trace {
        o.push_str(",\"trace\":[");
        for (i, t) in tr.iter().enumerate() {
            if i > 0 {
                o.push(',');
            }
            o.push_str("{\"action\":");
            match t.action {
                Some(a) => json_str(&model.actions[a].name, &mut o),
                None => o.push_str("null"),
            }
            o.push_str(",\"state\":{");
            for (j, v) in model.vars.iter().enumerate() {
                if j > 0 {
                    o.push(',');
                }
                json_str(&v.name.to_string(), &mut o);
                o.push(':');
                json_str(&var_text(&t.state, j), &mut o);
            }
            o.push_str("}}");
        }
        o.push(']');
    }
    o.push('}');
    o
}

pub fn setup_error_json(e: &Fail) -> (String, i32) {
    let (kind, msg) = match e {
        Fail::Tla(t) => (t.kind, t.msg.clone()),
        Fail::Check { message, .. } => ("error", message.clone()),
        Fail::Found => ("error", "internal error".to_string()),
    };
    let mut o = String::from("{\"status\":\"setup-error\",\"kind\":");
    json_str(kind, &mut o);
    o.push_str(",\"message\":");
    json_str(&msg, &mut o);
    o.push('}');
    (o, if kind == "config" { 151 } else { 150 })
}

struct CliEvents<'r> {
    rep: &'r Reporter,
    json: bool,
    first: bool,
}
impl Events for CliEvents<'_> {
    fn init_done(&mut self, init_generated: u64, init_distinct: u64) {
        if self.json {
            return;
        }
        self.first = false;
        let rep = self.rep;
        rep.msg(2189, 0, "Computing initial states...");
        if init_generated == init_distinct {
            rep.msg(2190, 0, &format!("Finished computing initial states: {} distinct state{} generated at {}.", init_distinct, if init_distinct == 1 { "" } else { "s" }, rep.now()));
        } else {
            rep.msg(
                2191,
                0,
                &format!("Finished computing initial states: {} state{} generated, with {} of them distinct at {}.", init_generated, if init_generated == 1 { "" } else { "s" }, init_distinct, rep.now()),
            );
        }
    }
    fn progress(&mut self, depth: u32, generated: u64, distinct: u64, queue: u64) {
        if self.json {
            return;
        }
        let rep = self.rep;
        rep.msg(
            2200,
            0,
            &format!("Progress({}) at {}: {} states generated, {} distinct states found, {} states left on queue.", depth, rep.now(), commas(generated as f64), commas(distinct as f64), commas(queue as f64)),
        );
    }
    fn note(&mut self, text: &str) {
        if !self.json {
            self.rep.plain(text);
        }
    }
    fn liveness(&mut self, phase: &str, branches: usize, depth: u32, generated: u64, distinct: u64) {
        if self.json {
            return;
        }
        let rep = self.rep;
        match phase {
            "branches" => rep.msg(2212, 0, &format!("Implied-temporal checking--satisfiability problem has {} branches.", branches)),
            // "start": the check of the complete graph at the end; "current": a periodic check of the
            // graph of the `distinct` states expanded so far (TLC prints no progress line before that
            // one); "off": -lncheck off, the end of the search without a check
            "start" | "current" | "off" => {
                if !rep.tool && phase != "current" {
                    rep.msg(
                        2200,
                        0,
                        &format!("Progress({}) at {}: {} states generated, {} distinct states found, 0 states left on queue.", depth, rep.now(), commas(generated as f64), commas(distinct as f64)),
                    );
                }
                if phase != "off" {
                    rep.msg(
                        2192,
                        0,
                        &format!(
                            "Checking {}temporal properties for the {} state space with {} total distinct states at ({})",
                            if branches > 1 { format!("{} branches of ", branches) } else { String::new() },
                            if phase == "start" { "complete" } else { "current" },
                            distinct as usize * branches,
                            rep.now()
                        ),
                    );
                }
            }
            _ => rep.msg(2267, 0, &format!("Finished checking temporal properties in 00s at {}", rep.now())),
        }
    }
}

const USAGE: &str = concat!("everystate ", env!("CARGO_PKG_VERSION"), " - a TLA+ model checker (TLC-compatible command line)\n\nUsage: everystate [options] SPEC[.tla]\n\n  -config FILE        configuration file (default: SPEC.cfg)\n  -deadlock           do not check for deadlock\n  -simulate [num=N][,file=PREFIX]   random simulation: generate N behaviors instead of all states\n                      (without num=N it runs until an error is found; with -json the default is 1000)\n  -depth N            simulation: maximal length of a behavior (default 100)\n  -seed N, -aril N    simulation: seed of the random choices (the same seed repeats the run)\n  -tool               machine-readable output (TLC's -tool message framing)\n  -dump [dot[,actionlabels]] FILE   write the reachable state graph\n  -json               print a single JSON result object instead of TLC-style output\n  -workers N|auto     search with N threads (auto: one per core); the result is the same as with 1\n  -store sqlite:FILE  keep the states found in the SQLite database FILE instead of in memory\n                      (one worker; needs a build with the sqlite feature)\n  -lncheck default|final|off   when temporal properties are checked: during the search and at the\n                      end (default), at the end only (final), never (off)\n  -fp N, -metadir DIR, ...   accepted for compatibility\n\n       everystate conform [options] -trace TRACE SPEC[.tla]\n\n  checks that a recorded run of the real system (JSON Lines) is a behaviour of the spec;\n  exit status 0 conforms, 20 does not conform (see: everystate conform -help)\n\nExit status: 0 success, 10 assumption, 11 deadlock, 12 safety, 13 liveness, 150 parse error, 151 config error.\n");

/// `-store sqlite:FILE`: the provider that keeps the states in that database.
#[cfg(feature = "sqlite")]
fn open_store(file: &str) -> Result<Box<dyn crate::store::StateStore>, String> {
    // EVERYSTATE_STORE_CHUNK: bytes per chunk (test hook)
    let chunk = std::env::var("EVERYSTATE_STORE_CHUNK").ok().and_then(|v| v.parse().ok());
    Ok(Box::new(crate::store::sql::File::open(file, chunk)?))
}
#[cfg(not(feature = "sqlite"))]
fn open_store(_: &str) -> Result<Box<dyn crate::store::StateStore>, String> {
    Err("this build has no SQLite state store".into())
}

/// The number of cores, which is what `-workers auto` means.
fn cores() -> usize {
    #[cfg(not(target_arch = "wasm32"))]
    return std::thread::available_parallelism().map_or(1, |n| n.get());
    #[cfg(target_arch = "wasm32")]
    1
}

/// `-workers N` with N > 1. EVERYSTATE_PAR_MIN (smallest level searched in parallel; setting it also
/// starts the workers at once) and EVERYSTATE_PAR_CHUNK (states per unit of work) are test hooks.
#[cfg(not(target_arch = "wasm32"))]
fn par_config(workers: usize, root_name: &str, cfg_text: String, sources: Vec<(String, String)>) -> Option<ParConfig> {
    if workers < 2 {
        return None;
    }
    let num = |k: &str| std::env::var(k).ok().and_then(|v| v.parse::<usize>().ok());
    let min = num("EVERYSTATE_PAR_MIN");
    Some(ParConfig {
        workers,
        factory: crate::par::model_factory(root_name.to_string(), cfg_text, sources),
        min_frontier: min.unwrap_or(64).max(1),
        eager: min.is_some(),
        chunk: num("EVERYSTATE_PAR_CHUNK").unwrap_or(0),
    })
}
#[cfg(target_arch = "wasm32")]
fn par_config(_: usize, _: &str, _: String, _: Vec<(String, String)>) -> Option<ParConfig> {
    None
}

struct Dump {
    file: String,
    dot: bool,
    opts: String,
}

/// Module sources: the spec's directory, then the library paths, then the bundled modules.
pub fn file_resolver(host: HostRef, dirs: Vec<String>, parsed: Rc<RefCell<Vec<String>>>) -> SourceResolver {
    Box::new(move |name: &str| {
        for d in &dirs {
            let p = path_join(d, &format!("{}.tla", name));
            if host.exists(&p) {
                if let Ok(bytes) = host.read_file(&p) {
                    parsed.borrow_mut().push(p);
                    return Some(String::from_utf8_lossy(&bytes).into_owned());
                }
            }
        }
        crate::bundled::BUNDLED.iter().find(|(n, _)| *n == name).map(|(_, s)| s.to_string())
    })
}

pub fn run_cli(argv: &[String], host: HostRef, library_paths: &[String]) -> i32 {
    // `everystate conform ...`: trace conformance (a lone `conform` is still the spec conform.tla)
    if argv.len() > 1 && argv[0] == "conform" {
        return crate::conform::run_cli(&argv[1..], host, library_paths);
    }
    if argv.first().map(|a| a == "pcal").unwrap_or(false) {
        // `everystate pcal [options] File`: the PlusCal translator
        return crate::pcal::trans::run(&argv[1..], host);
    }
    let mut spec: Option<String> = None;
    let mut config: Option<String> = None;
    let (mut deadlock, mut tool, mut json) = (true, false, false);
    let mut dump: Option<Dump> = None;
    let mut workers: usize = 1;
    // EVERYSTATE_LNCHECK_FIRST: the number of expanded states at the first periodic liveness check (test hook)
    let mut lncheck = match std::env::var("EVERYSTATE_LNCHECK_FIRST").ok().and_then(|v| v.parse::<usize>().ok()) {
        Some(first) => LnCheck::Periodic { first },
        None => LnCheck::default(),
    };
    let mut sim = crate::simulate::SimArgs::default();
    // -store sqlite:FILE: the database the states are kept in; None = memory
    let mut store_file: Option<String> = None;
    let mut ignored: Vec<&str> = vec![];
    let mut i = 0;
    while i < argv.len() {
        let a = argv[i].as_str();
        match a {
            "-workers" => {
                i += 1;
                workers = match argv.get(i).map(|s| s.as_str()) {
                    Some("auto") => cores(),
                    Some(n) => match n.parse::<usize>() {
                        Ok(n) if n >= 1 => n,
                        Ok(_) => {
                            host.print("Error: Error: at least one worker required.\n");
                            return 1;
                        }
                        Err(_) => {
                            host.print(&format!("Error: Error: worker number or 'auto' required. But encountered {}\n", n));
                            return 1;
                        }
                    },
                    None => {
                        host.print("Error: Error: expect an integer or 'auto' for -workers option.\n");
                        return 1;
                    }
                };
            }
            "-config" => {
                i += 1;
                config = argv.get(i).cloned();
            }
            "-lncheck" => {
                // TLC (TLC.java, TLCGlobals.doLiveness): the value is lower-cased; final and seqfinal check
                // the temporal properties at the end only, off not at all, and every other word is the
                // default without a complaint.
                i += 1;
                match argv.get(i).map(|s| s.to_lowercase()).as_deref() {
                    Some("final") | Some("seqfinal") => lncheck = LnCheck::Final,
                    Some("off") => lncheck = LnCheck::Off,
                    Some(_) => {}
                    None => {
                        host.print("Error: Error: expect a strategy such as final for -lncheck option.\n");
                        return 1;
                    }
                }
            }
            "-store" => {
                i += 1;
                store_file = match argv.get(i).map(|s| s.as_str()) {
                    Some(f) if f.len() > 7 && f.starts_with("sqlite:") && cfg!(feature = "sqlite") => Some(f[7..].to_string()),
                    Some(f) if f.starts_with("sqlite:") && !cfg!(feature = "sqlite") => {
                        host.print("Error: Error: this build has no SQLite state store (build it with: cargo build --release --features sqlite).\n");
                        return 1;
                    }
                    _ => {
                        host.print("Error: Error: expect sqlite:FILE for -store option.\n");
                        return 1;
                    }
                };
            }
            "-deadlock" => deadlock = false,
            "-cdot" | "-Dtlc2.tool.impl.Tool.cdot=true" => crate::eval::CDOT.store(true, std::sync::atomic::Ordering::Relaxed),
            "-tool" => tool = true,
            "-json" => json = true,
            "-dump" => {
                i += 1;
                let x = argv.get(i).cloned().unwrap_or_default();
                if x == "dot" || x.starts_with("dot,") {
                    i += 1;
                    dump = Some(Dump { file: argv.get(i).cloned().unwrap_or_default(), dot: true, opts: x.to_lowercase() });
                } else {
                    dump = Some(Dump { file: x, dot: false, opts: String::new() });
                }
            }
            "-dumpTrace" | "-loadTrace" => {
                ignored.push(a);
                i += 2;
            }
            "-simulate" | "-generate" | "-depth" | "-seed" | "-aril" => {
                if let Err(e) = sim.parse(argv, &mut i) {
                    host.print(&format!("{}\n", e));
                    return 1;
                }
            }
            "-h" | "-help" | "--help" => {
                host.print(USAGE);
                host.print(crate::pcal::USAGE);
                return 0;
            }
            "-version" | "--version" => {
                host.print(&format!("everystate {}\n", VERSION));
                return 0;
            }
            // TLC options that change what is checked or reported, and are not implemented
            "-continue" | "-difftrace" | "-view" => ignored.push(a),
            "-dfid" | "-recover" | "-inv" | "-invlevel" | "-postCondition" => {
                ignored.push(a);
                i += 1;
            }
            _ if arity1(a) => i += 1,
            // TLC options without an effect on the result here, and Java's own options from the stand-in
            "-cleanup" | "-nowarning" | "-terse" | "-gzip" | "-debug" | "-noGenerateSpecTE" | "-noGenerateSpecTEBin" => {}
            _ if a.eq_ignore_ascii_case("-noTE") || a.eq_ignore_ascii_case("-noTEBin") => {}
            "-debugger" => {
                if argv.get(i + 1).is_some_and(|x| x.starts_with("nosuspend") || x.starts_with("port")) {
                    i += 1;
                }
            }
            _ if a.starts_with("-D") || a.starts_with("-X") => {}
            _ if a.starts_with('-') => {
                host.print(&format!("Error: Error: unrecognized option: {}\n", a));
                host.print(USAGE);
                return 1;
            }
            _ => {
                if let Some(s) = &spec {
                    host.print(&format!("Error: more than one input files: {} and {}\n", s, a));
                    return 1;
                }
                spec = Some(a.to_string());
            }
        }
        i += 1;
    }
    let spec = match spec {
        Some(s) => s,
        None => {
            host.print(&format!("Error: Missing input TLA+ module.\n{}", USAGE));
            return 1;
        }
    };
    if !json {
        for o in &ignored {
            let what = match *o {
                "-continue" => "the check stops at the first violation",
                "-difftrace" => "traces print every variable in every state",
                "-dumpTrace" | "-loadTrace" => "no trace file is written or read",
                "-recover" => "the check starts from the initial states",
                "-dfid" => "the search is breadth-first",
                _ => "it has no effect",
            };
            host.print(&format!("Warning: the option {} is not supported by everystate: {}.\n", o, what));
        }
    }
    let spec_path = if spec.ends_with(".tla") { spec.clone() } else { format!("{}.tla", spec) };
    let cwd = host.cwd();
    let dir = dirname(&path_resolve(&cwd, &spec_path));
    let root_name = basename(&spec_path, ".tla").to_string();
    let mut cfg_path = config.clone().unwrap_or_else(|| format!("{}.cfg", root_name));
    if !cfg_path.ends_with(".cfg") && !host.exists(&cfg_path) && !host.exists(&path_join(&dir, &cfg_path)) {
        cfg_path.push_str(".cfg");
    }
    if !host.exists(&cfg_path) || config.is_none() {
        let in_dir = path_join(&dir, &cfg_path);
        if host.exists(&in_dir) {
            cfg_path = in_dir;
        }
    }
    let rep = Reporter { tool, host: host.clone(), init_label: RefCell::new(None) };
    let t0 = host.now_ms();
    let parsed: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(vec![]));
    let mut libs = vec![dir.clone()];
    libs.extend(library_paths.iter().cloned());
    let resolve = file_resolver(host.clone(), libs, parsed.clone());
    // -workers N: the worker threads build their own copy of the model from what is read here
    // (simulation runs on one thread, whatever the number of workers asked for)
    let sim = sim.options(json, host.now_ms());
    // -store: a store is read and written by one thread, in state order; simulation keeps no states
    let mut notes: Vec<&str> = vec![];
    if store_file.is_some() && sim.is_some() {
        store_file = None;
        notes.push("Note: -simulate keeps no states, so the state store (-store) is not used.");
    } else if store_file.is_some() && workers > 1 {
        notes.push("Note: with a state store (-store) the search runs on one worker; -workers is not used.");
    }
    let workers = if cfg!(target_arch = "wasm32") || sim.is_some() || store_file.is_some() { 1 } else { workers };
    crate::eval::WORKERS.store(workers, std::sync::atomic::Ordering::Relaxed);
    let sources: Rc<RefCell<Vec<(String, String)>>> = Rc::new(RefCell::new(vec![]));
    let cfg_text: RefCell<String> = RefCell::new(String::new());
    let resolve: SourceResolver = if workers > 1 {
        let sources = sources.clone();
        Box::new(move |name: &str| {
            let text = resolve(name);
            if let Some(t) = &text {
                sources.borrow_mut().push((name.to_string(), t.clone()));
            }
            text
        })
    } else {
        resolve
    };
    let pad = |n: i64| format!("{:02}", n);
    let finish = |code: i32| -> i32 {
        let ms = (host.now_ms() - t0).max(0.0) as i64;
        let s = ms / 1000;
        let dur = if tool {
            format!("{}ms", ms)
        } else if s < 60 {
            format!("{}s", pad(s))
        } else if s < 3600 {
            format!("{}min {}s", pad(s / 60), pad(s % 60))
        } else {
            format!("{}h {}min", pad(s / 3600), pad((s % 3600) / 60))
        };
        if !json {
            rep.msg(2186, 0, &format!("Finished in {} at ({})", dur, rep.now()));
        }
        code
    };
    if !json {
        rep.msg(2262, 0, &format!("TLC2 Version 2.19 of 08 August 2024 (everystate {})", VERSION));
        match &sim {
            Some(o) => rep.msg(2188, 0, &format!("Running Random Simulation with seed {} with 1 worker on 1 cores with 0MB heap and 0MB offheap memory (everystate {}, Rust).", o.seed, VERSION)),
            None => rep.msg(
                2187,
                0,
                &format!(
                    "Running breadth-first search Model-Checking with fp 0 and seed 0 with {} with 0MB heap and 0MB offheap memory (everystate {}, Rust, HashFPSet, MemStateQueue).",
                    if workers > 1 { format!("{} workers on {} cores", workers, cores()) } else { "1 worker on 1 cores".to_string() },
                    VERSION
                ),
            ),
        }
    }
    if !json {
        for n in &notes {
            rep.plain(n);
        }
    }
    let setup: R<Model> = (|| {
        if !host.exists(&cfg_path) {
            return err("config", format!("TLC encountered the following error reading the configuration file {}:\nFile not found.", cfg_path));
        }
        let text = String::from_utf8_lossy(&host.read_file(&cfg_path).unwrap_or_default()).into_owned();
        let cfg = parse_config(&text)?;
        *cfg_text.borrow_mut() = text;
        if !json && tool {
            rep.msg(2220, 0, "Starting SANY...");
        }
        let m = build_model(&root_name, resolve, &cfg, host.clone());
        if !json {
            // like SANY, say so when a PlusCal algorithm or its translation changed since it was translated
            let pcal = crate::pcal::trans::check_translations(&host, &parsed.borrow(), &root_name);
            for (i, p) in parsed.borrow().iter().enumerate() {
                rep.plain(&format!("Parsing file {}", p));
                host.print(&pcal.after_file[i]);
            }
            // (SANY gets as far as the warnings only if every module could be read and parsed)
            if !matches!(&m, Err(e) if matches!(&**e, Fail::Tla(t) if t.kind == "parse" || t.msg.starts_with("Cannot find source file"))) {
                host.print(&pcal.warnings);
            }
        }
        let m = m?;
        if !json {
            for name in &m.loader.load_order {
                rep.plain(&format!("Semantic processing of module {}", name));
            }
            if tool {
                rep.msg(2219, 0, "SANY finished.");
            }
        }
        Ok(m)
    })();
    let model = match setup {
        Ok(m) => m,
        Err(e) => {
            if json {
                let (o, code) = setup_error_json(&e);
                host.print(&format!("{}\n", o));
                return code;
            }
            return match &*e {
                Fail::Tla(t) if t.kind == "config" => {
                    rep.msg(1000, 1, &t.msg);
                    finish(151)
                }
                Fail::Tla(t) => {
                    rep.plain(&t.msg);
                    rep.msg(3002, 1, "Parsing or semantic analysis failed.");
                    finish(150)
                }
                _ => {
                    rep.msg(1000, 1, "internal error during setup");
                    finish(255)
                }
            };
        }
    };
    if !json {
        rep.msg(2185, 0, &format!("Starting... ({})", rep.now()));
    }
    if let Some(o) = &sim {
        let code = crate::simulate::run_cli(&rep, &model, o, deadlock, json, t0);
        return if json { code } else { finish(code) };
    }
    let mut events = CliEvents { rep: &rep, json, first: true };
    let par = par_config(workers, &root_name, cfg_text.take(), sources.take());
    let store = match store_file.as_deref().map(open_store) {
        None => None,
        Some(Ok(s)) => Some(s),
        Some(Err(e)) => {
            let e = Fail::Tla(TlaError { msg: format!("The state store cannot be opened: {}", e), loc: None, module: None, kind: "config" });
            if json {
                host.print(&format!("{}\n", setup_error_json(&e).0));
                return 151;
            }
            if let Fail::Tla(t) = &e {
                rep.msg(1000, 1, &t.msg);
            }
            return finish(151);
        }
    };
    let (res, checker) = model_check(&model, CheckOptions { check_deadlock: deadlock && model.check_deadlock, record_graph: dump.is_some(), lncheck, par, store }, &mut events);
    let first = events.first;
    if let Some(d) = &dump {
        if let Err(e) = write_dump(&model, &checker, d, &host) {
            rep.msg(1000, 1, &format!("Failed to write the state dump: {}", e));
        }
    }
    if json {
        host.print(&format!("{}\n", result_json(&model, &res, false)));
        return exit_of(&res);
    }
    if first {
        rep.msg(2189, 0, "Computing initial states...");
    }
    report(&rep, &model, &res, t0);
    finish(exit_of(&res))
}

/// ALIAS: the text TLC prints for a trace state when the configuration names an alias
/// (Tool.evalAlias and RecordValue.PrintTLCState).  `Ok(None)`: print the plain state.
/// `Err`: formatting threw, with the Java exception class and message.
fn alias_text(model: &Model, cur: &StateRef, nxt: &StateRef) -> Result<Option<String>, (String, String)> {
    let p = match &model.alias {
        Some(p) => p,
        None => return Ok(None),
    };
    let ev = crate::eval::ev();
    ev.set_state(cur, Some(nxt));
    ev.init_mode.set(false);
    ev.prime_depth.set(0);
    ev.call_depth.set(0);
    ev.n_assigned.set(0);
    let mut fields: Vec<(String, crate::value::Value)> = vec![];
    match ev.eval(p.e, &p.ctx) {
        Ok(crate::value::Value::Record(r)) => {
            // TLC prints the fields in the order of the record constructor, not sorted
            let mut order: Vec<StrId> = vec![];
            if let Some(Sym::Def(d)) = model.root.syms.get(name(&p.name)) {
                if let Some(b) = d.body.get() {
                    if let crate::ast::E::Rec(fs, _) = &b.e {
                        order = fs.iter().map(|f| f.0).collect();
                    }
                }
            }
            for id in order.iter().chain(r.names.iter()) {
                let k = str_of(*id).to_string();
                if fields.iter().any(|f| f.0 == k) {
                    continue;
                }
                if let Some(v) = r.get(*id) {
                    fields.push((k, v.clone()));
                }
            }
        }
        Ok(_) => return Ok(None),
        Err(e) => match *e {
            crate::intern::Fail::Tla(t) => {
                for (i, v) in model.vars.iter().enumerate() {
                    fields.push((v.name.to_string(), cur.get(i)));
                }
                fields.push(("_ALIASEvalError".into(), crate::value::Value::Str(str_id(&t.msg))));
            }
            _ => return Ok(None),
        },
    }
    let fi = fields.iter().position(|f| f.0 == "_format");
    let format = match fi {
        Some(i) => match &fields[i].1 {
            crate::value::Value::Str(s) => str_of(*s).to_string(),
            _ => return Err(("java.lang.ClassCastException".into(), "the _format field of an ALIAS must be a string".into())),
        },
        None => (if fields.len() == 1 { "%s = %s\n" } else { "/\\ %s = %s\n" }).to_string(),
    };
    let mut out = String::new();
    for (i, (k, v)) in fields.iter().enumerate() {
        if Some(i) == fi {
            continue;
        }
        match crate::community::java_format(&format, &[k.clone(), ppr(&fmt(v))]) {
            Ok(t) => out += &t,
            Err(_) => {
                // a conversion other than %s applied to a string argument
                let c: Vec<char> = format.chars().collect();
                let mut j = 0;
                while j < c.len() {
                    if c[j] == '%' {
                        j += 1;
                        while j < c.len() && !c[j].is_ascii_alphabetic() && c[j] != '%' {
                            j += 1;
                        }
                        if j < c.len() && !"sSn%".contains(c[j]) {
                            return Err(("java.util.IllegalFormatConversionException".into(), format!("{} != java.lang.String", c[j])));
                        }
                    }
                    j += 1;
                }
                return Err(("java.util.MissingFormatArgumentException".into(), format!("Format specifier in '{}'", format)));
            }
        }
    }
    Ok(Some(out))
}

fn print_trace(rep: &Reporter, model: &Model, res: &CheckResult) {
    if let Some(tr) = &res.trace {
        let init_label = rep.init_label.borrow();
        for (i, t) in tr.iter().enumerate() {
            let label = match (&*init_label, i) {
                (Some(l), 0) => l.clone(),
                _ => action_label(if i == 0 { None } else { t.action.map(|a| &model.actions[a]) }),
            };
            // the successor used for primed variables in an ALIAS: the next trace state, the state the
            // lasso returns to, or the state itself
            let nxt = match tr.get(i + 1) {
                Some(n) => &n.state,
                None => match res.loop_to {
                    Some(l) if l >= 0 && (l as usize) < tr.len() => &tr[l as usize].state,
                    _ => &t.state,
                },
            };
            // (TLCGet("level") in an ALIAS is the position of the state in the trace, as in TLC)
            let level = model.ev.stats.level.replace(i as i64 + 1);
            let alias = alias_text(model, &t.state, nxt);
            model.ev.stats.level.set(level);
            let text = match alias {
                Ok(Some(x)) => x,
                Ok(None) => state_text(model, &t.state),
                Err((class, m)) => {
                    rep.msg(
                        1000,
                        1,
                        &format!("TLC threw an unexpected exception.\nThis was probably caused by an error in the spec or model.\nSee the User Output or TLC Console for clues to what happened.\nThe exception was a {}\n: {}", class, m),
                    );
                    return;
                }
            };
            rep.msg(2217, 4, &format!("{}: {}\n{}", i + 1, label, text));
        }
    }
}

fn exp1(p: f64) -> String {
    // Number.prototype.toExponential(1), with Java's exponent format
    if p == 0.0 {
        return "0.0".into();
    }
    let s = format!("{:.1e}", p);
    s.replace('e', "E")
}

pub(crate) fn report(rep: &Reporter, model: &Model, res: &CheckResult, t0: f64) {
    let progress_line = || {
        let mins = ((rep.host.now_ms() - t0) / 60000.0).max(1e-6);
        rep.msg(
            2200,
            0,
            &format!(
                "Progress({}) at {}: {} states generated ({} s/min), {} distinct states found ({} ds/min), {} states left on queue.",
                res.depth,
                rep.now(),
                commas(res.generated as f64),
                commas(res.generated as f64 / mins),
                commas(res.distinct as f64),
                commas(res.distinct as f64 / mins),
                commas(res.queue as f64)
            ),
        );
    };
    let summary = || {
        if rep.tool {
            progress_line();
        }
        rep.msg(2199, 0, &format!("{} states generated, {} distinct states found, {} states left on queue.", res.generated, res.distinct, res.queue));
        rep.msg(2194, 0, &format!("The depth of the complete state graph search is {}.", res.depth));
        if let Some(o) = &res.outdegree {
            if res.status == "ok" || (rep.tool && !res.finite) {
                rep.msg(
                    2268,
                    0,
                    &format!("The average outdegree of the complete state graph is {} (minimum is {}, the maximum {} and the 95th percentile is {}).", o.avg, o.min, o.max, o.p95),
                );
            }
        }
    };
    let first_state = || res.trace.as_ref().map(|t| state_text(model, &t[0].state)).unwrap_or_default();
    let name = res.name.as_deref().unwrap_or("undefined");
    match res.status {
        "ok" => {
            let p = res.distinct as f64 * ((res.generated as f64 - res.distinct as f64) / 18446744073709551616.0);
            rep.msg(
                2193,
                0,
                &format!(
                    "Model checking completed. No error has been found.\n  Estimates of the probability that TLC did not check all reachable states\n  because two distinct states had the same fingerprint:\n  calculated (optimistic):  val = {}",
                    exp1(p)
                ),
            );
            summary();
            return;
        }
        "assumption" => {
            rep.msg(2104, 1, res.message.as_deref().unwrap_or(""));
            return;
        }
        "invariant-init" => {
            rep.msg(2107, 1, &format!("Invariant {} is violated by the initial state:\n{}", name, first_state()));
            return;
        }
        "implied-init" => {
            rep.msg(2108, 1, &format!("Property {} is violated by the initial state:\n{}", name, first_state()));
            return;
        }
        "invariant" => rep.msg(2110, 1, &format!("Invariant {} is violated.", name)),
        "action-property" => rep.msg(2112, 1, &format!("Action property {} is violated.", name)),
        "deadlock" => rep.msg(2114, 1, "Deadlock reached."),
        "liveness" => {
            rep.msg(2116, 1, "Temporal properties were violated.\n");
            rep.msg(2264, 1, "The following behavior constitutes a counter-example:\n");
            print_trace(rep, model, res);
            if res.finite {
                // found during the search: the behaviour ends in its last state (TLC prints no stuttering line)
                summary();
                return;
            }
            let n = res.trace.as_ref().map_or(0, |t| t.len());
            let la = action_label(res.loop_action.map(|a| &model.actions[a]));
            match res.loop_to {
                Some(l) if l >= 0 => {
                    if rep.tool {
                        rep.msg(2122, 4, &format!("{}: Back to state: {}\n", l + 1, la));
                    } else {
                        rep.host.print(&format!("Back to state {}: {}\n\n", l + 1, la));
                    }
                }
                _ => rep.msg(2218, 4, &format!("{}: Stuttering", n + 1)),
            }
            if rep.init_label.borrow().is_some() {
                return; // simulation prints its own statistics
            }
            rep.msg(2267, 0, &format!("Finished checking temporal properties in 00s at {}", rep.now()));
            if rep.tool {
                progress_line();
            }
            rep.msg(2199, 0, &format!("{} states generated, {} distinct states found, {} states left on queue.", res.generated, res.distinct, res.queue));
            return;
        }
        "incomplete" => rep.msg(2109, 1, &format!("{}\n", res.message.as_deref().unwrap_or(""))),
        _ => {
            let m = res.message.as_deref().unwrap_or("unknown error");
            if let Some(code) = res.code {
                rep.msg(code, 1, m);
            } else {
                if let Some(tr) = &res.trace {
                    if tr.len() == 1 && tr[0].id == -1 && tr[0].action.is_none() {
                        rep.msg(2102, 1, &format!("{}\nWhile working on the initial state:\n{}", m, state_text(model, &tr[0].state)));
                        if res.print_summary {
                            summary();
                        }
                        return;
                    }
                }
                rep.msg(
                    1000,
                    1,
                    &format!("TLC threw an unexpected exception.\nThis was probably caused by an error in the spec or model.\nSee the User Output or TLC Console for clues to what happened.\nThe exception was a java.lang.RuntimeException\n: {}", m),
                );
            }
        }
    }
    if res.trace.as_ref().map_or(false, |t| !t.is_empty()) {
        rep.msg(2121, 1, "The behavior up to this point is:");
        print_trace(rep, model, res);
    }
    if let Some(a) = &res.also {
        rep.msg(2116, 1, "Temporal properties were violated.\n");
        rep.msg(2264, 1, "The following behavior constitutes a counter-example:\n");
        print_trace(rep, model, a);
    }
    if let Some(cs) = &res.call_stack {
        rep.msg(2103, 1, &format!("The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\n{}", cs));
    }
    if res.print_summary {
        summary();
    }
}

fn write_dump(model: &Model, checker: &Checker, dump: &Dump, host: &HostRef) -> Result<(), String> {
    // (one state at a time: with a state store they are not in memory)
    let n = checker.states.len();
    if !dump.dot {
        let mut out = String::new();
        for i in 0..n {
            out += &format!("State {}:\n{}\n", i + 1, state_text(model, &checker.state_at(i)));
        }
        let file = if dump.file.ends_with(".dump") { dump.file.clone() } else { format!("{}.dump", dump.file) };
        return host.write_file(&file, out.as_bytes());
    }
    let labels = dump.opts.contains("actionlabels");
    let esc = |s: &str| -> String { s.replace('\\', "\\\\").replace('"', "\\\"").trim().replace('\n', "\\n") };
    let mut ids: Vec<String> = Vec::with_capacity(n);
    for i in 0..n {
        ids.push((crate::tshash::fingerprint(checker, &checker.state_at(i)).map_err(|_| "cannot fingerprint a state".to_string())?).to_string());
    }
    let mut lines: Vec<String> = vec!["strict digraph DiskGraph {".into(), "nodesep=0.35;".into(), "subgraph cluster_graph {".into(), "color=\"white\";".into()];
    // ranks: level -> state ids in insertion order
    let mut ranks: Vec<(u32, Vec<usize>)> = vec![];
    let mut rank = |i: usize, ranks: &mut Vec<(u32, Vec<usize>)>| {
        let l = checker.level_of(i);
        match ranks.iter_mut().find(|r| r.0 == l) {
            Some(r) => {
                if !r.1.contains(&i) {
                    r.1.push(i);
                }
            }
            None => ranks.push((l, vec![i])),
        }
    };
    let mut written = vec![false; n];
    for &i in &checker.inits {
        let i = i as usize;
        lines.push(format!("{} [label=\"{}\",style = filled]", ids[i], esc(&state_text(model, &checker.state_at(i)))));
        written[i] = true;
        rank(i, &mut ranks);
    }
    for s in 0..n {
        let empty: Vec<u32> = vec![];
        let (su, sa) = (checker.succ.get(s).unwrap_or(&empty), checker.succ_act.get(s).unwrap_or(&empty));
        for j in 0..su.len() {
            let t = su[j] as usize;
            let a = &model.actions[sa[j] as usize];
            lines.push(format!("{} -> {} [label=\"{}\",color=\"black\",fontcolor=\"black\"];", ids[s], ids[t], if labels { esc(&format!("{}{}", a.name, action_args(a))) } else { String::new() }));
            rank(s, &mut ranks);
            if !written[t] {
                written[t] = true;
                lines.push(format!("{} [label=\"{}\"];", ids[t], esc(&state_text(model, &checker.state_at(t)))));
            }
        }
    }
    ranks.sort_by_key(|r| r.0);
    for (_, set) in &ranks {
        lines.push(format!("{{rank = same; {}}}", set.iter().map(|i| format!("{};", ids[*i])).collect::<String>()));
    }
    lines.push("}".into());
    lines.push("}".into());
    let file = if dump.file.ends_with(".dot") { dump.file.clone() } else { format!("{}.dot", dump.file) };
    host.write_file(&file, (lines.join("\n") + "\n").as_bytes())
}

/// Emulates `java ... tla2sany.xml.XMLExporter [-o] [-I dir] SPEC`: a minimal XML description of the
/// root module (variables, definitions and their levels), enough for tools that only need the symbol table.
pub fn run_xml_exporter(argv: &[String], host: HostRef, library_paths: &[String], quiet: bool) -> i32 {
    let mut specs: Vec<String> = vec![];
    let mut libs: Vec<String> = vec![];
    let mut i = 0;
    while i < argv.len() {
        if argv[i] == "-I" {
            i += 1;
            if let Some(d) = argv.get(i) {
                libs.push(d.clone());
            }
        } else if quiet && matches!(argv[i].as_str(), "-suppressMessages" | "-messagesAsErrors") {
            i += 1;
        } else if !argv[i].starts_with('-') {
            specs.push(argv[i].clone());
        }
        i += 1;
    }
    if specs.is_empty() {
        host.print(if quiet { "At least 1 filename is required.\nTry 'SANY -help' for more information.\n" } else { "Usage: XMLExporter [-o] [-I dir] SPEC\n" });
        return 1;
    }
    // SANY (`quiet`: no XML) checks every file it is given, in order, and stops at the first with an error
    let first = if quiet { 0 } else { specs.len() - 1 };
    for spec in &specs[first..] {
        let code = xml_export(spec, &host, &libs, library_paths, quiet);
        if code != 0 {
            return code;
        }
    }
    0
}

fn xml_export(spec: &str, host: &HostRef, libs: &[String], library_paths: &[String], quiet: bool) -> i32 {
    let spec_path = if spec.ends_with(".tla") { spec.to_string() } else { format!("{}.tla", spec) };
    let dir = dirname(&path_resolve(&host.cwd(), &spec_path));
    let root_name = basename(&spec_path, ".tla").to_string();
    let mut dirs = vec![dir];
    dirs.extend(libs.iter().cloned());
    dirs.extend(library_paths.iter().cloned());
    let resolve = file_resolver(host.clone(), dirs, Rc::new(RefCell::new(vec![])));
    let mut loader = Loader::new(resolve, build_stdlib());
    loader.globals = global_defs();
    match loader.load(name(&root_name), None) {
        Ok(root) => {
            let esc = |t: &str| t.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;");
            let mut uid = 1;
            let mut entries = String::new();
            let mut refs = String::new();
            for v in &root.vars {
                uid += 1;
                refs += &format!("<OpDeclNodeRef><UID>{}</UID></OpDeclNodeRef>", uid);
                entries += &format!("<entry><UID>{}</UID><OpDeclNode><level>1</level><uniquename>{}</uniquename><arity>0</arity><kind>3</kind></OpDeclNode></entry>", uid, esc(&v.name.to_string()));
            }
            for c in &root.consts {
                uid += 1;
                refs += &format!("<OpDeclNodeRef><UID>{}</UID></OpDeclNodeRef>", uid);
                entries += &format!("<entry><UID>{}</UID><OpDeclNode><level>0</level><uniquename>{}</uniquename><arity>{}</arity><kind>2</kind></OpDeclNode></entry>", uid, esc(&c.name.to_string()), c.arity);
            }
            for (nm, sym) in &root.syms.items {
                if let Sym::Def(d) = sym {
                    if d.builtin.get().is_some() {
                        continue;
                    }
                    uid += 1;
                    refs += &format!("<UserDefinedOpKindRef><UID>{}</UID></UserDefinedOpKindRef>", uid);
                    entries += &format!(
                        "<entry><UID>{}</UID><UserDefinedOpKind><level>{}</level><uniquename>{}</uniquename><arity>{}</arity></UserDefinedOpKind></entry>",
                        uid,
                        def_level(d),
                        esc(&nm.to_string()),
                        d.params.len()
                    );
                }
            }
            if quiet {
                return 0;
            }
            host.print(&format!(
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<modules><RootModule>{}</RootModule><context><entry><UID>1</UID><ModuleNode><uniquename>{}</uniquename>{}</ModuleNode></entry>{}</context></modules>\n",
                esc(&root_name),
                esc(&root_name),
                refs,
                entries
            ));
            0
        }
        Err(e) => {
            let msg = match &*e {
                Fail::Tla(t) => t.msg.clone(),
                _ => "error".to_string(),
            };
            host.print(&format!("{}\n*** Errors: 1\n", msg));
            1
        }
    }
}

/// Emulates the `java` command line of the TLA+ tools, so that scripts which shell out to
/// `java -cp tla2tools.jar tlc2.TLC ...` can run on everystate unchanged.
pub fn run_java_shim(argv: &[String], host: HostRef) -> i32 {
    TLC_2_19_NAMES.store(true, std::sync::atomic::Ordering::Relaxed);
    let mut libs: Vec<String> = vec![];
    let mut i = 0;
    while i < argv.len() {
        let a = &argv[i];
        if let Some(l) = a.strip_prefix("-DTLA-Library=") {
            libs.extend(l.split([':', ';']).filter(|x| !x.is_empty()).map(|x| x.to_string()));
        } else if a == "-Dtlc2.tool.impl.Tool.cdot=true" {
            crate::eval::CDOT.store(true, std::sync::atomic::Ordering::Relaxed);
        } else if a == "-cp" || a == "-classpath" || a == "-jar" {
            i += 1;
        } else if a == "-version" || a == "--version" {
            // what a tool asks before it runs a jar: Java answers -version on stderr, --version on stdout
            let line = format!("openjdk version \"21\" (everystate {} standing in for java)\n", env!("CARGO_PKG_VERSION"));
            if a == "-version" {
                eprint!("{}", line);
            } else {
                host.print(&line);
            }
            return 0;
        } else if !a.starts_with('-') {
            break;
        }
        i += 1;
    }
    let main = argv.get(i).map(|s| s.as_str());
    let rest: &[String] = if i + 1 <= argv.len() { &argv[(i + 1).min(argv.len())..] } else { &[] };
    match main {
        Some("tlc2.TLC") => run_cli(rest, host, &libs),
        Some("tla2sany.xml.XMLExporter") => run_xml_exporter(rest, host, &libs, false),
        Some("tla2sany.SANY") => run_xml_exporter(rest, host, &libs, true),
        Some("pcal.trans") => crate::pcal::trans::run(rest, host),
        _ => {
            host.print(&format!("everystate java shim: unsupported main class {}\n", main.unwrap_or("(none)")));
            1
        }
    }
}