Skip to main content

mid_tools/egraph/
node.rs

1use std::{
2    fmt,
3    hash::{Hash, Hasher},
4    sync::Arc,
5};
6
7use super::EGraphRead;
8use crate::union_find::{ClassId, NoNode, UnionFind};
9
10// TODO: probably memoize this rather than use Arc
11pub struct ENode<F: ?Sized, C: ?Sized>(Arc<F>, Arc<[ClassId<C>]>);
12
13impl<F: ?Sized, C: ?Sized> ENode<F, C> {
14    #[must_use]
15    pub fn op(&self) -> &F { &self.0 }
16
17    #[must_use]
18    pub fn args(&self) -> &[ClassId<C>] { &self.1 }
19
20    pub fn classes_canonical(&self, uf: &UnionFind<C>) -> Result<bool, NoNode> {
21        for &arg in &*self.1 {
22            if arg != uf.find(arg)? {
23                return Ok(false);
24            }
25        }
26
27        Ok(true)
28    }
29
30    #[inline]
31    pub fn is_canonical<G: EGraphRead<FuncSymbol = F, Class = C>>(
32        &self,
33        eg: &G,
34    ) -> Result<bool, NoNode> {
35        eg.is_canonical(self)
36    }
37
38    pub fn try_map_args<G: Fn(ClassId<C>) -> Result<ClassId<C>, E>, E>(
39        &mut self,
40        f: G,
41    ) -> Result<bool, E> {
42        enum State<'a, C: ?Sized> {
43            Ref(&'a Arc<[ClassId<C>]>),
44            Mut(&'a mut [ClassId<C>]),
45        }
46
47        let mut args = State::Ref(&self.1);
48        for i in 0..self.1.len() {
49            match args {
50                State::Ref(a) => {
51                    // SAFETY: i is bounded by self.1.len()
52                    let arg = unsafe { a.get_unchecked(i) };
53                    let root = f(*arg)?;
54                    if root != *arg {
55                        let args_mut = Arc::make_mut(&mut self.1);
56                        // SAFETY: i is bounded by self.1.len()
57                        *unsafe { args_mut.get_unchecked_mut(i) } = root;
58                        args = State::Mut(args_mut);
59                    }
60                },
61                State::Mut(ref mut m) => {
62                    // SAFETY: i is bounded by self.1.len()
63                    let arg = unsafe { m.get_unchecked_mut(i) };
64                    *arg = f(*arg)?;
65                },
66            }
67        }
68
69        Ok(matches!(args, State::Mut(..)))
70    }
71
72    pub fn map_args<G: Fn(ClassId<C>) -> ClassId<C>>(&mut self, f: G) -> bool {
73        let Ok(res) = self.try_map_args::<_, std::convert::Infallible>(|a| Ok(f(a)));
74        res
75    }
76
77    pub fn canonicalize_classes(&mut self, uf: &UnionFind<C>) -> Result<bool, NoNode> {
78        self.try_map_args(|a| uf.find(a))
79    }
80
81    #[inline]
82    pub fn canonicalize<G: EGraphRead<FuncSymbol = F, Class = C>>(
83        &mut self,
84        eg: &G,
85    ) -> Result<bool, NoNode> {
86        eg.canonicalize(self)
87    }
88
89    #[inline]
90    pub fn to_canonical<G: EGraphRead<FuncSymbol = F, Class = C>>(
91        &self,
92        eg: &G,
93    ) -> Result<Self, NoNode> {
94        let mut ret = self.clone();
95        ret.canonicalize(eg).map(|_: bool| ret)
96    }
97}
98
99impl<F: ?Sized + fmt::Debug, C: ?Sized> fmt::Debug for ENode<F, C> {
100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101        #[repr(transparent)]
102        struct Args<'a, C: ?Sized>(&'a Arc<[ClassId<C>]>);
103
104        impl<C: ?Sized> fmt::Debug for Args<'_, C> {
105            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106                f.debug_list()
107                    .entries(self.0.iter().map(|c| c.id()))
108                    .finish()
109            }
110        }
111
112        let Self(op, args) = self;
113        f.debug_tuple("ENode")
114            .field(&op)
115            .field(&Args(args))
116            .finish()
117    }
118}
119
120impl<F: ?Sized, C: ?Sized> Clone for ENode<F, C> {
121    fn clone(&self) -> Self { Self(Arc::clone(&self.0), Arc::clone(&self.1)) }
122}
123
124impl<F: ?Sized + PartialEq, C: ?Sized> PartialEq for ENode<F, C> {
125    fn eq(&self, other: &Self) -> bool {
126        let Self(l_op, l_args) = self;
127        let Self(r_op, r_args) = other;
128        l_op == r_op && l_args == r_args
129    }
130}
131
132impl<F: ?Sized + Eq, C: ?Sized> Eq for ENode<F, C> {}
133
134impl<F: ?Sized + Ord, C: ?Sized> Ord for ENode<F, C> {
135    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
136        let Self(l_op, l_args) = self;
137        let Self(r_op, r_args) = other;
138        l_op.cmp(r_op).then_with(|| l_args.cmp(r_args))
139    }
140}
141
142impl<F: ?Sized + PartialOrd, C: ?Sized> PartialOrd for ENode<F, C> {
143    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
144        let Self(l_op, l_args) = self;
145        let Self(r_op, r_args) = other;
146        Some(l_op.partial_cmp(r_op)?.then_with(|| l_args.cmp(r_args)))
147    }
148}
149
150impl<F: ?Sized + Hash, C: ?Sized> Hash for ENode<F, C> {
151    fn hash<H: Hasher>(&self, state: &mut H) {
152        let Self(op, args) = self;
153        op.hash(state);
154        args.hash(state);
155    }
156}
157
158impl<F: ?Sized, C: ?Sized> ENode<F, C> {
159    pub const fn new(op: Arc<F>, args: Arc<[ClassId<C>]>) -> Self { Self(op, args) }
160}