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