Skip to content

Three trees T6 design turn 14: the seal (T6u) built once - #434

Merged
jfrolich merged 10 commits into
ocaml-to-rust-rewritefrom
three-trees-t6-seal-design
Nov 29, 2026
Merged

jfrolich merged 10 commits into
ocaml-to-rust-rewritefrom
three-trees-t6-seal-design

Conversation

@jfrolich

@jfrolich jfrolich commented Nov 29, 2026 •

Copy link
Copy Markdown
Owner

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.rs and 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

Item State What
C1, the lists of the if F3 and F5 write DONE The trees differ from the pass's and the text does not: nine branch shapes in four statements, 36 forms, each "same text" on both judges (as sealed against the flatten pass, and after the later passes on both). Accepted as decision 20; the test is in the build.
C2, the tests of the interface DONE The rows test of set_literal_body_adopting validates and reads purity; the builder's flags test has one carrier each of HAS_FUN, HAS_GLOBAL, SEAL; both pairs compare what each statement holds on both sides. Each seen to fail on the wrong body named.
C3, adopt_block_list and rows own under a weight DONE, option (a) No weighted switch is live in an arena the lowering writes: stated as the precondition, asserted in debug builds, the recount branch deleted.
C4, the prompt's contradiction DONE The prompt names every line of an external-shadow test that changes; any other change is the failure.
C5, the doc comment of mod both DONE Moved back to head the module.
C6, decision 17 DONE, and the decision was wrong A located conditional does reach the seal (min(2, 3) returned, source maps on) and the mappings differed. The seal now gives the location to the statement it writes; Js::location is new on trunk; two tests are in the build.
C7, decision 12 DONE The three reference outputs are in the decision; the build counts the form (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.
C8, cost DONE One paragraph in (g): what a statement no rule applies to pays. Nothing changed for it.
C9, the build posted again DONE Two new comments, // T6X-THROWAWAY T6u v2, against commit 84e1bb8; fetched back and applied in order. The prompt is brought in line.
C10, this section DONE

Every change to a check, a pinned number or a test since the first turn. On trunk in this pull request: bir::lower 595 to 596 (the_location_of_a_node_is_the_one_it_was_given, added; a_reader_reads_what_the_lowering_reads_today gains two assertions); three tests strengthened and none weakened (the_changed_body_of_a_function_literal_is_put_back_by_its_header on rows, a_changed_list_is_put_back_and_its_statement_gains_the_flags_of_its_statements on the builder, whose step count is now 1 + 4 for a list of four, and the two pairs); two debug assertions added (adopt_block_list, rows own); the recount branch of adopt_block_list deleted. bir::j 131 and emit::builder 85 unchanged. In the build: Sealed 80 to 88 bytes and Work 104 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::lower ends at 613, 597 after the first commit); Unit::sealed judges 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_adopting setting parents without repair (rows_stmt.rs, in that function) fails its rows test; the builder taking over HAS_FUN only (builder.rs:2011) fails the flags test and, run on the pairs, replay::both::a_changed_list_put_back; rows location without the flag test (rows.rs:323) fails the_location_of_a_node_is_the_one_it_was_given; in the build, seal::located doing nothing (seal.rs:411) fails the two location tests, unentered returning mode fails one, and a second offer in Replay::seal fails 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:

Function Rows Builder Called by the seal from
own Bir::detach when the parent is set, no step Builder::own_statement: nothing, plus a debug assertion on the handle's row seal::take (F1 to F6) and the block arm (F7, F8)
set_body_adopting write_block, then Bir::adopt_block_list set_body, and the statement's row gains the inherited flags of the statements put back Replay::statements, when a frame closes in which a rule wrote
set_literal_body_adopting the same on a literal's body set_literal_body the same, for a function literal's body

Bir::adopt_block_list is new in src/bir/edit.rs, which is outside the listed interface files: the parent links, the slot weight, the use counts and repair are private there, so the primitive has to live there.

Tests added (no existing test changed):

  • builder, 81 to 85: 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.
  • rows, 125 to 131: 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 pairs replay::both::a_changed_list_put_back and replay::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):

Break Line Fails
rows own body emptied rows_stmt.rs:564 6 tests
adopt_block_list without the parent store edit.rs:1282 4 tests
adopt_block_list without repair edit.rs:1283 a_changed_list_is_put_back_and_its_block_adopts_and_is_repaired
rows literal form without the adopt rows_stmt.rs:482 the rows test and its pair
builder: the flags line removed builder.rs:2011 the flags test
builder own_statement counting a step builder.rs:1989 the own test
builder set_literal_body_adopting emptied builder.rs:2022 the literal test
builder set_body_adopting without set_body builder.rs:2010 pair a_changed_list_put_back
builder literal form storing an empty list in set_literal_body_adopting (line not recorded; the failing output was cut short) pair the_changed_body_of_a_function_literal_put_back

Document: THREE_TREES.md 11.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 of own. No expected value of an existing test changes, no pin moves, nothing is ignored. Filters: bir::lower 595 (unchanged), bir::j 131 (was 125), emit::builder 85 (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): Frame 12 to 24 bytes; the four allocation pins of unit.rs 85, 103, 85, 155 to 86, 104, 86, 156; ten_thousand_nested_lists_move_each_statement_once rebuilt over nested ifs with its numbers kept; the oracles of oracle_tests.rs, export.rs and ffi_args.rs flatten the legacy side and drop pass 1 from the new side; bir_passes_oracle becomes the passes after flatten; finish_lowered_output deleted; #[serde(flatten)] on SwitchStats::sealed; 14 tests added (bir::lower 595 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 with git 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:

