repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by bugabinga

Budget compile time, gate dependencies, and prove per-frame layout (#9)

3e3df798044f2b6b31e68c3572e3846bd7d1aa9b

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

* Make dependencies a spec decision and budget compile time by caching

A worker agent that quietly adds a crate can drop a minute onto every
build and poison the incremental cache the workspace split exists to
protect, so dependency changes now require spec-owner escalation
(PROJECT-INVARIANTS §5) — prototypes stay exempt because validating a
candidate before production is their whole job. The compile budget is
split to match how the cost is actually felt: incremental rebuild of a
touched crate's reverse-dep closure is the governing dev/agent metric
and a structural guarantee of dependency siloing, while cold build and
crate count are a CI regression gate paid once. The fast tier scopes to
touched crates so that guarantee is realized, not erased by a
--workspace --all-features sweep.

Edits PROJECT-INVARIANTS §5/§11 and SPEC §2.3/§13.1/§17.1.

* Plan the per-frame layout prototype

§8 says Lua defines layout and the render loop ticks at 16ms, but never
says where resolution happens — and if it re-enters Lua every frame it
would put plugin-thread round-trips (p15: ~81us, serialized) on the 2ms
render path. p27 validates the intended design instead of assuming it:
Lua builds the tree once, Rust resolves Rects every frame with no Lua in
the loop.

Adds prototypes/PLAN.md section p27.

* Separate adding a dependency from bumping one

The prior rule treated a version bump like adding a crate, but they are
different acts: adding pulls a new concern into the architecture and
compile budget and must escalate, while bumping an already-approved
crate is security and compatibility upkeep that a dedicated dependency
agent should own. Routine bumps now ride the CI gates instead of a
per-bump escalation; only a semver-breaking, MSRV-raising, or
budget-tripping bump escalates like a new dependency, because those can
change behavior or cost.

Edits PROJECT-INVARIANTS §5 and SPEC §2.3.

* Prove per-frame layout resolves in Rust with no Lua in the loop

§8 said Lua defines layout and the render loop ticks at 16ms but never
said where resolution runs — and re-entering the plugin thread every
frame (p15: ~81us, serialized) would fight the 2ms budget. It doesn't
have to: Lua builds the tree once into an owned Send+static Rust
structure, the Lua value is dropped, and a pure resolver maps
(tree, size) to Rects every frame. A call counter stayed flat across
10k resolves at three terminal sizes; release p99 is 0.47us against the
2ms budget, and the resolved tree moves cross-thread and resolves
identically after the Lua state is gone.

Surfaced a real gap too: §8.7 has no operator to float an overlay over
a base layout, and leaves tabs/scrollable/Size::Pct rounding to the
resolver to invent.

Adds prototypes/p27-per-frame-layout.

* Pin the layout-resolution contract, keeping Lua off the render path

p27 proved the resolution model §8 had only implied: a plugin builds
the layout on change into an owned Send tree, the Lua value is dropped,
and a pure Rust resolver maps it to Rects every frame with zero Lua
re-entry — so the plugin thread's ~81us round-trips never touch the 2ms
budget (measured resolution is ~0.4us). The layout invariants become a
property-test target, and the overlay/tabs/scrollable/Size rounding
rules the prototype had to invent are now stated instead of left to the
implementer.

Edits SPEC §8.7/§17.6 and the p27 result block in prototypes/PLAN.md.

---------

Co-authored-by: Claude <noreply@anthropic.com>

Changed files (6)

+2097 / −10 text lines

Diff layout

docs/PROJECT-INVARIANTS.md

Modified

+28 / −1 text lines

254254Files that coding agents MUST NOT modify without explicit user approval:
255255- `docs/PROJECT-INVARIANTS.md`
256256- `docs/SPEC.md` (source of truth — agents read, don't edit without approval)
257- `Cargo.toml` workspace root (agents read dependencies, don't add/remove)
257- `Cargo.toml` workspace root
258- adding or removing a crate in any `Cargo.toml` `[dependencies]` (version
259 bumps are maintenance — see the dependency rule below)
258260- `.cargo/config.toml`
259261- `rust-toolchain.toml`
263**Adding a dependency is a spec decision; bumping one is maintenance.** A new
264third-party crate — or removing one — changes the architecture, crate set,
265compile budget, and siloing, so a worker agent escalates to the spec owner and
266never introduces a crate on its own initiative. The canonical set is SPEC §2.3
267and the change follows the spec-approval path. A **version bump** of an
268already-approved crate is routine upkeep, not a spec decision: it may be done
269by a dedicated dependency-maintenance agent or automation, provided it passes
270every gate — build, tests, clippy, `cargo deny`, and the §13.1 compile-budget
271regression gate. A bump that is semver-incompatible, raises the toolchain MSRV,
272or trips the compile-budget gate escalates like a new dependency, because it
273can change behavior or cost. Prototypes under `prototypes/` are exempt from all
274of this (SPEC §18): adding a crate to validate it before production is their
275job, and that evidence is what gets escalated.
261277Files that coding agents MAY modify freely:
262278- `*/src/*.rs` (implementation)
263279- `*/tests/*.rs` (tests)
407423- `mod.rs` files contain only module declarations and re-exports.
408424- Wildcard imports are forbidden outside tests.
426**Dependency siloing (incremental-build invariant).** Heavy or fast-moving
427third-party crates attach at the leaf crate that owns the concern —
428`reqwest`/`tokio` in `smith-ai`, `syntastica`/`ratatui` in `smith-tui`,
429`jj-lib`/`gix` behind `smith-core`/`smith-harness` — and MUST NOT propagate up
430into `smith`. The foundation crate is depended on by every other crate, so any
431churn or heavy dependency there invalidates the whole workspace's incremental
432cache; keeping it minimal is what lets an edit to one leaf crate rebuild
433without touching the others' compiled artifacts. `smith` carries only small,
434stable, universally-shared code (its one heavy dependency, `mlua`, is a locked
435exception because the SDK type surface needs it).
410437Architecture gates:
411438- `cargo run -p xtask -- arch` verifies stable Rust metadata/source invariants.
412439- `cargo run -p xtask -- pup` runs `cargo +nightly-2026-01-22 pup`.

docs/SPEC.md

Modified

+70 / −9 text lines

219219flate2 = "1"
220220```
222This list is the canonical dependency registry. Adding or removing a crate here
223is a spec decision (PROJECT-INVARIANTS §5): worker agents escalate to the spec
224owner and never introduce a dependency on their own; a prototype under
225`prototypes/` validates a candidate first, and its evidence is what the
226decision rests on. Version bumps of an already-listed crate are maintenance,
227not a spec decision — routine bumps ride the CI gates (build, tests,
228`cargo deny`, the §13.1 compile budget), while a semver-breaking, MSRV-raising,
229or budget-tripping bump escalates like a new dependency. Heavy dependencies
230attach at the crate that owns the concern and never propagate up into `smith`
231(PROJECT-INVARIANTS §11 dependency-siloing invariant), so a leaf-crate edit
232never rebuilds an unrelated crate's dependency tree.
222234Two version constraints are load-bearing (prototype-decided, p25/p26): `gix`
223235is pinned to the version `jj-lib` pulls (0.85) so the two never compile a
224236duplicate gix tree, and `jj-lib` is pinned exact because it is pre-1.0 with a
927939mutation:
929941- **Storage never shrinks.** The session file keeps every entry verbatim;
930 memory stays bounded by lazy loading (§13.1).
942 memory stays bounded by lazy loading (§13.2).
931943- **A compaction pass appends a summary entry** to the current path,
932944 recording the covered span (from/to `EntryId`), the summary text, and
933945 before/after token estimates.
14101422each panel carrying `visible`, `size`, and its own layout. Panels are invisible
14111423when empty. Default layout is a Lua plugin.
1425Composition rules (prototype-proven, p27):
1427- `overlay` floats over its container area and is excluded from the flow
1428 tiling set — flow siblings still tile as if it were absent, and the overlay
1429 is positioned by the §8.6 anchor model. Overlays may cover flow content by
1430 design (modals, command palette, autocomplete).
1431- `tabs` reserves a one-row tab bar; the active child gets the remaining area.
1432- `scrollable` is layout-transparent — a viewport over its child, not an axis
1433 partition.
1434- `Size::Percent` rounds to the nearest cell.
1436**Resolution (prototype-proven, p27).** Layout resolution never re-enters Lua
1437on the render path. A plugin builds the layout on change (`set_center_layout`,
1438`set_*_panel`); the harness converts that Lua tree once into an owned Rust
1439`LayoutTree` that retains no Lua handle (`Send + 'static`, so it can be built
1440off the render thread) and drops the Lua value. Every frame, a pure resolver
1441maps `(LayoutTree, terminal size) → Rect per widget slot` — deterministic for
1442equal inputs, zero Lua calls in the loop. This is what keeps §12's plugin-
1443thread round-trips (~81µs, serialized) off the §13 2ms frame budget; measured
1444per-frame resolution is ~0.4µs (release p99 &lt; 0.8µs) across 80×24 to 400×100.
14131446### 8.8 Theme
14151448Themes are Lua tables validated by Rust schemas (prototype-proven, p08).
24512484- Agent loop turn target < 30s excluding provider/network stalls beyond timeout.
24522485- Bench regressions fail nightly/release gates (thresholds in §17.9).
2454### 13.1 Memory Policy
2487### 13.1 Compile-Time Budget
2489Compile time is budgeted on two distinct axes, because they answer different
2490questions:
2492- **Incremental rebuild is the governing dev/agent metric.** After a one-crate
2493 edit, the rebuild recompiles that crate and its reverse-dependency closure
2494 only — never an unrelated leaf crate or its heavy dependency tree. This is a
2495 structural guarantee of the workspace split + dependency siloing
2496 (PROJECT-INVARIANTS §11), not just a time target; the edit→check loop that
2497 dominates agent and dev work depends on it.
2498- **Cold build and crate count are a CI-cost sub-budget.** The full transitive
2499 tree (mlua/LuaJIT, jj-lib, gix, reqwest+tokio, aws-lc/TLS, syntastica) is
2500 paid once and cached; the gate is on *regression* — a dependency change that
2501 materially grows cold build or crate count fails CI the same way a
2502 binary-size or bench regression does. Exact thresholds are set from the
2503 first real full-workspace build.
2505A single TLS backend is shared across `reqwest` and `gix` rather than shipping
2506two stacks (p25).
2508### 13.2 Memory Policy
24562510Prototype-proven against the measured session corpus (p09; see
24572511`docs/research/SMITH-MEMORY-ALLOCATION-PROFILE.md`):
25502604### 17.1 Fast Tier
2552Every commit:
2606Every commit, scoped to the touched crates and their reverse-dependency
2607closure (`-p <crate>`), so the §13.1 incremental guarantee is realized rather
2608than erased by a full-workspace `--all-features` sweep:
25542610```bash
25552611cargo fmt --check
2556cargo clippy --workspace --all-targets --all-features -- -D warnings
2612cargo clippy -p <touched...> --all-targets -- -D warnings
25572613cargo run -p xtask -- arch
2558cargo +nightly-2026-01-22 pup
2559cargo nextest run --profile fast
2560cargo test --doc
2614cargo +nightly-2026-01-22 pup -p <touched...>
2615cargo nextest run --profile fast -p <touched...>
2616cargo test --doc -p <touched...>
25612617```
2563Blocks push.
2619The full `--workspace --all-features` clippy/build/test sweep runs in the
2620medium tier (§17.2), not per-commit. Blocks push.
25652622Scope:
26502707- valid Lua config parsing,
26512708- token estimator monotonicity,
26522709- event-to-session-entry conversion,
2653- trace filtering preserves order.
2710- trace filtering preserves order,
2711- layout resolution (§8.7): every child Rect within its parent's bounds; flow
2712 siblings tile their axis without overlap; `expanded` is the exact remainder;
2713 `split` honors `split_ratio` (± one cell) and tiles exactly; resolution is
2714 deterministic for equal `(tree, size)`.
26552716Commit `proptest-regressions/`.

prototypes/PLAN.md

Modified

+77 / −0 text lines

18591859issues: P1 kstring pin; P2 §9.13 embed default, jj-lib API-stability caveat,
18601860gix 0.83→0.85 alignment.
1862## Campaign 5 — TUI layout resolution
1864## P27 — `p27-per-frame-layout`
1866### SPEC claims
1868- §8.7: "Rust provides primitives; Lua defines layout."
1869- §8.5: the render loop ticks at 16ms; §13: TUI frame draw < 2ms.
1870- §12/p15: Lua runs on one dedicated plugin thread; calls into it are ~81µs
1871 round-trips that serialize.
1873### Risk
1875If layout resolution calls INTO Lua every frame, it puts plugin-thread
1876round-trips on the render hot path — fighting both the 2ms budget and the §12
1877thread model. The intended-but-unstated design must be validated: Lua builds
1878the layout tree ONCE (or on change) into owned Rust data, and Rust resolves it
1879to ratatui `Rect`s every frame with ZERO Lua in the loop.
1881### Minimal artifact
1883```text
1884p27-per-frame-layout/
1885 Cargo.toml (mlua luajit vendored, ratatui — prototype-exempt deps)
1886 src/main.rs
1887```
1889A Lua plugin defines a layout via the §8.7 primitives; the harness converts it
1890once into an owned Rust `LayoutTree`; a resolver maps `(tree, terminal size) →
1891Rect per widget slot`, called every frame.
1893### Verify
1895```bash
1896cd prototypes/p27-per-frame-layout
1897cargo run -- build-once
1898cargo run -- resolve-frame
1899cargo run -- properties
1900cargo run -- invalidation
1901cargo run -- all
1902```
1904### Pass evidence
1906- the Lua-defined layout becomes owned Rust data; resolution runs with the Lua
1907 state uninvoked (a call counter proves zero Lua calls per frame), and works
1908 even after the tree is detached from Lua,
1909- per-frame resolution time measured at 80x24, 200x50, 400x100 for a realistic
1910 default tree (border panels + column of status/messages/input/hints +
1911 overlay) — reported, and far under 2ms,
1912- layout properties hold: children within parent bounds, siblings do not
1913 overlap, `expanded` fills the remainder, `split_ratio` honored, resolution
1914 deterministic for equal `(tree, size)` — the §17 property-test target,
1915- the tree is rebuilt only on explicit mutation (`set_center_layout` /
1916 `set_*_panel`); between mutations no Lua re-entry occurs.
1918### SPEC impact
1920State the §8 layout-resolution contract: Lua builds the layout tree on change
1921into owned Rust data; Rust resolves `Rect`s every frame as a pure,
1922deterministic function of `(tree, size)` with no Lua in the render loop; name
1923the layout property invariants as a §17 property-test target.
1925### Result
1927Status: complete. Proved: the two-phase zero-Lua-in-loop pipeline holds — a
1928Lua-call counter stayed flat across 10k resolves at 80×24/200×50/400×100; the
1929owned `LayoutTree` is `Send + 'static` (compile-asserted) and resolves
1930identically after `drop(lua)` on another thread; release per-frame resolution
1931median ~0.4µs / p99 &lt;0.8µs vs the 2ms budget; property invariants hold over
1932192 (tree,size) pairs. **Disproved nothing** (the "must re-enter Lua / can't
1933hit 2ms" counter-hypothesis is refuted). Surfaced a real gap: §8.7 had no
1934overlay-over-base composition operator, nor rules for tabs/scrollable/Size::Pct
1935— the prototype's resolutions are now the §8.7 composition rules. Folded into
1936§8.7 and §17.6. Spec issues: P1 resolution contract, P2 property target, P2
1937composition rules.
18621939## Reporting Template
18641941Each completed prototype updates this plan with a result block in the

prototypes/p27-per-frame-layout/Cargo.lock

Added
new file mode 100644

+817 / −0 text lines

1# This file is automatically @generated by Cargo.
2# It is not intended for manual editing.
3version = 4
4
5[[package]]
6name = "allocator-api2"
7version = "0.2.21"
8source = "registry+https://github.com/rust-lang/crates.io-index"
9checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
11[[package]]
12name = "autocfg"
13version = "1.5.1"
14source = "registry+https://github.com/rust-lang/crates.io-index"
15checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
17[[package]]
18name = "bitflags"
19version = "2.13.1"
20source = "registry+https://github.com/rust-lang/crates.io-index"
21checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
23[[package]]
24name = "bstr"
25version = "1.13.0"
26source = "registry+https://github.com/rust-lang/crates.io-index"
27checksum = "1f7dc094d718f2e1c1559ad110e27eeaae14a5465d3d56dd6dbd793079fbd530"
28dependencies = [
29 "memchr",
30 "serde_core",
31]
33[[package]]
34name = "cassowary"
35version = "0.3.0"
36source = "registry+https://github.com/rust-lang/crates.io-index"
37checksum = "df8670b8c7b9dae1793364eafadf7239c40d669904660c5960d74cfd80b46a53"
39[[package]]
40name = "castaway"
41version = "0.2.4"
42source = "registry+https://github.com/rust-lang/crates.io-index"
43checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a"
44dependencies = [
45 "rustversion",
46]
48[[package]]
49name = "cc"
50version = "1.2.67"
51source = "registry+https://github.com/rust-lang/crates.io-index"
52checksum = "e17dd265a7d0f31ef544e1b20e03add05d3b45b491b633b10d67145d2acc1a38"
53dependencies = [
54 "find-msvc-tools",
55 "shlex",
56]
58[[package]]
59name = "cfg-if"
60version = "1.0.4"
61source = "registry+https://github.com/rust-lang/crates.io-index"
62checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
64[[package]]
65name = "compact_str"
66version = "0.8.2"
67source = "registry+https://github.com/rust-lang/crates.io-index"
68checksum = "7fd622ebbb56a5b2ccb651b32b911cdeb2a9b4b11776b2473bf26a26a286244e"
69dependencies = [
70 "castaway",
71 "cfg-if",
72 "itoa",
73 "rustversion",
74 "ryu",
75 "static_assertions",
76]
78[[package]]
79name = "crossterm"
80version = "0.28.1"
81source = "registry+https://github.com/rust-lang/crates.io-index"
82checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6"
83dependencies = [
84 "bitflags",
85 "crossterm_winapi",
86 "mio",
87 "parking_lot",
88 "rustix 0.38.44",
89 "signal-hook",
90 "signal-hook-mio",
91 "winapi",
92]
94[[package]]
95name = "crossterm_winapi"
96version = "0.9.1"
97source = "registry+https://github.com/rust-lang/crates.io-index"
98checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b"
99dependencies = [
100 "winapi",
101]
103[[package]]
104name = "darling"
105version = "0.23.0"
106source = "registry+https://github.com/rust-lang/crates.io-index"
107checksum = "25ae13da2f202d56bd7f91c25fba009e7717a1e4a1cc98a76d844b65ae912e9d"
108dependencies = [
109 "darling_core",
110 "darling_macro",
111]
113[[package]]
114name = "darling_core"
115version = "0.23.0"
116source = "registry+https://github.com/rust-lang/crates.io-index"
117checksum = "9865a50f7c335f53564bb694ef660825eb8610e0a53d3e11bf1b0d3df31e03b0"
118dependencies = [
119 "ident_case",
120 "proc-macro2",
121 "quote",
122 "strsim",
123 "syn",
124]
126[[package]]
127name = "darling_macro"
128version = "0.23.0"
129source = "registry+https://github.com/rust-lang/crates.io-index"
130checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d"
131dependencies = [
132 "darling_core",
133 "quote",
134 "syn",
135]
137[[package]]
138name = "either"
139version = "1.16.0"
140source = "registry+https://github.com/rust-lang/crates.io-index"
141checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
143[[package]]
144name = "env_home"
145version = "0.1.0"
146source = "registry+https://github.com/rust-lang/crates.io-index"
147checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe"
149[[package]]
150name = "equivalent"
151version = "1.0.2"
152source = "registry+https://github.com/rust-lang/crates.io-index"
153checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
155[[package]]
156name = "erased-serde"
157version = "0.4.10"
158source = "registry+https://github.com/rust-lang/crates.io-index"
159checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec"
160dependencies = [
161 "serde",
162 "serde_core",
163 "typeid",
164]
166[[package]]
167name = "errno"
168version = "0.3.14"
169source = "registry+https://github.com/rust-lang/crates.io-index"
170checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
171dependencies = [
172 "libc",
173 "windows-sys 0.61.2",
174]
176[[package]]
177name = "find-msvc-tools"
178version = "0.1.9"
179source = "registry+https://github.com/rust-lang/crates.io-index"
180checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
182[[package]]
183name = "foldhash"
184version = "0.1.5"
185source = "registry+https://github.com/rust-lang/crates.io-index"
186checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
188[[package]]
189name = "hashbrown"
190version = "0.15.5"
191source = "registry+https://github.com/rust-lang/crates.io-index"
192checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
193dependencies = [
194 "allocator-api2",
195 "equivalent",
196 "foldhash",
197]
199[[package]]
200name = "heck"
201version = "0.5.0"
202source = "registry+https://github.com/rust-lang/crates.io-index"
203checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
205[[package]]
206name = "ident_case"
207version = "1.0.1"
208source = "registry+https://github.com/rust-lang/crates.io-index"
209checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
211[[package]]
212name = "indoc"
213version = "2.0.7"
214source = "registry+https://github.com/rust-lang/crates.io-index"
215checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706"
216dependencies = [
217 "rustversion",
218]
220[[package]]
221name = "instability"
222version = "0.3.12"
223source = "registry+https://github.com/rust-lang/crates.io-index"
224checksum = "5eb2d60ef19920a3a9193c3e371f726ec1dafc045dac788d0fb3704272458971"
225dependencies = [
226 "darling",
227 "indoc",
228 "proc-macro2",
229 "quote",
230 "syn",
231]
233[[package]]
234name = "itertools"
235version = "0.13.0"
236source = "registry+https://github.com/rust-lang/crates.io-index"
237checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
238dependencies = [
239 "either",
240]
242[[package]]
243name = "itoa"
244version = "1.0.18"
245source = "registry+https://github.com/rust-lang/crates.io-index"
246checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
248[[package]]
249name = "libc"
250version = "0.2.186"
251source = "registry+https://github.com/rust-lang/crates.io-index"
252checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
254[[package]]
255name = "linux-raw-sys"
256version = "0.4.15"
257source = "registry+https://github.com/rust-lang/crates.io-index"
258checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab"
260[[package]]
261name = "linux-raw-sys"
262version = "0.12.1"
263source = "registry+https://github.com/rust-lang/crates.io-index"
264checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
266[[package]]
267name = "lock_api"
268version = "0.4.14"
269source = "registry+https://github.com/rust-lang/crates.io-index"
270checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
271dependencies = [
272 "scopeguard",
273]
275[[package]]
276name = "log"
277version = "0.4.33"
278source = "registry+https://github.com/rust-lang/crates.io-index"
279checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
281[[package]]
282name = "lru"
283version = "0.12.5"
284source = "registry+https://github.com/rust-lang/crates.io-index"
285checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38"
286dependencies = [
287 "hashbrown",
288]
290[[package]]
291name = "lua-src"
292version = "547.0.0"
293source = "registry+https://github.com/rust-lang/crates.io-index"
294checksum = "1edaf29e3517b49b8b746701e5648ccb5785cde1c119062cbabbc5d5cd115e42"
295dependencies = [
296 "cc",
297]
299[[package]]
300name = "luajit-src"
301version = "210.5.12+a4f56a4"
302source = "registry+https://github.com/rust-lang/crates.io-index"
303checksum = "b3a8e7962a5368d5f264d045a5a255e90f9aa3fc1941ae15a8d2940d42cac671"
304dependencies = [
305 "cc",
306 "which",
307]
309[[package]]
310name = "memchr"
311version = "2.8.3"
312source = "registry+https://github.com/rust-lang/crates.io-index"
313checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
315[[package]]
316name = "mio"
317version = "1.2.2"
318source = "registry+https://github.com/rust-lang/crates.io-index"
319checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427"
320dependencies = [
321 "libc",
322 "log",
323 "wasi",
324 "windows-sys 0.61.2",
325]
327[[package]]
328name = "mlua"
329version = "0.10.5"
330source = "registry+https://github.com/rust-lang/crates.io-index"
331checksum = "c1f5f8fbebc7db5f671671134b9321c4b9aa9adeafccfd9a8c020ae45c6a35d0"
332dependencies = [
333 "bstr",
334 "either",
335 "erased-serde",
336 "mlua-sys",
337 "num-traits",
338 "parking_lot",
339 "rustc-hash",
340 "rustversion",
341 "serde",
342 "serde-value",
343]
345[[package]]
346name = "mlua-sys"
347version = "0.6.8"
348source = "registry+https://github.com/rust-lang/crates.io-index"
349checksum = "380c1f7e2099cafcf40e51d3a9f20a346977587aa4d012eae1f043149a728a93"
350dependencies = [
351 "cc",
352 "cfg-if",
353 "lua-src",
354 "luajit-src",
355 "pkg-config",
356]
358[[package]]
359name = "num-traits"
360version = "0.2.19"
361source = "registry+https://github.com/rust-lang/crates.io-index"
362checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
363dependencies = [
364 "autocfg",
365]
367[[package]]
368name = "ordered-float"
369version = "2.10.1"
370source = "registry+https://github.com/rust-lang/crates.io-index"
371checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c"
372dependencies = [
373 "num-traits",
374]
376[[package]]
377name = "p27-per-frame-layout"
378version = "0.1.0"
379dependencies = [
380 "mlua",
381 "ratatui",
382]
384[[package]]
385name = "parking_lot"
386version = "0.12.5"
387source = "registry+https://github.com/rust-lang/crates.io-index"
388checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
389dependencies = [
390 "lock_api",
391 "parking_lot_core",
392]
394[[package]]
395name = "parking_lot_core"
396version = "0.9.12"
397source = "registry+https://github.com/rust-lang/crates.io-index"
398checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
399dependencies = [
400 "cfg-if",
401 "libc",
402 "redox_syscall",
403 "smallvec",
404 "windows-link",
405]
407[[package]]
408name = "paste"
409version = "1.0.15"
410source = "registry+https://github.com/rust-lang/crates.io-index"
411checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
413[[package]]
414name = "pkg-config"
415version = "0.3.33"
416source = "registry+https://github.com/rust-lang/crates.io-index"
417checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
419[[package]]
420name = "proc-macro2"
421version = "1.0.106"
422source = "registry+https://github.com/rust-lang/crates.io-index"
423checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
424dependencies = [
425 "unicode-ident",
426]
428[[package]]
429name = "quote"
430version = "1.0.46"
431source = "registry+https://github.com/rust-lang/crates.io-index"
432checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
433dependencies = [
434 "proc-macro2",
435]
437[[package]]
438name = "ratatui"
439version = "0.29.0"
440source = "registry+https://github.com/rust-lang/crates.io-index"
441checksum = "eabd94c2f37801c20583fc49dd5cd6b0ba68c716787c2dd6ed18571e1e63117b"
442dependencies = [
443 "bitflags",
444 "cassowary",
445 "compact_str",
446 "crossterm",
447 "indoc",
448 "instability",
449 "itertools",
450 "lru",
451 "paste",
452 "strum",
453 "unicode-segmentation",
454 "unicode-truncate",
455 "unicode-width 0.2.0",
456]
458[[package]]
459name = "redox_syscall"
460version = "0.5.18"
461source = "registry+https://github.com/rust-lang/crates.io-index"
462checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
463dependencies = [
464 "bitflags",
465]
467[[package]]
468name = "rustc-hash"
469version = "2.1.3"
470source = "registry+https://github.com/rust-lang/crates.io-index"
471checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
473[[package]]
474name = "rustix"
475version = "0.38.44"
476source = "registry+https://github.com/rust-lang/crates.io-index"
477checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"
478dependencies = [
479 "bitflags",
480 "errno",
481 "libc",
482 "linux-raw-sys 0.4.15",
483 "windows-sys 0.59.0",
484]
486[[package]]
487name = "rustix"
488version = "1.1.4"
489source = "registry+https://github.com/rust-lang/crates.io-index"
490checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
491dependencies = [
492 "bitflags",
493 "errno",
494 "libc",
495 "linux-raw-sys 0.12.1",
496 "windows-sys 0.61.2",
497]
499[[package]]
500name = "rustversion"
501version = "1.0.23"
502source = "registry+https://github.com/rust-lang/crates.io-index"
503checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
505[[package]]
506name = "ryu"
507version = "1.0.23"
508source = "registry+https://github.com/rust-lang/crates.io-index"
509checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
511[[package]]
512name = "scopeguard"
513version = "1.2.0"
514source = "registry+https://github.com/rust-lang/crates.io-index"
515checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
517[[package]]
518name = "serde"
519version = "1.0.228"
520source = "registry+https://github.com/rust-lang/crates.io-index"
521checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
522dependencies = [
523 "serde_core",
524]
526[[package]]
527name = "serde-value"
528version = "0.7.0"
529source = "registry+https://github.com/rust-lang/crates.io-index"
530checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c"
531dependencies = [
532 "ordered-float",
533 "serde",
534]
536[[package]]
537name = "serde_core"
538version = "1.0.228"
539source = "registry+https://github.com/rust-lang/crates.io-index"
540checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
541dependencies = [
542 "serde_derive",
543]
545[[package]]
546name = "serde_derive"
547version = "1.0.228"
548source = "registry+https://github.com/rust-lang/crates.io-index"
549checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
550dependencies = [
551 "proc-macro2",
552 "quote",
553 "syn",
554]
556[[package]]
557name = "shlex"
558version = "2.0.1"
559source = "registry+https://github.com/rust-lang/crates.io-index"
560checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
562[[package]]
563name = "signal-hook"
564version = "0.3.18"
565source = "registry+https://github.com/rust-lang/crates.io-index"
566checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"
567dependencies = [
568 "libc",
569 "signal-hook-registry",
570]
572[[package]]
573name = "signal-hook-mio"
574version = "0.2.5"
575source = "registry+https://github.com/rust-lang/crates.io-index"
576checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc"
577dependencies = [
578 "libc",
579 "mio",
580 "signal-hook",
581]
583[[package]]
584name = "signal-hook-registry"
585version = "1.4.8"
586source = "registry+https://github.com/rust-lang/crates.io-index"
587checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
588dependencies = [
589 "errno",
590 "libc",
591]
593[[package]]
594name = "smallvec"
595version = "1.15.2"
596source = "registry+https://github.com/rust-lang/crates.io-index"
597checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
599[[package]]
600name = "static_assertions"
601version = "1.1.0"
602source = "registry+https://github.com/rust-lang/crates.io-index"
603checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f"
605[[package]]
606name = "strsim"
607version = "0.11.1"
608source = "registry+https://github.com/rust-lang/crates.io-index"
609checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
611[[package]]
612name = "strum"
613version = "0.26.3"
614source = "registry+https://github.com/rust-lang/crates.io-index"
615checksum = "8fec0f0aef304996cf250b31b5a10dee7980c85da9d759361292b8bca5a18f06"
616dependencies = [
617 "strum_macros",
618]
620[[package]]
621name = "strum_macros"
622version = "0.26.4"
623source = "registry+https://github.com/rust-lang/crates.io-index"
624checksum = "4c6bee85a5a24955dc440386795aa378cd9cf82acd5f764469152d2270e581be"
625dependencies = [
626 "heck",
627 "proc-macro2",
628 "quote",
629 "rustversion",
630 "syn",
631]
633[[package]]
634name = "syn"
635version = "2.0.119"
636source = "registry+https://github.com/rust-lang/crates.io-index"
637checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
638dependencies = [
639 "proc-macro2",
640 "quote",
641 "unicode-ident",
642]
644[[package]]
645name = "typeid"
646version = "1.0.3"
647source = "registry+https://github.com/rust-lang/crates.io-index"
648checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"
650[[package]]
651name = "unicode-ident"
652version = "1.0.24"
653source = "registry+https://github.com/rust-lang/crates.io-index"
654checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
656[[package]]
657name = "unicode-segmentation"
658version = "1.13.3"
659source = "registry+https://github.com/rust-lang/crates.io-index"
660checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
662[[package]]
663name = "unicode-truncate"
664version = "1.1.0"
665source = "registry+https://github.com/rust-lang/crates.io-index"
666checksum = "b3644627a5af5fa321c95b9b235a72fd24cd29c648c2c379431e6628655627bf"
667dependencies = [
668 "itertools",
669 "unicode-segmentation",
670 "unicode-width 0.1.14",
671]
673[[package]]
674name = "unicode-width"
675version = "0.1.14"
676source = "registry+https://github.com/rust-lang/crates.io-index"
677checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"
679[[package]]
680name = "unicode-width"
681version = "0.2.0"
682source = "registry+https://github.com/rust-lang/crates.io-index"
683checksum = "1fc81956842c57dac11422a97c3b8195a1ff727f06e85c84ed2e8aa277c9a0fd"
685[[package]]
686name = "wasi"
687version = "0.11.1+wasi-snapshot-preview1"
688source = "registry+https://github.com/rust-lang/crates.io-index"
689checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
691[[package]]
692name = "which"
693version = "7.0.3"
694source = "registry+https://github.com/rust-lang/crates.io-index"
695checksum = "24d643ce3fd3e5b54854602a080f34fb10ab75e0b813ee32d00ca2b44fa74762"
696dependencies = [
697 "either",
698 "env_home",
699 "rustix 1.1.4",
700 "winsafe",
701]
703[[package]]
704name = "winapi"
705version = "0.3.9"
706source = "registry+https://github.com/rust-lang/crates.io-index"
707checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
708dependencies = [
709 "winapi-i686-pc-windows-gnu",
710 "winapi-x86_64-pc-windows-gnu",
711]
713[[package]]
714name = "winapi-i686-pc-windows-gnu"
715version = "0.4.0"
716source = "registry+https://github.com/rust-lang/crates.io-index"
717checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
719[[package]]
720name = "winapi-x86_64-pc-windows-gnu"
721version = "0.4.0"
722source = "registry+https://github.com/rust-lang/crates.io-index"
723checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
725[[package]]
726name = "windows-link"
727version = "0.2.1"
728source = "registry+https://github.com/rust-lang/crates.io-index"
729checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
731[[package]]
732name = "windows-sys"
733version = "0.59.0"
734source = "registry+https://github.com/rust-lang/crates.io-index"
735checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
736dependencies = [
737 "windows-targets",
738]
740[[package]]
741name = "windows-sys"
742version = "0.61.2"
743source = "registry+https://github.com/rust-lang/crates.io-index"
744checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
745dependencies = [
746 "windows-link",
747]
749[[package]]
750name = "windows-targets"
751version = "0.52.6"
752source = "registry+https://github.com/rust-lang/crates.io-index"
753checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
754dependencies = [
755 "windows_aarch64_gnullvm",
756 "windows_aarch64_msvc",
757 "windows_i686_gnu",
758 "windows_i686_gnullvm",
759 "windows_i686_msvc",
760 "windows_x86_64_gnu",
761 "windows_x86_64_gnullvm",
762 "windows_x86_64_msvc",
763]
765[[package]]
766name = "windows_aarch64_gnullvm"
767version = "0.52.6"
768source = "registry+https://github.com/rust-lang/crates.io-index"
769checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
771[[package]]
772name = "windows_aarch64_msvc"
773version = "0.52.6"
774source = "registry+https://github.com/rust-lang/crates.io-index"
775checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
777[[package]]
778name = "windows_i686_gnu"
779version = "0.52.6"
780source = "registry+https://github.com/rust-lang/crates.io-index"
781checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
783[[package]]
784name = "windows_i686_gnullvm"
785version = "0.52.6"
786source = "registry+https://github.com/rust-lang/crates.io-index"
787checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
789[[package]]
790name = "windows_i686_msvc"
791version = "0.52.6"
792source = "registry+https://github.com/rust-lang/crates.io-index"
793checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
795[[package]]
796name = "windows_x86_64_gnu"
797version = "0.52.6"
798source = "registry+https://github.com/rust-lang/crates.io-index"
799checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
801[[package]]
802name = "windows_x86_64_gnullvm"
803version = "0.52.6"
804source = "registry+https://github.com/rust-lang/crates.io-index"
805checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
807[[package]]
808name = "windows_x86_64_msvc"
809version = "0.52.6"
810source = "registry+https://github.com/rust-lang/crates.io-index"
811checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
813[[package]]
814name = "winsafe"
815version = "0.0.19"
816source = "registry+https://github.com/rust-lang/crates.io-index"
817checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"

prototypes/p27-per-frame-layout/Cargo.toml

Added
new file mode 100644

+9 / −0 text lines

1[package]
2name = "p27-per-frame-layout"
3version = "0.1.0"
4edition = "2021"
5publish = false
6
7[dependencies]
8mlua = { version = "0.10", features = ["luajit", "vendored", "serialize"] }
9ratatui = "0.29"

prototypes/p27-per-frame-layout/src/main.rs

Added
new file mode 100644

+1096 / −0 text lines

1//! p27-per-frame-layout
2//!
3//! Proves or disproves docs/SPEC.md §8.7 / §8.5 / §8.6 / §13 claims:
4//!
5//! HYPOTHESIS: Lua builds the layout tree ONCE (on change) into an OWNED Rust
6//! data structure; Rust resolves that tree to ratatui `Rect`s EVERY frame with
7//! ZERO calls back into Lua.
8//!
9//! Model:
10//! (a) a Lua plugin builds a layout via §8.7 primitives, exposed as a
11//! `smith.tui.layout.*` table of Rust closures returning plain descriptor
12//! tables;
13//! (b) a ONE-TIME converter walks the returned Lua table into an owned Rust
14//! `LayoutTree` enum, after which the Lua `Value` is dropped;
15//! (c) a pure `resolve(tree, area) -> Vec<(SlotId, Rect)>` over owned data.
16//!
17//! A Lua-call counter (incremented by every `smith.tui.layout.*` closure, i.e.
18//! every time the Lua VM executes a layout primitive) proves zero Lua activity
19//! during the resolve loop: it freezes the instant conversion finishes.
20//!
21//! Scenarios (each exits 0 with PASS lines + numbers):
22//! build-once | resolve-frame | properties | invalidation | all
23//!
24//! Verify: `cargo run -- all` (release recommended: `cargo run --release -- all`)
26use std::sync::atomic::{AtomicU64, Ordering};
27use std::sync::Arc;
28use std::time::{Duration, Instant};
30use mlua::{Error as LuaError, Lua, Result as LuaResult, Table, Value};
31use ratatui::backend::TestBackend;
32use ratatui::buffer::Buffer;
33use ratatui::layout::{Constraint, Direction, Layout, Rect};
34use ratatui::widgets::{Block, Paragraph};
35use ratatui::Terminal;
37// ===========================================================================
38// Owned, Send-able layout tree (NO captured Lua handle anywhere).
39// ===========================================================================
41/// Identifier of a widget slot: an owned `String`, never a Lua reference.
42#[derive(Debug, Clone, PartialEq, Eq)]
43struct SlotId(String);
45/// §8.7 `Size`: absolute cells or a percentage of the available axis.
46#[derive(Debug, Clone, Copy, PartialEq)]
47enum Size {
48 Abs(u16),
49 Pct(u16),
50}
52/// §8.7 `BorderStyle`.
53#[derive(Debug, Clone, Copy, PartialEq)]
54enum BorderStyle {
55 None,
56 Single,
57 Double,
58 Rounded,
59 Thick,
60}
62#[derive(Debug, Clone, Copy, PartialEq)]
63enum ScrollDir {
64 Vertical,
65 Horizontal,
66 Both,
67}
69/// §8.6 nine-anchor overlay model.
70#[derive(Debug, Clone, Copy, PartialEq)]
71enum Anchor {
72 Center,
73 TopLeft,
74 TopCenter,
75 TopRight,
76 RightCenter,
77 BottomRight,
78 BottomCenter,
79 BottomLeft,
80 LeftCenter,
81}
83#[derive(Debug, Clone, Copy, PartialEq)]
84enum Axis {
85 Horizontal,
86 Vertical,
87}
89/// A border-layout panel: `visible`, `size`, and its own nested layout (§8.7).
90#[derive(Debug, Clone)]
91struct Panel {
92 visible: bool,
93 size: Size,
94 layout: Box<LayoutTree>,
95}
97/// The owned layout tree. Every field is owned data; the type is `Send +
98/// 'static` by construction (asserted below), so a built tree survives the
99/// death of the `Lua` state that produced it and can cross threads.
100#[derive(Debug, Clone)]
101enum LayoutTree {
102 Column(Vec<LayoutTree>),
103 Row(Vec<LayoutTree>),
104 Box {
105 width: Option<Size>,
106 height: Option<Size>,
107 border: BorderStyle,
108 child: Box<LayoutTree>,
109 },
110 Expanded(Box<LayoutTree>),
111 Scrollable {
112 // Direction is faithful to §8.7 but transparent to rect resolution
113 // (scrolling is a viewport concern, not a layout-partition concern).
114 #[allow(dead_code)]
115 dir: ScrollDir,
116 child: Box<LayoutTree>,
117 },
118 Overlay {
119 anchor: Anchor,
120 width: Size,
121 max_height: Size,
122 offset_x: i16,
123 offset_y: i16,
124 child: Box<LayoutTree>,
125 },
126 Spacer(Option<Size>),
127 Tabs {
128 active: usize,
129 children: Vec<LayoutTree>,
130 },
131 Split {
132 axis: Axis,
133 ratio: f32,
134 a: Box<LayoutTree>,
135 b: Box<LayoutTree>,
136 },
137 /// Predefined border layout: center + N/E/S/W panels.
138 Border {
139 center: Box<LayoutTree>,
140 north: Option<Panel>,
141 east: Option<Panel>,
142 south: Option<Panel>,
143 west: Option<Panel>,
144 },
145 WidgetSlot(SlotId),
146}
148/// Compile-time evidence that the owned tree captures no `!Send` Lua handle.
149/// If any variant held an `mlua::Function`/`Table`/`Value`, this would fail to
150/// compile (mlua without the `send` feature is `!Send`).
151const fn _assert_send<T: Send + 'static>() {}
152const _: () = _assert_send::<LayoutTree>();
154fn is_overlay(t: &LayoutTree) -> bool {
155 matches!(t, LayoutTree::Overlay { .. })
156}
158// ===========================================================================
159// (a) Lua `smith.tui.layout.*` API + call counter.
160// ===========================================================================
162/// Install `smith.tui.layout.*` builders. Every builder increments `counter`
163/// when the Lua VM invokes it — so the counter is a faithful "Lua executed a
164/// layout primitive" tally. The builders return plain descriptor tables
165/// (`{ kind = ..., ... }`); no Rust layout type is exposed to Lua.
166fn install_layout_api(lua: &Lua, counter: Arc<AtomicU64>) -> LuaResult<()> {
167 let smith = lua.create_table()?;
168 let tui = lua.create_table()?;
169 let layout = lua.create_table()?;
171 // Container/leaf builders that just tag the passed table with a `kind`.
172 for kind in ["column", "row", "box", "expanded", "scrollable", "overlay", "tabs", "split", "border"] {
173 let c = counter.clone();
174 let f = lua.create_function(move |_, t: Table| {
175 c.fetch_add(1, Ordering::Relaxed);
176 t.set("kind", kind)?;
177 Ok(t)
178 })?;
179 layout.set(kind, f)?;
180 }
182 // `slot(id)` -> { kind = "slot", id = id }
183 {
184 let c = counter.clone();
185 let f = lua.create_function(move |lua, id: String| {
186 c.fetch_add(1, Ordering::Relaxed);
187 let t = lua.create_table()?;
188 t.set("kind", "slot")?;
189 t.set("id", id)?;
190 Ok(t)
191 })?;
192 layout.set("slot", f)?;
193 }
195 // `spacer(size?)` -> { kind = "spacer", size = size? }
196 {
197 let c = counter.clone();
198 let f = lua.create_function(move |lua, size: Value| {
199 c.fetch_add(1, Ordering::Relaxed);
200 let t = lua.create_table()?;
201 t.set("kind", "spacer")?;
202 if !matches!(size, Value::Nil) {
203 t.set("size", size)?;
204 }
205 Ok(t)
206 })?;
207 layout.set("spacer", f)?;
208 }
210 tui.set("layout", layout)?;
211 smith.set("tui", tui)?;
212 lua.globals().set("smith", smith)?;
213 Ok(())
214}
216/// Build a `LayoutTree` from a Lua script that returns a layout descriptor.
217/// This is the ONE-TIME cost: the script runs, its primitives fire, we convert
218/// the returned table into owned data, and the Lua `Value` is dropped here.
219fn build_tree(lua: &Lua, script: &str) -> LuaResult<LayoutTree> {
220 let root: Value = lua.load(script).set_name("layout").eval()?;
221 let tree = convert(root)?;
222 // `root` was moved into `convert`; nothing Lua-borrowed escapes.
223 Ok(tree)
224}
226// ===========================================================================
227// (b) One-time converter: Lua descriptor table -> owned LayoutTree.
228// ===========================================================================
230fn rt(msg: impl Into<String>) -> LuaError {
231 LuaError::runtime(msg.into())
232}
234fn convert(v: Value) -> LuaResult<LayoutTree> {
235 let t = match v {
236 Value::Table(t) => t,
237 other => return Err(rt(format!("layout node must be a table, got {}", other.type_name()))),
238 };
239 let kind: String = t
240 .get::<Option<String>>("kind")?
241 .ok_or_else(|| rt("layout node missing 'kind'"))?;
243 match kind.as_str() {
244 "column" => Ok(LayoutTree::Column(convert_children(&t)?)),
245 "row" => Ok(LayoutTree::Row(convert_children(&t)?)),
246 "box" => Ok(LayoutTree::Box {
247 width: opt_size(&t, "width")?,
248 height: opt_size(&t, "height")?,
249 border: parse_border(t.get::<Option<String>>("border")?.as_deref())?,
250 child: Box::new(convert(t.get::<Value>(1)?)?),
251 }),
252 "expanded" => Ok(LayoutTree::Expanded(Box::new(convert(t.get::<Value>(1)?)?))),
253 "scrollable" => Ok(LayoutTree::Scrollable {
254 dir: parse_scroll(t.get::<Option<String>>("dir")?.as_deref())?,
255 child: Box::new(convert(t.get::<Value>(1)?)?),
256 }),
257 "overlay" => Ok(LayoutTree::Overlay {
258 anchor: parse_anchor(t.get::<Option<String>>("anchor")?.as_deref())?,
259 width: req_size(&t, "width")?,
260 max_height: req_size(&t, "max_height")?,
261 offset_x: t.get::<Option<i64>>("offset_x")?.unwrap_or(0) as i16,
262 offset_y: t.get::<Option<i64>>("offset_y")?.unwrap_or(0) as i16,
263 child: Box::new(convert(t.get::<Value>(1)?)?),
264 }),
265 "spacer" => Ok(LayoutTree::Spacer(opt_size(&t, "size")?)),
266 "tabs" => {
267 let active = t.get::<Option<i64>>("active")?.unwrap_or(0).max(0) as usize;
268 Ok(LayoutTree::Tabs {
269 active,
270 children: convert_children(&t)?,
271 })
272 }
273 "split" => Ok(LayoutTree::Split {
274 axis: parse_axis(t.get::<Option<String>>("dir")?.as_deref())?,
275 ratio: t.get::<Option<f64>>("ratio")?.unwrap_or(0.5) as f32,
276 a: Box::new(convert(t.get::<Value>(1)?)?),
277 b: Box::new(convert(t.get::<Value>(2)?)?),
278 }),
279 "border" => Ok(LayoutTree::Border {
280 center: Box::new(convert(t.get::<Value>("center")?)?),
281 north: opt_panel(&t, "north")?,
282 east: opt_panel(&t, "east")?,
283 south: opt_panel(&t, "south")?,
284 west: opt_panel(&t, "west")?,
285 }),
286 "slot" => Ok(LayoutTree::WidgetSlot(SlotId(
287 t.get::<Option<String>>("id")?
288 .ok_or_else(|| rt("slot missing 'id'"))?,
289 ))),
290 other => Err(rt(format!("unknown layout kind: {other}"))),
291 }
292}
294fn convert_children(t: &Table) -> LuaResult<Vec<LayoutTree>> {
295 let n = t.raw_len();
296 let mut out = Vec::with_capacity(n as usize);
297 for i in 1..=n {
298 out.push(convert(t.get::<Value>(i)?)?);
299 }
300 Ok(out)
301}
303fn parse_size_value(v: Value) -> LuaResult<Size> {
304 match v {
305 Value::Integer(n) => Ok(Size::Abs(n.max(0) as u16)),
306 Value::Number(n) => Ok(Size::Abs(n.max(0.0) as u16)),
307 Value::Table(t) => {
308 if let Some(p) = t.get::<Option<i64>>("pct")? {
309 Ok(Size::Pct(p.clamp(0, 100) as u16))
310 } else if let Some(a) = t.get::<Option<i64>>("abs")? {
311 Ok(Size::Abs(a.max(0) as u16))
312 } else {
313 Err(rt("size table needs `pct` or `abs`"))
314 }
315 }
316 other => Err(rt(format!("bad size value: {}", other.type_name()))),
317 }
318}
320fn opt_size(t: &Table, key: &str) -> LuaResult<Option<Size>> {
321 match t.get::<Value>(key)? {
322 Value::Nil => Ok(None),
323 v => Ok(Some(parse_size_value(v)?)),
324 }
325}
327fn req_size(t: &Table, key: &str) -> LuaResult<Size> {
328 opt_size(t, key)?.ok_or_else(|| rt(format!("missing required size `{key}`")))
329}
331fn opt_panel(t: &Table, key: &str) -> LuaResult<Option<Panel>> {
332 match t.get::<Value>(key)? {
333 Value::Nil => Ok(None),
334 Value::Table(p) => Ok(Some(Panel {
335 visible: p.get::<Option<bool>>("visible")?.unwrap_or(true),
336 size: req_size(&p, "size")?,
337 layout: Box::new(convert(p.get::<Value>("layout")?)?),
338 })),
339 other => Err(rt(format!("panel `{key}` must be a table, got {}", other.type_name()))),
340 }
341}
343fn parse_border(s: Option<&str>) -> LuaResult<BorderStyle> {
344 Ok(match s {
345 None | Some("none") => BorderStyle::None,
346 Some("single") => BorderStyle::Single,
347 Some("double") => BorderStyle::Double,
348 Some("rounded") => BorderStyle::Rounded,
349 Some("thick") => BorderStyle::Thick,
350 Some(other) => return Err(rt(format!("unknown border style: {other}"))),
351 })
352}
354fn parse_scroll(s: Option<&str>) -> LuaResult<ScrollDir> {
355 Ok(match s {
356 None | Some("vertical") => ScrollDir::Vertical,
357 Some("horizontal") => ScrollDir::Horizontal,
358 Some("both") => ScrollDir::Both,
359 Some(other) => return Err(rt(format!("unknown scroll dir: {other}"))),
360 })
361}
363fn parse_axis(s: Option<&str>) -> LuaResult<Axis> {
364 Ok(match s {
365 None | Some("horizontal") => Axis::Horizontal,
366 Some("vertical") => Axis::Vertical,
367 Some(other) => return Err(rt(format!("unknown split dir: {other}"))),
368 })
369}
371fn parse_anchor(s: Option<&str>) -> LuaResult<Anchor> {
372 let norm = s.unwrap_or("center").replace('_', "-");
373 Ok(match norm.as_str() {
374 "center" => Anchor::Center,
375 "top-left" => Anchor::TopLeft,
376 "top-center" | "top" => Anchor::TopCenter,
377 "top-right" => Anchor::TopRight,
378 "right-center" | "right" => Anchor::RightCenter,
379 "bottom-right" => Anchor::BottomRight,
380 "bottom-center" | "bottom" => Anchor::BottomCenter,
381 "bottom-left" => Anchor::BottomLeft,
382 "left-center" | "left" => Anchor::LeftCenter,
383 other => return Err(rt(format!("unknown anchor: {other}"))),
384 })
385}
387// ===========================================================================
388// (c) Pure resolver: (owned tree, area) -> Rect per slot. ZERO Lua.
389// ===========================================================================
390//
391// Column/Row/Split use ratatui `Layout`/`Constraint` (documented choice) so
392// tiling and remainder distribution match production widget code. The border
393// layout and overlay placement are hand-rolled (ratatui has no primitive for
394// them). Overlays float over their container's area and do NOT consume flow
395// space — see the spec note in the result block.
397fn resolve(tree: &LayoutTree, area: Rect) -> Vec<(SlotId, Rect)> {
398 let mut out = Vec::new();
399 resolve_node(tree, area, &mut out);
400 out
401}
403fn resolve_node(t: &LayoutTree, area: Rect, out: &mut Vec<(SlotId, Rect)>) {
404 match t {
405 LayoutTree::WidgetSlot(id) => out.push((id.clone(), area)),
406 LayoutTree::Spacer(_) => {} // occupies space via parent constraint; no slot
407 LayoutTree::Column(children) => resolve_flow(children, area, Direction::Vertical, out),
408 LayoutTree::Row(children) => resolve_flow(children, area, Direction::Horizontal, out),
409 LayoutTree::Expanded(child) => resolve_node(child, area, out),
410 LayoutTree::Scrollable { child, .. } => resolve_node(child, area, out),
411 LayoutTree::Box {
412 width,
413 height,
414 border,
415 child,
416 } => {
417 let w = width.map_or(area.width, |s| size_cells(s, area.width)).min(area.width);
418 let h = height.map_or(area.height, |s| size_cells(s, area.height)).min(area.height);
419 let box_rect = Rect { x: area.x, y: area.y, width: w, height: h };
420 let inner = if *border == BorderStyle::None {
421 box_rect
422 } else {
423 Rect {
424 x: box_rect.x.saturating_add(1),
425 y: box_rect.y.saturating_add(1),
426 width: box_rect.width.saturating_sub(2),
427 height: box_rect.height.saturating_sub(2),
428 }
429 };
430 resolve_node(child, inner, out);
431 }
432 LayoutTree::Overlay {
433 anchor,
434 width,
435 max_height,
436 offset_x,
437 offset_y,
438 child,
439 } => {
440 let rect = overlay_rect(area, *anchor, *width, *max_height, *offset_x, *offset_y);
441 resolve_node(child, rect, out);
442 }
443 LayoutTree::Tabs { active, children } => {
444 // Reserve the top row for the tab bar; render the active child below.
445 let content = Rect {
446 x: area.x,
447 y: area.y.saturating_add(1),
448 width: area.width,
449 height: area.height.saturating_sub(1),
450 };
451 if let Some(child) = children.get(*active) {
452 resolve_node(child, content, out);
453 }
454 }
455 LayoutTree::Split { axis, ratio, a, b } => {
456 let (ra, rb) = split_rect(area, *axis, *ratio);
457 resolve_node(a, ra, out);
458 resolve_node(b, rb, out);
459 }
460 LayoutTree::Border {
461 center,
462 north,
463 east,
464 south,
465 west,
466 } => resolve_border(center, north, east, south, west, area, out),
467 }
468}
470/// Column/Row via ratatui `Layout`. Flow children tile the axis; overlay
471/// children float over the whole container area without consuming space.
472fn resolve_flow(children: &[LayoutTree], area: Rect, dir: Direction, out: &mut Vec<(SlotId, Rect)>) {
473 let vertical = matches!(dir, Direction::Vertical);
474 let total = if vertical { area.height } else { area.width };
476 let flow: Vec<&LayoutTree> = children.iter().filter(|c| !is_overlay(c)).collect();
477 let floats: Vec<&LayoutTree> = children.iter().filter(|c| is_overlay(c)).collect();
479 if !flow.is_empty() {
480 let constraints: Vec<Constraint> = flow.iter().map(|c| axis_constraint(c, total, vertical)).collect();
481 let rects = Layout::default().direction(dir).constraints(constraints).split(area);
482 for (c, r) in flow.iter().zip(rects.iter()) {
483 resolve_node(c, *r, out);
484 }
485 }
486 for f in floats {
487 resolve_node(f, area, out);
488 }
489}
491/// Along-axis constraint for a flow child. Fixed for a box/spacer that names
492/// its along-axis size; `Fill(1)` (flex) for `expanded`, unsized spacers, and
493/// anything without an intrinsic along-axis size.
494fn axis_constraint(child: &LayoutTree, total: u16, vertical: bool) -> Constraint {
495 match child {
496 LayoutTree::Box { width, height, .. } => {
497 let s = if vertical { *height } else { *width };
498 match s {
499 Some(sz) => Constraint::Length(size_cells(sz, total)),
500 None => Constraint::Fill(1),
501 }
502 }
503 LayoutTree::Spacer(Some(sz)) => Constraint::Length(size_cells(*sz, total)),
504 LayoutTree::Spacer(None) => Constraint::Fill(1),
505 LayoutTree::Expanded(_) => Constraint::Fill(1),
506 _ => Constraint::Fill(1),
507 }
508}
510fn resolve_border(
511 center: &LayoutTree,
512 north: &Option<Panel>,
513 east: &Option<Panel>,
514 south: &Option<Panel>,
515 west: &Option<Panel>,
516 area: Rect,
517 out: &mut Vec<(SlotId, Rect)>,
518) {
519 let mut mid = area;
521 if let Some(p) = north.as_ref().filter(|p| p.visible) {
522 let h = size_cells(p.size, area.height).min(mid.height);
523 let r = Rect { x: mid.x, y: mid.y, width: mid.width, height: h };
524 resolve_node(&p.layout, r, out);
525 mid.y += h;
526 mid.height -= h;
527 }
528 if let Some(p) = south.as_ref().filter(|p| p.visible) {
529 let h = size_cells(p.size, area.height).min(mid.height);
530 let r = Rect { x: mid.x, y: mid.y + (mid.height - h), width: mid.width, height: h };
531 resolve_node(&p.layout, r, out);
532 mid.height -= h;
533 }
534 if let Some(p) = west.as_ref().filter(|p| p.visible) {
535 let w = size_cells(p.size, area.width).min(mid.width);
536 let r = Rect { x: mid.x, y: mid.y, width: w, height: mid.height };
537 resolve_node(&p.layout, r, out);
538 mid.x += w;
539 mid.width -= w;
540 }
541 if let Some(p) = east.as_ref().filter(|p| p.visible) {
542 let w = size_cells(p.size, area.width).min(mid.width);
543 let r = Rect { x: mid.x + (mid.width - w), y: mid.y, width: w, height: mid.height };
544 resolve_node(&p.layout, r, out);
545 mid.width -= w;
546 }
547 resolve_node(center, mid, out);
548}
550/// Hand-rolled split: honors `ratio` (± one cell of rounding) and tiles the
551/// axis exactly (no gap, no overlap).
552fn split_rect(area: Rect, axis: Axis, ratio: f32) -> (Rect, Rect) {
553 let r = ratio.clamp(0.0, 1.0);
554 match axis {
555 Axis::Horizontal => {
556 let wa = ((area.width as f32) * r).round().clamp(0.0, area.width as f32) as u16;
557 let a = Rect { x: area.x, y: area.y, width: wa, height: area.height };
558 let b = Rect { x: area.x + wa, y: area.y, width: area.width - wa, height: area.height };
559 (a, b)
560 }
561 Axis::Vertical => {
562 let ha = ((area.height as f32) * r).round().clamp(0.0, area.height as f32) as u16;
563 let a = Rect { x: area.x, y: area.y, width: area.width, height: ha };
564 let b = Rect { x: area.x, y: area.y + ha, width: area.width, height: area.height - ha };
565 (a, b)
566 }
567 }
568}
570fn overlay_rect(area: Rect, anchor: Anchor, width: Size, max_height: Size, ox: i16, oy: i16) -> Rect {
571 let w = size_cells(width, area.width).min(area.width);
572 let h = size_cells(max_height, area.height).min(area.height);
573 let (bx, by) = match anchor {
574 Anchor::Center => (mid(area.width, w), mid(area.height, h)),
575 Anchor::TopLeft => (0, 0),
576 Anchor::TopCenter => (mid(area.width, w), 0),
577 Anchor::TopRight => (area.width - w, 0),
578 Anchor::RightCenter => (area.width - w, mid(area.height, h)),
579 Anchor::BottomRight => (area.width - w, area.height - h),
580 Anchor::BottomCenter => (mid(area.width, w), area.height - h),
581 Anchor::BottomLeft => (0, area.height - h),
582 Anchor::LeftCenter => (0, mid(area.height, h)),
583 };
584 // Apply offset, then clamp so the overlay stays fully inside `area`.
585 let max_x = area.width.saturating_sub(w);
586 let max_y = area.height.saturating_sub(h);
587 let x = clamp_off(bx, ox, max_x);
588 let y = clamp_off(by, oy, max_y);
589 Rect { x: area.x + x, y: area.y + y, width: w, height: h }
590}
592fn mid(total: u16, part: u16) -> u16 {
593 total.saturating_sub(part) / 2
594}
596fn clamp_off(base: u16, off: i16, max: u16) -> u16 {
597 let v = base as i32 + off as i32;
598 v.clamp(0, max as i32) as u16
599}
601fn size_cells(size: Size, total: u16) -> u16 {
602 match size {
603 Size::Abs(n) => n.min(total),
604 Size::Pct(p) => ((total as u32 * p as u32) / 100) as u16,
605 }
606}
608// ===========================================================================
609// Realistic default layout script (§8.7 border layout).
610// ===========================================================================
612/// Root = a column whose sole flow child is an expanded border layout (fills
613/// the screen), plus one floating command-palette overlay centered over the
614/// whole terminal. The border's center is the status / messages / input / hint
615/// stack; the west panel is a scrollable file tree.
616const DEFAULT_LAYOUT: &str = r#"
617local L = smith.tui.layout
619local center = L.column{
620 L.box{ L.slot("status-bar"), height = 1 },
621 L.expanded{ L.slot("message-list") },
622 L.box{ L.slot("input"), height = 3, border = "rounded" },
623 L.box{ L.slot("hint-bar"), height = 1 },
624}
626local base = L.border{
627 center = center,
628 west = {
629 visible = true,
630 size = 24,
631 layout = L.scrollable{ L.slot("file-tree"), dir = "vertical" },
632 },
633}
635return L.column{
636 L.expanded{ base },
637 L.overlay{
638 L.box{ L.slot("command-palette"), border = "double" },
639 anchor = "center",
640 width = { pct = 60 },
641 max_height = { pct = 50 },
642 },
643}
644"#;
646/// A mutation: swap the center layout to a two-tab arrangement and hide the
647/// west panel. Used by the invalidation scenario as `set_center_layout`.
648const MUTATED_LAYOUT: &str = r#"
649local L = smith.tui.layout
650return L.border{
651 center = L.column{
652 L.box{ L.slot("status-bar"), height = 1 },
653 L.split{
654 L.expanded{ L.slot("message-list") },
655 L.scrollable{ L.slot("detail-pane") },
656 dir = "horizontal",
657 ratio = 0.7,
658 },
659 L.box{ L.slot("input"), height = 3 },
660 },
661}
662"#;
664// ===========================================================================
665// Scenario helpers.
666// ===========================================================================
668fn check(cond: bool, msg: &str) -> Result<(), String> {
669 if cond {
670 println!("PASS: {msg}");
671 Ok(())
672 } else {
673 Err(format!("FAIL: {msg}"))
674 }
675}
677fn us(d: Duration) -> f64 {
678 d.as_secs_f64() * 1_000_000.0
679}
681fn build_mode() -> &'static str {
682 if cfg!(debug_assertions) {
683 "debug"
684 } else {
685 "release"
686 }
687}
689fn contains(parent: Rect, child: Rect) -> bool {
690 child.width == 0
691 || child.height == 0
692 || (child.x >= parent.x
693 && child.y >= parent.y
694 && child.x + child.width <= parent.x + parent.width
695 && child.y + child.height <= parent.y + parent.height)
696}
698fn intersects(a: Rect, b: Rect) -> bool {
699 if a.width == 0 || a.height == 0 || b.width == 0 || b.height == 0 {
700 return false;
701 }
702 a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height
703}
705/// Render one resolved frame into a `TestBackend` to prove the Rects are usable
706/// widget targets. Returns the filled buffer.
707fn render_to_testbackend(slots: &[(SlotId, Rect)], w: u16, h: u16) -> Buffer {
708 let backend = TestBackend::new(w, h);
709 let mut term = Terminal::new(backend).expect("test backend");
710 term.draw(|f| {
711 for (slot, rect) in slots {
712 if rect.width == 0 || rect.height == 0 {
713 continue;
714 }
715 let block = Block::bordered().title(slot.0.clone());
716 f.render_widget(Paragraph::new(slot.0.clone()).block(block), *rect);
717 }
718 })
719 .expect("draw");
720 term.backend().buffer().clone()
721}
723fn nonblank_cells(buf: &Buffer, w: u16, h: u16) -> usize {
724 let mut n = 0;
725 for y in 0..h {
726 for x in 0..w {
727 if buf[(x, y)].symbol() != " " {
728 n += 1;
729 }
730 }
731 }
732 n
733}
735// ===========================================================================
736// Scenario: build-once
737// ===========================================================================
739fn build_once() -> Result<(), String> {
740 let counter = Arc::new(AtomicU64::new(0));
741 let lua = Lua::new();
742 install_layout_api(&lua, counter.clone()).map_err(|e| e.to_string())?;
744 check(counter.load(Ordering::Relaxed) == 0, "Lua-call counter starts at 0")?;
746 let tree = build_tree(&lua, DEFAULT_LAYOUT).map_err(|e| e.to_string())?;
747 let after_build = counter.load(Ordering::Relaxed);
748 check(after_build > 0, &format!("building the tree fired {after_build} Lua primitive calls"))?;
750 let area = Rect::new(0, 0, 120, 40);
751 let slots = resolve(&tree, area);
752 let ids: Vec<&str> = slots.iter().map(|(s, _)| s.0.as_str()).collect();
753 check(
754 ids.contains(&"status-bar")
755 && ids.contains(&"message-list")
756 && ids.contains(&"input")
757 && ids.contains(&"hint-bar")
758 && ids.contains(&"file-tree")
759 && ids.contains(&"command-palette"),
760 &format!("realistic tree resolves all six slots: {ids:?}"),
761 )?;
763 // Resolve many times; counter must not advance (zero Lua in the loop).
764 let frozen = counter.load(Ordering::Relaxed);
765 for _ in 0..5000 {
766 let _ = resolve(&tree, area);
767 }
768 check(
769 counter.load(Ordering::Relaxed) == frozen,
770 &format!("counter frozen at {frozen} across 5000 resolves (zero Lua calls)"),
771 )?;
773 // Independence: drop the entire Lua state, MOVE the tree to another thread,
774 // and resolve there. Compiles only because LayoutTree is Send + 'static;
775 // proves the tree owns no Lua handle.
776 drop(lua);
777 let expected = slots.clone();
778 let moved = tree; // move, no clone: the tree is fully owned
779 let handle = std::thread::spawn(move || resolve(&moved, Rect::new(0, 0, 120, 40)));
780 let after_drop = handle.join().map_err(|_| "resolve thread panicked".to_string())?;
781 check(
782 after_drop == expected,
783 "identical Rects after dropping Lua and resolving on another thread (Send, no Lua handle)",
784 )?;
785 check(
786 counter.load(Ordering::Relaxed) == frozen,
787 "counter still frozen after Lua state dropped",
788 )?;
790 println!("build-once: {} slots, {after_build} build-time Lua calls, 0 resolve-time Lua calls", slots.len());
791 Ok(())
792}
794// ===========================================================================
795// Scenario: resolve-frame
796// ===========================================================================
798fn resolve_frame() -> Result<(), String> {
799 let counter = Arc::new(AtomicU64::new(0));
800 let lua = Lua::new();
801 install_layout_api(&lua, counter.clone()).map_err(|e| e.to_string())?;
802 let tree = build_tree(&lua, DEFAULT_LAYOUT).map_err(|e| e.to_string())?;
804 const N: usize = 10_000;
805 const CEIL_US: f64 = 2000.0; // 2ms frame budget (§13), asserted even in debug
807 for &(w, h) in &[(80u16, 24u16), (200, 50), (400, 100)] {
808 let area = Rect::new(0, 0, w, h);
809 let before = counter.load(Ordering::Relaxed);
811 // Warmup.
812 for _ in 0..200 {
813 let _ = resolve(&tree, area);
814 }
816 let mut times = Vec::with_capacity(N);
817 for _ in 0..N {
818 let t0 = Instant::now();
819 let slots = resolve(&tree, area);
820 times.push(t0.elapsed());
821 std::hint::black_box(&slots);
822 }
823 times.sort();
824 let median = us(times[N / 2]);
825 let p99 = us(times[(N * 99) / 100]);
826 let delta = counter.load(Ordering::Relaxed) - before;
828 check(delta == 0, &format!("{w}x{h}: Lua-call delta over {N} resolves == 0"))?;
829 check(
830 p99 < CEIL_US,
831 &format!(
832 "{w}x{h}: median {median:.3}us / p99 {p99:.3}us per resolve (<< 2000us budget, {} build)",
833 build_mode()
834 ),
835 )?;
837 // Prove the Rects are usable: render one frame into a TestBackend.
838 let slots = resolve(&tree, area);
839 let buf = render_to_testbackend(&slots, w, h);
840 let painted = nonblank_cells(&buf, w, h);
841 check(
842 painted > 0,
843 &format!("{w}x{h}: rendered {} slots into TestBackend, {painted} non-blank cells", slots.len()),
844 )?;
845 }
847 Ok(())
848}
850// ===========================================================================
851// Scenario: properties
852// ===========================================================================
854fn properties() -> Result<(), String> {
855 // ---- Fixed tree: tiling / non-overlap / expanded remainder ----
856 let counter = Arc::new(AtomicU64::new(0));
857 let lua = Lua::new();
858 install_layout_api(&lua, counter.clone()).map_err(|e| e.to_string())?;
859 let tree = build_tree(&lua, DEFAULT_LAYOUT).map_err(|e| e.to_string())?;
861 let area = Rect::new(0, 0, 80, 24);
862 let slots = resolve(&tree, area);
863 let find = |id: &str| slots.iter().find(|(s, _)| s.0 == id).map(|(_, r)| *r).unwrap();
865 let status = find("status-bar");
866 let msgs = find("message-list");
867 let input = find("input"); // inner rect of a rounded box (height 3 -> inner 1)
868 let hint = find("hint-bar");
869 let tree_rect = find("file-tree");
871 // West panel is 24 wide; center starts at x=24.
872 check(tree_rect.x == 0 && tree_rect.width == 24, "west file-tree panel is 24 cells wide at x=0")?;
873 check(status.x == 24, "center column starts right of the 24-wide west panel")?;
875 // Center column stacks status(1) / expanded(msgs) / input-box(3) / hint(1),
876 // covering the full 24-row height with no overlap.
877 check(status.y == 0 && status.height == 1, "status bar: y=0 h=1")?;
878 check(hint.y == 23 && hint.height == 1, "hint bar pinned to last row (y=23 h=1)")?;
879 // message-list gets exactly the remainder: 24 - 1(status) - 3(input box) - 1(hint) = 19.
880 check(
881 msgs.height == 24 - 1 - 3 - 1,
882 &format!("expanded message-list takes exact remainder: {} == 19", msgs.height),
883 )?;
884 check(msgs.y == status.y + status.height, "message-list sits directly below status bar")?;
885 // input is the INNER rect of the rounded box on the row band [20,23): inner y=21 h=1.
886 check(input.y == 21 && input.height == 1, "input inner rect inside rounded box (y=21 h=1)")?;
887 check(!intersects(status, msgs) && !intersects(msgs, hint), "center flow siblings do not overlap")?;
889 // ---- Fixed tree: split honors ratio ----
890 let split_tree = LayoutTree::Split {
891 axis: Axis::Horizontal,
892 ratio: 0.3,
893 a: Box::new(LayoutTree::WidgetSlot(SlotId("a".into()))),
894 b: Box::new(LayoutTree::WidgetSlot(SlotId("b".into()))),
895 };
896 let sa = Rect::new(0, 0, 100, 10);
897 let sr = resolve(&split_tree, sa);
898 let ra = sr.iter().find(|(s, _)| s.0 == "a").unwrap().1;
899 let rb = sr.iter().find(|(s, _)| s.0 == "b").unwrap().1;
900 check(ra.width == 30, &format!("split ratio 0.3 of 100 -> left width {} == 30", ra.width))?;
901 check(ra.width + rb.width == 100 && rb.x == 30, "split tiles the axis exactly, no gap/overlap")?;
903 // ---- LCG-seeded random trees: containment, non-overlap, determinism ----
904 let sizes = [(80u16, 24u16), (137, 41), (200, 50)];
905 let mut checked = 0usize;
906 for seed in 0..64u64 {
907 let mut rng = Lcg(seed.wrapping_mul(0x9E3779B97F4A7C15).wrapping_add(1));
908 let mut next_id = 0u32;
909 let rtree = gen_tree(&mut rng, 4, &mut next_id);
910 for &(w, h) in &sizes {
911 let area = Rect::new(0, 0, w, h);
912 let r1 = resolve(&rtree, area);
913 let r2 = resolve(&rtree, area);
914 if r1 != r2 {
915 return Err(format!("FAIL: non-deterministic resolve for seed {seed} at {w}x{h}"));
916 }
917 for (_, rect) in &r1 {
918 if !contains(area, *rect) {
919 return Err(format!("FAIL: slot escapes root bounds (seed {seed}, {w}x{h}): {rect:?}"));
920 }
921 }
922 // No overlays are generated, so all leaf slots must be pairwise disjoint.
923 for i in 0..r1.len() {
924 for j in (i + 1)..r1.len() {
925 if intersects(r1[i].1, r1[j].1) {
926 return Err(format!(
927 "FAIL: overlapping slots (seed {seed}, {w}x{h}): {:?} vs {:?}",
928 r1[i], r1[j]
929 ));
930 }
931 }
932 }
933 checked += 1;
934 }
935 }
936 check(
937 checked == 64 * sizes.len(),
938 &format!("{checked} (tree,size) pairs: children within parent, siblings disjoint, resolve deterministic"),
939 )?;
941 println!("properties: §17 property-test target = {{within-parent, siblings-tile-no-overlap, expanded=remainder, split-ratio±rounding, deterministic}}");
942 Ok(())
943}
945/// Tiny LCG for reproducible random trees (no external rand dep).
946struct Lcg(u64);
947impl Lcg {
948 fn next_u64(&mut self) -> u64 {
949 self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
950 self.0
951 }
952 fn below(&mut self, n: usize) -> usize {
953 ((self.next_u64() >> 33) as usize) % n
954 }
955}
957/// Generate a partitioning tree (no overlays) so all leaf slots stay disjoint.
958fn gen_tree(rng: &mut Lcg, depth: u32, next_id: &mut u32) -> LayoutTree {
959 if depth == 0 || rng.below(3) == 0 {
960 let id = *next_id;
961 *next_id += 1;
962 return LayoutTree::WidgetSlot(SlotId(format!("s{id}")));
963 }
964 match rng.below(5) {
965 0 => {
966 let k = 2 + rng.below(3);
967 let children = (0..k)
968 .map(|_| {
969 // Mix fixed boxes and expanded children.
970 if rng.below(2) == 0 {
971 LayoutTree::Box {
972 width: None,
973 height: Some(Size::Abs(1 + rng.below(4) as u16)),
974 border: BorderStyle::None,
975 child: Box::new(gen_tree(rng, depth - 1, next_id)),
976 }
977 } else {
978 LayoutTree::Expanded(Box::new(gen_tree(rng, depth - 1, next_id)))
979 }
980 })
981 .collect();
982 LayoutTree::Column(children)
983 }
984 1 => {
985 let k = 2 + rng.below(3);
986 let children = (0..k).map(|_| LayoutTree::Expanded(Box::new(gen_tree(rng, depth - 1, next_id)))).collect();
987 LayoutTree::Row(children)
988 }
989 2 => LayoutTree::Split {
990 axis: if rng.below(2) == 0 { Axis::Horizontal } else { Axis::Vertical },
991 ratio: (1 + rng.below(9)) as f32 / 10.0,
992 a: Box::new(gen_tree(rng, depth - 1, next_id)),
993 b: Box::new(gen_tree(rng, depth - 1, next_id)),
994 },
995 3 => LayoutTree::Box {
996 width: None,
997 height: None,
998 border: if rng.below(2) == 0 { BorderStyle::Single } else { BorderStyle::None },
999 child: Box::new(gen_tree(rng, depth - 1, next_id)),
1000 },
1001 _ => LayoutTree::Scrollable {
1002 dir: ScrollDir::Vertical,
1003 child: Box::new(gen_tree(rng, depth - 1, next_id)),
1004 },
1005 }
1008// ===========================================================================
1009// Scenario: invalidation
1010// ===========================================================================
1012fn invalidation() -> Result<(), String> {
1013 let counter = Arc::new(AtomicU64::new(0));
1014 let lua = Lua::new();
1015 install_layout_api(&lua, counter.clone()).map_err(|e| e.to_string())?;
1017 // Build A.
1018 let tree_a = build_tree(&lua, DEFAULT_LAYOUT).map_err(|e| e.to_string())?;
1019 let after_a = counter.load(Ordering::Relaxed);
1020 check(after_a > 0, &format!("build A fired {after_a} Lua calls"))?;
1022 let area = Rect::new(0, 0, 100, 30);
1023 let slots_a = resolve(&tree_a, area);
1025 // Many resolves against A: no Lua re-entry.
1026 for _ in 0..3000 {
1027 let _ = resolve(&tree_a, area);
1028 }
1029 check(
1030 counter.load(Ordering::Relaxed) == after_a,
1031 &format!("counter frozen at {after_a} across 3000 resolves of tree A"),
1032 )?;
1034 // Explicit mutation: set_center_layout -> a NEW build fires Lua again.
1035 let tree_b = build_tree(&lua, MUTATED_LAYOUT).map_err(|e| e.to_string())?;
1036 let after_b = counter.load(Ordering::Relaxed);
1037 check(after_b > after_a, &format!("mutation (set_center_layout) rebuilds: {after_a} -> {after_b} Lua calls"))?;
1039 let slots_b = resolve(&tree_b, area);
1040 let ids_a: Vec<&str> = slots_a.iter().map(|(s, _)| s.0.as_str()).collect();
1041 let ids_b: Vec<&str> = slots_b.iter().map(|(s, _)| s.0.as_str()).collect();
1042 check(
1043 ids_b.contains(&"detail-pane") && !ids_a.contains(&"detail-pane"),
1044 "new tree exposes the mutated slot set (detail-pane appears only after mutation)",
1045 )?;
1047 // Resolves of B: still zero Lua re-entry.
1048 for _ in 0..3000 {
1049 let _ = resolve(&tree_b, area);
1050 }
1051 check(
1052 counter.load(Ordering::Relaxed) == after_b,
1053 &format!("counter frozen at {after_b} across 3000 resolves of tree B"),
1054 )?;
1056 println!("invalidation: tree rebuilds ONLY on explicit mutation; between mutations 0 Lua calls per frame");
1057 Ok(())
1060// ===========================================================================
1061// main
1062// ===========================================================================
1064fn run(scenario: &str) -> Result<(), String> {
1065 match scenario {
1066 "build-once" => build_once(),
1067 "resolve-frame" => resolve_frame(),
1068 "properties" => properties(),
1069 "invalidation" => invalidation(),
1070 "all" => {
1071 println!("== build-once ==");
1072 build_once()?;
1073 println!("== resolve-frame ==");
1074 resolve_frame()?;
1075 println!("== properties ==");
1076 properties()?;
1077 println!("== invalidation ==");
1078 invalidation()?;
1079 Ok(())
1080 }
1081 other => Err(format!(
1082 "unknown scenario '{other}'; use build-once|resolve-frame|properties|invalidation|all"
1083 )),
1084 }
1087fn main() {
1088 let scenario = std::env::args().nth(1).unwrap_or_else(|| "all".into());
1089 match run(&scenario) {
1090 Ok(()) => println!("PASS: p27 scenario '{scenario}' complete ({} build)", build_mode()),
1091 Err(e) => {
1092 eprintln!("{e}");
1093 std::process::exit(1);
1094 }
1095 }