mid-tools 0.0.0

Abstract tools for compiler middle ends
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
use hashbrown::{HashMap, HashSet};
pub use node::*;
pub use trace::EGraphTrace;

use crate::{
    dot,
    union_find::{ClassId, NoNode, Unioned},
};

pub mod congr;
pub mod fast;
mod node;
pub mod reference;
pub mod trace;

// TODO: a lot of this module could be cleaned up if they introduced a solution
//       for better derive bounds

pub mod prelude {
    pub use super::{EGraphCore, EGraphRead, EGraphUpgrade, EGraphUpgradeTrace, EGraphWrite};
}

pub trait EGraphCore {
    type FuncSymbol;
    type Class;

    fn add(
        &mut self,
        node: ENode<Self::FuncSymbol, Self::Class>,
    ) -> Result<ClassId<Self::Class>, NoNode>;
}

impl<T: ?Sized + EGraphCore> EGraphCore for &mut T {
    type Class = T::Class;
    type FuncSymbol = T::FuncSymbol;

    fn add(
        &mut self,
        node: ENode<Self::FuncSymbol, Self::Class>,
    ) -> Result<ClassId<Self::Class>, NoNode> {
        T::add(self, node)
    }
}

pub type ClassNodes<'a, G, S = hashbrown::DefaultHashBuilder> = HashMap<
    ClassId<<G as EGraphCore>::Class>,
    HashSet<&'a ENode<<G as EGraphCore>::FuncSymbol, <G as EGraphCore>::Class>, S>,
    S,
>;

pub trait EGraphRead: EGraphCore {
    type Hasher;

    fn find(&self, class: ClassId<Self::Class>) -> Result<ClassId<Self::Class>, NoNode>;

    /// Returns true if the node was modified
    fn canonicalize(&self, node: &mut ENode<Self::FuncSymbol, Self::Class>)
        -> Result<bool, NoNode>;

    fn is_canonical(&self, node: &ENode<Self::FuncSymbol, Self::Class>) -> Result<bool, NoNode>;

    fn class_nodes(&self) -> ClassNodes<'_, Self, Self::Hasher>;

    fn dot<M: trace::dot::Formatter<Self::FuncSymbol>>(&self, f: M) -> dot::Graph<'static>;
}

pub trait EGraphWrite: EGraphCore {
    fn merge(
        &mut self,
        a: ClassId<Self::Class>,
        b: ClassId<Self::Class>,
    ) -> Result<Unioned<Self::Class>, NoNode>;
}

pub trait EGraphWriteTrace: EGraphCore {
    fn merge_trace<T: EGraphTrace<Self::FuncSymbol, Self::Class>>(
        &mut self,
        a: ClassId<Self::Class>,
        b: ClassId<Self::Class>,
        t: &mut T,
    ) -> Result<Unioned<Self::Class>, NoNode>;
}

impl<T: EGraphWrite> EGraphWrite for &mut T {
    fn merge(
        &mut self,
        a: ClassId<Self::Class>,
        b: ClassId<Self::Class>,
    ) -> Result<Unioned<Self::Class>, NoNode> {
        T::merge(self, a, b)
    }
}

impl<G: EGraphWriteTrace> EGraphWriteTrace for &mut G {
    fn merge_trace<T: EGraphTrace<Self::FuncSymbol, Self::Class>>(
        &mut self,
        a: ClassId<Self::Class>,
        b: ClassId<Self::Class>,
        t: &mut T,
    ) -> Result<Unioned<Self::Class>, NoNode> {
        G::merge_trace(self, a, b, t)
    }
}

pub trait EGraphUpgradeTrace: EGraphRead {
    type WriteRef<'a, T: EGraphTrace<Self::FuncSymbol, Self::Class>>: EGraphWrite<
        FuncSymbol = Self::FuncSymbol,
        Class = Self::Class,
    >
    where Self: 'a;

    fn write_trace<T: EGraphTrace<Self::FuncSymbol, Self::Class>>(
        &mut self,
        tracer: T,
    ) -> Self::WriteRef<'_, T>;
}

pub trait EGraphUpgrade: EGraphUpgradeTrace {
    #[inline]
    fn write(&mut self) -> Self::WriteRef<'_, ()> { self.write_trace(()) }
}

impl<G: EGraphUpgradeTrace> EGraphUpgrade for G {}

#[derive(Debug)]
pub struct SimpleWriteRef<'a, G, T>(&'a mut G, T);

impl<G: EGraphRead + EGraphWriteTrace> EGraphUpgradeTrace for G {
    type WriteRef<'a, T: EGraphTrace<Self::FuncSymbol, Self::Class>>
        = SimpleWriteRef<'a, G, T>
    where Self: 'a;

