Repository navigation
Three trees T6 design turn 14: the seal (T6u) built once - #434
Conversation
Why:
The flatten rules of slice T6u run in the naming replay's walk: a
rule takes a statement of an open list apart and stages other
statements in its place. On rows a statement taken out of such a
list keeps its block as owner, so it could not be released or taken
apart, and `set_body` puts back only what it took.
`JsStmt::own` makes a statement taken out of a list the caller's;
`JsStmt::set_body_adopting` and `JsStmt::set_literal_body_adopting` put
back a list whose statements were replaced. Each has its body on rows
(`Bir::adopt_block_list`: the parent of each adopted statement, its use
weight, the block's facts repaired) and on the builder (`own_statement`,
`set_body_adopting`, `set_literal_body_adopting`: the statement's row
gains the inherited flags of what was put back), its cost in the doc
comment, a test on each side and a pair in `replay::both`. No caller
until the slice.
Co-authored-by: Jaap Frolich <jfrolich@gmail.com>
Session: https://os.submodule.nl/session/bks-0f9747f5-a705-7f4b-9555-b90c001e0c4b
Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com>
|
// T6X-THROWAWAY T6u (1 of 2), against commit 751e121 of this pull request's branch; apply in order with diff --git a/compiler-rust/src/bir/lower/export.rs b/compiler-rust/src/bir/lower/export.rs
index cc0d7f20d..56cb42c69 100644
--- a/compiler-rust/src/bir/lower/export.rs
+++ b/compiler-rust/src/bir/lower/export.rs
@@ -2266,4 +2266,8 @@ mod tests {
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");
diff --git a/compiler-rust/src/bir/lower/ffi_args.rs b/compiler-rust/src/bir/lower/ffi_args.rs
index 85e944100..93f939d4f 100644
--- a/compiler-rust/src/bir/lower/ffi_args.rs
+++ b/compiler-rust/src/bir/lower/ffi_args.rs
@@ -848,4 +848,7 @@ mod tests {
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(
diff --git a/compiler-rust/src/bir/lower/globals.rs b/compiler-rust/src/bir/lower/globals.rs
index 851fb7517..fac455bdf 100644
--- a/compiler-rust/src/bir/lower/globals.rs
+++ b/compiler-rust/src/bir/lower/globals.rs
@@ -472,6 +472,9 @@ fn simple_element<B: Js>(js: &B, a: &Pools, idents: &[Ident], item: B::Ref<'_>)
/// 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();
diff --git a/compiler-rust/src/bir/lower/mod.rs b/compiler-rust/src/bir/lower/mod.rs
index f72a87841..fe72a70f4 100644
--- a/compiler-rust/src/bir/lower/mod.rs
+++ b/compiler-rust/src/bir/lower/mod.rs
@@ -17,4 +17,5 @@ pub mod js;
pub mod js_stmt;
pub(crate) mod names;
+pub(crate) mod seal;
mod expr;
mod konst;
@@ -331,4 +332,7 @@ pub(crate) struct SwitchStats {
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,
}
@@ -848,4 +852,5 @@ impl<B: js_stmt::JsStmt> State<'_, B> {
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()
@@ -877,4 +882,5 @@ impl<B: js_stmt::JsStmt> State<'_, B> {
names_compared: 0,
names_uncompared: 0,
+ sealed,
},
printed,
diff --git a/compiler-rust/src/bir/lower/names.rs b/compiler-rust/src/bir/lower/names.rs
index 51209ed9d..3a6bcd7e9 100644
--- a/compiler-rust/src/bir/lower/names.rs
+++ b/compiler-rust/src/bir/lower/names.rs
@@ -34,4 +34,5 @@
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};
@@ -701,4 +702,6 @@ struct Frame<L> {
/// 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,
}
@@ -709,4 +712,7 @@ struct Held<S> {
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,
@@ -742,4 +748,6 @@ pub(crate) struct Scratch<B: JsStmt> {
/// 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<B::S>,
}
impl<B: JsStmt> Default for Scratch<B> {
@@ -753,4 +761,5 @@ impl<B: JsStmt> Default for Scratch<B> {
reservation: Vec::new(),
spelling: String::new(),
+ seal: seal::Work::default(),
}
}
@@ -783,5 +792,7 @@ impl<B: JsStmt> Storage<B> {
/// 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
@@ -797,4 +808,5 @@ impl<B: JsStmt> Storage<B> {
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()));
@@ -803,4 +815,10 @@ impl<B: JsStmt> Storage<B> {
self.tables.size(slots, log.free.len() + rows + slots, rows);
}
+
+ /// What the seal did in the last replay. Cost: O(1), a copy of 80
+ /// bytes.
+ pub(crate) fn sealed(&self) -> seal::Sealed {
+ self.scratch.seal.sealed
+ }
}
@@ -1046,16 +1064,34 @@ impl<B: JsStmt> Replay<'_, '_, B> {
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;
}
@@ -1064,4 +1100,8 @@ impl<B: JsStmt> Replay<'_, '_, B> {
self.globals.close();
}
+ if frame.seal.group {
+ self.close_group(frame.seal);
+ continue;
+ }
if frame.leave == QUIET {
self.quiet -= 1;
@@ -1069,21 +1109,34 @@ impl<B: JsStmt> Replay<'_, '_, B> {
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<B::L>) {
- 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();
@@ -1091,4 +1144,46 @@ impl<B: JsStmt> Replay<'_, '_, B> {
}
+ /// 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).
@@ -1098,8 +1193,10 @@ impl<B: JsStmt> 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;
@@ -1107,5 +1204,11 @@ impl<B: JsStmt> Replay<'_, '_, B> {
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);
@@ -1143,6 +1246,7 @@ impl<B: JsStmt> Replay<'_, '_, B> {
}
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
@@ -1176,5 +1280,5 @@ impl<B: JsStmt> Replay<'_, '_, B> {
/// `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;
@@ -1241,7 +1345,13 @@ impl<B: JsStmt> Replay<'_, '_, B> {
}
// 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
@@ -1278,5 +1388,5 @@ impl<B: JsStmt> Replay<'_, '_, B> {
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();
}
@@ -1393,6 +1503,7 @@ impl<B: JsStmt> 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);
@@ -1411,6 +1522,7 @@ impl<B: JsStmt> Replay<'_, '_, B> {
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);
@@ -1555,5 +1667,5 @@ mod tests {
assert_eq!(std::mem::size_of::<Child>(), 12);
assert_eq!(std::mem::size_of::<Place>(), 8);
- assert_eq!(std::mem::size_of::<Frame<crate::bir::ListId>>(), 12);
+ assert_eq!(std::mem::size_of::<Frame<crate::bir::ListId>>(), 24);
assert_eq!(std::mem::size_of::<Program<'_>>(), 64);
assert_eq!(std::mem::size_of::<Replayed>(), 48);
@@ -1738,4 +1850,7 @@ mod tests {
)
}
+ fn var(&mut self, var: VarId) -> NodeId {
+ self.b.new_node(View::Var { var }, 0)
+ }
/// `let var = [reads]`.
fn declare_read(&mut self, var: VarId, reads: &[VarId]) -> NodeId {
@@ -2902,23 +3017,31 @@ 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<NodeId>| {
+ 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<NodeId> = None;
+ let mut nested: Option<NodeId> = 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"));
@@ -2926,5 +3049,6 @@ mod tests {
};
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));
@@ -2935,11 +3059,10 @@ mod tests {
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());
@@ -2951,6 +3074,5 @@ mod tests {
});
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));
}
diff --git a/compiler-rust/src/bir/lower/oracle_tests.rs b/compiler-rust/src/bir/lower/oracle_tests.rs
index 92868e23b..d31403cd4 100644
--- a/compiler-rust/src/bir/lower/oracle_tests.rs
+++ b/compiler-rust/src/bir/lower/oracle_tests.rs
@@ -118,4 +118,9 @@ fn compare_oracle(mut arena: LamArena, root: Lam, resolver: Option<&crate::js_ir
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| {
@@ -1022,5 +1027,4 @@ fn export_coercion_consumes_the_export_tuple_occurrence() {
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;
@@ -1044,5 +1048,5 @@ fn export_coercion_consumes_the_export_tuple_occurrence() {
let (_, check) = compiler.compile_deps_program_with_lower_check::<true>(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);
@@ -1195,10 +1199,9 @@ 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);
@@ -1208,5 +1211,5 @@ fn step_a(build: impl Fn(&mut LamArena) -> Lam) -> (DecisionStats, Vec<(String,
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();
@@ -1442,5 +1445,4 @@ fn a_copied_function_doubles_the_legacy_count_of_the_variables_declared_inside_i
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));
@@ -1474,5 +1476,5 @@ fn a_copied_function_doubles_the_legacy_count_of_the_variables_declared_inside_i
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));
@@ -1592,6 +1594,8 @@ fn cached_external_templates_keep_fresh_binders_and_import_once() {
/// 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())
@@ -1601,5 +1605,4 @@ fn new_text(build: impl Fn(&mut LamArena) -> Lam, resolver: Option<&crate::js_ir
/// 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<Ident>) -> (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);
@@ -1624,5 +1627,4 @@ fn new_text_assigning(build: impl Fn(&mut LamArena) -> Lam, resolver: Option<&cr
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),
@@ -1640,6 +1642,6 @@ fn new_text_assigning(build: impl Fn(&mut LamArena) -> Lam, resolver: Option<&cr
/// 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)
@@ -1658,5 +1660,5 @@ fn ext_call(a: &mut LamArena, args: &[Lam]) -> Lam {
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.
@@ -1673,5 +1675,5 @@ fn the_lowering_decides_the_shadowed_global_the_tail_call_pass_would_hide() {
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);
@@ -1836,5 +1838,5 @@ fn an_imported_module_shadows_the_global_of_its_name_everywhere() {
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}");
@@ -1867,5 +1869,5 @@ fn a_module_whose_only_reference_the_flatten_pass_drops_still_shadows_the_global
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);
@@ -2482,9 +2484,9 @@ fn the_naming_log_agrees_on_a_closure_dropped_before_the_function_around_it_clos
}
-/// 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
@@ -2553,5 +2555,5 @@ fn an_assigned_element_the_substitution_pass_binds_shadows_the_global() {
};
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}");
diff --git a/compiler-rust/src/bir/lower/seal.rs b/compiler-rust/src/bir/lower/seal.rs
new file mode 100644
index 000000000..4c1b6d9b2
--- /dev/null
+++ b/compiler-rust/src/bir/lower/seal.rs
@@ -0,0 +1,412 @@
+//! 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};
+
+/// 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<S> {
+ 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,
+}
+
+/// The seal's storage in the replay's scratch, reused between units.
+pub(crate) struct Work<S> {
+ pub(crate) pending: Vec<Pending<S>>,
+ pub(crate) sealed: Sealed,
+}
+impl<S> Default for Work<S> {
+ /// 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<S> {
+ /// 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<B: JsStmt>(js: &mut B, a: &mut Pools, statement: B::S, mode: Mode, work: &mut Work<B::S>) -> Outcome<B::S> {
+ 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) = 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);
+ 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) = 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);
+ // 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)
+ }
+ };
+ 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<B: JsStmt>(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<B: Js>(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<B: JsStmt>(js: &mut B, a: &mut Pools, value: B::E, mode: Mode, work: &mut Work<B::S>) {
+ 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<B: JsStmt>(js: &mut B, a: &mut Pools, value: B::E) -> Option<B::S> {
+ 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<B: JsStmt>(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<B: Js>(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<B: JsStmt>(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<B: Js>(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. The pass
+/// gives the `if` the conditional's source location; no conditional the
+/// lowering builds has one (a debug build checks it), so none is read.
+/// Cost: O(1), one step of the implementation and three operands.
+fn conditional<B: Js>(js: &mut B, a: &mut Pools, value: B::E) -> (B::E, B::E, B::E) {
+ debug_assert!(!js.located(a, B::of(&value)), "a conditional with a source location at the seal");
+ 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)
+}
+
+#[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::<Mode>(), 1);
+ assert_eq!(std::mem::size_of::<Pending<S>>(), 8);
+ assert_eq!(std::mem::size_of::<Marks>(), 12);
+ assert_eq!(std::mem::size_of::<Outcome<S>>(), 8);
+ assert_eq!(std::mem::size_of::<Sealed>(), 80);
+ assert_eq!(std::mem::size_of::<Work<S>>(), 104);
+ }
+}
diff --git a/compiler-rust/src/bir/lower/unit.rs b/compiler-rust/src/bir/lower/unit.rs
index e9e56d747..d4153e373 100644
--- a/compiler-rust/src/bir/lower/unit.rs
+++ b/compiler-rust/src/bir/lower/unit.rs
@@ -120,20 +120,25 @@ mod tests {
// 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);
}
diff --git a/compiler-rust/src/lambda/lam_compile.rs b/compiler-rust/src/lambda/lam_compile.rs
index c06d09c25..bfd534093 100644
--- a/compiler-rust/src/lambda/lam_compile.rs
+++ b/compiler-rust/src/lambda/lam_compile.rs
@@ -677,8 +677,11 @@ impl LambdaCompiler {
}
- /// 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)
}
@@ -892,6 +895,14 @@ impl LambdaCompiler {
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) => {
@@ -920,11 +931,8 @@ impl LambdaCompiler {
// 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.
@@ -1029,17 +1037,4 @@ impl LambdaCompiler {
}
- /// 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<ModuleId>,
- ) -> 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 |
|
// T6X-THROWAWAY T6u (2 of 2), against commit 751e121 of this pull request's branch; apply in order with --- a/compiler-rust/src/bir/lower/names.rs
+++ b/compiler-rust/src/bir/lower/names.rs
@@ -1849,9 +1849,74 @@
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);
+ 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);
+ }
+ 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, expected, "the seal against the flatten pass");
+ (actual, 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);
@@ -3076,4 +3141,320 @@
// 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<NodeId>) -> (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);
+ (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)`.
+ 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));
+ // 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:?}");
+ }
}
--- a/compiler-rust/src/bir/lower/oracle_tests.rs
+++ b/compiler-rust/src/bir/lower/oracle_tests.rs
@@ -2876,3 +2876,61 @@
assert_eq!(more[0], more[1], "the allocations of the decision rise with the unit");
}
}
+
+/// `run = c => { let location = ext(); return c ? ext(<global location>) :
+/// 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(<global location>)
+/// : 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}");
+} |
…rompt Section 11.4 gains "T6u: the seal": the flatten rules as built beside the pass arm by arm, the three interface additions and their callers, what check mode compares once the new side runs no flatten pass, the rules against the external-shadow decision and the early end of the descent, the cut, the counts of a check-mode build before and after, and nineteen decisions. Section 11.9 gains the prompt "Task T6u:". Co-authored-by: Jaap Frolich <jfrolich@gmail.com> Session: https://os.submodule.nl/session/bks-0f9747f5-a705-7f4b-9555-b90c001e0c4b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com>
Co-authored-by: Jaap Frolich <jfrolich@gmail.com> Session: https://os.submodule.nl/session/bks-0f9747f5-a705-7f4b-9555-b90c001e0c4b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com>
…e-trees-t6-seal-design
|
First-pass checklist review at 74e6097 (a checklist for the final reviewer, not an approval). First-pass review (checklist, not an approval): Setup: Findings that matter most
1. Scope — PASS (with finding 5)What the body and 11.4 (b) say this turn puts on trunk:
The body says what was not done: the fixtures corpus, the parity suites, 2. Default path — PASS
3. Engineering standard (added lines of pr.diff) — PASS
4. Tests and oracles — PASS (PR) / note (build)
5. New scripts and fixtures — PASSNone added. 6. Privacy — PASS
7. Changelog — PASSchanges/three-trees-t6-design-14.internal.md starts with 8. Numbers in the body — PASS (sources partly shown)
9. Focused tests — not run (host review)11. Files against what a design turn may hold — PASSFiles: changes fragment; THREE_TREES.md (+540); edit.rs (+38); rows_stmt.rs (+19); rows_stmt_tests.rs (+243); js_stmt.rs (+61); builder.rs (+46); builder_tests.rs (+130). edit.rs is the only file outside the list, and the body explains it: "the parent links, the slot weight, the use counts and
/// The entries of the pool list of the block `block` that have no
/// parent become its statements, and the block's facts are computed
/// again: what a block needs after its row was written over a list
/// that holds statements made or detached since the list was taken
/// (`JsStmt::set_body_adopting` on rows). An entry that has a parent
/// is the block's own already (a debug build checks it). Returns the
/// number of statements adopted.
///
/// One read per entry and one store per statement adopted; the weight
/// of the block's slot is read once (O(1) in a unit without a
/// weighted switch, else one step per ancestor), and a statement
/// that carries another weight has its uses recounted, one step per
/// node of it. Then `repair`: the block's facts from its statements,
/// and its owners' while a fact changes. Allocates nothing.
pub(crate) fn adopt_block_list(&mut self, block: NodeId) -> u32 {
let list = self.node(block).block_list_id().expect("a statement list of a statement is a block");
let slot = if self.bulk { 1 } else { self.weight(block) };
let mut adopted = 0;
for i in 0..self.lists.get(list).len() {
let child = self.lists.get(list)[i];
match self.parents[child.index()] {
None => {
if !self.bulk {
let weight = self.weight(child);
if weight != slot {
self.adjust_counts(child, i64::from(slot) - i64::from(weight));
}
}
self.parents[child.index()] = Some(block);
adopted += 1;
}
Some(owner) => debug_assert_eq!(owner, block, "a statement put back into a list it was not taken from"),
}
}
self.repair(block);
adopted
}(i) What it does:
(ii) No default build reaches it: its only caller is rows (iii) Its stated cost matches its one loop (entries of the list), except for the 12. The three interface functions — PASS with findings 2 and 3
Tests, and one wrong body each would not catch:
13. The build against the legacy pass, rule by rule — FAIL-candidate (finding 1), otherwise SAME
14. "Without effect" (decision 5) — PASS by readingPass:
No kind answers differently. The remaining risk is a flag that goes stale after an edit, which 15. The open defect (decision 12) — PASS (the reading is right), cost noted
16. External-shadow decision, early end, quiet frames — PASS
_ 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"),Decision 13 says it "did not fire in the three filters or in either corpus". Item 3 asked for "the three corpora", so the fixtures corpus is still owed.
17. What check mode compares — PASS
18. Structures and cost — PASS
19. The prompt against the build — PASS except (g)(a) End-state searches, head → build:
All as the prompt says. (b) numstat of diff 1 alone ( (c) Counts: test attributes added are 1 in diff 1 and 13 in diff 2, consistent with 595→596→609. The pins in the head's unit.rs are 85/103/85/155. Self-test, run with (d) Every name the prompt gives exists in the build: (e) Precondition: the greps print 1 and 1 on the head. On HTTP 401 the prompt says: "commit locally, write in your final message exactly which commits are local, and end the turn at once". (f) The breaks are plausible by reading:
(g) FAIL: finding 4 (the shortcut "an external-shadow test of oracle_tests.rs changed" against the instruction to drop pass 1 from those tests). 20. Decisions 1-19
21. State lines, counts, cross-references — PASS
22. CI on 74e6097 — PASS
10. Where I would look hardest
|
A test added in this pull request stood between the comment and `mod both`. Co-authored-by: Jaap Frolich <jfrolich@gmail.com> Session: https://os.submodule.nl/session/bks-0f9747f5-a705-7f4b-9555-b90c001e0c4b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com>
`Bir::adopt_block_list` and the rows form of `JsStmt::own` state the precondition and check it in debug builds: the arena holds no weighted switch, so every use weight is 1. Only a `Switch` of level L is weighted, and the lowering writes its statements into an arena of its own. The recount, which then cannot run and stored no weight as `replace` does, is deleted. The doc comments also say that an adoption computes no capture. Co-authored-by: Jaap Frolich <jfrolich@gmail.com> Session: https://os.submodule.nl/session/bks-0f9747f5-a705-7f4b-9555-b90c001e0c4b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com>
…flag The rows test of `set_literal_body_adopting` validates the arena and reads the body's purity before and after; the builder's test of `set_body_adopting` has one carrier each of `HAS_FUN`, `HAS_GLOBAL` and `SEAL`; the two pairs of `replay::both` compare what each statement holds on both sides, by descent on rows and by flags on the builder. Co-authored-by: Jaap Frolich <jfrolich@gmail.com> Session: https://os.submodule.nl/session/bks-0f9747f5-a705-7f4b-9555-b90c001e0c4b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com>
`Js::location` gives the location a node was located with, or nothing. The seal needs it: the `if` the flatten pass writes for a conditional takes the conditional's source location, and a primitive of two literals (`min(2, 3)`) compiles to a located conditional on both sides. On rows the node's flag, then its cold row. The builder has no form of `located`, `locate` or `locate_stmt` yet, and none of this. Co-authored-by: Jaap Frolich <jfrolich@gmail.com> Session: https://os.submodule.nl/session/bks-0f9747f5-a705-7f4b-9555-b90c001e0c4b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com>
|
// T6X-THROWAWAY T6u v2 (1 of 2), against commit 84e1bb8 of this pull request's branch; apply in order with diff --git a/compiler-rust/src/bir/lower/export.rs b/compiler-rust/src/bir/lower/export.rs
index cc0d7f20d..56cb42c69 100644
--- a/compiler-rust/src/bir/lower/export.rs
+++ b/compiler-rust/src/bir/lower/export.rs
@@ -2266,4 +2266,8 @@ mod tests {
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");
diff --git a/compiler-rust/src/bir/lower/ffi_args.rs b/compiler-rust/src/bir/lower/ffi_args.rs
index 85e944100..93f939d4f 100644
--- a/compiler-rust/src/bir/lower/ffi_args.rs
+++ b/compiler-rust/src/bir/lower/ffi_args.rs
@@ -848,4 +848,7 @@ mod tests {
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(
diff --git a/compiler-rust/src/bir/lower/globals.rs b/compiler-rust/src/bir/lower/globals.rs
index 851fb7517..fac455bdf 100644
--- a/compiler-rust/src/bir/lower/globals.rs
+++ b/compiler-rust/src/bir/lower/globals.rs
@@ -472,6 +472,9 @@ fn simple_element<B: Js>(js: &B, a: &Pools, idents: &[Ident], item: B::Ref<'_>)
/// 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();
diff --git a/compiler-rust/src/bir/lower/mod.rs b/compiler-rust/src/bir/lower/mod.rs
index f72a87841..fe72a70f4 100644
--- a/compiler-rust/src/bir/lower/mod.rs
+++ b/compiler-rust/src/bir/lower/mod.rs
@@ -17,4 +17,5 @@ pub mod js;
pub mod js_stmt;
pub(crate) mod names;
+pub(crate) mod seal;
mod expr;
mod konst;
@@ -331,4 +332,7 @@ pub(crate) struct SwitchStats {
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,
}
@@ -848,4 +852,5 @@ impl<B: js_stmt::JsStmt> State<'_, B> {
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()
@@ -877,4 +882,5 @@ impl<B: js_stmt::JsStmt> State<'_, B> {
names_compared: 0,
names_uncompared: 0,
+ sealed,
},
printed,
diff --git a/compiler-rust/src/bir/lower/names.rs b/compiler-rust/src/bir/lower/names.rs
index 51209ed9d..8e376380a 100644
--- a/compiler-rust/src/bir/lower/names.rs
+++ b/compiler-rust/src/bir/lower/names.rs
@@ -34,4 +34,5 @@
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};
@@ -701,4 +702,6 @@ struct Frame<L> {
/// 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,
}
@@ -709,4 +712,7 @@ struct Held<S> {
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,
@@ -742,4 +748,6 @@ pub(crate) struct Scratch<B: JsStmt> {
/// 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<B::S>,
}
impl<B: JsStmt> Default for Scratch<B> {
@@ -753,4 +761,5 @@ impl<B: JsStmt> Default for Scratch<B> {
reservation: Vec::new(),
spelling: String::new(),
+ seal: seal::Work::default(),
}
}
@@ -783,5 +792,7 @@ impl<B: JsStmt> Storage<B> {
/// 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
@@ -797,4 +808,5 @@ impl<B: JsStmt> Storage<B> {
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()));
@@ -803,4 +815,10 @@ impl<B: JsStmt> Storage<B> {
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
+ }
}
@@ -923,14 +941,21 @@ pub(crate) fn replay<B: JsStmt>(
// 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 {
@@ -978,10 +1003,14 @@ pub(crate) fn replay<B: JsStmt>(
// 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;
}
@@ -994,4 +1023,6 @@ pub(crate) fn replay<B: JsStmt>(
}
}
+ // Only the seal releases a literal during the replay.
+ replay.scratch.seal.sealed.seal_dropped_literals = released_now - released;
}
replay.done.unnamed_references = unnamed;
@@ -1046,16 +1077,34 @@ impl<B: JsStmt> Replay<'_, '_, B> {
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;
}
@@ -1064,4 +1113,8 @@ impl<B: JsStmt> Replay<'_, '_, B> {
self.globals.close();
}
+ if frame.seal.group {
+ self.close_group(frame.seal);
+ continue;
+ }
if frame.leave == QUIET {
self.quiet -= 1;
@@ -1069,21 +1122,34 @@ impl<B: JsStmt> Replay<'_, '_, B> {
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<B::L>) {
- 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();
@@ -1091,4 +1157,46 @@ impl<B: JsStmt> Replay<'_, '_, B> {
}
+ /// 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).
@@ -1098,8 +1206,10 @@ impl<B: JsStmt> 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;
@@ -1107,5 +1217,11 @@ impl<B: JsStmt> Replay<'_, '_, B> {
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);
@@ -1143,6 +1259,7 @@ impl<B: JsStmt> Replay<'_, '_, B> {
}
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
@@ -1176,5 +1293,5 @@ impl<B: JsStmt> Replay<'_, '_, B> {
/// `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;
@@ -1241,7 +1358,13 @@ impl<B: JsStmt> Replay<'_, '_, B> {
}
// 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
@@ -1278,5 +1401,5 @@ impl<B: JsStmt> Replay<'_, '_, B> {
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();
}
@@ -1393,6 +1516,7 @@ impl<B: JsStmt> 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);
@@ -1411,6 +1535,7 @@ impl<B: JsStmt> Replay<'_, '_, B> {
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);
@@ -1555,5 +1680,5 @@ mod tests {
assert_eq!(std::mem::size_of::<Child>(), 12);
assert_eq!(std::mem::size_of::<Place>(), 8);
- assert_eq!(std::mem::size_of::<Frame<crate::bir::ListId>>(), 12);
+ assert_eq!(std::mem::size_of::<Frame<crate::bir::ListId>>(), 24);
assert_eq!(std::mem::size_of::<Program<'_>>(), 64);
assert_eq!(std::mem::size_of::<Replayed>(), 48);
@@ -1738,4 +1863,7 @@ mod tests {
)
}
+ fn var(&mut self, var: VarId) -> NodeId {
+ self.b.new_node(View::Var { var }, 0)
+ }
/// `let var = [reads]`.
fn declare_read(&mut self, var: VarId, reads: &[VarId]) -> NodeId {
@@ -2902,23 +3030,31 @@ 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<NodeId>| {
+ 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<NodeId> = None;
+ let mut nested: Option<NodeId> = 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"));
@@ -2926,5 +3062,6 @@ mod tests {
};
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));
@@ -2935,11 +3072,10 @@ mod tests {
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());
@@ -2951,6 +3087,5 @@ mod tests {
});
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));
}
diff --git a/compiler-rust/src/bir/lower/oracle_tests.rs b/compiler-rust/src/bir/lower/oracle_tests.rs
index 92868e23b..d31403cd4 100644
--- a/compiler-rust/src/bir/lower/oracle_tests.rs
+++ b/compiler-rust/src/bir/lower/oracle_tests.rs
@@ -118,4 +118,9 @@ fn compare_oracle(mut arena: LamArena, root: Lam, resolver: Option<&crate::js_ir
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| {
@@ -1022,5 +1027,4 @@ fn export_coercion_consumes_the_export_tuple_occurrence() {
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;
@@ -1044,5 +1048,5 @@ fn export_coercion_consumes_the_export_tuple_occurrence() {
let (_, check) = compiler.compile_deps_program_with_lower_check::<true>(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);
@@ -1195,10 +1199,9 @@ 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);
@@ -1208,5 +1211,5 @@ fn step_a(build: impl Fn(&mut LamArena) -> Lam) -> (DecisionStats, Vec<(String,
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();
@@ -1442,5 +1445,4 @@ fn a_copied_function_doubles_the_legacy_count_of_the_variables_declared_inside_i
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));
@@ -1474,5 +1476,5 @@ fn a_copied_function_doubles_the_legacy_count_of_the_variables_declared_inside_i
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));
@@ -1592,6 +1594,8 @@ fn cached_external_templates_keep_fresh_binders_and_import_once() {
/// 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())
@@ -1601,5 +1605,4 @@ fn new_text(build: impl Fn(&mut LamArena) -> Lam, resolver: Option<&crate::js_ir
/// 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<Ident>) -> (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);
@@ -1624,5 +1627,4 @@ fn new_text_assigning(build: impl Fn(&mut LamArena) -> Lam, resolver: Option<&cr
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),
@@ -1640,6 +1642,6 @@ fn new_text_assigning(build: impl Fn(&mut LamArena) -> Lam, resolver: Option<&cr
/// 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)
@@ -1658,5 +1660,5 @@ fn ext_call(a: &mut LamArena, args: &[Lam]) -> Lam {
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.
@@ -1673,5 +1675,5 @@ fn the_lowering_decides_the_shadowed_global_the_tail_call_pass_would_hide() {
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);
@@ -1836,5 +1838,5 @@ fn an_imported_module_shadows_the_global_of_its_name_everywhere() {
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}");
@@ -1867,5 +1869,5 @@ fn a_module_whose_only_reference_the_flatten_pass_drops_still_shadows_the_global
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);
@@ -2482,9 +2484,9 @@ fn the_naming_log_agrees_on_a_closure_dropped_before_the_function_around_it_clos
}
-/// 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
@@ -2553,5 +2555,5 @@ fn an_assigned_element_the_substitution_pass_binds_shadows_the_global() {
};
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}");
diff --git a/compiler-rust/src/bir/lower/seal.rs b/compiler-rust/src/bir/lower/seal.rs
new file mode 100644
index 000000000..00938b429
--- /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<S> {
+ 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<S> {
+ pub(crate) pending: Vec<Pending<S>>,
+ pub(crate) sealed: Sealed,
+}
+impl<S> Default for Work<S> {
+ /// 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<S> {
+ /// 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<B: JsStmt>(js: &mut B, a: &mut Pools, statement: B::S, mode: Mode, work: &mut Work<B::S>) -> Outcome<B::S> {
+ 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<B: JsStmt>(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<B: Js>(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<B: JsStmt>(js: &mut B, a: &mut Pools, value: B::E, mode: Mode, work: &mut Work<B::S>) {
+ 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<B: JsStmt>(js: &mut B, a: &mut Pools, value: B::E) -> Option<B::S> {
+ 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<B: JsStmt>(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<B: Js>(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<B: JsStmt>(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<B: Js>(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<B: Js>(js: &mut B, a: &mut Pools, value: B::E) -> (B::E, B::E, B::E, Option<LamLoc>) {
+ 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<B: JsStmt>(js: &mut B, a: &mut Pools, mut statement: B::S, loc: Option<LamLoc>) -> 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::<Mode>(), 1);
+ assert_eq!(std::mem::size_of::<Pending<S>>(), 8);
+ assert_eq!(std::mem::size_of::<Marks>(), 12);
+ assert_eq!(std::mem::size_of::<Outcome<S>>(), 8);
+ assert_eq!(std::mem::size_of::<Sealed>(), 88);
+ assert_eq!(std::mem::size_of::<Work<S>>(), 112);
+ }
+}
diff --git a/compiler-rust/src/bir/lower/unit.rs b/compiler-rust/src/bir/lower/unit.rs
index e9e56d747..d4153e373 100644
--- a/compiler-rust/src/bir/lower/unit.rs
+++ b/compiler-rust/src/bir/lower/unit.rs
@@ -120,20 +120,25 @@ mod tests {
// 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);
}
diff --git a/compiler-rust/src/lambda/lam_compile.rs b/compiler-rust/src/lambda/lam_compile.rs
index c06d09c25..bfd534093 100644
--- a/compiler-rust/src/lambda/lam_compile.rs
+++ b/compiler-rust/src/lambda/lam_compile.rs
@@ -677,8 +677,11 @@ impl LambdaCompiler {
}
- /// 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)
}
@@ -892,6 +895,14 @@ impl LambdaCompiler {
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) => {
@@ -920,11 +931,8 @@ impl LambdaCompiler {
// 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.
@@ -1029,17 +1037,4 @@ impl LambdaCompiler {
}
- /// 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<ModuleId>,
- ) -> 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 |
|
// T6X-THROWAWAY T6u v2 (2 of 2), against commit 84e1bb8 of this pull request's branch; apply in order with --- a/compiler-rust/src/bir/lower/names.rs
+++ b/compiler-rust/src/bir/lower/names.rs
@@ -1862,9 +1862,80 @@
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);
@@ -3089,4 +3160,422 @@
// 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<NodeId>) -> (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));
+ }
+ }
+ }
}
--- a/compiler-rust/src/bir/lower/oracle_tests.rs
+++ b/compiler-rust/src/bir/lower/oracle_tests.rs
@@ -2876,3 +2876,84 @@
assert_eq!(more[0], more[1], "the allocations of the decision rise with the unit");
}
}
+
+/// `run = c => { let location = ext(); return c ? ext(<global location>) :
+/// 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(<global location>)
+/// : 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);
+ }
+} |
…f its build Decision 20 records that the lists of the `if` F3 and F5 write differ from the pass's as trees and print the same in 36 forms on both judges. Decision 17 is corrected: a located conditional reaches the seal, which gives its location to the statement it writes. Decision 12 gains the reference's three outputs and the counter of the build. Decision 7 states the preconditions of the adopting primitive. (g) says what a statement pays. The prompt names the second build, its counts, and every line of an external-shadow test that changes. Co-authored-by: Jaap Frolich <jfrolich@gmail.com> Session: https://os.submodule.nl/session/bks-0f9747f5-a705-7f4b-9555-b90c001e0c4b Signed-off-by: open-session-submodule[bot] <341020755+open-session-submodule[bot]@users.noreply.github.com>
…e-trees-t6-seal-design
|
Coordinator review, final, at 9e25191 (the author did not write this review). It follows the first-pass checklist review above (7257787699) and one correction turn (C1 to C10, commits 230004c to 22bbc3d). What this pull request puts on trunk. Four functions of the lowering's interface ( What the first pass found and what the correction turn did with it.
What I checked myself.
Cost in check mode, measured on a 3,735-module application, ten alternating clean builds a side: the first build twice, +0.032% and +0.006% of the check build by means (+0.045% and +0.027% by medians); the second build, the one to apply, +0.000% by means and +0.029% by medians. The default build, which this code cannot reach, moved by +0.013% to +0.157% in the same runs: that is the size of the noise. Accepted: the slice costs between nothing and about +0.03%, and phase C stands at about +0.2% to +0.26% of its +0.3%. CI on 9e25191: 23 of 23. Owed, and to whom.
Not rerun by me: any cargo command (the three filters, clippy and Merging. The slice is built next, by applying the two v2 comments. |
Design turn 14 for slice T6u, the seal: the flatten rules F1 to F8 applied in the naming replay's walk, after which the new side of check mode runs no flatten pass. This pull request holds the interface the seal calls, the design, and the worker prompt. It holds no
seal.rsand converts no file of the lowering; the default build does not reach any of it and the generated JavaScript is unchanged.Corrections of the second turn
ifF3 and F5 writeset_literal_body_adoptingvalidates and reads purity; the builder's flags test has one carrier each ofHAS_FUN,HAS_GLOBAL,SEAL; both pairs compare what each statement holds on both sides. Each seen to fail on the wrong body named.adopt_block_listand rowsownunder a weightmod bothmin(2, 3)returned, source maps on) and the mappings differed. The seal now gives the location to the statement it writes;Js::locationis new on trunk; two tests are in the build.seal_dropped_literals), 0 on both corpora and 1 on the reproducer; the prompt says what the builder does if it is not zero. The fix is not designed.// T6X-THROWAWAY T6u v2, against commit 84e1bb8; fetched back and applied in order. The prompt is brought in line.Every change to a check, a pinned number or a test since the first turn. On trunk in this pull request:
bir::lower595 to 596 (the_location_of_a_node_is_the_one_it_was_given, added;a_reader_reads_what_the_lowering_reads_todaygains two assertions); three tests strengthened and none weakened (the_changed_body_of_a_function_literal_is_put_back_by_its_headeron rows,a_changed_list_is_put_back_and_its_statement_gains_the_flags_of_its_statementson the builder, whose step count is now1 + 4for a list of four, and the two pairs); two debug assertions added (adopt_block_list, rowsown); the recount branch ofadopt_block_listdeleted.bir::j131 andemit::builder85 unchanged. In the build:Sealed80 to 88 bytes andWork104 to 112 (the new counter); the debug assertion "a conditional with a source location at the seal" removed (it was wrong); three tests added (bir::lowerends at 613, 597 after the first commit);Unit::sealedjudges every hand-built test a second time, after the later passes. The allocation pins are as in the first build (86, 104, 86, 156).Breaks seen to fail in this turn: rows
set_literal_body_adoptingsetting parents withoutrepair(rows_stmt.rs, in that function) fails its rows test; the builder taking overHAS_FUNonly (builder.rs:2011) fails the flags test and, run on the pairs,replay::both::a_changed_list_put_back; rowslocationwithout the flag test (rows.rs:323) failsthe_location_of_a_node_is_the_one_it_was_given; in the build,seal::locateddoing nothing (seal.rs:411) fails the two location tests,unenteredreturningmodefails one, and a second offer inReplay::sealfails eleven.Not run in this turn either: the fixtures corpus, the parity suites locally, the 3,735-module application (the coordinator measured the first build there).
What is on trunk with this pull request
Interface (
JsStmt,src/bir/lower/js_stmt.rs), on rows and on the builder:ownBir::detachwhen the parent is set, no stepBuilder::own_statement: nothing, plus a debug assertion on the handle's rowseal::take(F1 to F6) and the block arm (F7, F8)set_body_adoptingwrite_block, thenBir::adopt_block_listset_body, and the statement's row gains the inherited flags of the statements put backReplay::statements, when a frame closes in which a rule wroteset_literal_body_adoptingset_literal_bodyBir::adopt_block_listis new insrc/bir/edit.rs, which is outside the listed interface files: the parent links, the slot weight, the use counts andrepairare private there, so the primitive has to live there.Tests added (no existing test changed):
a_statement_taken_out_of_a_list_is_the_callers_own,a_changed_list_is_put_back_and_its_statement_gains_the_flags_of_its_statements,a_changed_list_put_back_costs_one_step_a_statement_at_any_width,the_changed_body_of_a_function_literal_is_put_back_by_its_header.a_statement_taken_out_of_a_list_is_released_once_it_is_owned,a_changed_list_is_put_back_and_its_block_adopts_and_is_repaired,the_changed_body_of_a_function_literal_is_put_back_by_its_header,a_changed_list_put_back_costs_one_step_a_statement_at_any_width, and the pairsreplay::both::a_changed_list_put_backandreplay::both::the_changed_body_of_a_function_literal_put_back.Each seen to fail once on a break (line on the tree of commit 751e121):
ownbody emptiedadopt_block_listwithout the parent storeadopt_block_listwithoutrepaira_changed_list_is_put_back_and_its_block_adopts_and_is_repairedown_statementcounting a stepset_literal_body_adoptingemptiedset_body_adoptingwithoutset_bodya_changed_list_put_backset_literal_body_adopting(line not recorded; the failing output was cut short)the_changed_body_of_a_function_literal_put_backDocument:
THREE_TREES.md11.4 gains "T6u: the seal" ((a) to (g) and 19 decisions); 11.9 gains the prompt "Task T6u:".Every change to a check, a pinned number, a test or an attribute
In this pull request: the tests listed above are added;
#[inline]on the rows form ofown. No expected value of an existing test changes, no pin moves, nothing is ignored. Filters:bir::lower595 (unchanged),bir::j131 (was 125),emit::builder85 (was 81). Self-test:32 files, 0 transition calls.In the posted build of T6u (not on trunk; the worker's pull request will carry them):
Frame12 to 24 bytes; the four allocation pins ofunit.rs85, 103, 85, 155 to 86, 104, 86, 156;ten_thousand_nested_lists_move_each_statement_oncerebuilt over nestedifs with its numbers kept; the oracles oforacle_tests.rs,export.rsandffi_args.rsflatten the legacy side and drop pass 1 from the new side;bir_passes_oraclebecomes the passes after flatten;finish_lowered_outputdeleted;#[serde(flatten)]onSwitchStats::sealed; 14 tests added (bir::lower595 to 609).The build of T6u
The build to apply is the second: two comments that start
// T6X-THROWAWAY T6u v2, against commit 84e1bb8 (1 of 2, 2 of 2). The first build (on 751e121, comments 7257366508 and 7257366778) is superseded. It is two comments, not one: with two lines of context the diff is 80,104 characters and a comment holds 65,536. Both were fetched back, compared byte for byte with the saved files, and applied in order withgit apply.The cut is one slice in two commits: the code (695 added, 109 removed) and the hand-built tests (570 added). The first is over the 600-line guide and cannot be cut by rule, because a partly sealed program cannot be handed to the flatten pass for the rest (decision 16).
Check-mode debug build, commit 751e121 then the build:
tests/testsunnamed_referencesstatements=movesdescendedname_replay_stepsglobal_stepsglobals_qualifiedseal_offeredglobals_qualified,scopes,reservedare equal on every unit. The second build reads the same counters in every row, andseal_dropped_literals0 on both corpora. On it: filters 613 / 131 / 85 (597 after the first commit), clippy andcargo docclean on both commits, cost checkchanged/new=27; missing/generic=0, self-test33 files, 0 transition calls, row search 0.What a review should confirm
let run2 = c => { let _ = c ? (z => z + y) : ext2(); let y = ext(); y + 1 }under a top-levelyreads 1 name difference and 2 free-list differences in check mode with the build. On trunk the same unit reads 0, because the pass and the replay both read the unflattened program there, and both disagree with the JavaScript the backend prints: the seal makes an existing difference visible. No unit of the runtime or oftests/testshas the form. The build pins the behaviour with a test and does not fix it; it has to be designed before the flip.iflists of F3 and F5 hold the parts of a branch where the pass holds one block; accepted on equal text in 36 forms.edit.rsand has two preconditions (no weighted switch, asserted; no capture computed, stated).Not run
The fixtures corpus (no OCaml compiler was built in the sandbox), the parity suites,
Instruction count(read from CI), the 3,735-module application.Started by Jaap Frolich in this Assistant session