| @@ -0,0 +1,613 @@ |
| 1 | +//! Fusion rules for `std/list` pipelines of pure functions (issue #198, |
| 2 | +//! ADR 0043). |
| 3 | +//! |
| 4 | +//! A strict language fusing `map(xs, f)` into `filter` changes the order |
| 5 | +//! in which `f` and the predicate run — observable when they perform |
| 6 | +//! effects. So a rule fires only when every function involved is pure |
| 7 | +//! (`opt::pure`): no effects, and **no panics** — a crash is observable |
| 8 | +//! in Louise (a monitor sees `Crashed(message)`, ADR 0004), so a fused |
| 9 | +//! pipeline may not panic in a different element order, nor skip a panic |
| 10 | +//! the unfused one had (`length(map(xs, f))` with a panicking `f` is left |
| 11 | +//! alone). Divergence is imprecise, as in GHC: a pure stage that loops |
| 12 | +//! hangs fused or not. This is also why the pass runs after evidence |
| 13 | +//! specialisation: a dictionary call that is opaque before it is an |
| 14 | +//! `Int` addition after. A run that finishes normally computes the same |
| 15 | +//! value. |
| 16 | +//! |
| 17 | +//! The shapes matched (in A-normal form, so each stage is a `let` whose |
| 18 | +//! list argument another `let` bound earlier in the same chain): |
| 19 | +//! |
| 20 | +//! - `map(map(xs, f), g)` → `map(xs, f |> g)` |
| 21 | +//! - `fold(map(xs, f), z, g)` → `fold(xs, z, fn (a, x) { g(a, f(x)) })` |
| 22 | +//! - `fold(filter(xs, p), z, g)` → `fold(xs, z, fn (a, x) { if p(x) { g(a, x) } else { a } })` |
| 23 | +//! - `fold(range(lo, hi), z, g)` → a counting loop |
| 24 | +//! - `length(map(xs, f))` → `length(xs)` |
| 25 | +//! - `each(map(xs, f), g)` → `each(xs, f |> g)` |
| 26 | +//! |
| 27 | +//! There is no `filter ∘ map` rule: `filter(map(xs, f), p)` cannot become |
| 28 | +//! `filter(xs, p ∘ f)` — the map changes the *elements*, not just the |
| 29 | +//! predicate. (The epic's pipeline still fuses completely: `fold` of a |
| 30 | +//! `filter` of a `map` of a `range` fires `fold ∘ filter`, then `fold ∘ |
| 31 | +//! map`, then `fold ∘ range`.) Fusing a map through a filter is stream |
| 32 | +//! fusion's business (issue #199). |
| 33 | +//! |
| 34 | +//! The intermediate list must be used exactly once: the producer's `let` |
| 35 | +//! is removed (the stage performs nothing observable once its functions |
| 36 | +//! are pure, and its list is never built). Composition lambdas and the |
| 37 | +//! counting loop are new functions; the simplifier and the specialiser |
| 38 | +//! take it from there in the driver's next round. |
| 39 | + |
| 40 | +use std::collections::{HashMap, HashSet}; |
| 41 | + |
| 42 | +use super::pure; |
| 43 | +use super::simplify::{rebuild, split, uses}; |
| 44 | +use crate::ir::{Atom, Expr, FnDecl, FnId, Lit, Program, Span, Value, VarId}; |
| 45 | + |
| 46 | +/// A `std/list` function the rules know. |
| 47 | +#[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 48 | +enum Std { |
| 49 | + Map, |
| 50 | + Filter, |
| 51 | + Fold, |
| 52 | + Range, |
| 53 | + Length, |
| 54 | + Each, |
| 55 | +} |
| 56 | + |
| 57 | +/// The `std/list` function `f` is, if it is one — keyed on the module and |
| 58 | +/// the qualified name, the way lowering records them (and not a copy: |
| 59 | +/// those have no module, and by then the shape is gone). |
| 60 | +fn std_list(program: &Program, f: FnId) -> Option<Std> { |
| 61 | + let d = &program.fns[f as usize]; |
| 62 | + if d.module.as_deref() != Some("std/list") { |
| 63 | + return None; |
| 64 | + } |
| 65 | + Some(match d.name.as_str() { |
| 66 | + "std/list.map" => Std::Map, |
| 67 | + "std/list.filter" => Std::Filter, |
| 68 | + "std/list.fold" => Std::Fold, |
| 69 | + "std/list.range" => Std::Range, |
| 70 | + "std/list.length" => Std::Length, |
| 71 | + "std/list.each" => Std::Each, |
| 72 | + _ => return None, |
| 73 | + }) |
| 74 | +} |
| 75 | + |
| 76 | +/// A producer's binding: `v = map(xs, f)` — for a consumer rule to match |
| 77 | +/// on. Producers are `map`, `filter` and `range` (they build a list). |
| 78 | +#[derive(Clone)] |
| 79 | +struct Stage { |
| 80 | + produces: Std, |
| 81 | + args: Vec<Atom>, |
| 82 | +} |
| 83 | + |
| 84 | +/// A rewrite that fired, for `louise core -v`: the rule's name and where. |
| 85 | +pub struct Fired { |
| 86 | + pub rule: &'static str, |
| 87 | + pub span: Option<Span>, |
| 88 | +} |
| 89 | + |
| 90 | +/// A rule firing on a call: the extra `let`s to emit first (the composed |
| 91 | +/// closure), the value to replace the call with, the consumed producer's |
| 92 | +/// variable, and the rule's name. |
| 93 | +type Rewrite = ( |
| 94 | + Vec<(VarId, Value, Option<Span>)>, |
| 95 | + Value, |
| 96 | + VarId, |
| 97 | + &'static str, |
| 98 | +); |
| 99 | + |
| 100 | +/// Fuse pipelines in the functions `live` of `program`. Returns the new |
| 101 | +/// functions the rules made (so the driver can simplify them) and what |
| 102 | +/// fired. |
| 103 | +pub fn run_in(program: &mut Program, live: &[FnId]) -> (Vec<FnId>, Vec<Fired>) { |
| 104 | + let pure = pure::functions(program); |
| 105 | + let mut new_fns = Vec::new(); |
| 106 | + let mut fired = Vec::new(); |
| 107 | + for &id in live { |
| 108 | + let body = std::mem::replace(&mut program.fns[id as usize].body, Expr::Return(Atom::Unit)); |
| 109 | + let uses = uses(&body); |
| 110 | + let next_var = program.fns[id as usize].n_vars; |
| 111 | + let mut pass = Fuse { |
| 112 | + program: &mut *program, |
| 113 | + pure: &pure, |
| 114 | + pure_extra: HashSet::new(), |
| 115 | + uses, |
| 116 | + closures: HashMap::new(), |
| 117 | + stages: HashMap::new(), |
| 118 | + consumed: HashSet::new(), |
| 119 | + next_var, |
| 120 | + new_fns: Vec::new(), |
| 121 | + fired: Vec::new(), |
| 122 | + }; |
| 123 | + let body = pass.chain(body); |
| 124 | + let Fuse { |
| 125 | + next_var, |
| 126 | + new_fns: new, |
| 127 | + fired: f, |
| 128 | + .. |
| 129 | + } = pass; |
| 130 | + program.fns[id as usize].body = body; |
| 131 | + program.fns[id as usize].n_vars = next_var; |
| 132 | + new_fns.extend(new); |
| 133 | + fired.extend(f); |
| 134 | + } |
| 135 | + (new_fns, fired) |
| 136 | +} |
| 137 | + |
| 138 | +struct Fuse<'a> { |
| 139 | + program: &'a mut Program, |
| 140 | + pure: &'a HashSet<FnId>, |
| 141 | + /// Functions the rules composed of pure parts (pure themselves): |
| 142 | + /// registered so a cascaded rule fires in this walk already. |
| 143 | + pure_extra: HashSet<FnId>, |
| 144 | + uses: HashMap<VarId, u32>, |
| 145 | + /// The known closures in scope (`let f = closure …`). |
| 146 | + closures: HashMap<VarId, (FnId, Vec<Atom>)>, |
| 147 | + /// The producer stages in scope (`let v = map(xs, f)`). |
| 148 | + stages: HashMap<VarId, Stage>, |
| 149 | + /// Producer lets a rule consumed: dropped from the output (their |
| 150 | + /// single use was the consumer, and the stage is gone). |
| 151 | + consumed: HashSet<VarId>, |
| 152 | + /// Fresh variables for the closures the rules bind. |
| 153 | + next_var: u32, |
| 154 | + new_fns: Vec<FnId>, |
| 155 | + fired: Vec<Fired>, |
| 156 | +} |
| 157 | + |
| 158 | +impl Fuse<'_> { |
| 159 | + fn is_pure(&self, lam: &(FnId, Vec<Atom>)) -> bool { |
| 160 | + self.pure.contains(&lam.0) || self.pure_extra.contains(&lam.0) |
| 161 | + } |
| 162 | + |
| 163 | + /// A known, pure closure bound to this atom's variable. |
| 164 | + fn lam_of(&self, a: &Atom) -> Option<(FnId, Vec<Atom>)> { |
| 165 | + let Atom::Var(v) = a else { return None }; |
| 166 | + self.closures.get(v).cloned() |
| 167 | + } |
| 168 | + |
| 169 | + fn chain(&mut self, e: Expr) -> Expr { |
| 170 | + let (lets, end) = split(e); |
| 171 | + let mut out = Vec::with_capacity(lets.len()); |
| 172 | + for (v, value, span) in lets { |
| 173 | + // A fired rule can expose the next one (`fold(filter(…))` |
| 174 | + // becomes `fold` of a range, which is `fold ∘ range`): keep |
| 175 | + // firing while one matches. |
| 176 | + let mut value = value; |
| 177 | + let mut extra_all = Vec::new(); |
| 178 | + while let Some((extra, new_value, consumed, rule)) = self.rule(&value) { |
| 179 | + for (v2, value2, _) in &extra { |
| 180 | + self.record(*v2, value2); |
| 181 | + } |
| 182 | + extra_all.extend(extra); |
| 183 | + self.consumed.insert(consumed); |
| 184 | + self.fired.push(Fired { rule, span }); |
| 185 | + value = new_value; |
| 186 | + } |
| 187 | + self.record(v, &value); |
| 188 | + out.extend(extra_all); |
| 189 | + out.push((v, value, span)); |
| 190 | + } |
| 191 | + out.retain(|(v, _, _)| !self.consumed.contains(v)); |
| 192 | + let end = match end { |
| 193 | + Expr::Switch { on, cases, default } => Expr::Switch { |
| 194 | + on, |
| 195 | + cases: cases.into_iter().map(|(t, b)| (t, self.chain(b))).collect(), |
| 196 | + default: default.map(|d| Box::new(self.chain(*d))), |
| 197 | + }, |
| 198 | + Expr::SwitchLit { on, cases, default } => Expr::SwitchLit { |
| 199 | + on, |
| 200 | + cases: cases.into_iter().map(|(c, b)| (c, self.chain(b))).collect(), |
| 201 | + default: Box::new(self.chain(*default)), |
| 202 | + }, |
| 203 | + end => end, |
| 204 | + }; |
| 205 | + rebuild(out, end) |
| 206 | + } |
| 207 | + |
| 208 | + /// Record a closure or a producer stage bound by this `let` (a fired |
| 209 | + /// rule's new stage too, so rules cascade). |
| 210 | + fn record(&mut self, v: VarId, value: &Value) { |
| 211 | + match value { |
| 212 | + Value::Closure(g, caps) => { |
| 213 | + self.closures.insert(v, (*g, caps.clone())); |
| 214 | + } |
| 215 | + Value::CallFn(g, args) => { |
| 216 | + self.stages.remove(&v); |
| 217 | + if let Some(kind) = std_list(self.program, *g) |
| 218 | + && matches!(kind, Std::Map | Std::Filter | Std::Range) |
| 219 | + { |
| 220 | + self.stages.insert( |
| 221 | + v, |
| 222 | + Stage { |
| 223 | + produces: kind, |
| 224 | + args: args.clone(), |
| 225 | + }, |
| 226 | + ); |
| 227 | + } |
| 228 | + } |
| 229 | + _ => { |
| 230 | + self.closures.remove(&v); |
| 231 | + self.stages.remove(&v); |
| 232 | + } |
| 233 | + } |
| 234 | + } |
| 235 | + |
| 236 | + /// The rule firing on `value`, if any. |
| 237 | + fn rule(&mut self, value: &Value) -> Option<Rewrite> { |
| 238 | + let Value::CallFn(g, args) = value else { |
| 239 | + return None; |
| 240 | + }; |
| 241 | + let consumer = std_list(self.program, *g)?; |
| 242 | + if matches!(consumer, Std::Range) { |
| 243 | + return None; // a producer only |
| 244 | + } |
| 245 | + let Atom::Var(list_var) = args.first()? else { |
| 246 | + return None; |
| 247 | + }; |
| 248 | + let list_var = *list_var; |
| 249 | + if self.uses.get(&list_var) != Some(&1) { |
| 250 | + return None; // the intermediate must be used exactly once |
| 251 | + } |
| 252 | + let stage = self.stages.get(&list_var)?.clone(); |
| 253 | + match (consumer, stage.produces) { |
| 254 | + (Std::Map, Std::Map) | (Std::Each, Std::Map) => { |
| 255 | + let f = self.lam_of(&stage.args[1])?; |
| 256 | + let h = self.lam_of(&args[1])?; |
| 257 | + if !self.is_pure(&f) || !self.is_pure(&h) { |
| 258 | + return None; |
| 259 | + } |
| 260 | + let (bind, lam) = self.compose(&f, &h); |
| 261 | + let name = match consumer { |
| 262 | + Std::Map => "map ∘ map", |
| 263 | + _ => "each ∘ map", |
| 264 | + }; |
| 265 | + Some(( |
| 266 | + vec![bind], |
| 267 | + Value::CallFn(*g, vec![stage.args[0].clone(), lam]), |
| 268 | + list_var, |
| 269 | + name, |
| 270 | + )) |
| 271 | + } |
| 272 | + (Std::Fold, Std::Map) => { |
| 273 | + let f = self.lam_of(&stage.args[1])?; |
| 274 | + let step = self.lam_of(&args[2])?; |
| 275 | + if !self.is_pure(&f) || !self.is_pure(&step) { |
| 276 | + return None; |
| 277 | + } |
| 278 | + let (bind, lam) = self.fold_step_map(&f, &step); |
| 279 | + Some(( |
| 280 | + vec![bind], |
| 281 | + Value::CallFn(*g, vec![stage.args[0].clone(), args[1].clone(), lam]), |
| 282 | + list_var, |
| 283 | + "fold ∘ map", |
| 284 | + )) |
| 285 | + } |
| 286 | + (Std::Fold, Std::Filter) => { |
| 287 | + let p = self.lam_of(&stage.args[1])?; |
| 288 | + let step = self.lam_of(&args[2])?; |
| 289 | + if !self.is_pure(&p) || !self.is_pure(&step) { |
| 290 | + return None; |
| 291 | + } |
| 292 | + let (bind, lam) = self.fold_step_filter(&p, &step); |
| 293 | + Some(( |
| 294 | + vec![bind], |
| 295 | + Value::CallFn(*g, vec![stage.args[0].clone(), args[1].clone(), lam]), |
| 296 | + list_var, |
| 297 | + "fold ∘ filter", |
| 298 | + )) |
| 299 | + } |
| 300 | + (Std::Fold, Std::Range) => { |
| 301 | + let step = self.lam_of(&args[2])?; |
| 302 | + if !self.is_pure(&step) { |
| 303 | + return None; |
| 304 | + } |
| 305 | + let lo = stage.args[0].clone(); |
| 306 | + let hi = stage.args[1].clone(); |
| 307 | + let loop_fn = self.fold_range_loop(&step); |
| 308 | + let mut call_args = step.1.clone(); |
| 309 | + call_args.extend([lo, hi, args[1].clone()]); |
| 310 | + Some(( |
| 311 | + vec![], |
| 312 | + Value::CallFn(loop_fn, call_args), |
| 313 | + list_var, |
| 314 | + "fold ∘ range", |
| 315 | + )) |
| 316 | + } |
| 317 | + (Std::Length, Std::Map) => { |
| 318 | + let f = self.lam_of(&stage.args[1])?; |
| 319 | + if !self.is_pure(&f) { |
| 320 | + return None; |
| 321 | + } |
| 322 | + Some(( |
| 323 | + vec![], |
| 324 | + Value::CallFn(*g, vec![stage.args[0].clone()]), |
| 325 | + list_var, |
| 326 | + "length ∘ map", |
| 327 | + )) |
| 328 | + } |
| 329 | + _ => None, |
| 330 | + } |
| 331 | + } |
| 332 | + |
| 333 | + /// A fresh variable for the enclosing function. |
| 334 | + fn fresh(&mut self) -> VarId { |
| 335 | + let v = self.next_var; |
| 336 | + self.next_var += 1; |
| 337 | + v |
| 338 | + } |
| 339 | + |
| 340 | + /// A new function `f |> g`: `fn (caps_f…, caps_g…, x) { g(f(x)) }`. |
| 341 | + /// Returns the `let` binding its closure, and the closure's variable. |
| 342 | + fn compose( |
| 343 | + &mut self, |
| 344 | + f: &(FnId, Vec<Atom>), |
| 345 | + g: &(FnId, Vec<Atom>), |
| 346 | + ) -> ((VarId, Value, Option<Span>), Atom) { |
| 347 | + let mut next = 0u32; |
| 348 | + let mut fresh = || { |
| 349 | + let v = next; |
| 350 | + next += 1; |
| 351 | + v |
| 352 | + }; |
| 353 | + let cf: Vec<VarId> = f.1.iter().map(|_| fresh()).collect(); |
| 354 | + let cg: Vec<VarId> = g.1.iter().map(|_| fresh()).collect(); |
| 355 | + let x = fresh(); |
| 356 | + let (t, r) = (fresh(), fresh()); |
| 357 | + let body = rebuild( |
| 358 | + vec![ |
| 359 | + ( |
| 360 | + t, |
| 361 | + Value::CallFn( |
| 362 | + f.0, |
| 363 | + cf.iter() |
| 364 | + .map(|c| Atom::Var(*c)) |
| 365 | + .chain([Atom::Var(x)]) |
| 366 | + .collect(), |
| 367 | + ), |
| 368 | + None, |
| 369 | + ), |
| 370 | + ( |
| 371 | + r, |
| 372 | + Value::CallFn( |
| 373 | + g.0, |
| 374 | + cg.iter() |
| 375 | + .map(|c| Atom::Var(*c)) |
| 376 | + .chain([Atom::Var(t)]) |
| 377 | + .collect(), |
| 378 | + ), |
| 379 | + None, |
| 380 | + ), |
| 381 | + ], |
| 382 | + Expr::Return(Atom::Var(r)), |
| 383 | + ); |
| 384 | + let mut params: Vec<VarId> = cf.iter().chain(&cg).copied().collect(); |
| 385 | + params.push(x); |
| 386 | + let name = format!( |
| 387 | + "fusion {} |> {}", |
| 388 | + self.program.fns[f.0 as usize].name, self.program.fns[g.0 as usize].name |
| 389 | + ); |
| 390 | + let lam = self.new_fn(name, params, body, next); |
| 391 | + let v = self.fresh(); |
| 392 | + let mut caps = f.1.clone(); |
| 393 | + caps.extend(g.1.iter().cloned()); |
| 394 | + ((v, Value::Closure(lam, caps), None), Atom::Var(v)) |
| 395 | + } |
| 396 | + |
| 397 | + /// `fn (caps_f…, caps_g…, acc, x) { g(acc, f(x)) }` for fold ∘ map. |
| 398 | + /// Returns the `let` binding its closure, and the closure's variable. |
| 399 | + fn fold_step_map( |
| 400 | + &mut self, |
| 401 | + f: &(FnId, Vec<Atom>), |
| 402 | + g: &(FnId, Vec<Atom>), |
| 403 | + ) -> ((VarId, Value, Option<Span>), Atom) { |
| 404 | + let mut next = 0u32; |
| 405 | + let mut fresh = || { |
| 406 | + let v = next; |
| 407 | + next += 1; |
| 408 | + v |
| 409 | + }; |
| 410 | + let cf: Vec<VarId> = f.1.iter().map(|_| fresh()).collect(); |
| 411 | + let cg: Vec<VarId> = g.1.iter().map(|_| fresh()).collect(); |
| 412 | + let (acc, x, t, r) = (fresh(), fresh(), fresh(), fresh()); |
| 413 | + let body = rebuild( |
| 414 | + vec![ |
| 415 | + ( |
| 416 | + t, |
| 417 | + Value::CallFn( |
| 418 | + f.0, |
| 419 | + cf.iter() |
| 420 | + .map(|c| Atom::Var(*c)) |
| 421 | + .chain([Atom::Var(x)]) |
| 422 | + .collect(), |
| 423 | + ), |
| 424 | + None, |
| 425 | + ), |
| 426 | + ( |
| 427 | + r, |
| 428 | + Value::CallFn( |
| 429 | + g.0, |
| 430 | + cg.iter() |
| 431 | + .map(|c| Atom::Var(*c)) |
| 432 | + .chain([Atom::Var(acc), Atom::Var(t)]) |
| 433 | + .collect(), |
| 434 | + ), |
| 435 | + None, |
| 436 | + ), |
| 437 | + ], |
| 438 | + Expr::Return(Atom::Var(r)), |
| 439 | + ); |
| 440 | + let mut params: Vec<VarId> = cf.iter().chain(&cg).copied().collect(); |
| 441 | + params.extend([acc, x]); |
| 442 | + let name = format!( |
| 443 | + "fusion fold {} |> {}", |
| 444 | + self.program.fns[f.0 as usize].name, self.program.fns[g.0 as usize].name |
| 445 | + ); |
| 446 | + let lam = self.new_fn(name, params, body, next); |
| 447 | + let v = self.fresh(); |
| 448 | + let mut caps = f.1.clone(); |
| 449 | + caps.extend(g.1.iter().cloned()); |
| 450 | + ((v, Value::Closure(lam, caps), None), Atom::Var(v)) |
| 451 | + } |
| 452 | + |
| 453 | + /// `fn (caps_p…, caps_g…, acc, x) { if p(x) { g(acc, x) } else { acc } }` |
| 454 | + /// for fold ∘ filter. (A switch on the predicate's `Bool`; `True` is |
| 455 | + /// tag 1, lowering's `bool_value` convention.) |
| 456 | + fn fold_step_filter( |
| 457 | + &mut self, |
| 458 | + p: &(FnId, Vec<Atom>), |
| 459 | + g: &(FnId, Vec<Atom>), |
| 460 | + ) -> ((VarId, Value, Option<Span>), Atom) { |
| 461 | + let mut next = 0u32; |
| 462 | + let mut fresh = || { |
| 463 | + let v = next; |
| 464 | + next += 1; |
| 465 | + v |
| 466 | + }; |
| 467 | + let cp: Vec<VarId> = p.1.iter().map(|_| fresh()).collect(); |
| 468 | + let cg: Vec<VarId> = g.1.iter().map(|_| fresh()).collect(); |
| 469 | + let (acc, x, t, r) = (fresh(), fresh(), fresh(), fresh()); |
| 470 | + let body = rebuild( |
| 471 | + vec![( |
| 472 | + t, |
| 473 | + Value::CallFn( |
| 474 | + p.0, |
| 475 | + cp.iter() |
| 476 | + .map(|c| Atom::Var(*c)) |
| 477 | + .chain([Atom::Var(x)]) |
| 478 | + .collect(), |
| 479 | + ), |
| 480 | + None, |
| 481 | + )], |
| 482 | + Expr::Switch { |
| 483 | + on: Atom::Var(t), |
| 484 | + cases: vec![( |
| 485 | + 1, |
| 486 | + rebuild( |
| 487 | + vec![( |
| 488 | + r, |
| 489 | + Value::CallFn( |
| 490 | + g.0, |
| 491 | + cg.iter() |
| 492 | + .map(|c| Atom::Var(*c)) |
| 493 | + .chain([Atom::Var(acc), Atom::Var(x)]) |
| 494 | + .collect(), |
| 495 | + ), |
| 496 | + None, |
| 497 | + )], |
| 498 | + Expr::Return(Atom::Var(r)), |
| 499 | + ), |
| 500 | + )], |
| 501 | + default: Some(Box::new(Expr::Return(Atom::Var(acc)))), |
| 502 | + }, |
| 503 | + ); |
| 504 | + let mut params: Vec<VarId> = cp.iter().chain(&cg).copied().collect(); |
| 505 | + params.extend([acc, x]); |
| 506 | + let name = format!( |
| 507 | + "fusion fold if {} then {}", |
| 508 | + self.program.fns[p.0 as usize].name, self.program.fns[g.0 as usize].name |
| 509 | + ); |
| 510 | + let lam = self.new_fn(name, params, body, next); |
| 511 | + let v = self.fresh(); |
| 512 | + let mut caps = p.1.clone(); |
| 513 | + caps.extend(g.1.iter().cloned()); |
| 514 | + ((v, Value::Closure(lam, caps), None), Atom::Var(v)) |
| 515 | + } |
| 516 | + |
| 517 | + /// The counting loop for fold ∘ range: `fn (caps_g…, i, hi, acc)`, a |
| 518 | + /// tail call per element. The switch is on the `Order` from |
| 519 | + /// `tl_int_compare`: `Gt` is tag 2, as lowering numbers `type Order |
| 520 | + /// { Lt Eq Gt }`. |
| 521 | + fn fold_range_loop(&mut self, g: &(FnId, Vec<Atom>)) -> FnId { |
| 522 | + let mut next = 0u32; |
| 523 | + let mut fresh = || { |
| 524 | + let v = next; |
| 525 | + next += 1; |
| 526 | + v |
| 527 | + }; |
| 528 | + let cg: Vec<VarId> = g.1.iter().map(|_| fresh()).collect(); |
| 529 | + let (i, hi, acc) = (fresh(), fresh(), fresh()); |
| 530 | + let (ord, acc1, i1, r) = (fresh(), fresh(), fresh(), fresh()); |
| 531 | + let name = format!( |
| 532 | + "fusion fold range |> {}", |
| 533 | + self.program.fns[g.0 as usize].name |
| 534 | + ); |
| 535 | + // A placeholder body first: the loop's tail call names itself. |
| 536 | + let id = self.new_fn(name, Vec::new(), Expr::Return(Atom::Unit), 0); |
| 537 | + let step = rebuild( |
| 538 | + vec![ |
| 539 | + ( |
| 540 | + acc1, |
| 541 | + Value::CallFn( |
| 542 | + g.0, |
| 543 | + cg.iter() |
| 544 | + .map(|c| Atom::Var(*c)) |
| 545 | + .chain([Atom::Var(acc), Atom::Var(i)]) |
| 546 | + .collect(), |
| 547 | + ), |
| 548 | + None, |
| 549 | + ), |
| 550 | + ( |
| 551 | + i1, |
| 552 | + Value::CallExtern( |
| 553 | + "tl_int_add".into(), |
| 554 | + vec![Atom::Var(i), Atom::Lit(Lit::Int(1))], |
| 555 | + ), |
| 556 | + None, |
| 557 | + ), |
| 558 | + ( |
| 559 | + r, |
| 560 | + Value::CallFn( |
| 561 | + id, |
| 562 | + cg.iter() |
| 563 | + .map(|c| Atom::Var(*c)) |
| 564 | + .chain([Atom::Var(i1), Atom::Var(hi), Atom::Var(acc1)]) |
| 565 | + .collect(), |
| 566 | + ), |
| 567 | + None, |
| 568 | + ), |
| 569 | + ], |
| 570 | + Expr::Return(Atom::Var(r)), |
| 571 | + ); |
| 572 | + let body = rebuild( |
| 573 | + vec![( |
| 574 | + ord, |
| 575 | + Value::CallExtern("tl_int_compare".into(), vec![Atom::Var(i), Atom::Var(hi)]), |
| 576 | + None, |
| 577 | + )], |
| 578 | + Expr::Switch { |
| 579 | + on: Atom::Var(ord), |
| 580 | + cases: vec![(2, Expr::Return(Atom::Var(acc)))], |
| 581 | + default: Some(Box::new(step)), |
| 582 | + }, |
| 583 | + ); |
| 584 | + let mut params: Vec<VarId> = cg.clone(); |
| 585 | + params.extend([i, hi, acc]); |
| 586 | + let decl = &mut self.program.fns[id as usize]; |
| 587 | + decl.params = params; |
| 588 | + decl.body = body; |
| 589 | + decl.n_vars = next; |
| 590 | + id |
| 591 | + } |
| 592 | + |
| 593 | + /// A new generated function (no module, no span), registered as pure |
| 594 | + /// (its body calls pure functions) so a cascaded rule fires in this |
| 595 | + /// walk already. |
| 596 | + fn new_fn(&mut self, name: String, params: Vec<VarId>, body: Expr, n_vars: u32) -> FnId { |
| 597 | + self.program.fns.push(FnDecl { |
| 598 | + name, |
| 599 | + params, |
| 600 | + body, |
| 601 | + n_vars, |
| 602 | + borrowed: Default::default(), |
| 603 | + span: None, |
| 604 | + module: None, |
| 605 | + shapes: Default::default(), |
| 606 | + fip: false, |
| 607 | + }); |
| 608 | + let id = (self.program.fns.len() - 1) as FnId; |
| 609 | + self.pure_extra.insert(id); |
| 610 | + self.new_fns.push(id); |
| 611 | + id |
| 612 | + } |
| 613 | +} |