    #[inline]
    fn write_trace<T: EGraphTrace<Self::FuncSymbol, Self::Class>>(
        &mut self,
        tracer: T,
    ) -> Self::WriteRef<'_, T> {
        SimpleWriteRef(self, tracer)
    }
}

impl<G: EGraphCore, T> EGraphCore for SimpleWriteRef<'_, G, T> {
    type Class = G::Class;
    type FuncSymbol = G::FuncSymbol;

    #[inline]
    fn add(
        &mut self,
        node: ENode<Self::FuncSymbol, Self::Class>,
    ) -> Result<ClassId<Self::Class>, NoNode> {
        self.0.add(node)
    }
}

impl<G: EGraphWriteTrace, T: EGraphTrace<G::FuncSymbol, G::Class>> EGraphWrite
    for SimpleWriteRef<'_, G, T>
{
    #[inline]
    fn merge(
        &mut self,
        a: ClassId<Self::Class>,
        b: ClassId<Self::Class>,
    ) -> Result<Unioned<Self::Class>, NoNode> {
        self.0.merge_trace(a, b, &mut self.1)
    }
}

pub mod test_tools {
    use std::{collections::BTreeMap, fmt};

    use hashbrown::HashMap;

    use super::ENode;
    use crate::{bijection::Bijection, union_find::ClassId};

    #[derive(Debug)]
    pub struct EGraphParts<F, C> {
        pub uf: crate::union_find::UnionFind<C>,
        pub node_classes: HashMap<ENode<F, C>, ClassId<C>>,
    }

    pub fn assert_equiv<
        F: fmt::Debug + Ord,
        C,
        A: Into<EGraphParts<F, C>>,
        B: Into<EGraphParts<F, C>>,
    >(
        a: A,
        b: B,
    ) -> Bijection<ClassId<C>, ClassId<C>> {
        let EGraphParts {
            uf: a_uf,
            node_classes: a_node_classes,
        } = a.into();
        let EGraphParts {
            uf: b_uf,
            node_classes: b_node_classes,
        } = b.into();

        let mut mapping = Bijection::new();

        assert_eq!(a_uf.len(), b_uf.len());
        for (a, b) in a_uf.classes().zip(b_uf.classes()) {
            mapping
                .insert(a_uf.find(a).unwrap(), b_uf.find(b).unwrap())
                .unwrap();
        }

        let a_node_classes_mapped: BTreeMap<_, _> = a_node_classes
            .iter()
            .map(|(n, c)| {
                let mut n = n.clone();
                n.map_args(|c| *mapping.image(&c).unwrap());
                (n, *mapping.image(c).unwrap())
            })
            .collect();

        let b_node_classes_mapped: BTreeMap<_, _> = b_node_classes
            .iter()
            .map(|(n, c)| {
                let mut n = n.clone();
                n.map_args(|c| *mapping.preimage(&c).unwrap());
                (n, *mapping.preimage(c).unwrap())
            })
            .collect();

        assert_eq!(
            a_node_classes.into_iter().collect::<BTreeMap<_, _>>(),
            b_node_classes_mapped
        );
        assert_eq!(
            a_node_classes_mapped,
            b_node_classes.into_iter().collect::<BTreeMap<_, _>>()
        );

        mapping
    }
}

#[cfg(test)]
mod test {
    use std::collections::BTreeMap;

    use foldhash::fast::FixedState;
    use prop::sample::SizeRange;
    use proptest::prelude::*;

    use super::{prelude::*, test_tools::assert_equiv};

    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    struct Symbol(char);
    #[derive(Debug, Clone)]
    struct Tree(Symbol, Vec<Tree>);

    #[derive(Debug)]
    struct Expr;

    impl Tree {
        fn fold_impl<T>(self, f: &mut impl FnMut(Symbol, Vec<T>) -> T) -> T {
            let Self(sym, children) = self;
            let children = children.into_iter().map(|c| c.fold_impl(f)).collect();
            f(sym, children)
        }

        #[inline]
        fn fold<T>(self, mut f: impl FnMut(Symbol, Vec<T>) -> T) -> T { self.fold_impl(&mut f) }

        fn count(&self) -> usize {
            self.1
                .iter()
                .map(Tree::count)
                .reduce(|l, r| l.checked_add(r).unwrap())
                .unwrap_or(0)
                .checked_add(1)
                .unwrap()
        }
    }

    type Node = super::ENode<Symbol, Expr>;
    type SlowGraph = super::reference::EGraph<Symbol, Expr>;
    type CongrGraph = super::congr::EGraph<Symbol, Expr>;
    type FastGraph<S> = super::fast::EGraph<Symbol, Expr, S>;

    type Parts = super::test_tools::EGraphParts<Symbol, Expr>;

    // TODO: track that only merged and originally-equivalent nodes are still equivalent
    // fn assert_merges<G: EGraphRead>(
    //     merges: &[(usize, usize)],
    //     class: impl Fn(usize) -> ClassId<G::Class>,
    // ) {
    // }

