everystate 0.4.3

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
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
//! Module loading, symbol tables and static name resolution (port of modules.ts).
use crate::ast::*;
use crate::eval::{Ctx, Evaluator};
use crate::intern::*;
use crate::parser::parse_module;
use crate::value::Value;
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, HashSet};
use std::rc::Rc;

pub struct Decl {
    pub is_var: bool,
    pub name: Name,
    pub arity: usize,
    pub idx: Cell<i32>, // variable index (vars only; assigned for the root module)
    pub module: Name,
    pub value: RefCell<Option<Value>>,     // constants: value from the config
    pub subst: Cell<Option<&'static Def>>, // constants: replaced by a definition (C <- Def)
}

pub type NativeFn = fn(&Evaluator, &[Value]) -> R<Value>;
pub enum BFn {
    Native(NativeFn),
    Const(Value),
    /// constant operator defined by `F(v1, ..., vn) = value` lines in the config
    Table(RefCell<Vec<(Vec<Value>, Value)>>, Name),
}
pub struct Builtin {
    pub f: BFn,
    pub ops: u32,   // bit i set: argument i is operator-valued
    pub lazy: bool, // receives unevaluated thunks
    /// integer operators the evaluator computes inline: 1 +, 2 -, 3 <, 4 >, 5 <=, 6 >= (0: none)
    pub arith: u8,
}

pub struct Inst {
    pub orig: &'static Def,
    pub substs: Rc<Vec<InstSubst>>,
    pub nparams: usize,
    pub env_cache: RefCell<Option<Option<Rc<Ctx>>>>,
}

pub struct Def {
    pub name: Name,
    pub params: Vec<Param>,
    pub body: Cell<Option<N>>,
    pub module: Name,
    pub local: bool,
    pub loc: Loc,
    pub builtin: Cell<Option<&'static Builtin>>,
    pub inst: Option<Inst>,
    pub cache: RefCell<Option<Value>>,
    pub level: Cell<i8>,
    pub over: Cell<Option<&'static Def>>, // config replacement (Op <- Other)
    pub refs: RefCell<Option<Rc<RefCell<HashSet<Name>>>>>,
    pub enabled_only: RefCell<Vec<Option<bool>>>,
}
impl Def {
    pub fn new(name: Name, params: Vec<Param>, body: Option<N>, module: Name, local: bool, loc: Loc) -> Def {
        Def {
            name,
            params,
            body: Cell::new(body),
            module,
            local,
            loc,
            builtin: Cell::new(None),
            inst: None,
            cache: RefCell::new(None),
            level: Cell::new(-1),
            over: Cell::new(None),
            refs: RefCell::new(None),
            enabled_only: RefCell::new(Vec::new()),
        }
    }
    #[inline]
    pub fn resolved(&'static self) -> &'static Def {
        match self.over.get() {
            Some(d) => d,
            None => self,
        }
    }
}
pub fn leak<T>(x: T) -> &'static T {
    Box::leak(Box::new(x))
}

