diff --git a/changes/three-trees-t6-design-14.internal.md b/changes/three-trees-t6-design-14.internal.md new file mode 100644 index 0000000000..c9ab612339 --- /dev/null +++ b/changes/three-trees-t6-design-14.internal.md @@ -0,0 +1,4 @@ +- Three trees T6 design turn 14: the lowering interface can own a statement taken out of a list, put a changed list + back and read the source location of a node (`JsStmt::own`, `set_body_adopting`, `set_literal_body_adopting`, + `Js::location`; the first three on rows and on the builder, with a pair each for the two setters), and THREE_TREES.md + records the build of slice T6u (the seal: the flatten rules in the naming replay's walk) and its prompt. diff --git a/compiler-rust/docs/THREE_TREES.md b/compiler-rust/docs/THREE_TREES.md index 1c12b3b953..3462a1d4f5 100644 --- a/compiler-rust/docs/THREE_TREES.md +++ b/compiler-rust/docs/THREE_TREES.md @@ -7581,6 +7581,421 @@ decided or owed. check-mode runs and breaks; the fixtures corpus under T6r-f (the builder's CI runs it). +#### T6u: the seal + +Design turn 14. The seal is the flatten pass of the backend in use +(`Flatten::statement` and `Flatten::block_items`, +`lambda/js_pass_flatten_and_mark_dead.rs`) written once over the +statement interface and run by the naming replay's walk; with it the +new side of check mode runs no `apply_js_flatten_pass`. It was built +once, in a throw-away on commit 751e1216b of pull request 434, and +corrected once after the review of that build (the two comments there +that start `// T6X-THROWAWAY T6u v2`, on commit 84e1bb8ba7; the two +that start `// T6X-THROWAWAY T6u (` are the first build and are +superseded). Everything below marked "as built" is read from the +second build. The default build +does not reach it and its JavaScript is unchanged. + +**(a) F1 to F8 as built, beside the pass.** `seal::step(js, a, +statement, mode, work)` is given one statement the walk holds +(`Replay::seal`, called from `Replay::statements` for a statement +taken out of a list and for one popped from the work stack, before +the statement is named). It reads the statement's kind +(`JsStmt::stmt_kind`) and, for an `Exp` or a `Return`, the kind of its +value (`JsStmt::value_of`, `Js::kind`). A rule that applies takes the +statement apart and pushes what replaces it on `Work::pending`; the +walk pops and offers each again. A statement no rule applies to is +final. Each offer is one step (`Sealed::seal_offered`). + +| Rule | The pass's arm (condition as written) | The seal, as built | Reads | Makes | Releases | Cost | +| --- | --- | --- | --- | --- | --- | --- | +| F1 | `StmtKind::Exp(expr)`, `ExprKind::Seq(_, _)`: `flatten_sequence_statements`, then `S::block(&block, j)` | the two operands, each a part (`part`), the second pushed first; a chain is opened one operand an offer | kind of the value | two `exp` statements, or an empty block for a trivial part | the sequence node (`take_value`, `unpack_rev`) | O(1) an offer; a chain of n parts n - 1 offers | +| F2 | `ExprKind::CamlBlock(args, _, _)`: `S::exp` and `self.statement` an element, then `S::block` | `unpack_rev`, one `exp` an element, in order | kind of the value, kind of each element | one statement an element | the literal node; a trivial element | one step an element | +| F3 | `ExprKind::Cond(test, consequent, alternate)`: `branch` drops a side for which `expression_has_no_side_effects`; `(true, true)` gives the test or an empty block, `(true, false)` `If(not test)`, `(false, _)` `If(test)` | the same four cases over the `PURE` flag (decision 5); the branches are statements of the `if`'s lists and are offered where the walk reaches those lists (decision 20); the test is not entered; the statement written takes the conditional's source location (decision 17) | kind and location of the value, `PURE` of the three operands | `if_plain`, one or two lists of one statement, `not` | the conditional node; each dropped branch (one step a node of it) | O(1) and the release | +| F4 | `ExprKind::Bin(BinOp::Eq, target, value) if matches!(j.ek(value), ExprKind::Seq(_, _))` | the head a part, then `target = rest` offered again (so a chain costs one F4 a part) | kind and `aux` of the value, kind of its second operand | `bin_plain`, `exp` | the assignment and the sequence nodes | O(1) an offer | +| F5 | `StmtKind::Return(expr)`, `ExprKind::Cond(test, consequent, alternate)` | `if (test) { return yes } else { return no }`; each `return` is offered where the walk reaches its list (decision 20); the test is not entered; the `if` takes the conditional's source location | kind and location of the value | two `return_`, two lists, `if_plain` | the conditional node | O(1) | +| F6 | `StmtKind::Return(expr)`, `ExprKind::Seq(_, _)`: heads by `S::exp` and `self.statement`, `S::return_(last)`, `S::block`, then `map_statement_children(self, j, block)` | `return rest` pushed, then the head a part in `Mode::Entered` (decision 2) | kind of the value | `return_`, `exp` | the sequence node | O(1) an offer | +| F7 | `StmtKind::Block(block) if j.stmts(block).len() == 1` | one arm with F8: the block's statements pushed in order (`unblock`), offered again | kind of the statement | nothing | the block node | one step a statement | +| F8 | `Flatten::block_items`: `StmtKind::Block(inner) => flattened.extend_from_slice(j.stmts(inner))` | the same arm | the same | nothing | the block node | one step a statement | +| otherwise | `_ => { let e = self.expression(j, expr); ... }` and `_ => map_statement_children(self, j, stmt)` | `Outcome::Final`: the walk names the statement, then seals the bodies of its literals and its lists in the frame's mode | nothing more | nothing | nothing | O(1) | + +The three behaviours the table of "T6 design" (e) lacks, each a row of +the build: + +| Behaviour | In the pass | In the seal | Test | +| --- | --- | --- | --- | +| The statement constructor normalises | `S::exp` (`js_ir/build.rs`) makes an empty block of a number or `undefined` and drops the trivial side of a sequence | `trivial`, `strip`, `part`: a trivial part is an explicit empty block pushed as final in a list sealed once (the printer writes it as an empty line), and is dropped where the pass maps the result again | `f1_...` (`"f();\n\n\n"`), `f2_...`, `f6_...` | +| A second map | F6 ends with `map_statement_children` of its block, which maps the heads again: the test of an `if` F3 wrote is entered, an empty block is spliced away | `Mode::Entered` on the heads and everything below them | `the_heads_of_a_returned_sequence_are_sealed_with_their_tests_entered` | +| One level of splice | `block_items` splices the block a rule returned, one level: what a rule made of a part of F1, F2 or F4 stays a block inside it | `Pending::group` and a group frame: the statements a rule makes of a grouped part are staged apart and become one `explicit_block` when the frame closes (`Replay::close_group`) | `f1_...` third form (`"f();\ng();\n\nh();\n\n"`, `seal_groups` 1) | + +**(b) The interface additions.** The three of the probe are kept, as +landed in this pull request (`JsStmt` in `js_stmt.rs`, both sides, a +pair each for the two setters), and the review of the build added a +fourth, `Js::location` (decision 17): + +| Function | Kept | Caller in the seal | Rows | Builder | +| --- | --- | --- | --- | --- | +| `own(a, &mut statement)` | yes (decision 6) | `seal::take` (F1 to F6) and the block arm (F7, F8): a statement taken out of a list is still its block's until it is taken apart | `Bir::detach` when the parent is set; no step | `Builder::own_statement`: nothing, and a debug assertion that the handle's row is the table's | +| `set_body_adopting(a, &mut statement, slot, list)` | yes (decision 7) | `Replay::statements` when a frame closes with `Marks::changed`: the root list, and a list of a held statement | `write_block`, then `Bir::adopt_block_list` | `set_body`, and the statement's row gains the inherited flags of the statements put back | +| `set_literal_body_adopting(a, header, list)` | yes (decision 7) | the same place, for the body of a function literal | the same on the literal's body | `set_literal_body` | +| `Js::location(a, r)` | new (decision 17) | `seal::conditional`: the location of the conditional F3 or F5 takes apart, given to the statement written with `locate_stmt` | the node's flag, then its cold row | none: the builder has no form of `located`, `locate` or `locate_stmt` either | + +A list whose statements are all final as taken is put back with the +plain `set_body` (`changed` false): the adopting forms are paid only +where a rule wrote. + +**(c) What check mode compares once the seal is on.** Comparison by +comparison, the program on each side: + +| Comparison | Legacy side | New side | Independent? | +| --- | --- | --- | --- | +| `before` (lam_compile.rs, `compile_deps_program_with_lower_check`; shadow.rs prints both) | the backend's program after its own `apply_js_flatten_pass` | the lowering's program, sealed by the replay | yes: two implementations of the rules. Lost: the comparison of the two programs before any flatten | +| `after` | that program through `finish_flattened_output(.., ExternalShadow::Pass)` | the sealed program after `bridge_j::qualify`, through the same function without the external-shadow pass | the passes after flatten are the same code on both sides, as before | +| the naming log against the pass (`emit::compare_with_pass`) | the naming pass over the new side's sealed program | the replay's log | holds only on the seal's own output: both read the tree the seal wrote. It differs where the seal drops a function literal (decision 12) | +| `compare_decisions` | the legacy counts over the new side's program after `qualify` | the lowering's decisions | the counted program is now the seal's, where it was the flatten pass's of the new side's program: this comparison holds only because the seal produced that program. It is covered by `before` being identical on the same unit | +| the main oracle of oracle_tests.rs | the legacy lowering, then `apply_js_flatten_pass` | the lowering, sealed | yes | +| `new_text`, `new_text_assigning` and the passes lists of oracle_tests.rs | the legacy program through the listed passes (1 is flatten) | the sealed program through the listed passes without 1 | yes for pass 1; the later passes are the same code | +| `shadow_rule` | `apply_external_shadow_pass` of the legacy `before` | `shadow(export_js(..))` of the sealed program | yes | +| `export.rs::rule` | the legacy `before`, flattened, then `bir_passes_oracle` | the sealed program, then `bir_passes_oracle` | yes for the flatten; `bir_passes_oracle` is now the passes after flatten, the same code on both | +| `ffi_args.rs` | the expected program flattened | the sealed program | yes | +| `Unit::sealed` (names.rs tests) | the tree exported as built, then `apply_js_flatten_pass` | the same tree exported after the replay | yes: the direct judge of each rule | + +No sealed program is given to the flatten pass anywhere: the pass is +not idempotent (a block a group frame made would be spliced by a +second run). + +**(d) The rules against the decision, the early end and the quiet +frames.** + +| Rule | External-shadow decision | Early end of the descent (`unfound`) | Quiet frames | +| --- | --- | --- | --- | +| F1, F2, F4, F6 | cannot change it: the parts stay in the same list (a group block binds nothing: its statements are expression statements) | cannot: no literal is dropped or copied (a trivial part is a number or `undefined`) | not reached: an eta body is one `return callee(args)` | +| F3 | a reference can move into the list of the `if` F3 writes. That list declares nothing, and the bindings that cover it are those of the list around it: the decision is the same. Test: `a_global_in_a_branch_of_a_conditional_used_for_its_effect_is_covered_by_the_list_around_it` | CAN: a dropped branch may hold a function literal, whose closed row is then never found; `unfound` stays above zero and the descent runs to the end of the unit (decision 12). Test: `a_function_literal_in_a_branch_the_seal_drops_is_not_entered` | not reached | +| F5 | the same as F3, for `return`s. Test: `a_global_in_a_branch_the_seal_makes_a_list_of_is_covered_by_the_list_around_it` | cannot: nothing is dropped | not reached: the value of an eta body is a call | +| F7, F8 | cannot: `JsStmt::declarations` already reads the declarations of a block in a list as the list's own, so `enter_list` covered them before the splice | cannot | not reached | + +`Replay::unfound` and a dropped literal: no rule copies a literal, so +"a function literal found twice" cannot fire; a dropped literal leaves +the count above zero, which costs the early end and nothing else. The +literal's free entries were merged into the rows around it when its +row closed, and stay there: decision 12. + +**(e) Can F4 and F7 fire.** F4 fires in eleven lowering tests (`cond` +`if_statement_is_simplify_if_for_every_rule` and +`if_in_place_then_block_...`, `external` +`objects_and_methods_...`, the primitive inventory's `parraysetu`, +`pignore`, `pjs_object_set`, `psetfield` and +`simple_primitive_arms_match_legacy`, and one each in `prim_block`, +`untagged`, `prim_cmp`) and in no unit of the runtime or of +`tests/tests`. F7 fires in no lowering test and no unit of either +corpus: `cond.rs::block_statement` makes a block statement only of +more than one statement and `untagged.rs` takes a sole statement out +(`unnest`); every other `block_of` builds the list of an `if`, a +`switch` action or a loop, which is no block statement. A later +slice that hands the seal a block of one is T4g or T4e (a region +moved as one statement); until then the arm is kept because it is the +same arm as F8 and costs nothing. Both have a hand-built test +(`f4_an_assignment_of_a_sequence_is_its_head_then_the_assignment`, +`f7_and_f8_a_block_in_a_list_is_its_statements_in_the_list`), judged +by the flatten pass on the same tree. + +**(f) The cut.** One slice, T6u, in two commits, each compiling and +passing the three filters alone, check mode at zero differences after +the first: + +1. `seal.rs`, the walk (`names.rs`), the counters (`mod.rs`), the new + side of check mode (`lam_compile.rs`), the oracles (`oracle_tests.rs`, + `export.rs`, `ffi_args.rs`), the allocation pins (`unit.rs`), the + cost note of `deep_constant` (`globals.rs`): 695 lines added, 109 + removed. +2. The hand-built tests (`names.rs`, 489 lines) and three tests of + `oracle_tests.rs` (two of the external-shadow decision, one of + the location; 81 lines). + +The first commit is over the 600 lines a slice is cut to (decision +16). It cannot be cut by rule: a program sealed by some rules cannot +be given to the flatten pass for the rest ((c), last paragraph), so +the oracles move from "flatten the new side" to "flatten the legacy +side" with the first rule, and from then every rule a lowering test +reaches must be there. A first slice that holds the frames, the work +stack and the counters with every list `Mode::Off` (about 250 lines) +would compile and pass, and would move the frame's size and the four +allocation pins with no test that exercises what it adds; it was not +built and is not proposed. + +**(g) Cost by counts.** The check-mode debug build of the two +corpora, on commit 751e1216b and on the build: + +| Counter | Runtime, before | after | `tests/tests`, before | after | +| --- | --- | --- | --- | --- | +| units identical | 113 of 113 | 113 of 113 | 806 of 807 | 806 of 807 | +| naming log differences | 0 | 0 | 0 | 0 | +| `unnamed_references` | 0 | 0 | 0 | 0 | +| `statements` = `moves` | 1,934 | 2,286 | 22,236 | 24,037 | +| `descended` | 5,462 | 5,293 | 72,139 | 71,186 | +| `name_replay_steps` | 8,315 | 8,498 | 107,807 | 108,655 | +| `global_steps` | 2,729 | 2,729 | 26,076 | 26,091 | +| `globals_qualified` | 0 | 0 | 31 | 31 | +| `scopes` / `reserved` | 336 / 583 | 336 / 583 | 4,662 / 8,770 | 4,662 / 8,770 | +| `seal_offered` | | 2,303 | | 24,203 | +| F1 / F2 / F3 / F4 / F5 / F6 / F7 and F8 | | 7 / 0 / 5 / 0 / 166 / 7 / 3 | | 8 / 3 / 42 / 0 / 841 / 99 / 58 | +| `seal_dropped` / `seal_groups` | | 0 / 0 | | 0 / 2 | +| `seal_dropped_literals` (decision 12) | | 0 | | 0 | + +`globals_qualified`, `scopes`, `reserved`, `name_log_steps` and +`close_steps` are equal on every unit of both corpora; `moves` equals +`statements` on every unit. `statements` rises by what the rules make +(an `if` of F5 is one statement where the `return` was one, and its +two `return`s are two more). `descended` falls: the walk no longer +descends a conditional or a sequence the rules take apart. The seal +adds one step an offer: 2,303 and 24,203, against 8,498 and 108,655 +steps of the replay. Allocations: one a fresh unit (decision 14), +none warm. Not measured here: instructions (the probe read +0.008% of +the check-mode build; the coordinator measures the posted build), the +fixtures corpus (no OCaml compiler was built in the sandbox). The +second build read the same numbers in every row. + +What the walk pays a statement, by counts. Of the 24,203 offers of +`tests/tests`, 1,051 fire a rule. The other 23,152 pay: one counter, +one test of the mode, `stmt_kind`, for an `Exp` or a `Return` +`value_of` and one `kind`, an outcome of 8 bytes returned, and one +compare of the work stack's length with the frame's mark before the +next statement is taken. Nothing else of the build is paid by such a +statement. The frame's 12 bytes more are written once a list opened, +not once a statement, in place of the probe's push on a vector beside +the frames. The two modes of a held statement are two bytes of the 24 +a held statement had, written only for a statement with a function +literal or a list. A group frame opened twice on `tests/tests` and +never on the runtime. The location is read when F3 or F5 fires (883 +times). The counter of decision 12 adds one read a scope row at the +start of the replay, also in a unit whose decision is active (it had +no such loop), and one compare a row in the loop at its end. None of +it is plainly not needed. Measured by the coordinator on a +3,735-module application, ten alternating clean builds a side, the +first build against 751e1216b: the check-mode extra moves by +0.032% +of the check build by means and +0.045% by medians, where the default +build, which this code cannot reach, moves by +0.013% and +0.028% +(the noise of the run); the probe read +0.008%. The counts above do +not tell the two apart. + +**Decisions.** + +1. *Where the seal runs.* In `Replay::statements`, on each statement + as it is taken out of its list and before it is named, also where + the descent has ended (`want` 0): flattening does not depend on + there being a function. What a rule makes waits on one work stack + in the replay's scratch (`Scratch::seal`), reserved once by the + unit's node count; nothing recurses. Rests on: the step tests at + 1,000 and 10,000 (`the_seal_offers_each_statement_once_at_any_width_and_depth`, + `the_seal_splices_ten_thousand_nested_blocks_into_one_list`). +2. *Three modes.* `Mode::Off` (the body of a literal in a test the + pass does not enter, and a statement final as made), `Mode::Seal`, + `Mode::Entered` (below a head of F6, which the pass maps twice). A + held statement carries the mode of its literals and of its lists + apart (`Held::literal_mode`, `Held::body_mode`): F3 and F5 seal + the lists of the `if` they write and do not enter its test. Rests + on (a), second table, and its test. +3. *The statement constructor is part of the rules.* `trivial`, + `strip` and `part` are `S::exp`; without them the text differs by + empty lines. Rests on `f1_...`, `f2_...`, `f6_...`. +4. *A group frame* for the one-level splice. The frame is a frame of + the walk with `Marks::group`; it holds no list. Rests on the third + form of `f1_...` and on two units of `tests/tests` (`seal_groups` + 2). +5. *"Without effect" is the lowering's `PURE` flag*, where the pass + asks `expression_has_no_side_effects`. The two were not compared + node by node: the decision rests on zero differences in 113 and + 806 units and in the lowering tests, and is one a review should + confirm. +6. *`JsStmt::own` is kept.* A statement taken out of a list by + `take_at` keeps its parent on rows until the list is rebuilt; a + rule that takes it apart needs it released first. Rests on + `a_statement_taken_out_of_a_list_is_released_once_it_is_owned` and + on the break of its body (six tests fail). +7. *The two adopting setters are kept*, and on rows they are one + primitive, `Bir::adopt_block_list` (in `bir/edit.rs`, outside the + interface files: the parent links and `repair` are private there). + It sets the parent of each entry without one and repairs the + block: one step and one a statement adopted. It recounts no use + and stores no weight, and says so as a precondition a debug build + checks, as does the rows form of `own`: the arena holds no weighted + switch (`weighted_switches == 0`), so every use weight is 1. Only a + `Switch` of level L is weighted (`is_weighted_switch`, + `edge_weight`); the count rises and falls where such a node is + counted and released (`edit.rs`, the accounting of a node). The + lowering reads those from its source arena and writes level J into + an arena of its own (`State::with`, `Bir::default()`), the replay + runs on that arena after `finish_bulk` (`State::finish`), and a + JavaScript program imported into rows has none. The branch that + recounted ran in no test and, unlike `replace`, stored no weight: + it is deleted. A second precondition is stated and not checked: an + adoption computes no capture (`replace` does, `capture_moved`), so + the statements adopted use no variable across a function or a loop + boundary they did not use it across before; a test that adopted a + fresh `f();` into a literal's body failed validation with "missing + capture flag", and the rules never do that. On the builder the + statement's row gains the inherited flags of the statements put + back and loses none (a superset: a flag the rules removed below + stays set, which costs a descent and no correctness). Rests on the + four tests a side and the two pairs of `replay::both`. +8. *The seal's marks are in the frame.* `Frame` grows from 12 to 24 + bytes (`row_sizes`); no vector runs beside the frames. `Held` + stays 24, `Pending` is 8, `Marks` 12, `Sealed` 80. +9. *What check mode compares* is (c). `before` is "the backend after + its flatten pass" against "the lowering, sealed", not what the + re-cut table said ("legacy after P1 and P2"): P2 is in `after`, as + on trunk. +10. *No rule moves a binding across a list, a function, a loop or a + `switch`*, so the decision's `enter_list` and `leave` are + unchanged. Rests on (d), its two tests, and `globals_qualified` + equal on every unit. +11. *Quiet frames and literal bodies.* A quiet frame is walked with + the mode of the held statement's literals; an eta body matches no + rule. Nothing built for it. +12. *A literal the seal drops is an open point.* F3 drops a pure + branch, and a function literal is pure. Its row was closed while + the unit was built and its free entries are in the rows around + it, so the function around it reserves names its sealed body no + longer reads, and a later binder of such a name is renamed where + the pass, on the flattened program, keeps it. Seen: `let run2 = c + => { let _ = c ? (z => z + y) : ext2(); let y = ext(); y + 1 }` + under a top-level `y` reads `name_differences` 1 and + `free_differences` 2 in check mode with the build, 0 and 0 on + trunk (where the pass and the replay both read the unflattened + program, and both disagree with the JavaScript the backend + prints: the difference is there today and is not seen). No unit + of the runtime or of `tests/tests` has the form (`scopes` and + `reserved` equal on every unit). T6u lands with it, pinned by + `a_function_literal_in_a_branch_the_seal_drops_is_not_entered`. + Before the flip it needs one of: the drop done where the + expression statement is built, before the function around it + closes; or the free entries of a dropped literal taken out of the + rows around it. Neither is designed here. The reference names the + FLATTENED program (the coordinator's runs of the OCaml compiler + and of the default build of the Rust compiler, which agree): with + the literal dropped, `let _ = c ? (z => z + y) : ext2()` and the + same written `if c { ignore(z => z + y) } else { ext2() }` both + print `let y = ext(); return y + 1 | 0;` in the function; with + the literal kept, `if c { use(z => z + y) }`, both print `let y$1 + = ext();`. So the new naming must name the flattened program too. + The build counts the form: `Sealed::seal_dropped_literals`, the + function literals released during the replay (only the seal + releases one), read from the scope rows before and after the + walk; check mode reports it for each unit. It is 0 on the runtime + and on `tests/tests`, 1 on the reproducer, and the fixtures corpus + has not been read by anyone: the builder's bridge job shows it. +13. *The debug assertion owed by T6r-f's review (item 3):* both arms + of `Replay::statement` that take a literal without a closed row + assert the walk is quiet. It did not fire in the three filters or + in either corpus. If it fires in the worker's runs, the unit is + reported and the slice stops. +14. *One allocation more a fresh unit:* the work stack's + `reserve_exact`. The four pins of unit.rs move from 85, 103, 85, + 155 to 86, 104, 86, 156, the same at both widths; a warm replay + allocates nothing. +15. *F4 and F7 stay* though no corpus unit reaches them: (e). +16. *One slice, two commits, the first of 804 changed lines:* (f). +17. *The statement F3 or F5 writes takes the conditional's source + location*, as the pass gives it (`source_loc: j.expr_loc(expr)`). + The first build carried none and asserted that no lowered + conditional has one; that was wrong. The backend in use locates + the expression a call or a primitive with default compilation + compiles to (`compile_apply_call`, C:1372; C:1930), the lowering + does the same (`call.rs`, `prim.rs`: `js.locate`), and a primitive + of two literals compiles to a conditional: `min(2, 3)` is `2 < 3 + ? 2 : 3`, located, on both sides. Returned, it is the conditional + of an F5, and with source maps on the pass's `if` has a mapping + the first build's did not (`"mappings":";;;AAAI"` against `""`). + The seal reads the location (`Js::location`, new on trunk in this + pull request, rows only: the builder has no form of `located`, + `locate` or `locate_stmt`) and gives it to the statement it writes + (`locate_stmt`): the `if` of F5 and of F3, and the test F3 leaves + alone. Tests: `a_located_conditional_gives_its_location_to_the_if_the_seal_writes` + (the main oracle with mappings, every context) and + `the_statement_written_for_a_located_conditional_has_its_location` + (hand-built: F3, F5 and the test alone, located and not). A + located conditional with an effect in a branch, the F3 form, was + not found through the lowering (the located conditionals found + are pure), so F3 has the hand-built test only. The pass also gives + F3's statement the comment of the statement it replaces; the + lowering's interface makes no statement comment, so none can be + there. Neither corpus enables source maps. +18. *The counters* (`Sealed`, eleven `usize`, 88 bytes) are flattened + into `SwitchStats` (`#[serde(flatten)]`) and reported by check + mode. +19. *`deep_constant`'s cost note* (T6r-f review, item 7) says the + stack is the call's own local of eight entries, so a deeper + element allocates once a call. +20. *The lists of the `if` F3 and F5 write hold the parts of a + branch, where the pass holds one block.* The pass puts what + `this.statement(S::exp(e))` returns into `j.stmt_list(..)` as it + is: a branch F1, F2, F4 or F6 rewrites stays ONE block statement + in the `if`'s list. The seal seals that list like any other, so + the parts are statements of the list itself: `c ? (f(), g()) : + h();` is `If(c, [Block[f(); g()]], ..)` on the pass and `If(c, + [f(); g()], ..)` on the seal. The trees differ and the JavaScript + does not: the printer writes a block in a list without braces, + and no pass after the flatten pass reads the difference. Shown by + `a_branch_a_rule_rewrites_prints_as_the_pass_prints_it`: nine + branches (a sequence; a sequence with a trivial part, at its end + and in its middle; a block literal with a trivial first element; + a block literal of two; an assignment of a sequence; a + conditional; a sequence whose part is a block literal; a sequence + holding a conditional), each in four statements (used for its + effect; that as the head of a returned sequence, where the pass + splices too; returned; returned after a head), 36 forms. Each + prints the same text on both judges: as sealed against the + flatten pass, and after the passes that follow the flatten pass + on both programs (`bir_passes_oracle`). `Unit::sealed` runs both + judges for every hand-built test now. The tree difference is + accepted on that. + +**What this design changes in what T6 fixed before.** The re-cut row +T6u named `JsStmt::seal` on `Rows` and edits of `bir/shadow.rs`: +neither exists (the seal is not a function of the interface, and +shadow.rs is unchanged). `Bir::adopt_block_list` is new in +`bir/edit.rs`. `Frame` is 24 bytes. The allocation pins move by one. +`ten_thousand_nested_lists_move_each_statement_once` is rebuilt over +nested `if`s (plain nested blocks are spliced now), its numbers kept. +`bir_passes_oracle` is the passes after flatten. +`finish_lowered_output` is deleted (its one use is written out). +The rows form of `own` is `#[inline]`. In oracle_tests.rs the +expected side is flattened and the passes lists lose pass 1. + +`Js::location` is new in `js.rs` and on rows. + +Decisions a review should confirm: 7 (the superset of flags, and the +two preconditions of the primitive in edit.rs), 12, 16, 20. Decision +5 was confirmed node kind by node kind by the first review, and 17 +is corrected. + +**Corrections after the review of the fourteenth turn.** One line an +item of the coordinator's list. + +1. *The lists of the `if` F3 and F5 write.* `State:` the trees + differ, every text agrees on both judges in 36 forms; accepted as + decision 20, the test is in the build. +2. *The tests of the interface on trunk.* `State:` done in pull + request 434: the rows test of `set_literal_body_adopting` 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. Each seen to fail + on the wrong body named. +3. *`adopt_block_list` and rows `own` under a weight.* `State:` the + precondition is stated and asserted, the recount deleted (decision + 7). +4. *The prompt's contradiction on the external-shadow tests.* + `State:` the prompt names every line that changes ((10) of "the + task wins"). +5. *The doc comment of `mod both`.* `State:` moved back. +6. *Decision 17.* `State:` wrong as first written; the seal carries + the location, `Js::location` is on trunk, two tests are in the + build. +7. *Decision 12.* `State:` the three outputs are recorded and the + build counts the form; the fix is not designed. +8. *Cost.* `State:` accepted by the coordinator as measured; the + paragraph is in (g). + ### 11.5 Worker prompt for T4b Which form: it needs one experiment, because nothing read so far proves that @@ -14020,6 +14435,314 @@ count written from what the test prints without the reason; an changed. ``` +T6u (with the common block of phase C and the common block of T6x-a1 +to T6x-a4; read also 11.4 "T6u: the seal", (a) to (g) and decisions 1 +to 20). Written from a throw-away build that ran and was corrected +once after its review (pull request 434; the diff is the two comments +there that start `// T6X-THROWAWAY T6u v2`, "1 of 2" and "2 of 2", +built on the commit 84e1bb8ba7 of that pull request's branch: the +build is larger than one comment holds. The two comments that start +`// T6X-THROWAWAY T6u (` are the first build: not those). + +```text +Task T6u: the seal. The flatten rules F1 to F8 are applied by the walk +of the naming replay to each statement it takes out of a list +(src/bir/lower/seal.rs), and the new side of check mode stops running +the flatten pass. One slice, one pull request against +ocaml-to-rust-rewrite, titled "Three trees T6u: the seal". Changelog +fragment: changes/three-trees-t6u.internal.md, one bullet starting +with "- " (continuation lines indented by two spaces). + +Precondition, check it first and stop with a report if it fails. From +compiler-rust: `grep -c 'fn set_body_adopting' src/bir/lower/js_stmt.rs` +prints 1, `grep -c 'fn adopt_block_list' src/bir/edit.rs` prints 1 and +`grep -c 'fn location' src/bir/lower/js.rs` prints 1 (pull request 434 +is merged); `ls src/bir/lower/seal.rs` finds no +file; the three filters (`cargo test --manifest-path +compiler-rust/Cargo.toml --lib bir::lower`, `--lib bir::j`, `--lib +emit::builder`) read 596, 131 and 85, none ignored; `python3 +../scripts/count_lowering_ids.py --self-test` prints +`count_lowering_ids self-test ok: 32 files, 0 transition calls`; the +four allocation pins of src/bir/lower/unit.rs read 85, 103, 85, 155; +`grep -n apply_js_flatten_pass src/lambda/lam_compile.rs` prints +three lines (the import at 29, and two calls, at 927 and 1039 on the +head the slice was built on). If trunk moved, the base is what trunk +gives: say both numbers. + +Yours: src/bir/lower/seal.rs (new); in src/bir/lower/names.rs the +struct `Frame`, the struct `Held`, `Scratch`, `Storage::reserve`, the +new `Storage::sealed`, the two loops over the scope rows in `replay`, +`Replay::statements`, `Replay::open`, the new +`Replay::seal` and `Replay::close_group`, `Replay::give`, +`Replay::statement`, and in its tests `row_sizes`, +`ten_thousand_nested_lists_move_each_statement_once`, the helpers of +`Unit` and the tests this task names; src/bir/lower/mod.rs (the +module line and `SwitchStats::sealed`); in src/lambda/lam_compile.rs +`bir_passes_oracle`, the two sides of +`compile_deps_program_with_lower_check` and the deletion of +`finish_lowered_output`; the oracle helpers of +src/bir/lower/oracle_tests.rs, of `export.rs` (`rule`) and of +`ffi_args.rs`, and the two tests added at the end of oracle_tests.rs; +the four pins of src/bir/lower/unit.rs; the cost note of +`deep_constant` in src/bir/lower/globals.rs. Nothing else. You add no +function to a trait and none to `Rows` or the builder. Not yours: +src/bir/j, src/emit, src/bir/edit.rs, js.rs, js_stmt.rs, out.rs (the +interface is on trunk); src/bir/shadow.rs; scope.rs and close.rs; the +flatten pass src/lambda/js_pass_flatten_and_mark_dead.rs, which stays +as it is for the backend in use. + +How to build it. Apply the posted build AS IT IS, from the repository +root: save the fenced diff of each of the two comments to a file and +run `git apply` on the first, then on the second (the first line of a +comment, `// T6X-THROWAWAY T6u v2 ...`, is not part of the diff; a hunk +has two lines of context). If one does not apply, stop and report the +hunk: do not write the hunk by hand. Do not rewrap, reword or +reformat a doc comment or a line of it, and do not run a formatter +over a file. You may read the posted build and nothing of the probe. + +What the slice is, so that you can check what you applied: + +- seal.rs. `Mode { Off, Seal, Entered }` (1 byte); `Pending { + statement, mode, group }` (8 bytes on rows); `Marks { pending, + staged, mode, changed, group }` (12 bytes); `Sealed` (eleven + counters, 88 bytes); `Work { pending, sealed }`; `Outcome { Final { + statement, literals, bodies, written }, Replaced }`. `step(js, a, + statement, mode, work)` counts one offer, returns the statement as + final when `mode == Mode::Off`, and else matches the statement's + kind and its value's kind, in this order: `(Return, Cond)` F5, + `(Return, Seq)` F6, `(Exp, Seq)` F1, `(Exp, BlockLit)` F2, `(Exp, + Bin) if assigns_sequence` F4, `(Exp, Cond)` F3, `(Block, _)` F7 and + F8, anything else final in `mode`. The helpers are `take`, + `trivial`, `part`, `branch`, `strip`, `sequence`, + `assigns_sequence`, `pure`, `unentered`, `conditional`, `located`. + `conditional` gives the conditional's source location with its + three operands, and F3 and F5 give it to the statement they write + (`located`: `JsStmt::locate_stmt`). No node is read: every read is + `Js::kind`, `Js::aux`, `Js::has`, `Js::operand`, `Js::location`, + `JsStmt::stmt_kind` or `JsStmt::value_of`. +- names.rs. `Frame` gains `seal: Marks` (24 bytes); `Held` gains + `literal_mode` and `body_mode` (still 24); `Scratch::seal` is the + `Work`; `Storage::reserve` reserves `seal.pending` once, by the node + count. `Replay::statements` pops the pending statements of the + innermost frame before it takes the next statement of the list, + offers each to `Replay::seal`, and closes a frame with `set_body` + when no rule wrote in it and `set_body_adopting` (or + `set_literal_body_adopting`, for a literal's body) when one did; a + group frame closes by `close_group`. `Replay::statement` takes the + two modes and has, in both arms that take a function literal + without a closed row, `debug_assert!(quiet, "a function literal + without a closed row outside a quiet walk")`. `replay` counts, in + the loop over the scope rows at its start (which now runs in an + active unit too) and in the one at its end, the closed rows a header + names whose literal has no owner; the difference is + `Sealed::seal_dropped_literals`. +- lam_compile.rs. The backend in use flattens where it did (the call + is written out where `finish_lowered_output` was called); the gate's + `before` is its program after that pass; the new side calls + `bridge_j::qualify` and `finish_flattened_output` and no flatten. +- The oracles: the expected (legacy) program is flattened, the passes + lists lose pass 1, and nothing sealed is given to the flatten pass. + +Tests. After commit 1: `seal::tests::sizes` is new; `row_sizes` reads +24 for `Frame`; `ten_thousand_nested_lists_move_each_statement_once` +is built over nested `if`s (a block in a list is spliced now), its +numbers as before (20,001 moves and statements; 2 * 9,000 between the +two depths). After commit 2, in names.rs: +`f1_a_sequence_used_for_its_effect_is_its_parts_in_the_list`, +`f2_a_block_literal_used_for_its_effect_is_its_elements`, +`f3_a_conditional_used_for_its_effect_is_an_if_of_the_branches_with_an_effect`, +`f4_an_assignment_of_a_sequence_is_its_head_then_the_assignment`, +`f5_a_returned_conditional_is_an_if_of_returns`, +`f6_a_returned_sequence_is_its_heads_then_the_return`, +`f7_and_f8_a_block_in_a_list_is_its_statements_in_the_list`, +`the_heads_of_a_returned_sequence_are_sealed_with_their_tests_entered`, +`a_function_literal_in_a_branch_the_seal_drops_is_not_entered`, +`the_seal_offers_each_statement_once_at_any_width_and_depth`, +`the_seal_splices_ten_thousand_nested_blocks_into_one_list`, +`a_branch_a_rule_rewrites_prints_as_the_pass_prints_it`, +`the_statement_written_for_a_located_conditional_has_its_location`; +in oracle_tests.rs +`a_global_in_a_branch_the_seal_makes_a_list_of_is_covered_by_the_list_around_it`, +`a_global_in_a_branch_of_a_conditional_used_for_its_effect_is_covered_by_the_list_around_it` +and +`a_located_conditional_gives_its_location_to_the_if_the_seal_writes`. +A hand-built test is judged twice by `Unit::sealed`: the sealed tree +prints as the flatten pass prints the tree as built, and both print +the same after the passes that follow the flatten pass +(`bir_passes_oracle`). The two step tests and the location test are +not: their trees are too deep for the recursive export, or what they +read is not text (`Unit::sealed_deep`: the sealed tree validates). +The four allocation pins of unit.rs read 86, 104, 86, 156: one more a +fresh unit, the `reserve_exact` of the work stack (decision 14). If +you see other numbers, stop and report them; do not write the numbers +you see. + +Two breaks, each applied once, alone, and undone (never commit one); +paste the failing lines in the pull request: + +- In `Replay::seal`, as the first line of the `Outcome::Final` arm, + offer the statement a second time: `let seal::Outcome::Final { + statement, .. } = seal::step(&mut *self.js, &mut *self.bir, + statement, mode, &mut self.scratch.seal) else { unreachable!() };`. + Eleven tests of `--lib bir::lower` fail, all in `names` (those of + commit 2 that read `seal_offered`), + `the_seal_offers_each_statement_once_at_any_width_and_depth` among + them. +- In `seal::unentered`, return `mode`: one test fails, + `the_heads_of_a_returned_sequence_are_sealed_with_their_tests_entered`. + +A third, if you want to see the location held: in `seal::located`, +write `let _ = (loc, &mut statement);` for the `if let`: two fail, +`the_statement_written_for_a_located_conditional_has_its_location` +and `a_located_conditional_gives_its_location_to_the_if_the_seal_writes`. + +Where the common blocks and this task disagree, the task wins: (1) the +allocation pins move as said and `Frame` is 24 bytes; no other +`size_of` moves; (2) `Instruction count` is read and reported, not +held to a figure: the default build does not reach the lowering; (3) +the check-mode figure is not yours: the coordinator measures it on +the application, and you change no code to move it; (4) paste the +self-test's line, not the totals line: it reads 33 files after commit +1 (seal.rs is counted); (5) you wrap nothing: `B::stmt_from_node` and +the like are used in tests only; (6) "a changed expected value in a +test of the lowering": the tests named above change as said and no +other; (7) the fragment is one bullet, not one line; (8) the size: +commit 1 is 804 changed lines, accepted by the design (THREE_TREES +11.4, "T6u: the seal", decision 16); (9) the build is two comments, +not one; (10) the external-shadow tests of oracle_tests.rs change in +these lines and in no other: in `shadow_rule`, `new_text(build, None, +&[1])` becomes `new_text(build, None, &[])` and `&[1, 3, 4, 5, 6]` +becomes `&[3, 4, 5, 6]`; the same list loses its 1 in +`the_lowering_decides_the_shadowed_global_the_tail_call_pass_would_hide`, +`an_imported_module_shadows_the_global_of_its_name_everywhere`, +`a_module_whose_only_reference_the_flatten_pass_drops_still_shadows_the_global_of_its_name`, +`shadow_after_substitution` and +`an_assigned_element_the_substitution_pass_binds_shadows_the_global` +(one call each, with the comment above it where it names the passes); +`new_text_assigning` loses its arm `1 => flatten(program)` and the +import it used; `step_a` and +`a_copied_function_doubles_the_legacy_count_of_the_variables_declared_inside_it` +read `shadow(bridge_j::export_js(..))` without `flatten(..)`; +`export_coercion_consumes_the_export_tuple_occurrence` gives +`pair.before[0]` to `apply_external_shadow_pass` without flattening +it again. That is the posted build. An expected text, a count or an +assertion of any of these tests changed, or any other line of an +external-shadow test, is the failure the list below names. + +Commits, in order; each compiles and passes the three filters alone: + +1. The first comment, applied: seal.rs, names.rs, mod.rs, + lam_compile.rs, oracle_tests.rs, export.rs, ffi_args.rs, unit.rs, + globals.rs. It cannot be cut: the oracles flatten the legacy side + from the first rule on, and every rule a lowering test reaches must + then be there. +2. The second comment, applied: the hand-built tests. +3. The changelog fragment. + +End-state searches, from compiler-rust, run by the design turn on the +head the slice was built on and on the build. Before, then after. +`grep -n apply_js_flatten_pass src/lambda/lam_compile.rs`: three +lines (29, 927, 1039), then two (29, the import; 903, the backend in +use). `grep -c finish_lowered_output src/lambda/lam_compile.rs`: 3, +then 0. In src/bir/lower/names.rs: `grep -c 'seal::step'` 0, then 3 +(one call, two mentions in doc comments); `grep -c set_body_adopting` +0, then 3; `grep -c set_literal_body_adopting` 0, then 1; `grep -c 'a +function literal without a closed row outside a quiet walk'` 0, then +2. `grep -c 'mod seal' src/bir/lower/mod.rs`: 0, then 1. `grep -c +'js.own(' src/bir/lower/seal.rs`: 2; `grep -c 'js.location('` and +`grep -c locate_stmt` there: 1 and 1. `grep -c seal_dropped_literals +src/bir/lower/names.rs`: 0, then 4. `grep -c apply_js_flatten_pass +src/bir/lower/oracle_tests.rs`: 8, then 4. The row's search (the test +module cut off with `sed -E '/^mod tests|^#\[cfg\(test\)\]$/q' +src/bir/lower/F.rs`, then `grep -cE +'View::J|Op::J|View::S[A-Z]|Op::S[A-Z]|parents\['`): 0 for seal.rs, +names.rs, mod.rs, unit.rs and globals.rs, and 0 for every other +non-test file of src/bir/lower, before and after. + +Counts you must see: after commit 1 the three filters 597, 131, 85, +after commit 2 613, 131, 85, none ignored; the allocation pins 86, +104, 86, 156; `cargo clippy --manifest-path compiler-rust/Cargo.toml +--all-targets -- -D warnings` and `RUSTDOCFLAGS="-D warnings" cargo +doc --no-deps` (from compiler-rust) clean after each commit; from +compiler-rust `python3 ../scripts/check_lowering_cost_docs.py --base +origin/ocaml-to-rust-rewrite` ends `changed/new=27; +missing/generic=0`; the self-test prints `count_lowering_ids +self-test ok: 33 files, 0 transition calls`. `git diff --numstat` of +commit 1: 4 and 0 for export.rs, 3 and 0 for ffi_args.rs, 5 and 2 for +globals.rs, 6 and 0 for mod.rs, 194 and 59 for names.rs, 22 and 20 +for oracle_tests.rs, 433 and 0 for seal.rs, 10 and 5 for unit.rs, 18 +and 23 for lam_compile.rs. Of commit 2: 489 and 0 for names.rs, 81 +and 0 for oracle_tests.rs. + +Gates of the pull request, beside those of the common blocks: CI +`Backend bridge coverage` at zero differences, and in its output, for +the runtime, `tests/tests` and the fixtures: `moves` equal to +`statements`; `scopes`, `reserved` and `globals_qualified` equal to +the base's (paste both lines); `unnamed_references` 0; the naming log +against the pass summing to 0. On the design turn's sandbox, base +then build: runtime `statements` 1,934 then 2,286, `descended` 5,462 +then 5,293, `name_replay_steps` 8,315 then 8,498, `global_steps` +2,729 then 2,729, `globals_qualified` 0 then 0, `seal_offered` 2,303, +the rules F1 to F6 and F7 with F8 7, 0, 5, 0, 166, 7, 3, `seal_dropped` +0, `seal_groups` 0, `seal_dropped_literals` 0; `tests/tests` `statements` 22,236 then 24,037, +`descended` 72,139 then 71,186, `name_replay_steps` 107,807 then +108,655, `global_steps` 26,076 then 26,091, `globals_qualified` 31 +then 31, `seal_offered` 24,203, the rules 8, 3, 42, 0, 841, 99, 58, +`seal_dropped` 0, `seal_groups` 2, `seal_dropped_literals` 0. Report +CI's numbers and the rule counts of the fixtures, which the design +turn did not run, and `seal_dropped_literals` on each of the three +corpora. If it is not zero on a corpus, a unit of it has the form of +decision 12: find the unit (its report has the counter), write in the +pull request the unit, the source form and the two name texts (the +JavaScript the backend in use prints for the function and the names +the naming log gives it, from the unit's naming differences), and +stop: the fix is not this task's. Stop and +report, without changing code to hide it: a unit that is not +identical; a naming log difference (a unit where the seal drops a +function literal reads one: decision 12; name the unit and the +source form); `scopes` or `reserved` different from the base's on a +unit; the debug assertion "a function literal without a closed row +outside a quiet walk" firing (name the unit). The parity jobs green. `Instruction count` read and reported. The body lists the +allocation pins and the size that moved, every test changed or added +(the lists above), and that no attribute was added but +`#[serde(flatten)]` on `SwitchStats::sealed` and the `derive`s of +seal.rs. + +Run by the design turn, in a copy that was not pushed: the three +filters at 613, 131, 85 (597 after commit 1); clippy and `cargo doc` +clean on both commits; the cost check at `changed/new=27; +missing/generic=0`; the self-test at zero; the breaks above; a +check-mode debug build of the runtime and of `tests/tests` before and +after, with the lowering stage identical on the same units (113 of +113; 806 of 807), the naming log against the pass 0 differences, and +`globals_qualified`, `scopes`, `reserved`, `name_log_steps`, +`close_steps` and `unnamed_references` equal on every unit. Not run: +the parity suites, `Instruction count`, the fixtures corpus, the +3,735-module application. + +If `git push` or `gh` answers HTTP 401: commit locally, write in your +final message exactly which commits are local, and end the turn at +once. + +Shortcuts that count as failure, beside the common lists: the posted +build retyped, rewrapped or reformatted instead of applied; the +flatten pass run on the new side, on a sealed program, or kept beside +the seal "for the comparison"; a rule written as a recursion over a +sequence, a block or a list; a node read in seal.rs or in the walk +(`bir.view`, `bir.nodes[..]`, `bir.parents[..]`, a `View` or an `Op` +matched); a vector, a set or a map made per statement, per list or +per function; `set_body_adopting` called for a list no rule wrote in; +a function added to the interface, to `Rows` or to the builder; the +case of decision 12 "fixed" here (it is designed in a later turn: +report what you see); a debug assertion weakened or removed; a rule +dropped because no corpus unit reaches it (F4, F7); an expected text +of a hand-built test written from what the seal prints where the +flatten pass prints otherwise; an allocation count or a step count +written from what the test prints without the reason; an `allow`; a +test ignored; an external-shadow test of oracle_tests.rs changed in +any line but those of (10) above. +``` + ## 12. Risks and what was not measured Not measured: diff --git a/compiler-rust/src/bir/edit.rs b/compiler-rust/src/bir/edit.rs index 0cfc908c2b..2597427c37 100644 --- a/compiler-rust/src/bir/edit.rs +++ b/compiler-rust/src/bir/edit.rs @@ -1251,6 +1251,53 @@ impl Bir { self.parents[node.index()] = None; } + /// 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. + /// + /// Precondition: the arena holds no weighted switch (a debug build + /// checks it). Every use weight is then 1, so a statement adopted + /// into any slot keeps the counts its uses were taken with, and + /// nothing is recounted and no weight is stored. It holds wherever + /// the lowering's interface is used: only a `Switch` of level L is + /// weighted (`is_weighted_switch`), the lowering reads those from its + /// source arena and writes statements of level J into an arena of + /// its own, and a JavaScript program imported into rows has none. A + /// caller in an arena that can hold one needs [`Self::replace`], + /// which recounts and stores the slot's weight. + /// + /// Precondition, not checked here (`validate` reports it): a variable + /// an adopted statement uses is not carried across a function or a + /// loop by the adoption. No capture flag is computed, as + /// [`Self::replace`] computes it for a tree it attaches: the + /// statements the flatten rules make are made of the parts of a + /// statement of the same list. + /// + /// One read per entry and one store per statement adopted. 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 { + debug_assert_eq!(self.weighted_switches, 0, "a statement list adopted in an arena with a weighted switch"); + let list = self.node(block).block_list_id().expect("a statement list of a statement is a 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 => { + 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 + } + /// The use weight of a slot: 1, doubled for each switch default above it /// that today's counts visit twice. pub fn weight_of(&mut self, node: NodeId) -> u32 { diff --git a/compiler-rust/src/bir/j/rows.rs b/compiler-rust/src/bir/j/rows.rs index d0cd1444c3..6e12107128 100644 --- a/compiler-rust/src/bir/j/rows.rs +++ b/compiler-rust/src/bir/j/rows.rs @@ -319,6 +319,12 @@ impl Js for Rows { fn located(&self, a: &Pools, r: NodeId) -> bool { a.node(r).flags().contains(NodeFlags::JS_LOC_PRESENT) } + fn location(&self, a: &Pools, r: NodeId) -> Option { + if !a.node(r).flags().contains(NodeFlags::JS_LOC_PRESENT) { + return None; + } + a.cold(r).map(|cold| cold.loc) + } fn runs_no_code(&self, a: &Pools, r: NodeId) -> bool { facts::runs_no_code(a, r) } diff --git a/compiler-rust/src/bir/j/rows_stmt.rs b/compiler-rust/src/bir/j/rows_stmt.rs index 8f6177b3b0..b2014fa23b 100644 --- a/compiler-rust/src/bir/j/rows_stmt.rs +++ b/compiler-rust/src/bir/j/rows_stmt.rs @@ -72,6 +72,9 @@ //! | `below` | T6r | a walk on `Rows::work`, above what it holds, of the children of the statement that are no statements and of everything below them: a `JFun` is given by its header and not entered, a `Var` of a variable with `VarFlags::JS_GLOBAL` is given and, when `visit` says so, `Bir::qualify_global`ed; every other node has its children pushed, the last first; every node is read, whatever `want` is | //! | `reserve_below` | T6r | `Rows::work` gets room for one entry per node of the arena above what it holds: at most one allocation | //! | `declarations` | T6r | a walk on `Rows::work`, above what it holds, of the entries of the pool list and of the `statements` of every `SBlock` among them, to any depth: an `SDecl` or an `SRest` is given to `visit`, an `SBlock` has its entries pushed, the last first (an entry whose parent is not the block, a hole, is not); every other statement is read and left | +//! | `own` | T6u | `Bir::detach` of the row when it has a parent: the link to its block is cut and its use weight pinned; nothing for a row without a parent; no step | +//! | `set_body_adopting` | T6u | the block that is list `index` written again over the pool list given, as `set_body`; then `Bir::adopt_block_list`: each entry without a parent gets the block as its parent (its uses recounted when it carries another weight than the block's slot), and the block is `repair`ed; one step and one per entry adopted | +//! | `set_literal_body_adopting` | T6u | the same for the `SBlock` that is the `body` of the `JFun` of the header | //! | `effect_free` | T6q | the read `export.rs::has_toplevel_effect` made of a statement that is not a declaration row: a work stack (`Rows::work`) of the node's children for a compound statement, the `STRICT` flag of the value of `SExp` and `SReturn` and of every expression below a compound statement, `false` at `SThrow`, `SDebugger`, a jump, `SDecl`, `SRest`, `SForOf`, `SForAwaitOf`; one step per node read | //! | `release_stmt` | T6n | `Bir::release`; one step per node it frees | //! | `if_blocks` | T6n | `Bir::new_node(View::SIf { condition, then_, else_: Some(else_) }, 0)` over the two blocks; one step | @@ -556,6 +559,26 @@ impl JsStmt for Rows { self.work = work; read } + #[inline] + fn own(&mut self, a: &mut Pools, s: &mut S) { + // The statement keeps the use counts it was built with wherever + // it goes back: every weight is 1 without a weighted switch, and + // an arena of level J has none (`Bir::adopt_block_list`). + debug_assert_eq!(a.weighted_switches, 0, "a statement owned in an arena with a weighted switch"); + if a.parents[s.0.index()].is_some() { + a.detach(s.0); + } + } + fn set_body_adopting(&mut self, a: &mut Pools, s: &mut S, index: u32, body: ListId) { + let block = Self::body_block(a, s, index); + Self::write_block(a, block, body); + self.steps += 1 + u64::from(a.adopt_block_list(block)); + } + fn set_literal_body_adopting(&mut self, a: &mut Pools, header: FuncId, body: ListId) { + let block = Self::literal_block(a, header); + Self::write_block(a, block, body); + self.steps += 1 + u64::from(a.adopt_block_list(block)); + } fn effect_free(&mut self, a: &Pools, s: &S) -> bool { let mut work = std::mem::take(&mut self.work); debug_assert!(work.is_empty()); diff --git a/compiler-rust/src/bir/j/rows_stmt_tests.rs b/compiler-rust/src/bir/j/rows_stmt_tests.rs index fa7148feae..8e6cc6a061 100644 --- a/compiler-rust/src/bir/j/rows_stmt_tests.rs +++ b/compiler-rust/src/bir/j/rows_stmt_tests.rs @@ -1542,6 +1542,155 @@ mod replay { assert_eq!(reads[1], 10 * reads[0]); } + /// A statement taken out of a list a block still holds keeps the + /// block as its owner and cannot be released; once owned it is + /// detached, costs no step, and is released like any statement in + /// flight. A statement that has no owner stays as it is. + #[test] + fn a_statement_taken_out_of_a_list_is_released_once_it_is_owned() { + let mut u = unit(); + let mut r = Rows::default(); + let mut b = block(&mut r, &mut u, 3); + let before = listed(&u, &b, 0); + let list = r.body(&mut u.b, &mut b, 0); + let taken: Vec = (0..3).map(|at| r.take_at(&mut u.b, list, at)).collect(); + let [first, mut second, third] = <[S; 3]>::try_from(taken).expect("three statements"); + assert_eq!(u.b.parents[second.0.index()], Some(b.0)); + let steps = r.steps(); + r.own(&mut u.b, &mut second); + assert_eq!(r.steps(), steps, "owning counts no step"); + assert_eq!(u.b.parents[second.0.index()], None); + assert_eq!(r.stmt_id(&u.b, &second), before[1]); + // Owned twice, and a statement a constructor made: nothing to do. + r.own(&mut u.b, &mut second); + let x = r.var(&mut u.b, u.x); + let mut made = r.exp(&mut u.b, x); + r.own(&mut u.b, &mut made); + assert_eq!(u.b.parents[made.0.index()], None); + r.release_stmt(&mut u.b, second); + // The others are the block's still, and the list goes back with + // the statement made in place of the one released. + let rebuilt = r.list(&mut u.b, 3, [first, made, third].into_iter()); + r.set_body_adopting(&mut u.b, &mut b, 0, rebuilt); + let after = listed(&u, &b, 0); + assert_eq!((after[0], after[2]), (before[0], before[2])); + assert_ne!(after[1], before[1]); + } + + /// `callee();` over the variable `f`: a statement with an effect. + fn effect(r: &mut Rows, u: &mut Unit) -> S { + let callee = r.var(&mut u.b, u.f); + let value = call(r, u, callee, Vec::new()); + r.exp(&mut u.b, value) + } + + /// A list the caller changed is put back: the statements made since + /// it was taken get the block as their owner, those put back keep it, + /// and the block's facts are computed again (two pure statements made + /// a pure block; a call among them makes it one with an effect). + #[test] + fn a_changed_list_is_put_back_and_its_block_adopts_and_is_repaired() { + use crate::bir::NodeFlags; + let mut u = unit(); + let mut r = Rows::default(); + let mut b = block(&mut r, &mut u, 2); + assert!(u.b.node(b.0).flags().contains(NodeFlags::PURE)); + // As the replay finds a unit: its construction finished, so the + // arena keeps the use counts and the validation reads them. + u.b.finish_bulk(b.0); + u.b.validate(Some(b.0)).expect("the block as built"); + let list = r.body(&mut u.b, &mut b, 0); + let (first, mut second) = (r.take_at(&mut u.b, list, 0), r.take_at(&mut u.b, list, 1)); + r.own(&mut u.b, &mut second); + r.release_stmt(&mut u.b, second); + let (called, last) = (effect(&mut r, &mut u), { + let x = r.var(&mut u.b, u.x); + r.exp(&mut u.b, x) + }); + let expected = [first.0.0, called.0.0, last.0.0]; + let rebuilt = r.list(&mut u.b, 3, [first, called, last].into_iter()); + let steps = r.steps(); + r.set_body_adopting(&mut u.b, &mut b, 0, rebuilt); + // One step, and one for each of the two statements adopted. + assert_eq!(r.steps() - steps, 1 + 2); + assert_eq!(listed(&u, &b, 0), expected); + for id in expected { + assert_eq!(u.b.parents[id as usize], Some(b.0)); + } + assert!(!u.b.node(b.0).flags().contains(NodeFlags::PURE)); + u.b.validate(Some(b.0)).expect("the block with its changed list"); + assert_eq!((r.stmt_kind(&u.b, &b), r.bodies(&u.b, &b)), (Kind::Block, 1)); + } + + /// The changed body of a function literal is put back by its header, + /// its block adopting as a statement's list does. + #[test] + fn the_changed_body_of_a_function_literal_is_put_back_by_its_header() { + let mut u = unit(); + let mut r = Rows::default(); + use crate::bir::NodeFlags; + let (declaration, header) = literal(&mut r, &mut u, 2); + let body = Rows::literal_block(&u.b, header); + assert!(u.b.node(body).flags().contains(NodeFlags::PURE)); + // As the replay finds a unit: its construction finished, so the + // validation reads the facts and the use counts. + u.b.finish_bulk(declaration.0); + u.b.validate(Some(declaration.0)).expect("the literal as built"); + let list = r.literal_body(&mut u.b, header); + let (first, mut second) = (r.take_at(&mut u.b, list, 0), r.take_at(&mut u.b, list, 1)); + r.own(&mut u.b, &mut second); + r.release_stmt(&mut u.b, second); + // `x();`: a statement with an effect over the variable the body + // reads already (an adoption computes no capture). + let callee = r.var(&mut u.b, u.x); + let value = call(&mut r, &mut u, callee, Vec::new()); + let called = r.exp(&mut u.b, value); + let expected = vec![first.0.0, called.0.0]; + let rebuilt = r.list(&mut u.b, 2, [first, called].into_iter()); + let steps = r.steps(); + r.set_literal_body_adopting(&mut u.b, header, rebuilt); + assert_eq!(r.steps() - steps, 1 + 1); + assert_eq!(body_of(&u, header), expected); + assert_eq!(u.b.parents[expected[1] as usize], Some(body)); + // The body's facts are computed again: two pure statements made a + // pure body, a call among them makes it one with an effect. + assert!(!u.b.node(body).flags().contains(NodeFlags::PURE)); + u.b.validate(Some(declaration.0)).expect("the literal with its changed body"); + } + + /// A changed list put back costs one step a statement adopted, ten + /// times as many at ten times the width, and allocates nothing: every + /// statement of the list was made since the list was taken. + #[test] + fn a_changed_list_put_back_costs_one_step_a_statement_at_any_width() { + let mut steps = Vec::new(); + for width in [1_000u32, 10_000] { + let mut u = unit(); + let mut r = Rows::default(); + let mut b = block(&mut r, &mut u, width); + let list = r.body(&mut u.b, &mut b, 0); + for at in 0..width { + let mut taken = r.take_at(&mut u.b, list, at); + r.own(&mut u.b, &mut taken); + r.release_stmt(&mut u.b, taken); + } + let made: Vec = (0..width) + .map(|_| { + let x = r.var(&mut u.b, u.x); + r.exp(&mut u.b, x) + }) + .collect(); + let rebuilt = r.list(&mut u.b, width, made.into_iter()); + let before = r.steps(); + let allocations = allocation_counter::measure(|| r.set_body_adopting(&mut u.b, &mut b, 0, rebuilt)); + assert_eq!(allocations.count_total, 0, "{allocations:?}"); + steps.push(r.steps() - before); + assert_eq!(r.block_len(&u.b, &b), width); + } + assert!(steps[0] >= 1_000, "{steps:?}"); + assert!(steps[1] <= 11 * steps[0], "{steps:?}"); + } + /// The two implementations of the lowering's interface, given the /// same statement, find the same things: each test builds one form on /// rows and through the builder (`emit::builder`) and compares what @@ -1602,6 +1751,31 @@ mod replay { const BOTH: u16 = flag::HAS_FUN | flag::HAS_GLOBAL; + /// What each statement of `list` holds on rows, as the flags the + /// builder keeps for it (`HAS_FUN`, `HAS_GLOBAL`): what a descent + /// of the statement finds. The statements are taken and listed + /// again; returns the list to put back. + fn held_in(r: &mut Rows, u: &mut Unit, list: crate::bir::ListId) -> (Vec, crate::bir::ListId) { + let len = r.len(&u.b, list); + let mut held = Vec::new(); + let mut statements = Vec::new(); + for at in 0..len { + let mut statement = r.take_at(&mut u.b, list, at); + let found = found_on_rows(r, u, &mut statement, BOTH, &[]); + held.push(found.iter().fold(0, |all, (function, _)| all | if *function { flag::HAS_FUN } else { flag::HAS_GLOBAL })); + statements.push(statement); + } + (held, r.list(&mut u.b, len, statements.into_iter())) + } + + /// [`held_in`] for the one list of the block `block`. + fn held_on_rows(r: &mut Rows, u: &mut Unit, block: &mut S) -> Vec { + let list = r.body(&mut u.b, block, 0); + let (held, list) = held_in(r, u, list); + r.set_body(&mut u.b, block, 0, list); + held + } + /// `g4 = g5 + x;`: the variable an assignment writes. #[test] fn the_variable_an_assignment_writes() { @@ -1700,6 +1874,12 @@ mod replay { assert_eq!((&rows_found[..], &builder_found[..]), (expected, expected)); } + /// `v0;` on rows. + fn body_statement(r: &mut Rows, u: &mut Unit) -> S { + let value = r.var(&mut u.b, VarId(0)); + r.exp(&mut u.b, value) + } + /// A function literal of the next header over one `x;`, on rows. fn literal(r: &mut Rows, u: &mut Unit) -> E { function(r, u, None).0 @@ -2056,5 +2236,126 @@ mod replay { } alike(on_rows, on_builder, flag::HAS_GLOBAL, &[(false, 4)]); } + + /// `{ v0; v0; }` with its second statement owned, dropped and + /// replaced by `return v1;`, and a third `v0;` made: the list is + /// put back as a changed list on both sides, and both give a + /// block of the same three kinds in the same order whose first + /// statement is the one that was taken. + #[test] + fn a_changed_list_put_back() { + let (mut r, mut u) = (Rows::default(), arena()); + let statements = [body_statement(&mut r, &mut u), body_statement(&mut r, &mut u)]; + let list = r.list(&mut u.b, 2, statements.into_iter()); + let mut block = r.block_of(&mut u.b, list); + let list = r.body(&mut u.b, &mut block, 0); + let (first, mut second) = (r.take_at(&mut u.b, list, 0), r.take_at(&mut u.b, list, 1)); + let kept = r.stmt_id(&u.b, &first); + r.own(&mut u.b, &mut second); + r.release_stmt(&mut u.b, second); + let value = r.var(&mut u.b, VarId(4)); + let replaced = r.return_(&mut u.b, value); + let value = literal(&mut r, &mut u); + let last = r.exp(&mut u.b, value); + let rebuilt = r.list(&mut u.b, 3, [first, replaced, last].into_iter()); + r.set_body_adopting(&mut u.b, &mut block, 0, rebuilt); + let on_rows: Vec = (0..r.block_len(&u.b, &block)).map(|at| r.with_block_stmt(&u.b, &block, at, |s| r.stmt_kind(&u.b, s))).collect(); + assert_eq!(r.with_block_stmt(&u.b, &block, 0, |s| r.stmt_id(&u.b, s)), kept); + let rows_hold = held_on_rows(&mut r, &mut u, &mut block); + + let allocator = Allocator::default(); + let mut b = Builder::new(&allocator); + b.reserve_literals(1); + let mark = b.stage_mark(); + for _ in 0..2 { + let value = reference(&mut b, 0); + let statement = b.exp(value); + b.stage(statement); + } + let list = b.list(mark); + let mut block = b.block(list); + assert_eq!(block.row.flags & BOTH, 0); + let list = b.take_body(&mut block, 0); + let (first, mut second) = (b.take(list, 0), b.take(list, 1)); + let kept = first.stmt.node_id(); + b.own_statement(&mut second); + let value = reference(&mut b, 4); + let replaced = b.return_(value); + let value = built_literal(&mut b, 0); + let last = b.exp(value); + let mark = b.stage_mark(); + for statement in [first, replaced, last] { + b.stage(statement); + } + let rebuilt = b.list(mark); + b.set_body_adopting(&mut block, 0, rebuilt); + let on_builder: Vec = (0..b.block_len(&block)).map(|at| b.statement_row(b.block_statement(&block, at)).kind).collect(); + assert_eq!(b.block_statement(&block, 0).node_id(), kept); + assert_eq!((&on_rows[..], &on_builder[..]), (&[Kind::Exp, Kind::Return, Kind::Exp][..], &[Kind::Exp, Kind::Return, Kind::Exp][..])); + // What each statement holds, and the block over them: on rows + // what a descent finds, on the builder the flags a descent + // follows. The second holds a global, the third a function + // literal, the block both. + let builder_hold: Vec = (0..b.block_len(&block)).map(|at| b.statement_row(b.block_statement(&block, at)).flags & BOTH).collect(); + assert_eq!(rows_hold, [0, flag::HAS_GLOBAL, flag::HAS_FUN]); + assert_eq!(builder_hold, rows_hold); + assert_eq!(block.row.flags & BOTH, rows_hold.iter().fold(0, |all, held| all | held)); + assert_eq!(b.statement_row(&block.stmt), block.row); + } + + /// The body `v0; v0;` of a function literal with its second + /// statement owned, dropped and replaced by `return g4;`: put back + /// by the header as a changed list on both sides, and the body + /// taken again is the same two kinds on both. + #[test] + fn the_changed_body_of_a_function_literal_put_back() { + let (mut r, mut u) = (Rows::default(), arena()); + let header = u.b.function_header(crate::bir::VarSpan { start: 0, len: 0 }, Default::default(), LamLoc::NONE); + let statements = [body_statement(&mut r, &mut u), body_statement(&mut r, &mut u)]; + let list = r.list(&mut u.b, 2, statements.into_iter()); + let function = r.function(&mut u.b, header, list); + let _holder = r.exp(&mut u.b, function); + let list = r.literal_body(&mut u.b, header); + let (first, mut second) = (r.take_at(&mut u.b, list, 0), r.take_at(&mut u.b, list, 1)); + r.own(&mut u.b, &mut second); + r.release_stmt(&mut u.b, second); + let value = r.var(&mut u.b, VarId(4)); + let replaced = r.return_(&mut u.b, value); + let rebuilt = r.list(&mut u.b, 2, [first, replaced].into_iter()); + r.set_literal_body_adopting(&mut u.b, header, rebuilt); + let again = r.literal_body(&mut u.b, header); + let on_rows: Vec = (0..r.len(&u.b, again)).map(|at| r.kind_at(&u.b, again, at)).collect(); + let (rows_hold, again) = held_in(&mut r, &mut u, again); + r.set_literal_body(&mut u.b, header, again); + + let allocator = Allocator::default(); + let mut b = Builder::new(&allocator); + let mark = b.stage_mark(); + for _ in 0..2 { + let value = reference(&mut b, 0); + let statement = b.exp(value); + b.stage(statement); + } + let list = b.list(mark); + let _literal = b.function(header.0, list); + let list = b.literal_body(header.0); + let (first, mut second) = (b.take(list, 0), b.take(list, 1)); + b.own_statement(&mut second); + let value = reference(&mut b, 4); + let replaced = b.return_(value); + let mark = b.stage_mark(); + b.stage(first); + b.stage(replaced); + let rebuilt = b.list(mark); + b.set_literal_body_adopting(header.0, rebuilt); + let again = b.literal_body(header.0); + let on_builder: Vec = (0..again.len()).map(|at| b.row_at(again, at).kind).collect(); + assert_eq!((&on_rows[..], &on_builder[..]), (&[Kind::Exp, Kind::Return][..], &[Kind::Exp, Kind::Return][..])); + // What each statement of the body holds: on rows what a + // descent finds, on the builder the flags of its row. + let builder_hold: Vec = (0..again.len()).map(|at| b.row_at(again, at).flags & BOTH).collect(); + assert_eq!(rows_hold, [0, flag::HAS_GLOBAL]); + assert_eq!(builder_hold, rows_hold); + } } } diff --git a/compiler-rust/src/bir/lower/js.rs b/compiler-rust/src/bir/lower/js.rs index 2243d4f2a2..9d49180e83 100644 --- a/compiler-rust/src/bir/lower/js.rs +++ b/compiler-rust/src/bir/lower/js.rs @@ -161,6 +161,12 @@ pub trait Js { fn operand<'r>(&self, a: &'r Pools, r: Self::Ref<'r>, index: u32) -> Self::Ref<'r>; /// Whether the node has a source location. O(1). fn located(&self, a: &Pools, r: Self::Ref<'_>) -> bool; + /// The source location of the node, or nothing when it has none + /// ([`Js::located`]); a node located with `LamLoc::NONE` gives that. + /// O(1): the node's flags, then its cold row. (THREE_TREES 11.4, "T6u: + /// the seal", decision 17: `seal.rs`, the `if` a flatten rule writes + /// takes the location of the conditional it is made of.) + fn location(&self, a: &Pools, r: Self::Ref<'_>) -> Option; /// A:90 `runs_no_code`. One step per member of a chain of field reads /// with a position, to its base. fn runs_no_code(&self, a: &Pools, r: Self::Ref<'_>) -> bool; diff --git a/compiler-rust/src/bir/lower/js_stmt.rs b/compiler-rust/src/bir/lower/js_stmt.rs index 1ca2961b4f..3507f09528 100644 --- a/compiler-rust/src/bir/lower/js_stmt.rs +++ b/compiler-rust/src/bir/lower/js_stmt.rs @@ -614,6 +614,73 @@ pub trait JsStmt: Js { /// with [`JsStmt::with_stmt_at`] and [`JsStmt::with_block_stmt`] and /// recursed as deep as blocks nest.) fn declarations(&mut self, a: &Pools, list: Self::L, visit: impl FnMut(&Self, &Pools, &Self::S)) -> u32; + /// The statement `s`, taken out of a list in flight + /// ([`JsStmt::take_at`]) whose statements a statement or a function + /// literal still holds ([`JsStmt::body`], [`JsStmt::literal_body`]), + /// becomes the caller's own: it may be taken apart + /// ([`JsStmt::take_value`], [`JsStmt::unblock`]) or released + /// ([`JsStmt::release_stmt`]), which a statement taken out of such a + /// list may not be until it is owned. A statement that is the + /// caller's already (one a constructor made, one [`JsStmt::unblock`] + /// gave) stays as it is. An owned statement is not put back with + /// [`JsStmt::set_body`] or [`JsStmt::set_literal_body`]: the list + /// that holds it, or what was made of it, goes back with + /// [`JsStmt::set_body_adopting`] or + /// [`JsStmt::set_literal_body_adopting`]. `s` keeps its id. + /// + /// O(1); counts no step; allocates nothing. On rows a statement of + /// such a list keeps its block as owner while it is out: the link is + /// cut (`Bir::detach`, one store, and the statement's use weight is + /// pinned). An implementation that owns its nodes moved the statement + /// out of the list when it was taken: nothing is done. (THREE_TREES + /// 11.4, "T6u: the seal", decision 6: `seal.rs`, a statement a flatten + /// rule rewrites, before its value is taken or its block is spliced.) + fn own(&mut self, a: &mut Pools, s: &mut Self::S); + /// [`JsStmt::set_body`] for a list the caller changed: `body` becomes + /// list `index` of the statement `s`, in place of the one + /// [`JsStmt::body`] took, and its statements are those that call gave + /// that the caller put back, in any number, and statements that are + /// the caller's own (made since, owned with [`JsStmt::own`], given by + /// [`JsStmt::unblock`]), at any place. The list is consumed. The + /// facts `s` and the statements around it have of the list are + /// brought up to date: on rows the effect flags of the block and of + /// its owners while one changes; on an implementation that keeps + /// `HAS_FUN`, `SEAL` and `HAS_GLOBAL` with a statement, those of `s` + /// gain what the statements put back have and lose nothing (a flag + /// says "may hold": a walk that asks finds nothing below a flag that + /// stayed on). + /// + /// Precondition: the statements adopted use no variable from the + /// other side of a function or a loop than where the use was built + /// (a rule makes them of the parts of a statement of this list): no + /// capture is computed. On rows the arena holds no weighted switch, + /// which an arena the lowering writes never does, so no use is + /// counted again (`Bir::adopt_block_list`). + /// + /// One step, and one per statement adopted. On rows one read per + /// statement of the list, one store per statement adopted, and + /// `Bir::repair` of the block: its statements' flags, then one owner + /// at a time while a fact changes. On an implementation that owns its nodes the moves + /// of [`JsStmt::set_body`] and one store. Allocates nothing on rows; + /// on such an implementation the list's vector grows when the list is + /// longer than the one taken. Panics when `index` is not below + /// [`JsStmt::bodies`]. (THREE_TREES 11.4, "T6u: the seal", decision 7: + /// `names.rs`, `Replay::statements` and `Replay::give`, the rebuilt + /// list of a frame in which a flatten rule replaced a statement.) + fn set_body_adopting(&mut self, a: &mut Pools, s: &mut Self::S, index: u32, body: Self::L); + /// [`JsStmt::set_literal_body`] for a list the caller changed, as + /// [`JsStmt::set_body_adopting`] is [`JsStmt::set_body`] for one: + /// `body` becomes the body of the function literal of `header`. The + /// list is consumed. A function literal has no fact of its body (it + /// runs nothing, and who walks the body takes it by header), so on an + /// implementation that owns its nodes this is + /// [`JsStmt::set_literal_body`]; on rows the body's block adopts and + /// is repaired as a statement's list is. One step, and one per + /// statement adopted; the costs of [`JsStmt::set_body_adopting`]. + /// Panics when no literal of `header` is live. (Decision 7: + /// `names.rs`, the rebuilt list of a literal's frame in which a + /// flatten rule replaced a statement.) + fn set_literal_body_adopting(&mut self, a: &mut Pools, header: FuncId, body: Self::L); /// S:1053 `js_statement_no_side_effects`: the statement runs no code /// that can be observed. An expression statement and a `return` are /// free when their value is strictly pure (E:15); a block, an `if`, a diff --git a/compiler-rust/src/bir/lower/js_tests.rs b/compiler-rust/src/bir/lower/js_tests.rs index 472a538164..bd272c3a19 100644 --- a/compiler-rust/src/bir/lower/js_tests.rs +++ b/compiler-rust/src/bir/lower/js_tests.rs @@ -634,8 +634,11 @@ fn a_reader_reads_what_the_lowering_reads_today() { r.push(text); let mut call = r.call(a, f, mark, u.call); assert!(!r.located(a, Rows::of(&call))); + assert_eq!(r.location(a, Rows::of(&call)), None); r.locate(a, &mut call, crate::lambda::LamLoc::NONE); assert!(r.located(a, Rows::of(&call))); + // Located with no position is located: the location read is that one. + assert_eq!(r.location(a, Rows::of(&call)), Some(crate::lambda::LamLoc::NONE)); let root = Rows::of(&call); assert_eq!(r.id(a, root), Rows::node(Rows::from_node(root)).0); assert_eq!(r.kind(a, root), Kind::Call); @@ -1187,3 +1190,28 @@ fn the_id_bound_is_above_every_id() { assert!(r.id(&u.b, Rows::of(&x)) < r.id_bound(&u.b)); assert!(r.id(&u.b, Rows::of(&x)) >= before); } + +/// The location a node was given is the one read back, a comment added +/// after it or not; a node with a comment and no location has none. +#[test] +fn the_location_of_a_node_is_the_one_it_was_given() { + let mut u = unit(); + let mut r = Rows::default(); + let a = &mut u.b; + let mut locations = crate::lambda::LamLocTable::located(Default::default()); + let (first, second) = ( + locations.intern(crate::location::Location::new(Default::default(), 4, 12)), + locations.intern(crate::location::Location::new(Default::default(), 20, 30)), + ); + assert_ne!(first, second); + let (mut one, mut two, mut three) = (r.var(a, u.x), r.var(a, u.x), r.var(a, u.x)); + r.locate(a, &mut one, first); + r.locate(a, &mut two, second); + let label = a.intern_text("note"); + r.comment(a, &mut two, label); + r.comment(a, &mut three, label); + assert_eq!( + [r.location(a, Rows::of(&one)), r.location(a, Rows::of(&two)), r.location(a, Rows::of(&three))], + [Some(first), Some(second), None] + ); +} diff --git a/compiler-rust/src/emit/builder.rs b/compiler-rust/src/emit/builder.rs index a35c250a3b..ce94facbd0 100644 --- a/compiler-rust/src/emit/builder.rs +++ b/compiler-rust/src/emit/builder.rs @@ -1976,6 +1976,52 @@ impl<'a> Builder<'a> { *slot = body; } + /// The statement `statement`, taken out of a list in flight, is the + /// caller's own (the lowering's `JsStmt::own`): it may be taken apart + /// or dropped, and what is made of it goes back with + /// [`Builder::set_body_adopting`]. The builder moved the statement out + /// of the pool when it was taken ([`Builder::take`]) and no node + /// names it, so nothing is done: the function is the place the + /// lowering's call lands, and says so. O(1); counts no step. (Named + /// `own_statement`: `Builder::own` is the reader of a statement's own + /// expression.) + pub fn own_statement(&mut self, statement: &mut S<'a>) { + debug_assert_eq!(self.rows[statement.stmt.node_id().index()], statement.row, "a statement in hand has the row of its node"); + } + + /// [`Builder::set_body`] for a list the caller changed (the + /// lowering's `JsStmt::set_body_adopting`): the statements of `list` + /// are those [`Builder::take_body`] gave that the caller put back and + /// statements made since, in any number. The row of `statement` gains + /// the `HAS_FUN`, `SEAL` and `HAS_GLOBAL` of the statements put back, + /// in the handle and in the table, and loses no flag: a flag of a + /// statement says "may hold", so a list that lost its last function + /// literal leaves a flag a descent follows and finds nothing under. + /// One step, and one step, one move of 24 bytes and one flag read per + /// statement; one store of the row. The node's vector grows in the + /// arena when the list is longer than the one taken. Panics as + /// [`Builder::set_body`] does. + pub fn set_body_adopting(&mut self, statement: &mut S<'a>, index: usize, list: List) { + let start = list.start as usize; + let mut flags = 0; + for slot in &self.pool[start..start + list.len()] { + flags |= slot.as_ref().expect("a statement taken twice").row.flags; + } + self.set_body(statement, index, list); + statement.row.flags |= flags & INHERITED; + self.rows[statement.stmt.node_id().index()] = statement.row; + } + + /// [`Builder::set_literal_body`] for a list the caller changed (the + /// lowering's `JsStmt::set_literal_body_adopting`). The row of a + /// function literal has none of its body's flags + /// ([`Builder::function`]), so there is nothing to bring up to date: + /// the list is stored as [`Builder::set_literal_body`] stores it. One + /// step; O(1). Panics as it does. + pub fn set_literal_body_adopting(&mut self, header: u32, body: List) { + self.set_literal_body(header, body); + } + /// The expression of the statement `stmt` itself, as apart from the /// statements of its lists: the value of an expression statement, a /// `return`, a `throw` and a declaration that has one; the test of an diff --git a/compiler-rust/src/emit/builder_tests.rs b/compiler-rust/src/emit/builder_tests.rs index 8c7d1b84d6..d3791dd606 100644 --- a/compiler-rust/src/emit/builder_tests.rs +++ b/compiler-rust/src/emit/builder_tests.rs @@ -2693,6 +2693,147 @@ pub(crate) mod replay { assert!(b.path.is_empty() && b.depths.is_empty()); } + /// A statement taken out of a list is the caller's on the builder: + /// `own_statement` counts no step and leaves the statement, its row + /// and the pool as they were, and the statement can then be dropped + /// while another takes its place. + #[test] + fn a_statement_taken_out_of_a_list_is_the_callers_own() { + let allocator = Allocator::default(); + let mut b = Builder::new(&allocator); + let list = effects(&mut b, 2); + let mut block = b.block(list); + let list = b.take_body(&mut block, 0); + let (first, mut second) = (b.take(list, 0), b.take(list, 1)); + let (steps, slots, row, id) = (b.steps, b.pool.len(), second.row, second.stmt.node_id()); + b.own_statement(&mut second); + assert_eq!((b.steps, b.pool.len(), second.row, second.stmt.node_id()), (steps, slots, row, id)); + assert_eq!(b.statement_row(&second.stmt), row); + // The owned statement is dropped: `return v1;` stands in its place. + let kept = first.stmt.node_id().index(); + let value = b.reference(1, 0); + let replaced = b.return_(value); + let made = replaced.stmt.node_id().index(); + let mark = b.stage_mark(); + b.stage(first); + b.stage(replaced); + let rebuilt = b.list(mark); + b.set_body_adopting(&mut block, 0, rebuilt); + assert_eq!(listed(&mut block, 0), [kept, made]); + } + + /// A list the caller changed is put back with its statements in + /// order, a longer list too, and the statement gains the inherited + /// flags of what was put into it, in the handle and in the table: + /// here the `HAS_FUN` of a function literal. `set_body` writes no + /// row, so the same list put back with it leaves the flag off. + #[test] + fn a_changed_list_is_put_back_and_its_statement_gains_the_flags_of_its_statements() { + let allocator = Allocator::default(); + let mut b = Builder::new(&allocator); + b.reserve_literals(4); + for adopting in [true, false] { + let list = effects(&mut b, 2); + let mut block = b.block(list); + const INHERITED: u16 = flag::HAS_FUN | flag::SEAL | flag::HAS_GLOBAL; + assert_eq!(block.row.flags & INHERITED, 0); + let list = b.take_body(&mut block, 0); + let (first, mut second) = (b.take(list, 0), b.take(list, 1)); + b.own_statement(&mut second); + // Three statements made since, each the one carrier of one + // inherited flag: a function literal, a reference to a + // global, a sequence that is not in print form. + let body = effects(&mut b, 1); + let literal = b.function(u32::from(adopting), body); + let literal = b.exp(literal); + let global = b.reference(1, var::GLOBAL); + let global = b.exp(global); + let (one, two, three) = (b.reference(0, 0), b.reference(0, 0), b.reference(0, 0)); + let inner = b.seq(two, three); + let chain = b.seq(one, inner); + let chain = b.exp(chain); + assert_eq!([literal.row.flags & INHERITED, global.row.flags & INHERITED, chain.row.flags & INHERITED], [flag::HAS_FUN, flag::HAS_GLOBAL, flag::SEAL]); + let expected = [first.stmt.node_id().index(), literal.stmt.node_id().index(), global.stmt.node_id().index(), chain.stmt.node_id().index()]; + let mark = b.stage_mark(); + for statement in [first, literal, global, chain] { + b.stage(statement); + } + let rebuilt = b.list(mark); + let steps = b.steps; + if adopting { + b.set_body_adopting(&mut block, 0, rebuilt); + } else { + b.set_body(&mut block, 0, rebuilt); + } + // One step, and one a statement moved. + assert_eq!(b.steps - steps, 1 + 4); + assert_eq!(listed(&mut block, 0), expected); + // Every inherited flag is taken over, each from its one + // carrier; the plain form takes none. + assert_eq!(block.row.flags & INHERITED, if adopting { INHERITED } else { 0 }); + assert_eq!(b.statement_row(&block.stmt), block.row); + assert_eq!(block.row.kind, Kind::Block); + } + } + + /// A changed list put back costs one step and one move a statement: + /// ten times as many at ten times the width, every statement of the + /// list made since the list was taken. + #[test] + fn a_changed_list_put_back_costs_one_step_a_statement_at_any_width() { + let mut steps = Vec::new(); + for width in [1_000usize, 10_000] { + let allocator = Allocator::default(); + let mut b = Builder::new(&allocator); + let list = effects(&mut b, width); + let mut block = b.block(list); + let list = b.take_body(&mut block, 0); + for at in 0..width { + let mut taken = b.take(list, at); + b.own_statement(&mut taken); + } + let rebuilt = effects(&mut b, width); + let before = b.steps; + b.set_body_adopting(&mut block, 0, rebuilt); + steps.push(b.steps - before); + assert_eq!(b.block_len(&block), width); + } + assert!(steps[0] >= 1_000, "{steps:?}"); + assert!(steps[1] <= 11 * steps[0], "{steps:?}"); + } + + /// The changed body of a function literal is put back by its header: + /// what is there afterwards is the list given, a statement made since + /// the body was taken among its statements. + #[test] + fn the_changed_body_of_a_function_literal_is_put_back_by_its_header() { + let allocator = Allocator::default(); + let mut b = Builder::new(&allocator); + b.reserve_literals(4); + let body = effects(&mut b, 2); + let literal = b.function(3, body); + let row = literal.row; + let list = b.literal_body(3); + let (first, mut second) = (b.take(list, 0), b.take(list, 1)); + b.own_statement(&mut second); + let value = b.reference(1, 0); + let replaced = b.return_(value); + let expected = [first.stmt.node_id().index(), replaced.stmt.node_id().index()]; + let mark = b.stage_mark(); + b.stage(first); + b.stage(replaced); + let rebuilt = b.list(mark); + let steps = b.steps; + b.set_literal_body_adopting(3, rebuilt); + assert_eq!(b.steps - steps, 1); + let again = b.literal_body(3); + assert_eq!((again, &ids(&b, again)[..]), (rebuilt, &expected[..])); + assert_eq!([b.row_at(again, 0).kind, b.row_at(again, 1).kind], [Kind::Exp, Kind::Return]); + b.set_literal_body(3, again); + // The literal's row has none of its body's facts: it is as built. + assert_eq!(b.row(&literal.expr), row); + } + /// What [`found`] gives as (is a literal, header or variable): the /// form the tests of `bir::j` compare the two implementations in /// (`rows_stmt_tests.rs`, `replay::both`).