Counter Runtime tests/tests
units identical 113 of 113, both 806 of 807, both
naming log differences, unnamed_references 0, both 0, both
statements = moves 1,934 to 2,286 22,236 to 24,037
descended 5,462 to 5,293 72,139 to 71,186
name_replay_steps 8,315 to 8,498 107,807 to 108,655
global_steps 2,729 to 2,729 26,076 to 26,091
globals_qualified 0 to 0 31 to 31
seal_offered 2,303 24,203
F1 / F2 / F3 / F4 / F5 / F6 / F7+F8 7 / 0 / 5 / 0 / 166 / 7 / 3 8 / 3 / 42 / 0 / 841 / 99 / 58

globals_qualified, scopes, reserved are equal on every unit. The second build reads the same counters in every row, and seal_dropped_literals 0 on both corpora. On it: filters 613 / 131 / 85 (597 after the first commit), clippy and cargo doc clean on both commits, cost check changed/new=27; missing/generic=0, self-test 33 files, 0 transition calls, row search 0.

What a review should confirm

  • Decision 12, an open defect. F3 drops a pure branch, and a function literal is pure. Its free entries stay in the rows around it, so the replay reserves a name the flattened program no longer reads. let run2 = c => { let _ = c ? (z => z + y) : ext2(); let y = ext(); y + 1 } under a top-level y reads 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 of tests/tests has the form. The build pins the behaviour with a test and does not fix it; it has to be designed before the flip.
  • Decision 20: the if lists of F3 and F5 hold the parts of a branch where the pass holds one block; accepted on equal text in 36 forms.
  • Decision 7: the builder's row gains flags and loses none; the primitive lives in edit.rs and has two preconditions (no weighted switch, asserted; no capture computed, stated).
  • Decision 16: the size of the first commit.

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

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>
@jfrolich

Copy link
Copy Markdown
Owner Author

// T6X-THROWAWAY T6u (1 of 2), against commit 751e121 of this pull request's branch; apply in order with git apply

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

@jfrolich

Copy link
Copy Markdown
Owner Author

// T6X-THROWAWAY T6u (2 of 2), against commit 751e121 of this pull request's branch; apply in order with git apply

--- 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}");
+}

open-session-submodule Bot and others added 3 commits November 29, 2026 14:37
…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>
@jfrolich
jfrolich marked this pull request as ready for review November 29, 2026 15:02
@jfrolich

Copy link
Copy Markdown
Owner Author

First-pass checklist review at 74e6097 (a checklist for the final reviewer, not an approval).

First-pass review (checklist, not an approval):

Setup: git fetch origin; D=origin/ocaml-to-rust-rewrite...origin/three-trees-t6-seal-design; git diff $D > $TMPDIR/pr.diff (8 files, +1081, -0). The build was set up as the brief asks. a = git archive 751e1216bf with the two comments applied. The fences were extracted with Python (chr(96)*3); diff 1 runs from its first diff --git (1109 lines) and diff 2 from --- a/ (462 lines). Both apply cleanly with git apply --unsafe-paths --directory=.: Applied patch compiler-rust/src/bir/lower/names.rs cleanly. and ... oracle_tests.rs cleanly. for diff 2, and no error for diff 1. hd = git archive origin/three-trees-t6-seal-design compiler-rust. No cargo was run (host review).

Findings that matter most

  1. F3/F5 put a different tree in their if lists than the pass does (UNCLEAR whether it shows). The pass's branch and F5 call this.statement(S::exp(e)) and put the result straight into j.stmt_list(&[..]) (js_pass_flatten_and_mark_dead.rs:874-899, 942-946). Nothing splices it there, so a branch that F1, F2 or F6 rewrites stays one Block[..] statement inside the if list.
    • The seal puts the branch into the if list as an exp or return_ statement (seal.rs:141-146, 223-253). The walk then seals that list like any other, so F1, F6 and F8 splice the parts into the list.
    • Smallest shapes: c ? (f(), g()) : h(); and return c ? (f(), g()) : h();. The pass gives If(c, [Block[f(); g()]], ..) (for the return form, [Block[f(); return g()]]). The seal gives If(c, [f(); g()], ..).
    • The printer writes a Block in a nested list without braces (printer.rs:633-639), so the lower text agrees. The passes after flatten then run on two different trees. I found none that cares (tailcall: StmtKind::Block(b) => list(..), js_pass_tailcall_inline.rs:109; Substitute::block_items maps without splicing).
    • No hand-built test has a sequence branch: f3 and f5 use calls and nested conditionals only.
    • What would decide it: a Unit::sealed form of each shape run through bir_passes_oracle on both sides, or the CI lower+passes text on a unit with that shape.
  2. The PR's rows set_literal_body_adopting and its test. The test (the_changed_body_of_a_function_literal_is_put_back_by_its_header) asserts the steps and one parent link, but never calls validate and checks no flag. A body that only sets the parents, without repair, would pass it and its pair. The pair compares statement kinds only.
  3. Bir::adopt_block_list's recount branch (edit.rs:1276-1281) is not covered by any test, and it differs from replace.
    • replace re-pins the slot's weight after its recount (self.weights[target.index()] = target_weight;, edit.rs:1200). adopt_block_list leaves the child's cached weight at the old value.
    • A statement a rule made has no cached weight, while its moved value's uses were counted at the old weight and never uncounted (detach keeps them).
    • This is harmless only while weighted_switches == 0, where every weight is 1 (weight, edit.rs:719). That holds when no L-level weighted View::Switch is live during the replay. I could not confirm that by reading: UNCLEAR.
  4. The prompt contradicts itself. Its list of "shortcuts that count as failure" includes "an external-shadow test of oracle_tests.rs changed". Yet the build changes shadow_rule and the pass lists of four external-shadow tests (&[1, 3, 4, 5, 6] → &[3, 4, 5, 6], and new_text(build, None, &[1]) → &[]). The prompt also tells the builder that "the passes lists lose pass 1". The list of "the task wins" overrides does not settle this.
  5. The PR moves an existing doc comment. The new rows test was inserted between the doc comment of mod both and mod both itself. At rows_stmt_tests.rs:1545-1555 (head), the comment "The two implementations of the lowering's interface, given the same statement, find the same things: …" now heads a_statement_taken_out_of_a_list_is_released_once_it_is_owned, and mod both (line 1687) has no doc comment.