#[derive(Copy, Clone)]
pub enum Sym {
    Decl(&'static Decl),
    Def(&'static Def),
}
impl Sym {
    fn same(&self, o: &Sym) -> bool {
        match (self, o) {
            (Sym::Decl(a), Sym::Decl(b)) => std::ptr::eq(*a, *b),
            (Sym::Def(a), Sym::Def(b)) => std::ptr::eq(*a, *b),
            _ => false,
        }
    }
    pub fn module(&self) -> Name {
        match self {
            Sym::Decl(d) => d.module,
            Sym::Def(d) => d.module,
        }
    }
    fn is_inst(&self) -> bool {
        matches!(self, Sym::Def(d) if d.inst.is_some())
    }
}

/// Insertion-ordered map (JS Map semantics: re-setting a key keeps its position).
#[derive(Default, Clone)]
pub struct OrdMap {
    idx: HashMap<Name, usize>,
    pub items: Vec<(Name, Sym)>,
}
impl OrdMap {
    pub fn get(&self, k: Name) -> Option<Sym> {
        self.idx.get(&k).map(|&i| self.items[i].1)
    }
    pub fn set(&mut self, k: Name, v: Sym) {
        match self.idx.get(&k) {
            Some(&i) => self.items[i].1 = v,
            None => {
                self.idx.insert(k, self.items.len());
                self.items.push((k, v));
            }
        }
    }
}

pub struct Assume {
    pub e: N,
    pub name: Option<Name>,
    pub module: Name,
    /// AXIOM: parsed and resolved like ASSUME, but TLC does not evaluate it (SpecProcessor.assumptionIsAxiom).
    pub axiom: bool,
}

#[derive(Default)]
pub struct ModuleInfo {
    pub name: Option<Name>,
    pub syms: OrdMap,
    pub exports: OrdMap,
    pub consts: Vec<&'static Decl>,
    pub vars: Vec<&'static Decl>,
    pub assumes: Vec<&'static Assume>,
    pub own_defs: Vec<&'static Def>,
}

pub type SourceResolver = Box<dyn Fn(&str) -> Option<String>>;

type Scope = Vec<(Name, bool, Option<LocalDef>)>;

pub struct Loader {
    pub modules: HashMap<Name, Rc<ModuleInfo>>,
    pub builtins: HashMap<Name, Rc<ModuleInfo>>,
    pub resolve_source: SourceResolver,
    pub load_order: Vec<Name>,
    loading: HashSet<Name>,
    pub globals: OrdMap,
    extra_sources: HashMap<String, String>,
    /// name resolution: the identifiers bound and the labels met since the enclosing definition or label
    lab: (Vec<Name>, Vec<Name>),
}

fn sem_err<T>(msg: String, loc: Option<Loc>, module: Name) -> R<T> {
    Err(Box::new(Fail::Tla(TlaError { msg, loc, module: Some(name_str(module).to_string()), kind: "semantic" })))
}

fn contains_ptr<T>(v: &[&'static T], x: &'static T) -> bool {
    v.iter().any(|y| std::ptr::eq(*y, x))
}

impl Loader {
    pub fn new(resolve_source: SourceResolver, builtins: HashMap<Name, Rc<ModuleInfo>>) -> Loader {
        Loader { modules: HashMap::new(), builtins, resolve_source, load_order: vec![], loading: HashSet::new(), globals: OrdMap::default(), extra_sources: HashMap::new(), lab: Default::default() }
    }

    fn scan_extra_modules(&mut self, src: &str) {
        // /^[ \t]*-{4,}[ \t]*MODULE[ \t]+(\w+)[ \t]*-{4,}/gm
        let mut first = true;
        let mut offset = 0usize;
        let mut nl = 0usize;
        for line in src.split('\n') {
            let b = line.as_bytes();
            let mut i = 0;
            let ws = |i: &mut usize| {
                while *i < b.len() && (b[*i] == b' ' || b[*i] == b'\t') {
                    *i += 1;
                }
            };
            let dashes = |i: &mut usize| -> bool {
                let s = *i;
                while *i < b.len() && b[*i] == b'-' {
                    *i += 1;
                }
                *i - s >= 4
            };
            ws(&mut i);
            let mut found: Option<String> = None;
            if dashes(&mut i) {
                ws(&mut i);
                if line[i..].starts_with("MODULE") {
                    i += 6;
                    let s = i;
                    ws(&mut i);
                    if i > s {
                        let w = i;
                        while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'_') {
                            i += 1;
                        }
                        if i > w {
                            let word = &line[w..i];
                            ws(&mut i);
                            if dashes(&mut i) {
                                found = Some(word.to_string());
                            }
                        }
                    }
                }
            }
            if let Some(w) = found {
                if first {
                    first = false;
                } else if !self.extra_sources.contains_key(&w) {
                    self.extra_sources.insert(w, "\n".repeat(nl) + &src[offset..]);
                }
            }
            offset += line.len() + 1;
            nl += 1;
        }
    }

    pub fn load(&mut self, name: Name, from: Option<Name>) -> R<Rc<ModuleInfo>> {
        if let Some(m) = self.modules.get(&name) {
            return Ok(m.clone());
        }
        if let Some(b) = self.builtins.get(&name) {
            let b = b.clone();
            self.modules.insert(name, b.clone());
            return Ok(b);
        }
        if self.loading.contains(&name) {
            return sem_err(format!("Circular dependency among modules involving {}", name), None, name);
        }
        let mut src = (self.resolve_source)(&name_str(name));
        // A file may hold several top-level modules; the later ones are found by name when no file exists.
        match &src {
            None => src = self.extra_sources.get(&*name_str(name)).cloned(),
            Some(s) => {
                let s = s.clone();
                self.scan_extra_modules(&s)
            }
        }
        let src = match src {
            Some(s) => s,
            None => {
                let msg = format!("Cannot find source file for module {}{}.", name, from.map(|f| format!(" imported in module {}", f)).unwrap_or_default());
                return Err(Box::new(Fail::Tla(TlaError { msg, loc: None, module: from.map(|f| name_str(f).to_string()), kind: "semantic" })));
            }
        };
        self.loading.insert(name);
        let ast: &'static ModuleNode = leak(parse_module(&src, &name_str(name))?);
        if ast.name != name {
            return sem_err(format!("File name '{}' does not match the name '{}' of the top level module it contains.", name, ast.name), None, name);
        }
        let info = Rc::new(self.process(ast, None)?);
        self.loading.remove(&name);
        self.modules.insert(name, info.clone());
        self.load_order.push(name);
        Ok(info)
    }

    fn process(&mut self, ast: &'static ModuleNode, outer: Option<&ModuleInfo>) -> R<ModuleInfo> {
        let mut info = ModuleInfo { name: Some(ast.name), ..Default::default() };
        if let Some(o) = outer {
            for (k, v) in &o.syms.items {
                info.syms.set(*k, *v);
            }
        }
        let mut inner: HashMap<Name, Rc<ModuleInfo>> = HashMap::new();
        fn add(info: &mut ModuleInfo, outer: Option<&ModuleInfo>, me: Name, name: Name, sym: Sym, local: bool, loc: Loc) -> R<()> {
            if let Some(prev) = info.syms.get(name) {
                if !prev.same(&sym) {
                    let own = sym.module() == me && !sym.is_inst();
                    let prev_own = prev.module() == me && !prev.is_inst();
                    if !own {
                        return Ok(()); // imported symbols: first one wins
                    }
                    if prev_own && !outer.map_or(false, |o| o.syms.get(name).map_or(false, |x| x.same(&prev))) {
                        return sem_err(format!("Multiply-defined symbol '{}' in module {}", name, me), Some(loc), me);
                    }
                }
            }
            info.syms.set(name, sym);
            if !local {
                info.exports.set(name, sym);
            }
            Ok(())
        }
        let me = ast.name;
        for m in &ast.extends {
            let ext = self.load(*m, Some(me))?;
            for (k, v) in &ext.exports.items {
                add(&mut info, outer, me, *k, *v, false, [0; 4])?;
            }
            for c in &ext.consts {
                if !contains_ptr(&info.consts, c) {
                    info.consts.push(c);
                }
            }
            for v in &ext.vars {
                if !contains_ptr(&info.vars, v) {
                    info.vars.push(v);
                }
            }
            for a in &ext.assumes {
                if !contains_ptr(&info.assumes, a) {
                    info.assumes.push(a);
                }
            }
        }
        let mut resolve_later: Vec<(&'static InstNode, Rc<Vec<InstSubst>>)> = vec![];
        let mut theorem_defs: Vec<&'static Def> = vec![];
        for u in &ast.units {
            match u {
                Unit::Variables(names) => {
                    for n in names {
                        let d = leak(Decl { is_var: true, name: *n, arity: 0, idx: Cell::new(-1), module: me, value: RefCell::new(None), subst: Cell::new(None) });
                        info.vars.push(d);
                        add(&mut info, outer, me, *n, Sym::Decl(d), false, [0; 4])?;
                    }
                }
                Unit::Constants(decls) => {
                    for p in decls {
                        let d = leak(Decl { is_var: false, name: p.name, arity: p.arity, idx: Cell::new(-1), module: me, value: RefCell::new(None), subst: Cell::new(None) });
                        info.consts.push(d);
                        add(&mut info, outer, me, p.name, Sym::Decl(d), false, [0; 4])?;
                    }
                }
                Unit::Def(dn) => {
                    let def = leak(Def::new(dn.name, dn.params.clone(), Some(&dn.body), me, dn.local, dn.loc));
                    add(&mut info, outer, me, dn.name, Sym::Def(def), dn.local, dn.loc)?;
                    info.own_defs.push(def);
                }
                Unit::Instance(u) => {
                    // importInstance
                    let m = match inner.get(&u.module) {
                        Some(m) => m.clone(),
                        None => self.load(u.module, Some(me))?,
                    };
                    let mut explicit: HashMap<Name, N> = HashMap::new();
                    for (sn, se) in &u.substs {
                        if !m.consts.iter().any(|c| c.name == *sn) && !m.vars.iter().any(|v| v.name == *sn) {
                            return sem_err(format!("Substitution target '{}' is not a CONSTANT or VARIABLE of module {}", sn, u.module), Some(u.loc), me);
                        }
                        explicit.insert(*sn, se);
                    }
                    let mut substs: Vec<InstSubst> = vec![];
                    for d in m.consts.iter().chain(m.vars.iter()) {
                        let e: N = match explicit.get(&d.name) {
                            Some(e) => e,
                            None => leak(Node::new(u.loc, E::App { name: d.name, args: vec![], sel: None, r: Cell::new(Res::None), implicit: true })),
                        };
                        substs.push(InstSubst { name: d.name, e, arity: d.arity });
                    }
                    let substs = Rc::new(substs);
                    let prefix = u.name;
                    for (nm, sym) in &m.exports.items {
                        let sd = match sym {
                            Sym::Def(d) => *d,
                            _ => continue,
                        };
                        if sd.builtin.get().is_some() && prefix.is_none() {
                            add(&mut info, outer, me, *nm, *sym, u.local, sd.loc)?;
                            continue;
                        }
                        if substs.is_empty() && u.params.is_empty() && prefix.is_none() {
                            add(&mut info, outer, me, *nm, *sym, u.local, sd.loc)?;
                            continue;
                        }
                        let dname = match prefix {
                            Some(p) => name(&format!("{}!{}", p, nm)),
                            None => *nm,
                        };
                        let mut params = u.params.clone();
                        params.extend(sd.params.iter().cloned());
                        let mut def = Def::new(dname, params, None, me, u.local, sd.loc);
                        def.inst = Some(Inst { orig: sd, substs: substs.clone(), nparams: u.params.len(), env_cache: RefCell::new(None) });
                        let def = leak(def);
                        add(&mut info, outer, me, dname, Sym::Def(def), u.local, sd.loc)?;
                    }
                    resolve_later.push((u, substs));
                }
                Unit::Assume { name: nm, e, loc, axiom } => {
                    info.assumes.push(leak(Assume { e, name: *nm, module: me, axiom: *axiom }));
                    if let Some(nm) = nm {
                        let def = leak(Def::new(*nm, vec![], Some(e), me, false, *loc));
                        add(&mut info, outer, me, *nm, Sym::Def(def), false, *loc)?;
                    }
                }
                Unit::Theorem { name: nm, e, loc } => {
                    if let Some(nm) = nm {
                        if !matches!(e.e, E::AssumeProve) {
                            let def = leak(Def::new(*nm, vec![], Some(e), me, false, *loc));
                            add(&mut info, outer, me, *nm, Sym::Def(def), false, *loc)?;
                            info.own_defs.push(def);
                            theorem_defs.push(def);
                        }
                    }
                }
                Unit::Module(m) => {
                    let i = self.process(m, Some(&info))?;
                    inner.insert(m.name, Rc::new(i));
                }
                Unit::Recursive => {}
            }
        }
        // pass 2: resolve names
        for d in info.own_defs.clone() {
            let mut scope: Scope = d.params.iter().map(|p| (p.name, false, None)).collect();
            let body = d.body.get().unwrap();
            self.lab = Default::default();
            if let Err(e) = self.resolve(body, &mut scope, &info) {
                // Theorems may mention things we do not model (proof-only constructs); ignore them.
                if !matches!(*e, Fail::Tla(_)) || !contains_ptr(&theorem_defs, d) {
                    return Err(e);
                }
                d.body.set(Some(leak(Node::new(d.loc, E::Bool(true)))));
            }
        }
        for a in info.assumes.clone() {
            if a.module == me {
                self.lab = Default::default();
                self.resolve(a.e, &mut vec![], &info)?;
            }
        }
        for (u, substs) in resolve_later {
            let mut scope: Scope = u.params.iter().map(|p| (p.name, false, None)).collect();
            self.lab = Default::default();
            for s in substs.iter() {
                if matches!(s.e.e, E::App { .. }) {
                    s.e.op_arg.set(true);
                }
                self.resolve(s.e, &mut scope, &info)?;
            }
        }
        for s in &ast.strings {
            str_id(s);
        }
        Ok(info)
    }

    fn resolve_bounds(&mut self, bs: &'static [Bound], scope: &mut Scope, m: &ModuleInfo) -> R<()> {
        for b in bs {
            if let Some(s) = &b.set {
                self.resolve(s, scope, m)?;
            }
        }
        Ok(())
    }

    fn resolve(&mut self, n: N, scope: &mut Scope, m: &ModuleInfo) -> R<()> {
        n.module.set(m.name);
        let mark = scope.len();
        // a label names the identifiers bound since the enclosing definition or label (SANY checks this where the
        // label is, so that a selector can supply all of them)
        let mut outer = None;
        for w in &n.wraps {
            if let Wrap::Label(x, ps) = w {
                let bad = if self.lab.1.contains(x) {
                    Some(format!("Duplicate label `{}'.", x))
                } else if let Some(p) = ps.iter().find(|p| !self.lab.0.contains(p)) {
                    Some(format!("Illegal parameter {} of label `{}'.", p, x))
                } else {
                    self.lab.0.iter().find(|b| !ps.contains(b)).map(|b| format!("Label {} must contain formal parameter `{}'.", x, b))
                };
                if let Some(msg) = bad {
                    return sem_err(msg, Some(n.loc), m.name.unwrap());
                }
                self.lab.1.push(*x);
                let o = std::mem::take(&mut self.lab);
                outer.get_or_insert(o);
            }
        }
        let lmark = self.lab.0.len();
        fn push_bound(scope: &mut Scope, b: &Bound) {
            if let Some(ns) = &b.names {
                scope.extend(ns.iter().map(|x| (*x, false, None)));
            } else if let Some(t) = &b.tuple {
                scope.extend(t.iter().map(|x| (*x, false, None)));
            }
        }
        match &n.e {
            E::Num(_) | E::Str(..) | E::Bool(_) | E::At | E::StepRef | E::AssumeProve => {}
            E::App { name: nm, args, sel, r, .. } => {
                let l = n.loc;
                let me = m.name.unwrap();
                if let Some(e) = scope.iter_mut().rev().find(|e| e.0 == *nm) {
                    if sel.as_ref().map_or(false, |s| s.iter().any(|p| !matches!(p.k, SelK::Name(_)))) {
                        return sem_err(format!("Cannot take subexpression of `{}'.", nm), Some(l), me);
                    }
                    e.1 = true;
                    r.set(Res::Local);
                    if e.2.is_some() {
                        n.ld.set(e.2);
                    }
                } else {
                    // the shortest prefix A!B that is a symbol; what follows it selects a subexpression
                    let find = |x: Name| m.syms.get(x).or_else(|| self.globals.get(x));
                    let mut found = (find(*nm), &[][..], args.len());
                    if let Some(parts) = sel {
                        let mut pre = String::new();
                        let mut given = 0;
                        for (i, p) in parts.iter().enumerate() {
                            let SelK::Name(x) = p.k else { break };
                            pre = if i == 0 { x.to_string() } else { format!("{}!{}", pre, x) };
                            given += p.nargs;
                            if let Some(s) = find(name(&pre)) {
                                found = (Some(s), &parts[i + 1..], given);
                                break;
                            }
                        }
                    }
                    let (sym, rest, given) = match found {
                        (Some(s), rest, given) => (s, rest, given),
                        _ => return sem_err(format!("Unknown operator: `{}'.", nm), Some(l), me),
                    };
                    let (want, base) = match sym {
                        Sym::Decl(d) => {
                            r.set(Res::Decl(d));
                            (if d.is_var { 0 } else { d.arity }, None)
                        }
                        Sym::Def(d) => {
                            r.set(Res::Def(d));
                            (d.resolved().params.len(), Some(d))
                        }
                    };
                    // arity check (a bare operator name is fine where an operator argument is expected)
                    let exact = !(args.is_empty() && n.op_arg.get());
                    if given != want && exact {
                        return sem_err(
                            format!("line {}, col {} to line {}, col {} of module {}\n\nThe operator {} requires {} arguments.", l[0], l[1], l[2], l[3], me, nm, want),
                            Some(l),
                            me,
                        );
                    }
                    if !rest.is_empty() {
                        let full = name(&sel_text(sel.as_ref().unwrap()));
                        match base.map_or_else(|| Err(format!("Cannot take subexpression of `{}'.", nm)), |d| sub_def(full, d, rest, exact)) {
                            Ok(d) => r.set(Res::Def(d)),
                            Err(e) => return sem_err(format!("line {}, col {} to line {}, col {} of module {}\n\n{}", l[0], l[1], l[2], l[3], me, e), Some(l), me),
                        }
                    }
                }
                for a in args {
                    if let E::App { args: aa, .. } = &a.e {
                        if aa.is_empty() {
                            a.op_arg.set(true);
                        }
                    }
                    self.resolve(a, scope, m)?;
                }
            }
            E::Quant { bounds, body, .. } => {
                self.resolve_bounds(bounds, scope, m)?;
                for b in bounds {
                    push_bound(scope, b);
                }
                self.lab.0.extend(scope[mark..].iter().map(|e| e.0));
                self.resolve(body, scope, m)?;
            }
            E::SetMap { e, bounds } => {
                self.resolve_bounds(bounds, scope, m)?;
                for b in bounds {
                    push_bound(scope, b);
                }
                self.lab.0.extend(scope[mark..].iter().map(|e| e.0));
                self.resolve(e, scope, m)?;
            }
            E::FnDef { bounds, body, recname, is_rec } => {
                self.resolve_bounds(bounds, scope, m)?;
                for b in bounds {
                    push_bound(scope, b);
                }
                self.lab.0.extend(scope[mark..].iter().map(|e| e.0));
                if let Some(rn) = recname {
                    scope.push((*rn, false, Some(LocalDef::Fn)));
                }
                self.resolve(body, scope, m)?;
                if let Some(rn) = recname {
                    // the innermost entry with that name within this frame
                    let used = scope[mark..].iter().rev().find(|e| e.0 == *rn).map_or(false, |e| e.1);
                    is_rec.set(used);
                }
            }
            E::Choose { bound, body } => {
                if let Some(s) = &bound.set {
                    self.resolve(s, scope, m)?;
                }
                push_bound(scope, bound);
                self.lab.0.extend(scope[mark..].iter().map(|e| e.0));
                self.resolve(body, scope, m)?;
            }
            E::SetFilter { bound, pred } => {
                if let Some(s) = &bound.set {
                    self.resolve(s, scope, m)?;
                }
                push_bound(scope, bound);
                self.lab.0.extend(scope[mark..].iter().map(|e| e.0));
                self.resolve(pred, scope, m)?;
            }
            E::TQuant { names, body } => {
                scope.extend(names.iter().map(|x| (*x, false, None)));
                self.lab.0.extend(scope[mark..].iter().map(|e| e.0));
                self.resolve(body, scope, m)?;
            }
            E::Lambda { params, body } => {
                scope.extend(params.iter().map(|p| (p.name, false, None)));
                self.lab.0.extend(scope[mark..].iter().map(|e| e.0));
                self.resolve(body, scope, m)?;
            }
            E::Let { defs, body } => {
                let mut names: Vec<Name> = vec![];
                for d in defs.iter() {
                    match d {
                        LetDef::Def(d) => names.push(d.name),
                        LetDef::Inst(d) => {
                            if d.inst_defs.get().is_none() {
                                let im = self.load(d.module, m.name)?;
                                let mut substs = vec![];
                                for c in im.consts.iter().chain(im.vars.iter()) {
                                    let e: N = match d.substs.iter().find(|x| x.0 == c.name) {
                                        Some(x) => &x.1,
                                        None => leak(Node::new(d.loc, E::App { name: c.name, args: vec![], sel: None, r: Cell::new(Res::None), implicit: true })),
                                    };
                                    substs.push(InstSubst { name: c.name, arity: c.arity, e });
                                }
                                let substs = Rc::new(substs);
                                let mut idefs: Vec<&'static Def> = vec![];
                                let prefix = d.name.map(|x| name_str(x).to_string()).unwrap_or_else(|| "null".into());
                                for (nm, sym) in &im.exports.items {
                                    if let Sym::Def(sd) = sym {
                                        let mut params = d.params.clone();
                                        params.extend(sd.params.iter().cloned());
                                        let mut def = Def::new(name(&format!("{}!{}", prefix, nm)), params, None, m.name.unwrap(), true, sd.loc);
                                        def.inst = Some(Inst { orig: sd, substs: substs.clone(), nparams: d.params.len(), env_cache: RefCell::new(None) });
                                        idefs.push(leak(def));
                                    }
                                }
                                let _ = d.inst_substs.set(substs);
                                let _ = d.inst_defs.set(idefs);
                            }
                            for x in d.inst_defs.get().unwrap() {
                                names.push(x.name);
                            }
                        }
                    }
                }
                let let_start = scope.len();
                scope.extend(names.iter().map(|x| (*x, false, None)));
                for d in defs.iter() {
                    if let LetDef::Def(d) = d {
                        if d.params.is_empty() {
                            if let Some(e) = scope[let_start..].iter_mut().rev().find(|e| e.0 == d.name) {
                                e.2 = Some(LocalDef::Let(d));
                            }
                        }
                    }
                }
                let s = scope.len();
                for d in defs.iter() {
                    match d {
                        LetDef::Inst(d) => {
                            scope.extend(d.params.iter().map(|p| (p.name, false, None)));
                            for x in d.inst_substs.get().unwrap().iter() {
                                if matches!(x.e.e, E::App { .. }) {
                                    x.e.op_arg.set(true);
                                }
                                self.resolve(x.e, scope, m)?;
                            }
                            scope.truncate(s);
                        }
                        LetDef::Def(d) => {
                            scope.extend(d.params.iter().map(|p| (p.name, false, None)));
                            let o = std::mem::take(&mut self.lab);
                            self.resolve(&d.body, scope, m)?;
                            self.lab = o;
                            // keep `used` marks of outer names; drop the parameter frame
                            scope.truncate(s);
                        }
                    }
                }
                self.resolve(body, scope, m)?;
            }
            E::Case { arms, other } => {
                for (c, e) in arms {
                    self.resolve(c, scope, m)?;
                    self.resolve(e, scope, m)?;
                }
                if let Some(o) = other {
                    self.resolve(o, scope, m)?;
                }
            }
            E::Rec(fields, _) | E::RecSet(fields) => {
                for (_, e) in fields {
                    self.resolve(e, scope, m)?;
                }
            }
            E::Except { base, updates } => {
                self.resolve(base, scope, m)?;
                for (path, val) in updates {
                    for p in path {
                        self.resolve(p, scope, m)?;
                    }
                    self.resolve(val, scope, m)?;
                }
            }
            E::FnApp { f, args } => {
                self.resolve(f, scope, m)?;
                for a in args {
                    self.resolve(a, scope, m)?;
                }
            }
            E::Dot { e, .. } => self.resolve(e, scope, m)?,
            E::Op(_, a) => {
                for x in a {
                    self.resolve(x, scope, m)?;
                }
            }
        }
        scope.truncate(mark);
        match outer {
            Some(o) => self.lab = o,
            None => self.lab.0.truncate(lmark),
        }
        Ok(())
    }
}

// ---- labels and subexpression selectors (TLA+ version 2; SANY's Generator.selectorToNode) ----

fn sel_text(parts: &[Sel]) -> String {
    let part = |p: &Sel| match p.k {
        SelK::Name(x) => x.to_string(),
        SelK::Num(k) => k.to_string(),
        SelK::Left => "<<".into(),
        SelK::Right => ">>".into(),
        SelK::At => "@".into(),
        SelK::Colon => ":".into(),
        SelK::Args => "(...)".into(),
    };
    parts.iter().map(part).collect::<Vec<_>>().join("!")
}

/// The label `x` of the expression at `at` (a node and how many of its `wraps` are behind us): labels inside another
/// label or inside a LET definition belong to that one. The LETs passed on the way are added to `lets`.
fn find_label(at: (N, usize), x: Name, lets: &mut Vec<&'static [LetDef]>) -> Option<(N, usize)> {
    let (n, depth) = at;
    for (i, w) in n.wraps.iter().enumerate().skip(depth) {
        if let Wrap::Label(l, _) = w {
            return if *l == x { Some((n, i + 1)) } else { None };
        }
    }
    if let E::Let { defs, body } = &n.e {
        lets.push(defs);
        let r = find_label((body, 0), x, lets);
        if r.is_none() {
            lets.pop();
        }
        return r;
    }
    let mut r = None;
    for_children(n, &mut |c| {
        if r.is_none() {
            r = find_label((c, 0), x, lets);
        }
    });
    r
}

/// The definition that `d!parts` denotes: its parameters are those of `d`, then the identifiers bound on the way to
/// the subexpression (label parameters, `!(args)`, `!@`), then those of a LET definition named last; its body is the
/// subexpression inside the LETs it is in. With `exact`, every part must come with the arguments it binds.
fn sub_def(full: Name, d: &'static Def, parts: &'static [Sel], exact: bool) -> Result<&'static Def, String> {
    if let Some(inst) = &d.inst {
        let o = sub_def(full, inst.orig, parts, exact)?;
        let mut def = Def::new(full, [&d.params[..inst.nparams], &o.params[..]].concat(), None, d.module, true, d.loc);
        def.inst = Some(Inst { orig: o, substs: inst.substs.clone(), nparams: inst.nparams, env_cache: RefCell::new(None) });
        return Ok(leak(def));
    }
    let Some(body) = d.body.get() else { return Err(format!("Cannot take subexpression of `{}'.", d.name)) };
    #[derive(PartialEq)]
    enum Prev {
        Def,
        Label,
        Sub,
    }
    let text = |p: &Sel| sel_text(std::slice::from_ref(p));
    // SANY's ArgNum: which of `arity` operands the selector names
    let arg = |p: &Sel, arity: usize| match p.k {
        SelK::Num(k) if k >= 1 && k as usize <= arity => Ok(k as usize - 1),
        SelK::Left if arity > 0 => Ok(0),
        SelK::Right if arity == 2 => Ok(1),
        _ => Err(format!("Nonexistent operand specified by `{}'.", text(p))),
    };
    let binds = |p: &Sel, names: &[Name], params: &mut Vec<Param>| {
        if exact && p.nargs != names.len() {
            return Err(format!("`{}' used with {} argument(s) where {} identifier(s) are bound.", text(p), p.nargs, names.len()));
        }
        params.extend(names.iter().map(|x| Param { name: *x, arity: 0 }));
        Ok(())
    };
    let unsupported = |what: &str| Err(format!("Subexpression selectors are not supported for {}.", what));
    let mut params = d.params.clone();
    let mut lets: Vec<&'static [LetDef]> = vec![];
    let mut cur: (N, usize) = (body, 0);
    let mut prev = Prev::Def;
    let mut i = 0;
    while i < parts.len() {
        let p = &parts[i];
        let (n, mut depth) = cur;
        i += 1;
        match p.k {
            SelK::Name(x) if prev != Prev::Sub => {
                cur = find_label(cur, x, &mut lets).ok_or_else(|| format!("Cannot find label `{}'.", x))?;
                if let Wrap::Label(_, ps) = &cur.0.wraps[cur.1 - 1] {
                    binds(p, ps, &mut params)?;
                }
                prev = Prev::Label;
                continue;
            }
            SelK::Name(x) => {
                let defs = match &n.e {
                    E::Let { defs, .. } if !n.wraps[depth..].iter().any(|w| matches!(w, Wrap::Bullet)) => *defs,
                    _ => return Err("A name selector here must be from a LET clause.".into()),
                };
                let ld = defs.iter().find_map(|ld| match ld {
                    LetDef::Def(ld) if ld.name == x => Some(ld),
                    _ => None,
                });
                let Some(ld) = ld else { return Err(format!("Unknown operator: `{}'.", x)) };
                if exact && p.nargs != ld.params.len() {
                    return Err(format!("The operator {} requires {} arguments.", x, ld.params.len()));
                }
                lets.push(defs);
                params.extend(ld.params.iter().cloned());
                cur = (&ld.body, 0);
                prev = Prev::Def;
                continue;
            }
            SelK::Colon => {
                let named_next = matches!(parts.get(i), Some(Sel { k: SelK::Name(_), .. }));
                if prev == Prev::Sub || !(named_next || (i == parts.len() && prev == Prev::Def)) {
                    return Err("`!:' can be used only after a name and either at the end after an operator name or before an operator name.".into());
                }
                prev = Prev::Sub;
                continue;
            }
            _ => {}
        }
        prev = Prev::Sub;
        while let Some(Wrap::Label(..)) = n.wraps.get(depth) {
            depth += 1;
        }
        if depth < n.wraps.len() {
            // a junction list with one item
            arg(p, 1)?;
            cur = (n, depth + 1);
            continue;
        }
        let binder = matches!(p.k, SelK::Args | SelK::At);
        // quantifier-like constructs: `!(args)` and `!@` go to the body, a number to the set of a bound
        let bounds = |bs: &'static [Bound], body: N, params: &mut Vec<Param>| -> Result<N, String> {
            if binder {
                let names: Vec<Name> = bs.iter().flat_map(|b| b.names.iter().chain(b.tuple.iter()).flatten().copied()).collect();
                binds(p, &names, params)?;
                return Ok(body);
            }
            let sets: Vec<N> = bs.iter().filter_map(|b| b.set.as_deref()).collect();
            Ok(sets[arg(p, sets.len())?])
        };
        let next: N = match &n.e {
            E::Let { defs, body } => {
                if arg(p, 1).is_err() {
                    return Err("A LET/IN expression has only one operand.".into());
                }
                lets.push(defs);
                body
            }
            E::Op(K::And | K::Or, a) if a.len() > 2 && !n.junction => match arg(p, 2)? {
                // a /\ b /\ c is (a /\ b) /\ c, kept here as one node
                0 => return unsupported("the left operand of a chain of infix /\\ or \\/"),
                _ => &a[a.len() - 1],
            },
            E::App { args: a, .. } | E::Op(_, a) => &a[arg(p, a.len())?],
            E::FnApp { f, args } => match arg(p, 2)? {
                0 => f,
                _ if args.len() == 1 => &args[0],
                _ => return unsupported("the argument of a function applied to several arguments"),
            },
            E::Dot { e, field } => match arg(p, 2)? {
                0 => e,
                _ => leak(Node::new(n.loc, E::Str(str_of(*field), Cell::new(Some(*field))))),
            },
            E::Rec(fs, _) | E::RecSet(fs) => &fs[arg(p, fs.len())?].1,
            E::Except { base, updates } => match arg(p, 1 + updates.len())? {
                0 => base,
                _ => return Err("Selecting subexpression of an EXCEPT not yet implemented.".into()),
            },
            E::Case { arms, other } => {
                let Some(p2) = parts.get(i) else { return Err("Subexpression of CASE must have form !i!j.".into()) };
                i += 1;
                let k = arg(p, arms.len() + other.is_some() as usize)?;
                let which = arg(p2, 2).map_err(|_| "Second selector for CASE subexpression must specify one of two operands.".to_string())?;
                match (arms.get(k), which, other) {
                    (Some(a), 0, _) => &a.0,
                    (Some(a), _, _) => &a.1,
                    (None, 1, Some(o)) => o,
                    _ => return Err("Selecting OTHER in a CASE statement.".into()),
                }
            }
            E::FnDef { is_rec, .. } if binder && is_rec.get() => return unsupported("the body of a recursive function definition"),
            E::Quant { bounds: bs, body, .. } | E::SetMap { e: body, bounds: bs } | E::FnDef { bounds: bs, body, .. } => bounds(bs, body, &mut params)?,
            E::Choose { bound, body } | E::SetFilter { bound, pred: body } => bounds(std::slice::from_ref(bound), body, &mut params)?,
            E::TQuant { names, body } if binder => {
                binds(p, names, &mut params)?;
                body
            }
            E::Lambda { params: ps, body } if binder => {
                binds(p, &ps.iter().map(|x| x.name).collect::<Vec<_>>(), &mut params)?;
                body
            }
            E::TQuant { .. } | E::Lambda { .. } => return Err(arg(p, 0).unwrap_err()),
            _ => return Err("Selecting subexpression of expression that has none.".into()),
        };
        cur = (next, 0);
    }
    let mut e = cur.0;
    if matches!(e.e, E::AssumeProve | E::StepRef) {
        return Err("ASSUME/PROVE used where an expression is required.".into());
    }
    let module = e.module.get().or(Some(d.module));
    for defs in lets.into_iter().rev() {
        e = leak(Node::new(e.loc, E::Let { defs, body: e }));
        e.module.set(module);
    }
    Ok(leak(Def::new(full, params, Some(e), d.module, true, d.loc)))
}

// ---- expression levels: 0 constant, 1 state, 2 action, 3 temporal ----
pub fn level_of(n: N) -> i8 {
    let c = n.lvl.get();
    if c >= 0 {
        return c;
    }
    let mut l: i8 = 0;
    macro_rules! up {
        ($x:expr) => {{
            let v = level_of($x);
            if v > l {
                l = v;
            }
        }};
    }
    match &n.e {
        E::Num(_) | E::Str(..) | E::Bool(_) | E::At | E::StepRef | E::AssumeProve => {}
        E::App { args, r, .. } => {
            match r.get() {
                Res::Decl(d) => {
                    if d.is_var {
                        l = 1;
                    } else if let Some(s) = d.subst.get() {
                        l = def_level(s);
                    }
                }
                Res::Def(d) => l = def_level(d),
                _ => {}
            }
            for (i, a) in args.iter().enumerate() {
                // an action argument that the operator only uses under ENABLED contributes state level
                let only_enabled = level_of(a) == 2 && l < 2 && matches!(r.get(), Res::Def(d) if param_only_enabled(d, i));
                if only_enabled {
                    if l < 1 {
                        l = 1;
                    }
                } else {
                    up!(a);
                }
            }
        }
        E::Op(k, a) => match k {
            K::Prime | K::Unchanged | K::BoxAct | K::AngleAct | K::Cdot => l = 2,
            K::Enabled => l = 1,
            K::Always | K::Eventually | K::LeadsTo | K::Guarantee | K::Wf | K::Sf => l = 3,
            _ => {
                for x in a {
                    up!(x);
                }
            }
        },
        E::TQuant { .. } => l = 3,
        E::Quant { bounds, body, .. } | E::FnDef { bounds, body, .. } => {
            for b in bounds {
                if let Some(s) = &b.set {
                    up!(s);
                }
            }
            up!(body);
        }
        E::SetMap { e, bounds } => {
            for b in bounds {
                if let Some(s) = &b.set {
                    up!(s);
                }
            }
            up!(e);
        }
        E::Choose { bound, body } => {
            if let Some(s) = &bound.set {
                up!(s);
            }
            up!(body);
        }
        E::SetFilter { bound, pred } => {
            if let Some(s) = &bound.set {
                up!(s);
            }
            up!(pred);
        }
        E::Lambda { body, .. } => up!(body),
        E::Let { defs, body } => {
            for d in defs.iter() {
                if let LetDef::Def(d) = d {
                    up!(&d.body);
                }
            }
            up!(body);
        }
        E::Case { arms, other } => {
            for (c, e) in arms {
                up!(c);
                up!(e);
            }
            if let Some(o) = other {
                up!(o);
            }
        }
        E::Rec(f, _) | E::RecSet(f) => {
            for (_, e) in f {
                up!(e);
            }
        }
        E::Except { base, updates } => {
            up!(base);
            for (path, val) in updates {
                for p in path {
                    up!(p);
                }
                up!(val);
            }
        }
        E::FnApp { f, args } => {
            up!(f);
            for a in args {
                up!(a);
            }
        }
        E::Dot { e, .. } => up!(e),
    }
    n.lvl.set(l);
    l
}

pub fn def_level(d: &'static Def) -> i8 {
    if let Some(o) = d.over.get() {
        return def_level(o);
    }
    if d.level.get() >= 0 {
        return d.level.get();
    }
    d.level.set(0); // recursion guard
    let mut l = 0;
    if let Some(inst) = &d.inst {
        l = def_level(inst.orig);
        let refs = decl_refs(inst.orig);
        let refs = refs.borrow().clone();
        for s in inst.substs.iter() {
            if refs.contains(&s.name) {
                l = l.max(level_of(s.e));
            }
        }
    } else if let Some(b) = d.body.get() {
        l = level_of(b);
    }
    d.level.set(l);
    l
}

/// Names of CONSTANT/VARIABLE declarations a definition (transitively) depends on.
pub fn decl_refs(d: &'static Def) -> Rc<RefCell<HashSet<Name>>> {
    if let Some(r) = d.refs.borrow().as_ref() {
        return r.clone();
    }
    let out = Rc::new(RefCell::new(HashSet::new()));
    *d.refs.borrow_mut() = Some(out.clone());
    if let Some(inst) = &d.inst {
        let inner = decl_refs(inst.orig).borrow().clone();
        for s in inst.substs.iter() {
            if inner.contains(&s.name) {
                collect_refs(s.e, &out);
            }
        }
    } else if let Some(b) = d.body.get() {
        collect_refs(b, &out);
    }
    out
}

fn collect_refs(n: N, out: &Rc<RefCell<HashSet<Name>>>) {
    if let E::App { r, .. } = &n.e {
        match r.get() {
            Res::Def(d) => {
                let inner = decl_refs(d);
                if !Rc::ptr_eq(&inner, out) {
                    let items: Vec<Name> = inner.borrow().iter().copied().collect();
                    out.borrow_mut().extend(items);
                }
            }
            Res::Decl(d) => {
                out.borrow_mut().insert(d.name);
            }
            _ => {}
        }
    }
    for_children(n, &mut |c| collect_refs(c, out));
}

/// Calls `f` on every direct child expression of `n` (including LET definitions and instance substitutions).
pub fn for_children(n: N, f: &mut dyn FnMut(N)) {
    let mut bounds = |bs: &'static [Bound], f: &mut dyn FnMut(N)| {
        for b in bs {
            if let Some(s) = &b.set {
                f(s);
            }
        }
    };
    match &n.e {
        E::Num(_) | E::Str(..) | E::Bool(_) | E::At | E::StepRef | E::AssumeProve => {}
        E::App { args, .. } => {
            for a in args {
                f(a);
            }
        }
        E::Op(_, a) => {
            for x in a {
                f(x);
            }
        }
        E::Case { arms, other } => {
            for (c, e) in arms {
                f(c);
                f(e);
            }
            if let Some(o) = other {
                f(o);
            }
        }
        E::Let { defs, body } => {
            for d in defs.iter() {
                match d {
                    LetDef::Def(d) => f(&d.body),
                    LetDef::Inst(d) => match d.inst_substs.get() {
                        Some(ss) => {
                            for s in ss.iter() {
                                f(s.e);
                            }
                        }
                        None => {
                            for s in &d.substs {
                                f(&s.1);
                            }
                        }
                    },
                }
            }
            f(body);
        }
        E::Quant { bounds: bs, body, .. } | E::FnDef { bounds: bs, body, .. } => {
            bounds(bs, f);
            f(body);
        }
        E::SetMap { e, bounds: bs } => {
            f(e);
            bounds(bs, f);
        }
        E::Choose { bound, body } => {
            if let Some(s) = &bound.set {
                f(s);
            }
            f(body);
        }
        E::SetFilter { bound, pred } => {
            if let Some(s) = &bound.set {
                f(s);
            }
            f(pred);
        }
        E::Rec(fs, _) | E::RecSet(fs) => {
            for (_, e) in fs {
                f(e);
            }
        }
        E::Except { base, updates } => {
            f(base);
            for (path, val) in updates {
                for p in path {
                    f(p);
                }
                f(val);
            }
        }
        E::FnApp { f: fun, args } => {
            f(fun);
            for a in args {
                f(a);
            }
        }
        E::Dot { e, .. } => f(e),
        E::Lambda { body, .. } | E::TQuant { body, .. } => f(body),
    }
}

