RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
Add the splitting tools and document C splits
Claudeec57752bc2c1
diff --git a/AGENTS.md b/AGENTS.mdindex 126b471..0febcf7 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -16,10 +16,10 @@ the one for the directory you work in: `src/files`, `src/editor`,* Add tests only when really needed or asked; prefer extending existing ones.* Keep files small enough to read whole. When a file you touch grows past~800 lines or a function past ~150, split it by concern (below), moving- code verbatim. Tests go in a `*_tests.zig` beside the code once they- outgrow a screen. Exempt: generated or table files (`ui/fold_data.zig`,- `ipc/commands.zig`) and the C rendering core, whose static state splitting- would have to share across translation units.+ code verbatim (C and C++ too). Tests go in a `*_tests.zig` beside the code+ once they outgrow a screen. Exempt: generated or table files+ (`ui/fold_data.zig`, `ipc/commands.zig`). `tools/split/` moves Zig+ declarations from a spec and checks C splits; read its README first.* Before finishing: build Debug and `-Doptimize=ReleaseSafe`, run`zig build test` and the integration tests for what you touched. Somesuites fail on HEAD: compare with a `git worktree` of HEAD before calling a@@ -55,6 +55,16 @@ Tests that used to sit in the big file are in a `*tests.zig` file reached by a`test { _ = @import(...); }` block: a file nothing imports contributes no tests.State (`var`) stays in the file that uses it; an alias would copy it.+C splits keep the public header and the file's lifecycle in the original+(`projection.c`, `scene_output.c`, `scene_pass.c`), with the parts+(`projection_*.c`, …) sharing a private `*_internal.h`: the structs, and small+per-item helpers as `static inline` (no LTO, so a file boundary must not cost+them inlining); other shared functions lose `static` and take the file's+prefix. `build/support.zig` lists the parts, and fixtures that `#include` a .c+include every part (`projection_test.c`); their cases are `*_test_*.c` files+included into the same unit. The transfers helper is `files/torrent/helper*.cpp`+around `helper.hpp`, all in `namespace helper`.+## Rendering and damageRead [rendering details](docs/agent-notes/rendering.md) before changing@@ -72,8 +82,8 @@ panel painting. The key rules:buffer or rect node keeps its pixels in a hidden wlr_scene *carrier* that theoutput pass reads; every setter keeps the two in step, and every change asksfor a frame through the scene's hook. Client surfaces are own nodes too- (`node_surface.c`, ported from wlr_scene_surface/subsurface_tree/xdg_shell/- drag_icon): a surface is a buffer node whose `surface` binding follows its+ (`node_surface.c`, `node_subsurface_tree.c`, `node_xdg_shell.c`, ported from+ wlr_scene_surface/subsurface_tree/xdg_shell/drag_icon): a surface is a buffer node whose `surface` binding follows itswl_surface, an xdg surface a tree. The carrier's signals (`outputs_update`,`output_sample`, `frame_done`) are where the binding listens, so the projectionraises them on the carrier. Hits come from `Projection.nodeAt` (a leaf node; adiff --git a/docs/agent-notes/map.md b/docs/agent-notes/map.mdindex 802cc34..b9d2d0c 100644--- a/docs/agent-notes/map.md+++ b/docs/agent-notes/map.md@@ -62,9 +62,12 @@ Also in `src/`: `Shell.zig` (xdg-shell and decorations), `Popup.zig`,(Alt+Tab), `workspaces.zig`, `snap.zig`, `auto_tiling.zig`, `window_tabs.zig`.**Rendering** (read [rendering details](rendering.md) first): own scene nodes-`node.zig`/`node.c`/`node_surface.c`; `projection.zig`/`.c` (geometry and-damage); `scene_output.zig`/`.c`, `scene_pass.c`, `scene_damage.c`,-`scene_outputs.zig`/`.c` (the output pass); `glass.zig`/`.c`; `chrome.zig`+`node.zig`/`node.c`, client surfaces `node_surface.c` (+ `node_subsurface_tree.c`,+`node_xdg_shell.c`); `projection.zig`/`.c` (geometry and damage; parts+`projection_props`, `_resolve`, `_present`, `_pass`, `_pick.c`);+`scene_output.zig`/`.c` (+ `_collect`, `_effects`, `_draw.c`), `scene_pass.c`+(+ `_draw`, `_backdrop.c`), `scene_damage.c`, `scene_outputs.zig`/`.c` (the+output pass); `glass.zig`/`.c`; `chrome.zig`(+ `chrome_paint.zig`, `chrome_tabs.zig`) for window frames; `panel_buffer`,`panel_paint` and `panel_present.zig` for compositor-drawn panels;`camera.zig`, `geometry.zig`, `color.zig`.@@ -108,5 +111,6 @@ damage); `scene_output.zig`/`.c`, `scene_pass.c`, `scene_damage.c`,compositor's code), `ipc_tests.zig`, `files_tests.zig`, `editor_tests.zig`,`images_tests.zig`, `pdf_tests.zig` and the shared modules. Other`*_tests.zig` files sit beside their code and are reached through-`test { _ = @import(...); }` blocks; C fixtures are `src/*_test.c`;-integration suites are `tests/*.py`.+`test { _ = @import(...); }` blocks; C fixtures are `src/*_test.c` (cases in+`*_test_*.c`); integration suites are `tests/*.py`. Splitting tools are in+`tools/split/`.diff --git a/docs/agent-notes/rendering.md b/docs/agent-notes/rendering.mdindex 298e669..29bb58c 100644--- a/docs/agent-notes/rendering.md+++ b/docs/agent-notes/rendering.md@@ -20,7 +20,7 @@ chrome, capture, or retained panel painting. General rules remain inbuffer and carries footprint, opacity and input only, so the projectiondamages that footprint itself. CSD windows have no shape and keep the`border_rects` outline. A changed clip damages its rim itself- (`projection.c`); a point the shape cuts away is declined by the pick+ (`projection_resolve.c`); a point the shape cuts away is declined by the pick(`pick_world`), so the pick falls to what is below. Window capture draws the client alone and ishanded the shape explicitly. The ring is one `max(1, round(border * scale))`.Without the shaped programs (`chrome.shapes` false) windows are square, with@@ -35,7 +35,7 @@ chrome, capture, or retained panel painting. General rules remain instays): persist raster sizes.* **Glass is drawn by the output pass** (stage 5, `docs/plans/scene-graph-stage5.md`).`glass.c` only registers effects: a bufferless node just below its target, to- which resolve gives the target's box. When an effect re-blurs, `scene_output.c`+ which resolve gives the target's box. When an effect re-blurs, `scene_output_draw.c`redirects the pass (`rediwm_scene_pass_begin_backdrop`) and draws the itemsbelow it into an image a quarter of the logical size of its padded extent(target + 3 sigma), blurs that and composites it through the shape (shaped@@ -52,7 +52,7 @@ chrome, capture, or retained panel painting. General rules remain inis checked by `glass_reblur.py`.* **Owned GL beside wlroots:** wlroots draws with client-side vertex arrays, soany GL work of ours must put `GL_ARRAY_BUFFER` (and the rest of the state it- touched) back before a wlroots pass runs, as `scene_pass.c`'s `leave()` does; a quad+ touched) back before a wlroots pass runs, as `scene_pass_leave()` does; a quadVBO left bound makes wlroots draw half a rectangle. A border is drawn in thesame pass as its body, never over it (`docs/plans/scene-graph-stage1.md`).* **Commit only via `Output.commitFrameState`**, never@@ -74,7 +74,7 @@ chrome, capture, or retained panel painting. General rules remain inthe caller. The programs cost the driver about 430 KiB (a GL program costs130-150 KiB whatever its size), so `enable_shapes` builds them on request, neverwith the renderer; before it a shaped draw fails the pass. Blend NONE is only- valid inside `rediwm_clip_opaque`, minus the ring (`scene_output.c` draws a+ valid inside `rediwm_clip_opaque`, minus the ring (`scene_output_draw.c` draws aclipped item's ring-free core plain and the rest through the shape). Thedistance ramp is not area coverage (up to 18 of 208 levels at one pixel of acurved edge): that is expected.@@ -91,7 +91,8 @@ chrome, capture, or retained panel painting. General rules remain in(`Projection.damageBuffer` after `setBuffer`, or `presentOwned`). Cache keysinclude visual state, text, geometry and Cairo transform; round globallybefore subtracting projection group origins.-* **Projection is resolve, then present** (`projection.c`, `scene_graph.h`).+* **Projection is resolve, then present** (`projection_resolve.c`,+ `projection_present.c`, `scene_graph.h`; `projection.c` has the overview).`resolve` turns the source tree into typed items (kind, unroundedlayout-space edges, composed scale, content) listed in paint order per groupand shows nothing; `present` rounds once (`rediwm_edges_snap`, edges notdiff --git a/tools/split/README.md b/tools/split/README.mdnew file mode 100644index 0000000..f8c8824--- /dev/null+++ b/tools/split/README.md@@ -0,0 +1,64 @@+# Splitting large files++Scripts that split a big source file by concern while moving its code verbatim,+and check afterwards that nothing was lost. The conventions they follow are in+the root `AGENTS.md` ("Split files"). Run everything from the repository root,+on a clean tree, one file per commit, so `git diff` and `git checkout` undo a+bad run.++| Script | Does |+|---|---|+| `zoutline.py FILE [--in NAME] [--min N]` | lists a Zig file's declarations (or a container's members) with line ranges and sizes |+| `zsplit.py SPEC` | moves top-level declarations into group files; the parent keeps one alias per method |+| `znested.py SPEC` | the same for the methods of a nested `pub const Name = struct { ... }` |+| `zarms.py SPEC` | moves arms of a function's top-level `switch` into sub-handlers in group files |+| `zhoist.py PARENT NAME NEWFILE` | turns a nested struct into its own file-struct |+| `zverify.py REV PARENT GROUP...` | checks a Zig split against the parent at `REV` |+| `coutline.py FILE` | lists a C/C++ file's definitions with the file's own functions each calls |+| `csplit.py` | helpers for the short per-file script that splits a C or C++ file |+| `cverify.py ORIGINAL NEW...` | checks a C/C++ split line by line (`ORIGINAL` may be `REV:path`) |++## Zig++1. `python3 tools/split/zoutline.py src/Dock.zig --min 20` and read the file's+ own comments to find groups of declarations that belong together: what one+ concern needs, what only tests use. Aim for files of a few hundred lines.+2. Write a spec: the parent, then per group its path, a one-line `//!` doc and+ selectors (names, regexes or line ranges of the original). The script's+ docstring has the format; `examples/` holds specs used on this tree (their+ line numbers fit the files as they were before those splits).+3. Run the script. It prints how the parent imports each group. Group files+ import what they use; `var`s stay in the parent and are referenced as+ `parent.name`; private declarations used across files become `pub`.+4. `zig fmt` the new files, then `zverify.py HEAD PARENT GROUP...`: it should+ report nothing missing and add only imports and aliases.+5. Build Debug and `-Doptimize=ReleaseSafe` and run `zig build test`. If moved+ code holds translated strings, run `zig build i18n-extract` (the catalogs'+ source references move with it); if the parent is in `po/lint-files`, list+ the new files there too. Update the file lists in `AGENTS.md` and+ `docs/agent-notes/map.md` when a new host or prefix appears.++Things the scripts leave to you: a moved declaration that uses `@This()` (it+warns), comments between declarations that describe a whole section (they go+with the declaration below them), and anything outside `src/` that names a+moved function by file.++## C and C++++There is no spec: a C split is a short script that reads the original,+`expect`s the lines it cuts at, and writes the private header and the parts+from line ranges, renaming what the parts now share+(`examples/scene_output_split.py`, built on `csplit.py`).++1. `python3 tools/split/coutline.py src/scene_output.c` shows each function,+ whether it is static, and what it calls. Cut where few calls cross.+2. Structs and small helpers called per item go to `NAME_internal.h` (helpers+ as `static inline`); larger functions called across parts lose `static` and+ take the file's prefix; state stays `static` in the one part that uses it.+ C++ shares state as `inline` variables in a namespace instead.+3. Run the script, then `cverify.py REV:src/scene_output.c src/scene_output*.c+ src/scene_output_internal.h`: only the edits you meant should remain.+4. List the parts in the build (`build/support.zig`, `build/tests.zig`), make+ fixtures that `#include` the .c include every part, and build with the+ file's usual flags (most use `-Werror`), Debug and ReleaseSafe, and with+ `-Ddamage-audit=true` for the rendering core.diff --git a/tools/split/coutline.py b/tools/split/coutline.pynew file mode 100755index 0000000..b3e8fb2--- /dev/null+++ b/tools/split/coutline.py@@ -0,0 +1,76 @@+#!/usr/bin/env python3+"""Outline a C or C++ file to plan a split.++ coutline.py FILE++One line per top-level definition with its line range. Functions show `s`+(static) or `X` (exported), their length and the file's own functions they+call: cut where few calls cross, and the callees that do cross become the+shared helpers (see csplit.py). Approximate: it counts braces and does not+follow macros or C++ namespaces.+"""+import re, sys++def strip(src):+ # blank comments and strings, keep newlines+ out = []+ i, n = 0, len(src)+ while i < n:+ if src.startswith('/*', i):+ j = src.find('*/', i + 2); j = n if j < 0 else j + 2+ out.append(re.sub(r'[^\n]', ' ', src[i:j])); i = j+ elif src.startswith('//', i):+ j = src.find('\n', i); j = n if j < 0 else j+ out.append(' ' * (j - i)); i = j+ elif src[i] in '"\'':+ q = src[i]; j = i + 1+ while j < n and src[j] != q:+ j += 2 if src[j] == '\\' else 1+ out.append(q + ' ' * (j - i - 1) + q); i = j + 1+ else:+ out.append(src[i]); i += 1+ return ''.join(out)++def defs(path):+ src = open(path).read()+ code = strip(src)+ lines = code.split('\n')+ res = [] # (name, kind, start, end, static)+ depth = 0+ start = None+ for idx, line in enumerate(lines):+ if depth == 0 and start is None and line.strip() and not line.startswith((' ', '\t', '#', '}')):+ start = idx+ for ch in line:+ if ch == '{': depth += 1+ elif ch == '}': depth -= 1+ if depth == 0 and start is not None:+ t = line.rstrip()+ if t.endswith(';') or t.endswith('}'):+ head = ' '.join(lines[start:idx + 1])+ m = re.search(r'(\w+)\s*\([^;{]*\)\s*\{', head)+ if m and '{' in head and not re.match(r'\s*(static\s+)?(const\s+)?struct\s+\w+\s+\w+\s*=', head):+ res.append((m.group(1), 'fn', start, idx + 1, head.lstrip().startswith('static')))+ else:+ sm = re.match(r'\s*struct\s+(\w+)\s*\{', head)+ if sm:+ res.append((sm.group(1), 'struct', start, idx + 1, False))+ else:+ vm = re.search(r'(\w+)\s*(\[[^\]]*\])?\s*(=|;)', head)+ res.append((vm.group(1) if vm else '?', 'decl', start, idx + 1, 'static' in head))+ start = None+ return src, lines, res++if __name__ == '__main__':+ if len(sys.argv) != 2:+ raise SystemExit(__doc__)+ path = sys.argv[1]+ src, lines, res = defs(path)+ fns = {r[0] for r in res if r[1] == 'fn'}+ for name, kind, s, e, st in res:+ if kind != 'fn':+ print(f'{s+1:5d}-{e:5d} {kind:6s} {name}')+ continue+ body = '\n'.join(lines[s:e])+ calls = sorted({m for m in re.findall(r'\b(\w+)\s*\(', body) if m in fns and m != name})+ print(f'{s+1:5d}-{e:5d} {"s" if st else "X"} {e-s:4d}L {name}: {" ".join(calls)}')diff --git a/tools/split/csplit.py b/tools/split/csplit.pynew file mode 100644index 0000000..7fe56e1--- /dev/null+++ b/tools/split/csplit.py@@ -0,0 +1,63 @@+"""Helpers for the short script that splits one C or C++ file.++A C split is a script per file (examples/scene_output_split.py) rather than a+spec: it reads the original, asserts the lines it cuts at, and writes the+private header and the parts from line ranges of the original, copied verbatim+except where it drops `static` or renames what the parts now share. Plan it+with coutline.py, check it with cverify.py, then build with -Werror.++The convention (AGENTS.md, "Split files"): the public header stays as it was;+`NAME_internal.h` holds the structs and the small per-item helpers as+`static inline` (release builds have no LTO, so a file boundary must not cost+them inlining); other functions shared between the parts lose `static` and+gain the file's prefix; a test fixture that `#include`s the .c includes every+part; the build lists the parts.+"""+import re+import subprocess+++class Source:+ """The original file, read from a path or REV:path; line numbers are 1-based."""++ def __init__(self, path, renames=None):+ if ':' in path and not path.startswith('/'):+ text = subprocess.run(['git', 'show', path], capture_output=True, text=True, check=True).stdout+ else:+ text = open(path).read()+ self.lines = text.split('\n')+ self.renames = renames or {}++ def R(self, a, b):+ """Lines a..b, inclusive."""+ return self.lines[a - 1:b]++ def expect(self, n, prefix):+ """Stops the split unless line n starts with `prefix`: the file changed."""+ assert self.lines[n - 1].startswith(prefix), (n, self.lines[n - 1])++ def rename(self, block):+ """Applies the renames to identifiers in code, never in `//` comments;+ `.name` and `->name` (fields) are left alone."""+ out = []+ for line in block:+ code, sep, comment = line.partition('//')+ for old, new in self.renames.items():+ code = re.sub(r'(?<![\w.>])' + old + r'\b', new, code)+ out.append(code + sep + comment)+ return out+++def unstatic(block, inline=False):+ """Drops `static` from the block's first definition line (or makes it+ `static inline`, for a helper moving into the private header)."""+ block = list(block)+ i = next(k for k, l in enumerate(block) if l.startswith('static '))+ block[i] = re.sub(r'^static ', 'static inline ' if inline else '', block[i])+ return block+++def write(path, lines):+ """Writes the lines with one trailing newline and no runs of blank lines."""+ text = '\n'.join(lines).rstrip('\n') + '\n'+ open(path, 'w').write(re.sub(r'\n{3,}', '\n\n', text))diff --git a/tools/split/cverify.py b/tools/split/cverify.pynew file mode 100755index 0000000..faed4ac--- /dev/null+++ b/tools/split/cverify.py@@ -0,0 +1,37 @@+#!/usr/bin/env python3+"""Line accounting for a C or C++ split.++ cverify.py ORIGINAL NEW...++ORIGINAL is a path or REV:path (read with `git show`). Prints the stripped,+non-blank lines that the NEW files lack or add as a multiset. What remains+should be only the edits the split meant: dropped `static`, renamed shared+functions, the new headers, includes and file comments.+"""+import subprocess+import sys+from collections import Counter+++def read(path):+ if ':' in path and not path.startswith('/'):+ return subprocess.run(['git', 'show', path], capture_output=True, text=True, check=True).stdout+ return open(path).read()+++def main():+ if len(sys.argv) < 3:+ raise SystemExit(__doc__)+ before = Counter(l.strip() for l in read(sys.argv[1]).split('\n') if l.strip())+ after = Counter()+ for p in sys.argv[2:]:+ after.update(l.strip() for l in open(p).read().split('\n') if l.strip())+ for k, v in (before - after).items():+ print(f'MISSING x{v}: {k[:140]}')+ for k, v in (after - before).items():+ print(f'ADDED x{v}: {k[:140]}')+ print(f'missing={sum((before - after).values())} added={sum((after - before).values())}')+++if __name__ == '__main__':+ main()diff --git a/tools/split/examples/dbus_connection.spec b/tools/split/examples/dbus_connection.specnew file mode 100644index 0000000..d6fa5bd--- /dev/null+++ b/tools/split/examples/dbus_connection.spec@@ -0,0 +1,8 @@+# znested.py: the Connection struct into connection_*.zig, the first step of+# 1250383 (line numbers of its parent).+parent src/dbus/connection.zig+container Connection+group src/dbus/connection_calls.zig Handlers and calls: method and signal registration, match rules, calls, replies (also deferred) and signals.+ 142-342+group src/dbus/connection_io.zig Wire I/O: serials, sending, dispatching incoming messages, reading (with fds), writing, and the loop's fd and timer callbacks.+ 343-580diff --git a/tools/split/examples/dock.spec b/tools/split/examples/dock.specnew file mode 100644index 0000000..6154715--- /dev/null+++ b/tools/split/examples/dock.spec@@ -0,0 +1,12 @@+# zsplit.py: Dock.zig into dock/, as in f0d590f (line numbers of its parent).+parent src/Dock.zig+group src/dock/reveal.zig Space reservation and auto-hide: the reserved strip, footprint, reveal/hide timing and pointer proximity.+ 273-424+group src/dock/items.zig Items: shortcuts, resolved pins, window matching and the window picker, item layout and hover zoom geometry.+ 426-790+group src/dock/paint.zig Painting: look keys, the retained raster with per-item cells, items, marks and the background.+ 792-1116+group src/dock/pointer.zig Pointer input: tooltip, motion, presses, clicks, context menu, hiding shortcuts and launching.+ 1118-1301 1469-1543+group src/dock/pins.zig Pinned apps: drop slots, reordering, pinning and unpinning, and saving the pin list.+ 1303-1433diff --git a/tools/split/examples/ipc_handlers.spec b/tools/split/examples/ipc_handlers.specnew file mode 100644index 0000000..63748cb--- /dev/null+++ b/tools/split/examples/ipc_handlers.spec@@ -0,0 +1,10 @@+# zarms.py: handleAction's switch into handlers_*.zig sub-handlers, the action+# half of 0507c7c (line numbers of its parent).+parent src/ipc/handlers.zig+function handleAction+group src/ipc/handlers_input.zig handleInputAction Synthetic input actions: pointer, keys, text, gestures, drags and widget clicks.+ move_cursor move_cursor_relative pointer_button click scroll pinch swipe key key_press type_text drag click_widget hover_widget+group src/ipc/handlers_windows.zig handleWindowAction Window and workspace actions: focus, close, move, spawn, tiling, sizing and zoom.+ focus_window close_window move_window_to spawn set_desktop_mode set_window_gap set_floating_apps set_workspace_layout switch_workspace move_to_workspace tiling_action maximize_window minimize_window restore_window fullscreen_window stop_xwayland set_window_size set_window_zoom+group src/ipc/handlers_frames.zig handleFrameAction Screenshots, frame waits, buffer dumps, pixel samples and performance stats.+ screenshot stop_all_capture wait_for wait_for_frame dump_buffer sample_pixels get_performance_stats reset_performance_statsdiff --git a/tools/split/examples/scene_output_split.py b/tools/split/examples/scene_output_split.pynew file mode 100755index 0000000..8c5fe85--- /dev/null+++ b/tools/split/examples/scene_output_split.py@@ -0,0 +1,110 @@+#!/usr/bin/env python3+"""How src/scene_output.c was split: an example for csplit.py.++ scene_output_split.py [ORIGINAL]++ORIGINAL defaults to src/scene_output.c; it only matches the file as it was+before the split (pass REV:src/scene_output.c with the split commit's parent+to rerun it), and every `expect` stops it on anything else. Run from the+repository root.+"""+import os+import sys++sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))+from csplit import Source, unstatic, write # noqa: E402++src = Source(sys.argv[1] if len(sys.argv) > 1 else 'src/scene_output.c', renames={+ 'collect': 'scene_output_collect', 'clear_entries': 'scene_output_clear_entries',+ 'decide_effects': 'scene_output_decide_effects', 'render_entry': 'scene_output_render_entry'})+R, expect, rename = src.R, src.expect, src.rename++expect(3, '#define WLR_USE_UNSTABLE')+expect(31, '#include <wlr/util/transform.h>')+expect(33, '// Stage 5c')+expect(78, 'static bool render_entry(')+expect(80, 'struct rediwm_output_renderer {')+expect(87, 'struct rediwm_output_renderer *rediwm_output_renderer_create(')+expect(160, '// Stage 3 parity')+expect(163, 'static struct wlr_box device_box(')+expect(176, 'static void device_region(')+expect(179, '// Which device corner')+expect(218, '// What of a clipped item')+expect(236, 'struct collector {')+expect(252, 'static bool same_clip(')+expect(258, 'static bool collect(')+expect(366, 'static void clear_entries(')+expect(374, '// The node\'s own texture cache.')+expect(389, 'static void sample(')+expect(399, 'static bool try_scanout(')+expect(443, '// Most entries lie outside')+expect(453, '// ---- Effects')+expect(454, 'uint64_t rediwm_scene_output_reblurs;')+expect(491, '// Decides, bottom to top')+expect(496, 'static bool decide_effects(')+expect(590, 'static void render_effect(')+expect(676, '// `backdrop`: drawing into')+expect(679, 'static bool render_entry(')+expect(808, '#ifdef REDIWM_DAMAGE_AUDIT')+expect(900, '#endif')+expect(901, 'bool rediwm_scene_output_build_state(')+expect(1034, '}')++hdr = ['// Private to scene_output*.c: what the output pass keeps per output and builds',+ '// per frame, and the device-space helpers every part uses (`static inline`, so a',+ '// file boundary costs them no inlining). Everyone else uses scene_output.h.',+ '#ifndef REDIWM_SCENE_OUTPUT_INTERNAL_H',+ '#define REDIWM_SCENE_OUTPUT_INTERNAL_H', '']+hdr += R(3, 31) + ['']+hdr += R(33, 77) # effect_cache, output_state, entry+hdr += R(80, 86) # struct rediwm_output_renderer+hdr += R(160, 162) + unstatic(R(163, 175), inline=True) # device_box+hdr += unstatic(R(176, 178), inline=True) # device_region+hdr += R(236, 251) # struct collector+hdr += ['',+ '// Shared between the parts (scene_output_*.c).',+ 'extern uint64_t rediwm_scene_output_reblurs;',+ 'bool scene_output_collect(const struct rediwm_item *item, struct rediwm_node *transport, void *data);',+ 'void scene_output_clear_entries(struct rediwm_output_renderer *r);',+ 'bool scene_output_decide_effects(struct rediwm_output_renderer *r, struct output_state *os,',+ ' struct rediwm_scene_output *out, const struct output_view *v, pixman_region32_t *changed);',+ 'bool scene_output_render_entry(struct rediwm_output_renderer *r, struct entry *e, struct rediwm_scene_output *out,',+ ' struct wlr_render_pass *pass, const struct output_view *v, pixman_region32_t *damage, bool backdrop);',+ '',+ '#endif']+write('src/scene_output_internal.h', hdr)++core = R(1, 2) + ['#include "scene_output_internal.h"', '',+ '// The parts: scene_output_collect.c turns the graph into this frame\'s entries,',+ '// scene_output_effects.c decides which glass blurs are re-taken and',+ '// scene_output_draw.c draws entries and effects. This file keeps the',+ '// per-output state, direct scanout, the damage audit and the frame build.', '']+core += R(87, 159)+core += R(389, 442) # sample, try_scanout+core += rename(R(808, 1034)) # audit, build_state+write('src/scene_output.c', core)++col = ['// What a frame draws: the graph\'s items, top to bottom, culled against what is',+ '// above them, with their visible and opaque regions. Part of scene_output.c.',+ '#include "scene_output_internal.h"', '']+col += R(218, 235) # clip_cover+col += R(252, 257) # same_clip+col += rename(unstatic(R(258, 365))) # collect+col += rename(unstatic(R(366, 373))) # clear_entries+write('src/scene_output_collect.c', col)++eff = R(453, 453) + ['// Part of scene_output.c.', '#include "scene_output_internal.h"', '']+eff += R(454, 490)+eff += R(491, 495) + rename(unstatic(R(496, 589)))+write('src/scene_output_effects.c', eff)++draw = ['// Drawing entries through the owned pass (scene_pass.c): clipped shapes, rects,',+ '// textures, shadows and glass. Part of scene_output.c.',+ '#include "scene_output_internal.h"', '']+draw += R(179, 217) # device_radii, shape_for+draw += R(374, 388) # buffer_texture+draw += R(443, 452) # misses_damage+draw += rename(R(590, 675))+draw += R(676, 678) + rename(unstatic(R(679, 807)))+write('src/scene_output_draw.c', draw)+print('ok')diff --git a/tools/split/zarms.py b/tools/split/zarms.pynew file mode 100755index 0000000..70c4d82--- /dev/null+++ b/tools/split/zarms.py@@ -0,0 +1,223 @@+#!/usr/bin/env python3+"""Move arms of a function's top-level `switch` into sub-handlers in sibling files.++Spec (see examples/ipc_handlers.spec):+ parent src/ipc/handlers.zig+ function handleAction+ group src/ipc/handlers_input.zig handleInput Synthetic input actions.+ move_cursor click scroll ...++The function's body must be a single exhaustive `switch` whose every arm+returns. Each group becomes `pub fn NAME(<same params>) <same return type>`+with the moved arms verbatim plus `else => unreachable`; the parent keeps one+arm `.a, .b => return group.NAME(params...)` where the first moved arm was.+"""+import os+import re+import sys++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from zsplit import parse, strip_code, rich_tokens, is_copyable, rewrite_import_paths, nested_decls # noqa: E402+++def main():+ if len(sys.argv) != 2:+ raise SystemExit(__doc__)+ spec = open(sys.argv[1]).read().split('\n')+ parent = function = None+ groups = []+ for raw in spec:+ line = raw.split('#', 1)[0].rstrip()+ if not line.strip():+ continue+ if line.startswith('parent '):+ parent = line.split(None, 1)[1].strip()+ elif line.startswith('function '):+ function = line.split(None, 1)[1].strip()+ elif line.startswith('group '):+ parts = line.split(None, 3)+ groups.append([parts[1], parts[2], parts[3] if len(parts) > 3 else '', []])+ else:+ groups[-1][3].extend(t.lstrip('.') for t in line.split())+ lines = open(parent).read().split('\n')+ decls = parse(lines)+ by_name = {d.name: d for d in decls if d.kind in ('fn', 'const', 'var')}+ fn = by_name[function]+ parent_dir = os.path.dirname(parent)+ parent_stem = os.path.splitext(os.path.basename(parent))[0]++ # Signature: from the decl line to the line ending with `{`.+ sig_end = fn.decl_line+ while not strip_code(lines[sig_end]).rstrip().endswith('{'):+ sig_end += 1+ sig = '\n'.join(lines[fn.decl_line:sig_end + 1])+ m = re.search(r'fn\s+\w+\s*\((.*)\)\s*([^{]*)\{\s*$', sig, re.S)+ params_src, ret = m.group(1), m.group(2).strip()+ params = []+ for p in re.split(r',\s*(?![^()]*\))', params_src):+ p = p.strip()+ if not p:+ continue+ pm = re.match(r'(?:comptime\s+|noalias\s+)?(\w+)\s*:', p)+ params.append((pm.group(1), p))++ # Locate the switch.+ candidates = [k for k in range(sig_end + 1, fn.end) if re.match(r'^ switch \((\w+)\) \{\s*$', lines[k])]+ if not candidates:+ raise SystemExit(f'{function}: no top-level switch')+ sw = candidates[-1]+ for k in range(sig_end + 1, sw):+ if re.match(r'^ (const|var) ', lines[k]):+ raise SystemExit(f'{function}: prelude declares {lines[k].strip()}; arms may depend on it')+ switch_var = re.match(r'^ switch \((\w+)\)', lines[sw]).group(1)+ # Arms: lines indented 8 at switch depth 1.+ arms = [] # [start, end, tags]+ depth = 0+ i = sw+ close = None+ pending_comment = None+ while i < fn.end:+ code = strip_code(lines[i])+ if i > sw and depth == 1:+ st = lines[i]+ if st.startswith(' //') and not st.startswith(' '):+ if pending_comment is None:+ pending_comment = i+ elif re.match(r'^ \.', st) or re.match(r'^ else\b', st):+ tags = []+ head = code.split('=>', 1)[0]+ tags = re.findall(r'\.(\w+)', head)+ if arms and arms[-1][1] is None:+ arms[-1][1] = pending_comment if pending_comment is not None else i+ arms.append([pending_comment if pending_comment is not None else i, None, tags])+ pending_comment = None+ elif st.strip() == '}' and st.startswith(' }'):+ pass+ elif st.strip():+ pending_comment = None+ for c in code:+ if c in '{([':+ depth += 1+ elif c in '})]':+ depth -= 1+ if i > sw and depth == 0:+ close = i+ break+ i += 1+ if arms and arms[-1][1] is None:+ arms[-1][1] = close+ tag_arm = {}+ for a in arms:+ for t in a[2]:+ tag_arm[t] = a++ owner = {}+ for gi, g in enumerate(groups):+ for t in g[3]:+ if t not in tag_arm:+ raise SystemExit(f'no arm for .{t}')+ owner[id(tag_arm[t])] = gi++ outputs = []+ for gi, (gpath, gname, gdoc, _) in enumerate(groups):+ gdir = os.path.dirname(gpath)+ mine = [a for a in arms if owner.get(id(a)) == gi]+ body = '\n'.join('\n'.join(lines[a[0]:a[1]]) for a in mine)+ bare, calls, qualified = rich_tokens(body)+ sig_bare = rich_tokens(sig)[0]+ used = (bare | sig_bare) & set(by_name)+ copies, aliases = [], []+ pending = sorted(used)+ seen = set()+ while pending:+ name = pending.pop()+ if name in seen:+ continue+ seen.add(name)+ d = by_name[name]+ text = '\n'.join(lines[d.decl_line:d.end])+ if is_copyable(d, text):+ copies.append(d)+ for ident in rich_tokens(text.split('=', 1)[1])[0]:+ if ident in by_name and ident not in seen:+ pending.append(ident)+ continue+ aliases.append(name)+ out = []+ for dl in gdoc.split('\\n') if gdoc else []:+ out.append('//! ' + dl)+ if out:+ out.append('')+ for d in sorted(copies, key=lambda d: d.decl_line):+ text = re.sub(r'^pub\s+', '', '\n'.join(lines[d.decl_line:d.end]))+ out.append(rewrite_import_paths(text, parent_dir, gdir))+ if aliases:+ out.append(f'const {parent_stem} = @import("{os.path.relpath(parent, gdir)}");')+ for name in sorted(aliases, key=lambda n: by_name[n].decl_line):+ out.append(f'const {name} = {parent_stem}.{name};')+ out.append('')+ out.append(f'pub fn {gname}(')+ for pname, p in params:+ out.append(f' {p},')+ out.append(f') {ret} {{')+ for pname, _ in params:+ if pname not in bare and pname != switch_var:+ out.append(f' _ = {pname};')+ out.append(f' switch ({switch_var}) {{')+ out.append(rewrite_import_paths(body, parent_dir, gdir))+ out.append(' else => unreachable,')+ out.append(' }')+ out.append('}')+ if os.path.exists(gpath):+ raise SystemExit(f'{gpath} exists')+ open(gpath, 'w').write('\n'.join(out) + '\n')+ outputs.append((gi, mine, aliases, calls, qualified))++ need_pub = set()+ for gi, mine, aliases, _, _ in outputs:+ need_pub.update(aliases)+ new = list(lines)+ for d in decls:+ if d.kind not in ('const', 'var'):+ continue+ for idx, name, pub in nested_decls(lines, d):+ if pub:+ continue+ if any(name in calls or (d.name, name) in qualified for _, _, _, calls, qualified in outputs):+ new[idx] = re.sub(r'^(\s*)', r'\1pub ', new[idx], count=1)+ for name in need_pub:+ d = by_name[name]+ if not d.pub:+ new[d.decl_line] = re.sub(r'^(\s*)', r'\1pub ', new[d.decl_line], count=1)+ remove = [False] * len(new)+ insert = {}+ args = ', '.join(p for p, _ in params)+ for gi, mine, _, _, _ in outputs:+ gpath, gname = groups[gi][0], groups[gi][1]+ ident = os.path.splitext(os.path.basename(gpath))[0]+ tags = [t for a in mine for t in a[2]]+ insert[mine[0][0]] = f' {", ".join("." + t for t in tags)} => return {ident}.{gname}({args}),'+ for a in mine:+ for k in range(a[0], a[1]):+ remove[k] = True+ result = []+ for k, line in enumerate(new):+ if k in insert:+ result.append(insert[k])+ if not remove[k]:+ result.append(line)+ # Imports for the groups: after the last top-level @import line.+ last_import = max(i for i, l in enumerate(result) if re.match(r'^(pub )?const \w+ = @import\(', l) and not l.startswith(' '))+ imports = []+ for gi, _, _, _, _ in outputs:+ gpath = groups[gi][0]+ ident = os.path.splitext(os.path.basename(gpath))[0]+ imports.append(f'const {ident} = @import("{os.path.relpath(gpath, parent_dir)}");')+ result[last_import + 1:last_import + 1] = imports+ open(parent, 'w').write('\n'.join(result).rstrip('\n') + '\n')+ for gi, mine, aliases, _, _ in outputs:+ print(f'{groups[gi][0]}: {len(mine)} arms')+++if __name__ == '__main__':+ main()diff --git a/tools/split/zhoist.py b/tools/split/zhoist.pynew file mode 100755index 0000000..58b9be6--- /dev/null+++ b/tools/split/zhoist.py@@ -0,0 +1,155 @@+#!/usr/bin/env python3+"""Hoist a nested `pub const Name = struct { ... };` into its own file-struct.++ zhoist.py PARENT NAME NEWFILE++The parent keeps `pub const Name = @import("NEWFILE");` (with the doc+comment). The new file gets the imports the body uses, aliases for the+parent's other declarations it uses, `const Name = @This();` and the+dedented body.+"""+import os+import re+import sys++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from zsplit import parse, rich_tokens, is_copyable, rewrite_import_paths, strip_code, nested_decls # noqa: E402+++def main():+ if len(sys.argv) != 4:+ raise SystemExit(__doc__)+ parent, name, newfile = sys.argv[1:4]+ lines = open(parent).read().split('\n')+ decls = parse(lines)+ by_name = {d.name: d for d in decls if d.kind in ('fn', 'const', 'var')}+ d = by_name[name]+ head = lines[d.decl_line]+ if not re.match(r'^(pub\s+)?const\s+' + name + r'\s*=\s*(extern\s+|packed\s+)?struct\s*\{\s*$', head):+ raise SystemExit(f'unexpected container header: {head}')+ if lines[d.end - 1].strip() != '};':+ raise SystemExit('container does not end with `};`')+ body = lines[d.decl_line + 1:d.end - 1]+ ded = []+ for l in body:+ if l.startswith(' '):+ ded.append(l[4:])+ elif l.strip() == '':+ ded.append('')+ else:+ ded.append(l)+ body_text = '\n'.join(ded)+ parent_dir = os.path.dirname(parent)+ new_dir = os.path.dirname(newfile)+ parent_stem = os.path.splitext(os.path.basename(parent))[0]++ bare, calls, qualified = rich_tokens(body_text)+ inner = {x.name: x for x in parse(ded) if x.kind in ('fn', 'const', 'var')}+ copies, aliases = [], []+ pending = sorted(n for n in bare if n in by_name and n != name and n not in inner)+ seen = set()+ while pending:+ n = pending.pop()+ if n in seen:+ continue+ seen.add(n)+ x = by_name[n]+ text = '\n'.join(lines[x.decl_line:x.end])+ if is_copyable(x, text):+ copies.append(x)+ for ident in rich_tokens(text.split('=', 1)[1])[0]:+ if ident in by_name and ident not in seen and ident != name:+ pending.append(ident)+ continue+ if x.kind == 'var':+ raise SystemExit(f'body uses parent var {n}; handle by hand')+ aliases.append(n)++ # Parent code that reaches private members of the container.+ rest = '\n'.join(lines[:d.start] + lines[d.end:])+ _, rcalls, rqual = rich_tokens(rest)+ widen = set()+ for n, x in inner.items():+ if not x.pub and (n in rcalls or (name, n) in rqual):+ widen.add(x.decl_line)+ for k in widen:+ ded[k] = re.sub(r'^(\s*)', r'\1pub ', ded[k], count=1)++ # Fields share the file-struct's namespace with declarations.+ fields = set()+ for x in parse(ded):+ if x.kind == 'field':+ fm = re.match(r'^\s*(\w+)\s*:', ded[x.decl_line])+ if fm:+ fields.add(fm.group(1))+ renames = {}+ for x in copies:+ if x.name in fields:+ renames[x.name] = x.name + '_mod'+ for n in aliases:+ if n in fields:+ raise SystemExit(f'alias {n} collides with a field; handle by hand')+ if renames:+ def ren(line):+ code = strip_code(line)+ out_l, last = [], 0+ for m in re.finditer(r'[A-Za-z_][A-Za-z0-9_]*', code):+ st = m.start()+ prev = code[st - 1] if st > 0 else ''+ if m.group(0) in renames and prev not in ('.', '@') and not (prev.isalnum() or prev == '_'):+ # skip field declarations `name: T`+ if code[m.end():].lstrip().startswith(':') and code[:st].strip() == '':+ continue+ out_l.append(line[last:st])+ out_l.append(renames[m.group(0)])+ last = m.end()+ out_l.append(line[last:])+ return ''.join(out_l)+ ded = [ren(l) for l in ded]+ print(f'renamed imports clashing with fields: {renames}')++ doc = [l for l in lines[d.start:d.decl_line]]+ out = []+ for l in doc:+ s = l.strip()+ if s.startswith('///'):+ out.append('//!' + s[3:])+ if out:+ out.append('')+ for x in sorted(copies, key=lambda x: x.decl_line):+ text = re.sub(r'^pub\s+', '', '\n'.join(lines[x.decl_line:x.end]))+ if x.name in renames:+ text = re.sub(r'^const\s+' + x.name + r'\b', 'const ' + renames[x.name], text)+ out.append(rewrite_import_paths(text, parent_dir, new_dir))+ if aliases:+ out.append(f'const {parent_stem} = @import("{os.path.relpath(parent, new_dir)}");')+ for n in sorted(aliases, key=lambda n: by_name[n].decl_line):+ out.append(f'const {n} = {parent_stem}.{n};')+ out.append(f'const {name} = @This();')+ out.append('')+ out.append(rewrite_import_paths('\n'.join(ded), parent_dir, new_dir).strip('\n'))+ if os.path.exists(newfile):+ raise SystemExit(f'{newfile} exists')+ open(newfile, 'w').write('\n'.join(out) + '\n')++ new = list(lines)+ # Members of the parent's other containers that the body reaches.+ for x in decls:+ if x is d or x.kind not in ('const', 'var'):+ continue+ for idx, mname, mpub in nested_decls(lines, x):+ if not mpub and (mname in calls or (x.name, mname) in qualified):+ new[idx] = re.sub(r'^(\s*)', r'\1pub ', new[idx], count=1)+ for n in aliases:+ x = by_name[n]+ if not x.pub:+ new[x.decl_line] = re.sub(r'^(\s*)', r'\1pub ', new[x.decl_line], count=1)+ pub = 'pub ' if head.startswith('pub') else ''+ repl = new[d.start:d.decl_line] + [f'{pub}const {name} = @import("{os.path.relpath(newfile, parent_dir)}");']+ new[d.start:d.end] = repl+ open(parent, 'w').write('\n'.join(new).rstrip('\n') + '\n')+ print(f'{newfile}: {len(body)} lines; {len(aliases)} parent aliases, {len(widen)} members widened')+++if __name__ == '__main__':+ main()diff --git a/tools/split/znested.py b/tools/split/znested.pynew file mode 100755index 0000000..9edf0c5--- /dev/null+++ b/tools/split/znested.py@@ -0,0 +1,296 @@+#!/usr/bin/env python3+"""Move methods out of a nested `pub const Name = struct { ... };` into sibling files.++Spec (see examples/dbus_connection.spec):+ parent src/images/app.zig+ container App+ group src/images/app_paint.zig Painting.+ paint paintToolbar 600-800 # inner names or original line ranges++Group files import the container as `const App = @import("app.zig").App;`+(like desktop/app.zig). The container keeps one alias per moved declaration+that anything still uses; group imports go at the parent's top level.+"""+import os+import re+import sys++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from zsplit import parse, rich_tokens, is_copyable, rewrite_import_paths, nested_decls, strip_code # noqa: E402++PUB = lambda line: re.sub(r'^(\s*)', r'\1pub ', line, count=1) # noqa: E731+++def main():+ if len(sys.argv) != 2:+ raise SystemExit(__doc__)+ spec = open(sys.argv[1]).read().split('\n')+ parent = cname = None+ groups = []+ for raw in spec:+ line = raw.split('#', 1)[0].rstrip()+ if not line.strip():+ continue+ if line.startswith('parent '):+ parent = line.split(None, 1)[1].strip()+ elif line.startswith('container '):+ cname = line.split(None, 1)[1].strip()+ elif line.startswith('group '):+ parts = line.split(None, 2)+ groups.append([parts[1], parts[2] if len(parts) > 2 else '', []])+ else:+ groups[-1][2].extend(line.split())+ lines = open(parent).read().split('\n')+ outer = parse(lines)+ outer_by = {d.name: d for d in outer if d.kind in ('fn', 'const', 'var')}+ C = outer_by[cname]+ if not re.match(r'^(pub\s+)?const\s+' + cname + r'\s*=\s*struct\s*\{\s*$', lines[C.decl_line]):+ raise SystemExit('unexpected container header')+ body_start = C.decl_line + 1+ body_end = C.end - 1 # index of `};`+ ded = [l[4:] if l.startswith(' ') else l for l in lines[body_start:body_end]]+ inner = parse(ded)+ off = body_start+ inner_by = {d.name: d for d in inner if d.kind in ('fn', 'const', 'var')}+ parent_dir = os.path.dirname(parent)+ parent_stem = os.path.splitext(os.path.basename(parent))[0]++ owner = {}+ for gi, (gpath, gdoc, sels) in enumerate(groups):+ for sel in sels:+ rm = re.match(r'^(\d+)-(\d+)$', sel)+ if rm:+ lo, hi = int(rm.group(1)) - 1, int(rm.group(2)) - 1+ matched = [d for d in inner if lo <= d.decl_line + off <= hi and d.kind != 'field']+ elif sel in inner_by:+ matched = [inner_by[sel]]+ else:+ rx = re.compile('^(?:' + sel + ')$')+ matched = [d for d in inner if d.kind in ('fn', 'const', 'var') and rx.match(d.name)]+ if not matched:+ raise SystemExit(f'selector {sel!r} matched nothing')+ for d in matched:+ if d.kind in ('field', 'test', 'comptime'):+ raise SystemExit(f'cannot move {d}')+ if d.kind == 'var':+ raise SystemExit(f'cannot move container var {d.name}')+ owner[id(d)] = gi+ moved = [d for d in inner if id(d) in owner]++ def gtext(gi):+ return '\n'.join('\n'.join(ded[d.start:d.end]) for d in moved if owner[id(d)] == gi)+ container_rest = '\n'.join('\n'.join(ded[d.start:d.end]) for d in inner if id(d) not in owner)+ outer_rest = '\n'.join('\n'.join(lines[d.start:d.end]) for d in outer if d is not C)+ info = {g: rich_tokens(gtext(g)) for g in range(len(groups))}+ info_c = rich_tokens(container_rest)+ info_o = rich_tokens(outer_rest)++ inner_pub = set() # inner (unmoved) names to make pub+ outer_pub = set() # outer names to make pub+ alias_needed, alias_pub = set(), set()+ nested_pub_lines = set() # absolute line indexes in `lines` (outer structs / unmoved inner structs)+ group_nested_pub = {} # (gi, ded index) -> True for members of moved structs+ copies = {g: [] for g in range(len(groups))}+ inner_alias = {g: [] for g in range(len(groups))}+ outer_alias = {g: [] for g in range(len(groups))}+ need_container = {g: False for g in range(len(groups))}++ def loc(d):+ return owner.get(id(d), -1)++ for g, (bare, calls, qual) in info.items():+ # Inner names (bare inside the struct scope).+ for n in sorted(bare):+ if n in inner_by:+ d = inner_by[n]+ if loc(d) == g:+ continue+ need_container[g] = True+ inner_alias[g].append(n)+ if loc(d) == -1:+ inner_pub.add(n)+ else:+ alias_needed.add(n)+ alias_pub.add(n)+ elif n == cname:+ need_container[g] = True+ # Outer names.+ pending = sorted(n for n in bare if n in outer_by and n not in inner_by and n != cname)+ seen = set()+ while pending:+ n = pending.pop()+ if n in seen:+ continue+ seen.add(n)+ d = outer_by[n]+ text = '\n'.join(lines[d.decl_line:d.end])+ if is_copyable(d, text):+ copies[g].append(d)+ for ident in rich_tokens(text.split('=', 1)[1])[0]:+ if ident in outer_by and ident not in seen and ident != cname:+ pending.append(ident)+ continue+ if d.kind == 'var':+ raise SystemExit(f'group {g} uses outer var {n}; handle by hand')+ outer_alias[g].append(n)+ outer_pub.add(n)+ # Methods called on the container from a group file.+ for n in set(calls) | {q for (p, q) in qual if p == cname}:+ d = inner_by.get(n)+ if d is None:+ continue+ if loc(d) == -1:+ inner_pub.add(n)+ elif loc(d) != g:+ alias_needed.add(n)+ alias_pub.add(n)+ else:+ # own group: still reached through the container alias by self.n()+ alias_needed.add(n)+ alias_pub.add(n)+ # Remaining container/outer code reaching moved decls.+ for bare, calls, qual in (info_c, info_o):+ for n in set(bare) | set(calls) | {q for (p, q) in qual if p == cname}:+ d = inner_by.get(n)+ if d is not None and loc(d) != -1:+ if n in bare and (bare is info_o[0]):+ continue # outer bare names don't see container members+ alias_needed.add(n)+ for d in moved:+ if d.pub:+ alias_needed.add(d.name)+ alias_pub.add(d.name)++ # Members of structs reached across the boundary.+ all_texts = {('g', g): info[g] for g in info}+ all_texts[('c',)] = info_c+ all_texts[('o',)] = info_o+ for d in outer:+ if d is C or d.kind not in ('const', 'var'):+ continue+ for idx, n, pub in nested_decls(lines, d):+ if pub:+ continue+ if any(n in calls or (d.name, n) in qual for key, (b, calls, qual) in all_texts.items() if key[0] == 'g'):+ nested_pub_lines.add(idx)+ for d in inner:+ if d.kind not in ('const', 'var'):+ continue+ here = loc(d)+ for idx, n, pub in nested_decls(ded, d):+ if pub:+ continue+ for key, (b, calls, qual) in all_texts.items():+ where = key[1] if key[0] == 'g' else -1+ if where == here:+ continue+ if n in calls or (d.name, n) in qual:+ if here == -1:+ nested_pub_lines.add(idx + off)+ else:+ group_nested_pub[(here, idx)] = True++ # Import identifiers.+ taken = set(outer_by) | set(inner_by)+ for g in info:+ taken |= info[g][0]+ idents = []+ for g in groups:+ if ':' in g[0]:+ g[0], ident = g[0].split(':', 1)+ else:+ ident = os.path.splitext(os.path.basename(g[0]))[0]+ if ident in taken:+ raise SystemExit(f'group ident {ident} collides')+ idents.append(ident)+ mod_ident = parent_stem + '_mod'++ for g, (gpath, gdoc, _) in enumerate(groups):+ gdir = os.path.dirname(gpath)+ out = []+ for dl in gdoc.split('\\n') if gdoc else []:+ out.append('//! ' + dl)+ if out:+ out.append('')+ for d in sorted(copies[g], key=lambda d: d.decl_line):+ out.append(rewrite_import_paths(re.sub(r'^pub\s+', '', '\n'.join(lines[d.decl_line:d.end])), parent_dir, gdir))+ rel = os.path.relpath(parent, gdir)+ if outer_alias[g]:+ out.append(f'const {mod_ident} = @import("{rel}");')+ out.append(f'const {cname} = {mod_ident}.{cname};')+ for n in sorted(outer_alias[g], key=lambda n: outer_by[n].decl_line):+ out.append(f'const {n} = {mod_ident}.{n};')+ elif need_container[g]:+ out.append(f'const {cname} = @import("{rel}").{cname};')+ for n in sorted(set(inner_alias[g]), key=lambda n: inner_by[n].decl_line):+ out.append(f'const {n} = {cname}.{n};')+ out.append('')+ mine = [d for d in moved if owner[id(d)] == g]+ for i, d in enumerate(mine):+ tl = list(ded[d.start:d.end])+ r = d.decl_line - d.start+ if not d.pub:+ tl[r] = PUB(tl[r])+ for k in range(len(tl)):+ if group_nested_pub.get((g, d.start + k)):+ tl[k] = PUB(tl[k])+ out.append(rewrite_import_paths('\n'.join(tl), parent_dir, gdir))+ if i + 1 < len(mine):+ out.append('')+ if os.path.exists(gpath):+ raise SystemExit(f'{gpath} exists')+ os.makedirs(gdir or '.', exist_ok=True)+ open(gpath, 'w').write('\n'.join(out).rstrip('\n') + '\n')++ new = list(lines)+ for n in outer_pub:+ d = outer_by[n]+ if not d.pub:+ new[d.decl_line] = PUB(new[d.decl_line])+ for n in inner_pub:+ d = inner_by[n]+ if not d.pub:+ new[d.decl_line + off] = PUB(new[d.decl_line + off])+ for idx in nested_pub_lines:+ new[idx] = PUB(new[idx])+ remove = [False] * len(new)+ insert = {}+ first = {}+ for d in moved:+ first.setdefault(owner[id(d)], d)+ for g, d in first.items():+ block = []+ for m in moved:+ if owner[id(m)] == g and m.name in alias_needed:+ pub = 'pub ' if (m.pub or m.name in alias_pub) else ''+ block.append(f' {pub}const {m.name} = {idents[g]}.{m.name};')+ insert[d.start + off] = block+ for d in moved:+ for k in range(d.start, d.end):+ remove[k + off] = True+ nxt = d.end + off+ if nxt < body_end and new[nxt].strip() == '' and (d.start + off) not in insert:+ remove[nxt] = True+ result = []+ for k, line in enumerate(new):+ if k in insert:+ if insert[k]:+ if result and result[-1].strip() != '':+ result.append('')+ result.extend(insert[k])+ if not remove[k]:+ result.append(line)+ # Group imports after the last top-level @import before the container.+ cpos = next(i for i, l in enumerate(result) if re.match(r'^(pub\s+)?const\s+' + cname + r'\s*=\s*struct', l))+ last = max(i for i in range(cpos) if re.match(r'^(pub )?const \w+ = @import\(', result[i]))+ imports = [f'const {idents[g]} = @import("{os.path.relpath(groups[g][0], parent_dir)}");' for g in range(len(groups))]+ result[last + 1:last + 1] = imports+ text = '\n'.join(result)+ text = re.sub(r'\n{3,}', '\n\n', text)+ open(parent, 'w').write(text.rstrip('\n') + '\n')+ for g in range(len(groups)):+ print(f'{groups[g][0]}: {len([d for d in moved if owner[id(d)] == g])} decls as {idents[g]}')+++if __name__ == '__main__':+ main()diff --git a/tools/split/zoutline.py b/tools/split/zoutline.pynew file mode 100755index 0000000..c918ca6--- /dev/null+++ b/tools/split/zoutline.py@@ -0,0 +1,53 @@+#!/usr/bin/env python3+"""Outline a Zig file's declarations to pick split points.++ zoutline.py FILE [--in NAME] [--min LINES]++Prints each declaration's line range (from its declaration line, which is what+a spec's N-M range matches), its length including doc comments, its size and+its first line. --in NAME lists the members of the top-level container+`const NAME = struct { ... };` instead, with the file's own line numbers (for+znested.py and zhoist.py); --min hides declarations shorter than LINES.+"""+import os+import sys++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from zsplit import parse # noqa: E402+++def main():+ args = sys.argv[1:]+ path, container, minimum = None, None, 0+ while args:+ a = args.pop(0)+ if a == '--in' and args:+ container = args.pop(0)+ elif a == '--min' and args:+ minimum = int(args.pop(0))+ elif path is None and not a.startswith('-'):+ path = a+ else:+ raise SystemExit(__doc__)+ if path is None:+ raise SystemExit(__doc__)+ lines = open(path).read().split('\n')+ offset = 0+ if container:+ d = next((x for x in parse(lines) if x.name == container), None)+ if d is None:+ raise SystemExit(f'{path}: no top-level declaration {container}')+ print(f'{container}: lines {d.decl_line + 1}-{d.end}')+ offset = d.decl_line + 1+ lines = [l[4:] if l.startswith(' ') else l for l in lines[offset:d.end - 1]]+ for d in parse(lines):+ count = d.end - d.start+ if count < minimum or d.kind == 'field':+ continue+ size = sum(len(l) + 1 for l in lines[d.start:d.end])+ print(f'{d.decl_line + offset + 1:5d}-{d.end + offset:5d} {count:4d}L {size:6d}B '+ f'{lines[d.decl_line].strip()[:100]}')+++if __name__ == '__main__':+ main()diff --git a/tools/split/zsplit.py b/tools/split/zsplit.pynew file mode 100755index 0000000..3d2f626--- /dev/null+++ b/tools/split/zsplit.py@@ -0,0 +1,544 @@+#!/usr/bin/env python3+"""Move top-level declarations of a Zig file into sibling "group" files.++ zsplit.py SPEC++Spec file format (see examples/dock.spec):++ parent src/Dock.zig+ group src/dock/paint.zig Painting the dock: rasters, icons and badges.+ paint paintItem 120-340+ group src/dock/hover.zig Hover and tooltip tracking.+ hover.* # regex over decl names+ test:"dock hover" # a test block by name prefix++Names select top-level decls; N-M selects every top-level decl starting in that+line range (1-based, of the original parent). The text after a group's path+becomes its `//!` doc (a literal `\\n` starts a new line); `path:ident` forces+the name the parent imports the group as. The parent keeps one alias line per+moved declaration (pub when the original was pub or another file needs it),+right where the group's first declaration was. Group files import the parent+for the non-copyable names they use; `var`s stay in the parent and are+referenced as `parent.name`. A group of tests only is reached through a+`test { _ = @import(...); }` block.+"""+import os+import re+import sys++IDENT = re.compile(r'[A-Za-z_][A-Za-z0-9_]*')+DECL_RE = re.compile(+ r'^(?P<pub>pub\s+)?(?:(?:export|extern)(?:\s+"[^"]*")?\s+)?(?:(?:inline|noinline)\s+)?'+ r'(?:threadlocal\s+)?(?P<kind>fn|const|var)\s+(?P<name>@"[^"]+"|[A-Za-z_][A-Za-z0-9_]*)')+TEST_RE = re.compile(r'^test\b\s*(?P<name>"[^"]*"|[A-Za-z_][A-Za-z0-9_]*)?')+COMPTIME_RE = re.compile(r'^comptime\s*\{')+++def strip_code(line):+ """Returns the line with comments removed and string/char contents blanked."""+ out = []+ j = 0+ n = len(line)+ s = line.lstrip()+ if s.startswith('\\\\'):+ return ''+ while j < n:+ c = line[j]+ if line.startswith('//', j):+ break+ if c == '"':+ out.append('"')+ j += 1+ while j < n:+ if line[j] == '\\':+ j += 2+ continue+ if line[j] == '"':+ break+ j += 1+ out.append('"')+ j += 1+ continue+ if c == "'":+ out.append("'")+ j += 1+ while j < n:+ if line[j] == '\\':+ j += 2+ continue+ if line[j] == "'":+ break+ j += 1+ out.append("'")+ j += 1+ continue+ out.append(c)+ j += 1+ return ''.join(out)+++class Decl:+ def __init__(self, start, decl_line, end, kind, name, pub, header):+ self.start = start # index of first line incl. doc comments+ self.decl_line = decl_line # index of the declaration line+ self.end = end # exclusive+ self.kind = kind # fn const var test comptime field+ self.name = name+ self.pub = pub+ self.header = header++ def __repr__(self):+ return f'Decl({self.kind} {self.name} {self.start + 1}-{self.end})'+++def parse(lines):+ decls = []+ depth = 0+ cur = None+ doc_start = None+ for idx, line in enumerate(lines):+ stripped = line.strip()+ code = strip_code(line)+ if depth == 0 and cur is None:+ if stripped.startswith('//!'):+ doc_start = None+ elif stripped.startswith('//'):+ if doc_start is None:+ doc_start = idx+ elif stripped == '':+ doc_start = None+ else:+ m = DECL_RE.match(stripped)+ start = doc_start if doc_start is not None else idx+ doc_start = None+ if m:+ cur = [start, idx, m.group('kind'), m.group('name'), bool(m.group('pub')), stripped]+ elif TEST_RE.match(stripped):+ tm = TEST_RE.match(stripped)+ cur = [start, idx, 'test', 'test:' + (tm.group('name') or ''), False, stripped]+ elif COMPTIME_RE.match(stripped):+ cur = [start, idx, 'comptime', 'comptime@%d' % idx, False, stripped]+ else:+ cur = [start, idx, 'field', 'field@%d' % idx, False, stripped]+ for c in code:+ if c in '{([':+ depth += 1+ elif c in '})]':+ depth -= 1+ if cur is not None and depth == 0:+ t = code.rstrip()+ ends = t.endswith(';') or t.endswith('}')+ if cur[2] == 'field':+ ends = ends or t.endswith(',')+ if ends:+ decls.append(Decl(cur[0], cur[1], idx + 1, cur[2], cur[3], cur[4], cur[5]))+ cur = None+ if cur is not None:+ raise SystemExit(f'unterminated declaration at line {cur[1] + 1}: {cur[5]}')+ return decls+++def nested_decls(lines, d):+ """(line_idx, name, pub) for declarations directly inside a container decl."""+ out = []+ depth = 0+ for idx in range(d.decl_line, d.end):+ code = strip_code(lines[idx])+ if depth == 1:+ m = DECL_RE.match(lines[idx].strip())+ if m:+ out.append((idx, m.group('name'), bool(m.group('pub'))))+ for c in code:+ if c in '{([':+ depth += 1+ elif c in '})]':+ depth -= 1+ return out+++def rich_tokens(text):+ """(bare identifiers, identifiers called as `.name(`, (qualifier, name) pairs)."""+ bare, calls, qualified = set(), set(), set()+ for line in text.split('\n'):+ code = strip_code(line)+ for m in IDENT.finditer(code):+ s, e = m.start(), m.end()+ prev = code[s - 1] if s > 0 else ''+ if prev == '@' or (prev and (prev.isalnum() or prev == '_')):+ continue+ name = m.group(0)+ if prev == '.' and s >= 2 and code[s - 2] == '.':+ prev = '' # range `a..b`+ if prev != '.':+ bare.add(name)+ continue+ rest = code[e:].lstrip()+ if rest.startswith('('):+ calls.add(name)+ q = re.search(r'([A-Za-z_][A-Za-z0-9_]*)\s*\.$', code[:s])+ if q:+ qualified.add((q.group(1), name))+ return bare, calls, qualified+++def import_target(text):+ m = re.search(r'@import\("([^"]+)"\)', text)+ return m.group(1) if m else None+++def rewrite_import_paths(text, from_dir, to_dir):+ if os.path.normpath(from_dir) == os.path.normpath(to_dir):+ return text++ def fix(m):+ builtin, p = m.group(1), m.group(2)+ # Module imports ("std", "ui") have no extension; files do.+ if p.startswith('/') or '.' not in os.path.basename(p):+ return m.group(0)+ absp = os.path.normpath(os.path.join(from_dir, p))+ rel = os.path.relpath(absp, to_dir)+ return '@%s("%s")' % (builtin, rel)+ return re.sub(r'@(import|embedFile)\("([^"]+)"\)', fix, text)+++def is_copyable(decl, text):+ """A const whose value is an import or a pure path/scoped-log off one."""+ if decl.kind != 'const':+ return False+ body = text.strip()+ m = re.match(r'^(?:pub\s+)?const\s+\w+\s*(?::\s*[^=]+)?=\s*(.*);$', body, re.S)+ if not m:+ return False+ rhs = m.group(1).strip()+ if '\n' in rhs:+ return False+ if rhs.startswith('@import('):+ return True+ if re.match(r'^@This\(\)$', rhs):+ return False+ if re.match(r'^std\.log\.scoped\(\.\w+\)$', rhs):+ return True+ if re.match(r'^@cImport', rhs):+ return False+ # dotted path off another identifier+ if re.match(r'^[A-Za-z_]\w*(\.[A-Za-z_]\w*|\.@"[^"]+")+$', rhs):+ return True+ if re.match(r'^@import\("[^"]+"\)(\.[A-Za-z_]\w*)+$', rhs):+ return True+ return False+++def main():+ if len(sys.argv) != 2:+ raise SystemExit(__doc__)+ spec_path = sys.argv[1]+ spec = open(spec_path).read().split('\n')+ parent = None+ groups = [] # (path, doc, selectors)+ for raw in spec:+ line = raw.split('#', 1)[0].rstrip() if not raw.lstrip().startswith('test:') else raw.rstrip()+ if not line.strip():+ continue+ if line.startswith('parent '):+ parent = line.split(None, 1)[1].strip()+ elif line.startswith('group '):+ parts = line.split(None, 2)+ groups.append([parts[1], parts[2] if len(parts) > 2 else '', []])+ else:+ if line.strip().startswith('test:'):+ groups[-1][2].append(line.strip())+ else:+ groups[-1][2].extend(line.split())+ assert parent and groups++ src = open(parent).read()+ lines = src.split('\n')+ decls = parse(lines)+ by_name = {}+ for d in decls:+ if d.kind in ('fn', 'const', 'var'):+ by_name[d.name] = d+ parent_dir = os.path.dirname(parent)+ parent_stem = os.path.splitext(os.path.basename(parent))[0]++ # The parent's self alias (const Dock = @This();)+ self_alias = None+ for d in decls:+ if d.kind == 'const' and re.search(r'=\s*@This\(\)\s*;', '\n'.join(lines[d.decl_line:d.end])):+ self_alias = d.name++ # Assign decls to groups.+ owner = {}+ for gi, (gpath, gdoc, sels) in enumerate(groups):+ for sel in sels:+ matched = []+ rm = re.match(r'^(\d+)-(\d+)$', sel)+ if rm:+ lo, hi = int(rm.group(1)) - 1, int(rm.group(2)) - 1+ matched = [d for d in decls if lo <= d.decl_line <= hi and d.kind not in ('field',)]+ elif sel.startswith('test:'):+ pref = sel[5:]+ matched = [d for d in decls if d.kind == 'test' and d.name[5:].startswith(pref)]+ elif sel in by_name:+ matched = [by_name[sel]]+ else:+ rx = re.compile('^(?:' + sel + ')$')+ matched = [d for d in decls if d.kind in ('fn', 'const', 'var') and rx.match(d.name)]+ if not matched:+ raise SystemExit(f'selector {sel!r} matched nothing')+ for d in matched:+ if d.kind == 'field':+ raise SystemExit(f'cannot move field {d}')+ if id(d) in owner and owner[id(d)] != gi:+ raise SystemExit(f'{d} selected by two groups')+ owner[id(d)] = gi++ moved = [d for d in decls if id(d) in owner]+ for d in moved:+ if d.kind == 'var':+ print(f'warning: moving var {d.name}; check references', file=sys.stderr)++ # Identify the import name each group gets in the parent.+ taken = set(by_name) | rich_tokens(src)[0]+ group_ident = []+ for g in groups:+ if ':' in g[0]:+ g[0], forced = g[0].split(':', 1)+ taken.add(forced)+ group_ident.append(forced)+ continue+ gpath = g[0]+ stem = os.path.splitext(os.path.basename(gpath))[0]+ base = stem if stem not in taken else parent_stem.lower() + '_' + stem+ ident = base+ k = 2+ while ident in taken:+ ident = f'{base}{k}'+ k += 1+ taken.add(ident)+ group_ident.append(ident)++ # Parent import identifier used inside group files.+ parent_ident = self_alias or parent_stem+ if not self_alias:+ used_anywhere = set()+ for d in moved:+ used_anywhere |= rich_tokens('\n'.join(lines[d.start:d.end]))[0]+ if parent_ident in by_name or parent_ident in used_anywhere:+ parent_ident = parent_stem + '_mod'++ has_fields = any(d.kind == 'field' for d in decls)+ is_struct_file = bool(self_alias) or has_fields++ def loc(d):+ return owner.get(id(d), -1)++ texts = {-1: '\n'.join('\n'.join(lines[d.start:d.end]) for d in decls if id(d) not in owner)}+ for gi in range(len(groups)):+ texts[gi] = '\n'.join('\n'.join(lines[d.start:d.end]) for d in moved if owner[id(d)] == gi)+ info = {f: rich_tokens(t) for f, t in texts.items()}++ need_pub = set() # top-level names in the parent that must become pub+ alias_needed = set() # moved names the parent must alias+ alias_pub_needed = set()+ nested_pub_lines = set()+ copies = {gi: [] for gi in range(len(groups))}+ aliases = {gi: [] for gi in range(len(groups))}+ var_refs = {gi: [] for gi in range(len(groups))}+ needs_parent = {gi: False for gi in range(len(groups))}++ def through_parent(f, name):+ d = by_name[name]+ if loc(d) == -1:+ need_pub.add(name)+ else:+ alias_needed.add(name)+ alias_pub_needed.add(name)++ for f, (bare, calls, qualified) in info.items():+ pending = sorted(n for n in bare if n in by_name and loc(by_name[n]) != f)+ seen = set()+ while pending:+ name = pending.pop()+ if name in seen:+ continue+ seen.add(name)+ d = by_name[name]+ if f == -1:+ alias_needed.add(name) # parent code using a moved decl+ continue+ text = '\n'.join(lines[d.decl_line:d.end])+ if name == self_alias:+ needs_parent[f] = True+ continue+ if loc(d) == -1 and is_copyable(d, text):+ copies[f].append(d)+ for ident in rich_tokens(text.split('=', 1)[1])[0]:+ if ident in by_name and ident not in seen and loc(by_name[ident]) != f:+ pending.append(ident)+ continue+ needs_parent[f] = True+ if d.kind == 'var':+ var_refs[f].append(name)+ else:+ aliases[f].append(name)+ through_parent(f, name)+ if is_struct_file:+ members = set(calls) | {n for (q, n) in qualified if q == self_alias}+ for name in members:+ d = by_name.get(name)+ if d is None or d.kind not in ('fn', 'const', 'var'):+ continue+ if loc(d) == -1:+ if f != -1:+ need_pub.add(name)+ else:+ alias_needed.add(name)+ if f != -1:+ alias_pub_needed.add(name)++ for d in decls:+ if d.kind not in ('const', 'var'):+ continue+ members = nested_decls(lines, d)+ for idx, name, pub in members:+ if pub:+ continue+ for f, (bare, calls, qualified) in info.items():+ if f == loc(d):+ continue+ if name in calls or (d.name, name) in qualified:+ nested_pub_lines.add(idx)++ alias_pub = {}+ for d in moved:+ if d.kind in ('fn', 'const', 'var'):+ if d.pub:+ alias_needed.add(d.name)+ alias_pub[d.name] = d.pub or d.name in alias_pub_needed++ group_outputs = []+ for gi, (gpath, gdoc, _) in enumerate(groups):+ mine = [d for d in moved if owner[id(d)] == gi]+ if '@This()' in texts[gi]:+ print(f'warning: @This() in moved code for {gpath}', file=sys.stderr)+ group_outputs.append((gpath, gdoc, mine, copies[gi], aliases[gi], var_refs[gi], needs_parent[gi]))++ # Write group files.+ for gpath, gdoc, mine, copies, aliases, var_refs, needs_parent in group_outputs:+ gdir = os.path.dirname(gpath)+ out = []+ for dl in gdoc.split('\\n') if gdoc else []:+ out.append('//! ' + dl if dl else '//!')+ if out:+ out.append('')+ copies_sorted = sorted(copies, key=lambda d: d.decl_line)+ for d in copies_sorted:+ text = '\n'.join(lines[d.decl_line:d.end])+ text = re.sub(r'^pub\s+', '', text)+ out.append(rewrite_import_paths(text, parent_dir, gdir))+ if needs_parent:+ rel = os.path.relpath(parent, gdir)+ out.append(f'const {parent_ident} = @import("{rel}");')+ for name in sorted(aliases, key=lambda n: by_name[n].decl_line):+ out.append(f'const {name} = {parent_ident}.{name};')+ out.append('')+ for i, d in enumerate(mine):+ text_lines = lines[d.start:d.end]+ # make the decl pub (unless test/comptime)+ rel = d.decl_line - d.start+ text_lines = list(text_lines)+ if d.kind in ('fn', 'const', 'var') and not d.pub:+ text_lines[rel] = re.sub(r'^(\s*)', r'\1pub ', text_lines[rel], count=1)+ for k in range(len(text_lines)):+ if d.start + k in nested_pub_lines:+ text_lines[k] = re.sub(r'^(\s*)', r'\1pub ', text_lines[k], count=1)+ text = '\n'.join(text_lines)+ text = rewrite_import_paths(text, parent_dir, gdir)+ if var_refs:+ code_vars = set(var_refs)++ def sub_line(line):+ code = strip_code(line)+ res = []+ last = 0+ for m in IDENT.finditer(code):+ nm = m.group(0)+ s = m.start()+ prev = code[s - 1] if s > 0 else ''+ if prev == '.' and s >= 2 and code[s - 2] == '.':+ prev = '' # range `a..b`+ if nm in code_vars and prev not in ('.', '@') and not (prev.isalnum() or prev == '_'):+ res.append(line[last:s])+ res.append(f'{parent_ident}.{nm}')+ last = m.end()+ res.append(line[last:])+ return ''.join(res)+ text = '\n'.join(sub_line(l) for l in text.split('\n'))+ out.append(text)+ if i + 1 < len(mine):+ out.append('')+ os.makedirs(gdir or '.', exist_ok=True)+ if os.path.exists(gpath):+ raise SystemExit(f'{gpath} exists')+ open(gpath, 'w').write('\n'.join(out).rstrip('\n') + '\n')++ # Rewrite the parent.+ new = list(lines)+ # Make needed decls pub.+ for name in need_pub:+ d = by_name.get(name)+ if d is None or id(d) in owner or d.pub:+ continue+ new[d.decl_line] = re.sub(r'^(\s*)', r'\1pub ', new[d.decl_line], count=1)+ for idx in nested_pub_lines:+ new[idx] = re.sub(r'^(\s*)', r'\1pub ', new[idx], count=1)+ # Replace moved ranges; first decl of each group gets the alias block.+ first_of_group = {}+ for d in moved:+ gi = owner[id(d)]+ if gi not in first_of_group:+ first_of_group[gi] = d+ remove = [False] * len(new)+ insert_at = {}+ for gi, d in first_of_group.items():+ gpath = groups[gi][0]+ rel = os.path.relpath(gpath, parent_dir)+ members = [m for m in moved if owner[id(m)] == gi]+ if any(m.kind == 'test' for m in members) and not any(m.name in alias_needed for m in members if m.kind in ('fn', 'const', 'var')):+ insert_at[d.start] = ['test {', f' _ = @import("{rel}");', '}']+ continue+ block = [f'const {group_ident[gi]} = @import("{rel}");']+ for md in [m for m in moved if owner[id(m)] == gi]:+ if md.kind in ('fn', 'const', 'var') and md.name in alias_needed:+ pub = 'pub ' if alias_pub[md.name] else ''+ block.append(f'{pub}const {md.name} = {group_ident[gi]}.{md.name};')+ if any(m.kind == 'test' for m in members):+ block += ['test {', f' _ = {group_ident[gi]};', '}']+ insert_at[d.start] = block+ for d in moved:+ for i in range(d.start, d.end):+ remove[i] = True+ # swallow one blank line after the decl to avoid double blanks+ if d.end < len(new) and new[d.end].strip() == '' and d.start not in insert_at:+ remove[d.end] = True+ result = []+ for i, line in enumerate(new):+ if i in insert_at:+ if result and result[-1].strip() != '':+ result.append('')+ result.extend(insert_at[i])+ if not remove[i]:+ result.append(line)+ continue+ if not remove[i]:+ result.append(line)+ text = '\n'.join(result)+ text = re.sub(r'\n{3,}', '\n\n', text)+ open(parent, 'w').write(text.rstrip('\n') + '\n')+ for gi, ident in enumerate(group_ident):+ print(f'{groups[gi][0]}: {len([d for d in moved if owner[id(d)] == gi])} decls as {ident}')+++if __name__ == '__main__':+ main()diff --git a/tools/split/zverify.py b/tools/split/zverify.pynew file mode 100755index 0000000..b986165--- /dev/null+++ b/tools/split/zverify.py@@ -0,0 +1,46 @@+#!/usr/bin/env python3+"""Check that a Zig split moved code verbatim.++ zverify.py REV PARENT GROUP...++Every non-blank line of PARENT at git revision REV must still appear in PARENT+or a GROUP file (ignoring indentation, a `pub ` prefix and `../` in import+paths), and the lines added must be imports, aliases (`const x = a.b;`) or `//!`+docs. Prints what is missing or added otherwise: only the rewrites the tools+make on purpose (`parent.var` references, a group's `test { ... }` block) should+remain.+"""+import re+import subprocess+import sys+from collections import Counter++ALIAS = re.compile(r'^const \w+ = (@import\("[^"]+"\)(\.\w+)*|[\w.]+(\.\w+)*|std\.log\.scoped\(\.\w+\));$')+++def norm(line):+ line = re.sub(r'^pub\s+', '', line.strip())+ return re.sub(r'@(import|embedFile)\("(?:\.\./)+', r'@\1("', line)+++def main():+ if len(sys.argv) < 3:+ raise SystemExit(__doc__)+ rev, paths = sys.argv[1], sys.argv[2:]+ orig = subprocess.run(['git', 'show', f'{rev}:{paths[0]}'], capture_output=True, text=True,+ check=True).stdout+ before = Counter(norm(l) for l in orig.split('\n') if l.strip())+ after = Counter()+ for p in paths:+ after.update(norm(l) for l in open(p).read().split('\n') if l.strip())+ missing = before - after+ added = {k: v for k, v in (after - before).items() if not ALIAS.match(k) and not k.startswith('//!')}+ for k, v in missing.items():+ print(f'MISSING x{v}: {k[:150]}')+ for k, v in added.items():+ print(f'ADDED x{v}: {k[:150]}')+ print(f'missing={sum(missing.values())} added={sum(added.values())}')+++if __name__ == '__main__':+ main()