| 1 |
//! Lazy expansion of the egraph |
| 2 |
//! |
| 3 |
//! This modules provides the helpers and logic to lazyly iterate through the |
| 4 |
//! egraph, providing potentially infinite random expressions from an initial egraph |
| 5 |
|
| 6 |
use super::lang::Lang; |
| 7 |
use crate::mutators::peephole::{ |
| 8 |
EG, |
| 9 |
eggsy::{RandomExtractor, encoder::rebuild::build_expr_inner}, |
| 10 |
}; |
| 11 |
use egg::{AstSize, Id, Language, RecExpr}; |
| 12 |
use rand::{Rng, SeedableRng, prelude::SmallRng}; |
| 13 |
use std::{cell::RefCell, rc::Rc}; |
| 14 |
|
| 15 |
/// Returns a lazy iterator over all possible expressions that can be |
| 16 |
/// constructed starting in eclass *Id*. If the eclass *Id* is the root of the |
| 17 |
/// expression to mutate, this function will return a random but semantically |
| 18 |
/// equivalent (based on the rewriting rules) expression. |
| 19 |
/// |
| 20 |
/// Starting by the *Id* eclass in the egraph it selects a random node. |
| 21 |
/// Depending on the node, the cartesian product of the operands iterators |
| 22 |
/// (lazy_expand calls) is built to provide a random expression. |
| 23 |
/// |
| 24 |
/// Let's assume the language formed only by the `add` and `100` nodes, with the |
| 25 |
/// rewriting rule `?x => add ?x 0`. And let's assume also that we want to |
| 26 |
/// return a random expression out of the parsing of the former integer |
| 27 |
/// expression `100`. When the egraph is constructed, the expression `100` is in |
| 28 |
/// the same eclass than `add 100 0`. But, since we defined the rewriting rule |
| 29 |
/// for any node, recursivelly, all nodes are in the same equivalence class. |
| 30 |
/// |
| 31 |
/// If we call `lazy_expand` to randomly construct an expression out of the |
| 32 |
/// egraph starting at equivalence class `i`, a random node is first selected |
| 33 |
/// from the selected starting eclass. |
| 34 |
/// |
| 35 |
/// For this case, let's assume the `add i 0` node is selected. The iterator |
| 36 |
/// will then build the lazy iterator upon this, something like |
| 37 |
/// `add(lazy_expand(i), lazy_expand(0)) => add(add(lazy_expand(i), 0), 0)`, and |
| 38 |
/// so on until the max depth is reached and the smallest expression that can be |
| 39 |
/// constructed for i is filled up. Every time the `next` method is called a new |
| 40 |
/// expression is returned until no more are expressions are available due to |
| 41 |
/// the *depth* argument. |
| 42 |
/// |
| 43 |
/// Notice that if new nodes are added to the Lang enum, the corresponding random |
| 44 |
/// construction of equivalent expressions needs to be added to this method. |
| 45 |
pub fn lazy_expand<'a>( |
| 46 |
id: Id, |
| 47 |
egraph: Rc<EG>, |
| 48 |
depth: u32, |
| 49 |
rnd: Rc<RefCell<SmallRng>>, |
| 50 |
recexpr: Rc<RefCell<RecExpr<Lang>>>, |
| 51 |
) -> Box<dyn Iterator<Item = Id> + 'a> { |
| 52 |
if depth == 0 { |
| 53 |
let cf = AstSize; |
| 54 |
let extractor = RandomExtractor::new(&egraph, cf); |
| 55 |
let shorter = extractor |
| 56 |
.extract_smallest(id, &recexpr, |a, b, c| build_expr_inner(a, b, c)) |
| 57 |
.unwrap(); |
| 58 |
|
| 59 |
return Box::new(vec![shorter].into_iter()); |
| 60 |
} |
| 61 |
|
| 62 |
let nodes = egraph[id].nodes.clone(); |
| 63 |
let count = nodes.len(); |
| 64 |
// For each eclass, at least one node exists |
| 65 |
let split_at = rnd.borrow_mut().random_range(0..count); |
| 66 |
let indices = (split_at..count).into_iter().chain(0..split_at); |
| 67 |
|
| 68 |
let t = indices |
| 69 |
.map(move |i| nodes[i].clone()) |
| 70 |
.map(move |mut l| { |
| 71 |
let depth = match l { |
| 72 |
// This is a patch to avoid expansion of non-statically known |
| 73 |
// values. |
| 74 |
Lang::UnfoldI32(_) | Lang::UnfoldI64(_) => 0, |
| 75 |
_ => depth - 1, |
| 76 |
}; |
| 77 |
let children = l.children_mut(); |
| 78 |
let rec = recexpr.clone(); |
| 79 |
let iter: Box<dyn Iterator<Item = Id>> = match children.len() { |
| 80 |
// Without any child nodes we can simply add this `Lang` value |
| 81 |
// and move on. |
| 82 |
0 => Box::new(std::iter::once(recexpr.borrow_mut().add(l))), |
| 83 |
|
| 84 |
// With one child node we try to update the current node with |
| 85 |
// all possible expansions of the child node. |
| 86 |
1 => Box::new( |
| 87 |
lazy_expand( |
| 88 |
children[0], |
| 89 |
egraph.clone(), |
| 90 |
depth, |
| 91 |
rnd.clone(), |
| 92 |
recexpr.clone(), |
| 93 |
) |
| 94 |
.map(move |id| { |
| 95 |
let mut l = l.clone(); |
| 96 |
l.children_mut()[0] = id; |
| 97 |
rec.clone().borrow_mut().add(l) |
| 98 |
}), |
| 99 |
), |
| 100 |
|
| 101 |
// With two child nodes a cartesian product of expansions is |
| 102 |
// attempted. |
| 103 |
2 => { |
| 104 |
let rec = recexpr.clone(); |
| 105 |
let egraph = egraph.clone(); |
| 106 |
let rnd = rnd.clone(); |
| 107 |
let recexpr = recexpr.clone(); |
| 108 |
let left = children[0]; |
| 109 |
let right = children[1]; |
| 110 |
Box::new( |
| 111 |
lazy_expand(left, egraph.clone(), depth, rnd.clone(), recexpr.clone()) |
| 112 |
.flat_map(move |e| { |
| 113 |
std::iter::repeat(e).zip(lazy_expand( |
| 114 |
right, |
| 115 |
egraph.clone(), |
| 116 |
depth, |
| 117 |
rnd.clone(), |
| 118 |
recexpr.clone(), |
| 119 |
)) |
| 120 |
}) |
| 121 |
.map(move |(left, right)| { |
| 122 |
let mut l = l.clone(); |
| 123 |
l.children_mut()[0] = left; |
| 124 |
l.children_mut()[1] = right; |
| 125 |
rec.borrow_mut().add(l) |
| 126 |
}), |
| 127 |
) |
| 128 |
} |
| 129 |
|
| 130 |
// FIXME I could not find a way to have a cartesian product of |
| 131 |
// dynamic size collection of Iterators This can also be solved |
| 132 |
// if we turn Call and Container enodes to be binary trees where |
| 133 |
// the left operand is a real Id and the second is a container, |
| 134 |
// and so on until all arguments are expressed in the binary |
| 135 |
// tree For example |
| 136 |
// (call.$1 a b c d) can be turned into (call.$1 a (container b (container c (container d))))) |
| 137 |
_ => { |
| 138 |
for child in children { |
| 139 |
*child = lazy_expand( |
| 140 |
*child, |
| 141 |
egraph.clone(), |
| 142 |
depth, |
| 143 |
rnd.clone(), |
| 144 |
recexpr.clone(), |
| 145 |
) |
| 146 |
.next() |
| 147 |
.unwrap(); |
| 148 |
} |
| 149 |
Box::new(std::iter::once(recexpr.borrow_mut().add(l))) |
| 150 |
} |
| 151 |
}; |
| 152 |
iter |
| 153 |
}) |
| 154 |
.flatten(); |
| 155 |
Box::new(t) |
| 156 |
} |
| 157 |
|
| 158 |
/// Lazy expand helper |
| 159 |
pub fn lazy_expand_aux<'a>( |
| 160 |
id: Id, |
| 161 |
egraph: EG, |
| 162 |
depth: u32, |
| 163 |
seed: u64, |
| 164 |
) -> Box<dyn Iterator<Item = RecExpr<Lang>> + 'a> { |
| 165 |
let expr_buffer = RecExpr::default(); |
| 166 |
let recexpr = Rc::new(RefCell::new(expr_buffer)); |
| 167 |
// FIXME, |
| 168 |
let r = SmallRng::seed_from_u64(seed); |
| 169 |
let refrnd = Rc::new(RefCell::new(r)); |
| 170 |
let recexprcp = recexpr.clone(); |
| 171 |
let recexprcp2 = recexpr; |
| 172 |
let eg = Rc::new(egraph); |
| 173 |
let it = lazy_expand(id, eg, depth, refrnd, recexprcp).map(move |_id| { |
| 174 |
let expr = RecExpr::from(recexprcp2.borrow().as_ref().to_vec()); |
| 175 |
expr |
| 176 |
}); |
| 177 |
|
| 178 |
Box::new(it) |
| 179 |
} |
| 180 |
|
| 181 |
#[cfg(test)] |
| 182 |
mod tests { |
| 183 |
use crate::ModuleInfo; |
| 184 |
use crate::mutators::peephole::eggsy::{ |
| 185 |
analysis::PeepholeMutationAnalysis, expr_enumerator::lazy_expand, lang::Lang, |
| 186 |
}; |
| 187 |
use egg::{AstSize, RecExpr, Rewrite, Runner, rewrite}; |
| 188 |
use rand::{SeedableRng, prelude::SmallRng}; |
| 189 |
use std::{cell::RefCell, collections::HashMap, rc::Rc}; |
| 190 |
|
| 191 |
#[derive(Clone, Copy, Debug)] |
| 192 |
struct Mimi { |
| 193 |
id: usize, |
| 194 |
} |
| 195 |
impl Mimi { |
| 196 |
pub fn used(&self) { |
| 197 |
println!("mimi {}", self.id) |
| 198 |
} |
| 199 |
} |
| 200 |
#[test] |
| 201 |
fn test_lazy() { |
| 202 |
let o1 = vec![Mimi { id: 1 }, Mimi { id: 2 }].into_iter(); |
| 203 |
let o2 = vec![Mimi { id: 2 }, Mimi { id: 3 }].into_iter(); |
| 204 |
|
| 205 |
let mut l = o1 |
| 206 |
.flat_map(|e| std::iter::repeat(e).zip(o2.clone())) |
| 207 |
.map(|(l, r)| { |
| 208 |
l.used(); |
| 209 |
r.used(); |
| 210 |
(l, r) |
| 211 |
}); |
| 212 |
|
| 213 |
println!("1 {:?}", l.next()); |
| 214 |
println!("2 {:?}", l.next()); |
| 215 |
println!("3 {:?}", l.next()); |
| 216 |
println!("4 {:?}", l.next()); |
| 217 |
} |
| 218 |
|
| 219 |
#[test] |
| 220 |
fn test_rec_iterator() { |
| 221 |
let rules: &[Rewrite<Lang, PeepholeMutationAnalysis>] = &[ |
| 222 |
rewrite!("rule"; "?x" => "(i32.add ?x i32.const.0)"), |
| 223 |
rewrite!("rule2"; "(i32.add ?y ?x)" => "(i32.add ?x ?y)"), |
| 224 |
rewrite!("rule2"; "i32.const.0" => "(i32.sub i32.const.50 i32.const.500)"), |
| 225 |
//rewrite!("rule3"; "?x" => "(i32.mul ?x 1_i32)"), |
| 226 |
//rewrite!("rule4"; "0_i32" => "(i32.unfold 0_i32)"), |
| 227 |
//rewrite!("rule5"; "1_i32" => "(i32.unfold 1_i32)"), |
| 228 |
]; |
| 229 |
|
| 230 |
let expr = "(i32.add i32.const.100 i32.const.200)"; |
| 231 |
|
| 232 |
let empty_wasm = wat::parse_str("(module)").unwrap(); |
| 233 |
let info = ModuleInfo::new(&empty_wasm).unwrap(); |
| 234 |
let analysis = PeepholeMutationAnalysis::new(&info, vec![]); |
| 235 |
let runner = Runner::<Lang, PeepholeMutationAnalysis, ()>::new(analysis) |
| 236 |
.with_iter_limit(1) // only one iterations, do not wait for eq saturation, increasing only by one it affects the execution time of the mutator by a lot |
| 237 |
.with_expr(&expr.parse().unwrap()) |
| 238 |
.run(rules); |
| 239 |
let mut egraph = runner.egraph; |
| 240 |
let _cf = AstSize; |
| 241 |
|
| 242 |
let _enumeration_start = std::time::Instant::now(); |
| 243 |
let root = egraph.add_expr(&expr.parse().unwrap()); |
| 244 |
let rnd = SmallRng::seed_from_u64(0); |
| 245 |
let recexpr = RecExpr::default(); |
| 246 |
let rnd = Rc::new(RefCell::new(rnd)); |
| 247 |
let recexpr = Rc::new(RefCell::new(recexpr)); |
| 248 |
let r = recexpr.clone(); |
| 249 |
let mut it = lazy_expand(root, Rc::new(egraph), 10, rnd, recexpr); |
| 250 |
let mut h: HashMap<String, usize> = HashMap::new(); |
| 251 |
for _ in 0..100000 { |
| 252 |
if let Some(_) = it.next() { |
| 253 |
let t = format!("{}", r.borrow()); |
| 254 |
|
| 255 |
assert!(!h.contains_key(&t)); |
| 256 |
|
| 257 |
h.insert(t, 1); |
| 258 |
} else { |
| 259 |
break; |
| 260 |
} |
| 261 |
} |
| 262 |
} |
| 263 |
} |