/// Is the parameterless LET definition `d` a closed constant: no state, no free local identifier (parameter,
/// bound variable, outer LET definition) and only operators without side effects? Its value is then the same
/// wherever the LET is evaluated, and the evaluator computes it once.
pub fn let_closed(d: &'static DefNode) -> bool {
    let c = d.closed.get();
    if c >= 0 {
        return c == 1;
    }
    fn names(b: &'static Bound, bound: &mut Vec<Name>) {
        if let Some(ns) = &b.names {
            bound.extend(ns.iter().copied());
        }
        if let Some(ns) = &b.tuple {
            bound.extend(ns.iter().copied());
        }
    }
    // true: `n` is fine
    fn ok(n: N, bound: &mut Vec<Name>) -> bool {
        let mark = bound.len();
        let r = match &n.e {
            E::At | E::StepRef | E::AssumeProve | E::TQuant { .. } => false,
            E::App { name, args, r, .. } => {
                (match r.get() {
                    Res::Local => bound.contains(name),
                    Res::Decl(dc) => !dc.is_var && dc.subst.get().is_none() && dc.arity == 0,
                    Res::Def(x) => {
                        let x = x.resolved();
                        if x.inst.is_some() {
                            false
                        } else if x.builtin.get().is_some() {
                            // standard modules whose operators are pure functions of their arguments
                            matches!(&*x.module.to_string(), "Naturals" | "Integers" | "Reals" | "Sequences" | "FiniteSets" | "Bags")
                        } else {
                            // a user constant: evaluated once anyway
                            x.params.is_empty() && def_level(x) == 0
                        }
                    }
                    Res::None => false,
                }) && args.iter().all(|a| ok(a, bound))
            }
            E::Quant { bounds, body, .. } | E::FnDef { bounds, body, .. } => {
                let sets = bounds.iter().all(|b| b.set.as_ref().map_or(false, |s| ok(s, bound)));
                if let E::FnDef { recname: Some(rn), .. } = &n.e {
                    bound.push(*rn);
                }
                for b in bounds {
                    names(b, bound);
                }
                sets && ok(body, bound)
            }
            E::SetMap { e, bounds } => {
                let sets = bounds.iter().all(|b| b.set.as_ref().map_or(false, |s| ok(s, bound)));
                for b in bounds {
                    names(b, bound);
                }
                sets && ok(e, bound)
            }
            E::Choose { bound: b, body } | E::SetFilter { bound: b, pred: body } => {
                let set = b.set.as_ref().map_or(false, |s| ok(s, bound));
                names(b, bound);
                set && ok(body, bound)
            }
            E::Lambda { params, body } => {
                bound.extend(params.iter().map(|p| p.name));
                ok(body, bound)
            }
            E::Let { defs, body } => {
                let mut all = true;
                for d in defs.iter() {
                    match d {
                        LetDef::Inst(_) => all = false,
                        LetDef::Def(d) => {
                            bound.push(d.name); // recursive LET operators refer to themselves
                            let m2 = bound.len();
                            bound.extend(d.params.iter().map(|p| p.name));
                            all = all && ok(&d.body, bound);
                            bound.truncate(m2);
                        }
                    }
                }
                all && ok(body, bound)
            }
            _ => {
                let mut all = true;
                for_children(n, &mut |c| all = all && ok(c, bound));
                all
            }
        };
        bound.truncate(mark);
        r
    }
    let r = d.params.is_empty() && level_of(&d.body) == 0 && ok(&d.body, &mut Vec::new());
    d.closed.set(r as i8);
    r
}

/// Can evaluating `n` yield a function constructor directly (through IF/CASE/LET/definitions)? TLC keeps such a
/// function unevaluated when it is immediately applied (f[x]) or is the body of a recursive function.
pub fn tail_fn(n: N) -> bool {
    let c = n.tf.get();
    if c >= 0 {
        return c == 1;
    }
    n.tf.set(0); // recursion guard
    let r = match &n.e {
        E::FnDef { .. } => true,
        E::Op(K::If, a) => tail_fn(&a[1]) || tail_fn(&a[2]),
        E::Case { arms, other } => arms.iter().any(|(_, e)| tail_fn(e)) || other.as_ref().map_or(false, |o| tail_fn(o)),
        E::Let { body, .. } => tail_fn(body),
        E::FnApp { f, .. } => tail_fn(f),
        E::App { args, r, .. } => match r.get() {
            Res::Local => match n.ld.get() {
                Some(LocalDef::Fn) if args.is_empty() => true,
                Some(LocalDef::Let(d)) if args.is_empty() => tail_fn(&d.body),
                _ => false,
            },
            Res::Def(x) => {
                let mut d = x.resolved();
                while let Some(inst) = &d.inst {
                    d = inst.orig.resolved();
                }
                match d.body.get() {
                    Some(b) if d.builtin.get().is_none() => tail_fn(b),
                    _ => false,
                }
            }
            _ => false,
        },
        _ => false,
    };
    n.tf.set(r as i8);
    r
}

