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
use crate::{
Binder1,
BType,
Comp,
Ident,
LogOpN,
Quantifier,
Sig,
Val,
};
use graph_cycles::Cycles;
use petgraph::graph::Graph;
use std::collections::HashMap;
use std::collections::HashSet;
pub struct SortIndex(pub Vec<BType>);
pub type Cycle = Vec<BType>;
pub fn render_cycle(c: &Cycle) -> String {
if c.len() == 1 {
format!("self-loop ⤷ {} ⤴", c[0])
} else {
// Normalize the starting-point of the cycle so that we can
// test based on error message matches.
let c = normalize_cycle(c.clone());
let mut s = String::new();
let mut first = true;
s.push_str("⤷ ");
for b in c {
if first {
s.push_str(&format!("{} ", b));
} else {
s.push_str(&format!("→ {} ", b));
}
first = false;
}
s.push_str(&format!("⤴"));
s
}
}
// Rotate the cycle to start with the alphabetically-first sort.
fn normalize_cycle(c: Cycle) -> Cycle {
if c.len() <= 1 {
c
} else {
let mut idxs: Vec<(usize, &BType)> = c.iter().enumerate().collect();
// Sort by comparing the string renderings.
idxs.sort_by(|b1,b2| b1.1.render().cmp(&b2.1.render()));
// Get the index of the first item.
let head = idxs[0].0;
let mut out = Vec::with_capacity(c.len());
for i in 0..(c.len()) {
out.push(c[(head + i) % c.len()].clone());
}
out
}
}
impl SortIndex {
fn to_index(&self, s: &BType) -> usize {
for (i,s1) in self.0.iter().enumerate() {
if s1 == s {
return i
}
}
panic!("No index found for base type {}", s)
}
fn from_index(&self, i: usize) -> BType {
self.0[i].clone()
}
}
#[derive(Clone, PartialEq, Eq)]
enum QNode {
Exists(Vec<BType>, QTree),
Forall(Vec<BType>, QTree),
}
impl QNode {
fn negate(&self) -> Self {
match self {
Self::Exists(bs, t) =>
Self::Forall(bs.clone(), t.negate()),
Self::Forall(bs, t) =>
Self::Exists(bs.clone(), t.negate()),
}
}
}
#[derive(Clone, PartialEq, Eq)]
struct QTree(Vec<QNode>);
impl QTree {
fn new() -> Self { Self(Vec::new()) }
fn merge(&mut self, mut other: Self) {
self.0.append(&mut other.0);
}
fn negate(&self) -> Self {
Self(self.0.iter().map(|n| n.negate()).collect())
}
fn wrap_with(self, q: Quantifier, bs: Vec<BType>) -> Self {
let n = match q {
Quantifier::Exists => QNode::Exists(bs, self),
Quantifier::Forall => QNode::Forall(bs, self),
};
QTree(vec![n])
}
fn merge_vals<'a,I: Iterator<Item=&'a Val>>(
&mut self,
ctx: &HashMap<Ident, Option<Self>>,
vs: I,
also_negate: bool,
) {
for v in vs {
match v {
Val::Literal(_) => {},
Val::OpCode(..) => {},
Val::Var(x, _, _, _) => match ctx.get(x) {
// This is a proposition
Some(Some(qt)) => {
self.merge(qt.clone());
if also_negate {
self.merge(qt.negate());
}
}
// This is a quantified value
Some(None) => {}
// Assume this is a constructor
None => {}
}
v => panic!("epr_check found unexpected val form in an equation: {:?}", v),
}
}
}
/// Record the tree's Forall->Exists alternations in a sort graph.
fn sort_graph(&self) -> SortGraph {
let mut graph = SortGraph::new();
self.sort_graph_r(&mut graph, HashSet::new());
graph
}
fn sort_graph_r(
&self,
graph: &mut SortGraph,
within_foralls: HashSet<BType>,
) {
for n in &self.0 {
match n {
QNode::Exists(bs, t) => {
for b1 in &within_foralls {
for b2 in bs {
graph.add_edge(b1.clone(), b2.clone());
}
}
t.sort_graph_r(graph, within_foralls.clone());
}
QNode::Forall(bs, t) => {
let mut fs = within_foralls.clone();
for b in bs {
fs.insert(b.clone());
}
t.sort_graph_r(graph, fs);
}
}
}
}
}
#[derive(Clone)]
pub struct SortGraph(HashSet<(BType,BType)>);
impl SortGraph {
pub fn new() -> Self { SortGraph(HashSet::new()) }
fn add_edge(&mut self, s1: BType, s2: BType) {
assert!(
s1 != BType::prop() && s2 != BType::prop(),
"sort graph edges should not be on 'bool'",
);
self.0.insert((s1,s2));
}
pub fn get_cycles(&self) -> Vec<Vec<BType>> {
let index = self.get_index();
let mut i_graph = Vec::new();
for (s1,s2) in self.0.iter() {
let i1 = index.to_index(s1);
let i2 = index.to_index(s2);
i_graph.push((i1 as u32,i2 as u32));
}
let g = Graph::<(), ()>::from_edges(i_graph);
let mut cycles = Vec::new();
g.visit_all_cycles(|_g, c| {
let mut c_s = Vec::new();
for i in c.iter() {
c_s.push(index.from_index(i.index()));
}
cycles.push(c_s);
});
cycles
}
fn get_index(&self) -> SortIndex {
let mut sorts = HashSet::new();
for (s1,s2) in self.0.iter() {
sorts.insert(s1.clone());
sorts.insert(s2.clone());
}
SortIndex(sorts.into_iter().collect())
}
pub fn append(&mut self, other: Self) {
self.0.extend(other.0);
}
}
pub fn test() -> Graph<(), ()> {
let g = Graph::<(), ()>::from_edges([
(1, 2),
(2, 3),
(3, 4),
(3, 2),
]);
g.visit_all_cycles(|_g, c| {
println!("Cycle: {c:?}");
});
g
}
impl Comp {
pub fn sort_graph(&self) -> SortGraph {
// self.sort_graph_r(HashSet::new())
let t = self.qtree();
t.sort_graph()
}
fn qtree(&self) -> QTree {
self.qtree_r(HashMap::new())
}
fn qtree_r(&self, mut ctx: HashMap<Ident, Option<QTree>>) -> QTree {
// In the context, x := Some(t) means that x is a proposition
// with qtree t. x := None means that x is a quantified
// value, which has no qtree. If x is not present, it means
// that x is unbound, or a constructor.
match self {
Comp::Bind1(Binder1::LogQuantifier(q, xs, body), x, m) => {
let mut bs = Vec::new();
let mut body_ctx = ctx.clone();
for (qx,qt) in xs {
// Record qx as a quantified value, shadowing any
// proposition that was already in the context
// under that name.
body_ctx.insert(qx.clone(), None);
// Collect the quantified base types, which will
// define the qnode for this quantifier.
for s in qt.clone().flatten() {
bs.push(s.unwrap_base().unwrap())
}
}
// Get the qtree of the body, and wrap it in a qnode
// that describes this quantifier.
let t = body.qtree_r(body_ctx).wrap_with(*q, bs);
// Record x as a proposition, described by the qtree.
ctx.insert(x.clone(), Some(t));
// Process the rest of the computation.
m.qtree_r(ctx)
}
Comp::Bind1(Binder1::Eq(_pol, left_vs, right_vs), x, m) => {
// The polarity (whether this is is_eq or is_not_eq)
// doesn't make a difference for the qtree.
let mut t = QTree::new();
// For each proposition we find among the equated
// values, we add its qtree twice (positive and
// negative) to x's qtree.
t.merge_vals(&ctx, left_vs.iter().chain(right_vs), true);
ctx.insert(x.clone(), Some(t));
m.qtree_r(ctx)
}
Comp::Bind1(Binder1::LogOpN(op, vs), x, m) => {
let mut t = QTree::new();
match op {
LogOpN::Pred(..) => {
t.merge_vals(&ctx, vs.iter(), true);
}
LogOpN::Or | LogOpN::And => {
t.merge_vals(&ctx, vs.iter(), false);
}
}
ctx.insert(x.clone(), Some(t));
m.qtree_r(ctx)
}
Comp::Ite(v, m1, m2) => {
let mut t = QTree::new();
t.merge_vals(&ctx, std::iter::once(v), true);
t.merge(m1.qtree_r(ctx.clone()));
t.merge(m2.qtree_r(ctx));
t
}
Comp::Return(vs) => {
let mut t = QTree::new();
t.merge_vals(&ctx, vs.iter(), false);
t
}
c => panic!("qtree_r can't handle {:?}", c)
}
}
}
impl Sig {
pub fn sort_graph_combined(&self, term: &Comp) -> SortGraph {
let (_, axioms) = self.relevant_with_axioms(term);
let mut graph = SortGraph::new();
for a in &axioms {
graph.append(a.sort_graph());
}
graph.append(term.sort_graph());
graph
}
// pub fn sort_graph(&self) -> SortGraph {
// // Operator axioms are counted when they are spliced into the
// // main assertion, so we only look at the axioms here.
// let mut graph = SortGraph::new();
// for a in self.axioms.iter() {
// graph.append(a.sort_graph());
// }
// graph
// }
}