1. Scope — PASS (with finding 5)

What the body and 11.4 (b) say this turn puts on trunk:

  • JsStmt::own, set_body_adopting, set_literal_body_adopting: js_stmt.rs:617-677 (trait); rows_stmt.rs:562-577 (rows); builder.rs:1979-2023 (own_statement, set_body_adopting, set_literal_body_adopting).
  • Bir::adopt_block_list: edit.rs:1254-1290.
  • Tests: rows_stmt_tests.rs (4 in mod replay, 2 in replay::both), builder_tests.rs (4). grep -c '^+.*#\[test\]' pr.diff → 10.
  • Document: THREE_TREES.md:7584-7864 ("T6u: the seal", (a)-(g), decisions 1-19) and 14301-14565 (the prompt).
  • Fragment: changes/three-trees-t6-design-14.internal.md.

The body says what was not done: the fixtures corpus, the parity suites, Instruction count (read from CI) and the 3,735-module application. Done but not asked for: #[inline] on rows own (stated in the body), and finding 5.

2. Default path — PASS

  • PR: no default-path function changes. grep -rn "own_statement\|\.set_body_adopting(\|set_literal_body_adopting(" compiler-rust/src (head, non-test) → no output. Only Rows implements JsStmt (rows_stmt.rs:110), and nothing calls the new functions.
  • Build: compile_deps_program_with_lower_check::<false> is the default path (compile_deps_program_in_arena, lam_compile.rs:758). It used to call finish_lowered_output (flatten, then finish_flattened_output(.., Pass)). Now it inlines the same two calls (build lam_compile.rs:901-906), so the default behaviour is the same.
  • The one change is before: it is now captured after flatten, and only if CHECK. The body gives no default-path measurement. CI Instruction count on this PR reads -1,490,808 (-0.034%), but that is for the PR, not the build.

