From acfedcd1486d8bc505cd9d573868fed3e62c38e1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 6 Nov 2026 23:19:28 -0800 Subject: [PATCH 001/322] linesweeper: the crossing height in docs/sweep.typ divides the starting gap lem-intersection-height-error defined t as the ending gap alpha(y_1) - beta(y_1) over the sum of both gaps. The gap beta - alpha between two segments is D0 (1 - t) - D1 t, which is zero at t = D0 / (D0 + D1), with D0 = beta(y_0) - alpha(y_0) the starting gap. With D0 = 1 and D1 = 3 the old formula gave t = 0.75, while the segments cross at t = 0.25. The code in src/curve/line.rs already divides the starting gap. The lemma and its proof now use the starting gap as the numerator c, which also matches the proof's alpha(y) - beta(y) = -c + s d. SOURCE.json records the patch in local_patches and the new sha256 of docs/sweep.typ. README.craft.md and NOTICE say one file is changed. --- NOTICE | 8 ++++---- vendor/linesweeper/README.craft.md | 17 +++++++++++------ vendor/linesweeper/SOURCE.json | 6 ++++-- vendor/linesweeper/docs/sweep.typ | 12 ++++++------ 4 files changed, 25 insertions(+), 18 deletions(-) diff --git a/NOTICE b/NOTICE index bd88d43e7a..e830ba21f0 100644 --- a/NOTICE +++ b/NOTICE @@ -218,10 +218,10 @@ applications retain their own document-font selection and licensing policy. linesweeper linesweeper 0.5.0 (https://crates.io/crates/linesweeper/0.5.0), MIT OR Apache-2.0, is stored in -vendor/linesweeper with its upstream license files and no file changed. Its manifest names Joe Neeman -as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See -vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance and the files -left out. +vendor/linesweeper with its upstream license files and one local patch, to docs/sweep.typ. Its +manifest names Joe Neeman as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See +vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, local changes +and the files left out. Platform lifecycle source provenance diff --git a/vendor/linesweeper/README.craft.md b/vendor/linesweeper/README.craft.md index f683ca53de..9614df2a19 100644 --- a/vendor/linesweeper/README.craft.md +++ b/vendor/linesweeper/README.craft.md @@ -1,15 +1,20 @@ # Local linesweeper 0.5.0 copy -This is the crates.io linesweeper 0.5.0 package (MIT OR Apache-2.0) with some files left out and no +This is the crates.io linesweeper 0.5.0 package (MIT OR Apache-2.0) with some files left out and one file changed. `.cargo_vcs_info.json` names the commit it was packaged from, `824b0791a750f7b27b8edcbb6c6244d0e629875e`. That commit is not in the GitHub repository the manifest names, which is archived; its README says development moved off GitHub. -Every file here except this one and `SOURCE.json` is byte for byte the file in the `.crate` archive. -`SOURCE.json` records the hash of the `.crate` download (`source_archive_sha256`) and, for every file -kept, the hash in the package (`source_sha256`) and the hash here (`sha256`). `upstream_repository` is -null because no public repository this copy can name holds `upstream_revision`. `local_patches` is -empty. +Every file here except this one, `SOURCE.json` and `docs/sweep.typ` is byte for byte the file in the +`.crate` archive. `SOURCE.json` records the hash of the `.crate` download (`source_archive_sha256`) +and, for every file kept, the hash in the package (`source_sha256`) and the hash here (`sha256`). +`upstream_repository` is null because no public repository this copy can name holds +`upstream_revision`. `local_patches` lists each change: + +- `docs/sweep.typ`: the crossing-height lemma (`lem-intersection-height-error`) and its proof divide + the starting gap `beta(y_0) - alpha(y_0)` by the sum of both gaps. With the ending gap + `alpha(y_1) - beta(y_1)` as the numerator, gaps of 1 and 3 gave `t = 0.75`, while the segments + cross at `t = 0.25`. `omitted_files` lists the 43 files of the package left out here, with their hashes: diff --git a/vendor/linesweeper/SOURCE.json b/vendor/linesweeper/SOURCE.json index 9c71e51add..86d49ef3b3 100644 --- a/vendor/linesweeper/SOURCE.json +++ b/vendor/linesweeper/SOURCE.json @@ -7,7 +7,9 @@ "upstream_repository": null, "upstream_revision": "824b0791a750f7b27b8edcbb6c6244d0e629875e", "upstream_directory": "", - "local_patches": [], + "local_patches": [ + "In `docs/sweep.typ`, the crossing-height lemma and its proof use the starting gap `beta(y_0) - alpha(y_0)` as the numerator of `t`, instead of the ending gap `alpha(y_1) - beta(y_1)`, so that `y_0 + t(y_1 - y_0)` is the height where the segments cross." + ], "files": [ { "path": ".cargo_vcs_info.json", "source_sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc", "source_git_blob": null, "sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc" }, { "path": ".gitignore", "source_sha256": "88b59092499ae05234330eb7d0b01e953e969caf05261530e3765eef02536cf0", "source_git_blob": null, "sha256": "88b59092499ae05234330eb7d0b01e953e969caf05261530e3765eef02536cf0" }, @@ -21,7 +23,7 @@ { "path": "benches/linebender_logo.rs", "source_sha256": "d10867f43439d37f0e1da5d30eaed9ab3bfbe655ed47212f65dc20ab4db65cb3", "source_git_blob": null, "sha256": "d10867f43439d37f0e1da5d30eaed9ab3bfbe655ed47212f65dc20ab4db65cb3" }, { "path": "benches/painted_dreams.rs", "source_sha256": "073008db93840d380710e13ed3ae38e08cb823f10c12e5f838dac1ccf37eaecf", "source_git_blob": null, "sha256": "073008db93840d380710e13ed3ae38e08cb823f10c12e5f838dac1ccf37eaecf" }, { "path": "benches/synthetic.rs", "source_sha256": "7ce59bef2e1c4f28b00cb89feb15bc71ca4b098a8d27e7b02ea699aca9bcc810", "source_git_blob": null, "sha256": "7ce59bef2e1c4f28b00cb89feb15bc71ca4b098a8d27e7b02ea699aca9bcc810" }, - { "path": "docs/sweep.typ", "source_sha256": "4766082c8672a7bb4356b5581043489c13b4e3fb8931ba3a5f0a473fab0172f3", "source_git_blob": null, "sha256": "4766082c8672a7bb4356b5581043489c13b4e3fb8931ba3a5f0a473fab0172f3" }, + { "path": "docs/sweep.typ", "source_sha256": "4766082c8672a7bb4356b5581043489c13b4e3fb8931ba3a5f0a473fab0172f3", "source_git_blob": null, "sha256": "73860d363c4a12140e1cbdf8f02d050ed6c526a6f9b3d5d537ad51bfb4962b5d" }, { "path": "examples/boolean_op.rs", "source_sha256": "3b38a1ccda7e736cce4b191a3a45ab4824c4c365190e3eb637b2fb39b5996c9f", "source_git_blob": null, "sha256": "3b38a1ccda7e736cce4b191a3a45ab4824c4c365190e3eb637b2fb39b5996c9f" }, { "path": "examples/bus.rs", "source_sha256": "e206a08be73899f564188052c8ecc15526b54606e52ee2935a64ce6b5723da33", "source_git_blob": null, "sha256": "e206a08be73899f564188052c8ecc15526b54606e52ee2935a64ce6b5723da33" }, { "path": "examples/curve_metrics.rs", "source_sha256": "0db6a5327fd2119a03a9a66624fea3e04b6bbb519655667ad30487aee6c787d2", "source_git_blob": null, "sha256": "0db6a5327fd2119a03a9a66624fea3e04b6bbb519655667ad30487aee6c787d2" }, diff --git a/vendor/linesweeper/docs/sweep.typ b/vendor/linesweeper/docs/sweep.typ index 0f83ac1c6e..6d3323f405 100644 --- a/vendor/linesweeper/docs/sweep.typ +++ b/vendor/linesweeper/docs/sweep.typ @@ -719,7 +719,7 @@ and assume that $beta(y_0) - alpha(y_0) >= 0$ and $ alpha(y_1) - beta(y_1) > 16/3 (epsilon + 2 epsilon_0 M). $ -Define $t = (alpha(y_1) - beta(y_1)) / (alpha(y_1) - beta(y_1) + beta(y_0) - alpha(y_0)$ and set $y = y_0 + t(y_1 - y_0)$. The +Define $t = (beta(y_0) - alpha(y_0)) / (beta(y_0) - alpha(y_0) + alpha(y_1) - beta(y_1))$ and set $y = y_0 + t(y_1 - y_0)$. The natural way to compute $y$ produces an approximation $hat(y)$ satisfying $ |alpha(hat(y)) - beta(hat(y))| <= 4(epsilon + 2 epsilon_0 M) (1 + max(1/m_alpha, 1/m_beta)), @@ -731,18 +731,18 @@ Basically, this says we can find a good approximate crossing height as long as t #proof[ First, note that at least one of $alpha(y_0)$ or $beta(y_0)$ is calculated exactly; similarly for $alpha(y_1)$ and $beta(y_1)$. -Therefore the absolute error in calculating $alpha(y_1) - beta(y_1)$ is at most $epsilon + epsilon_0 M$ (where the $epsilon_0 M$ comes +Therefore the absolute error in calculating $beta(y_0) - alpha(y_0)$ is at most $epsilon + epsilon_0 M$ (where the $epsilon_0 M$ comes from rounding after the summation) and the absolute error in calculating -$(alpha(y_1) - beta(y_1)) + (beta(y_0) - alpha(y_0))$ is at most $2 epsilon + 3 epsilon_0 M$. -These errors aren't independent, though, since both terms involve a computation of $alpha(y_1) - beta(y_1)$. -Specifically, let $c = alpha(y_1) - beta(y_1)$ and let $d = (alpha(y_1) - beta(y_1)) + (beta(y_0) - alpha(y_0))$; suppose +$(beta(y_0) - alpha(y_0)) + (alpha(y_1) - beta(y_1))$ is at most $2 epsilon + 3 epsilon_0 M$. +These errors aren't independent, though, since both terms involve a computation of $beta(y_0) - alpha(y_0)$. +Specifically, let $c = beta(y_0) - alpha(y_0)$ and let $d = (beta(y_0) - alpha(y_0)) + (alpha(y_1) - beta(y_1))$; suppose our calculation of $c$ has error $epsilon_c$ and our calculation of $d$ has error $epsilon_d$. Then $ |epsilon_c - epsilon_d| <= epsilon + 2 epsilon_0 M, $ -because this is the *additional* error introduced into $d$ by computing $beta(y_0) - alpha(y_0)$ and adding it to the other term. +because this is the *additional* error introduced into $d$ by computing $alpha(y_1) - beta(y_1)$ and adding it to the other term. Now we consider the quotient From dec46890b7f87b4ec24b44ff7036c38680fc0dc1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 7 Nov 2026 10:11:10 -0800 Subject: [PATCH 002/322] linesweeper: exact copies of a shape no longer rescan the bundle for every touch Exact copies of a shape queue a touch event for every pair of coincident segments, and the touch branch of Sweeper::handle_intersection scanned the whole bundle in both directions for each one. Sweeping n copies took time growing faster than n^3: 200 copies of a 4-point polygon took 3.9 s and 400 copies took 98 s in a release build. The touch branch now runs its scan right or left from a segment at most once per sweep line until the sweep-line order changes. A repeated scan reads the same order, y and segments and would only push events already queued, so the output does not change. README.craft.md, SOURCE.json and NOTICE record the change as a local patch. --- NOTICE | 6 +- vendor/linesweeper/README.craft.md | 20 ++- vendor/linesweeper/SOURCE.json | 6 +- vendor/linesweeper/src/sweep/sweep_line.rs | 165 ++++++++++++++++++++- 4 files changed, 182 insertions(+), 15 deletions(-) diff --git a/NOTICE b/NOTICE index bd88d43e7a..70c163182c 100644 --- a/NOTICE +++ b/NOTICE @@ -218,10 +218,10 @@ applications retain their own document-font selection and licensing policy. linesweeper linesweeper 0.5.0 (https://crates.io/crates/linesweeper/0.5.0), MIT OR Apache-2.0, is stored in -vendor/linesweeper with its upstream license files and no file changed. Its manifest names Joe Neeman +vendor/linesweeper with its upstream license files and one local patch. Its manifest names Joe Neeman as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See -vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance and the files -left out. +vendor/linesweeper/README.craft.md and vendor/linesweeper/SOURCE.json for provenance, the local +change and the files left out. Platform lifecycle source provenance diff --git a/vendor/linesweeper/README.craft.md b/vendor/linesweeper/README.craft.md index f683ca53de..92736078e5 100644 --- a/vendor/linesweeper/README.craft.md +++ b/vendor/linesweeper/README.craft.md @@ -1,15 +1,21 @@ # Local linesweeper 0.5.0 copy -This is the crates.io linesweeper 0.5.0 package (MIT OR Apache-2.0) with some files left out and no -file changed. `.cargo_vcs_info.json` names the commit it was packaged from, +This is the crates.io linesweeper 0.5.0 package (MIT OR Apache-2.0) with some files left out and the +local patches listed below. `.cargo_vcs_info.json` names the commit it was packaged from, `824b0791a750f7b27b8edcbb6c6244d0e629875e`. That commit is not in the GitHub repository the manifest names, which is archived; its README says development moved off GitHub. -Every file here except this one and `SOURCE.json` is byte for byte the file in the `.crate` archive. -`SOURCE.json` records the hash of the `.crate` download (`source_archive_sha256`) and, for every file -kept, the hash in the package (`source_sha256`) and the hash here (`sha256`). `upstream_repository` is -null because no public repository this copy can name holds `upstream_revision`. `local_patches` is -empty. +Every file here except this one, `SOURCE.json` and the patched files below is byte for byte the file +in the `.crate` archive. `SOURCE.json` records the hash of the `.crate` download +(`source_archive_sha256`) and, for every file kept, the hash in the package (`source_sha256`) and the +hash here (`sha256`). `upstream_repository` is null because no public repository this copy can name +holds `upstream_revision`. `local_patches` describes each local patch. + +## Local patches + +| File | Change | +|---|---| +| `src/sweep/sweep_line.rs` | The touch branch of `Sweeper::handle_intersection` runs its scan right from a segment, or left from a segment, at most once per sweep line until the sweep-line order changes. Exact copies of a shape queue a touch event for every pair of coincident segments, and each event used to scan the whole bundle in both directions, so sweeping `n` copies took time growing faster than `n^3`. The skipped scans would only push events already queued, so the output does not change. The `coincident_copies_scan_once_per_order` test counts the scans for 60 copies of two shapes, and `coincident_copies_keep_the_fill` compares the output fill with the input's nonzero fill for 200 inputs with exact, reversed and split copies. | `omitted_files` lists the 43 files of the package left out here, with their hashes: diff --git a/vendor/linesweeper/SOURCE.json b/vendor/linesweeper/SOURCE.json index 9c71e51add..138ca6a21a 100644 --- a/vendor/linesweeper/SOURCE.json +++ b/vendor/linesweeper/SOURCE.json @@ -7,7 +7,9 @@ "upstream_repository": null, "upstream_revision": "824b0791a750f7b27b8edcbb6c6244d0e629875e", "upstream_directory": "", - "local_patches": [], + "local_patches": [ + "In `src/sweep/sweep_line.rs`, the touch branch of `Sweeper::handle_intersection` runs each scan from a segment in a direction at most once per sweep line until the sweep-line order changes, so exact copies of a shape no longer rescan the whole coincident bundle for every touch event." + ], "files": [ { "path": ".cargo_vcs_info.json", "source_sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc", "source_git_blob": null, "sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc" }, { "path": ".gitignore", "source_sha256": "88b59092499ae05234330eb7d0b01e953e969caf05261530e3765eef02536cf0", "source_git_blob": null, "sha256": "88b59092499ae05234330eb7d0b01e953e969caf05261530e3765eef02536cf0" }, @@ -62,7 +64,7 @@ { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__square.snap", "source_sha256": "b35c3e6a38d5ecdd8acf315ba0b0bd6485cd8b40193fdd76bd446bdfdb6eda77", "source_git_blob": null, "sha256": "b35c3e6a38d5ecdd8acf315ba0b0bd6485cd8b40193fdd76bd446bdfdb6eda77" }, { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__square_and_diamond.snap", "source_sha256": "3f01a76fb7ff4aef0fd55fd869602d4a2b69fff1bd65632f406b275b5d6af600", "source_git_blob": null, "sha256": "3f01a76fb7ff4aef0fd55fd869602d4a2b69fff1bd65632f406b275b5d6af600" }, { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__two_squares.snap", "source_sha256": "79e3c95e563a66c0ce244125470a106a18dfe29f276b732defd305406c873c7e", "source_git_blob": null, "sha256": "79e3c95e563a66c0ce244125470a106a18dfe29f276b732defd305406c873c7e" }, - { "path": "src/sweep/sweep_line.rs", "source_sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3", "source_git_blob": null, "sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3" }, + { "path": "src/sweep/sweep_line.rs", "source_sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3", "source_git_blob": null, "sha256": "8e2997347238f11d645647a69a30c4e00d997f63dac163e73f242aa0918d4917" }, { "path": "src/topology.rs", "source_sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b", "source_git_blob": null, "sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b" }, { "path": "src/treevec.rs", "source_sha256": "d88b9fbf02fa9f318560e1d483d465555f2b696ae12c00f8e4f5b71ea6779445", "source_git_blob": null, "sha256": "d88b9fbf02fa9f318560e1d483d465555f2b696ae12c00f8e4f5b71ea6779445" }, { "path": "src/typed_vec.rs", "source_sha256": "3e9a2675b8a40d8fc4df0575bd9d0d16b5604d18e9b78638dd5a612b28fc4c30", "source_git_blob": null, "sha256": "3e9a2675b8a40d8fc4df0575bd9d0d16b5604d18e9b78638dd5a612b28fc4c30" }, diff --git a/vendor/linesweeper/src/sweep/sweep_line.rs b/vendor/linesweeper/src/sweep/sweep_line.rs index b4b1883e29..bfa8dc0c8f 100644 --- a/vendor/linesweeper/src/sweep/sweep_line.rs +++ b/vendor/linesweeper/src/sweep/sweep_line.rs @@ -350,6 +350,17 @@ pub struct Sweeper<'a> { comparisons: RefCell, conservative_comparisons: RefCell, + + // Craft patch (coincident touch rescan): the (segment, scans right) pairs + // whose touch-event scan in `handle_intersection` already ran at the + // current `y` with the current sweep-line order. A scan reads only the + // order, `y` and the segments, so running it again before the order + // changes pushes only events it already pushed. Exact copies of a shape + // queue a touch event for every pair of coincident segments, and each one + // used to scan the whole bundle in both directions. + touch_scans: rustc_hash::FxHashSet<(SegIdx, bool)>, + #[cfg(test)] + touch_scan_count: usize, } impl<'segs> Sweeper<'segs> { @@ -377,6 +388,9 @@ impl<'segs> Sweeper<'segs> { horizontals: Vec::new(), comparisons: RefCell::new(ComparisonCache::new(eps, eps / 2.0)), conservative_comparisons: RefCell::new(ComparisonCache::new(4.0 * eps, eps / 2.0)), + touch_scans: rustc_hash::FxHashSet::default(), + #[cfg(test)] + touch_scan_count: 0, } } @@ -469,6 +483,7 @@ impl<'segs> Sweeper<'segs> { self.y = y; self.segs_needing_positions.clear(); self.horizontals.clear(); + self.touch_scans.clear(); } fn intersection_scan_right(&mut self, start_idx: usize, which: WhichTouch) { @@ -785,6 +800,9 @@ impl<'segs> Sweeper<'segs> { } } + // The order changes below, so earlier touch scans no longer stand. + self.touch_scans.clear(); + // Remove them in reverse to make indexing easier. let mut removed = Vec::with_capacity(to_move.len()); for &j in to_move.iter().rev() { @@ -830,9 +848,21 @@ impl<'segs> Sweeper<'segs> { // We haven't changed the order of any segments, but the "touch" event // we just processed might have been a witness for the crossing invariant. - // So we need to scan. - self.intersection_scan_right(right_idx, WhichTouch::Mid); - self.intersection_scan_left(left_idx, WhichTouch::Mid); + // So we need to scan, unless the same scan already ran with this order. + if self.touch_scans.insert((right, true)) { + #[cfg(test)] + { + self.touch_scan_count += 1; + } + self.intersection_scan_right(right_idx, WhichTouch::Mid); + } + if self.touch_scans.insert((left, false)) { + #[cfg(test)] + { + self.touch_scan_count += 1; + } + self.intersection_scan_left(left_idx, WhichTouch::Mid); + } } } @@ -2084,6 +2114,135 @@ mod tests { insta::assert_ron_snapshot!(snapshot_outputs(segs, 0.25)); } + fn closed_polyline(points: &[(f64, f64)]) -> BezPath { + let mut path = BezPath::new(); + path.move_to(points[0]); + for &p in &points[1..] { + path.line_to(p); + } + path.close_path(); + path + } + + fn copies(shape: &BezPath, n: usize) -> BezPath { + (0..n).flat_map(|_| shape.iter()).collect() + } + + // Exact copies of a shape queue a touch event for every pair of coincident + // segments. Each touch-event scan runs at most once per segment and + // direction for each sweep-line order, so the number of scans stays + // linear in the number of segments, and the output is the output for one + // copy. + #[test] + fn coincident_copies_scan_once_per_order() { + use crate::topology::Topology; + + let quad = closed_polyline(&[(0.0, 0.0), (100.0, 37.0), (60.0, 90.0), (10.0, 70.0)]); + let rect = closed_polyline(&[(0.0, 0.0), (100.0, 0.0), (100.0, 50.0), (0.0, 50.0)]); + for shape in [quad, rect] { + let path = copies(&shape, 60); + let mut segs = Segments::default(); + segs.add_bez_path(&path).unwrap(); + let mut sweep = Sweeper::new(&segs, 1e-6); + let mut bufs = SweepLineBuffers::default(); + let mut lines = 0; + while sweep.next_line(&mut bufs).is_some() { + lines += 1; + } + assert!( + sweep.touch_scan_count <= 2 * segs.len() * lines, + "{} touch scans for {} segments on {lines} sweep lines", + sweep.touch_scan_count, + segs.len() + ); + + let contour_paths = |path: &BezPath| -> Vec { + Topology::from_path(path, 1e-6) + .unwrap() + .contours(|w| *w != 0) + .contours() + .map(|c| c.path.clone()) + .collect() + }; + assert_eq!(contour_paths(&path), contour_paths(&shape)); + } + } + + // Small polygons on an integer grid, with exact, reversed and + // midpoint-split copies of some of them. The nonzero fill of the output + // contours matches the nonzero fill of the input. + #[test] + fn coincident_copies_keep_the_fill() { + use crate::topology::Topology; + use kurbo::{ParamCurve, ParamCurveNearest, Shape}; + + let mut state = 0x9e37_79b9_7f4a_7c15_u64; + let mut next = |n: u64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % n + }; + for case in 0..200 { + let mut polygons: Vec> = Vec::new(); + for _ in 0..1 + next(3) { + let len = 3 + next(3); + let polygon = (0..len).map(|_| (next(9) as f64, next(9) as f64)).collect(); + polygons.push(polygon); + } + for _ in 0..1 + next(3) { + let source = polygons[next(polygons.len() as u64) as usize].clone(); + let copy = match next(3) { + 0 => source, + 1 => source.into_iter().rev().collect(), + _ => { + let mut split = Vec::new(); + for (i, &(x0, y0)) in source.iter().enumerate() { + let (x1, y1) = source[(i + 1) % source.len()]; + split.push((x0, y0)); + split.push(((x0 + x1) / 2.0, (y0 + y1) / 2.0)); + } + split + } + }; + polygons.push(copy); + } + let input: BezPath = polygons + .iter() + .flat_map(|p| closed_polyline(p).into_iter()) + .collect(); + + let top = Topology::from_path(&input, 1e-6).unwrap(); + let contours = top.contours(|w| *w != 0); + for i in 0..64 { + for j in 0..64 { + let p = kurbo::Point::new(i as f64 / 8.0 + 0.0137, j as f64 / 8.0 + 0.0291); + // Skip points too close to an input edge to say which + // side they are on. + let near_edge = input.segments().any(|seg| { + let line = kurbo::Line::new(seg.start(), seg.end()); + let t = line.nearest(p, 0.0).t; + line.eval(t).distance(p) < 1e-3 + }); + if near_edge { + continue; + } + let expected = input.winding(p) != 0; + let enclosing = contours + .contours() + .filter(|c| c.path.winding(p) != 0) + .count(); + assert_eq!( + enclosing % 2 == 1, + expected, + "case {case} at {p:?}: {}", + input.to_svg() + ); + } + } + } + } + #[test] fn empty_sweep_line() { let segs = Segments::default(); From 5034f7afebc579f194c6eec0f1782d2ec0c28c1a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 7 Nov 2026 10:30:21 -0800 Subject: [PATCH 003/322] linesweeper: compare the combined winding in the coincident-touch test The sample-point check sums the winding of every output contour and compares its nonzero state with the input's nonzero winding, so same-direction nested contours around an unfilled point fail the test. --- vendor/linesweeper/SOURCE.json | 2 +- vendor/linesweeper/src/sweep/sweep_line.rs | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/vendor/linesweeper/SOURCE.json b/vendor/linesweeper/SOURCE.json index 138ca6a21a..dca8b972a8 100644 --- a/vendor/linesweeper/SOURCE.json +++ b/vendor/linesweeper/SOURCE.json @@ -64,7 +64,7 @@ { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__square.snap", "source_sha256": "b35c3e6a38d5ecdd8acf315ba0b0bd6485cd8b40193fdd76bd446bdfdb6eda77", "source_git_blob": null, "sha256": "b35c3e6a38d5ecdd8acf315ba0b0bd6485cd8b40193fdd76bd446bdfdb6eda77" }, { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__square_and_diamond.snap", "source_sha256": "3f01a76fb7ff4aef0fd55fd869602d4a2b69fff1bd65632f406b275b5d6af600", "source_git_blob": null, "sha256": "3f01a76fb7ff4aef0fd55fd869602d4a2b69fff1bd65632f406b275b5d6af600" }, { "path": "src/sweep/snapshots/linesweeper__sweep__sweep_line__tests__two_squares.snap", "source_sha256": "79e3c95e563a66c0ce244125470a106a18dfe29f276b732defd305406c873c7e", "source_git_blob": null, "sha256": "79e3c95e563a66c0ce244125470a106a18dfe29f276b732defd305406c873c7e" }, - { "path": "src/sweep/sweep_line.rs", "source_sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3", "source_git_blob": null, "sha256": "8e2997347238f11d645647a69a30c4e00d997f63dac163e73f242aa0918d4917" }, + { "path": "src/sweep/sweep_line.rs", "source_sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3", "source_git_blob": null, "sha256": "644dcaeacd1afcf056920916acdf271f099dc5e0c0324b5fbacd6aae4f597adb" }, { "path": "src/topology.rs", "source_sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b", "source_git_blob": null, "sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b" }, { "path": "src/treevec.rs", "source_sha256": "d88b9fbf02fa9f318560e1d483d465555f2b696ae12c00f8e4f5b71ea6779445", "source_git_blob": null, "sha256": "d88b9fbf02fa9f318560e1d483d465555f2b696ae12c00f8e4f5b71ea6779445" }, { "path": "src/typed_vec.rs", "source_sha256": "3e9a2675b8a40d8fc4df0575bd9d0d16b5604d18e9b78638dd5a612b28fc4c30", "source_git_blob": null, "sha256": "3e9a2675b8a40d8fc4df0575bd9d0d16b5604d18e9b78638dd5a612b28fc4c30" }, diff --git a/vendor/linesweeper/src/sweep/sweep_line.rs b/vendor/linesweeper/src/sweep/sweep_line.rs index bfa8dc0c8f..1caa6403d1 100644 --- a/vendor/linesweeper/src/sweep/sweep_line.rs +++ b/vendor/linesweeper/src/sweep/sweep_line.rs @@ -2228,12 +2228,12 @@ mod tests { continue; } let expected = input.winding(p) != 0; - let enclosing = contours + let output_winding: i32 = contours .contours() - .filter(|c| c.path.winding(p) != 0) - .count(); + .map(|c| c.path.winding(p)) + .sum(); assert_eq!( - enclosing % 2 == 1, + output_winding != 0, expected, "case {case} at {p:?}: {}", input.to_svg() From a29a6d4162ec704ca2b9ea33fdbb19e8e13aa898 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 04:45:03 -0800 Subject: [PATCH 004/322] linesweeper: the crossing-height proof in docs/sweep.typ divides d by y_1 - y_0 The proof's inverse-slope step divided d by y_1 - y_1, which is zero. The patch notes in SOURCE.json and README.craft.md, and the file's hash, are updated. --- vendor/linesweeper/README.craft.md | 3 ++- vendor/linesweeper/SOURCE.json | 4 ++-- vendor/linesweeper/docs/sweep.typ | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/vendor/linesweeper/README.craft.md b/vendor/linesweeper/README.craft.md index 9614df2a19..afd7fbccb5 100644 --- a/vendor/linesweeper/README.craft.md +++ b/vendor/linesweeper/README.craft.md @@ -14,7 +14,8 @@ and, for every file kept, the hash in the package (`source_sha256`) and the hash - `docs/sweep.typ`: the crossing-height lemma (`lem-intersection-height-error`) and its proof divide the starting gap `beta(y_0) - alpha(y_0)` by the sum of both gaps. With the ending gap `alpha(y_1) - beta(y_1)` as the numerator, gaps of 1 and 3 gave `t = 0.75`, while the segments - cross at `t = 0.25`. + cross at `t = 0.25`. The proof's inverse-slope difference is `d/(y_1 - y_0)`; the package has + `d/(y_1 - y_1)`, whose denominator is zero. `omitted_files` lists the 43 files of the package left out here, with their hashes: diff --git a/vendor/linesweeper/SOURCE.json b/vendor/linesweeper/SOURCE.json index 86d49ef3b3..a46d783d4f 100644 --- a/vendor/linesweeper/SOURCE.json +++ b/vendor/linesweeper/SOURCE.json @@ -8,7 +8,7 @@ "upstream_revision": "824b0791a750f7b27b8edcbb6c6244d0e629875e", "upstream_directory": "", "local_patches": [ - "In `docs/sweep.typ`, the crossing-height lemma and its proof use the starting gap `beta(y_0) - alpha(y_0)` as the numerator of `t`, instead of the ending gap `alpha(y_1) - beta(y_1)`, so that `y_0 + t(y_1 - y_0)` is the height where the segments cross." + "In `docs/sweep.typ`, the crossing-height lemma and its proof use the starting gap `beta(y_0) - alpha(y_0)` as the numerator of `t`, instead of the ending gap `alpha(y_1) - beta(y_1)`, so that `y_0 + t(y_1 - y_0)` is the height where the segments cross, and the proof's inverse-slope difference is `d/(y_1 - y_0)` instead of `d/(y_1 - y_1)`." ], "files": [ { "path": ".cargo_vcs_info.json", "source_sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc", "source_git_blob": null, "sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc" }, @@ -23,7 +23,7 @@ { "path": "benches/linebender_logo.rs", "source_sha256": "d10867f43439d37f0e1da5d30eaed9ab3bfbe655ed47212f65dc20ab4db65cb3", "source_git_blob": null, "sha256": "d10867f43439d37f0e1da5d30eaed9ab3bfbe655ed47212f65dc20ab4db65cb3" }, { "path": "benches/painted_dreams.rs", "source_sha256": "073008db93840d380710e13ed3ae38e08cb823f10c12e5f838dac1ccf37eaecf", "source_git_blob": null, "sha256": "073008db93840d380710e13ed3ae38e08cb823f10c12e5f838dac1ccf37eaecf" }, { "path": "benches/synthetic.rs", "source_sha256": "7ce59bef2e1c4f28b00cb89feb15bc71ca4b098a8d27e7b02ea699aca9bcc810", "source_git_blob": null, "sha256": "7ce59bef2e1c4f28b00cb89feb15bc71ca4b098a8d27e7b02ea699aca9bcc810" }, - { "path": "docs/sweep.typ", "source_sha256": "4766082c8672a7bb4356b5581043489c13b4e3fb8931ba3a5f0a473fab0172f3", "source_git_blob": null, "sha256": "73860d363c4a12140e1cbdf8f02d050ed6c526a6f9b3d5d537ad51bfb4962b5d" }, + { "path": "docs/sweep.typ", "source_sha256": "4766082c8672a7bb4356b5581043489c13b4e3fb8931ba3a5f0a473fab0172f3", "source_git_blob": null, "sha256": "db1f41677594b44c5e3f3db351c525b91cd125b07f1f945ed2f0e17d35b5bad3" }, { "path": "examples/boolean_op.rs", "source_sha256": "3b38a1ccda7e736cce4b191a3a45ab4824c4c365190e3eb637b2fb39b5996c9f", "source_git_blob": null, "sha256": "3b38a1ccda7e736cce4b191a3a45ab4824c4c365190e3eb637b2fb39b5996c9f" }, { "path": "examples/bus.rs", "source_sha256": "e206a08be73899f564188052c8ecc15526b54606e52ee2935a64ce6b5723da33", "source_git_blob": null, "sha256": "e206a08be73899f564188052c8ecc15526b54606e52ee2935a64ce6b5723da33" }, { "path": "examples/curve_metrics.rs", "source_sha256": "0db6a5327fd2119a03a9a66624fea3e04b6bbb519655667ad30487aee6c787d2", "source_git_blob": null, "sha256": "0db6a5327fd2119a03a9a66624fea3e04b6bbb519655667ad30487aee6c787d2" }, diff --git a/vendor/linesweeper/docs/sweep.typ b/vendor/linesweeper/docs/sweep.typ index 6d3323f405..c915e63b7b 100644 --- a/vendor/linesweeper/docs/sweep.typ +++ b/vendor/linesweeper/docs/sweep.typ @@ -789,7 +789,7 @@ abs(alpha(hat(y)) - beta(hat(y))) <= (2 epsilon_0 + epsilon_t) d + (epsilon_0 M) $ If we assume that $16 (epsilon + 2 epsilon_0 M) / d <= 3$ then $epsilon_t d <= 4 epsilon + 8 epsilon_0 M$. -Since $d/(y_1 - y_1)$ is the difference of the inverse-slopes of $alpha$ and $beta$, it's bounded by twice +Since $d/(y_1 - y_0)$ is the difference of the inverse-slopes of $alpha$ and $beta$, it's bounded by twice the maximum of these inverse-slopes. ] From 2cdbd4b9c1c27d04ee3d1f9f1c106185020c564b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 12:46:09 -0800 Subject: [PATCH 005/322] linesweeper: curves that cross just after a shared start are not reported as ordered transversal_after compared its two slope bounds by cross-multiplying them with the dy/dt bounds, which reverses the comparison when a dy/dt bound is negative. When rounding leaves a curve's first control point just below its start point, the minimum dy/dt is slightly negative, and two curves that leave a shared start point toward each other were reported as keeping their left-to-right order. The function now returns false unless both dy/dt bounds are positive. transversal_before reflects its curves and calls transversal_after, so it is fixed too. --- vendor/linesweeper/README.craft.md | 20 +++++---- vendor/linesweeper/SOURCE.json | 6 ++- vendor/linesweeper/src/curve/transverse.rs | 49 +++++++++++++++++++++- 3 files changed, 65 insertions(+), 10 deletions(-) diff --git a/vendor/linesweeper/README.craft.md b/vendor/linesweeper/README.craft.md index f683ca53de..5f0d0fd6cc 100644 --- a/vendor/linesweeper/README.craft.md +++ b/vendor/linesweeper/README.craft.md @@ -1,15 +1,21 @@ # Local linesweeper 0.5.0 copy -This is the crates.io linesweeper 0.5.0 package (MIT OR Apache-2.0) with some files left out and no -file changed. `.cargo_vcs_info.json` names the commit it was packaged from, +This is the crates.io linesweeper 0.5.0 package (MIT OR Apache-2.0) with some files left out and the +local patches listed below. `.cargo_vcs_info.json` names the commit it was packaged from, `824b0791a750f7b27b8edcbb6c6244d0e629875e`. That commit is not in the GitHub repository the manifest names, which is archived; its README says development moved off GitHub. -Every file here except this one and `SOURCE.json` is byte for byte the file in the `.crate` archive. -`SOURCE.json` records the hash of the `.crate` download (`source_archive_sha256`) and, for every file -kept, the hash in the package (`source_sha256`) and the hash here (`sha256`). `upstream_repository` is -null because no public repository this copy can name holds `upstream_revision`. `local_patches` is -empty. +Every file here except this one, `SOURCE.json` and the patched files below is byte for byte the file +in the `.crate` archive. `SOURCE.json` records the hash of the `.crate` download +(`source_archive_sha256`) and, for every file kept, the hash in the package (`source_sha256`) and the +hash here (`sha256`). `upstream_repository` is null because no public repository this copy can name +holds `upstream_revision`. `local_patches` describes each local patch. + +## Local patches + +| File | Change | +|---|---| +| `src/curve/transverse.rs` | `transversal_after` returns `false` when either dy/dt bound it divides by is zero, negative or nan. It compared the two slope bounds by cross-multiplying, which reverses the comparison when a bound is negative. Two curves that leave a shared start point in opposite directions, with their first control points one ulp below the start, were reported as keeping their left-to-right order although they cross. `transversal_before` reflects its curves and calls `transversal_after`, so it returned the same wrong answer. The `crossing_with_negative_start_dy` test checks both functions. | `omitted_files` lists the 43 files of the package left out here, with their hashes: diff --git a/vendor/linesweeper/SOURCE.json b/vendor/linesweeper/SOURCE.json index 9c71e51add..98d72030b5 100644 --- a/vendor/linesweeper/SOURCE.json +++ b/vendor/linesweeper/SOURCE.json @@ -7,7 +7,9 @@ "upstream_repository": null, "upstream_revision": "824b0791a750f7b27b8edcbb6c6244d0e629875e", "upstream_directory": "", - "local_patches": [], + "local_patches": [ + "In `src/curve/transverse.rs`, `transversal_after` (and `transversal_before`, which calls it) returns `false` when either dy/dt bound is not positive, instead of cross-multiplying the slope bounds, which reverses the comparison for a negative bound." + ], "files": [ { "path": ".cargo_vcs_info.json", "source_sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc", "source_git_blob": null, "sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc" }, { "path": ".gitignore", "source_sha256": "88b59092499ae05234330eb7d0b01e953e969caf05261530e3765eef02536cf0", "source_git_blob": null, "sha256": "88b59092499ae05234330eb7d0b01e953e969caf05261530e3765eef02536cf0" }, @@ -34,7 +36,7 @@ { "path": "src/curve/line.rs", "source_sha256": "07aebead4b0050410a3f9f28b66062b6016c115df58e2b2669470263cd352f3e", "source_git_blob": null, "sha256": "07aebead4b0050410a3f9f28b66062b6016c115df58e2b2669470263cd352f3e" }, { "path": "src/curve/mod.rs", "source_sha256": "36a8dbe96ac1d3bec307dc63b504206ec7fdfc11d10799fbb1a8990c29b8c5f2", "source_git_blob": null, "sha256": "36a8dbe96ac1d3bec307dc63b504206ec7fdfc11d10799fbb1a8990c29b8c5f2" }, { "path": "src/curve/split_quad.rs", "source_sha256": "b8aae4ce7c16fa623724f667e1058130a9c7eed693b5b01e8b9e16632b8ec45f", "source_git_blob": null, "sha256": "b8aae4ce7c16fa623724f667e1058130a9c7eed693b5b01e8b9e16632b8ec45f" }, - { "path": "src/curve/transverse.rs", "source_sha256": "be9c695531f4cb0fe73af13e78040b51b9476c193d84562e701aadd07b3fd06e", "source_git_blob": null, "sha256": "be9c695531f4cb0fe73af13e78040b51b9476c193d84562e701aadd07b3fd06e" }, + { "path": "src/curve/transverse.rs", "source_sha256": "be9c695531f4cb0fe73af13e78040b51b9476c193d84562e701aadd07b3fd06e", "source_git_blob": null, "sha256": "e1b8658f2b6e0e502bc81d16c393a16a426b6cc1572477ca809ca861fc005de9" }, { "path": "src/generators.rs", "source_sha256": "cc9f2441546db9204219294c354449809dda77dffad06fec8a30f45df01e6fef", "source_git_blob": null, "sha256": "cc9f2441546db9204219294c354449809dda77dffad06fec8a30f45df01e6fef" }, { "path": "src/geom.rs", "source_sha256": "9878ffa6d4a13fa2c9149741c137205ca01acb626a5b9f86a3db75cf91b63a08", "source_git_blob": null, "sha256": "9878ffa6d4a13fa2c9149741c137205ca01acb626a5b9f86a3db75cf91b63a08" }, { "path": "src/lib.rs", "source_sha256": "761c153c3b5c449569ff85c571344b9252ea64f7f0b0424fb4819041b03d13c6", "source_git_blob": null, "sha256": "761c153c3b5c449569ff85c571344b9252ea64f7f0b0424fb4819041b03d13c6" }, diff --git a/vendor/linesweeper/src/curve/transverse.rs b/vendor/linesweeper/src/curve/transverse.rs index be3a96fffa..0432e0505c 100644 --- a/vendor/linesweeper/src/curve/transverse.rs +++ b/vendor/linesweeper/src/curve/transverse.rs @@ -88,7 +88,15 @@ pub fn transversal_after(left: CubicBez, right: CubicBez, y1: f64) -> bool { quad_max_between(r2.y, r1.y, r0.y, 0.0..=t1_right) }; - left_max_dx_dt * right_dy_dt < right_min_dx_dt * left_dy_dt + // We want `left_max_dx_dt / left_dy_dt < right_min_dx_dt / right_dy_dt`. + // Multiplying out keeps the direction of that inequality only when both + // dy/dt bounds are positive. A bound at or below zero (for example after + // rounding leaves a control point slightly below the start) does not bound + // the slope at all, so we give the conservative answer. Writing the test + // as `> 0.0` also returns `false` for nan. + left_dy_dt > 0.0 + && right_dy_dt > 0.0 + && left_max_dx_dt * right_dy_dt < right_min_dx_dt * left_dy_dt } pub fn transversal_before(left: CubicBez, right: CubicBez, y0: f64) -> bool { @@ -186,4 +194,43 @@ mod tests { assert!(transversal_after(left, right, 0.01)); } + + // Two curves that leave the same start point in opposite directions, the + // left one to the right and the right one to the left, so they cross right + // after the start. Their first control points are at `p1_y`. + fn crossing_pair(p1_y: f64) -> (CubicBez, CubicBez) { + let left = CubicBez { + p0: (0., 1.).into(), + p1: (1., p1_y).into(), + p2: (2., 2.).into(), + p3: (3., 3.).into(), + }; + let right = CubicBez { + p0: (0., 1.).into(), + p1: (-1., p1_y).into(), + p2: (-2., 2.).into(), + p3: (-3., 3.).into(), + }; + (left, right) + } + + #[test] + fn crossing_with_negative_start_dy() { + let one_below = 1.0f64.next_down(); + for p1_y in [1.0 - 1e-6, 1.0 - 1e-12, one_below, 1.0, 1.0f64.next_up()] { + let (left, right) = crossing_pair(p1_y); + assert!(!transversal_after(left, right, 1.5), "p1.y = {p1_y:e}"); + } + + // The same pair reflected in y, so that the last control points are + // slightly above the end. + let reflect = |c: CubicBez| CubicBez { + p0: (c.p3.x, -c.p3.y).into(), + p1: (c.p2.x, -c.p2.y).into(), + p2: (c.p1.x, -c.p1.y).into(), + p3: (c.p0.x, -c.p0.y).into(), + }; + let (left, right) = crossing_pair(one_below); + assert!(!transversal_before(reflect(left), reflect(right), -1.5)); + } } From 78867caa87c53c758a6fe1147b4661140c168bb1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 9 Nov 2026 06:11:48 -0800 Subject: [PATCH 006/322] linesweeper: the crossing-height bounds in docs/sweep.typ use absolute inverse slopes Slopes can be negative, so the lemma's bound and the later bound on the crossing height take the absolute values of 1/m_alpha and 1/m_beta, as the proof's inverse-slope bound requires. --- vendor/linesweeper/README.craft.md | 3 ++- vendor/linesweeper/SOURCE.json | 4 ++-- vendor/linesweeper/docs/sweep.typ | 6 +++--- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/vendor/linesweeper/README.craft.md b/vendor/linesweeper/README.craft.md index afd7fbccb5..907075aa4a 100644 --- a/vendor/linesweeper/README.craft.md +++ b/vendor/linesweeper/README.craft.md @@ -15,7 +15,8 @@ and, for every file kept, the hash in the package (`source_sha256`) and the hash the starting gap `beta(y_0) - alpha(y_0)` by the sum of both gaps. With the ending gap `alpha(y_1) - beta(y_1)` as the numerator, gaps of 1 and 3 gave `t = 0.75`, while the segments cross at `t = 0.25`. The proof's inverse-slope difference is `d/(y_1 - y_0)`; the package has - `d/(y_1 - y_1)`, whose denominator is zero. + `d/(y_1 - y_1)`, whose denominator is zero. The lemma's bound and the later bound on the crossing + height use the absolute values of `1/m_alpha` and `1/m_beta`, because the slopes can be negative. `omitted_files` lists the 43 files of the package left out here, with their hashes: diff --git a/vendor/linesweeper/SOURCE.json b/vendor/linesweeper/SOURCE.json index a46d783d4f..30a10c2685 100644 --- a/vendor/linesweeper/SOURCE.json +++ b/vendor/linesweeper/SOURCE.json @@ -8,7 +8,7 @@ "upstream_revision": "824b0791a750f7b27b8edcbb6c6244d0e629875e", "upstream_directory": "", "local_patches": [ - "In `docs/sweep.typ`, the crossing-height lemma and its proof use the starting gap `beta(y_0) - alpha(y_0)` as the numerator of `t`, instead of the ending gap `alpha(y_1) - beta(y_1)`, so that `y_0 + t(y_1 - y_0)` is the height where the segments cross, and the proof's inverse-slope difference is `d/(y_1 - y_0)` instead of `d/(y_1 - y_1)`." + "In `docs/sweep.typ`, the crossing-height lemma and its proof use the starting gap `beta(y_0) - alpha(y_0)` as the numerator of `t`, instead of the ending gap `alpha(y_1) - beta(y_1)`, so that `y_0 + t(y_1 - y_0)` is the height where the segments cross, and the proof's inverse-slope difference is `d/(y_1 - y_0)` instead of `d/(y_1 - y_1)`. The lemma's bound and the later bound on the crossing height use the absolute values of the inverse slopes, because the slopes can be negative." ], "files": [ { "path": ".cargo_vcs_info.json", "source_sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc", "source_git_blob": null, "sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc" }, @@ -23,7 +23,7 @@ { "path": "benches/linebender_logo.rs", "source_sha256": "d10867f43439d37f0e1da5d30eaed9ab3bfbe655ed47212f65dc20ab4db65cb3", "source_git_blob": null, "sha256": "d10867f43439d37f0e1da5d30eaed9ab3bfbe655ed47212f65dc20ab4db65cb3" }, { "path": "benches/painted_dreams.rs", "source_sha256": "073008db93840d380710e13ed3ae38e08cb823f10c12e5f838dac1ccf37eaecf", "source_git_blob": null, "sha256": "073008db93840d380710e13ed3ae38e08cb823f10c12e5f838dac1ccf37eaecf" }, { "path": "benches/synthetic.rs", "source_sha256": "7ce59bef2e1c4f28b00cb89feb15bc71ca4b098a8d27e7b02ea699aca9bcc810", "source_git_blob": null, "sha256": "7ce59bef2e1c4f28b00cb89feb15bc71ca4b098a8d27e7b02ea699aca9bcc810" }, - { "path": "docs/sweep.typ", "source_sha256": "4766082c8672a7bb4356b5581043489c13b4e3fb8931ba3a5f0a473fab0172f3", "source_git_blob": null, "sha256": "db1f41677594b44c5e3f3db351c525b91cd125b07f1f945ed2f0e17d35b5bad3" }, + { "path": "docs/sweep.typ", "source_sha256": "4766082c8672a7bb4356b5581043489c13b4e3fb8931ba3a5f0a473fab0172f3", "source_git_blob": null, "sha256": "56da7b931e85da5353608950f609a4a4e5d6fea1f231b6413ad9b8c7ed8b9bcb" }, { "path": "examples/boolean_op.rs", "source_sha256": "3b38a1ccda7e736cce4b191a3a45ab4824c4c365190e3eb637b2fb39b5996c9f", "source_git_blob": null, "sha256": "3b38a1ccda7e736cce4b191a3a45ab4824c4c365190e3eb637b2fb39b5996c9f" }, { "path": "examples/bus.rs", "source_sha256": "e206a08be73899f564188052c8ecc15526b54606e52ee2935a64ce6b5723da33", "source_git_blob": null, "sha256": "e206a08be73899f564188052c8ecc15526b54606e52ee2935a64ce6b5723da33" }, { "path": "examples/curve_metrics.rs", "source_sha256": "0db6a5327fd2119a03a9a66624fea3e04b6bbb519655667ad30487aee6c787d2", "source_git_blob": null, "sha256": "0db6a5327fd2119a03a9a66624fea3e04b6bbb519655667ad30487aee6c787d2" }, diff --git a/vendor/linesweeper/docs/sweep.typ b/vendor/linesweeper/docs/sweep.typ index c915e63b7b..956a50312f 100644 --- a/vendor/linesweeper/docs/sweep.typ +++ b/vendor/linesweeper/docs/sweep.typ @@ -722,7 +722,7 @@ $ Define $t = (beta(y_0) - alpha(y_0)) / (beta(y_0) - alpha(y_0) + alpha(y_1) - beta(y_1))$ and set $y = y_0 + t(y_1 - y_0)$. The natural way to compute $y$ produces an approximation $hat(y)$ satisfying $ -|alpha(hat(y)) - beta(hat(y))| <= 4(epsilon + 2 epsilon_0 M) (1 + max(1/m_alpha, 1/m_beta)), +|alpha(hat(y)) - beta(hat(y))| <= 4(epsilon + 2 epsilon_0 M) (1 + max(1/abs(m_alpha), 1/abs(m_beta))), $ where $m_alpha$ and $m_beta$ are the slopes of $alpha$ and $beta$. ] @@ -790,7 +790,7 @@ $ If we assume that $16 (epsilon + 2 epsilon_0 M) / d <= 3$ then $epsilon_t d <= 4 epsilon + 8 epsilon_0 M$. Since $d/(y_1 - y_0)$ is the difference of the inverse-slopes of $alpha$ and $beta$, it's bounded by twice -the maximum of these inverse-slopes. +the maximum absolute value of these inverse-slopes. ] Putting all this together (and handling the "chamfers" yet): @@ -802,7 +802,7 @@ and take $delta = 64 epsilon_0 M$. If $epsilon_0 <= 1/4$ then - If $alpha$ $(3 delta)/4$-crosses $beta$, we can compute a crossing height $hat(y)$ such that $ - |alpha(hat(y)) - beta(hat(y))| <= (9 delta) /16 (1 + max(1/m_alpha, 1/m_beta)). + |alpha(hat(y)) - beta(hat(y))| <= (9 delta) /16 (1 + max(1/abs(m_alpha), 1/abs(m_beta))). $ ] From 72ad73223571a90b61c2a14186f73800c75e9073 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 21:44:12 -0800 Subject: [PATCH 007/322] craft-docx: read and write the hide spelling and grammar errors settings Settings gains hide_spelling_errors and hide_grammar_errors, the per-document Hide spelling errors and Hide grammar errors options. craft-docx reads w:hideSpellingErrors and w:hideGrammaticalErrors from settings.xml, writes them after w:mirrorMargins and before w:proofState, and lists them as owned in the settings merge, so a saved file carries each one once and drops it when it is turned off. --- crates/docx/src/read/meta.rs | 2 ++ crates/docx/src/write/settings.rs | 7 ++++ crates/docx/src/write/settings_merge.rs | 2 ++ crates/docx/tests/it/settings_merge.rs | 47 +++++++++++++++++++++++++ crates/wordmodel/src/settings.rs | 9 +++++ 5 files changed, 67 insertions(+) diff --git a/crates/docx/src/read/meta.rs b/crates/docx/src/read/meta.rs index bb4804e0d2..fa5ef62efb 100644 --- a/crates/docx/src/read/meta.rs +++ b/crates/docx/src/read/meta.rs @@ -24,6 +24,8 @@ impl Reader<'_> { "w:linkStyles" => s.link_styles = on_off(k), "w:removePersonalInformation" => s.remove_personal_info = on_off(k), "w:removeDateAndTime" => s.remove_date_time = on_off(k), + "w:hideSpellingErrors" => s.hide_spelling_errors = on_off(k), + "w:hideGrammaticalErrors" => s.hide_grammar_errors = on_off(k), "w:compat" => { s.allow_space_of_same_style_in_table = k.child("w:allowSpaceOfSameStyleInTable").is_some_and(on_off); // Only Word's own setting: another `w:uri` names a different application's. diff --git a/crates/docx/src/write/settings.rs b/crates/docx/src/write/settings.rs index 18f9f8239f..53fbe2be48 100644 --- a/crates/docx/src/write/settings.rs +++ b/crates/docx/src/write/settings.rs @@ -50,6 +50,13 @@ pub(super) fn settings_xml(doc: &Document, footnotes: bool, endnotes: bool, temp if s.mirror_margins { w.empty("w:mirrorMargins", &[]); } + // After `w:gutterAtTop` and before `w:proofState` in CT_Settings. + if s.hide_spelling_errors { + w.empty("w:hideSpellingErrors", &[]); + } + if s.hide_grammar_errors { + w.empty("w:hideGrammaticalErrors", &[]); + } if let Some(id) = template_rel { w.empty("w:attachedTemplate", &[("r:id", id)]); } diff --git a/crates/docx/src/write/settings_merge.rs b/crates/docx/src/write/settings_merge.rs index 981b9c0988..1b9ef69980 100644 --- a/crates/docx/src/write/settings_merge.rs +++ b/crates/docx/src/write/settings_merge.rs @@ -18,6 +18,8 @@ const OWNED: &[&str] = &[ "w:removeDateAndTime", "w:displayBackgroundShape", "w:mirrorMargins", + "w:hideSpellingErrors", + "w:hideGrammaticalErrors", "w:attachedTemplate", "w:linkStyles", "w:trackRevisions", diff --git a/crates/docx/tests/it/settings_merge.rs b/crates/docx/tests/it/settings_merge.rs index c07986795e..312564626c 100644 --- a/crates/docx/tests/it/settings_merge.rs +++ b/crates/docx/tests/it/settings_merge.rs @@ -163,3 +163,50 @@ fn do_not_track_moves_round_trips() { assert!(s.contains(""), "{s}"); assert!(!craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap().settings.track_moves); } + +/// Hide spelling errors and Hide grammar errors in this document only (`w:hideSpellingErrors`, +/// `w:hideGrammaticalErrors`) are read, written once each (before `w:proofState` in a merged +/// part), written in a generated part, and left out when they are turned off. +#[test] +fn hidden_proofing_errors_round_trip() { + let original = SETTINGS.replace("") < pos(&s, "")); + assert!(pos(&s, "") < pos(&s, ""), "{s}"); + assert!(pos(&s, "") < pos(&s, "") && !s.contains("hideSpellingErrors"), "{s}"); + let back = craft_docx::read(&craft_docx::write(&doc).unwrap()).unwrap(); + assert!(back.settings.hide_grammar_errors && !back.settings.hide_spelling_errors); +} diff --git a/crates/wordmodel/src/settings.rs b/crates/wordmodel/src/settings.rs index 67be5590a1..9ab03f2414 100644 --- a/crates/wordmodel/src/settings.rs +++ b/crates/wordmodel/src/settings.rs @@ -166,6 +166,13 @@ pub struct Settings { /// comments and tracked changes are saved without `w:date`. #[serde(skip_serializing_if = "std::ops::Not::not")] pub remove_date_time: bool, + /// Hide spelling errors in this document only (`w:hideSpellingErrors`): no squiggles under + /// misspelled words. Spelling & Grammar (F7) still finds them. + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub hide_spelling_errors: bool, + /// Hide grammar errors in this document only (`w:hideGrammaticalErrors`). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub hide_grammar_errors: bool, /// The document was opened from ODF: the standard's rules that differ from Word's apply as /// it is laid out. #[serde(skip_serializing_if = "Option::is_none")] @@ -328,6 +335,8 @@ impl Default for Settings { zoom: None, remove_personal_info: false, remove_date_time: false, + hide_spelling_errors: false, + hide_grammar_errors: false, odf: None, } } From 87bbc1c711398b307c195b604cb6fdfe8a570a60 Mon Sep 17 00:00:00 2001 From: Zach Shallbetter Date: Fri, 16 Oct 2026 13:51:16 -0700 Subject: [PATCH 008/322] craft-testkit: add source-level platform regression guards (closes #139) Add craft-testkit with source guards for platform rules that broke before: - predefined_quit: flags calls of muda PredefinedMenuItem::quit that bypass dirty document save prompts and window teardown on macOS. - wgsl_float_literals: scans WGSL shaders using PhotoCraft's decimal float scanner and flags literals exceeding f32 finite range that fail on WebGPU compilers (Tint). - std_instant: flags lines naming std::time::Instant without web_time in code running on the web, preventing wasm32 runtime panics. - rust_sources: directory crawler discovering a crate's .rs sources while excluding test files and test directories. --- Cargo.lock | 4 + Cargo.toml | 1 + crates/testkit/Cargo.toml | 13 + crates/testkit/README.md | 79 ++++++ crates/testkit/src/guards.rs | 465 +++++++++++++++++++++++++++++++++ crates/testkit/src/lib.rs | 32 +++ crates/testkit/tests/guards.rs | 330 +++++++++++++++++++++++ 7 files changed, 924 insertions(+) create mode 100644 crates/testkit/Cargo.toml create mode 100644 crates/testkit/README.md create mode 100644 crates/testkit/src/guards.rs create mode 100644 crates/testkit/src/lib.rs create mode 100644 crates/testkit/tests/guards.rs diff --git a/Cargo.lock b/Cargo.lock index 3d8cf4a7b3..7b8d513e3b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2569,6 +2569,10 @@ dependencies = [ "kurbo 0.13.1", ] +[[package]] +name = "craft-testkit" +version = "0.1.0" + [[package]] name = "craft-text" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 576efca6f1..fab6b70440 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -138,6 +138,7 @@ craft-stencilcraft-format = { path = "crates/stencilcraft-format" } craft-stencilcraft-document = { path = "crates/stencilcraft-document" } craft-svg-paths = { path = "crates/svg-paths" } craft-stream-codecs = { path = "crates/stream-codecs" } +craft-testkit = { path = "crates/testkit" } craft-text = { path = "crates/text" } craft-texture = { path = "crates/texture" } craft-tga = { path = "crates/tga" } diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml new file mode 100644 index 0000000000..d2a3b3179f --- /dev/null +++ b/crates/testkit/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "craft-testkit" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true +description = "Source-level platform regression guards and verification utilities for the Craft application suite" + +[dependencies] + +[lints] +workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md new file mode 100644 index 0000000000..d7208396b6 --- /dev/null +++ b/crates/testkit/README.md @@ -0,0 +1,79 @@ +# craft-testkit + +Source-level platform regression guards and verification utilities for the Craft application suite. + +## Overview + +`craft-testkit` provides lightweight, non-panicking source guards that prevent applications in the Craft ecosystem from repeating platform defects that were previously diagnosed and resolved in peer applications: + +1. **`predefined_quit`**: Flags direct calls to `muda`'s `PredefinedMenuItem::quit` outside comments. On macOS, this predefined menu item routes directly to `NSApplication terminate:`, completely bypassing application dirty document checks and unsaved changes save prompts. Applications should instead wire Quit through `craft-quit` lifecycle interceptors. +2. **`wgsl_float_literals` / `wgsl_float_literals_in`**: Scans WGSL shader sources using PhotoCraft's decimal float scanner and flags literals whose absolute value exceeds `f32::MAX` (such as `3.40282347e38`). While native compilers (`naga`) round these down, browser WebGPU compilers (`Tint` in Chromium) reject them with fatal pipeline compilation errors, forcing applications into CPU fallback rendering. Exact values equal to `f32::MAX` must be written as exact hex float literals (`0x1.fffffep+127f`). +3. **`std_instant`**: Flags lines naming `std::time::Instant` outside comments without `web_time`. On `wasm32-unknown-unknown`, `std::time::Instant::now()` panics at runtime with `"time not implemented on this platform"`. Code targeting the web must use `web_time::Instant`. +4. **`rust_sources`**: Recursively discovers a crate's `.rs` source files while excluding integration tests (`tests/`), test modules (`tests.rs`, `tests_*.rs`, `*_tests.rs`, `*_test.rs`), and build artifacts (`target/`, `.git/`). + +## Epistemic Scope: Syntactic Guards vs Runtime Validation + +Source-level guards provide deterministic syntactic evidence about codebase structure: + +### What They Establish +- Checked source files do not contain forbidden symbol invocations, known out-of-range literal representations, or platform-hazardous imports. +- Reusable, deterministic checks that run in milliseconds as regular Cargo tests without external runners. + +### What They Cannot Establish +- **Runtime execution safety**: Syntactic checks do not verify whether code branches actually execute at runtime. +- **Semantic type resolution**: The scanners do not resolve arbitrary type aliases (e.g. `use std::time as t; t::Instant::now()`) or expand procedural macros. +- **Complex target predicates**: While `std_instant` recognizes direct item-level non-wasm target conditions (e.g. `#[cfg(not(target_arch = "wasm32"))]`), it does not evaluate arbitrary multi-crate boolean expressions. Applications should scope `std_instant` tests to the specific crates that compile into their web distribution. +- **Driver and host OS behavior**: Syntactic checks do not verify WebGPU driver compatibility or host window manager event dispatch. + +Source guards serve as fast, zero-dependency regression gates in application test suites, complementing platform integration tests and CI workflows. + +## Consumer Adoption Examples + +### 1. PhotoCraft: Adopt `wgsl_float_literals` and `predefined_quit` + +In `photocraft/crates/gpu/src/lib.rs`, replace the in-tree `decimal_float_literals` helper with `craft_testkit::wgsl_float_literals`: + +```rust +#[test] +fn shader_float_literals_fit_f32() { + let bad = craft_testkit::wgsl_float_literals(SHADER); + assert!( + bad.is_empty(), + "float literals outside f32 finite range reject on WebGPU (Tint):\n{}", + bad.iter().map(|f| f.to_string()).collect::>().join("\n") + ); +} +``` + +In `photocraft/apps/photocraft/tests/native_menu_tests.rs`: + +```rust +#[test] +fn no_unintercepted_predefined_quit_in_menu() { + let sources = craft_testkit::rust_sources("src").expect("scan sources"); + let findings = craft_testkit::predefined_quit(&sources); + assert!( + findings.is_empty(), + "predefined muda Quit bypasses dirty document save prompts:\n{}", + findings.iter().map(|f| f.to_string()).collect::>().join("\n") + ); +} +``` + +### 2. FilmCraft: Adopt `std_instant` and `wgsl_float_literals` + +In `filmcraft/crates/engine/src/wasm_clock_tests.rs`, replace in-tree textual search with `craft_testkit::std_instant`: + +```rust +#[test] +fn no_std_instant_in_code_the_web_build_runs() { + let sources = craft_testkit::rust_sources(Path::new(env!("CARGO_MANIFEST_DIR")).join("src")) + .expect("scan engine sources"); + let findings = craft_testkit::std_instant(&sources); + assert!( + findings.is_empty(), + "std::time::Instant panics on wasm32; use web_time::Instant:\n{}", + findings.iter().map(|f| f.to_string()).collect::>().join("\n") + ); +} +``` diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs new file mode 100644 index 0000000000..2f8c50d234 --- /dev/null +++ b/crates/testkit/src/guards.rs @@ -0,0 +1,465 @@ +//! Platform regression guards checking source code for known defects and lifecycle hazards. + +use std::fmt; +#[cfg(not(target_arch = "wasm32"))] +use std::path::Path; + +/// A diagnostic finding reported by a source guard. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Finding { + /// File path where the violation was detected. + pub path: String, + /// 1-based line number of the violation. + pub line: usize, + /// Diagnostic context (the offending code snippet or float literal). + pub text: String, +} + +impl Finding { + /// Create a new diagnostic finding. + pub fn new(path: impl Into, line: usize, text: impl Into) -> Self { + Self { path: path.into(), line, text: text.into() } + } +} + +impl fmt::Display for Finding { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.path.is_empty() { write!(f, "{}: {}", self.line, self.text) } else { write!(f, "{}:{}: {}", self.path, self.line, self.text) } + } +} + +/// Abstraction over a source file path and its text content. +pub trait AsFileSource { + /// Path of the source file. + fn path(&self) -> &str; + /// Text content of the source file. + fn content(&self) -> &str; +} + +impl AsFileSource for (String, String) { + fn path(&self) -> &str { + &self.0 + } + fn content(&self) -> &str { + &self.1 + } +} + +impl AsFileSource for &(String, String) { + fn path(&self) -> &str { + &self.0 + } + fn content(&self) -> &str { + &self.1 + } +} + +impl AsFileSource for (&str, &str) { + fn path(&self) -> &str { + self.0 + } + fn content(&self) -> &str { + self.1 + } +} + +impl AsFileSource for &(&str, &str) { + fn path(&self) -> &str { + self.0 + } + fn content(&self) -> &str { + self.1 + } +} + +impl AsFileSource for (String, &str) { + fn path(&self) -> &str { + &self.0 + } + fn content(&self) -> &str { + self.1 + } +} + +impl AsFileSource for &(String, &str) { + fn path(&self) -> &str { + &self.0 + } + fn content(&self) -> &str { + self.1 + } +} + +impl AsFileSource for (&str, String) { + fn path(&self) -> &str { + self.0 + } + fn content(&self) -> &str { + &self.1 + } +} + +impl AsFileSource for &(&str, String) { + fn path(&self) -> &str { + self.0 + } + fn content(&self) -> &str { + &self.1 + } +} + +/// Replace code comments and string literals with whitespace while preserving newlines and line counts. +/// +/// Handles single-line comments (`//`), block comments (`/* ... */`, including nested comments), +/// normal string literals (`"..."`), and raw string literals (`r#"..."#`). +fn mask_comments_and_strings(code: &str) -> String { + let mut out = String::with_capacity(code.len()); + let chars: Vec = code.chars().collect(); + let len = chars.len(); + let mut i = 0; + let mut in_line_comment = false; + let mut block_comment_depth: usize = 0; + let mut in_normal_string = false; + let mut raw_string_hashes: Option = None; + let mut escape = false; + + while i < len { + let c = chars[i]; + if in_line_comment { + if c == '\n' { + in_line_comment = false; + out.push('\n'); + } else { + out.push(' '); + } + i += 1; + } else if block_comment_depth > 0 { + if c == '*' && i + 1 < len && chars[i + 1] == '/' { + block_comment_depth = block_comment_depth.saturating_sub(1); + out.push(' '); + out.push(' '); + i += 2; + } else if c == '/' && i + 1 < len && chars[i + 1] == '*' { + block_comment_depth = block_comment_depth.saturating_add(1); + out.push(' '); + out.push(' '); + i += 2; + } else if c == '\n' { + out.push('\n'); + i += 1; + } else { + out.push(' '); + i += 1; + } + } else if let Some(hashes) = raw_string_hashes { + if c == '"' { + let mut match_hashes = true; + if i + hashes < len { + for h in 0..hashes { + if chars[i + 1 + h] != '#' { + match_hashes = false; + break; + } + } + } else { + match_hashes = false; + } + if match_hashes { + raw_string_hashes = None; + for _ in 0..=hashes { + out.push(' '); + } + i += 1 + hashes; + continue; + } + } + if c == '\n' { + out.push('\n'); + } else { + out.push(' '); + } + i += 1; + } else if in_normal_string { + if escape { + escape = false; + out.push(' '); + } else if c == '\\' { + escape = true; + out.push(' '); + } else if c == '"' { + in_normal_string = false; + out.push(' '); + } else if c == '\n' { + out.push('\n'); + } else { + out.push(' '); + } + i += 1; + } else { + if c == '/' && i + 1 < len && chars[i + 1] == '/' { + in_line_comment = true; + out.push(' '); + out.push(' '); + i += 2; + } else if c == '/' && i + 1 < len && chars[i + 1] == '*' { + block_comment_depth = 1; + out.push(' '); + out.push(' '); + i += 2; + } else if c == '"' { + in_normal_string = true; + out.push(' '); + i += 1; + } else if c == 'r' && i + 1 < len && (chars[i + 1] == '"' || chars[i + 1] == '#') { + let mut j = i + 1; + let mut hashes = 0; + while j < len && chars[j] == '#' { + hashes += 1; + j += 1; + } + if j < len && chars[j] == '"' { + raw_string_hashes = Some(hashes); + for _ in i..=j { + out.push(' '); + } + i = j + 1; + } else { + out.push(c); + i += 1; + } + } else { + out.push(c); + i += 1; + } + } + } + out +} + +/// Guard: detects direct calls to `muda`'s predefined Quit menu item. +/// +/// Using `PredefinedMenuItem::quit` connects the macOS menu directly to `NSApplication terminate:`, +/// which bypasses dirty document checks, unsaved changes save prompts, and lifecycle cleanup. +/// Applications should route Quit through custom menu items or interceptors connected to `craft-quit`. +pub fn predefined_quit(files: I) -> Vec +where + I: IntoIterator, + I::Item: AsFileSource, +{ + let mut findings = Vec::new(); + for file in files { + let path = file.path(); + let content = file.content(); + let masked = mask_comments_and_strings(content); + + for (orig_line, (idx, masked_line)) in content.lines().zip(masked.lines().enumerate()) { + let normalized = masked_line.replace(' ', ""); + if normalized.contains("PredefinedMenuItem::quit") || normalized.contains("PredefinedMenuItem::Quit") { + findings.push(Finding::new(path, idx + 1, orig_line.trim())); + } + } + } + findings +} + +/// Guard: detects uses of `std::time::Instant` outside comments in code paths running on the web. +/// +/// On `wasm32-unknown-unknown`, `std::time::Instant::now()` panics with "time not implemented +/// on this platform". Crates running in the browser should use `web_time::Instant`, which maps to +/// `std::time::Instant` on native platforms and `performance.now()` on the web. +/// +/// ### Syntactic Scope and Limitations +/// +/// * **Targeted files**: Callers should pass files from crates that compile into the application's web build. +/// * **Allowed patterns**: Comments, string literals, lines containing `web_time`, and items decorated with +/// explicit non-wasm target conditions (e.g. `#[cfg(not(target_arch = "wasm32"))]` or `#[cfg(target_os = ...)]`) +/// are skipped. +/// * **Limitations**: This is a lexical source guard. It does not perform semantic type resolution, macro +/// expansion, or track arbitrary module aliases (e.g. `use std::time as t; t::Instant`). +pub fn std_instant(files: I) -> Vec +where + I: IntoIterator, + I::Item: AsFileSource, +{ + let mut findings = Vec::new(); + for file in files { + let path = file.path(); + let content = file.content(); + let masked = mask_comments_and_strings(content); + + let mut in_cfg_non_wasm = false; + let mut cfg_brace_depth: usize = 0; + + for (orig_line, (idx, masked_line)) in content.lines().zip(masked.lines().enumerate()) { + let is_comment_only = masked_line.trim().is_empty(); + let line_has_cfg_non_wasm = !is_comment_only + && (orig_line.contains("cfg(not(target_arch = \"wasm32\"))") + || orig_line.contains("cfg(target_arch = \"x86_64\")") + || orig_line.contains("cfg(target_arch = \"aarch64\")") + || orig_line.contains("cfg(target_os =")); + + if line_has_cfg_non_wasm { + in_cfg_non_wasm = true; + } + + let names_std_instant = + masked_line.contains("time::Instant") || (masked_line.contains("use std::time::") && masked_line.contains("Instant")); + + if names_std_instant && !masked_line.contains("web_time") && !in_cfg_non_wasm { + findings.push(Finding::new(path, idx + 1, orig_line.trim())); + } + + if in_cfg_non_wasm && !is_comment_only { + let opens = masked_line.chars().filter(|&c| c == '{').count(); + let closes = masked_line.chars().filter(|&c| c == '}').count(); + if cfg_brace_depth == 0 { + if opens > 0 { + cfg_brace_depth = cfg_brace_depth.saturating_add(opens).saturating_sub(closes); + if cfg_brace_depth == 0 { + in_cfg_non_wasm = false; + } + } else if masked_line.contains(';') { + in_cfg_non_wasm = false; + } + } else { + cfg_brace_depth = cfg_brace_depth.saturating_add(opens).saturating_sub(closes); + if cfg_brace_depth == 0 { + in_cfg_non_wasm = false; + } + } + } + } + } + findings +} + +/// Guard: scans a single WGSL shader string and detects decimal float literals outside `f32`'s finite range. +/// +/// Browser WebGPU compilers (such as Chrome's Tint) reject float literals exceeding `f32::MAX` +/// (e.g. `3.40282347e38`), triggering fatal pipeline build errors and fallback to CPU rendering. +/// Exact values equal to `f32::MAX` should be written as hex float literals (e.g. `0x1.fffffep+127f`). +/// +/// ### Policy and Limitations +/// +/// * **Conservative mathematical bound**: The guard evaluates the parsed mathematical magnitude against +/// `f64::from(f32::MAX)`. Any decimal literal exceeding this threshold is flagged, even if native +/// compilers like `naga` would round it down to `f32::MAX`. +/// * **Hexadecimal floats**: Exact hex float literals (`0x...p...`) are skipped as they represent exact bit patterns. +/// * **Comments and strings**: Comments (`//` and `/* ... */`) and string contents are masked out prior to scanning. +pub fn wgsl_float_literals(wgsl: &str) -> Vec { + wgsl_float_literals_in([("", wgsl)]) +} + +/// Guard: scans multiple WGSL shader files and detects decimal float literals outside `f32`'s finite range. +pub fn wgsl_float_literals_in(files: I) -> Vec +where + I: IntoIterator, + I::Item: AsFileSource, +{ + let mut findings = Vec::new(); + for file in files { + let path = file.path(); + let content = file.content(); + let masked = mask_comments_and_strings(content); + + for (n, line) in masked.lines().enumerate() { + let code = line.as_bytes(); + let mut i = 0; + while i < code.len() { + let digit_or_dot = code[i].is_ascii_digit() || (code[i] == b'.' && code.get(i + 1).is_some_and(u8::is_ascii_digit)); + let word_before = i > 0 && (code[i - 1].is_ascii_alphanumeric() || code[i - 1] == b'_' || code[i - 1] == b'.'); + if !digit_or_dot || word_before { + i += 1; + continue; + } + // Skip hex float literals (e.g. 0x1.fffffep+127f, 0x1.0p0h) + if code[i] == b'0' && matches!(code.get(i + 1), Some(b'x' | b'X')) { + i += 2; + while i < code.len() && (code[i].is_ascii_hexdigit() || matches!(code[i], b'.' | b'p' | b'P' | b'+' | b'-' | b'f' | b'h')) { + i += 1; + } + continue; + } + let start = i; + while i < code.len() && (code[i].is_ascii_digit() || code[i] == b'.') { + i += 1; + } + if i < code.len() && matches!(code[i], b'e' | b'E') { + let mut j = i + 1; + if j < code.len() && matches!(code[j], b'+' | b'-') { + j += 1; + } + if j < code.len() && code[j].is_ascii_digit() { + i = j; + while i < code.len() && code[i].is_ascii_digit() { + i += 1; + } + } + } + let literal = String::from_utf8_lossy(&code[start..i]); + if i < code.len() && matches!(code[i], b'f' | b'h') { + i += 1; + } + let is_overflow = match literal.parse::() { + Ok(v) => !v.is_finite() || v.abs() > f64::from(f32::MAX), + Err(_) => true, + }; + if is_overflow { + findings.push(Finding::new(path, n + 1, literal.into_owned())); + } + } + } + } + findings +} + +/// Recursively collect all Rust source files under `dir`, excluding test files and test directories. +/// +/// Excluded files: +/// * `tests.rs` +/// * `tests_*.rs` +/// * `*_tests.rs` +/// * `*_test.rs` +/// * `test.rs` +/// * Any file within a directory component named `tests`, `benches`, `examples`, `.git`, or `target`. +/// +/// Results are sorted lexicographically by file path for deterministic behavior across platforms. +#[cfg(not(target_arch = "wasm32"))] +pub fn rust_sources(dir: impl AsRef) -> std::io::Result> { + let root = dir.as_ref(); + let mut files = Vec::new(); + let mut dirs = vec![root.to_path_buf()]; + + while let Some(d) = dirs.pop() { + let entries = std::fs::read_dir(&d)?; + for entry in entries { + let entry = entry?; + let p = entry.path(); + let metadata = std::fs::metadata(&p)?; + if metadata.is_dir() { + let dirname = p.file_name().and_then(|n| n.to_str()).unwrap_or_default(); + if dirname.starts_with('.') || dirname == "target" || dirname == "tests" || dirname == "benches" || dirname == "examples" { + continue; + } + dirs.push(p); + } else if metadata.is_file() { + let name = p.file_name().and_then(|n| n.to_str()).unwrap_or_default(); + if !name.ends_with(".rs") { + continue; + } + if name == "tests.rs" || name.starts_with("tests_") || name.ends_with("_tests.rs") || name.ends_with("_test.rs") || name == "test.rs" + { + continue; + } + if p.components().any(|c| c.as_os_str() == "tests") { + continue; + } + let content = std::fs::read_to_string(&p)?; + files.push((p.display().to_string(), content)); + } + } + } + + files.sort_by(|a, b| a.0.cmp(&b.0)); + Ok(files) +} diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs new file mode 100644 index 0000000000..b0e61fc8b5 --- /dev/null +++ b/crates/testkit/src/lib.rs @@ -0,0 +1,32 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +//! Source-level platform regression guards and verification utilities for the Craft application suite. +//! +//! This crate provides non-panicking source analysis guards that detect known platform hazards +//! and lifecycle regressions across Craft applications: +//! +//! * [`guards::predefined_quit`]: flags direct calls to `muda`'s predefined Quit item that bypass +//! dirty document save prompts and window teardown on macOS. +//! * [`guards::wgsl_float_literals`]: flags decimal float literals exceeding `f32`'s finite range, +//! which break browser WebGPU compilers (Tint) and trigger CPU fallbacks. +//! * [`guards::std_instant`]: flags uses of `std::time::Instant` in code paths targeting the web, +//! where `std::time::Instant::now()` panics on `wasm32`. +//! * [`guards::rust_sources`]: directory crawler collecting `.rs` sources while excluding tests. +//! +//! ### Epistemic Scope: What Source Guards Establish vs What They Cannot +//! +//! Source-level guards provide deterministic syntactic evidence about codebase structure. +//! They establish that checked source files do not contain forbidden symbol names, known invalid +//! literal patterns, or unsafe platform invocations. +//! +//! They do **not** establish runtime correctness, protocol concurrency safety, or platform behavior +//! under foreign host environments. They are lightweight syntactic regression gates designed to complement, +//! rather than replace, platform integration tests and CI execution. + +pub mod guards; + +pub use guards::{Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; + +#[cfg(not(target_arch = "wasm32"))] +pub use guards::rust_sources; diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs new file mode 100644 index 0000000000..ee6daae7d7 --- /dev/null +++ b/crates/testkit/tests/guards.rs @@ -0,0 +1,330 @@ +use craft_testkit::{Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; + +#[test] +fn test_finding_display() { + let f1 = Finding::new("src/menu.rs", 42, "PredefinedMenuItem::quit()"); + assert_eq!(f1.to_string(), "src/menu.rs:42: PredefinedMenuItem::quit()"); + + let f2 = Finding::new("", 156, "3.40282347e38"); + assert_eq!(f2.to_string(), "156: 3.40282347e38"); +} + +#[test] +fn test_predefined_quit_positive() { + let source = r#" +fn setup_menu() { + let quit = PredefinedMenuItem::quit(Some("Quit")); + bar.add(quit); +} +"#; + let findings = predefined_quit([("src/menu.rs", source)]); + assert_eq!(findings.len(), 1); + assert_eq!(findings[0].path, "src/menu.rs"); + assert_eq!(findings[0].line, 3); + assert_eq!(findings[0].text, "let quit = PredefinedMenuItem::quit(Some(\"Quit\"));"); + assert_eq!(findings[0].to_string(), "src/menu.rs:3: let quit = PredefinedMenuItem::quit(Some(\"Quit\"));"); +} + +#[test] +fn test_predefined_quit_negative_and_comments() { + let source = r#" +// PredefinedMenuItem::quit(None) - do not use this! +/* + * PredefinedMenuItem::quit is hazardous + */ +fn setup_menu() { + let sep = PredefinedMenuItem::separator(); + let hide = PredefinedMenuItem::hide(Some("Hide")); + let note = "PredefinedMenuItem::quit in string should not trigger"; +} +"#; + let findings = predefined_quit([("src/safe_menu.rs", source)]); + assert!(findings.is_empty(), "expected zero findings for comments, separators, and strings: {findings:?}"); +} + +/// Historical failure: FilmCraft `apps/filmcraft/src/native_menu.rs:56` +/// used `PredefinedMenuItem::quit`, routing directly to `NSApplication terminate:` and bypassing save prompts. +#[test] +fn test_historical_filmcraft_native_menu_quit_regression() { + let problematic_source = r#" + let predefined = [ + (hide_label, PredefinedMenuItem::hide(Some(app.ui.language.tr(hide_label)))), + (hide_others_label, PredefinedMenuItem::hide_others(Some(app.ui.language.tr(hide_others_label)))), + (quit_label, PredefinedMenuItem::quit(Some(app.ui.language.tr(quit_label)))), + ]; +"#; + let findings = predefined_quit([("apps/filmcraft/src/native_menu.rs", problematic_source)]); + assert_eq!(findings.len(), 1); + assert_eq!(findings[0].line, 5); + assert_eq!(findings[0].text, "(quit_label, PredefinedMenuItem::quit(Some(app.ui.language.tr(quit_label)))),"); + + // Corrected source wires Quit via MenuItem::with_id and craft-quit lifecycle + let corrected_source = r#" + let quit = MenuItem::with_id("app.quit", label("app.quit", "Quit FilmCraft"), true, None); + let predefined = [ + (hide_label, PredefinedMenuItem::hide(Some(app.ui.language.tr(hide_label)))), + (hide_others_label, PredefinedMenuItem::hide_others(Some(app.ui.language.tr(hide_others_label)))), + ]; +"#; + let corrected_findings = predefined_quit([("apps/filmcraft/src/native_menu.rs", corrected_source)]); + assert!(corrected_findings.is_empty()); +} + +#[test] +fn test_std_instant_positive() { + let source = r#" +use std::time::Instant; +use std::time::{Duration, Instant as StdInstant}; + +fn measure() { + let t0 = std::time::Instant::now(); +} +"#; + let findings = std_instant([("src/clock.rs", source)]); + assert_eq!(findings.len(), 3); + assert_eq!(findings[0].line, 2); + assert_eq!(findings[1].line, 3); + assert_eq!(findings[2].line, 6); +} + +#[test] +fn test_std_instant_negative_and_web_time() { + let source = r#" +// std::time::Instant::now() causes wasm panic +/* + use std::time::Instant; +*/ +use web_time::Instant; +use std::time::Duration; + +fn measure() { + let t0 = web_time::Instant::now(); + let d = Duration::from_millis(100); +} +"#; + let findings = std_instant([("src/safe_clock.rs", source)]); + assert!(findings.is_empty(), "expected zero findings for web_time, duration, and comments: {findings:?}"); +} + +/// Historical failure: FilmCraft `crates/engine/src/wasm_clock_tests.rs` +/// jobs running synchronously on wasm32 called `std::time::Instant::now()`, panicking at runtime. +#[test] +fn test_historical_filmcraft_wasm_clock_instant_regression() { + let problematic_source = r#" + use std::time::Instant; + + pub fn run_job() { + let t0 = std::time::Instant::now(); + } +"#; + let findings = std_instant([("crates/engine/src/job.rs", problematic_source)]); + assert_eq!(findings.len(), 2); + + let corrected_source = r#" + use web_time::Instant; + + pub fn run_job() { + let t0 = web_time::Instant::now(); + } +"#; + let corrected_findings = std_instant([("crates/engine/src/job.rs", corrected_source)]); + assert!(corrected_findings.is_empty()); + + // User's specific conditional compilation test case: + let native_guarded_inline = r#" +#[cfg(not(target_arch = "wasm32"))] fn timestamp() -> std::time::Instant { std::time::Instant::now() } +"#; + assert!(std_instant([("src/native.rs", native_guarded_inline)]).is_empty()); + + let native_guarded_multiline = r#" +#[cfg(not(target_arch = "wasm32"))] +fn timestamp() -> std::time::Instant { + std::time::Instant::now() +} +"#; + assert!(std_instant([("src/native.rs", native_guarded_multiline)]).is_empty()); +} + +/// Historical failure: PhotoCraft PR #1722 / #1982 `crates/gpu/src/compose.wgsl:156` +/// `const F32_MAX: f32 = 3.40282347e38;` is slightly above f32::MAX. Naga rounds it natively, +/// but Chromium WebGPU compiler (Tint) rejects it, disabling the GPU compositor. +#[test] +fn test_historical_photocraft_compose_wgsl_regression() { + let problematic_shader = r#" +// line 156 of compose.wgsl +const F32_MAX: f32 = 3.40282347e38; +"#; + let findings = wgsl_float_literals(problematic_shader); + assert_eq!(findings.len(), 1); + assert_eq!(findings[0].line, 3); + assert_eq!(findings[0].text, "3.40282347e38"); + + // Corrected shader uses exact hexadecimal float representation + let corrected_shader = r#" +// exact f32::MAX bit for bit +const F32_MAX: f32 = 0x1.fffffep+127f; +"#; + let corrected_findings = wgsl_float_literals(corrected_shader); + assert!(corrected_findings.is_empty()); +} + +#[test] +fn test_wgsl_float_literals_controls() { + // 1. Scientific notation and signed values + let signed_and_sci = r#" +const OVER_POS: f32 = 1e39; +const OVER_NEG: f32 = -1e39; +const VALID_POS: f32 = 1.5e10; +const VALID_NEG: f32 = -1.5e10; +const VALID_TINY: f32 = 1e-40; +"#; + let findings = wgsl_float_literals(signed_and_sci); + assert_eq!(findings.len(), 2); + assert_eq!(findings[0].text, "1e39"); + assert_eq!(findings[1].text, "1e39"); // Scanned magnitude of -1e39 + + // 2. Hexadecimal floating-point representations + let hex_floats = r#" +const EXACT_MAX: f32 = 0x1.fffffep+127f; +const ONE_P0: f32 = 0x1.0p0; +const HALF_HEX: f32 = 0x1.0p-1h; +"#; + assert!(wgsl_float_literals(hex_floats).is_empty()); + + // 3. Literals appearing inside comments + let in_comments = r#" +// const F32_MAX = 3.40282347e38; +/* + const OVERFLOW = 1e40; +*/ +"#; + assert!(wgsl_float_literals(in_comments).is_empty()); + + // 4. Numeric suffixes (f, h) + let suffixes = r#" +const BAD_F: f32 = 3.40282347e38f; +const GOOD_F: f32 = 1.0f; +const GOOD_H: f16 = 0.5h; +"#; + let suffix_findings = wgsl_float_literals(suffixes); + assert_eq!(suffix_findings.len(), 1); + assert_eq!(suffix_findings[0].text, "3.40282347e38"); + + // 5. Embedded in identifiers or other tokens + let idents = r#" +let var_1 = 1.0; +let layer2 = 2.0; +let coord_0 = 0.0; +"#; + assert!(wgsl_float_literals(idents).is_empty()); +} + +#[test] +fn test_wgsl_float_literals_in_multiple_files() { + let s1 = "const A: f32 = 1.0;\nconst B: f32 = 3.40282347e38;\n"; + let s2 = "const OK: f32 = 0x1.fffffep+127f;\n"; + let s3 = "const BAD: f32 = 9.99e38;\n"; + + let files = [("shaders/compose.wgsl", s1), ("shaders/clean.wgsl", s2), ("shaders/fx.wgsl", s3)]; + let findings = wgsl_float_literals_in(files); + assert_eq!(findings.len(), 2); + assert_eq!(findings[0].path, "shaders/compose.wgsl"); + assert_eq!(findings[0].line, 2); + assert_eq!(findings[0].text, "3.40282347e38"); + assert_eq!(findings[1].path, "shaders/fx.wgsl"); + assert_eq!(findings[1].line, 1); + assert_eq!(findings[1].text, "9.99e38"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn test_predefined_quit_qualified_and_whitespace() { + let source = r#" +fn setup() { + let q1 = muda::PredefinedMenuItem::quit(None); + let q2 = PredefinedMenuItem :: quit(Some("Quit")); + let q3 = crate::menu::PredefinedMenuItem::Quit; +} +"#; + let findings = predefined_quit([("src/menu.rs", source)]); + assert_eq!(findings.len(), 3); + assert_eq!(findings[0].line, 3); + assert_eq!(findings[1].line, 4); + assert_eq!(findings[2].line, 5); +} + +#[test] +fn test_std_instant_module_alias() { + let source = r#" +use std::time; + +fn run() { + let t0 = time::Instant::now(); +} +"#; + let findings = std_instant([("src/worker.rs", source)]); + assert_eq!(findings.len(), 1); + assert_eq!(findings[0].line, 5); +} + +#[test] +fn test_wgsl_exact_f32_max_boundary() { + // 3.4028234663852886e38 is mathematical f32::MAX bit for bit + let exact_valid = r#" +const EXACT_MAX: f32 = 3.4028234663852886e38; +const NEG_EXACT_MAX: f32 = -3.4028234663852886e38; +"#; + assert!(wgsl_float_literals(exact_valid).is_empty()); + + // 3.40282347e38 is slightly above f32::MAX + let just_over = r#" +const OVER_POS: f32 = 3.40282347e38; +const OVER_NEG: f32 = -3.40282347e38; +"#; + let findings = wgsl_float_literals(just_over); + assert_eq!(findings.len(), 2); + assert_eq!(findings[0].text, "3.40282347e38"); + assert_eq!(findings[1].text, "3.40282347e38"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn test_rust_sources_filtering() { + use craft_testkit::rust_sources; + use std::fs::{self, File}; + use std::io::Write; + + let temp_dir = std::env::temp_dir().join(format!("craft_testkit_test_{}", std::process::id())); + let _ = fs::remove_dir_all(&temp_dir); + fs::create_dir_all(temp_dir.join("src").join("sub")).expect("create temp sub"); + fs::create_dir_all(temp_dir.join("tests")).expect("create temp tests"); + fs::create_dir_all(temp_dir.join("target")).expect("create temp target"); + fs::create_dir_all(temp_dir.join(".github")).expect("create temp dot-dir"); + + let create_file = |path: std::path::PathBuf, content: &str| { + let mut f = File::create(path).expect("create file"); + f.write_all(content.as_bytes()).expect("write content"); + }; + + create_file(temp_dir.join("src").join("lib.rs"), "pub fn lib() {}"); + create_file(temp_dir.join("src").join("sub").join("mod.rs"), "pub fn sub() {}"); + create_file(temp_dir.join("src").join("tests.rs"), "// should exclude"); + create_file(temp_dir.join("src").join("tests_foo.rs"), "// should exclude"); + create_file(temp_dir.join("src").join("foo_tests.rs"), "// should exclude"); + create_file(temp_dir.join("src").join("foo_test.rs"), "// should exclude"); + create_file(temp_dir.join("tests").join("integ.rs"), "// should exclude"); + create_file(temp_dir.join("target").join("gen.rs"), "// should exclude"); + create_file(temp_dir.join(".github").join("action.rs"), "// should exclude dot-dir"); + create_file(temp_dir.join("src").join("README.md"), "# Not a rust source"); + + let sources = rust_sources(&temp_dir).expect("rust_sources"); + let names: Vec = sources.iter().map(|(p, _)| std::path::Path::new(p).file_name().unwrap().to_string_lossy().into_owned()).collect(); + + assert_eq!(names, vec!["lib.rs", "mod.rs"]); + + // Test passing &[(&str, &str)] to guards + let findings = predefined_quit(&sources); + assert!(findings.is_empty()); + + let _ = fs::remove_dir_all(&temp_dir); +} From 46ce2045854a67985738dab631be17f8dd63e8fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 10:54:36 -0800 Subject: [PATCH 009/322] craft-ods: build the testing module only for tests and the test-support feature `craft_ods::testing`, which builds small `.ods` packages in code, was compiled into every build of the crate. It is now behind `cfg(any(test, feature = "test-support"))`, as `craft-sf2`'s `fixture` is. The crate's own integration test and doctest enable the feature through a dev-dependency on the crate itself. A crate that calls `craft_ods::testing` now needs `features = ["test-support"]`. Users of `craft_ods::testing`: the crate doctest (`src/lib.rs`) and `tests/read.rs`. No other craft-libs crate uses it. --- Cargo.lock | 1 + crates/ods/Cargo.toml | 5 +++++ crates/ods/README.md | 6 ++++++ crates/ods/src/lib.rs | 1 + 4 files changed, 13 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 3d8cf4a7b3..3d002a6f46 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2095,6 +2095,7 @@ name = "craft-ods" version = "0.1.0" dependencies = [ "craft-odf", + "craft-ods", "craft-sheet", "craft-xml", "thiserror 2.0.21", diff --git a/crates/ods/Cargo.toml b/crates/ods/Cargo.toml index 814e6d9c3e..3b405d8ee4 100644 --- a/crates/ods/Cargo.toml +++ b/crates/ods/Cargo.toml @@ -10,6 +10,10 @@ repository.workspace = true [lints] workspace = true +[features] +# `testing`: small `.ods` packages built in code, for the tests of crates that read them. +test-support = [] + [dependencies] craft-odf = { workspace = true } craft-sheet = { workspace = true } @@ -18,3 +22,4 @@ thiserror = { workspace = true } [dev-dependencies] craft-odf = { workspace = true } +craft-ods = { path = ".", features = ["test-support"] } diff --git a/crates/ods/README.md b/crates/ods/README.md index eb255349a6..3c9111b71a 100644 --- a/crates/ods/README.md +++ b/crates/ods/README.md @@ -35,3 +35,9 @@ expanded; blank padding past the grid's edge is clipped, data past it is an erro `craft-xml`'s depth and attribute limits. At most 1024 tables. `Options::only_sheet` keeps one sheet's cells and lists the others by name. + +## Features + +- `test-support`: `testing`, which builds small `.ods` packages in code (`spreadsheet`, + `content`, `package`), for the tests of crates that read spreadsheets. Not a general + spreadsheet writer. diff --git a/crates/ods/src/lib.rs b/crates/ods/src/lib.rs index e96e22df2f..3adcc14313 100644 --- a/crates/ods/src/lib.rs +++ b/crates/ods/src/lib.rs @@ -30,6 +30,7 @@ mod content; mod model; +#[cfg(any(test, feature = "test-support"))] #[doc(hidden)] pub mod testing; From 52b917fce5bdab996288dc79c4d8b75af84bcb4d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:16:07 -0800 Subject: [PATCH 010/322] craft-testkit: guards read Rust tokens, check hex and f16 floats, and bound rust_sources predefined_quit and std_instant now run on a small Rust lexer instead of a masked line search: - Character and byte literals such as '"' no longer open a phantom string that hides the code after them. - A Quit call split by tabs or a line break around :: is reported, a different name such as MyPredefinedMenuItem or quitter is not, and a use muda::PredefinedMenuItem as X rename is followed. - std_instant reports std::time::Instant, ::Instant where a use binds m to std::time, and each use that imports std::time::Instant or std::time::*. A line that also names web_time is still reported, and an unrelated time::Instant is not. - cfg attributes are read from code, not from strings or comments, and evaluated for wasm32-unknown-unknown (all, any, not, unix, windows, target_* keys). An outer attribute covers the item after it, an inner one the rest of its module. A predicate that depends on a feature or test is checked. wgsl_float_literals skips integer literals, reports hexadecimal floats above f32::MAX, and checks an h-suffixed float against 65504. rust_sources does not follow symbolic links, skips folders that hold a CACHEDIR.TAG file, no longer drops every file when the root itself is under a folder named tests, and returns an error for a file over 8 MiB, more than 256 MiB in all or more than 50,000 files. rust_sources_with_limits takes other limits. The tests use a scratch folder that is never reused and is removed when a test panics. The crate is not published, and the root README lists it. --- README.md | 3 + crates/testkit/Cargo.toml | 1 + crates/testkit/README.md | 25 +- crates/testkit/src/guards.rs | 1012 ++++++++++++++++++++----- crates/testkit/src/lib.rs | 11 +- crates/testkit/tests/guards.rs | 397 +++++++++- crates/testkit/tests/source_limits.rs | 99 +++ 7 files changed, 1313 insertions(+), 235 deletions(-) create mode 100644 crates/testkit/tests/source_limits.rs diff --git a/README.md b/README.md index c6e95bd4f9..adbb6c120e 100644 --- a/README.md +++ b/README.md @@ -345,6 +345,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit check for drawing a tree with resvg. Apps take usvg from here, not as their own dependency. - [`craft-svg-paths`](crates/svg-paths/src/lib.rs): the former name of `craft-svg`'s `paths`, `color` and `write`; re-exports them for existing users. +- [`craft-testkit`](crates/testkit/README.md): test support for the apps' own tests. Its `guards` module + reports source patterns that broke platforms before: muda's predefined Quit item, WGSL float literals + out of range, and `std::time::Instant` in code the web build runs. Not published. - [`craft-text`](crates/text/README.md): text processing below the composer. Its `hyphen` module finds hyphenation points, with a bundled US English dictionary and patterns and optional hypher patterns for 47 more languages (one cargo feature each). diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index d2a3b3179f..d32ed735f4 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -6,6 +6,7 @@ license.workspace = true rust-version.workspace = true repository.workspace = true description = "Source-level platform regression guards and verification utilities for the Craft application suite" +publish = false [dependencies] diff --git a/crates/testkit/README.md b/crates/testkit/README.md index d7208396b6..75e74d7b82 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -6,10 +6,10 @@ Source-level platform regression guards and verification utilities for the Craft `craft-testkit` provides lightweight, non-panicking source guards that prevent applications in the Craft ecosystem from repeating platform defects that were previously diagnosed and resolved in peer applications: -1. **`predefined_quit`**: Flags direct calls to `muda`'s `PredefinedMenuItem::quit` outside comments. On macOS, this predefined menu item routes directly to `NSApplication terminate:`, completely bypassing application dirty document checks and unsaved changes save prompts. Applications should instead wire Quit through `craft-quit` lifecycle interceptors. -2. **`wgsl_float_literals` / `wgsl_float_literals_in`**: Scans WGSL shader sources using PhotoCraft's decimal float scanner and flags literals whose absolute value exceeds `f32::MAX` (such as `3.40282347e38`). While native compilers (`naga`) round these down, browser WebGPU compilers (`Tint` in Chromium) reject them with fatal pipeline compilation errors, forcing applications into CPU fallback rendering. Exact values equal to `f32::MAX` must be written as exact hex float literals (`0x1.fffffep+127f`). -3. **`std_instant`**: Flags lines naming `std::time::Instant` outside comments without `web_time`. On `wasm32-unknown-unknown`, `std::time::Instant::now()` panics at runtime with `"time not implemented on this platform"`. Code targeting the web must use `web_time::Instant`. -4. **`rust_sources`**: Recursively discovers a crate's `.rs` source files while excluding integration tests (`tests/`), test modules (`tests.rs`, `tests_*.rs`, `*_tests.rs`, `*_test.rs`), and build artifacts (`target/`, `.git/`). +1. **`predefined_quit`**: Flags direct calls to `muda`'s `PredefinedMenuItem::quit` outside comments, strings and character literals, also with whitespace or a line break around `::` and through a `use muda::PredefinedMenuItem as ...` rename. On macOS, this predefined menu item routes directly to `NSApplication terminate:`, completely bypassing application dirty document checks and unsaved changes save prompts. Applications should instead wire Quit through `craft-quit` lifecycle interceptors. +2. **`wgsl_float_literals` / `wgsl_float_literals_in`**: Scans WGSL shader sources and flags decimal and hexadecimal float literals whose value exceeds `f32::MAX` (such as `3.40282347e38` or `0x1p+500f`), or 65504, the largest finite `f16`, for a literal with an `h` suffix. Integer literals are not checked. Some native compilers round such literals down, but browser WebGPU compilers reject them with pipeline compilation errors, forcing applications into CPU fallback rendering. Exact values equal to `f32::MAX` can be written as `3.4028234663852886e38` or as the hex float `0x1.fffffep+127f`. +3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`. Other crates' `Instant` (such as `web_time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`. On that target, `std::time::Instant::now()` panics at runtime with `"time not implemented on this platform"`. Code targeting the web must use `web_time::Instant`. +4. **`rust_sources`**: Recursively discovers a crate's `.rs` source files while excluding integration tests (`tests/`), test modules (`tests.rs`, `tests_*.rs`, `*_tests.rs`, `*_test.rs`), build artifacts (`target/`, any folder holding a `CACHEDIR.TAG` file, `.git/` and other folders whose name starts with `.`) and symbolic links, which it does not follow. A file over 8 MiB, more than 256 MiB in all or more than 50,000 files returns an error; `rust_sources_with_limits` takes other limits. It is not built for `wasm32`. ## Epistemic Scope: Syntactic Guards vs Runtime Validation @@ -21,8 +21,8 @@ Source-level guards provide deterministic syntactic evidence about codebase stru ### What They Cannot Establish - **Runtime execution safety**: Syntactic checks do not verify whether code branches actually execute at runtime. -- **Semantic type resolution**: The scanners do not resolve arbitrary type aliases (e.g. `use std::time as t; t::Instant::now()`) or expand procedural macros. -- **Complex target predicates**: While `std_instant` recognizes direct item-level non-wasm target conditions (e.g. `#[cfg(not(target_arch = "wasm32"))]`), it does not evaluate arbitrary multi-crate boolean expressions. Applications should scope `std_instant` tests to the specific crates that compile into their web distribution. +- **Semantic type resolution**: The scanners follow `use` renames within one file only. They do not resolve paths through other modules or re-exports, a rename of `std` itself, or expand macros. +- **Complex target predicates**: `std_instant` evaluates `cfg` predicates (`all`, `any`, `not`, `unix`, `windows` and the `target_*` keys) for `wasm32-unknown-unknown`, on outer attributes for the item that follows and on inner attributes (`#![cfg(...)]`) for the rest of the module. A predicate that depends on a feature or on `test` is not known from the source, so its item is checked. Applications should scope `std_instant` tests to the specific crates that compile into their web distribution. - **Driver and host OS behavior**: Syntactic checks do not verify WebGPU driver compatibility or host window manager event dispatch. Source guards serve as fast, zero-dependency regression gates in application test suites, complementing platform integration tests and CI workflows. @@ -77,3 +77,16 @@ fn no_std_instant_in_code_the_web_build_runs() { ); } ``` + +## Origin + +| Module | Source | Path | Commit | +|---|---|---|---| +| `guards` | storytold/craft-libs#163 (zachshallbetter), with the rules of PhotoCraft's shader float test and FilmCraft's web clock test | `crates/testkit/src/guards.rs` | `e92825e427` | + +## Migration + +| Consumer | Guard | Replaces | State | +|---|---|---|---| +| PhotoCraft | `wgsl_float_literals` | `crates/gpu/src/tests.rs` scanner | Not started | +| FilmCraft | `std_instant` | `crates/engine/src/wasm_clock_tests.rs` search | Not started | diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index 2f8c50d234..a8a14401ef 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -1,5 +1,6 @@ //! Platform regression guards checking source code for known defects and lifecycle hazards. +use std::collections::BTreeSet; use std::fmt; #[cfg(not(target_arch = "wasm32"))] use std::path::Path; @@ -108,132 +109,529 @@ impl AsFileSource for &(&str, String) { } } -/// Replace code comments and string literals with whitespace while preserving newlines and line counts. +/// The deepest `use` group nesting and `cfg` predicate nesting the guards follow. Deeper input is +/// read as far as this depth, so hostile nesting cannot exhaust the stack. +const MAX_NESTING: usize = 64; + +/// The kind of a Rust token. Comments are dropped; string, character and number literals keep no text +/// except string contents, which `cfg` predicates compare. +#[derive(Debug, Clone, PartialEq, Eq)] +enum Kind { + Ident(String), + Punct(char), + Str(String), + Other, +} + +#[derive(Debug, Clone)] +struct Token { + kind: Kind, + line: usize, +} + +impl Token { + fn is_ident(&self, name: &str) -> bool { + matches!(&self.kind, Kind::Ident(s) if s == name) + } + + fn is_punct(&self, c: char) -> bool { + self.kind == Kind::Punct(c) + } +} + +fn is_ident_start(c: char) -> bool { + c == '_' || c.is_alphabetic() +} + +fn is_ident_continue(c: char) -> bool { + c == '_' || c.is_alphanumeric() +} + +/// Split Rust source into tokens with 1-based line numbers. /// -/// Handles single-line comments (`//`), block comments (`/* ... */`, including nested comments), -/// normal string literals (`"..."`), and raw string literals (`r#"..."#`). -fn mask_comments_and_strings(code: &str) -> String { - let mut out = String::with_capacity(code.len()); +/// Line comments, nested block comments, string literals (normal, byte, C and raw strings with any +/// number of `#`), character and byte literals, lifetimes and raw identifiers are recognized, so a quote +/// or comment marker inside one of them does not hide the code after it. Unterminated literals and +/// comments run to the end of the input. +fn lex_rust(code: &str) -> Vec { let chars: Vec = code.chars().collect(); let len = chars.len(); + let at = |i: usize| chars.get(i).copied(); + let mut tokens = Vec::new(); let mut i = 0; - let mut in_line_comment = false; - let mut block_comment_depth: usize = 0; - let mut in_normal_string = false; - let mut raw_string_hashes: Option = None; - let mut escape = false; + let mut line = 1usize; while i < len { let c = chars[i]; - if in_line_comment { - if c == '\n' { - in_line_comment = false; - out.push('\n'); - } else { - out.push(' '); - } + if c == '\n' { + line += 1; i += 1; - } else if block_comment_depth > 0 { - if c == '*' && i + 1 < len && chars[i + 1] == '/' { - block_comment_depth = block_comment_depth.saturating_sub(1); - out.push(' '); - out.push(' '); - i += 2; - } else if c == '/' && i + 1 < len && chars[i + 1] == '*' { - block_comment_depth = block_comment_depth.saturating_add(1); - out.push(' '); - out.push(' '); - i += 2; - } else if c == '\n' { - out.push('\n'); - i += 1; - } else { - out.push(' '); + } else if c.is_whitespace() { + i += 1; + } else if c == '/' && at(i + 1) == Some('/') { + while i < len && chars[i] != '\n' { i += 1; } - } else if let Some(hashes) = raw_string_hashes { - if c == '"' { - let mut match_hashes = true; - if i + hashes < len { - for h in 0..hashes { - if chars[i + 1 + h] != '#' { - match_hashes = false; - break; - } - } + } else if c == '/' && at(i + 1) == Some('*') { + let mut depth = 1usize; + i += 2; + while i < len && depth > 0 { + if chars[i] == '/' && at(i + 1) == Some('*') { + depth += 1; + i += 2; + } else if chars[i] == '*' && at(i + 1) == Some('/') { + depth -= 1; + i += 2; } else { - match_hashes = false; - } - if match_hashes { - raw_string_hashes = None; - for _ in 0..=hashes { - out.push(' '); + if chars[i] == '\n' { + line += 1; } - i += 1 + hashes; + i += 1; + } + } + } else if is_ident_start(c) { + let start = i; + while i < len && is_ident_continue(chars[i]) { + i += 1; + } + let word: String = chars[start..i].iter().collect(); + let token_line = line; + if matches!(word.as_str(), "r" | "br" | "cr") && matches!(at(i), Some('"' | '#')) { + let mut j = i; + while j < len && chars[j] == '#' { + j += 1; + } + let hashes = j - i; + if at(j) == Some('"') { + let (end, text) = scan_raw_string(&chars, j + 1, hashes, &mut line); + tokens.push(Token { kind: Kind::Str(text), line: token_line }); + i = end; + continue; + } + if word == "r" && hashes == 1 && at(j).is_some_and(is_ident_start) { + let name_start = j; + while j < len && is_ident_continue(chars[j]) { + j += 1; + } + tokens.push(Token { kind: Kind::Ident(chars[name_start..j].iter().collect()), line: token_line }); + i = j; continue; } } - if c == '\n' { - out.push('\n'); - } else { - out.push(' '); + if matches!(word.as_str(), "b" | "c") && at(i) == Some('"') { + let (end, text) = scan_string(&chars, i + 1, &mut line); + tokens.push(Token { kind: Kind::Str(text), line: token_line }); + i = end; + continue; } - i += 1; - } else if in_normal_string { - if escape { - escape = false; - out.push(' '); - } else if c == '\\' { - escape = true; - out.push(' '); - } else if c == '"' { - in_normal_string = false; - out.push(' '); - } else if c == '\n' { - out.push('\n'); - } else { - out.push(' '); + if word == "b" + && at(i) == Some('\'') + && let Some(end) = char_literal_end(&chars, i) + { + tokens.push(Token { kind: Kind::Other, line: token_line }); + i = end; + continue; } - i += 1; - } else { - if c == '/' && i + 1 < len && chars[i + 1] == '/' { - in_line_comment = true; - out.push(' '); - out.push(' '); - i += 2; - } else if c == '/' && i + 1 < len && chars[i + 1] == '*' { - block_comment_depth = 1; - out.push(' '); - out.push(' '); - i += 2; - } else if c == '"' { - in_normal_string = true; - out.push(' '); + tokens.push(Token { kind: Kind::Ident(word), line: token_line }); + } else if c.is_ascii_digit() { + while i < len && (is_ident_continue(chars[i]) || (chars[i] == '.' && at(i + 1).is_some_and(|d| d.is_ascii_digit()))) { i += 1; - } else if c == 'r' && i + 1 < len && (chars[i + 1] == '"' || chars[i + 1] == '#') { - let mut j = i + 1; - let mut hashes = 0; - while j < len && chars[j] == '#' { - hashes += 1; - j += 1; - } - if j < len && chars[j] == '"' { - raw_string_hashes = Some(hashes); - for _ in i..=j { - out.push(' '); - } - i = j + 1; - } else { - out.push(c); + } + tokens.push(Token { kind: Kind::Other, line }); + } else if c == '"' { + let token_line = line; + let (end, text) = scan_string(&chars, i + 1, &mut line); + tokens.push(Token { kind: Kind::Str(text), line: token_line }); + i = end; + } else if c == '\'' { + if let Some(end) = char_literal_end(&chars, i) { + i = end; + } else { + // A lifetime or a loop label. + i += 1; + while i < len && is_ident_continue(chars[i]) { i += 1; } - } else { - out.push(c); - i += 1; } + tokens.push(Token { kind: Kind::Other, line }); + } else { + tokens.push(Token { kind: Kind::Punct(c), line }); + i += 1; } } - out + tokens +} + +/// Read a normal string body starting after its opening quote. Returns the index after the closing +/// quote and the body as written, escapes included. +fn scan_string(chars: &[char], mut i: usize, line: &mut usize) -> (usize, String) { + let start = i; + while i < chars.len() { + match chars[i] { + '\\' => { + if chars.get(i + 1) == Some(&'\n') { + *line += 1; + } + i += 2; + } + '"' => return (i + 1, chars[start..i].iter().collect()), + '\n' => { + *line += 1; + i += 1; + } + _ => i += 1, + } + } + (chars.len(), chars[start.min(chars.len())..].iter().collect()) +} + +/// Read a raw string body starting after its opening quote; it ends at a quote followed by `hashes` `#`. +fn scan_raw_string(chars: &[char], mut i: usize, hashes: usize, line: &mut usize) -> (usize, String) { + let start = i; + while i < chars.len() { + if chars[i] == '"' && (1..=hashes).all(|h| chars.get(i + h) == Some(&'#')) { + return (i + 1 + hashes, chars[start..i].iter().collect()); + } + if chars[i] == '\n' { + *line += 1; + } + i += 1; + } + (chars.len(), chars[start.min(chars.len())..].iter().collect()) +} + +/// The index after a character or byte literal whose opening quote is at `quote`, or `None` when the +/// quote starts a lifetime or a label. +fn char_literal_end(chars: &[char], quote: usize) -> Option { + match chars.get(quote + 1) { + Some('\\') => { + // An escape: `\n`, `\'`, `\x7f`, `\u{10FFFF}`. The longest is twelve characters. + let mut j = quote + 3; + while j < chars.len() && j <= quote + 12 && chars[j] != '\'' && chars[j] != '\n' { + j += 1; + } + (chars.get(j) == Some(&'\'')).then_some(j + 1) + } + Some('\n') | None => None, + Some(_) => (chars.get(quote + 2) == Some(&'\'')).then_some(quote + 3), + } +} + +/// Rust keywords that can come right before a path that starts with `::`, as in `return ::std::time`. +/// `crate`, `self`, `super` and `Self` are path segments and are not listed. +const KEYWORDS: &[&str] = &[ + "as", "async", "await", "box", "break", "const", "continue", "dyn", "else", "enum", "extern", "fn", "for", "if", "impl", "in", "let", "loop", + "match", "mod", "move", "mut", "pub", "ref", "return", "static", "struct", "trait", "type", "unsafe", "use", "where", "while", "yield", +]; + +/// Whether `toks[i]` follows `::` that itself follows a path segment, as `time` does in `a::time`. +fn continues_a_path(toks: &[Token], i: usize) -> bool { + i >= 3 + && toks[i - 1].is_punct(':') + && toks[i - 2].is_punct(':') + && match &toks[i - 3].kind { + Kind::Ident(s) => !KEYWORDS.contains(&s.as_str()), + Kind::Punct('>') => true, + _ => false, + } +} + +/// Whether `toks[i..]` starts with `::` followed by the identifier `name`. +fn then_path(toks: &[Token], i: usize, name: impl Fn(&str) -> bool) -> bool { + toks.get(i).is_some_and(|t| t.is_punct(':')) + && toks.get(i + 1).is_some_and(|t| t.is_punct(':')) + && toks.get(i + 2).is_some_and(|t| matches!(&t.kind, Kind::Ident(s) if name(s))) +} + +/// One name a `use` declaration brings into scope. +#[derive(Debug)] +struct UseLeaf { + /// The full path, `self` removed and without a leading `::`. + path: Vec, + /// The name it is bound to; `None` for a glob import. + name: Option, + line: usize, + /// Index of the `use` keyword. + start: usize, +} + +/// Every name the `use` declarations of a file bring into scope. +fn use_leaves(toks: &[Token]) -> Vec { + let mut leaves = Vec::new(); + let mut i = 0; + while i < toks.len() { + if toks[i].is_ident("use") && !continues_a_path(toks, i) { + let start = i; + let end = (i + 1..toks.len()).find(|&j| toks[j].is_punct(';')).unwrap_or(toks.len()); + let mut pos = i + 1; + let mut prefix = Vec::new(); + parse_use_tree(&toks[..end], &mut pos, &mut prefix, start, &mut leaves, 0); + i = end; + } else { + i += 1; + } + } + leaves +} + +fn parse_use_tree(toks: &[Token], pos: &mut usize, prefix: &mut Vec, start: usize, out: &mut Vec, depth: usize) { + let base = prefix.len(); + if toks.get(*pos).is_some_and(|t| t.is_punct(':')) && toks.get(*pos + 1).is_some_and(|t| t.is_punct(':')) { + *pos += 2; + } + while let Some(tok) = toks.get(*pos) { + match &tok.kind { + Kind::Ident(name) => { + *pos += 1; + if toks.get(*pos).is_some_and(|t| t.is_punct(':')) && toks.get(*pos + 1).is_some_and(|t| t.is_punct(':')) { + prefix.push(name.clone()); + *pos += 2; + continue; + } + let mut path = prefix.clone(); + if name != "self" { + path.push(name.clone()); + } + let mut bound = path.last().cloned(); + if toks.get(*pos).is_some_and(|t| t.is_ident("as")) + && let Some(Kind::Ident(alias)) = toks.get(*pos + 1).map(|t| &t.kind) + { + bound = Some(alias.clone()); + *pos += 2; + } + if let Some(bound) = bound.filter(|b| b != "_") { + out.push(UseLeaf { path, name: Some(bound), line: tok.line, start }); + } + break; + } + Kind::Punct('*') => { + out.push(UseLeaf { path: prefix.clone(), name: None, line: tok.line, start }); + *pos += 1; + break; + } + Kind::Punct('{') => { + *pos += 1; + while let Some(t) = toks.get(*pos) { + if t.is_punct('}') { + *pos += 1; + break; + } + let before = *pos; + if !t.is_punct(',') && depth < MAX_NESTING { + parse_use_tree(toks, pos, prefix, start, out, depth + 1); + } + if *pos == before { + *pos += 1; + } + } + break; + } + _ => break, + } + } + prefix.truncate(base); +} + +/// A value of a `cfg` predicate on `wasm32-unknown-unknown`, where the value of a feature or of +/// `test` is not known from the source. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Tri { + True, + False, + Unknown, +} + +impl Tri { + fn from_bool(b: bool) -> Self { + if b { Self::True } else { Self::False } + } + + fn not(self) -> Self { + match self { + Self::True => Self::False, + Self::False => Self::True, + Self::Unknown => Self::Unknown, + } + } +} + +/// Evaluate the `cfg` predicate at `toks[*pos]` for `wasm32-unknown-unknown`. +fn eval_cfg(toks: &[Token], pos: &mut usize, depth: usize) -> Tri { + let Some(Kind::Ident(name)) = toks.get(*pos).map(|t| &t.kind) else { + return Tri::Unknown; + }; + *pos += 1; + if toks.get(*pos).is_some_and(|t| t.is_punct('=')) { + let value = match toks.get(*pos + 1).map(|t| &t.kind) { + Some(Kind::Str(v)) => v.clone(), + _ => return Tri::Unknown, + }; + *pos += 2; + let expected = match name.as_str() { + "target_arch" => "wasm32", + "target_os" | "target_vendor" => "unknown", + "target_family" => "wasm", + "target_env" => "", + "target_pointer_width" => "32", + "target_endian" => "little", + _ => return Tri::Unknown, + }; + return Tri::from_bool(value == expected); + } + if toks.get(*pos).is_some_and(|t| t.is_punct('(')) { + *pos += 1; + let mut values = Vec::new(); + while let Some(t) = toks.get(*pos) { + if t.is_punct(')') { + *pos += 1; + break; + } + if t.is_punct(',') || depth >= MAX_NESTING { + *pos += 1; + continue; + } + let before = *pos; + values.push(eval_cfg(toks, pos, depth + 1)); + if *pos == before { + *pos += 1; + } + } + return match name.as_str() { + "not" => values.first().map_or(Tri::Unknown, |v| v.not()), + "all" if values.contains(&Tri::False) => Tri::False, + "all" if values.contains(&Tri::Unknown) => Tri::Unknown, + "all" => Tri::True, + "any" if values.contains(&Tri::True) => Tri::True, + "any" if values.contains(&Tri::Unknown) => Tri::Unknown, + "any" => Tri::False, + _ => Tri::Unknown, + }; + } + match name.as_str() { + "unix" | "windows" => Tri::False, + _ => Tri::Unknown, + } +} + +/// The index of the token that closes the bracket opened at `open`, or `toks.len()`. +fn matching_close(toks: &[Token], open: usize) -> usize { + let mut depth = 0usize; + for (j, t) in toks.iter().enumerate().skip(open) { + match t.kind { + Kind::Punct('(' | '[' | '{') => depth += 1, + Kind::Punct(')' | ']' | '}') => { + depth = depth.saturating_sub(1); + if depth == 0 { + return j; + } + } + _ => {} + } + } + toks.len() +} + +/// Keywords whose item or expression ends with its closing brace rather than with `;`. +const BLOCK_KEYWORDS: &[&str] = + &["fn", "mod", "impl", "trait", "struct", "enum", "union", "extern", "macro_rules", "if", "match", "loop", "while", "for", "unsafe"]; + +/// The index after the item, statement, field or match arm that starts at `start`, or with `inner`, the +/// index of the bracket that closes the enclosing scope. +/// +/// It ends after a `;` or a `,` outside brackets, after the closing brace of a block item (one that +/// starts with a keyword in [`BLOCK_KEYWORDS`] or is a macro call with braces) or of a match arm's +/// block, or before a closing bracket of the enclosing scope. A `,` inside the angle brackets of a +/// field's or a `let`'s type ends the item early, which leaves the rest of it checked. +fn item_end(toks: &[Token], start: usize, inner: bool) -> usize { + let mut depth = 0usize; + let mut block_item = false; + let mut arm = false; + let mut j = start; + while j < toks.len() { + let at_top = depth == 0 && !inner; + match &toks[j].kind { + Kind::Ident(k) if at_top && BLOCK_KEYWORDS.contains(&k.as_str()) => block_item = true, + Kind::Punct('!') if at_top && toks.get(j + 1).is_some_and(|t| t.is_punct('{')) => block_item = true, + Kind::Punct('=') if at_top && toks.get(j + 1).is_some_and(|t| t.is_punct('>')) => arm = true, + Kind::Punct('(' | '[' | '{') => depth += 1, + Kind::Punct(c @ (')' | ']' | '}')) => { + if depth == 0 { + return j; + } + depth -= 1; + if depth == 0 && *c == '}' && (block_item || arm) && !inner { + if toks.get(j + 1).is_some_and(|t| t.is_ident("else")) { + j += 1; + continue; + } + let comma = toks.get(j + 1).is_some_and(|t| t.is_punct(',')); + return if arm && comma { j + 2 } else { j + 1 }; + } + } + Kind::Punct(';') if at_top => return j + 1, + Kind::Punct(',') if at_top && (arm || !block_item) => return j + 1, + _ => {} + } + j += 1; + } + toks.len() +} + +/// Mark the tokens of every item whose `cfg` attribute is false on `wasm32-unknown-unknown`. +/// +/// An outer attribute (`#[cfg(...)]`) covers the item after it; an inner attribute (`#![cfg(...)]`) +/// covers the rest of the module or block it is in. +fn native_only(toks: &[Token]) -> Vec { + let mut skip = vec![false; toks.len()]; + let mut i = 0; + while i < toks.len() { + if !toks[i].is_punct('#') { + i += 1; + continue; + } + let inner = toks.get(i + 1).is_some_and(|t| t.is_punct('!')); + let open = if inner { i + 2 } else { i + 1 }; + if !toks.get(open).is_some_and(|t| t.is_punct('[')) { + i += 1; + continue; + } + let close = matching_close(toks, open); + if close >= toks.len() { + // An unclosed attribute: no later bracket closes it, so nothing after it is an item. + break; + } + let excluded = toks.get(open + 1).is_some_and(|t| t.is_ident("cfg")) && toks.get(open + 2).is_some_and(|t| t.is_punct('(')) && { + let mut pos = open + 3; + eval_cfg(&toks[..close], &mut pos, 0) == Tri::False + }; + if !excluded { + i = close + 1; + continue; + } + // Further outer attributes on the same item. + let mut item = close + 1; + while !inner && item < toks.len() && toks[item].is_punct('#') && toks.get(item + 1).is_some_and(|t| t.is_punct('[')) { + item = matching_close(toks, item + 1).saturating_add(1); + } + let end = item_end(toks, item.min(toks.len()), inner); + for s in skip.iter_mut().take(end).skip(i) { + *s = true; + } + i = end.max(i + 1); + } + skip +} + +/// Add one finding for each line in `lines`, in line order, with the trimmed text of that line. +fn report(findings: &mut Vec, path: &str, content: &str, lines: &BTreeSet) { + if lines.is_empty() { + return; + } + let text: Vec<&str> = content.lines().collect(); + for &line in lines { + let line_text = text.get(line.saturating_sub(1)).map_or("", |s| s.trim()); + findings.push(Finding::new(path, line, line_text)); + } } /// Guard: detects direct calls to `muda`'s predefined Quit menu item. @@ -241,6 +639,12 @@ fn mask_comments_and_strings(code: &str) -> String { /// Using `PredefinedMenuItem::quit` connects the macOS menu directly to `NSApplication terminate:`, /// which bypasses dirty document checks, unsaved changes save prompts, and lifecycle cleanup. /// Applications should route Quit through custom menu items or interceptors connected to `craft-quit`. +/// +/// The guard reads Rust tokens, so comments, strings and character literals are ignored, and whitespace +/// or line breaks around `::` do not hide a call. It also follows a `use` that renames muda's type +/// (`use muda::PredefinedMenuItem as Item;` then `Item::quit`); a rename of another crate's +/// `PredefinedMenuItem` is not followed. Each finding names the line where the +/// type's name starts, once per line, in line order. pub fn predefined_quit(files: I) -> Vec where I: IntoIterator, @@ -250,19 +654,27 @@ where for file in files { let path = file.path(); let content = file.content(); - let masked = mask_comments_and_strings(content); - - for (orig_line, (idx, masked_line)) in content.lines().zip(masked.lines().enumerate()) { - let normalized = masked_line.replace(' ', ""); - if normalized.contains("PredefinedMenuItem::quit") || normalized.contains("PredefinedMenuItem::Quit") { - findings.push(Finding::new(path, idx + 1, orig_line.trim())); + let toks = lex_rust(content); + let aliases: BTreeSet = use_leaves(&toks) + .into_iter() + .filter(|leaf| leaf.path == ["muda", "PredefinedMenuItem"]) + .filter_map(|leaf| leaf.name) + .filter(|name| name != "PredefinedMenuItem") + .collect(); + let mut lines = BTreeSet::new(); + for (i, tok) in toks.iter().enumerate() { + let Kind::Ident(name) = &tok.kind else { continue }; + let named = name == "PredefinedMenuItem" || (aliases.contains(name) && !continues_a_path(&toks, i)); + if named && then_path(&toks, i + 1, |s| s == "quit" || s == "Quit") { + lines.insert(tok.line); } } + report(&mut findings, path, content, &lines); } findings } -/// Guard: detects uses of `std::time::Instant` outside comments in code paths running on the web. +/// Guard: detects uses of `std::time::Instant` in code paths running on the web. /// /// On `wasm32-unknown-unknown`, `std::time::Instant::now()` panics with "time not implemented /// on this platform". Crates running in the browser should use `web_time::Instant`, which maps to @@ -271,11 +683,19 @@ where /// ### Syntactic Scope and Limitations /// /// * **Targeted files**: Callers should pass files from crates that compile into the application's web build. -/// * **Allowed patterns**: Comments, string literals, lines containing `web_time`, and items decorated with -/// explicit non-wasm target conditions (e.g. `#[cfg(not(target_arch = "wasm32"))]` or `#[cfg(target_os = ...)]`) -/// are skipped. -/// * **Limitations**: This is a lexical source guard. It does not perform semantic type resolution, macro -/// expansion, or track arbitrary module aliases (e.g. `use std::time as t; t::Instant`). +/// * **What is reported**: the paths `std::time::Instant` and `::std::time::Instant`; `::Instant` where a +/// `use` outside a native-only item binds `m` to `std::time` (`use std::time;`, `use std::time as t;`, +/// `use std::time::{self as t}`); +/// and every `use` that imports `std::time::Instant` or `std::time::*`, under any name. Each finding names +/// the line where the path starts, once per line, in line order. +/// * **What is skipped**: comments, string and character literals, other crates' `Instant` (`web_time::Instant`, +/// a `time` module that is not `std::time`), and items whose `cfg` attribute is false on `wasm32-unknown-unknown` +/// (for example `#[cfg(not(target_arch = "wasm32"))]`, `#[cfg(all(unix, ...))]`, `#[cfg(target_os = "macos")]`, +/// or `#![cfg(...)]` for the rest of a module). A predicate that depends on a feature or on `test` is not +/// known from the source, so the item is checked. +/// * **Limitations**: This is a lexical source guard. It does not expand macros, resolve paths through other +/// modules or re-exports, rename `std` itself (`use std as s;`), or follow aliases in a different scope than +/// the file. pub fn std_instant(files: I) -> Vec where I: IntoIterator, @@ -285,72 +705,187 @@ where for file in files { let path = file.path(); let content = file.content(); - let masked = mask_comments_and_strings(content); + let toks = lex_rust(content); + let skip = native_only(&toks); + let leaves = use_leaves(&toks); + let modules: BTreeSet = leaves + .iter() + .filter(|leaf| leaf.path == ["std", "time"] && !skip.get(leaf.start).copied().unwrap_or(false)) + .filter_map(|leaf| leaf.name.clone()) + .collect(); + let is_std_time = |path: &[String]| path == ["std", "time"] || (path.len() == 1 && modules.contains(&path[0])); - let mut in_cfg_non_wasm = false; - let mut cfg_brace_depth: usize = 0; - - for (orig_line, (idx, masked_line)) in content.lines().zip(masked.lines().enumerate()) { - let is_comment_only = masked_line.trim().is_empty(); - let line_has_cfg_non_wasm = !is_comment_only - && (orig_line.contains("cfg(not(target_arch = \"wasm32\"))") - || orig_line.contains("cfg(target_arch = \"x86_64\")") - || orig_line.contains("cfg(target_arch = \"aarch64\")") - || orig_line.contains("cfg(target_os =")); - - if line_has_cfg_non_wasm { - in_cfg_non_wasm = true; + let mut lines = BTreeSet::new(); + for leaf in &leaves { + if skip.get(leaf.start).copied().unwrap_or(false) { + continue; } - - let names_std_instant = - masked_line.contains("time::Instant") || (masked_line.contains("use std::time::") && masked_line.contains("Instant")); - - if names_std_instant && !masked_line.contains("web_time") && !in_cfg_non_wasm { - findings.push(Finding::new(path, idx + 1, orig_line.trim())); - } - - if in_cfg_non_wasm && !is_comment_only { - let opens = masked_line.chars().filter(|&c| c == '{').count(); - let closes = masked_line.chars().filter(|&c| c == '}').count(); - if cfg_brace_depth == 0 { - if opens > 0 { - cfg_brace_depth = cfg_brace_depth.saturating_add(opens).saturating_sub(closes); - if cfg_brace_depth == 0 { - in_cfg_non_wasm = false; - } - } else if masked_line.contains(';') { - in_cfg_non_wasm = false; - } - } else { - cfg_brace_depth = cfg_brace_depth.saturating_add(opens).saturating_sub(closes); - if cfg_brace_depth == 0 { - in_cfg_non_wasm = false; - } - } + let imports_instant = if leaf.name.is_none() { + is_std_time(&leaf.path) + } else { + leaf.path.split_last().is_some_and(|(last, parent)| last == "Instant" && is_std_time(parent)) + }; + if imports_instant { + lines.insert(leaf.line); } } + for (i, tok) in toks.iter().enumerate() { + if skip[i] || continues_a_path(&toks, i) { + continue; + } + let Kind::Ident(name) = &tok.kind else { continue }; + let hit = if name == "std" { + then_path(&toks, i + 1, |s| s == "time") && then_path(&toks, i + 4, |s| s == "Instant") + } else { + modules.contains(name) && then_path(&toks, i + 1, |s| s == "Instant") + }; + if hit { + lines.insert(tok.line); + } + } + report(&mut findings, path, content, &lines); } findings } -/// Guard: scans a single WGSL shader string and detects decimal float literals outside `f32`'s finite range. +/// Replace WGSL comments (`//` and nested `/* ... */`) with spaces, keeping line breaks. +fn mask_wgsl_comments(code: &str) -> String { + let chars: Vec = code.chars().collect(); + let len = chars.len(); + let mut out = String::with_capacity(code.len()); + let mut i = 0; + let mut depth = 0usize; + let mut in_line = false; + while i < len { + let c = chars[i]; + let next = chars.get(i + 1).copied(); + if c == '\n' { + in_line = false; + out.push('\n'); + i += 1; + } else if in_line { + out.push(' '); + i += 1; + } else if c == '/' && next == Some('*') { + depth += 1; + out.push_str(" "); + i += 2; + } else if depth > 0 && c == '*' && next == Some('/') { + depth -= 1; + out.push_str(" "); + i += 2; + } else if depth > 0 { + out.push(' '); + i += 1; + } else if c == '/' && next == Some('/') { + in_line = true; + out.push_str(" "); + i += 2; + } else { + out.push(c); + i += 1; + } + } + out +} + +/// The largest finite value of the type a WGSL float literal with this suffix has. +fn float_limit(suffix: Option) -> f64 { + if suffix == Some(b'h') { 65504.0 } else { f64::from(f32::MAX) } +} + +/// Read a WGSL hexadecimal literal starting at the `0` of `0x`. Returns the index after it, the length of +/// its text without a suffix, and whether it is a float above the range of its type. +fn scan_wgsl_hex(code: &[u8], start: usize) -> (usize, usize, bool) { + // Significant hex digits kept; 15 hold 60 bits, more than an f64 mantissa. + const KEPT: usize = 15; + let mut i = start + 2; + let mut mantissa = 0f64; + let mut kept = 0usize; + let mut exponent: i64 = 0; + let mut digits = 0usize; + let mut digit = |d: u8, fraction: bool, exponent: &mut i64| { + let value = (d as char).to_digit(16).unwrap_or(0); + if mantissa == 0.0 && value == 0 { + if fraction { + *exponent -= 4; + } + } else if kept < KEPT { + mantissa = mantissa * 16.0 + f64::from(value); + kept += 1; + if fraction { + *exponent -= 4; + } + } else if !fraction { + *exponent += 4; + } + }; + while i < code.len() && code[i].is_ascii_hexdigit() { + digit(code[i], false, &mut exponent); + digits += 1; + i += 1; + } + let mut is_float = false; + if code.get(i) == Some(&b'.') { + is_float = true; + i += 1; + while i < code.len() && code[i].is_ascii_hexdigit() { + digit(code[i], true, &mut exponent); + digits += 1; + i += 1; + } + } + let mut has_exponent = false; + if matches!(code.get(i), Some(b'p' | b'P')) { + let mut j = i + 1; + let negative = code.get(j) == Some(&b'-'); + if matches!(code.get(j), Some(b'+' | b'-')) { + j += 1; + } + if code.get(j).is_some_and(u8::is_ascii_digit) { + let mut e: i64 = 0; + while j < code.len() && code[j].is_ascii_digit() { + e = (e * 10 + i64::from(code[j] - b'0')).min(1_000_000); + j += 1; + } + exponent += if negative { -e } else { e }; + has_exponent = true; + is_float = true; + i = j; + } + } + let text_len = i - start; + let suffix = if has_exponent && matches!(code.get(i), Some(b'f' | b'h')) { code.get(i).copied() } else { None }; + let end = if suffix.is_some() || (!is_float && matches!(code.get(i), Some(b'i' | b'u'))) { i + 1 } else { i }; + if !is_float || digits == 0 || mantissa == 0.0 { + return (end, text_len, false); + } + let scale = i32::try_from(exponent.clamp(-4000, 4000)).unwrap_or(0); + let value = mantissa * 2f64.powi(scale); + (end, text_len, !value.is_finite() || value > float_limit(suffix)) +} + +/// Guard: scans a single WGSL shader string and detects float literals outside their type's finite range. /// -/// Browser WebGPU compilers (such as Chrome's Tint) reject float literals exceeding `f32::MAX` -/// (e.g. `3.40282347e38`), triggering fatal pipeline build errors and fallback to CPU rendering. -/// Exact values equal to `f32::MAX` should be written as hex float literals (e.g. `0x1.fffffep+127f`). +/// WebGPU compilers in browsers reject a float literal above `f32::MAX` (e.g. `3.40282347e38`) with a +/// pipeline build error, which turns off GPU rendering. Exact values equal to `f32::MAX` can be written +/// as `3.4028234663852886e38` or as the hex float `0x1.fffffep+127f`. /// /// ### Policy and Limitations /// -/// * **Conservative mathematical bound**: The guard evaluates the parsed mathematical magnitude against -/// `f64::from(f32::MAX)`. Any decimal literal exceeding this threshold is flagged, even if native -/// compilers like `naga` would round it down to `f32::MAX`. -/// * **Hexadecimal floats**: Exact hex float literals (`0x...p...`) are skipped as they represent exact bit patterns. -/// * **Comments and strings**: Comments (`//` and `/* ... */`) and string contents are masked out prior to scanning. +/// * **Conservative mathematical bound**: The guard compares the literal's value, rounded to `f64`, +/// with `f64::from(f32::MAX)`, or with 65504 (the largest finite `f16`) for an `h` suffix. Any literal +/// above it is reported, even one that a compiler would round down to the maximum. +/// * **Which literals**: decimal floats (with a `.`, an exponent or an `f`/`h` suffix) and hexadecimal floats +/// (`0x` with a `.` or a `p` exponent). Integer literals (`123`, `123u`, `0xFFi`, `0x1f`) are not floats and +/// are not reported. A `-` in front is not part of the literal, so `-1e39` is reported as `1e39`. +/// * **Comments**: Comments (`//` and nested `/* ... */`) are masked out prior to scanning. pub fn wgsl_float_literals(wgsl: &str) -> Vec { wgsl_float_literals_in([("", wgsl)]) } -/// Guard: scans multiple WGSL shader files and detects decimal float literals outside `f32`'s finite range. +/// Guard: scans multiple WGSL shader files and detects float literals outside their type's finite range, +/// with the rules of [`wgsl_float_literals`]. pub fn wgsl_float_literals_in(files: I) -> Vec where I: IntoIterator, @@ -359,8 +894,7 @@ where let mut findings = Vec::new(); for file in files { let path = file.path(); - let content = file.content(); - let masked = mask_comments_and_strings(content); + let masked = mask_wgsl_comments(file.content()); for (n, line) in masked.lines().enumerate() { let code = line.as_bytes(); @@ -372,40 +906,61 @@ where i += 1; continue; } - // Skip hex float literals (e.g. 0x1.fffffep+127f, 0x1.0p0h) + let start = i; if code[i] == b'0' && matches!(code.get(i + 1), Some(b'x' | b'X')) { - i += 2; - while i < code.len() && (code[i].is_ascii_hexdigit() || matches!(code[i], b'.' | b'p' | b'P' | b'+' | b'-' | b'f' | b'h')) { - i += 1; + let (end, text_len, over) = scan_wgsl_hex(code, i); + if over { + findings.push(Finding::new(path, n + 1, String::from_utf8_lossy(&code[start..start + text_len]).into_owned())); } + i = end.max(i + 1); continue; } - let start = i; - while i < code.len() && (code[i].is_ascii_digit() || code[i] == b'.') { + let mut is_float = false; + while i < code.len() && code[i].is_ascii_digit() { i += 1; } - if i < code.len() && matches!(code[i], b'e' | b'E') { + if code.get(i) == Some(&b'.') { + is_float = true; + i += 1; + while i < code.len() && code[i].is_ascii_digit() { + i += 1; + } + } + if matches!(code.get(i), Some(b'e' | b'E')) { let mut j = i + 1; - if j < code.len() && matches!(code[j], b'+' | b'-') { + if matches!(code.get(j), Some(b'+' | b'-')) { j += 1; } - if j < code.len() && code[j].is_ascii_digit() { + if code.get(j).is_some_and(u8::is_ascii_digit) { + is_float = true; i = j; while i < code.len() && code[i].is_ascii_digit() { i += 1; } } } - let literal = String::from_utf8_lossy(&code[start..i]); - if i < code.len() && matches!(code[i], b'f' | b'h') { - i += 1; + let literal = String::from_utf8_lossy(&code[start..i]).into_owned(); + let suffix = match code.get(i) { + Some(&s @ (b'f' | b'h')) => { + is_float = true; + i += 1; + Some(s) + } + Some(b'i' | b'u') if !is_float => { + i += 1; + None + } + _ => None, + }; + if !is_float { + continue; } let is_overflow = match literal.parse::() { - Ok(v) => !v.is_finite() || v.abs() > f64::from(f32::MAX), + Ok(v) => !v.is_finite() || v.abs() > float_limit(suffix), Err(_) => true, }; if is_overflow { - findings.push(Finding::new(path, n + 1, literal.into_owned())); + findings.push(Finding::new(path, n + 1, literal)); } } } @@ -413,7 +968,42 @@ where findings } -/// Recursively collect all Rust source files under `dir`, excluding test files and test directories. +/// Size limits for [`rust_sources_with_limits`]. An input over a limit is an error. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SourceLimits { + /// The largest single file read, in bytes. Default 8 MiB. + pub max_file_bytes: u64, + /// The largest total of all files read, in bytes. Default 256 MiB. + pub max_total_bytes: u64, + /// The most files read. Default 50,000. + pub max_files: usize, +} + +#[cfg(not(target_arch = "wasm32"))] +impl Default for SourceLimits { + fn default() -> Self { + Self { max_file_bytes: 8 << 20, max_total_bytes: 256 << 20, max_files: 50_000 } + } +} + +/// The first line of a `CACHEDIR.TAG` file, which marks a folder of generated files +/// (). Cargo writes one in each target folder. +#[cfg(not(target_arch = "wasm32"))] +const CACHEDIR_SIGNATURE: &[u8] = b"Signature: 8a477f597d28d172789f06886806bc55"; + +#[cfg(not(target_arch = "wasm32"))] +fn is_cache_dir(dir: &Path) -> bool { + use std::io::Read; + let Ok(file) = std::fs::File::open(dir.join("CACHEDIR.TAG")) else { + return false; + }; + let mut head = Vec::with_capacity(CACHEDIR_SIGNATURE.len()); + file.take(CACHEDIR_SIGNATURE.len() as u64).read_to_end(&mut head).is_ok() && head == CACHEDIR_SIGNATURE +} + +/// Recursively collect all Rust source files under `dir`, excluding test files and test directories, +/// with the default [`SourceLimits`]. /// /// Excluded files: /// * `tests.rs` @@ -421,29 +1011,44 @@ where /// * `*_tests.rs` /// * `*_test.rs` /// * `test.rs` -/// * Any file within a directory component named `tests`, `benches`, `examples`, `.git`, or `target`. +/// * Any file below `dir` within a directory named `tests`, `benches`, `examples` or `target`, or whose +/// name starts with `.`, or that holds a `CACHEDIR.TAG` file (a build output folder with another name). +/// * Symbolic links (and, on Windows, junctions) to files or folders, which are not followed. /// /// Results are sorted lexicographically by file path for deterministic behavior across platforms. #[cfg(not(target_arch = "wasm32"))] pub fn rust_sources(dir: impl AsRef) -> std::io::Result> { + rust_sources_with_limits(dir, SourceLimits::default()) +} + +/// [`rust_sources`] with explicit size limits. A file over `max_file_bytes` returns an error of kind +/// [`std::io::ErrorKind::FileTooLarge`]; more than `max_files` files or `max_total_bytes` bytes in all +/// returns an error of kind [`std::io::ErrorKind::QuotaExceeded`]. +#[cfg(not(target_arch = "wasm32"))] +pub fn rust_sources_with_limits(dir: impl AsRef, limits: SourceLimits) -> std::io::Result> { + use std::io::{Error, ErrorKind, Read}; + let root = dir.as_ref(); let mut files = Vec::new(); + let mut total: u64 = 0; let mut dirs = vec![root.to_path_buf()]; while let Some(d) = dirs.pop() { - let entries = std::fs::read_dir(&d)?; - for entry in entries { + for entry in std::fs::read_dir(&d)? { let entry = entry?; let p = entry.path(); - let metadata = std::fs::metadata(&p)?; - if metadata.is_dir() { - let dirname = p.file_name().and_then(|n| n.to_str()).unwrap_or_default(); - if dirname.starts_with('.') || dirname == "target" || dirname == "tests" || dirname == "benches" || dirname == "examples" { + let kind = entry.file_type()?; + if kind.is_symlink() { + continue; + } + let name = entry.file_name(); + let name = name.to_string_lossy(); + if kind.is_dir() { + if name.starts_with('.') || name == "target" || name == "tests" || name == "benches" || name == "examples" || is_cache_dir(&p) { continue; } dirs.push(p); - } else if metadata.is_file() { - let name = p.file_name().and_then(|n| n.to_str()).unwrap_or_default(); + } else if kind.is_file() { if !name.ends_with(".rs") { continue; } @@ -451,10 +1056,29 @@ pub fn rust_sources(dir: impl AsRef) -> std::io::Result= limits.max_files { + return Err(Error::new( + ErrorKind::QuotaExceeded, + format!("more than {} Rust source files under {}", limits.max_files, root.display()), + )); + } + let over_file = || Error::new(ErrorKind::FileTooLarge, format!("{} is larger than {} bytes", p.display(), limits.max_file_bytes)); + if entry.metadata()?.len() > limits.max_file_bytes { + return Err(over_file()); + } + let mut content = String::new(); + std::fs::File::open(&p)?.take(limits.max_file_bytes.saturating_add(1)).read_to_string(&mut content)?; + let size = content.len() as u64; + if size > limits.max_file_bytes { + return Err(over_file()); + } + total = total.saturating_add(size); + if total > limits.max_total_bytes { + return Err(Error::new( + ErrorKind::QuotaExceeded, + format!("Rust sources under {} are larger than {} bytes in all", root.display(), limits.max_total_bytes), + )); } - let content = std::fs::read_to_string(&p)?; files.push((p.display().to_string(), content)); } } diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index b0e61fc8b5..b484c6ef69 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -8,11 +8,12 @@ //! //! * [`guards::predefined_quit`]: flags direct calls to `muda`'s predefined Quit item that bypass //! dirty document save prompts and window teardown on macOS. -//! * [`guards::wgsl_float_literals`]: flags decimal float literals exceeding `f32`'s finite range, -//! which break browser WebGPU compilers (Tint) and trigger CPU fallbacks. +//! * [`guards::wgsl_float_literals`]: flags WGSL float literals above the finite range of `f32` +//! (or of `f16` for an `h` suffix), which browser WebGPU compilers reject. //! * [`guards::std_instant`]: flags uses of `std::time::Instant` in code paths targeting the web, //! where `std::time::Instant::now()` panics on `wasm32`. -//! * [`guards::rust_sources`]: directory crawler collecting `.rs` sources while excluding tests. +//! * [`guards::rust_sources`]: directory crawler collecting `.rs` sources while excluding tests, with +//! size limits ([`guards::rust_sources_with_limits`]). It is not built for `wasm32`. //! //! ### Epistemic Scope: What Source Guards Establish vs What They Cannot //! @@ -26,7 +27,7 @@ pub mod guards; -pub use guards::{Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; +pub use guards::{AsFileSource, Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; #[cfg(not(target_arch = "wasm32"))] -pub use guards::rust_sources; +pub use guards::{SourceLimits, rust_sources, rust_sources_with_limits}; diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index ee6daae7d7..a2a419ca18 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -1,5 +1,54 @@ use craft_testkit::{Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; +/// A scratch folder under the system temporary folder that this test made and removes on drop, +/// also when the test panics. A folder that already exists is never emptied or reused. +#[cfg(not(target_arch = "wasm32"))] +struct ScratchDir(std::path::PathBuf); + +#[cfg(not(target_arch = "wasm32"))] +impl ScratchDir { + fn new(tag: &str) -> Self { + let base = std::env::temp_dir(); + for n in 0..1000u32 { + let path = base.join(format!("craft_testkit_{tag}_{}_{n}", std::process::id())); + match std::fs::create_dir(&path) { + Ok(()) => return Self(path), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => panic!("create scratch folder {}: {e}", path.display()), + } + } + panic!("no free scratch folder name for {tag}"); + } + + fn path(&self) -> &std::path::Path { + &self.0 + } + + fn write(&self, relative: &str, content: &str) { + let path = self.0.join(relative); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).expect("create parent folder"); + } + std::fs::write(path, content).expect("write file"); + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for ScratchDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +#[cfg(not(target_arch = "wasm32"))] +fn file_names(sources: &[(String, String)]) -> Vec { + sources.iter().map(|(p, _)| std::path::Path::new(p).file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()).collect() +} + +fn lines(findings: &[Finding]) -> Vec { + findings.iter().map(|f| f.line).collect() +} + #[test] fn test_finding_display() { let f1 = Finding::new("src/menu.rs", 42, "PredefinedMenuItem::quit()"); @@ -287,44 +336,332 @@ const OVER_NEG: f32 = -3.40282347e38; assert_eq!(findings[1].text, "3.40282347e38"); } +#[test] +fn character_literals_do_not_hide_the_code_after_them() { + let source = r#" +fn menu<'a>(label: &'a str) { + let quote = '"'; + let quit = PredefinedMenuItem::quit(None); + let apostrophe = '\''; + let t0 = std::time::Instant::now(); + let b = b'"'; + let later = PredefinedMenuItem::quit(Some(label)); +} +"#; + assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![4, 8]); + assert_eq!(lines(&std_instant([("src/menu.rs", source)])), vec![6]); +} + +#[test] +fn strings_hold_comment_markers_without_hiding_code() { + let source = r##" +fn menu() { + let a = "/* not a comment"; + let quit = PredefinedMenuItem::quit(None); + let b = b"// not a comment either"; + let c = r#"*/ " still a raw string"#; + let t0 = std::time::Instant::now(); + let d = "PredefinedMenuItem::quit std::time::Instant"; +} +"##; + assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![4]); + assert_eq!(lines(&std_instant([("src/menu.rs", source)])), vec![7]); +} + +#[test] +fn nested_block_comments_stay_masked() { + let source = "/* outer /* inner */ PredefinedMenuItem::quit(None); std::time::Instant::now(); */\nlet q = PredefinedMenuItem::quit(None);\n"; + assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![2]); + assert!(std_instant([("src/menu.rs", source)]).is_empty()); +} + +#[test] +fn predefined_quit_sees_tabs_and_line_breaks_around_the_path_separator() { + let source = "fn menu() {\n let a = PredefinedMenuItem\t::\tquit(None);\n let b = muda::PredefinedMenuItem\n ::quit(None);\n}\n"; + let findings = predefined_quit([("src/menu.rs", source)]); + assert_eq!(lines(&findings), vec![2, 3]); + assert_eq!(findings[1].text, "let b = muda::PredefinedMenuItem"); +} + +#[test] +fn predefined_quit_matches_whole_names_only() { + let other_names = r#" +fn menu() { + let a = MyPredefinedMenuItem::quit(None); + let b = PredefinedMenuItem::quitter(); + let c = PredefinedMenuItem::quit_label(); +} +"#; + assert!(predefined_quit([("src/menu.rs", other_names)]).is_empty()); + + let aliased = r#" +use muda::{PredefinedMenuItem as Item, MenuItem}; +fn menu() { + let a = Item::quit(None); + let b = other::Item::quit(None); +} +"#; + assert_eq!(lines(&predefined_quit([("src/menu.rs", aliased)])), vec![4]); + + let other_crate = r#" +use other_menu::PredefinedMenuItem as Item; +fn menu() { + let a = Item::quit(None); +} +"#; + assert!(predefined_quit([("src/menu.rs", other_crate)]).is_empty()); +} + +#[test] +fn std_instant_ignores_an_alias_that_only_a_native_cfg_imports() { + let source = r#" +#[cfg(not(target_arch = "wasm32"))] +use std::time as clock; +#[cfg(target_arch = "wasm32")] +use web_time as clock; + +fn now() { + let t = clock::Instant::now(); +} +"#; + assert!(std_instant([("src/clock.rs", source)]).is_empty()); +} + +#[test] +fn std_instant_reads_cfg_from_code_not_from_strings_or_comments() { + let cfg_in_string = r##" +fn now() -> u64 { let _s = r#"cfg(target_os = "linux")"#; + let t = std::time::Instant::now(); + 0 +} +"##; + assert_eq!(lines(&std_instant([("src/a.rs", cfg_in_string)])), vec![3]); + + let cfg_in_comment = r#" +fn web() { // cfg(target_os = "linux") + let t = std::time::Instant::now(); +} +"#; + assert_eq!(lines(&std_instant([("src/b.rs", cfg_in_comment)])), vec![3]); +} + +#[test] +fn std_instant_skips_only_the_item_a_native_cfg_covers() { + let source = r#" +#[cfg(not(target_arch = "wasm32"))] +fn native() -> std::time::Instant { std::time::Instant::now() } +fn web() -> std::time::Instant { std::time::Instant::now() } + +#[cfg(all(unix, not(target_arch = "wasm32")))] +#[inline] +fn unix_only() { + let t = std::time::Instant::now(); +} + +#[cfg(feature = "native-clock")] +fn by_feature() { let t = std::time::Instant::now(); } + +#[cfg(any(target_arch = "wasm32", windows))] +fn also_web() { let t = std::time::Instant::now(); } + +#[cfg(target_os = "unknown")] +fn unknown_os() { let t = std::time::Instant::now(); } + +#[cfg(target_os = "macos")] +use std::time::Instant as MacInstant; +"#; + assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![4, 13, 16, 19]); +} + +#[test] +fn std_instant_inner_cfg_covers_the_whole_file() { + let source = r#" +#![cfg(not(target_arch = "wasm32"))] +use std::time::Instant; + +fn now() -> Instant { + std::time::Instant::now() +} +"#; + assert!(std_instant([("src/native.rs", source)]).is_empty()); +} + +#[test] +fn std_instant_reports_a_std_use_on_a_line_that_also_names_web_time() { + let source = "fn pair() {\n let p = (web_time::Instant::now(), std::time::Instant::now());\n}\n"; + assert_eq!(lines(&std_instant([("src/pair.rs", source)])), vec![2]); +} + +#[test] +fn std_instant_needs_std_behind_a_bare_time_path() { + let source = r#" +use crate::time; + +fn tick() { + let t = time::Instant::new(); +} +"#; + assert!(std_instant([("src/tick.rs", source)]).is_empty()); +} + +#[test] +fn std_instant_follows_module_and_type_aliases() { + let source = r#" +use std::time as t; +use std::time::{self as clock, Duration}; +use std::{time::Instant as I, fmt}; +use web_time as wt; + +fn run() { + let a = t::Instant::now(); + let b = clock::Instant::now(); + let c = wt::Instant::now(); + let d = x::t::Instant::now(); +} +"#; + assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![4, 8, 9]); +} + +#[test] +fn wgsl_integer_literals_are_not_floats() { + let shader = r#" +const BIG_ABSTRACT = 400000000000000000000000000000000000000000; +const BIG_U = 1000000000000000000000000000000000000000u; +const BIG_I = 1000000000000000000000000000000000000000i; +const HEX_INT = 0xFFFFFFFFu; +const HEX_F_DIGIT = 0x1f; +const FLOAT_DOT: f32 = 340282356779733661637539395458142568448.0; +const FLOAT_SUFFIX: f32 = 400000000000000000000000000000000000000f; +const NEG_EXP: f32 = -4e38; +"#; + let findings = wgsl_float_literals(shader); + assert_eq!(lines(&findings), vec![7, 8, 9]); + assert_eq!(findings[0].text, "340282356779733661637539395458142568448.0"); + assert_eq!(findings[1].text, "400000000000000000000000000000000000000"); + assert_eq!(findings[2].text, "4e38"); +} + +#[test] +fn wgsl_hex_floats_outside_the_range_are_reported() { + let shader = r#" +const EXACT_MAX: f32 = 0x1.fffffep+127f; +const HUGE: f32 = 0x1p+500f; +const JUST_OVER: f32 = 0x1.000002p+128; +const UPPER: f32 = 0X1P128; +const TINY: f32 = 0x1p-500; +const ZERO: f32 = 0x0.0p99999; +const F16_MAX: f16 = 0x1.ffcp15h; +const F16_OVER: f16 = 0x1.0p16h; +"#; + let findings = wgsl_float_literals(shader); + assert_eq!(lines(&findings), vec![3, 4, 5, 9]); + assert_eq!(findings[0].text, "0x1p+500"); + assert_eq!(findings[3].text, "0x1.0p16"); +} + +#[test] +fn wgsl_block_comment_markers_inside_line_comments_do_not_open_a_comment() { + let shader = "// a /* inside a line comment\nconst BAD: f32 = 4e38;\n/* block // with a line marker */ const ALSO_BAD: f32 = 5e38;\n"; + let findings = wgsl_float_literals(shader); + assert_eq!(lines(&findings), vec![2, 3]); +} + +#[test] +fn wgsl_half_floats_use_the_f16_range() { + let shader = "const OK: f16 = 65504.0h;\nconst OVER: f16 = 70000.0h;\nconst F32_OK: f32 = 70000.0f;\n"; + let findings = wgsl_float_literals(shader); + assert_eq!(lines(&findings), vec![2]); + assert_eq!(findings[0].text, "70000.0"); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn test_rust_sources_filtering() { use craft_testkit::rust_sources; - use std::fs::{self, File}; - use std::io::Write; - let temp_dir = std::env::temp_dir().join(format!("craft_testkit_test_{}", std::process::id())); - let _ = fs::remove_dir_all(&temp_dir); - fs::create_dir_all(temp_dir.join("src").join("sub")).expect("create temp sub"); - fs::create_dir_all(temp_dir.join("tests")).expect("create temp tests"); - fs::create_dir_all(temp_dir.join("target")).expect("create temp target"); - fs::create_dir_all(temp_dir.join(".github")).expect("create temp dot-dir"); + let dir = ScratchDir::new("filtering"); + dir.write("src/lib.rs", "pub fn lib() {}"); + dir.write("src/sub/mod.rs", "pub fn sub() {}"); + dir.write("src/tests.rs", "// should exclude"); + dir.write("src/tests_foo.rs", "// should exclude"); + dir.write("src/foo_tests.rs", "// should exclude"); + dir.write("src/foo_test.rs", "// should exclude"); + dir.write("tests/integ.rs", "// should exclude"); + dir.write("target/gen.rs", "// should exclude"); + dir.write(".github/action.rs", "// should exclude dot-dir"); + dir.write("src/README.md", "# Not a rust source"); - let create_file = |path: std::path::PathBuf, content: &str| { - let mut f = File::create(path).expect("create file"); - f.write_all(content.as_bytes()).expect("write content"); - }; + let sources = rust_sources(dir.path()).expect("rust_sources"); + assert_eq!(file_names(&sources), vec!["lib.rs", "mod.rs"]); - create_file(temp_dir.join("src").join("lib.rs"), "pub fn lib() {}"); - create_file(temp_dir.join("src").join("sub").join("mod.rs"), "pub fn sub() {}"); - create_file(temp_dir.join("src").join("tests.rs"), "// should exclude"); - create_file(temp_dir.join("src").join("tests_foo.rs"), "// should exclude"); - create_file(temp_dir.join("src").join("foo_tests.rs"), "// should exclude"); - create_file(temp_dir.join("src").join("foo_test.rs"), "// should exclude"); - create_file(temp_dir.join("tests").join("integ.rs"), "// should exclude"); - create_file(temp_dir.join("target").join("gen.rs"), "// should exclude"); - create_file(temp_dir.join(".github").join("action.rs"), "// should exclude dot-dir"); - create_file(temp_dir.join("src").join("README.md"), "# Not a rust source"); - - let sources = rust_sources(&temp_dir).expect("rust_sources"); - let names: Vec = sources.iter().map(|(p, _)| std::path::Path::new(p).file_name().unwrap().to_string_lossy().into_owned()).collect(); - - assert_eq!(names, vec!["lib.rs", "mod.rs"]); - - // Test passing &[(&str, &str)] to guards + // Test passing &[(String, String)] to guards let findings = predefined_quit(&sources); assert!(findings.is_empty()); +} - let _ = fs::remove_dir_all(&temp_dir); +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn rust_sources_lists_a_root_inside_a_folder_named_tests() { + let dir = ScratchDir::new("root_in_tests"); + dir.write("tests/app/src/lib.rs", "pub fn lib() {}"); + let sources = craft_testkit::rust_sources(dir.path().join("tests").join("app")).expect("rust_sources"); + assert_eq!(file_names(&sources), vec!["lib.rs"]); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn rust_sources_skips_build_output_folders_marked_with_cachedir_tag() { + let dir = ScratchDir::new("cachedir"); + dir.write("src/lib.rs", "pub fn lib() {}"); + dir.write("out/CACHEDIR.TAG", "Signature: 8a477f597d28d172789f06886806bc55\n# build output\n"); + dir.write("out/debug/build/gen.rs", "pub fn generated() {}"); + dir.write("notes/CACHEDIR.TAG", "not a cache tag\n"); + dir.write("notes/kept.rs", "pub fn kept() {}"); + let sources = craft_testkit::rust_sources(dir.path()).expect("rust_sources"); + assert_eq!(file_names(&sources), vec!["kept.rs", "lib.rs"]); +} + +#[cfg(unix)] +#[test] +fn rust_sources_does_not_follow_a_symlink_out_of_the_root() { + let outside = ScratchDir::new("symlink_outside"); + outside.write("evil.rs", "pub fn evil() {}"); + let dir = ScratchDir::new("symlink_root"); + dir.write("src/lib.rs", "pub fn lib() {}"); + std::os::unix::fs::symlink(outside.path(), dir.path().join("src").join("linked")).expect("symlink folder"); + std::os::unix::fs::symlink(outside.path().join("evil.rs"), dir.path().join("src").join("evil.rs")).expect("symlink file"); + let sources = craft_testkit::rust_sources(dir.path()).expect("rust_sources"); + assert_eq!(file_names(&sources), vec!["lib.rs"]); +} + +#[cfg(unix)] +#[test] +fn rust_sources_does_not_loop_on_a_symlink_cycle() { + let dir = ScratchDir::new("symlink_cycle"); + dir.write("src/lib.rs", "pub fn lib() {}"); + std::os::unix::fs::symlink(dir.path().join("src"), dir.path().join("src").join("again")).expect("symlink cycle"); + let sources = craft_testkit::rust_sources(dir.path()).expect("rust_sources"); + assert_eq!(file_names(&sources), vec!["lib.rs"]); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn scratch_dirs_leave_existing_folders_alone_and_clean_up_on_panic() { + let taken = std::env::temp_dir().join(format!("craft_testkit_sentinel_{}_0", std::process::id())); + std::fs::create_dir(&taken).expect("create the folder the helper would pick first"); + std::fs::write(taken.join("sentinel"), "keep").expect("write sentinel"); + + let made = std::panic::catch_unwind(|| { + let dir = ScratchDir::new("sentinel"); + let path = dir.path().to_path_buf(); + assert!(path.exists()); + std::panic::panic_any(path); + }); + let payload = made.expect_err("the closure panics"); + let path = payload.downcast_ref::().expect("panic payload is the path").clone(); + + assert_ne!(path, taken); + assert!(!path.exists(), "the scratch folder is removed when the test panics"); + assert_eq!(std::fs::read_to_string(taken.join("sentinel")).expect("sentinel survives"), "keep"); + std::fs::remove_dir_all(&taken).expect("remove the pre-made folder"); } diff --git a/crates/testkit/tests/source_limits.rs b/crates/testkit/tests/source_limits.rs new file mode 100644 index 0000000000..a90b7f4cf4 --- /dev/null +++ b/crates/testkit/tests/source_limits.rs @@ -0,0 +1,99 @@ +#![cfg(not(target_arch = "wasm32"))] + +use craft_testkit::{SourceLimits, rust_sources_with_limits}; +use std::io::ErrorKind; +use std::path::{Path, PathBuf}; + +/// A scratch folder that this test made and removes on drop, also when the test panics. +struct ScratchDir(PathBuf); + +impl ScratchDir { + fn new(tag: &str) -> Self { + let base = std::env::temp_dir(); + for n in 0..1000u32 { + let path = base.join(format!("craft_testkit_limits_{tag}_{}_{n}", std::process::id())); + match std::fs::create_dir(&path) { + Ok(()) => return Self(path), + Err(e) if e.kind() == ErrorKind::AlreadyExists => continue, + Err(e) => panic!("create scratch folder {}: {e}", path.display()), + } + } + panic!("no free scratch folder name for {tag}"); + } + + fn path(&self) -> &Path { + &self.0 + } + + fn write(&self, relative: &str, content: &str) { + let path = self.0.join(relative); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).expect("create parent folder"); + } + std::fs::write(path, content).expect("write file"); + } +} + +impl Drop for ScratchDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +fn three_files(tag: &str) -> ScratchDir { + let dir = ScratchDir::new(tag); + dir.write("src/a.rs", "0123456789"); + dir.write("src/b.rs", "0123456789"); + dir.write("src/c.rs", "0123456789"); + dir +} + +#[test] +fn defaults_are_documented_values() { + let limits = SourceLimits::default(); + assert_eq!(limits.max_file_bytes, 8 << 20); + assert_eq!(limits.max_total_bytes, 256 << 20); + assert_eq!(limits.max_files, 50_000); +} + +#[test] +fn files_within_the_limits_are_read() { + let dir = three_files("within"); + let limits = SourceLimits { max_file_bytes: 10, max_total_bytes: 30, max_files: 3 }; + let sources = rust_sources_with_limits(dir.path(), limits).expect("within limits"); + assert_eq!(sources.len(), 3); + assert!(sources.iter().all(|(_, content)| content == "0123456789")); +} + +#[test] +fn a_file_over_the_size_limit_is_an_error() { + let dir = three_files("file"); + let limits = SourceLimits { max_file_bytes: 9, ..SourceLimits::default() }; + let err = rust_sources_with_limits(dir.path(), limits).expect_err("file over the limit"); + assert_eq!(err.kind(), ErrorKind::FileTooLarge); +} + +#[test] +fn files_over_the_total_limit_are_an_error() { + let dir = three_files("total"); + let limits = SourceLimits { max_total_bytes: 29, ..SourceLimits::default() }; + let err = rust_sources_with_limits(dir.path(), limits).expect_err("total over the limit"); + assert_eq!(err.kind(), ErrorKind::QuotaExceeded); +} + +#[test] +fn more_files_than_the_count_limit_is_an_error() { + let dir = three_files("count"); + let limits = SourceLimits { max_files: 2, ..SourceLimits::default() }; + let err = rust_sources_with_limits(dir.path(), limits).expect_err("too many files"); + assert_eq!(err.kind(), ErrorKind::QuotaExceeded); +} + +#[test] +fn files_the_filter_skips_do_not_count_against_the_limits() { + let dir = three_files("skipped"); + dir.write("src/tests.rs", &"x".repeat(100)); + dir.write("tests/big.rs", &"x".repeat(100)); + let limits = SourceLimits { max_file_bytes: 10, max_total_bytes: 30, max_files: 3 }; + assert_eq!(rust_sources_with_limits(dir.path(), limits).expect("skipped files are not read").len(), 3); +} From d3783357223e56be0a5615e2639e6573ae91fcf0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:17:12 -0800 Subject: [PATCH 011/322] craft-testkit: add the serial module with a reentrant test lock TestLock is a lock a static can hold (TestLock::new is const). The thread that holds it can take it again, and it is released when the last of that thread's guards is dropped, in any order. A panic while it is held does not block the next holder, and a poisoned internal mutex is recovered. Guards are not Send. gpu_lock() is the one lock of the process for GPU tests, and hold_gpu_lock() keeps it until the calling thread ends; a second call on the same thread does nothing more. The module is native only and reads no environment variables. The lock comes from PhotoCraft's crates/testkit/src/gpu.rs and DeckCraft's crates/ui-egui/src/gpu_lock.rs, with the thread-held form from EffectCraft's crates/gpu/src/tests.rs. a_panicked_holder_does_not_block_the_next_test and holders_take_turns keep their names; holders_take_turns now waits on channels instead of sleeping 2 ms. --- Cargo.lock | 4 + Cargo.toml | 1 + crates/testkit/Cargo.toml | 14 ++ crates/testkit/README.md | 48 +++++ crates/testkit/src/lib.rs | 11 ++ crates/testkit/src/serial.rs | 331 +++++++++++++++++++++++++++++++++++ 6 files changed, 409 insertions(+) create mode 100644 crates/testkit/Cargo.toml create mode 100644 crates/testkit/README.md create mode 100644 crates/testkit/src/lib.rs create mode 100644 crates/testkit/src/serial.rs diff --git a/Cargo.lock b/Cargo.lock index 3d8cf4a7b3..7b8d513e3b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2569,6 +2569,10 @@ dependencies = [ "kurbo 0.13.1", ] +[[package]] +name = "craft-testkit" +version = "0.1.0" + [[package]] name = "craft-text" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 576efca6f1..fab6b70440 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -138,6 +138,7 @@ craft-stencilcraft-format = { path = "crates/stencilcraft-format" } craft-stencilcraft-document = { path = "crates/stencilcraft-document" } craft-svg-paths = { path = "crates/svg-paths" } craft-stream-codecs = { path = "crates/stream-codecs" } +craft-testkit = { path = "crates/testkit" } craft-text = { path = "crates/text" } craft-texture = { path = "crates/texture" } craft-tga = { path = "crates/tga" } diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml new file mode 100644 index 0000000000..5a67bd19b2 --- /dev/null +++ b/crates/testkit/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "craft-testkit" +description = "Shared test support for the Craft apps: a reentrant test lock and other helpers. Test support only." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true +publish = false + +[dependencies] + +[lints] +workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md new file mode 100644 index 0000000000..485496ea77 --- /dev/null +++ b/crates/testkit/README.md @@ -0,0 +1,48 @@ +# craft-testkit + +Shared test support for the Craft apps. The crate is not published, and apps and craft-libs crates +take it under `[dev-dependencies]`. + +## serial + +`serial` is native only. + +- `TestLock::new()` is `const`, so a lock can be a `static`: + `static L: TestLock = TestLock::new(); let _g = L.hold();`. +- The thread that holds a lock can call `hold()` again. The lock is released when the last of that + thread's guards is dropped, in any order. +- A test that panics while it holds a lock does not block the next one, and a poisoned internal + mutex is recovered. +- `gpu_lock()` is the one lock of the process for tests that build a GPU harness or device. + `hold_gpu_lock()` takes it and keeps it until the calling thread ends; a second call on the same + thread does nothing more. +- A guard is not `Send`. The lock covers one process: under nextest each test runs in its own + process. +- The module reads no environment variables and prints nothing. + +The tests use channel handshakes and contain no sleeps or time limits. + +## Origin + +| Module | Source repository | Path | SHA | +|---|---|---|---| +| `serial` | storytold/photocraft | `crates/testkit/src/gpu.rs` | `0d3b1e8523` | +| `serial` | storytold/deckcraft | `crates/ui-egui/src/gpu_lock.rs` | `b0c77ebd6a` | +| `serial` | storytold/effectcraft | `crates/ui-egui/tests/it/gpu_test.rs`, `crates/gpu/src/tests.rs` | `f029bbadb2` | +| `serial` | storytold/pdfcraft | `apps/pdfcraft/src/tests.rs` | `346d803080` | + +`a_panicked_holder_does_not_block_the_next_test` and `holders_take_turns` keep their names from +PhotoCraft and DeckCraft. `holders_take_turns` waits on channels where the copies slept 2 ms. + +## Migration + +| Consumer | Module | Switched | +|---|---|---| +| PhotoCraft | `serial` | No | +| DeckCraft | `serial` | No | +| EffectCraft | `serial` | No | +| PdfCraft | `serial` | No | + +## Maintainer + +To be agreed in the review of the crate's first pull request. diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs new file mode 100644 index 0000000000..9830ded4ef --- /dev/null +++ b/crates/testkit/src/lib.rs @@ -0,0 +1,11 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] +//! Shared test support for the Craft apps. Test support only: unpublished, and used as a +//! dev-dependency. +//! +//! [`serial`] holds [`serial::TestLock`], a lock that a `static` can hold and that the thread +//! holding it can take again, and [`serial::gpu_lock`], the one lock every GPU test of a process +//! takes. It is native only. + +#[cfg(not(target_arch = "wasm32"))] +pub mod serial; diff --git a/crates/testkit/src/serial.rs b/crates/testkit/src/serial.rs new file mode 100644 index 0000000000..72fa9cff78 --- /dev/null +++ b/crates/testkit/src/serial.rs @@ -0,0 +1,331 @@ +//! Locks that keep the tests of one process out of a section at the same time. +//! +//! `cargo test` runs a binary's tests on parallel threads. A test that must not overlap another +//! one takes a [`TestLock`] for its whole run: +//! +//! ``` +//! use craft_testkit::serial::TestLock; +//! +//! static FILES: TestLock = TestLock::new(); +//! +//! let _files = FILES.hold(); +//! // The rest of the test runs while no other thread holds `FILES`. +//! ``` +//! +//! The thread that holds a lock can take it again. Each [`TestLock::hold`] returns a guard, and the +//! lock is free again when the last of that thread's guards is dropped, in any order. A test that +//! panics while it holds a lock releases the lock as its guards unwind, so the next test is not +//! blocked. A lock works inside one process only: under nextest each test is its own process, and +//! the lock is never contended. Waiting threads take the lock in no particular order. +//! +//! [`gpu_lock`] is the one lock of the process for tests that build a GPU harness or a wgpu device. +//! Several graphics drivers crash when one process drives wgpu devices from more than one thread +//! at once. Take it on the test's first line (`let _gpu = gpu_lock();`) so it is released last. +//! [`hold_gpu_lock`] takes the same lock and keeps it until the calling thread ends. + +use std::cell::RefCell; +use std::marker::PhantomData; +use std::rc::Rc; +use std::sync::{Condvar, Mutex, MutexGuard, PoisonError}; +use std::thread::{self, ThreadId}; + +/// Which thread holds a [`TestLock`], and how many of its guards are alive. +#[derive(Debug)] +struct State { + owner: Option, + depth: usize, + /// Threads blocked in [`TestLock::hold`], so a test can tell that a thread is waiting. + #[cfg(test)] + waiting: usize, +} + +/// A lock for tests that one thread holds at a time and that the holding thread can take again. +/// +/// [`TestLock::new`] is `const`, so a lock can be a `static`. A panic while the lock is held does +/// not poison it. +#[derive(Debug)] +pub struct TestLock { + state: Mutex, + free: Condvar, +} + +impl TestLock { + /// A lock that no thread holds. + pub const fn new() -> Self { + Self { + state: Mutex::new(State { + owner: None, + depth: 0, + #[cfg(test)] + waiting: 0, + }), + free: Condvar::new(), + } + } + + /// Waits until no other thread holds the lock, then holds it until the returned guard and every + /// other guard of this thread are dropped. A thread that already holds the lock gets another + /// guard at once. + /// + /// A thread that keeps `usize::MAX` guards alive at once (for example by forgetting them) blocks + /// in its next call instead of letting the count wrap. + pub fn hold(&self) -> TestLockGuard<'_> { + let me = thread::current().id(); + let mut state = self.lock_state(); + loop { + match state.owner { + None => { + state.owner = Some(me); + state.depth = 1; + break; + } + Some(owner) if owner == me && state.depth < usize::MAX => { + state.depth += 1; + break; + } + Some(_) => { + #[cfg(test)] + { + state.waiting += 1; + } + state = self.free.wait(state).unwrap_or_else(PoisonError::into_inner); + #[cfg(test)] + { + state.waiting -= 1; + } + } + } + } + drop(state); + TestLockGuard { lock: self, not_send: PhantomData } + } + + fn lock_state(&self) -> MutexGuard<'_, State> { + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } +} + +impl Default for TestLock { + fn default() -> Self { + Self::new() + } +} + +/// One hold of a [`TestLock`]. The lock is released when the last guard of the holding thread is +/// dropped. A guard is not `Send`: it is dropped on the thread that took it. +#[derive(Debug)] +#[must_use = "the lock is released when the guard is dropped"] +pub struct TestLockGuard<'a> { + lock: &'a TestLock, + not_send: PhantomData>, +} + +impl Drop for TestLockGuard<'_> { + fn drop(&mut self) { + let mut state = self.lock.lock_state(); + state.depth = state.depth.saturating_sub(1); + if state.depth == 0 { + state.owner = None; + drop(state); + self.lock.free.notify_one(); + } + } +} + +static GPU_LOCK: TestLock = TestLock::new(); + +thread_local! { + static HELD_GPU: RefCell>> = const { RefCell::new(None) }; +} + +/// Holds the process's GPU lock for as long as the guard lives. Take it before the test creates a +/// GPU harness or device, and keep it for the whole test, harness included. +pub fn gpu_lock() -> TestLockGuard<'static> { + GPU_LOCK.hold() +} + +/// Holds the process's GPU lock until the calling thread ends. Calling it again on the same thread +/// does nothing more. Called on a long-lived thread, such as a harness's main thread, it keeps +/// every other thread out of [`gpu_lock`] until that thread ends. +/// +/// The lock is released by the thread's local-variable destructors, so it is not released when the +/// process exits or aborts while the thread runs. While the thread's locals are being destroyed, +/// the call returns without taking the lock. +pub fn hold_gpu_lock() { + let _ = HELD_GPU.try_with(|held| { + if let Ok(mut held) = held.try_borrow_mut() + && held.is_none() + { + *held = Some(gpu_lock()); + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::mpsc; + + fn owner_and_depth(lock: &TestLock) -> (Option, usize) { + let state = lock.lock_state(); + (state.owner, state.depth) + } + + /// Yields until `ready` is true of the lock's state. + fn until(lock: &TestLock, ready: impl Fn(&State) -> bool) { + while !ready(&lock.lock_state()) { + thread::yield_now(); + } + } + + #[test] + fn a_panicked_holder_does_not_block_the_next_test() { + let holder = thread::spawn(|| { + let _gpu = gpu_lock(); + panic!("a GPU test failed"); + }); + let id = holder.thread().id(); + let _ = holder.join(); + assert_ne!(owner_and_depth(&GPU_LOCK).0, Some(id)); + drop(gpu_lock()); + } + + #[test] + fn poisoned_state_recovers() { + let lock = &TestLock::new(); + let poisoned = thread::scope(|s| { + s.spawn(|| { + let _state = lock.state.lock(); + panic!("poison the state"); + }) + .join() + }); + assert!(poisoned.is_err()); + assert!(lock.state.is_poisoned()); + let outer = lock.hold(); + thread::scope(|s| { + let (tx, rx) = mpsc::channel(); + s.spawn(move || { + let _held = lock.hold(); + tx.send(()).unwrap(); + }); + until(lock, |state| state.waiting == 1); + drop(outer); + rx.recv().unwrap(); + }); + assert_eq!(owner_and_depth(lock), (None, 0)); + } + + #[test] + fn holders_take_turns() { + let lock = &TestLock::new(); + let inside = &AtomicUsize::new(0); + let max = &AtomicUsize::new(0); + let first = lock.hold(); + thread::scope(|s| { + let (entered_tx, entered_rx) = mpsc::channel(); + let releases: Vec<_> = (0..8) + .map(|i| { + let (release_tx, release_rx) = mpsc::channel::<()>(); + let entered_tx = entered_tx.clone(); + s.spawn(move || { + let _held = lock.hold(); + let now = inside.fetch_add(1, Ordering::SeqCst) + 1; + max.fetch_max(now, Ordering::SeqCst); + entered_tx.send(i).unwrap(); + release_rx.recv().unwrap(); + inside.fetch_sub(1, Ordering::SeqCst); + }); + release_tx + }) + .collect(); + until(lock, |state| state.waiting + inside.load(Ordering::SeqCst) == 8); + drop(first); + for _ in 0..8 { + let i: usize = entered_rx.recv().unwrap(); + releases[i].send(()).unwrap(); + } + }); + assert_eq!(max.load(Ordering::SeqCst), 1); + } + + #[test] + fn static_lock_is_const_and_reentrant() { + static LOCK: TestLock = TestLock::new(); + let outer = LOCK.hold(); + let inner = LOCK.hold(); + assert_eq!(owner_and_depth(&LOCK), (Some(thread::current().id()), 2)); + drop(inner); + drop(outer); + assert_eq!(owner_and_depth(&LOCK), (None, 0)); + } + + #[test] + fn nested_guards_drop_in_either_order() { + for outer_first in [true, false] { + let lock = &TestLock::new(); + let outer = lock.hold(); + let inner = lock.hold(); + thread::scope(|s| { + let (tx, rx) = mpsc::channel(); + s.spawn(move || { + let _held = lock.hold(); + tx.send(()).unwrap(); + }); + until(lock, |state| state.waiting == 1); + let (first, second) = if outer_first { (outer, inner) } else { (inner, outer) }; + drop(first); + assert_eq!(owner_and_depth(lock), (Some(thread::current().id()), 1), "outer_first: {outer_first}"); + drop(second); + rx.recv().unwrap(); + }); + assert_eq!(owner_and_depth(lock), (None, 0)); + } + } + + #[test] + fn gpu_thread_hold_is_idempotent_and_releases_at_exit() { + let holder = thread::spawn(|| { + let early = gpu_lock(); + hold_gpu_lock(); + hold_gpu_lock(); + let with_early = owner_and_depth(&GPU_LOCK); + drop(early); + let held = owner_and_depth(&GPU_LOCK); + let late = gpu_lock(); + let with_late = owner_and_depth(&GPU_LOCK); + drop(late); + let held_again = owner_and_depth(&GPU_LOCK); + [with_early, held, with_late, held_again] + }); + let id = Some(holder.thread().id()); + let depths = holder.join().unwrap(); + assert_eq!(depths, [(id, 2), (id, 1), (id, 2), (id, 1)]); + assert_ne!(owner_and_depth(&GPU_LOCK).0, id); + drop(gpu_lock()); + } + + #[test] + fn different_locks_are_independent() { + let a = TestLock::new(); + let b = TestLock::new(); + let _a = a.hold(); + assert_eq!(owner_and_depth(&b), (None, 0)); + thread::scope(|s| s.spawn(|| drop(b.hold())).join()).unwrap(); + assert_eq!(owner_and_depth(&b), (None, 0)); + } + + trait AmbiguousIfSend { + fn some_item() {} + } + impl AmbiguousIfSend<()> for T {} + impl AmbiguousIfSend for T {} + + #[test] + fn guard_is_not_send() { + // Compiles only while `TestLockGuard` is not `Send`: for a `Send` guard both impls apply and + // the call is ambiguous. + let _ = as AmbiguousIfSend<_>>::some_item; + } +} From b9d451674eee23ac1b3858d4341e83be45f18153 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:40:45 -0800 Subject: [PATCH 012/322] craft-testkit: std_instant skips module files a native-only mod declares std_instant read each file on its own, so `#[cfg(not(target_arch = "wasm32"))] mod native;` in lib.rs did not stop it from reporting std::time::Instant in native.rs when both came from one rust_sources call. std_instant now first collects every `mod name;` declaration and treats the file it names as native-only when the declaration is inside an item whose cfg is false on wasm32-unknown-unknown, along with the files that file declares. A file that a declaration outside such items also reaches from a crate root is still checked. Module files are found by rustc's rules: next to lib.rs, main.rs and mod.rs, in the stem folder of any other file, below enclosing inline modules, and through #[path] on the declaration or on an enclosing inline module. Declarations inside more than 64 inline modules are not followed, so their files are checked. --- crates/testkit/README.md | 4 +- crates/testkit/src/guards.rs | 296 ++++++++++++++++++++++++++++++++- crates/testkit/tests/guards.rs | 145 ++++++++++++++++ 3 files changed, 441 insertions(+), 4 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 75e74d7b82..b6042e0bb1 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -8,7 +8,7 @@ Source-level platform regression guards and verification utilities for the Craft 1. **`predefined_quit`**: Flags direct calls to `muda`'s `PredefinedMenuItem::quit` outside comments, strings and character literals, also with whitespace or a line break around `::` and through a `use muda::PredefinedMenuItem as ...` rename. On macOS, this predefined menu item routes directly to `NSApplication terminate:`, completely bypassing application dirty document checks and unsaved changes save prompts. Applications should instead wire Quit through `craft-quit` lifecycle interceptors. 2. **`wgsl_float_literals` / `wgsl_float_literals_in`**: Scans WGSL shader sources and flags decimal and hexadecimal float literals whose value exceeds `f32::MAX` (such as `3.40282347e38` or `0x1p+500f`), or 65504, the largest finite `f16`, for a literal with an `h` suffix. Integer literals are not checked. Some native compilers round such literals down, but browser WebGPU compilers reject them with pipeline compilation errors, forcing applications into CPU fallback rendering. Exact values equal to `f32::MAX` can be written as `3.4028234663852886e38` or as the hex float `0x1.fffffep+127f`. -3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`. Other crates' `Instant` (such as `web_time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`. On that target, `std::time::Instant::now()` panics at runtime with `"time not implemented on this platform"`. Code targeting the web must use `web_time::Instant`. +3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`. Other crates' `Instant` (such as `web_time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`. A `mod name;` inside such an item also skips the module's file (`name.rs` or `name/mod.rs`, or the file a `#[path]` attribute names) and the files of the modules declared in it, when they are among the files passed in and no declaration outside such items also reaches them. On that target, `std::time::Instant::now()` panics at runtime with `"time not implemented on this platform"`. Code targeting the web must use `web_time::Instant`. 4. **`rust_sources`**: Recursively discovers a crate's `.rs` source files while excluding integration tests (`tests/`), test modules (`tests.rs`, `tests_*.rs`, `*_tests.rs`, `*_test.rs`), build artifacts (`target/`, any folder holding a `CACHEDIR.TAG` file, `.git/` and other folders whose name starts with `.`) and symbolic links, which it does not follow. A file over 8 MiB, more than 256 MiB in all or more than 50,000 files returns an error; `rust_sources_with_limits` takes other limits. It is not built for `wasm32`. ## Epistemic Scope: Syntactic Guards vs Runtime Validation @@ -22,7 +22,7 @@ Source-level guards provide deterministic syntactic evidence about codebase stru ### What They Cannot Establish - **Runtime execution safety**: Syntactic checks do not verify whether code branches actually execute at runtime. - **Semantic type resolution**: The scanners follow `use` renames within one file only. They do not resolve paths through other modules or re-exports, a rename of `std` itself, or expand macros. -- **Complex target predicates**: `std_instant` evaluates `cfg` predicates (`all`, `any`, `not`, `unix`, `windows` and the `target_*` keys) for `wasm32-unknown-unknown`, on outer attributes for the item that follows and on inner attributes (`#![cfg(...)]`) for the rest of the module. A predicate that depends on a feature or on `test` is not known from the source, so its item is checked. Applications should scope `std_instant` tests to the specific crates that compile into their web distribution. +- **Complex target predicates**: `std_instant` evaluates `cfg` predicates (`all`, `any`, `not`, `unix`, `windows` and the `target_*` keys) for `wasm32-unknown-unknown`, on outer attributes for the item that follows and on inner attributes (`#![cfg(...)]`) for the rest of the module, and on `mod name;` declarations for the module's file and its descendants. It compares file paths as text, so the files must come from one `rust_sources` call or be named the same way. A predicate that depends on a feature or on `test` is not known from the source, so its item is checked. Applications should scope `std_instant` tests to the specific crates that compile into their web distribution. - **Driver and host OS behavior**: Syntactic checks do not verify WebGPU driver compatibility or host window manager event dispatch. Source guards serve as fast, zero-dependency regression gates in application test suites, complementing platform integration tests and CI workflows. diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index a8a14401ef..1588884e7d 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -1,9 +1,10 @@ //! Platform regression guards checking source code for known defects and lifecycle hazards. -use std::collections::BTreeSet; +use std::collections::{BTreeMap, BTreeSet}; use std::fmt; #[cfg(not(target_arch = "wasm32"))] use std::path::Path; +use std::rc::Rc; /// A diagnostic finding reported by a source guard. #[derive(Debug, Clone, PartialEq, Eq)] @@ -622,6 +623,273 @@ fn native_only(toks: &[Token]) -> Vec { skip } +/// A module declaration, `mod name;` or the head of `mod name { ... }`. +#[derive(Debug, Clone)] +struct ModName { + name: String, + /// The string of a `#[path = "..."]` attribute on the declaration. + path_attribute: Option, +} + +/// An out-of-line module declaration, `mod name;`. +#[derive(Debug)] +struct ModDecl { + module: ModName, + /// The inline modules (`mod a { ... }`) the declaration is inside, outermost first, shared between the + /// declarations inside them. + inline: Vec>, + /// Whether the declaration is inside an item whose `cfg` is false on `wasm32-unknown-unknown`. + native: bool, +} + +/// The most tokens [`path_attribute`] reads back from one `mod` keyword, so that hostile nesting cannot +/// make the scan quadratic. +const ATTRIBUTE_SCAN_LIMIT: usize = 4096; + +/// The index of the bracket `open` that matches the bracket `close` at `toks[end - 1]`, reading back +/// from `end`, or `None` when it is not found within `budget` tokens. +fn matching_open_back(toks: &[Token], end: usize, open: char, close: char, budget: &mut usize) -> Option { + let mut depth = 0usize; + let mut j = end; + while j > 0 && *budget > 0 { + j -= 1; + *budget -= 1; + if toks[j].is_punct(close) { + depth += 1; + } else if toks[j].is_punct(open) { + depth = depth.saturating_sub(1); + if depth == 0 { + return Some(j); + } + } + } + None +} + +/// The string of a `#[path = "..."]` outer attribute on the item whose `mod` keyword is at `toks[m]`. +fn path_attribute(toks: &[Token], m: usize) -> Option { + let mut budget = ATTRIBUTE_SCAN_LIMIT; + let mut k = m; + if k > 0 && toks[k - 1].is_punct(')') { + // A visibility such as `pub(crate)`. + let j = matching_open_back(toks, k, '(', ')', &mut budget)?; + if j > 0 && toks[j - 1].is_ident("pub") { + k = j - 1; + } + } else if k > 0 && toks[k - 1].is_ident("pub") { + k -= 1; + } + let mut found = None; + while k > 0 && toks[k - 1].is_punct(']') { + let Some(j) = matching_open_back(toks, k, '[', ']', &mut budget) else { break }; + if j == 0 || !toks[j - 1].is_punct('#') { + break; + } + if toks.get(j + 1).is_some_and(|t| t.is_ident("path")) + && toks.get(j + 2).is_some_and(|t| t.is_punct('=')) + && let Some(Kind::Str(s)) = toks.get(j + 3).map(|t| &t.kind) + { + found = Some(s.clone()); + } + k = j - 1; + } + found +} + +/// What an open brace in [`module_decls`] opened. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Brace { + /// A block that is not an inline module. + Block, + /// An inline module, pushed on the inline stack. + Module, + /// An inline module deeper than [`MAX_NESTING`], not tracked. + TooDeep, +} + +/// Every out-of-line module declaration in a file, in one pass that tracks the inline modules around it. +/// +/// Declarations inside more than [`MAX_NESTING`] inline modules are left out, so their files are checked. +fn module_decls(toks: &[Token], skip: &[bool]) -> Vec { + let mut decls = Vec::new(); + let mut braces: Vec = Vec::new(); + let mut inline: Vec> = Vec::new(); + let mut too_deep = 0usize; + for (i, tok) in toks.iter().enumerate() { + match &tok.kind { + Kind::Punct('{') => { + let brace = match i.checked_sub(2).map(|j| (&toks[j], &toks[j + 1].kind)) { + Some((m, Kind::Ident(name))) if m.is_ident("mod") => { + if too_deep == 0 && inline.len() < MAX_NESTING { + inline.push(Rc::new(ModName { name: name.clone(), path_attribute: path_attribute(toks, i - 2) })); + Brace::Module + } else { + too_deep += 1; + Brace::TooDeep + } + } + _ => Brace::Block, + }; + braces.push(brace); + } + Kind::Punct('}') => match braces.pop() { + Some(Brace::Module) => { + inline.pop(); + } + Some(Brace::TooDeep) => too_deep -= 1, + _ => {} + }, + Kind::Ident(k) if k == "mod" && too_deep == 0 => { + if let Some(Kind::Ident(name)) = toks.get(i + 1).map(|t| &t.kind) + && toks.get(i + 2).is_some_and(|t| t.is_punct(';')) + { + decls.push(ModDecl { + module: ModName { name: name.clone(), path_attribute: path_attribute(toks, i) }, + inline: inline.clone(), + native: skip.get(i).copied().unwrap_or(false), + }); + } + } + _ => {} + } + } + decls +} + +/// A path with `\` read as `/`, empty and `.` components removed and `..` applied to the component before it. +fn normalize_path(path: &str) -> String { + let path = path.replace('\\', "/"); + let absolute = path.starts_with('/'); + let mut parts: Vec<&str> = Vec::new(); + for part in path.split('/') { + match part { + "" | "." => {} + ".." if parts.last().is_some_and(|p| *p != "..") => { + parts.pop(); + } + p => parts.push(p), + } + } + let joined = parts.join("/"); + if absolute { format!("/{joined}") } else { joined } +} + +/// `child` below the folder `parent`, normalized. A `child` that is an absolute path (`/x`, `\x` or `C:...`) +/// stands alone. `\\` is read as one separator, since a string literal keeps its escapes. +fn join_path(parent: &str, child: &str) -> String { + let child = child.replace("\\\\", "/"); + if parent.is_empty() || child.starts_with('/') || child.starts_with('\\') || child.as_bytes().get(1) == Some(&b':') { + normalize_path(&child) + } else { + normalize_path(&format!("{parent}/{child}")) + } +} + +/// The paths, normalized, where the module `decl` declared in the file at `parent` (normalized) can be. +/// +/// The modules of `lib.rs`, `main.rs` and `mod.rs` are in the file's folder, and those of any other file +/// are in the folder named after its stem. Each inline module around the declaration adds a folder named +/// after it, or with a `path` attribute, moves to that path relative to the current folder (without the +/// stem folder). The module is then `.rs` or `/mod.rs` there, or with a `path` attribute, that +/// path relative to the current folder, again without the stem folder. +fn module_files(parent: &str, decl: &ModDecl) -> Vec { + let (dir, file) = match parent.rsplit_once('/') { + Some(("", file)) => ("/", file), + Some(split) => split, + None => ("", parent), + }; + let mut folder = dir.to_string(); + let mut stem = (!matches!(file, "lib.rs" | "main.rs" | "mod.rs")).then(|| file.strip_suffix(".rs").unwrap_or(file)); + for inline in &decl.inline { + if let Some(attr) = &inline.path_attribute { + folder = join_path(&folder, attr); + stem = None; + } else { + if let Some(stem) = stem.take() { + folder = join_path(&folder, stem); + } + folder = join_path(&folder, &inline.name); + } + } + if let Some(attr) = &decl.module.path_attribute { + return vec![join_path(&folder, attr)]; + } + if let Some(stem) = stem { + folder = join_path(&folder, stem); + } + let name = &decl.module.name; + vec![join_path(&folder, &format!("{name}.rs")), join_path(&folder, &format!("{name}/mod.rs"))] +} + +/// For each file, whether it is native-only: a `mod` declaration in a native-only item, or any declaration +/// in a native-only file, names it, and no chain of declarations outside native-only items reaches it from +/// a crate root (a file that no declaration names). +fn native_only_files(paths: &[String], decls: &[Vec]) -> Vec { + let mut index: BTreeMap<&str, Vec> = BTreeMap::new(); + for (i, path) in paths.iter().enumerate() { + index.entry(path.as_str()).or_default().push(i); + } + // The files each declaration names, in the order of `decls`. + let children: Vec)>> = decls + .iter() + .enumerate() + .map(|(parent, file_decls)| { + file_decls + .iter() + .map(|decl| { + let files = + module_files(&paths[parent], decl).iter().flat_map(|c| index.get(c.as_str()).into_iter().flatten().copied()).collect(); + (decl.native, files) + }) + .collect() + }) + .collect(); + + // Files the web build compiles: crate roots, and every file a declaration outside a native-only item + // of such a file names. + let mut named = vec![false; paths.len()]; + for (_, files) in children.iter().flatten() { + for &j in files { + named[j] = true; + } + } + let mut web = vec![false; paths.len()]; + let mut queue: Vec = (0..paths.len()).filter(|&j| !named[j]).collect(); + for &j in &queue { + web[j] = true; + } + while let Some(parent) = queue.pop() { + for (_, files) in children[parent].iter().filter(|(is_native, _)| !is_native) { + for &j in files { + if !web[j] { + web[j] = true; + queue.push(j); + } + } + } + } + + // Files a native-only declaration names, and their descendants. + let mut native = vec![false; paths.len()]; + let mut mark = |files: &[usize], queue: &mut Vec| { + for &j in files { + if !native[j] { + native[j] = true; + queue.push(j); + } + } + }; + for (_, files) in children.iter().flatten().filter(|(is_native, _)| *is_native) { + mark(files, &mut queue); + } + while let Some(parent) = queue.pop() { + for (_, files) in &children[parent] { + mark(files, &mut queue); + } + } + native.iter().zip(&web).map(|(&n, &w)| n && !w).collect() +} + /// Add one finding for each line in `lines`, in line order, with the trimmed text of that line. fn report(findings: &mut Vec, path: &str, content: &str, lines: &BTreeSet) { if lines.is_empty() { @@ -693,6 +961,15 @@ where /// (for example `#[cfg(not(target_arch = "wasm32"))]`, `#[cfg(all(unix, ...))]`, `#[cfg(target_os = "macos")]`, /// or `#![cfg(...)]` for the rest of a module). A predicate that depends on a feature or on `test` is not /// known from the source, so the item is checked. +/// * **Module files**: a `mod name;` inside such an item makes the module's file native-only, and so are the +/// files of the modules declared in it, when they are among `files`, unless a chain of declarations outside +/// such items also reaches the file from a crate root (a file that no declaration names). The module's file is `name.rs` or +/// `name/mod.rs` next to `lib.rs`, `main.rs` or `mod.rs`, and in the folder named after any other file's +/// stem, below the folders of enclosing inline modules; a `#[path = "..."]` attribute on the declaration +/// or on an enclosing inline module is followed. Paths are compared as text with `\` read as `/`, so the files must be named the same way +/// (for example all from one `rust_sources` call), and a crate root other than `lib.rs` or `main.rs` +/// (such as `src/bin/tool.rs`) is read as an ordinary module file. A declaration inside more than 64 inline +/// modules is not followed, so its file is checked. /// * **Limitations**: This is a lexical source guard. It does not expand macros, resolve paths through other /// modules or re-exports, rename `std` itself (`use std as s;`), or follow aliases in a different scope than /// the file. @@ -701,8 +978,23 @@ where I: IntoIterator, I::Item: AsFileSource, { + let files: Vec = files.into_iter().collect(); + let paths: Vec = files.iter().map(|file| normalize_path(file.path())).collect(); + // Only the declarations are kept from this pass, so the tokens of every file are never held at once. + let decls: Vec> = files + .iter() + .map(|file| { + let toks = lex_rust(file.content()); + module_decls(&toks, &native_only(&toks)) + }) + .collect(); + let excluded = native_only_files(&paths, &decls); + let mut findings = Vec::new(); - for file in files { + for (file, excluded) in files.iter().zip(excluded) { + if excluded { + continue; + } let path = file.path(); let content = file.content(); let toks = lex_rust(content); diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index a2a419ca18..a68209be9d 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -522,6 +522,151 @@ fn run() { assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![4, 8, 9]); } +fn finding_paths(findings: &[Finding]) -> Vec<&str> { + findings.iter().map(|f| f.path.as_str()).collect() +} + +#[test] +fn std_instant_skips_module_files_a_native_cfg_declares() { + let lib = r#" +#[cfg(not(target_arch = "wasm32"))] +mod native; +mod web; +#[cfg(feature = "extra")] +mod extra; +"#; + let native = "mod clock;\npub fn now() -> std::time::Instant { std::time::Instant::now() }\n"; + let native_clock = "use std::time::Instant;\n"; + let web = "#[cfg(unix)]\nmod imp;\npub fn now() { let _t = std::time::Instant::now(); }\n"; + let web_imp = "use std::time::Instant;\n"; + let sibling_imp = "use std::time::Instant;\n"; + let extra = "use std::time::Instant;\n"; + let files = [ + ("src/lib.rs", lib), + ("src/native.rs", native), + ("src/native/clock.rs", native_clock), + ("src/web.rs", web), + ("src/web/imp.rs", web_imp), + ("src/imp.rs", sibling_imp), + ("src/extra.rs", extra), + ]; + assert_eq!(finding_paths(&std_instant(files)), vec!["src/web.rs", "src/imp.rs", "src/extra.rs"]); +} + +#[test] +fn std_instant_skips_native_module_files_by_mod_rs_path_attribute_and_inline_module() { + let main = r#" +#[cfg(unix)] +pub(crate) mod sys; +#[cfg(target_os = "macos")] +#[path = "platform/mac_clock.rs"] +mod mac; +#[cfg(windows)] +mod outer { + mod inner; +} +#[cfg(unix)] +#[path = "platform/native.rs"] +pub(in crate) mod native; +"#; + let clock = "use std::time::Instant;\n"; + let files = [ + ("C:\\app\\src\\main.rs", main), + ("C:\\app\\src\\platform\\native.rs", clock), + ("C:\\app\\src\\sys\\mod.rs", "mod detail;\n"), + ("C:\\app\\src\\sys\\detail.rs", clock), + ("C:\\app\\src\\platform\\mac_clock.rs", clock), + ("C:\\app\\src\\outer\\inner.rs", clock), + ("C:\\app\\src\\mac.rs", clock), + ]; + assert_eq!(finding_paths(&std_instant(files)), vec!["C:\\app\\src\\mac.rs"]); +} + +#[test] +fn std_instant_checks_a_module_file_that_a_web_declaration_also_names() { + let lib = r#" +#[cfg(windows)] +mod imp; +#[cfg(target_arch = "wasm32")] +mod imp; +#[cfg(unix)] +mod sys; +"#; + let files = [ + ("src/lib.rs", lib), + ("src/imp.rs", "mod detail;\n"), + ("src/imp/detail.rs", "use std::time::Instant;\n"), + ("src/sys.rs", "#[path = \"imp/detail.rs\"]\nmod shared;\n"), + ]; + assert_eq!(finding_paths(&std_instant(files)), vec!["src/imp/detail.rs"]); +} + +#[test] +fn std_instant_reads_an_inline_module_path_attribute_as_the_folder_of_its_modules() { + let lib = r#" +#[cfg(unix)] +#[path = "native"] +mod platform { + mod clock; +} +mod web; +"#; + let web = r#" +#[path = "shared"] +mod inner { + #[cfg(windows)] + mod tick; +} +"#; + let clock = "use std::time::Instant;\n"; + let files = [ + ("src/lib.rs", lib), + ("src/native/clock.rs", clock), + ("src/platform/clock.rs", clock), + ("src/web.rs", web), + ("src/shared/tick.rs", clock), + ("src/web/shared/tick.rs", clock), + ]; + assert_eq!(finding_paths(&std_instant(files)), vec!["src/platform/clock.rs", "src/web/shared/tick.rs"]); +} + +#[test] +fn std_instant_reads_top_level_path_attributes_of_a_non_mod_rs_file_from_its_folder() { + let a = r#" +#[cfg(unix)] +#[path = "native.rs"] +mod imp; +#[cfg(unix)] +#[path = "native"] +mod platform { + mod clock; +} +"#; + let clock = "use std::time::Instant;\n"; + let files = [ + ("src/lib.rs", "mod a;\n"), + ("src/a.rs", a), + ("src/native.rs", clock), + ("src/native/clock.rs", clock), + ("src/a/native.rs", clock), + ("src/a/native/clock.rs", clock), + ]; + assert_eq!(finding_paths(&std_instant(files)), vec!["src/a/native.rs", "src/a/native/clock.rs"]); +} + +#[test] +fn std_instant_checks_module_files_declared_deeper_than_its_nesting_limit() { + let lib = format!("{}#[cfg(unix)]\nmod deep;\n{}", "mod m {\n".repeat(70), "}\n".repeat(70)); + let shallow_lib = format!("{}#[cfg(unix)]\nmod deep;\n{}", "mod m {\n".repeat(3), "}\n".repeat(3)); + let deep_path = format!("src/{}deep.rs", "m/".repeat(70)); + let shallow_path = format!("src/{}deep.rs", "m/".repeat(3)); + let clock = "use std::time::Instant;\n"; + let files = [("src/lib.rs", lib.as_str()), (deep_path.as_str(), clock)]; + assert_eq!(finding_paths(&std_instant(files)), vec![deep_path.as_str()]); + let files = [("src/lib.rs", shallow_lib.as_str()), (shallow_path.as_str(), clock)]; + assert!(std_instant(files).is_empty()); +} + #[test] fn wgsl_integer_literals_are_not_floats() { let shader = r#" From b89076646da878483fc56ed9790865697062e9c9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:55:02 -0800 Subject: [PATCH 013/322] craft-testkit: rust_sources docs name the CACHEDIR.TAG signature it checks rust_sources skips a folder only when its CACHEDIR.TAG starts with the line Signature: 8a477f597d28d172789f06886806bc55. The doc comment and the crate README now say so instead of naming any CACHEDIR.TAG file. --- crates/testkit/README.md | 2 +- crates/testkit/src/guards.rs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index b6042e0bb1..5fc8ea3de1 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -9,7 +9,7 @@ Source-level platform regression guards and verification utilities for the Craft 1. **`predefined_quit`**: Flags direct calls to `muda`'s `PredefinedMenuItem::quit` outside comments, strings and character literals, also with whitespace or a line break around `::` and through a `use muda::PredefinedMenuItem as ...` rename. On macOS, this predefined menu item routes directly to `NSApplication terminate:`, completely bypassing application dirty document checks and unsaved changes save prompts. Applications should instead wire Quit through `craft-quit` lifecycle interceptors. 2. **`wgsl_float_literals` / `wgsl_float_literals_in`**: Scans WGSL shader sources and flags decimal and hexadecimal float literals whose value exceeds `f32::MAX` (such as `3.40282347e38` or `0x1p+500f`), or 65504, the largest finite `f16`, for a literal with an `h` suffix. Integer literals are not checked. Some native compilers round such literals down, but browser WebGPU compilers reject them with pipeline compilation errors, forcing applications into CPU fallback rendering. Exact values equal to `f32::MAX` can be written as `3.4028234663852886e38` or as the hex float `0x1.fffffep+127f`. 3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`. Other crates' `Instant` (such as `web_time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`. A `mod name;` inside such an item also skips the module's file (`name.rs` or `name/mod.rs`, or the file a `#[path]` attribute names) and the files of the modules declared in it, when they are among the files passed in and no declaration outside such items also reaches them. On that target, `std::time::Instant::now()` panics at runtime with `"time not implemented on this platform"`. Code targeting the web must use `web_time::Instant`. -4. **`rust_sources`**: Recursively discovers a crate's `.rs` source files while excluding integration tests (`tests/`), test modules (`tests.rs`, `tests_*.rs`, `*_tests.rs`, `*_test.rs`), build artifacts (`target/`, any folder holding a `CACHEDIR.TAG` file, `.git/` and other folders whose name starts with `.`) and symbolic links, which it does not follow. A file over 8 MiB, more than 256 MiB in all or more than 50,000 files returns an error; `rust_sources_with_limits` takes other limits. It is not built for `wasm32`. +4. **`rust_sources`**: Recursively discovers a crate's `.rs` source files while excluding integration tests (`tests/`), test modules (`tests.rs`, `tests_*.rs`, `*_tests.rs`, `*_test.rs`), build artifacts (`target/`, any folder holding a `CACHEDIR.TAG` file that starts with the line `Signature: 8a477f597d28d172789f06886806bc55`, `.git/` and other folders whose name starts with `.`) and symbolic links, which it does not follow. A file over 8 MiB, more than 256 MiB in all or more than 50,000 files returns an error; `rust_sources_with_limits` takes other limits. It is not built for `wasm32`. ## Epistemic Scope: Syntactic Guards vs Runtime Validation diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index 1588884e7d..f1ddbb781a 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -1304,7 +1304,8 @@ fn is_cache_dir(dir: &Path) -> bool { /// * `*_test.rs` /// * `test.rs` /// * Any file below `dir` within a directory named `tests`, `benches`, `examples` or `target`, or whose -/// name starts with `.`, or that holds a `CACHEDIR.TAG` file (a build output folder with another name). +/// name starts with `.`, or that holds a `CACHEDIR.TAG` file starting with the signature line +/// `Signature: 8a477f597d28d172789f06886806bc55` (a build output folder with another name). /// * Symbolic links (and, on Windows, junctions) to files or folders, which are not followed. /// /// Results are sorted lexicographically by file path for deterministic behavior across platforms. From 804d0aefe5a3397eb5ba01c59eaa98349d3df619 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:56:24 -0800 Subject: [PATCH 014/322] craft-ods: state the test-support feature in full sentences in the README --- crates/ods/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ods/README.md b/crates/ods/README.md index 3c9111b71a..bac06a2bf9 100644 --- a/crates/ods/README.md +++ b/crates/ods/README.md @@ -38,6 +38,6 @@ expanded; blank padding past the grid's edge is clipped, data past it is an erro ## Features -- `test-support`: `testing`, which builds small `.ods` packages in code (`spreadsheet`, - `content`, `package`), for the tests of crates that read spreadsheets. Not a general +- `test-support` enables `testing`, which builds small `.ods` packages in code (`spreadsheet`, + `content`, `package`) for the tests of crates that read spreadsheets. It is not a general spreadsheet writer. From 836433ccb9e2dc261da1f74b1c33bdcf94105ff9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:01:40 -0800 Subject: [PATCH 015/322] craft-testkit: wgsl_float_literals docs say the limit check uses the value rounded to f64 README item 2, the wgsl_float_literals rustdoc and the boundary test comment now say the scanner compares each literal's value rounded to f64, so a literal that exceeds the maximum by less than f64 precision, such as 0x1.fffffe000000001p+127f, is not reported. They also say 0x1.fffffep+127f equals f32::MAX and 3.4028234663852886e38 rounds to it. --- crates/testkit/README.md | 2 +- crates/testkit/src/guards.rs | 8 +++++--- crates/testkit/tests/guards.rs | 2 +- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 5fc8ea3de1..36b87bb89d 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -7,7 +7,7 @@ Source-level platform regression guards and verification utilities for the Craft `craft-testkit` provides lightweight, non-panicking source guards that prevent applications in the Craft ecosystem from repeating platform defects that were previously diagnosed and resolved in peer applications: 1. **`predefined_quit`**: Flags direct calls to `muda`'s `PredefinedMenuItem::quit` outside comments, strings and character literals, also with whitespace or a line break around `::` and through a `use muda::PredefinedMenuItem as ...` rename. On macOS, this predefined menu item routes directly to `NSApplication terminate:`, completely bypassing application dirty document checks and unsaved changes save prompts. Applications should instead wire Quit through `craft-quit` lifecycle interceptors. -2. **`wgsl_float_literals` / `wgsl_float_literals_in`**: Scans WGSL shader sources and flags decimal and hexadecimal float literals whose value exceeds `f32::MAX` (such as `3.40282347e38` or `0x1p+500f`), or 65504, the largest finite `f16`, for a literal with an `h` suffix. Integer literals are not checked. Some native compilers round such literals down, but browser WebGPU compilers reject them with pipeline compilation errors, forcing applications into CPU fallback rendering. Exact values equal to `f32::MAX` can be written as `3.4028234663852886e38` or as the hex float `0x1.fffffep+127f`. +2. **`wgsl_float_literals` / `wgsl_float_literals_in`**: Scans WGSL shader sources and flags decimal and hexadecimal float literals whose value, rounded to `f64`, exceeds `f32::MAX` (such as `3.40282347e38` or `0x1p+500f`), or 65504, the largest finite `f16`, for a literal with an `h` suffix. A literal that exceeds the maximum by less than `f64` precision rounds to the maximum and is not reported. Integer literals are not checked. Some native compilers round such literals down, but browser WebGPU compilers reject them with pipeline compilation errors, forcing applications into CPU fallback rendering. `f32::MAX` can be written as the hex float `0x1.fffffep+127f`, which equals it, or as the decimal `3.4028234663852886e38`, which rounds to it. 3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`. Other crates' `Instant` (such as `web_time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`. A `mod name;` inside such an item also skips the module's file (`name.rs` or `name/mod.rs`, or the file a `#[path]` attribute names) and the files of the modules declared in it, when they are among the files passed in and no declaration outside such items also reaches them. On that target, `std::time::Instant::now()` panics at runtime with `"time not implemented on this platform"`. Code targeting the web must use `web_time::Instant`. 4. **`rust_sources`**: Recursively discovers a crate's `.rs` source files while excluding integration tests (`tests/`), test modules (`tests.rs`, `tests_*.rs`, `*_tests.rs`, `*_test.rs`), build artifacts (`target/`, any folder holding a `CACHEDIR.TAG` file that starts with the line `Signature: 8a477f597d28d172789f06886806bc55`, `.git/` and other folders whose name starts with `.`) and symbolic links, which it does not follow. A file over 8 MiB, more than 256 MiB in all or more than 50,000 files returns an error; `rust_sources_with_limits` takes other limits. It is not built for `wasm32`. diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index f1ddbb781a..3df0ad8667 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -1160,14 +1160,16 @@ fn scan_wgsl_hex(code: &[u8], start: usize) -> (usize, usize, bool) { /// Guard: scans a single WGSL shader string and detects float literals outside their type's finite range. /// /// WebGPU compilers in browsers reject a float literal above `f32::MAX` (e.g. `3.40282347e38`) with a -/// pipeline build error, which turns off GPU rendering. Exact values equal to `f32::MAX` can be written -/// as `3.4028234663852886e38` or as the hex float `0x1.fffffep+127f`. +/// pipeline build error, which turns off GPU rendering. `f32::MAX` can be written as the hex float +/// `0x1.fffffep+127f`, which equals it, or as the decimal `3.4028234663852886e38`, which rounds to it. /// /// ### Policy and Limitations /// /// * **Conservative mathematical bound**: The guard compares the literal's value, rounded to `f64`, /// with `f64::from(f32::MAX)`, or with 65504 (the largest finite `f16`) for an `h` suffix. Any literal -/// above it is reported, even one that a compiler would round down to the maximum. +/// above it is reported, even one that a compiler would round down to the maximum. A literal that exceeds +/// the maximum by less than `f64` precision (such as `0x1.fffffe000000001p+127f`) rounds to the maximum and +/// is not reported. /// * **Which literals**: decimal floats (with a `.`, an exponent or an `f`/`h` suffix) and hexadecimal floats /// (`0x` with a `.` or a `p` exponent). Integer literals (`123`, `123u`, `0xFFi`, `0x1f`) are not floats and /// are not reported. A `-` in front is not part of the literal, so `-1e39` is reported as `1e39`. diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index a68209be9d..76b3e754ea 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -318,7 +318,7 @@ fn run() { #[test] fn test_wgsl_exact_f32_max_boundary() { - // 3.4028234663852886e38 is mathematical f32::MAX bit for bit + // 3.4028234663852886e38 rounds to f32::MAX, as an f32 and as an f64 let exact_valid = r#" const EXACT_MAX: f32 = 3.4028234663852886e38; const NEG_EXACT_MAX: f32 = -3.4028234663852886e38; From 5c53194e407c92e42958810348081ed41e50af1c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:12:08 -0800 Subject: [PATCH 016/322] craft-testkit: a native cfg on a block statement covers the block and its method-call suffix item_end now ends a cfg-gated statement that starts with a bare block at the block's closing brace, so code after it is checked. When a `.` or `?` follows the closing brace of a block item, the item runs on to its `;` or `,`, so a method call after a cfg-gated block or `unsafe` block stays covered by the cfg. --- crates/testkit/src/guards.rs | 16 +++++++++++++--- crates/testkit/tests/guards.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/crates/testkit/src/guards.rs b/crates/testkit/src/guards.rs index 3df0ad8667..77006af6f3 100644 --- a/crates/testkit/src/guards.rs +++ b/crates/testkit/src/guards.rs @@ -540,9 +540,10 @@ const BLOCK_KEYWORDS: &[&str] = /// index of the bracket that closes the enclosing scope. /// /// It ends after a `;` or a `,` outside brackets, after the closing brace of a block item (one that -/// starts with a keyword in [`BLOCK_KEYWORDS`] or is a macro call with braces) or of a match arm's -/// block, or before a closing bracket of the enclosing scope. A `,` inside the angle brackets of a -/// field's or a `let`'s type ends the item early, which leaves the rest of it checked. +/// starts with `{` or a keyword in [`BLOCK_KEYWORDS`], or is a macro call with braces) or of a match +/// arm's block, or before a closing bracket of the enclosing scope. When a `.` or `?` follows the +/// closing brace of a block item, the item runs on to its `;` or `,`. A `,` inside the angle brackets +/// of a field's or a `let`'s type ends the item early, which leaves the rest of it checked. fn item_end(toks: &[Token], start: usize, inner: bool) -> usize { let mut depth = 0usize; let mut block_item = false; @@ -550,6 +551,9 @@ fn item_end(toks: &[Token], start: usize, inner: bool) -> usize { let mut j = start; while j < toks.len() { let at_top = depth == 0 && !inner; + if j == start && at_top && toks[j].is_punct('{') { + block_item = true; + } match &toks[j].kind { Kind::Ident(k) if at_top && BLOCK_KEYWORDS.contains(&k.as_str()) => block_item = true, Kind::Punct('!') if at_top && toks.get(j + 1).is_some_and(|t| t.is_punct('{')) => block_item = true, @@ -565,6 +569,12 @@ fn item_end(toks: &[Token], start: usize, inner: bool) -> usize { j += 1; continue; } + if toks.get(j + 1).is_some_and(|t| t.is_punct('.') || t.is_punct('?')) { + // A method call, field or `?` after the block continues the expression to its `;` or `,`. + block_item = false; + j += 1; + continue; + } let comma = toks.get(j + 1).is_some_and(|t| t.is_punct(',')); return if arm && comma { j + 2 } else { j + 1 }; } diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 76b3e754ea..5d3df778fe 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -473,6 +473,34 @@ use std::time::Instant as MacInstant; assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![4, 13, 16, 19]); } +#[test] +fn std_instant_ends_a_native_cfg_block_statement_at_its_closing_brace() { + let source = r#" +fn run() { + #[cfg(unix)] { + let _a = std::time::Instant::now(); + } + let t = std::time::Instant::now(); +} +"#; + assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![6]); +} + +#[test] +fn std_instant_skips_a_method_call_after_a_native_cfg_block() { + let source = r#" +fn run(x: Option) -> Option { + #[cfg(unix)] + { 0u64 }.saturating_add(std::time::Instant::now().elapsed().as_nanos() as u64); + #[cfg(unix)] + unsafe { x }.map(|_| std::time::Instant::now())?; + let t = std::time::Instant::now(); + x +} +"#; + assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![7]); +} + #[test] fn std_instant_inner_cfg_covers_the_whole_file() { let source = r#" From 4b740e0075e413a7acc91edb52fbf2c5b368aa0b Mon Sep 17 00:00:00 2001 From: alehel Date: Sat, 14 Nov 2026 21:18:45 +0100 Subject: [PATCH 017/322] craft-audio: ALAC shifts off fewer low bytes in quiet 24- and 32-bit packets (#1368) Apple's reference stores 1 (24-bit) or 2 (32-bit) low bytes of every sample uncompressed, so a 4096-frame stereo packet of 24-bit silence was 8224 bytes. Each element now shifts off the fewest bytes that keep its samples one bit narrower than the reference's prediction width. A 32-bit pair keeps at least one byte, since the format allows no wider prediction. Co-Authored-By: Claude Opus 5.5 --- crates/audio/README.md | 2 +- crates/audio/src/alac/encoder.rs | 123 +++++++++++++++++++++++++++--- crates/audio/src/alac/mod.rs | 4 +- crates/audio/tests/codecs/alac.rs | 36 +++++++++ 4 files changed, 153 insertions(+), 12 deletions(-) diff --git a/crates/audio/README.md b/crates/audio/README.md index 5a5df4f2f5..8546bc6a7b 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -540,7 +540,7 @@ Each codec module's rustdoc lists the coding tools it implements. | MP1/MP2 (`mpa`) | ISO/IEC 11172-3, 13818-3 | Layer I and II, MPEG-1/2/2.5, 8–48 kHz; also the Layer II rate/mode pairs the spec disallows (ffmpeg's default mono 384 kbit/s); no free format | ffmpeg-encoded streams, 73–84 dB SNR | | MP3 decoder (`mp3`) | ISO/IEC 11172-3, 13818-3 | Layer III, MPEG-1/2/2.5, 8–48 kHz, every bit rate, CBR and VBR; mono, stereo, dual channel, joint stereo (mid/side and intensity); long, short and mixed blocks; bit reservoir; CRC read, not checked; Xing / Info / VBRI and LAME tags; no free format (read through symphonia) | ffmpeg's float decoder: 127–131 dB SNR on LAME streams of every sampling frequency (CBR, VBR, CRC, no reservoir, transients with short blocks) and on this crate's encoder's; intensity stereo and mixed blocks through LAME frames edited to use them (112–131 dB) | | MP3 encoder (`mp3`) | ISO/IEC 11172-3, 13818-3 | Layer III, constant bit rate: 32–320 kbit/s at 32/44.1/48 kHz, 8–160 kbit/s at 16/22.05/24 kHz; mono, stereo, joint stereo (mid/side); bit reservoir; long blocks only; no Xing/Info tag, VBR, CRC or free format | ffmpeg decodes every Huffman code as intended; full encodes at every sampling frequency checked with ffprobe and by SNR of ffmpeg's decode | -| ALAC (`alac`) | Apple's reference implementation | decode and encode, 1–8 channels, 16/20/24/32 bits (decode: any depth 1–32), fast mode, magic cookie in MP4/Matroska and CAF form | Apple's reference: same packets from the encoder, same samples from both decoders on 766 configurations; ffmpeg: bit-exact both ways | +| ALAC (`alac`) | Apple's reference implementation | decode and encode, 1–8 channels, 16/20/24/32 bits (decode: any depth 1–32), fast mode, magic cookie in MP4/Matroska and CAF form | Apple's reference: same packets from the encoder (except 24- and 32-bit packets quiet enough to shift off fewer low bytes, such as silence), same samples from both decoders on 766 configurations; ffmpeg: bit-exact both ways | ### MP3 encoding diff --git a/crates/audio/src/alac/encoder.rs b/crates/audio/src/alac/encoder.rs index a589a9060a..2c7773e715 100644 --- a/crates/audio/src/alac/encoder.rs +++ b/crates/audio/src/alac/encoder.rs @@ -8,7 +8,11 @@ //! //! The search (stereo matrixing, 4 or 8 predictor coefficients) and the state kept across //! packets (coefficients, the last matrixing, and the buffers the trial runs read stale parts of) -//! follow the reference, so for the same input this writes the same packets as it. +//! follow the reference, so for the same input this writes the same packets as it, with one +//! exception: the shifted-off low bytes. The reference passes 1 (24-bit) or 2 (32-bit) low bytes +//! of every sample through uncompressed, even for silence. Here an element shifts off fewer bytes +//! in a packet whose samples fit well within the width the reference predicts (see +//! [`packet_shift`]), so silence and quiet passages are not padded with a byte or two per sample. use super::ag::{self, AgParams}; use super::bits::{BitCounter, BitSink, BitWriter}; @@ -100,6 +104,25 @@ fn bytes_shifted(bit_depth: u32) -> u32 { } } +/// The bytes an element shifts off in one packet: the fewest, down from the reference's +/// [`bytes_shifted`], that leave every sample at least one bit narrower than the width the +/// reference predicts (`bit_depth − 8 · bytes_shifted`). The predictor then works on values no +/// wider than in the reference, so its arithmetic stays in the same range; only fewer low bytes go +/// out uncompressed. The spare bit is there because at the full width, coding the low byte through +/// the predictor costs about as much as storing it, and for 24-bit mono measured 2% more. +/// A 32-bit pair keeps at least 1: with none, its prediction width (33 bits) exceeds the 32 the +/// format allows. +fn packet_shift(bit_depth: u32, channels: &[&[i32]]) -> u32 { + let reference = bytes_shifted(bit_depth); + let width = bit_depth - reference * 8 - 1; + let floor = u32::from(bit_depth == 32 && channels.len() == 2); + let fits = |bytes: u32| { + let (lo, hi) = (-(1i64 << (width - 1)), (1i64 << (width - 1)) - 1); + channels.iter().flat_map(|c| c.iter()).all(|&x| (lo..=hi).contains(&i64::from(x >> (bytes * 8)))) + }; + (floor..reference).find(|&b| fits(b)).unwrap_or(reference) +} + impl Encoder { /// An encoder for `cfg`. pub fn new(cfg: EncoderConfig) -> Result { @@ -191,11 +214,12 @@ impl Encoder { w.put(cpe_tag, 4); cpe_tag += 1; let (l, r) = (channels[index], channels[index + 1]); + let bs = packet_shift(self.bit_depth, &[l, r]); // as in the reference, fast mode applies to stereo streams only if self.cfg.fast && channels.len() == 2 { - self.encode_stereo_fast(&mut w, index, l, r)?; + self.encode_stereo_fast(&mut w, index, l, r, bs)?; } else { - self.encode_stereo(&mut w, index, l, r)?; + self.encode_stereo(&mut w, index, l, r, bs)?; } index += 2; } @@ -203,7 +227,8 @@ impl Encoder { let tag = if element == ID_LFE { &mut lfe_tag } else { &mut sce_tag }; w.put(*tag, 4); *tag += 1; - self.encode_mono(&mut w, index, channels[index])?; + let bs = packet_shift(self.bit_depth, &[channels[index]]); + self.encode_mono(&mut w, index, channels[index], bs)?; index += 1; } } @@ -231,10 +256,10 @@ impl Encoder { } /// `EncodeStereo`: a channel pair with the matrixing and coefficient search. - fn encode_stereo(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32]) -> Result<()> { + /// `bs`: the bytes shifted off, from [`packet_shift`]. + fn encode_stereo(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32], bs: u32) -> Result<()> { let start = w.bit_len(); let n = l.len(); - let bs = bytes_shifted(self.bit_depth); let chan_bits = self.bit_depth - bs * 8 + 1; let partial = self.partial(n); let params = AgParams::new(ag::MB0, PB_FACTOR * ag::PB0 / 4, ag::KB0); @@ -329,10 +354,9 @@ impl Encoder { } /// `EncodeStereoFast`: a channel pair without matrixing or search. - fn encode_stereo_fast(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32]) -> Result<()> { + fn encode_stereo_fast(&mut self, w: &mut BitWriter, ch: usize, l: &[i32], r: &[i32], bs: u32) -> Result<()> { let start = w.bit_len(); let n = l.len(); - let bs = bytes_shifted(self.bit_depth); let chan_bits = self.bit_depth - bs * 8 + 1; let partial = self.partial(n); let params = AgParams::new(ag::MB0, PB_FACTOR * ag::PB0 / 4, ag::KB0); @@ -396,10 +420,9 @@ impl Encoder { } /// `EncodeMono`: one channel (SCE or LFE). - fn encode_mono(&mut self, w: &mut BitWriter, ch: usize, input: &[i32]) -> Result<()> { + fn encode_mono(&mut self, w: &mut BitWriter, ch: usize, input: &[i32], bs: u32) -> Result<()> { let start = w.bit_len(); let n = input.len(); - let bs = bytes_shifted(self.bit_depth); let shift = bs * 8; let chan_bits = self.bit_depth - shift; let partial = self.partial(n); @@ -577,4 +600,84 @@ mod tests { assert!(enc.encode(&[&[40_000], &[0]]).is_err()); assert!(enc.encode(&[&[-32_768], &[32_767]]).is_ok()); } + + /// One packet of `frames` frames per element, encoded and decoded back; its size in bytes. + fn packet_bytes(cfg: EncoderConfig, input: &[Vec]) -> usize { + let mut enc = Encoder::new(cfg).unwrap(); + let chunk: Vec<&[i32]> = input.iter().map(Vec::as_slice).collect(); + let p = enc.encode(&chunk).unwrap(); + let mut dec = Decoder::new(&enc.cookie()).unwrap(); + assert_eq!(dec.decode(&p).unwrap(), input, "{cfg:?}"); + p.len() + } + + /// The reference shifts 1 (24-bit) or 2 (32-bit) low bytes of every sample off and stores them + /// uncompressed, so a 4096-frame stereo packet of 24-bit silence was 8224 bytes (#1368). + #[test] + fn silence_is_a_few_bytes_at_every_depth() { + for bits in [16, 20, 24, 32] { + for ch in [1, 2, 6] { + for fast in [false, true] { + let cfg = EncoderConfig::new(48_000, ch, bits).with_fast(fast); + let bytes = packet_bytes(cfg, &vec![vec![0; 4096]; usize::from(ch)]); + // a 32-bit pair keeps one shifted byte per sample: the format allows no less + let floor = if bits == 32 { 4096 * 2 * (usize::from(ch) / 2) } else { 0 }; + assert!(bytes <= floor + 40 * usize::from(ch), "{bits} bits, {ch} ch, fast {fast}: {bytes} bytes"); + } + } + } + } + + /// Quiet audio (within 12 bits) at 24 and 32 bits shifts nothing off and comes within 10% of + /// the same audio at 16 bits (the wider prediction width makes the coder's escapes longer); + /// the reference stored a byte or two more per sample. Samples at the edges of each width and + /// loud audio decode exactly. + #[test] + fn quiet_packets_compress_like_16_bit_audio_and_loud_ones_round_trip() { + let quiet = signal(4096, 2, 12); + let at16 = packet_bytes(EncoderConfig::new(48_000, 2, 16), &quiet); + let at24 = packet_bytes(EncoderConfig::new(48_000, 2, 24), &quiet); + assert!(at24 * 10 <= at16 * 11, "24-bit {at24} bytes, 16-bit {at16}"); + let mono = vec![quiet[0].clone()]; + let at16 = packet_bytes(EncoderConfig::new(48_000, 1, 16), &mono); + let at32 = packet_bytes(EncoderConfig::new(48_000, 1, 32), &mono); + assert!(at32 * 10 <= at16 * 11, "32-bit mono {at32} bytes, 16-bit {at16}"); + // the samples just past each narrower width, and loud audio, decode exactly + for bits in [24u32, 32] { + for ch in [1u8, 2] { + let edge: Vec> = (0..ch) + .map(|c| { + (0..4096) + .map(|i| match (i + usize::from(c)) % 4 { + 0 => (16_384 << (bits - 24)) - 1, + 1 => -(16_384 << (bits - 24)), + 2 => 16_384 << (bits - 24), + _ => -(16_384 << (bits - 24)) - 1, + }) + .collect() + }) + .collect(); + packet_bytes(EncoderConfig::new(48_000, ch, bits as u8), &edge); + packet_bytes(EncoderConfig::new(48_000, ch, bits as u8), &signal(4096, usize::from(ch), bits)); + } + } + } + + #[test] + fn the_shift_is_the_fewest_bytes_that_keep_the_reference_width() { + let z = [0i32; 4]; + assert_eq!(packet_shift(16, &[&z]), 0); + assert_eq!(packet_shift(24, &[&z, &z]), 0); + assert_eq!(packet_shift(24, &[&[16_383, -16_384], &z]), 0); + assert_eq!(packet_shift(24, &[&[16_384], &z]), 1); + assert_eq!(packet_shift(24, &[&[-16_385]]), 1); + assert_eq!(packet_shift(24, &[&[32_767]]), 1); + assert_eq!(packet_shift(32, &[&z]), 0); + assert_eq!(packet_shift(32, &[&[16_383]]), 0); + assert_eq!(packet_shift(32, &[&z, &z]), 1); + assert_eq!(packet_shift(32, &[&[1 << 21]]), 1); + assert_eq!(packet_shift(32, &[&[1 << 22]]), 2); + assert_eq!(packet_shift(32, &[&[i32::MIN]]), 2); + assert_eq!(packet_shift(32, &[&[i32::MAX], &z]), 2); + } } diff --git a/crates/audio/src/alac/mod.rs b/crates/audio/src/alac/mod.rs index a797d1ab68..5547cc47ce 100644 --- a/crates/audio/src/alac/mod.rs +++ b/crates/audio/src/alac/mod.rs @@ -23,7 +23,9 @@ //! reference: hostile input returns errors instead of reading or writing out of bounds, integer //! arithmetic wraps where C would overflow, the 4- and 8-tap predictor loops are folded into the //! general one (same values), the sample-width variants of the matrix routines into one routine -//! over `i32`, and the encoder fills in the cookie's average bit rate. +//! over `i32`, the encoder fills in the cookie's average bit rate, and it shifts off fewer low +//! bytes in packets whose samples fit a narrower width (silence and quiet passages at 24 and 32 +//! bits), where the reference always passes them through uncompressed. // The bit I/O, coder, predictor and matrix modules serve both halves; with only one of // `alac-decode` and `alac-encode` built, the other half's routines are unused. diff --git a/crates/audio/tests/codecs/alac.rs b/crates/audio/tests/codecs/alac.rs index 5b42f2e836..a29e898a34 100644 --- a/crates/audio/tests/codecs/alac.rs +++ b/crates/audio/tests/codecs/alac.rs @@ -153,3 +153,39 @@ fn ffmpeg_decodes_our_alac_exactly() { } } } + +/// Quiet and silent passages at 24 and 32 bits, which our encoder codes with fewer shifted-off +/// low bytes than Apple's reference (#1368), decode exactly in ffmpeg. The packets alternate +/// between silence, audio within 12 bits, audio at the narrower widths' edges and full scale, so +/// one stream changes its shift from packet to packet. +#[test] +fn ffmpeg_decodes_our_quiet_alac_exactly() { + let Some(ff) = crate::testkit::ffmpeg_or_skip("alac oracle") else { return }; + for (channels, bits) in [(1, 24), (2, 24), (6, 24), (1, 32), (2, 32)] { + let full = input(channels, bits, 4 * 4096); + let wav: Vec> = full + .iter() + .map(|c| { + c.iter() + .enumerate() + .map(|(i, &x)| match i / 4096 { + 0 => 0, + 1 => x >> (bits - 12), + 2 => (x >> (bits - 15)) << (bits - 24), + _ => x, + }) + .collect() + }) + .collect(); + // ffmpeg does not decode escaped 32-bit stereo frames: keep the full-scale packet for 24 + let wav: Vec> = if bits == 32 { wav.iter().map(|c| c[..3 * 4096].to_vec()).collect() } else { wav }; + let m4a = our_m4a(&wav, bits, 4096); + let path = dir().join(format!("ours_quiet_{channels}ch_{bits}.m4a")); + std::fs::write(&path, &m4a).unwrap(); + let theirs = ffmpeg_decode(&ff, &path, channels, bits); + assert!(theirs == wav, "{channels} ch, {bits} bits: ffmpeg's decode differs from the input"); + if bits <= 24 { + assert!(our_decode(&m4a, bits) == wav, "{channels} ch, {bits} bits: our decode differs"); + } + } +} From 6c7f2159ac37478fae0b88cc55f5e24262d46cbc Mon Sep 17 00:00:00 2001 From: alehel Date: Sat, 14 Nov 2026 21:59:14 +0100 Subject: [PATCH 018/322] craft-audio: PacketEncoder, one packet interface over the encoders PacketEncoder::new(codec, &EncodeOptions, sample_rate, channels) covers AAC-LC, ALAC, MP3, AC-3, E-AC-3 and Opus, each behind its feature. It takes planar f32 in WAV channel order, maps the channels onto the codec's order (quantizing for ALAC at the configured depth), and returns EncodedPacket { data, pts, duration }; finish() drains the rest. The encoder reports codec_params() (codec, rate, channels, extradata), layout(), priming(), padding(), bitrate() and bit_depth() for a muxer. FileEncoder's coded formats now go through it: the codec dispatch, channel maps and rate selection moved from write/coded.rs to packet.rs, and coded.rs keeps only the M4A and raw sinks. The files written are byte-identical to before. Refs #1230 (point 3). Co-Authored-By: Claude Opus 5.5 --- crates/audio/Cargo.toml | 3 +- crates/audio/README.md | 76 +- crates/audio/src/lib.rs | 21 + crates/audio/src/packet.rs | 683 ++++++++++++++++++ .../src/{write/coded => packet}/tests.rs | 24 +- crates/audio/src/write/coded.rs | 411 ++--------- crates/audio/src/write/mod.rs | 2 +- crates/audio/tests/codecs/main.rs | 1 + crates/audio/tests/codecs/packet_encoder.rs | 239 ++++++ 9 files changed, 1098 insertions(+), 362 deletions(-) create mode 100644 crates/audio/src/packet.rs rename crates/audio/src/{write/coded => packet}/tests.rs (90%) create mode 100644 crates/audio/tests/codecs/packet_encoder.rs diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index d132f23da2..38781ec845 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -23,7 +23,7 @@ decode-native = ["aac-decode", "alac-decode", "opus-decode", "ac3-decode", "mpa- # The symphonia fallback for the formats with no native decoder yet. symphonia = ["decode-native", "dep:symphonia"] # Every encoder: the lossless file writers and the AAC, ALAC, AC-3/E-AC-3, MP3 and Opus encoders. -# All but Opus are also file formats of `encode` and `FileEncoder`. +# All but Opus are also file formats of `encode` and `FileEncoder`; all are codecs of `PacketEncoder`. encode = ["lossless-encode", "aac-encode", "alac-encode", "ac3-encode", "eac3-encode", "mp3-encode", "opus-encode"] # Encode WAV/BWF/RF64, AIFF/AIFF-C and FLAC files. lossless-encode = ["pcm-encode", "flac-encode"] @@ -36,6 +36,7 @@ aac-decode = ["craft-media/bitstream"] # The AAC encoder (`aac::Encoder`), and AAC in M4A through `encode` and `FileEncoder`. aac-encode = ["craft-media/bitstream", "craft-media/isobmff"] opus-decode = [] +# The Opus encoder (`opus::encoder`), and Opus through `PacketEncoder`. opus-encode = [] ac3-decode = ["craft-media/bitstream"] mpa-decode = ["craft-media/bitstream"] diff --git a/crates/audio/README.md b/crates/audio/README.md index 5a5df4f2f5..5e5922ebdc 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -33,15 +33,15 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou | `lossless-encode` | WAV, AIFF and FLAC writing | `pcm-encode`, `flac-encode` | | `pcm-encode` | `encode`, `FileEncoder` for WAV and AIFF; `wav_float_header`; `pcm_wav_file`, `pcm_wav_header`, `pcm_aiff_file`, `pcm_aiff_header` (minimal files around integer PCM bytes, for essence embedded in AAF / OMF) | none | | `flac-encode` | `encode`, `FileEncoder` for FLAC; `flac::Encoder`, the packet encoder for callers that mux FLAC themselves | craft-media `bitstream` | -| `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A | craft-media `bitstream`; `aac-encode` also `isobmff` | +| `aac-decode`, `aac-encode` | `aac::Decoder`, `aac::Encoder`; with `aac-decode`, `aac::latm_config` / `latm_split` for LOAS / LATM frames (AAC in MPEG transport streams); with `aac-encode`, `encode`, `FileEncoder` for AAC in M4A and `PacketEncoder` for AAC | craft-media `bitstream`; `aac-encode` also `isobmff` | | `alac-decode` | `alac::Decoder` | none | -| `alac-encode` | `alac::Encoder`; `encode`, `FileEncoder` for ALAC in M4A | craft-media `isobmff` | -| `opus-decode`, `opus-encode` | `opus::Decoder`/`StreamDecoder`, `opus::Encoder` | none | +| `alac-encode` | `alac::Encoder`; `encode`, `FileEncoder` for ALAC in M4A; `PacketEncoder` for ALAC | craft-media `isobmff` | +| `opus-decode`, `opus-encode` | `opus::Decoder`/`StreamDecoder`, `opus::Encoder`; with `opus-encode`, `PacketEncoder` for Opus | none | | `ac3-decode` | `ac3::Decoder`, `ac3::ProgrammeDecoder` | craft-media `bitstream` | -| `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder`; `encode`, `FileEncoder` for AC-3 and E-AC-3 streams | craft-media `bitstream` | +| `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder`; `encode`, `FileEncoder` for AC-3 and E-AC-3 streams; `PacketEncoder` for them | craft-media `bitstream` | | `mpa-decode` | `mpa::Decoder` | craft-media `bitstream` | | `mp3-decode` | `mp3::Decoder`, `mp3::InfoTag` | `mpa-decode` | -| `mp3-encode` | `mp3::Encoder`; `encode`, `FileEncoder` for MP3 | craft-media `bitstream` | +| `mp3-encode` | `mp3::Encoder`; `encode`, `FileEncoder` for MP3; `PacketEncoder` for MP3 | craft-media `bitstream` | | `peaks` | `peaks::Peaks` | none | | `rayon` | parallel AAC encoding (with `aac-encode`) | `rayon` | | `serde` | `Serialize`/`Deserialize` on the shared types | `serde` | @@ -304,12 +304,72 @@ file needs that step before it is written again. An M4A's edit list skips the AAC encoder's priming (1024 frames) and ends at the last frame written, so the file decodes to the length that went in. An MP3, AC-3 or E-AC-3 stream has no -place for that (see [Limits](#limits)). For a container of your own, use the codec modules below. +place for that (see [Limits](#limits)). For a container of your own, use `PacketEncoder` below. + +### Encode packets for your own container + +`PacketEncoder` is the encode-side counterpart of `TrackDecoder`: one interface over the AAC-LC, +ALAC, MP3, AC-3, E-AC-3 and Opus encoders for an app that muxes the audio itself (a video export +to MP4, Matroska or MXF). It returns packets and writes no file; `FileEncoder` writes its coded +formats through it. + +```rust +use craft_audio::{CodecId, EncodeFormat, EncodeOptions, PacketEncoder}; + +let opts = EncodeOptions::new(EncodeFormat::Aac).with_layout(info.layout).with_bitrate(384_000); +let mut enc = PacketEncoder::new(CodecId::Aac, &opts, 48_000, 6)?; +for block in blocks { // planar f32 in WAV order, any length + for p in enc.encode(&block.channels, block.frames())? { + mux.write(p.pts, p.duration, &p.data)?; // pts and duration in samples at the rate + } +} +for p in enc.finish()? { + mux.write(p.pts, p.duration, &p.data)?; +} +let params = enc.codec_params(); // codec, rate, channels, extradata: what TrackDecoder::new takes +let priming = enc.priming(); // decoded samples before the first input frame +let padding = enc.padding(); // decoded samples after the last one +``` + +It takes the `EncodeOptions` of `FileEncoder` and reads `rate_control`, `layout`, and for ALAC +`bit_depth` and `dither`; `format` is ignored, so `EncodeOptions::default()` with a bit rate will +do for any codec. Input is planar `f32` in WAV channel order. `layout` names the speakers, the +channels are reordered into the codec's order, and ALAC's samples are quantized to the bit depth. +`layout()` reports the speakers the stream carries, in WAV order: the codec's layout for the count +(AAC's 5.1 has side surrounds, ALAC's back surrounds), or the AC-3 coding mode the layout chose. + +| `CodecId` | Feature | Frames per packet | `extradata()` | `priming()` | +|---|---|---|---|---| +| `Aac` (LC) | `aac-encode` | 1024 | `AudioSpecificConfig` | 1024 | +| `Alac` | `alac-encode` | 4096, the last one shorter | `alac` box payload / CodecPrivate | 0 | +| `Mp3` | `mp3-encode` | 1152 (576 below 32 kHz), one frame per packet | empty | 1057 | +| `Ac3`, `Eac3` | `ac3-encode`, `eac3-encode` | 1536 | empty | 256 | +| `Opus` | `opus-encode` | 960 (20 ms) | `OpusHead` | the pre-skip | + +The sample rates, channel counts and layouts are those of the `EncodeFormat` of the same name; +Opus takes 48 kHz mono or stereo at a constant bit rate, 64 kbit/s per channel by default. A codec +with no encoder here, and one whose feature is off, are `Unsupported`; settings a codec cannot take +get the error `EncodeOptions::check` gives for the format. + +Timing: a packet's `pts` is where its decoded audio starts, counted from the first decoded sample, +so input frame `n` is at `n + priming()`. `finish` pads the end with silence until a decoder +returns every input frame, and the durations add up to `priming() + frames() + padding()`. A muxer +skips the priming (MP4: `TrackConfig::media_start` or an edit list; Matroska: `CodecDelay`; Opus: +the pre-skip, which `OpusHead` already holds) and trims the padding (the end of an MP4 edit, +Matroska's `DiscardPadding`). ALAC's `extradata` records the largest packet and the average bit +rate, so read it after `finish`. `bitrate()` is the constant rate used (`None` for ALAC and AAC by +quality); `bit_depth()` is ALAC's. + +`encode` refuses a block without one slice per channel, or with a slice shorter than `frames`, +and encodes nothing. After `finish`, or after an encode that failed, every call returns an error. +E-AC-3 7.1 is encoded as 7.1, and this crate's `TrackDecoder` plays its 5.1 substream (see +[Limits](#limits)). ### Encode AAC packets -For an `.m4a` file, use `EncodeFormat::Aac` above. `aac::Encoder` is the packet encoder behind it, -for muxing into a container of your own: +For an `.m4a` file, use `EncodeFormat::Aac` above, and for packets in WAV channel order, +`PacketEncoder`. `aac::Encoder` is the codec's own encoder behind both, with the settings +`EncodeOptions` does not have (bandwidth, TNS, M/S stereo, window shape, ADTS): ```rust use craft_audio::AudioError; diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index 1c6c73dcfe..64a94995b4 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -20,6 +20,9 @@ //! (`aac-encode`, `alac-encode`) and MP3, AC-3 and E-AC-3 streams (`mp3-encode`, `ac3-encode`, //! `eac3-encode`), whole-buffer or incremental into any `Write + Seek`. Feature //! `lossless-encode` turns on WAV, AIFF and FLAC; feature `encode` turns on every format and encoder. +//! - [`PacketEncoder`] (any of `aac-encode`, `alac-encode`, `mp3-encode`, `ac3-encode`, +//! `eac3-encode`, `opus-encode`): planar `f32` in WAV channel order to packets of AAC-LC, ALAC, +//! MP3, AC-3, E-AC-3 or Opus, with their timing and codec configuration, for an app's own muxer. //! - [`wav_pcm`], [`aiff_pcm`] (feature `decode-native`) and [`pcm_wav_file`], [`pcm_wav_header`], //! [`pcm_aiff_file`], [`pcm_aiff_header`] (feature `pcm-encode`): the integer PCM of a WAV or AIFF //! file bit for bit, and minimal files around such PCM, for essence embedded in other containers. @@ -45,6 +48,15 @@ pub mod mp3; pub mod mpa; #[cfg(any(feature = "opus-decode", feature = "opus-encode"))] pub mod opus; +#[cfg(any( + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode", + feature = "opus-encode" +))] +mod packet; #[cfg(any(feature = "aac-decode", feature = "alac-decode", feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode"))] mod pcm; #[cfg(feature = "peaks")] @@ -96,6 +108,15 @@ pub use buffer::AudioBuffer; pub use craft_media; pub use craft_media::{ByteSource, CodecId, CodecParams, Container, PcmFormat, ReadSeekSource}; pub use layout::{ChannelLayout, Speaker}; +#[cfg(any( + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode", + feature = "opus-encode" +))] +pub use packet::{EncodedPacket, PacketEncoder}; #[cfg(feature = "decode-native")] pub use read::SharedSource; #[cfg(feature = "decode-native")] diff --git a/crates/audio/src/packet.rs b/crates/audio/src/packet.rs new file mode 100644 index 0000000000..4f2d6cb8c4 --- /dev/null +++ b/crates/audio/src/packet.rs @@ -0,0 +1,683 @@ +//! [`PacketEncoder`]: one interface over the AAC-LC, ALAC, MP3, AC-3, E-AC-3 and Opus encoders, for +//! a caller that puts the packets in its own container. It takes planar `f32` in WAV channel order, +//! maps the channels onto the codec's order, and returns packets with their timing; the coded +//! formats of [`FileEncoder`](crate::FileEncoder) are written through it. + +// Each codec is its own feature: with only some of them built, the other halves of the shared +// code are unused. +#![cfg_attr( + not(all( + feature = "aac-encode", + feature = "alac-encode", + feature = "mp3-encode", + feature = "ac3-encode", + feature = "eac3-encode", + feature = "opus-encode" + )), + allow(dead_code, unused_imports, unused_variables, unused_mut) +)] + +use crate::layout::channel_map; +use crate::{AudioError, ChannelLayout, CodecId, CodecParams, EncodeFormat, EncodeOptions, RateControl, Result}; + +/// Frames handed to a codec at a time, so its buffers and the packets returned for one call stay +/// small however long a block is. Also the frames of an ALAC packet. +pub(crate) const CHUNK: usize = 4096; + +/// Bits per second per channel when no rate is asked for: AAC and Opus. +const AAC_DEFAULT_BPS_PER_CHANNEL: u32 = 64_000; +const OPUS_DEFAULT_BPS_PER_CHANNEL: u32 = 64_000; +/// Kilobits per second per channel when no rate is asked for: MP3, and AC-3 and E-AC-3 (per +/// full-bandwidth channel). +const DEFAULT_KBPS_PER_CHANNEL: u32 = 96; + +/// Opus's layouts by channel count: RFC 7845 mapping family 0 (mono, and stereo as L R). +const OPUS_LAYOUT_MASKS: [&[u32]; 2] = [&[0x4], &[0x3]]; + +/// One packet from a [`PacketEncoder`]. +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EncodedPacket { + /// The coded bytes: an AAC raw data block (no ADTS header), an ALAC packet, one MP3 frame, + /// one AC-3 syncframe or an E-AC-3 access unit, one Opus packet. + pub data: Vec, + /// Where the packet's decoded audio starts, in samples at the sample rate from the first + /// decoded sample of the stream. The encoder's [priming](PacketEncoder::priming) comes first, + /// so input frame `n` is at `n + priming`. + pub pts: u64, + /// The samples per channel the packet decodes to, the last packet's padding included. + pub duration: u32, +} + +/// Encodes audio to packets of one codec, for a muxer of the caller's own: the encode-side +/// counterpart of [`TrackDecoder`](crate::TrackDecoder). Built from a [`CodecId`] and the +/// [`EncodeOptions`] of [`FileEncoder`](crate::FileEncoder), of which it reads the rate control, +/// the layout, and for ALAC the bit depth and dither. +/// +/// Input is planar `f32` in WAV channel order, one slice per channel, at any block size; packets +/// come out as they are completed, and [`finish`](Self::finish) returns the rest. What a container +/// needs to describe the track is on the encoder: [`codec_params`](Self::codec_params) (codec, +/// rate, channels and [`extradata`](Self::extradata)), [`layout`](Self::layout), +/// [`priming`](Self::priming), and after `finish` [`padding`](Self::padding). +/// +/// | Codec | Feature | Packet | `extradata` | Priming | +/// |---|---|---|---|---| +/// | [`CodecId::Aac`] (LC) | `aac-encode` | 1024 frames | `AudioSpecificConfig` | 1024 | +/// | [`CodecId::Alac`] | `alac-encode` | 4096 frames | the `alac` box / CodecPrivate | 0 | +/// | [`CodecId::Mp3`] | `mp3-encode` | 1152 frames (576 below 32 kHz) | none | 1057 | +/// | [`CodecId::Ac3`], [`CodecId::Eac3`] | `ac3-encode`, `eac3-encode` | 1536 frames | none | 256 | +/// | [`CodecId::Opus`] | `opus-encode` | 960 frames (20 ms) | `OpusHead` | the pre-skip | +/// +/// ``` +/// # #[cfg(all(feature = "aac-encode", feature = "aac-decode"))] { +/// use craft_audio::{CodecId, EncodeFormat, EncodeOptions, PacketEncoder, TrackDecoder}; +/// +/// let opts = EncodeOptions::new(EncodeFormat::Aac).with_bitrate(128_000); +/// let mut enc = PacketEncoder::new(CodecId::Aac, &opts, 48_000, 2)?; +/// let block = [vec![0.25f32; 4800], vec![-0.25f32; 4800]]; // 0.1 s, one Vec per channel +/// let mut packets = enc.encode(&block, 4800)?; +/// packets.extend(enc.finish()?); +/// assert_eq!(enc.priming(), 1024); +/// assert_eq!(packets.iter().map(|p| u64::from(p.duration)).sum::(), 1024 + 4800 + enc.padding()); +/// +/// // The description a muxer writes is what a decoder reads. +/// let mut dec = TrackDecoder::new(&enc.codec_params(), &[])?; +/// assert_eq!(dec.decode(&packets[0].data)?.frames(), 1024); +/// # } +/// # Ok::<(), craft_audio::AudioError>(()) +/// ``` +pub struct PacketEncoder { + codec: CodecId, + inner: Inner, + sample_rate: u32, + /// The speakers of the channels encoded, in WAV order. + layout: ChannelLayout, + /// For each codec channel, the caller's channel that feeds it. + map: Vec, + bitrate: Option, + /// The integer depth of a lossless codec. + bit_depth: Option, + /// Where the next packet starts. + pts: u64, + /// Frames of input taken. + frames: u64, + finished: bool, + /// Set when a call failed: the packets of that block are lost, so the stream has a gap and + /// every later call is refused. + failed: bool, +} + +impl std::fmt::Debug for PacketEncoder { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PacketEncoder") + .field("codec", &self.codec) + .field("sample_rate", &self.sample_rate) + .field("layout", &self.layout) + .field("frames", &self.frames) + .finish_non_exhaustive() + } +} + +/// A packet encoder of one of the codecs, taking planar `f32` in its own channel order. +enum Inner { + #[cfg(feature = "aac-encode")] + Aac(Box), + #[cfg(feature = "alac-encode")] + Alac { + enc: Box, + quantizers: Vec, + /// Quantized samples of the packet being filled, per channel. + pending: Vec>, + }, + #[cfg(feature = "mp3-encode")] + Mp3 { + enc: Box, + /// Bytes the encoder returned that do not yet make a whole frame. + bytes: Vec, + }, + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + Ac3 { + enc: Box, + /// The block with every sample finite and within ±1, as the encoder requires. + planes: Vec>, + }, + #[cfg(feature = "opus-encode")] + Opus { + enc: Box, + /// Interleaved samples of the frame being filled. + pending: Vec, + /// Frames of the decoded stream the packets so far cover. + coded: u64, + }, +} + +/// The speakers of `mask` as labels: `"L R C LFE Ls Rs"`. +fn labels(mask: u32) -> String { + ChannelLayout::from_mask(mask).speakers().iter().map(|s| s.label()).collect::>().join(" ") +} + +/// The speakers of the caller's layout, for an error message. +fn given(layout: &ChannelLayout) -> String { + layout.mask().map_or_else(|| "without speaker assignment".into(), labels) +} + +/// [`channel_map`] for a codec with one layout per channel count (the first of `masks`), and +/// that layout; or why the audio does not fit. +fn fixed_map(masks: &[u32], name: &str, order: Option<&[usize]>, layout: &ChannelLayout) -> Result<(Vec, ChannelLayout)> { + let Some(&mask) = masks.first() else { + return Err(AudioError::Unsupported(format!("{name} cannot hold {} channels", layout.channels()))); + }; + let map = channel_map(mask, order, layout).ok_or_else(|| { + AudioError::Unsupported(format!("{name} holds {} channels as {}; the audio is {}", layout.channels(), labels(mask), given(layout))) + })?; + Ok((map, ChannelLayout::from_mask(mask))) +} + +/// The encoder's channel order over AAC's layout for the count: [`crate::aac::aac_order`], and for +/// 8 channels configuration 7's C, Lc Rc, L R, Ls Rs, LFE over the WAV order L R C LFE Ls Rs Lc Rc. +#[cfg(feature = "aac-encode")] +pub(super) fn aac_order(channels: usize) -> Option<&'static [usize]> { + if channels == 8 { Some(&[2, 6, 7, 0, 1, 4, 5, 3]) } else { crate::aac::aac_order(channels) } +} + +/// The lowest AAC bit rate used, per channel: 6 kbit/s, and a quarter of the sample rate (256 +/// bits a frame). The encoder accepts less, and from about half of this down codes silence; a +/// stream of silence is no answer to a low bit rate (or to kbit/s given as bit/s). +#[cfg(feature = "aac-encode")] +fn aac_floor_per_channel(sample_rate: u32) -> u32 { + (sample_rate / 4).max(6000) +} + +/// The AAC rate control for `rate`: a bit rate is kept within what the stream can carry, a +/// quality of 0–1 spans the encoder's VBR range. +#[cfg(feature = "aac-encode")] +pub(super) fn aac_mode(rate: Option, sample_rate: u32, channels: usize) -> crate::aac::BitrateMode { + use crate::aac::BitrateMode; + let (lo, hi) = crate::aac::cbr_range(sample_rate, channels); + let lo = lo.max(aac_floor_per_channel(sample_rate).saturating_mul(channels as u32)).min(hi.max(lo)); + // An empty range (a rate or channel count the encoder refuses anyway) leaves the rate alone. + let fit = |bps: u32| if lo <= hi { bps.clamp(lo, hi) } else { bps }; + match rate { + None => BitrateMode::Cbr(fit(AAC_DEFAULT_BPS_PER_CHANNEL.saturating_mul(channels as u32))), + Some(RateControl::Bitrate(bps)) => BitrateMode::Cbr(fit(bps)), + // NaN stays NaN, which the encoder refuses. + Some(RateControl::Quality(q)) => BitrateMode::Vbr(1.0 + 4.0 * q.clamp(0.0, 1.0)), + } +} + +/// The bit rate in bits per second for a codec with constant bit rates only. +fn constant_bps(name: &str, rate: Option, default: u32) -> Result { + match rate { + None => Ok(default), + Some(RateControl::Bitrate(bps)) => Ok(bps), + Some(RateControl::Quality(_)) => { + Err(AudioError::Unsupported(format!("{name} is encoded at a constant bit rate; set a bit rate, not a quality"))) + } + } +} + +/// The AC-3 or E-AC-3 settings for audio with `layout`, and the channel map onto them: the coding +/// mode whose speakers the layout names, at the nearest bit rate the stream can carry. +#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] +pub(super) fn ac3_config( + codec: crate::ac3::encoder::Codec, + sample_rate: u32, + layout: &ChannelLayout, + rate: Option, +) -> Result<(crate::ac3::encoder::Config, Vec)> { + use crate::ac3::encoder::{Codec, CodingMode, Config}; + use CodingMode::*; + let name = if codec == Codec::Ac3 { "AC-3" } else { "E-AC-3" }; + let modes = [Mono, Stereo, ThreeFront, StereoSurround, ThreeFrontSurround, StereoTwoSurround, ThreeFrontTwoSurround, Surround71]; + let found = modes.iter().flat_map(|&mode| [false, true].map(|lfe| (mode, lfe))).find_map(|(mode, lfe)| { + // 7.1 is an E-AC-3 programme with an LFE; the encoder has no other. + if mode == Surround71 && (codec != Codec::Eac3 || !lfe) { + return None; + } + let config = Config { codec, sample_rate, bitrate_kbps: 0, mode, lfe }; + let map = channel_map(config.channel_layout().mask()?, None, layout)?; + Some((config, map)) + }); + let Some((mut config, map)) = found else { + return Err(AudioError::Unsupported(format!("{name} has no coding mode for {} channels that are {}", layout.channels(), given(layout)))); + }; + let full = config.mode.channels() as u32; + let want = constant_bps(name, rate, DEFAULT_KBPS_PER_CHANNEL * full * 1000)? / 1000; + // What `Config::validate` asks of the rate: enough for the channels, and for AC-3 an entry of + // the frame size table, for E-AC-3 a syncframe its 11-bit word count can hold. + let least = if config.mode == Surround71 { 384 } else { 32 * full }; + config.bitrate_kbps = match codec { + Codec::Ac3 => { + let floor = crate::ac3::BITRATES.iter().copied().find(|&r| r >= least).unwrap_or(least); + crate::ac3::BITRATES.iter().rev().copied().find(|&r| r <= want).filter(|&r| r >= floor).unwrap_or(floor) + } + Codec::Eac3 => { + let most = if config.mode == Surround71 { 1024 } else { (2048 * u64::from(sample_rate) / 96_000).min(1024) as u32 }; + want.clamp(least, most.max(least)) + } + }; + Ok((config, map)) +} + +/// The feature a codec's encoder is built with, or `None` for a codec with no encoder here. +fn feature(codec: CodecId) -> Option<&'static str> { + Some(match codec { + CodecId::Aac => "aac-encode", + CodecId::Alac => "alac-encode", + CodecId::Mp3 => "mp3-encode", + CodecId::Ac3 => "ac3-encode", + CodecId::Eac3 => "eac3-encode", + CodecId::Opus => "opus-encode", + _ => return None, + }) +} + +impl PacketEncoder { + /// An encoder of `codec` for `channels` channels at `sample_rate`. Of `opts` it reads + /// `rate_control` and `layout` (as [`FileEncoder`](crate::FileEncoder) does: the speakers of + /// the caller's channels, mapped onto the codec's layout), and for ALAC `bit_depth` and + /// `dither`; `format`, `bwf` and `force_rf64` are for files and ignored. + /// + /// Opus takes 48 kHz mono or stereo at a constant bit rate (64 kbit/s per channel when none + /// is asked for); the others take what their [`EncodeFormat`] lists. A codec this crate has + /// no encoder for, and one whose feature is not built, are [`AudioError::Unsupported`]. A + /// rate, channel count, layout or rate control the codec cannot take is refused with the error + /// [`EncodeOptions::check`] gives for the format (`Unsupported` for a layout or rate control). + pub fn new(codec: CodecId, opts: &EncodeOptions, sample_rate: u32, channels: u16) -> Result { + let Some(feature) = feature(codec) else { + return Err(AudioError::Unsupported(format!("no packet encoder for {}", codec.name()))); + }; + let built = [ + (CodecId::Aac, cfg!(feature = "aac-encode")), + (CodecId::Alac, cfg!(feature = "alac-encode")), + (CodecId::Mp3, cfg!(feature = "mp3-encode")), + (CodecId::Ac3, cfg!(feature = "ac3-encode")), + (CodecId::Eac3, cfg!(feature = "eac3-encode")), + (CodecId::Opus, cfg!(feature = "opus-encode")), + ]; + if !built.contains(&(codec, true)) { + return Err(AudioError::Unsupported(format!("encoding {} needs the `{feature}` feature", codec.name()))); + } + let n = usize::from(channels); + // As the file writers word it. + if channels == 0 { + return Err(AudioError::Encode("buffer has no channels".into())); + } + if sample_rate == 0 { + return Err(AudioError::Encode("sample rate is 0".into())); + } + if let Some(layout) = &opts.layout + && layout.channels() != channels + { + return Err(AudioError::Encode(format!("a {}-channel layout for {channels} channels", layout.channels()))); + } + let given = opts.layout.unwrap_or_else(|| ChannelLayout::default_for(channels)); + let (inner, map, layout, bitrate, bit_depth) = match codec { + #[cfg(feature = "aac-encode")] + CodecId::Aac => { + let (map, layout) = fixed_map(EncodeFormat::Aac.layout_masks(channels), "AAC", aac_order(n), &given)?; + let mode = aac_mode(opts.rate_control, sample_rate, n); + let config = crate::aac::EncoderConfig { mode, ..crate::aac::EncoderConfig::cbr(sample_rate, n, 0) }; + let bitrate = match mode { + crate::aac::BitrateMode::Cbr(bps) => Some(bps), + crate::aac::BitrateMode::Vbr(_) => None, + }; + (Inner::Aac(Box::new(crate::aac::Encoder::new(config)?)), map, layout, bitrate, None) + } + #[cfg(feature = "alac-encode")] + CodecId::Alac => { + let count = u8::try_from(channels).unwrap_or(u8::MAX); + let (map, layout) = fixed_map(EncodeFormat::Alac.layout_masks(channels), "ALAC", crate::alac::alac_order(count), &given)?; + let bits = match opts.bit_depth { + crate::BitDepth::Int16 => 16, + crate::BitDepth::Int24 => 24, + crate::BitDepth::Int32 => 32, + crate::BitDepth::Float32 => return Err(AudioError::Unsupported("ALAC cannot store 32-bit float samples".into())), + }; + let config = crate::alac::EncoderConfig::new(sample_rate, count, bits).with_frame_length(CHUNK as u32); + let enc = crate::alac::Encoder::new(config)?; + let quantizers = crate::write::pcm::Quantizer::per_channel(u32::from(bits), opts.dither, n); + (Inner::Alac { enc: Box::new(enc), quantizers, pending: vec![Vec::new(); n] }, map, layout, None, Some(bits)) + } + #[cfg(feature = "mp3-encode")] + CodecId::Mp3 => { + let (map, layout) = fixed_map(EncodeFormat::Mp3.layout_masks(channels), "MP3", None, &given)?; + let want = constant_bps("MP3", opts.rate_control, DEFAULT_KBPS_PER_CHANNEL * u32::from(channels) * 1000)? / 1000; + // A sample rate MP3 has not is the encoder's to refuse. + let kbps = crate::mp3::nearest_bitrate(sample_rate, want).unwrap_or(want); + let enc = crate::mp3::Encoder::new(crate::mp3::Config::cbr(sample_rate, n, kbps))?; + (Inner::Mp3 { enc: Box::new(enc), bytes: Vec::new() }, map, layout, Some(kbps.saturating_mul(1000)), None) + } + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + CodecId::Ac3 | CodecId::Eac3 => { + let which = if codec == CodecId::Ac3 { crate::ac3::encoder::Codec::Ac3 } else { crate::ac3::encoder::Codec::Eac3 }; + let (config, map) = ac3_config(which, sample_rate, &given, opts.rate_control)?; + let enc = crate::ac3::encoder::Encoder::new(config)?; + let layout = enc.channel_layout(); + let bitrate = Some(config.bitrate_kbps.saturating_mul(1000)); + (Inner::Ac3 { enc: Box::new(enc), planes: vec![Vec::new(); n] }, map, layout, bitrate, None) + } + #[cfg(feature = "opus-encode")] + CodecId::Opus => { + let masks = n.checked_sub(1).and_then(|i| OPUS_LAYOUT_MASKS.get(i)).copied().unwrap_or_default(); + let (map, layout) = fixed_map(masks, "Opus", None, &given)?; + if sample_rate != 48_000 { + return Err(AudioError::Unsupported(format!("Opus is encoded at 48000 Hz, not {sample_rate} Hz"))); + } + let bps = constant_bps("Opus", opts.rate_control, OPUS_DEFAULT_BPS_PER_CHANNEL * u32::from(channels))?; + let enc = crate::opus::encoder::Encoder::new(channels as u8, bps)?; + let bitrate = Some(enc.bitrate()); + (Inner::Opus { enc: Box::new(enc), pending: Vec::new(), coded: 0 }, map, layout, bitrate, None) + } + #[allow(unreachable_patterns)] + _ => return Err(AudioError::Unsupported(format!("no packet encoder for {}", codec.name()))), + }; + Ok(PacketEncoder { codec, inner, sample_rate, layout, map, bitrate, bit_depth, pts: 0, frames: 0, finished: false, failed: false }) + } + + /// The codec of the packets. + pub fn codec(&self) -> CodecId { + self.codec + } + + /// The sample rate of the audio and of the packets' timing. + pub fn sample_rate(&self) -> u32 { + self.sample_rate + } + + /// The number of channels. + pub fn channels(&self) -> u16 { + self.layout.channels() + } + + /// The speakers of the channels encoded, in WAV order: the codec's layout for the channel + /// count (for AC-3 and E-AC-3, the coding mode's), which is what a decoder reports. Where the + /// codec has one surround pair, it is the codec's (AAC's 5.1 has side surrounds, ALAC's back + /// ones), whichever pair the caller's layout named. + pub fn layout(&self) -> ChannelLayout { + self.layout + } + + /// The constant bit rate in bits per second for all channels together, as + /// [`RateControl::Bitrate`] describes the rate the stream settles on; `None` for ALAC and + /// for AAC at a constant quality. + pub fn bitrate(&self) -> Option { + self.bitrate + } + + /// The bits per sample of a lossless codec (ALAC), `None` for the lossy ones. + pub fn bit_depth(&self) -> Option { + self.bit_depth + } + + /// The codec configuration a container stores: AAC's `AudioSpecificConfig` (MP4 `esds` + /// decoder-specific info, Matroska CodecPrivate), ALAC's configuration as MP4's `alac` box + /// and Matroska's CodecPrivate hold it, Opus's `OpusHead`; empty for MP3, AC-3 and E-AC-3. + /// ALAC's records the largest packet and the average bit rate so far, so read it after + /// [`finish`](Self::finish). + pub fn extradata(&self) -> Vec { + match &self.inner { + #[cfg(feature = "aac-encode")] + Inner::Aac(enc) => enc.audio_specific_config(), + #[cfg(feature = "alac-encode")] + Inner::Alac { enc, .. } => enc.cookie(), + #[cfg(feature = "opus-encode")] + Inner::Opus { enc, .. } => enc.opus_head(), + #[allow(unreachable_patterns)] + _ => Vec::new(), + } + } + + /// The codec, sample rate, channels and [`extradata`](Self::extradata): the description + /// [`TrackDecoder::new`](crate::TrackDecoder::new) takes, and what a muxer's track needs. + pub fn codec_params(&self) -> CodecParams { + CodecParams::new(self.codec).with_sample_rate(self.sample_rate).with_channels(self.channels()).with_extradata(self.extradata()) + } + + /// Decoded samples before the first input frame: the encoder's delay, which a container + /// skips (an MP4 edit list's media time, Matroska's CodecDelay, Opus's pre-skip, which + /// `OpusHead` already holds). 0 for ALAC. + pub fn priming(&self) -> u32 { + match &self.inner { + #[cfg(feature = "aac-encode")] + Inner::Aac(enc) => enc.priming_samples(), + #[cfg(feature = "mp3-encode")] + Inner::Mp3 { enc, .. } => enc.delay(), + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + Inner::Ac3 { enc, .. } => enc.priming_samples(), + #[cfg(feature = "opus-encode")] + Inner::Opus { enc, .. } => u32::from(enc.pre_skip()), + #[allow(unreachable_patterns)] + _ => 0, + } + } + + /// Frames of input taken so far. + pub fn frames(&self) -> u64 { + self.frames + } + + /// Decoded samples after the last input frame, which a container trims (the end of an MP4 + /// edit, Matroska's DiscardPadding): the packets' durations add up to + /// [`priming`](Self::priming) + [`frames`](Self::frames) + this. Complete after + /// [`finish`](Self::finish). + pub fn padding(&self) -> u64 { + self.pts.saturating_sub(u64::from(self.priming()).saturating_add(self.frames)) + } + + /// Encodes the first `frames` frames of `block`, one slice per channel in WAV order + /// (`&[Vec]`, `&[&[f32]]`, …), and returns the packets completed. Samples are full scale + /// at ±1; NaN is taken as 0, and what a codec cannot carry above full scale is clipped. + /// + /// `block` must have one slice per channel, each at least `frames` long; otherwise nothing is + /// encoded and the error is [`AudioError::Encode`]. A call after [`finish`](Self::finish) is + /// an error too. When encoding itself fails, the packets of the block are lost, and every + /// later call fails rather than return a stream with a gap. + pub fn encode>(&mut self, block: &[C], frames: usize) -> Result> { + self.usable()?; + let channels = usize::from(self.channels()); + if block.len() != channels { + return Err(AudioError::Encode(format!("a block of {} channels for a {channels}-channel stream", block.len()))); + } + if let Some(short) = block.iter().map(|c| c.as_ref().len()).filter(|&n| n < frames).min() { + return Err(AudioError::Encode(format!("{frames} frames asked for, but a channel holds {short}"))); + } + let mut out = Vec::new(); + for at in (0..frames).step_by(CHUNK) { + let end = frames.min(at + CHUNK); + let planes: Vec<&[f32]> = self.map.iter().map(|&c| block.get(c).and_then(|p| p.as_ref().get(at..end)).unwrap_or_default()).collect(); + if let Err(e) = self.push(&planes, &mut out) { + self.failed = true; + return Err(e); + } + self.frames = self.frames.saturating_add((end - at) as u64); + } + Ok(out) + } + + /// Encodes what the encoder still holds, padded with silence to whole packets and as far as + /// a decoder needs to return every input frame after the priming, and returns the last + /// packets. Later calls of [`encode`](Self::encode) and `finish` are errors; the description + /// ([`extradata`](Self::extradata), [`padding`](Self::padding)) stays readable. + pub fn finish(&mut self) -> Result> { + self.usable()?; + self.finished = true; + let mut out = Vec::new(); + let done = self.drain(&mut out); + if done.is_err() { + self.failed = true; + } + done.map(|()| out) + } + + fn usable(&self) -> Result<()> { + if self.failed { + Err(AudioError::Encode("the packet encoder already failed; its stream is incomplete".into())) + } else if self.finished { + Err(AudioError::Encode("the packet encoder is finished".into())) + } else { + Ok(()) + } + } + + /// Appends a packet of `duration` decoded samples at the current position. + fn emit(pts: &mut u64, out: &mut Vec, data: Vec, duration: u32) { + out.push(EncodedPacket { data, pts: *pts, duration }); + *pts = pts.saturating_add(u64::from(duration)); + } + + /// Encodes `planes` (one slice per codec channel, equally long, at most [`CHUNK`] frames) + /// and appends the packets completed. + fn push(&mut self, planes: &[&[f32]], out: &mut Vec) -> Result<()> { + let pts = &mut self.pts; + match &mut self.inner { + #[cfg(feature = "aac-encode")] + Inner::Aac(enc) => { + for data in enc.encode(planes) { + Self::emit(pts, out, data, crate::aac::FRAME_LEN as u32); + } + } + #[cfg(feature = "alac-encode")] + Inner::Alac { enc, quantizers, pending } => { + let frames = planes.first().map_or(0, |p| p.len()); + let mut at = 0; + while at < frames { + let filled = pending.first().map_or(0, Vec::len); + let end = frames.min(at + CHUNK.saturating_sub(filled).max(1)); + for ((dst, q), src) in pending.iter_mut().zip(quantizers.iter_mut()).zip(planes) { + dst.extend(src.get(at..end).unwrap_or_default().iter().map(|&s| q.quantize(s))); + } + at = end; + if pending.first().is_some_and(|p| p.len() >= CHUNK) { + alac_packet(enc, pending, pts, out)?; + } + } + } + #[cfg(feature = "mp3-encode")] + Inner::Mp3 { enc, bytes } => { + bytes.extend(enc.encode(planes)); + mp3_frames(enc, bytes, pts, out)?; + } + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + Inner::Ac3 { enc, planes: clean } => { + for (dst, src) in clean.iter_mut().zip(planes) { + dst.clear(); + dst.extend(src.iter().map(|&s| if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) })); + } + let refs: Vec<&[f32]> = clean.iter().map(Vec::as_slice).collect(); + for p in enc.push(&refs)? { + Self::emit(pts, out, p.data, p.samples); + } + } + #[cfg(feature = "opus-encode")] + Inner::Opus { enc, pending, coded } => { + let frames = planes.first().map_or(0, |p| p.len()); + for i in 0..frames { + pending.extend(planes.iter().map(|p| p.get(i).copied().map_or(0.0, |s| if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) }))); + if pending.len() == crate::opus::encoder::Encoder::FRAME_SIZE * planes.len() { + opus_packet(enc, pending, coded, pts, out)?; + } + } + } + } + Ok(()) + } + + /// Encodes what the codec still holds and appends the last packets. + fn drain(&mut self, out: &mut Vec) -> Result<()> { + let pts = &mut self.pts; + match &mut self.inner { + #[cfg(feature = "aac-encode")] + Inner::Aac(enc) => { + for data in enc.flush() { + Self::emit(pts, out, data, crate::aac::FRAME_LEN as u32); + } + } + #[cfg(feature = "alac-encode")] + Inner::Alac { enc, pending, .. } => { + if pending.first().is_some_and(|p| !p.is_empty()) { + alac_packet(enc, pending, pts, out)?; + } + } + #[cfg(feature = "mp3-encode")] + Inner::Mp3 { enc, bytes } => { + bytes.extend(enc.flush()); + mp3_frames(enc, bytes, pts, out)?; + if !bytes.is_empty() { + return Err(AudioError::Encode(format!("the MP3 encoder ended with {} bytes that are not a whole frame", bytes.len()))); + } + } + #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] + Inner::Ac3 { enc, .. } => { + for p in enc.finish()?.packets { + Self::emit(pts, out, p.data, p.samples); + } + } + #[cfg(feature = "opus-encode")] + Inner::Opus { enc, pending, coded } => { + // Every input frame decodes after the pre-skip: as many packets as that takes. + let size = crate::opus::encoder::Encoder::FRAME_SIZE as u64; + let needed = if self.frames == 0 { 0 } else { (self.frames + u64::from(enc.pre_skip())).div_ceil(size) * size }; + let width = usize::from(enc.channels()); + while *coded < needed { + pending.resize(crate::opus::encoder::Encoder::FRAME_SIZE * width, 0.0); + opus_packet(enc, pending, coded, pts, out)?; + } + } + } + Ok(()) + } +} + +/// Encodes the pending samples as one ALAC packet and empties them. +#[cfg(feature = "alac-encode")] +fn alac_packet(enc: &mut crate::alac::Encoder, pending: &mut [Vec], pts: &mut u64, out: &mut Vec) -> Result<()> { + let refs: Vec<&[i32]> = pending.iter().map(Vec::as_slice).collect(); + let frames = refs.first().map_or(0, |p| p.len()) as u32; + let data = enc.encode(&refs)?; + pending.iter_mut().for_each(Vec::clear); + PacketEncoder::emit(pts, out, data, frames); + Ok(()) +} + +/// Encodes one full frame of pending interleaved samples as an Opus packet and empties them. +#[cfg(feature = "opus-encode")] +fn opus_packet( + enc: &mut crate::opus::encoder::Encoder, + pending: &mut Vec, + coded: &mut u64, + pts: &mut u64, + out: &mut Vec, +) -> Result<()> { + let data = enc.encode_float(pending)?; + pending.clear(); + let size = crate::opus::encoder::Encoder::FRAME_SIZE as u32; + *coded += u64::from(size); + PacketEncoder::emit(pts, out, data, size); + Ok(()) +} + +/// Splits the whole MP3 frames off the front of `bytes`. The encoder writes constant-rate frames +/// back to back, so each one's length follows from its header's padding bit. +#[cfg(feature = "mp3-encode")] +fn mp3_frames(enc: &crate::mp3::Encoder, bytes: &mut Vec, pts: &mut u64, out: &mut Vec) -> Result<()> { + let samples = enc.frame_samples(); + let config = enc.config(); + // Bytes per frame: samples / 8 × bit rate / sample rate, plus the padding slot. + let base = (samples as u64 / 8 * u64::from(config.bitrate_kbps) * 1000 / u64::from(config.sample_rate.max(1))) as usize; + let mut at = 0; + while let Some(header) = bytes.get(at..at + 4) { + if header[0] != 0xFF || header[1] & 0xE0 != 0xE0 { + return Err(AudioError::Encode("the MP3 encoder returned bytes that are not a frame".into())); + } + let len = base + usize::from((header[2] >> 1) & 1); + let Some(frame) = bytes.get(at..at + len).filter(|_| len > 4) else { break }; + PacketEncoder::emit(pts, out, frame.to_vec(), samples as u32); + at += len; + } + bytes.drain(..at); + Ok(()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/audio/src/write/coded/tests.rs b/crates/audio/src/packet/tests.rs similarity index 90% rename from crates/audio/src/write/coded/tests.rs rename to crates/audio/src/packet/tests.rs index cbdbd3375b..0056a6b162 100644 --- a/crates/audio/src/write/coded/tests.rs +++ b/crates/audio/src/packet/tests.rs @@ -1,6 +1,6 @@ use super::*; -use crate::Speaker; +use crate::{CodecId, Speaker}; fn map(mask: u32, order: Option<&[usize]>, layout: u32) -> Option> { channel_map(mask, order, &ChannelLayout::from_mask(layout)) @@ -165,3 +165,25 @@ fn the_listed_sample_rates_are_the_encoders() { assert_eq!(EncodeFormat::Aac.sample_rates().unwrap(), sorted(&crate::aac::SAMPLE_RATES)); assert_eq!(EncodeFormat::Mp3.sample_rates().unwrap(), sorted(&crate::mp3::SAMPLE_RATES)); } + +/// A codec whose feature is not built is refused, as `EncodeOptions::check` refuses its format. +#[test] +fn unbuilt_codecs_are_unsupported() { + let built = [ + (CodecId::Aac, cfg!(feature = "aac-encode")), + (CodecId::Alac, cfg!(feature = "alac-encode")), + (CodecId::Mp3, cfg!(feature = "mp3-encode")), + (CodecId::Ac3, cfg!(feature = "ac3-encode")), + (CodecId::Eac3, cfg!(feature = "eac3-encode")), + (CodecId::Opus, cfg!(feature = "opus-encode")), + ]; + let opts = EncodeOptions::default().with_bit_depth(crate::BitDepth::Int16); + for (codec, built) in built { + let made = PacketEncoder::new(codec, &opts, 48_000, 2); + if built { + assert!(made.is_ok(), "{codec:?}: {made:?}"); + } else { + assert!(matches!(&made, Err(AudioError::Unsupported(m)) if m.contains("feature")), "{codec:?}: {made:?}"); + } + } +} diff --git a/crates/audio/src/write/coded.rs b/crates/audio/src/write/coded.rs index 0d0dd626f4..040d590d0d 100644 --- a/crates/audio/src/write/coded.rs +++ b/crates/audio/src/write/coded.rs @@ -1,7 +1,7 @@ //! The coded formats of [`FileEncoder`](crate::FileEncoder): AAC-LC and ALAC in M4A (through -//! craft-media's MP4 muxer) and MP3, AC-3 and E-AC-3 as raw streams. [`Writer`] maps the caller's -//! WAV-order channels onto the encoder's order, drives the packet encoder, and for M4A records the -//! encoder's priming and the exact length in the edit list. +//! craft-media's MP4 muxer) and MP3, AC-3 and E-AC-3 as raw streams. [`Writer`] drives a +//! [`PacketEncoder`], which maps the caller's WAV-order channels onto the codec's order, and for +//! M4A records the encoder's priming and the exact length in the edit list. // Each codec is its own feature, and so are the two sinks: with only some of them built, the // other halves of the shared code are unused. @@ -11,271 +11,10 @@ )] use super::failed_write_error; -use super::pcm::validate_layout; -use crate::layout::channel_map; -use crate::{AudioBuffer, AudioError, ChannelLayout, EncodeFormat, EncodeOptions, RateControl, Result}; +use crate::packet::{EncodedPacket, PacketEncoder}; +use crate::{AudioBuffer, AudioError, CodecId, EncodeFormat, EncodeOptions, Result}; use std::io::{Cursor, Seek, Write}; -/// Frames handed to the encoder at a time, so its buffers and the packets waiting to be written -/// stay small however long a block is. Also the frames of an ALAC packet. -const CHUNK: usize = 4096; - -/// Bits per second per channel when no rate is asked for: AAC. -const AAC_DEFAULT_BPS_PER_CHANNEL: u32 = 64_000; -/// Kilobits per second per channel when no rate is asked for: MP3, and AC-3 and E-AC-3 (per -/// full-bandwidth channel). -const DEFAULT_KBPS_PER_CHANNEL: u32 = 96; - -/// The speakers of `mask` as labels: `"L R C LFE Ls Rs"`. -fn labels(mask: u32) -> String { - ChannelLayout::from_mask(mask).speakers().iter().map(|s| s.label()).collect::>().join(" ") -} - -/// [`channel_map`] for a format with one layout per channel count ([`EncodeFormat::layout_masks`]), -/// or why the audio does not fit. -fn fixed_map(format: EncodeFormat, name: &str, order: Option<&[usize]>, layout: &ChannelLayout) -> Result> { - let Some(&mask) = format.layout_masks(layout.channels()).first() else { - return Err(AudioError::Unsupported(format!("{name} cannot hold {} channels", layout.channels()))); - }; - channel_map(mask, order, layout).ok_or_else(|| { - AudioError::Unsupported(format!("{name} holds {} channels as {}; the audio is {}", layout.channels(), labels(mask), given(layout))) - }) -} - -/// The speakers of the caller's layout, for an error message. -fn given(layout: &ChannelLayout) -> String { - layout.mask().map_or_else(|| "without speaker assignment".into(), labels) -} - -/// The encoder's channel order over AAC's layout for the count: [`crate::aac::aac_order`], and for 8 channels -/// configuration 7's C, Lc Rc, L R, Ls Rs, LFE over the WAV order L R C LFE Ls Rs Lc Rc. -#[cfg(feature = "aac-encode")] -fn aac_order(channels: usize) -> Option<&'static [usize]> { - if channels == 8 { Some(&[2, 6, 7, 0, 1, 4, 5, 3]) } else { crate::aac::aac_order(channels) } -} - -/// The lowest AAC bit rate the writer uses, per channel: 6 kbit/s, and a quarter of the sample -/// rate (256 bits a frame). The encoder accepts less, and from about half of this down codes -/// silence; a file of silence is no answer to a low bit rate (or to kbit/s given as bit/s). -#[cfg(feature = "aac-encode")] -fn aac_floor_per_channel(sample_rate: u32) -> u32 { - (sample_rate / 4).max(6000) -} - -/// The AAC rate control for `rate`: a bit rate is kept within what the stream can carry, a -/// quality of 0–1 spans the encoder's VBR range. -#[cfg(feature = "aac-encode")] -fn aac_mode(rate: Option, sample_rate: u32, channels: usize) -> crate::aac::BitrateMode { - use crate::aac::BitrateMode; - let (lo, hi) = crate::aac::cbr_range(sample_rate, channels); - let lo = lo.max(aac_floor_per_channel(sample_rate).saturating_mul(channels as u32)).min(hi.max(lo)); - // An empty range (a rate or channel count the encoder refuses anyway) leaves the rate alone. - let fit = |bps: u32| if lo <= hi { bps.clamp(lo, hi) } else { bps }; - match rate { - None => BitrateMode::Cbr(fit(AAC_DEFAULT_BPS_PER_CHANNEL.saturating_mul(channels as u32))), - Some(RateControl::Bitrate(bps)) => BitrateMode::Cbr(fit(bps)), - // NaN stays NaN, which the encoder refuses. - Some(RateControl::Quality(q)) => BitrateMode::Vbr(1.0 + 4.0 * q.clamp(0.0, 1.0)), - } -} - -/// The bit rate in kbit/s for a codec with constant bit rates only. -fn constant_kbps(name: &str, rate: Option, default: u32) -> Result { - match rate { - None => Ok(default), - Some(RateControl::Bitrate(bps)) => Ok(bps / 1000), - Some(RateControl::Quality(_)) => { - Err(AudioError::Unsupported(format!("{name} is encoded at a constant bit rate; set a bit rate, not a quality"))) - } - } -} - -/// The AC-3 or E-AC-3 settings for audio with `layout`, and the channel map onto them: the coding -/// mode whose speakers the layout names, at the nearest bit rate the stream can carry. -#[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] -fn ac3_config( - codec: crate::ac3::encoder::Codec, - sample_rate: u32, - layout: &ChannelLayout, - rate: Option, -) -> Result<(crate::ac3::encoder::Config, Vec)> { - use crate::ac3::encoder::{Codec, CodingMode, Config}; - use CodingMode::*; - let name = if codec == Codec::Ac3 { "AC-3" } else { "E-AC-3" }; - let modes = [Mono, Stereo, ThreeFront, StereoSurround, ThreeFrontSurround, StereoTwoSurround, ThreeFrontTwoSurround, Surround71]; - let found = modes.iter().flat_map(|&mode| [false, true].map(|lfe| (mode, lfe))).find_map(|(mode, lfe)| { - // 7.1 is an E-AC-3 programme with an LFE; the encoder has no other. - if mode == Surround71 && (codec != Codec::Eac3 || !lfe) { - return None; - } - let config = Config { codec, sample_rate, bitrate_kbps: 0, mode, lfe }; - let map = channel_map(config.channel_layout().mask()?, None, layout)?; - Some((config, map)) - }); - let Some((mut config, map)) = found else { - return Err(AudioError::Unsupported(format!("{name} has no coding mode for {} channels that are {}", layout.channels(), given(layout)))); - }; - let full = config.mode.channels() as u32; - let want = constant_kbps(name, rate, DEFAULT_KBPS_PER_CHANNEL * full)?; - // What `Config::validate` asks of the rate: enough for the channels, and for AC-3 an entry of - // the frame size table, for E-AC-3 a syncframe its 11-bit word count can hold. - let least = if config.mode == Surround71 { 384 } else { 32 * full }; - config.bitrate_kbps = match codec { - Codec::Ac3 => { - let floor = crate::ac3::BITRATES.iter().copied().find(|&r| r >= least).unwrap_or(least); - crate::ac3::BITRATES.iter().rev().copied().find(|&r| r <= want).filter(|&r| r >= floor).unwrap_or(floor) - } - Codec::Eac3 => { - let most = if config.mode == Surround71 { 1024 } else { (2048 * u64::from(sample_rate) / 96_000).min(1024) as u32 }; - want.clamp(least, most.max(least)) - } - }; - Ok((config, map)) -} - -/// One encoded packet and the frames it decodes to. -struct Packet { - data: Vec, - frames: u32, -} - -/// A packet encoder of any of the codecs, taking planar `f32` in its own channel order. -enum Codec { - #[cfg(feature = "aac-encode")] - Aac(Box), - #[cfg(feature = "alac-encode")] - Alac { - enc: Box, - quantizers: Vec, - /// Quantized samples of the packet being filled, per channel. - pending: Vec>, - }, - #[cfg(feature = "mp3-encode")] - Mp3(Box), - #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] - Ac3 { - enc: Box, - /// The block with every sample finite and within ±1, as the encoder requires. - planes: Vec>, - }, -} - -impl Codec { - /// Encodes `planes` (one slice per encoder channel, equally long, at most [`CHUNK`] frames) - /// and appends the packets completed. - fn push(&mut self, planes: &[&[f32]], out: &mut Vec) -> Result<()> { - match self { - #[cfg(feature = "aac-encode")] - Codec::Aac(enc) => out.extend(enc.encode(planes).into_iter().map(|data| Packet { data, frames: crate::aac::FRAME_LEN as u32 })), - #[cfg(feature = "alac-encode")] - Codec::Alac { enc, quantizers, pending } => { - let frames = planes.first().map_or(0, |p| p.len()); - let mut at = 0; - while at < frames { - let filled = pending.first().map_or(0, Vec::len); - let end = frames.min(at + CHUNK.saturating_sub(filled).max(1)); - for ((dst, q), src) in pending.iter_mut().zip(quantizers.iter_mut()).zip(planes) { - dst.extend(src.get(at..end).unwrap_or_default().iter().map(|&s| q.quantize(s))); - } - at = end; - if pending.first().is_some_and(|p| p.len() >= CHUNK) { - alac_packet(enc, pending, out)?; - } - } - } - #[cfg(feature = "mp3-encode")] - Codec::Mp3(enc) => { - let data = enc.encode(planes); - if !data.is_empty() { - out.push(Packet { data, frames: 0 }); - } - } - #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] - Codec::Ac3 { enc, planes: clean } => { - for (dst, src) in clean.iter_mut().zip(planes) { - dst.clear(); - dst.extend(src.iter().map(|&s| if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) })); - } - let refs: Vec<&[f32]> = clean.iter().map(Vec::as_slice).collect(); - out.extend(enc.push(&refs)?.into_iter().map(|p| Packet { data: p.data, frames: p.samples })); - } - } - Ok(()) - } - - /// Encodes what the encoder still holds and appends the last packets. - fn finish(&mut self, out: &mut Vec) -> Result<()> { - match self { - #[cfg(feature = "aac-encode")] - Codec::Aac(enc) => out.extend(enc.flush().into_iter().map(|data| Packet { data, frames: crate::aac::FRAME_LEN as u32 })), - #[cfg(feature = "alac-encode")] - Codec::Alac { enc, pending, .. } => { - if pending.first().is_some_and(|p| !p.is_empty()) { - alac_packet(enc, pending, out)?; - } - } - #[cfg(feature = "mp3-encode")] - Codec::Mp3(enc) => { - let data = enc.flush(); - if !data.is_empty() { - out.push(Packet { data, frames: 0 }); - } - } - #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] - Codec::Ac3 { enc, .. } => out.extend(enc.finish()?.packets.into_iter().map(|p| Packet { data: p.data, frames: p.samples })), - } - Ok(()) - } - - /// Decoded frames before the first frame of the audio. - fn priming(&self) -> u32 { - match self { - #[cfg(feature = "aac-encode")] - Codec::Aac(enc) => enc.priming_samples(), - #[allow(unreachable_patterns)] - _ => 0, - } - } - - /// The MP4 sample entry of the stream as encoded so far (`bytes` in packets of `frames` - /// frames in all): the configuration a decoder needs, with the average bit rate. - #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] - fn sample_entry(&self, sample_rate: u32, channels: u32, bytes: u64, frames: u64) -> Option { - use craft_media::isobmff::{CodecConfig, FourCc, SampleEntry}; - match self { - #[cfg(feature = "aac-encode")] - Codec::Aac(enc) => { - let mut entry = SampleEntry::aac(enc.audio_specific_config(), channels, sample_rate); - if let CodecConfig::Aac(config) = &mut entry.codec - && frames > 0 - { - let bps = u128::from(bytes) * 8 * u128::from(sample_rate) / u128::from(frames); - config.avg_bitrate = u32::try_from(bps).unwrap_or(u32::MAX); - } - Some(entry) - } - #[cfg(feature = "alac-encode")] - Codec::Alac { enc, .. } => { - let bits = u16::from(enc.encoder_config().bit_depth); - Some(SampleEntry::audio(FourCc(*b"alac"), CodecConfig::Alac { cookie: enc.cookie() }, channels, f64::from(sample_rate), bits)) - } - #[allow(unreachable_patterns)] - _ => None, - } - } -} - -/// Encodes the pending samples as one ALAC packet and empties them. -#[cfg(feature = "alac-encode")] -fn alac_packet(enc: &mut crate::alac::Encoder, pending: &mut [Vec], out: &mut Vec) -> Result<()> { - let refs: Vec<&[i32]> = pending.iter().map(Vec::as_slice).collect(); - let frames = refs.first().map_or(0, |p| p.len()) as u32; - let data = enc.encode(&refs)?; - pending.iter_mut().for_each(Vec::clear); - out.push(Packet { data, frames }); - Ok(()) -} - /// A muxer's error as this crate's: a failed write stays an I/O error. #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] fn mux_error(e: craft_media::isobmff::Error) -> AudioError { @@ -285,6 +24,31 @@ fn mux_error(e: craft_media::isobmff::Error) -> AudioError { } } +/// The MP4 sample entry of the stream as encoded so far (`bytes` in packets of `frames` frames in +/// all): the configuration a decoder needs, with the average bit rate. +#[cfg(any(feature = "aac-encode", feature = "alac-encode"))] +fn sample_entry(enc: &PacketEncoder, bytes: u64, frames: u64) -> Option { + use craft_media::isobmff::{CodecConfig, FourCc, SampleEntry}; + let (rate, channels) = (enc.sample_rate(), u32::from(enc.channels())); + match enc.codec() { + CodecId::Aac => { + let mut entry = SampleEntry::aac(enc.extradata(), channels, rate); + if let CodecConfig::Aac(config) = &mut entry.codec + && frames > 0 + { + let bps = u128::from(bytes) * 8 * u128::from(rate) / u128::from(frames); + config.avg_bitrate = u32::try_from(bps).unwrap_or(u32::MAX); + } + Some(entry) + } + CodecId::Alac => { + let bits = u16::from(enc.bit_depth().unwrap_or(16)); + Some(SampleEntry::audio(FourCc(*b"alac"), CodecConfig::Alac { cookie: enc.extradata() }, channels, f64::from(rate), bits)) + } + _ => None, + } +} + /// An M4A file being written: one audio track whose samples are the packets. /// /// The last packet is held back until the length is known: its duration is cut to the audio's @@ -298,9 +62,8 @@ struct M4a { track: Option, entry: craft_media::isobmff::SampleEntry, sample_rate: u32, - channels: u32, priming: u32, - held: Option, + held: Option, /// Frames and bytes of the packets written, the held one not counted. frames: u64, bytes: u64, @@ -308,13 +71,14 @@ struct M4a { #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] impl M4a { - fn new(out: W, codec: &Codec, sample_rate: u32, channels: u32) -> Result { + fn new(out: W, enc: &PacketEncoder) -> Result { use craft_media::isobmff::{Brand, Mp4Writer, WriterOptions}; - let entry = codec.sample_entry(sample_rate, channels, 0, 0).ok_or_else(|| AudioError::Unsupported("M4A holds AAC and ALAC".into()))?; + let entry = sample_entry(enc, 0, 0).ok_or_else(|| AudioError::Unsupported("M4A holds AAC and ALAC".into()))?; + let sample_rate = enc.sample_rate(); let mut options = WriterOptions::new(Brand::Mp4); options.movie_timescale = sample_rate; let mux = Mp4Writer::new(out, options).map_err(mux_error)?; - Ok(M4a { mux, track: None, entry, sample_rate, channels, priming: codec.priming(), held: None, frames: 0, bytes: 0 }) + Ok(M4a { mux, track: None, entry, sample_rate, priming: enc.priming(), held: None, frames: 0, bytes: 0 }) } fn track(&mut self, has_audio: bool) -> Result { @@ -333,7 +97,7 @@ impl M4a { Ok(track) } - fn sample(&mut self, packet: &Packet, duration: u32) -> Result<()> { + fn sample(&mut self, packet: &EncodedPacket, duration: u32) -> Result<()> { let track = self.track(true)?; let sample = craft_media::isobmff::WriteSample { data: &packet.data, duration, composition_offset: 0, is_sync: true }; self.mux.write_sample(track, sample).map_err(mux_error)?; @@ -342,22 +106,22 @@ impl M4a { Ok(()) } - fn write(&mut self, packet: Packet) -> Result<()> { + fn write(&mut self, packet: EncodedPacket) -> Result<()> { if let Some(held) = self.held.replace(packet) { - self.sample(&held, held.frames)?; + self.sample(&held, held.duration)?; } Ok(()) } - /// Writes the last packet, cut to the end of `audio_frames` frames of audio, and the `moov`. - fn finish(mut self, codec: &Codec, audio_frames: u64) -> Result { + /// Writes the last packet, cut to the end of the audio the encoder took, and the `moov`. + fn finish(mut self, enc: &PacketEncoder) -> Result { if let Some(held) = self.held.take() { - let rest = (u64::from(self.priming) + audio_frames).saturating_sub(self.frames); - self.sample(&held, rest.min(u64::from(held.frames)) as u32)?; + let rest = (u64::from(self.priming) + enc.frames()).saturating_sub(self.frames); + self.sample(&held, rest.min(u64::from(held.duration)) as u32)?; } let track = self.track(false)?; // The configuration is complete only now: the bit rate, and ALAC's largest packet. - if let Some(entry) = codec.sample_entry(self.sample_rate, self.channels, self.bytes, self.frames) { + if let Some(entry) = sample_entry(enc, self.bytes, self.frames) { self.mux.set_sample_entry(track, entry).map_err(mux_error)?; } self.mux.finish().map_err(mux_error) @@ -374,15 +138,8 @@ enum Sink { /// A file of one of the coded formats written block by block. pub(crate) struct Writer { - codec: Codec, + enc: PacketEncoder, sink: Sink, - /// For each encoder channel, the caller's channel that feeds it. - map: Vec, - /// The constant bit rate the encoder was set to, bits per second; `None` for ALAC and for - /// AAC at a constant quality. - bitrate: Option, - frames: u64, - packets: Vec, /// Set when a write has failed: the encoder and the sink no longer agree, so the writer /// refuses every later call. failed: bool, @@ -390,68 +147,23 @@ pub(crate) struct Writer { impl Writer { pub(crate) fn new(out: W, opts: &EncodeOptions, sample_rate: u32, channels: usize) -> Result { - validate_layout(channels, sample_rate)?; - let layout = opts.layout.unwrap_or_else(|| ChannelLayout::default_for(channels as u16)); - let (codec, map, bitrate) = match opts.format { - #[cfg(feature = "aac-encode")] - EncodeFormat::Aac => { - let map = fixed_map(EncodeFormat::Aac, "AAC", aac_order(channels), &layout)?; - let mode = aac_mode(opts.rate_control, sample_rate, channels); - let config = crate::aac::EncoderConfig { mode, ..crate::aac::EncoderConfig::cbr(sample_rate, channels, 0) }; - let bitrate = match mode { - crate::aac::BitrateMode::Cbr(bps) => Some(bps), - crate::aac::BitrateMode::Vbr(_) => None, - }; - (Codec::Aac(Box::new(crate::aac::Encoder::new(config)?)), map, bitrate) - } - #[cfg(feature = "alac-encode")] - EncodeFormat::Alac => { - let count = u8::try_from(channels).unwrap_or(u8::MAX); - let map = fixed_map(EncodeFormat::Alac, "ALAC", crate::alac::alac_order(count), &layout)?; - let bits = match opts.bit_depth { - crate::BitDepth::Int16 => 16, - crate::BitDepth::Int24 => 24, - crate::BitDepth::Int32 => 32, - crate::BitDepth::Float32 => return Err(AudioError::Unsupported("ALAC cannot store 32-bit float samples".into())), - }; - let enc = crate::alac::Encoder::new(crate::alac::EncoderConfig::new(sample_rate, count, bits).with_frame_length(CHUNK as u32))?; - let quantizers = super::pcm::Quantizer::per_channel(u32::from(bits), opts.dither, channels); - (Codec::Alac { enc: Box::new(enc), quantizers, pending: vec![Vec::new(); channels] }, map, None) - } - #[cfg(feature = "mp3-encode")] - EncodeFormat::Mp3 => { - let map = fixed_map(EncodeFormat::Mp3, "MP3", None, &layout)?; - let want = constant_kbps("MP3", opts.rate_control, DEFAULT_KBPS_PER_CHANNEL * channels as u32)?; - // A sample rate MP3 has not is the encoder's to refuse. - let kbps = crate::mp3::nearest_bitrate(sample_rate, want).unwrap_or(want); - let enc = crate::mp3::Encoder::new(crate::mp3::Config::cbr(sample_rate, channels, kbps))?; - (Codec::Mp3(Box::new(enc)), map, Some(kbps.saturating_mul(1000))) - } - #[cfg(any(feature = "ac3-encode", feature = "eac3-encode"))] - EncodeFormat::Ac3 | EncodeFormat::Eac3 => { - let codec = if opts.format == EncodeFormat::Ac3 { crate::ac3::encoder::Codec::Ac3 } else { crate::ac3::encoder::Codec::Eac3 }; - let (config, map) = ac3_config(codec, sample_rate, &layout, opts.rate_control)?; - let enc = crate::ac3::encoder::Encoder::new(config)?; - (Codec::Ac3 { enc: Box::new(enc), planes: vec![Vec::new(); channels] }, map, Some(config.bitrate_kbps.saturating_mul(1000))) - } - #[allow(unreachable_patterns)] - f => return Err(AudioError::Unsupported(format!("writing {f:?}"))), - }; + let channels = u16::try_from(channels).map_err(|_| AudioError::Encode("too many channels".into()))?; + let enc = PacketEncoder::new(opts.format.codec(), opts, sample_rate, channels)?; let sink = match opts.format { #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] - EncodeFormat::Aac | EncodeFormat::Alac => Sink::M4a(Box::new(M4a::new(out, &codec, sample_rate, channels as u32)?)), + EncodeFormat::Aac | EncodeFormat::Alac => Sink::M4a(Box::new(M4a::new(out, &enc)?)), _ => Sink::Raw(out), }; - Ok(Writer { codec, sink, map, bitrate, frames: 0, packets: Vec::new(), failed: false }) + Ok(Writer { enc, sink, failed: false }) } pub(crate) fn bitrate(&self) -> Option { - self.bitrate + self.enc.bitrate() } - /// Hands the packets waiting to the sink. - fn drain(&mut self) -> Result<()> { - for packet in self.packets.drain(..) { + /// Hands `packets` to the sink. + fn drain(&mut self, packets: Vec) -> Result<()> { + for packet in packets { match &mut self.sink { #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] Sink::M4a(m4a) => m4a.write(packet)?, @@ -466,16 +178,16 @@ impl Writer { if self.failed { return Err(failed_write_error()); } - for at in (0..frames).step_by(CHUNK) { - let end = frames.min(at + CHUNK); - let planes: Vec<&[f32]> = self.map.iter().map(|&c| block.get(c).and_then(|p| p.as_ref().get(at..end)).unwrap_or_default()).collect(); - let written = self.codec.push(&planes, &mut self.packets).and_then(|()| self.drain()); + // A block at a time, so the packets waiting for the sink stay few however long it is. + for at in (0..frames).step_by(crate::packet::CHUNK) { + let end = frames.min(at + crate::packet::CHUNK); + let part: Vec<&[f32]> = block.iter().map(|c| c.as_ref().get(at..end).unwrap_or_default()).collect(); + let written = self.enc.encode(&part, end - at).and_then(|packets| self.drain(packets)); if let Err(e) = written { self.failed = true; return Err(e); } } - self.frames = self.frames.saturating_add(frames as u64); Ok(()) } @@ -483,11 +195,11 @@ impl Writer { if self.failed { return Err(failed_write_error()); } - self.codec.finish(&mut self.packets)?; - self.drain()?; + let last = self.enc.finish()?; + self.drain(last)?; match self.sink { #[cfg(any(feature = "aac-encode", feature = "alac-encode"))] - Sink::M4a(m4a) => m4a.finish(&self.codec, self.frames), + Sink::M4a(m4a) => m4a.finish(&self.enc), Sink::Raw(mut out) => { out.flush()?; Ok(out) @@ -501,6 +213,3 @@ pub(crate) fn encode(buf: &AudioBuffer, opts: &EncodeOptions) -> Result> w.write(&buf.channels, buf.frames())?; Ok(w.finish()?.into_inner()) } - -#[cfg(test)] -mod tests; diff --git a/crates/audio/src/write/mod.rs b/crates/audio/src/write/mod.rs index 0de55c394b..b5e3d64e4c 100644 --- a/crates/audio/src/write/mod.rs +++ b/crates/audio/src/write/mod.rs @@ -8,7 +8,7 @@ mod aiff; mod coded; #[cfg(feature = "flac-encode")] pub(crate) mod flac; -mod pcm; +pub(crate) mod pcm; #[cfg(feature = "pcm-encode")] mod raw; #[cfg(feature = "pcm-encode")] diff --git a/crates/audio/tests/codecs/main.rs b/crates/audio/tests/codecs/main.rs index c1c9e2131b..a2e865fe24 100644 --- a/crates/audio/tests/codecs/main.rs +++ b/crates/audio/tests/codecs/main.rs @@ -18,5 +18,6 @@ mod mp3_encoder_oracle; mod mpa_oracle; mod opus; mod opusenc; +mod packet_encoder; mod routing_oracle; mod track_decoder; diff --git a/crates/audio/tests/codecs/packet_encoder.rs b/crates/audio/tests/codecs/packet_encoder.rs new file mode 100644 index 0000000000..0933443699 --- /dev/null +++ b/crates/audio/tests/codecs/packet_encoder.rs @@ -0,0 +1,239 @@ +//! `PacketEncoder`: every codec round-trips through `TrackDecoder` from the description the +//! encoder gives, at the length that was encoded and with each channel on its speaker. + +use std::io::Cursor; + +use craft_audio::{ + AudioError, BitDepth, ChannelLayout, CodecId, EncodeFormat, EncodeOptions, EncodedPacket, FileEncoder, PacketEncoder, TrackDecoder, +}; + +/// `channels` channels of `frames` frames, each a tone of its own frequency low enough for an LFE. +fn tones(sample_rate: u32, channels: usize, frames: usize) -> Vec> { + (0..channels) + .map(|c| { + let step = (40.0 + 9.0 * c as f32) * std::f32::consts::TAU / sample_rate as f32; + (0..frames).map(|i| ((i as f32 * step).sin() * 0.4 * 32768.0).round() / 32768.0).collect() + }) + .collect() +} + +/// Normalised correlation of two signals over the samples both have. +fn correlation(a: &[f32], b: &[f32]) -> f64 { + let (mut ab, mut aa, mut bb) = (0f64, 0f64, 0f64); + for (&x, &y) in a.iter().zip(b) { + let (x, y) = (f64::from(x), f64::from(y)); + ab += x * y; + aa += x * x; + bb += y * y; + } + ab / (aa * bb).sqrt().max(1e-30) +} + +/// Encodes `input` in uneven blocks and returns the packets. +fn encode(enc: &mut PacketEncoder, input: &[Vec]) -> Vec { + let frames = input[0].len(); + let mut packets = Vec::new(); + let mut at = 0; + for n in [1, 999, 4096, 10_000, 7, usize::MAX].into_iter().cycle() { + let n = n.min(frames - at); + let block: Vec<&[f32]> = input.iter().map(|c| &c[at..at + n]).collect(); + packets.extend(enc.encode(&block, n).unwrap()); + at += n; + if at == frames { + break; + } + } + packets.extend(enc.finish().unwrap()); + packets +} + +/// Encodes, checks the timing the packets carry, decodes them from the encoder's description, and +/// returns the decoded audio from the first input frame on, cut to the input's length, and the +/// layout the decoder reports. +fn decode_back(codec: CodecId, opts: &EncodeOptions, sample_rate: u32, input: &[Vec]) -> (PacketEncoder, Vec>, ChannelLayout) { + let frames = input[0].len(); + let mut enc = PacketEncoder::new(codec, opts, sample_rate, input.len() as u16).unwrap(); + let packets = encode(&mut enc, input); + assert_eq!(enc.frames(), frames as u64); + // The packets follow one another, and add up to the priming, the audio and the padding. + let mut pts = 0; + for p in &packets { + assert_eq!(p.pts, pts, "{codec:?}"); + pts += u64::from(p.duration); + } + assert_eq!(pts, u64::from(enc.priming()) + frames as u64 + enc.padding(), "{codec:?}"); + let last = packets.last().map_or(0, |p| u64::from(p.duration)); + assert!(enc.padding() < last, "{codec:?}: {} samples of padding after a packet of {last}", enc.padding()); + + let lookahead: Vec<&[u8]> = packets.iter().take(craft_audio::LOOKAHEAD_PACKETS).map(|p| p.data.as_slice()).collect(); + let mut dec = TrackDecoder::new(&enc.codec_params(), &lookahead).unwrap(); + assert_eq!((dec.codec(), dec.sample_rate()), (codec, sample_rate), "{codec:?}"); + let mut out = vec![Vec::new(); usize::from(dec.channels())]; + for p in &packets { + let block = dec.decode(&p.data).unwrap(); + assert_eq!(block.frames(), p.duration as usize, "{codec:?}: a packet's duration is what it decodes to"); + for (o, c) in out.iter_mut().zip(block.channels) { + o.extend(c); + } + } + let skip = enc.priming() as usize; + let out = out.into_iter().map(|c| c[skip..skip + frames].to_vec()).collect(); + (enc, out, dec.layout()) +} + +/// [`decode_back`] for a codec whose decoder returns every channel: on the speakers encoded. +fn round_trip(codec: CodecId, opts: &EncodeOptions, sample_rate: u32, input: &[Vec]) -> (PacketEncoder, Vec>) { + let (enc, out, layout) = decode_back(codec, opts, sample_rate, input); + assert_eq!(layout, enc.layout(), "{codec:?}"); + (enc, out) +} + +/// Each decoded channel is its input channel, in place: it matches that channel and no other. The +/// AC-3 encoders low-pass the LFE, which shifts its phase, so the match is by magnitude. +fn assert_in_place(codec: CodecId, input: &[Vec], output: &[Vec], least: f64) { + for (c, got) in output.iter().enumerate() { + let scores: Vec = input.iter().map(|want| correlation(want, got).abs()).collect(); + let least = if matches!(codec, CodecId::Ac3 | CodecId::Eac3) && c == 3 { 0.5 } else { least }; + assert!(scores[c] > least, "{codec:?} channel {c}: {scores:?}"); + for (other, &score) in scores.iter().enumerate().filter(|&(o, _)| o != c) { + assert!(score < scores[c] - 0.3, "{codec:?} channel {c} matches channel {other}: {scores:?}"); + } + } +} + +#[test] +fn aac_round_trips_in_place() { + let input = tones(48_000, 6, 30_001); + let opts = EncodeOptions::new(EncodeFormat::Aac).with_bitrate(384_000); + let (enc, out) = round_trip(CodecId::Aac, &opts, 48_000, &input); + assert_eq!((enc.priming(), enc.layout(), enc.bitrate()), (1024, ChannelLayout::SURROUND_5_1_SIDE, Some(384_000))); + assert_eq!(enc.extradata().len(), 2, "an AudioSpecificConfig for channel configuration 6"); + assert_in_place(CodecId::Aac, &input, &out, 0.95); +} + +/// 16-bit ALAC is lossless: the input comes back bit for bit. +#[test] +fn alac_round_trips_exactly() { + let input = tones(44_100, 6, 10_000); + let opts = EncodeOptions::new(EncodeFormat::Alac).with_bit_depth(BitDepth::Int16).with_layout(ChannelLayout::SURROUND_5_1); + let (enc, out) = round_trip(CodecId::Alac, &opts, 44_100, &input); + assert_eq!((enc.priming(), enc.padding(), enc.bit_depth(), enc.layout()), (0, 0, Some(16), ChannelLayout::SURROUND_5_1)); + assert_eq!(out, input); +} + +#[test] +fn mp3_round_trips_in_place() { + for (rate, frame) in [(48_000, 1152), (44_100, 1152), (24_000, 576)] { + let input = tones(rate, 2, 20_000); + let opts = EncodeOptions::new(EncodeFormat::Mp3).with_bitrate(192_000); + let mut enc = PacketEncoder::new(CodecId::Mp3, &opts, rate, 2).unwrap(); + let packets = encode(&mut enc, &input); + assert!(packets.iter().all(|p| p.duration == frame && p.data[0] == 0xFF), "{rate} Hz"); + let (enc, out) = round_trip(CodecId::Mp3, &opts, rate, &input); + assert_eq!((enc.priming(), enc.extradata()), (1057, vec![])); + assert_in_place(CodecId::Mp3, &input, &out, 0.95); + } +} + +#[test] +fn ac3_round_trips_in_place() { + let input = tones(48_000, 6, 20_000); + let (enc, out) = round_trip(CodecId::Ac3, &EncodeOptions::new(EncodeFormat::Ac3), 48_000, &input); + assert_eq!((enc.priming(), enc.layout(), enc.bitrate()), (256, ChannelLayout::SURROUND_5_1_SIDE, Some(448_000))); + assert_in_place(CodecId::Ac3, &input, &out, 0.9); +} + +#[test] +fn eac3_round_trips_in_place() { + let input = tones(48_000, 6, 20_000); + let (enc, out) = round_trip(CodecId::Eac3, &EncodeOptions::new(EncodeFormat::Eac3), 48_000, &input); + assert_eq!((enc.priming(), enc.layout()), (256, ChannelLayout::SURROUND_5_1_SIDE)); + assert_in_place(CodecId::Eac3, &input, &out, 0.9); +} + +/// 7.1 E-AC-3 is encoded as 7.1; `TrackDecoder` plays its 5.1 independent substream (see the +/// README), at the same length. +#[test] +fn eac3_7_1_decodes_as_its_5_1_substream() { + let input = tones(48_000, 8, 20_000); + let opts = EncodeOptions::new(EncodeFormat::Eac3).with_layout(ChannelLayout::SURROUND_7_1); + let (enc, out, layout) = decode_back(CodecId::Eac3, &opts, 48_000, &input); + assert_eq!((enc.layout(), enc.channels(), layout), (ChannelLayout::SURROUND_7_1, 8, ChannelLayout::SURROUND_5_1_SIDE)); + assert!(out.iter().all(|c| c.len() == 20_000)); +} + +#[test] +fn opus_round_trips_in_place() { + for channels in [1, 2] { + let input = tones(48_000, channels, 20_000); + let opts = EncodeOptions::default().with_bitrate(128_000); + let (enc, out) = round_trip(CodecId::Opus, &opts, 48_000, &input); + let head = enc.extradata(); + assert_eq!((&head[..8], head[9], u32::from(u16::from_le_bytes([head[10], head[11]]))), (&b"OpusHead"[..], channels as u8, enc.priming())); + assert_in_place(CodecId::Opus, &input, &out, 0.9); + } +} + +/// The raw streams `FileEncoder` writes are the packets in a row. +#[test] +fn file_encoder_writes_the_packets() { + for (format, layout) in [(EncodeFormat::Mp3, ChannelLayout::STEREO), (EncodeFormat::Ac3, ChannelLayout::SURROUND_5_1)] { + let input = tones(48_000, usize::from(layout.channels()), 12_345); + let opts = EncodeOptions::new(format).with_layout(layout); + let mut file = FileEncoder::new(Cursor::new(Vec::new()), &opts, 48_000, layout.channels()).unwrap(); + file.write(&input, 12_345).unwrap(); + let file = file.finish().unwrap().into_inner(); + let mut enc = PacketEncoder::new(format.codec(), &opts, 48_000, layout.channels()).unwrap(); + let packets: Vec = encode(&mut enc, &input).into_iter().flat_map(|p| p.data).collect(); + assert_eq!(file, packets, "{format:?}"); + } +} + +/// What a codec cannot take is refused, and as `EncodeOptions::check` refuses it for the format. +#[test] +fn unsupported_settings_are_refused() { + let unsupported = + |codec, opts: &EncodeOptions, rate, channels| matches!(PacketEncoder::new(codec, opts, rate, channels), Err(AudioError::Unsupported(_))); + let opts = EncodeOptions::default(); + assert!(unsupported(CodecId::Vorbis, &opts, 48_000, 2)); + assert!(unsupported(CodecId::Flac, &opts, 48_000, 2)); + assert!(unsupported(CodecId::Opus, &opts, 44_100, 2)); + assert!(unsupported(CodecId::Opus, &opts, 48_000, 3)); + assert!(unsupported(CodecId::Opus, &opts.clone().with_quality(0.5), 48_000, 2)); + for (codec, format, rate, channels) in [ + (CodecId::Mp3, EncodeFormat::Mp3, 96_000, 2), + (CodecId::Mp3, EncodeFormat::Mp3, 48_000, 0), + (CodecId::Mp3, EncodeFormat::Mp3, 48_000, 6), + (CodecId::Ac3, EncodeFormat::Ac3, 48_000, 8), + (CodecId::Aac, EncodeFormat::Aac, 44_000, 2), + ] { + let opts = EncodeOptions::new(format); + let (packets, file) = (PacketEncoder::new(codec, &opts, rate, channels).map(drop), opts.check(rate, channels)); + assert_eq!(format!("{packets:?}"), format!("{file:?}"), "{codec:?} {rate} {channels}"); + assert!(packets.is_err()); + } + assert!(unsupported(CodecId::Alac, &opts.clone().with_bit_depth(BitDepth::Float32), 48_000, 2)); + assert!(unsupported(CodecId::Ac3, &opts.clone().with_layout(ChannelLayout::unordered(2)), 48_000, 2)); + // A layout for another channel count is the caller's mistake. + assert!(matches!(PacketEncoder::new(CodecId::Aac, &opts.with_layout(ChannelLayout::STEREO), 48_000, 1), Err(AudioError::Encode(_)))); +} + +/// Blocks that do not fit, and calls after `finish`, are errors that leave the stream as it was. +#[test] +fn misuse_is_an_error() { + let mut enc = PacketEncoder::new(CodecId::Aac, &EncodeOptions::new(EncodeFormat::Aac), 48_000, 2).unwrap(); + let short = [vec![0.0f32; 10], vec![0.0; 5]]; + assert!(matches!(enc.encode(&short, 10), Err(AudioError::Encode(_)))); + assert!(matches!(enc.encode(&short[..1], 5), Err(AudioError::Encode(_)))); + assert_eq!(enc.frames(), 0); + assert!(enc.encode(&short, 5).unwrap().is_empty()); + assert_eq!(enc.finish().unwrap().len(), 2, "5 frames after 1024 of priming fit in two packets"); + assert!(matches!(enc.finish(), Err(AudioError::Encode(_)))); + assert!(matches!(enc.encode(&short, 5), Err(AudioError::Encode(_)))); + // An encoder given nothing returns nothing. + for codec in [CodecId::Aac, CodecId::Alac, CodecId::Mp3, CodecId::Ac3, CodecId::Eac3, CodecId::Opus] { + let mut enc = PacketEncoder::new(codec, &EncodeOptions::default().with_bit_depth(BitDepth::Int16), 48_000, 2).unwrap(); + assert!(enc.finish().unwrap().is_empty(), "{codec:?}"); + assert_eq!(enc.padding(), 0); + } +} From 2abb1c6a8078eabf3bea5896bfb17c5805f5a651 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:03:11 -0800 Subject: [PATCH 019/322] craft-testkit: test the guards on split use groups, brace literals, escaped line breaks, deep nesting and broken links New tests cover cases the guards already handle: - wgsl_float_literals checks a literal that follows a hex literal and an operator (0x1.0p0+1e39, 0xFF+1e39, 0x1f-4e38). - std_instant reports Instant in a use group split over several lines. - '{' and '}' character literals do not end a native cfg item early. - An escaped line break in a string keeps the line numbers after it. - Use groups and cfg predicates nested 100,000 deep return without exhausting the stack. - rust_sources skips a broken symbolic link to a file or a folder. --- crates/testkit/tests/guards.rs | 71 ++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/crates/testkit/tests/guards.rs b/crates/testkit/tests/guards.rs index 5d3df778fe..169fdd5734 100644 --- a/crates/testkit/tests/guards.rs +++ b/crates/testkit/tests/guards.rs @@ -550,6 +550,57 @@ fn run() { assert_eq!(lines(&std_instant([("src/run.rs", source)])), vec![4, 8, 9]); } +#[test] +fn std_instant_reads_a_use_group_split_over_several_lines() { + let source = r#" +use std::time::{ + Instant +}; +use std::time::{ + Duration, + Instant as Clock, +}; +"#; + let findings = std_instant([("src/clock.rs", source)]); + assert_eq!(lines(&findings), vec![3, 7]); + assert_eq!(findings[0].text, "Instant"); +} + +#[test] +fn std_instant_does_not_count_brace_character_literals_as_braces() { + let source = r#" +#[cfg(unix)] +fn native() { let open = '{'; let b = b'{'; let t = std::time::Instant::now(); } +fn web() { let close = '}'; let t = std::time::Instant::now(); } +#[cfg(unix)] +fn native_two() { let close = '}'; let t = std::time::Instant::now(); } +fn web_two() { let t = std::time::Instant::now(); } +"#; + assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![4, 7]); +} + +#[test] +fn an_escaped_line_break_in_a_string_keeps_line_numbers() { + let source = + "fn web() {\n let s = \"one \\\n two\";\n let t = std::time::Instant::now();\n let q = PredefinedMenuItem::quit(None);\n}\n"; + assert_eq!(lines(&std_instant([("src/web.rs", source)])), vec![4]); + assert_eq!(lines(&predefined_quit([("src/web.rs", source)])), vec![5]); +} + +#[test] +fn deeply_nested_use_groups_and_cfg_predicates_do_not_exhaust_the_stack() { + let depth = 100_000; + let use_groups = format!("use std::time::{}Instant{};\nfn f() {{}}\n", "{".repeat(depth), "}".repeat(depth)); + assert!(std_instant([("src/deep.rs", use_groups.as_str())]).is_empty()); + assert!(predefined_quit([("src/deep.rs", use_groups.as_str())]).is_empty()); + + let cfg = format!("#[cfg({}unix{})]\nfn f() {{ let t = std::time::Instant::now(); }}\n", "not(".repeat(depth), ")".repeat(depth)); + assert_eq!(lines(&std_instant([("src/deep.rs", cfg.as_str())])), vec![2]); + + let shallow = "use std::time::{{{Instant}}};\n"; + assert_eq!(lines(&std_instant([("src/shallow.rs", shallow)])), vec![1]); +} + fn finding_paths(findings: &[Finding]) -> Vec<&str> { findings.iter().map(|f| f.path.as_str()).collect() } @@ -732,6 +783,15 @@ const F16_OVER: f16 = 0x1.0p16h; assert_eq!(findings[3].text, "0x1.0p16"); } +#[test] +fn wgsl_literals_after_a_hex_literal_and_an_operator_are_checked() { + let shader = "const A = 0x1.0p0+1e39;\nconst B = 0xFF+1e39;\nconst C = 0x1f-4e38;\nconst D = 0xAu*2.0+5e38;\nconst E = 0x1p1-0x1p+500;\n"; + let findings = wgsl_float_literals(shader); + assert_eq!(lines(&findings), vec![1, 2, 3, 4, 5]); + let texts: Vec<&str> = findings.iter().map(|f| f.text.as_str()).collect(); + assert_eq!(texts, vec!["1e39", "1e39", "4e38", "5e38", "0x1p+500"]); +} + #[test] fn wgsl_block_comment_markers_inside_line_comments_do_not_open_a_comment() { let shader = "// a /* inside a line comment\nconst BAD: f32 = 4e38;\n/* block // with a line marker */ const ALSO_BAD: f32 = 5e38;\n"; @@ -817,6 +877,17 @@ fn rust_sources_does_not_loop_on_a_symlink_cycle() { assert_eq!(file_names(&sources), vec!["lib.rs"]); } +#[cfg(unix)] +#[test] +fn rust_sources_skips_a_broken_symlink() { + let dir = ScratchDir::new("symlink_broken"); + dir.write("src/lib.rs", "pub fn lib() {}"); + std::os::unix::fs::symlink(dir.path().join("missing.rs"), dir.path().join("src").join("gone.rs")).expect("symlink file"); + std::os::unix::fs::symlink(dir.path().join("missing"), dir.path().join("src").join("gone")).expect("symlink folder"); + let sources = craft_testkit::rust_sources(dir.path()).expect("rust_sources"); + assert_eq!(file_names(&sources), vec!["lib.rs"]); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn scratch_dirs_leave_existing_folders_alone_and_clean_up_on_panic() { From da31f4949afb30e6ded41759b10e99435a56d902 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:45:24 -0800 Subject: [PATCH 020/322] craft-xtask: add the gate's step runner, slot lock and per-step report A library for the apps' cargo xtask binaries. Each app keeps its xtask binary, step list and policy, and calls the library. - runner: run_steps runs the steps in order, stops at the first failure and prints the ok, FAIL and skip summary. root takes the caller's manifest directory and returns an error instead of panicking. The test commands from nextest_or_test and doctest pass --workspace --exclude , so a test build does not rebuild the running xtask executable (storytold/craft-common-actions#185). cargo test is the default; nextest is opt-in with a fallback. A Cancel flag stops the run, and run_cancelable ends the child's process group or tree. - lock (feature): 1 to 64 slots held across processes with file locks in a caller-chosen directory. A slot count outside 1 to 64 is an error on try_acquire, acquire and holders before any file is opened. Owner files are read to at most 4096 bytes, holders lists only slots whose lock is held, and waiting can be canceled. - report (feature): schema 1 JSON with step, command, status and duration_ms per step, written with craft-atomic so a failed write keeps the previous report. It is written while the run holds its slot; a run that does not take its slot writes no report. From DesignCraft xtask/src/main.rs (8b169f8e) and LightCraft xtask/src/ci_lock.rs and ci.rs (25ffe3e5); LightCraft's two lock tests move in. DesignCraft and LightCraft are the planned consumers; no app switches here. --- Cargo.lock | 9 + Cargo.toml | 1 + README.md | 1 + crates/xtask/Cargo.toml | 25 ++ crates/xtask/README.md | 113 +++++ crates/xtask/src/lib.rs | 50 +++ crates/xtask/src/lock.rs | 333 +++++++++++++++ crates/xtask/src/report.rs | 164 ++++++++ crates/xtask/src/runner.rs | 819 +++++++++++++++++++++++++++++++++++++ 9 files changed, 1515 insertions(+) create mode 100644 crates/xtask/Cargo.toml create mode 100644 crates/xtask/README.md create mode 100644 crates/xtask/src/lib.rs create mode 100644 crates/xtask/src/lock.rs create mode 100644 crates/xtask/src/report.rs create mode 100644 crates/xtask/src/runner.rs diff --git a/Cargo.lock b/Cargo.lock index c11a134ae5..ba2b91439c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2839,6 +2839,15 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xtask" +version = "0.1.0" +dependencies = [ + "craft-atomic", + "serde_json", + "tempfile", +] + [[package]] name = "craft-y4m" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 576efca6f1..464b73532e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -36,6 +36,7 @@ kurbo = "0.13" thiserror = "2" craft-aaf = { path = "crates/aaf" } craft-atomic = { path = "crates/atomic" } +craft-xtask = { path = "crates/xtask" } craft-captions = { path = "crates/captions" } craft-cfb = { path = "crates/cfb" } craft-codepage = { path = "crates/codepage" } diff --git a/README.md b/README.md index c6e95bd4f9..34bba45518 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,7 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit - [`craft-assuan`](crates/assuan/README.md): the Assuan protocol and gpg-agent's operations (key lookup, signing a digest, decrypting a session key) over any `Read + Write` stream, with a bounded canonical S-expression reader. No sockets; everything the agent sends is capped. - [`craft-affinity`](crates/affinity/README.md): bounded reader for native Affinity documents (`.af`, `.afdesign`, `.afphoto`, `.afpub`): archive, object stream and a neutral document model with layers, artboards, vectors, text, tables, images and masks. Read only; mapping onto an app's document stays in the app. - [`craft-atomic`](crates/atomic/README.md): Crash-safe atomic file writing and replacement with same-directory staging, directory fsync, Apple `F_FULLFSYNC` fallback, transient lock backoff, and fault injection for the Craft suite. +- [`craft-xtask`](crates/xtask/README.md): a library for the apps' `cargo xtask` binaries: the gate's step runner (steps in order, stop at the first failure, the ok, FAIL and skip summary, workspace tests that exclude the running xtask package), an optional slot lock held across processes and an optional per-step JSON report. Each app keeps its step list and its own policy. Planned for DesignCraft and LightCraft. - [`craft-captions`](crates/captions/README.md): caption and subtitle files behind one neutral model (cues with exact tick times): SubRip, WebVTT, Scenarist SCC, MacCaption MCC, EBU STL and TTML / IMSC1 / DFXP readers and writers, and CEA-608 / CEA-708 byte-pair coding. Carved from diff --git a/crates/xtask/Cargo.toml b/crates/xtask/Cargo.toml new file mode 100644 index 0000000000..6b561b543b --- /dev/null +++ b/crates/xtask/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "craft-xtask" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true +description = "Library for the Craft apps' cargo xtask binaries: the gate's step runner, an optional slot lock shared across processes and a per-step JSON report" + +[lints] +workspace = true + +[features] +default = [] +# One-at-a-time (or N-at-a-time) gate runs per machine, through file locks in a caller-chosen folder. +lock = [] +# The per-step JSON report, replaced atomically. +report = ["dep:serde_json", "dep:craft-atomic"] + +[dependencies] +craft-atomic = { workspace = true, optional = true } +serde_json = { workspace = true, optional = true } + +[dev-dependencies] +tempfile = "3" diff --git a/crates/xtask/README.md b/crates/xtask/README.md new file mode 100644 index 0000000000..75228c3d66 --- /dev/null +++ b/crates/xtask/README.md @@ -0,0 +1,113 @@ +# craft-xtask + +A library for the Craft apps' `cargo xtask` binaries. Each app keeps its own `xtask` binary, command +dispatch, step list, test targets and app-only commands, and calls this crate with its own policy. +The crate is native only and is a dependency of an app's `xtask` package only. + +| Module | Feature | Contents | +|---|---|---| +| `runner` | always | `Step`, `run_steps` (steps in order, stop at the first failure, the `ok`, `FAIL` and `skip` summary), `root`, `cargo`, `run`, `run_cancelable`, `nextest_or_test`, `doctest`, `Cancel` | +| `lock` | `lock` | `LockConfig`, `try_acquire`, `acquire`, `holders`: 1 to 64 slots held across processes through file locks in a directory the app chooses | +| `report` | `report` | `write` and `to_json`: the per-step JSON report (schema 1), replaced atomically through `craft-atomic` | + +No feature is on by default. `report` adds `serde_json` and `craft-atomic`. + +## Use + +```rust,no_run +use std::path::Path; +use craft_xtask::runner::{self, RunOptions, Step, TestMode}; + +fn ci() -> Result<(), String> { + let root = runner::root(Path::new(env!("CARGO_MANIFEST_DIR")))?; + let mut steps = vec![ + Step::new("fmt", |log| { + let mut c = runner::cargo(&root); + c.args(["fmt", "--all", "--", "--check"]); + runner::run(c, log.command("cargo fmt --all -- --check")) + }), + Step::new("test", |log| { + let (c, label) = runner::nextest_or_test(&root, "xtask", TestMode::CargoTest, &["--lib", "--bins", "--tests"])?; + runner::run(c, log.command(&label)) + }), + ]; + runner::run_steps(&mut steps, &RunOptions::default())?; + Ok(()) +} +``` + +- `root` takes the app's own `CARGO_MANIFEST_DIR` and returns its parent, which must hold a + `Cargo.toml`. It returns an error instead of panicking. +- `nextest_or_test` and `doctest` build `cargo test --workspace --exclude ` (or + `cargo nextest run` with the same arguments). The exclusion keeps the test build from rebuilding the + running `xtask` executable, which Windows does not allow while it runs + ([storytold/craft-common-actions#185](https://github.com/storytold/craft-common-actions/issues/185)). + `TestMode::CargoTest` is the default and probes nothing. `TestMode::PreferNextest` runs nextest when + `cargo nextest --version` succeeds and otherwise runs `cargo test` with a note; the label names the + command that runs. +- Child processes inherit stdin, stdout and stderr. Their output is not decoded or stored. +- With `RunOptions::with_cancel`, a set `Cancel` flag stops the run before the next step, and + `run_cancelable` ends a running child with the processes it started and waits for it. On Unix the + child runs in its own process group, which `kill -s KILL` ends, so a terminal's Ctrl-C reaches only + the xtask and the app's Ctrl-C handler sets the flag. On Windows `taskkill /T /F` ends the tree. + +## Errors + +`runner::Error` is `Config` (a root without `Cargo.toml`, an invalid package name, a slot count +outside 1 to 64), `Step` (the step and the error it returned), `Canceled`, `Lock` (the lock directory +or file could not be opened or locked) or `Report` (the run passed but the report could not be +written). A report that cannot be written after a failed run is printed to stderr, and the run keeps +its `Step` error. + +## Lock + +`RunOptions::with_lock(LockConfig::new(dir, slots, owner_label))` takes one of `slots` lock files in +`dir` before the first step and releases it when `run_steps` returns. The OS releases a lock when its +process ends. A slot count of 0 or more than 64, or a poll interval (`with_poll`, 2 s by default) of zero, is an +error before any file is opened. Next to each +held lock file, an owner file holds the owner label, which waiting runs print; `holders` reads at +most 4096 bytes of each and leaves out an owner file whose slot is free, such as one a killed run left +behind. Where the lock files live, the environment variables that set them, and +whether a run uses a lock at all are the app's choice. + +## Report + +`RunOptions::with_report(path)` writes the report after the run, passed or not, and before the run +releases its lock slot. A run with a lock that does not take it (a configuration or lock error, or a +cancel while waiting) runs no step and writes no report. The report looks like this: + +```json +{ + "schema": 1, + "steps": [ + { "step": "fmt", "command": "cargo fmt --all -- --check", "status": "ok", "duration_ms": 812 }, + { "step": "test", "command": null, "status": "fail", "duration_ms": 4031 }, + { "step": "wasm", "command": null, "status": "skip", "duration_ms": null } + ] +} +``` + +`status` is `ok`, `fail`, `canceled` or `skip`. The file is staged beside `path` and renamed over it, +so a reader never sees a partial report, and a failed write leaves the previous report in place. +Machine, GPU, corpus and skip details stay in the app's own report. + +## Origin + +| Part | Source | +|---|---| +| `runner`: the step loop and summary, `root`, `cargo`, `run`, the nextest probe and fallback, doctests | DesignCraft `xtask/src/main.rs:68-82`, `:160-201`, `:204-249` at [8b169f8](https://github.com/storytold/designcraft/blob/8b169f8ee7832e60ed1ac4c9f5dd34f954d3a992/xtask/src/main.rs) | +| `lock` and its tests `one_slot_is_exclusive_until_dropped`, `more_slots_admit_more_runs` | LightCraft `xtask/src/ci_lock.rs` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/ci_lock.rs) | +| `report`: the per-step fields | LightCraft `xtask/src/ci.rs:347-414` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/ci.rs#L347-L414) | +| The root and slot-count errors, the `--exclude` of the xtask package, cancellation, the bounded owner read and the atomic report | written here | + +## Migration + +No app uses this crate yet. + +| App | Status | +|---|---| +| DesignCraft | Planned: `cmd_ci`, `root`, `cargo`, `run`, `cmd_test` and `cmd_doctest` move to `runner`, with `TestMode::PreferNextest`. The step list, `TEST_TARGETS` and the i18n report stay in the app. | +| LightCraft | Planned: `ci_lock.rs` moves to `lock`, with `LIGHTCRAFT_CI_LOCK` and `LIGHTCRAFT_CI_SLOTS` read by the app. The machine, GPU, corpus and skip report stays in the app. | + +Maintainers: the craft-libs maintainers, until a responsible maintainer or team is agreed in the +review of this crate's first pull request. diff --git a/crates/xtask/src/lib.rs b/crates/xtask/src/lib.rs new file mode 100644 index 0000000000..2ed8390e00 --- /dev/null +++ b/crates/xtask/src/lib.rs @@ -0,0 +1,50 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +//! Library for the Craft apps' `cargo xtask` binaries. +//! +//! Each app keeps its own `xtask` binary, its command dispatch, its step list and its app-only +//! commands, and calls this crate with its own policy: +//! +//! - [`runner`]: the gate's step runner. [`runner::run_steps`] runs the steps in order, stops at the +//! first failure and prints the `ok`, `FAIL` and `skip` summary. [`runner::root`], +//! [`runner::cargo`], [`runner::run`] and [`runner::nextest_or_test`] build and run the commands. +//! - `lock` (feature `lock`): a fixed number of slots, held across processes through file locks, so +//! that gate runs in several checkouts of one machine take turns. +//! - `report` (feature `report`): the per-step JSON report, replaced atomically. +//! +//! ```no_run +//! use std::path::Path; +//! use craft_xtask::runner::{self, RunOptions, Step, TestMode}; +//! +//! fn ci() -> Result<(), runner::Error> { +//! // The app's own manifest directory, never this library's. +//! let root = runner::root(Path::new(env!("CARGO_MANIFEST_DIR")))?; +//! let mut steps = vec![ +//! Step::new("fmt", |log| { +//! let mut c = runner::cargo(&root); +//! c.args(["fmt", "--all", "--", "--check"]); +//! runner::run(c, log.command("cargo fmt --all -- --check")) +//! }), +//! Step::new("test", |log| { +//! let (c, label) = runner::nextest_or_test(&root, "xtask", TestMode::CargoTest, &["--lib", "--bins", "--tests"])?; +//! runner::run(c, log.command(&label)) +//! }), +//! ]; +//! runner::run_steps(&mut steps, &RunOptions::default()).map(|_| ()) +//! } +//! ``` + +#[cfg(feature = "lock")] +pub mod lock; +#[cfg(feature = "report")] +pub mod report; +pub mod runner; + +/// Keeps the tests that start child processes apart from the tests that check whether a slot is free. +/// A child holds copies of the parent's open files, and so its file locks, until it starts its program. +#[cfg(test)] +pub(crate) fn spawn_guard() -> std::sync::MutexGuard<'static, ()> { + static GUARD: std::sync::Mutex<()> = std::sync::Mutex::new(()); + GUARD.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} diff --git a/crates/xtask/src/lock.rs b/crates/xtask/src/lock.rs new file mode 100644 index 0000000000..965b71408d --- /dev/null +++ b/crates/xtask/src/lock.rs @@ -0,0 +1,333 @@ +//! A fixed number of gate runs at a time on one machine. +//! +//! A gate run builds the workspace several times with one job per CPU, and several checkouts running +//! it at once slow each other down. [`acquire`] takes one of `slots` lock files in a directory the app +//! chooses (usually a per-user cache directory shared by every checkout) and holds it until the +//! [`Held`] guard is dropped. The operating system releases the lock when the process ends, crashed +//! or not. Runs that use the same directory and slot count share one pool; separate directories are +//! separate pools. Running without a lock is the caller's choice: it passes no [`LockConfig`]. +//! +//! Next to each held lock file, a `.owner` file holds the holder's label, which waiting runs print. + +use std::fs::{File, OpenOptions, TryLockError}; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +use crate::runner::{Cancel, Error}; + +/// The most slots a [`LockConfig`] can name. +pub const MAX_SLOTS: usize = 64; +/// The longest owner label [`holders`] reads from one owner file. +pub const MAX_OWNER_BYTES: u64 = 4096; +/// How often [`acquire`] tries again by default while every slot is held. +pub const DEFAULT_POLL: Duration = Duration::from_secs(2); +/// The longest [`acquire`] sleeps before it checks for cancellation again. +const CANCEL_CHECK: Duration = Duration::from_millis(50); + +/// Where the lock files are and how many runs may hold one at once. +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LockConfig { + /// The directory of the lock files. It is created when missing. + pub directory: PathBuf, + /// How many runs may hold a slot at once, from 1 to [`MAX_SLOTS`]. + pub slots: usize, + /// What waiting runs print about this run, for example `pid 123 in /src/app: cargo xtask ci`. + pub owner_label: String, + /// How often [`acquire`] tries again while every slot is held. + pub poll: Duration, +} + +impl LockConfig { + /// `slots` slots in `directory`, labeled `owner_label`, polled every [`DEFAULT_POLL`]. + pub fn new(directory: impl Into, slots: usize, owner_label: impl Into) -> Self { + Self { directory: directory.into(), slots, owner_label: owner_label.into(), poll: DEFAULT_POLL } + } + + /// Sets how often [`acquire`] tries again. + pub fn with_poll(mut self, poll: Duration) -> Self { + self.poll = poll; + self + } + + fn check(&self) -> Result<(), Error> { + if !(1..=MAX_SLOTS).contains(&self.slots) { + return Err(Error::Config(format!("lock: {} slots: the slot count must be from 1 to {MAX_SLOTS}", self.slots))); + } + if self.poll.is_zero() { + return Err(Error::Config("lock: the poll interval must be longer than zero".to_owned())); + } + Ok(()) + } +} + +/// A held slot. Dropping it releases the slot and removes its owner file. +#[derive(Debug)] +pub struct Held { + _file: File, + owner: PathBuf, +} + +impl Drop for Held { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.owner); + } +} + +fn slot_path(dir: &Path, slot: usize) -> PathBuf { + if slot == 0 { dir.join("ci.lock") } else { dir.join(format!("ci-{}.lock", slot + 1)) } +} + +fn owner_path(lock: &Path) -> PathBuf { + lock.with_extension("lock.owner") +} + +/// Takes the first free slot, or returns `None` when every slot is held. +pub fn try_acquire(config: &LockConfig) -> Result, Error> { + config.check()?; + let dir = &config.directory; + std::fs::create_dir_all(dir).map_err(|e| Error::Lock(format!("{}: {e}", dir.display())))?; + for slot in 0..config.slots { + let path = slot_path(dir, slot); + let file = + OpenOptions::new().create(true).truncate(false).write(true).open(&path).map_err(|e| Error::Lock(format!("{}: {e}", path.display())))?; + match file.try_lock() { + Ok(()) => return Ok(Some(Held { _file: file, owner: record_owner(&path, &config.owner_label) })), + Err(TryLockError::WouldBlock) => continue, + Err(TryLockError::Error(e)) => return Err(Error::Lock(format!("{}: {e}", path.display()))), + } + } + Ok(None) +} + +/// Writes the owner file of a slot this run holds. The owner is kept in a separate file because a +/// lock on Windows is mandatory, so other runs could not read the lock file itself. +fn record_owner(lock: &Path, label: &str) -> PathBuf { + let owner_file = owner_path(lock); + // A new file: an entry left under the name (a link planted in a shared lock directory) is removed, + // never written through. + let removed = std::fs::remove_file(&owner_file); + let written = OpenOptions::new().write(true).create_new(true).open(&owner_file).and_then(|mut f| f.write_all(label.as_bytes())); + if let (Err(e), Err(w)) = (&removed, &written) + && e.kind() != std::io::ErrorKind::NotFound + { + eprintln!("lock: could not record the owner in {} ({e}; {w}): waiting runs may show a stale owner", owner_file.display()); + } + owner_file +} + +/// The owner labels of the held slots, as their holders wrote them, each cut to [`MAX_OWNER_BYTES`]. +/// +/// A slot whose lock file is missing or free is left out, also when a run that ended without dropping +/// its [`Held`] guard left its owner file behind. +pub fn holders(config: &LockConfig) -> Result, Error> { + config.check()?; + Ok((0..config.slots) + .map(|slot| slot_path(&config.directory, slot)) + .filter(|lock| is_held(lock)) + .filter_map(|lock| read_owner(&owner_path(&lock))) + .collect()) +} + +/// Whether a run holds the slot whose lock file is `lock`. The file is opened read-only and never +/// created; a free slot is locked shared for a moment and released when the file closes. +fn is_held(lock: &Path) -> bool { + match File::open(lock) { + Ok(file) => matches!(file.try_lock_shared(), Err(TryLockError::WouldBlock)), + Err(_) => false, + } +} + +fn read_owner(path: &Path) -> Option { + let mut bytes = Vec::new(); + File::open(path).ok()?.take(MAX_OWNER_BYTES).read_to_end(&mut bytes).ok()?; + let text = String::from_utf8_lossy(&bytes).trim().to_owned(); + (!text.is_empty()).then_some(text) +} + +/// Waits for a slot, printing the holders once while it waits. +/// +/// Returns [`Error::Canceled`] when `cancel` is set while waiting, and a configuration or lock error +/// before any wait. +pub fn acquire(config: &LockConfig, cancel: Option<&Cancel>) -> Result { + acquire_with(config, cancel, || { + eprintln!("=== lock: waiting for another run to finish ({} at a time) ===", config.slots); + for h in holders(config).unwrap_or_default() { + eprintln!(" running: {h}"); + } + }) +} + +fn acquire_with(config: &LockConfig, cancel: Option<&Cancel>, on_wait: impl FnOnce()) -> Result { + if let Some(held) = try_acquire(config)? { + return Ok(held); + } + let waiting = Instant::now(); + on_wait(); + loop { + if !pause(config.poll, cancel) { + return Err(Error::Canceled { step: None }); + } + if let Some(held) = try_acquire(config)? { + eprintln!("=== lock: waited {:.0} s for a slot ===", waiting.elapsed().as_secs_f64()); + return Ok(held); + } + } +} + +/// Sleeps for `poll`, checking `cancel` every [`CANCEL_CHECK`]. Returns `false` when canceled. A +/// `poll` too long for the clock to represent waits until canceled. +fn pause(poll: Duration, cancel: Option<&Cancel>) -> bool { + let until = Instant::now().checked_add(poll); + loop { + if cancel.is_some_and(Cancel::is_canceled) { + return false; + } + let left = match until { + Some(until) => until.saturating_duration_since(Instant::now()), + None => CANCEL_CHECK, + }; + if left.is_zero() { + return true; + } + std::thread::sleep(left.min(CANCEL_CHECK)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::runner::{RunOptions, Step, run_steps_to}; + use std::sync::mpsc; + + fn config(dir: &Path, slots: usize, owner: &str) -> LockConfig { + LockConfig::new(dir, slots, owner).with_poll(Duration::from_millis(1)) + } + + #[test] + fn one_slot_is_exclusive_until_dropped() { + let _guard = crate::spawn_guard(); + let dir = tempfile::tempdir().expect("temporary directory"); + let first = try_acquire(&config(dir.path(), 1, "first")).unwrap().expect("free slot"); + assert!(try_acquire(&config(dir.path(), 1, "second")).unwrap().is_none()); + assert_eq!(holders(&config(dir.path(), 1, "")).unwrap(), ["first"]); + drop(first); + assert!(holders(&config(dir.path(), 1, "")).unwrap().is_empty()); + assert!(try_acquire(&config(dir.path(), 1, "third")).unwrap().is_some()); + } + + #[test] + fn more_slots_admit_more_runs() { + let _guard = crate::spawn_guard(); + let dir = tempfile::tempdir().expect("temporary directory"); + let a = try_acquire(&config(dir.path(), 2, "a")).unwrap(); + let b = try_acquire(&config(dir.path(), 2, "b")).unwrap(); + assert!(a.is_some() && b.is_some()); + assert!(try_acquire(&config(dir.path(), 2, "c")).unwrap().is_none()); + assert_eq!(holders(&config(dir.path(), 2, "")).unwrap(), ["a", "b"]); + } + + #[test] + fn slot_count_is_bounded() { + let _guard = crate::spawn_guard(); + let dir = tempfile::tempdir().expect("temporary directory"); + for slots in [0, MAX_SLOTS + 1, usize::MAX] { + let c = config(dir.path(), slots, "x"); + assert!(matches!(try_acquire(&c), Err(Error::Config(_))), "{slots}"); + assert!(matches!(holders(&c), Err(Error::Config(_))), "{slots}"); + assert!(matches!(acquire(&c, None), Err(Error::Config(_))), "{slots}"); + } + assert!(matches!(try_acquire(&config(dir.path(), 1, "x").with_poll(Duration::ZERO)), Err(Error::Config(_)))); + // Nothing was created for the rejected configurations. + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0); + + let one = try_acquire(&config(dir.path(), 1, "one")).unwrap(); + assert!(one.is_some()); + let all: Vec = (0..MAX_SLOTS - 1).filter_map(|_| try_acquire(&config(dir.path(), MAX_SLOTS, "n")).unwrap()).collect(); + assert_eq!(all.len(), MAX_SLOTS - 1); + assert!(try_acquire(&config(dir.path(), MAX_SLOTS, "full")).unwrap().is_none()); + } + + #[test] + fn owner_labels_are_read_within_the_limit() { + let _guard = crate::spawn_guard(); + let dir = tempfile::tempdir().expect("temporary directory"); + let c = config(dir.path(), 1, ""); + let _held = try_acquire(&c).unwrap().expect("free slot"); + std::fs::write(owner_path(&slot_path(dir.path(), 0)), vec![b'x'; 3 * MAX_OWNER_BYTES as usize]).unwrap(); + assert_eq!(holders(&c).unwrap(), ["x".repeat(MAX_OWNER_BYTES as usize)]); + } + + #[test] + fn owner_files_of_free_slots_are_not_holders() { + let _guard = crate::spawn_guard(); + let dir = tempfile::tempdir().expect("temporary directory"); + let c = config(dir.path(), 2, ""); + // The first slot: a run that ended without dropping its guard left its lock and owner files. + std::fs::write(slot_path(dir.path(), 0), b"").unwrap(); + std::fs::write(owner_path(&slot_path(dir.path(), 0)), b"crashed").unwrap(); + // The second slot: an owner file with no lock file. + std::fs::write(owner_path(&slot_path(dir.path(), 1)), b"orphan").unwrap(); + assert!(holders(&c).unwrap().is_empty()); + + // A live holder of the first slot is listed, and the free second slot still is not. + let _held = try_acquire(&config(dir.path(), 2, "live")).unwrap().expect("free slot"); + assert_eq!(holders(&c).unwrap(), ["live"]); + } + + #[test] + fn lock_wait_cancels_and_releases() { + let _guard = crate::spawn_guard(); + let dir = tempfile::tempdir().expect("temporary directory"); + let holder = try_acquire(&config(dir.path(), 1, "holder")).unwrap().expect("free slot"); + + // A waiter stops waiting when canceled, also with a poll interval the clock cannot add. + for poll in [Duration::from_millis(1), Duration::MAX] { + let cancel = Cancel::new(); + let (waiting, waited) = mpsc::channel(); + let waiter = { + let (c, cancel) = (config(dir.path(), 1, "waiter").with_poll(poll), cancel.clone()); + std::thread::spawn(move || acquire_with(&c, Some(&cancel), || waiting.send(()).unwrap()).map(drop)) + }; + waited.recv().unwrap(); + cancel.cancel(); + assert_eq!(waiter.join().unwrap(), Err(Error::Canceled { step: None }), "{poll:?}"); + } + + // A waiter gets the slot once the holder drops it. + let (waiting, waited) = mpsc::channel(); + let waiter = { + let c = config(dir.path(), 1, "next"); + std::thread::spawn(move || acquire_with(&c, None, || waiting.send(()).unwrap()).map(drop)) + }; + waited.recv().unwrap(); + drop(holder); + assert_eq!(waiter.join().unwrap(), Ok(())); + + // A run that fails or is canceled releases its slot when it returns. + let c = config(dir.path(), 1, "run"); + let mut failing = vec![Step::new("test", |_| Err("failed".to_owned()))]; + let result = run_steps_to(&mut failing, &RunOptions::default().with_lock(c.clone()), &mut Vec::new(), &mut Vec::new()); + assert!(matches!(result, Err(Error::Step { .. }))); + assert!(try_acquire(&c).unwrap().is_some()); + + let cancel = Cancel::new(); + cancel.cancel(); + let mut canceled = vec![Step::new("test", |_| Ok(()))]; + let options = RunOptions::default().with_lock(c.clone()).with_cancel(cancel); + let result = run_steps_to(&mut canceled, &options, &mut Vec::new(), &mut Vec::new()); + assert!(matches!(result, Err(Error::Canceled { .. }))); + assert!(try_acquire(&c).unwrap().is_some()); + + // A run waiting for a held slot ends when canceled, without running a step. + let held = try_acquire(&c).unwrap().expect("free slot"); + let cancel = Cancel::new(); + cancel.cancel(); + let mut never = vec![Step::new("test", |_| Err("ran".to_owned()))]; + let options = RunOptions::default().with_lock(c.clone()).with_cancel(cancel); + let result = run_steps_to(&mut never, &options, &mut Vec::new(), &mut Vec::new()); + assert_eq!(result, Err(Error::Canceled { step: None })); + drop(held); + } +} diff --git a/crates/xtask/src/report.rs b/crates/xtask/src/report.rs new file mode 100644 index 0000000000..f876d06f99 --- /dev/null +++ b/crates/xtask/src/report.rs @@ -0,0 +1,164 @@ +//! The per-step JSON report of a gate run. +//! +//! Schema 1 holds the schema number and one object per step, in run order: +//! +//! ```json +//! { +//! "schema": 1, +//! "steps": [ +//! { "step": "fmt", "command": "cargo fmt --all -- --check", "status": "ok", "duration_ms": 812 }, +//! { "step": "test", "command": null, "status": "fail", "duration_ms": 4031 }, +//! { "step": "wasm", "command": null, "status": "skip", "duration_ms": null } +//! ] +//! } +//! ``` +//! +//! `status` is `ok`, `fail`, `canceled` or `skip`. `command` is `null` when the step recorded none, +//! and `duration_ms` is `null` for a step that did not start. Machine, GPU and other app-specific +//! details stay in the app's own report. +//! +//! The file is replaced atomically with `craft_atomic`: a reader sees the previous complete report or +//! the new one, never a partial file, and a failed write leaves the previous report in place. + +use std::io; +use std::path::Path; + +use craft_atomic::{AtomicFs, RealFs, RenameRetry}; +use serde_json::{Value, json}; + +use crate::runner::StepRecord; + +/// The schema number the report carries. +pub const SCHEMA: u64 = 1; + +/// The report of `records` as JSON. +pub fn to_json(records: &[StepRecord]) -> Value { + let steps: Vec = records + .iter() + .map(|r| { + json!({ + "step": r.step, + "command": r.command, + "status": r.status.as_str(), + "duration_ms": r.duration.map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX)), + }) + }) + .collect(); + json!({ "schema": SCHEMA, "steps": steps }) +} + +/// Writes the report of `records` to `path`, replacing any earlier report atomically. +pub fn write(path: &Path, records: &[StepRecord]) -> io::Result<()> { + write_custom(&RealFs, RenameRetry::platform(), path, records) +} + +fn write_custom(fs: &dyn AtomicFs, retry: RenameRetry, path: &Path, records: &[StepRecord]) -> io::Result<()> { + let mut bytes = serde_json::to_vec_pretty(&to_json(records)).map_err(io::Error::other)?; + bytes.push(b'\n'); + craft_atomic::atomic_write_custom(fs, retry, path, &bytes) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::runner::{Error, RunOptions, Step, run_steps_to}; + use craft_atomic::NewFilePermissions; + use std::fs::{File, Permissions}; + + /// The real file system with every rename failing. + struct FailingRename; + + impl AtomicFs for FailingRename { + fn create_new(&self, path: &Path, permissions: NewFilePermissions) -> io::Result { + RealFs.create_new(path, permissions) + } + fn sync(&self, file: &File) -> io::Result<()> { + RealFs.sync(file) + } + fn rename(&self, _from: &Path, _to: &Path) -> io::Result<()> { + Err(io::Error::other("injected rename failure")) + } + fn hard_link(&self, from: &Path, to: &Path) -> io::Result<()> { + RealFs.hard_link(from, to) + } + fn remove(&self, path: &Path) -> io::Result<()> { + RealFs.remove(path) + } + fn sync_dir(&self, dir: &Path) -> io::Result<()> { + RealFs.sync_dir(dir) + } + fn set_permissions(&self, file: &File, perms: Permissions) -> io::Result<()> { + RealFs.set_permissions(file, perms) + } + } + + fn keys(v: &Value) -> Vec<&str> { + let mut k: Vec<&str> = v.as_object().expect("an object").keys().map(String::as_str).collect(); + k.sort_unstable(); + k + } + + #[test] + fn report_shape_and_atomic_replacement() { + let dir = tempfile::tempdir().expect("temporary directory"); + let path = dir.path().join("ci.json"); + let mut steps = vec![ + Step::new("fmt", |log| { + log.command("cargo fmt --all -- --check"); + Ok(()) + }), + Step::new("test", |_| Err("exited with 101".to_owned())), + Step::new("wasm", |_| Ok(())).with_command("cargo check --target wasm32-unknown-unknown"), + ]; + let options = RunOptions::default().with_report(&path); + let result = run_steps_to(&mut steps, &options, &mut Vec::new(), &mut Vec::new()); + assert!(matches!(result, Err(Error::Step { .. }))); + + let written = std::fs::read(&path).unwrap(); + let report: Value = serde_json::from_slice(&written).unwrap(); + assert_eq!(keys(&report), ["schema", "steps"]); + assert_eq!(report["schema"], 1); + let rows = report["steps"].as_array().unwrap(); + assert_eq!(rows.len(), 3); + for row in rows { + assert_eq!(keys(row), ["command", "duration_ms", "status", "step"]); + } + assert_eq!(rows[0]["step"], "fmt"); + assert_eq!(rows[0]["command"], "cargo fmt --all -- --check"); + assert_eq!(rows[0]["status"], "ok"); + assert!(rows[0]["duration_ms"].is_u64()); + assert_eq!(rows[1]["command"], Value::Null); + assert_eq!(rows[1]["status"], "fail"); + assert!(rows[1]["duration_ms"].is_u64()); + assert_eq!(rows[2]["status"], "skip"); + assert_eq!(rows[2]["command"], "cargo check --target wasm32-unknown-unknown"); + assert_eq!(rows[2]["duration_ms"], Value::Null); + + // A failed replacement keeps the previous complete report and returns the error. + let records = vec![StepRecord { step: "fmt".into(), command: None, status: crate::runner::Status::Ok, duration: None }]; + let no_retry = RenameRetry { attempts: 0, first_delay_ms: 0 }; + assert!(write_custom(&FailingRename, no_retry, &path, &records).is_err()); + assert_eq!(std::fs::read(&path).unwrap(), written); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1, "a staging file was left behind"); + } + + #[test] + fn report_errors_never_pass_a_failed_run() { + let dir = tempfile::tempdir().expect("temporary directory"); + let unwritable = dir.path().join("missing").join("ci.json"); + let options = RunOptions::default().with_report(&unwritable); + + let mut passing = vec![Step::new("fmt", |_| Ok(()))]; + let mut out = Vec::new(); + let result = run_steps_to(&mut passing, &options, &mut out, &mut Vec::new()); + assert!(matches!(result, Err(Error::Report(_))), "{result:?}"); + let out = String::from_utf8_lossy(&out); + assert!(out.starts_with("\nCI summary:\n FAIL report: ") && out.ends_with("\n ok fmt\n") && !out.contains("passed"), "{out}"); + + let mut failing = vec![Step::new("fmt", |_| Err("bad".to_owned()))]; + let mut err = Vec::new(); + let result = run_steps_to(&mut failing, &options, &mut Vec::new(), &mut err); + assert_eq!(result, Err(Error::Step { step: "fmt".into(), cause: "bad".into() })); + assert!(String::from_utf8_lossy(&err).contains("report: ")); + } +} diff --git a/crates/xtask/src/runner.rs b/crates/xtask/src/runner.rs new file mode 100644 index 0000000000..459e9e8869 --- /dev/null +++ b/crates/xtask/src/runner.rs @@ -0,0 +1,819 @@ +//! The gate's step runner. +//! +//! An app builds its step list (`fmt`, `clippy`, `test` and its own checks) and passes it to +//! [`run_steps`], which runs the steps in order, stops at the first failure and prints a summary: +//! +//! ```text +//! CI summary: +//! ok fmt +//! FAIL clippy: cargo clippy --workspace --all-targets -- -D warnings: exited with exit status: 101 +//! skip test +//! ``` +//! +//! The workspace root comes from the caller ([`root`] takes the app's own xtask manifest directory), +//! and the test commands that [`nextest_or_test`] and [`doctest`] build exclude the running xtask +//! package, so that a test build never has to replace the `xtask` executable that is running it. +//! Child processes inherit stdout and stderr; their output is passed through as bytes and never +//! decoded or stored. + +use std::ffi::{OsStr, OsString}; +use std::fmt; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, ExitStatus, Stdio}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +/// How often [`run_cancelable`] checks a running child for exit or cancellation. +const CHILD_POLL: Duration = Duration::from_millis(50); + +/// Why a run did not pass. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Error { + /// The caller passed a configuration this crate cannot use (a root without `Cargo.toml`, an + /// invalid package name, a slot count outside 1 to 64). + Config(String), + /// A step returned an error. Later steps did not run. + Step { + /// The step's name. + step: String, + /// The error the step returned. + cause: String, + }, + /// The run was canceled, at the named step or before the first one. + Canceled { + /// The step that was canceled, or `None` when the run was canceled while waiting for a lock. + step: Option, + }, + /// The lock could not be set up or taken. + Lock(String), + /// The gate passed but its report could not be written. + Report(String), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Config(m) => f.write_str(m), + Error::Step { step, cause } => write!(f, "step `{step}` failed: {cause}"), + Error::Canceled { step: Some(step) } => write!(f, "canceled at step `{step}`"), + Error::Canceled { step: None } => f.write_str("canceled before the first step"), + Error::Lock(m) => write!(f, "lock: {m}"), + Error::Report(m) => write!(f, "report: {m}"), + } + } +} + +impl std::error::Error for Error {} + +impl From for String { + fn from(e: Error) -> Self { + e.to_string() + } +} + +/// A cancellation flag shared between the run and whoever stops it (a Ctrl-C handler, a test). +#[derive(Debug, Clone, Default)] +pub struct Cancel(Arc); + +impl Cancel { + /// A flag that is not set. + pub fn new() -> Self { + Self::default() + } + + /// Sets the flag. Every clone sees it. + pub fn cancel(&self) { + self.0.store(true, Ordering::SeqCst); + } + + /// Whether [`Cancel::cancel`] has been called on this flag or a clone of it. + pub fn is_canceled(&self) -> bool { + self.0.load(Ordering::SeqCst) + } +} + +/// What a running step records about itself. +#[derive(Debug, Default)] +pub struct StepLog { + command: Option, +} + +impl StepLog { + /// Records the command the step runs, for the report, and returns `label` so that it can be + /// passed on to [`run`]. + pub fn command<'s>(&mut self, label: &'s str) -> &'s str { + self.command = Some(label.to_owned()); + label + } +} + +/// A step's body. It returns the error to print in the summary. +pub type StepFn<'a> = Box Result<(), String> + 'a>; + +/// One step of a gate run. +pub struct Step<'a> { + /// The name shown in the heading, the summary and the report. + pub name: String, + /// The command shown in the report when the step does not record one itself. + pub command: Option, + /// The step's body. + pub run: StepFn<'a>, +} + +impl<'a> Step<'a> { + /// A step named `name` that runs `run`. + pub fn new(name: impl Into, run: impl FnMut(&mut StepLog) -> Result<(), String> + 'a) -> Self { + Self { name: name.into(), command: None, run: Box::new(run) } + } + + /// Sets the command shown in the report until the step records another one. + pub fn with_command(mut self, label: impl Into) -> Self { + self.command = Some(label.into()); + self + } +} + +impl fmt::Debug for Step<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Step").field("name", &self.name).field("command", &self.command).finish_non_exhaustive() + } +} + +/// How a step ended. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Status { + /// The step passed. + Ok, + /// The step returned an error. + Fail, + /// The run was canceled before or while this step ran. + Canceled, + /// The step did not run because an earlier step failed or was canceled. + Skip, +} + +impl Status { + /// The status as the summary and the report write it: `ok`, `fail`, `canceled` or `skip`. + pub fn as_str(self) -> &'static str { + match self { + Status::Ok => "ok", + Status::Fail => "fail", + Status::Canceled => "canceled", + Status::Skip => "skip", + } + } +} + +/// The result of one step. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StepRecord { + /// The step's name. + pub step: String, + /// The command the step recorded, if any. + pub command: Option, + /// How the step ended. + pub status: Status, + /// How long the step ran; `None` for a step that did not start. + pub duration: Option, +} + +/// Options for [`run_steps`]. +#[non_exhaustive] +#[derive(Debug, Clone)] +pub struct RunOptions { + /// The word in each step heading (`=== ci: fmt ===`) and, in capitals, the summary (`CI summary:`). + pub title: String, + /// Stops the run when set: the current child is ended and no later step starts. + pub cancel: Option, + /// A slot to hold for the whole run; `None` runs without a lock. + #[cfg(feature = "lock")] + pub lock: Option, + /// Where to write the per-step JSON report; `None` writes none. + #[cfg(feature = "report")] + pub report: Option, +} + +impl Default for RunOptions { + fn default() -> Self { + Self { + title: "ci".to_owned(), + cancel: None, + #[cfg(feature = "lock")] + lock: None, + #[cfg(feature = "report")] + report: None, + } + } +} + +impl RunOptions { + /// Sets the heading and summary word. + pub fn with_title(mut self, title: impl Into) -> Self { + self.title = title.into(); + self + } + + /// Sets the cancellation flag. + pub fn with_cancel(mut self, cancel: Cancel) -> Self { + self.cancel = Some(cancel); + self + } + + /// Holds a slot of `lock` for the whole run. + #[cfg(feature = "lock")] + pub fn with_lock(mut self, lock: crate::lock::LockConfig) -> Self { + self.lock = Some(lock); + self + } + + /// Writes the per-step JSON report to `path` after the run, whether it passed or not. A run that + /// does not take its lock writes no report. + #[cfg(feature = "report")] + pub fn with_report(mut self, path: impl Into) -> Self { + self.report = Some(path.into()); + self + } + + fn is_canceled(&self) -> bool { + self.cancel.as_ref().is_some_and(Cancel::is_canceled) + } +} + +/// Runs `steps` in order and stops at the first failure. +/// +/// Each step's heading goes to stderr and the summary to stdout. With a lock configured, a slot is +/// taken before the first step and released when this function returns, whatever the outcome. With a +/// report configured, it is written after the run, passed or not, while the slot is still held. When +/// the lock is not taken (a configuration or lock error, or a cancel while waiting), no step runs and +/// no report is written. A report that cannot be written turns a passed run into [`Error::Report`]; a +/// failed run keeps its own error and the report error is printed. An empty list passes. +pub fn run_steps(steps: &mut [Step<'_>], options: &RunOptions) -> Result, Error> { + run_steps_to(steps, options, &mut io::stdout(), &mut io::stderr()) +} + +/// [`run_steps`] with the summary written to `out` and the headings to `err`. +pub fn run_steps_to(steps: &mut [Step<'_>], options: &RunOptions, out: &mut dyn Write, err: &mut dyn Write) -> Result, Error> { + // The slot stays held until the report is written, so a later run's report replaces this one. + // A run that did not take the lock writes no report, so it never replaces the report of a run + // that holds the slot. + let held = take_lock(options); + let (records, result) = match &held { + Ok(_) => { + let (records, result) = execute(steps, options, err); + let result = finish_report(&records, result, options, err); + (records, result) + } + Err(e) => (not_started(steps, Status::Skip), Err(e.clone())), + }; + print_summary(&records, &result, options, out); + drop(held); + result.map(|()| records) +} + +#[cfg(feature = "lock")] +fn take_lock(options: &RunOptions) -> Result, Error> { + options.lock.as_ref().map(|config| crate::lock::acquire(config, options.cancel.as_ref())).transpose() +} + +#[cfg(not(feature = "lock"))] +fn take_lock(_options: &RunOptions) -> Result<(), Error> { + Ok(()) +} + +#[cfg(feature = "report")] +fn finish_report(records: &[StepRecord], result: Result<(), Error>, options: &RunOptions, err: &mut dyn Write) -> Result<(), Error> { + let Some(path) = &options.report else { + return result; + }; + match (crate::report::write(path, records), result) { + (Ok(()), result) => result, + (Err(e), Ok(())) => Err(Error::Report(format!("{}: {e}", path.display()))), + (Err(e), Err(gate)) => { + let _ = writeln!(err, "report: {}: {e}", path.display()); + Err(gate) + } + } +} + +#[cfg(not(feature = "report"))] +fn finish_report(_records: &[StepRecord], result: Result<(), Error>, _options: &RunOptions, _err: &mut dyn Write) -> Result<(), Error> { + result +} + +fn not_started(steps: &[Step<'_>], status: Status) -> Vec { + steps.iter().map(|s| StepRecord { step: s.name.clone(), command: s.command.clone(), status, duration: None }).collect() +} + +fn execute(steps: &mut [Step<'_>], options: &RunOptions, err: &mut dyn Write) -> (Vec, Result<(), Error>) { + let mut records = Vec::with_capacity(steps.len()); + let mut result = Ok(()); + for step in steps.iter_mut() { + if result.is_err() { + records.push(StepRecord { step: step.name.clone(), command: step.command.clone(), status: Status::Skip, duration: None }); + continue; + } + if options.is_canceled() { + records.push(StepRecord { step: step.name.clone(), command: step.command.clone(), status: Status::Canceled, duration: None }); + result = Err(Error::Canceled { step: Some(step.name.clone()) }); + continue; + } + let (record, outcome) = run_one(step, options, err); + records.push(record); + result = outcome; + } + (records, result) +} + +fn run_one(step: &mut Step<'_>, options: &RunOptions, err: &mut dyn Write) -> (StepRecord, Result<(), Error>) { + let _ = writeln!(err, "\n=== {}: {} ===", options.title, step.name); + let mut log = StepLog { command: step.command.clone() }; + let started = Instant::now(); + let outcome = (step.run)(&mut log); + let duration = Some(started.elapsed()); + let (status, result) = match outcome { + _ if options.is_canceled() => (Status::Canceled, Err(Error::Canceled { step: Some(step.name.clone()) })), + Ok(()) => (Status::Ok, Ok(())), + Err(cause) => (Status::Fail, Err(Error::Step { step: step.name.clone(), cause })), + }; + (StepRecord { step: step.name.clone(), command: log.command, status, duration }, result) +} + +fn print_summary(records: &[StepRecord], result: &Result<(), Error>, options: &RunOptions, out: &mut dyn Write) { + let title = options.title.to_uppercase(); + if result.is_ok() { + let names: Vec<&str> = records.iter().map(|r| r.step.as_str()).collect(); + let _ = if names.is_empty() { + writeln!(out, "\n{title} summary: all 0 steps passed") + } else { + writeln!(out, "\n{title} summary: all {} steps passed ({})", names.len(), names.join(", ")) + }; + return; + } + let _ = writeln!(out, "\n{title} summary:"); + if let Err(e @ (Error::Config(_) | Error::Lock(_) | Error::Report(_) | Error::Canceled { step: None })) = result { + let _ = writeln!(out, " FAIL {e}"); + } + for r in records { + let _ = match (r.status, result) { + (Status::Ok, _) => writeln!(out, " ok {}", r.step), + (Status::Fail, Err(Error::Step { cause, .. })) => writeln!(out, " FAIL {}: {cause}", r.step), + (Status::Fail, _) => writeln!(out, " FAIL {}", r.step), + (Status::Canceled, _) => writeln!(out, " cancel {}", r.step), + (Status::Skip, _) => writeln!(out, " skip {}", r.step), + }; + } +} + +/// The workspace root of an app: the parent of its xtask manifest directory. +/// +/// Pass the app's own `Path::new(env!("CARGO_MANIFEST_DIR"))`. The parent must hold a +/// `Cargo.toml`; a layout where it does not passes its root to [`cargo`] directly instead. +pub fn root(xtask_manifest_dir: &Path) -> Result { + let parent = xtask_manifest_dir + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .ok_or_else(|| Error::Config(format!("{}: the xtask manifest directory has no parent directory", xtask_manifest_dir.display())))?; + if !parent.join("Cargo.toml").is_file() { + return Err(Error::Config(format!("{}: no Cargo.toml here, so this is not the workspace root", parent.display()))); + } + Ok(parent.to_path_buf()) +} + +/// `cargo` (the `CARGO` the xtask was started with, or `cargo` from `PATH`) with `root` as its +/// working directory. +pub fn cargo(root: &Path) -> Command { + let program = std::env::var_os("CARGO").filter(|p| !p.is_empty()).unwrap_or_else(|| OsString::from("cargo")); + let mut c = Command::new(program); + c.current_dir(root); + c +} + +/// Prints `$ label` to stderr and runs `cmd` with inherited stdin, stdout and stderr. +/// +/// Returns an error when the command cannot be started or exits with a failure status. +pub fn run(mut cmd: Command, label: &str) -> Result<(), String> { + eprintln!("$ {label}"); + let status = cmd.status().map_err(|e| spawn_error(label, &e))?; + exit_result(label, status) +} + +/// [`run`] that ends the child, with the processes it started, and waits for it to exit when +/// `cancel` is set while it runs. +/// +/// On Unix the child runs in a process group of its own, so a terminal's Ctrl-C reaches the xtask +/// and not the child: the app's Ctrl-C handler sets `cancel`, and this function ends the group with +/// `kill -s KILL`. On Windows it ends the process tree with `taskkill /T /F`. When that tool cannot +/// be run, only the child itself is ended. +pub fn run_cancelable(mut cmd: Command, label: &str, cancel: &Cancel) -> Result<(), String> { + eprintln!("$ {label}"); + #[cfg(unix)] + std::os::unix::process::CommandExt::process_group(&mut cmd, 0); + let mut child = cmd.spawn().map_err(|e| spawn_error(label, &e))?; + loop { + if let Some(status) = child.try_wait().map_err(|e| format!("{label}: {e}"))? { + return exit_result(label, status); + } + if cancel.is_canceled() { + let killed = end_tree(&mut child); + let reaped = child.wait(); + return match (killed, reaped) { + (_, Ok(_)) => Err(format!("{label}: canceled")), + (Err(k), Err(w)) => Err(format!("{label}: canceled, but the child could not be ended ({k}; {w})")), + (Ok(()), Err(w)) => Err(format!("{label}: canceled, but waiting for the child failed ({w})")), + }; + } + std::thread::sleep(CHILD_POLL); + } +} + +/// Ends `child` and every process in its group (Unix) or tree (Windows), falling back to the child +/// alone when the system tool fails. +fn end_tree(child: &mut Child) -> io::Result<()> { + let id = child.id().to_string(); + #[cfg(unix)] + let tree = Command::new("kill").args(["-s", "KILL", "--", &format!("-{id}")]).stdout(Stdio::null()).stderr(Stdio::null()).status(); + #[cfg(windows)] + let tree = Command::new("taskkill").args(["/T", "/F", "/PID", &id]).stdout(Stdio::null()).stderr(Stdio::null()).status(); + #[cfg(not(any(unix, windows)))] + let tree: io::Result = Err(io::Error::new(io::ErrorKind::Unsupported, id)); + match tree { + Ok(status) if status.success() => Ok(()), + _ => child.kill(), + } +} + +fn spawn_error(label: &str, e: &io::Error) -> String { + format!("{label}: failed to spawn: {e}") +} + +fn exit_result(label: &str, status: ExitStatus) -> Result<(), String> { + if status.success() { Ok(()) } else { Err(format!("{label}: exited with {status}")) } +} + +/// Which test runner [`nextest_or_test`] uses. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum TestMode { + /// `cargo test`. Nothing is probed. + #[default] + CargoTest, + /// `cargo nextest run` when `cargo nextest --version` succeeds, otherwise `cargo test` with a note. + PreferNextest, +} + +/// The workspace test command and its label, with the running xtask package excluded. +/// +/// The command is `cargo test --workspace --exclude ` or, with +/// [`TestMode::PreferNextest`] and nextest installed, `cargo nextest run --workspace --exclude +/// `. `args` holds the app's targets, features and filters. The label names +/// the command that will run, so a fallback shows as `cargo test`. +pub fn nextest_or_test(root: &Path, xtask_package: &str, mode: TestMode, args: &[impl AsRef]) -> Result<(Command, String), Error> { + select_test(cargo(root), xtask_package, mode, args, || nextest_available(cargo(root))) +} + +/// [`nextest_or_test`] with the nextest probe passed in. +fn select_test( + cargo: Command, + xtask_package: &str, + mode: TestMode, + args: &[impl AsRef], + probe: impl FnOnce() -> bool, +) -> Result<(Command, String), Error> { + check_package(xtask_package)?; + let nextest = match mode { + TestMode::CargoTest => false, + TestMode::PreferNextest => { + let found = probe(); + if !found { + eprintln!("note: cargo-nextest is not installed, running cargo test (cargo install cargo-nextest --locked)"); + } + found + } + }; + Ok(test_command(cargo, xtask_package, if nextest { &["nextest", "run"] } else { &["test"] }, args)) +} + +/// The workspace doctest command and its label: `cargo test --workspace --exclude +/// --doc `. nextest does not run doctests. +pub fn doctest(root: &Path, xtask_package: &str, args: &[impl AsRef]) -> Result<(Command, String), Error> { + check_package(xtask_package)?; + let doc_args: Vec<&OsStr> = std::iter::once(OsStr::new("--doc")).chain(args.iter().map(AsRef::as_ref)).collect(); + Ok(test_command(cargo(root), xtask_package, &["test"], &doc_args)) +} + +/// Whether `cargo nextest --version` succeeds for this `cargo` command. +pub fn nextest_available(mut cargo: Command) -> bool { + cargo.args(["nextest", "--version"]).stdout(Stdio::null()).stderr(Stdio::null()).status().is_ok_and(|s| s.success()) +} + +fn test_command(mut c: Command, xtask_package: &str, tool: &[&str], args: &[impl AsRef]) -> (Command, String) { + c.args(tool).args(["--workspace", "--exclude", xtask_package]).args(args); + let mut label = format!("cargo {} --workspace --exclude {xtask_package}", tool.join(" ")); + for a in args { + label.push(' '); + label.push_str(&a.as_ref().to_string_lossy()); + } + (c, label) +} + +/// A Cargo package name: ASCII letters, digits, `-` and `_`, not starting with `-`. +fn check_package(name: &str) -> Result<(), Error> { + let valid = !name.is_empty() && !name.starts_with('-') && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'); + if valid { Ok(()) } else { Err(Error::Config(format!("`{name}` is not a package name to exclude from the test build"))) } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + + fn args(c: &Command) -> Vec { + c.get_args().map(|a| a.to_string_lossy().into_owned()).collect() + } + + fn run_capture(steps: &mut [Step<'_>], options: &RunOptions) -> (Result, Error>, String, String) { + let (mut out, mut err) = (Vec::new(), Vec::new()); + let result = run_steps_to(steps, options, &mut out, &mut err); + (result, String::from_utf8_lossy(&out).into_owned(), String::from_utf8_lossy(&err).into_owned()) + } + + #[test] + fn run_steps_success_failure_and_skips() { + let later_ran = Cell::new(false); + let mut steps = vec![ + Step::new("fmt", |_| Ok(())), + Step::new("clippy", |log| Err(format!("{}: exited with 101", log.command("cargo clippy")))), + Step::new("test", |_| { + later_ran.set(true); + Ok(()) + }), + ]; + let (result, out, err) = run_capture(&mut steps, &RunOptions::default()); + assert_eq!(result, Err(Error::Step { step: "clippy".into(), cause: "cargo clippy: exited with 101".into() })); + assert!(!later_ran.get(), "a step after the failure ran"); + assert_eq!(out, "\nCI summary:\n ok fmt\n FAIL clippy: cargo clippy: exited with 101\n skip test\n"); + assert!(err.contains("=== ci: fmt ===") && err.contains("=== ci: clippy ===") && !err.contains("=== ci: test ==="), "{err}"); + + let mut passing = vec![Step::new("fmt", |_| Ok(())), Step::new("test", |_| Ok(()))]; + let (result, out, _) = run_capture(&mut passing, &RunOptions::default().with_title("gate")); + let records = result.unwrap_or_default(); + assert_eq!(records.iter().map(|r| r.status).collect::>(), [Status::Ok, Status::Ok]); + assert_eq!(out, "\nGATE summary: all 2 steps passed (fmt, test)\n"); + } + + #[test] + fn run_steps_empty() { + let (result, out, err) = run_capture(&mut [], &RunOptions::default()); + assert_eq!(result, Ok(Vec::new())); + assert_eq!(out, "\nCI summary: all 0 steps passed\n"); + assert!(err.is_empty()); + } + + #[test] + fn run_steps_canceled_runs_nothing_more() { + let cancel = Cancel::new(); + let ran = Cell::new(0); + let mut steps = vec![ + Step::new("fmt", |_| { + ran.set(ran.get() + 1); + cancel.cancel(); + Err("interrupted".to_owned()) + }), + Step::new("test", |_| { + ran.set(ran.get() + 1); + Ok(()) + }), + ]; + let options = RunOptions::default().with_cancel(cancel.clone()); + let (result, out, _) = run_capture(&mut steps, &options); + assert_eq!(result, Err(Error::Canceled { step: Some("fmt".into()) })); + assert_eq!(ran.get(), 1); + assert_eq!(out, "\nCI summary:\n cancel fmt\n skip test\n"); + + // A last step that passes after the flag was set does not make the run pass. + let late = Cancel::new(); + let mut last = vec![Step::new("last", |_| { + late.cancel(); + Ok(()) + })]; + let (result, out, _) = run_capture(&mut last, &RunOptions::default().with_cancel(late.clone())); + assert_eq!(result, Err(Error::Canceled { step: Some("last".into()) })); + assert_eq!(out, "\nCI summary:\n cancel last\n"); + + let mut again = vec![Step::new("fmt", |_| Ok(()))]; + let (result, out, _) = run_capture(&mut again, &options); + assert_eq!(result, Err(Error::Canceled { step: Some("fmt".into()) })); + assert!(!out.contains("passed"), "{out}"); + } + + #[cfg(all(feature = "lock", feature = "report"))] + #[test] + fn a_run_without_its_lock_writes_no_report() { + use crate::lock::{LockConfig, try_acquire}; + let _guard = crate::spawn_guard(); + let Ok(dir) = tempfile::tempdir() else { panic!("no temporary directory") }; + let locks = dir.path().join("locks"); + let lock = LockConfig::new(&locks, 1, "holder").with_poll(Duration::from_millis(1)); + let Ok(Some(_held)) = try_acquire(&lock) else { panic!("free slot") }; + + // A run canceled while another run holds the slot leaves that run's report alone. + let report = dir.path().join("ci.json"); + let Ok(()) = std::fs::write(&report, b"sentinel") else { panic!("cannot write the sentinel") }; + let cancel = Cancel::new(); + cancel.cancel(); + let ran = Cell::new(false); + let mut steps = vec![Step::new("test", |_| { + ran.set(true); + Ok(()) + })]; + let options = RunOptions::default().with_lock(lock.clone()).with_report(&report).with_cancel(cancel); + let (result, out, _) = run_capture(&mut steps, &options); + assert_eq!(result, Err(Error::Canceled { step: None })); + assert!(!ran.get(), "a step ran without the lock"); + assert_eq!(out, "\nCI summary:\n FAIL canceled before the first step\n skip test\n"); + assert_eq!(std::fs::read(&report).ok(), Some(b"sentinel".to_vec())); + + // A rejected lock configuration creates no report file. + let fresh = dir.path().join("rejected.json"); + let options = RunOptions::default().with_lock(LockConfig::new(&locks, 0, "zero")).with_report(&fresh); + let (result, _, _) = run_capture(&mut [Step::new("test", |_| Ok(()))], &options); + assert!(matches!(result, Err(Error::Config(_))), "{result:?}"); + assert!(!fresh.exists(), "a report was written without the lock"); + + // A lock directory that cannot be created leaves the existing report alone. + let not_a_dir = dir.path().join("file"); + let Ok(()) = std::fs::write(¬_a_dir, b"") else { panic!("cannot write the file") }; + let options = RunOptions::default().with_lock(LockConfig::new(not_a_dir.join("locks"), 1, "run")).with_report(&report); + let (result, _, _) = run_capture(&mut [Step::new("test", |_| Ok(()))], &options); + assert!(matches!(result, Err(Error::Lock(_))), "{result:?}"); + assert_eq!(std::fs::read(&report).ok(), Some(b"sentinel".to_vec())); + } + + #[test] + fn root_uses_callers_manifest() { + let Ok(dir) = tempfile::tempdir() else { panic!("no temporary directory") }; + let app = dir.path().join("app"); + let xtask = app.join("xtask"); + let Ok(()) = std::fs::create_dir_all(&xtask) else { panic!("cannot create the fixture") }; + let Ok(()) = std::fs::write(app.join("Cargo.toml"), "[workspace]\n") else { panic!("cannot write the fixture") }; + assert_eq!(root(&xtask), Ok(app.clone())); + assert_eq!(cargo(&app).get_current_dir(), Some(app.as_path())); + + // A manifest directory whose parent is not a workspace, and one with no parent at all. + assert!(matches!(root(&dir.path().join("xtask")), Err(Error::Config(_)))); + assert!(matches!(root(Path::new("xtask")), Err(Error::Config(_)))); + assert!(matches!(root(Path::new("")), Err(Error::Config(_)))); + } + + #[test] + fn workspace_tests_exclude_running_package() { + let root = Path::new("."); + let targets = ["--lib", "--bins", "--tests"]; + let (c, label) = test_command(cargo(root), "designcraft-xtask", &["test"], &targets); + assert_eq!(args(&c), ["test", "--workspace", "--exclude", "designcraft-xtask", "--lib", "--bins", "--tests"]); + assert_eq!(label, "cargo test --workspace --exclude designcraft-xtask --lib --bins --tests"); + + let (c, label) = test_command(cargo(root), "xtask", &["nextest", "run"], &targets); + assert_eq!(args(&c), ["nextest", "run", "--workspace", "--exclude", "xtask", "--lib", "--bins", "--tests"]); + assert_eq!(label, "cargo nextest run --workspace --exclude xtask --lib --bins --tests"); + + let Ok((c, label)) = nextest_or_test(root, "xtask", TestMode::CargoTest, &targets) else { panic!("valid package") }; + assert_eq!(args(&c), ["test", "--workspace", "--exclude", "xtask", "--lib", "--bins", "--tests"]); + assert_eq!(label, "cargo test --workspace --exclude xtask --lib --bins --tests"); + + let Ok((c, label)) = doctest(root, "xtask", &["--features", "full"]) else { panic!("valid package") }; + assert_eq!(args(&c), ["test", "--workspace", "--exclude", "xtask", "--doc", "--features", "full"]); + assert_eq!(label, "cargo test --workspace --exclude xtask --doc --features full"); + + for bad in ["", "-p", "--workspace", "two words", "x;y"] { + assert!(matches!(nextest_or_test(root, bad, TestMode::CargoTest, &targets), Err(Error::Config(_))), "{bad:?}"); + assert!(matches!(doctest(root, bad, &[] as &[&str]), Err(Error::Config(_))), "{bad:?}"); + } + } + + #[test] + fn missing_tools_and_output_bytes() { + let _guard = crate::spawn_guard(); + let missing = "craft-xtask-test-no-such-program"; + let Err(e) = run(Command::new(missing), "missing tool") else { panic!("a missing program ran") }; + assert!(e.starts_with("missing tool: failed to spawn: "), "{e}"); + assert!(!nextest_available(Command::new(missing))); + + // PreferNextest without nextest falls back to cargo test; CargoTest never probes. + let targets = ["--lib"]; + let fallback = select_test(cargo(Path::new(".")), "xtask", TestMode::PreferNextest, &targets, || nextest_available(Command::new(missing))); + let Ok((c, label)) = fallback else { panic!("valid package") }; + assert_eq!(args(&c), ["test", "--workspace", "--exclude", "xtask", "--lib"]); + assert_eq!(label, "cargo test --workspace --exclude xtask --lib"); + let Ok((c, label)) = select_test(cargo(Path::new(".")), "xtask", TestMode::PreferNextest, &targets, || true) else { panic!("valid package") }; + assert_eq!(args(&c), ["nextest", "run", "--workspace", "--exclude", "xtask", "--lib"]); + assert_eq!(label, "cargo nextest run --workspace --exclude xtask --lib"); + let probed = Cell::new(false); + let Ok((c, _)) = select_test(cargo(Path::new(".")), "xtask", TestMode::CargoTest, &targets, || { + probed.set(true); + true + }) else { + panic!("valid package") + }; + assert_eq!(args(&c)[0], "test"); + assert!(!probed.get(), "CargoTest probed for nextest"); + + // A child's output that is not UTF-8 reaches the stream it was given unchanged. + let (mut reader, writer) = io::pipe().expect("pipe"); + let mut child = test_child("runner::tests::bytes_child", BYTES_CHILD); + child.stdout(writer).stderr(Stdio::null()); + assert_eq!(run(child, "bytes"), Ok(())); + let mut got = Vec::new(); + io::Read::read_to_end(&mut reader, &mut got).expect("child output"); + assert!(got.windows(RAW_BYTES.len()).any(|w| w == RAW_BYTES), "{got:?}"); + + // The test binary itself, given a flag it does not know, exits with a failure status. + let Ok(exe) = std::env::current_exe() else { panic!("no test executable") }; + let mut child = Command::new(&exe); + child.arg("--craft-xtask-unknown-flag").stdout(Stdio::null()).stderr(Stdio::null()); + let Err(e) = run(child, "child") else { panic!("an unknown flag passed") }; + assert!(e.starts_with("child: exited with "), "{e}"); + + let mut steps = vec![Step::new("cargo", |log| run(Command::new(missing), log.command("cargo"))), Step::new("after", |_| Ok(()))]; + let (result, out, _) = run_capture(&mut steps, &RunOptions::default()); + assert!(matches!(&result, Err(Error::Step { step, cause }) if step == "cargo" && cause.contains("failed to spawn")), "{result:?}"); + assert!(out.contains(" FAIL cargo: cargo: failed to spawn: ") && out.ends_with("\n skip after\n"), "{out}"); + } + + const TREE_CHILD: &str = "CRAFT_XTASK_TREE_CHILD"; + const BLOCKED_CHILD: &str = "CRAFT_XTASK_BLOCKED_CHILD"; + const BYTES_CHILD: &str = "CRAFT_XTASK_BYTES_CHILD"; + const RAW_BYTES: &[u8] = b"\xff\xfe\x00 not UTF-8 \x80\xc3\n"; + + /// This test binary, run as a child that runs only the ignored test `name`. + fn test_child(name: &str, env: &str) -> Command { + let exe = std::env::current_exe().expect("test executable"); + let mut c = Command::new(exe); + c.args(["--ignored", "--exact", name, "--nocapture"]).env(env, "1").stdin(Stdio::null()); + c + } + + /// Reads a pipe whose writing end this process also holds, so the read never ends. + fn block_forever() { + let (mut reader, _writer) = io::pipe().expect("pipe"); + let _ = io::Read::read_to_end(&mut reader, &mut Vec::new()); + } + + #[test] + fn run_cancelable_ends_the_process_tree() { + use io::BufRead; + let _guard = crate::spawn_guard(); + let (reader, writer) = io::pipe().expect("pipe"); + let mut child = test_child("runner::tests::tree_child", TREE_CHILD); + child.stdout(writer).stderr(Stdio::null()); + let cancel = Cancel::new(); + let runner = { + let cancel = cancel.clone(); + std::thread::spawn(move || run_cancelable(child, "tree", &cancel)) + }; + // The child prints `ready` once it has started its own child, which shares the pipe. + let mut lines = io::BufReader::new(reader); + let mut line = String::new(); + while !line.trim_end().ends_with("ready") { + line.clear(); + assert_ne!(lines.read_line(&mut line).expect("child output"), 0, "the child ended before it was ready"); + } + cancel.cancel(); + assert_eq!(runner.join().expect("runner thread"), Err("tree: canceled".to_owned())); + // The pipe ends only when every process holding it has ended, the child's child included. + io::Read::read_to_end(&mut lines, &mut Vec::new()).expect("pipe end"); + } + + /// Starts a blocked child of its own, says `ready`, and blocks; run by `run_cancelable_ends_the_process_tree`. + #[test] + #[ignore = "child process of run_cancelable_ends_the_process_tree"] + fn tree_child() { + if std::env::var_os(TREE_CHILD).is_some() { + let mut grandchild = test_child("runner::tests::blocked_child", BLOCKED_CHILD).spawn().expect("grandchild"); + let mut out = io::stdout(); + writeln!(out, "ready").and_then(|()| out.flush()).expect("stdout"); + // The grandchild never exits, so this blocks too. + let _ = grandchild.wait(); + } + } + + /// Writes bytes that are not UTF-8 to stdout; run by `missing_tools_and_output_bytes`. + #[test] + #[ignore = "child process of missing_tools_and_output_bytes"] + fn bytes_child() { + if std::env::var_os(BYTES_CHILD).is_some() { + let mut out = io::stdout(); + out.write_all(RAW_BYTES).and_then(|()| out.flush()).expect("stdout"); + } + } + + /// Blocks; run by `tree_child`. + #[test] + #[ignore = "child process of tree_child"] + fn blocked_child() { + if std::env::var_os(BLOCKED_CHILD).is_some() { + block_forever(); + } + } +} From 19b98454a95af071ebfb0450b59e6ea01d4ad6c0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:11:12 -0800 Subject: [PATCH 021/322] craft-testkit: seeded xorshift64 and xorshift64* generators for test input Add craft_testkit::rng with XorShift64 (shifts 13, 7, 17) and XorShift64Star (shifts 12, 25, 27, output multiplied by 0x2545_F491_4F6C_DD1D, state kept unmultiplied). Each has new, next, below, byte and fill. - new returns SeedError::ZeroSeed for a seed of 0, which would make either recurrence return 0 forever. - below takes one draw modulo the bound; a bound of 0 returns 0 after one draw, as the DNx and JPEG suites do today. - byte is the low 8 bits of one draw; fill takes one byte() per output byte in index order, and an empty slice takes no draw. The module uses no std-only items and builds for wasm32-unknown-unknown. Its tests pin the first outputs of both generators for the DNx and JPEG seeds and compare draws with the generators those suites define. The README gains the module's description and rows for it in the Origin and Migration tables. --- crates/testkit/README.md | 24 ++++ crates/testkit/src/lib.rs | 4 + crates/testkit/src/rng.rs | 269 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 297 insertions(+) create mode 100644 crates/testkit/src/rng.rs diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 36b87bb89d..c59a29fc5b 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -11,6 +11,24 @@ Source-level platform regression guards and verification utilities for the Craft 3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`. Other crates' `Instant` (such as `web_time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`. A `mod name;` inside such an item also skips the module's file (`name.rs` or `name/mod.rs`, or the file a `#[path]` attribute names) and the files of the modules declared in it, when they are among the files passed in and no declaration outside such items also reaches them. On that target, `std::time::Instant::now()` panics at runtime with `"time not implemented on this platform"`. Code targeting the web must use `web_time::Instant`. 4. **`rust_sources`**: Recursively discovers a crate's `.rs` source files while excluding integration tests (`tests/`), test modules (`tests.rs`, `tests_*.rs`, `*_tests.rs`, `*_test.rs`), build artifacts (`target/`, any folder holding a `CACHEDIR.TAG` file that starts with the line `Signature: 8a477f597d28d172789f06886806bc55`, `.git/` and other folders whose name starts with `.`) and symbolic links, which it does not follow. A file over 8 MiB, more than 256 MiB in all or more than 50,000 files returns an error; `rust_sources_with_limits` takes other limits. It is not built for `wasm32`. +## Random test input: `rng` + +`craft_testkit::rng` holds two seeded generators for repeatable test input. They are not suitable for cryptography. + +| Type | Recurrence | Output | +|---|---|---| +| `XorShift64` | `x ^= x << 13; x ^= x >> 7; x ^= x << 17` | the new state | +| `XorShift64Star` | `x ^= x >> 12; x ^= x << 25; x ^= x >> 27` | the new state multiplied by `0x2545_F491_4F6C_DD1D` | + +Each type has `new(seed) -> Result`, which returns `SeedError::ZeroSeed` for a seed of 0, and these methods: + +- `next()` advances the state and returns one draw. +- `below(n)` returns one draw modulo `n`. A bound of 0 returns 0 and still takes a draw. The modulo is slightly biased toward small values when `n` does not divide 2^64. +- `byte()` returns the low 8 bits of one draw. +- `fill(out)` sets each byte of `out` to one `byte()`, in index order. An empty slice takes no draw. + +A suite that switches to `rng` keeps the generator and seed it uses today, so its inputs do not change. The module builds for `wasm32-unknown-unknown`. + ## Epistemic Scope: Syntactic Guards vs Runtime Validation Source-level guards provide deterministic syntactic evidence about codebase structure: @@ -83,6 +101,9 @@ fn no_std_instant_in_code_the_web_build_runs() { | Module | Source | Path | Commit | |---|---|---|---| | `guards` | storytold/craft-libs#163 (zachshallbetter), with the rules of PhotoCraft's shader float test and FilmCraft's web clock test | `crates/testkit/src/guards.rs` | `e92825e427` | +| `rng` (`XorShift64`) | storytold/filmcraft | `crates/dnx/tests/it/fuzz_hostile.rs:9-20` | `0a881266` | +| `rng` (`XorShift64`) | storytold/craft-libs | `crates/video/tests/dnx/fuzz_hostile.rs:9-20` | `9f10d434` | +| `rng` (`XorShift64Star`) | storytold/craft-libs | `crates/jpeg/tests/mutation.rs:28-46` | `97c83dc9` | ## Migration @@ -90,3 +111,6 @@ fn no_std_instant_in_code_the_web_build_runs() { |---|---|---|---| | PhotoCraft | `wgsl_float_literals` | `crates/gpu/src/tests.rs` scanner | Not started | | FilmCraft | `std_instant` | `crates/engine/src/wasm_clock_tests.rs` search | Not started | +| craft-libs `video` | `rng::XorShift64` | the generator in `tests/dnx/fuzz_hostile.rs` and the other `fuzz_hostile.rs` suites | Not started | +| craft-libs `jpeg` | `rng::XorShift64Star` | the generator in `tests/mutation.rs` | Not started | +| FilmCraft | `rng::XorShift64` | the generator in `crates/dnx/tests/it/fuzz_hostile.rs` | Not started | diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index b484c6ef69..74666a22af 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -15,6 +15,9 @@ //! * [`guards::rust_sources`]: directory crawler collecting `.rs` sources while excluding tests, with //! size limits ([`guards::rust_sources_with_limits`]). It is not built for `wasm32`. //! +//! [`rng`] holds two seeded generators for repeatable test input, [`rng::XorShift64`] and +//! [`rng::XorShift64Star`], each with `next`, `below`, `byte` and `fill`. +//! //! ### Epistemic Scope: What Source Guards Establish vs What They Cannot //! //! Source-level guards provide deterministic syntactic evidence about codebase structure. @@ -26,6 +29,7 @@ //! rather than replace, platform integration tests and CI execution. pub mod guards; +pub mod rng; pub use guards::{AsFileSource, Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; diff --git a/crates/testkit/src/rng.rs b/crates/testkit/src/rng.rs new file mode 100644 index 0000000000..f20428eacc --- /dev/null +++ b/crates/testkit/src/rng.rs @@ -0,0 +1,269 @@ +//! Deterministic generators for test input: seeded, repeatable, and not suitable for cryptography. +//! +//! [`XorShift64`] is Marsaglia's xorshift64 with the shift triple 13, 7, 17. [`XorShift64Star`] is +//! Vigna's xorshift64*: shifts 12, 25 and 27 on the state, and the output is the state multiplied by +//! `0x2545_F491_4F6C_DD1D`. The state keeps the unmultiplied value. +//! +//! Both generators take a nonzero seed: with a zero state, either recurrence returns zero forever, so +//! [`XorShift64::new`] and [`XorShift64Star::new`] return [`SeedError::ZeroSeed`] for it. +//! +//! [`below`](XorShift64::below) reduces one draw modulo the bound. The result is slightly biased toward +//! small values for a bound that does not divide 2^64, and a bound of 0 returns 0 after one draw. +//! [`byte`](XorShift64::byte) returns the low 8 bits of one draw, and [`fill`](XorShift64::fill) sets +//! each byte of a slice to one [`byte`](XorShift64::byte) in index order. + +use std::fmt; + +/// The seed passed to a generator's constructor cannot start a sequence. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SeedError { + /// The seed is 0, which the xorshift recurrences map to 0 on every draw. + ZeroSeed, +} + +impl fmt::Display for SeedError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + SeedError::ZeroSeed => f.write_str("an xorshift generator needs a nonzero seed"), + } + } +} + +impl std::error::Error for SeedError {} + +/// Marsaglia's xorshift64 generator (`x ^= x << 13; x ^= x >> 7; x ^= x << 17`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct XorShift64(u64); + +impl XorShift64 { + /// Start a sequence from `seed`. Returns [`SeedError::ZeroSeed`] when `seed` is 0. + pub fn new(seed: u64) -> Result { + if seed == 0 { Err(SeedError::ZeroSeed) } else { Ok(Self(seed)) } + } + + /// Advance the state and return it. + #[allow(clippy::should_implement_trait)] + pub fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + + /// One draw reduced modulo `n`, so the result is below `n`. A bound of 0 returns 0 and still takes a draw. + pub fn below(&mut self, n: usize) -> usize { + (self.next() % n.max(1) as u64) as usize + } + + /// The low 8 bits of one draw. + pub fn byte(&mut self) -> u8 { + self.next() as u8 + } + + /// Set each byte of `out` to one [`byte`](Self::byte), in index order. An empty slice takes no draw. + pub fn fill(&mut self, out: &mut [u8]) { + for b in out { + *b = self.byte(); + } + } +} + +/// Vigna's xorshift64* generator: the state shifts by 12, 25 and 27, and each output is the new state +/// multiplied by `0x2545_F491_4F6C_DD1D`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct XorShift64Star(u64); + +impl XorShift64Star { + /// Start a sequence from `seed`. Returns [`SeedError::ZeroSeed`] when `seed` is 0. + pub fn new(seed: u64) -> Result { + if seed == 0 { Err(SeedError::ZeroSeed) } else { Ok(Self(seed)) } + } + + /// Advance the state and return it multiplied by `0x2545_F491_4F6C_DD1D`. + #[allow(clippy::should_implement_trait)] + pub fn next(&mut self) -> u64 { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + + /// One draw reduced modulo `n`, so the result is below `n`. A bound of 0 returns 0 and still takes a draw. + pub fn below(&mut self, n: usize) -> usize { + (self.next() % n.max(1) as u64) as usize + } + + /// The low 8 bits of one draw. + pub fn byte(&mut self) -> u8 { + self.next() as u8 + } + + /// Set each byte of `out` to one [`byte`](Self::byte), in index order. An empty slice takes no draw. + pub fn fill(&mut self, out: &mut [u8]) { + for b in out { + *b = self.byte(); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const SEED: u64 = 0x9e37_79b9_7f4a_7c15; + const JPEG_SEED_2: u64 = 0xD1B5_4A32_D192_ED03; + + /// The generator of craft-libs `crates/video/tests/dnx/fuzz_hostile.rs` and FilmCraft + /// `crates/dnx/tests/it/fuzz_hostile.rs`, as those suites define it. + struct DnxRng(u64); + impl DnxRng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 << 13; + self.0 ^= self.0 >> 7; + self.0 ^= self.0 << 17; + self.0 + } + fn below(&mut self, n: usize) -> usize { + (self.next() % n.max(1) as u64) as usize + } + } + + /// The generator of craft-libs `crates/jpeg/tests/mutation.rs`, as that suite defines it. + struct JpegRng(u64); + impl JpegRng { + fn next(&mut self) -> u64 { + self.0 ^= self.0 >> 12; + self.0 ^= self.0 << 25; + self.0 ^= self.0 >> 27; + self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + fn below(&mut self, n: usize) -> usize { + (self.next() % n.max(1) as u64) as usize + } + fn byte(&mut self) -> u8 { + self.next() as u8 + } + } + + fn xs(seed: u64) -> XorShift64 { + match XorShift64::new(seed) { + Ok(r) => r, + Err(e) => panic!("seed {seed:#x}: {e}"), + } + } + + fn xss(seed: u64) -> XorShift64Star { + match XorShift64Star::new(seed) { + Ok(r) => r, + Err(e) => panic!("seed {seed:#x}: {e}"), + } + } + + #[test] + fn xorshift64_reference_sequence() { + let mut r = xs(SEED); + let got: Vec = (0..4).map(|_| r.next()).collect(); + assert_eq!(got, [0xdc1b_77ae_0bf3_4dad, 0x64f0_eeb9_026e_6076, 0x7b07_ce91_e590_6136, 0x305f_050c_368d_cc74]); + } + + #[test] + fn xorshift64star_reference_sequence() { + let mut r = xss(SEED); + let got: Vec = (0..4).map(|_| r.next()).collect(); + assert_eq!(got, [0x0d83_b3e2_9a21_487a, 0x54c4_4c79_f1fe_9d67, 0xa845_f342_007a_0e78, 0x7d6e_0b87_8a79_4779]); + } + + #[test] + fn below_range_and_zero() { + let bounds = [1usize, 2, 3, 7, 10, 255, 256, 1000, usize::MAX]; + let mut a = xs(SEED); + let mut b = xss(SEED); + for _ in 0..64 { + for n in bounds { + assert!(a.below(n) < n, "XorShift64::below({n})"); + assert!(b.below(n) < n, "XorShift64Star::below({n})"); + } + } + + let (mut a, mut a_peer) = (xs(SEED), xs(SEED)); + assert_eq!(a.below(0), 0); + a_peer.next(); + assert_eq!(a, a_peer, "below(0) takes one draw"); + + let (mut b, mut b_peer) = (xss(SEED), xss(SEED)); + assert_eq!(b.below(0), 0); + b_peer.next(); + assert_eq!(b, b_peer, "below(0) takes one draw"); + } + + #[test] + fn byte_is_next_low_byte() { + let (mut a, mut a_peer) = (xs(SEED), xs(SEED)); + let (mut b, mut b_peer) = (xss(SEED), xss(SEED)); + for _ in 0..32 { + assert_eq!(a.byte(), a_peer.next() as u8); + assert_eq!(b.byte(), b_peer.next() as u8); + } + assert_eq!(a, a_peer); + assert_eq!(b, b_peer); + } + + #[test] + fn fill_matches_successive_bytes() { + for len in [0usize, 1, 2, 9, 64] { + let (mut a, mut a_peer) = (xs(SEED), xs(SEED)); + let mut out = vec![0xAAu8; len]; + a.fill(&mut out); + assert_eq!(out.len(), len); + let expect: Vec = (0..len).map(|_| a_peer.byte()).collect(); + assert_eq!(out, expect, "XorShift64::fill of {len} bytes"); + assert_eq!(a.next(), a_peer.next(), "XorShift64 state after fill of {len} bytes"); + + let (mut b, mut b_peer) = (xss(SEED), xss(SEED)); + let mut out = vec![0xAAu8; len]; + b.fill(&mut out); + assert_eq!(out.len(), len); + let expect: Vec = (0..len).map(|_| b_peer.byte()).collect(); + assert_eq!(out, expect, "XorShift64Star::fill of {len} bytes"); + assert_eq!(b.next(), b_peer.next(), "XorShift64Star state after fill of {len} bytes"); + } + } + + #[test] + fn zero_seed_is_rejected() { + assert_eq!(XorShift64::new(0), Err(SeedError::ZeroSeed)); + assert_eq!(XorShift64Star::new(0), Err(SeedError::ZeroSeed)); + assert!(XorShift64::new(1).is_ok()); + assert!(XorShift64Star::new(1).is_ok()); + assert!(XorShift64::new(u64::MAX).is_ok()); + assert!(XorShift64Star::new(u64::MAX).is_ok()); + } + + #[test] + fn dnx_and_jpeg_sequences_match() { + // The DNx suites seed with `SEED ^ index` for each seed frame. + for si in 0..5u64 { + let mut ours = xs(SEED ^ si); + let mut theirs = DnxRng(SEED ^ si); + for n in [0usize, 1, 17, 4096, 65_535] { + assert_eq!(ours.below(n), theirs.below(n)); + assert_eq!(ours.next(), theirs.next()); + assert_eq!(ours.byte(), theirs.next() as u8); + } + } + + for seed in [SEED, JPEG_SEED_2] { + let mut ours = xss(seed); + let mut theirs = JpegRng(seed); + for n in [0usize, 1, 17, 4096, 65_535] { + assert_eq!(ours.below(n), theirs.below(n)); + assert_eq!(ours.byte(), theirs.byte()); + assert_eq!(ours.next(), theirs.next()); + } + } + + let mut r = xss(JPEG_SEED_2); + let got: Vec = (0..4).map(|_| r.next()).collect(); + assert_eq!(got, [0x015f_6958_028f_9348, 0xca16_c6bb_fa7f_a781, 0x5a65_feae_5ef1_f5e3, 0x54c4_89ba_613d_6dff]); + } +} From dc8f3481022ca2ecfeaf8023ac3f33ce81b6d863 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:43:35 -0800 Subject: [PATCH 022/322] craft-xtask: count Rust files, lines and tests per crate without following links Adds the stats module behind a new stats feature, the library form of the apps' cargo xtask stats. The app passes its cargo metadata JSON, a function that builds its cargo command, and a writer. Compared with the app copies, links and junctions are not followed, every input has a size limit, only workspace members are walked, a member nested in another member's folder is counted once, and malformed or duplicate packages are errors. The exact-mode tests start child processes and take spawn_guard like the runner and lock tests. --- crates/xtask/Cargo.toml | 2 + crates/xtask/README.md | 47 +- crates/xtask/src/lib.rs | 3 + crates/xtask/src/stats.rs | 898 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 948 insertions(+), 2 deletions(-) create mode 100644 crates/xtask/src/stats.rs diff --git a/crates/xtask/Cargo.toml b/crates/xtask/Cargo.toml index 6b561b543b..ed7be0d7ff 100644 --- a/crates/xtask/Cargo.toml +++ b/crates/xtask/Cargo.toml @@ -16,6 +16,8 @@ default = [] lock = [] # The per-step JSON report, replaced atomically. report = ["dep:serde_json", "dep:craft-atomic"] +# `cargo xtask stats`: files, lines and tests of Rust per workspace crate, read from `cargo metadata`. +stats = ["dep:serde_json"] [dependencies] craft-atomic = { workspace = true, optional = true } diff --git a/crates/xtask/README.md b/crates/xtask/README.md index 75228c3d66..cfe87e2247 100644 --- a/crates/xtask/README.md +++ b/crates/xtask/README.md @@ -9,8 +9,10 @@ The crate is native only and is a dependency of an app's `xtask` package only. | `runner` | always | `Step`, `run_steps` (steps in order, stop at the first failure, the `ok`, `FAIL` and `skip` summary), `root`, `cargo`, `run`, `run_cancelable`, `nextest_or_test`, `doctest`, `Cancel` | | `lock` | `lock` | `LockConfig`, `try_acquire`, `acquire`, `holders`: 1 to 64 slots held across processes through file locks in a directory the app chooses | | `report` | `report` | `write` and `to_json`: the per-step JSON report (schema 1), replaced atomically through `craft-atomic` | +| `stats` | `stats` | `run`, `collect` and `write_table`: files, lines and tests of Rust per workspace crate (`cargo xtask stats`) | -No feature is on by default. `report` adds `serde_json` and `craft-atomic`. +No feature is on by default. `report` adds `serde_json` and `craft-atomic`, and `stats` adds +`serde_json`. ## Use @@ -91,6 +93,42 @@ cancel while waiting) runs no step and writes no report. The report looks like t so a reader never sees a partial report, and a failed write leaves the previous report in place. Machine, GPU, corpus and skip details stay in the app's own report. +## Stats + +`cargo xtask stats [--exact]` prints the `.rs` files, lines, `#[test]` attributes and `proptest!` blocks +of each workspace crate. The app passes the `cargo metadata --format-version 1 --no-deps` JSON, a +function that builds its `cargo` command, and a writer: + +```rust,ignore +Some("stats") => { + let options = craft_xtask::stats::Options { exact: rest.contains(&"--exact"), ..Default::default() }; + craft_xtask::stats::run(&metadata_bytes()?, &options, cargo, &mut std::io::stdout().lock()) + .map(drop) + .map_err(|e| e.to_string()) +} +``` + +- Each workspace member's folder is walked. Folders named `target` or `fuzz` and folders whose names + start with `.` are skipped, and a member inside another member's folder is counted in its own row + only. Symbolic links and Windows junctions are not followed, to folders or to files. +- `#[test]` counts the text `#[test]` on lines that do not start with `//`. Tests that macros generate + count once, and `#[tokio::test]` is not counted. `--exact` runs + `cargo test -q -p -- --list` for each crate and counts the lines that end in `: test`. A + crate whose listing fails shows `error`, and a line under the table names it. +- `Limits` bounds every input. A larger input is an error naming the path and the limit: + + | Limit | Default | + |---|---| + | `metadata_bytes`: the `cargo metadata` JSON | 64 MiB | + | `source_bytes`: one `.rs` file | 16 MiB | + | `total_source_bytes`: all `.rs` files of a run | 1 GiB | + | `entries`: folder entries of a run | 1,000,000 | + | `depth`: folder levels below a crate's folder | 256 | + | `harness_output_bytes`: one crate's `--list` output | 64 MiB | + + A folder or file that cannot be read and a `.rs` file that is not UTF-8 are errors too. +- `collect` returns the `Report` without writing it, and `write_table` writes a `Report`. + ## Origin | Part | Source | @@ -98,7 +136,11 @@ Machine, GPU, corpus and skip details stay in the app's own report. | `runner`: the step loop and summary, `root`, `cargo`, `run`, the nextest probe and fallback, doctests | DesignCraft `xtask/src/main.rs:68-82`, `:160-201`, `:204-249` at [8b169f8](https://github.com/storytold/designcraft/blob/8b169f8ee7832e60ed1ac4c9f5dd34f954d3a992/xtask/src/main.rs) | | `lock` and its tests `one_slot_is_exclusive_until_dropped`, `more_slots_admit_more_runs` | LightCraft `xtask/src/ci_lock.rs` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/ci_lock.rs) | | `report`: the per-step fields | LightCraft `xtask/src/ci.rs:347-414` at [25ffe3e](https://github.com/storytold/lightcraft/blob/25ffe3e5d4ac754829b99dd7368d94185adbf8d5/xtask/src/ci.rs#L347-L414) | -| The root and slot-count errors, the `--exclude` of the xtask package, cancellation, the bounded owner read and the atomic report | written here | +| `stats`: the folder walk that skips directory links, and the table | DesignCraft `xtask/src/stats.rs` at `dc9eea2695` | +| `stats`: regular files only, and `a_walk_does_not_follow_directory_links` | WordCraft `xtask/src/stats.rs` at `6b163b33dc` | +| `stats`: the entry budget that returns an error, and its two tests | CADCraft `xtask/src/stats.rs` at `ca87680fb0` | +| `stats`: the per-file size limit, and its two tests | GridCraft `xtask/src/stats.rs` at `9e9f13114f` | +| The root and slot-count errors, the `--exclude` of the xtask package, cancellation, the bounded owner read and the atomic report; in `stats`, the metadata, total-size, depth and `--list` output limits, the metadata checks and the line naming failed listings | written here | ## Migration @@ -108,6 +150,7 @@ No app uses this crate yet. |---|---| | DesignCraft | Planned: `cmd_ci`, `root`, `cargo`, `run`, `cmd_test` and `cmd_doctest` move to `runner`, with `TestMode::PreferNextest`. The step list, `TEST_TARGETS` and the i18n report stay in the app. | | LightCraft | Planned: `ci_lock.rs` moves to `lock`, with `LIGHTCRAFT_CI_LOCK` and `LIGHTCRAFT_CI_SLOTS` read by the app. The machine, GPU, corpus and skip report stays in the app. | +| CADCraft, DeckCraft, DesignCraft, GridCraft, LightCraft, PhotoCraft, VectorCraft, WordCraft | Planned: `xtask/src/stats.rs` moves to `stats`. Each app's switch lists its per-crate counts before and after in its pull request. | Maintainers: the craft-libs maintainers, until a responsible maintainer or team is agreed in the review of this crate's first pull request. diff --git a/crates/xtask/src/lib.rs b/crates/xtask/src/lib.rs index 2ed8390e00..eb92226999 100644 --- a/crates/xtask/src/lib.rs +++ b/crates/xtask/src/lib.rs @@ -12,6 +12,7 @@ //! - `lock` (feature `lock`): a fixed number of slots, held across processes through file locks, so //! that gate runs in several checkouts of one machine take turns. //! - `report` (feature `report`): the per-step JSON report, replaced atomically. +//! - `stats` (feature `stats`): files, lines and tests of Rust per workspace crate (`cargo xtask stats`). //! //! ```no_run //! use std::path::Path; @@ -40,6 +41,8 @@ pub mod lock; #[cfg(feature = "report")] pub mod report; pub mod runner; +#[cfg(feature = "stats")] +pub mod stats; /// Keeps the tests that start child processes apart from the tests that check whether a slot is free. /// A child holds copies of the parent's open files, and so its file locks, until it starts its program. diff --git a/crates/xtask/src/stats.rs b/crates/xtask/src/stats.rs new file mode 100644 index 0000000000..c51590e897 --- /dev/null +++ b/crates/xtask/src/stats.rs @@ -0,0 +1,898 @@ +//! `cargo xtask stats`: files, lines and tests of Rust per workspace crate. +//! +//! [`run`] reads the workspace packages from the `cargo metadata --format-version 1 --no-deps` JSON the +//! caller passes in, walks each package's folder and writes a table to the caller's writer: +//! +//! ```text +//! crate files lines #[test] proptest! +//! -------------------------------------------------------------- +//! app-core 12 3410 41 2 +//! -------------------------------------------------------------- +//! TOTAL 12 3410 41 2 +//! ``` +//! +//! What it counts: +//! +//! - Every regular file whose name ends in `.rs`, in the package's folder and the folders below it. +//! Folders named `target` or `fuzz`, and folders whose names start with `.`, are skipped. The +//! folder of another workspace member is counted in that member's row only. +//! Symbolic links (and Windows junctions) are not followed, to folders or to files. +//! - Lines as [`str::lines`] counts them, blank and comment lines included. +//! - `#[test]` is an estimate read from the text: each `#[test]` on a line that does not start with +//! `//`. `#[tokio::test]` and the tests inside `proptest!` are not counted; each line that starts +//! with `proptest!` counts as one block in its own column. +//! - With [`Options::exact`], the harness column runs `cargo test -q -p -- --list` for each +//! crate and counts the output lines that end in `: test`. A crate whose command fails shows +//! `error`, the harness total leaves it out, and a line under the table says how many failed. +//! +//! Every input has a size limit ([`Limits`]); an input over a limit, a folder or file that cannot be +//! read, and a source that is not UTF-8 return an [`Error`] naming the path, and nothing is written. + +use std::collections::HashSet; +use std::fmt; +use std::fs::File; +use std::io::{self, Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +/// Size limits for one [`run`]. An input over a limit is an [`Error`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Limits { + /// Bytes of `cargo metadata` JSON, checked before it is parsed. Default 64 MiB. + pub metadata_bytes: usize, + /// Bytes of one `.rs` file. Default 16 MiB. + pub source_bytes: u64, + /// Bytes of all `.rs` files read in one run. Default 1 GiB. + pub total_source_bytes: u64, + /// Folder entries visited in one run, all crates together. Default 1,000,000. + pub entries: usize, + /// Levels of folders below a crate's folder. Default 256. + pub depth: usize, + /// Bytes of standard output from one crate's `cargo test -- --list`, in exact mode. Default 64 MiB. + pub harness_output_bytes: u64, +} + +impl Default for Limits { + fn default() -> Self { + Limits { + metadata_bytes: 64 << 20, + source_bytes: 16 << 20, + total_source_bytes: 1 << 30, + entries: 1_000_000, + depth: 256, + harness_output_bytes: 64 << 20, + } + } +} + +/// How [`run`] counts. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Options { + /// Ask each crate's test harness for its test count (`--exact`). + pub exact: bool, + /// The size limits. + pub limits: Limits, +} + +/// Counts for one crate, or for all of them. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct Counts { + /// `.rs` files. + pub files: usize, + /// Lines in those files. + pub lines: usize, + /// `#[test]` attributes found in the text. + pub tests: usize, + /// Lines that start a `proptest!` block. + pub proptests: usize, +} + +impl Counts { + fn add(&mut self, other: &Counts) { + self.files = self.files.saturating_add(other.files); + self.lines = self.lines.saturating_add(other.lines); + self.tests = self.tests.saturating_add(other.tests); + self.proptests = self.proptests.saturating_add(other.proptests); + } + + fn add_source(&mut self, src: &str) { + let (tests, proptests) = count_tests(src); + self.add(&Counts { files: 1, lines: src.lines().count(), tests, proptests }); + } +} + +/// The result of one crate's `cargo test -- --list`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Harness { + /// The command succeeded and listed this many tests. + Listed(usize), + /// The command could not start or did not succeed; the text says why. + Failed(String), +} + +/// One crate's row. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Row { + /// The package name. + pub name: String, + /// The package's `Cargo.toml`, as `cargo metadata` gives it. + pub manifest_path: PathBuf, + /// What the walk of the package's folder found. + pub counts: Counts, + /// The harness count, in exact mode only. + pub harness: Option, +} + +/// Every crate's counts, sorted by package name and then by manifest path. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Report { + /// One row per workspace package. + pub rows: Vec, + /// The sum of the rows' counts. + pub total: Counts, + /// Whether the harness counts were asked for. + pub exact: bool, +} + +impl Report { + /// The sum of the harness counts that succeeded, or `None` outside exact mode. + pub fn harness_total(&self) -> Option { + self.exact.then(|| { + self.rows + .iter() + .filter_map(|r| match r.harness { + Some(Harness::Listed(n)) => Some(n), + _ => None, + }) + .fold(0, usize::saturating_add) + }) + } + + /// The rows whose harness command failed. + pub fn harness_failures(&self) -> impl Iterator { + self.rows.iter().filter(|r| matches!(r.harness, Some(Harness::Failed(_)))) + } +} + +/// Why [`run`] stopped. +#[derive(Debug)] +pub enum Error { + /// The `cargo metadata` JSON is too large, is not JSON, or lacks a field. + Metadata(String), + /// A folder or file could not be read. + Io { + /// The folder or file. + path: PathBuf, + /// The error reading it. + source: io::Error, + }, + /// A `.rs` file is not UTF-8. + NotUtf8(PathBuf), + /// A `.rs` file is larger than [`Limits::source_bytes`]. + SourceTooLarge { + /// The file. + path: PathBuf, + /// The limit in bytes. + limit: u64, + }, + /// Reading a file would take the run past [`Limits::total_source_bytes`]. + TotalTooLarge { + /// The file being read. + path: PathBuf, + /// The limit in bytes. + limit: u64, + }, + /// The run visited [`Limits::entries`] folder entries. + TooManyEntries { + /// The folder being read. + path: PathBuf, + /// The limit. + limit: usize, + }, + /// A folder is more than [`Limits::depth`] levels below its crate's folder. + TooDeep { + /// The folder. + path: PathBuf, + /// The limit. + limit: usize, + }, + /// A crate's `cargo test -- --list` printed more than [`Limits::harness_output_bytes`]. + HarnessOutputTooLarge { + /// The package name. + package: String, + /// The limit in bytes. + limit: u64, + }, + /// The table could not be written. + Write(io::Error), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Metadata(why) => write!(f, "cargo metadata: {why}"), + Error::Io { path, source } => write!(f, "{}: {source}", path.display()), + Error::NotUtf8(path) => write!(f, "{}: not UTF-8", path.display()), + Error::SourceTooLarge { path, limit } => write!(f, "{}: larger than the limit of {limit} bytes for one source", path.display()), + Error::TotalTooLarge { path, limit } => { + write!(f, "{}: reading it passes the limit of {limit} bytes for all sources", path.display()) + } + Error::TooManyEntries { path, limit } => write!(f, "{}: the walk reached its limit of {limit} folder entries", path.display()), + Error::TooDeep { path, limit } => write!(f, "{}: more than {limit} folders deep", path.display()), + Error::HarnessOutputTooLarge { package, limit } => { + write!(f, "cargo test -p {package} -- --list: printed more than the limit of {limit} bytes") + } + Error::Write(e) => write!(f, "writing the table: {e}"), + } + } +} + +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Error::Io { source, .. } | Error::Write(source) => Some(source), + _ => None, + } + } +} + +/// Counts every workspace crate in `metadata_json` and writes the table to `out`. +/// +/// `cargo` builds the app's `cargo` command (program, folder and environment); in exact mode the +/// arguments `test -q -p -- --list` are added to it for each crate. Outside exact mode it is +/// not called. Nothing is written when an [`Error`] is returned before the table. +pub fn run(metadata_json: &[u8], options: &Options, cargo: impl FnMut() -> Command, out: &mut impl Write) -> Result { + let report = collect(metadata_json, options, cargo)?; + write_table(&report, out).map_err(Error::Write)?; + Ok(report) +} + +/// Counts every workspace crate in `metadata_json`, as [`run`] does, without writing anything. +pub fn collect(metadata_json: &[u8], options: &Options, mut cargo: impl FnMut() -> Command) -> Result { + let limits = &options.limits; + let packages = packages(metadata_json, limits.metadata_bytes)?; + let mut dirs = Vec::with_capacity(packages.len()); + for package in &packages { + let dir = package + .manifest_path + .parent() + .ok_or_else(|| Error::Metadata(format!("package {}: manifest path {} has no folder", package.name, package.manifest_path.display())))?; + dirs.push(dir.to_path_buf()); + } + let members = dirs.iter().cloned().collect(); + let mut walker = Walker { limits, members, entries: 0, bytes: 0 }; + let mut rows = Vec::new(); + let mut total = Counts::default(); + for (package, dir) in packages.into_iter().zip(dirs) { + let counts = walker.walk(&dir)?; + total.add(&counts); + let harness = if options.exact { Some(harness_count(&mut cargo, &package.name, limits.harness_output_bytes)?) } else { None }; + rows.push(Row { name: package.name, manifest_path: package.manifest_path, counts, harness }); + } + Ok(Report { rows, total, exact: options.exact }) +} + +/// Writes `report` as the `cargo xtask stats` table. +pub fn write_table(report: &Report, out: &mut impl Write) -> io::Result<()> { + let exact = report.exact; + let exact_col = if exact { format!(" {:>8}", "harness") } else { String::new() }; + writeln!(out, "{:<26} {:>6} {:>8} {:>7} {:>10}{exact_col}", "crate", "files", "lines", "#[test]", "proptest!")?; + let rule = "-".repeat(62 + if exact { 9 } else { 0 }); + writeln!(out, "{rule}")?; + for row in &report.rows { + let c = &row.counts; + let ex = match &row.harness { + None => String::new(), + Some(Harness::Listed(n)) => format!(" {n:>8}"), + Some(Harness::Failed(_)) => format!(" {:>8}", "error"), + }; + writeln!(out, "{:<26} {:>6} {:>8} {:>7} {:>10}{ex}", row.name, c.files, c.lines, c.tests, c.proptests)?; + } + writeln!(out, "{rule}")?; + let t = &report.total; + let ex = report.harness_total().map_or_else(String::new, |n| format!(" {n:>8}")); + writeln!(out, "{:<26} {:>6} {:>8} {:>7} {:>10}{ex}", "TOTAL", t.files, t.lines, t.tests, t.proptests)?; + if exact { + let failed: Vec<&str> = report.harness_failures().map(|r| r.name.as_str()).collect(); + if !failed.is_empty() { + writeln!(out, "\n(The harness total leaves out {} crate(s) whose test listing failed: {}.)", failed.len(), failed.join(", "))?; + } + } else { + writeln!(out, "\n(#[test] counts source attributes; macro-generated tests count once. Use --exact for harness counts.)")?; + } + Ok(()) +} + +/// A workspace package from `cargo metadata`. +struct Package { + name: String, + manifest_path: PathBuf, +} + +/// The workspace members of `cargo metadata` JSON, sorted by name and then by manifest path. +/// +/// Packages that are not workspace members (dependencies, when the JSON was made without +/// `--no-deps`) are left out. A member without a package entry, a package listed twice, and a missing +/// or non-string `id`, `name` or `manifest_path` are errors. +fn packages(json: &[u8], limit: usize) -> Result, Error> { + if json.len() > limit { + return Err(Error::Metadata(format!("{} bytes of JSON is more than the limit of {limit}", json.len()))); + } + let meta: serde_json::Value = serde_json::from_slice(json).map_err(|e| Error::Metadata(format!("not JSON: {e}")))?; + let field = |v: &serde_json::Value, what: &str| -> Result { + v.as_str().map(str::to_owned).ok_or_else(|| Error::Metadata(format!("{what} is missing or not a string"))) + }; + let members = meta["workspace_members"].as_array().ok_or_else(|| Error::Metadata("workspace_members is missing".into()))?; + let mut wanted = HashSet::new(); + for member in members { + wanted.insert(field(member, "a workspace_members entry")?); + } + let list = meta["packages"].as_array().ok_or_else(|| Error::Metadata("packages is missing".into()))?; + let mut found = HashSet::new(); + let mut paths = HashSet::new(); + let mut out = Vec::new(); + for p in list { + let id = field(&p["id"], "a package id")?; + if !wanted.contains(&id) { + continue; + } + let name = field(&p["name"], &format!("the name of package {id}"))?; + let manifest_path = PathBuf::from(field(&p["manifest_path"], &format!("the manifest_path of package {id}"))?); + if !found.insert(id.clone()) || !paths.insert(manifest_path.clone()) { + return Err(Error::Metadata(format!("package {id} ({}) is listed twice", manifest_path.display()))); + } + out.push(Package { name, manifest_path }); + } + if let Some(missing) = wanted.iter().find(|id| !found.contains(*id)) { + return Err(Error::Metadata(format!("workspace member {missing} has no package entry"))); + } + out.sort_by(|a, b| a.name.cmp(&b.name).then_with(|| a.manifest_path.cmp(&b.manifest_path))); + Ok(out) +} + +/// Walks crate folders within one run's entry and byte budgets. +struct Walker<'a> { + limits: &'a Limits, + /// The folders of every workspace member. A member's folder inside another member's folder is + /// counted in its own row only. + members: HashSet, + entries: usize, + bytes: u64, +} + +impl Walker<'_> { + /// Counts the `.rs` files under `root`, without following links. + fn walk(&mut self, root: &Path) -> Result { + let mut counts = Counts::default(); + let mut pending = vec![(root.to_path_buf(), 0usize)]; + while let Some((dir, depth)) = pending.pop() { + let io_err = |source| Error::Io { path: dir.clone(), source }; + for entry in std::fs::read_dir(&dir).map_err(io_err)? { + let entry = entry.map_err(io_err)?; + if self.entries >= self.limits.entries { + return Err(Error::TooManyEntries { path: dir.clone(), limit: self.limits.entries }); + } + self.entries += 1; + let path = entry.path(); + // The entry's own type: a link is never followed, so links to a parent folder, or + // many links to one folder, do not multiply the walk, and a link to a file outside + // the crate is not counted. + let kind = entry.file_type().map_err(|source| Error::Io { path: path.clone(), source })?; + let name = entry.file_name(); + let name = name.to_string_lossy(); + if kind.is_symlink() { + continue; + } + if kind.is_dir() { + // Nested fuzz workspaces and build output are not part of the crate. + if name == "target" || name == "fuzz" || name.starts_with('.') || self.members.contains(&path) { + continue; + } + if depth >= self.limits.depth { + return Err(Error::TooDeep { path, limit: self.limits.depth }); + } + pending.push((path, depth + 1)); + } else if kind.is_file() && name.ends_with(".rs") { + let src = self.read_source(&path)?; + counts.add_source(&src); + } + } + } + Ok(counts) + } + + /// A source file's text, read within the per-file and per-run byte limits. A file that grew + /// past a limit while it is read is an error too, since the read stops one byte past the limit. + fn read_source(&mut self, path: &Path) -> Result { + let per_file = self.limits.source_bytes; + let left = self.limits.total_source_bytes.saturating_sub(self.bytes); + let cap = per_file.min(left); + let io_err = |source| Error::Io { path: path.to_path_buf(), source }; + let file = File::open(path).map_err(io_err)?; + let Some(bytes) = read_bounded(file, cap).map_err(io_err)? else { + return Err(if per_file <= left { + Error::SourceTooLarge { path: path.to_path_buf(), limit: per_file } + } else { + Error::TotalTooLarge { path: path.to_path_buf(), limit: self.limits.total_source_bytes } + }); + }; + self.bytes = self.bytes.saturating_add(bytes.len() as u64); + String::from_utf8(bytes).map_err(|_| Error::NotUtf8(path.to_path_buf())) + } +} + +/// Everything `reader` gives, or `None` when that is more than `limit` bytes. +fn read_bounded(reader: impl Read, limit: u64) -> io::Result>> { + let mut buf = Vec::new(); + reader.take(limit.saturating_add(1)).read_to_end(&mut buf)?; + Ok((buf.len() as u64 <= limit).then_some(buf)) +} + +/// `#[test]` attributes and `proptest!` blocks (each block may hold many +/// property tests, and macro-generated tests are only counted once; use +/// `--exact` for harness-accurate numbers). +fn count_tests(src: &str) -> (usize, usize) { + let mut tests = 0; + let mut props = 0; + for line in src.lines() { + let t = line.trim_start(); + if t.starts_with("//") { + continue; + } + tests += t.matches("#[test]").count(); + if t.starts_with("proptest!") { + props += 1; + } + } + (tests, props) +} + +/// The tests a `-- --list` output names: the lines that end in `: test`. +fn count_listed(stdout: &[u8]) -> usize { + String::from_utf8_lossy(stdout).lines().filter(|l| l.ends_with(": test")).count() +} + +/// Runs `cargo test -q -p -- --list` and counts the tests it lists. Output past `limit` is +/// an error; a command that cannot start or fails is a [`Harness::Failed`] row. +fn harness_count(cargo: &mut impl FnMut() -> Command, package: &str, limit: u64) -> Result { + let mut cmd = cargo(); + cmd.args(["test", "-q", "-p", package, "--", "--list"]).stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::null()); + let mut child = match cmd.spawn() { + Ok(child) => child, + Err(e) => return Ok(Harness::Failed(format!("could not start: {e}"))), + }; + let read = match child.stdout.take() { + Some(stdout) => read_bounded(stdout, limit), + None => Err(io::Error::other("no output pipe")), + }; + let stdout = match read { + Ok(Some(stdout)) => stdout, + Ok(None) => { + stop(&mut child); + return Err(Error::HarnessOutputTooLarge { package: package.to_owned(), limit }); + } + Err(e) => { + stop(&mut child); + return Ok(Harness::Failed(format!("reading its output: {e}"))); + } + }; + match child.wait() { + Ok(status) if status.success() => Ok(Harness::Listed(count_listed(&stdout))), + Ok(status) => Ok(Harness::Failed(format!("exited with {status}"))), + Err(e) => Ok(Harness::Failed(format!("waiting for it: {e}"))), + } +} + +/// Ends a child whose output is no longer read. +fn stop(child: &mut std::process::Child) { + let _ = child.kill(); + let _ = child.wait(); +} + +#[cfg(test)] +mod tests { + use super::{Counts, Error, Harness, Limits, Options, Report, Row, Walker, collect, count_listed, count_tests, read_bounded, write_table}; + use std::collections::HashSet; + use std::path::{Path, PathBuf}; + use std::process::Command; + + /// A new, private directory: `create_dir` fails if the name exists (even as a link), so a + /// directory somebody else made in advance is never used. + fn private_dir(tag: &str) -> PathBuf { + let mut n = 0u32; + loop { + let dir = std::env::temp_dir().join(format!("craft-xtask-stats-{tag}-{}-{n}", std::process::id())); + let mut b = std::fs::DirBuilder::new(); + #[cfg(unix)] + std::os::unix::fs::DirBuilderExt::mode(&mut b, 0o700); + match b.create(&dir) { + Ok(()) => return dir, + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(e) => panic!("{e}"), + } + n += 1; + } + } + + fn walk_with(dir: &Path, limits: &Limits) -> Result { + Walker { limits, members: HashSet::new(), entries: 0, bytes: 0 }.walk(dir) + } + + fn walk(dir: &Path) -> Result { + walk_with(dir, &Limits::default()) + } + + /// `cargo metadata --no-deps` JSON for packages `(id, name, folder)`, all workspace members. + fn metadata(packages: &[(&str, &str, &Path)]) -> Vec { + let list: Vec<_> = + packages.iter().map(|(id, name, dir)| serde_json::json!({ "id": id, "name": name, "manifest_path": dir.join("Cargo.toml") })).collect(); + let ids: Vec<_> = packages.iter().map(|(id, _, _)| id).collect(); + serde_json::to_vec(&serde_json::json!({ "packages": list, "workspace_members": ids })).unwrap() + } + + fn no_cargo() -> Command { + panic!("cargo is only run in exact mode") + } + + #[test] + fn counts_attributes_and_proptest_blocks() { + let src = "#[test]\nfn a() {}\n// #[test] commented\n #[test]\nfn b() {}\nproptest! {\n}\n"; + assert_eq!(count_tests(src), (2, 1)); + } + + #[cfg(unix)] + #[test] + fn a_walk_does_not_follow_directory_links() { + let dir = private_dir("loop"); + std::fs::write(dir.join("a.rs"), "#[test]\n").unwrap(); + std::os::unix::fs::symlink(&dir, dir.join("loop")).unwrap(); + let c = walk(&dir); + let _ = std::fs::remove_dir_all(&dir); + let c = c.unwrap(); + assert_eq!((c.files, c.tests), (1, 1)); + } + + /// A directory alias does not cause its Rust source to be counted twice. + #[cfg(unix)] + #[test] + fn walk_does_not_follow_directory_symlinks() { + use std::os::unix::fs::symlink; + let base = private_dir("xtask"); + let real = base.join("real"); + std::fs::create_dir_all(&real).unwrap(); + std::fs::write(real.join("a.rs"), "fn a() {}\n").unwrap(); + // A directory symlink pointing back at `real` would be re-scanned if followed. + symlink(&real, base.join("alias")).unwrap(); + let c = walk(&base).unwrap(); + assert_eq!(c.files, 1, "the aliased directory was followed and counted twice"); + std::fs::remove_dir_all(&base).ok(); + } + + /// Traversal reports an exhausted entry budget and accepts a tree that exactly fits it. + #[test] + fn walk_reports_budget_exhaustion() { + let base = private_dir("stats-budget"); + std::fs::write(base.join("a.rs"), "fn a() {}\n").unwrap(); + let none = walk_with(&base, &Limits { entries: 0, ..Limits::default() }); + let one = walk_with(&base, &Limits { entries: 1, ..Limits::default() }); + std::fs::remove_dir_all(&base).unwrap(); + assert!(matches!(none, Err(Error::TooManyEntries { limit: 0, .. })), "{none:?}"); + assert_eq!(one.unwrap().files, 1); + } + + #[test] + fn a_source_past_the_size_limit_is_not_read() { + let dir = private_dir("size"); + let (small, big) = (dir.join("a.rs"), dir.join("b.rs")); + std::fs::write(&small, "fn a() {}\n").unwrap(); + std::fs::write(&big, "fn b() { }\n").unwrap(); + let limits = Limits { source_bytes: 10, ..Limits::default() }; + let mut walker = Walker { limits: &limits, members: HashSet::new(), entries: 0, bytes: 0 }; + let small_text = walker.read_source(&small); + let big_text = walker.read_source(&big); + let _ = std::fs::remove_dir_all(dir); + assert_eq!(small_text.unwrap(), "fn a() {}\n"); + assert!(matches!(big_text, Err(Error::SourceTooLarge { limit: 10, .. })), "{big_text:?}"); + } + + #[cfg(unix)] + #[test] + fn walk_counts_regular_sources_once_and_skips_links_and_big_files() { + let dir = private_dir("walk"); + let sub = dir.join("sub"); + std::fs::create_dir(&sub).unwrap(); + std::fs::write(dir.join("a.rs"), "#[test]\nfn a() {}\n").unwrap(); + std::fs::write(sub.join("b.rs"), "fn b() {}\n").unwrap(); + // A directory link back to the root and a file link are not followed. + std::os::unix::fs::symlink(&dir, sub.join("loop")).unwrap(); + std::os::unix::fs::symlink(dir.join("a.rs"), sub.join("link.rs")).unwrap(); + let linked = walk(&dir); + // A source over the size limit is an error, not a silently smaller count. + std::fs::write(dir.join("big.rs"), "x".repeat(64)).unwrap(); + let big = walk_with(&dir, &Limits { source_bytes: 32, ..Limits::default() }); + let _ = std::fs::remove_dir_all(dir); + let c = linked.unwrap(); + assert_eq!((c.files, c.tests), (2, 1)); + assert!(matches!(big, Err(Error::SourceTooLarge { limit: 32, .. })), "{big:?}"); + } + + #[test] + fn a_source_exactly_at_the_size_limit_is_read() { + let dir = private_dir("exact-size"); + std::fs::write(dir.join("a.rs"), "fn a() {}\n").unwrap(); + let at = walk_with(&dir, &Limits { source_bytes: 10, ..Limits::default() }); + let under = walk_with(&dir, &Limits { source_bytes: 9, ..Limits::default() }); + let _ = std::fs::remove_dir_all(dir); + assert_eq!(at.unwrap().files, 1); + assert!(matches!(under, Err(Error::SourceTooLarge { limit: 9, .. })), "{under:?}"); + } + + #[test] + fn the_total_source_limit_spans_every_file_of_the_run() { + let dir = private_dir("total"); + std::fs::write(dir.join("a.rs"), "fn a() {}\n").unwrap(); + std::fs::write(dir.join("b.rs"), "fn b() {}\n").unwrap(); + let fits = walk_with(&dir, &Limits { total_source_bytes: 20, ..Limits::default() }); + let over = walk_with(&dir, &Limits { total_source_bytes: 19, ..Limits::default() }); + let _ = std::fs::remove_dir_all(dir); + assert_eq!(fits.unwrap().files, 2); + assert!(matches!(over, Err(Error::TotalTooLarge { limit: 19, .. })), "{over:?}"); + } + + #[test] + fn a_folder_past_the_depth_limit_is_an_error() { + let dir = private_dir("depth"); + std::fs::create_dir_all(dir.join("a").join("b")).unwrap(); + std::fs::write(dir.join("a").join("b").join("c.rs"), "fn c() {}\n").unwrap(); + let fits = walk_with(&dir, &Limits { depth: 2, ..Limits::default() }); + let over = walk_with(&dir, &Limits { depth: 1, ..Limits::default() }); + let _ = std::fs::remove_dir_all(dir); + assert_eq!(fits.unwrap().files, 1); + assert!(matches!(&over, Err(Error::TooDeep { path, limit: 1 }) if path.ends_with("b")), "{over:?}"); + } + + #[test] + fn build_output_fuzz_and_hidden_entries_are_skipped() { + let dir = private_dir("skip"); + for skipped in ["target", "fuzz", ".git"] { + std::fs::create_dir(dir.join(skipped)).unwrap(); + std::fs::write(dir.join(skipped).join("x.rs"), "#[test]\n").unwrap(); + } + std::fs::write(dir.join("lib.rs"), "#[test]\n").unwrap(); + std::fs::write(dir.join("notes.rs.txt"), "#[test]\n").unwrap(); + // Only folders are skipped by a leading dot; a file named so is still a source. + std::fs::write(dir.join(".hidden.rs"), "#[test]\n").unwrap(); + let c = walk(&dir); + let _ = std::fs::remove_dir_all(dir); + assert_eq!(c.unwrap(), Counts { files: 2, lines: 2, tests: 2, proptests: 0 }); + } + + #[test] + fn a_source_that_is_not_utf8_is_an_error() { + let dir = private_dir("utf8"); + std::fs::write(dir.join("a.rs"), b"fn a() {}\n\xff\n").unwrap(); + let c = walk(&dir); + let _ = std::fs::remove_dir_all(dir); + assert!(matches!(&c, Err(Error::NotUtf8(path)) if path.ends_with("a.rs")), "{c:?}"); + } + + #[test] + fn a_missing_package_folder_is_an_error() { + let dir = private_dir("missing"); + let gone = dir.join("gone"); + let json = metadata(&[("gone 0.1.0", "gone", &gone)]); + let report = collect(&json, &Options::default(), no_cargo); + let _ = std::fs::remove_dir_all(dir); + assert!(matches!(&report, Err(Error::Io { path, .. }) if *path == gone), "{report:?}"); + } + + #[test] + fn metadata_over_its_limit_is_refused_before_it_is_parsed() { + let options = Options { limits: Limits { metadata_bytes: 4, ..Limits::default() }, ..Options::default() }; + let report = collect(b"not json at all", &options, no_cargo); + assert!(matches!(&report, Err(Error::Metadata(why)) if why.contains("limit")), "{report:?}"); + } + + #[test] + fn malformed_metadata_is_an_error() { + let dir = private_dir("malformed"); + let manifest = dir.join("Cargo.toml"); + let cases = [ + serde_json::json!({ "packages": [] }), + serde_json::json!({ "workspace_members": [] }), + serde_json::json!({ "workspace_members": [1], "packages": [] }), + serde_json::json!({ "workspace_members": ["a"], "packages": [] }), + serde_json::json!({ "workspace_members": ["a"], "packages": [{ "id": "a", "manifest_path": manifest }] }), + serde_json::json!({ "workspace_members": ["a"], "packages": [{ "id": "a", "name": "a" }] }), + serde_json::json!({ "workspace_members": ["a"], "packages": [{ "name": "a", "manifest_path": manifest }] }), + ]; + let results: Vec<_> = cases.iter().map(|c| collect(&serde_json::to_vec(c).unwrap(), &Options::default(), no_cargo)).collect(); + let not_json = collect(b"{", &Options::default(), no_cargo); + let _ = std::fs::remove_dir_all(dir); + for (case, result) in cases.iter().zip(&results) { + assert!(matches!(result, Err(Error::Metadata(_))), "{case}: {result:?}"); + } + assert!(matches!(not_json, Err(Error::Metadata(_))), "{not_json:?}"); + } + + #[test] + fn a_package_listed_twice_is_an_error() { + let dir = private_dir("twice"); + let twice = metadata(&[("a 0.1.0", "a", &dir), ("a 0.1.0", "a", &dir)]); + let same_folder = metadata(&[("a 0.1.0", "a", &dir), ("b 0.1.0", "b", &dir)]); + let twice = collect(&twice, &Options::default(), no_cargo); + let same_folder = collect(&same_folder, &Options::default(), no_cargo); + let _ = std::fs::remove_dir_all(dir); + assert!(matches!(&twice, Err(Error::Metadata(why)) if why.contains("twice")), "{twice:?}"); + assert!(matches!(&same_folder, Err(Error::Metadata(why)) if why.contains("twice")), "{same_folder:?}"); + } + + #[test] + fn packages_outside_the_workspace_are_not_walked() { + let dir = private_dir("deps"); + std::fs::write(dir.join("lib.rs"), "#[test]\n").unwrap(); + let dependency = dir.join("not-here"); + let json = serde_json::to_vec(&serde_json::json!({ + "workspace_members": ["a 0.1.0"], + "packages": [ + { "id": "dep 1.0.0", "name": "dep", "manifest_path": dependency.join("Cargo.toml") }, + { "id": "a 0.1.0", "name": "a", "manifest_path": dir.join("Cargo.toml") }, + ], + })) + .unwrap(); + let report = collect(&json, &Options::default(), no_cargo); + let _ = std::fs::remove_dir_all(dir); + let report = report.unwrap(); + assert_eq!(report.rows.iter().map(|r| r.name.as_str()).collect::>(), ["a"]); + assert_eq!(report.total.tests, 1); + } + + #[test] + fn rows_sort_by_name_and_the_total_adds_them() { + let dir = private_dir("order"); + for (name, src) in [("zeta", "#[test]\n#[test]\n"), ("alpha", "proptest! {\n}\n")] { + std::fs::create_dir(dir.join(name)).unwrap(); + std::fs::write(dir.join(name).join("lib.rs"), src).unwrap(); + } + let json = metadata(&[("z 0.1.0", "zeta", &dir.join("zeta")), ("a 0.1.0", "alpha", &dir.join("alpha"))]); + let report = collect(&json, &Options::default(), no_cargo); + let _ = std::fs::remove_dir_all(dir); + let report = report.unwrap(); + assert_eq!(report.rows.iter().map(|r| r.name.as_str()).collect::>(), ["alpha", "zeta"]); + assert_eq!(report.total, Counts { files: 2, lines: 4, tests: 2, proptests: 1 }); + assert_eq!(report.harness_total(), None); + } + + #[test] + fn a_nested_workspace_member_is_counted_in_its_own_row_only() { + let dir = private_dir("nested"); + std::fs::create_dir_all(dir.join("src")).unwrap(); + std::fs::write(dir.join("src").join("main.rs"), "fn main() {}\n").unwrap(); + std::fs::create_dir_all(dir.join("xtask").join("src")).unwrap(); + std::fs::write(dir.join("xtask").join("src").join("main.rs"), "#[test]\nfn t() {}\n").unwrap(); + let json = metadata(&[("app 0.1.0", "app", &dir), ("xtask 0.1.0", "xtask", &dir.join("xtask"))]); + let report = collect(&json, &Options::default(), no_cargo); + let _ = std::fs::remove_dir_all(dir); + let report = report.unwrap(); + let rows: Vec<_> = report.rows.iter().map(|r| (r.name.as_str(), r.counts.files, r.counts.tests)).collect(); + assert_eq!(rows, [("app", 1, 0), ("xtask", 1, 1)]); + assert_eq!((report.total.files, report.total.tests), (2, 1)); + } + + fn row(name: &str, counts: Counts, harness: Option) -> Row { + Row { name: name.into(), manifest_path: PathBuf::from(name).join("Cargo.toml"), counts, harness } + } + + fn table(report: &Report) -> String { + let mut out = Vec::new(); + write_table(report, &mut out).unwrap(); + String::from_utf8(out).unwrap() + } + + #[test] + fn the_table_keeps_its_columns() { + let counts = Counts { files: 3, lines: 120, tests: 7, proptests: 1 }; + let report = Report { rows: vec![row("app-core", counts, None)], total: counts, exact: false }; + let expected = concat!( + "crate files lines #[test] proptest!\n", + "--------------------------------------------------------------\n", + "app-core 3 120 7 1\n", + "--------------------------------------------------------------\n", + "TOTAL 3 120 7 1\n", + "\n(#[test] counts source attributes; macro-generated tests count once. Use --exact for harness counts.)\n", + ); + assert_eq!(table(&report), expected); + } + + #[test] + fn the_exact_table_marks_failed_listings_and_leaves_them_out_of_the_total() { + let counts = Counts { files: 1, lines: 2, tests: 1, proptests: 0 }; + let report = Report { + rows: vec![row("a", counts, Some(Harness::Listed(4))), row("b", counts, Some(Harness::Failed("exited with 101".into())))], + total: Counts { files: 2, lines: 4, tests: 2, proptests: 0 }, + exact: true, + }; + let expected = concat!( + "crate files lines #[test] proptest! harness\n", + "-----------------------------------------------------------------------\n", + "a 1 2 1 0 4\n", + "b 1 2 1 0 error\n", + "-----------------------------------------------------------------------\n", + "TOTAL 2 4 2 0 4\n", + "\n(The harness total leaves out 1 crate(s) whose test listing failed: b.)\n", + ); + assert_eq!(table(&report), expected); + assert_eq!(report.harness_total(), Some(4)); + assert_eq!(report.harness_failures().map(|r| r.name.as_str()).collect::>(), ["b"]); + } + + #[test] + fn listed_tests_are_the_lines_that_end_in_test() { + assert_eq!(count_listed(b"a::one: test\na::two: test\nbench: benchmark\n\n2 tests, 1 benchmark\n"), 2); + assert_eq!(count_listed(b""), 0); + } + + #[test] + fn a_bounded_read_refuses_more_than_its_limit() { + assert_eq!(read_bounded(&b"abcd"[..], 4).unwrap().as_deref(), Some(&b"abcd"[..])); + assert_eq!(read_bounded(&b"abcde"[..], 4).unwrap(), None); + assert_eq!(read_bounded(&b""[..], 0).unwrap().as_deref(), Some(&b""[..])); + } + + /// A stand-in for `cargo`: `sh -c