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
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
//! Scopes: where the binding stage's predicates are evaluated.
//!
//! TLC keeps every role of a model (an initial predicate, an action, an
//! invariant, an implied action, a constraint) as an `Action`: an expression
//! with the `Context` it is evaluated in (`tlc2.tool.Action`). The context is
//! what `SpecProcessor.processConfigSpec` and `Tool.getActions` built while
//! they walked down to the expression: the parameters of operators they
//! inlined (`getOpContext`, lazily), the values of the `\E` variables they
//! split on, and the instance substitutions they passed (`Specs.addSubsts`).
//!
//! A [`Scope`] is that context over dive's environments: a frame of the
//! definition the expression belongs to (with its parents) and the dynamic
//! substitutions. The binding stage builds scopes with the methods on
//! [`crate::Evaluator`] below and hands each role to the checker as an
//! expression plus a scope.
use std::sync::Arc;
use dive_ir::{Arg, DefId, DefScope, Expr, ExprId, LocalRef, OpRef, Pass, Slot};
use dive_value::Value;
use crate::Evaluator;
use crate::env::{Dyn, Env, Ev, St, Sv, Thunk};
use crate::error::{EvalError, Result};
pub(crate) type BindingColumn = (Vec<usize>, bool, Arc<[Value]>);
/// TLC's `Context` of a role (see the module documentation). Cheap to clone.
#[derive(Clone, Debug)]
pub struct Scope {
pub(crate) env: Env,
pub(crate) owner: Arc<dive_ir::Ir>,
pub(crate) names: Arc<dive_value::Interner>,
pub(crate) context: std::sync::Weak<crate::core::Core>,
/// The innermost substitution entered, whose location labels the
/// actions found under it.
pub(crate) wrapper: Option<ExprId>,
}
impl Scope {
/// Whether this context retains an INSTANCE substitution. Temporal
/// argument admission uses this to preserve the pinned reference's
/// explicit refusal for exported parameterized INSTANCE formulas.
#[must_use]
pub fn has_substitutions(&self) -> bool {
self.env.dynamic.subst.is_some()
}
/// Whether two scopes retain the same analysis environment owners.
///
/// This is an identity test for active-walk cycle detection only. It is not
/// semantic scope equality, an atom/cache key, or an admission certificate.
/// A negative answer does not prove inequivalence. Dynamic `@` contexts
/// return false without inspecting, comparing or calling their values.
///
/// ```
/// # fn retained(scope: &dive_eval::Scope) {
/// let clone = scope.clone();
/// let same_owner = scope.same_analysis_context(&clone);
/// # let _ = same_owner; }
/// ```
#[must_use]
pub fn same_analysis_context(&self, other: &Self) -> bool {
let same_substitution = match (&self.env.dynamic.subst, &other.env.dynamic.subst) {
(None, None) => true,
(Some(left), Some(right)) => Arc::ptr_eq(left, right),
_ => false,
};
self.env.dynamic.at.is_none()
&& other.env.dynamic.at.is_none()
&& self.context.ptr_eq(&other.context)
&& Arc::ptr_eq(&self.owner, &other.owner)
&& Arc::ptr_eq(&self.names, &other.names)
&& Arc::ptr_eq(&self.env.frame, &other.env.frame)
&& same_substitution
&& self.env.dynamic.cut == other.env.dynamic.cut
&& self.wrapper == other.wrapper
}
/// The definition whose frame the scope's expressions are evaluated in.
#[must_use]
pub fn def(&self) -> DefId {
self.env.frame.def
}
}
/// What a slot of a scope holds, as the binding stage needs to see it.
#[derive(Clone, Debug)]
pub enum SlotView {
/// Nothing is bound.
Unset,
/// A value.
Value(Value),
/// A pure unknown value for conservative state-level analysis only.
/// Forcing it is an explicit error; it is never a guessed runtime value.
AnalysisBound,
/// A pure unknown value of a binder over a constant domain, for
/// constant-level analysis only. Forcing it is the explicit
/// [`EvalError::is_analysis_only`] error; it is never a guessed value.
AnalysisConstant,
/// A lazy argument (`LazyValue`): the expression and the scope it is
/// evaluated in.
Lazy(ExprId, Scope),
/// An actual recursive function. Callers must inspect its owned domains,
/// captured context and body; this does not establish purity or finiteness.
Function(Arc<crate::LazyFcn>),
/// An operator argument or another lazy function: not an expression.
Other,
}
impl Evaluator {
/// Resolves a known user operator for non-evaluating context analysis.
///
/// Preserves its lexical parent and dynamic substitution context. Each
/// ordinary value formal is bound to [`SlotView::AnalysisBound`], which is
/// state-level for analysis and cannot be forced as a runtime value. This
/// does not prove purity: callers must inspect the returned body and scope.
/// Native, built-in, configured constant, unresolved, recursive, overridden
/// and higher-order targets return `None` without evaluation or callbacks.
/// A definition used by any configured operator constant is also refused,
/// even when explicitly passed, because captured bindings erase its origin.
/// Callers must also prove [`Self::scope_operator_captures`], including
/// unused lexical/dynamic operator arguments, under their own work budget.
/// Use [`Self::scope_apply_param`] with real arguments for execution.
///
/// # Errors
/// An invalid definition, enclosing frame or foreign captured context.
pub fn scope_operator_analysis(
&self,
scope: &Scope,
operator: &OpRef,
) -> Result<Option<(DefId, Scope)>> {
self.validate_scope(scope)?;
let value = match operator {
OpRef::Def(def) => {
self.admit_def(*def)?;
let target = self.core.redirect(*def);
self.admit_def(target)?;
self.admit_parent(scope, target)?;
self.core.op_value(&scope.env, operator)?
}
OpRef::Param(local) => {
let Some(frame) = scope.env.frame_up(local.up) else {
return Ok(None);
};
let Some(Sv::Op(value)) = frame.slots.get(local.slot.index()) else {
return Ok(None);
};
(**value).clone()
}
_ => return Ok(None),
};
self.operator_value_analysis(scope, value)
}
/// Resolves an authoritative, bounded pure native operator actual.
///
/// Only `Sequences!Len`, `Sequences!Head`, `Sequences!Append` and
/// `FiniteSets!Cardinality`
/// are admitted. This is callback-free metadata inspection, not a purity
/// or truth certificate. Callers must prove the captured context, arity
/// and actual expression arguments independently. Configured targets and
/// replacements conservatively refuse, including a directly supplied
/// same native target; opaque, builtin and other native targets refuse.
/// Each target/configuration inspection charges `work` before access.
///
/// # Errors
/// Invalid ownership/reference or exhausted inspection work.
pub fn scope_native_operator_analysis(
&self,
scope: &Scope,
operator: &OpRef,
work: &mut usize,
) -> Result<Option<dive_ir::StdOp>> {
self.validate_scope(scope)?;
Self::operator_capture_step(work)?;
let value = match operator {
OpRef::Def(def) => {
self.admit_def(*def)?;
let target = self.core.redirect(*def);
self.admit_def(target)?;
self.admit_parent(scope, target)?;
self.core.op_value(&scope.env, operator)?
}
OpRef::Std(op) => crate::env::OpVal::Std(*op),
OpRef::Param(local) => {
let Some(frame) = scope.env.frame_up(local.up) else {
return Ok(None);
};
let Some(Sv::Op(value)) = frame.slots.get(local.slot.index()) else {
return Ok(None);
};
(**value).clone()
}
_ => return Ok(None),
};
self.native_operator_value(&value, work)
}
fn native_operator_value(
&self,
value: &crate::env::OpVal,
work: &mut usize,
) -> Result<Option<dive_ir::StdOp>> {
use dive_ir::StdOp;
let native = match value {
crate::env::OpVal::Std(op) => *op,
crate::env::OpVal::Def {
def,
parent,
dynamic,
} => {
// Native calls have no lexical body. Do not discard a supplied
// foreign/opaque lexical or dynamic capture as irrelevant.
if parent.is_some() || dynamic.is_some() {
return Ok(None);
}
Self::operator_capture_step(work)?;
let target = self.admit_def(*def)?;
if self.is_value_override(*def) {
return Ok(None);
}
let Some(op) = target.std else {
return Ok(None);
};
op
}
_ => return Ok(None),
};
if !matches!(
native,
StdOp::SequencesLen
| StdOp::SequencesHead
| StdOp::SequencesAppend
| StdOp::FiniteSetsCardinality
) {
return Ok(None);
}
// Native values, like user Def values, do not retain configured origin.
for binding in &self.core.consts {
Self::operator_capture_step(work)?;
if let Some(crate::ConstBinding::Def(bound)) = binding {
let target = self.admit_def(self.core.redirect(*bound))?;
if target.std == Some(native) {
return Ok(None);
}
}
}
for (index, target) in self.core.ir.defs().iter().enumerate() {
Self::operator_capture_step(work)?;
if target.std == Some(native) {
let def =
DefId(u32::try_from(index).map_err(|_| {
EvalError::resource_limit("native operator definition index")
})?);
if self.is_value_override(def) || self.core.redirect(def) != def {
return Ok(None);
}
}
}
Ok(Some(native))
}
pub(crate) fn operator_value_analysis(
&self,
scope: &Scope,
value: crate::env::OpVal,
) -> Result<Option<(DefId, Scope)>> {
let crate::env::OpVal::Def {
def,
parent,
dynamic,
} = value
else {
return Ok(None);
};
let target = self.admit_def(def)?;
// OpVal::Def does not retain configured-constant origin. Conservatively
// refuse every such target, including an explicitly passed same def.
if self.core.consts.iter().flatten().any(|binding| {
matches!(binding, crate::ConstBinding::Def(bound) if self.core.redirect(*bound) == def)
}) {
return Ok(None);
}
if target.recursive
|| target.std.is_some()
|| self.is_value_override(def)
|| target.params.iter().any(|param| param.arity != 0)
{
return Ok(None);
}
let mut env = Env::new(
def,
target.depth,
target.frame.len(),
parent,
dynamic.unwrap_or_else(|| scope.env.dynamic.clone()),
);
for i in 0..target.params.len() {
env.bind(i, Sv::AnalysisBound);
}
Ok(Some((
def,
Scope {
owner: self.core.ir.clone(),
names: self.core.names.clone(),
context: Arc::downgrade(&self.core),
env,
wrapper: scope.wrapper,
},
)))
}
pub(crate) fn selectseq_value_analysis(
&self,
scope: &Scope,
value: crate::env::OpVal,
work: &mut usize,
) -> Result<Option<(DefId, Scope)>> {
self.validate_scope(scope)?;
*work = work
.checked_sub(self.core.consts.len().saturating_add(1))
.ok_or_else(|| EvalError::resource_limit("SelectSeq target work"))?;
let crate::env::OpVal::Def {
def,
parent,
dynamic: None,
} = &value
else {
return Err(EvalError::unsupported(
"SelectSeq retained dynamic/native callback",
));
};
let definition = self.admit_def(*def)?;
match definition.scope {
DefScope::Local { parent: owner } | DefScope::Inline { parent: owner }
if parent.as_ref().is_none_or(|frame| {
frame.def != owner || frame.depth != definition.depth.saturating_sub(1)
}) =>
{
return Err(EvalError::unsupported(
"SelectSeq incompatible lexical callback owner",
));
}
DefScope::TopLevel if parent.is_some() => {
return Err(EvalError::unsupported(
"SelectSeq unexpected lexical callback owner",
));
}
_ => {}
}
self.operator_value_analysis(scope, value)
}
/// Projects every captured lazy expression and known user operator body.
///
/// This performs no evaluation, normalization or callback. Returned bodies
/// retain lexical/dynamic ownership and analysis-only ordinary formals;
/// callers must independently prove each one, including unused captures.
/// Opaque functions/operators and configured/recursive/native targets return
/// `None`. Each context, substitution link and slot consumes `work` before
/// inspection or enqueue; retained context depth is capped at 128.
/// Stored values are not forced and this is not a value-purity certificate.
/// Dynamic `@` bindings conservatively refuse instead of hashing values.
///
/// # Errors
/// Invalid ownership/reference or the supplied work/context depth bound.
pub fn scope_operator_captures(
&self,
scope: &Scope,
work: &mut usize,
) -> Result<Option<Vec<(ExprId, Scope)>>> {
self.operator_captures(scope, work, false)
}
pub(crate) fn operator_captures(
&self,
scope: &Scope,
work: &mut usize,
selectseq: bool,
) -> Result<Option<Vec<(ExprId, Scope)>>> {
self.validate_scope(scope)?;
Self::operator_capture_step(work)?;
let mut captures = Vec::new();
let mut todo = vec![(scope.env.clone(), 0_usize)];
let mut frames = std::collections::HashSet::new();
let mut links = std::collections::HashSet::new();
// Retain every traversed owner for the walk: allocation addresses must
// not be recycled while they occur in identity keys.
let mut owners = Vec::new();
while let Some((env, depth)) = todo.pop() {
if depth > 128 {
return Err(EvalError::resource_limit("operator capture context depth"));
}
if env.dynamic.at.is_some() {
return Ok(None); // No Value hash/equality is capture authority.
}
Self::operator_capture_step(work)?;
owners.push(env.clone());
let context_scope = Scope {
env: env.clone(),
..scope.clone()
};
let mut slots = Vec::new();
let dynamic_key = (
env.dynamic
.subst
.as_ref()
.map_or(0, |head| Arc::as_ptr(head) as usize),
env.dynamic.cut,
);
let frame_key = (Arc::as_ptr(&env.frame) as usize, dynamic_key);
if !frames.contains(&frame_key) {
Self::operator_capture_step(work)?;
frames.insert(frame_key);
for slot in &env.frame.slots {
Self::operator_capture_step(work)?;
slots.push(slot);
}
if let Some(parent) = &env.frame.parent {
Self::operator_capture_step(work)?;
todo.push((
Env {
frame: parent.clone(),
dynamic: env.dynamic.clone(),
},
depth + 1,
));
}
}
let mut link = env.dynamic.subst.as_deref();
while let Some(binding) = link {
let link_key = (std::ptr::from_ref(binding) as usize, dynamic_key);
if links.contains(&link_key) {
break;
}
Self::operator_capture_step(work)?;
links.insert(link_key);
slots.push(&binding.val);
link = binding.next.as_deref();
}
for slot in slots {
Self::operator_capture_step(work)?;
let (expr, source) = match slot {
Sv::Thunk(thunk) => {
self.admit_expr(thunk.expr)?;
(
thunk.expr,
Scope {
env: thunk.env.clone(),
..scope.clone()
},
)
}
Sv::Op(operator) => {
if selectseq
&& !matches!(&**operator, crate::env::OpVal::Def { dynamic: None, .. })
{
return Ok(None);
}
if !selectseq && self.native_operator_value(operator, work)?.is_some() {
// The whitelist has no lexical body/captured callback.
// Actual arguments still require independent proof.
continue;
}
let resolved = if selectseq {
self.selectseq_value_analysis(&context_scope, *operator.clone(), work)?
} else {
self.operator_value_analysis(&context_scope, *operator.clone())?
};
let Some((def, source)) = resolved else {
return Ok(None);
};
(self.core.ir.def(def).body, source)
}
Sv::Fcn(_) => return Ok(None),
Sv::Unset | Sv::Val(_) | Sv::AnalysisBound | Sv::AnalysisConstant => continue,
};
self.validate_scope(&source)?;
Self::operator_capture_step(work)?;
todo.push((source.env.clone(), depth + 1));
captures.push((expr, source));
}
}
Ok(Some(captures))
}
fn operator_capture_step(work: &mut usize) -> Result<()> {
*work = work
.checked_sub(1)
.ok_or_else(|| EvalError::resource_limit("operator capture work"))?;
Ok(())
}
/// Enters an application of `def` to `args` in `scope`, as TLC's
/// `getOpContext` does: each expression argument is bound lazily (a
/// `LazyValue` over `scope`), each operator argument to the operator.
///
/// # Errors
/// An arity mismatch or a missing enclosing frame (bugs), or an operator
/// argument TLC cannot look up.
pub fn scope_apply(&self, scope: &Scope, def: DefId, args: &[Arg]) -> Result<Scope> {
self.validate_scope(scope)?;
self.admit_args(scope, def, args)?;
let core = &self.core;
let d = self.admit_def(def)?;
if args.len() != d.params.len() {
return Err(EvalError::bug(format!(
"{} applied to {} arguments, expects {}",
d.name,
args.len(),
d.params.len()
)));
}
let parent = self.admit_parent(scope, def)?;
let mut callee = Env::new(
def,
d.depth,
d.frame.len(),
parent,
scope.env.dynamic.clone(),
);
for (i, a) in args.iter().enumerate() {
let sv = match a {
Arg::Expr { expr, .. } => Sv::Thunk(Thunk::new(*expr, scope.env.clone(), true)),
Arg::Op { op, .. } => Sv::op(core.op_value(&scope.env, op)?),
};
callee.bind(i, sv);
}
Ok(Scope {
owner: self.core.ir.clone(),
names: self.core.names.clone(),
context: Arc::downgrade(&self.core),
env: callee,
wrapper: scope.wrapper,
})
}
/// Enters an application of an operator parameter: the definition TLC's
/// lookup of the parameter gives (the operator passed for it), entered as
/// [`Evaluator::scope_apply`] enters a definition. `None` if the
/// parameter is not bound to a user definition.
///
/// # Errors
/// As [`Evaluator::scope_apply`].
#[must_use]
pub fn scope_apply_param(
&self,
scope: &Scope,
r: LocalRef,
args: &[Arg],
) -> Option<Result<(DefId, Scope)>> {
if let Err(e) = self.validate_scope(scope) {
return Some(Err(e));
}
let core = &self.core;
let frame = scope.env.frame_up(r.up)?;
let Some(Sv::Op(op)) = frame.slots.get(r.slot.index()) else {
return None;
};
let crate::env::OpVal::Def {
def,
parent,
dynamic,
} = &**op
else {
return None;
};
let def = *def;
if let Err(e) = self.admit_args(scope, def, args) {
return Some(Err(e));
}
let d = core.ir.def(def);
if args.len() != d.params.len() || core.ir.def(def).std.is_some() {
return None;
}
let parent = match d.scope {
DefScope::Local { .. } | DefScope::Inline { .. } => parent.clone(),
_ => None,
};
let mut callee = Env::new(
def,
d.depth,
d.frame.len(),
parent,
dynamic.clone().unwrap_or_else(|| scope.env.dynamic.clone()),
);
for (i, a) in args.iter().enumerate() {
let sv = match a {
Arg::Expr { expr, .. } => Sv::Thunk(Thunk::new(*expr, scope.env.clone(), true)),
Arg::Op { op, .. } => match core.op_value(&scope.env, op) {
Ok(v) => Sv::op(v),
Err(e) => return Some(Err(e)),
},
};
callee.bind(i, sv);
}
Some(Ok((
def,
Scope {
owner: self.core.ir.clone(),
names: self.core.names.clone(),
context: Arc::downgrade(&self.core),
env: callee,
wrapper: scope.wrapper,
},
)))
}
/// The scope of `def`'s body with none of its parameters bound, as TLC's
/// `getLevelBound` sees the body of an operator it looks into: a
/// parameter it meets is not in the context. A `LET` operator or `LAMBDA`
/// keeps `scope`'s frame as its parent; a zero-arity `LET` definition is
/// evaluated in `scope` itself.
///
/// # Errors
/// A foreign scope, missing definition or missing enclosing frame.
pub fn scope_unbound(&self, scope: &Scope, def: DefId) -> Result<Scope> {
self.validate_scope(scope)?;
let d = self.admit_def(def)?;
let parent = self.admit_parent(scope, def)?;
Ok(match d.scope {
DefScope::LetValue { .. } => scope.clone(),
DefScope::TopLevel => return self.scope(def),
DefScope::Local { .. } | DefScope::Inline { .. } => Scope {
owner: self.core.ir.clone(),
names: self.core.names.clone(),
context: Arc::downgrade(&self.core),
env: Env::new(
def,
d.depth,
d.frame.len(),
parent,
scope.env.dynamic.clone(),
),
wrapper: scope.wrapper,
},
})
}
/// Enters an application of `def` whose parameters are bound to values, as
/// `Tool.getActionsAppl` does when it inlines an operator
/// (`con1.cons(formals[i], aval)`).
///
/// # Errors
/// An arity mismatch or a missing enclosing frame (bugs).
pub fn scope_call_values(
&self,
scope: &Scope,
def: DefId,
values: Vec<Value>,
) -> Result<Scope> {
self.validate_scope(scope)?;
let d = self.admit_def(def)?;
if d.params.iter().any(|p| p.arity != 0) {
return Err(crate::ContextError::new(
crate::ContextErrorKind::Arity,
"operator parameter requires an operator binding",
)
.into());
}
if values.len() != d.params.len() {
return Err(crate::ContextError::new(
crate::ContextErrorKind::Arity,
"value argument count",
)
.into());
}
let mut s = match d.scope {
DefScope::LetValue { .. } => return Ok(scope.clone()),
_ => self.scope_unbound(scope, def)?,
};
if matches!(d.scope, DefScope::TopLevel) {
s.env.dynamic = scope.env.dynamic.clone();
}
for (i, v) in values.into_iter().enumerate() {
s.env.bind(i, Sv::Val(v));
}
Ok(s)
}
/// The scope of a zero-arity `LET` definition's body (`DefScope::LetValue`
/// evaluates in its parent's frame) or of a definition with no parameters
/// entered from `scope`.
///
/// # Errors
/// As [`Evaluator::scope_apply`].
pub fn scope_enter(&self, scope: &Scope, def: DefId) -> Result<Scope> {
self.validate_scope(scope)?;
if matches!(self.admit_def(def)?.scope, DefScope::LetValue { .. }) {
self.admit_parent(scope, def)?;
return Ok(scope.clone());
}
self.scope_apply(scope, def, &[])
}
/// A fresh frame of the top-level definition `def`: the context in which
/// `SpecProcessor` finds a configured formula's parts.
///
/// # Errors
/// A missing definition or a definition requiring an enclosing lexical frame.
pub fn scope(&self, def: DefId) -> Result<Scope> {
let d = self.admit_def(def)?;
if d.scope != DefScope::TopLevel {
return Err(crate::ContextError::new(
crate::ContextErrorKind::Structure,
"definition requires an enclosing lexical frame",
)
.into());
}
Ok(Scope {
owner: self.core.ir.clone(),
names: self.core.names.clone(),
context: Arc::downgrade(&self.core),
env: Env::new(def, d.depth, d.frame.len(), None, Dyn::default()),
wrapper: None,
})
}
/// `scope` under the substitutions of `subst`, an [`Expr::Subst`] node of
/// its frame, as TLC wraps a formula found under an `INSTANCE` in a
/// substitution (`Specs.addSubsts`) that the generator then evaluates as
/// uncached lazy values (`Tool.java:960-990`, `:488-498`). Labels of
/// actions in the result name the substitution's location, as TLC's
/// wrapper does.
///
/// # Errors
/// A bug if `subst` is not a substitution; an evaluation error of a
/// binding TLC evaluates eagerly (none: every expression binding is lazy).
pub fn scope_subst(&self, scope: &Scope, subst: ExprId) -> Result<Scope> {
self.admit_scoped_expr(scope, subst)?;
self.validate_scope(scope)?;
let Expr::Subst { bindings, .. } = &self.core.ir.node(subst).expr else {
return Err(EvalError::bug(
"scope_subst on a node that is not a substitution",
));
};
let env = self
.core
.bind_subst(&scope.env, &St::default(), bindings, false)?;
Ok(Scope {
owner: self.core.ir.clone(),
names: self.core.names.clone(),
context: Arc::downgrade(&self.core),
env,
wrapper: Some(subst),
})
}
/// The context of a call `apply` (an application of a user definition)
/// made in `scope`: a fresh frame of the definition with its arguments
/// bound as uncached lazy values (`getOpContext(..., false)`, as
/// `SpecProcessor.processConfigSpec` inlines a parameterized formula).
/// Returns the definition called.
///
/// # Errors
/// A bug if `apply` is not such an application.
pub fn scope_call(&self, scope: &Scope, apply: ExprId) -> Result<(Scope, DefId)> {
self.admit_scoped_expr(scope, apply)?;
self.validate_scope(scope)?;
let (d, args): (&DefId, &[Arg]) = match &self.core.ir.node(apply).expr {
Expr::Apply {
callee: OpRef::Def(d),
args,
} => (d, args),
Expr::Def(d) => (d, &[]),
_ => return Err(EvalError::bug("scope_call on a node that is not a call")),
};
let d = self.core.redirect(*d);
self.admit_args(scope, d, args)?;
let def = self.admit_def(d)?;
let parent = self.admit_parent(scope, d)?;
let mut env = Env::new(
d,
def.depth,
def.frame.len(),
parent,
scope.env.dynamic.clone(),
);
for (i, a) in args.iter().enumerate() {
let sv = match a {
Arg::Expr { expr, pass } => match pass {
Pass::Strict => Sv::from(self.core.eval(
&mut scope.env.clone(),
&St::constant(),
*expr,
)?),
Pass::Lazy | Pass::Direct => {
Sv::Thunk(Thunk::new(*expr, scope.env.clone(), false))
}
},
Arg::Op { op, .. } => Sv::op(self.core.op_value(&scope.env, op)?),
};
env.bind(i, sv);
}
Ok((
Scope {
owner: self.core.ir.clone(),
names: self.core.names.clone(),
context: Arc::downgrade(&self.core),
env,
wrapper: scope.wrapper,
},
d,
))
}
/// Binds the zero-arity definitions of a `LET` (an [`Expr::Let`]) in
/// `scope`, so that its body can be evaluated there. TLC does not bind
/// them when it walks a specification (`processConfigSpec`, `getActions`):
/// it finds each definition by its node and evaluates its body at every
/// use. The thunks are therefore not cached, which is indistinguishable
/// from TLC.
///
/// # Errors
/// If `let_expr` is not a `LET`.
pub fn scope_let(&self, scope: &Scope, let_expr: ExprId) -> Result<Scope> {
self.scope_let_mode(scope, let_expr, false)
}
/// Enters a LET reached during actual expression/query evaluation. Each
/// zero-arity value retains its lexical creation context and TLC cachability;
/// no body is evaluated. Structural planning uses [`Self::scope_let`].
///
/// # Errors
/// A foreign scope or an expression that is not an admitted LET.
pub fn scope_eval_let(&self, scope: &Scope, let_expr: ExprId) -> Result<Scope> {
self.scope_let_mode(scope, let_expr, true)
}
fn scope_let_mode(&self, scope: &Scope, let_expr: ExprId, cachable: bool) -> Result<Scope> {
self.admit_scoped_expr(scope, let_expr)?;
self.validate_scope(scope)?;
let core = &self.core;
let Expr::Let { defs, .. } = core.ir.expr(let_expr) else {
return Err(EvalError::bug("scope_let on a node that is not a LET"));
};
let mut env = scope.env.clone();
for &d in defs {
if let DefScope::LetValue { slot, .. } = core.ir.def(d).scope {
let body = core.ir.def(d).body;
env.bind(
slot.index(),
Sv::Thunk(Thunk::new(body, env.clone(), cachable)),
);
}
}
Ok(Scope {
owner: self.core.ir.clone(),
names: self.core.names.clone(),
context: Arc::downgrade(&self.core),
env,
wrapper: scope.wrapper,
})
}
/// The scope without its instance substitutions: what TLC's context holds
/// while `processConfigProps` walks under a substitution (TLC keeps the
/// substitutions apart, to wrap them around what it finds).
///
/// # Errors
/// A foreign scope or inadmissible captured value.
pub fn scope_without_substs(&self, scope: &Scope) -> Result<Scope> {
self.validate_scope(scope)?;
let mut env = scope.env.clone();
env.dynamic.subst = None;
Ok(Scope {
owner: self.core.ir.clone(),
names: self.core.names.clone(),
context: Arc::downgrade(&self.core),
env,
wrapper: scope.wrapper,
})
}
/// Binds a slot of the scope's own frame to a value: a variable of a split
/// `\E`, or a parameter of an operator inlined with its value
/// (`Tool.getActionsAppl`).
///
/// # Errors
/// A foreign scope, unknown slot or inadmissible value.
pub fn scope_bind(&self, scope: &Scope, slot: Slot, v: Value) -> Result<Scope> {
self.validate_scope(scope)?;
if slot.index() >= scope.env.frame.slots.len() {
return Err(crate::ContextError::new(
crate::ContextErrorKind::UnknownId,
"scope binding slot",
)
.into());
}
if self
.admit_def(scope.def())?
.params
.get(slot.index())
.is_some_and(|p| p.arity != 0)
{
return Err(crate::ContextError::new(
crate::ContextErrorKind::Arity,
"operator parameter requires an operator binding",
)
.into());
}
let mut env = scope.env.clone();
env.bind(slot.index(), Sv::Val(v));
Ok(Scope {
owner: self.core.ir.clone(),
names: self.core.names.clone(),
context: Arc::downgrade(&self.core),
env,
wrapper: scope.wrapper,
})
}
/// The values bound to the parameters of `def` in the innermost frame of
/// `def` in `scope` (walking out through enclosing frames), in parameter
/// order; `None` for a parameter bound to anything but a value. This is
/// what TLC prints in an action's label (`Action.getLocation`).
#[must_use]
pub fn scope_params(&self, scope: &Scope, def: DefId) -> Vec<Option<Value>> {
if self.validate_scope(scope).is_err() {
return Vec::new();
}
let Some(d) = self.core.ir.defs().get(def.index()) else {
return Vec::new();
};
let n = d.params.len();
let mut f = Some(&scope.env.frame);
while let Some(frame) = f {
if frame.def == def {
return (0..n)
.map(|i| match frame.slots.get(i) {
Some(Sv::Val(v)) => Some(v.clone()),
_ => None,
})
.collect();
}
f = frame.parent.as_ref();
}
vec![None; n]
}
/// Branches at the current dynamic depth for one ENABLED query.
/// Captured older scopes and bindings entered later retain their own cutoffs.
///
/// # Errors
/// A foreign scope.
pub fn scope_enabled(&self, scope: &Scope) -> Result<Scope> {
self.validate_scope(scope)?;
let mut result = scope.clone();
result.env.dynamic.branch();
Ok(result)
}
/// Looks up an actual substitution under the supplied evaluation control.
/// `None` means absent; `Some(SlotView::Unset)` means explicitly unbound.
/// Variable cutoff applies to primed reads inside ENABLED and all reads in
/// its primed successor; constants are never hidden by that cutoff.
///
/// # Errors
/// A foreign scope/state or an unknown declaration.
pub fn scope_substitution(
&self,
scope: &Scope,
decl: dive_ir::DeclId,
st: &St,
primed: bool,
) -> Result<Option<SlotView>> {
self.validate_scope(scope)?;
self.validate_state_context(st)?;
let declaration = self.core.ir.decls().get(decl.index()).ok_or_else(|| {
crate::ContextError::new(
crate::ContextErrorKind::UnknownId,
"substitution declaration",
)
})?;
let cutoff = declaration.variable
&& (st.is(crate::env::control::PRIMED)
|| (primed && st.is(crate::env::control::ENABLED)));
Ok(scope
.env
.dynamic
.lookup_cut(decl, cutoff)
.map(|slot| match slot {
Sv::Unset => SlotView::Unset,
Sv::Val(value) => SlotView::Value(value.clone()),
Sv::AnalysisBound => SlotView::AnalysisBound,
Sv::AnalysisConstant => SlotView::AnalysisConstant,
Sv::Thunk(thunk) => SlotView::Lazy(
thunk.expr,
Scope {
owner: self.core.ir.clone(),
names: self.core.names.clone(),
context: Arc::downgrade(&self.core),
env: thunk.env.clone(),
wrapper: scope.wrapper,
},
),
Sv::Fcn(function) if function.rec_slot.is_some() && function.excepts.is_empty() => {
SlotView::Function(function.clone())
}
Sv::Fcn(_) | Sv::Op(_) => SlotView::Other,
}))
}
/// The uncaptured top-level definition substituted for an operator.
///
/// This only reads binding metadata. It does not execute the operator or
/// prove its body pure. Lexical or dynamic captures and native/built-in
/// operator values return `None`; a compiler must retain its named refusal
/// for those contexts instead of dropping them.
///
/// # Errors
/// A foreign scope, unknown declaration, or inconsistent operator arity.
pub fn scope_subst_operator(
&self,
scope: &Scope,
decl: dive_ir::DeclId,
) -> Result<Option<DefId>> {
self.validate_scope(scope)?;
let declaration = self.core.ir.decls().get(decl.index()).ok_or_else(|| {
crate::ContextError::new(
crate::ContextErrorKind::UnknownId,
"substitution declaration",
)
})?;
let Some(Sv::Op(operator)) = scope.env.dynamic.lookup(decl) else {
return Ok(None);
};
let crate::env::OpVal::Def {
def,
parent: None,
dynamic: None,
} = &**operator
else {
return Ok(None);
};
let target = self.admit_def(*def)?;
if target.scope != DefScope::TopLevel || target.std.is_some() {
return Ok(None);
}
if target.params.len() != declaration.arity as usize {
return Err(crate::ContextError::new(
crate::ContextErrorKind::Arity,
"substituted operator argument count",
)
.into());
}
Ok(Some(*def))
}
/// What the innermost substitution of `decl` in `scope` holds, if any.
#[must_use]
pub fn scope_subst_slot(&self, scope: &Scope, decl: dive_ir::DeclId) -> SlotView {
if self.validate_scope(scope).is_err() {
return SlotView::Other;
}
match scope.env.dynamic.lookup(decl) {
None | Some(Sv::Unset) => SlotView::Unset,
Some(Sv::Val(v)) => SlotView::Value(v.clone()),
Some(Sv::AnalysisBound) => SlotView::AnalysisBound,
Some(Sv::AnalysisConstant) => SlotView::AnalysisConstant,
Some(Sv::Thunk(t)) => SlotView::Lazy(
t.expr,
Scope {
owner: self.core.ir.clone(),
names: self.core.names.clone(),
context: Arc::downgrade(&self.core),
env: t.env.clone(),
wrapper: scope.wrapper,
},
),
Some(_) => SlotView::Other,
}
}
/// What a local reference in `scope` holds.
#[must_use]
pub fn scope_slot(&self, scope: &Scope, r: LocalRef) -> SlotView {
if self.validate_scope(scope).is_err() {
return SlotView::Other;
}
let Some(frame) = scope.env.frame_up(r.up) else {
return SlotView::Unset;
};
match frame.slots.get(r.slot.index()) {
None | Some(Sv::Unset) => SlotView::Unset,
Some(Sv::Val(v)) => SlotView::Value(v.clone()),
Some(Sv::AnalysisBound) => SlotView::AnalysisBound,
Some(Sv::AnalysisConstant) => SlotView::AnalysisConstant,
Some(Sv::Thunk(t)) => SlotView::Lazy(
t.expr,
Scope {
owner: self.core.ir.clone(),
names: self.core.names.clone(),
context: Arc::downgrade(&self.core),
env: t.env.clone(),
wrapper: scope.wrapper,
},
),
Some(Sv::Fcn(function))
if function.rec_slot.is_some() && function.excepts.is_empty() =>
{
SlotView::Function(function.clone())
}
Some(_) => SlotView::Other,
}
}
/// The bindings of a bounded `\E` (an [`Expr::Quant`]) in `scope`, in
/// TLC's enumeration order (`ContextEnumerator`, first variable fastest):
/// one scope per binding, each with the variables bound. The domains are
/// evaluated in `st` (TLC's `getActions` uses the empty state).
///
/// # Errors
/// Any error evaluating or enumerating a domain.
pub fn scope_bindings(&self, scope: &Scope, quant: ExprId, st: &St) -> Result<Vec<Scope>> {
self.admit_scoped_expr(scope, quant)?;
self.validate_scope(scope)?;
self.validate_state_context(st)?;
let core = &self.core;
let Expr::Quant { bounds, .. } = core.ir.expr(quant) else {
return Err(EvalError::bug(
"scope_bindings on a node that is not a quantifier",
));
};
let mut env = scope.env.clone();
let mut out = Vec::new();
core.for_each_context(&mut env, st, bounds, quant, &mut |_, env| {
out.push(Scope {
owner: self.core.ir.clone(),
names: self.core.names.clone(),
context: Arc::downgrade(&self.core),
env: env.clone(),
wrapper: scope.wrapper,
});
Ok(true)
})?;
Ok(out)
}
/// Enumerates finite bindings of a quantifier, set filter/map or function
/// constructor with entry-count bounds.
/// Explicit sets, intervals and structurally finite lazy constructors are
/// supported. Domain entries, materialized component/value slots and
/// Cartesian bindings are each bounded by `limit`, before retaining
/// them. Pure captured filters over bounded structural inputs are admitted;
/// infinite, opaque and unresolved-effect domains remain explicit refusals.
/// Order is the profile's exploration order, first variable fastest.
/// This is expression binding, not successor generation.
///
/// # Errors
/// Missing/nonfinite bounds, domain evaluation or tuple-pattern errors,
/// and explicit domain/binding resource limits.
pub fn scope_bindings_bounded(
&self,
scope: &Scope,
quant: ExprId,
st: &St,
limit: usize,
) -> Result<Vec<Scope>> {
let columns = self.bounded_binding_columns(scope, quant, st, limit)?;
self.bounded_body_contexts(scope, quant, &columns, limit)
}
// All domain evaluation, bounded-domain inspection and enumeration remains
// before any body. The public eager API and private cursor share this order.
fn bounded_binding_columns(
&self,
scope: &Scope,
quant: ExprId,
st: &St,
limit: usize,
) -> Result<Vec<BindingColumn>> {
self.admit_scoped_expr(scope, quant)?;
self.validate_scope(scope)?;
self.validate_state_context(st)?;
let core = &self.core;
let bounds: &[dive_ir::Bound] = match core.ir.expr(quant) {
Expr::Quant { bounds, .. }
| Expr::SetMap { bounds, .. }
| Expr::FcnCons { bounds, .. } => bounds,
Expr::SetFilter { bound, .. } => std::slice::from_ref(bound),
_ => return Err(EvalError::bug("bounded bindings require a finite binder")),
};
let mut columns = Vec::new();
let mut entries = 0_usize;
let mut budget = crate::bounded_domain::Budget::new(limit, core.opts.max_depth, core.ctx);
for b in bounds {
let dom = b
.domain
.ok_or_else(|| EvalError::unsupported("unbounded quantifier"))?;
let Value::Set(set) = self.eval_scoped(scope, dom, st)? else {
return Err(EvalError::unsupported("quantifier domain is not a set"));
};
budget.set(&set, 0)?;
let size = usize::try_from(set.size(core.ctx)?)
.map_err(|_| EvalError::resource_limit("quantifier domain entries"))?;
entries = entries
.checked_add(size)
.filter(|n| *n <= limit)
.ok_or_else(|| EvalError::resource_limit("quantifier domain entries"))?;
let values = core.explore(&set)?;
if b.tuple {
columns.push((
b.vars.iter().map(|slot| slot.index()).collect(),
true,
values,
));
} else {
for &v in &b.vars {
columns.push((vec![v.index()], false, values.clone()));
}
}
}
Ok(columns)
}
fn bounded_binding_count(columns: &[BindingColumn], limit: usize) -> Result<usize> {
columns
.iter()
.try_fold(1_usize, |n, (_, _, ds)| n.checked_mul(ds.len()))
.filter(|n| *n <= limit)
.ok_or_else(|| EvalError::resource_limit("quantifier bindings"))
}
pub(crate) fn bounded_body_contexts(
&self,
scope: &Scope,
quant: ExprId,
columns: &[BindingColumn],
limit: usize,
) -> Result<Vec<Scope>> {
let count = Self::bounded_binding_count(columns, limit)?;
let mut result = Vec::with_capacity(count);
for i in 0..count {
let mut scope = scope.clone();
let mut quotient = i;
for (slots, tuple, values) in columns {
let value = &values[quotient % values.len()];
quotient /= values.len();
self.core
.bind_one(&mut scope.env, slots, *tuple, value, quant)?;
}
result.push(scope);
}
Ok(result)
}
/// Binds each finite constructor/quantifier variable to a pure unknown.
/// This context is only for conservative level and purity analysis of
/// state-dependent domains. It does not evaluate a domain, assume it is
/// finite, or choose a sample value. Every slot is conservatively state
/// level and cannot be forced by the interpreter. Runtime evaluation
/// must use the original scope with concrete bounded domain bindings.
///
/// # Errors
/// A non-binder expression or an unbounded domain.
pub fn scope_binder_analysis(&self, scope: &Scope, expr: ExprId) -> Result<Scope> {
self.binder_analysis(scope, expr, &Sv::AnalysisBound)
}
/// Binds each variable of a finite non-recursive binder over a constant
/// domain to a pure constant-level unknown ([`SlotView::AnalysisConstant`]).
///
/// Static level and purity analysis visits the body once in this context
/// instead of once per binding: a bound value is a constant that cannot
/// change the body's effects or the level of anything but itself. The
/// domain is not evaluated, assumed finite or sampled; forcing a slot is
/// the [`EvalError::is_analysis_only`] refusal. The caller must have
/// established that every domain is constant level and pure. Runtime
/// evaluation must use the original scope with concrete bindings.
///
/// # Errors
/// A non-binder or recursive-function expression, or an unbounded domain.
pub fn scope_constant_binder_analysis(&self, scope: &Scope, expr: ExprId) -> Result<Scope> {
self.admit_scoped_expr(scope, expr)?;
if matches!(self.core.ir.expr(expr), Expr::RecFcn { .. }) {
return Err(EvalError::bug(
"constant binder analysis of a recursive function",
));
}
self.binder_analysis(scope, expr, &Sv::AnalysisConstant)
}
fn binder_analysis(&self, scope: &Scope, expr: ExprId, unknown: &Sv) -> Result<Scope> {
self.admit_scoped_expr(scope, expr)?;
self.validate_scope(scope)?;
let bounds: &[dive_ir::Bound] = match self.core.ir.expr(expr) {
Expr::Quant { bounds, .. }
| Expr::SetMap { bounds, .. }
| Expr::FcnCons { bounds, .. }
| Expr::RecFcn { bounds, .. } => bounds,
Expr::SetFilter { bound, .. } => std::slice::from_ref(bound),
_ => return Err(EvalError::bug("analysis scope requires a finite binder")),
};
let mut result = scope.clone();
if let Expr::RecFcn { name, .. } = self.core.ir.expr(expr) {
result.env.bind(name.index(), Sv::AnalysisBound);
}
for bound in bounds {
if bound.domain.is_none() {
return Err(EvalError::unsupported("unbounded analysis domain"));
}
for slot in &bound.vars {
result.env.bind(slot.index(), unknown.clone());
}
}
Ok(result)
}
/// Evaluates `expr` in `scope`.
///
/// # Errors
/// Any evaluation error, refusal or resource limit.
pub fn eval_scoped(&self, scope: &Scope, expr: ExprId, st: &St) -> Result<Value> {
self.admit_scoped_expr(scope, expr)?;
self.validate_scope(scope)?;
self.validate_state_context(st)?;
let mut env = scope.env.clone();
let ev = self.core.eval(&mut env, st, expr)?;
self.core.force_fcn(ev)
}
/// Evaluates an argument of an operator application in `scope`, as TLC's
/// `getActionsAppl` does before it inlines the operator
/// (`this.eval(args[i], con, TLCState.Empty)`).
///
/// # Errors
/// Any evaluation error; an operator argument is not a value.
pub fn eval_arg(&self, scope: &Scope, arg: &Arg, st: &St) -> Result<Value> {
self.validate_scope(scope)?;
self.validate_state_context(st)?;
match arg {
Arg::Expr { expr, .. } => self.eval_scoped(scope, *expr, st),
Arg::Op { .. } => Err(EvalError::unsupported(
"an operator argument where TLC expects a value",
)),
}
}
/// Evaluates the body of a zero-arity definition at start-up and keeps
/// the value for every later use, as `SpecProcessor.processConstantDefns`
/// does (`WorkerValue.demux(opDefEvaluator, opDef.getBody())`, then
/// `opDef.setToolObject(toolId, val)`). The body is evaluated every time
/// this is called, as TLC evaluates it every time it meets it; the first
/// value is kept (TLC keeps the last, which is the same value unless the
/// definition draws random values). On failure nothing is kept and the
/// definition stays lazy; TLC swallows the error.
///
/// A function TLC would keep as a lambda (`FcnLambdaValue`) is not kept:
/// the definition stays lazy, and `Ok(None)` is returned. dive has no
/// value form for such a function, and re-evaluating it is
/// indistinguishable unless it is impure.
///
/// # Errors
/// The evaluation error, which the binding stage swallows as TLC does.
pub fn precompute(&self, def: DefId) -> Result<Option<Value>> {
let core = &self.core;
let d = self.admit_def(def)?;
let mut env = Env::new(def, d.depth, d.frame.len(), None, Dyn::default());
let st = St::constant()
.with_control(crate::env::control::CONST | crate::env::control::PRECOMPUTE);
// Pure calls repeated within this evaluation are evaluated once
// (`crate::startup_calls`); their results last only as long as it.
let lock = || {
core.startup_calls
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
};
*lock() = Some(crate::startup_calls::StartupCalls::default());
let ev = core.eval(&mut env, &st, d.body);
if let Some(calls) = lock().take() {
core.startup_call_hits
.fetch_add(calls.hits, std::sync::atomic::Ordering::Relaxed);
}
let ev = ev?;
let Ev::V(v) = ev else {
return Ok(None);
};
if let Some(cell) = core.startup.get(def.index()) {
let _ = cell.set(v.clone());
}
Ok(Some(v))
}
/// The value [`Evaluator::precompute`] kept for a definition.
#[must_use]
pub fn precomputed(&self, def: DefId) -> Option<Value> {
self.core
.startup
.get(def.index())
.and_then(|c| c.get())
.cloned()
}
}
impl crate::core::Core {
/// Binds `bindings` (an instance's substitutions) over `env`: lazy values
/// over the outer context, cached or not as TLC creates them.
pub(crate) fn bind_subst(
self: &Arc<Self>,
env: &Env,
st: &St,
bindings: &[dive_ir::SubstBinding],
cachable: bool,
) -> Result<Env> {
let outer = env.clone();
let mut env1 = env.clone();
for b in bindings {
let val = match &b.value {
Arg::Expr { expr, pass } => match pass {
Pass::Strict => Sv::from(self.eval(&mut outer.clone(), st, *expr)?),
Pass::Lazy | Pass::Direct => {
Sv::Thunk(Thunk::new(*expr, outer.clone(), cachable))
}
},
Arg::Op { op, .. } => Sv::op(self.op_value(&outer, op)?),
};
env1.dynamic.push(b.decl, val);
}
Ok(env1)
}
}
#[cfg(test)]
#[allow(clippy::expect_used, reason = "owned capture-identity fixtures")]
mod operator_capture_tests {
use super::*;
use crate::env::OpVal;
#[test]
fn split_operator_metadata_rejects_foreign_and_captured_contexts() {
let analysis = dive_sema::analyze_source(
"SplitOperator.tla",
"---- MODULE SplitOperator ----\nCONSTANT F(_)\nTarget(v)==v\nRoot==TRUE\n====\n",
&dive_sema::Options::default(),
);
assert!(analysis.accepted());
let ir = Arc::new(dive_ir::lower(&analysis).expect("lower"));
let ev = Evaluator::new(crate::Model::new(ir.clone()), crate::Options::default())
.expect("evaluator");
let def = ir.root_def("Target").expect("Target");
let root = ir.root_def("Root").expect("Root");
let decl = ir.consts()[0];
let mut scope = ev.scope(root).expect("scope");
scope.env.dynamic.push(
decl,
Sv::op(OpVal::Def {
def,
parent: None,
dynamic: None,
}),
);
assert_eq!(
ev.scope_subst_operator(&scope, decl).expect("metadata"),
Some(def)
);
let other = Evaluator::new(crate::Model::new(ir.clone()), crate::Options::default())
.expect("other evaluator");
assert!(other.scope_subst_operator(&scope, decl).is_err());
assert!(
ev.scope_subst_operator(&scope, dive_ir::DeclId(u32::MAX))
.is_err()
);
for (parent, dynamic) in [
(Some(scope.env.frame.clone()), None),
(None, Some(Dyn::default())),
] {
let mut retained = scope.clone();
retained.env.dynamic.push(
decl,
Sv::op(OpVal::Def {
def,
parent,
dynamic,
}),
);
assert!(
ev.scope_subst_operator(&retained, decl)
.expect("captured metadata")
.is_none()
);
}
}
#[test]
fn same_lexical_frame_is_inspected_under_each_dynamic_context() {
let analysis = dive_sema::analyze_source(
"CaptureIdentity.tla",
"---- MODULE CaptureIdentity ----\nEXTENDS TLC\nCONSTANT A(_)\nGood(v)==v\nEvil(v)==PrintT(v)\nProbe(v)==A(v)\nHolder(F(_),saved)==TRUE\nRoot(a,b)==TRUE\n====\n",
&dive_sema::Options::default(),
);
assert!(analysis.accepted());
let ir = Arc::new(dive_ir::lower(&analysis).expect("lower"));
let ev = Evaluator::new(crate::Model::new(ir.clone()), crate::Options::default())
.expect("evaluator");
let def = |name| ir.root_def(name).expect("definition");
let operator = |def| {
Sv::op(OpVal::Def {
def,
parent: None,
dynamic: None,
})
};
let mut shared = ev.scope(def("Holder")).expect("holder").env;
shared.bind(0, operator(def("Probe")));
shared.bind(1, Sv::AnalysisBound);
let decl = ir
.decls()
.iter()
.position(|d| d.name.as_str() == "A")
.map(|i| dive_ir::DeclId(u32::try_from(i).expect("decl")))
.expect("A");
let contexts: Vec<_> = ["Good", "Evil"]
.into_iter()
.map(|name| {
let mut env = shared.clone();
env.dynamic.push(decl, operator(def(name)));
env
})
.collect();
assert!(Arc::ptr_eq(&contexts[0].frame, &contexts[1].frame));
let mut scope = ev.scope(def("Root")).expect("root");
for (i, env) in contexts.into_iter().enumerate() {
scope.env.bind(
i,
Sv::Thunk(Thunk::new(ir.def(def("Root")).body, env, false)),
);
}
let projected = ev
.scope_operator_captures(&scope, &mut 1_000)
.expect("ownership and work")
.expect("known user targets");
assert!(
projected
.iter()
.any(|(expr, _)| *expr == ir.def(def("Evil")).body)
);
let probe_contexts: Vec<_> = projected
.iter()
.filter(|(expr, _)| *expr == ir.def(def("Probe")).body)
.collect();
assert_eq!(probe_contexts.len(), 2);
let bindings: Vec<_> = probe_contexts
.iter()
.map(
|(_, context)| match context.env.dynamic.lookup(decl).expect("substitution") {
Sv::Op(op) => match &**op {
OpVal::Def { def, .. } => *def,
_ => def("Root"),
},
_ => def("Root"),
},
)
.collect();
assert!(bindings.contains(&def("Good")) && bindings.contains(&def("Evil")));
let mut at = scope.clone();
at.env.dynamic.at = Some(true.into());
assert!(
ev.scope_operator_captures(&at, &mut 1_000)
.expect("at refusal")
.is_none()
);
assert_eq!(ev.take_output(), Vec::<String>::new());
}
}
#[cfg(test)]
mod bounded_count_tests {
use super::*;
#[test]
fn no_columns_is_one_binding_but_empty_domain_is_zero_even_at_zero_limit() {
assert_eq!(Evaluator::bounded_binding_count(&[], 1), Ok(1));
assert_eq!(
Evaluator::bounded_binding_count(&[], 0),
Err(EvalError::resource_limit("quantifier bindings"))
);
let columns = vec![(vec![0], false, Arc::<[Value]>::from([]))];
assert_eq!(Evaluator::bounded_binding_count(&columns, 0), Ok(0));
}
}