/// Does definition `d0` use its i-th parameter only inside ENABLED?
fn param_only_enabled(d0: &'static Def, i: usize) -> bool {
    let mut d = d0.resolved();
    let mut skip = 0;
    while let Some(inst) = &d.inst {
        skip += inst.nparams;
        d = inst.orig.resolved();
    }
    if i < skip {
        return false;
    }
    let i = i - skip;
    let body = match d.body.get() {
        Some(b) if i < d.params.len() => b,
        _ => return false,
    };
    if let Some(Some(v)) = d.enabled_only.borrow().get(i) {
        return *v;
    }
    let pname = d.params[i].name;
    let mut used = false;
    fn walk(x: N, pname: Name, used: &mut bool) -> bool {
        if x.is_k(K::Enabled) {
            *used = true;
            return true;
        }
        if let E::App { name, r, .. } = &x.e {
            if *name == pname && matches!(r.get(), Res::Local) {
                return false;
            }
        }
        let mut ok = true;
        for_children(x, &mut |c| {
            if ok && !walk(c, pname, used) {
                ok = false;
            }
        });
        ok
    }
    let v = walk(body, pname, &mut used) && used;
    let mut c = d.enabled_only.borrow_mut();
    if c.len() <= i {
        c.resize(i + 1, None);
    }
    c[i] = Some(v);
    v
}