    // TODO: test adding after merging
    fn run_reference(tree: &Tree, merges: &Vec<(usize, usize)>) {
        let mut graph = SlowGraph::new();
        let mut classes = BTreeMap::new();
        let mut class_list = vec![];

        let root = tree.clone().fold(|sym, args| {
            let node = Node::new(sym.into(), args.into());
            let class = graph.add(node.clone()).unwrap();

            class_list.push(class);

            assert_eq!(*classes.entry(node).or_insert(class), class);

            class
        });

        graph.find(root).unwrap();

        for &(a, b) in merges {
            let a = class_list[a];
            let b = class_list[b];
            graph.write().merge(a, b).unwrap();
        }
    }

    // TODO: test adding after merging
    fn run<
        A: Default + Clone + EGraphUpgrade<FuncSymbol = Symbol, Class = Expr> + Into<Parts>,
        B: Clone + EGraphUpgrade<FuncSymbol = Symbol, Class = Expr> + Into<Parts>,
    >(
        mut b: B,
        tree: &Tree,
        merges: &Vec<(usize, usize)>,
        stepwise: bool,
    ) {
        let mut a = A::default();
        let mut classes = BTreeMap::new();
        let mut class_list = vec![];

        let root = tree.clone().fold(|sym, args| {
            let node = Node::new(sym.into(), args.into());

            let class = a.add(node.clone()).unwrap();
            assert_eq!(b.add(node.clone()).unwrap(), class);

            class_list.push(class);

            assert_eq!(*classes.entry(node).or_insert(class), class);

            class
        });

        // Sanity assertion that the root ended up in the graphs
        a.find(root).unwrap();
        b.find(root).unwrap();

        if stepwise {
            for &(l, r) in merges {
                let l = class_list[l];
                let r = class_list[r];
                a.write().merge(l, r).unwrap();
                b.write().merge(l, r).unwrap();

                assert_equiv(a.clone(), b.clone());
            }
        } else {
            {
                let mut a = a.write();
                let mut b = b.write();

                for &(l, r) in merges {
                    let l = class_list[l];
                    let r = class_list[r];
                    a.merge(l, r).unwrap();
                    b.merge(l, r).unwrap();
                }
            }

            assert_equiv(a, b);
        }
    }

    fn nodes_and_merges(
        symbol: impl Strategy<Value = char> + Clone + 'static,
        depth: u32,
        tree_size: u32,
        branch_size: u32,
        merge_size: impl Into<SizeRange>,
    ) -> impl Strategy<Value = (Tree, Vec<(usize, usize)>)> {
        let sym = symbol.prop_map(Symbol);
        let merge_size = merge_size.into();

        sym.clone()
            .prop_map(|s| Tree(s, vec![]))
            .prop_recursive(depth, tree_size, branch_size, move |t| {
                (
                    sym.clone(),
                    prop::collection::vec(t, 0..=(branch_size.try_into().unwrap())),
                )
                    .prop_map(|(s, c)| Tree(s, c))
            })
            .prop_flat_map(move |t| {
                let id = 0..t.count();
                prop::collection::vec((id.clone(), id), merge_size.clone())
                    .prop_map(move |m| (t.clone(), m))
            })
    }

    proptest! {
        #![proptest_config(ProptestConfig {
            // cases: 1 << 17,
            max_shrink_time: 0,
            max_shrink_iters: 16384,
            // max_shrink_iters: 1 << 18,
            ..ProptestConfig::default()
        })]

        #[test]
        fn reference(
            (nodes, merges) in nodes_and_merges(
                crate::prop::symbol(),
                32,
                512,
                6,
                1..=128,
            ),
        ) {
            run_reference(&nodes, &merges);
        }

        #[test]
        fn batched(
            (nodes, merges) in nodes_and_merges(
                crate::prop::symbol(),
                32,
                512,
                6,
                1..=128,
            ),
            seed in any::<u64>(),
        ) {
            run::<SlowGraph, FastGraph<_>>(
                FastGraph::with_hasher(FixedState::with_seed(seed)),
                &nodes,
                &merges,
                false,
            );
        }

        #[test]
        fn stepwise(
            (nodes, merges) in nodes_and_merges(
                crate::prop::symbol(),
                32,
                512,
                6,
                1..=128,
            ),
            seed in any::<u64>(),
        ) {
            run::<SlowGraph, FastGraph<_>>(
                FastGraph::with_hasher(FixedState::with_seed(seed)),
                &nodes,
                &merges,
                true,
            );
        }

        #[test]
        fn congr(
            (nodes, merges) in nodes_and_merges(
                crate::prop::symbol(),
                32,
                512,
                6,
                1..=128,
            ),
        ) {
            run::<SlowGraph, CongrGraph>(CongrGraph::default(), &nodes, &merges, true);
        }
    }
}