From acfedcd1486d8bc505cd9d573868fed3e62c38e1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 6 Nov 2026 23:19:28 -0800 Subject: [PATCH 001/786] 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 20368232acacc11bb5b83817ca9a62be80c6a6a0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 7 Nov 2026 08:56:01 -0800 Subject: [PATCH 002/786] linesweeper: nearly coincident segments no longer loop forever at one y When nearly coincident segments do not compare transitively, handling one intersection queued another pair at the same y again, and the pairs cycled forever through the same positions while segs_needing_positions grew. Five circles of radius 50, each moved by (7e-7, 3.5e-7), hang Sweeper::next_line this way. next_line now handles a pair at most once per sweep line for each pair of positions the two segments hold. A repeat is queued at the pair's next order change instead, when that comes before both segments end. The repeated_intersections_at_one_y test sweeps the five circles. Test builds panic after n^4 intersection events on one sweep line, so the test fails instead of hanging without the 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 | 69 +++++++++++++++++++++- 4 files changed, 88 insertions(+), 13 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..3bc5964f7f 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` | `Sweeper::next_line` handles a pair of segments at most once per sweep line for each pair of positions the two segments hold. A pair queued again at the same `y` and positions is queued at the pair's next order change instead, when that comes before both segments end. Nearly coincident segments whose comparisons are not transitive used to queue the same pairs at one `y` forever while memory grew. The `repeated_intersections_at_one_y` test sweeps five circles 7e-7 apart; test builds panic after `n^4` intersection events on one sweep line. | `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..3bee04a7b7 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`, `Sweeper::next_line` handles a pair of segments at most once per sweep line for each pair of positions they hold and queues a repeat at the pair's next order change, so nearly coincident segments whose comparisons are not transitive no longer loop forever at one y." + ], "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": "e9c93858dc54dad40f2c4d4965243b9fc19a5ec64eb8bcd561aedb5c7596bf08" }, { "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..de6ae66ba9 100644 --- a/vendor/linesweeper/src/sweep/sweep_line.rs +++ b/vendor/linesweeper/src/sweep/sweep_line.rs @@ -7,6 +7,8 @@ use std::cell::{RefCell, RefMut}; #[cfg(feature = "slow-asserts")] use std::ops::DerefMut; +use rustc_hash::FxHashSet; + use crate::{ curve::{self, CurveInteraction, CurveOrder, Order}, geom::Segment, @@ -433,8 +435,48 @@ impl<'segs> Sweeper<'segs> { } // Process all the intersection events at this y. + // + // Craft patch (repeated intersection): when nearly coincident segments + // do not compare transitively, handling one pair can queue another + // pair at this same y again, and the pairs can cycle forever through + // the same positions. A pair is handled at most once per y for each + // pair of positions it holds in the sweep line; a repeat is queued + // again at the pair's next order change instead, if that comes before + // both ends. + let mut handled = FxHashSet::default(); + #[cfg(test)] + let mut events_at_y = 0usize; while let Some(intersection) = self.events.next_intersection_at_y(y) { - self.handle_intersection(intersection.left, intersection.right); + #[cfg(test)] + { + events_at_y += 1; + let n = self.segments.len(); + assert!( + events_at_y <= n.saturating_pow(4), + "{events_at_y} intersection events at y={y:?} for {n} segments" + ); + } + let (left, right) = (intersection.left, intersection.right); + let positions = (self.line.position(left), self.line.position(right)); + if !handled.insert((left, right, positions)) { + let next_y = self + .compare_segments(left, right) + .iter() + .map(|(_, end, _)| end) + .find(|end| *end > y); + if let Some(next_y) = next_y + && next_y < self.segments[left].end().y + && next_y < self.segments[right].end().y + { + self.events.push(IntersectionEvent { + y: next_y, + left, + right, + }); + } + continue; + } + self.handle_intersection(left, right); self.check_invariants(); } @@ -2055,6 +2097,31 @@ mod tests { insta::assert_ron_snapshot!(snapshot_outputs(segs, 0.1)); } + // Five circles, each moved by (7e-7, 3.5e-7) from the one before, have + // nearly coincident curves whose comparisons are not transitive. Their + // sweep used to queue the same intersections at one y forever. The event + // count check in `next_line` stops a test build at n^4 events on one + // sweep line. + #[test] + fn repeated_intersections_at_one_y() { + use kurbo::{Circle, Shape}; + + let mut circles = BezPath::new(); + for i in 0..5 { + let center = (500.0 + i as f64 * 7e-7, 500.0 + i as f64 * 3.5e-7); + circles.extend(Circle::new(center, 50.0).path_elements(0.1)); + } + let mut segs = Segments::default(); + segs.add_bez_path(&circles).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!(lines > 0); + } + #[test] fn conservative_line_order() { // Here's an example where c0 gets "ish" with c1 in the middle, c0 gets "ish" with c2 From e81c48f1f1cc25fc45b54d4b601ee112ee370297 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 7 Nov 2026 09:16:01 -0800 Subject: [PATCH 003/786] linesweeper: a delayed intersection at a segment's end no longer panics Sweeper::handle_intersection delays an intersection when a segment between the pair compares out of order, and queued the delayed event at y1.min(y2) without checking the segments' ends. When that y was the end of one of the two segments, handling the event there panicked in CurveOrder::entry_at, which finds no order entry ending after y. The delayed event is now queued only when its y is before the ends of both segments, the same rule the intersection scans use. The delayed_intersection_at_a_segment_end test sweeps three wide, flat contours (x up to 1e12, y below 1e-3) through Topology::from_path and expects 4 contours; without the change it panics at src/curve/mod.rs:357. README.craft.md, SOURCE.json and NOTICE record the change as a local patch. --- NOTICE | 6 +-- vendor/linesweeper/README.craft.md | 1 + vendor/linesweeper/SOURCE.json | 5 ++- vendor/linesweeper/src/sweep/sweep_line.rs | 43 +++++++++++++++++++--- 4 files changed, 45 insertions(+), 10 deletions(-) diff --git a/NOTICE b/NOTICE index 70c163182c..f914acf874 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 one local patch. Its manifest names Joe Neeman -as author, and its LICENSE-MIT reads "Copyright (c) 2018 Raph Levien". See +vendor/linesweeper with its upstream license files and two local patches. 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, the local -change and the files left out. +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 3bc5964f7f..2d5c5a4f4c 100644 --- a/vendor/linesweeper/README.craft.md +++ b/vendor/linesweeper/README.craft.md @@ -16,6 +16,7 @@ holds `upstream_revision`. `local_patches` describes each local patch. | File | Change | |---|---| | `src/sweep/sweep_line.rs` | `Sweeper::next_line` handles a pair of segments at most once per sweep line for each pair of positions the two segments hold. A pair queued again at the same `y` and positions is queued at the pair's next order change instead, when that comes before both segments end. Nearly coincident segments whose comparisons are not transitive used to queue the same pairs at one `y` forever while memory grew. The `repeated_intersections_at_one_y` test sweeps five circles 7e-7 apart; test builds panic after `n^4` intersection events on one sweep line. | +| `src/sweep/sweep_line.rs` | `Sweeper::handle_intersection` queues a delayed intersection only when its `y` is before the ends of both segments, as the intersection scans do. A delayed intersection at a segment's end used to panic in `CurveOrder::entry_at`. The `delayed_intersection_at_a_segment_end` test sweeps three wide, flat contours whose sweep delayed an intersection to a segment's end. | `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 3bee04a7b7..b9d1cc8a76 100644 --- a/vendor/linesweeper/SOURCE.json +++ b/vendor/linesweeper/SOURCE.json @@ -8,7 +8,8 @@ "upstream_revision": "824b0791a750f7b27b8edcbb6c6244d0e629875e", "upstream_directory": "", "local_patches": [ - "In `src/sweep/sweep_line.rs`, `Sweeper::next_line` handles a pair of segments at most once per sweep line for each pair of positions they hold and queues a repeat at the pair's next order change, so nearly coincident segments whose comparisons are not transitive no longer loop forever at one y." + "In `src/sweep/sweep_line.rs`, `Sweeper::next_line` handles a pair of segments at most once per sweep line for each pair of positions they hold and queues a repeat at the pair's next order change, so nearly coincident segments whose comparisons are not transitive no longer loop forever at one y.", + "In `src/sweep/sweep_line.rs`, `Sweeper::handle_intersection` queues a delayed intersection only when its y is before the ends of both segments, so a delayed intersection at a segment's end no longer panics in `CurveOrder::entry_at`." ], "files": [ { "path": ".cargo_vcs_info.json", "source_sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc", "source_git_blob": null, "sha256": "47fba6a9dbdf445a5c97f783c9be62093035f9d5e5cdc2cf3216ad8259bcd8fc" }, @@ -64,7 +65,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": "e9c93858dc54dad40f2c4d4965243b9fc19a5ec64eb8bcd561aedb5c7596bf08" }, + { "path": "src/sweep/sweep_line.rs", "source_sha256": "822b261f682911ea0c0370eaf17d9201a1e639b315359dcb6a3b877a229816e3", "source_git_blob": null, "sha256": "75b56bf0262b1989ef056a851522857f97806721d1e2f2f73e4e765ff8b17da7" }, { "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 de6ae66ba9..d5bcc02565 100644 --- a/vendor/linesweeper/src/sweep/sweep_line.rs +++ b/vendor/linesweeper/src/sweep/sweep_line.rs @@ -807,11 +807,20 @@ impl<'segs> Sweeper<'segs> { let (_, y2, j_right_order) = self.compare_segments(seg_j_idx, right).entry_at(self.y); if j_right_order == Order::Left { - self.events.push(IntersectionEvent { - y: y1.min(y2), - left, - right, - }); + // Craft patch (delayed intersection at an end): the + // delayed event is queued only when it comes before + // both ends, as in the scans that queue intersections. + // An event at an end makes `entry_at` panic. + let delayed_y = y1.min(y2); + if delayed_y < self.segments[left].end().y + && delayed_y < self.segments[right].end().y + { + self.events.push(IntersectionEvent { + y: delayed_y, + left, + right, + }); + } return; } @@ -2122,6 +2131,30 @@ mod tests { assert!(lines > 0); } + // Wide, flat shapes (x up to 1e12, y below 1e-3) whose sweep delays an + // intersection to exactly the end of one of its segments. Handling the + // delayed event there used to panic in `CurveOrder::entry_at`. + #[test] + fn delayed_intersection_at_a_segment_end() { + let path = BezPath::from_svg( + "M501064307397.10095,0.0009848607387959033 \ + L106201373767.89085,0.0006710749289289315 \ + C417687393573.9515,0.0004160951440753873 304110132978.1276,0.00038371209900965467 283049238030.7473,0.000948649831345387 Z \ + M198139564203.8839,0.00026113917505891313 \ + Q925286056821.7639,0.0001263989183887222 706548805870.0378,0.0005146463318510499 \ + C481577318901.41956,0.000572151300098751 38743762463.54683,0.000935423896736907 333105974166.1391,0.00039093790825889355 \ + C838434423640.872,0.0005209836434131965 252410595074.9046,0.00021445561842374318 649987299514.814,0.0005284926072103142 Z \ + M425570790862.5174,0.0002275798137344196 \ + C643548474934.2626,0.00016915804040910177 896953683318.0679,0.000915403101629657 231887429918.8749,0.0004275752018309249 \ + Q960890561259.0065,0.0005825265493017958 735584660921.8835,0.000238439768009997 \ + Q676310419912.8419,0.00003744704696150181 803912734785.0077,0.0008084425285905149 Z", + ) + .unwrap(); + let top = + crate::topology::Topology::::from_path(&path, 1.3655076163260652e-2).unwrap(); + assert_eq!(top.contours(|w| *w != 0).contours().count(), 4); + } + #[test] fn conservative_line_order() { // Here's an example where c0 gets "ish" with c1 in the middle, c0 gets "ish" with c2 From dec46890b7f87b4ec24b44ff7036c38680fc0dc1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 7 Nov 2026 10:11:10 -0800 Subject: [PATCH 004/786] 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 005/786] 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 006/786] 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 18b61d7ab088a8a53799e2a3dff0f94bf9f7094a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 11:24:24 -0800 Subject: [PATCH 007/786] linesweeper: neighboring segments share stored winding numbers Topology stored a full copy of both sides' winding numbers for every output segment, although a segment's clockwise side is the same value as the previous segment's counter-clockwise side. With a winding number type that holds one entry per covering input, each value was stored twice. Each side is now an Arc, and the sweep gives neighboring segments the same Arc. For 500 squares that all cross each other, building the Topology peaked at 2,769.4 MB and now peaks at 2,102.5 MB, with the same contours. The public accessors do not change. A Topology is Send and Sync only when W is both. --- vendor/linesweeper/README.craft.md | 20 ++-- vendor/linesweeper/SOURCE.json | 6 +- vendor/linesweeper/src/topology.rs | 151 ++++++++++++++++++++++++----- 3 files changed, 146 insertions(+), 31 deletions(-) diff --git a/vendor/linesweeper/README.craft.md b/vendor/linesweeper/README.craft.md index f683ca53de..f24a3828a6 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/topology.rs` | `Topology` stores each side of an output segment's winding numbers behind an `Arc`, and the sweep gives a segment's clockwise side and the previous segment's counter-clockwise side the same `Arc`. Before, every segment held its own copy of both sides, so a winding number type that allocates (one entry per covering input) stored each value twice. For 500 squares that all cross each other, with a winding number type like `craft-prepress`'s, building the `Topology` peaked at 2,769.4 MB and now peaks at 2,102.5 MB, and `craft_prepress::flatten::geom::regions` peaked at 3,535.2 MB and now peaks at 2,842.1 MB, with the same regions. `winding_clockwise`, `winding_counter_clockwise` and `HalfSegmentWindingNumbers` do not change. A `Topology` is now `Send` and `Sync` only when `W` is both `Send` and `Sync`. Code comments label the changes `Craft patch (winding storage)`. The `neighboring_segments_share_winding_numbers` test checks the sharing, and `staggered_squares_winding_numbers_count_the_covering_squares` checks the areas covered by each number of squares. | `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..d21764ee7b 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/topology.rs`, `Topology` stores each side of an output segment's winding numbers behind an `Arc`, and the sweep gives a segment's clockwise side and the previous segment's counter-clockwise side the same `Arc`. Without it, every segment holds its own copy of both sides: for 500 squares that all cross each other, `Topology::from_paths` with a winding number type that holds one entry per covering input peaks at 2,769.4 MB and `craft_prepress::flatten::geom::regions` at 3,535.2 MB. With it they peak at 2,102.5 MB and 2,842.1 MB, with the same contours and regions. A `Topology` is `Send` and `Sync` only when `W` is both. The tests `topology::tests::neighboring_segments_share_winding_numbers` and `topology::tests::staggered_squares_winding_numbers_count_the_covering_squares` cover it." + ], "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" }, @@ -63,7 +65,7 @@ { "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/topology.rs", "source_sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b", "source_git_blob": null, "sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b" }, + { "path": "src/topology.rs", "source_sha256": "9c9b48bc3853884425127e2d64e8ed957ba0d27e1696e2c457e95282e52d6a5b", "source_git_blob": null, "sha256": "ffaab7e48caa441630e794fb2f1e9287aa5f370c3eaf360ee265b5d49fbc02a4" }, { "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" }, { "path": "tests/fonts.rs", "source_sha256": "081604ebf560a19ff0427efd9a17eaaa0a3b46ad0bf58323fd6e21b6c0764400", "source_git_blob": null, "sha256": "081604ebf560a19ff0427efd9a17eaaa0a3b46ad0bf58323fd6e21b6c0764400" }, diff --git a/vendor/linesweeper/src/topology.rs b/vendor/linesweeper/src/topology.rs index 8420d015a5..3a0ef76bed 100644 --- a/vendor/linesweeper/src/topology.rs +++ b/vendor/linesweeper/src/topology.rs @@ -4,6 +4,7 @@ //! like winding number computations and boolean operations. use std::collections::VecDeque; +use std::sync::Arc; use kurbo::{BezPath, ParamCurve, Rect, Shape}; @@ -161,14 +162,6 @@ pub struct HalfSegmentWindingNumbers { pub clockwise: W, } -impl HalfSegmentWindingNumbers { - /// A half-segment's winding numbers are trivial if they're the same on both sides. - /// In this case, the segment is invisible to the topology of the sets. - fn is_trivial(&self) -> bool { - self.counter_clockwise == self.clockwise - } -} - impl std::fmt::Debug for HalfSegmentWindingNumbers { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( @@ -179,6 +172,52 @@ impl std::fmt::Debug for HalfSegmentWindingNumbers { } } +// Craft patch (winding storage). +/// The winding numbers a topology stores for an output segment: the two sides of +/// [`HalfSegmentWindingNumbers`], each behind an `Arc`. +/// +/// The sweep builds each segment's winding numbers from a running winding number, +/// so a segment's clockwise side is the same value as the counter-clockwise side +/// of the segment before it. The two segments hold clones of one `Arc`, and each +/// distinct winding number is stored once. +#[derive(Clone)] +struct SegmentWindingNumbers { + counter_clockwise: Arc, + clockwise: Arc, +} + +impl SegmentWindingNumbers { + /// A half-segment's winding numbers are trivial if they're the same on both sides. + /// In this case, the segment is invisible to the topology of the sets. + fn is_trivial(&self) -> bool { + Arc::ptr_eq(&self.counter_clockwise, &self.clockwise) + || self.counter_clockwise == self.clockwise + } +} + +impl std::fmt::Debug for SegmentWindingNumbers { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "cw {:?} | cc {:?}", + self.clockwise, self.counter_clockwise + ) + } +} + +// Craft patch (winding storage): serialized as a `HalfSegmentWindingNumbers`, +// which the snapshot tests record. +#[cfg(test)] +impl serde::Serialize for SegmentWindingNumbers { + fn serialize(&self, serializer: S) -> Result { + use serde::ser::SerializeStruct; + let mut s = serializer.serialize_struct("HalfSegmentWindingNumbers", 2)?; + s.serialize_field("counter_clockwise", &*self.counter_clockwise)?; + s.serialize_field("clockwise", &*self.clockwise)?; + s.end() + } +} + /// An index into the set of output segments. /// /// There's no compile-time magic preventing misuse of this index, but you @@ -412,7 +451,10 @@ pub struct Topology { /// `HalfSegmentWindingNumbers` for each `HalfOutputSegIdx`. But since the two halves of /// the winding numbers are determined by one another, we only store the winding numbers /// for the start half of the output segment. - winding: OutputSegVec>, + /// + /// Craft patch (winding storage): neighboring segments share each side's + /// value through an `Arc` (see [`SegmentWindingNumbers`]). + winding: OutputSegVec>, /// The output points. points: PointVec, /// The segment endpoints, as indices into `points`. @@ -696,7 +738,7 @@ impl Topology { &mut self, idx: SegIdx, p: PointIdx, - winding: HalfSegmentWindingNumbers, + winding: SegmentWindingNumbers, horizontal: bool, positively_oriented: bool, ) -> OutputSegIdx { @@ -734,8 +776,11 @@ impl Topology { mut scan_west: Option, ) { let y = pos.line().y(); - let mut winding = scan_west - .map(|idx| self.winding[idx].counter_clockwise.clone()) + // Craft patch (winding storage): `winding` and `w` below are shared with + // the segments that store them, and each step makes a new `Arc` instead + // of changing the shared value. + let mut winding: Arc = scan_west + .map(|idx| Arc::clone(&self.winding[idx].counter_clockwise)) .unwrap_or_default(); // A re-usable buffer for holding temporary lists of segment indices. We @@ -771,12 +816,14 @@ impl Topology { // Also, calculate their winding numbers and update `winding`. seg_buf.clear(); for new_seg in connected_segs.connected_down() { - let prev_winding = winding.clone(); + let prev_winding = Arc::clone(&winding); let orientation = segments.positively_oriented(new_seg); - winding += W::single(self.tag[new_seg], !orientation); - let windings = HalfSegmentWindingNumbers { + let mut next = W::clone(&winding); + next += W::single(self.tag[new_seg], !orientation); + winding = Arc::new(next); + let windings = SegmentWindingNumbers { clockwise: prev_winding, - counter_clockwise: winding.clone(), + counter_clockwise: Arc::clone(&winding), }; let half_seg = self.new_half_seg(new_seg, p, windings, false, orientation); self.scan_west[half_seg] = scan_west; @@ -803,14 +850,16 @@ impl Topology { // We don't want to update our "global" winding number state because that's supposed // to keep track of the winding number below the current sweep line. - let mut w = winding.clone(); + let mut w = Arc::clone(&winding); seg_buf.clear(); for (new_seg, same_orientation) in hsegs { - let prev_w = w.clone(); + let prev_w = Arc::clone(&w); let orientation = same_orientation == segments.positively_oriented(new_seg); - w += W::single(self.tag[new_seg], !orientation); - let windings = HalfSegmentWindingNumbers { - counter_clockwise: w.clone(), + let mut next = W::clone(&w); + next += W::single(self.tag[new_seg], !orientation); + w = Arc::new(next); + let windings = SegmentWindingNumbers { + counter_clockwise: Arc::clone(&w), clockwise: prev_w, }; let half_seg = self.new_half_seg(new_seg, p, windings, true, orientation); @@ -917,8 +966,10 @@ impl Topology { // coincident then they'd better both be first halves. debug_assert!(cw_nbr.first_half); self.delete(idx); + // Craft patch (winding storage): share the value instead of + // copying it. self.winding[cw_nbr.idx].counter_clockwise = - self.winding[idx].counter_clockwise.clone(); + Arc::clone(&self.winding[idx].counter_clockwise); if self.winding[cw_nbr.idx].is_trivial() { self.delete(cw_nbr.idx); @@ -2288,6 +2339,62 @@ mod tests { insta::assert_ron_snapshot!(top); } + // Craft patch (winding storage). + /// `n` squares of side `n`, each one step right and down from the last, so the + /// edges of every square cross the edges of every other square. + fn staggered_squares(n: usize) -> Vec { + use kurbo::Shape as _; + (0..n) + .map(|i| { + let (i, n) = (i as f64, n as f64); + kurbo::Rect::new(i, i + 0.25, i + n, i + n + 0.25).to_path(0.1) + }) + .collect() + } + + // Craft patch (winding storage). + #[test] + fn neighboring_segments_share_winding_numbers() { + let paths = staggered_squares(8); + let top = Topology::::from_paths(paths.iter().map(|p| (p, ())), 1e-6).unwrap(); + let mut sides = 0; + let mut stored = std::collections::HashSet::new(); + for idx in top.segment_indices() { + let w = &top.winding[idx]; + for side in [&w.clockwise, &w.counter_clockwise] { + sides += 1; + stored.insert(std::sync::Arc::as_ptr(side)); + } + } + // A segment's clockwise side is the counter-clockwise side of the segment + // before it in the sweep, so most sides share a stored value. + assert!( + stored.len() * 3 <= sides * 2, + "{} winding numbers stored for {sides} sides", + stored.len() + ); + } + + // Craft patch (winding storage). + #[test] + fn staggered_squares_winding_numbers_count_the_covering_squares() { + use kurbo::Shape as _; + let paths = staggered_squares(8); + let top = Topology::::from_paths(paths.iter().map(|p| (p, ())), 1e-6).unwrap(); + for k in 1..=8 { + // The points covered by at least `k` squares form `9 - k` squares of + // side `9 - k`, each one step from the last. + let s = f64::from(9 - k); + let expected = s * s + (s - 1.0) * (2.0 * s - 1.0); + let contours = top.contours(|w| w.abs() >= k); + let area: f64 = contours.contours().map(|c| c.path.area().abs()).sum(); + assert!( + (area - expected).abs() < 1e-9, + "k = {k}: {area} != {expected}" + ); + } + } + #[test] fn diamond() { let segs = [[p(0.0, 0.0), p(1.0, 1.0), p(0.0, 2.0), p(-1.0, 1.0)]]; From d1d19c6edf2c01ca014794e331681643f1837a81 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 11:46:48 -0800 Subject: [PATCH 008/786] linesweeper: adding many paths no longer sorts the whole arena on every call Segments::add_bez_path and add_non_closed_bez_path called update_enter_exit, which sorted the whole enter and exit vectors on every call, so adding n paths one at a time took time quadratic in n. - update_enter_exit sorts only the new entrances and exits and merges them into the sorted ones, in the order a stable sort of the whole vector gave before. - Segments::add_bez_paths and add_non_closed_bez_paths add a collection of paths and merge once. On an open subpath, add_bez_paths keeps the paths before it and adds nothing of that path or later ones. - README.craft.md, SOURCE.json and NOTICE record the local patch. --- NOTICE | 6 +- vendor/linesweeper/README.craft.md | 22 +- vendor/linesweeper/SOURCE.json | 6 +- vendor/linesweeper/src/segments.rs | 344 ++++++++++++++++++++++++++++- 4 files changed, 358 insertions(+), 20 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..84022c1664 100644 --- a/vendor/linesweeper/README.craft.md +++ b/vendor/linesweeper/README.craft.md @@ -1,15 +1,23 @@ # 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 +changes listed under Local changes. `.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 files under Local changes 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 change. + +## Local changes + +| Change | Code comment label | Touches | Tests | +|---|---|---|---| +| Adding paths one at a time no longer sorts every entrance and exit in the arena on each call: the new entries are sorted and merged into the sorted ones, in the same order as before. `Segments::add_bez_paths` and `Segments::add_non_closed_bez_paths` add many paths and merge once; on an open subpath, `add_bez_paths` keeps the paths before it and adds nothing of that path or later ones | `Craft patch (batch paths)` | `src/segments.rs` | `segments::tests::add_bez_paths_matches_repeated_add_bez_path`, `segments::tests::add_non_closed_bez_paths_matches_repeated_add_non_closed_bez_path`, `segments::tests::add_bez_paths_stops_at_an_open_path`, `segments::tests::merged_entrances_and_exits_match_a_full_sort`, `segments::tests::paths_added_in_height_order_are_not_sorted_again` | + +Every change here updates this table and `SOURCE.json` in the same commit. `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..6acc2a48d7 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/segments.rs`, `update_enter_exit` sorts only the new entrances and exits and merges them into the sorted ones, in the order a stable sort of the whole list gives, instead of sorting the whole list on every call. `Segments::add_bez_paths` and `Segments::add_non_closed_bez_paths` add a collection of paths and merge once, as `add_closed_polylines` and `Topology::from_paths` already do, and `add_bez_paths` removes the segments of a path with an open subpath before it returns the error. Without it, adding 2,000 triangles one at a time from the top row down takes 6,006,993 entrance comparisons, and adding n paths one at a time takes time quadratic in n. The tests `segments::tests::add_bez_paths_matches_repeated_add_bez_path`, `segments::tests::add_non_closed_bez_paths_matches_repeated_add_non_closed_bez_path`, `segments::tests::add_bez_paths_stops_at_an_open_path`, `segments::tests::merged_entrances_and_exits_match_a_full_sort` and `segments::tests::paths_added_in_height_order_are_not_sorted_again` cover it." + ], "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" }, @@ -42,7 +44,7 @@ { "path": "src/order.rs", "source_sha256": "7e5b04eae8af134abb032e995f1d3c2ac473822923dfee8d463d9ade6ffeb596", "source_git_blob": null, "sha256": "7e5b04eae8af134abb032e995f1d3c2ac473822923dfee8d463d9ade6ffeb596" }, { "path": "src/perturbation.rs", "source_sha256": "fa274a822bbdf65f8e53e403eef78034dd87964b3f1d3134a064df4ec8cef9c5", "source_git_blob": null, "sha256": "fa274a822bbdf65f8e53e403eef78034dd87964b3f1d3134a064df4ec8cef9c5" }, { "path": "src/position.rs", "source_sha256": "dfa70840805ecccf5b7eb6122921e46ca60c24cb7b3c17f3b55ffc2549368ab0", "source_git_blob": null, "sha256": "dfa70840805ecccf5b7eb6122921e46ca60c24cb7b3c17f3b55ffc2549368ab0" }, - { "path": "src/segments.rs", "source_sha256": "379f9455120492d237cb5a62b3fc06da018a72e2eb75bbfcd61b4cce501d9bbc", "source_git_blob": null, "sha256": "379f9455120492d237cb5a62b3fc06da018a72e2eb75bbfcd61b4cce501d9bbc" }, + { "path": "src/segments.rs", "source_sha256": "379f9455120492d237cb5a62b3fc06da018a72e2eb75bbfcd61b4cce501d9bbc", "source_git_blob": null, "sha256": "717ef16f77623ae020307dff376032c9948aff2f7008bd797507b9f67095d6d0" }, { "path": "src/snapshots/linesweeper__tests__empty_horizontals.snap", "source_sha256": "e319881853e889badf6524f19af4cd6f112e8dd71bdc516826f4463134a82244", "source_git_blob": null, "sha256": "e319881853e889badf6524f19af4cd6f112e8dd71bdc516826f4463134a82244" }, { "path": "src/snapshots/linesweeper__tests__two_squares.snap", "source_sha256": "01961e0311a5af3b8f13eb52a2a7112560c47cf86771c04e40475dc6f15a0846", "source_git_blob": null, "sha256": "01961e0311a5af3b8f13eb52a2a7112560c47cf86771c04e40475dc6f15a0846" }, { "path": "src/snapshots/linesweeper__topology__tests__diamond.snap", "source_sha256": "cfaefd620a0a3d1376861bca09cd7c658ef00a32635b88f1b259a9b39cd15502", "source_git_blob": null, "sha256": "cfaefd620a0a3d1376861bca09cd7c658ef00a32635b88f1b259a9b39cd15502" }, diff --git a/vendor/linesweeper/src/segments.rs b/vendor/linesweeper/src/segments.rs index 909eb01d2e..37c4f8f573 100644 --- a/vendor/linesweeper/src/segments.rs +++ b/vendor/linesweeper/src/segments.rs @@ -131,6 +131,66 @@ fn pairs(xs: &[T]) -> impl Iterator { xs.windows(2).map(|pair| (&pair[0], &pair[1])) } +// Craft patch (batch paths): counts calls to `enter_order` in tests. +#[cfg(test)] +thread_local! { + static ENTER_COMPARISONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +// Craft patch (batch paths): the order of `Segments::enter`, by entrance +// height and then by horizontal position at that height. +fn enter_order( + segs: &SegVec, + (y1, seg1): &(f64, SegIdx), + (y2, seg2): &(f64, SegIdx), +) -> std::cmp::Ordering { + #[cfg(test)] + ENTER_COMPARISONS.with(|c| c.set(c.get() + 1)); + CheapOrderedFloat::from(*y1) + .cmp(&CheapOrderedFloat::from(*y2)) + .then_with(|| { + CheapOrderedFloat::from(segs[*seg1].at_y(*y1)) + .cmp(&CheapOrderedFloat::from(segs[*seg2].at_y(*y1))) + }) +} + +// Craft patch (batch paths): sorts `v[old_len..]` and merges it into +// `v[..old_len]`, which must already be sorted by `cmp`. The result is the +// order a stable sort of all of `v` gives: on a tie, an entry from before +// `old_len` comes first. Only the part of the sorted prefix that the new +// entries reach is moved, so entries added below every existing one cost a +// sort of the new entries and a binary search. +fn merge_sorted_tail( + v: &mut Vec, + old_len: usize, + mut cmp: impl FnMut(&T, &T) -> std::cmp::Ordering, +) { + let mut tail = v.split_off(old_len); + tail.sort_by(&mut cmp); + let Some(first) = tail.first() else { + return; + }; + let pos = v.partition_point(|e| cmp(e, first) != std::cmp::Ordering::Greater); + if pos == v.len() { + v.append(&mut tail); + return; + } + let suffix = v.split_off(pos); + v.reserve(suffix.len() + tail.len()); + let (mut i, mut j) = (0, 0); + while i < suffix.len() && j < tail.len() { + if cmp(&tail[j], &suffix[i]) == std::cmp::Ordering::Less { + v.push(tail[j]); + j += 1; + } else { + v.push(suffix[i]); + i += 1; + } + } + v.extend_from_slice(&suffix[i..]); + v.extend_from_slice(&tail[j..]); +} + struct SubpathIter<'a, I: Iterator> { inner: &'a mut Peekable, started: bool, @@ -298,6 +358,10 @@ impl Segments { /// Add a Bézier path to this arena. /// /// The path can contain multiple subpaths, and each of them must be closed. + /// + /// Each call merges the path's entrances and exits into the sorted ones + /// already in the arena, which moves every existing entry that sorts after + /// them. To add many paths, call [`Segments::add_bez_paths`] once instead. pub fn add_bez_path(&mut self, p: &BezPath) -> Result<(), NonClosedPath> { let old_len = self.segs.len(); self.add_path_without_updating_enter_exit(p, true)?; @@ -308,6 +372,11 @@ impl Segments { /// Add a Bézier path to this arena. /// /// The path can contain multiple subpaths, and each of them may or may not be closed. + /// + /// Each call merges the path's entrances and exits into the sorted ones + /// already in the arena, which moves every existing entry that sorts after + /// them. To add many paths, call [`Segments::add_non_closed_bez_paths`] + /// once instead. pub fn add_non_closed_bez_path(&mut self, p: &BezPath) -> Result<(), NonClosedPath> { let old_len = self.segs.len(); self.add_path_without_updating_enter_exit(p, false)?; @@ -315,6 +384,71 @@ impl Segments { Ok(()) } + // Craft patch (batch paths): add every path, then sort the entrances and exits once. + /// Add a collection of Bézier paths to this arena. + /// + /// Every subpath must be closed. When every path is closed, this gives the + /// same arena as calling [`Segments::add_bez_path`] on each path in turn, + /// and it sorts the entrances and exits once instead of once per path. + /// + /// If a subpath is not closed, this returns the error for the first such + /// subpath. The paths before the one holding it stay in the arena, and no + /// segment of that path or of any later path is added. + pub fn add_bez_paths<'a>( + &mut self, + ps: impl IntoIterator, + ) -> Result<(), NonClosedPath> { + self.add_paths_updating_enter_exit_once(ps, true) + } + + // Craft patch (batch paths). + /// Add a collection of Bézier paths to this arena. + /// + /// Each subpath may or may not be closed. This gives the same arena as + /// calling [`Segments::add_non_closed_bez_path`] on each path in turn, and + /// it sorts the entrances and exits once instead of once per path. + pub fn add_non_closed_bez_paths<'a>( + &mut self, + ps: impl IntoIterator, + ) -> Result<(), NonClosedPath> { + self.add_paths_updating_enter_exit_once(ps, false) + } + + // Craft patch (batch paths). + fn add_paths_updating_enter_exit_once<'a>( + &mut self, + ps: impl IntoIterator, + must_be_closed: bool, + ) -> Result<(), NonClosedPath> { + let old_len = self.segs.len(); + let mut result = Ok(()); + for p in ps { + let path_start = self.segs.len(); + result = self.add_path_without_updating_enter_exit(p, must_be_closed); + if result.is_err() { + // The failing path's segments are removed, so none is left + // linked to an index past the end of the arena. + self.truncate_unentered(path_start); + break; + } + } + self.update_enter_exit(old_len); + result + } + + // Craft patch (batch paths): drops every segment at index `len` or above. + // `enter` and `exit` are left alone, so this is only for segments that + // `update_enter_exit` has not seen yet. + fn truncate_unentered(&mut self, len: usize) { + self.segs.inner.truncate(len); + self.horizontal_decomps.inner.truncate(len); + self.contour_prev.inner.truncate(len); + self.contour_next.inner.truncate(len); + self.orientation.inner.truncate(len); + self.split_from_predecessor.inner.truncate(len); + self.input_segs.inner.truncate(len); + } + pub(crate) fn add_path_without_updating_enter_exit( &mut self, p: &BezPath, @@ -415,6 +549,9 @@ impl Segments { } pub(crate) fn update_enter_exit(&mut self, old_len: usize) { + // Craft patch (batch paths). + let enter_old_len = self.enter.len(); + let exit_old_len = self.exit.len(); for idx in old_len..self.len() { let seg_idx = SegIdx(idx); let seg = &self.segs[seg_idx]; @@ -428,15 +565,15 @@ impl Segments { // We sort the enter segments by y position, and then by horizontal // start position so that they're fairly likely to get inserted in the // sweep-line in order (which makes the indexing fix-ups faster). - self.enter.sort_by(|(y1, seg1), (y2, seg2)| { - CheapOrderedFloat::from(*y1) - .cmp(&CheapOrderedFloat::from(*y2)) - .then_with(|| { - CheapOrderedFloat::from(self.segs[*seg1].at_y(*y1)) - .cmp(&CheapOrderedFloat::from(self.segs[*seg2].at_y(*y1))) - }) + // + // Craft patch (batch paths): the entries before `old_len` are already + // sorted, so only the new entries are sorted and then merged in. This + // gives the same order as a stable sort of the whole vector. + let segs = &self.segs; + merge_sorted_tail(&mut self.enter, enter_old_len, |a, b| { + enter_order(segs, a, b) }); - self.exit.sort_by(|(y1, _), (y2, _)| { + merge_sorted_tail(&mut self.exit, exit_old_len, |(y1, _), (y2, _)| { CheapOrderedFloat::from(*y1).cmp(&CheapOrderedFloat::from(*y2)) }); } @@ -480,3 +617,194 @@ impl std::ops::Index for Segments { &self.segs[index] } } + +// Craft patch (batch paths). +#[cfg(test)] +mod tests { + use kurbo::BezPath; + + use super::{SegIdx, Segments}; + use crate::num::CheapOrderedFloat; + + // Paths on a small integer grid, so that many segments share entrance + // heights and entrance positions, with lines, quadratics and cubics. + fn grid_paths(count: usize, closed: bool) -> Vec { + let mut state: u64 = 0x2545_f491_4f6c_dd1d; + let mut next = move || { + state = state + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + ((state >> 33) % 12) as f64 + }; + (0..count) + .map(|i| { + let mut p = BezPath::new(); + p.move_to((next(), next())); + match i % 3 { + 0 => { + p.line_to((next(), next())); + p.line_to((next(), next())); + } + 1 => { + p.quad_to((next(), next()), (next(), next())); + p.line_to((next(), next())); + } + _ => { + p.curve_to((next(), next()), (next(), next()), (next(), next())); + } + } + if closed { + p.close_path(); + } + p + }) + .collect() + } + + fn assert_same_arena(a: &Segments, b: &Segments) { + assert_eq!(a.segs, b.segs); + assert_eq!(a.orientation, b.orientation); + assert_eq!(a.contour_prev, b.contour_prev); + assert_eq!(a.contour_next, b.contour_next); + assert_eq!(a.enter, b.enter); + assert_eq!(a.exit, b.exit); + } + + #[test] + fn add_bez_paths_matches_repeated_add_bez_path() { + let paths = grid_paths(300, true); + let mut one_by_one = Segments::default(); + for p in &paths { + one_by_one.add_bez_path(p).unwrap(); + } + let mut batch = Segments::default(); + batch.add_bez_paths(&paths).unwrap(); + batch.check_invariants(); + assert!(batch.len() > 600); + assert_same_arena(&one_by_one, &batch); + + // A second batch adds to the arena that is already there. + let more = grid_paths(50, true); + for p in &more { + one_by_one.add_bez_path(p).unwrap(); + } + batch.add_bez_paths(&more).unwrap(); + assert_same_arena(&one_by_one, &batch); + } + + #[test] + fn add_non_closed_bez_paths_matches_repeated_add_non_closed_bez_path() { + let paths = grid_paths(300, false); + let mut one_by_one = Segments::default(); + for p in &paths { + one_by_one.add_non_closed_bez_path(p).unwrap(); + } + let mut batch = Segments::default(); + batch.add_non_closed_bez_paths(&paths).unwrap(); + batch.check_invariants(); + assert_same_arena(&one_by_one, &batch); + } + + #[test] + fn add_bez_paths_stops_at_an_open_path() { + let mut paths = grid_paths(4, true); + let mut open = BezPath::new(); + open.move_to((0.0, 0.0)); + open.line_to((1.0, 5.0)); + paths.insert(2, open); + + let mut segments = Segments::default(); + let err = segments.add_bez_paths(&paths).unwrap_err(); + assert_eq!(err.start_point, kurbo::Point::new(0.0, 0.0)); + assert_eq!(err.end_point, kurbo::Point::new(1.0, 5.0)); + + // The two paths before the open one stay, and nothing of the open + // path or the paths after it is added. + segments.check_invariants(); + let mut expected = Segments::default(); + expected.add_bez_paths(&paths[..2]).unwrap(); + assert_same_arena(&expected, &segments); + assert_eq!(segments.input_segs, expected.input_segs); + assert_eq!( + segments.split_from_predecessor, + expected.split_from_predecessor + ); + } + + type Events = Vec<(f64, SegIdx)>; + + // The entrance and exit order that sorting every entry in index order + // gives, as `update_enter_exit` did before it merged new entries in. + fn sorted_from_scratch(s: &Segments) -> (Events, Events) { + let mut enter = Vec::new(); + let mut exit = Vec::new(); + for idx in s.indices() { + let seg = &s[idx]; + enter.push((seg.start().y, idx)); + if !seg.is_horizontal() { + exit.push((seg.end().y, idx)); + } + } + enter.sort_by(|a, b| super::enter_order(&s.segs, a, b)); + exit.sort_by(|(y1, _), (y2, _)| { + CheapOrderedFloat::from(*y1).cmp(&CheapOrderedFloat::from(*y2)) + }); + (enter, exit) + } + + #[test] + fn merged_entrances_and_exits_match_a_full_sort() { + // Paths added one at a time land above, below and among the ones + // already there, with many equal heights and positions. + let mut one_by_one = Segments::default(); + for p in &grid_paths(400, true) { + one_by_one.add_bez_path(p).unwrap(); + let (enter, exit) = sorted_from_scratch(&one_by_one); + assert_eq!(one_by_one.enter, enter); + assert_eq!(one_by_one.exit, exit); + } + + let mut batches = Segments::default(); + let paths = grid_paths(400, false); + for chunk in paths.chunks(37) { + batches.add_non_closed_bez_paths(chunk).unwrap(); + let (enter, exit) = sorted_from_scratch(&batches); + assert_eq!(batches.enter, enter); + assert_eq!(batches.exit, exit); + } + } + + #[test] + fn paths_added_in_height_order_are_not_sorted_again() { + // 2,000 triangles in rows of 400, added one at a time from the top + // row down and left to right. + let triangles: Vec = (0..2000) + .map(|i| { + let x = (i % 400) as f64 * 3.0; + let y = (i / 400) as f64 * 3.0; + let mut p = BezPath::new(); + p.move_to((x, y)); + p.line_to((x + 2.0, y)); + p.line_to((x + 1.0, y + 2.0)); + p.close_path(); + p + }) + .collect(); + let mut segments = Segments::default(); + super::ENTER_COMPARISONS.with(|c| c.set(0)); + for p in &triangles { + segments.add_bez_path(p).unwrap(); + } + let comparisons = super::ENTER_COMPARISONS.with(|c| c.get()); + assert_eq!(segments.len(), 6000); + // Sorting all the entrances on every call compares each existing + // entrance at least once per call, about 6,000,000 comparisons here. + assert!( + comparisons < 64 * 6000, + "{comparisons} entrance comparisons" + ); + let (enter, exit) = sorted_from_scratch(&segments); + assert_eq!(segments.enter, enter); + assert_eq!(segments.exit, exit); + } +} From 2cdbd4b9c1c27d04ee3d1f9f1c106185020c564b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 8 Nov 2026 12:46:09 -0800 Subject: [PATCH 009/786] 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 010/786] 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 011/786] 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 012/786] 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 013/786] 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 014/786] 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 015/786] 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 016/786] 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 017/786] 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 018/786] 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 b84bd0613608059066b370c2f7f639d908696bbf Mon Sep 17 00:00:00 2001 From: alehel Date: Sat, 14 Nov 2026 20:57:29 +0100 Subject: [PATCH 019/786] craft-audio: README says opus::wav_order is for mapping family 1 only Co-Authored-By: Claude Opus 5.5 --- crates/audio/README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/audio/README.md b/crates/audio/README.md index 5a5df4f2f5..d8ff8a860e 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -209,7 +209,9 @@ target, call `reset()`, decode from there, and drop the output before the target The codec modules are also usable on their own. `aac::Decoder` and `opus::Decoder` return the codec's channel order; `aac::wav_order(channel_config)` and `opus::wav_order(channels)` map it to -WAV order. `ac3::Decoder` and `mpa::Decoder` output WAV order. +WAV order. `opus::wav_order` applies only to mapping family 1; other families have no speaker +assignment, and `TrackDecoder` leaves their channels in stream order. `ac3::Decoder` and +`mpa::Decoder` output WAV order. ### Encode a file From 836433ccb9e2dc261da1f74b1c33bdcf94105ff9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:01:40 -0800 Subject: [PATCH 020/786] 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 021/786] 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 022/786] 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 023/786] 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 024/786] 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 97d1335caf05952ef8cc336f905f42541488d660 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:10:27 -0800 Subject: [PATCH 025/786] craft-testkit: skip or fail a test that lacks a program, a corpus or the craft-fonts faces Add the skip module to craft-testkit, for the Craft apps and the craft-libs crates to take as a dev-dependency. - skip(reason, required_var) prints one "SKIPPED: " line to stderr and returns false, or fails the test when the variable is exactly 1. Unset, empty, 0, true, " 1" and "1\n" all skip. - or_skip!(probe, var) binds the Ok value of a Result or skips and returns; or_skip!(probe, var, value) returns the given value, for a test that returns a Result. - craft_fonts(present, required) takes both values from the caller's build; craft_fonts_cover(text, faces) checks that one face maps every character of the text that is not whitespace. A carriage return or line feed in a reason is printed as \r or \n, so one skip is one line. The module is native only and does not change the process environment; its tests that read a variable run the test binary again as a child process. --- Cargo.lock | 3 + README.md | 4 +- crates/testkit/Cargo.toml | 5 +- crates/testkit/README.md | 59 ++++++ crates/testkit/src/lib.rs | 6 + crates/testkit/src/skip.rs | 379 +++++++++++++++++++++++++++++++++++++ 6 files changed, 454 insertions(+), 2 deletions(-) create mode 100644 crates/testkit/src/skip.rs diff --git a/Cargo.lock b/Cargo.lock index c8aee49f29..182a0deb6d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2573,6 +2573,9 @@ dependencies = [ [[package]] name = "craft-testkit" version = "0.1.0" +dependencies = [ + "skrifa 0.47.0", +] [[package]] name = "craft-text" diff --git a/README.md b/README.md index adbb6c120e..6b015e678c 100644 --- a/README.md +++ b/README.md @@ -347,7 +347,9 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit `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. + out of range, and `std::time::Instant` in code the web build runs. Its `skip` module prints a + `SKIPPED:` line when a test lacks a program, a corpus or the craft-fonts faces, or fails the test when + the variable the caller names is exactly `1`. 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 d32ed735f4..de033a3259 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -5,10 +5,13 @@ 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" +description = "Source-level platform regression guards, skip-or-fail helpers and verification utilities for the Craft application suite" publish = false [dependencies] +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +skrifa = { version = "0.47", default-features = false, features = ["std"] } + [lints] workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 36b87bb89d..1e4cfc02f8 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -27,6 +27,54 @@ Source-level guards provide deterministic syntactic evidence about codebase stru Source guards serve as fast, zero-dependency regression gates in application test suites, complementing platform integration tests and CI workflows. +## skip + +The `skip` module is not built for `wasm32`. A test that needs something a test environment may lack +(a program, a corpus file, the craft-fonts faces) skips or fails under one rule: + +- When the variable the caller names is exactly `1`, the absence fails the test. No skip line is + printed. +- Otherwise, including when the variable is unset, empty, `0`, `true`, ` 1` or `1` followed by a + line feed, the helper prints `SKIPPED: ` and one line feed to stderr, and the test + returns and passes. Carriage returns and line feeds in the reason are printed as `\r` and `\n`. + +The caller passes the name its repository uses today, such as `CRAFT_MEDIA_REQUIRE_ORACLES`, +`CRAFT_PDF_ORACLES_REQUIRED`, `PDFCRAFT_ORACLES_REQUIRED` or `FILMCRAFT_REQUIRE_ORACLES`. +`skip::REQUIRED_VAR` (`CRAFT_TEST_REQUIRED`) is the default name. + +```rust +use craft_testkit::skip::{REQUIRED_VAR, craft_fonts, skip}; + +#[test] +fn renders_with_qpdf() { + let qpdf = craft_testkit::or_skip!(find_qpdf(), REQUIRED_VAR); + // ... +} + +#[test] +fn draws_japanese() { + if !craft_fonts(HAS_CRAFT_FONTS, CRAFT_FONTS_REQUIRED) { + return; + } + // ... +} +``` + +`or_skip!` evaluates a `Result` once, binds the `Ok` value, and on `Err` skips with the error's +`Display` text as the reason. The two-argument form returns `()`; a test that returns a `Result` +passes the value to return as the third argument, for example `Ok(())`. + +`craft_fonts(present, required)` takes both values from the caller's build: a build constant, an +`option_env!` value, or the table `craft-fonts-build` generates. A required failure names +`CRAFT_FONTS_REQUIRED=1`. + +`craft_fonts_cover(text, faces)` returns `true` when one face maps every character of `text` that +is not whitespace. Each face is font data with its index in a collection (`0` for a single font). A +face that does not parse covers nothing, and coverage is not combined across faces. + +The module does not change the process environment. Its tests that read a real variable run the +test binary again as a child process with that variable set. + ## Consumer Adoption Examples ### 1. PhotoCraft: Adopt `wgsl_float_literals` and `predefined_quit` @@ -83,6 +131,11 @@ 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` | +| `skip` | storytold/lightcraft | `crates/testkit/src/lib.rs` (`skip!`, `record`) | `7ebbb17a82` | +| `skip` | storytold/pdfcraft | `crates/oracle/src/lib.rs` (`or_skip!`, `REQUIRED_VAR`) | `ee9bf28126` | +| `skip` | storytold/filmcraft | `crates/testkit/src/lib.rs` (`require_*!`), `crates/testkit/src/oracle.rs` (`skip`) | `cff7e1442e` | +| `skip` | storytold/craft-libs | `crates/media-testkit/src/lib.rs` (`skip`, `skip_with`) | `75a654f4f8` | +| `skip` | storytold/gridcraft | `crates/ui-egui/src/theme.rs` (`craft_fonts_cover`) | `06c2b1440b` | ## Migration @@ -90,3 +143,9 @@ 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 | +| LightCraft | `skip` | `lightcraft-testkit`'s `skip!`, which keeps its JSON skip log on top of `skip` | Not started | +| PdfCraft | `skip` | `pdfcraft-oracle`'s `or_skip!`, which reads any value of `PDFCRAFT_ORACLES_REQUIRED` | Not started | +| FilmCraft | `skip` | `filmcraft-testkit`'s `require_*!` and `skip`, which accept `1`, `true`, `yes` and `on` | Not started | +| GridCraft | `skip` | `craft_fonts_cover`, which reads GridCraft's embedded face table | Not started | +| craft-libs `craft-media-testkit` | `skip` | `skip` and `skip_with`, which accept `1`, `true`, `yes` and `on` | Not started | +| craft-libs `pdf` tests | `skip` | `or_skip!` in `crates/pdf/tests/cos/oracle.rs`, which reads any value of `CRAFT_PDF_ORACLES_REQUIRED` | Not started | diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index b484c6ef69..4f989f2694 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -15,6 +15,10 @@ //! * [`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`. //! +//! [`skip`] decides what a test does when something it needs is missing (a program, a corpus, +//! the craft-fonts faces): it prints one `SKIPPED:` line and returns, or fails the test when the +//! variable the caller names is exactly `1`. It is not built for `wasm32`. +//! //! ### Epistemic Scope: What Source Guards Establish vs What They Cannot //! //! Source-level guards provide deterministic syntactic evidence about codebase structure. @@ -26,6 +30,8 @@ //! rather than replace, platform integration tests and CI execution. pub mod guards; +#[cfg(not(target_arch = "wasm32"))] +pub mod skip; pub use guards::{AsFileSource, Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; diff --git a/crates/testkit/src/skip.rs b/crates/testkit/src/skip.rs new file mode 100644 index 0000000000..183db3b97d --- /dev/null +++ b/crates/testkit/src/skip.rs @@ -0,0 +1,379 @@ +//! Skip-or-fail for a test that needs something a test environment may lack: a program, a corpus +//! file, the craft-fonts faces. +//! +//! An optional absence prints one line to stderr, `SKIPPED: `, and the test returns and +//! passes. When the variable the caller names is exactly `1`, the absence fails the test instead +//! and no skip line is printed. Unset, empty, `0`, `true`, ` 1` and `1\n` all leave the test +//! optional. The caller passes the name its repository uses, such as `CRAFT_MEDIA_REQUIRE_ORACLES` +//! or `CRAFT_PDF_ORACLES_REQUIRED`; [`REQUIRED_VAR`] is the default name. +//! +//! ```no_run +//! use craft_testkit::skip::{REQUIRED_VAR, skip}; +//! +//! fn find_qpdf() -> Result { +//! Err("qpdf is not on PATH".into()) +//! } +//! +//! // A test returning `()`: bind the program or return. +//! let qpdf = craft_testkit::or_skip!(find_qpdf(), REQUIRED_VAR); +//! # let _ = qpdf; +//! +//! // The same rule without a `Result` to match on. +//! let gpu_available = false; +//! if !gpu_available && !skip("no GPU adapter", REQUIRED_VAR) { +//! return; +//! } +//! ``` +//! +//! A reason that holds a carriage return or a line feed is printed with them written as `\r` and +//! `\n`, so one skip is one line. Each line is written with one call while stderr is locked, so +//! lines from tests running in parallel do not mix; their order is not fixed. + +use std::ffi::OsStr; + +/// The default name of the variable that makes a skip fail the test. +pub const REQUIRED_VAR: &str = "CRAFT_TEST_REQUIRED"; + +/// The variable `craft-fonts-build` reads, named by [`craft_fonts`] when it fails a test. +pub const FONTS_REQUIRED_VAR: &str = "CRAFT_FONTS_REQUIRED"; + +/// Whether the variable `var` is set to exactly `1`. Any other value, a value that is not valid +/// Unicode, and an unset variable return `false`. +pub fn required(var: &str) -> bool { + is_required_value(std::env::var_os(var).as_deref()) +} + +fn is_required_value(value: Option<&OsStr>) -> bool { + value == Some(OsStr::new("1")) +} + +/// Skip the calling test: print `SKIPPED: ` and return `false`, or fail the test when +/// `required_var` is exactly `1`. The caller returns from the test itself: +/// `if !skip(reason, var) { return; }`. +pub fn skip(reason: &str, required_var: &str) -> bool { + skip_with(required(required_var), reason, required_var) +} + +/// Fail the test when `required` is set, otherwise print the skip line and return `false`. It +/// fails the test with a panic. +#[allow(clippy::panic)] +fn skip_with(required: bool, reason: &str, required_var: &str) -> bool { + if required { + panic!("{reason}, and {required_var}=1 forbids skipping this test"); + } + eprint!("{}", skip_line(reason)); + false +} + +/// The skip line for `reason`, with its carriage returns and line feeds escaped, ending in one +/// line feed. +fn skip_line(reason: &str) -> String { + let mut line = String::with_capacity("SKIPPED: \n".len() + reason.len()); + line.push_str("SKIPPED: "); + for c in reason.chars() { + match c { + '\r' => line.push_str("\\r"), + '\n' => line.push_str("\\n"), + c => line.push(c), + } + } + line.push('\n'); + line +} + +/// Whether a test that needs the craft-fonts faces can run. Returns `true` when `present` is set. +/// Without the faces it prints a skip line and returns `false`, or fails the test when `required` +/// is set. The caller passes both values from its build: a build constant, an `option_env!` +/// value, or the table `craft-fonts-build` generates. +pub fn craft_fonts(present: bool, required: bool) -> bool { + present || skip_with(required, "craft-fonts faces unavailable (build with CRAFT_FONTS_DIR)", FONTS_REQUIRED_VAR) +} + +/// Whether one of `faces` maps every character of `text` that is not whitespace. Each face is +/// font data and the index of the face in a collection (`0` for a single font). A face that does +/// not parse covers nothing, and the characters must all come from the same face. Each combining +/// mark is a character of its own. Text that is empty or only whitespace is covered when at least +/// one face parses. +pub fn craft_fonts_cover(text: &str, faces: &[(&[u8], u32)]) -> bool { + use skrifa::MetadataProvider as _; + faces.iter().any(|&(data, index)| { + let Ok(font) = skrifa::FontRef::from_index(data, index) else { + return false; + }; + let map = font.charmap(); + text.chars().filter(|c| !c.is_whitespace()).all(|c| map.map(c).is_some()) + }) +} + +/// Binds the `Ok` value of a `Result` probe, or skips the calling test under the rule of +/// [`skip`](crate::skip::skip) and returns from it. The probe is evaluated once, and its error is +/// the skip reason, so the error type implements `Display`. +/// +/// `or_skip!(probe, var)` returns `()` and belongs in a test returning `()`. +/// `or_skip!(probe, var, value)` returns `value`, for example `Ok(())` in a test that returns a +/// `Result`. +#[macro_export] +macro_rules! or_skip { + ($probe:expr, $required_var:expr) => { + $crate::or_skip!($probe, $required_var, ()) + }; + ($probe:expr, $required_var:expr, $ret:expr) => { + match $probe { + ::core::result::Result::Ok(value) => value, + ::core::result::Result::Err(absent) => { + let _ = $crate::skip::skip(&::std::string::ToString::to_string(&absent), $required_var); + return $ret; + } + } + }; +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + use std::process::{Command, Output}; + + /// The case the child process runs; unset in an ordinary test run. + const CHILD_CASE: &str = "CRAFT_TESTKIT_SKIP_CHILD"; + /// A variable no test sets, for skips that must stay optional. + const NEVER_SET: &str = "CRAFT_TESTKIT_SKIP_NEVER_SET"; + + /// Runs `child` below in a new process of this test binary, with `REQUIRED_VAR` set to + /// `required` or removed, so no test changes this process's environment. + fn run_child(case: &str, required: Option<&str>) -> Output { + let exe = std::env::current_exe().expect("the test binary's path"); + let mut cmd = Command::new(exe); + cmd.args(["skip::tests::child", "--exact", "--nocapture", "--test-threads=1"]).env(CHILD_CASE, case); + match required { + Some(value) => cmd.env(REQUIRED_VAR, value), + None => cmd.env_remove(REQUIRED_VAR), + }; + cmd.output().expect("run the test binary") + } + + fn stderr(out: &Output) -> String { + String::from_utf8_lossy(&out.stderr).into_owned() + } + + #[test] + fn child() { + let Some(case) = std::env::var_os(CHILD_CASE) else { + return; + }; + match case.to_str() { + Some("skip") => { + assert!(!skip("probe absent", REQUIRED_VAR)); + eprintln!("returned from skip"); + } + Some("or_skip") => { + let value: u32 = crate::or_skip!(Err::("probe absent"), REQUIRED_VAR); + eprintln!("ran on with {value}"); + } + Some("threads") => std::thread::scope(|s| { + for i in 0..8 { + s.spawn(move || skip(&format!("thread {i}\r\nsecond half"), REQUIRED_VAR)); + } + }), + other => panic!("unknown child case {other:?}"), + } + } + + /// Unset, empty, `0`, `true`, a leading space and a trailing line feed are optional; only + /// exactly `1` is required. + #[test] + fn only_exactly_1_is_required() { + assert!(!is_required_value(None)); + for value in ["", "0", "true", "TRUE", "yes", "on", " 1", "1 ", "1\n", "01", "11"] { + assert!(!is_required_value(Some(OsStr::new(value))), "{value:?}"); + } + assert!(is_required_value(Some(OsStr::new("1")))); + } + + #[cfg(unix)] + #[test] + fn a_value_that_is_not_unicode_is_optional() { + use std::os::unix::ffi::OsStrExt as _; + assert!(!is_required_value(Some(OsStr::from_bytes(b"1\xff")))); + assert!(!is_required_value(Some(OsStr::from_bytes(b"\xff")))); + } + + /// Absence is never silent, and which of the two loud forms it takes is decided by the + /// variable: exactly `1` fails the test, and `0` (fatal under the any-value rule) skips. + #[test] + fn a_missing_oracle_is_fatal_exactly_when_it_is_required() { + let var = "CRAFT_PDF_ORACLES_REQUIRED"; + assert!(!skip_with(is_required_value(Some(OsStr::new("0"))), "qpdf is not on PATH", var)); + assert!(!skip_with(is_required_value(Some(OsStr::new(""))), "qpdf is not on PATH", var)); + + let failed = std::panic::catch_unwind(|| skip_with(is_required_value(Some(OsStr::new("1"))), "qpdf is not on PATH", var)); + let message = failed.expect_err("a required absence fails the test"); + let message = message.downcast_ref::().expect("a formatted message"); + assert!(message.contains("qpdf is not on PATH"), "{message}"); + assert!(message.contains("CRAFT_PDF_ORACLES_REQUIRED=1"), "{message}"); + } + + #[test] + fn a_skip_line_is_one_line_with_its_reason_escaped() { + assert_eq!(skip_line("qpdf is not on PATH"), "SKIPPED: qpdf is not on PATH\n"); + let line = skip_line("first\r\nsecond\nthird\r"); + assert_eq!(line, "SKIPPED: first\\r\\nsecond\\nthird\\r\n"); + assert_eq!(line.lines().count(), 1); + assert_eq!(skip_line(""), "SKIPPED: \n"); + } + + /// The variable is read from the environment, and only exactly `1` fails the test. + #[test] + fn skip_reads_its_variable_from_the_environment() { + for value in [None, Some(""), Some("0"), Some("true"), Some(" 1")] { + let out = run_child("skip", value); + let err = stderr(&out); + assert!(out.status.success(), "{value:?}: {err}"); + assert_eq!(err.matches("SKIPPED: probe absent\n").count(), 1, "{value:?}: {err}"); + assert!(err.contains("returned from skip"), "{value:?}: {err}"); + } + let out = run_child("skip", Some("1")); + let err = stderr(&out); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("probe absent, and CRAFT_TEST_REQUIRED=1 forbids skipping this test"), "{err}"); + assert!(!err.contains("SKIPPED:"), "{err}"); + assert!(!err.contains("returned from skip"), "{err}"); + } + + #[test] + fn or_skip_returns_from_the_test_when_optional_and_fails_when_required() { + let out = run_child("or_skip", None); + let err = stderr(&out); + assert!(out.status.success(), "{err}"); + assert!(err.contains("SKIPPED: probe absent\n"), "{err}"); + assert!(!err.contains("ran on"), "{err}"); + + let out = run_child("or_skip", Some("1")); + let err = stderr(&out); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("CRAFT_TEST_REQUIRED=1"), "{err}"); + assert!(!err.contains("SKIPPED:"), "{err}"); + assert!(!err.contains("ran on"), "{err}"); + } + + #[test] + fn skip_lines_from_parallel_threads_stay_whole() { + let out = run_child("threads", None); + let err = stderr(&out); + assert!(out.status.success(), "{err}"); + let mut lines: Vec<&str> = err.lines().filter(|l| l.contains("SKIPPED") || l.contains("second half")).collect(); + lines.sort_unstable(); + let expected: Vec = (0..8).map(|i| format!("SKIPPED: thread {i}\\r\\nsecond half")).collect(); + assert_eq!(lines, expected, "{err}"); + } + + #[test] + fn or_skip_yields_the_value_and_evaluates_the_probe_once() { + let probes = Cell::new(0); + let probe = || { + probes.set(probes.get() + 1); + Ok::(7) + }; + let value = crate::or_skip!(probe(), NEVER_SET); + assert_eq!(value, 7); + assert_eq!(probes.get(), 1); + } + + #[test] + fn or_skip_returns_the_given_value_from_a_result_test() { + fn run(probes: &Cell) -> Result { + let value: u32 = crate::or_skip!( + { + probes.set(probes.get() + 1); + Err::("probe absent".into()) + }, + NEVER_SET, + Ok(0) + ); + Ok(value + 1) + } + let probes = Cell::new(0); + assert_eq!(run(&probes), Ok(0)); + assert_eq!(probes.get(), 1); + } + + #[test] + fn craft_fonts_runs_skips_or_fails() { + assert!(craft_fonts(true, false)); + assert!(craft_fonts(true, true)); + assert!(!craft_fonts(false, false)); + let failed = std::panic::catch_unwind(|| craft_fonts(false, true)); + let message = failed.expect_err("missing required faces fail the test"); + let message = message.downcast_ref::().expect("a formatted message"); + assert!(message.contains("CRAFT_FONTS_REQUIRED=1"), "{message}"); + } + + /// A font holding only a format 12 `cmap` table that maps each range of code points. + fn face(ranges: &[(u32, u32)]) -> Vec { + let subtable_len = 16 + 12 * ranges.len() as u32; + let mut data = Vec::new(); + data.extend_from_slice(&0x0001_0000u32.to_be_bytes()); + for v in [1u16, 16, 0, 0] { + data.extend_from_slice(&v.to_be_bytes()); + } + data.extend_from_slice(b"cmap"); + for v in [0u32, 28, 12 + subtable_len] { + data.extend_from_slice(&v.to_be_bytes()); + } + for v in [0u16, 1, 3, 10] { + data.extend_from_slice(&v.to_be_bytes()); + } + data.extend_from_slice(&12u32.to_be_bytes()); + data.extend_from_slice(&12u16.to_be_bytes()); + data.extend_from_slice(&0u16.to_be_bytes()); + for v in [subtable_len, 0, ranges.len() as u32] { + data.extend_from_slice(&v.to_be_bytes()); + } + let mut glyph = 1u32; + for &(start, end) in ranges { + for v in [start, end, glyph] { + data.extend_from_slice(&v.to_be_bytes()); + } + glyph += end - start + 1; + } + data + } + + #[test] + fn craft_fonts_cover_the_advertised_scripts() { + let latin_greek_cyrillic = face(&[(0x41, 0x5A), (0x61, 0x7A), (0x391, 0x3C9), (0x410, 0x44F)]); + let faces: &[(&[u8], u32)] = &[(&latin_greek_cyrillic, 0)]; + for sample in ["Craft", "Αλφα", "Привет", "Craft Αλφα Привет"] { + assert!(craft_fonts_cover(sample, faces), "{sample}"); + } + assert!(!craft_fonts_cover("日本", faces)); + assert!(!craft_fonts_cover("Craft!", faces)); + } + + #[test] + fn coverage_needs_one_face_that_parses_and_maps_every_character() { + let a = face(&[(u32::from('A'), u32::from('A'))]); + let b = face(&[(u32::from('B'), u32::from('B'))]); + let e = face(&[(u32::from('e'), u32::from('e'))]); + let e_acute = face(&[(u32::from('e'), u32::from('e')), (0x301, 0x301)]); + let garbage: &[u8] = b"not a font"; + + assert!(!craft_fonts_cover("", &[])); + assert!(!craft_fonts_cover("A", &[])); + assert!(!craft_fonts_cover("", &[(garbage, 0)])); + assert!(!craft_fonts_cover("A", &[(garbage, 0)])); + assert!(!craft_fonts_cover("A", &[(&a, 1)]), "a single font has no face 1"); + + assert!(craft_fonts_cover("", &[(&a, 0)])); + assert!(craft_fonts_cover(" \t\n\u{3000}", &[(&a, 0)])); + assert!(craft_fonts_cover(" A A ", &[(&a, 0)])); + assert!(craft_fonts_cover("A", &[(garbage, 0), (&a, 0)])); + + assert!(craft_fonts_cover("A", &[(&a, 0), (&b, 0)])); + assert!(craft_fonts_cover("B", &[(&a, 0), (&b, 0)])); + assert!(!craft_fonts_cover("AB", &[(&a, 0), (&b, 0)]), "each face covers only part of the text"); + + assert!(!craft_fonts_cover("e\u{301}", &[(&e, 0)]), "the combining mark is not mapped"); + assert!(craft_fonts_cover("e\u{301}", &[(&e_acute, 0)])); + } +} From 3a710e4c62a55feb4ad1b250305dbcbc9fb83f7c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:41:12 -0800 Subject: [PATCH 026/786] craft-texture: tests check the sRGB pair against the standard, craft-cms, craft-mesh and craft-psd The new tests in crates/texture/tests/srgb.rs compare linear_to_srgb and srgb_to_linear with the IEC 61966-2-1 formulas at every 8-bit and 16-bit code, check both thresholds (0.0031308 and 0.04045) and their neighbors, round trips, and that the outputs do not decrease over the code grids. They pin the behavior outside [0, 1]: negative values stay on the linear segment, values above 1 follow the power segment, infinities keep their sign and NaN stays NaN. craft-mesh's pair and craft-psd's float::srgb_encode must match bit for bit, and craft-cms's srgb_trc() curve within 2.4e-7. craft-cms, craft-mesh and craft-psd are dev-dependencies of craft-texture. --- Cargo.lock | 3 + crates/texture/Cargo.toml | 5 + crates/texture/tests/srgb.rs | 192 +++++++++++++++++++++++++++++++++++ 3 files changed, 200 insertions(+) create mode 100644 crates/texture/tests/srgb.rs diff --git a/Cargo.lock b/Cargo.lock index c11a134ae5..18890555a6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2591,6 +2591,9 @@ dependencies = [ name = "craft-texture" version = "0.1.0" dependencies = [ + "craft-cms", + "craft-mesh", + "craft-psd", "rayon", "thiserror 2.0.21", ] diff --git a/crates/texture/Cargo.toml b/crates/texture/Cargo.toml index 78868dd879..cb56a4217f 100644 --- a/crates/texture/Cargo.toml +++ b/crates/texture/Cargo.toml @@ -17,3 +17,8 @@ workspace = true [dependencies] rayon = { workspace = true, optional = true } thiserror = { workspace = true } + +[dev-dependencies] +craft-cms = { workspace = true } +craft-mesh = { workspace = true } +craft-psd = { workspace = true } diff --git a/crates/texture/tests/srgb.rs b/crates/texture/tests/srgb.rs new file mode 100644 index 0000000000..8884c6e3f3 --- /dev/null +++ b/crates/texture/tests/srgb.rs @@ -0,0 +1,192 @@ +//! The scalar sRGB pair against IEC 61966-2-1 and against the copies of it in craft-cms, +//! craft-mesh and craft-psd. +//! +//! The encoding is the one the ICC sRGB registry entry gives for IEC 61966-2-1:1999 +//! (); the decoding is the CSS Color 4 sample code +//! (). Outside `[0, 1]` the pair keeps +//! its own rule: negative values stay on the linear segment and values above 1 follow the power +//! segment. + +use craft_texture::{linear_to_srgb, srgb_to_linear}; + +/// The largest difference allowed between the `f32` pair and the `f64` formulas. +const STANDARD_TOLERANCE: f32 = 3.0e-7; +/// The largest difference allowed between the pair and craft-cms's ICC curve, which is evaluated +/// in `f64` and returned as `f32`. +const CMS_TOLERANCE: f32 = 2.4e-7; +/// The 8-bit and 16-bit code ranges. +const DEPTHS: [u32; 2] = [255, 65_535]; + +/// One direction of an sRGB pair. +type Scalar = fn(f32) -> f32; + +fn encode64(c: f64) -> f64 { + if c <= 0.003_130_8 { c * 12.92 } else { 1.055 * c.powf(1.0 / 2.4) - 0.055 } +} + +fn decode64(c: f64) -> f64 { + if c <= 0.040_45 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) } +} + +/// Every code of a depth with its normalized value. +fn codes(max: u32) -> impl Iterator { + (0..=max).map(move |n| (n, n as f32 / max as f32)) +} + +/// The largest difference between `f` and `g` over every code of a depth, and the code it is at. +fn worst(max: u32, f: impl Fn(f32) -> f32, g: impl Fn(f32) -> f32) -> (f32, u32) { + codes(max).map(|(n, v)| ((f(v) - g(v)).abs(), n)).fold((0.0, 0), |a, b| if b.0 > a.0 { b } else { a }) +} + +/// Inputs outside `[0, 1]` that the crates' copies must also agree on. +const OUTSIDE: [f32; 10] = [-0.0, -1.0e-6, -0.5, -1.0, -100.0, 1.5, 2.0, 100.0, f32::INFINITY, f32::NEG_INFINITY]; + +#[test] +fn encode_matches_the_standard_at_every_8_and_16_bit_code() { + for max in DEPTHS { + let (d, n) = worst(max, linear_to_srgb, |v| encode64(f64::from(v)) as f32); + assert!(d <= STANDARD_TOLERANCE, "code {n} of {max} is {d} from the standard"); + } +} + +#[test] +fn decode_matches_the_standard_at_every_8_and_16_bit_code() { + for max in DEPTHS { + let (d, n) = worst(max, srgb_to_linear, |v| decode64(f64::from(v)) as f32); + assert!(d <= STANDARD_TOLERANCE, "code {n} of {max} is {d} from the standard"); + } +} + +#[test] +fn every_encoded_code_round_trips() { + for max in DEPTHS { + for (n, v) in codes(max) { + let back = (linear_to_srgb(srgb_to_linear(v)) * max as f32).round() as u32; + assert_eq!(back, n, "code {n} of {max}"); + } + } +} + +#[test] +fn every_linear_code_round_trips_within_rounding() { + for max in DEPTHS { + let (d, n) = worst(max, |v| srgb_to_linear(linear_to_srgb(v)), |v| v); + assert!(d <= STANDARD_TOLERANCE, "code {n} of {max} comes back {d} away"); + } +} + +#[test] +fn outputs_do_not_decrease_over_the_code_grids() { + for max in DEPTHS { + for f in [linear_to_srgb, srgb_to_linear] { + let out: Vec = codes(max).map(|(_, v)| f(v)).collect(); + let fall = out.windows(2).position(|w| w[1] < w[0]); + assert_eq!(fall, None, "the output falls after code {fall:?} of {max}"); + } + } +} + +#[test] +fn encode_changes_segment_after_0_0031308() { + let t = 0.003_130_8_f32; + for v in [t.next_down(), t] { + assert_eq!(linear_to_srgb(v), v * 12.92, "{v} is on the linear segment"); + } + let above = t.next_up(); + assert_eq!(linear_to_srgb(above), 1.055 * above.powf(1.0 / 2.4) - 0.055); + for v in [t.next_down(), t, above] { + assert!((linear_to_srgb(v) - encode64(f64::from(v)) as f32).abs() <= STANDARD_TOLERANCE, "{v}"); + } +} + +#[test] +fn decode_changes_segment_after_0_04045() { + let t = 0.040_45_f32; + for v in [t.next_down(), t] { + assert_eq!(srgb_to_linear(v), v / 12.92, "{v} is on the linear segment"); + } + let above = t.next_up(); + assert_eq!(srgb_to_linear(above), ((above + 0.055) / 1.055).powf(2.4)); + for v in [t.next_down(), t, above] { + assert!((srgb_to_linear(v) - decode64(f64::from(v)) as f32).abs() <= STANDARD_TOLERANCE, "{v}"); + } +} + +#[test] +fn zero_and_one_map_to_themselves() { + for f in [linear_to_srgb, srgb_to_linear] { + assert_eq!(f(0.0).to_bits(), 0.0_f32.to_bits()); + assert_eq!(f(-0.0).to_bits(), (-0.0_f32).to_bits()); + assert!((f(1.0) - 1.0).abs() <= f32::EPSILON); + } +} + +#[test] +fn values_above_one_follow_the_power_segment() { + for v in [1.000_001_f32, 1.5, 2.0, 10.0] { + let (e, d) = (encode64(f64::from(v)), decode64(f64::from(v))); + assert!((f64::from(linear_to_srgb(v)) - e).abs() <= e * 1.0e-6, "encode {v}"); + assert!((f64::from(srgb_to_linear(v)) - d).abs() <= d * 1.0e-6, "decode {v}"); + } + assert!((linear_to_srgb(2.0) - 1.353_256).abs() < 1.0e-6); + assert!((srgb_to_linear(2.0) - 4.953_846).abs() < 1.0e-5); +} + +#[test] +fn negative_values_stay_on_the_linear_segment() { + for v in [-f32::MIN_POSITIVE, -1.0e-6, -0.003_130_8, -0.040_45, -0.5, -1.0, -100.0] { + assert_eq!(linear_to_srgb(v), v * 12.92, "encode {v}"); + assert_eq!(srgb_to_linear(v), v / 12.92, "decode {v}"); + } + assert!((linear_to_srgb(-1.0) + 12.92).abs() < 1.0e-5); + assert!((srgb_to_linear(-1.0) + 0.077_399_38).abs() < 1.0e-7); +} + +#[test] +fn infinities_keep_their_sign_and_nan_stays_nan() { + for f in [linear_to_srgb, srgb_to_linear] { + assert_eq!(f(f32::INFINITY), f32::INFINITY); + assert_eq!(f(f32::NEG_INFINITY), f32::NEG_INFINITY); + assert!(f(f32::NAN).is_nan()); + } +} + +#[test] +fn mesh_pair_matches_bit_for_bit() { + let pairs: [(Scalar, Scalar); 2] = [(linear_to_srgb, craft_mesh::linear_to_srgb), (srgb_to_linear, craft_mesh::srgb_to_linear)]; + for (ours, mesh) in pairs { + for max in DEPTHS { + for (n, v) in codes(max) { + assert_eq!(ours(v).to_bits(), mesh(v).to_bits(), "code {n} of {max}"); + } + } + for v in OUTSIDE { + assert_eq!(ours(v).to_bits(), mesh(v).to_bits(), "{v}"); + } + assert!(mesh(f32::NAN).is_nan()); + } +} + +#[test] +fn psd_encoder_matches_bit_for_bit() { + for max in DEPTHS { + for (n, v) in codes(max) { + assert_eq!(linear_to_srgb(v).to_bits(), craft_psd::float::srgb_encode(v).to_bits(), "code {n} of {max}"); + } + } + for v in OUTSIDE { + assert_eq!(linear_to_srgb(v).to_bits(), craft_psd::float::srgb_encode(v).to_bits(), "{v}"); + } + assert!(craft_psd::float::srgb_encode(f32::NAN).is_nan()); +} + +#[test] +fn cms_curve_matches_within_rounding() { + let trc = craft_cms::curve::srgb_trc(); + for max in DEPTHS { + let (d, n) = worst(max, srgb_to_linear, |v| trc.eval(v)); + assert!(d <= CMS_TOLERANCE, "decode code {n} of {max} is {d} from craft-cms"); + let (d, n) = worst(max, linear_to_srgb, |v| trc.eval_inverse(v)); + assert!(d <= CMS_TOLERANCE, "encode code {n} of {max} is {d} from craft-cms"); + } +} From da31f4949afb30e6ded41759b10e99435a56d902 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:45:24 -0800 Subject: [PATCH 027/786] 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 028/786] 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 a221d6081b113fc30a5ea50732880f55c130593c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 11:32:46 -0800 Subject: [PATCH 029/786] craft-testkit: parse pinned-corpus manifests and check a corpus folder against them Add craft_testkit::corpus behind the corpus feature (native only, sha2). - Manifest::parse reads one tab-separated row per file: the SHA-256 as 64 hexadecimal digits in either case, a relative path with / between its parts, and optional license and URL columns. It skips blank lines and lines whose first character other than a space or tab is #, and reads LF and CRLF. A row with fewer than 2 or more than 4 columns, a bad digest, a path that is empty, absolute, has an empty, . or .. part or holds \, : or NUL, or a repeated path returns a ManifestError naming the line instead of panicking. - verify checks that each listed file resolves inside the folder after symbolic links are followed, is a regular file (checked before it is opened, so a directory or a named pipe is refused), is within the size limit, and has the listed SHA-256. An empty manifest is an error. - pinned(var, manifest) returns the folder the variable names (default CRAFT_CORPUS) after verify. With the variable unset it prints one "SKIPPED: corpus not given: set to its folder" line and returns None, or fails the test when _REQUIRED is exactly 1. A set but empty variable, a manifest that does not parse or a folder that does not match fails the test. - Limits: a manifest of at most 1 MiB and 10,000 rows, files of at most 8 GiB, hashed 64 KiB at a time. The parser follows the loader in crates/affinity/tests/support/corpus.rs, which has no tests of its own; that crate switches in its own pull request. The README gains the module's description and its Origin and Migration tables. --- Cargo.lock | 3 + crates/testkit/Cargo.toml | 5 + crates/testkit/README.md | 30 ++ crates/testkit/src/corpus.rs | 890 +++++++++++++++++++++++++++++++++++ crates/testkit/src/lib.rs | 6 + 5 files changed, 934 insertions(+) create mode 100644 crates/testkit/src/corpus.rs diff --git a/Cargo.lock b/Cargo.lock index c8aee49f29..edc19d31a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2573,6 +2573,9 @@ dependencies = [ [[package]] name = "craft-testkit" version = "0.1.0" +dependencies = [ + "sha2 0.10.9", +] [[package]] name = "craft-text" diff --git a/crates/testkit/Cargo.toml b/crates/testkit/Cargo.toml index d32ed735f4..33bf1c9d9d 100644 --- a/crates/testkit/Cargo.toml +++ b/crates/testkit/Cargo.toml @@ -8,7 +8,12 @@ repository.workspace = true description = "Source-level platform regression guards and verification utilities for the Craft application suite" publish = false +[features] +# Pinned-corpus manifests and the `corpus::pinned` test gate (native only). +corpus = ["dep:sha2"] + [dependencies] +sha2 = { version = "0.10", default-features = false, features = ["std"], optional = true } [lints] workspace = true diff --git a/crates/testkit/README.md b/crates/testkit/README.md index 36b87bb89d..ab948e4f2e 100644 --- a/crates/testkit/README.md +++ b/crates/testkit/README.md @@ -11,6 +11,36 @@ 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`. +## Pinned corpora: `corpus` + +`craft_testkit::corpus` is behind the `corpus` feature and is native only. It parses a corpus manifest and checks a folder of files against it. + +A manifest has one row per file, with tab-separated columns: the SHA-256 as 64 hexadecimal digits in either case, the path relative to the corpus folder with `/` between its parts, and optional license and URL columns. Blank lines and lines whose first character other than a space or a tab is `#` are skipped. LF and CRLF line endings are both read. + +- `Manifest::parse(text)` returns a `ManifestError` naming the line for a row with fewer than 2 or more than 4 columns, a digest that is not 64 hexadecimal digits, a path that is empty, starts with `/`, has an empty, `.` or `..` part, or holds a `\`, a `:` or a NUL character, and a path listed twice. An empty optional column is `None`. +- `Manifest::read(path, &limits)` reads a manifest file, stopping one byte past the size limit. A path that is not a regular file, such as a folder or a named pipe, returns `ManifestError::NotAFile` without being opened. +- `verify(dir, &manifest)` checks that each listed file resolves inside `dir` after symbolic links are followed, is a regular file within the size limit, and has the listed SHA-256. It returns a `VerifyError` naming the path. A manifest with no rows is an error. +- `pinned(var, manifest)` is the gate a test calls. `var` names the folder variable, and `None` reads `CRAFT_CORPUS`. The corpus is required when the variable of the same name plus `_REQUIRED` (by default `CRAFT_CORPUS_REQUIRED`) is exactly `1`. With the folder variable unset and the corpus optional, it prints `SKIPPED: corpus not given: set to its folder` to stderr and returns `None`. With the folder variable unset and the corpus required, or set to an empty value, a manifest that does not parse or a folder that does not match, it fails the test. Otherwise it returns the folder. + +`Limits` sets the size limits: by default a manifest of at most 1 MiB and 10,000 rows, and files of at most 8 GiB each, read 64 KiB at a time. No function downloads a file or changes the process environment. + +### Origin + +| Module | Source repository | Path | Revision | +|---|---|---|---| +| `corpus` | storytold/craft-libs | `crates/affinity/tests/support/corpus.rs:18-35` | `75a654f4` | + +### Migration + +| Consumer | Today | State | +|---|---|---| +| craft-libs `affinity` | `tests/support/corpus.rs` reads `corpus.tsv` (already tab-separated) from `AFFINITY_CORPUS` | Pending: a separate pull request switches it | +| craft-libs `raw` | `docs/raf-corpus.sha256` separates digest and path with two spaces | Pending: the list is converted to tabs in a separate pull request | +| LightCraft | `crates/raw/tests/it/corpus.rs` checks the RAF list | Pending: a separate pull request switches it | +| PhotoCraft | `crates/io/tests/it/corpus.rs` and `xtask/*-corpus.sha256` (two-space lists) | Pending: the lists are converted to tabs in a separate pull request | +| CADCraft | `crates/io/src/roundtrip/tests.rs` scans `CADCRAFT_CORPUS_DIR` without a checksum list | Pending: needs a pinned list first | +| VectorCraft | `crates/affinity/tests/support/corpus.rs` reads a two-space list | Pending: the list is converted to tabs in a separate pull request | + ## Epistemic Scope: Syntactic Guards vs Runtime Validation Source-level guards provide deterministic syntactic evidence about codebase structure: diff --git a/crates/testkit/src/corpus.rs b/crates/testkit/src/corpus.rs new file mode 100644 index 0000000000..fb0a4e4d91 --- /dev/null +++ b/crates/testkit/src/corpus.rs @@ -0,0 +1,890 @@ +//! Pinned test corpora: a folder of files listed in a manifest, each checked against its SHA-256. +//! +//! A manifest has one tab-separated row per file: the SHA-256 as 64 hexadecimal digits, the +//! file's path relative to the corpus folder, and optional license and URL columns. In this +//! example each `\t` stands for one tab character: +//! +//! ```text +//! # Public Affinity documents +//! cc8ca0db0d8fc545eb29153be900f153fa6b7b7eac068d05e54a502aba1264fe\tafdesignload-color.afdesign\tMIT\thttps://example.org/color.afdesign +//! 9a17f500d09fb3b1a70d24aabdc2882955ec3eac3700a474549e6100be3a8484\tmore/layer_mode.afdesign +//! ``` +//! +//! [`Manifest::parse`] skips blank lines and lines whose first character other than a space or a +//! tab is `#`. A `#` later in a row is part of that row. It returns a [`ManifestError`] naming the +//! line of a row with fewer than 2 or more than 4 columns, a digest that is not 64 hexadecimal +//! digits, a path that is empty, absolute or leaves the folder, or a path listed twice. Paths use +//! `/` between their parts. +//! +//! [`pinned`] is the gate a test calls: it returns the corpus folder named by a variable after +//! checking every listed file, prints one `SKIPPED:` line and returns `None` when the variable is +//! unset and the corpus is optional, and fails the test otherwise. [`verify`] runs the same check +//! and returns a [`VerifyError`] instead of failing. No function here downloads a file or changes +//! the process environment. +//! +//! Every input has a size limit, set by [`Limits`]: a manifest of at most 1 MiB and 10,000 rows, +//! and files of at most 8 GiB each, read 64 KiB at a time. + +use std::collections::HashSet; +use std::ffi::{OsStr, OsString}; +use std::fmt; +use std::fs::File; +use std::io::{self, Read}; +use std::path::{Path, PathBuf}; + +use sha2::{Digest, Sha256}; + +/// The variable [`pinned`] reads when the caller names none. +pub const DEFAULT_VAR: &str = "CRAFT_CORPUS"; + +/// The suffix [`pinned`] adds to the folder variable's name to form the name of the variable that +/// makes the corpus required. +pub const REQUIRED_SUFFIX: &str = "_REQUIRED"; + +/// The size of each read while a file is hashed. +const CHUNK: usize = 64 * 1024; + +/// Size limits for a manifest and for the files it lists. An input over a limit is an error. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Limits { + /// The largest manifest in bytes. Default 1 MiB. + pub max_manifest_bytes: usize, + /// The most rows a manifest may list. Default 10,000. + pub max_entries: usize, + /// The largest listed file in bytes. Default 8 GiB. + pub max_file_bytes: u64, +} + +impl Default for Limits { + fn default() -> Self { + Self { max_manifest_bytes: 1024 * 1024, max_entries: 10_000, max_file_bytes: 8 * 1024 * 1024 * 1024 } + } +} + +/// One row of a manifest. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Entry { + digest: [u8; 32], + path: String, + license: Option, + url: Option, + line: usize, +} + +impl Entry { + /// The file's SHA-256. + pub fn digest(&self) -> &[u8; 32] { + &self.digest + } + + /// The file's path relative to the corpus folder, with `/` between its parts. + pub fn path(&self) -> &str { + &self.path + } + + /// The license column, when the row has one that is not empty. + pub fn license(&self) -> Option<&str> { + self.license.as_deref() + } + + /// The URL column, when the row has one that is not empty. + pub fn url(&self) -> Option<&str> { + self.url.as_deref() + } + + /// The 1-based line of the manifest that holds the row. + pub fn line(&self) -> usize { + self.line + } + + /// The file's path under `dir`. + fn path_in(&self, dir: &Path) -> PathBuf { + let mut path = dir.to_path_buf(); + path.extend(self.path.split('/')); + path + } +} + +/// A parsed manifest: the rows in the order the manifest lists them. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Manifest { + entries: Vec, +} + +impl Manifest { + /// Parses `text` under the default [`Limits`]. + pub fn parse(text: &str) -> Result { + Self::parse_with_limits(text, &Limits::default()) + } + + /// Parses `text`. A manifest longer than `limits.max_manifest_bytes` or with more than + /// `limits.max_entries` rows is an error. + pub fn parse_with_limits(text: &str, limits: &Limits) -> Result { + if text.len() > limits.max_manifest_bytes { + return Err(ManifestError::TooLarge { limit: limits.max_manifest_bytes }); + } + let mut entries: Vec = Vec::new(); + let mut seen: HashSet<&str> = HashSet::new(); + for (index, raw) in text.lines().enumerate() { + let line = index + 1; + let content = raw.trim_start_matches([' ', '\t']); + if content.trim().is_empty() || content.starts_with('#') { + continue; + } + if entries.len() == limits.max_entries { + return Err(ManifestError::TooManyEntries { limit: limits.max_entries }); + } + let columns: Vec<&str> = raw.split('\t').collect(); + if !(2..=4).contains(&columns.len()) { + return Err(ManifestError::Columns { line, found: columns.len() }); + } + let digest = parse_digest(columns[0]).ok_or(ManifestError::Digest { line })?; + let path = columns[1]; + check_path(path).map_err(|reason| ManifestError::Path { line, reason })?; + if !seen.insert(path) { + let first = entries.iter().find(|e| e.path == path).map_or(0, |e| e.line); + return Err(ManifestError::Duplicate { line, first }); + } + let optional = |i: usize| columns.get(i).filter(|c| !c.is_empty()).map(|c| (*c).to_owned()); + entries.push(Entry { digest, path: path.to_owned(), license: optional(2), url: optional(3), line }); + } + Ok(Self { entries }) + } + + /// Reads and parses the manifest file at `path`. A path that is not a regular file is refused + /// before it is opened. Reading stops after `limits.max_manifest_bytes` bytes plus one, so an + /// oversized file is not read whole. + pub fn read(path: &Path, limits: &Limits) -> Result { + if !std::fs::metadata(path).map_err(ManifestError::Io)?.is_file() { + return Err(ManifestError::NotAFile); + } + let file = File::open(path).map_err(ManifestError::Io)?; + if !file.metadata().map_err(ManifestError::Io)?.is_file() { + return Err(ManifestError::NotAFile); + } + let cap = u64::try_from(limits.max_manifest_bytes).unwrap_or(u64::MAX).saturating_add(1); + let mut bytes = Vec::new(); + file.take(cap).read_to_end(&mut bytes).map_err(ManifestError::Io)?; + if bytes.len() > limits.max_manifest_bytes { + return Err(ManifestError::TooLarge { limit: limits.max_manifest_bytes }); + } + let text = String::from_utf8(bytes).map_err(|_| ManifestError::NotUtf8)?; + Self::parse_with_limits(&text, limits) + } + + /// The rows, in manifest order. + pub fn entries(&self) -> &[Entry] { + &self.entries + } + + /// The paths of the rows, in manifest order. + pub fn names(&self) -> impl Iterator { + self.entries.iter().map(Entry::path) + } +} + +/// Decodes 64 ASCII hexadecimal digits, in either case. +fn parse_digest(text: &str) -> Option<[u8; 32]> { + let bytes = text.as_bytes(); + if bytes.len() != 64 { + return None; + } + let mut digest = [0u8; 32]; + let (pairs, _) = bytes.as_chunks::<2>(); + for (out, &[high, low]) in digest.iter_mut().zip(pairs) { + let high = char::from(high).to_digit(16)?; + let low = char::from(low).to_digit(16)?; + *out = u8::try_from(high * 16 + low).ok()?; + } + Some(digest) +} + +/// Checks that `path` is relative and stays in the corpus folder: parts separated by `/`, none +/// empty, `.` or `..`, and no `\`, `:` or NUL anywhere, so the same row means the same file on +/// every platform. +fn check_path(path: &str) -> Result<(), PathError> { + if path.is_empty() { + return Err(PathError::Empty); + } + if path.contains(['\\', ':', '\0']) { + return Err(PathError::Character); + } + for part in path.split('/') { + match part { + "" => return Err(if path.starts_with('/') { PathError::Absolute } else { PathError::EmptyPart }), + "." | ".." => return Err(PathError::DotPart), + _ => {} + } + } + Ok(()) +} + +/// Why a manifest path was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PathError { + /// The path is empty. + Empty, + /// The path starts with `/`. + Absolute, + /// The path has an empty part (`a//b`, or a trailing `/`). + EmptyPart, + /// The path has a `.` or `..` part. + DotPart, + /// The path holds a `\`, a `:` or a NUL character. + Character, +} + +impl fmt::Display for PathError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match self { + Self::Empty => "the path is empty", + Self::Absolute => "the path is absolute", + Self::EmptyPart => "the path has an empty part", + Self::DotPart => "the path has a . or .. part", + Self::Character => "the path holds a \\, a : or a NUL character", + }) + } +} + +/// Why a manifest could not be read or parsed. +#[derive(Debug)] +pub enum ManifestError { + /// The manifest is longer than the limit in bytes. + TooLarge { + /// The limit in bytes. + limit: usize, + }, + /// The manifest lists more rows than the limit. + TooManyEntries { + /// The limit in rows. + limit: usize, + }, + /// A row does not have 2, 3 or 4 tab-separated columns. + Columns { + /// The 1-based line of the row. + line: usize, + /// The number of columns found. + found: usize, + }, + /// A row's digest is not 64 hexadecimal digits. + Digest { + /// The 1-based line of the row. + line: usize, + }, + /// A row's path is refused. + Path { + /// The 1-based line of the row. + line: usize, + /// Why the path is refused. + reason: PathError, + }, + /// A row repeats the path of an earlier row. + Duplicate { + /// The 1-based line of the repeated row. + line: usize, + /// The 1-based line of the earlier row. + first: usize, + }, + /// The manifest path does not name a regular file. + NotAFile, + /// The manifest file is not UTF-8. + NotUtf8, + /// The manifest file could not be read. + Io(io::Error), +} + +impl fmt::Display for ManifestError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::TooLarge { limit } => write!(f, "the manifest is longer than {limit} bytes"), + Self::TooManyEntries { limit } => write!(f, "the manifest lists more than {limit} files"), + Self::Columns { line, found } => write!(f, "line {line}: {found} tab-separated columns, expected 2 to 4"), + Self::Digest { line } => write!(f, "line {line}: the SHA-256 is not 64 hexadecimal digits"), + Self::Path { line, reason } => write!(f, "line {line}: {reason}"), + Self::Duplicate { line, first } => write!(f, "line {line}: the path is already listed on line {first}"), + Self::NotAFile => f.write_str("the manifest is not a regular file"), + Self::NotUtf8 => f.write_str("the manifest is not UTF-8"), + Self::Io(error) => write!(f, "the manifest could not be read: {error}"), + } + } +} + +impl std::error::Error for ManifestError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Io(error) => Some(error), + _ => None, + } + } +} + +/// Why a corpus folder does not match its manifest. +#[derive(Debug)] +pub enum VerifyError { + /// The manifest lists no files, so the folder would be accepted without a check. + EmptyManifest, + /// The corpus folder could not be resolved. + Folder { + /// The folder. + dir: PathBuf, + /// The error resolving it. + error: io::Error, + }, + /// A listed file is missing or could not be resolved. + Missing { + /// The path the manifest lists. + path: String, + /// The error resolving it. + error: io::Error, + }, + /// A listed path resolves outside the corpus folder, through a symbolic link. + Escapes { + /// The path the manifest lists. + path: String, + }, + /// A listed path is not a regular file. + NotAFile { + /// The path the manifest lists. + path: String, + }, + /// A listed file is larger than the limit. + TooLarge { + /// The path the manifest lists. + path: String, + /// The limit in bytes. + limit: u64, + }, + /// A listed file could not be read. + Read { + /// The path the manifest lists. + path: String, + /// The read error. + error: io::Error, + }, + /// A listed file's SHA-256 differs from the manifest's. + Modified { + /// The path the manifest lists. + path: String, + }, +} + +impl fmt::Display for VerifyError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::EmptyManifest => f.write_str("the manifest lists no files"), + Self::Folder { dir, error } => write!(f, "corpus folder {}: {error}", dir.display()), + Self::Missing { path, error } => write!(f, "{path}: missing: {error}"), + Self::Escapes { path } => write!(f, "{path}: resolves outside the corpus folder"), + Self::NotAFile { path } => write!(f, "{path}: not a regular file"), + Self::TooLarge { path, limit } => write!(f, "{path}: larger than {limit} bytes"), + Self::Read { path, error } => write!(f, "{path}: {error}"), + Self::Modified { path } => write!(f, "{path}: SHA-256 differs from the manifest"), + } + } +} + +impl std::error::Error for VerifyError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Folder { error, .. } | Self::Missing { error, .. } | Self::Read { error, .. } => Some(error), + _ => None, + } + } +} + +/// Checks every file `manifest` lists in `dir` under the default [`Limits`]. +pub fn verify(dir: &Path, manifest: &Manifest) -> Result<(), VerifyError> { + verify_with_limits(dir, manifest, &Limits::default()) +} + +/// Checks every file `manifest` lists in `dir`: each must resolve inside `dir` after symbolic +/// links are followed, be a regular file of at most `limits.max_file_bytes` bytes, and have the +/// listed SHA-256. Returns the first failure in manifest order. An empty manifest is an error. +pub fn verify_with_limits(dir: &Path, manifest: &Manifest, limits: &Limits) -> Result<(), VerifyError> { + if manifest.entries.is_empty() { + return Err(VerifyError::EmptyManifest); + } + let root = dir.canonicalize().map_err(|error| VerifyError::Folder { dir: dir.to_path_buf(), error })?; + let mut buf = vec![0u8; CHUNK]; + for entry in &manifest.entries { + verify_entry(&root, entry, limits, &mut buf)?; + } + Ok(()) +} + +fn verify_entry(root: &Path, entry: &Entry, limits: &Limits, buf: &mut [u8]) -> Result<(), VerifyError> { + let path = || entry.path.clone(); + let target = entry.path_in(root).canonicalize().map_err(|error| VerifyError::Missing { path: path(), error })?; + if !target.starts_with(root) { + return Err(VerifyError::Escapes { path: path() }); + } + let kind = std::fs::metadata(&target).map_err(|error| VerifyError::Read { path: path(), error })?; + if !kind.is_file() { + return Err(VerifyError::NotAFile { path: path() }); + } + let file = File::open(&target).map_err(|error| VerifyError::Read { path: path(), error })?; + let meta = file.metadata().map_err(|error| VerifyError::Read { path: path(), error })?; + if !meta.is_file() { + return Err(VerifyError::NotAFile { path: path() }); + } + if meta.len() > limits.max_file_bytes { + return Err(VerifyError::TooLarge { path: path(), limit: limits.max_file_bytes }); + } + let mut reader = file.take(limits.max_file_bytes.saturating_add(1)); + let mut hasher = Sha256::new(); + let mut total: u64 = 0; + loop { + let n = match reader.read(buf) { + Ok(0) => break, + Ok(n) => n, + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + Err(error) => return Err(VerifyError::Read { path: path(), error }), + }; + total = total.saturating_add(n as u64); + if total > limits.max_file_bytes { + return Err(VerifyError::TooLarge { path: path(), limit: limits.max_file_bytes }); + } + hasher.update(&buf[..n]); + } + if hasher.finalize().as_slice() != entry.digest.as_slice() { + return Err(VerifyError::Modified { path: path() }); + } + Ok(()) +} + +/// The corpus folder the variable `var` names (default [`DEFAULT_VAR`]), after every file +/// `manifest` lists has been checked with [`verify`]. +/// +/// The corpus is required when the variable named `var` plus [`REQUIRED_SUFFIX`] (by default +/// `CRAFT_CORPUS_REQUIRED`) is exactly `1`; unset, empty, `0`, `true` and any other value leave it +/// optional. +/// +/// - Folder variable unset and the corpus optional: prints one line, +/// `SKIPPED: corpus not given: set to its folder`, to stderr and returns `None`. +/// - Folder variable unset and the corpus required: fails the test. +/// - Folder variable set, even to an empty value: fails the test unless the manifest parses and +/// every listed file matches. +/// +/// It fails the test with a panic whose message names the variable and the failure. +#[allow(clippy::panic)] +pub fn pinned(var: Option<&str>, manifest: &str) -> Option { + let var = var.unwrap_or(DEFAULT_VAR); + let required_var = format!("{var}{REQUIRED_SUFFIX}"); + let required = std::env::var_os(&required_var).as_deref() == Some(OsStr::new("1")); + match gate(std::env::var_os(var), required, var, &required_var, manifest) { + Ok(Some(dir)) => Some(dir), + Ok(None) => { + eprintln!("SKIPPED: corpus not given: set {var} to its folder"); + None + } + Err(message) => panic!("{message}"), + } +} + +/// The decision of [`pinned`], without reading the environment or printing: `Ok(None)` skips and +/// `Err` holds the message the test fails with. +fn gate(folder: Option, required: bool, var: &str, required_var: &str, manifest: &str) -> Result, String> { + let Some(folder) = folder else { + return if required { Err(format!("corpus not given: {var} is unset and {required_var}=1 forbids skipping")) } else { Ok(None) }; + }; + if folder.is_empty() { + return Err(format!("{var} is set but empty")); + } + let dir = PathBuf::from(folder); + let manifest = Manifest::parse(manifest).map_err(|e| format!("corpus manifest for {var}: {e}"))?; + verify(&dir, &manifest).map_err(|e| format!("pinned corpus in {} ({var}): {e}", dir.display()))?; + Ok(Some(dir)) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::process::{Command, Output}; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// The case the child process runs; unset in an ordinary test run. + const CHILD_CASE: &str = "CRAFT_TESTKIT_CORPUS_CHILD"; + /// The folder variable the child's `pinned` reads. + const VAR: &str = "CRAFT_TESTKIT_CORPUS_DIR"; + /// The required variable that goes with [`VAR`]. + const REQUIRED: &str = "CRAFT_TESTKIT_CORPUS_DIR_REQUIRED"; + + const HELLO: &[u8] = b"hello world"; + /// SHA-256 of `hello world`. + const HELLO_SHA: &str = "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"; + const EMPTY_SHA: &str = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; + + /// A folder under the system temporary folder, removed on drop. + struct Scratch(PathBuf); + + impl Scratch { + fn new() -> Self { + static NEXT: AtomicUsize = AtomicUsize::new(0); + let n = NEXT.fetch_add(1, Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!("craft_testkit_corpus_{}_{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).expect("create scratch folder"); + Self(dir) + } + + fn write(&self, rel: &str, bytes: &[u8]) -> PathBuf { + let path = self.0.join(rel); + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).expect("create parent"); + } + std::fs::write(&path, bytes).expect("write file"); + path + } + } + + impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn parse_err(text: &str) -> ManifestError { + Manifest::parse(text).expect_err("the manifest is refused") + } + + #[test] + fn comments_are_skipped() { + let text = format!("# pinned corpus\n # indented comment\n\t# tab-indented comment\n{HELLO_SHA}\thello.txt\n#{EMPTY_SHA}\tempty.txt\n"); + let manifest = Manifest::parse(&text).expect("parse"); + assert_eq!(manifest.names().collect::>(), ["hello.txt"]); + assert_eq!(manifest.entries()[0].line(), 4); + } + + #[test] + fn a_hash_inside_a_row_is_not_a_comment() { + let manifest = Manifest::parse(&format!("{HELLO_SHA}\tdir/#1.txt\tMIT\thttps://example.org/a#b\n")).expect("parse"); + let entry = &manifest.entries()[0]; + assert_eq!(entry.path(), "dir/#1.txt"); + assert_eq!(entry.url(), Some("https://example.org/a#b")); + } + + #[test] + fn blank_lines_are_skipped() { + let text = format!("\n \n\t\n{HELLO_SHA}\thello.txt\n\n{EMPTY_SHA}\tempty.txt\n \t \n"); + let manifest = Manifest::parse(&text).expect("parse"); + assert_eq!(manifest.entries().len(), 2); + assert_eq!(manifest.entries()[0].line(), 4); + assert_eq!(manifest.entries()[1].line(), 6); + assert_eq!(Manifest::parse("").expect("parse").entries().len(), 0); + } + + #[test] + fn malformed_row_is_error() { + assert!(matches!(parse_err(HELLO_SHA), ManifestError::Columns { line: 1, found: 1 })); + assert!(matches!(parse_err(&format!("# c\n{HELLO_SHA} hello.txt\n")), ManifestError::Columns { line: 2, found: 1 })); + assert!(matches!(parse_err(&format!("{HELLO_SHA}\ta\tMIT\turl\textra\n")), ManifestError::Columns { line: 1, found: 5 })); + assert!(matches!(parse_err(&format!("{HELLO_SHA}\t\n")), ManifestError::Path { line: 1, reason: PathError::Empty })); + assert!(matches!(parse_err("\thello.txt\n"), ManifestError::Digest { line: 1 })); + } + + #[test] + fn wrong_digest_length_is_error() { + assert!(matches!(parse_err(&format!("{}\ta\n", &HELLO_SHA[..63])), ManifestError::Digest { line: 1 })); + assert!(matches!(parse_err(&format!("{HELLO_SHA}0\ta\n")), ManifestError::Digest { line: 1 })); + assert!(matches!(parse_err(&format!(" {HELLO_SHA}\ta\n")), ManifestError::Digest { line: 1 })); + } + + #[test] + fn non_hex_digest_is_error() { + let bad = format!("{}g", &HELLO_SHA[..63]); + assert!(matches!(parse_err(&format!("{bad}\ta\n")), ManifestError::Digest { line: 1 })); + let sign = format!("+{}", &HELLO_SHA[..63]); + assert!(matches!(parse_err(&format!("{sign}\ta\n")), ManifestError::Digest { line: 1 })); + let wide = format!("{}é", &HELLO_SHA[..62]); + assert!(matches!(parse_err(&format!("{wide}\ta\n")), ManifestError::Digest { line: 1 })); + } + + #[test] + fn rows_take_two_to_four_columns_and_empty_optional_columns_are_none() { + let text = format!( + "{HELLO_SHA}\ta.txt\n{HELLO_SHA}\tb.txt\tMIT\n{HELLO_SHA}\tc.txt\tMIT\thttps://example.org/c\n{HELLO_SHA}\td.txt\t\n{HELLO_SHA}\te.txt\t\thttps://example.org/e\n" + ); + let manifest = Manifest::parse(&text).expect("parse"); + let cols: Vec<_> = manifest.entries().iter().map(|e| (e.path(), e.license(), e.url())).collect(); + assert_eq!( + cols, + [ + ("a.txt", None, None), + ("b.txt", Some("MIT"), None), + ("c.txt", Some("MIT"), Some("https://example.org/c")), + ("d.txt", None, None), + ("e.txt", None, Some("https://example.org/e")), + ] + ); + } + + #[test] + fn crlf_lines_and_uppercase_digests_parse() { + let upper = HELLO_SHA.to_ascii_uppercase(); + let manifest = Manifest::parse(&format!("# c\r\n{upper}\thello.txt\tMIT\r\n\r\n")).expect("parse"); + let entry = &manifest.entries()[0]; + assert_eq!(entry.license(), Some("MIT")); + assert_eq!(entry.digest()[..4], [0xb9, 0x4d, 0x27, 0xb9]); + assert_eq!(entry.digest(), Manifest::parse(&format!("{HELLO_SHA}\thello.txt")).expect("parse").entries()[0].digest()); + } + + #[test] + fn duplicate_path_is_error() { + let text = format!("{HELLO_SHA}\ta/b.txt\n# c\n{HELLO_SHA}\ta/b.txt\n"); + assert!(matches!(parse_err(&text), ManifestError::Duplicate { line: 3, first: 1 })); + } + + #[test] + fn paths_that_leave_the_folder_are_errors() { + let cases = [ + ("/etc/passwd", PathError::Absolute), + ("../outside", PathError::DotPart), + ("a/../../outside", PathError::DotPart), + ("./a", PathError::DotPart), + ("a//b", PathError::EmptyPart), + ("a/", PathError::EmptyPart), + ("C:/Windows/win.ini", PathError::Character), + ("C:a", PathError::Character), + ("\\\\server\\share\\a", PathError::Character), + ("a\\..\\..\\b", PathError::Character), + ]; + for (path, expected) in cases { + match parse_err(&format!("{HELLO_SHA}\t{path}\n")) { + ManifestError::Path { line: 1, reason } => assert_eq!(reason, expected, "{path}"), + other => panic!("{path}: {other}"), + } + } + } + + #[test] + fn manifest_limits_are_errors() { + let text = format!("{HELLO_SHA}\ta\n{HELLO_SHA}\tb\n"); + let limits = Limits { max_entries: 1, ..Limits::default() }; + assert!(matches!(Manifest::parse_with_limits(&text, &limits), Err(ManifestError::TooManyEntries { limit: 1 }))); + let limits = Limits { max_entries: 2, ..Limits::default() }; + assert_eq!(Manifest::parse_with_limits(&text, &limits).expect("parse").entries().len(), 2); + + let limits = Limits { max_manifest_bytes: text.len() - 1, ..Limits::default() }; + assert!(matches!(Manifest::parse_with_limits(&text, &limits), Err(ManifestError::TooLarge { .. }))); + let limits = Limits { max_manifest_bytes: text.len(), ..Limits::default() }; + assert!(Manifest::parse_with_limits(&text, &limits).is_ok()); + + let scratch = Scratch::new(); + let path = scratch.write("corpus.tsv", text.as_bytes()); + assert_eq!(Manifest::read(&path, &Limits::default()).expect("read").entries().len(), 2); + let limits = Limits { max_manifest_bytes: text.len() - 1, ..Limits::default() }; + assert!(matches!(Manifest::read(&path, &limits), Err(ManifestError::TooLarge { .. }))); + let bad = scratch.write("bad.tsv", b"\xff\xfe"); + assert!(matches!(Manifest::read(&bad, &Limits::default()), Err(ManifestError::NotUtf8))); + assert!(matches!(Manifest::read(&scratch.0.join("absent.tsv"), &Limits::default()), Err(ManifestError::Io(_)))); + } + + fn hello_corpus() -> (Scratch, Manifest) { + let scratch = Scratch::new(); + scratch.write("hello.txt", HELLO); + scratch.write("sub/empty.bin", b""); + let manifest = Manifest::parse(&format!("{HELLO_SHA}\thello.txt\tMIT\n{EMPTY_SHA}\tsub/empty.bin\n")).expect("parse"); + (scratch, manifest) + } + + #[test] + fn a_matching_folder_verifies() { + let (scratch, manifest) = hello_corpus(); + verify(&scratch.0, &manifest).expect("the corpus matches"); + } + + #[test] + fn missing_file_fails() { + let (scratch, manifest) = hello_corpus(); + std::fs::remove_file(scratch.0.join("sub").join("empty.bin")).expect("remove"); + match verify(&scratch.0, &manifest) { + Err(VerifyError::Missing { path, .. }) => assert_eq!(path, "sub/empty.bin"), + other => panic!("{other:?}"), + } + assert!(matches!(verify(&scratch.0.join("absent"), &manifest), Err(VerifyError::Folder { .. }))); + } + + #[test] + fn modified_file_fails() { + let (scratch, manifest) = hello_corpus(); + scratch.write("hello.txt", b"hello world!"); + match verify(&scratch.0, &manifest) { + Err(VerifyError::Modified { path }) => assert_eq!(path, "hello.txt"), + other => panic!("{other:?}"), + } + } + + #[test] + fn an_empty_manifest_or_a_folder_entry_fails() { + let (scratch, _) = hello_corpus(); + assert!(matches!(verify(&scratch.0, &Manifest::default()), Err(VerifyError::EmptyManifest))); + let manifest = Manifest::parse(&format!("{EMPTY_SHA}\tsub\n")).expect("parse"); + assert!(matches!(verify(&scratch.0, &manifest), Err(VerifyError::NotAFile { .. }))); + } + + /// A named pipe is refused before it is opened; opening one for reading waits for a writer. + #[cfg(unix)] + #[test] + fn a_named_pipe_fails_without_being_opened() { + let scratch = Scratch::new(); + let fifo = scratch.0.join("pipe"); + let made = Command::new("mkfifo").arg(&fifo).status().expect("run mkfifo"); + assert!(made.success(), "mkfifo failed"); + let manifest = Manifest::parse(&format!("{EMPTY_SHA}\tpipe\n")).expect("parse"); + match verify(&scratch.0, &manifest) { + Err(VerifyError::NotAFile { path }) => assert_eq!(path, "pipe"), + other => panic!("{other:?}"), + } + } + + /// A manifest path that names a named pipe or a folder is refused before it is opened. + #[cfg(unix)] + #[test] + fn a_manifest_that_is_not_a_file_fails_without_being_opened() { + let scratch = Scratch::new(); + let fifo = scratch.0.join("corpus.tsv"); + let made = Command::new("mkfifo").arg(&fifo).status().expect("run mkfifo"); + assert!(made.success(), "mkfifo failed"); + assert!(matches!(Manifest::read(&scratch.0, &Limits::default()), Err(ManifestError::NotAFile))); + assert!(matches!(Manifest::read(&fifo, &Limits::default()), Err(ManifestError::NotAFile))); + } + + #[test] + fn file_size_limit_is_error() { + let (scratch, manifest) = hello_corpus(); + let limits = Limits { max_file_bytes: HELLO.len() as u64, ..Limits::default() }; + verify_with_limits(&scratch.0, &manifest, &limits).expect("a file at the limit passes"); + let limits = Limits { max_file_bytes: HELLO.len() as u64 - 1, ..Limits::default() }; + match verify_with_limits(&scratch.0, &manifest, &limits) { + Err(VerifyError::TooLarge { path, limit }) => assert_eq!((path.as_str(), limit), ("hello.txt", 10)), + other => panic!("{other:?}"), + } + } + + #[test] + fn a_file_larger_than_one_read_hashes_whole() { + let scratch = Scratch::new(); + let bytes: Vec = (0..CHUNK * 2 + 7).map(|i| (i % 251) as u8).collect(); + scratch.write("big.bin", &bytes); + let hex: String = Sha256::digest(&bytes).iter().map(|b| format!("{b:02x}")).collect(); + let manifest = Manifest::parse(&format!("{hex}\tbig.bin\n")).expect("parse"); + verify(&scratch.0, &manifest).expect("the whole file is hashed"); + scratch.write("big.bin", &bytes[..CHUNK]); + assert!(matches!(verify(&scratch.0, &manifest), Err(VerifyError::Modified { .. }))); + } + + #[cfg(unix)] + #[test] + fn a_symbolic_link_out_of_the_folder_fails() { + let outside = Scratch::new(); + let target = outside.write("hello.txt", HELLO); + let corpus = Scratch::new(); + std::os::unix::fs::symlink(&target, corpus.0.join("hello.txt")).expect("symlink"); + let manifest = Manifest::parse(&format!("{HELLO_SHA}\thello.txt\n")).expect("parse"); + match verify(&corpus.0, &manifest) { + Err(VerifyError::Escapes { path }) => assert_eq!(path, "hello.txt"), + other => panic!("{other:?}"), + } + std::os::unix::fs::symlink(&outside.0, corpus.0.join("out")).expect("symlink"); + let manifest = Manifest::parse(&format!("{HELLO_SHA}\tout/hello.txt\n")).expect("parse"); + assert!(matches!(verify(&corpus.0, &manifest), Err(VerifyError::Escapes { .. }))); + } + + #[test] + fn the_gate_skips_only_an_optional_unset_corpus() { + let (scratch, _) = hello_corpus(); + let manifest = format!("{HELLO_SHA}\thello.txt\n"); + assert_eq!(gate(None, false, VAR, REQUIRED, &manifest), Ok(None)); + let required = gate(None, true, VAR, REQUIRED, &manifest).expect_err("required"); + assert!(required.contains(&format!("{REQUIRED}=1")), "{required}"); + let dir = scratch.0.clone().into_os_string(); + assert_eq!(gate(Some(dir.clone()), false, VAR, REQUIRED, &manifest), Ok(Some(scratch.0.clone()))); + let empty = gate(Some(OsString::new()), false, VAR, REQUIRED, &manifest).expect_err("empty"); + assert!(empty.contains("empty"), "{empty}"); + let bad = gate(Some(dir.clone()), false, VAR, REQUIRED, "# c\nnot a row\n").expect_err("bad manifest"); + assert!(bad.contains("line 2"), "{bad}"); + let missing = gate(Some(dir), false, VAR, REQUIRED, &format!("{EMPTY_SHA}\tabsent.bin\n")).expect_err("missing"); + assert!(missing.contains("absent.bin"), "{missing}"); + } + + /// Runs `child` below in a new process of this test binary with the given variables set and + /// every other corpus variable removed, so no test changes this process's environment. + fn run_child(case: &str, vars: &[(&str, &str)]) -> Output { + let exe = std::env::current_exe().expect("the test binary's path"); + let mut cmd = Command::new(exe); + cmd.args(["corpus::tests::child", "--exact", "--nocapture", "--test-threads=1"]).env(CHILD_CASE, case); + for name in [VAR, REQUIRED, DEFAULT_VAR, "CRAFT_CORPUS_REQUIRED"] { + cmd.env_remove(name); + } + for (name, value) in vars { + cmd.env(name, value); + } + cmd.output().expect("run the test binary") + } + + #[test] + fn child() { + let Some(case) = std::env::var_os(CHILD_CASE) else { + return; + }; + let manifest = format!("{HELLO_SHA}\thello.txt\n"); + let found = match case.to_str() { + Some("named") => pinned(Some(VAR), &manifest), + Some("default") => pinned(None, &manifest), + other => panic!("unknown child case {other:?}"), + }; + eprintln!("pinned returned {}", found.map_or_else(|| "none".to_owned(), |d| d.display().to_string())); + } + + #[test] + fn required_variable_unset_fails() { + for value in [None, Some(""), Some("0"), Some("true"), Some(" 1"), Some("1\n")] { + let vars: Vec<(&str, &str)> = value.map(|v| (REQUIRED, v)).into_iter().collect(); + let out = run_child("named", &vars); + let err = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{value:?}: {err}"); + assert_eq!(err.matches(&format!("SKIPPED: corpus not given: set {VAR} to its folder\n")).count(), 1, "{value:?}: {err}"); + assert!(err.contains("pinned returned none"), "{value:?}: {err}"); + } + let out = run_child("named", &[(REQUIRED, "1")]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err}"); + assert!(err.contains(&format!("{REQUIRED}=1 forbids skipping")), "{err}"); + assert!(!err.contains("SKIPPED:"), "{err}"); + assert!(!err.contains("pinned returned"), "{err}"); + } + + #[test] + fn pinned_reads_the_named_folder_and_fails_on_a_bad_one() { + let (scratch, _) = hello_corpus(); + let dir = scratch.0.to_str().expect("a UTF-8 temporary path"); + let out = run_child("named", &[(VAR, dir)]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{err}"); + assert!(err.contains(&format!("pinned returned {dir}")), "{err}"); + + scratch.write("hello.txt", b"changed"); + let out = run_child("named", &[(VAR, dir)]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("hello.txt: SHA-256 differs from the manifest"), "{err}"); + + let out = run_child("named", &[(VAR, "")]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err}"); + assert!(err.contains(&format!("{VAR} is set but empty")), "{err}"); + } + + #[test] + fn pinned_defaults_to_craft_corpus() { + let out = run_child("default", &[]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(out.status.success(), "{err}"); + assert!(err.contains("SKIPPED: corpus not given: set CRAFT_CORPUS to its folder\n"), "{err}"); + + let out = run_child("default", &[("CRAFT_CORPUS_REQUIRED", "1")]); + let err = String::from_utf8_lossy(&out.stderr); + assert!(!out.status.success(), "{err}"); + assert!(err.contains("CRAFT_CORPUS_REQUIRED=1 forbids skipping"), "{err}"); + } +} diff --git a/crates/testkit/src/lib.rs b/crates/testkit/src/lib.rs index b484c6ef69..bb41162311 100644 --- a/crates/testkit/src/lib.rs +++ b/crates/testkit/src/lib.rs @@ -15,6 +15,10 @@ //! * [`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`. //! +//! With the `corpus` feature, `corpus` (native only) parses pinned-corpus manifests and checks a +//! corpus folder against them: `corpus::Manifest`, `corpus::verify` and the test gate +//! `corpus::pinned`. +//! //! ### Epistemic Scope: What Source Guards Establish vs What They Cannot //! //! Source-level guards provide deterministic syntactic evidence about codebase structure. @@ -25,6 +29,8 @@ //! under foreign host environments. They are lightweight syntactic regression gates designed to complement, //! rather than replace, platform integration tests and CI execution. +#[cfg(all(feature = "corpus", not(target_arch = "wasm32")))] +pub mod corpus; pub mod guards; pub use guards::{AsFileSource, Finding, predefined_quit, std_instant, wgsl_float_literals, wgsl_float_literals_in}; From 50aabe2c5a62186475489e25c1aec008e2bf8841 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:18:49 -0800 Subject: [PATCH 030/786] craft-xtask: add the workspace version command The version feature adds version::run, which reads the [workspace.package] version of the root Cargo.toml and, with set X.Y.Z[-pre], writes it and runs cargo update --workspace (offline first). The caller passes its workspace root, its Cargo program and the words after version. - validate rejects build metadata, leading zeros, numbers above u64::MAX and numeric prerelease identifiers with a leading zero. - replace also moves the version of each path dependency in [workspace.dependencies] whose requirement is "OLD" or "=OLD". - The manifest is read with a one-pass TOML scanner that keeps comments, quotes and LF, CRLF and CR line endings, and accepts the version as a table key, a dotted key or an inline table. A manifest it cannot read, a duplicate version or an invalid current version is an error before anything is written. - When both updates fail, Cargo.toml and Cargo.lock are put back and the error says so. Both files are replaced through craft-atomic. - Cargo.toml is read up to 1 MiB and Cargo.lock up to 64 MiB by default (Limits). - One set runs at a time in a workspace. A set takes its locks before it reads Cargo.toml and holds them until it returns: on Unix the workspace directory, on Windows workspace.lock opened without delete sharing, plus an owner-labeled lock in target/xtask-version/version-/ and, when it can be opened, one in ~/.cache/craft-xtask/version-/. A set that finds a lock held returns an error naming the other run and writes nothing. lock_dirs returns the lock directories. The version feature turns on lock. From SoundCraft xtask/src/version.rs (6c84416c) and PdfCraft xtask/src/version.rs (3e306453); their tests move in under the same names. --- crates/xtask/Cargo.toml | 5 +- crates/xtask/README.md | 48 +- crates/xtask/src/lib.rs | 5 + crates/xtask/src/version.rs | 1161 +++++++++++++++++++++++++++++++++++ 4 files changed, 1217 insertions(+), 2 deletions(-) create mode 100644 crates/xtask/src/version.rs diff --git a/crates/xtask/Cargo.toml b/crates/xtask/Cargo.toml index 6b561b543b..45a71758d6 100644 --- a/crates/xtask/Cargo.toml +++ b/crates/xtask/Cargo.toml @@ -5,7 +5,7 @@ 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" +description = "Library for the Craft apps' cargo xtask binaries: the gate's step runner, an optional slot lock shared across processes, a per-step JSON report and the workspace version command" [lints] workspace = true @@ -16,6 +16,9 @@ default = [] lock = [] # The per-step JSON report, replaced atomically. report = ["dep:serde_json", "dep:craft-atomic"] +# `cargo xtask version [set X.Y.Z[-pre]]`, with Cargo.toml and Cargo.lock replaced atomically and one +# `set` at a time per workspace through `lock`. +version = ["lock", "dep:craft-atomic"] [dependencies] craft-atomic = { workspace = true, optional = true } diff --git a/crates/xtask/README.md b/crates/xtask/README.md index 75228c3d66..4bc5243f0c 100644 --- a/crates/xtask/README.md +++ b/crates/xtask/README.md @@ -9,8 +9,9 @@ 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` | +| `version` | `version` | `run`, `run_with`, `Limits`, `lock_dirs`, `read`, `replace`, `validate`: `cargo xtask version [set X.Y.Z[-pre]]` on the root `Cargo.toml` | -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`; `version` adds `craft-atomic` and turns on `lock`. ## Use @@ -91,6 +92,47 @@ 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. +## Version + +```rust,no_run +use std::path::Path; +use craft_xtask::runner; + +/// `rest` holds the words after `version`. +fn version(rest: &[&str]) -> Result<(), String> { + let root = runner::root(Path::new(env!("CARGO_MANIFEST_DIR")))?; + let cargo = std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into()); + craft_xtask::version::run(&root, &cargo, rest) +} +``` + +- `cargo xtask version` prints the `version` of `[workspace.package]`. +- `cargo xtask version set X.Y.Z[-pre]` checks the new version, writes it into `Cargo.toml`, runs + `cargo update --workspace --offline` in the root and, when that fails, `cargo update --workspace`, + and prints `version: OLD -> NEW`. It also moves the `version` of each path dependency in + `[workspace.dependencies]` whose requirement is `"OLD"` or `"=OLD"`; registry dependencies and path + dependencies at other versions keep theirs. +- A version is `MAJOR.MINOR.PATCH` with an optional `-pre.release`: no leading zeros, numbers up to + `u64::MAX`, and no build metadata (`+...`). +- When both updates fail, `Cargo.toml` and `Cargo.lock` are put back as they were (a lock file that did + not exist is removed) and the error says so. Both files are replaced atomically through + `craft-atomic`. +- Setting the current version prints `version: OLD (unchanged)` and writes only its lock file. +- One `set` runs at a time in a workspace. Before it reads `Cargo.toml`, it takes its locks and + holds them until it returns. On Unix it locks the workspace directory itself; on Windows it locks + `workspace.lock` in the first directory below, opened so that the file cannot be deleted while it + is held. Every process that writes the workspace shares that lock, and `cargo clean` cannot remove + it. It also takes the locks in `lock_dirs(root)`: + `target/xtask-version/version-/` (required; its owner file names the + run) and `~/.cache/craft-xtask/version-/` (when its file can be + opened). A `set` that finds a lock held returns an error naming the other run and writes + nothing. +- The root manifest is read with a scanner that keeps comments, quotes and line endings (LF, CRLF and + CR) and accepts the version as `[workspace.package]` `version`, a dotted key or an inline table. A + manifest it cannot read, a duplicate version, a version that is not a one-line string, or a current + version that is not valid is an error before anything is written. `Cargo.toml` is read up to 1 MiB + and `Cargo.lock` up to 64 MiB by default; `run_with` takes other `Limits`. + ## Origin | Part | Source | @@ -98,6 +140,9 @@ 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) | +| `version`: `read`, `validate` with the overflow and prerelease checks, the restore after a failed update, and the tests `reads_the_workspace_version`, `replaces_only_the_workspace_version`, `keeps_crlf_line_endings`, `validates_versions`, `rejects_what_cargo_rejects`, `a_failed_update_restores_the_manifest` | SoundCraft `xtask/src/version.rs` at [6c84416](https://github.com/storytold/soundcraft/blob/6c84416c3cffb72d8d350ddfefc4fc9ee954ca1a/xtask/src/version.rs) | +| `version`: the path dependency pins and the test `moves_the_workspace_crates_pins_with_it` | PdfCraft `xtask/src/version.rs` at [3e30645](https://github.com/storytold/pdfcraft/blob/3e3064532f04fd6ec769c6bd7b2c97464757970e/xtask/src/version.rs) | +| `version`: the TOML scanner, the `=OLD` pins, the `Cargo.lock` restore, the size limits, the unchanged-version case and the one-`set`-at-a-time lock | written here | | The root and slot-count errors, the `--exclude` of the xtask package, cancellation, the bounded owner read and the atomic report | written here | ## Migration @@ -108,6 +153,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. | +| SoundCraft, PdfCraft | Planned: `xtask/src/version.rs` moves to `version`, with the app's root and `CARGO` passed to `run`. `the_real_manifest_has_a_valid_version`, and PdfCraft's `workspace_rust_version_covers_the_ui_crate`, stay 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 index 2ed8390e00..c65a545f23 100644 --- a/crates/xtask/src/lib.rs +++ b/crates/xtask/src/lib.rs @@ -12,6 +12,9 @@ //! - `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. +//! - `version` (feature `version`): `cargo xtask version [set X.Y.Z[-pre]]`, which reads and sets the +//! `[workspace.package]` version of the root `Cargo.toml` and moves the workspace crates' path +//! dependency pins with it. //! //! ```no_run //! use std::path::Path; @@ -40,6 +43,8 @@ pub mod lock; #[cfg(feature = "report")] pub mod report; pub mod runner; +#[cfg(feature = "version")] +pub mod version; /// 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/version.rs b/crates/xtask/src/version.rs new file mode 100644 index 0000000000..ed166f0c70 --- /dev/null +++ b/crates/xtask/src/version.rs @@ -0,0 +1,1161 @@ +//! `cargo xtask version [set X.Y.Z[-pre]]`: the workspace version in the root `Cargo.toml`. +//! +//! The version is the `version` key of `[workspace.package]`; member crates inherit it with +//! `version.workspace = true`. [`read`] returns it, [`validate`] checks a new one and [`replace`] +//! returns the manifest with the new version, together with the `version` of every path dependency +//! in `[workspace.dependencies]` whose requirement is the old version (`"OLD"` or `"=OLD"`). +//! [`run`] is the command: the caller passes its workspace root, the Cargo program to run and the +//! words after `version`. +//! +//! The manifest is read with a small TOML scanner that keeps every byte outside the changed strings, +//! comments and line endings included. The root version may be written in any TOML form +//! (`[workspace.package]` with `version = "…"`, a dotted key, an inline table), with double or +//! single quotes. A manifest the scanner cannot read, a duplicate key, a version that is not a +//! one-line string, or a current version that is not valid returns an error before anything is +//! written. + +use std::collections::HashSet; +use std::ffi::OsStr; +use std::fs::File; +use std::io::{self, Read, Write}; +use std::ops::Range; +use std::path::{Path, PathBuf}; +use std::process::Command; + +/// The largest root `Cargo.toml` [`run`] reads, in bytes. +pub const DEFAULT_MAX_MANIFEST_BYTES: u64 = 1 << 20; +/// The largest `Cargo.lock` [`run`] keeps in memory to put back after a failed `cargo update`, in bytes. +pub const DEFAULT_MAX_LOCK_BYTES: u64 = 64 << 20; +/// How deeply arrays and inline tables may nest in the manifest. +const MAX_DEPTH: usize = 64; +const USAGE: &str = "usage: cargo xtask version [set X.Y.Z[-pre]]"; +const ROOT_VERSION: [&str; 3] = ["workspace", "package", "version"]; + +/// Size limits for [`run_with`]. +#[non_exhaustive] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Limits { + /// The largest root `Cargo.toml` that is read; a larger one is an error before anything is written. + pub max_manifest_bytes: u64, + /// The largest `Cargo.lock` that is kept to put back after a failed update; a larger one is an + /// error before anything is written. + pub max_lock_bytes: u64, +} + +impl Default for Limits { + fn default() -> Self { + Self { max_manifest_bytes: DEFAULT_MAX_MANIFEST_BYTES, max_lock_bytes: DEFAULT_MAX_LOCK_BYTES } + } +} + +impl Limits { + /// Sets the largest root `Cargo.toml` that is read. + pub fn with_max_manifest_bytes(mut self, bytes: u64) -> Self { + self.max_manifest_bytes = bytes; + self + } + + /// Sets the largest `Cargo.lock` that is kept for a restore. + pub fn with_max_lock_bytes(mut self, bytes: u64) -> Self { + self.max_lock_bytes = bytes; + self + } +} + +/// The `version` of `[workspace.package]`. +pub fn read(manifest: &str) -> Result { + let entries = scan(manifest)?; + Ok(root_version(&entries)?.text.clone()) +} + +/// `manifest` with the workspace version set to `new`, and every path dependency in +/// `[workspace.dependencies]` whose `version` is the old version (`"OLD"` or `"=OLD"`) moved with +/// it. Registry dependencies and path dependencies at other versions keep their requirement, and +/// every other byte is unchanged. +pub fn replace(manifest: &str, new: &str) -> Result { + validate(new)?; + let entries = scan(manifest)?; + let root = root_version(&entries)?; + let old = root.text.as_str(); + validate(old).map_err(|e| format!("the current [workspace.package] version is not valid: {e}"))?; + let mut edits = vec![(root, new.to_owned())]; + edits.extend(path_pins(&entries, old).into_iter().map(|(pin, prefix)| (pin, format!("{prefix}{new}")))); + edits.sort_by_key(|(s, _)| s.span.start); + let mut out = String::with_capacity(manifest.len() + edits.len() * new.len()); + let mut at = 0; + for (s, text) in edits { + out.push_str(slice(manifest, at..s.span.start)?); + let q = char::from(s.quote); + out.push(q); + out.push_str(&text); + out.push(q); + at = s.span.end; + } + out.push_str(slice(manifest, at..manifest.len())?); + Ok(out) +} + +/// Semver without build metadata: `MAJOR.MINOR.PATCH` plus an optional `-pre.release` tag. +/// +/// The three numbers have no leading zero and fit in a `u64`. Each prerelease identifier is +/// nonempty ASCII letters, digits and `-`, and a numeric one has no leading zero. +pub fn validate(v: &str) -> Result<(), String> { + let bad = || Err(format!("`{v}` is not a version like 1.2.3 or 1.2.3-rc.1")); + let (core, pre) = match v.split_once('-') { + Some((c, p)) => (c, Some(p)), + None => (v, None), + }; + let nums: Vec<&str> = core.split('.').collect(); + if nums.len() != 3 + || nums.iter().any(|n| !n.bytes().all(|b| b.is_ascii_digit()) || (n.len() > 1 && n.starts_with('0')) || n.parse::().is_err()) + { + return bad(); + } + let bad_id = |id: &str| { + id.is_empty() + || !id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') + || (id.len() > 1 && id.starts_with('0') && id.bytes().all(|b| b.is_ascii_digit())) + }; + if let Some(p) = pre + && (p.is_empty() || p.split('.').any(bad_id)) + { + return bad(); + } + Ok(()) +} + +/// `cargo xtask version [set X.Y.Z[-pre]]` with the default [`Limits`]. +/// +/// `root` is the workspace root, `cargo_program` the Cargo to run there (an app usually passes its +/// `CARGO` variable, or `cargo`), and `args` the words after `version`. +/// +/// - With no words, prints the version. +/// - With `set NEW`, writes the new version into `Cargo.toml` (see [`replace`]), runs +/// `cargo update --workspace --offline` and, when that fails, `cargo update --workspace`, then prints +/// `version: OLD -> NEW`. When both updates fail, `Cargo.toml` and `Cargo.lock` are put back as they +/// were and the error says so. Setting the current version prints `version: OLD (unchanged)` and +/// writes only its lock file. One `set` runs at a time in a workspace: it holds its locks (see +/// [`lock_dirs`]) from reading `Cargo.toml` until it returns, and a `set` that finds a lock held +/// returns an error naming the other run and writes nothing. +/// - Other words return the usage error. +pub fn run(root: &Path, cargo_program: &OsStr, args: &[&str]) -> Result<(), String> { + run_with(root, cargo_program, args, &Limits::default()) +} + +/// [`run`] with the caller's [`Limits`]. +pub fn run_with(root: &Path, cargo_program: &OsStr, args: &[&str], limits: &Limits) -> Result<(), String> { + run_to(root, args, limits, None, &mut io::stdout(), || update_lock(root, cargo_program)) +} + +/// The directories of the owner-labeled locks that a `set` in the workspace at `root` holds. +/// +/// Before these, a `set` locks the workspace directory itself on Unix, and on Windows +/// `workspace.lock` in the first directory, opened so that it cannot be deleted while held. Every +/// process that writes the workspace shares that lock, and `cargo clean` cannot remove it. +/// +/// The first directory is `target/xtask-version/version-` in the +/// workspace: its lock is required and its owner file names the run that holds it. The second, when +/// there is a home directory, is `~/.cache/craft-xtask/version-`; a +/// `set` also takes the lock there when it can open the lock file. +/// +/// The locks are not on `Cargo.toml` or `Cargo.lock` because a lock on Windows is mandatory and +/// would stop the replacement of `Cargo.toml` and Cargo's own use of `Cargo.lock`. +pub fn lock_dirs(root: &Path) -> Result, String> { + let canonical = std::fs::canonicalize(root).map_err(|e| format!("{}: {e}", root.display()))?; + let name = format!("version-{:016x}", fnv1a(canonical.to_string_lossy().as_bytes())); + // A `target` linked from several workspaces holds one directory per workspace. + let mut dirs = vec![canonical.join("target").join("xtask-version").join(&name)]; + dirs.extend(std::env::home_dir().filter(|h| h.is_absolute()).map(|h| h.join(".cache").join("craft-xtask").join(name))); + Ok(dirs) +} + +/// The 64-bit FNV-1a hash, which stays the same across Rust releases. +fn fnv1a(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3)) +} + +/// [`run_with`] that prints to `out`, refreshes `Cargo.lock` with `update`, and keeps its locks in +/// `lock_at` (or [`lock_dirs`] when `None`). +fn run_to( + root: &Path, + args: &[&str], + limits: &Limits, + lock_at: Option<&[PathBuf]>, + out: &mut dyn Write, + update: impl FnOnce() -> Result<(), String>, +) -> Result<(), String> { + let new = match args { + [] => None, + ["set", new] => Some(*new), + _ => return Err(USAGE.into()), + }; + let manifest = root.join("Cargo.toml"); + let load = || -> Result<(String, String), String> { + let text = + String::from_utf8(read_bounded(&manifest, limits.max_manifest_bytes)?).map_err(|_| format!("{}: not UTF-8", manifest.display()))?; + let old = read(&text)?; + Ok((text, old)) + }; + let Some(new) = new else { + return say(out, &load()?.1); + }; + validate(new)?; + // Held from the read of `Cargo.toml` through any restore, so that two `set` runs never interleave + // and an unchanged version is not reported while another run may still put an older one back. + let _held = lock_workspace(root, lock_at, new)?; + let (text, old) = load()?; + let updated = replace(&text, new)?; + if old == new { + return say(out, &format!("version: {old} (unchanged)")); + } + let lock_path = root.join("Cargo.lock"); + let lock = match std::fs::symlink_metadata(&lock_path) { + Err(e) if e.kind() == io::ErrorKind::NotFound => None, + _ => Some(read_bounded(&lock_path, limits.max_lock_bytes)?), + }; + write_file(&manifest, updated.as_bytes())?; + if let Err(e) = update() { + return Err(restore(&manifest, &text, &old, &lock_path, lock.as_deref(), e)); + } + say(out, &format!("version: {old} -> {new}")) +} + +/// The locks a `set` holds until it returns. +struct WorkspaceLock { + _base: File, + _held: Vec, +} + +/// The lock that every process writing the workspace at `root` shares and that `cargo clean` cannot +/// remove while it is held, or `None` when another process holds it. On Unix it is a lock on the +/// workspace directory itself. On Windows it is `workspace.lock` in `dir`, opened without delete +/// sharing, so the file cannot be deleted while it is open. +fn base_lock(root: &Path, dir: &Path) -> Result, String> { + let fail = |e: io::Error| format!("could not take the version lock, nothing was written: {e}"); + #[cfg(windows)] + let file = { + use std::os::windows::fs::OpenOptionsExt; + const FILE_SHARE_READ: u32 = 0x1; + const FILE_SHARE_WRITE: u32 = 0x2; + let _ = root; + std::fs::create_dir_all(dir).map_err(fail)?; + std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE) + .open(dir.join("workspace.lock")) + .map_err(fail)? + }; + #[cfg(not(windows))] + let file = { + let _ = dir; + File::open(root).map_err(fail)? + }; + match file.try_lock() { + Ok(()) => Ok(Some(file)), + Err(std::fs::TryLockError::WouldBlock) => Ok(None), + Err(std::fs::TryLockError::Error(e)) => Err(fail(e)), + } +} + +/// Takes the workspace's `version set` locks without waiting: [`base_lock`], then the owner-labeled +/// locks in `lock_at` (or [`lock_dirs`]). The lock in the first directory is required; a later +/// directory whose lock file cannot be opened is skipped. When another run holds any of them, +/// releases the others and returns an error that names that run. +fn lock_workspace(root: &Path, lock_at: Option<&[PathBuf]>, new: &str) -> Result { + let dirs = match lock_at { + Some(dirs) => dirs.to_vec(), + None => lock_dirs(root)?, + }; + let label = format!("pid {} in {}: cargo xtask version set {new}", std::process::id(), root.display()); + let busy = |dir: &Path| { + let config = crate::lock::LockConfig::new(dir, 1, ""); + let other = crate::lock::holders(&config).ok().and_then(|h| h.into_iter().next()).unwrap_or_else(|| "another run".to_owned()); + format!("another `cargo xtask version set` is running in this workspace ({other}); nothing was written, try again when it ends") + }; + let first = dirs.first().ok_or_else(|| "could not take the version lock: no lock directory".to_owned())?; + let Some(base) = base_lock(root, first)? else { + return Err(busy(first)); + }; + let mut held = Vec::new(); + for (i, dir) in dirs.iter().enumerate() { + let config = crate::lock::LockConfig::new(dir, 1, label.clone()); + match crate::lock::try_acquire(&config) { + Ok(Some(h)) => held.push(h), + Ok(None) => return Err(busy(dir)), + Err(e) if i == 0 => return Err(format!("could not take the version lock, nothing was written: {e}")), + Err(_) => {} + } + } + Ok(WorkspaceLock { _base: base, _held: held }) +} + +fn say(out: &mut dyn Write, line: &str) -> Result<(), String> { + writeln!(out, "{line}").map_err(|e| format!("write the output: {e}")) +} + +/// Puts `Cargo.toml` and `Cargo.lock` back after `cargo update` failed with `error`. +fn restore(manifest: &Path, text: &str, old: &str, lock_path: &Path, lock: Option<&[u8]>, error: String) -> String { + let mut msg = match write_file(manifest, text.as_bytes()) { + Ok(()) => format!("{error}; Cargo.toml restored to {old}"), + Err(r) => format!("{error}; could not restore Cargo.toml: {r}"), + }; + let lock_back = match lock { + Some(bytes) => write_file(lock_path, bytes), + None => match std::fs::remove_file(lock_path) { + Err(e) if e.kind() != io::ErrorKind::NotFound => Err(format!("remove {}: {e}", lock_path.display())), + _ => Ok(()), + }, + }; + if let Err(r) = lock_back { + msg.push_str(&format!("; could not restore Cargo.lock: {r}")); + } + msg +} + +/// The file at `path`, or an error when it is larger than `max` bytes. +fn read_bounded(path: &Path, max: u64) -> Result, String> { + let too_big = |len: u64| format!("{}: {len} bytes, more than the {max}-byte limit", path.display()); + let file = File::open(path).map_err(|e| format!("read {}: {e}", path.display()))?; + let len = file.metadata().map_err(|e| format!("read {}: {e}", path.display()))?.len(); + if len > max { + return Err(too_big(len)); + } + let mut bytes = Vec::new(); + file.take(max.saturating_add(1)).read_to_end(&mut bytes).map_err(|e| format!("read {}: {e}", path.display()))?; + if bytes.len() as u64 > max { + return Err(too_big(bytes.len() as u64)); + } + Ok(bytes) +} + +/// Replaces `path` atomically: a half-written root manifest breaks every build in the workspace. +fn write_file(path: &Path, bytes: &[u8]) -> Result<(), String> { + craft_atomic::atomic_write(path, bytes).map_err(|e| format!("write {}: {e}", path.display())) +} + +/// Refreshes the workspace members' entries in `Cargo.lock`, without upgrading dependencies. +fn update_lock(root: &Path, cargo_program: &OsStr) -> Result<(), String> { + let update = |offline: bool| { + let mut c = Command::new(cargo_program); + c.current_dir(root).args(["update", "--workspace"]); + if offline { + c.arg("--offline"); + } + crate::runner::run(c, if offline { "cargo update --workspace --offline" } else { "cargo update --workspace" }) + }; + update(true).or_else(|_| update(false)) +} + +fn slice(s: &str, r: Range) -> Result<&str, String> { + s.get(r).ok_or_else(|| "Cargo.toml: an edit does not fall on a character boundary".to_owned()) +} + +/// A one-line string value: the byte range of its quoted token, its text and its quote character. +#[derive(Debug, Clone, PartialEq, Eq)] +struct Str { + span: Range, + text: String, + quote: u8, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +enum Value { + Str(Str), + /// A multi-line string. + LongStr, + /// A number, boolean, date, array or inline table. + Other, +} + +/// A key of the manifest with its full dotted path (table, dotted key and inline tables). +#[derive(Debug, Clone, PartialEq, Eq)] +struct Entry { + path: Vec, + value: Value, +} + +/// The `[workspace.package]` version string. +fn root_version(entries: &[Entry]) -> Result<&Str, String> { + let mut found = entries.iter().filter(|e| e.path.iter().map(String::as_str).eq(ROOT_VERSION)); + let first = found.next().ok_or("no `version` in [workspace.package] of the root Cargo.toml")?; + if found.next().is_some() { + return Err("[workspace.package] version is set more than once in Cargo.toml".into()); + } + match &first.value { + Value::Str(s) if s.text.is_empty() => Err("empty [workspace.package] version".into()), + Value::Str(s) => Ok(s), + Value::LongStr => Err("[workspace.package] version is a multi-line string; write it as `version = \"X.Y.Z\"`".into()), + Value::Other => Err("[workspace.package] version is not a string".into()), + } +} + +/// The `version` strings of path dependencies in `[workspace.dependencies]` that require `old`, each +/// with the operator in front of the version (`""` or `"="`). +fn path_pins<'a>(entries: &'a [Entry], old: &str) -> Vec<(&'a Str, String)> { + let dep = |e: &'a Entry| match e.path.as_slice() { + [w, d, name, key] if w == "workspace" && d == "dependencies" => Some((name.as_str(), key.as_str(), &e.value)), + _ => None, + }; + let with_path: HashSet<&str> = entries.iter().filter_map(dep).filter(|(_, k, _)| *k == "path").map(|(n, _, _)| n).collect(); + entries + .iter() + .filter_map(dep) + .filter_map(|(name, key, value)| match value { + Value::Str(s) if key == "version" => Some((name, s)), + _ => None, + }) + .filter_map(|(name, s)| { + let prefix = s.text.strip_suffix(old)?; + matches!(prefix.trim(), "" | "=").then(|| (name, s, prefix.to_owned())) + }) + .filter(|(name, _, _)| with_path.contains(name)) + .map(|(_, s, prefix)| (s, prefix)) + .collect() +} + +/// Every key of `manifest` whose value is not inside an array. +fn scan(manifest: &str) -> Result, String> { + let mut s = Scanner { s: manifest, b: manifest.as_bytes(), i: 0, table: Vec::new(), out: Vec::new() }; + loop { + s.skip_blank()?; + match s.peek() { + None => return Ok(s.out), + Some(b'[') => s.header()?, + Some(_) => s.key_value()?, + } + s.end_of_line()?; + } +} + +/// A single pass over the manifest that records each key and the byte range of each one-line string. +struct Scanner<'a> { + s: &'a str, + b: &'a [u8], + i: usize, + table: Vec, + out: Vec, +} + +impl Scanner<'_> { + fn peek(&self) -> Option { + self.b.get(self.i).copied() + } + + fn at(&self, text: &str) -> bool { + self.b.get(self.i..).is_some_and(|rest| rest.starts_with(text.as_bytes())) + } + + fn err(&self, what: &str) -> String { + let before = self.b.get(..self.i).unwrap_or(self.b); + let breaks = before.iter().enumerate().filter(|&(at, &b)| b == b'\n' || (b == b'\r' && before.get(at + 1) != Some(&b'\n'))).count(); + let line = 1 + breaks; + format!("Cargo.toml line {line}: {what}") + } + + fn expect(&mut self, c: u8) -> Result<(), String> { + if self.peek() == Some(c) { + self.i += 1; + Ok(()) + } else { + Err(self.err(&format!("expected `{}`", char::from(c)))) + } + } + + fn skip_spaces(&mut self) { + while matches!(self.peek(), Some(b' ' | b'\t')) { + self.i += 1; + } + } + + fn skip_comment(&mut self) { + if self.peek() == Some(b'#') { + while !matches!(self.peek(), None | Some(b'\n' | b'\r')) { + self.i += 1; + } + } + } + + /// Skips a line ending: LF, CRLF or a lone CR. + fn newline(&mut self) -> bool { + match self.peek() { + Some(b'\n') => self.i += 1, + Some(b'\r') => self.i += if self.b.get(self.i + 1) == Some(&b'\n') { 2 } else { 1 }, + _ => return false, + } + true + } + + /// Skips spaces, comments and line endings. + fn skip_blank(&mut self) -> Result<(), String> { + loop { + self.skip_spaces(); + self.skip_comment(); + if !self.newline() { + return Ok(()); + } + } + } + + fn end_of_line(&mut self) -> Result<(), String> { + self.skip_spaces(); + self.skip_comment(); + if self.peek().is_none() || self.newline() { Ok(()) } else { Err(self.err("expected the end of the line")) } + } + + /// `[table]` or `[[array.of.tables]]`. + fn header(&mut self) -> Result<(), String> { + self.i += 1; + let array = self.peek() == Some(b'['); + if array { + self.i += 1; + } + let mut path = self.key()?; + self.expect(b']')?; + if array { + self.expect(b']')?; + path.push("[]".to_owned()); + } + self.table = path; + Ok(()) + } + + fn key_value(&mut self) -> Result<(), String> { + let key = self.key()?; + self.expect(b'=')?; + let mut path = self.table.clone(); + path.extend(key); + self.value(Some(path), 0) + } + + /// A dotted key, with the spaces around it. + fn key(&mut self) -> Result, String> { + let mut parts = Vec::new(); + loop { + self.skip_spaces(); + parts.push(self.simple_key()?); + self.skip_spaces(); + if self.peek() != Some(b'.') { + return Ok(parts); + } + self.i += 1; + } + } + + fn simple_key(&mut self) -> Result { + match self.peek() { + Some(b'"') if !self.at("\"\"\"") => Ok(self.basic()?.text), + Some(b'\'') if !self.at("'''") => Ok(self.literal()?.text), + _ => { + let start = self.i; + while self.peek().is_some_and(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') { + self.i += 1; + } + if start == self.i { + return Err(self.err("expected a key")); + } + slice(self.s, start..self.i).map(str::to_owned) + } + } + } + + /// A value; it is recorded under `path` unless `path` is `None` (inside an array). + fn value(&mut self, path: Option>, depth: usize) -> Result<(), String> { + if depth > MAX_DEPTH { + return Err(self.err("arrays and inline tables nest too deeply")); + } + self.skip_spaces(); + let value = match self.peek() { + Some(b'"') if self.at("\"\"\"") => self.long_string(b'"').map(|()| Value::LongStr)?, + Some(b'\'') if self.at("'''") => self.long_string(b'\'').map(|()| Value::LongStr)?, + Some(b'"') => Value::Str(self.basic()?), + Some(b'\'') => Value::Str(self.literal()?), + Some(b'[') => self.array(depth).map(|()| Value::Other)?, + Some(b'{') => self.inline_table(path.as_deref(), depth).map(|()| Value::Other)?, + _ => self.scalar().map(|()| Value::Other)?, + }; + if let Some(path) = path { + self.out.push(Entry { path, value }); + } + Ok(()) + } + + /// A number, boolean or date; only its extent matters. + fn scalar(&mut self) -> Result<(), String> { + let start = self.i; + let ends = |b: u8| matches!(b, b' ' | b'\t' | b'\r' | b'\n' | b',' | b']' | b'}' | b'#'); + while self.peek().is_some_and(|b| !ends(b)) { + self.i += 1; + } + // A date and a time may be separated by one space: `1979-05-27 07:32:00Z`. + let date = self.i - start == 10 && self.b.get(start + 4) == Some(&b'-'); + if date && self.peek() == Some(b' ') && self.b.get(self.i + 1).is_some_and(u8::is_ascii_digit) { + self.i += 1; + while self.peek().is_some_and(|b| !ends(b)) { + self.i += 1; + } + } + if start == self.i { Err(self.err("expected a value")) } else { Ok(()) } + } + + fn array(&mut self, depth: usize) -> Result<(), String> { + self.i += 1; + loop { + self.skip_blank()?; + if self.peek() == Some(b']') { + self.i += 1; + return Ok(()); + } + self.value(None, depth + 1)?; + self.skip_blank()?; + match self.peek() { + Some(b',') => self.i += 1, + Some(b']') => { + self.i += 1; + return Ok(()); + } + _ => return Err(self.err("expected `,` or `]` in an array")), + } + } + } + + /// An inline table; line breaks inside it are accepted. + fn inline_table(&mut self, path: Option<&[String]>, depth: usize) -> Result<(), String> { + self.i += 1; + loop { + self.skip_blank()?; + if self.peek() == Some(b'}') { + self.i += 1; + return Ok(()); + } + let key = self.key()?; + self.expect(b'=')?; + let child = path.map(|p| p.iter().cloned().chain(key).collect()); + self.value(child, depth + 1)?; + self.skip_blank()?; + match self.peek() { + Some(b',') => self.i += 1, + Some(b'}') => { + self.i += 1; + return Ok(()); + } + _ => return Err(self.err("expected `,` or `}` in an inline table")), + } + } + } + + /// A one-line `"…"` string, with its escapes decoded. + fn basic(&mut self) -> Result { + let start = self.i; + self.i += 1; + let mut text = String::new(); + loop { + match self.peek() { + None | Some(b'\n' | b'\r') => return Err(self.err("unterminated string")), + Some(b'"') => break, + Some(b'\\') => text.push(self.escape()?), + Some(_) => { + let run = self.i; + while self.peek().is_some_and(|b| !matches!(b, b'"' | b'\\' | b'\n' | b'\r')) { + self.i += 1; + } + text.push_str(slice(self.s, run..self.i)?); + } + } + } + self.i += 1; + Ok(Str { span: start..self.i, text, quote: b'"' }) + } + + fn escape(&mut self) -> Result { + self.i += 1; + let c = self.peek().ok_or_else(|| self.err("unterminated string"))?; + self.i += 1; + let digits = match c { + b'"' => return Ok('"'), + b'\\' => return Ok('\\'), + b'b' => return Ok('\u{8}'), + b't' => return Ok('\t'), + b'n' => return Ok('\n'), + b'f' => return Ok('\u{c}'), + b'r' => return Ok('\r'), + b'e' => return Ok('\u{1b}'), + b'u' => 4, + b'U' => 8, + _ => return Err(self.err("unknown escape in a string")), + }; + let hex = self.s.get(self.i..self.i + digits).filter(|h| h.bytes().all(|b| b.is_ascii_hexdigit())); + let ch = hex.and_then(|h| u32::from_str_radix(h, 16).ok()).and_then(char::from_u32).ok_or_else(|| self.err("invalid unicode escape"))?; + self.i += digits; + Ok(ch) + } + + /// A one-line `'…'` string. + fn literal(&mut self) -> Result { + let start = self.i; + self.i += 1; + while self.peek().is_some_and(|b| !matches!(b, b'\'' | b'\n' | b'\r')) { + self.i += 1; + } + if self.peek() != Some(b'\'') { + return Err(self.err("unterminated string")); + } + let text = slice(self.s, start + 1..self.i)?.to_owned(); + self.i += 1; + Ok(Str { span: start..self.i, text, quote: b'\'' }) + } + + /// A `"""…"""` or `'''…'''` string; only its extent matters. + fn long_string(&mut self, q: u8) -> Result<(), String> { + self.i += 3; + loop { + match self.peek() { + None => return Err(self.err("unterminated multi-line string")), + Some(b'\\') if q == b'"' => self.i += 2, + Some(c) if c == q && self.b.get(self.i..self.i + 3) == Some(&[q, q, q][..]) => { + self.i += 3; + // Up to two more quotes belong to the string. + for _ in 0..2 { + if self.peek() == Some(q) { + self.i += 1; + } + } + return Ok(()); + } + Some(_) => self.i += 1, + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::Cell; + + const MANIFEST: &str = "[workspace]\nmembers = [\"a\"]\n\n[workspace.package]\nversion = \"0.1.0\"\nedition = \"2024\"\n\n[workspace.dependencies]\nfoo = { version = \"1\" }\n"; + + /// A workspace folder holding `manifest` as its `Cargo.toml` and, when given, `lock` as its `Cargo.lock`. + fn workspace(manifest: &str, lock: Option<&str>) -> tempfile::TempDir { + let dir = tempfile::tempdir().unwrap(); + std::fs::write(dir.path().join("Cargo.toml"), manifest).unwrap(); + if let Some(lock) = lock { + std::fs::write(dir.path().join("Cargo.lock"), lock).unwrap(); + } + dir + } + + /// The lock directory of the tests' runs: inside the test's own workspace folder, which is removed + /// with it. + fn test_lock_dir(root: &Path) -> PathBuf { + root.join("target").join("xtask-version") + } + + fn run_limited(root: &Path, args: &[&str], limits: &Limits, update: impl FnOnce() -> Result<(), String>) -> Result<(), String> { + run_to(root, args, limits, Some(&[test_lock_dir(root)]), &mut Vec::new(), update) + } + + fn run_in(root: &Path, args: &[&str], update: impl FnOnce() -> Result<(), String>) -> (Result<(), String>, String) { + let mut out = Vec::new(); + let result = run_to(root, args, &Limits::default(), Some(&[test_lock_dir(root)]), &mut out, update); + (result, String::from_utf8(out).unwrap()) + } + + fn file(root: &Path, name: &str) -> Option { + std::fs::read_to_string(root.join(name)).ok() + } + + #[test] + fn reads_the_workspace_version() { + assert_eq!(read(MANIFEST).unwrap(), "0.1.0"); + assert!(read("[package]\nversion = \"1.0.0\"\n").is_err()); + } + + #[test] + fn replaces_only_the_workspace_version() { + let out = replace(MANIFEST, "1.2.3-rc.1").unwrap(); + assert_eq!(read(&out).unwrap(), "1.2.3-rc.1"); + assert_eq!(out, MANIFEST.replace("version = \"0.1.0\"", "version = \"1.2.3-rc.1\"")); + assert!(out.contains("foo = { version = \"1\" }")); + // Setting the old version back gives the same bytes. + assert_eq!(replace(&out, "0.1.0").unwrap(), MANIFEST); + } + + #[test] + fn keeps_crlf_line_endings() { + let crlf = MANIFEST.replace('\n', "\r\n"); + let out = replace(&crlf, "2.0.0").unwrap(); + assert_eq!(out, crlf.replace("\"0.1.0\"", "\"2.0.0\"")); + } + + #[test] + fn validates_versions() { + for ok in ["0.1.0", "1.20.300", "1.0.0-rc.1", "1.0.0-alpha", "1.0.0-x-y.2"] { + assert!(validate(ok).is_ok(), "{ok}"); + } + for bad in ["1.0", "1.0.0.0", "v1.0.0", "01.0.0", "1.0.0-", "1.0.0-a..b", "1.0.0+meta", "1.a.0", ""] { + assert!(validate(bad).is_err(), "{bad}"); + } + assert!(replace(MANIFEST, "nope").is_err()); + } + + #[test] + fn rejects_what_cargo_rejects() { + for bad in ["1.0.0-01", "1.0.0-rc.01", "1.0.0-0.00", "1.0.0-rc.1.007", "99999999999999999999.0.0", "1.18446744073709551616.0"] { + assert!(validate(bad).is_err(), "{bad}"); + assert!(replace(MANIFEST, bad).is_err(), "{bad}"); + } + for ok in ["1.0.0-0", "1.0.0-rc.0", "1.0.0-0a", "1.0.0-01a", "1.0.0-99999999999999999999", "18446744073709551615.0.0"] { + assert!(validate(ok).is_ok(), "{ok}"); + } + } + + #[test] + fn moves_the_workspace_crates_pins_with_it() { + let manifest = "[workspace.package]\nversion = \"0.1.0\"\n\n[workspace.dependencies]\n\ + own = { path = \"crates/own\", version = \"0.1.0\" }\n\ + exact = { path = \"crates/exact\", version = \"=0.1.0\" }\n\ + dep = { version = \"0.1.0\" }\n\ + other = { path = \"crates/other\", version = \"0.2\" }\n\ + newer = { path = \"crates/newer\", version = \"0.1.0-rc.1\" }\n"; + let out = replace(manifest, "0.2.0").unwrap(); + assert!(out.contains("own = { path = \"crates/own\", version = \"0.2.0\" }"), "{out}"); + assert!(out.contains("exact = { path = \"crates/exact\", version = \"=0.2.0\" }"), "{out}"); + assert!(out.contains("dep = { version = \"0.1.0\" }"), "a registry dependency keeps its version"); + assert!(out.contains("other = { path = \"crates/other\", version = \"0.2\" }")); + assert!(out.contains("newer = { path = \"crates/newer\", version = \"0.1.0-rc.1\" }")); + } + + #[test] + fn a_failed_update_restores_the_manifest() { + // Two sets in one workspace: a child started by another test must not hold the first one's lock. + let _guard = crate::spawn_guard(); + let dir = workspace(MANIFEST, None); + let (err, out) = run_in(dir.path(), &["set", "2.0.0"], || Err("cargo update failed".into())); + let err = err.unwrap_err(); + assert!(err.contains("restored to 0.1.0"), "{err}"); + assert_eq!(out, "", "a failed set printed success"); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + let (ok, out) = run_in(dir.path(), &["set", "2.0.0"], || Ok(())); + assert_eq!(ok, Ok(())); + assert_eq!(out, "version: 0.1.0 -> 2.0.0\n"); + assert_eq!(read(&file(dir.path(), "Cargo.toml").unwrap()).unwrap(), "2.0.0"); + } + + #[test] + fn the_real_manifest_has_a_valid_version() { + let text = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("../../Cargo.toml")).unwrap(); + let version = read(&text).unwrap(); + validate(&version).unwrap(); + // craft-libs pins its own crates with `version = "=X.Y.Z"`; a set moves those pins too. + let out = replace(&text, "99.0.0").unwrap(); + let pins = text.matches(&format!("version = \"={version}\"")).count(); + assert!(pins > 0, "the root manifest has no `=` pin of its own version"); + assert_eq!(out.matches("version = \"=99.0.0\"").count(), pins, "{out}"); + assert_eq!(replace(&out, &version).unwrap(), text); + } + + #[test] + fn reads_commented_and_single_quoted_versions() { + let manifest = "[workspace.package] # shared\nversion = '1.2.3' # the release\nedition = \"2024\"\n"; + assert_eq!(read(manifest).unwrap(), "1.2.3"); + let out = replace(manifest, "1.3.0").unwrap(); + assert_eq!(out, "[workspace.package] # shared\nversion = '1.3.0' # the release\nedition = \"2024\"\n"); + let spaced = "[ workspace . package ]\n\"version\"=\"1.2.3\"#c\n"; + assert_eq!(replace(spaced, "1.2.4").unwrap(), "[ workspace . package ]\n\"version\"=\"1.2.4\"#c\n"); + } + + #[test] + fn accepts_dotted_workspace_package_version() { + for manifest in [ + "[workspace]\npackage.version = \"0.3.0\"\n", + "workspace.package.version = \"0.3.0\"\n", + "[workspace]\npackage = { version = \"0.3.0\", edition = \"2024\" }\n", + ] { + assert_eq!(read(manifest).unwrap(), "0.3.0", "{manifest}"); + assert_eq!(replace(manifest, "0.4.0").unwrap(), manifest.replace("0.3.0", "0.4.0")); + } + } + + #[test] + fn leaves_member_version_workspace_alone() { + let manifest = "[package]\nname = \"a\"\nversion.workspace = true\n\n[workspace.package]\nversion = \"0.1.0\"\n\n\ + [workspace.dependencies]\na = { path = \"a\", version.workspace = true }\n"; + let out = replace(manifest, "0.2.0").unwrap(); + assert_eq!(out, manifest.replace("version = \"0.1.0\"", "version = \"0.2.0\"")); + assert!(read("[package]\nversion.workspace = true\n").is_err()); + } + + #[test] + fn moves_multiline_path_dependency_pin() { + let manifest = "[workspace.package]\nversion = \"0.1.0\"\n\n\ + [workspace.dependencies]\n\ + spread = {\n path = \"crates/spread\",\n version = \"0.1.0\",\n}\n\ + dotted.path = \"crates/dotted\"\ndotted.version = \"0.1.0\"\n\n\ + [workspace.dependencies.own]\nversion = \"0.1.0\"\n# the crate\npath = \"crates/own\"\n\n\ + [workspace.dependencies.registry]\nversion = \"0.1.0\"\n"; + let out = replace(manifest, "0.1.1").unwrap(); + let expected = manifest.replacen("0.1.0", "0.1.1", 4); + assert_eq!(out, expected); + assert!(out.ends_with("[workspace.dependencies.registry]\nversion = \"0.1.0\"\n"), "{out}"); + } + + #[test] + fn preserves_mixed_and_cr_line_endings() { + let mixed = "[workspace]\r\nmembers = [\r\"a\",\n]\r\n[workspace.package]\rversion = \"0.1.0\"\r\n# end\r"; + let out = replace(mixed, "0.2.0").unwrap(); + assert_eq!(out, mixed.replace("0.1.0", "0.2.0")); + let cr = MANIFEST.replace('\n', "\r"); + assert_eq!(read(&cr).unwrap(), "0.1.0"); + assert_eq!(replace(&cr, "2.0.0").unwrap(), cr.replace("\"0.1.0\"", "\"2.0.0\"")); + } + + #[test] + fn ignores_brackets_and_keys_inside_strings_and_arrays() { + let manifest = "[workspace]\nmembers = [\n [\"nested\"],\n \"b\",\n]\nnote = \"\"\"\n[workspace.package]\nversion = \"9.9.9\"\n\"\"\"\n\ + title = '[workspace.package]'\n\n[workspace.package]\nversion = \"0.1.0\"\n"; + assert_eq!(read(manifest).unwrap(), "0.1.0"); + assert_eq!(replace(manifest, "0.2.0").unwrap(), manifest.replace("\"0.1.0\"", "\"0.2.0\"")); + } + + #[test] + fn rejects_unsupported_and_ambiguous_manifests() { + let deep = format!("[workspace.package]\nversion = \"0.1.0\"\nx = {}{}\n", "[".repeat(100), "]".repeat(100)); + for (manifest, what) in [ + ("[workspace.package]\nversion = \"0.1.0\"\n[workspace]\npackage.version = \"0.2.0\"\n", "more than once"), + ("[workspace.package]\nversion = \"\"\"0.1.0\"\"\"\n", "multi-line"), + ("[workspace.package]\nversion = 1\n", "not a string"), + ("[workspace.package]\nversion = \"\"\n", "empty"), + ("[workspace.package]\nversion = \"0.1.0\n", "unterminated"), + ("[workspace.package]\nversion = \"0.1.0\" extra\n", "end of the line"), + ("[workspace.package\nversion = \"0.1.0\"\n", "expected `]`"), + ("[workspace.package]\nversion = \"\\q\"\n", "escape"), + (deep.as_str(), "nest too deeply"), + ] { + let Err(e) = replace(manifest, "1.0.0") else { panic!("accepted {manifest:?}") }; + assert!(e.contains(what), "{manifest:?}: {e}"); + } + let Err(e) = replace("[workspace.package]\nversion = \"1.0\"\n", "1.0.1") else { panic!("an invalid current version was replaced") }; + assert!(e.contains("current"), "{e}"); + } + + #[test] + fn rejects_oversized_manifest_before_write() { + let dir = workspace(MANIFEST, None); + let ran = Cell::new(false); + let limits = Limits::default().with_max_manifest_bytes(MANIFEST.len() as u64 - 1); + let result = run_limited(dir.path(), &["set", "2.0.0"], &limits, || { + ran.set(true); + Ok(()) + }); + let Err(e) = result else { panic!("an oversized manifest was read") }; + assert!(e.contains("limit"), "{e}"); + assert!(!ran.get()); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + let exact = Limits::default().with_max_manifest_bytes(MANIFEST.len() as u64); + assert_eq!(run_limited(dir.path(), &[], &exact, || Ok(())), Ok(())); + + let dir = workspace(MANIFEST, Some("lock")); + let small_lock = Limits::default().with_max_lock_bytes(3); + let Err(e) = run_limited(dir.path(), &["set", "2.0.0"], &small_lock, || Ok(())) else { panic!("an oversized lock was read") }; + assert!(e.contains("Cargo.lock") && e.contains("limit"), "{e}"); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + } + + #[test] + fn restores_lockfile_after_failed_update() { + let dir = workspace(MANIFEST, Some("old lock\r\n")); + let lock = dir.path().join("Cargo.lock"); + let (err, _) = run_in(dir.path(), &["set", "2.0.0"], || { + std::fs::write(&lock, "half-updated lock").unwrap(); + Err("cargo update failed".into()) + }); + assert!(err.unwrap_err().contains("restored to 0.1.0")); + assert_eq!(file(dir.path(), "Cargo.lock").as_deref(), Some("old lock\r\n")); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + + // A lock that the failed update created is removed again. + let dir = workspace(MANIFEST, None); + let lock = dir.path().join("Cargo.lock"); + let (err, _) = run_in(dir.path(), &["set", "2.0.0"], || { + std::fs::write(&lock, "new lock").unwrap(); + Err("cargo update failed".into()) + }); + assert!(err.is_err()); + assert!(!lock.exists()); + } + + #[test] + fn setting_current_version_does_not_run_cargo() { + let dir = workspace(MANIFEST, None); + let ran = Cell::new(false); + let (result, out) = run_in(dir.path(), &["set", "0.1.0"], || { + ran.set(true); + Ok(()) + }); + assert_eq!(result, Ok(())); + assert_eq!(out, "version: 0.1.0 (unchanged)\n"); + assert!(!ran.get()); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + assert_eq!(file(dir.path(), "Cargo.lock"), None); + } + + #[test] + fn lock_dirs_cover_the_workspace_and_the_account() { + let (a, b) = (workspace(MANIFEST, None), workspace(MANIFEST, None)); + let dirs_a = lock_dirs(a.path()).unwrap(); + assert_eq!(lock_dirs(&a.path().join(".")).unwrap(), dirs_a, "two spellings of one root"); + assert_ne!(lock_dirs(b.path()).unwrap(), dirs_a); + let canonical = std::fs::canonicalize(a.path()).unwrap(); + assert_eq!(dirs_a[0].parent(), Some(canonical.join("target").join("xtask-version").as_path())); + // Both directories are named for the workspace, so a `target` shared by two workspaces keeps + // their locks apart. + let name = dirs_a[0].file_name().unwrap().to_string_lossy().into_owned(); + assert!(name.starts_with("version-"), "{name}"); + assert!(dirs_a.iter().all(|d| d.file_name() == dirs_a[0].file_name())); + for dir in &dirs_a[1..] { + assert!(dir.is_absolute() && dir.parent().is_some_and(|p| p.ends_with("craft-xtask")), "{}", dir.display()); + assert!(!dir.starts_with(&canonical), "{}", dir.display()); + } + assert!(dirs_a.len() <= 2); + assert!(lock_dirs(&a.path().join("missing")).is_err()); + // FNV-1a's published test value, so the name stays the same across builds. + assert_eq!(fnv1a(b"a"), 0xaf63_dc4c_8601_ec8c); + } + + #[test] + fn a_held_workspace_lock_refuses_the_set_whatever_the_lock_directories() { + let _guard = crate::spawn_guard(); + let dir = workspace(MANIFEST, Some("old lock\n")); + let other = base_lock(dir.path(), &test_lock_dir(dir.path())).unwrap().expect("free lock"); + // A run whose owner-labeled lock directories differ from the holder's still meets its lock. + let elsewhere = tempfile::tempdir().unwrap(); + let ran = Cell::new(false); + let result = run_to(dir.path(), &["set", "2.0.0"], &Limits::default(), Some(&[elsewhere.path().join("lock")]), &mut Vec::new(), || { + ran.set(true); + Ok(()) + }); + assert!(result.is_err_and(|e| e.contains("another `cargo xtask version set`"))); + assert!(!ran.get()); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + assert_eq!(file(dir.path(), "Cargo.lock").as_deref(), Some("old lock\n")); + drop(other); + assert_eq!(run_in(dir.path(), &["set", "2.0.0"], || Ok(())).0, Ok(())); + } + + #[test] + fn the_workspace_lock_is_required_and_a_later_one_is_optional() { + let _guard = crate::spawn_guard(); + let dir = workspace(MANIFEST, None); + // A directory cannot be made under a file. + let blocked = dir.path().join("Cargo.toml").join("lock"); + let first = test_lock_dir(dir.path()); + let result = run_to(dir.path(), &["set", "2.0.0"], &Limits::default(), Some(&[first.clone(), blocked.clone()]), &mut Vec::new(), || Ok(())); + assert_eq!(result, Ok(())); + assert!(first.join("ci.lock").exists()); + + // A run holding the lock in a later directory refuses the set too. + let later = dir.path().join("later"); + let other = crate::lock::try_acquire(&crate::lock::LockConfig::new(&later, 1, "pid 8 in /w: cargo xtask version set 4.0.0")) + .unwrap() + .expect("free lock"); + let ran = Cell::new(false); + let dirs = [first.clone(), blocked.clone(), later.clone()]; + let result = run_to(dir.path(), &["set", "3.0.0"], &Limits::default(), Some(&dirs), &mut Vec::new(), || { + ran.set(true); + Ok(()) + }); + assert!(result.is_err_and(|e| e.contains("pid 8 in /w"))); + assert!(!ran.get()); + assert_eq!(read(&file(dir.path(), "Cargo.toml").unwrap()).unwrap(), "2.0.0"); + drop(other); + // The lock taken in the first directory before the refusal was released. + assert!(crate::lock::try_acquire(&crate::lock::LockConfig::new(&first, 1, "x")).unwrap().is_some()); + + // Without the first lock, nothing is written. + let dir = workspace(MANIFEST, None); + let blocked = dir.path().join("Cargo.toml").join("lock"); + let ran = Cell::new(false); + let result = run_to(dir.path(), &["set", "2.0.0"], &Limits::default(), Some(&[blocked, test_lock_dir(dir.path())]), &mut Vec::new(), || { + ran.set(true); + Ok(()) + }); + assert!(result.is_err_and(|e| e.contains("could not take the version lock"))); + assert!(!ran.get()); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + } + + #[test] + fn prints_the_version_and_rejects_other_words() { + let dir = workspace(MANIFEST, None); + assert_eq!(run_in(dir.path(), &[], || Ok(())), (Ok(()), "0.1.0\n".to_owned())); + for args in [&["set"][..], &["set", "1.0.0", "2.0.0"], &["get"], &["set", "1.0.0+meta"]] { + let (result, out) = run_in(dir.path(), args, || panic!("cargo ran for {args:?}")); + assert!(result.is_err(), "{args:?}"); + assert_eq!(out, ""); + } + assert_eq!(run_in(dir.path(), &["get"], || Ok(())).0, Err(USAGE.to_owned())); + assert!(run_in(&dir.path().join("missing"), &[], || Ok(())).0.unwrap_err().starts_with("read ")); + } + + #[test] + fn leaves_no_staging_files() { + let _guard = crate::spawn_guard(); + let dir = workspace(MANIFEST, Some("lock")); + let names = || { + let mut n: Vec = std::fs::read_dir(dir.path()).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect(); + n.sort(); + n + }; + let lock_files = || { + std::fs::read_dir(test_lock_dir(dir.path())).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect::>() + }; + let no_owner = |files: Vec| files.iter().all(|f| !f.ends_with(".owner")); + let _ = run_in(dir.path(), &["set", "2.0.0"], || Err("cargo update failed".into())); + assert_eq!(names(), ["Cargo.lock", "Cargo.toml", "target"]); + assert!(no_owner(lock_files()), "the owner file outlived the run: {:?}", lock_files()); + assert_eq!(run_in(dir.path(), &["set", "2.0.0"], || Ok(())).0, Ok(())); + assert_eq!(names(), ["Cargo.lock", "Cargo.toml", "target"]); + assert!(no_owner(lock_files()), "{:?}", lock_files()); + } + + #[test] + fn concurrent_set_is_refused_before_anything_is_written() { + let _guard = crate::spawn_guard(); + let dir = workspace(MANIFEST, Some("old lock\n")); + let config = crate::lock::LockConfig::new(test_lock_dir(dir.path()), 1, "pid 7 in /w: cargo xtask version set 9.0.0"); + let other = crate::lock::try_acquire(&config).unwrap().expect("free lock"); + let ran = Cell::new(false); + let (result, out) = run_in(dir.path(), &["set", "2.0.0"], || { + ran.set(true); + Err("cargo update failed".into()) + }); + let err = result.unwrap_err(); + assert!(err.contains("another `cargo xtask version set`") && err.contains("pid 7 in /w"), "{err}"); + assert_eq!(out, ""); + assert!(!ran.get(), "cargo update ran while another set held the lock"); + assert_eq!(file(dir.path(), "Cargo.toml").as_deref(), Some(MANIFEST)); + assert_eq!(file(dir.path(), "Cargo.lock").as_deref(), Some("old lock\n")); + // Reading the version does not take the lock. Setting the current one does: the other run may + // still put an older version back. + assert_eq!(run_in(dir.path(), &[], || Ok(())), (Ok(()), "0.1.0\n".to_owned())); + let (unchanged, out) = run_in(dir.path(), &["set", "0.1.0"], || Ok(())); + assert!(unchanged.is_err_and(|e| e.contains("pid 7 in /w")), "{out}"); + assert_eq!(out, ""); + // An invalid version is refused before the lock. + assert!(run_in(dir.path(), &["set", "nope"], || Ok(())).0.unwrap_err().contains("not a version")); + drop(other); + assert_eq!(run_in(dir.path(), &["set", "2.0.0"], || Ok(())), (Ok(()), "version: 0.1.0 -> 2.0.0\n".to_owned())); + } + + #[test] + fn replaces_the_existing_manifest() { + let dir = workspace(MANIFEST, None); + // An open reader of the old manifest does not stop the replacement. + let reader = File::open(dir.path().join("Cargo.toml")).unwrap(); + assert_eq!(run_in(dir.path(), &["set", "3.0.0"], || Ok(())).0, Ok(())); + drop(reader); + assert_eq!(read(&file(dir.path(), "Cargo.toml").unwrap()).unwrap(), "3.0.0"); + } +} From dc8f3481022ca2ecfeaf8023ac3f33ce81b6d863 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:43:35 -0800 Subject: [PATCH 031/786] 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