semi_persistent_egraph/
extract.rs1use crate::ast::Span;
6use crate::ast::Term;
7use crate::canon::{MSetCanon, VarCanon};
8use crate::config::EGraphConfig;
9use crate::containers::DenseId;
10use crate::egraph::EGraph;
11use crate::literal::LitVal;
12use crate::multiplicity::MultiplicityLike;
13
14#[derive(Clone, Debug, PartialEq, Eq)]
16pub enum ExtractError {
17 AllUnextractable {
20 class: usize,
22 ops: Vec<String>,
24 },
25 NoGroundTerm {
28 class: usize,
30 },
31}
32
33impl std::fmt::Display for ExtractError {
34 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35 match self {
36 ExtractError::AllUnextractable { class, ops } => write!(
37 f,
38 "e-class {class} has no extractable node: every node is an :unextractable op ({})",
39 ops.join(", ")
40 ),
41 ExtractError::NoGroundTerm { class } => write!(
42 f,
43 "e-class {class} has no ground term: no node has a fully extractable child set"
44 ),
45 }
46 }
47}
48
49impl std::error::Error for ExtractError {}
50
51pub fn extract_best<Cfg, L, const T: bool, const P: bool>(
58 eg: &EGraph<Cfg, L, T, P>,
59 root: Cfg::G,
60) -> Result<Term, ExtractError>
61where
62 Cfg: EGraphConfig,
63 L: LitVal,
64 MSetCanon: VarCanon<Cfg::G, Cfg::C>,
65{
66 let n = eg.len();
67 let meta = eg.ops().meta_table();
71
72 const UNSET: usize = usize::MAX;
84 let mut best_cost: Vec<usize> = vec![UNSET; n];
85 let mut best_node: Vec<Cfg::G> = vec![Cfg::G::default(); n];
86
87 loop {
88 let mut changed = false;
89 for id in eg.node_ids() {
90 let m = meta[eg.node_op(id).to_usize()];
94 if m.unextractable {
95 continue;
96 }
97 let repr = eg.find_const(id);
98
99 let mut total: usize = m.cost as usize;
100 let mut ok = true;
101 eg.for_each_child(id, |child, mult| {
102 if !ok {
103 return;
104 }
105 let c = best_cost[eg.find_const(child).to_usize()];
106 if c == UNSET {
107 ok = false;
108 } else {
109 total = total.saturating_add(c.saturating_mul(mult.to_usize()));
110 }
111 });
112 if !ok {
113 continue;
114 }
115
116 let slot = repr.to_usize();
117 if total < best_cost[slot] {
118 best_cost[slot] = total;
119 best_node[slot] = id;
120 changed = true;
121 }
122 }
123 if !changed {
124 break;
125 }
126 }
127
128 let root_repr = eg.find_const(root);
129 if best_cost[root_repr.to_usize()] == UNSET {
130 return Err(diagnose(eg, &meta, root_repr));
131 }
132 Ok(reconstruct(eg, &best_node, root_repr))
133}
134
135fn diagnose<Cfg, L, const T: bool, const P: bool>(
138 eg: &EGraph<Cfg, L, T, P>,
139 meta: &[crate::registry::OpMeta],
140 repr: Cfg::G,
141) -> ExtractError
142where
143 Cfg: EGraphConfig,
144 L: LitVal,
145 MSetCanon: VarCanon<Cfg::G, Cfg::C>,
146{
147 let class = repr.to_usize();
148 let mut ops: Vec<String> = Vec::new();
149 let mut any = false;
150 let mut all_unextractable = true;
151 for id in eg.node_ids() {
152 if eg.find_const(id) != repr {
153 continue;
154 }
155 any = true;
156 if meta[eg.node_op(id).to_usize()].unextractable {
157 let name = eg.node_op_name(id);
158 if !ops.iter().any(|o| o == name) {
159 ops.push(name.to_string());
160 }
161 } else {
162 all_unextractable = false;
163 }
164 }
165 if any && all_unextractable {
166 ExtractError::AllUnextractable { class, ops }
167 } else {
168 ExtractError::NoGroundTerm { class }
169 }
170}
171
172fn reconstruct<Cfg, L, const T: bool, const P: bool>(
173 eg: &EGraph<Cfg, L, T, P>,
174 best_node: &[Cfg::G],
175 repr: Cfg::G,
176) -> Term
177where
178 Cfg: EGraphConfig,
179 L: LitVal,
180 MSetCanon: VarCanon<Cfg::G, Cfg::C>,
181{
182 let id = best_node[repr.to_usize()];
183 let name = eg.node_op_name(id).to_string();
184
185 if let Some(val) = eg.get_lit_val(id) {
186 return Term::Lit(val.to_string(), Span::Dummy);
187 }
188
189 let mut children = Vec::new();
190 eg.for_each_child(id, |child, mult| {
191 if mult == Cfg::M::ZERO {
192 return;
193 }
194 let t = reconstruct(eg, best_node, eg.find_const(child));
195 for _ in 1..mult.to_usize() {
202 children.push(t.clone());
203 }
204 children.push(t);
205 });
206
207 Term::App {
208 op: name,
209 children,
210 span: Span::Dummy,
211 }
212}