diff --git a/changes/three-trees-t6u.internal.md b/changes/three-trees-t6u.internal.md new file mode 100644 index 0000000000..9c9aa2a724 --- /dev/null +++ b/changes/three-trees-t6u.internal.md @@ -0,0 +1,3 @@ +- Seal the lowered program in the naming replay: the walk applies the flatten + rules to each statement it takes out of a list, and check mode no longer runs + the flatten pass on the new side. diff --git a/compiler-rust/src/bir/lower/export.rs b/compiler-rust/src/bir/lower/export.rs index cc0d7f20d4..56cb42c69c 100644 --- a/compiler-rust/src/bir/lower/export.rs +++ b/compiler-rust/src/bir/lower/export.rs @@ -2265,6 +2265,10 @@ mod tests { let mut a = a; let mut compiler = LambdaCompiler::new(); let before = compiler.bir_export_oracle(&mut a, root); + // The lowering's statements are flattened by the seal: the legacy + // program is compared after its flatten pass, and the lowering's + // program runs the passes after it, as the gate does. + let before = crate::lambda::js_pass_flatten_and_mark_dead::apply_js_flatten_pass(before); let text = print(&before); assert_eq!(print(&new_before), text, "before the passes"); let after = compiler.bir_passes_oracle(before); diff --git a/compiler-rust/src/bir/lower/ffi_args.rs b/compiler-rust/src/bir/lower/ffi_args.rs index 85e944100d..93f939d4f1 100644 --- a/compiler-rust/src/bir/lower/ffi_args.rs +++ b/compiler-rust/src/bir/lower/ffi_args.rs @@ -847,6 +847,9 @@ mod tests { modules: vec![], side_effect: None, }; + // The seal flattens the lowering's statements in the replay's + // walk: the legacy program is compared after its flatten pass. + let expected = crate::lambda::js_pass_flatten_and_mark_dead::apply_js_flatten_pass(expected); let print = |p: &JsDepsProgram| { crate::js_ir::print_deps_program_with_directives_and_options( p, diff --git a/compiler-rust/src/bir/lower/globals.rs b/compiler-rust/src/bir/lower/globals.rs index 851fb75178..fac455bdfb 100644 --- a/compiler-rust/src/bir/lower/globals.rs +++ b/compiler-rust/src/bir/lower/globals.rs @@ -471,8 +471,11 @@ fn simple_element(js: &B, a: &Pools, idents: &[Ident], item: B::Ref<'_>) /// node of the element it reads, up to the first that is none. A loop /// over the options and blocks that are open, innermost last, each with /// the operand to read next: no recursion, and no allocation for an -/// element that nests at most eight deep (a deeper one spills the stack -/// once). +/// element that nests at most eight deep. The stack is the call's own +/// (a local of eight entries, not a scratch of the walk), so an element +/// that nests deeper allocates once in every call that reads it, and +/// frees it at the call's end. It is called for the elements of a block +/// declaration in a unit that has an underscored global only. fn deep_constant<'r, B: Js>(js: &B, a: &'r Pools, item: B::Ref<'r>, steps: &mut usize) -> bool { let mut open: smallvec::SmallVec<[(B::Ref<'r>, u32); 8]> = smallvec::SmallVec::new(); let mut next = Some(item); diff --git a/compiler-rust/src/bir/lower/mod.rs b/compiler-rust/src/bir/lower/mod.rs index f72a878417..fe72a70f4d 100644 --- a/compiler-rust/src/bir/lower/mod.rs +++ b/compiler-rust/src/bir/lower/mod.rs @@ -16,6 +16,7 @@ mod globals; pub mod js; pub mod js_stmt; pub(crate) mod names; +pub(crate) mod seal; mod expr; mod konst; mod prim; @@ -330,6 +331,9 @@ pub(crate) struct SwitchStats { /// when the pass does not support the unit. pub names_compared: usize, pub names_uncompared: usize, + /// What the seal of the replay's walk rewrote, per rule. + #[serde(flatten)] + pub sealed: seal::Sealed, } /// The decisions of step A (`close::decide`) compared with those of the @@ -847,6 +851,7 @@ impl State<'_, B> { globals::decide(&mut self.arena, &self.idents); let mut printed = crate::emit::Printed::default(); let (replayed, name_imports) = self.replay_names(&mut block, &mut printed); + let sealed = self.names.sealed(); debug_assert_eq!(self.js.stmt_id(&self.arena, &block), root.0, "the root keeps its id through the replay"); let (adopted_nodes, name_log_steps) = self.arena.js_scope.as_ref() .map_or((0, 0), |scope| (scope.names.adopted_nodes, scope.names.steps)); @@ -876,6 +881,7 @@ impl State<'_, B> { name_replay_steps: replayed.steps(), names_compared: 0, names_uncompared: 0, + sealed, }, printed, name_imports, diff --git a/compiler-rust/src/bir/lower/names.rs b/compiler-rust/src/bir/lower/names.rs index 51209ed9d5..454fb65b18 100644 --- a/compiler-rust/src/bir/lower/names.rs +++ b/compiler-rust/src/bir/lower/names.rs @@ -33,6 +33,7 @@ //! names are not printed yet. use super::js::{Found, Js, JsxHead, Pools}; use super::js_stmt::{Below, JsStmt}; +use super::seal::{self, Marks, Mode}; use crate::bir::{Bir, FuncId, ImportId, NodeId, VarId}; use crate::emit::row::{Kind, flag}; use crate::emit::{Printed, Subject, Tables}; @@ -700,6 +701,8 @@ struct Frame { at: u32, /// The scope row to leave when the frame is done, or `ScopeId::NONE`. leave: u32, + /// The seal's part of the frame (`seal::Marks`). + seal: Marks, } /// A statement taken out of its list whose function literals and lists @@ -708,6 +711,9 @@ struct Frame { struct Held { statement: S, kind: Kind, + /// How the seal treats the bodies of its literals and its lists. + literal_mode: Mode, + body_mode: Mode, /// Literals and bodies opened so far. next: u32, first: u32, @@ -741,6 +747,8 @@ pub(crate) struct Scratch { reservation: Vec, /// The spelling of a cached bound's base, reused. spelling: String, + /// The seal's work stack and what it did in the last replay. + seal: seal::Work, } impl Default for Scratch { /// Empty vectors. Cost: O(1), no allocation. @@ -752,6 +760,7 @@ impl Default for Scratch { literals: Vec::new(), reservation: Vec::new(), spelling: String::new(), + seal: seal::Work::default(), } } } @@ -782,7 +791,9 @@ impl Storage { /// storage costs a number of allocations that does not grow with the /// unit (LOWERING_ALLOCATION_SCALING.md lists them). The bounds: one /// staged statement per node, one literal per row, a reservation no - /// longer than the longest free list and its binder, one list entry per + /// longer than the longest free list and its binder, one statement the + /// seal has pending per node (a statement a rule makes holds a node + /// that was there), one list entry per /// import (the reservations of export coercion are pushed where the /// coercion makes them, `State::reserve_name`); for the tables /// (`Tables::size`) one group and one visible name per slot, and one @@ -796,12 +807,19 @@ impl Storage { let longest = log.rows.iter().map(|row| row.free_len as usize).max().unwrap_or(0); let scratch = &mut self.scratch; scratch.staged.reserve_exact(bir.nodes.len().saturating_sub(scratch.staged.len())); + scratch.seal.pending.reserve_exact(bir.nodes.len().saturating_sub(scratch.seal.pending.len())); scratch.literals.reserve_exact((rows - 1).saturating_sub(scratch.literals.len())); scratch.reservation.reserve_exact((longest + 1).saturating_sub(scratch.reservation.len())); self.imports.reserve_exact(imports.saturating_sub(self.imports.len())); let slots = bir.vars.len() + imports; self.tables.size(slots, log.free.len() + rows + slots, rows); } + + /// What the seal did in the last replay. Cost: O(1), a copy of 88 + /// bytes. + pub(crate) fn sealed(&self) -> seal::Sealed { + self.scratch.seal.sealed + } } /// What one replay did. @@ -922,16 +940,23 @@ pub(crate) fn replay( // The literals the descent can find: the closed rows a header names. // When the last is found the descent has nothing left to look for. An // active unit descends every statement for its references to globals. + // Of those, the rows whose literal is released already: the seal + // releases more when it drops a branch that holds one, and the + // difference at the end is `Sealed::seal_dropped_literals`. One read + // a row. let mut unfound = 0; + let mut released = 0; + for (row, info) in log.rows.iter().enumerate().skip(1) { + if info.flags & ScopeRow::CLOSED != 0 && log.scope(info.function) == Some(ScopeId(row as u32)) { + unfound += 1; + released += usize::from(bir.func_owners.get(info.function.index()).copied().flatten().is_none()); + } + } if globals.active { want |= flag::HAS_GLOBAL; - } else { - for (row, info) in log.rows.iter().enumerate().skip(1) { - unfound += u32::from(info.flags & ScopeRow::CLOSED != 0 && log.scope(info.function) == Some(ScopeId(row as u32))); - } - if unfound == 0 { - want = 0; - } + unfound = 0; + } else if unfound == 0 { + want = 0; } if want != 0 { js.reserve_below(bir); @@ -977,12 +1002,16 @@ pub(crate) fn replay( } // The parameters of the functions the printer eta-reduces, read // from the rows: one read per row and per such parameter, no node. + let mut released_now = 0; for (row, info) in log.rows.iter().enumerate().skip(1) { - if info.flags & ScopeRow::CLOSED == 0 - || log.scope(info.function) != Some(ScopeId(row as u32)) - || replay.bir.func_owners.get(info.function.index()).copied().flatten().is_none() - || !replay.eta(*info) - { + if info.flags & ScopeRow::CLOSED == 0 || log.scope(info.function) != Some(ScopeId(row as u32)) { + continue; + } + if replay.bir.func_owners.get(info.function.index()).copied().flatten().is_none() { + released_now += 1; + continue; + } + if !replay.eta(*info) { continue; } for i in 0..replay.bir.function(info.function).params.len() { @@ -993,6 +1022,8 @@ pub(crate) fn replay( } } } + // Only the seal releases a literal during the replay. + replay.scratch.seal.sealed.seal_dropped_literals = released_now - released; } replay.done.unnamed_references = unnamed; let done = replay.done; @@ -1045,51 +1076,128 @@ impl Replay<'_, '_, B> { self.scratch.held.clear(); self.scratch.staged.clear(); self.scratch.literals.clear(); + self.scratch.seal.pending.clear(); + self.scratch.seal.sealed = seal::Sealed::default(); let list = self.js.body(self.bir, root, 0); - self.open(Frame { list, at: 0, leave: ScopeId::NONE.0 }); + self.open(list, 0, ScopeId::NONE.0, Mode::Seal); if self.globals.active { self.globals.enter_list(&mut *self.js, self.bir, self.idents, list); } while let Some(&frame) = self.scratch.frames.last() { + // What the rules made of the frame's last statement is offered + // before the next statement of the list. + if self.scratch.seal.pending.len() > frame.seal.pending as usize { + let seal::Pending { statement, mode, group } = self.scratch.seal.pending.pop().expect("a pending statement"); + let base = index(self.scratch.seal.pending.len()); + if self.seal(statement, mode) && group { + // What the rule made of a grouped part becomes one + // block (`seal::Pending::group`): a frame of its own + // over the statements the rule pushed, with no list. + self.scratch.seal.sealed.seal_groups += 1; + let len = self.js.len(self.bir, frame.list); + self.open(frame.list, len, ScopeId::NONE.0, mode); + let marks = &mut self.scratch.frames.last_mut().expect("the group's frame").seal; + (marks.pending, marks.group) = (base, true); + } + continue; + } let len = self.js.len(self.bir, frame.list); if frame.at < len { self.scratch.frames.last_mut().expect("the frame read").at += 1; - self.done.statements += 1; let statement = self.js.take_at(self.bir, frame.list, frame.at); - self.statement(statement); + self.seal(statement, frame.seal.mode); continue; } self.scratch.frames.pop(); if self.globals.active { self.globals.close(); } + if frame.seal.group { + self.close_group(frame.seal); + continue; + } if frame.leave == QUIET { self.quiet -= 1; } else if frame.leave != ScopeId::NONE.0 { self.tables.leave(); } + let start = frame.seal.staged as usize; + let len = index(self.scratch.staged.len() - start); self.done.moves += len as usize; let Replay { js, bir, scratch, .. } = &mut *self; - let start = scratch.staged.len() - len as usize; let rebuilt = js.list(bir, len, scratch.staged.drain(start..)); if self.scratch.frames.is_empty() { - self.js.set_body(self.bir, root, 0, rebuilt); + if frame.seal.changed { + self.js.set_body_adopting(self.bir, root, 0, rebuilt); + } else { + self.js.set_body(self.bir, root, 0, rebuilt); + } return; } - self.give(rebuilt); + self.give(rebuilt, frame.seal.changed); } } - /// Open the frame of a list; in an active unit the bindings entered - /// from here on are the list's, left when the frame is done. Cost: - /// O(1), one push, two in an active unit. - fn open(&mut self, frame: Frame) { - self.scratch.frames.push(frame); + /// Open the frame of `list`, read from statement `at`, whose + /// statements the walk seals in `mode`; in an active unit the + /// bindings entered from here on are the list's, left when the frame + /// is done. Cost: O(1), one push, two in an active unit. + fn open(&mut self, list: B::L, at: u32, leave: u32, mode: Mode) { + let marks = Marks { + pending: index(self.scratch.seal.pending.len()), + staged: index(self.scratch.staged.len()), + mode, + changed: false, + group: false, + }; + self.scratch.frames.push(Frame { list, at, leave, seal: marks }); if self.globals.active { self.globals.open(); } } + /// Offer `statement`, taken out of a list of `mode` or made by a + /// rule, to the seal (`seal::step`); a statement that is final is + /// reached (`statement`), one step. A statement a rule wrote or + /// replaced marks the innermost frame changed. Returns whether a rule + /// replaced the statement by what it pushed on the work stack. Cost: + /// `seal::step`, then `statement`. + fn seal(&mut self, statement: B::S, mode: Mode) -> bool { + match seal::step(&mut *self.js, &mut *self.bir, statement, mode, &mut self.scratch.seal) { + seal::Outcome::Final { statement, literals, bodies, written } => { + if written { + self.scratch.frames.last_mut().expect("an open list").seal.changed = true; + } + self.done.statements += 1; + self.statement(statement, literals, bodies); + false + } + seal::Outcome::Replaced => { + self.scratch.frames.last_mut().expect("an open list").seal.changed = true; + true + } + } + } + + /// The statements a group frame staged become one statement of the + /// list below it, as the pass's `S::block` makes one of a rule's + /// results: one is itself, none an empty block, more a block over + /// them (it keeps its braces on rows, so no later walk splices it). + /// Cost: one step, and one move per statement. + fn close_group(&mut self, marks: Marks) { + let start = marks.staged as usize; + let len = index(self.scratch.staged.len() - start); + if len == 1 { + return; + } + self.done.moves += len as usize; + self.done.statements += 1; + let Replay { js, bir, scratch, .. } = &mut *self; + let list = js.list(bir, len, scratch.staged.drain(start..)); + let block = js.explicit_block(bir, list); + self.scratch.staged.push(block); + } + /// The header of the literal an entry of `Scratch::literals` stands /// for. Cost: O(1). fn header(&self, entry: u32) -> FuncId { @@ -1097,16 +1205,24 @@ impl Replay<'_, '_, B> { } /// The list a frame rebuilt, given back to the statement it was taken - /// from: a literal's body or one of its lists. Then the statement's next - /// literal or list is opened (`advance`). Cost: O(1), one write, then - /// `advance`. - fn give(&mut self, rebuilt: B::L) { + /// from: a literal's body or one of its lists, as a changed list + /// (`JsStmt::set_body_adopting`) when a rule of the seal replaced one + /// of its statements. Then the statement's next literal or list is + /// opened (`advance`). Cost: O(1), one write, then `advance`; for a + /// changed list one read per statement of it. + fn give(&mut self, rebuilt: B::L, changed: bool) { let held = self.scratch.held.last_mut().expect("a frame's statement"); let slot = held.next - 1; if slot < held.literals { let entry = self.scratch.literals[(held.first + slot) as usize]; let header = self.header(entry); - self.js.set_literal_body(self.bir, header, rebuilt); + if changed { + self.js.set_literal_body_adopting(self.bir, header, rebuilt); + } else { + self.js.set_literal_body(self.bir, header, rebuilt); + } + } else if changed { + self.js.set_body_adopting(self.bir, &mut held.statement, slot - held.literals, rebuilt); } else { self.js.set_body(self.bir, &mut held.statement, slot - held.literals, rebuilt); } @@ -1142,8 +1258,9 @@ impl Replay<'_, '_, B> { self.enter_cases(); } let held = self.scratch.held.last_mut().expect("a held statement"); + let mode = held.body_mode; let list = self.js.body(self.bir, &mut held.statement, body); - self.open(Frame { list, at: 0, leave: ScopeId::NONE.0 }); + self.open(list, 0, ScopeId::NONE.0, mode); if self.globals.active { // A catch variable covers its handler. The // declarations of a list cover it; those of a block @@ -1175,7 +1292,7 @@ impl Replay<'_, '_, B> { /// without one is not walked. Cost: one `Tables::add` per binder, /// `finish` for a range loop, one step per node the descent reads /// and one per literal found, one push. - fn statement(&mut self, mut statement: B::S) { + fn statement(&mut self, mut statement: B::S, literal_mode: Mode, body_mode: Mode) { let kind = self.js.stmt_kind(self.bir, &statement); let quiet = self.quiet != 0; match kind { @@ -1240,9 +1357,15 @@ impl Replay<'_, '_, B> { named += 1; } // Not named, and walked all the same where the - // references to globals are decided. - _ if active => found.push(UNNAMED | header.0), - _ => {} + // references to globals are decided. Outside a quiet + // walk every literal has a closed row (THREE_TREES + // 11.4, "T6r", corrections after the review of the + // thirteenth turn, item 3). + _ if active => { + debug_assert!(quiet, "a function literal without a closed row outside a quiet walk"); + found.push(UNNAMED | header.0); + } + _ => debug_assert!(quiet, "a function literal without a closed row outside a quiet walk"), } false } @@ -1277,7 +1400,7 @@ impl Replay<'_, '_, B> { // start them after the loop variable. self.globals.open_at(cover); } - self.scratch.held.push(Held { statement, kind, next: 0, first: index(first), literals, bodies }); + self.scratch.held.push(Held { statement, kind, literal_mode, body_mode, next: 0, first: index(first), literals, bodies }); self.advance(); } @@ -1392,8 +1515,9 @@ impl Replay<'_, '_, B> { } self.name(self.bir.function_parameter(info.function, i)); } + let mode = self.scratch.held.last().expect("a held statement").literal_mode; let list = self.js.literal_body(self.bir, header); - self.open(Frame { list, at: 0, leave: row }); + self.open(list, 0, row, mode); if self.globals.active { self.enter_function(header, list); } @@ -1410,8 +1534,9 @@ impl Replay<'_, '_, B> { if !self.globals.active { return false; } + let mode = self.scratch.held.last().expect("a held statement").literal_mode; let list = self.js.literal_body(self.bir, header); - self.open(Frame { list, at: 0, leave: QUIET }); + self.open(list, 0, QUIET, mode); self.quiet += 1; self.enter_function(header, list); true @@ -1554,7 +1679,7 @@ mod tests { assert_eq!(std::mem::size_of::(), 16); assert_eq!(std::mem::size_of::(), 12); assert_eq!(std::mem::size_of::(), 8); - assert_eq!(std::mem::size_of::>(), 12); + assert_eq!(std::mem::size_of::>(), 24); assert_eq!(std::mem::size_of::>(), 64); assert_eq!(std::mem::size_of::(), 48); assert_eq!(std::mem::size_of::>(), 24); @@ -1737,6 +1862,80 @@ mod tests { printed.finishes.iter().map(|name| name.to_string()).collect(), ) } + /// `f()`: an expression with an effect. + fn call(&mut self, f: VarId) -> NodeId { + let callee = self.b.new_node(View::Var { var: f }, 0); + let info = self.b.js_info(crate::bir::JsPayload::Call(Default::default())); + self.b.new_node(View::JCall { callee, args: &[], info }, 0) + } + fn seq(&mut self, first: NodeId, second: NodeId) -> NodeId { + self.b.new_node(View::JSeq { first, second }, 0) + } + fn cond(&mut self, condition: NodeId, then_: NodeId, else_: NodeId) -> NodeId { + self.b.new_node(View::JCond { condition, then_, else_ }, 0) + } + fn var(&mut self, var: VarId) -> NodeId { + self.b.new_node(View::Var { var }, 0) + } + /// `{ statements }`: a block statement that stands in a list. + fn braces(&mut self, statements: &[NodeId]) -> NodeId { + self.b.new_node(View::SBlock { statements }, 1) + } + /// `[values]` as a block literal (a tuple). + fn tuple(&mut self, values: &[NodeId]) -> NodeId { + let info = self.b.js_info(crate::bir::JsPayload::Block(crate::lambda::lam_tag_info::TagInfo::Tuple)); + self.b.new_node(View::JBlockLit { values, info }, crate::js_ir::op::MutableFlag::Immutable as u16) + } + /// The unit whose top-level statements are `statements`, as + /// JavaScript, twice: flattened by the pass of the backend in use + /// (the tree exported as built, then `apply_js_flatten_pass`) and + /// sealed by the replay's walk (the tree exported after `replay`). + /// The two texts are equal, and the sealed tree validates. Returns + /// the text, what the seal did and what the replay did. + fn sealed(mut self, statements: &[NodeId]) -> (String, seal::Sealed, Replayed) { + use crate::bir::bridge_j::{Imported, export_js}; + let root = self.block(statements); + self.b.finish_bulk(root); + // The text, and the text after the passes that follow the + // flatten pass (`bir_passes_oracle`, what both sides of the + // gate run). + let print = |imported: &Imported, flatten: bool| { + let mut js = export_js(imported).expect("the tree exports"); + if flatten { + js = crate::lambda::js_pass_flatten_and_mark_dead::apply_js_flatten_pass(js); + } + let text = crate::js_ir::print_deps_program_with_directives_and_options(&js, None, &[], false, false, false); + let js = crate::lambda::lam_compile::LambdaCompiler::new().bir_passes_oracle(js); + (text, crate::js_ir::print_deps_program_with_directives_and_options(&js, None, &[], false, false, false)) + }; + let imported = Imported::from_lowering(self.b, root, self.idents); + let expected = print(&imported, true); + let Imported { arena: mut b, idents, .. } = imported; + let program = Program { imports: &[], reservations: &[], exports: &[], raw: &[] }; + let (mut scratch, mut printed) = (Scratch::default(), Printed::default()); + let replayed = replay(&mut Rows::default(), &mut b, &mut Rows::stmt_from_node(root), &idents, &program, (&mut Tables::default(), &mut scratch), &mut printed); + b.validate(Some(root)).expect("the sealed tree is whole"); + let sealed = scratch.seal.sealed; + let actual = print(&Imported::from_lowering(b, root, idents), false); + assert_eq!(actual.0, expected.0, "the seal against the flatten pass"); + assert_eq!(actual.1, expected.1, "the seal against the flatten pass, after the passes that follow it"); + (actual.0, sealed, replayed) + } + /// The unit whose top-level statements are `statements`, replayed + /// with nothing exported or printed (a tree too deep for the + /// recursive export and flatten pass of the backend in use): the + /// sealed tree validates. Returns the statements of the root list + /// after the walk, what the seal did and what the replay did. + fn sealed_deep(mut self, statements: &[NodeId]) -> (usize, seal::Sealed, Replayed) { + let root = self.block(statements); + self.b.finish_bulk(root); + let program = Program { imports: &[], reservations: &[], exports: &[], raw: &[] }; + let (mut scratch, mut printed) = (Scratch::default(), Printed::default()); + let replayed = replay(&mut Rows::default(), &mut self.b, &mut Rows::stmt_from_node(root), &self.idents, &program, (&mut Tables::default(), &mut scratch), &mut printed); + self.b.validate(Some(root)).expect("the sealed tree is whole"); + let View::SBlock { statements } = self.b.view(root) else { panic!("the root list") }; + (statements.len(), scratch.seal.sealed, replayed) + } /// `let var = [reads]`. fn declare_read(&mut self, var: VarId, reads: &[VarId]) -> NodeId { let value = self.read(reads); @@ -2901,31 +3100,40 @@ mod tests { #[test] fn ten_thousand_nested_lists_move_each_statement_once() { - // `{ v; { v; { v; ... } } }`, `depth` blocks deep, each a list of - // a statement and the next block: the walk keeps one frame an open - // list and one held block a level, takes each statement out of its - // list once and stages it once, whatever the depth (no recursion: - // a recursive walk would not return from 10,000 levels). + // `if (v) { v; if (v) { v; ... } }`, `depth` conditionals deep, + // each list a statement and the next conditional: the walk keeps + // one frame an open list and one held statement a level, takes + // each statement out of its list once and stages it once, whatever + // the depth (no recursion: a recursive walk would not return from + // 10,000 levels). The lists are those of conditionals, which stay + // lists: a block statement in a list is spliced into it by the + // seal (`the_seal_splices_ten_thousand_nested_blocks_into_one_list`). + let guarded = |u: &mut Unit, v: VarId, inner: Option| { + let value = u.read(&[v]); + let effect = u.effect(value); + let then_ = match inner { + Some(inner) => u.block(&[effect, inner]), + None => u.block(&[effect]), + }; + let condition = u.var(v); + u.b.new_node(View::SIf { condition, then_, else_: None }, 0) + }; let run = |depth: usize| { let mut u = Unit::new(); let v = u.local("v"); - let mut block: Option = None; + let mut nested: Option = None; for _ in 0..depth { - let value = u.read(&[v]); - let effect = u.effect(value); - block = Some(match block { - Some(inner) => u.block(&[effect, inner]), - None => u.block(&[effect]), - }); + nested = Some(guarded(&mut u, v, nested)); } let null = u.b.new_node(View::JNull, 0); - let statements = [u.declare(v, null), block.expect("a block")]; + let statements = [u.declare(v, null), nested.expect("a conditional")]; let (names, replayed) = u.names(&statements, &[]); assert_eq!(name(&names, v), Some("v")); replayed }; let (small, large) = (run(1_000), run(10_000)); - // A level: its statement and its block. One move a statement. + // A level: its statement and its conditional. One move a + // statement. assert_eq!(large.statements - small.statements, 2 * 9_000); assert_eq!((small.moves, large.moves), (small.statements, large.statements)); // Every statement is in one list, and no list is walked twice: the @@ -2934,13 +3142,12 @@ mod tests { // A warm walk as deep allocates nothing. let mut u = Unit::new(); let v = u.local("v"); - let mut block = u.block(&[]); + let value = u.read(&[v]); + let mut nested = u.effect(value); for _ in 0..10_000 { - let value = u.read(&[v]); - let effect = u.effect(value); - block = u.block(&[effect, block]); + nested = guarded(&mut u, v, Some(nested)); } - let root = u.block(&[block]); + let root = u.block(&[nested]); let program = Program { imports: &[], reservations: &[], exports: &[], raw: &[] }; let (mut tables, mut scratch, mut printed) = (Tables::default(), Scratch::default(), Printed::default()); let mut rows = Rows::default(); @@ -2950,8 +3157,425 @@ mod tests { assert_eq!(second, first); }); assert_eq!(allocations.count_total, 0, "{allocations:?}"); - // The effects, the blocks below the outermost (the empty one - // among them) and the outermost. + // The effects (the innermost among them) and the conditionals. assert_eq!((first.moves, first.statements), (20_001, 20_001)); } + + // ---- The seal (THREE_TREES 11.4, "T6u: the seal") ---- + + /// The statements of a printed unit: the text without the three empty + /// lines before it and the comment that ends it. + fn statements_of(text: &str) -> &str { + let text = &text[..text.rfind("/*").expect("a printed unit")]; + text.strip_prefix("\n\n\n").unwrap_or(text) + } + + /// One form sealed (`Unit::sealed`: the text is the flatten pass's): + /// the statements printed, and what the seal did. + fn seal_of(build: impl FnOnce(&mut Unit) -> Vec) -> (String, seal::Sealed) { + let mut u = Unit::new(); + let statements = build(&mut u); + let (text, sealed, replayed) = u.sealed(&statements); + assert_eq!(replayed.moves, replayed.statements); + assert_eq!(sealed.seal_dropped_literals, 0); + (statements_of(&text).to_string(), sealed) + } + + /// What the seal did, in the order `(offered, [F1, F2, F3, F4, F5, F6, + /// F7 and F8], dropped, groups)`; no form but the one that says so + /// drops a function literal. + fn did(sealed: seal::Sealed) -> (usize, [usize; 7], usize, usize) { + let s = sealed; + (s.seal_offered, [s.seal_f1, s.seal_f2, s.seal_f3, s.seal_f4, s.seal_f5, s.seal_f6, s.seal_f78], s.seal_dropped, s.seal_groups) + } + + fn one(b: &mut Bir) -> NodeId { + crate::bir::j::plain::int(b, 1) + } + + #[test] + fn f1_a_sequence_used_for_its_effect_is_its_parts_in_the_list() { + // `(f(), g()), h();`: each part a statement of the list the + // sequence stood in, the nested sequence opened in its turn. Five + // statements offered: the sequence, its two parts, the two parts + // of the first. + let (text, sealed) = seal_of(|u| { + let (f, g, h) = (u.local("f"), u.local("g"), u.local("h")); + let (a, b, c) = (u.call(f), u.call(g), u.call(h)); + let inner = u.seq(a, b); + let chain = u.seq(inner, c); + vec![u.effect(chain)] + }); + assert_eq!(text, "f();\n\ng();\n\nh();\n\n"); + assert_eq!(did(sealed), (5, [2, 0, 0, 0, 0, 0, 0], 0, 0)); + // `f(), 1;`: a part with no effect is an empty block in the list + // (the pass's `S::exp`), which prints as the empty line after + // `f();`. It is not dropped: the pass maps the parts of F1 once. + let (text, sealed) = seal_of(|u| { + let f = u.local("f"); + let a = u.call(f); + let one = one(&mut u.b); + let chain = u.seq(a, one); + vec![u.effect(chain)] + }); + assert_eq!(text, "f();\n\n\n"); + assert_eq!(did(sealed), (3, [1, 0, 0, 0, 0, 0, 0], 0, 0)); + // `[f(), g()], h();`: a part that a rule makes several statements + // of is ONE statement of the list, a block that keeps its braces + // (the pass splices one level): the group frame. + let (text, sealed) = seal_of(|u| { + let (f, g, h) = (u.local("f"), u.local("g"), u.local("h")); + let (a, b, c) = (u.call(f), u.call(g), u.call(h)); + let literal = u.tuple(&[a, b]); + let chain = u.seq(literal, c); + vec![u.effect(chain)] + }); + assert_eq!(text, "f();\ng();\n\nh();\n\n"); + assert_eq!(did(sealed), (5, [1, 1, 0, 0, 0, 0, 0], 0, 1)); + } + + #[test] + fn f2_a_block_literal_used_for_its_effect_is_its_elements() { + // `[f(), 1, g()];`: an element a statement, the one with no effect + // an empty block. + let (text, sealed) = seal_of(|u| { + let (f, g) = (u.local("f"), u.local("g")); + let (a, b) = (u.call(f), u.call(g)); + let one = one(&mut u.b); + let literal = u.tuple(&[a, one, b]); + vec![u.effect(literal)] + }); + assert_eq!(text, "f();\n\n\ng();\n\n"); + assert_eq!(did(sealed), (4, [0, 1, 0, 0, 0, 0, 0], 0, 0)); + // `[1];`: nothing is left of the statement. + let (text, sealed) = seal_of(|u| { + let one = one(&mut u.b); + let literal = u.tuple(&[one]); + vec![u.effect(literal)] + }); + assert_eq!(text, ""); + assert_eq!(did(sealed), (1, [0, 1, 0, 0, 0, 0, 0], 1, 0)); + } + + #[test] + fn f3_a_conditional_used_for_its_effect_is_an_if_of_the_branches_with_an_effect() { + // `test ? yes : no;` by which of the three has an effect. + let shape = |yes: bool, no: bool, test: bool| { + let (text, sealed) = seal_of(|u| { + let (f, g, h, c, x) = (u.local("f"), u.local("g"), u.local("h"), u.local("c"), u.local("x")); + let condition = if test { u.call(h) } else { u.var(c) }; + let then_ = if yes { u.call(f) } else { u.var(x) }; + let else_ = if no { u.call(g) } else { u.var(x) }; + let value = u.cond(condition, then_, else_); + vec![u.effect(value)] + }); + (text, did(sealed)) + }; + let f3 = [0, 0, 1, 0, 0, 0, 0]; + // Both branches: the `if`, then each branch offered in its list. + assert_eq!(shape(true, true, false), ("if (c) {\n f();\n} else {\n g();\n}\n\n".to_string(), (3, f3, 0, 0))); + assert_eq!(shape(true, false, false), ("if (c) {\n f();\n}\n\n".to_string(), (2, f3, 0, 0))); + // Only the second: the test negated. + assert_eq!(shape(false, true, false), ("if (!c) {\n g();\n}\n\n".to_string(), (2, f3, 0, 0))); + // Neither, and a test with an effect: the test is the statement. + assert_eq!(shape(false, false, true), ("h();\n\n".to_string(), (1, f3, 0, 0))); + // None of the three: nothing is left. + assert_eq!(shape(false, false, false), (String::new(), (1, f3, 1, 0))); + } + + #[test] + fn f4_an_assignment_of_a_sequence_is_its_head_then_the_assignment() { + // `x = (f(), g());`. No unit of either corpus has the form (the + // lowering writes the head before the assignment where it builds + // one), eleven lowering tests do. + let (text, sealed) = seal_of(|u| { + let (f, g, x) = (u.local("f"), u.local("g"), u.local("x")); + let (a, b) = (u.call(f), u.call(g)); + let value = u.seq(a, b); + let target = u.var(x); + let assignment = u.b.new_node(View::JBin { left: target, right: value }, crate::js_ir::BinOp::Eq as u16); + vec![u.effect(assignment)] + }); + assert_eq!(text, "f();\n\nx = g();\n\n"); + assert_eq!(did(sealed), (3, [0, 0, 0, 1, 0, 0, 0], 0, 0)); + } + + #[test] + fn f5_a_returned_conditional_is_an_if_of_returns() { + // `return c ? (d ? f() : g()) : h();`: the `return` of a branch is + // offered where the walk reaches the `if`'s list, so the nested + // conditional is opened too. + let (text, sealed) = seal_of(|u| { + let (f, g, h, c, d) = (u.local("f"), u.local("g"), u.local("h"), u.local("c"), u.local("d")); + let (a, b, e) = (u.call(f), u.call(g), u.call(h)); + let (outer, inner) = (u.var(c), u.var(d)); + let nested = u.cond(inner, a, b); + let value = u.cond(outer, nested, e); + vec![u.ret(value)] + }); + assert_eq!(text, "if (c) {\n if (d) {\n return f();\n } else {\n return g();\n }\n} else {\n return h();\n}\n\n"); + assert_eq!(did(sealed), (5, [0, 0, 0, 0, 2, 0, 0], 0, 0)); + } + + #[test] + fn f6_a_returned_sequence_is_its_heads_then_the_return() { + // `return ((f(), 1), g()), h();`: the heads are mapped twice by + // the pass, so the head with no effect is dropped, not kept as an + // empty block as F1 alone keeps it. + let (text, sealed) = seal_of(|u| { + let (f, g, h) = (u.local("f"), u.local("g"), u.local("h")); + let (a, b, c) = (u.call(f), u.call(g), u.call(h)); + let one = one(&mut u.b); + let heads = u.seq(a, one); + let heads = u.seq(heads, b); + let value = u.seq(heads, c); + vec![u.ret(value)] + }); + assert_eq!(text, "f();\n\ng();\n\nreturn h();\n\n"); + assert_eq!(did(sealed), (6, [2, 0, 0, 0, 0, 1, 0], 1, 0)); + } + + #[test] + fn f7_and_f8_a_block_in_a_list_is_its_statements_in_the_list() { + // `{ f(); } { {} { g(); h(); } }`: a block of one statement (F7, + // which no lowering test and no unit of either corpus builds: the + // lowering makes a block statement only of more than one), an + // empty block and blocks of several (F8), nested. + let (text, sealed) = seal_of(|u| { + let (f, g, h) = (u.local("f"), u.local("g"), u.local("h")); + let (a, b, c) = (u.call(f), u.call(g), u.call(h)); + let (a, b, c) = (u.effect(a), u.effect(b), u.effect(c)); + let one = u.braces(&[a]); + let empty = u.braces(&[]); + let inner = u.braces(&[b, c]); + let outer = u.braces(&[empty, inner]); + vec![one, outer] + }); + assert_eq!(text, "f();\n\ng();\n\nh();\n\n"); + assert_eq!(did(sealed), (7, [0, 0, 0, 0, 0, 0, 4], 0, 0)); + } + + #[test] + fn the_heads_of_a_returned_sequence_are_sealed_with_their_tests_entered() { + // `((() => { f(), g() })()) ? f() : g()`, alone and as the head of + // a returned sequence. Alone, the pass does not map the test of + // the `if` it writes: the literal's body keeps its sequence. As a + // head of F6 the result is mapped a second time, which enters the + // test: the body is two statements (`Mode::Entered`). + let form = |returned: bool| { + seal_of(|u| { + let (f, g, h) = (u.local("f"), u.local("g"), u.local("h")); + let header = u.header(None, 0); + open(&mut u.b); + let (a, b) = (u.call(f), u.call(g)); + let both = u.seq(a, b); + let body = u.effect(both); + let (literal, _) = u.function(header, &[body]); + let info = u.b.js_info(crate::bir::JsPayload::Call(Default::default())); + let test = u.b.new_node(View::JCall { callee: literal, args: &[], info }, 0); + let (yes, no) = (u.call(f), u.call(g)); + let value = u.cond(test, yes, no); + if returned { + let last = u.call(h); + let value = u.seq(value, last); + vec![u.ret(value)] + } else { + vec![u.effect(value)] + } + }) + }; + let (text, sealed) = form(false); + assert_eq!(text, "if ((() => f(), g())()) {\n f();\n} else {\n g();\n}\n\n"); + assert_eq!(did(sealed), (4, [0, 0, 1, 0, 0, 0, 0], 0, 0)); + let (text, sealed) = form(true); + assert_eq!(text, "if ((() => {\n f();\n g();\n })()) {\n f();\n} else {\n g();\n}\n\nreturn h();\n\n"); + assert_eq!(did(sealed), (8, [1, 0, 1, 0, 0, 1, 0], 0, 0)); + } + + #[test] + fn a_function_literal_in_a_branch_the_seal_drops_is_not_entered() { + // `function F() { c ? (() => [y]) : f(); }`: F3 keeps the branch + // with an effect and drops the literal. The flatten pass drops it + // too, and the text is the pass's. The literal's row was closed + // while the unit was built, so `y` stays in the free list of `F` + // (three entries where the pass, on the flattened program, finds + // `c` and `f`): `F` reserves a name its body no longer reads. + let mut u = Unit::new(); + let (y, c, f, big) = (u.local("y"), u.local("c"), u.local("f"), u.local("F")); + let (dy, dc, df) = (u.declare_read(y, &[]), u.declare_read(c, &[]), u.declare_read(f, &[])); + let outer = u.header(None, 0); + open(&mut u.b); + let inner = u.header(None, 0); + open(&mut u.b); + let read = u.read(&[y]); + let result = u.ret(read); + let (literal, _) = u.function(inner, &[result]); + let (test, call) = (u.var(c), u.call(f)); + let value = u.cond(test, literal, call); + let statement = u.effect(value); + let (function, scope) = u.function(outer, &[statement]); + assert_eq!(u.free(scope).len(), 3); + let declare = u.declare(big, function); + let (text, sealed, replayed) = u.sealed(&[dy, dc, df, declare]); + assert!(text.contains("function F() {\n if (!c) {\n f();\n }\n}\n"), "{text}"); + assert_eq!(did(sealed), (6, [0, 0, 1, 0, 0, 0, 0], 0, 0)); + // The counter check mode reports for the form. + assert_eq!(sealed.seal_dropped_literals, 1); + // One row read (that of `F`), its three free entries and its + // binder reserved; the row of the dropped literal is never read, + // and no reference is left unnamed. + assert_eq!((replayed.scopes, replayed.reserved, replayed.unnamed_references), (1, 4, 0)); + } + + #[test] + fn the_seal_offers_each_statement_once_at_any_width_and_depth() { + // `(((f(), f()), f()), ...);`, `count` calls in one statement: F1 + // opens a sequence once and offers each part once, so `2 * count - + // 1` statements are offered (the sequences and the calls) and the + // work stack is never deeper than the chain. A body that offered a + // statement twice would read twice the number. + let chain = |count: usize| { + let (listed, sealed, replayed) = { + let mut u = Unit::new(); + let f = u.local("f"); + let mut value = u.call(f); + for _ in 1..count { + let next = u.call(f); + value = u.seq(value, next); + } + let statement = u.effect(value); + u.sealed_deep(&[statement]) + }; + assert_eq!((listed, replayed.statements, replayed.moves), (count, count, count)); + (sealed.seal_offered, sealed.seal_f1, replayed.steps()) + }; + let (small, large) = (chain(1_000), chain(10_000)); + assert_eq!((small.0, small.1), (2 * 1_000 - 1, 1_000 - 1)); + assert_eq!((large.0, large.1), (2 * 10_000 - 1, 10_000 - 1)); + assert!(small.2 >= 1_000 && large.2 <= 11 * small.2, "{small:?} {large:?}"); + assert!(small.0 >= 1_000 && large.0 <= 11 * small.0, "{small:?} {large:?}"); + } + + #[test] + fn the_seal_splices_ten_thousand_nested_blocks_into_one_list() { + // `{ f(); { f(); { ... } } }`, `depth` blocks deep: every + // statement ends in the one list, each block is opened once (F8) + // and each statement offered once; no recursion. + let nested = |depth: usize| { + let mut u = Unit::new(); + let f = u.local("f"); + let call = u.call(f); + let mut block = u.effect(call); + for _ in 0..depth { + let call = u.call(f); + let effect = u.effect(call); + block = u.braces(&[effect, block]); + } + let (listed, sealed, replayed) = u.sealed_deep(&[block]); + assert_eq!((listed, replayed.statements, replayed.moves), (depth + 1, depth + 1, depth + 1)); + (sealed.seal_offered, sealed.seal_f78, replayed.steps()) + }; + let (small, large) = (nested(1_000), nested(10_000)); + assert_eq!((small.0, small.1), (2 * 1_000 + 1, 1_000)); + assert_eq!((large.0, large.1), (2 * 10_000 + 1, 10_000)); + assert!(small.2 >= 1_000 && large.2 <= 11 * small.2, "{small:?} {large:?}"); + } + /// The branch of `c ? branch : h()` in four statements: 0 used for its + /// effect, 1 as the head of a returned sequence (`Mode::Entered`, + /// where the pass splices too), 2 returned, 3 returned after a head. + #[test] + fn a_branch_a_rule_rewrites_prints_as_the_pass_prints_it() { + // The lists of the `if` F3 and F5 write. The pass puts what a + // rule makes of a branch into the list as ONE block statement + // (`j.stmt_list(&ifso)`, `j.stmt_list(&[c])`); the seal seals the + // list like any other, so the parts are statements of the list + // itself. The printer writes a block in a list without braces, + // and no pass after the flatten pass reads the difference: each + // shape of a branch, in each of four statements, prints the same + // on both sides, as sealed and after the passes that follow + // (`Unit::sealed`, both judges). THREE_TREES 11.4, "T6u: the + // seal", decision 20. + type Build = fn(&mut Unit, [VarId; 7]) -> NodeId; + let branches: [(&str, Build, [&str; 4]); 9] = [ + ("seq", |u, v| { let (a, b) = (u.call(v[0]), u.call(v[1])); u.seq(a, b) }, + ["if (c) {\n f();\n g();\n} else {\n h();\n}\n\n", "if (c) {\n f();\n g();\n} else {\n h();\n}\n\nreturn k();\n\n", "if (c) {\n f();\n return g();\n} else {\n return h();\n}\n\n", "k();\n\nif (c) {\n f();\n return g();\n} else {\n return h();\n}\n\n"]), + ("seq trivial", |u, v| { let a = u.call(v[0]); let one = one(&mut u.b); u.seq(a, one) }, + ["if (c) {\n f();\n} else {\n h();\n}\n\n", "if (c) {\n f();\n} else {\n h();\n}\n\nreturn k();\n\n", "if (c) {\n f();\n return 1;\n} else {\n return h();\n}\n\n", "k();\n\nif (c) {\n f();\n return 1;\n} else {\n return h();\n}\n\n"]), + ("seq trivial mid", |u, v| { let (a, b) = (u.call(v[0]), u.call(v[1])); let one = one(&mut u.b); let s = u.seq(a, one); u.seq(s, b) }, + ["if (c) {\n f();\n g();\n} else {\n h();\n}\n\n", "if (c) {\n f();\n g();\n} else {\n h();\n}\n\nreturn k();\n\n", "if (c) {\n f();\n return g();\n} else {\n return h();\n}\n\n", "k();\n\nif (c) {\n f();\n return g();\n} else {\n return h();\n}\n\n"]), + ("lit trivial first", |u, v| { let a = u.call(v[0]); let one = one(&mut u.b); u.tuple(&[one, a]) }, + ["if (c) {\n f();\n} else {\n h();\n}\n\n", "if (c) {\n f();\n} else {\n h();\n}\n\nreturn k();\n\n", "if (c) {\n return [\n 1,\n f()\n ];\n} else {\n return h();\n}\n\n", "k();\n\nif (c) {\n return [\n 1,\n f()\n ];\n} else {\n return h();\n}\n\n"]), + ("lit two", |u, v| { let (a, b) = (u.call(v[0]), u.call(v[1])); u.tuple(&[a, b]) }, + ["if (c) {\n f();\n g();\n} else {\n h();\n}\n\n", "if (c) {\n f();\n g();\n} else {\n h();\n}\n\nreturn k();\n\n", "if (c) {\n return [\n f(),\n g()\n ];\n} else {\n return h();\n}\n\n", "k();\n\nif (c) {\n return [\n f(),\n g()\n ];\n} else {\n return h();\n}\n\n"]), + ("assign seq", |u, v| { let (a, b) = (u.call(v[0]), u.call(v[1])); let value = u.seq(a, b); let target = u.var(v[5]); u.b.new_node(View::JBin { left: target, right: value }, crate::js_ir::BinOp::Eq as u16) }, + ["if (c) {\n f();\n x = g();\n} else {\n h();\n}\n\n", "if (c) {\n f();\n x = g();\n} else {\n h();\n}\n\nreturn k();\n\n", "if (c) {\n return x = (f(), g());\n} else {\n return h();\n}\n\n", "k();\n\nif (c) {\n return x = (f(), g());\n} else {\n return h();\n}\n\n"]), + ("cond", |u, v| { let (a, b, d) = (u.call(v[0]), u.call(v[1]), u.var(v[4])); u.cond(d, a, b) }, + ["if (c) {\n if (d) {\n f();\n } else {\n g();\n }\n} else {\n h();\n}\n\n", "if (c) {\n if (d) {\n f();\n } else {\n g();\n }\n} else {\n h();\n}\n\nreturn k();\n\n", "if (c) {\n if (d) {\n return f();\n } else {\n return g();\n }\n} else {\n return h();\n}\n\n", "k();\n\nif (c) {\n if (d) {\n return f();\n } else {\n return g();\n }\n} else {\n return h();\n}\n\n"]), + ("seq of lit", |u, v| { let (a, b, c) = (u.call(v[0]), u.call(v[1]), u.call(v[6])); let l = u.tuple(&[a, b]); u.seq(l, c) }, + ["if (c) {\n f();\n g();\n k();\n} else {\n h();\n}\n\n", "if (c) {\n f();\n g();\n k();\n} else {\n h();\n}\n\nreturn k();\n\n", "if (c) {\n f();\n g();\n return k();\n} else {\n return h();\n}\n\n", "k();\n\nif (c) {\n f();\n g();\n return k();\n} else {\n return h();\n}\n\n"]), + ("seq of cond", |u, v| { let (a, b, c, d) = (u.call(v[0]), u.call(v[1]), u.call(v[6]), u.var(v[4])); let k = u.cond(d, a, b); u.seq(k, c) }, + ["if (c) {\n if (d) {\n f();\n } else {\n g();\n }\n k();\n} else {\n h();\n}\n\n", "if (c) {\n if (d) {\n f();\n } else {\n g();\n }\n k();\n} else {\n h();\n}\n\nreturn k();\n\n", "if (c) {\n if (d) {\n f();\n } else {\n g();\n }\n return k();\n} else {\n return h();\n}\n\n", "k();\n\nif (c) {\n if (d) {\n f();\n } else {\n g();\n }\n return k();\n} else {\n return h();\n}\n\n"]), + ]; + for (name, build, expected) in branches { + for (form, expected) in expected.into_iter().enumerate() { + let (text, _) = seal_of(|u| { + let v = [u.local("f"), u.local("g"), u.local("h"), u.local("c"), u.local("d"), u.local("x"), u.local("k")]; + let branch = build(u, v); + let (test, other) = (u.var(v[3]), u.call(v[2])); + let value = u.cond(test, branch, other); + match form { + 0 => vec![u.effect(value)], + 1 => { + let last = u.call(v[6]); + let value = u.seq(value, last); + vec![u.ret(value)] + } + 2 => vec![u.ret(value)], + _ => { + let first = u.call(v[6]); + let value = u.seq(first, value); + vec![u.ret(value)] + } + } + }); + assert_eq!(text, expected, "{name}, statement {form}"); + } + } + } + /// The statement a rule writes for a located conditional has the + /// conditional's location: the `if` of F3 and of F5, and the test + /// that is left alone when neither branch of an F3 has an effect. + #[test] + fn the_statement_written_for_a_located_conditional_has_its_location() { + use crate::bir::NodeFlags; + use crate::bir::lower::js::Js; + let mut locations = crate::lambda::LamLocTable::located(Default::default()); + let loc = locations.intern(crate::location::Location::new(Default::default(), 4, 12)); + for (form, kind) in [(0, crate::bir::Op::SIf), (1, crate::bir::Op::SIf), (2, crate::bir::Op::SExp)] { + for located in [true, false] { + let mut u = Unit::new(); + let (f, g, c, x) = (u.local("f"), u.local("g"), u.local("c"), u.local("x")); + let (yes, no, test) = match form { + 2 => (u.var(x), u.var(x), u.call(c)), + _ => (u.call(f), u.call(g), u.var(c)), + }; + let value = u.cond(test, yes, no); + if located { + let mut value = Rows::from_node(value); + Rows::default().locate(&mut u.b, &mut value, loc); + } + let statement = if form == 1 { u.ret(value) } else { u.effect(value) }; + let root = u.block(&[statement]); + u.b.finish_bulk(root); + let program = Program { imports: &[], reservations: &[], exports: &[], raw: &[] }; + replay(&mut Rows::default(), &mut u.b, &mut Rows::stmt_from_node(root), &u.idents, &program, (&mut Tables::default(), &mut Scratch::default()), &mut Printed::default()); + u.b.validate(Some(root)).expect("the sealed tree is whole"); + let View::SBlock { statements } = u.b.view(root) else { panic!("the root list") }; + let written = statements[0]; + assert_eq!(u.b.node(written).op(), kind); + assert_eq!(u.b.node(written).flags().contains(NodeFlags::JS_LOC_PRESENT), located); + assert_eq!(u.b.cold(written).map(|cold| cold.loc), located.then_some(loc)); + } + } + } } diff --git a/compiler-rust/src/bir/lower/oracle_tests.rs b/compiler-rust/src/bir/lower/oracle_tests.rs index 92868e23b4..34b3c38136 100644 --- a/compiler-rust/src/bir/lower/oracle_tests.rs +++ b/compiler-rust/src/bir/lower/oracle_tests.rs @@ -117,6 +117,11 @@ fn compare_oracle(mut arena: LamArena, root: Lam, resolver: Option<&crate::js_ir modules: vec![], side_effect: None, }; + // The seal flattens the lowering's statements in the replay's + // walk, so the legacy program is compared after its flatten + // pass. The lowering's program is not given to that pass: a + // second run of it splices the blocks its first run leaves. + let expected = crate::lambda::js_pass_flatten_and_mark_dead::apply_js_flatten_pass(expected); for preserve in [false, true] { let print = |p: &JsDepsProgram| { crate::js_ir::print_deps_program_with_directives_and_options( @@ -1021,7 +1026,6 @@ fn export_coercion_consumes_the_export_tuple_occurrence() { // itself, so `built` is the count the tail-call pass reads. use crate::lambda::{LamLoc, TagInfo}; use crate::lambda::lam_primitive::{Mutable, Primitive}; - use crate::lambda::js_pass_flatten_and_mark_dead::apply_js_flatten_pass; use crate::lambda::js_pass_external_shadow::apply_external_shadow_pass; use crate::lambda::js_pass_tailcall_inline::UseCounts; use crate::bir::shadow::LowerCheck; @@ -1043,7 +1047,7 @@ fn export_coercion_consumes_the_export_tuple_occurrence() { let mut compiler = LambdaCompiler::new(); let (_, check) = compiler.compile_deps_program_with_lower_check::(a, root, Default::default()); let Some(LowerCheck::Supported(pair)) = check else { panic!("supported export tuple") }; - let legacy = apply_external_shadow_pass(apply_js_flatten_pass(pair.before[0].clone())); + let legacy = apply_external_shadow_pass(pair.before[0].clone()); let mut counts = UseCounts::default(); crate::js_ir::walk::walk_block(&mut counts, &legacy.program.arena, &legacy.program.block); assert_eq!(counts.counts.get(&f).copied().unwrap_or(0), 0); @@ -1194,12 +1198,11 @@ fn flattening_after_a_site_in_a_returned_conditional_was_spliced_maps_its_predic } /// Step A's decisions for one Lambda (not simplified first) against the -/// legacy tail-call pass on the same program after P1 and P2: the comparison +/// legacy tail-call pass on the same program, sealed, after P2: the comparison /// counters, and `(name, status, inline, built)` per decided declaration. fn step_a(build: impl Fn(&mut LamArena) -> Lam) -> (DecisionStats, Vec<(String, crate::js_ir::op::UsedStats, bool, u32)>) { use crate::js_ir::op::UsedStats; use crate::lambda::js_pass_external_shadow::apply_external_shadow_pass as shadow; - use crate::lambda::js_pass_flatten_and_mark_dead::apply_js_flatten_pass as flatten; let mut a = LamArena::new(); let root = build(&mut a); let input = bridge::import_lambda(&a, root).unwrap(); @@ -1207,7 +1210,7 @@ fn step_a(build: impl Fn(&mut LamArena) -> Lam) -> (DecisionStats, Vec<(String, let mut state = State::new(input); let probed = state.probe(Cx::value(), source_root).unwrap(); let lowered = state.complete(Cx::value(), probed); - let program = shadow(flatten(bridge_j::export_js(&lowered.program).unwrap())); + let program = shadow(bridge_j::export_js(&lowered.program).unwrap()); let scope = lowered.program.arena.js_scope.as_ref().unwrap(); let decisions: Vec<_> = scope.decisions.iter().map(|decision| (lowered.program.idents[decision.var.index()], *decision)).collect(); let stats = crate::bir::shadow::compare_decisions(&decisions, &program.program); @@ -1441,7 +1444,6 @@ fn a_copied_function_doubles_the_legacy_count_of_the_variables_declared_inside_i use crate::js_ir::op::UsedStats; use crate::lambda::LamLoc; use crate::lambda::js_pass_external_shadow::apply_external_shadow_pass as shadow; - use crate::lambda::js_pass_flatten_and_mark_dead::apply_js_flatten_pass as flatten; let mut a = LamArena::new(); let (g, p) = (Ident::new("g", 10, IdentFlags::NONE), Ident::new("p", 11, IdentFlags::NONE)); let (ext, read) = (a.var(Ident::new("ext", 13, IdentFlags::NONE)), a.var(p)); @@ -1473,7 +1475,7 @@ fn a_copied_function_doubles_the_legacy_count_of_the_variables_declared_inside_i assert_eq!(decisions.len(), 1); assert_eq!((decisions[0].1.status(), decisions[0].1.inline(), decisions[0].1.built()), (UsedStats::OncePure as u32, true, 1)); // The legacy pass on the same program: `g` is used twice, no candidate. - let program = shadow(flatten(bridge_j::export_js(&lowered.program).unwrap())); + let program = shadow(bridge_j::export_js(&lowered.program).unwrap()); let legacy = crate::lambda::js_pass_tailcall_inline::decisions(&program.program); assert_eq!(legacy[&g], (UsedStats::Used, 2, false)); let stats = crate::bir::shadow::compare_decisions(&decisions, &program.program); @@ -1591,8 +1593,10 @@ fn cached_external_templates_keep_fresh_binders_and_import_once() { /// The new side of the gate on the function `build` gives, bound to an /// exported `run`: lowered, the references the lowering marked written as /// `globalThis.name` (`bridge_j::qualify`), then the legacy passes `order` -/// names (as `legacy_text`), printed. `order` never holds pass 2 here: the -/// new side runs no external-shadow pass (THREE_TREES 11.4, "T5 design"). +/// names (as `legacy_text`), printed. `order` never holds pass 1 or pass 2 +/// here: the new side's statements are flattened by the seal (THREE_TREES +/// 11.4, "T6u: the seal") and it runs no external-shadow pass ("T5 +/// design"). fn new_text(build: impl Fn(&mut LamArena) -> Lam, resolver: Option<&crate::js_ir::ModulePathResolver>, order: &[u8]) -> (String, usize) { new_text_assigning(build, resolver, order, &Default::default()) } @@ -1600,7 +1604,6 @@ fn new_text(build: impl Fn(&mut LamArena) -> Lam, resolver: Option<&crate::js_ir /// `new_text` with `assignable` given to P3 and P5, as check mode gives the /// new side the backend in use's set (`finish_flattened_output`). fn new_text_assigning(build: impl Fn(&mut LamArena) -> Lam, resolver: Option<&crate::js_ir::ModulePathResolver>, order: &[u8], assignable: &ahash::AHashSet) -> (String, usize) { - use crate::lambda::js_pass_flatten_and_mark_dead::apply_js_flatten_pass as flatten; let mut a = LamArena::new(); let root = build(&mut a); let exported = Ident::new("run", 900, IdentFlags::NONE); @@ -1623,7 +1626,6 @@ fn new_text_assigning(build: impl Fn(&mut LamArena) -> Lam, resolver: Option<&cr let mut program = JsDepsProgram { program: JsProgram::new_in(program.program.block, vec![exported], program.program.arena), modules: vec![], side_effect: None }; for pass in order { program = match pass { - 1 => flatten(program), 3 => crate::lambda::js_pass_tailcall_inline::apply_js_tailcall_inline_pass(program, assignable), 4 => crate::lambda::js_pass_record_rest::apply_js_record_rest_pass(program), 5 => crate::lambda::js_pass_flatten_and_mark_dead::apply_js_flatten_and_mark_dead_pass(program, assignable, false), @@ -1639,8 +1641,8 @@ fn new_text_assigning(build: impl Fn(&mut LamArena) -> Lam, resolver: Option<&cr /// and after all passes. Returns the final text and the number of /// references the lowering marked. fn shadow_rule(build: impl Fn(&mut LamArena) -> Lam + Copy) -> (String, usize) { - assert_eq!(new_text(build, None, &[1]).0, legacy_text(build, &[1, 2])); - let (text, marked) = new_text(build, None, &[1, 3, 4, 5, 6]); + assert_eq!(new_text(build, None, &[]).0, legacy_text(build, &[1, 2])); + let (text, marked) = new_text(build, None, &[3, 4, 5, 6]); assert_eq!(text, legacy_text(build, &[1, 2, 3, 4, 5, 6])); (text, marked) } @@ -1657,7 +1659,7 @@ fn ext_call(a: &mut LamArena, args: &[Lam]) -> Lam { #[test] fn the_lowering_decides_the_shadowed_global_the_tail_call_pass_would_hide() { // THREE_TREES.md 11.4, "T4c design" (c), first counterexample, on the - // new side: lowered, then P1, P3, P4, P5, P6 and no P2. The parameter + // new side: lowered and sealed, then P3, P4, P5, P6 and no P2. The parameter // `location` is around the reference when the lowering decides, so the // reference is qualified although P3 then removes the parameter. use crate::lambda::LamLoc; @@ -1672,7 +1674,7 @@ fn the_lowering_decides_the_shadowed_global_the_tail_call_pass_would_hide() { let inner = a.let_(LetKind::Strict, g, function, applied); a.function_(1, &[arg], inner, Default::default(), LamLoc::NONE) }; - let (text, marked) = new_text(build, None, &[1, 3, 4, 5, 6]); + let (text, marked) = new_text(build, None, &[3, 4, 5, 6]); assert_eq!(text, "\n\n\nfunction run(a) {\n return ext(a, globalThis.location);\n}\n\nexport {\n run,\n}\n/* No side effect */\n"); assert_eq!(marked, 1); assert_eq!(text, legacy_text(build, &[1, 2, 3, 4, 5, 6])); @@ -1835,7 +1837,7 @@ fn an_imported_module_shadows_the_global_of_its_name_everywhere() { let body = ext_call(a, &[field, global]); a.function_(0, &[], body, Default::default(), LamLoc::NONE) }; - let (text, marked) = new_text(build, Some(&resolver), &[1, 3, 4, 5, 6]); + let (text, marked) = new_text(build, Some(&resolver), &[3, 4, 5, 6]); assert_eq!(marked, 1); assert!(text.contains("return ext(Other.run, globalThis.Other);"), "{text}"); } @@ -1866,7 +1868,7 @@ fn a_module_whose_only_reference_the_flatten_pass_drops_still_shadows_the_global let body = a.seq_raw(ignored, result); a.function_(1, &[c], body, Default::default(), LamLoc::NONE) }; - let (new, marked) = new_text(build, Some(&resolver), &[1, 3, 4, 5, 6]); + let (new, marked) = new_text(build, Some(&resolver), &[3, 4, 5, 6]); let legacy = legacy_text(build, &[1, 2, 3, 4, 5, 6]); assert_eq!(marked, 1); // The new side: qualified. @@ -2481,11 +2483,11 @@ fn the_naming_log_agrees_on_a_closure_dropped_before_the_function_around_it_clos names_agree(a, root, None, false); } -/// The new side, lowered and run through P1, P3, P4, P5 and P6, against the +/// The new side, lowered, sealed and run through P3, P4, P5 and P6, against the /// backend in use, which runs P2 after P5 (`finish_flattened_output`: /// P1, P3, P4, P5, P2, P6). Returns the text. fn shadow_after_substitution(build: impl Fn(&mut LamArena) -> Lam + Copy) -> String { - let (text, _) = new_text(build, None, &[1, 3, 4, 5, 6]); + let (text, _) = new_text(build, None, &[3, 4, 5, 6]); assert_eq!(text, legacy_text(build, &[1, 3, 4, 5, 2, 6])); text } @@ -2552,7 +2554,7 @@ fn an_assigned_element_the_substitution_pass_binds_shadows_the_global() { a.function_(0, &[], variable, Default::default(), LamLoc::NONE) }; let assignable = std::iter::once(x).collect(); - let (text, _) = new_text_assigning(build, None, &[1, 3, 4, 5, 6], &assignable); + let (text, _) = new_text_assigning(build, None, &[3, 4, 5, 6], &assignable); assert_eq!(text, legacy_text_assigning(build, &[1, 3, 4, 5, 2, 6], &assignable)); assert!(text.contains(" let t_0 = x;\n"), "{text}"); assert!(text.contains("ext(t_0, globalThis.t_0)"), "{text}"); @@ -2874,3 +2876,84 @@ fn the_decision_allocates_the_same_at_a_thousand_and_at_ten_thousand_bindings_an assert_eq!(more[0], more[1], "the allocations of the decision rise with the unit"); } } + +/// `run = c => { let location = ext(); return c ? ext() : +/// ext(location) }`: the seal's F5 writes the returned conditional as an +/// `if`, so the reference to the global stands in a list of its own when +/// the walk decides it. That list binds nothing, and the declaration of +/// the function's list covers it as it covered the `return`: the +/// reference is qualified, as the backend in use qualifies it after its +/// flatten pass. +#[test] +fn a_global_in_a_branch_the_seal_makes_a_list_of_is_covered_by_the_list_around_it() { + use crate::lambda::LamLoc; + let build = |a: &mut LamArena| { + let (c, local) = (Ident::new("c", 12, IdentFlags::NONE), Ident::new("location", 14, IdentFlags::NONE)); + let global = js_global(a, "location"); + let yes = ext_call(a, &[global]); + let read = a.var(local); + let no = ext_call(a, &[read]); + let test = a.var(c); + let chosen = a.if_(test, yes, no); + let value = ext_call(a, &[]); + let body = a.let_(LetKind::Strict, local, value, chosen); + a.function_(1, &[c], body, Default::default(), LamLoc::NONE) + }; + // The lowering writes one `return` of a conditional: the `if` is the + // seal's. + assert!(legacy_text(build, &[]).contains(" return c ? ext(location) : ext(location$1);\n"), "{}", legacy_text(build, &[])); + let (text, marked) = shadow_rule(build); + assert_eq!(marked, 1); + assert!(text.contains(" if (c) {\n return ext(globalThis.location);\n } else {\n return ext(location);\n }\n"), "{text}"); +} + +/// `run = c => { let location = ext(); ignore(c ? ext() +/// : ext(location)); return 3 }`: the same for the seal's F3, which writes +/// a conditional used for its effect as an `if`. +#[test] +fn a_global_in_a_branch_of_a_conditional_used_for_its_effect_is_covered_by_the_list_around_it() { + use crate::lambda::LamLoc; + use crate::lambda::lam_primitive::Primitive; + let build = |a: &mut LamArena| { + let (c, local) = (Ident::new("c", 12, IdentFlags::NONE), Ident::new("location", 14, IdentFlags::NONE)); + let global = js_global(a, "location"); + let yes = ext_call(a, &[global]); + let read = a.var(local); + let no = ext_call(a, &[read]); + let test = a.var(c); + let chosen = a.if_(test, yes, no); + let ignored = a.prim_raw(Primitive::Pignore, &[chosen], LamLoc::NONE); + let three = a.const_(C::Int { i: 3, comment: None }); + let rest = a.seq_raw(ignored, three); + let value = ext_call(a, &[]); + let body = a.let_(LetKind::Strict, local, value, rest); + a.function_(1, &[c], body, Default::default(), LamLoc::NONE) + }; + assert!(legacy_text(build, &[]).contains(" c ? ext(location) : ext(location$1);\n"), "{}", legacy_text(build, &[])); + let (text, marked) = shadow_rule(build); + assert_eq!(marked, 1); + assert!(text.contains(" if (c) {\n ext(globalThis.location);\n } else {\n ext(location);\n }\n return 3;\n"), "{text}"); +} + +/// `min(2, 3)`, `max(2, 3)` and `min(7, 3)`, located, in every context: +/// the primitive of two literals compiles to the conditional `2 < 3 ? 2 : +/// 3`, which carries the primitive's location on both sides (C:1930, +/// `prim.rs`). Returned it is the conditional of an F5: the `if` the pass +/// writes takes the conditional's location (`j.expr_loc(expr)`), and so +/// does the seal's. The mappings are compared (`compare_mapped`); a seal +/// that leaves the `if` without the location gives no mapping where the +/// pass gives one. +#[test] +fn a_located_conditional_gives_its_location_to_the_if_the_seal_writes() { + use crate::lambda::LamLocTable; + use crate::lambda::lam_primitive::Primitive; + for (primitive, both) in [(Primitive::Pintmin, false), (Primitive::Pintmax, false), (Primitive::Pintmin, true)] { + let mut locations = LamLocTable::located(Default::default()); + let loc = locations.intern(crate::location::Location::new(Default::default(), 4, 12)); + let mut a = LamArena::new(); + let x = a.const_(C::Int { i: if both { 7 } else { 2 }, comment: None }); + let other = a.const_(C::Int { i: 3, comment: None }); + let root = a.prim_raw(primitive, &[x, other], loc); + compare_mapped(a, root, &locations); + } +} diff --git a/compiler-rust/src/bir/lower/seal.rs b/compiler-rust/src/bir/lower/seal.rs new file mode 100644 index 0000000000..00938b429b --- /dev/null +++ b/compiler-rust/src/bir/lower/seal.rs @@ -0,0 +1,433 @@ +//! The seal (THREE_TREES 11.4, "T6 design" (e) and "T6u: the seal"): the +//! flatten rules F1 to F8, applied by the naming replay's walk to each +//! statement it takes out of a list, before the statement is named. +//! +//! The rules are those of the backend in use (`Flatten::statement` and +//! `Flatten::block_items` in `lambda/js_pass_flatten_and_mark_dead.rs`), +//! written once over the interface. The replay calls [`step`] with a +//! statement in hand; what a rule makes is pushed on [`Work::pending`], +//! the work stack of the replay's scratch, and offered to the rules again +//! when the replay pops it. A statement no rule applies to is final: the +//! replay names and stages it. Nothing recurses, and nothing is allocated +//! once the work stack has its capacity. +//! +//! A rule reads the statement in hand ([`JsStmt::stmt_kind`], +//! [`JsStmt::value_of`]) and the kind, the `aux` and the flags of its +//! value's node and of that node's operands ([`Js::kind`], [`Js::aux`], +//! [`Js::has`], [`Js::operand`]): O(1) each, and no node is found from an +//! id. +use super::js::{Js, Pools}; +use super::js_stmt::JsStmt; +use crate::emit::row::{Kind, flag}; +use crate::lambda::LamLoc; + +/// What the walk does to the statements of a list (and of the lists and +/// literals below it). One byte. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Mode { + /// The rules are not applied: the body of a function literal that + /// stands in the test of an `if` F3 or F5 wrote, which the pass does + /// not enter, and a statement that is final as a rule made it. + Off, + /// The rules are applied once. + Seal, + /// The rules are applied, and the test of an `if` F3 or F5 writes is + /// entered: the heads of an F6, which the pass maps a second time + /// (`map_statement_children` of its block), and everything below + /// them. + Entered, +} + +/// A statement the rules made, waiting to be offered to them again. +/// `group`: it is a part of a sequence or an element of a block literal +/// in a list sealed once, so what a rule makes of it stays one block +/// statement (the pass's F1, F2 and F4 splice their results one level +/// only, and the printer writes a block's statements without the empty +/// lines it puts between those of the top level). 8 bytes with the +/// statement of rows. +pub(crate) struct Pending { + pub(crate) statement: S, + pub(crate) mode: Mode, + pub(crate) group: bool, +} + +/// The seal's part of one open list of the replay, kept in the list's +/// frame: where its pending and its staged statements start, its mode, +/// and whether a rule replaced one of its statements (the list is then +/// put back with [`JsStmt::set_body_adopting`]). `group`: the frame is no +/// list but the statements a rule made of a grouped part +/// ([`Pending::group`]), which become one block when it closes. 12 +/// bytes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Marks { + pub(crate) pending: u32, + pub(crate) staged: u32, + pub(crate) mode: Mode, + pub(crate) changed: bool, + pub(crate) group: bool, +} + +/// What the seal did in one unit, per rule. Check mode reports it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize)] +pub(crate) struct Sealed { + /// Statements offered to the rules: taken out of a list, or popped + /// from the work stack. One step each. + pub seal_offered: usize, + pub seal_f1: usize, + pub seal_f2: usize, + pub seal_f3: usize, + pub seal_f4: usize, + pub seal_f5: usize, + pub seal_f6: usize, + /// F7 and F8: block statements spliced into the list they stand in. + pub seal_f78: usize, + /// Statements the rules dropped: a part without effect, an `Exp` of a + /// conditional with nothing left. + pub seal_dropped: usize, + /// Grouped parts a rule rewrote, each made one block statement + /// ([`Pending::group`]). + pub seal_groups: usize, + /// Function literals released during the replay: those of a branch + /// without effect that F3 dropped, and the literals inside them. The + /// rows around such a literal keep its free entries, so the replay + /// reserves names the sealed program does not read (THREE_TREES 11.4, + /// "T6u: the seal", decision 12). Counted by the replay from the + /// scope rows, before and after its walk. + pub seal_dropped_literals: usize, +} + +/// The seal's storage in the replay's scratch, reused between units. +pub(crate) struct Work { + pub(crate) pending: Vec>, + pub(crate) sealed: Sealed, +} +impl Default for Work { + /// An empty stack. Cost: O(1), no allocation. + fn default() -> Self { + Self { pending: Vec::new(), sealed: Sealed::default() } + } +} + +/// What [`step`] did with the statement it was given. +pub(crate) enum Outcome { + /// The statement is final: it is named and staged. `literals` is the + /// mode of the bodies of its function literals, `bodies` that of its + /// lists; `written` says a rule wrote it in place of the one given. + Final { statement: S, literals: Mode, bodies: Mode, written: bool }, + /// A rule replaced the statement by what it pushed on the work stack + /// (nothing, for a dropped statement). + Replaced, +} + +/// Offer `statement`, in a list of `mode`, to the rules F1 to F8. A rule +/// that applies takes the statement apart and pushes what replaces it on +/// `work.pending`, the statement to be offered first on top. The +/// statement is owned ([`JsStmt::own`]) before it is taken apart. +/// +/// Cost: one step (`Sealed::seal_offered`); the kind of the statement +/// and, for an `Exp` or a `Return`, of its value (for an `Exp` of an +/// assignment the `aux` and the kind of its second operand too); and the +/// interface functions of the rule that applies, O(1) each but F2 and +/// F8, which cost one step per element or statement taken out. Nothing +/// is allocated once `work.pending` has held as many statements. +pub(crate) fn step(js: &mut B, a: &mut Pools, statement: B::S, mode: Mode, work: &mut Work) -> Outcome { + work.sealed.seal_offered += 1; + if mode == Mode::Off { + return Outcome::Final { statement, literals: Mode::Off, bodies: Mode::Off, written: false }; + } + let kind = js.stmt_kind(a, &statement); + let value = js.value_of(a, &statement).map(|value| js.kind(a, value)); + match (kind, value) { + // F5 `Return(Cond)`: `if (test) { return yes } else { return no }`; + // each `return` is sealed where the walk reaches the `if`'s lists, + // the test is not entered (`StmtKind::Return(expr)`, + // `ExprKind::Cond(test, consequent, alternate)`). + (Kind::Return, Some(Kind::Cond)) => { + work.sealed.seal_f5 += 1; + let value = take(js, a, statement); + let (test, yes, no, loc) = conditional(js, a, value); + let yes = js.return_(a, yes); + let no = js.return_(a, no); + let yes = js.list(a, 1, std::iter::once(yes)); + let no = js.list(a, 1, std::iter::once(no)); + let written = js.if_plain(a, test, yes, no); + let written = located(js, a, written, loc); + Outcome::Final { statement: written, literals: unentered(mode), bodies: mode, written: true } + } + // F6 `Return(Seq)`: the head as a statement, then `return` of the + // rest, each offered again. The pass maps its result once more + // (`map_statement_children(self, j, block)`), so the heads are + // sealed with their tests entered. + (Kind::Return, Some(Kind::Seq)) => { + work.sealed.seal_f6 += 1; + let value = take(js, a, statement); + let (head, rest) = sequence(js, a, value); + let rest = js.return_(a, rest); + work.pending.push(Pending { statement: rest, mode, group: false }); + part(js, a, head, Mode::Entered, work); + Outcome::Replaced + } + // F1 `Exp(Seq)`: one statement per part, in order, each offered + // again; a chain is split one operand a step. + (Kind::Exp, Some(Kind::Seq)) => { + work.sealed.seal_f1 += 1; + let value = take(js, a, statement); + let (first, second) = sequence(js, a, value); + part(js, a, second, mode, work); + part(js, a, first, mode, work); + Outcome::Replaced + } + // F2 `Exp` of a block literal: one statement per element, in + // order, each as the pass's constructor makes it; a trivial + // element is the pass's empty block, which stays when the literal + // has two elements or more and the list is sealed once (its + // `S::block` of one statement splices it away). + (Kind::Exp, Some(Kind::BlockLit)) => { + work.sealed.seal_f2 += 1; + let value = take(js, a, statement); + let elements = js.unpack_rev(a, value); + let start = work.pending.len(); + for _ in 0..elements { + let element = js.pop(); + let element = strip(js, a, element); + if !trivial(js, a, &element) { + work.pending.push(Pending { statement: js.exp(a, element), mode, group: mode == Mode::Seal }); + continue; + } + js.release(a, element); + if elements < 2 || mode == Mode::Entered { + work.sealed.seal_dropped += 1; + continue; + } + let empty = js.list(a, 0, std::iter::empty()); + work.pending.push(Pending { statement: js.explicit_block(a, empty), mode: Mode::Off, group: false }); + } + work.pending[start..].reverse(); + Outcome::Replaced + } + // F4 `Exp(target = Seq)`: the head as a statement, then the + // assignment of the rest, each offered again. + (Kind::Exp, Some(Kind::Bin)) if assigns_sequence(js, a, &statement) => { + work.sealed.seal_f4 += 1; + let value = take(js, a, statement); + let operands = js.unpack_rev(a, value); + debug_assert_eq!(operands, 2, "an assignment has two operands"); + let target = js.pop(); + let value = js.pop(); + let (head, rest) = sequence(js, a, value); + let assignment = js.bin_plain(a, crate::js_ir::BinOp::Eq, target, rest); + let assignment = js.exp(a, assignment); + work.pending.push(Pending { statement: assignment, mode, group: false }); + part(js, a, head, mode, work); + Outcome::Replaced + } + // F3 `Exp(Cond)`: an `if`; a branch without effect (the lowering's + // `PURE`) is dropped and released, the test negated when only the + // else-branch is left; the test alone, or nothing, when both go. + // The test is not entered. + (Kind::Exp, Some(Kind::Cond)) => { + work.sealed.seal_f3 += 1; + let value = take(js, a, statement); + let (test, yes, no, loc) = conditional(js, a, value); + let yes = branch(js, a, yes); + let no = branch(js, a, no); + let written = match (yes, no) { + (None, None) if pure(js, a, &test) => { + work.sealed.seal_dropped += 1; + js.release(a, test); + return Outcome::Replaced; + } + (None, None) => { + let statement = js.exp(a, test); + let statement = located(js, a, statement, loc); + // Mapped as a statement when the pass maps the result + // again (F6's heads). + if mode == Mode::Entered { + work.pending.push(Pending { statement, mode, group: false }); + return Outcome::Replaced; + } + return Outcome::Final { statement, literals: Mode::Off, bodies: mode, written: true }; + } + (None, Some(no)) => { + let test = js.not(a, test); + let yes = js.list(a, 1, std::iter::once(no)); + let no = js.list(a, 0, std::iter::empty()); + js.if_plain(a, test, yes, no) + } + (Some(yes), no) => { + let yes = js.list(a, 1, std::iter::once(yes)); + let no = match no { + Some(no) => js.list(a, 1, std::iter::once(no)), + None => js.list(a, 0, std::iter::empty()), + }; + js.if_plain(a, test, yes, no) + } + }; + let written = located(js, a, written, loc); + Outcome::Final { statement: written, literals: unentered(mode), bodies: mode, written: true } + } + // F7 and F8: a block statement in a list is spliced into it; its + // statements are offered to the rules again, in order (a block of + // one is that statement, `j.stmts(block).len() == 1`; the others + // `Flatten::block_items`). + (Kind::Block, _) => { + work.sealed.seal_f78 += 1; + let mut statement = statement; + js.own(a, &mut statement); + let start = work.pending.len(); + let pending = &mut work.pending; + js.unblock(a, statement, |inner| pending.push(Pending { statement: inner, mode, group: false })); + work.pending[start..].reverse(); + Outcome::Replaced + } + _ => Outcome::Final { statement, literals: mode, bodies: mode, written: false }, + } +} + +/// The value of the statement in hand, which a rule rewrites: the +/// statement is owned ([`JsStmt::own`]), taken apart and released. Cost: +/// O(1), one step of the implementation. +fn take(js: &mut B, a: &mut Pools, mut statement: B::S) -> B::E { + js.own(a, &mut statement); + js.take_value(a, statement) +} + +/// Whether `e` is what the pass's statement constructor makes an empty +/// block of (`js_ir::build::stmt::exp`, `expression_stmt_is_trivial`): a +/// number or `undefined`. Cost: O(1). +fn trivial(js: &B, a: &Pools, e: &B::E) -> bool { + matches!(js.kind(a, B::of(e)), Kind::Number | Kind::Undefined) +} + +/// A part of a sequence (F1, F4, F6) as an expression statement offered +/// to the rules in `mode`, pushed on the work stack. A trivial part is the +/// empty block of the pass's constructor: in a list sealed once it stays +/// (F1 splices its result one level only, and the printer writes the +/// block as an empty line), so it is pushed as final (`Mode::Off`); where +/// the pass maps the result again (`Mode::Entered`) that map splices it +/// away, so it is released. Cost: O(1), one push. +fn part(js: &mut B, a: &mut Pools, value: B::E, mode: Mode, work: &mut Work) { + if trivial(js, a, &value) { + js.release(a, value); + if mode == Mode::Entered { + work.sealed.seal_dropped += 1; + return; + } + let empty = js.list(a, 0, std::iter::empty()); + let statement = js.explicit_block(a, empty); + work.pending.push(Pending { statement, mode: Mode::Off, group: false }); + return; + } + // A sequence is the rest of the same split (the pass splits a chain + // whole); any other part is one the pass makes a statement of. + let group = mode == Mode::Seal && js.kind(a, B::of(&value)) != Kind::Seq; + let statement = js.exp(a, value); + work.pending.push(Pending { statement, mode, group }); +} + +/// A branch of an F3 as the statement of the `if`'s list, or nothing for +/// a branch without effect, which is released (the pass's `branch`: +/// `expression_has_no_side_effects`, else `S::exp`). The statement is not +/// offered to the rules here: the walk seals it where it reaches the +/// `if`'s list. Cost: O(1) and [`strip`]; the release of a dropped +/// branch costs one step per node of it. +fn branch(js: &mut B, a: &mut Pools, value: B::E) -> Option { + if pure(js, a, &value) { + js.release(a, value); + return None; + } + let value = strip(js, a, value); + Some(js.exp(a, value)) +} + +/// What the pass's statement constructor keeps of `value` +/// (`js_ir::build::stmt::exp`): of a sequence with a trivial side, the +/// other side, again while there is one. Cost: O(1) a side dropped +/// (`Js::keep_operand`). +fn strip(js: &mut B, a: &mut Pools, mut value: B::E) -> B::E { + while js.kind(a, B::of(&value)) == Kind::Seq { + let (first, second) = (js.operand(a, B::of(&value), 0), js.operand(a, B::of(&value), 1)); + let keep = if matches!(js.kind(a, first), Kind::Number | Kind::Undefined) { + 1 + } else if matches!(js.kind(a, second), Kind::Number | Kind::Undefined) { + 0 + } else { + break; + }; + value = js.keep_operand(a, value, keep); + } + value +} + +/// The two operands of a sequence, taken apart. Cost: O(1), one step of +/// the implementation and two operands. +fn sequence(js: &mut B, a: &mut Pools, value: B::E) -> (B::E, B::E) { + let operands = js.unpack_rev(a, value); + debug_assert_eq!(operands, 2, "a sequence has two operands"); + let first = js.pop(); + let second = js.pop(); + (first, second) +} + +/// Whether the expression statement `statement` is an assignment whose +/// value is a sequence (F4). Cost: O(1), the `aux` of the value and the +/// kind of its second operand. +fn assigns_sequence(js: &B, a: &Pools, statement: &B::S) -> bool { + let Some(value) = js.value_of(a, statement) else { return false }; + js.aux(a, value) == crate::js_ir::BinOp::Eq as u8 && js.kind(a, js.operand(a, value, 1)) == Kind::Seq +} + +/// Whether `e` has no effect: the lowering's `PURE` flag (the pass asks +/// `expression_has_no_side_effects`). Cost: O(1). +fn pure(js: &B, a: &Pools, e: &B::E) -> bool { + js.has(a, B::of(e), flag::PURE) +} + +/// The mode of the literals in the test of an `if` that F3 or F5 wrote in +/// a list of `mode`: not entered, unless the pass maps the `if` again. +/// Cost: O(1). +fn unentered(mode: Mode) -> Mode { + if mode == Mode::Entered { Mode::Entered } else { Mode::Off } +} + +/// The test and the two branches of a conditional, taken apart, and its +/// source location, which the statement a rule writes in its place takes +/// (the pass's `source_loc: j.expr_loc(expr)`; a call or a primitive that +/// compiles to a conditional is located, C:1372 and C:1930). Cost: O(1), +/// one step of the implementation and three operands. +fn conditional(js: &mut B, a: &mut Pools, value: B::E) -> (B::E, B::E, B::E, Option) { + let loc = js.location(a, B::of(&value)); + let operands = js.unpack_rev(a, value); + debug_assert_eq!(operands, 3, "a conditional has three operands"); + let test = js.pop(); + let yes = js.pop(); + let no = js.pop(); + (test, yes, no, loc) +} + +/// `statement` with the location of the conditional it was written for, +/// when that had one. Cost: O(1). +fn located(js: &mut B, a: &mut Pools, mut statement: B::S, loc: Option) -> B::S { + if let Some(loc) = loc { + js.locate_stmt(a, &mut statement, loc); + } + statement +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The size of every type the seal adds, with the statement of rows + /// (4 bytes). + #[test] + fn sizes() { + type S = crate::bir::j::rows_stmt::S; + assert_eq!(std::mem::size_of::(), 1); + assert_eq!(std::mem::size_of::>(), 8); + assert_eq!(std::mem::size_of::(), 12); + assert_eq!(std::mem::size_of::>(), 8); + assert_eq!(std::mem::size_of::(), 88); + assert_eq!(std::mem::size_of::>(), 112); + } +} diff --git a/compiler-rust/src/bir/lower/unit.rs b/compiler-rust/src/bir/lower/unit.rs index e9e56d747f..d4153e3730 100644 --- a/compiler-rust/src/bir/lower/unit.rs +++ b/compiler-rust/src/bir/lower/unit.rs @@ -119,22 +119,27 @@ mod tests { // recursion and no longer pushes every statement of the top level // through `Tables::path`, which nothing else allocates in these two // units (`row_of` does in the other two). THREE_TREES 11.4, "T6x-e - // and T6x-f: the fold reads where its rows are", decision 10. + // and T6x-f: the fold reads where its rows are", decision 10. Each + // reads one higher since T6u: the work stack of the seal + // (`seal::Work::pending`), reserved once a unit by its nodes + // (`names::Storage::reserve`), so that a block or a literal a rule + // takes apart grows nothing (THREE_TREES 11.4, "T6u: the seal", + // decision 14). #[test] fn full_unit_allocation_boundary_conditionals() { - assert_unit_allocation_count("conditionals", 85); + assert_unit_allocation_count("conditionals", 86); } #[test] fn full_unit_allocation_boundary_switches() { - assert_unit_allocation_count("switches", 103); + assert_unit_allocation_count("switches", 104); } #[test] fn full_unit_allocation_boundary_applications() { - assert_unit_allocation_count("applications", 85); + assert_unit_allocation_count("applications", 86); } #[test] fn full_unit_allocation_boundary_untagged() { - assert_unit_allocation_count("untagged", 155); + assert_unit_allocation_count("untagged", 156); } /// Import is outside measurement; fresh state construction, lowering, diff --git a/compiler-rust/src/lambda/lam_compile.rs b/compiler-rust/src/lambda/lam_compile.rs index c06d09c250..bfd5340930 100644 --- a/compiler-rust/src/lambda/lam_compile.rs +++ b/compiler-rust/src/lambda/lam_compile.rs @@ -676,10 +676,13 @@ impl LambdaCompiler { self.coerce_lowered_output(j, compiled, None) } - /// The six JS passes, for the same tests. + /// The JS passes after the flatten step, for the same tests: what + /// both sides of the gate run, the backend in use on its program + /// after its flatten pass and the new side on the lowering's program, + /// whose statements the seal flattened (`bir/lower/seal.rs`). #[cfg(test)] pub(crate) fn bir_passes_oracle(&mut self, deps: DepsProgram) -> DepsProgram { - self.finish_lowered_output(deps, &AHashSet::new()) + self.finish_flattened_output(deps, &AHashSet::new(), ExternalShadow::Pass) } /// The program the new lowering's coercion describes, for the same tests. @@ -891,8 +894,16 @@ impl LambdaCompiler { drop(a); let shadow_side_effect = if CHECK { side_effect.clone() } else { None }; let deps = self.coerce_lowered_output(j, compiled, side_effect); + // C:828: the flatten pass of the backend in use. The gate's + // `before` is its program after that pass: the lowering's + // program is flattened where its statements are sealed + // (`bir/lower/seal.rs`). + let deps = { + let _phase = info_span!("compiler.js_pass_flatten").entered(); + apply_js_flatten_pass(deps) + }; let before = if CHECK { Some(deps.clone()) } else { None }; - let deps = self.finish_lowered_output(deps, &possible_required_modules); + let deps = self.finish_flattened_output(deps, &possible_required_modules, ExternalShadow::Pass); let checked = candidate.map(|candidate| match candidate { Ok(candidate) => { let crate::bir::shadow::LowerCandidate { arena: j, block, exports, reservations, dynamic_imports: dynamic, mut stats, decisions, qualified, names } = candidate; @@ -919,13 +930,10 @@ impl LambdaCompiler { // THREE_TREES 11.4, "T5 design": the lowering decided // which references to JavaScript globals are shadowed; // the new side writes them and runs no external-shadow - // pass. - let mut shadowed = new_before.clone(); - crate::bir::bridge_j::qualify(&mut shadowed, &qualified); - let flattened = { - let _phase = info_span!("compiler.js_pass_flatten").entered(); - apply_js_flatten_pass(shadowed) - }; + // pass. "T6u: the seal": its statements are flattened + // by the seal, and it runs no flatten pass. + let mut flattened = new_before.clone(); + crate::bir::bridge_j::qualify(&mut flattened, &qualified); // "T4c design": the lowering's step A against the // tail-call pass on the program that pass receives. // Counted in the report; the pass decides. @@ -1028,19 +1036,6 @@ impl LambdaCompiler { coerced_program(j, block, exports, name_reservations, side_effect) } - /// C:828–881: the six JS passes and dependency tail, shared by both lowerings. - fn finish_lowered_output( - &mut self, - mut deps: DepsProgram, - possible_required_modules: &AHashSet, - ) -> DepsProgram { - deps = { - let _phase = info_span!("compiler.js_pass_flatten").entered(); - apply_js_flatten_pass(deps) - }; - self.finish_flattened_output(deps, possible_required_modules, ExternalShadow::Pass) - } - /// The passes after the flatten step, and the dependency tail. The new /// side of the gate enters here with `ExternalShadow::Decided`: its /// references to shadowed globals were decided by the lowering.