| @@ -0,0 +1,1738 @@ |
| 1 | +//! Precompiled renderers for HTML templates (ADR 0054; the SSR plan's |
| 2 | +//! Phase 3b). |
| 3 | +//! |
| 4 | +//! A render of a statically known tree — `html.render(t)`, or, once |
| 5 | +//! the simplifier has inlined `render`, `build_string(render_into(t, |
| 6 | +//! bytes.builder()))` — becomes the sequence of builder appends |
| 7 | +//! `render_into` would run, compiled against the tree's shape: static |
| 8 | +//! parts (a whole static subtree included) folded to one string |
| 9 | +//! constant at compile time, text holes escaped in place |
| 10 | +//! (`tl_bytes_append_escaped`), `Raw` holes appended as is, opaque |
| 11 | +//! element and list holes rendered by the ordinary |
| 12 | +//! `render_into`/`render_all` into the same builder. The `Element` |
| 13 | +//! tree is never built. |
| 14 | +//! |
| 15 | +//! What fires: |
| 16 | +//! |
| 17 | +//! - **A locally visible literal**: the rendered variable is bound in |
| 18 | +//! the same function to a tree of the `std/html` and `List` |
| 19 | +//! constructions (`Node`/`Text`/`Raw`/`Fragment`/`Attribute`/`Flag`, |
| 20 | +//! `Cons`/`Nil`) with literal or hole fields, every construction |
| 21 | +//! used exactly once (the tree is unobservable). |
| 22 | +//! - **A component call**: the rendered value — or any element hole — |
| 23 | +//! is a direct call of a function whose body returns such a tree (a |
| 24 | +//! component). The body is translated with the call's arguments, so |
| 25 | +//! components compose without being inlined away; past the depth or |
| 26 | +//! expansion budget, or for a body that is not a literal tree, the |
| 27 | +//! position falls back to `render_into` of the call, as today. |
| 28 | +//! - **`render_all(list.map(xs, f), b)`** — the rows of a table — |
| 29 | +//! becomes `list.fold(xs, b, f$render)` with a generated step |
| 30 | +//! function: the per-row tree is never built either. |
| 31 | +//! |
| 32 | +//! Why the order of effects is preserved: the pass *deletes* only |
| 33 | +//! constructions, which allocate and nothing else. A component call's |
| 34 | +//! non-tree bindings *move* from the call's position to the render's, |
| 35 | +//! and that only when nothing can tell — the commute rule: either |
| 36 | +//! everything the move relocates is boring (pure and non-panicking: |
| 37 | +//! fusion's gate, ADR 0043, `opt::pure`), or every binding between the |
| 38 | +//! two positions is. The `map` fusion interleaves a row function's |
| 39 | +//! applications with the renders of earlier rows; the renders are |
| 40 | +//! pure (the builder externs are the runtime's `owned`, effect-free |
| 41 | +//! ones, unobservable until `build_string`), so the applications' own |
| 42 | +//! effects stay in order. Byte-identity is by construction: the |
| 43 | +//! compile-time folder calls the same `louise_rt_prims::html_escape` |
| 44 | +//! the runtime escaper uses, the void-element list mirrors |
| 45 | +//! `std/html.is_void` (pinned by `tests/run/html_hoist.lse`), and |
| 46 | +//! everything dynamic goes through the same runtime entry points as |
| 47 | +//! `render_into`. |
| 48 | +//! |
| 49 | +//! Eligibility is structural: a tree shared, stored, matched on or |
| 50 | +//! returned is built as today (every construction's single use is |
| 51 | +//! checked); a body with an early `exit` (ADR 0037) is never |
| 52 | +//! translated (an inlined `exit` would leave the wrong function); a |
| 53 | +//! copied binding that refers to a consumed construction (the tree |
| 54 | +//! observed) aborts the translation; and `LOUISE_NO_PRECOMPILE` turns |
| 55 | +//! the pass off. |
| 56 | + |
| 57 | +use std::collections::{HashMap, HashSet}; |
| 58 | +use std::rc::Rc; |
| 59 | + |
| 60 | +use super::pure; |
| 61 | +use super::simplify::{rebuild, split, uses, visit_exprs}; |
| 62 | +use crate::ir::{Atom, Expr, FnDecl, FnId, Lit, Program, Span, Value, VarId}; |
| 63 | + |
| 64 | +/// `LOUISE_NO_PRECOMPILE` builds the tree and renders it, as before. |
| 65 | +const DISABLE_VAR: &str = "LOUISE_NO_PRECOMPILE"; |
| 66 | + |
| 67 | +/// The most component expansions at one site; past it, positions fall |
| 68 | +/// back to `render_into` (a huge page still precompiles its skeleton). |
| 69 | +const MAX_EXPANSIONS: u32 = 64; |
| 70 | + |
| 71 | +/// The deepest component nesting translated in place; deeper calls |
| 72 | +/// fall back to `render_into` of the call. |
| 73 | +const MAX_DEPTH: u32 = 32; |
| 74 | + |
| 75 | +/// The `std` functions the pass compiles against, resolved once by |
| 76 | +/// module and qualified name (the way lowering records them — a |
| 77 | +/// specialiser's copy has no module and is not matched). |
| 78 | +struct Std { |
| 79 | + /// `std/html.render`. |
| 80 | + render: FnId, |
| 81 | + /// `std/html.render_into` (the fallback for an opaque element). |
| 82 | + render_into: FnId, |
| 83 | + /// `std/html.render_all` (the fallback for an opaque list). |
| 84 | + render_all: FnId, |
| 85 | + /// `std/list.map`. |
| 86 | + map: FnId, |
| 87 | + /// `std/list.fold`. |
| 88 | + fold: FnId, |
| 89 | +} |
| 90 | + |
| 91 | +impl Std { |
| 92 | + fn resolve(program: &Program) -> Option<Std> { |
| 93 | + let find = |module: &str, name: &str| { |
| 94 | + program |
| 95 | + .fns |
| 96 | + .iter() |
| 97 | + .position(|d| d.module.as_deref() == Some(module) && d.name == name) |
| 98 | + .map(|i| i as FnId) |
| 99 | + }; |
| 100 | + Some(Std { |
| 101 | + render: find("std/html", "std/html.render")?, |
| 102 | + render_into: find("std/html", "std/html.render_into")?, |
| 103 | + render_all: find("std/html", "std/html.render_all")?, |
| 104 | + map: find("std/list", "std/list.map")?, |
| 105 | + fold: find("std/list", "std/list.fold")?, |
| 106 | + }) |
| 107 | + } |
| 108 | +} |
| 109 | + |
| 110 | +/// A function body, indexed for the tree walk: every `let`'s value by |
| 111 | +/// its variable, and the use count of every variable. |
| 112 | +struct Body { |
| 113 | + bindings: HashMap<VarId, Value>, |
| 114 | + uses: HashMap<VarId, u32>, |
| 115 | + /// An early `exit` (ADR 0037) anywhere: such a body is never |
| 116 | + /// translated (an inlined `exit` would leave the wrong function). |
| 117 | + has_exit: bool, |
| 118 | +} |
| 119 | + |
| 120 | +impl Body { |
| 121 | + fn of(e: &Expr) -> Body { |
| 122 | + let mut bindings = HashMap::new(); |
| 123 | + let mut has_exit = false; |
| 124 | + visit_exprs(e, &mut |e| match e { |
| 125 | + Expr::Let(v, value, _, _) => { |
| 126 | + bindings.insert(*v, (**value).clone()); |
| 127 | + } |
| 128 | + Expr::Exit(_) => has_exit = true, |
| 129 | + _ => {} |
| 130 | + }); |
| 131 | + Body { |
| 132 | + bindings, |
| 133 | + uses: uses(e), |
| 134 | + has_exit, |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + /// The bottom frame of a generated function's walk: its parameters |
| 139 | + /// live in it (its own variables predate it). |
| 140 | + fn empty() -> Body { |
| 141 | + Body { |
| 142 | + bindings: HashMap::new(), |
| 143 | + uses: HashMap::new(), |
| 144 | + has_exit: false, |
| 145 | + } |
| 146 | + } |
| 147 | +} |
| 148 | + |
| 149 | +/// Precompile the render sites of `live`; how many fired, and the step |
| 150 | +/// functions `map` fusions generated (the driver simplifies them in |
| 151 | +/// its next round). |
| 152 | +pub fn run_in(program: &mut Program, live: &[FnId]) -> (usize, Vec<FnId>) { |
| 153 | + if std::env::var_os(DISABLE_VAR).is_some() { |
| 154 | + return (0, Vec::new()); |
| 155 | + } |
| 156 | + let Some(std) = Std::resolve(program) else { |
| 157 | + return (0, Vec::new()); |
| 158 | + }; |
| 159 | + let boring = pure::functions(program); |
| 160 | + let mut pre = Pre { |
| 161 | + program, |
| 162 | + std, |
| 163 | + boring, |
| 164 | + bodies: HashMap::new(), |
| 165 | + variants: HashMap::new(), |
| 166 | + new_fns: Vec::new(), |
| 167 | + next_var: 0, |
| 168 | + expansions: 0, |
| 169 | + stack: Vec::new(), |
| 170 | + boring_out: true, |
| 171 | + frame_ids: 0, |
| 172 | + }; |
| 173 | + let mut sites = 0; |
| 174 | + let mut rewritten = Vec::new(); |
| 175 | + for &id in live { |
| 176 | + if program.fns[id as usize].is_constant_dictionary() { |
| 177 | + continue; |
| 178 | + } |
| 179 | + if let Some((n, body, n_vars)) = pre.function(id) { |
| 180 | + sites += n; |
| 181 | + rewritten.push((id, body, n_vars)); |
| 182 | + } |
| 183 | + } |
| 184 | + let new_fns = std::mem::take(&mut pre.new_fns); |
| 185 | + drop(pre); |
| 186 | + for (id, body, n_vars) in rewritten { |
| 187 | + let f = &mut program.fns[id as usize]; |
| 188 | + f.body = body; |
| 189 | + f.n_vars = n_vars; |
| 190 | + } |
| 191 | + let new = (0..new_fns.len()) |
| 192 | + .map(|i| (program.fns.len() + i) as FnId) |
| 193 | + .collect(); |
| 194 | + program.fns.extend(new_fns); |
| 195 | + (sites, new) |
| 196 | +} |
| 197 | + |
| 198 | +struct Pre<'p> { |
| 199 | + program: &'p Program, |
| 200 | + std: Std, |
| 201 | + /// The pure (and so panic-free) functions: fusion's gate (ADR |
| 202 | + /// 0043, `opt::pure`); what a moved binding may call. |
| 203 | + boring: HashSet<FnId>, |
| 204 | + /// Body indexes, built on demand and kept (a component is |
| 205 | + /// translated at every site that renders it). |
| 206 | + bodies: HashMap<FnId, Rc<Body>>, |
| 207 | + /// The `map` fusion's step functions and whether their bodies are |
| 208 | + /// boring, by function and capture count. |
| 209 | + variants: HashMap<(FnId, usize), (FnId, bool)>, |
| 210 | + new_fns: Vec<FnDecl>, |
| 211 | + /// Fresh variables of the function being rewritten (a generated |
| 212 | + /// step function has its own). |
| 213 | + next_var: u32, |
| 214 | + /// Component expansions left at this site. |
| 215 | + expansions: u32, |
| 216 | + /// The functions being translated (a component that renders itself |
| 217 | + /// falls back to `render_into` at the recursion). |
| 218 | + stack: Vec<FnId>, |
| 219 | + /// Whether everything emitted for the translation in flight is |
| 220 | + /// boring (the commute rule's first disjunct). |
| 221 | + boring_out: bool, |
| 222 | + /// Frame ids (a frame's consumed entries must not collide with a |
| 223 | + /// later frame's at the same depth). |
| 224 | + frame_ids: usize, |
| 225 | +} |
| 226 | + |
| 227 | +/// A function body being translated, as a frame of the walk: the |
| 228 | +/// site's own function at the bottom, an inlined component's body per |
| 229 | +/// nested frame above it. |
| 230 | +struct Frame { |
| 231 | + /// Unique within a site's translation (frames come and go as |
| 232 | + /// inlines push and pop; consumed entries are keyed by it). |
| 233 | + id: usize, |
| 234 | + body: Rc<Body>, |
| 235 | + /// The body's expression (a component frame's; the bottom frame's |
| 236 | + /// is unused: the rewrite edits the function). |
| 237 | + expr: Rc<Expr>, |
| 238 | + /// The frame's variables as atoms of the bottom frame's function: |
| 239 | + /// parameters (bound at the inline), and every `let` (pre-assigned |
| 240 | + /// a fresh variable before the walk, so an emitted append can |
| 241 | + /// refer to what the copy pass binds). |
| 242 | + env: HashMap<VarId, Atom>, |
| 243 | + /// The `let` variables of the chain holding the render call, in |
| 244 | + /// order, and the render call's index among them (a component |
| 245 | + /// frame's: the end of its body) — the positions of the commute |
| 246 | + /// rule. |
| 247 | + lets: Vec<VarId>, |
| 248 | + render_pos: usize, |
| 249 | +} |
| 250 | + |
| 251 | +/// The state of a site's translation. |
| 252 | +struct Walk { |
| 253 | + frames: Vec<Frame>, |
| 254 | + /// The tree constructions and inlined calls consumed so far, per |
| 255 | + /// frame, with the log to roll a failed translation back. |
| 256 | + consumed: HashSet<(usize, VarId)>, |
| 257 | + log: Vec<(usize, VarId)>, |
| 258 | +} |
| 259 | + |
| 260 | +impl Walk { |
| 261 | + /// `a` as seen from frame `fi`, resolved: `let x = atom` aliases |
| 262 | + /// chased within a frame, parameters crossed to the caller's. The |
| 263 | + /// frame the atom belongs to, and the atom. A parameter's argument |
| 264 | + /// is an atom of the bottom frame (environments hold those), so |
| 265 | + /// the chase continues there. |
| 266 | + fn resolve_from(&self, mut fi: usize, a: &Atom) -> (usize, Atom) { |
| 267 | + let mut a = a.clone(); |
| 268 | + loop { |
| 269 | + let frame = &self.frames[fi]; |
| 270 | + let Atom::Var(v) = a else { return (fi, a) }; |
| 271 | + match frame.body.bindings.get(&v) { |
| 272 | + Some(Value::Atom(next)) => a = next.clone(), |
| 273 | + Some(_) => return (fi, Atom::Var(v)), |
| 274 | + None => match frame.env.get(&v) { |
| 275 | + // A parameter: the caller's atom for it. |
| 276 | + Some(next) => { |
| 277 | + a = next.clone(); |
| 278 | + fi = 0; |
| 279 | + } |
| 280 | + // A parameter of the site's function: opaque. |
| 281 | + None => return (fi, Atom::Var(v)), |
| 282 | + }, |
| 283 | + } |
| 284 | + } |
| 285 | + } |
| 286 | + |
| 287 | + /// The binding of `a`'s variable (as seen from frame `fi`), |
| 288 | + /// resolved. |
| 289 | + fn binding_from(&self, fi: usize, a: &Atom) -> Option<(usize, VarId, Value)> { |
| 290 | + let (fi, a) = self.resolve_from(fi, a); |
| 291 | + let Atom::Var(v) = a else { return None }; |
| 292 | + let value = self.frames[fi].body.bindings.get(&v)?.clone(); |
| 293 | + Some((fi, v, value)) |
| 294 | + } |
| 295 | + |
| 296 | + /// Mark `(fi, v)` consumed: a tree construction walked, a call |
| 297 | + /// inlined. `false` (the position falls back, the value stays |
| 298 | + /// built) when the variable has another use — the tree would be |
| 299 | + /// observable. |
| 300 | + fn consume(&mut self, fi: usize, v: VarId) -> bool { |
| 301 | + let key = (self.frames[fi].id, v); |
| 302 | + if self.consumed.contains(&key) { |
| 303 | + return true; |
| 304 | + } |
| 305 | + if self.frames[fi].body.uses.get(&v) != Some(&1) { |
| 306 | + return false; |
| 307 | + } |
| 308 | + self.consumed.insert(key); |
| 309 | + self.log.push(key); |
| 310 | + true |
| 311 | + } |
| 312 | + |
| 313 | + fn consumed(&self, fi: usize, v: VarId) -> bool { |
| 314 | + self.consumed.contains(&(self.frames[fi].id, v)) |
| 315 | + } |
| 316 | + |
| 317 | + fn mark(&self) -> usize { |
| 318 | + self.log.len() |
| 319 | + } |
| 320 | + |
| 321 | + fn rollback(&mut self, mark: usize) { |
| 322 | + while self.log.len() > mark { |
| 323 | + let Some((fi, v)) = self.log.pop() else { break }; |
| 324 | + self.consumed.remove(&(fi, v)); |
| 325 | + } |
| 326 | + } |
| 327 | +} |
| 328 | + |
| 329 | +/// The `let`s being emitted for a render, threading a builder |
| 330 | +/// variable; adjacent static chunks merge into one append. |
| 331 | +#[derive(Default)] |
| 332 | +struct Out { |
| 333 | + lets: Vec<(VarId, Value, Option<Span>)>, |
| 334 | + /// The last `let` when it is a static-chunk append (its literal |
| 335 | + /// the next chunk merges into). |
| 336 | + last_chunk: Option<usize>, |
| 337 | +} |
| 338 | + |
| 339 | +/// A position to roll emissions back to: the `let`s then, and the |
| 340 | +/// length of the chunk being merged into then (a merge extends it in |
| 341 | +/// place). |
| 342 | +struct OutMark { |
| 343 | + lets: usize, |
| 344 | + chunk: Option<(usize, usize)>, |
| 345 | +} |
| 346 | + |
| 347 | +impl Out { |
| 348 | + fn append(&mut self, other: Out) { |
| 349 | + let base = self.lets.len(); |
| 350 | + self.last_chunk = other.last_chunk.map(|i| i + base); |
| 351 | + self.lets.extend(other.lets); |
| 352 | + } |
| 353 | + |
| 354 | + fn mark(&self) -> OutMark { |
| 355 | + OutMark { |
| 356 | + lets: self.lets.len(), |
| 357 | + chunk: self.last_chunk.map(|i| { |
| 358 | + let (_, value, _) = &self.lets[i]; |
| 359 | + let Some(Value::CallExtern(_, args)) = Some(value) else { |
| 360 | + unreachable!() |
| 361 | + }; |
| 362 | + let Some(Atom::Lit(Lit::String(s))) = args.get(1) else { |
| 363 | + unreachable!() |
| 364 | + }; |
| 365 | + (i, s.len()) |
| 366 | + }), |
| 367 | + } |
| 368 | + } |
| 369 | + |
| 370 | + /// Forget the emissions since `mark` (a failed translation), |
| 371 | + /// including what a merge added to a kept chunk. |
| 372 | + fn truncate(&mut self, mark: OutMark) { |
| 373 | + self.lets.truncate(mark.lets); |
| 374 | + self.last_chunk = match mark.chunk { |
| 375 | + Some((i, len)) if i < self.lets.len() => { |
| 376 | + let (_, value, _) = &mut self.lets[i]; |
| 377 | + let Some(Value::CallExtern(_, args)) = Some(value) else { |
| 378 | + unreachable!() |
| 379 | + }; |
| 380 | + let Some(Atom::Lit(Lit::String(s))) = args.get_mut(1) else { |
| 381 | + unreachable!() |
| 382 | + }; |
| 383 | + s.truncate(len); |
| 384 | + Some(i) |
| 385 | + } |
| 386 | + _ => None, |
| 387 | + }; |
| 388 | + } |
| 389 | +} |
| 390 | + |
| 391 | +/// A chain of `let`s (a replacement, or one being rebuilt). |
| 392 | +type Lets = Vec<(VarId, Value, Option<Span>)>; |
| 393 | + |
| 394 | +/// A render site found in a chain. |
| 395 | +struct Site { |
| 396 | + /// The variable the render call binds. |
| 397 | + result: VarId, |
| 398 | + /// The rendered tree. |
| 399 | + tree: Atom, |
| 400 | + /// The builder (`None`: `render(t)`, to be created; `Some(b)`: |
| 401 | + /// `render_into(t, b)` of `render` inlined, `b` a fresh builder). |
| 402 | + builder: Option<Atom>, |
| 403 | + /// The chain's `let` variables, and the render call's index. |
| 404 | + chain: Vec<VarId>, |
| 405 | + pos: usize, |
| 406 | +} |
| 407 | + |
| 408 | +/// Whether a component call was translated in place or fell back to |
| 409 | +/// `render_into` of it. |
| 410 | +enum Inline { |
| 411 | + Inlined, |
| 412 | + FellBack, |
| 413 | +} |
| 414 | + |
| 415 | +impl<'p> Pre<'p> { |
| 416 | + fn body_of(&mut self, f: FnId) -> Rc<Body> { |
| 417 | + self.bodies |
| 418 | + .entry(f) |
| 419 | + .or_insert_with(|| Rc::new(Body::of(&self.program.fns[f as usize].body))) |
| 420 | + .clone() |
| 421 | + } |
| 422 | + |
| 423 | + fn fresh(&mut self) -> VarId { |
| 424 | + let v = self.next_var; |
| 425 | + self.next_var += 1; |
| 426 | + v |
| 427 | + } |
| 428 | + |
| 429 | + fn frame_id(&mut self) -> usize { |
| 430 | + let id = self.frame_ids; |
| 431 | + self.frame_ids += 1; |
| 432 | + id |
| 433 | + } |
| 434 | + |
| 435 | + /// A `let`'s value is boring: pure and panic-free, so it commutes |
| 436 | + /// with anything (and a monitor never sees it crash, ADR 0004). |
| 437 | + fn boring_value(&self, value: &Value) -> bool { |
| 438 | + match value { |
| 439 | + Value::Atom(_) |
| 440 | + | Value::Construct { .. } |
| 441 | + | Value::Tuple(_) |
| 442 | + | Value::Closure(..) |
| 443 | + | Value::Field(..) |
| 444 | + | Value::Prim(..) => true, |
| 445 | + Value::CallExtern(sym, args) => pure::extern_pure(sym, args), |
| 446 | + Value::CallFn(g, _) => { |
| 447 | + self.boring.contains(g) || self.program.fns[*g as usize].is_constant_dictionary() |
| 448 | + } |
| 449 | + _ => false, |
| 450 | + } |
| 451 | + } |
| 452 | + |
| 453 | + /// Precompile the render sites of `f`; how many fired, and the |
| 454 | + /// rewritten body and its variable count. |
| 455 | + fn function(&mut self, id: FnId) -> Option<(usize, Expr, u32)> { |
| 456 | + self.next_var = self.program.fns[id as usize].n_vars; |
| 457 | + let body = self.body_of(id); |
| 458 | + let mut sites = Vec::new(); |
| 459 | + self.scan(&body, &self.program.fns[id as usize].body, &mut sites); |
| 460 | + if sites.is_empty() { |
| 461 | + return None; |
| 462 | + } |
| 463 | + self.stack.push(id); |
| 464 | + let mut dead = HashSet::new(); |
| 465 | + let mut replacements: HashMap<VarId, Lets> = HashMap::new(); |
| 466 | + let mut fired = 0; |
| 467 | + for site in sites { |
| 468 | + self.expansions = MAX_EXPANSIONS; |
| 469 | + if let Some((replacement, consumed)) = self.render_site(body.clone(), &site) { |
| 470 | + dead.extend(consumed); |
| 471 | + replacements.insert(site.result, replacement); |
| 472 | + fired += 1; |
| 473 | + } |
| 474 | + } |
| 475 | + self.stack.pop(); |
| 476 | + if fired == 0 { |
| 477 | + return None; |
| 478 | + } |
| 479 | + let body = rewrite( |
| 480 | + self.program.fns[id as usize].body.clone(), |
| 481 | + &dead, |
| 482 | + &replacements, |
| 483 | + ); |
| 484 | + Some((fired, body, self.next_var)) |
| 485 | + } |
| 486 | + |
| 487 | + /// The render sites of a chain and its nested blocks. |
| 488 | + fn scan(&self, body: &Body, e: &Expr, sites: &mut Vec<Site>) { |
| 489 | + let (lets, end) = split_ref(e); |
| 490 | + let chain: Vec<VarId> = lets.iter().map(|(v, _, _)| *v).collect(); |
| 491 | + for (i, (v, value, _)) in lets.iter().enumerate() { |
| 492 | + if let Value::Block(b) = value { |
| 493 | + self.scan(body, b, sites); |
| 494 | + } |
| 495 | + match value { |
| 496 | + // `render(t)`: the builder is the call's own. |
| 497 | + Value::CallFn(g, args) |
| 498 | + if *g == self.std.render |
| 499 | + && args.len() == 1 |
| 500 | + && matches!(args[0], Atom::Var(_)) => |
| 501 | + { |
| 502 | + sites.push(Site { |
| 503 | + result: *v, |
| 504 | + tree: args[0].clone(), |
| 505 | + builder: None, |
| 506 | + chain: chain.clone(), |
| 507 | + pos: i, |
| 508 | + }); |
| 509 | + } |
| 510 | + // `render_into(t, b)` with `b` a fresh builder: |
| 511 | + // `render` inlined. A fallback the pass itself emitted |
| 512 | + // has a mid-chain `b` and never matches. |
| 513 | + Value::CallFn(g, args) |
| 514 | + if *g == self.std.render_into |
| 515 | + && args.len() == 2 |
| 516 | + && matches!(args[0], Atom::Var(_)) |
| 517 | + && self.fresh_builder(body, &args[1]) => |
| 518 | + { |
| 519 | + sites.push(Site { |
| 520 | + result: *v, |
| 521 | + tree: args[0].clone(), |
| 522 | + builder: Some(args[1].clone()), |
| 523 | + chain: chain.clone(), |
| 524 | + pos: i, |
| 525 | + }); |
| 526 | + } |
| 527 | + _ => {} |
| 528 | + } |
| 529 | + } |
| 530 | + match end { |
| 531 | + Expr::Switch { cases, default, .. } => { |
| 532 | + for (_, arm) in cases { |
| 533 | + self.scan(body, arm, sites); |
| 534 | + } |
| 535 | + if let Some(arm) = default { |
| 536 | + self.scan(body, arm, sites); |
| 537 | + } |
| 538 | + } |
| 539 | + Expr::SwitchLit { cases, default, .. } => { |
| 540 | + for (_, arm) in cases { |
| 541 | + self.scan(body, arm, sites); |
| 542 | + } |
| 543 | + self.scan(body, default, sites); |
| 544 | + } |
| 545 | + _ => {} |
| 546 | + } |
| 547 | + } |
| 548 | + |
| 549 | + /// Whether `a` is bound to a fresh builder (`bytes.builder()`, |
| 550 | + /// after inlining the `tl_bytes_builder` extern). |
| 551 | + fn fresh_builder(&self, body: &Body, a: &Atom) -> bool { |
| 552 | + let mut a = a; |
| 553 | + loop { |
| 554 | + let Atom::Var(v) = a else { return false }; |
| 555 | + match body.bindings.get(v) { |
| 556 | + Some(Value::Atom(next)) => a = next, |
| 557 | + Some(Value::CallFn(g, args)) => { |
| 558 | + let d = &self.program.fns[*g as usize]; |
| 559 | + return args.is_empty() |
| 560 | + && d.module.as_deref() == Some("std/bytes") |
| 561 | + && d.name == "std/bytes.builder"; |
| 562 | + } |
| 563 | + Some(Value::CallExtern(sym, _)) => return sym == "tl_bytes_builder", |
| 564 | + _ => return false, |
| 565 | + } |
| 566 | + } |
| 567 | + } |
| 568 | + |
| 569 | + /// The replacement for a site: the appends the render compiles |
| 570 | + /// to, and the tree constructions and inlined calls of the |
| 571 | + /// function to delete. `None`: the site does not fire. |
| 572 | + fn render_site(&mut self, body: Rc<Body>, site: &Site) -> Option<(Lets, HashSet<VarId>)> { |
| 573 | + let mut walk = Walk { |
| 574 | + frames: vec![Frame { |
| 575 | + id: self.frame_id(), |
| 576 | + body, |
| 577 | + expr: Rc::new(Expr::Return(Atom::Unit)), |
| 578 | + env: HashMap::new(), |
| 579 | + lets: site.chain.clone(), |
| 580 | + render_pos: site.pos, |
| 581 | + }], |
| 582 | + consumed: HashSet::new(), |
| 583 | + log: Vec::new(), |
| 584 | + }; |
| 585 | + let site_frame = walk.frames[0].id; |
| 586 | + let mut out = Out::default(); |
| 587 | + let mut cur = match &site.builder { |
| 588 | + Some(b) => { |
| 589 | + let (_, Atom::Var(b)) = walk.resolve_from(0, b) else { |
| 590 | + return None; |
| 591 | + }; |
| 592 | + b |
| 593 | + } |
| 594 | + None => { |
| 595 | + let b = self.fresh(); |
| 596 | + self.step( |
| 597 | + &mut out, |
| 598 | + b, |
| 599 | + Value::CallExtern("tl_bytes_builder".into(), vec![Atom::Lit(Lit::Int(0))]), |
| 600 | + ); |
| 601 | + b |
| 602 | + } |
| 603 | + }; |
| 604 | + // The rendered value itself must be a tree or a component |
| 605 | + // call; an opaque value is not a site. |
| 606 | + let (fi, t, binding) = walk.binding_from(0, &site.tree)?; |
| 607 | + self.boring_out = true; |
| 608 | + let mark = walk.mark(); |
| 609 | + let fired = match binding { |
| 610 | + Value::Construct { name, args, .. } => { |
| 611 | + walk.consume(fi, t) |
| 612 | + && self |
| 613 | + .construct(&mut walk, fi, t, &name, &args, &mut out, &mut cur, 0) |
| 614 | + .is_ok() |
| 615 | + } |
| 616 | + Value::CallFn(g, args) => { |
| 617 | + match self.inline_call(&mut walk, fi, t, g, &args, &mut out, &mut cur, 0) { |
| 618 | + Inline::Inlined => true, |
| 619 | + Inline::FellBack => false, |
| 620 | + } |
| 621 | + } |
| 622 | + // `render(if … { <a/> } else { <b/> })`: each arm renders. |
| 623 | + Value::Block(b) => self.block_hole(&mut walk, fi, t, &b, &mut out, &mut cur, 0), |
| 624 | + _ => false, |
| 625 | + }; |
| 626 | + if !fired { |
| 627 | + walk.rollback(mark); |
| 628 | + return None; |
| 629 | + } |
| 630 | + let mut lets = out.lets; |
| 631 | + match &site.builder { |
| 632 | + // `render(t)`'s result is the built string. |
| 633 | + None => lets.push(( |
| 634 | + site.result, |
| 635 | + Value::CallExtern("tl_bytes_build_string".into(), vec![Atom::Var(cur)]), |
| 636 | + None, |
| 637 | + )), |
| 638 | + // `render_into(t, b)`'s is the final builder. |
| 639 | + Some(_) => lets.push((site.result, Value::Atom(Atom::Var(cur)), None)), |
| 640 | + } |
| 641 | + let dead = walk |
| 642 | + .consumed |
| 643 | + .iter() |
| 644 | + .filter(|(frame, _)| *frame == site_frame) |
| 645 | + .map(|(_, v)| *v) |
| 646 | + .collect(); |
| 647 | + Some((lets, dead)) |
| 648 | + } |
| 649 | + |
| 650 | + // ---- the tree walk ------------------------------------------------ |
| 651 | + |
| 652 | + /// One `let` of an append (or a copied binding). |
| 653 | + fn step(&mut self, out: &mut Out, v: VarId, value: Value) { |
| 654 | + out.last_chunk = None; |
| 655 | + out.lets.push((v, value, None)); |
| 656 | + } |
| 657 | + |
| 658 | + /// A static chunk, merged into the previous one when adjacent. |
| 659 | + fn chunk(&mut self, out: &mut Out, cur: &mut VarId, s: String) { |
| 660 | + if s.is_empty() { |
| 661 | + return; |
| 662 | + } |
| 663 | + if let Some(i) = out.last_chunk { |
| 664 | + let (_, value, _) = &mut out.lets[i]; |
| 665 | + let Some(Value::CallExtern(_, args)) = Some(value) else { |
| 666 | + unreachable!() |
| 667 | + }; |
| 668 | + let Some(Atom::Lit(Lit::String(prev))) = args.get_mut(1) else { |
| 669 | + unreachable!() |
| 670 | + }; |
| 671 | + prev.push_str(&s); |
| 672 | + return; |
| 673 | + } |
| 674 | + let b = self.fresh(); |
| 675 | + out.lets.push(( |
| 676 | + b, |
| 677 | + Value::CallExtern( |
| 678 | + "tl_bytes_append_string".into(), |
| 679 | + vec![Atom::Var(*cur), Atom::Lit(Lit::String(s))], |
| 680 | + ), |
| 681 | + None, |
| 682 | + )); |
| 683 | + out.last_chunk = Some(out.lets.len() - 1); |
| 684 | + *cur = b; |
| 685 | + } |
| 686 | + |
| 687 | + /// The bottom frame's atom for a frame's variable, for an emitted |
| 688 | + /// append: the frame's environment holds it (a parameter's |
| 689 | + /// argument, a copied `let`'s fresh variable); the bottom frame's |
| 690 | + /// own variables are theirs. `None`: a consumed variable — the |
| 691 | + /// tree was observed; the translation aborts. |
| 692 | + fn emit_atom(walk: &Walk, fi: usize, v: VarId) -> Option<Atom> { |
| 693 | + if walk.consumed(fi, v) { |
| 694 | + return None; |
| 695 | + } |
| 696 | + if let Some(a) = walk.frames[fi].env.get(&v) { |
| 697 | + return Some(a.clone()); |
| 698 | + } |
| 699 | + if fi == 0 { |
| 700 | + return Some(Atom::Var(v)); |
| 701 | + } |
| 702 | + None |
| 703 | + } |
| 704 | + |
| 705 | + /// `render_into(a, cur)`: the fallback for an opaque element. |
| 706 | + fn render_el( |
| 707 | + &mut self, |
| 708 | + walk: &Walk, |
| 709 | + fi: usize, |
| 710 | + v: VarId, |
| 711 | + out: &mut Out, |
| 712 | + cur: &mut VarId, |
| 713 | + ) -> Result<(), ()> { |
| 714 | + let a = Self::emit_atom(walk, fi, v).ok_or(())?; |
| 715 | + let b = self.fresh(); |
| 716 | + self.step( |
| 717 | + out, |
| 718 | + b, |
| 719 | + Value::CallFn(self.std.render_into, vec![a, Atom::Var(*cur)]), |
| 720 | + ); |
| 721 | + *cur = b; |
| 722 | + Ok(()) |
| 723 | + } |
| 724 | + |
| 725 | + /// `render_all(a, cur)`: the fallback for an opaque list. |
| 726 | + fn render_all( |
| 727 | + &mut self, |
| 728 | + walk: &Walk, |
| 729 | + fi: usize, |
| 730 | + v: VarId, |
| 731 | + out: &mut Out, |
| 732 | + cur: &mut VarId, |
| 733 | + ) -> Result<(), ()> { |
| 734 | + let a = Self::emit_atom(walk, fi, v).ok_or(())?; |
| 735 | + let b = self.fresh(); |
| 736 | + self.step( |
| 737 | + out, |
| 738 | + b, |
| 739 | + Value::CallFn(self.std.render_all, vec![a, Atom::Var(*cur)]), |
| 740 | + ); |
| 741 | + *cur = b; |
| 742 | + Ok(()) |
| 743 | + } |
| 744 | + |
| 745 | + /// An element of the tree: a construction (walked), a component |
| 746 | + /// call (translated), or an opaque hole (the fallback). |
| 747 | + #[allow(clippy::too_many_arguments)] |
| 748 | + fn element( |
| 749 | + &mut self, |
| 750 | + walk: &mut Walk, |
| 751 | + fi: usize, |
| 752 | + a: &Atom, |
| 753 | + out: &mut Out, |
| 754 | + cur: &mut VarId, |
| 755 | + depth: u32, |
| 756 | + ) -> Result<(), ()> { |
| 757 | + let Some((fi, v, binding)) = walk.binding_from(fi, a) else { |
| 758 | + return Err(()); // a literal is never an element |
| 759 | + }; |
| 760 | + match binding { |
| 761 | + Value::Construct { name, args, .. } => { |
| 762 | + let mark = walk.mark(); |
| 763 | + let omark = out.mark(); |
| 764 | + if !walk.consume(fi, v) { |
| 765 | + // A shared subtree stays built; render it. |
| 766 | + self.render_el(walk, fi, v, out, cur)?; |
| 767 | + return Ok(()); |
| 768 | + } |
| 769 | + match self.construct(walk, fi, v, &name, &args, out, cur, depth) { |
| 770 | + Ok(()) => Ok(()), |
| 771 | + Err(()) => { |
| 772 | + // Not `std/html`'s shape after all (a dynamic |
| 773 | + // tag, say): render the construction. |
| 774 | + walk.rollback(mark); |
| 775 | + out.truncate(omark); |
| 776 | + self.render_el(walk, fi, v, out, cur) |
| 777 | + } |
| 778 | + } |
| 779 | + } |
| 780 | + Value::CallFn(g, args) => { |
| 781 | + match self.inline_call(walk, fi, v, g, &args, out, cur, depth) { |
| 782 | + Inline::Inlined => Ok(()), |
| 783 | + Inline::FellBack => self.render_el(walk, fi, v, out, cur), |
| 784 | + } |
| 785 | + } |
| 786 | + // A hole whose value an if/match computes: render each arm. |
| 787 | + Value::Block(b) => { |
| 788 | + if !self.block_hole(walk, fi, v, &b, out, cur, depth) { |
| 789 | + self.render_el(walk, fi, v, out, cur)?; |
| 790 | + } |
| 791 | + Ok(()) |
| 792 | + } |
| 793 | + // An opaque hole: a parameter, a closure call, a |
| 794 | + // projection. |
| 795 | + _ => self.render_el(walk, fi, v, out, cur), |
| 796 | + } |
| 797 | + } |
| 798 | + |
| 799 | + /// A `Node`/`Text`/`Raw`/`Fragment` construction, rendered. The |
| 800 | + /// variable was consumed by the caller. `Err`: not `std/html`'s |
| 801 | + /// shape (the caller renders the construction instead). |
| 802 | + #[allow(clippy::too_many_arguments)] |
| 803 | + fn construct( |
| 804 | + &mut self, |
| 805 | + walk: &mut Walk, |
| 806 | + fi: usize, |
| 807 | + v: VarId, |
| 808 | + name: &str, |
| 809 | + args: &[Atom], |
| 810 | + out: &mut Out, |
| 811 | + cur: &mut VarId, |
| 812 | + depth: u32, |
| 813 | + ) -> Result<(), ()> { |
| 814 | + let _ = v; |
| 815 | + match (name, args) { |
| 816 | + ("Node", [tag, attrs, children]) => { |
| 817 | + let (_, Atom::Lit(Lit::String(tag))) = walk.resolve_from(fi, tag) else { |
| 818 | + return Err(()); |
| 819 | + }; |
| 820 | + self.chunk(out, cur, format!("<{tag}")); |
| 821 | + self.attrs(walk, fi, attrs, out, cur, depth)?; |
| 822 | + self.chunk(out, cur, ">".to_owned()); |
| 823 | + if !is_void(&tag) { |
| 824 | + self.children(walk, fi, children, out, cur, depth)?; |
| 825 | + self.chunk(out, cur, format!("</{tag}>")); |
| 826 | + } |
| 827 | + Ok(()) |
| 828 | + } |
| 829 | + ("Text", [a]) => match walk.resolve_from(fi, a) { |
| 830 | + (_, Atom::Lit(Lit::String(s))) => { |
| 831 | + let s = louise_rt_prims::html_escape(&s); |
| 832 | + self.chunk(out, cur, s); |
| 833 | + Ok(()) |
| 834 | + } |
| 835 | + (xfi, Atom::Var(x)) => { |
| 836 | + let Some(a) = Self::emit_atom(walk, xfi, x) else { |
| 837 | + return Err(()); |
| 838 | + }; |
| 839 | + let b = self.fresh(); |
| 840 | + self.step( |
| 841 | + out, |
| 842 | + b, |
| 843 | + Value::CallExtern( |
| 844 | + "tl_bytes_append_escaped".into(), |
| 845 | + vec![Atom::Var(*cur), a], |
| 846 | + ), |
| 847 | + ); |
| 848 | + *cur = b; |
| 849 | + Ok(()) |
| 850 | + } |
| 851 | + _ => Err(()), |
| 852 | + }, |
| 853 | + ("Raw", [a]) => match walk.resolve_from(fi, a) { |
| 854 | + (_, Atom::Lit(Lit::String(s))) => { |
| 855 | + self.chunk(out, cur, s); |
| 856 | + Ok(()) |
| 857 | + } |
| 858 | + (xfi, Atom::Var(x)) => { |
| 859 | + let Some(a) = Self::emit_atom(walk, xfi, x) else { |
| 860 | + return Err(()); |
| 861 | + }; |
| 862 | + let b = self.fresh(); |
| 863 | + self.step( |
| 864 | + out, |
| 865 | + b, |
| 866 | + Value::CallExtern( |
| 867 | + "tl_bytes_append_string".into(), |
| 868 | + vec![Atom::Var(*cur), a], |
| 869 | + ), |
| 870 | + ); |
| 871 | + *cur = b; |
| 872 | + Ok(()) |
| 873 | + } |
| 874 | + _ => Err(()), |
| 875 | + }, |
| 876 | + ("Fragment", [l]) => self.children(walk, fi, l, out, cur, depth), |
| 877 | + _ => Err(()), |
| 878 | + } |
| 879 | + } |
| 880 | + |
| 881 | + /// The attributes of a node: a `Cons` chain of `Attribute` and |
| 882 | + /// `Flag` constructions (always one, from lowering). |
| 883 | + #[allow(clippy::too_many_arguments)] |
| 884 | + fn attrs( |
| 885 | + &mut self, |
| 886 | + walk: &mut Walk, |
| 887 | + fi: usize, |
| 888 | + a: &Atom, |
| 889 | + out: &mut Out, |
| 890 | + cur: &mut VarId, |
| 891 | + depth: u32, |
| 892 | + ) -> Result<(), ()> { |
| 893 | + let Some((afi, v, binding)) = walk.binding_from(fi, a) else { |
| 894 | + return Err(()); |
| 895 | + }; |
| 896 | + match binding { |
| 897 | + Value::Construct { name, args, .. } if name == "Nil" && args.is_empty() => Ok(()), |
| 898 | + Value::Construct { name, args, .. } if name == "Cons" && args.len() == 2 => { |
| 899 | + if !walk.consume(afi, v) { |
| 900 | + return Err(()); |
| 901 | + } |
| 902 | + self.attr(walk, afi, &args[0], out, cur, depth)?; |
| 903 | + self.attrs(walk, afi, &args[1], out, cur, depth) |
| 904 | + } |
| 905 | + _ => Err(()), |
| 906 | + } |
| 907 | + } |
| 908 | + |
| 909 | + /// One attribute: ` name="value"` (the value escaped), or ` name` |
| 910 | + /// when a flag is on. |
| 911 | + #[allow(clippy::too_many_arguments)] |
| 912 | + fn attr( |
| 913 | + &mut self, |
| 914 | + walk: &mut Walk, |
| 915 | + fi: usize, |
| 916 | + a: &Atom, |
| 917 | + out: &mut Out, |
| 918 | + cur: &mut VarId, |
| 919 | + depth: u32, |
| 920 | + ) -> Result<(), ()> { |
| 921 | + let _ = depth; |
| 922 | + let Some((afi, v, binding)) = walk.binding_from(fi, a) else { |
| 923 | + return Err(()); |
| 924 | + }; |
| 925 | + let Value::Construct { name, args, .. } = binding else { |
| 926 | + return Err(()); |
| 927 | + }; |
| 928 | + if !walk.consume(afi, v) { |
| 929 | + return Err(()); |
| 930 | + } |
| 931 | + match (name.as_str(), args.as_slice()) { |
| 932 | + ("Attribute", [name, value]) => { |
| 933 | + let (_, Atom::Lit(Lit::String(name))) = walk.resolve_from(afi, name) else { |
| 934 | + return Err(()); |
| 935 | + }; |
| 936 | + self.chunk(out, cur, format!(" {name}=\"")); |
| 937 | + match walk.resolve_from(afi, value) { |
| 938 | + (_, Atom::Lit(Lit::String(s))) => { |
| 939 | + let s = louise_rt_prims::html_escape(&s); |
| 940 | + self.chunk(out, cur, s); |
| 941 | + } |
| 942 | + (xfi, Atom::Var(x)) => { |
| 943 | + let Some(a) = Self::emit_atom(walk, xfi, x) else { |
| 944 | + return Err(()); |
| 945 | + }; |
| 946 | + let b = self.fresh(); |
| 947 | + self.step( |
| 948 | + out, |
| 949 | + b, |
| 950 | + Value::CallExtern( |
| 951 | + "tl_bytes_append_escaped".into(), |
| 952 | + vec![Atom::Var(*cur), a], |
| 953 | + ), |
| 954 | + ); |
| 955 | + *cur = b; |
| 956 | + } |
| 957 | + _ => return Err(()), |
| 958 | + } |
| 959 | + self.chunk(out, cur, "\"".to_owned()); |
| 960 | + Ok(()) |
| 961 | + } |
| 962 | + ("Flag", [name, on]) => { |
| 963 | + let (_, Atom::Lit(Lit::String(name))) = walk.resolve_from(afi, name) else { |
| 964 | + return Err(()); |
| 965 | + }; |
| 966 | + // A constant flag folds (`<input checked/>`). |
| 967 | + if let Some((ofi, ov, Value::Construct { tag, args, .. })) = |
| 968 | + walk.binding_from(afi, on) |
| 969 | + && args.is_empty() |
| 970 | + && tag <= 1 |
| 971 | + && walk.consume(ofi, ov) |
| 972 | + { |
| 973 | + if tag == 1 { |
| 974 | + self.chunk(out, cur, format!(" {name}")); |
| 975 | + } |
| 976 | + return Ok(()); |
| 977 | + } |
| 978 | + let (ofi, Atom::Var(on)) = walk.resolve_from(afi, on) else { |
| 979 | + return Err(()); |
| 980 | + }; |
| 981 | + let Some(on) = Self::emit_atom(walk, ofi, on) else { |
| 982 | + return Err(()); |
| 983 | + }; |
| 984 | + // `if on { append " name" }`. |
| 985 | + let t = self.fresh(); |
| 986 | + let blk = self.fresh(); |
| 987 | + out.last_chunk = None; |
| 988 | + out.lets.push(( |
| 989 | + blk, |
| 990 | + Value::Block(Box::new(Expr::Switch { |
| 991 | + on, |
| 992 | + cases: vec![( |
| 993 | + 1, |
| 994 | + rebuild( |
| 995 | + vec![( |
| 996 | + t, |
| 997 | + Value::CallExtern( |
| 998 | + "tl_bytes_append_string".into(), |
| 999 | + vec![ |
| 1000 | + Atom::Var(*cur), |
| 1001 | + Atom::Lit(Lit::String(format!(" {name}"))), |
| 1002 | + ], |
| 1003 | + ), |
| 1004 | + None, |
| 1005 | + )], |
| 1006 | + Expr::Return(Atom::Var(t)), |
| 1007 | + ), |
| 1008 | + )], |
| 1009 | + default: Some(Box::new(Expr::Return(Atom::Var(*cur)))), |
| 1010 | + })), |
| 1011 | + None, |
| 1012 | + )); |
| 1013 | + *cur = blk; |
| 1014 | + Ok(()) |
| 1015 | + } |
| 1016 | + _ => Err(()), |
| 1017 | + } |
| 1018 | + } |
| 1019 | + |
| 1020 | + /// The children of a node (or a fragment's list): a `Cons` chain |
| 1021 | + /// walked element by element; a `list.map` fused; anything else |
| 1022 | + /// rendered by `render_all`. |
| 1023 | + #[allow(clippy::too_many_arguments)] |
| 1024 | + fn children( |
| 1025 | + &mut self, |
| 1026 | + walk: &mut Walk, |
| 1027 | + fi: usize, |
| 1028 | + a: &Atom, |
| 1029 | + out: &mut Out, |
| 1030 | + cur: &mut VarId, |
| 1031 | + depth: u32, |
| 1032 | + ) -> Result<(), ()> { |
| 1033 | + let Some((cfi, v, binding)) = walk.binding_from(fi, a) else { |
| 1034 | + return Err(()); |
| 1035 | + }; |
| 1036 | + match binding { |
| 1037 | + Value::Construct { name, args, .. } if name == "Nil" && args.is_empty() => Ok(()), |
| 1038 | + Value::Construct { name, args, .. } if name == "Cons" && args.len() == 2 => { |
| 1039 | + if !walk.consume(cfi, v) { |
| 1040 | + return self.render_all(walk, cfi, v, out, cur); |
| 1041 | + } |
| 1042 | + self.element(walk, cfi, &args[0], out, cur, depth)?; |
| 1043 | + self.children(walk, cfi, &args[1], out, cur, depth) |
| 1044 | + } |
| 1045 | + Value::CallFn(g, args) if g == self.std.map && args.len() == 2 && depth < MAX_DEPTH => { |
| 1046 | + let (xs, f) = (args[0].clone(), args[1].clone()); |
| 1047 | + self.map_fusion(walk, cfi, v, xs, f, out, cur, depth) |
| 1048 | + } |
| 1049 | + _ => self.render_all(walk, cfi, v, out, cur), |
| 1050 | + } |
| 1051 | + } |
| 1052 | + |
| 1053 | + /// `render_all(map(xs, f), cur)` as `fold(xs, cur, f$render)`: the |
| 1054 | + /// rows' trees are never built. The row function's applications |
| 1055 | + /// keep their order (the renders they interleave with are pure), |
| 1056 | + /// so `f` needs no purity — but moving the `map` call's own |
| 1057 | + /// evaluation is the commute rule, as for any moved binding. |
| 1058 | + #[allow(clippy::too_many_arguments)] |
| 1059 | + fn map_fusion( |
| 1060 | + &mut self, |
| 1061 | + walk: &mut Walk, |
| 1062 | + fi: usize, |
| 1063 | + v: VarId, |
| 1064 | + xs: Atom, |
| 1065 | + f: Atom, |
| 1066 | + out: &mut Out, |
| 1067 | + cur: &mut VarId, |
| 1068 | + depth: u32, |
| 1069 | + ) -> Result<(), ()> { |
| 1070 | + // What the fusion needs: the closure's function, its captures |
| 1071 | + // and the list, as the bottom frame's atoms, and the step |
| 1072 | + // function (generated, or reused). |
| 1073 | + let attempt = (|pre: &mut Self| { |
| 1074 | + if pre.expansions == 0 { |
| 1075 | + return None; |
| 1076 | + } |
| 1077 | + let (cfi, _, Value::Closure(g, caps)) = walk.binding_from(fi, &f)? else { |
| 1078 | + return None; |
| 1079 | + }; |
| 1080 | + let (variant, variant_boring) = pre.map_variant(g, caps.len(), depth)?; |
| 1081 | + let caps: Option<Vec<Atom>> = caps |
| 1082 | + .iter() |
| 1083 | + .map(|c| { |
| 1084 | + let (cfi, c) = walk.resolve_from(cfi, c); |
| 1085 | + match c { |
| 1086 | + Atom::Var(c) => Self::emit_atom(walk, cfi, c), |
| 1087 | + c => Some(c), |
| 1088 | + } |
| 1089 | + }) |
| 1090 | + .collect(); |
| 1091 | + let xs = { |
| 1092 | + let (xfi, x) = walk.resolve_from(fi, &xs); |
| 1093 | + match x { |
| 1094 | + Atom::Var(x) => Self::emit_atom(walk, xfi, x), |
| 1095 | + x => Some(x), |
| 1096 | + } |
| 1097 | + }; |
| 1098 | + Some((variant, variant_boring, caps?, xs?)) |
| 1099 | + })(self); |
| 1100 | + // The commute rule: the map's evaluation moves to the render. |
| 1101 | + let fused = match attempt { |
| 1102 | + Some((variant, variant_boring, caps, xs)) => { |
| 1103 | + self.commutes(walk, fi, v, variant_boring) && walk.consume(fi, v) && { |
| 1104 | + self.expansions -= 1; |
| 1105 | + self.boring_out = false; // `fold` calls the step closure |
| 1106 | + let clo = self.fresh(); |
| 1107 | + self.step(out, clo, Value::Closure(variant, caps)); |
| 1108 | + let b = self.fresh(); |
| 1109 | + self.step( |
| 1110 | + out, |
| 1111 | + b, |
| 1112 | + Value::CallFn(self.std.fold, vec![xs, Atom::Var(*cur), Atom::Var(clo)]), |
| 1113 | + ); |
| 1114 | + *cur = b; |
| 1115 | + true |
| 1116 | + } |
| 1117 | + } |
| 1118 | + None => false, |
| 1119 | + }; |
| 1120 | + if !fused { |
| 1121 | + self.render_all(walk, fi, v, out, cur)?; |
| 1122 | + } |
| 1123 | + Ok(()) |
| 1124 | + } |
| 1125 | + |
| 1126 | + /// The step function of a `map` fusion: `f$render(b, captures…, x)` |
| 1127 | + /// renders `f(x)` into `b`. `None`: `f` is not translatable at |
| 1128 | + /// all — no fusion. With a body that does not translate, the step |
| 1129 | + /// falls back to building the row and rendering it: the fusion |
| 1130 | + /// still fires (the list is never consed). |
| 1131 | + fn map_variant(&mut self, g: FnId, n_caps: usize, depth: u32) -> Option<(FnId, bool)> { |
| 1132 | + if let Some(&found) = self.variants.get(&(g, n_caps)) { |
| 1133 | + return Some(found); |
| 1134 | + } |
| 1135 | + let decl = &self.program.fns[g as usize]; |
| 1136 | + if decl.params.len() != n_caps + 1 { |
| 1137 | + return None; |
| 1138 | + } |
| 1139 | + // b, the captures, x. |
| 1140 | + let n_params = (n_caps + 2) as VarId; |
| 1141 | + let (b, x) = (n_caps as VarId, (n_caps + 1) as VarId); |
| 1142 | + let id = (self.program.fns.len() + self.new_fns.len()) as FnId; |
| 1143 | + // Pushed before the translation (a placeholder body, filled in |
| 1144 | + // below): nested and recursive rows find the id in the memo, |
| 1145 | + // and it is final — the translation can generate more. |
| 1146 | + let name = format!("{}$render", self.program.fns[g as usize].name); |
| 1147 | + self.new_fns.push(FnDecl { |
| 1148 | + name, |
| 1149 | + params: (0..n_params).collect(), |
| 1150 | + body: Expr::Panic("louise: a precompile variant escaped its translation".into()), |
| 1151 | + n_vars: n_params, |
| 1152 | + borrowed: Default::default(), |
| 1153 | + span: None, |
| 1154 | + module: None, |
| 1155 | + shapes: Default::default(), |
| 1156 | + fip: false, |
| 1157 | + cpr_arity: None, |
| 1158 | + unbox_sig: None, |
| 1159 | + }); |
| 1160 | + self.variants.insert((g, n_caps), (id, false)); |
| 1161 | + let gbody = self.body_of(g); |
| 1162 | + let translatable = !gbody.has_exit && !self.stack.contains(&g); |
| 1163 | + // Parameters to the step's own variables. |
| 1164 | + let env: HashMap<VarId, Atom> = decl |
| 1165 | + .params |
| 1166 | + .iter() |
| 1167 | + .enumerate() |
| 1168 | + .map(|(i, p)| { |
| 1169 | + let v = if i < n_caps { i as VarId } else { x }; |
| 1170 | + (*p, Atom::Var(v)) |
| 1171 | + }) |
| 1172 | + .collect(); |
| 1173 | + let saved = self.next_var; |
| 1174 | + self.next_var = n_params; |
| 1175 | + let saved_boring = self.boring_out; |
| 1176 | + self.boring_out = true; |
| 1177 | + let gexpr = Rc::new(decl.body.clone()); |
| 1178 | + let mut walk = Walk { |
| 1179 | + frames: vec![ |
| 1180 | + // The step function's own variable space (its |
| 1181 | + // parameters); `g`'s body sits above it, its |
| 1182 | + // parameters mapped to them. |
| 1183 | + Frame { |
| 1184 | + id: self.frame_id(), |
| 1185 | + body: Rc::new(Body::empty()), |
| 1186 | + expr: Rc::new(Expr::Return(Atom::Unit)), |
| 1187 | + env: HashMap::new(), |
| 1188 | + lets: Vec::new(), |
| 1189 | + render_pos: 0, |
| 1190 | + }, |
| 1191 | + Frame { |
| 1192 | + id: self.frame_id(), |
| 1193 | + body: gbody, |
| 1194 | + expr: gexpr, |
| 1195 | + env, |
| 1196 | + lets: Vec::new(), |
| 1197 | + render_pos: 0, |
| 1198 | + }, |
| 1199 | + ], |
| 1200 | + consumed: HashSet::new(), |
| 1201 | + log: Vec::new(), |
| 1202 | + }; |
| 1203 | + let translated = if translatable { |
| 1204 | + self.stack.push(g); |
| 1205 | + let translated = self.translate_body(&mut walk, b, depth + 1); |
| 1206 | + self.stack.pop(); |
| 1207 | + translated |
| 1208 | + } else { |
| 1209 | + Err(()) |
| 1210 | + }; |
| 1211 | + let boring = self.boring_out && translated.is_ok(); |
| 1212 | + self.boring_out = saved_boring; |
| 1213 | + let body = match translated { |
| 1214 | + Ok((out, end)) => rebuild(out.lets, end), |
| 1215 | + Err(()) => { |
| 1216 | + // The fallback: build the row and render it. |
| 1217 | + let t = n_params; |
| 1218 | + let r = t + 1; |
| 1219 | + let mut args: Vec<Atom> = (0..n_caps).map(|i| Atom::Var(i as VarId)).collect(); |
| 1220 | + args.push(Atom::Var(x)); |
| 1221 | + rebuild( |
| 1222 | + vec![ |
| 1223 | + (t, Value::CallFn(g, args), None), |
| 1224 | + ( |
| 1225 | + r, |
| 1226 | + Value::CallFn(self.std.render_into, vec![Atom::Var(t), Atom::Var(b)]), |
| 1227 | + None, |
| 1228 | + ), |
| 1229 | + ], |
| 1230 | + Expr::Return(Atom::Var(r)), |
| 1231 | + ) |
| 1232 | + } |
| 1233 | + }; |
| 1234 | + let n_vars = self.next_var.max(n_params + 2); |
| 1235 | + self.next_var = saved; |
| 1236 | + let slot = &mut self.new_fns[(id as usize) - self.program.fns.len()]; |
| 1237 | + slot.body = body; |
| 1238 | + slot.n_vars = n_vars; |
| 1239 | + let found = (id, boring); |
| 1240 | + self.variants.insert((g, n_caps), found); |
| 1241 | + Some(found) |
| 1242 | + } |
| 1243 | + |
| 1244 | + /// A hole bound to a block (an if/match's value): translate each |
| 1245 | + /// arm to render its tree. The block's contents move to the |
| 1246 | + /// render: the commute rule decides, as for a component call. |
| 1247 | + /// `false` (nothing emitted, consumption rolled back): the caller |
| 1248 | + /// renders the block's value. |
| 1249 | + #[allow(clippy::too_many_arguments)] |
| 1250 | + fn block_hole( |
| 1251 | + &mut self, |
| 1252 | + walk: &mut Walk, |
| 1253 | + fi: usize, |
| 1254 | + v: VarId, |
| 1255 | + b: &Expr, |
| 1256 | + out: &mut Out, |
| 1257 | + cur: &mut VarId, |
| 1258 | + depth: u32, |
| 1259 | + ) -> bool { |
| 1260 | + let mark = walk.mark(); |
| 1261 | + let omark = out.mark(); |
| 1262 | + if !walk.consume(fi, v) { |
| 1263 | + return false; |
| 1264 | + } |
| 1265 | + let saved = self.boring_out; |
| 1266 | + self.boring_out = true; |
| 1267 | + let mut bcur = *cur; |
| 1268 | + let mut body_out = Out::default(); |
| 1269 | + let translated = self.emit_expr(walk, fi, b, &mut body_out, &mut bcur, depth); |
| 1270 | + let boring = self.boring_out; |
| 1271 | + self.boring_out = saved; |
| 1272 | + let Ok(end) = translated else { |
| 1273 | + walk.rollback(mark); |
| 1274 | + out.truncate(omark); |
| 1275 | + return false; |
| 1276 | + }; |
| 1277 | + if !self.commutes(walk, fi, v, boring) { |
| 1278 | + walk.rollback(mark); |
| 1279 | + out.truncate(omark); |
| 1280 | + return false; |
| 1281 | + } |
| 1282 | + self.boring_out &= boring; |
| 1283 | + let blk = self.fresh(); |
| 1284 | + self.step( |
| 1285 | + out, |
| 1286 | + blk, |
| 1287 | + Value::Block(Box::new(rebuild(body_out.lets, end))), |
| 1288 | + ); |
| 1289 | + *cur = blk; |
| 1290 | + true |
| 1291 | + } |
| 1292 | + |
| 1293 | + /// A component call rendered: translate `g`'s body with its |
| 1294 | + /// parameters bound to the call's arguments; fall back to |
| 1295 | + /// `render_into` of the call when the body is not a literal tree, |
| 1296 | + /// or when moving its bindings would not commute (the rule of the |
| 1297 | + /// module documentation). Emits nothing on `FellBack` (the caller |
| 1298 | + /// emits the fallback). |
| 1299 | + #[allow(clippy::too_many_arguments)] |
| 1300 | + fn inline_call( |
| 1301 | + &mut self, |
| 1302 | + walk: &mut Walk, |
| 1303 | + fi: usize, |
| 1304 | + v: VarId, |
| 1305 | + g: FnId, |
| 1306 | + args: &[Atom], |
| 1307 | + out: &mut Out, |
| 1308 | + cur: &mut VarId, |
| 1309 | + depth: u32, |
| 1310 | + ) -> Inline { |
| 1311 | + let decl = &self.program.fns[g as usize]; |
| 1312 | + if decl.params.len() != args.len() |
| 1313 | + || self.expansions == 0 |
| 1314 | + || depth >= MAX_DEPTH |
| 1315 | + || self.stack.contains(&g) |
| 1316 | + { |
| 1317 | + return Inline::FellBack; |
| 1318 | + } |
| 1319 | + let gbody = self.body_of(g); |
| 1320 | + if gbody.has_exit { |
| 1321 | + return Inline::FellBack; |
| 1322 | + } |
| 1323 | + // The arguments, as the bottom frame's atoms. |
| 1324 | + let mut env = HashMap::new(); |
| 1325 | + for (p, a) in decl.params.iter().zip(args.iter()) { |
| 1326 | + let (afi, a) = walk.resolve_from(fi, a); |
| 1327 | + let Some(a) = (match a { |
| 1328 | + Atom::Var(av) => Self::emit_atom(walk, afi, av), |
| 1329 | + a => Some(a), |
| 1330 | + }) else { |
| 1331 | + return Inline::FellBack; |
| 1332 | + }; |
| 1333 | + env.insert(*p, a); |
| 1334 | + } |
| 1335 | + let gexpr = Rc::new(decl.body.clone()); |
| 1336 | + let lets: Vec<VarId> = top_lets(&gexpr); |
| 1337 | + let render_pos = lets.len(); |
| 1338 | + let mark = walk.mark(); |
| 1339 | + let frame_id = self.frame_id(); |
| 1340 | + walk.frames.push(Frame { |
| 1341 | + id: frame_id, |
| 1342 | + body: gbody, |
| 1343 | + expr: gexpr, |
| 1344 | + env, |
| 1345 | + lets, |
| 1346 | + render_pos, |
| 1347 | + }); |
| 1348 | + self.expansions -= 1; |
| 1349 | + self.stack.push(g); |
| 1350 | + let saved_boring = self.boring_out; |
| 1351 | + self.boring_out = true; |
| 1352 | + let translated = self.translate_body(walk, *cur, depth + 1); |
| 1353 | + self.stack.pop(); |
| 1354 | + let boring = self.boring_out; |
| 1355 | + self.boring_out = saved_boring; |
| 1356 | + walk.frames.pop(); |
| 1357 | + let Ok((body_out, end)) = translated else { |
| 1358 | + walk.rollback(mark); |
| 1359 | + return Inline::FellBack; |
| 1360 | + }; |
| 1361 | + // The commute rule: the call's evaluation moves to the render. |
| 1362 | + if !self.commutes(walk, fi, v, boring) || !walk.consume(fi, v) { |
| 1363 | + walk.rollback(mark); |
| 1364 | + return Inline::FellBack; |
| 1365 | + } |
| 1366 | + self.boring_out &= boring; |
| 1367 | + out.append(body_out); |
| 1368 | + match end { |
| 1369 | + Expr::Return(Atom::Var(b)) => *cur = b, |
| 1370 | + // A component whose body is a match: the switch yields the |
| 1371 | + // builder per arm. (A `Panic` end never yields: the site is |
| 1372 | + // unreachable after it, as the call was.) |
| 1373 | + end => { |
| 1374 | + let blk = self.fresh(); |
| 1375 | + self.step(out, blk, Value::Block(Box::new(end))); |
| 1376 | + *cur = blk; |
| 1377 | + } |
| 1378 | + } |
| 1379 | + Inline::Inlined |
| 1380 | + } |
| 1381 | + |
| 1382 | + /// The commute rule for moving the evaluation of `call_var` (in |
| 1383 | + /// frame `fi`) to the render position: fine when what moves is |
| 1384 | + /// boring, or when everything between the two positions is. |
| 1385 | + fn commutes(&self, walk: &Walk, fi: usize, call_var: VarId, moved_boring: bool) -> bool { |
| 1386 | + if moved_boring { |
| 1387 | + return true; |
| 1388 | + } |
| 1389 | + let frame = &walk.frames[fi]; |
| 1390 | + let Some(p) = frame.lets.iter().position(|v| *v == call_var) else { |
| 1391 | + return false; |
| 1392 | + }; |
| 1393 | + frame.lets[p + 1..frame.render_pos].iter().all(|v| { |
| 1394 | + frame |
| 1395 | + .body |
| 1396 | + .bindings |
| 1397 | + .get(v) |
| 1398 | + .is_some_and(|value| self.boring_value(value)) |
| 1399 | + }) |
| 1400 | + } |
| 1401 | + |
| 1402 | + /// Translate the top frame's body: its surviving bindings in order, |
| 1403 | + /// then the appends its tree compiles to. The result: the `let`s, |
| 1404 | + /// and the end — `Return(final builder)`, a `Switch` of such ends, |
| 1405 | + /// or a `Panic`. |
| 1406 | + fn translate_body( |
| 1407 | + &mut self, |
| 1408 | + walk: &mut Walk, |
| 1409 | + mut cur: VarId, |
| 1410 | + depth: u32, |
| 1411 | + ) -> Result<(Out, Expr), ()> { |
| 1412 | + let fi = walk.frames.len() - 1; |
| 1413 | + let expr = walk.frames[fi].expr.clone(); |
| 1414 | + // Pre-assign a fresh variable to every `let`, so the walk can |
| 1415 | + // emit appends referring to what the copy pass binds. (The |
| 1416 | + // consumed ones' go unused.) |
| 1417 | + let mut preassign = Vec::new(); |
| 1418 | + visit_exprs(&expr, &mut |e| { |
| 1419 | + if let Expr::Let(v, _, _, _) = e { |
| 1420 | + preassign.push(*v); |
| 1421 | + } |
| 1422 | + }); |
| 1423 | + for v in preassign { |
| 1424 | + let fresh = self.fresh(); |
| 1425 | + walk.frames[fi].env.entry(v).or_insert(Atom::Var(fresh)); |
| 1426 | + } |
| 1427 | + let mut out = Out::default(); |
| 1428 | + let end = self.emit_expr(walk, fi, &expr, &mut out, &mut cur, depth)?; |
| 1429 | + Ok((out, end)) |
| 1430 | + } |
| 1431 | + |
| 1432 | + /// Emit the chain `e` of frame `fi`: the appends of its end first |
| 1433 | + /// (they decide what is consumed), then its surviving bindings in |
| 1434 | + /// order. Returns the chain's end for the caller to rebuild with. |
| 1435 | + #[allow(clippy::too_many_arguments)] |
| 1436 | + fn emit_expr( |
| 1437 | + &mut self, |
| 1438 | + walk: &mut Walk, |
| 1439 | + fi: usize, |
| 1440 | + e: &Expr, |
| 1441 | + out: &mut Out, |
| 1442 | + cur: &mut VarId, |
| 1443 | + depth: u32, |
| 1444 | + ) -> Result<Expr, ()> { |
| 1445 | + let (lets, end) = split_ref(e); |
| 1446 | + // The end's appends first: they decide what is consumed. |
| 1447 | + let end = match end { |
| 1448 | + Expr::Return(a) => { |
| 1449 | + let mut post = Out::default(); |
| 1450 | + self.element(walk, fi, a, &mut post, cur, depth)?; |
| 1451 | + self.copy_lets(walk, fi, &lets, out)?; |
| 1452 | + out.append(post); |
| 1453 | + return Ok(Expr::Return(Atom::Var(*cur))); |
| 1454 | + } |
| 1455 | + Expr::Panic(msg) => { |
| 1456 | + self.boring_out = false; |
| 1457 | + Expr::Panic(msg.clone()) |
| 1458 | + } |
| 1459 | + Expr::Switch { on, cases, default } => { |
| 1460 | + let on = self.remap_atom(walk, fi, on)?; |
| 1461 | + let mut new_cases = Vec::new(); |
| 1462 | + for (tag, arm) in cases { |
| 1463 | + new_cases.push((*tag, self.emit_arm(walk, fi, arm, *cur, depth)?)); |
| 1464 | + } |
| 1465 | + let default = match default { |
| 1466 | + Some(d) => Some(Box::new(self.emit_arm(walk, fi, d, *cur, depth)?)), |
| 1467 | + None => None, |
| 1468 | + }; |
| 1469 | + Expr::Switch { |
| 1470 | + on, |
| 1471 | + cases: new_cases, |
| 1472 | + default, |
| 1473 | + } |
| 1474 | + } |
| 1475 | + Expr::SwitchLit { on, cases, default } => { |
| 1476 | + let on = self.remap_atom(walk, fi, on)?; |
| 1477 | + let mut new_cases = Vec::new(); |
| 1478 | + for (lit, arm) in cases { |
| 1479 | + new_cases.push((lit.clone(), self.emit_arm(walk, fi, arm, *cur, depth)?)); |
| 1480 | + } |
| 1481 | + Expr::SwitchLit { |
| 1482 | + on, |
| 1483 | + cases: new_cases, |
| 1484 | + default: Box::new(self.emit_arm(walk, fi, default, *cur, depth)?), |
| 1485 | + } |
| 1486 | + } |
| 1487 | + // `has_exit` ruled the body out; `LetN`/`Dup`/… come after |
| 1488 | + // this pass. |
| 1489 | + _ => return Err(()), |
| 1490 | + }; |
| 1491 | + self.copy_lets(walk, fi, &lets, out)?; |
| 1492 | + Ok(end) |
| 1493 | + } |
| 1494 | + |
| 1495 | + /// An arm of a switch end: its own chain, starting from the |
| 1496 | + /// builder before the switch. |
| 1497 | + #[allow(clippy::too_many_arguments)] |
| 1498 | + fn emit_arm( |
| 1499 | + &mut self, |
| 1500 | + walk: &mut Walk, |
| 1501 | + fi: usize, |
| 1502 | + arm: &Expr, |
| 1503 | + cur: VarId, |
| 1504 | + depth: u32, |
| 1505 | + ) -> Result<Expr, ()> { |
| 1506 | + let mut arm_out = Out::default(); |
| 1507 | + let mut arm_cur = cur; |
| 1508 | + let end = self.emit_expr(walk, fi, arm, &mut arm_out, &mut arm_cur, depth)?; |
| 1509 | + Ok(rebuild(arm_out.lets, end)) |
| 1510 | + } |
| 1511 | + |
| 1512 | + /// The chain's surviving bindings, copied in order. |
| 1513 | + fn copy_lets( |
| 1514 | + &mut self, |
| 1515 | + walk: &mut Walk, |
| 1516 | + fi: usize, |
| 1517 | + lets: &[(VarId, &Value, Option<Span>)], |
| 1518 | + out: &mut Out, |
| 1519 | + ) -> Result<(), ()> { |
| 1520 | + for (v, value, span) in lets { |
| 1521 | + if walk.consumed(fi, *v) { |
| 1522 | + continue; |
| 1523 | + } |
| 1524 | + let value = self.remap_value(walk, fi, value)?; |
| 1525 | + self.boring_out &= self.boring_value(&value); |
| 1526 | + let Some(Atom::Var(to)) = walk.frames[fi].env.get(v).cloned() else { |
| 1527 | + return Err(()); |
| 1528 | + }; |
| 1529 | + out.last_chunk = None; |
| 1530 | + out.lets.push((to, value, *span)); |
| 1531 | + } |
| 1532 | + Ok(()) |
| 1533 | + } |
| 1534 | + |
| 1535 | + /// A copied binding's value, its atoms remapped to the bottom |
| 1536 | + /// frame. `Err`: it refers to a consumed construction — the tree |
| 1537 | + /// is observed, the translation aborts. |
| 1538 | + fn remap_value(&mut self, walk: &mut Walk, fi: usize, value: &Value) -> Result<Value, ()> { |
| 1539 | + let mut value = value.clone(); |
| 1540 | + self.remap_atoms_in(walk, fi, &mut value)?; |
| 1541 | + Ok(value) |
| 1542 | + } |
| 1543 | + |
| 1544 | + fn remap_atoms_in(&mut self, walk: &mut Walk, fi: usize, value: &mut Value) -> Result<(), ()> { |
| 1545 | + match value { |
| 1546 | + Value::Block(b) => { |
| 1547 | + **b = self.remap_expr(walk, fi, b)?; |
| 1548 | + Ok(()) |
| 1549 | + } |
| 1550 | + value => remap_atoms(value, &mut |a| self.remap_atom(walk, fi, a)), |
| 1551 | + } |
| 1552 | + } |
| 1553 | + |
| 1554 | + /// A whole expression remapped (a copied binding's block). |
| 1555 | + fn remap_expr(&mut self, walk: &mut Walk, fi: usize, e: &Expr) -> Result<Expr, ()> { |
| 1556 | + let (lets, end) = split_ref(e); |
| 1557 | + let mut out = Vec::new(); |
| 1558 | + for (v, value, span) in lets { |
| 1559 | + if walk.consumed(fi, v) { |
| 1560 | + continue; |
| 1561 | + } |
| 1562 | + let value = self.remap_value(walk, fi, value)?; |
| 1563 | + let Some(Atom::Var(to)) = walk.frames[fi].env.get(&v).cloned() else { |
| 1564 | + return Err(()); |
| 1565 | + }; |
| 1566 | + out.push((to, value, span)); |
| 1567 | + } |
| 1568 | + let end = match end { |
| 1569 | + Expr::Return(a) => Expr::Return(self.remap_atom(walk, fi, a)?), |
| 1570 | + Expr::Exit(a) => Expr::Exit(self.remap_atom(walk, fi, a)?), |
| 1571 | + Expr::Panic(msg) => Expr::Panic(msg.clone()), |
| 1572 | + Expr::Switch { on, cases, default } => Expr::Switch { |
| 1573 | + on: self.remap_atom(walk, fi, on)?, |
| 1574 | + cases: cases |
| 1575 | + .iter() |
| 1576 | + .map(|(t, arm)| Ok((*t, self.remap_expr(walk, fi, arm)?))) |
| 1577 | + .collect::<Result<Vec<_>, ()>>()?, |
| 1578 | + default: match default { |
| 1579 | + Some(d) => Some(Box::new(self.remap_expr(walk, fi, d)?)), |
| 1580 | + None => None, |
| 1581 | + }, |
| 1582 | + }, |
| 1583 | + Expr::SwitchLit { on, cases, default } => Expr::SwitchLit { |
| 1584 | + on: self.remap_atom(walk, fi, on)?, |
| 1585 | + cases: cases |
| 1586 | + .iter() |
| 1587 | + .map(|(l, arm)| Ok((l.clone(), self.remap_expr(walk, fi, arm)?))) |
| 1588 | + .collect::<Result<Vec<_>, ()>>()?, |
| 1589 | + default: Box::new(self.remap_expr(walk, fi, default)?), |
| 1590 | + }, |
| 1591 | + // `LetN`/`Dup`/… come after this pass. |
| 1592 | + _ => return Err(()), |
| 1593 | + }; |
| 1594 | + Ok(rebuild(out, end)) |
| 1595 | + } |
| 1596 | + |
| 1597 | + fn remap_atom(&mut self, walk: &Walk, fi: usize, a: &Atom) -> Result<Atom, ()> { |
| 1598 | + let Atom::Var(v) = a else { |
| 1599 | + return Ok(a.clone()); |
| 1600 | + }; |
| 1601 | + Self::emit_atom(walk, fi, *v).ok_or(()) |
| 1602 | + } |
| 1603 | +} |
| 1604 | + |
| 1605 | +/// The `let` variables of an expression's top chain, in order. |
| 1606 | +fn top_lets(e: &Expr) -> Vec<VarId> { |
| 1607 | + let (lets, _) = split_ref(e); |
| 1608 | + lets.iter().map(|(v, _, _)| *v).collect() |
| 1609 | +} |
| 1610 | + |
| 1611 | +/// `let v = value; rest`, as the chain of its `let`s and the end they |
| 1612 | +/// lead to (a reference: [`split`] takes ownership). |
| 1613 | +#[allow(clippy::type_complexity)] |
| 1614 | +fn split_ref(mut e: &Expr) -> (Vec<(VarId, &Value, Option<Span>)>, &Expr) { |
| 1615 | + let mut lets = Vec::new(); |
| 1616 | + while let Expr::Let(v, value, rest, span) = e { |
| 1617 | + lets.push((*v, &**value, *span)); |
| 1618 | + e = rest; |
| 1619 | + } |
| 1620 | + (lets, e) |
| 1621 | +} |
| 1622 | + |
| 1623 | +/// Rewrite a function's body: the consumed `let`s dropped, each fired |
| 1624 | +/// site's render call replaced by its appends. |
| 1625 | +fn rewrite(e: Expr, dead: &HashSet<VarId>, replacements: &HashMap<VarId, Lets>) -> Expr { |
| 1626 | + let (lets, end) = split(e); |
| 1627 | + let mut out = Vec::new(); |
| 1628 | + for (v, value, span) in lets { |
| 1629 | + if dead.contains(&v) { |
| 1630 | + continue; |
| 1631 | + } |
| 1632 | + if let Some(replacement) = replacements.get(&v) { |
| 1633 | + out.extend(replacement.iter().cloned()); |
| 1634 | + continue; |
| 1635 | + } |
| 1636 | + let value = match value { |
| 1637 | + Value::Block(b) => Value::Block(Box::new(rewrite(*b, dead, replacements))), |
| 1638 | + value => value, |
| 1639 | + }; |
| 1640 | + out.push((v, value, span)); |
| 1641 | + } |
| 1642 | + let end = match end { |
| 1643 | + Expr::Switch { on, cases, default } => Expr::Switch { |
| 1644 | + on, |
| 1645 | + cases: cases |
| 1646 | + .into_iter() |
| 1647 | + .map(|(t, arm)| (t, rewrite(arm, dead, replacements))) |
| 1648 | + .collect(), |
| 1649 | + default: default.map(|d| Box::new(rewrite(*d, dead, replacements))), |
| 1650 | + }, |
| 1651 | + Expr::SwitchLit { on, cases, default } => Expr::SwitchLit { |
| 1652 | + on, |
| 1653 | + cases: cases |
| 1654 | + .into_iter() |
| 1655 | + .map(|(l, arm)| (l, rewrite(arm, dead, replacements))) |
| 1656 | + .collect(), |
| 1657 | + default: Box::new(rewrite(*default, dead, replacements)), |
| 1658 | + }, |
| 1659 | + end => end, |
| 1660 | + }; |
| 1661 | + rebuild(out, end) |
| 1662 | +} |
| 1663 | + |
| 1664 | +/// Map every atom of a value (blocks excepted: the caller remaps |
| 1665 | +/// those). |
| 1666 | +fn remap_atoms(value: &mut Value, f: &mut impl FnMut(&Atom) -> Result<Atom, ()>) -> Result<(), ()> { |
| 1667 | + let mut one = |a: &mut Atom| -> Result<(), ()> { |
| 1668 | + *a = f(a)?; |
| 1669 | + Ok(()) |
| 1670 | + }; |
| 1671 | + match value { |
| 1672 | + Value::Atom(a) => one(a), |
| 1673 | + Value::Call(f2, args) => { |
| 1674 | + one(f2)?; |
| 1675 | + remap_atoms_all(args, f) |
| 1676 | + } |
| 1677 | + Value::CallFn(_, args) | Value::CallExtern(_, args) | Value::Prim(_, args) => { |
| 1678 | + remap_atoms_all(args, f) |
| 1679 | + } |
| 1680 | + Value::Construct { args, .. } | Value::Tuple(args) => remap_atoms_all(args, f), |
| 1681 | + Value::Field(a, _) => one(a), |
| 1682 | + Value::Closure(_, caps) => remap_atoms_all(caps, f), |
| 1683 | + Value::Perform { cap, args, .. } => { |
| 1684 | + one(cap)?; |
| 1685 | + remap_atoms_all(args, f) |
| 1686 | + } |
| 1687 | + Value::Handle { |
| 1688 | + body, ret, clauses, .. |
| 1689 | + } => { |
| 1690 | + one(body)?; |
| 1691 | + if let Some(r) = ret { |
| 1692 | + one(r)?; |
| 1693 | + } |
| 1694 | + remap_atoms_all(clauses, f) |
| 1695 | + } |
| 1696 | + Value::Region { body, .. } => one(body), |
| 1697 | + Value::Defer { body, cleanup } => { |
| 1698 | + one(body)?; |
| 1699 | + one(cleanup) |
| 1700 | + } |
| 1701 | + // Blocks are remapped by the caller; the rest postdate this pass. |
| 1702 | + Value::Block(_) |
| 1703 | + | Value::Reuse { .. } |
| 1704 | + | Value::CtxExtend { .. } |
| 1705 | + | Value::CtxApply { .. } => Err(()), |
| 1706 | + } |
| 1707 | +} |
| 1708 | + |
| 1709 | +fn remap_atoms_all( |
| 1710 | + args: &mut [Atom], |
| 1711 | + f: &mut impl FnMut(&Atom) -> Result<Atom, ()>, |
| 1712 | +) -> Result<(), ()> { |
| 1713 | + for a in args { |
| 1714 | + *a = f(a)?; |
| 1715 | + } |
| 1716 | + Ok(()) |
| 1717 | +} |
| 1718 | + |
| 1719 | +/// The void elements of `std/html.is_void` (pinned by |
| 1720 | +/// `tests/run/html_hoist.lse`). |
| 1721 | +fn is_void(tag: &str) -> bool { |
| 1722 | + matches!( |
| 1723 | + tag, |
| 1724 | + "area" |
| 1725 | + | "base" |
| 1726 | + | "br" |
| 1727 | + | "col" |
| 1728 | + | "embed" |
| 1729 | + | "hr" |
| 1730 | + | "img" |
| 1731 | + | "input" |
| 1732 | + | "link" |
| 1733 | + | "meta" |
| 1734 | + | "source" |
| 1735 | + | "track" |
| 1736 | + | "wbr" |
| 1737 | + ) |
| 1738 | +} |