Skip to main content

semi_persistent_egraph/
extract.rs

1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3//! Optimal term extraction: pull the lowest-cost term from an e-class.
4
5use 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/// Why [`extract_best`] could not produce a term.
15#[derive(Clone, Debug, PartialEq, Eq)]
16pub enum ExtractError {
17    /// The class has nodes, but every one of them belongs to an op declared
18    /// `:unextractable`, so the class denotes no extractable term.
19    AllUnextractable {
20        /// The class's representative id, as a plain index.
21        class: usize,
22        /// The op names of the class's nodes, deduplicated, in first-seen order.
23        ops: Vec<String>,
24    },
25    /// No node in the class has a fully costed child set: the class is reachable only
26    /// through cycles, or through classes that are themselves not extractable.
27    NoGroundTerm {
28        /// The class's representative id, as a plain index.
29        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
51/// Extract the cheapest term from the e-class containing `root`.
52///
53/// Cost = the sum of the per-node costs of the term's nodes, where a node costs its op's
54/// declared `:cost` (default 1, so an undeclared program keeps the historical AST-size cost
55/// model) and an AC child of multiplicity k counts k times. Nodes whose op is declared
56/// `:unextractable` are never selected.
57pub 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    // Per-op cost and extractability, indexed by op id: the fixpoint below revisits every
68    // node on every pass, and a registry lookup per visit would pay for the same two fields
69    // repeatedly.
70    let meta = eg.ops().meta_table();
71
72    // Both tables are indexed by class id rather than hashed. Ids here are
73    // dense by construction — the scan below is over `eg.node_ids()` and
74    // every representative is one of those ids — so a hash map's key storage,
75    // hashing and probing all buy nothing over a direct index.
76    //
77    // `UNSET` doubles as the "no entry yet" marker for *both* tables: they are
78    // only ever written together, and a saturated cost of `UNSET` is never
79    // recorded (it cannot be `<` the incumbent, `UNSET` included), so
80    // `best_cost[i] != UNSET` holds exactly when class `i` has a best node.
81    // That is the same condition the previous map-based code expressed as
82    // `get(..).unwrap_or(usize::MAX)`.
83    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            // `:unextractable` is a filter on candidate nodes, not a cost: an excluded node
91            // never becomes a class's best, but the class stays extractable through its
92            // other nodes.
93            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
135/// Explain an empty result: name the class, and say whether it was excluded by
136/// `:unextractable` or is simply not grounded. Runs once, only on the failure path.
137fn 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        // `mult - 1` clones and then move the original in, rather than `mult`
196        // clones followed by dropping it. At the overwhelmingly common `mult == 1`
197        // that is one deep copy saved per child, and deep copies compound: the
198        // previous form made extraction of a depth-`d` chain O(d^2) node copies
199        // for a `d`-node result, because each level copied the whole subterm its
200        // recursive call had just built and then threw the original away.
201        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}