3. Engineering standard (added lines of pr.diff) — PASS

  • (a) Cost stated on every new function: trait docs ("O(1); counts no step; allocates nothing", "One step, and one per statement adopted…"), adopt_block_list ("One read per entry and one store per statement adopted…"), builder ("One step, and one step, one move of 24 bytes and one flag read per statement").
  • (b) Step tests at 10,000: rows and builder a_changed_list_put_back_costs_one_step_a_statement_at_any_width (widths 1,000 and 10,000; asserts steps[0] >= 1_000 and steps[1] <= 11 * steps[0]; rows also asserts 0 allocations).
  • (c) grep -E 'HashMap|HashSet|BTreeMap' over the added lines → none.
  • (d) Allocation hits are all in tests (pr.diff lines 674-1136: collect, Vec::new, vec!). Production has no allocation. builder.rs:2010 .expect("a statement taken twice") is a panic, not an allocation.
  • (e) Locks, atomics, RefCell: none.
  • (f) No second pass over a tree.
  • (g) No new struct or enum in the PR.
  • (h) allow(, unsafe, todo!, #[ignore]: none; one #[inline] (pr.diff:636).

4. Tests and oracles — PASS (PR) / note (build)

  • PR: additions only. git diff --stat shows 0 deletions, and no ratchet file is touched.
  • Build (not on trunk): the oracles move as the design says (d1.diff:451-588).
    • step_a and a_copied_function_doubles… now count on shadow(export_js(lowered)) with no flatten(..). That is valid only because State::complete → finish runs replay_names, which seals (build mod.rs:808-853).
    • ten_thousand_nested_lists_move_each_statement_once is rebuilt over ifs with its numbers kept (20,001 / 2·9,000).
    • export_coercion_consumes_the_export_tuple_occurrence drops its own apply_js_flatten_pass because before[0] is now already flattened. That is right: a second run would not be idempotent.
    • No assertion is deleted.

5. New scripts and fixtures — PASS

None added.

6. Privacy — PASS

grep -n -i -E "tella|submodule\.nl|rescript-bench-corpus|/Users/|opensession|jake" on pr.diff → no hits. On d1/d2 → no hits. The only hits are the Session trailers in the commit messages.

7. Changelog — PASS

changes/three-trees-t6-design-14.internal.md starts with - Three trees T6 des…. git diff --name-only $D -- CHANGELOG.md → empty.

8. Numbers in the body — PASS (sources partly shown)

  • The counter table (units, statements, descended, name_replay_steps, global_steps, globals_qualified, seal_offered, rule counts) is given without the command that produced it.
  • The "before" column matches CI Backend bridge coverage on this head: runtime statements 1934, descended 5462, name_replay_steps 8315, reserved 583, scopes 336; tests/tests 22236 / 72139 / 107807 / 8770 / 4662, globals_qualified 31.
  • The filters (595/131/85) match CI (section 22).
  • The build's figures (609, 86/104/86/156, 33 files) cannot be checked without cargo. The self-test I could run (section 19c).

9. Focused tests — not run (host review)


11. Files against what a design turn may hold — PASS

Files: 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 repair are private there".

Bir::adopt_block_list (head edit.rs:1254-1290), whole:

    /// 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:

  • Parent links: sets parents[child] = Some(block) for each orphan entry. An entry that has another owner is only debug-asserted; a release build would leave that statement with two owners.
  • Slot weight: read once.
  • Use counts: adjusted by slot - weight when they differ.
  • repair(block): recomputes PURE, NO_ALLOC, STRICT and control facts, walking upward while a fact changes (edit.rs:950-985).
  • The closest existing function is replace/replace_impl (edit.rs:1111-1231). After its recount it does self.weights[target.index()] = target_weight; (l.1200), and it calls capture_moved for a detached tree (l.1228-1230). adopt_block_list does neither. Capture: no seal rule moves a use across a function or loop boundary, so this is fine for the seal. Weight cache: finding 3.

(ii) No default build reaches it: its only caller is rows set_body_adopting/set_literal_body_adopting, called from names.rs (check mode only, prepare_lower under if CHECK, lam_compile.rs:884).

(iii) Its stated cost matches its one loop (entries of the list), except for the adjust_counts subtree walk, which the doc names.

12. The three interface functions — PASS with findings 2 and 3

own.

  • Trait (js_stmt.rs:617-638): the statement taken by take_at "becomes the caller's own…". Cost: "O(1); counts no step; allocates nothing". Precondition: taken out of a list in flight; afterwards not to be put back with plain set_body.
  • Rows: if a.parents[s.0.index()].is_some() { a.detach(s.0); }.
  • Builder (builder.rs:1988): debug_assert_eq!(self.rows[statement.stmt.node_id().index()], statement.row, ..).
  • Both do what the doc says. Before own, a caller of take_at (rows_stmt.rs:157-160, just S(a.lists.get(list)[index])) holds a statement whose parent is still the block. After it, the parent is None and the weight is pinned.
  • Closest existing function: take_block_stmt (rows_stmt.rs:353-358, block_entry + a.detach + one step). It reads an entry of an SBlock statement, not a list in flight, so it is not a duplicate. release_stmt frees; lend_block_stmt lends and asserts the id is unchanged.

set_body_adopting.

  • Rows: let block = Self::body_block(a, s, index); Self::write_block(a, block, body); self.steps += 1 + u64::from(a.adopt_block_list(block));.
  • Rows set_body (rows_stmt.rs:466-474) debug-asserts that every entry's parent is the block. It refuses any other statement because write_block sets no parent links and repairs nothing: an orphan would stay unowned and the block's facts would go stale.
  • The adopting form fixes the parents, the weights and the facts, with the caveats in finding 3 and 11(i).
  • Builder (builder.rs:2004-2013): ORs row.flags over the pool slots, calls set_body, then statement.row.flags |= flags & INHERITED (INHERITED = HAS_FUN | SEAL | HAS_GLOBAL, builder.rs:80) and stores the row.
  • Can a rule remove the only carrier of a flag? Yes. F3 drops a pure branch, and both a function literal and a global Var are pure (facts.rs:16-24). The parent then keeps a stale SET flag, and only SET: rules only move existing nodes into new exp/return/if/block rows whose flags are unions of their children's, and no rule adds a function or a global.
  • Who reads the flag: below of the held statement ran before its bodies were opened, so a stale flag is read only by later readers of the builder rows. Rows has no such flag (Rows::has maps node bits, rows.rs:223-231; rows below reads every node). A stale CLEAR flag, which would lose a find, cannot happen by my reading.

set_literal_body_adopting. Rows: same as above on literal_block(a, header). Builder: self.set_literal_body(header, body). Both match their docs.

Tests, and one wrong body each would not catch:

  • Rows own: a.parents[..] = None without the weight pin passes. No test has a weighted switch.
  • Rows set_body_adopting: removing the adjust_counts branch passes (finding 3).
  • Rows set_literal_body_adopting: no repair passes (finding 2).
  • Builder own_statement: an empty body passes. That is what it is meant to be, minus the assertion.
  • Builder set_body_adopting: OR-ing only HAS_FUN (losing SEAL and HAS_GLOBAL) passes. a_changed_list_is_put_back_and_its_statement_gains_the_flags_of_its_statements checks only & flag::HAS_FUN.
  • Builder literal form: none found (it is one call).
  • The two replay::both pairs do not use alike. They compare the list of Kinds on each side ([Exp, Return, Exp], [Exp, Return]) and that the first statement keeps its id. No flags, no ids across sides.

13. The build against the legacy pass, rule by rule — FAIL-candidate (finding 1), otherwise SAME

Pass arm (head js_pass_flatten_and_mark_dead.rs) Seal (build seal.rs) Verdict
832-842 block_items: self.statement then StmtKind::Block(inner) => extend (F8) 262-271 (Kind::Block, _): own, unblock, reverse, re-offer SAME in lists the mapper maps. DIFFERENT in F3/F5 if lists (finding 1)
847-854 Exp/Seq → flatten_sequence_statements + S::block (F1) 163-170 + part 298-315 SAME. The chain is split one operand per offer; group gives the one-level splice; a trivial part is an empty block (Mode::Off)
855-867 Exp/CamlBlock (F2) 176-198 SAME (empty block kept only for ≥2 elements in Seal, matching S::block of one)
868-910 Exp/Cond (F3), test not mapped, source_loc: loc, comment: cold.comment 219-257, literals: unentered(mode) Rule SAME. The statement's comment is not carried (take releases it); the lowering's interface makes no statement comments (grep -n "fn .*comment" js.rs js_stmt.rs → only Js::comment on expressions), so it cannot show on the new side. The if list is DIFFERENT (finding 1)
911-932 Exp/Bin(Eq, _, Seq) (F4); target mapped later by self.statement(assign) 201-214, re-offered assignment SAME
933-936 Exp other: self.expression (maps the literals) 272 Final { literals: mode } SAME
939-955 Return/Cond (F5): each return mapped once, test not mapped 137-147 Rule SAME. if list DIFFERENT (finding 1: return c ? (f(), g()) : h())
956-978 Return/Seq (F6) + map_statement_children (second map) 152-160, heads Mode::Entered SAME (in Entered: no groups, trivial dropped, F3 tests entered)
979-982 Return other 272 SAME
984-987 Block of len 1 → self.statement(inner) (F7) 262-271 SAME
988 _ => map_statement_children (declarations, throw, loops, switch, try, labels) 272 Final; the walk opens lists with body_mode and literals with literal_mode SAME (no rule on a declaration's or throw's value on either side)
993-1003 / 1005-1013 full flatten of a chain sequence + re-offer SAME
  • Arm order: the value kinds are exclusive, so the order only matters for F4's guard, which is the same on both sides.
  • Recursion: the pass fires a rule first and maps the pieces after. The seal pushes the pieces and offers them later; a final statement's literals and lists are sealed after it is named. Same order.
  • The three behaviours outside the table:
    • S::exp (build.rs:1207-1222): strip/trivial reproduce it, including the recursive drop of a trivial side.
    • F6's second map: Mode::Entered.
    • One-level splice: group.
  • An if branch that becomes empty: an empty list on both sides; else_block_is_omitted_like_ocaml treats [] and [Block[]] alike.
  • Function-literal bodies: reached through Replay::literal and unnamed_literal with held.literal_mode (build names.rs:1507, 1526).

14. "Without effect" (decision 5) — PASS by reading

Pass: js_ir/build.rs:102-158 expression_has_no_side_effects. Build: pure = js.has(e, flag::PURE). On rows that is node bit 0 (rows.rs:223-225), set from j::facts::purity(self, id, false, ..) (edit.rs:812, 877, and repair 957-971). facts.rs:8-94 is documented as "B:102 expression_has_no_side_effects".

Kind Pass PURE (facts.rs, strict=false)
variable / global (Var, Qualified) true true (Var, JQualified)
constant (num/str/bool/null/undefined/json) true true
function literal true true (JFun)
member read StaticIndex / CamlBlockTag pure(target) JDot → child(object) (aux 1 = CamlBlockTag, bridge_j.rs:1140)
index read both JIndex both
call false, except Array.isArray(x) same (is_array_is_array)
new false false
binary op / comparison op != Eq && both same (the div/mod check is strict-only)
conditional all three all three
sequence both both
array / block literal all all
object no spread && all same
template / interpolated true / all JTemplate all values
tagged template tag && all JTagged same
typeof, not, bnot, length, nullish, optional inner same
in, string append both both
assignment false (Eq) false
raw JS, await, spread, record rest false false
JSX false false

No kind answers differently. The remaining risk is a flag that goes stale after an edit, which repair is meant to prevent.

15. The open defect (decision 12) — PASS (the reading is right), cost noted

  • On trunk (head lam_compile.rs): compare_with_pass(&names.printed, .., &new_before, ..) reads new_before, the lowering's unflattened program (coerced_program(..)). apply_js_flatten_pass runs on the new side only later (l.927, on shadowed). The replay also walks the unflattened tree. So on trunk both sides of the naming comparison read the unflattened program, and the designer's sentence is right.
  • The build does not change where the backend's own printed names come from (the printer on the legacy program). It changes the program compare_with_pass walks: the sealed one.
  • The dropped literal's free entries were merged into the enclosing rows at close time. The build's pinned test (a_function_literal_in_a_branch_the_seal_drops_is_not_entered) asserts u.free(scope).len() == 3 and (scopes, reserved, unnamed_references) == (1, 4, 0).
  • checked_sub(..).expect("a function literal found twice") (build names.rs:1372) cannot fire: no rule copies a literal. A dropped literal keeps unfound above 0, so the early end never comes for the rest of that unit. That is a cost, and the build does nothing about it (11.4 (d): "costs the early end and nothing else").

16. External-shadow decision, early end, quiet frames — PASS

  • Order: the root's enter_list runs right after open(list, .., Mode::Seal) and before any statement is sealed (build names.rs:1069-1072). A held statement's list gets enter_list at advance (build names.rs:1247-1262). That includes the new if lists of F3/F5, which are given a frame like any list (self.open(list, 0, ScopeId::NONE.0, mode)). Blocks and switches are excluded.
  • F8: enter_list reads the declarations of nested SBlocks "to any depth" (JsStmt::declarations), so a block spliced after the parent's enter_list was already covered. I found no shape where the decision reads a different program than the legacy pass after flatten.
  • Early end: sealing does not depend on want; Replay::statements calls self.seal(..) for every take_at (build names.rs:1095). Literal bodies are opened only when found, which rests on T6r item 3: every literal has a closed row, and a unit with a literal has a row past the first.
  • Quiet frames: unnamed_literal opens with held.literal_mode (build names.rs:1526), so the body is sealed.
  • Item 3's assertion is in both arms (build names.rs:1351-1355):
                    _ 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.

  • Item 7: the build's globals.rs reads: "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."

17. What check mode compares — PASS

  • before: [before.expect(..), new_before]. Left: the backend's program after its own apply_js_flatten_pass (build l.901-905). Right: coerced_program(..) of the sealed lowering.
  • after: [deps, new_after], the same finish_flattened_output on both sides, Pass vs Decided.
  • Naming log: the legacy naming pass on the sealed program against the replay's log.
  • compare_decisions: legacy counts on the sealed program after qualify.
  • Oracles: see 11.4 (c) and section 4. The legacy side is flattened once (oracle_tests.rs compare_oracle, export.rs:2269, ffi_args.rs:851), and nothing sealed is given to the pass.
  • No comparison has the same new code on both sides. Unit::sealed exports the same tree before and after the replay and judges by apply_js_flatten_pass, so it is independent.
  • finish_lowered_output on trunk was called at head l.682 (bir_passes_oracle) and l.895 (default path). Both behaviours are kept (build l.684 finish_flattened_output(.., Pass); l.901-906).
  • grep -n apply_js_flatten_pass in the build's lam_compile.rs → 29: (import), 903:, as the prompt says.

18. Structures and cost — PASS

  • Frame: was { list, at, leave }, 12 bytes. Gains seal: Marks (pending: u32, staged: u32, mode, changed, group), so 24 bytes. row_sizes asserts 24.
  • Live frames: one per open list plus group frames, so nesting depth.
  • seal::tests::sizes: Mode 1, Pending 8, Marks 12, Outcome 8, Sealed 80, Work 104.
  • Work stack: Scratch::seal.pending, reserved once to the node count (build names.rs:810). The seal also uses the rows operand stack (unpack_rev/pop, rows.rs:513-627), and every step pops what it pushes before it returns. Between pops, F2 calls strip/release/exp/list, none of which touch operands. Rows::work (below, declarations) is separate.
  • Loops:
    • F2: for _ in 0..elements (literal arity).
    • strip: while kind == Seq (removes a node per turn).
    • unblock: per statement.
    • The Replay::statements loop: statements plus pending.
    • close_group: drains staged.
    • Nothing recurses.
  • Step tests: the_seal_offers_each_statement_once_at_any_width_and_depth asserts exact counts (2n-1 offered, n-1 F1), small >= 1_000 and large <= 11 * small for both steps and offers. the_seal_splices_ten_thousand_nested_blocks_into_one_list asserts 2n+1 offered and n F7/F8. Prompt break 1 is the one seen to fail.
  • Pins: the one extra allocation is scratch.seal.pending.reserve_exact(..), once per fresh unit.
  • Added production lines of the build:
    • expect( ×6 in names.rs (pop().expect("a pending statement") per pending statement; frames.last_mut().expect(..) per offer; held.last().expect(..) per literal).
    • Closures: seal.rs:131 .map(|value| js.kind(a, value)) per offer, and seal.rs:268 |inner| pending.push(..) per block.
    • seal.rs:99 Vec::new() in Default (no allocation).
    • new_before.clone() existed before as shadowed.
    • No unsafe, inline, cold, HashMap, format! or Box::new.

19. The prompt against the build — PASS except (g)

(a) End-state searches, head → build:

  • grep -n apply_js_flatten_pass lam_compile.rs: 29, 927, 1039 → 29, 903.
  • finish_lowered_output: 3 → 0.
  • names.rs seal::step: 0 → 3; set_body_adopting: 0 → 3; set_literal_body_adopting: 0 → 1; the quiet message: 0 → 2.
  • mod seal: 0 → 1. js.own( in seal.rs: 2.
  • oracle_tests apply_js_flatten_pass: 8 → 4.
  • Row search: 0 for every non-test file, both trees.

All as the prompt says.

(b) numstat of diff 1 alone (git diff --no-index --numstat): export 4/0, ffi_args 3/0, globals 5/2, mod 6/0, names 169/47, oracle_tests 22/20, seal 412/0, unit 10/5, lam_compile 18/23. Diff 2: names 381/0, oracle_tests 58/0. These equal the prompt's commit 1 and commit 2.

(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 python3 -I ../scripts/count_lowering_ids.py --self-test: 751e121 → 32 files; build → 33 files.

(d) Every name the prompt gives exists in the build: take, trivial, part, branch, strip, sequence, assigns_sequence, pure, unentered, conditional, close_group, Storage::sealed, sealed_deep, row_sizes, the 13 tests, and the interface functions stmt_kind, value_of, kind, aux, has, operand, located, keep_operand, unpack_rev, unblock, explicit_block, if_plain, bin_plain, not, return_, take_value. None is missing.

(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:

  • Re-offer in the Final arm: every hand-built test asserts seal_offered, so 11 fail.
  • unentered returning mode: the_heads_of… form(false) seals the literal in the test.

(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

  1. Seal in Replay::statements, no recursion. CONFIRMED by reading (names.rs:1078-1096).
  2. Three modes. CONFIRMED against pass l.868-978.
  3. The constructor is part of the rules. CONFIRMED (build.rs:1207-1222 against strip/trivial/part).
  4. Group frame. CONFIRMED by reading.
  5. PURE equals B:102. CONFIRMED node by node (section 14).
  6. own kept. CONFIRMED (take_at does not detach).
  7. Adopting setters and superset flags. CONFIRMED, with DOUBT on the recount branch (finding 3) and on test coverage (finding 2).
  8. Frame 24. CONFIRMED (row_sizes).
  9. before is "backend after flatten" against "sealed". CONFIRMED (l.901-905, 950).
  10. No binding crosses a list. CONFIRMED by reading the rules: they make exp, return, if and blocks of existing statements.
  11. Quiet frames sealed with literal_mode. CONFIRMED.
  12. Open defect. CONFIRMED (section 15).
  13. Assertion in both arms. CONFIRMED in code; it held on two corpora, not three.
  14. +1 allocation. CONFIRMED (one reserve_exact); the count itself is NOT CHECKED (no cargo).
  15. F4 and F7 kept. CONFIRMED as the same arm. "Eleven lowering tests" NOT CHECKED.
  16. 746 lines (649+97) and no cut. Numbers CONFIRMED. The "cannot be cut" argument is sound: once the oracles flatten the legacy side, every rule must be there.
  17. No location on the if. DOUBT. The pass gives the new if source_loc: j.expr_loc(expr) (l.902-908, 947-953). On the legacy side a conditional can get a location from compile_apply_call or from compile_primitive with default compilation (with_expr_loc when expr_loc is none, lam_compile.rs:1375-1377, 1931-1935) if that call or primitive compiles to a Cond. The build's debug assertion checks only the lowering's side. A source map would show it as a statement mapping at if (. What decides it: any legacy Cond that is located (source-map oracle test on an inlined call or primitive that yields a conditional).
  18. #[serde(flatten)] sealed. CONFIRMED (build mod.rs).
  19. deep_constant note. CONFIRMED (quoted in section 16).

21. State lines, counts, cross-references — PASS

  • grep -E '^[-+].*State:' over the doc hunks → none added or changed.
  • The subsection's counts equal the body's tables.
  • Cited headings exist: "T6 design" (l.2431), "T6: the interface" (3114), "T6x-e and T6x-f…" (5040), "T6r…" (5909), "Corrections after the review of the thirteenth turn" (7502, items 3 and 7 at 7535 and 7569), "T4c design" (1052).
  • docs/LOWERING_ALLOCATION_SCALING.md exists.

22. CI on 74e6097 — PASS

  • gh pr checks 434: every check passes. Among them: Backend bridge coverage, base/head/compare, build, build-system-tests (and macOS), compiler-tests, compiler-warnings, the oxc parity jobs, the parity jobs (analysis, diagnostics, gentype, javascript, stdlib), Signature equality, Snapshot equivalence, script-tests, Playground wasm, Derived code.
  • compiler-tests log: test bir::lower::… ok 595, test bir::j::… ok 131, test emit::builder… ok 85, and FAILED 0. Library result: test result: ok. 3293 passed; 0 failed; 42 ignored. I did not compare the 42 ignored with the base; the PR adds no #[ignore].
  • compiler-warnings: pass (clippy -D warnings, rustdoc -D warnings).
  • Instruction count: base 4,355,437,189, head 4,353,946,381, change -1,490,808 (-0.034%), "Within the threshold of +0.1%".
  • Backend bridge coverage: lower identical fixtures 617/617, runtime 113/113, tests/tests 806/807 (1 shared Lambda subtree with binder). name_differences, free_differences and finish_differences are 0 in all three. unnamed_references is 0.

10. Where I would look hardest

  1. Finding 1, the if lists of F3/F5. It is the only rule-level tree difference I found, and every hand-built test and the gate compare printed text, which cannot see it.
  2. adopt_block_list against replace (finding 3): the weight cache and the recount for new statements. It is a general primitive on trunk now, documented for "statements made or detached", but only proved for weight 1.
  3. Decision 17 and the comment field of F3/F5: the pass carries the conditional's source_loc and the statement's comment into the if, and the seal carries neither. Only source-map oracle tests could tell, and none is added for F3/F5.

@jfrolich
jfrolich marked this pull request as draft November 29, 2026 15:06
open-session-submodule Bot and others added 4 commits November 29, 2026 15:14
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>
@jfrolich

Copy link
Copy Markdown
Owner Author

// T6X-THROWAWAY T6u v2 (1 of 2), against commit 84e1bb8 of this pull request's branch; apply in order with git apply

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

@jfrolich

Copy link
Copy Markdown
Owner Author

// T6X-THROWAWAY T6u v2 (2 of 2), against commit 84e1bb8 of this pull request's branch; apply in order with git apply

--- 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);
+    }
+}

open-session-submodule Bot and others added 2 commits November 29, 2026 15:30
…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>
@jfrolich
jfrolich marked this pull request as ready for review November 29, 2026 15:56
@jfrolich

Copy link
Copy Markdown
Owner Author

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 (JsStmt::own, set_body_adopting, set_literal_body_adopting on rows and on the builder; Js::location on rows), Bir::adopt_block_list, their tests, the design "T6u: the seal" (decisions 1 to 20) and the prompt "Task T6u: the seal.". The slice itself is not here: it is the two comments // T6X-THROWAWAY T6u v2 (7258109306, 7258109687). No default build reaches any of it.

What the first pass found and what the correction turn did with it.

  1. The lists of the if F3 and F5 write hold the parts of a branch where the pass holds one block statement. The generated JavaScript is the contract, not the tree: the correction turn shows 36 forms (nine branch shapes in four statements) printing the same on two judges, as sealed against the flatten pass and after the passes that follow it on both programs, and Unit::sealed now runs the second judge for every hand-built test. Accepted as decision 20.
  2. Interface tests that passed on a wrong body: the rows test of set_literal_body_adopting now validates and reads the body's purity; the builder's flags test has one carrier each of HAS_FUN, HAS_GLOBAL and SEAL; the two pairs compare what each statement holds on both sides.
  3. adopt_block_list under a weight: the recount branch, which ran in no test and stored no weight, is deleted; the precondition (no weighted switch in the arena) is stated and debug-asserted there and in rows own. I read it: is_weighted_switch (edit.rs:657) matches a View::Switch only, the count moves at edit.rs:702 and 704 and nowhere else, and the lowering writes level J into an arena of its own.
  4. Decision 17 was wrong. A located conditional does reach the seal (min(2, 3) returned compiles to a located 2 < 3 ? 2 : 3 on both sides; with source maps on, the pass's if had a mapping and the first build's had none, and the first build's own debug assertion fired). The seal now reads the conditional's location and gives it to the statement it writes. This is the first pass's DOUBT confirmed by a run.
  5. The prompt's contradiction on the external-shadow tests is gone: item (10) names every line that changes, and any other is the failure.
  6. The doc comment of mod both heads its module again.

What I checked myself.

  • The delta of built code since the first head, whole: edit.rs, rows.rs, rows_stmt.rs, js.rs, js_stmt.rs, and the three test files.
  • The second build applies in order on 84e1bb8 and on this head. Its numstat is the prompt's: 695 added and 109 removed in the first commit's files, 570 added in the tests (names.rs 683 / 59 and oracle_tests.rs 103 / 20 in all, seal.rs 433).
  • The prompt's end-state searches on the applied build: js.own( 2, js.location( 1, locate_stmt 1 in seal.rs; seal_dropped_literals 4 in names.rs; apply_js_flatten_pass at the import and one call of lam_compile.rs, finish_lowered_output gone; the row search prints 0 for every file of src/bir/lower outside the three whole-file test modules; count_lowering_ids.py --self-test "33 files, 0 transition calls"; the cost-note check changed/new=27; missing/generic=0.
  • The second build against the first, whole (seal.rs 32 / 11, names.rs 138 / 17, oracle_tests.rs 23 / 0): the location, the counter, the second judge, the tests. Nothing else moved.
  • F3 and F5 of the build beside Flatten::statement (js_pass_flatten_and_mark_dead.rs 868 to 912 and 938 to 956): the four cases of F3 and the one of F5 are the pass's; the location is carried now; the statement's comment is not, and cannot be (the interface makes no statement comment).
  • The new counter subtracts two unsigned counts. It cannot wrap: a function header's owner is written when its literal node is accounted (edit.rs:495) and cleared when it is released (520), and nothing in the replay accounts a literal for a header that had none.
  • Decision 12, by programs put to the OCaml compiler and to the default build: with the literal dropped both print let y = ext();, with it kept both print let y$1 = ext();. The reference names the flattened program, so the defect is the new naming's, and the build makes it visible instead of hiding it.

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. bir::lower 596, bir::j 131, emit::builder 85, tc:: 434; library 3311 passed, 0 failed, 25 ignored. Instruction count +0.017% (4,355,117,422 to 4,355,869,269) on code the default build does not reach: noise.

Owed, and to whom.

  1. Decision 12 (a function literal in a branch F3 drops keeps its free names reserved): a design of its own before the flip, and it must cover every later rule that drops an expression holding a function literal (the mark-dead and shake slices). The counter seal_dropped_literals is 0 on the runtime and on tests/tests.
  2. The builder of T6u reports the fixtures corpus, which nobody has run under the seal: the rule counts, the naming log and seal_dropped_literals. If the counter is not zero there it stops, as the prompt says.
  3. The builder over oxc has no located, locate, locate_stmt or location: owed to T6v, with a pair for each.
  4. F3 with a located conditional and an effect in a branch has a hand-built test only (no such conditional was found through the lowering); the comment F3 gives its statement is not carried. Owed to the slice that first compares mappings on the new side.
  5. adopt_block_list computes no capture: stated, not checked. A debug check is owed to the first caller outside the seal.
  6. Item 8 of "Corrections after the review of the fourteenth turn" quotes the first measurement only; the three are above.

Not rerun by me: any cargo command (the three filters, clippy and cargo doc are CI's on this head and the designer's on the build); the 36 forms and the breaks the designer saw fail; the check-mode debug builds of the runtime and tests/tests on the second build; the fixtures corpus and the parity suites on the build.

Merging. The slice is built next, by applying the two v2 comments.

@jfrolich
jfrolich merged commit 9b76caf into ocaml-to-rust-rewrite Nov 29, 2026
23 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant