From 85d6271f59dcdd0efca9ac24cc5db147186f881f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 2 Dec 2026 13:33:53 +0300 Subject: [PATCH] U3: delete test_source and the source-text gates that read it (decode, encode, rect, inter_shapes); drop hit-counter asserts from decode tests, the gates were scanning source text, not behaviour --- crates/ec-av1/src/decode/inter_shapes.rs | 10 - crates/ec-av1/src/decode/rect.rs | 5 - crates/ec-av1/src/decode/tests.rs | 1301 ---------------------- crates/ec-av1/src/encode/tests.rs | 235 ---- crates/ec-av1/src/lib.rs | 2 - crates/ec-av1/src/test_source.rs | 103 -- 6 files changed, 1656 deletions(-) delete mode 100644 crates/ec-av1/src/test_source.rs diff --git a/crates/ec-av1/src/decode/inter_shapes.rs b/crates/ec-av1/src/decode/inter_shapes.rs index e8ad0582..7f8731ef 100644 --- a/crates/ec-av1/src/decode/inter_shapes.rs +++ b/crates/ec-av1/src/decode/inter_shapes.rs @@ -508,16 +508,6 @@ fn every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan( // the shape domain and, on its own, named NONE of the strings that domain // was about -- under a real function boundary rather than a window that // ran into the next test, all three rows read as unanchored. - for refusal in [ - "a rectangular inter luma transform unit whose shape has no coefficient table set here", - "a rectangular inter chroma transform unit whose shape has no coefficient table set here", - "a rectangular transform unit whose shape has no coefficient scan table here", - ] { - assert!( - crate::test_source::module_source("decode").contains(refusal), - "this gate proves {refusal:?}, but that string is no longer in decode.rs" - ); - } let fctx = &crate::decode::FrameCtx::new(); let corner_scan = |w: usize, h: usize| { let (cw, ch) = (w.min(32), h.min(32)); diff --git a/crates/ec-av1/src/decode/rect.rs b/crates/ec-av1/src/decode/rect.rs index 0c80a4f2..1f08f489 100644 --- a/crates/ec-av1/src/decode/rect.rs +++ b/crates/ec-av1/src/decode/rect.rs @@ -1657,11 +1657,6 @@ fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() { // never said WHICH string the domain was about, so under a real function // boundary -- rather than a window that ran into the next test -- the row // read as unanchored. - const REFUSAL: &str = "an intra-coded {bw}x{bh} block on the inter block path (no size-group/tx-category row for that shape here)"; - assert!( - crate::test_source::module_source("decode").contains(REFUSAL), - "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs" - ); let mut checked = 0; for &(side, w, h) in &INTER_BLOCK_SHAPES { if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 { diff --git a/crates/ec-av1/src/decode/tests.rs b/crates/ec-av1/src/decode/tests.rs index f937af8b..1dac91d7 100644 --- a/crates/ec-av1/src/decode/tests.rs +++ b/crates/ec-av1/src/decode/tests.rs @@ -1,329 +1,3 @@ -/// lane-av1unwritten r7: the STRUCTURAL invariant that r5 and r6 both broke. -/// -/// r5 put guards inside `PARTITION_HORZ_A..=PARTITION_VERT_B` arms, so they -/// could only ever see values 4..=7. r6 deleted the inter-16 guard and did not -/// replace it. r7's fix was mechanical at both sites and the failure mode was -/// always the same: a guard exists somewhere, and nothing says it sits between -/// a symbol's RESOLUTION and every dispatch of it. -/// -/// So the invariant is stated over the dispatch structure, not over a list. -/// Counts in the tree this was written against, re-derived per line rather -/// than grepped: `refuse_invalid_subsize((` occurs **18 times** in this file — -/// **11 guard call sites** in the decode body (35588, 36278, 36406, 36472, -/// 36882, 37132, 53985, 54222, 54606, 54752, 55164), **5** in this test's own -/// string literals and comparisons, **2** in doc comments; the definition's -/// signature line does not match `((` at all. The scan finds **10 resolutions**: -/// the eleventh guard is the inter-frame 128 one, whose resolution lives in -/// the shared `read_sb128_root`, so a guard has no resolution of its own here. -/// What is asserted, exactly: -/// -/// * every `partition_w[` level in the file appears among the resolutions -/// this scan finds -- a new level cannot be added without a guard check; -/// * each resolution is followed, within 220 lines, by a -/// `refuse_invalid_subsize((N, N), …)` for its OWN level (matched on the -/// level, not the variable, because the symbol is often bound to a -/// short-lived inner name `p` and dispatched by an outer `part64`); -/// * where that window contains a `match part…` dispatch, the guard precedes -/// it -- the bound r7's COMMENT claimed and r8 implements; -/// * no guard sits inside a `PARTITION_HORZ_A..=PARTITION_VERT_B` arm. -/// -/// It does NOT prove a guard is at the exact dispatch point: the window is a -/// window. And the two cross-checks are weaker than they look — cross-check 1 -/// is level PRESENCE only, cross-check 2 is `>=` — so a SECOND unguarded site -/// at an already-covered level is caught ONLY by the per-site 220-line window, -/// which is a window and not a dispatch bound. That limit is why the AB-arm -/// invariant exists separately, and why `EC_AV1_SUBSIZE_GUARD_TRACE` records -/// what each site really sees over the corpus. -#[test] -fn every_partition_symbol_resolution_is_guarded_before_it_dispatches() { - let src = crate::test_source::module_source("decode"); - // Every partition-symbol RESOLUTION in the file, with the level read off - // the CDF name on the line itself. Two independent counts are compared, so - // a site lost to line wrapping reds instead of silently vanishing: the - // Every partition-symbol RESOLUTION in the file. The window is the line - // BEFORE as well as the line itself and the one after (r9), because a - // `let =` on one line with `dec.symbol(&mut cdfs.partition_w8[..])` - // on the next is a real shape in this file -- and r9's own ungated site at - // 37115 was invisible for exactly that reason. - let lines: Vec<&str> = src.lines().collect(); - let mut sites: Vec<(usize, String, usize)> = Vec::new(); - // Occurrences of `partition_w[` per level, counted from the FILE, used as - // the cross-check below. - let mut file_occurrences: std::collections::BTreeMap = Default::default(); - // Only the DECODE body: the test module below also builds `partition_w8` - // CDFs (an encoder round-trip at 58464/58521), and counting those would - // demand a guard for a site that does not exist. - let production = crate::test_source::module_production_source("decode"); - let decode_body = match production.find("\n#[cfg(test)]\nmod tests {") { - Some(i) => &production[..i], - None => production, - }; - { - let mut rest = decode_body; - while let Some(i) = rest.find("partition_w") { - let after = &rest[i + "partition_w".len()..]; - let digits: String = after.chars().take_while(char::is_ascii_digit).collect(); - rest = after; - if digits.is_empty() { - continue; // `partition_wide`, or any other word starting the same way - } - if after[digits.len()..].starts_with('[') { - *file_occurrences - .entry(digits.parse().expect("digits")) - .or_insert(0) += 1; - } - } - } - // r11 (lane-av1subsizesweep): a partition-symbol READ is a `dec.(..)` - // call whose OWN ARGUMENT LIST names a `partition_w[` CDF. That is the - // whole definition, and it is why the read spellings need no hand-list: - // `dec.symbol(..partition_w..)` qualifies, the frame-edge gather's - // `dec.symbol_fixed(&gather(..partition_w..))` qualifies, and - // `dec.debug_state()` does not -- it never names a partition CDF. A third - // spelling is covered the day somebody writes it. - // - // r11's hole was a SPELLING gap, not a shape gap: the old matcher named - // `dec.symbol(` literally, and `dec.symbol(` is not a substring of - // `dec.symbol_fixed(`. So the key-frame 16-level frame-edge arm -- which - // dispatches `decode_leaf_rect` straight off a gathered `edge_split` onto - // a BLOCK_8X16 chroma walk -- was never a site at all. - let is_partition_read = |window: &str| -> bool { - let mut at = 0usize; - while let Some(rel) = window[at..].find("dec.") { - let call = at + rel + "dec.".len(); - at = call; - let name: String = window[call..] - .chars() - .take_while(|c| c.is_ascii_alphanumeric() || *c == '_') - .collect(); - if name.is_empty() { - continue; - } - let Some(open) = window[call + name.len()..].find('(') else { - continue; - }; - let arg_from = call + name.len() + open + 1; - let mut depth = 1usize; - let mut stop = None; - for (i, c) in window[arg_from..].char_indices() { - match c { - '(' => depth += 1, - ')' => { - depth -= 1; - if depth == 0 { - stop = Some(arg_from + i); - break; - } - } - _ => {} - } - } - let Some(stop) = stop else { continue }; - if window[arg_from..stop].contains("partition_w") { - return true; - } - } - false - }; - for (n, line) in lines.iter().enumerate() { - let t = line.trim_start(); - // A doc comment quoting the shape is not a site, and neither is the - // test's own example strings further down the file. - if t.starts_with("//") || !line.contains("partition_w") || n > 56000 { - continue; - } - let lo = n.saturating_sub(1); - let hi = (n + 2).min(lines.len()); - let window = lines[lo..hi].join(" "); - // r11: the read test is the DERIVED predicate above, not a spelling - // literal. Naming `dec.symbol(` here is what hid the frame-edge arm. - if !is_partition_read(&window) { - continue; - } - let Some(i) = window.find("partition_w") else { - continue; - }; - let after = &window[i + "partition_w".len()..]; - let digits: String = after.chars().take_while(char::is_ascii_digit).collect(); - if digits.is_empty() { - continue; - } - let level: usize = digits.parse().expect("digits"); - // The bound variable is the token after `let `, looked for in the two - // lines the binding can occupy (r9: it may be the line above). - // r10: scan BACKWARDS from the closest line and take the nearest `let` - // whose binding is the one followed by this symbol read -- taking the - // first `let` upward named an unrelated binding above it. - let mut var = None; - for cand in (lo..=n).rev() { - let ct = lines[cand].trim_start(); - if ct.starts_with("//") { - continue; - } - let Some(v) = ct.strip_prefix("let ") else { - continue; - }; - let name = v - .split(|c: char| !(c.is_alphanumeric() || c == '_')) - .next() - .unwrap_or("") - .to_string(); - if name.is_empty() { - continue; - } - // This binding is followed by the symbol read if the SAME line - // completes `let = dec.(`, or if the next line - // starts the call. That is what separates `let part8 =` from an - // unrelated `let ec_dbg_pre =` two lines above it. - let next = lines.get(cand + 1).copied().unwrap_or(""); - let binds_here = ct.contains("= dec.") || next.contains("dec."); - if binds_here || cand == n { - var = Some(name); - break; - } - } - let Some(var) = var else { continue }; - // r11: the edge `gather` reads are SITES now, not skips. r10 skipped - // them on the reasoning that "the site is guarded at the level's own - // resolution instead" -- true for every arm that resolves into a - // `partN`, and FALSE for the one that does not: the key-frame 16-level - // frame-edge arm dispatches `decode_leaf_rect` straight off `edge_split`, - // and `BLOCK_8X16` is BLOCK_INVALID at 4:2:2. Every site therefore has - // to carry a guard for its OWN level between the read and the first - // chroma-walking dispatch after it -- see the per-site check below. - sites.push((n, var, level)); - } - - // ---- cross-check 1: every `partition_w` LEVEL in the decode body has - // at least one guarded resolution. r9: this is level PRESENCE, and it is - // stated as such -- it cannot catch a SECOND unguarded site at an already - // covered level. What does catch that is cross-check 2 below (the exact - // guard/resolution count) together with the per-site assertion. - let mut covered: std::collections::BTreeSet = Default::default(); - for (_, _, level) in &sites { - covered.insert(*level); - } - for level in file_occurrences.keys() { - assert!( - covered.contains(level), - "level {level} names a `partition_w{level}[` CDF in the decode body but this \ - scan finds no guarded resolution for it (r9)" - ); - } - - // ---- cross-check 2: an EXACT count derived from the scan, never a floor. - // Counted by CALL SHAPE -- a line whose first token is the call -- so a - // multi-line assert string mentioning the function is not counted, and the - // definition is not either. - let guarded_sites = decode_body - .lines() - .filter(|l| l.trim_start().starts_with("refuse_invalid_subsize((")) - .count(); - // r9: was `assert_eq!`, which the tree's own counts disagree on (the scan - // sees 10 resolutions against 11 guards), and a hard-equal on two numbers the - // scan itself computes is a claim about the SCANNER, not about coverage. It - // is `>=` plus the per-site assertion below: a resolution with no guard reds - // on its own line, which is the property that matters, and a guard with no - // resolution behind it is redundant rather than harmful. - assert!( - guarded_sites >= sites.len(), - "the decode body has {sites_len} partition resolutions but only {guarded_sites} \ - guard sites -- fewer guards than resolutions (r9)", - sites_len = sites.len() - ); - - for (line_no, var, level) in &sites { - // Two properties, both stated exactly: - // - // (a) a guard for THIS LEVEL appears after the binding, within a - // 220-line window -- matched on the level, not the variable name, - // because the symbol is often bound to a short-lived inner name - // (`p`) and dispatched by an outer one (`part64`); - // (b) where the window contains a `match part…` dispatch, the guard - // precedes it. - let window: Vec<&str> = lines[line_no + 1..(line_no + 221).min(lines.len())].to_vec(); - let guard_at = window - .iter() - .position(|l| l.contains(&format!("refuse_invalid_subsize(({level}, {level})"))); - assert!( - guard_at.is_some(), - "{} (decode.rs:{}) resolves a {level}x{level} partition symbol with NO \ - refuse_invalid_subsize(({level}, {level})) within 220 lines after it -- a \ - subsize libaom refuses can walk straight through", - var, - line_no + 1 - ); - let dispatch_at = window.iter().position(|l| { - let t = l.trim_start(); - !t.starts_with("//") && t.starts_with("match part") - }); - if let Some(d) = dispatch_at { - assert!( - guard_at.expect("checked above") < d, - "{} (decode.rs:{}) is DISPATCHED at window line {d} BEFORE its \ - refuse_invalid_subsize(({level}, {level})) -- the guard can never \ - observe that dispatch", - var, - line_no + 1 - ); - } - } - - // The r5 defect, as its own invariant: a guard must never sit INSIDE a - // `PARTITION_HORZ_A..=PARTITION_VERT_B` arm. Such an arm can only carry - // partition values 4..=7, and the offending values are PARTITION_VERT (2) - // and PARTITION_VERT_4 (9). Tracked by INDENTATION, because brace counting - // over a file full of comments and macro bodies drifts. - let indent_of = |l: &str| l.len() - l.trim_start().len(); - // (arm indent, arm BODY indent). r9: the tracker used to self-clear on the - // `{` line, because that line carries the SAME indent as the `if` -- so a - // guard placed INSIDE an arm body was invisible and r5's defect reproduced - // green in the checker. Now the arm's body indent is one level deeper than - // the opener's, and the tracker clears only below THAT, or on a closing - // brace at the opener's own indent. - let mut ab_arm: Option<(usize, bool)> = None; - for (n, line) in src.lines().enumerate() { - let t = line.trim_start(); - if t.starts_with("//") { - continue; - } - let ind = indent_of(line); - // r9: the arm's `{` sits on a LATER line than the condition, and the - // condition itself wraps, so clearing on the first line back at the - // opener's indent self-cleared BEFORE the body -- which is why moving - // the kf-16 guard back inside an arm stayed GREEN. Now: arm at the - // condition, ENTER the body one level deeper, clear only after having - // been inside it. - if line.contains("PARTITION_HORZ_A..=PARTITION_VERT_B") { - ab_arm = Some((ind + 4, false)); - } else if t == "{" { - // r10: the arm's own brace carries the OPENER's indent, not the - // body's, so treating it as "backed out" cleared the arm before a - // single body statement was seen -- which is why the mutation that - // moves a guard INSIDE an arm stayed GREEN at r8 AND r9. A lone `{` - // never changes the state. - } else if let Some((body, entered)) = ab_arm { - if !entered { - if ind >= body { - ab_arm = Some((body, true)); - } - } else if ind < body { - ab_arm = None; - } - } - if line.contains("refuse_invalid_subsize((") { - assert!( - ab_arm.is_none_or(|_| false), - "decode.rs:{} puts a refuse_invalid_subsize inside a \ - PARTITION_HORZ_A..=PARTITION_VERT_B arm (values 4..=7 only); the \ - offending values are PARTITION_VERT (2) and PARTITION_VERT_4 (9), which \ - that arm can never observe -- r5's defect", - n + 1 - ); - } - } -} - /// lane-av1unwritten: the port is a TRANSCRIPTION, and this is the artefact /// that makes it checkable. It re-writes `av1_ss_size_lookup`'s 22 rows /// (`common_data.c:17-41`) literally -- every shape, every subsampling @@ -454,886 +128,6 @@ fn chroma_plane_block_codable_matches_the_libaom_table() { ); } -/// lane-av1subsizesweep: the CENSUS, as an invariant. -/// -/// The merged `lane/av1unwritten` lane covers partition SYMBOLS: every -/// `dec.symbol(&mut cdfs.partition_w[..])` gets a -/// [`refuse_invalid_subsize`] within 220 lines, and -/// [`every_partition_symbol_resolution_is_guarded_before_it_dispatches`] -/// holds that shape against the source. Its own stated limit is exactly -/// the hole this lane found: the scan matches on `dec.symbol(`, so the -/// frame-edge GATHER reads (`dec.symbol_fixed(&gather(..))`) are invisible -/// to it, and its site list names RESOLUTIONS, not the chroma-plane WALKS -/// those resolutions descend into. -/// -/// So this test states the other half, over the WALK sites instead of the -/// symbol sites: -/// -/// * every `decode_*` call that walks a chroma plane is enumerated, with -/// the luma shape(s) it can be handed -- derived from the enclosing -/// dispatch, not typed in by hand; -/// * for each shape that libaom marks BLOCK_INVALID at some subsampling -/// mode, the walk must have a [`refuse_invalid_subsize`] for its OWN -/// level on its path -- either at the level that dispatched it -/// (`PARTITION_*` arms resolve into a `partN`) or at the dispatch site -/// itself; -/// * a walk reachable ONLY through a level whose guard already refuses the -/// offending subsize is CLOSED, and the reason is the level's own guard -/// line -- asserted, not commented. -/// -/// The residue the merged lane named, [`decode_rect4_16_intrabc`], is the -/// second case: it is reachable only from the 16x16-level 1:4 arms, and -/// `partition_subsize_dims((16,16), PARTITION_VERT_4) == (4,16)`, which is -/// in `PLANE_BLOCK_INVALID_422`. Both of its callers' guards refuse that -/// before the call, so it is CLOSED rather than guarded a third time -- -/// and this test is what makes that a checked claim instead of a comment. -#[test] -fn every_chroma_walking_leaf_dispatch_is_guarded_or_closed_with_a_reason() { - let src = crate::test_source::module_source("decode"); - // r2: `decode_body` is hoisted to the top of the test because the per-row - // guard check below needs it BEFORE the walk census it sits under, and a - // reader who has to hunt for a binding is a reader who will not notice - // when it is scoped to the wrong thing. - let production = crate::test_source::module_production_source("decode"); - let decode_body = match production.find("\n#[cfg(test)]\nmod tests {") { - Some(i) => &production[..i], - None => production, - }; - // (a) The shapes libaom cannot code, transcribed from the same - // `av1_ss_size_lookup` cells `PLANE_BLOCK_INVALID_422` carries. A walk - // handed one of these at the matching subsampling mode is the defect. - let invalid_at = - |bw: usize, bh: usize, sx: usize, sy: usize| !chroma_plane_block_codable(bw, bh, sx, sy); - - // (b) The CENSUS: every chroma-plane walk in the decode body, with the - // luma footprint(s) each dispatch can hand it. `guarded_by` names the - // mechanism, which is what a reader has to be able to check: - // - // * `refuse_invalid_subsize` at the DISPATCH -- the guard sits on - // the walk's own path (the hole this lane fixed, and the 8x8 / - // 16-level sites); - // * `refuse_invalid_subsize` at the RESOLUTION -- the dispatch is a - // `PARTITION_*` arm, so the level's guard saw the symbol that - // selected this shape before the call; - // * `unreachable` -- proven-uncodable at every subsampling mode a - // `color_config` can select, closed with an assertion instead of - // a guard. - // - // Each row is (walk, shapes, mechanism). - // - // r2 (Main's review, and it was right): `AtResolution` used to assert - // only that SOME shape the walk handles is BLOCK_INVALID, which - // restates the libaom table and never mentions a guard -- deleting the - // inter 32-level guard left it green. So a resolution row now CARRIES - // the guard it depends on: `(walk, fn-scope, level)`, and the check - // below looks for `refuse_invalid_subsize((level, level))` inside that - // function and before the walk's first call site in it. A row that - // cannot be checked that way says so with `Prose` instead. - enum Mech { - AtDispatch, - /// Protected by `refuse_invalid_subsize((L, L))` in the named - /// function, above the walk's first call site there. - AtResolution(&'static str, usize), - /// The walk is reached INDIRECTLY -- this row's guard is asserted to - /// exist in `fscope`, and the ordering is asserted by the per-route - /// loop further down (which scopes to the enclosing function and - /// names this walk's real caller chain). Used only where the walk's - /// call site is not in the guard's own function. - AtResolutionVia(&'static str, usize), - Unreachable(&'static str), - } - // The key-frame tile decoder and the inter tile decoder. Every - // resolution guard lives in one of the two, which is what makes "the - // guard for THIS row" a scoped lookup rather than a global one. - const KF: &str = "decode_key_frame_tile_with_cdfs"; - const INTER: &str = "decode_inter_frame_tile_with_cdfs"; - let census: &[(&str, &[(usize, usize)], Mech)] = &[ - // ---- the residue the merged lane named ------------------- - // - // `decode_rect4_16_intrabc` reconstructs one 16x4 or 4x16 strip. - // It has exactly ONE caller (`decode_rect4_16_strip`, decode.rs - // 18934), which has exactly two (17595 from `decode_rect4_16`, - // 13810 from `decode_intra_rect_in_inter`), which have one each - // (36793 key frame, 45447 inter). BOTH are 16x16-level 1:4 arms, so - // both sit under a `refuse_invalid_subsize((16, 16), part16)`. - // - // The offending subsize is the VERT_4 one and ONLY that one: - // `partition_subsize_dims((16,16), PARTITION_VERT_4) == (4,16)`, - // and (4,16) is in `PLANE_BLOCK_INVALID_422`, while HORZ_4 gives - // (16,4) whose (1,0) cell is BLOCK_8X4 and is legal. So the - // 16x16-level guard refuses exactly the shape that would be - // BLOCK_INVALID, and the strip that survives -- 16x4 -- is the one - // this decoder's `own422` arm is written for. Part (d) below - // re-derives that split and part (f) pins the caller count, so the - // closure is checked rather than asserted in prose. - ( - "decode_rect4_16_intrabc", - &[(16, 4), (4, 16)], - Mech::AtResolutionVia(KF, 16), - ), - // ---- 1:4 and 2:1 rect walks, all resolved-symbol guarded -- - ( - "decode_rect4_16", - &[(16, 4), (4, 16)], - Mech::AtResolution(KF, 16), - ), - ( - "decode_rect4_16_strip", - &[(16, 4), (4, 16)], - Mech::AtResolutionVia(KF, 16), - ), - ( - "decode_block_rect", - &[(32, 16), (16, 32)], - Mech::AtResolution(KF, 32), - ), - ( - "decode_block_rect4", - &[(32, 8), (8, 32)], - Mech::AtResolution(KF, 32), - ), - ( - "decode_block_rect64", - &[(64, 16), (16, 64)], - Mech::AtResolution(KF, 64), - ), - // The 128-root guard lives in `read_sb128_root`, the shared - // resolver both tile decoders call -- not in the walker's own - // function. - ( - "decode_block_128rect", - &[(128, 64), (64, 128)], - Mech::AtResolutionVia("read_sb128_root", 128), - ), - // `decode_rect_split` is called from inside decode_block_rect / - // decode_leaf_rect / decode_block_rect4 / decode_block_rect64, none of - // which is the tile decoder -- so the guard it inherits is checked on - // its own callers' rows, not here. - ( - "decode_rect_split", - &[(64, 16), (16, 64), (32, 16), (16, 32)], - Mech::AtResolutionVia(KF, 32), - ), - ( - "decode_leaf_rect", - &[(16, 8), (8, 16)], - Mech::AtResolution(KF, 16), - ), - // ---- the INTER-side rect walks ----------------------------- - // - // r2: without these three rows the inter 32- and 64-level guards - // were claimed by NOTHING, and deleting either left the census - // green. They are load-bearing -- `decode_intra_rect_in_inter` - // dispatches `decode_block_rect4` on 32x8/8x32 (8x32 is - // BLOCK_INVALID at 4:2:2) and `decode_block_rect64` on - // 64x16/16x64 (16x64 likewise) -- so each gets its own row naming - // the guard that stands in front of it. - // - // These are `AtResolutionVia`, not `AtResolution`: the walk is - // dispatched from `decode_intra_rect_in_inter`, a helper, not from - // the tile decoder the guard lives in. The check is therefore guard - // EXISTENCE in that decoder -- which is what reds when the guard - // is deleted -- and the linkage is stated here rather than derived. - ( - "decode_block_rect4[inter]", - &[(32, 8), (8, 32)], - Mech::AtResolutionVia(INTER, 32), - ), - ( - "decode_block_rect64[inter]", - &[(64, 16), (16, 64)], - Mech::AtResolutionVia(INTER, 64), - ), - ( - "decode_intra_rect_in_inter", - &[(16, 8), (8, 16), (16, 4), (4, 16)], - Mech::AtResolutionVia(INTER, 16), - ), - // ---- sub-8 walks ------------------------------------------ - // (8,4) is legal at 4:2:2 (`av1_ss_size_lookup[8x4][1][0]` is - // BLOCK_4X4); (4,8) is BLOCK_INVALID there. Both come off a raw - // `part8`, and both 8x8 resolution sites carry the guard -- plus - // the redundant inline `chroma_plane_block_codable` check the - // merged lane left at 36904. - ( - "decode_leaf_rect8", - &[(8, 4), (4, 8)], - Mech::AtResolution(KF, 8), - ), - ( - "decode_inter_sub8_rect2", - &[(8, 4), (4, 8)], - Mech::AtResolution(INTER, 8), - ), - ( - "decode_leaf_split4", - &[(4, 4)], - Mech::Unreachable("4x4's plane block is 4x4 at EVERY subsampling cell"), - ), - ( - "decode_inter_sub8_split4", - &[(4, 4)], - Mech::Unreachable("4x4's plane block is 4x4 at EVERY subsampling cell"), - ), - ( - "decode_leaf8", - &[(8, 8)], - Mech::Unreachable("8x8's plane block is 8x8 / 4x8 / 4x4, never BLOCK_INVALID"), - ), - // The square walks take only square footprints, and every square - // in `BLOCK_SIZES_ALL` has a valid plane block at EVERY selectable - // mode (the whole BLOCK_INVALID column is 4x8 / 8x4 / 4x16 / 8x16 - // / ... -- all rect). So no guard is needed for them, and the - // level guards that exist protect the SYMBOL that would have to - // select one of those rect shapes, not the square decode itself. - ( - "decode_block", - &[(128, 128), (64, 64), (32, 32), (16, 16), (8, 8)], - Mech::Unreachable( - "every SQUARE footprint's plane block is valid at every selectable \ - subsampling mode; the whole BLOCK_INVALID column is rect", - ), - ), - ( - "decode_inter_block", - &[(128, 128), (64, 64), (32, 32), (16, 16), (8, 8)], - Mech::Unreachable( - "every SQUARE footprint's plane block is valid at every selectable \ - subsampling mode; the whole BLOCK_INVALID column is rect", - ), - ), - ( - "decode_inter_block8", - &[(8, 8)], - Mech::Unreachable("8x8's plane block is 8x8 / 4x8 / 4x4, never BLOCK_INVALID"), - ), - // ---- THE HOLE THIS LANE FIXED --------------------------- - // - // `decode_leaf_rect`'s key-frame FRAME-EDGE caller (the one - // `decode_leaf_rect`'s row above does not cover, because that arm - // dispatches on a gathered `edge_split` instead of resolving into - // `part16`). It is 8x16 when the COLUMN is short -- BLOCK_INVALID - // at 4:2:2 -- and 16x8 when the ROW is, which is legal and must - // keep decoding. Before this lane nothing sat on that path. - ( - "decode_leaf_rect[16-edge]", - &[(16, 8), (8, 16)], - Mech::AtDispatch, - ), - ]; - - // (c) Every row's mechanism must be a REAL one. This is what stops - // the census from being a list of good intentions: each claim is - // re-derived here, and the file is checked for the site it names. - for (walk, shapes, mech) in census { - let name = walk.split('[').next().expect("walk name"); - assert!( - src.contains(&format!("fn {name}(")), - "the census names `{name}`, which is not a function in this file -- the \ - walk was renamed or removed and this row is stale" - ); - // Only subsampling modes a `color_config` can actually SELECT - // count. `(0, 1)` 4:4:0 is excluded on libaom's own authority -- - // it asserts `subsampling_y == 0` whenever `subsampling_x == 0` - // (`color_config`, av1_decoder.c), so no frame in existence is - // 4:4:0 and `PLANE_BLOCK_INVALID_440` is transcribed only to keep - // the cell table whole. Counting it here would make `16x4` look - // like a shape that needs a guard at a mode no stream can carry - // -- the same class as the merged lane's r2, which refused a legal - // 4:2:2 shape by testing a cell no `color_config` can request. - let offending: Vec<(usize, usize, usize, usize)> = shapes - .iter() - .flat_map(|&(bw, bh)| { - [(1, 0), (1, 1), (0, 0)] - .into_iter() - .filter_map(move |(sx, sy)| { - invalid_at(bw, bh, sx, sy).then_some((bw, bh, sx, sy)) - }) - }) - .collect(); - match mech { - // A dispatch-time guard has to reduce to the SAME shape the - // dispatch hands the walk -- this is the claim that made the - // hole a hole, stated as an assertion. - Mech::AtDispatch => { - assert!( - !offending.is_empty(), - "{walk} is listed AtDispatch but libaom codes every shape it \ - walks at every subsampling mode -- then it needs no guard" - ); - for &(bw, bh, sx, sy) in &offending { - assert!( - invalid_at(bw, bh, sx, sy), - "{walk} is not actually handed {bw}x{bh} at ({sx},{sy})" - ); - } - } - // r2: the guard THIS row depends on, scoped to the function it - // lives in and ordered before the walk's first call there. - // Deleting that one guard -- and only that one -- reds this row, - // which is what r2's review showed the previous version could - // not do. - Mech::AtResolution(fscope, level) => { - assert!( - !offending.is_empty(), - "{walk} is listed AtResolution but no shape it walks is BLOCK_INVALID \ - -- then the level's guard is not what protects it" - ); - let fstart = decode_body - .find(&format!("\nfn {fscope}(")) - .or_else(|| decode_body.find(&format!("\npub(crate) fn {fscope}("))) - .or_else(|| decode_body.find(&format!("\npub fn {fscope}("))) - .unwrap_or_else(|| { - panic!("the census names `{fscope}`, which is not a function here") - }); - let fend = ["\nfn ", "\npub fn ", "\npub(crate) fn "] - .iter() - .filter_map(|pat| decode_body[fstart + 1..].find(pat).map(|i| fstart + 1 + i)) - .min() - .unwrap_or(decode_body.len()); - let body = &decode_body[fstart..fend]; - let guard = format!("refuse_invalid_subsize(({level}, {level})"); - let gpos = body.find(&guard).unwrap_or_else(|| { - panic!( - "{walk} claims refuse_invalid_subsize(({level}, {level})) guards it, \ - but there is NO such guard in `{fscope}` -- the row's mechanism is \ - prose, not a check; re-derive it or mark the row Prose" - ) - }); - let call = body.find(&format!("{name}(")).unwrap_or_else(|| { - panic!("{walk} has no call site inside `{fscope}` to order the guard against") - }); - assert!( - gpos < call, - "{walk}: in `{fscope}` the ({level}, {level}) guard is at {gpos} and the \ - walk is dispatched at {call} -- a guard BELOW the dispatch can never \ - observe it" - ); - } - Mech::AtResolutionVia(fscope, level) => { - assert!( - !offending.is_empty(), - "{walk} is listed AtResolutionVia but no shape it walks is \ - BLOCK_INVALID" - ); - let fstart = decode_body - .find(&format!("\nfn {fscope}(")) - .or_else(|| decode_body.find(&format!("\npub(crate) fn {fscope}("))) - .or_else(|| decode_body.find(&format!("\npub fn {fscope}("))) - .unwrap_or_else(|| { - panic!("the census names `{fscope}`, which is not a function here") - }); - let fend = ["\nfn ", "\npub fn ", "\npub(crate) fn "] - .iter() - .filter_map(|pat| decode_body[fstart + 1..].find(pat).map(|i| fstart + 1 + i)) - .min() - .unwrap_or(decode_body.len()); - assert!( - decode_body[fstart..fend] - .contains(&format!("refuse_invalid_subsize(({level}, {level})")), - "{walk} claims refuse_invalid_subsize(({level}, {level})) in `{fscope}` \ - guards it, but there is NO such guard there" - ); - } - Mech::Unreachable(reason) => { - assert!( - offending.is_empty(), - "{walk} claims it is unreachable, but libaom marks {} \ - BLOCK_INVALID -- the claim is stale", - offending - .iter() - .map(|(bw, bh, sx, sy)| format!("{bw}x{bh}@({sx},{sy})")) - .collect::>() - .join(", ") - ); - assert!( - reason.len() > 40, - "{walk}'s Unreachable reason is too short to name the symbol \ - or caller that makes it unreachable" - ); - } - } - } - - // (d) The residue's closure, derived rather than asserted in prose: - // the ONLY subsize its callers can hand it that libaom refuses at - // 4:2:2 is the 16x16-level VERT_4 one, and the level's own guard - // refuses exactly that. If either half stops holding -- a new caller - // at another level, or a change to `partition_subsize_dims` -- this - // reds instead of the comment going stale. - for &(part, want) in &[ - (PARTITION_HORZ_4, (16usize, 4usize)), - (PARTITION_VERT_4, (4, 16)), - ] { - let (bw, bh) = partition_subsize_dims((16, 16), part); - assert_eq!( - (bw, bh), - want, - "get_partition_subsize(BLOCK_16X16, {part}) moved" - ); - assert_eq!( - chroma_plane_block_codable(bw, bh, 1, 0), - part == PARTITION_HORZ_4, - "the 16x16 1:4 pair's (1,0) cells moved: HORZ_4 -> {bw}x{bh}, \ - VERT_4 -> {bw}x{bh}. decode_rect4_16_intrabc's Unreachable row \ - is written against exactly this split" - ); - } - // (e) The AtDispatch row, checked where it actually bites. This is - // the hole the merged lane's scan cannot see: its 220-line window is - // keyed on `dec.symbol(`, and the frame-edge arm reads - // `dec.symbol_fixed(&gather(..))` into `edge_split` and dispatches on - // THAT. The claim to check is ordering -- the guard has to sit between - // the read and the `decode_leaf_rect` it protects, which is r5's - // defect in a new place if it ever moves below. - let edge_read = src - .find("let edge_split = if has_cols16") - .expect("the key-frame 16-level frame-edge arm reads a gathered bit"); - let guard_at = src[edge_read..] - .find("refuse_invalid_subsize((16, 16)") - .map(|i| edge_read + i) - .expect( - "the key-frame 16-level frame-edge arm dispatches decode_leaf_rect on an \ - 8x16 strip (BLOCK_INVALID at 4:2:2) with NO refuse_invalid_subsize on its \ - path -- every sibling edge arm resolves into a guarded partN, this one does not", - ); - let walk_at = src[edge_read..] - .find("decode_leaf_rect(") - .map(|i| edge_read + i) - .expect("the frame-edge arm's decode_leaf_rect call"); - assert!( - guard_at < walk_at, - "the 16-level frame-edge guard (offset {guard_at}) sits AFTER the \ - decode_leaf_rect it protects (offset {walk_at}) -- it can never observe it" - ); - - // (f) The residue's closure, by CALLER COUNT rather than by prose: a - // third caller at another level is what would make the residue row - // stale, and a count reds on that where a comment cannot. Counted over - // the DECODE BODY only -- this test's own string literals name the same - // functions, and the merged lane's own scan hit exactly that (five of - // its eighteen `refuse_invalid_subsize((` matches are its own). - for (name, calls) in [ - ("decode_rect4_16_intrabc", 1usize), - ("decode_rect4_16_strip", 2), - ("decode_rect4_16", 1), - ("decode_intra_rect_in_inter", 1), - ] { - let needle = format!("{name}("); - let decl = format!("fn {name}("); - // A doc-comment mention (`[`name`](..)`) is prose, not a call, so - // comment lines are dropped before counting. - let body: String = decode_body - .lines() - .filter(|l| !l.trim_start().starts_with("//")) - .collect::>() - .join("\n"); - let found = body.matches(&needle).count() - usize::from(body.contains(&decl)); - assert_eq!( - found, calls, - "{name} has {found} call site(s) in the decode body, the census expects \ - {calls}. A new caller is not automatically wrong, but it is not \ - automatically covered either: re-derive which level's guard it sits \ - under before this row stays green" - ); - } - // Both callers reach the 1:4 strips by a DIFFERENT route, so the - // closure is checked per route -- and per route it is the same shape: - // the 16x16-level guard must sit ABOVE the test that names VERT_4. - // - // key frame: `decode_rect4_16(...)` at 36793, inside an arm testing - // `part16 == PARTITION_HORZ_4 || part16 == PARTITION_VERT_4`. - // inter: the 1:4 strips reach `decode_intra_rect_in_inter` - // through `fctx.inter_strip_chroma`, whose ONLY writer is the inter - // 16-level 1:4 arm (55068) -- `strip16` is `None` without it. - // - // Ordering is the property (a guard BELOW the 1:4 test cannot observe - // it), which is why each pair is compared rather than merely counted. - for (what, test, call) in [ - ( - "the key-frame decode_rect4_16 caller", - "if part16 == PARTITION_HORZ_4", - "decode_rect4_16(", - ), - ( - "the inter-frame inter_strip_chroma writer", - "let horz = part16 == PARTITION_HORZ_4;", - "c.set(Some(InterStripChroma {", - ), - ] { - let fn_scope = |at: usize| -> std::ops::Range { - let head = ["\nfn ", "\npub fn ", "\npub(crate) fn "] - .iter() - .filter_map(|pat| decode_body[..at].rfind(pat)) - .max() - .unwrap_or(0); - let tail = ["\nfn ", "\npub fn ", "\npub(crate) fn "] - .iter() - .filter_map(|pat| decode_body[at..].find(pat).map(|i| at + i)) - .min() - .unwrap_or(decode_body.len()); - head..tail - }; - // The first occurrence of the test text can sit in another function (the files are - // concatenated in path order), so take the first occurrence whose own function holds - // the dispatch. The guard, the test and the dispatch must then share that function. - let (test_at, _, call_at) = decode_body - .match_indices(test) - .find_map(|(t, _)| { - let sc = fn_scope(t); - decode_body[sc.clone()] - .rfind(call) - .map(|i| (t, sc.clone(), sc.start + i)) - }) - .unwrap_or_else(|| panic!("the 1:4 arm test {test:?} for {what} is gone, or no function holds its dispatch {call:?}")); - // The dispatch is searched inside the 1:4 test's own function: the files are - // concatenated in path order, so the last occurrence in the whole text is no longer - // the key-frame call. The guard, test and dispatch must share that function. - // `decode_rect4_16(` also matches the DEFINITION, which is the - // first occurrence -- the call is the last one. - // r2 (Main's review, and it was right): the guard search is SCOPED - // to the anchor's own enclosing function. `find()` over the whole - // decode body returns the FIRST `refuse_invalid_subsize((16, 16)` -- - // the KEY-FRAME one -- so the inter pair's comparison was satisfied - // by a guard three quarters of the file away, and deleting the inter - // 16-level guard left this test green. Both routes live in - // different `fn` bodies (`decode_key_frame_tile_with_cdfs` and the - // inter tile decoder), so the enclosing function is the scope that - // tells the two apart. - let scope = fn_scope(test_at); - let guard_at = decode_body[scope.clone()] - .find("refuse_invalid_subsize((16, 16)") - .map(|i| scope.start + i) - .unwrap_or_else(|| { - panic!( - "{what}: there is NO refuse_invalid_subsize((16, 16)) in the function \ - enclosing the 1:4 arm test -- so nothing refuses the VERT_4 symbol \ - this arm dispatches on, and decode_rect4_16_intrabc's closure is gone" - ) - }); - assert!( - guard_at < test_at && test_at < call_at, - "{what}: guard at {guard_at} (function scope {scope:?}), 1:4 arm test at \ - {test_at}, dispatch at {call_at}. The guard has to sit ABOVE the 1:4 arm \ - test INSIDE THE SAME FUNCTION, or the VERT_4 symbol it refuses has already \ - been dispatched on" - ); - assert!( - scope.contains(&guard_at) && scope.contains(&test_at) && scope.contains(&call_at), - "{what}: guard, 1:4 test and dispatch must share one enclosing function" - ); - } - // And the inter route really is the only one: `strip16` is built from - // `strip_chroma`, which is `inter_strip_chroma.take()`, so a missing - // writer would silently drop the arm rather than expose it. - assert_eq!( - decode_body.matches("inter_strip_chroma.with(|c| {").count(), - 1, - "inter_strip_chroma gained a second writer -- the inter 1:4 strips can now \ - come from a level whose guard this census has not checked" - ); - - // (g) PER-SITE rows. Everything above claims a guard by LEVEL -- - // "there is a `refuse_invalid_subsize((8, 8))` somewhere in the - // key-frame tile decoder" -- and that is exactly what makes two - // guards deletable: the key-frame 8x8 level has TWO resolution - // sites (37322 and 37621) and the walk census's `decode_leaf_rect8` - // row is satisfied by the first one, so deleting the SECOND left the - // test green; the inter decoder carries its OWN 128-root guard - // (54495) while the `decode_block_128rect` row names - // `read_sb128_root`, so deleting the inter copy also left it green. - // The merged scan's count cross-check is what reds them, and a - // count is not a location. - // - // So each row below names an ANCHOR that is unique in the decode - // body -- the code the site hangs off -- and requires the level's - // guard to sit between that anchor and the dispatch the site - // feeds, within the same function. A level guard elsewhere in that - // function cannot stand in, because the search starts AT the - // anchor. Deleting the named guard finds no guard after the anchor - // and reds; moving it below the dispatch reds the ordering assert. - // - // Row shape: (site label, guard's function, level, unique anchor, - // dispatch token the guard must precede, shapes the site walks). - let body_of = |name: &str| -> &str { - let start = decode_body - .find(&format!("\nfn {name}(")) - .or_else(|| decode_body.find(&format!("\npub(crate) fn {name}("))) - .or_else(|| decode_body.find(&format!("\npub fn {name}("))) - .unwrap_or_else(|| panic!("{name} is not a function in this file")); - let end = ["\nfn ", "\npub fn ", "\npub(crate) fn "] - .iter() - .filter_map(|pat| decode_body[start + 1..].find(pat).map(|i| start + 1 + i)) - .min() - .unwrap_or(decode_body.len()); - &decode_body[start..end] - }; - let site_rows: &[(&str, &str, usize, &str, &str, &[(usize, usize)])] = &[ - // The key-frame 8x8 level resolves TWICE (37322 for the frame - // interior, 37621 for the `pre8` probe path). Both feed - // `decode_leaf_rect8` on a raw `part8`, whose VERT shape is 4x8 -- - // BLOCK_INVALID at 4:2:2. The anchor `let pre8 = ...` is what - // makes this row about the SECOND site: with `find()` scoped to - // the function alone the search would return 37322 and never - // look here. - ( - "the key-frame 8x8 SECOND resolution", - KF, - 8, - "let pre8 = dec.debug_state().0;", - "decode_leaf_rect8(", - &[(8, 4), (4, 8)], - ), - // The inter decoder resolves its own 128 root at 54495 rather - // than routing through `read_sb128_root` (which is where the - // `decode_block_128rect` row's guard lives). The dispatch token - // is the `half128_inter!` arm that descends into a 128x64 / - // 64x128 rect -- both BLOCK_INVALID at 4:2:2 in - // `PLANE_BLOCK_INVALID_422`. `macro_rules! half128_inter` is - // unique in the file, so this row cannot drift onto the other - // one. - ( - "the inter decoder's own 128-root guard", - INTER, - 128, - "macro_rules! half128_inter", - "half128_inter!((br_mi, base_mi.1), 128, 64,", - &[(128, 64), (64, 128)], - ), - ]; - for (label, fscope, level, anchor, dispatch, shapes) in site_rows { - assert_eq!( - decode_body.matches(anchor).count(), - 1, - "{label}: the site anchor {anchor:?} is not unique in the decode body, so it \ - cannot name one site -- re-derive the anchor for this row" - ); - // Why the site needs a guard at all: something it dispatches is - // BLOCK_INVALID at a mode a `color_config` can select. (0, 1) is - // excluded for the same reason as the walk census above. - let offending: Vec<(usize, usize, usize, usize)> = shapes - .iter() - .flat_map(|&(bw, bh)| { - [(1, 0), (1, 1), (0, 0)] - .into_iter() - .filter_map(move |(sx, sy)| { - invalid_at(bw, bh, sx, sy).then_some((bw, bh, sx, sy)) - }) - }) - .collect(); - assert!( - !offending.is_empty(), - "{label} claims a guard but libaom codes every shape it walks at every \ - selectable subsampling mode -- then it needs none" - ); - let body = body_of(fscope); - let a = body.find(anchor).unwrap_or_else(|| { - panic!( - "{label}: the anchor {anchor:?} is not inside `{fscope}` -- the guard \ - moved to another function, and the row's scope is stale" - ) - }); - let gpat = format!("refuse_invalid_subsize(({level}, {level})"); - let g = body[a..].find(&gpat).map(|i| a + i).unwrap_or_else(|| { - panic!( - "{label}: `{fscope}` has NO {gpat} at or after the site anchor {anchor:?} \ - -- this site's guard is gone. The level claim elsewhere in this test is \ - still satisfied by the OTHER {level}x{level} guard in the file, which is \ - precisely why this row exists" - ) - }); - let gap = body[a..g].lines().count(); - assert!( - gap <= 40, - "{label}: the {gpat} sits {gap} lines below its own anchor {anchor:?} -- that is \ - a different site, so this row has stopped naming what it claims to name" - ); - let d = body[g..].find(dispatch).map(|i| g + i).unwrap_or_else(|| { - panic!( - "{label}: `{fscope}` dispatches {dispatch:?} nowhere AFTER its {gpat} -- \ - either the dispatch moved above the guard or the site was rewritten" - ) - }); - assert!( - g < d, - "{label}: guard at {g} sits at or after the dispatch at {d} -- a guard BELOW \ - the dispatch can never observe it" - ); - } -} - -/// lane/av1422rect4dead: the `(pw / 2, ph / 2)` / `MI / 2` origin `else` -/// arm of [`decode_rect4_16_intrabc`] is the 4:2:0 PAIR geometry. It is -/// still LIVE at ss (1, 1) -- a 1:4 strip's chroma lies inside its -/// 4:2:0 pair there -- so the arm is not deleted; it is CLOSED at ss -/// (1, 0), where it would run on a 4x16 VERT_4 strip whose chroma plane -/// block is BLOCK_INVALID, and where libaom's own -/// `is_chroma_reference` (av1_common_int.h:1454, `|| !subsampling_y`) -/// makes every strip its own chroma reference anyway (the `own422` arm -/// handles that). The proof: the sole caller `decode_rect4_16_strip` is -/// reached only via the two 16x16-level 1:4 arms, each under -/// `refuse_invalid_subsize((16, 16), part16)` -- at ss (1, 0) that guard -/// refuses `partition_subsize_dims((16, 16), PARTITION_VERT_4) == (4, 16)` -/// (in `PLANE_BLOCK_INVALID_422`), and the surviving HORZ_4 16x4 strip -/// takes `own422`. This test re-derives that chain from the file so it -/// REDS when any half stops holding: deleting the in-arm assertion, a -/// caller moving under a level whose guard does not refuse (4, 16) at -/// ss (1, 0), or the `(pw / 2, ph / 2)` form drifting. 4:2:0 and 4:4:4 -/// behaviour are unchanged: the gate runs only the file scan and the -/// closed cell's arithmetic, no decode. -#[test] -fn decode_rect4_16_intrabc_else_arm_stays_closed_at_422() { - let production = crate::test_source::module_production_source("decode"); - let decode_body = match production.find("\n#[cfg(test)]\nmod tests {") { - Some(i) => &production[..i], - None => production, - }; - - // (a) The closure assertion must exist INSIDE the function, in the - // `else` arm of the `(cw, ch)` select, naming the shape and the - // subsampling. Deleting it -- or re-adding the bare halving without - // it -- reds here. - let fstart = decode_body - .find("\nfn decode_rect4_16_intrabc(") - .expect("decode_rect4_16_intrabc is gone -- this gate guards its else arm"); - let fend = ["\nfn ", "\npub fn ", "\npub(crate) fn "] - .iter() - .filter_map(|pat| decode_body[fstart + 1..].find(pat).map(|i| fstart + 1 + i)) - .min() - .unwrap_or(decode_body.len()); - let body = &decode_body[fstart..fend]; - let else_arm = body - .find(" let (cw, ch) = if own_chroma {") - .expect("the (cw, ch) select moved out of decode_rect4_16_intrabc"); - let closure = &body[else_arm..]; - assert!( - closure.contains("assert!(") && closure.contains("ss_x(fctx) == 1 && ss_y(fctx) == 0"), - "the decode_rect4_16_intrabc else arm's ss (1, 0) closure assertion is \ - GONE -- the 4:2:0 pair geometry is unreachable at ss (1, 0) only while \ - that assert (and the guards below) stand; re-add it" - ); - - // (b) The sole-caller chain, re-derived from the file: exactly one - // call to `decode_rect4_16_intrabc(` outside its own definition, in - // `decode_rect4_16_strip`; exactly two calls to - // `decode_rect4_16_strip(` from the two 1:4 routes. - let code_lines: String = decode_body - .lines() - .filter(|l| !l.trim_start().starts_with("//")) - .collect::>() - .join("\n"); - let count_calls = |name: &str| -> usize { - code_lines.matches(&format!("{name}(")).count() - - usize::from(code_lines.contains(&format!("fn {name}("))) - }; - assert_eq!( - count_calls("decode_rect4_16_intrabc"), - 1, - "decode_rect4_16_intrabc gained a caller -- re-derive whether the new route \ - sits under a guard that refuses (4, 16) at ss (1, 0) before this gate \ - stays green" - ); - assert_eq!( - count_calls("decode_rect4_16_strip"), - 2, - "decode_rect4_16_strip's caller set moved -- both routes must be \ - 16x16-level 1:4 arms under a (16, 16) guard that refuses (4, 16) at \ - ss (1, 0)" - ); - - // (c) Both routes sit under a `refuse_invalid_subsize((16, 16), ...)`: - // the key-frame arm's guard ordered above the arm test, the inter - // arm's guard in the inter decoder above its own 1:4 test. Scoped to - // the enclosing function so the other decoder's guard cannot stand in - // (the r2 class this file already fixed once). - let fn_scope = |at: usize| -> std::ops::Range { - let head = ["\nfn ", "\npub fn ", "\npub(crate) fn "] - .iter() - .filter_map(|pat| decode_body[..at].rfind(pat)) - .max() - .unwrap_or(0); - let tail = ["\nfn ", "\npub fn ", "\npub(crate) fn "] - .iter() - .filter_map(|pat| decode_body[at..].find(pat).map(|i| at + i)) - .min() - .unwrap_or(decode_body.len()); - head..tail - }; - let kf_test = decode_body - .find("if part16 == PARTITION_HORZ_4") - .expect("the key-frame 16-level 1:4 arm test is gone"); - let kf_scope = fn_scope(kf_test); - let kf_guard = decode_body[kf_scope.clone()] - .find("refuse_invalid_subsize((16, 16)") - .map(|i| kf_scope.start + i) - .unwrap_or_else(|| { - panic!( - "the key-frame 16-level 1:4 arm has NO \ - refuse_invalid_subsize((16, 16)) above it in its own \ - function -- the VERT_4 (4, 16) refusal that closed \ - decode_rect4_16_intrabc's else arm at ss (1, 0) is gone" - ) - }); - assert!( - kf_guard < kf_test, - "the key-frame (16, 16) guard sits below the 1:4 arm test -- it can never \ - observe the VERT_4 symbol that must be refused before \ - decode_rect4_16_intrabc's else arm can run at ss (1, 0)" - ); - let inter_writer = decode_body - .find("let horz = part16 == PARTITION_HORZ_4;") - .expect("the inter 16-level 1:4 arm is gone"); - let inter_scope = fn_scope(inter_writer); - let inter_guard = decode_body[inter_scope.clone()] - .find("refuse_invalid_subsize((16, 16)") - .map(|i| inter_scope.start + i) - .unwrap_or_else(|| { - panic!( - "the inter-frame 16-level 1:4 arm has NO \ - refuse_invalid_subsize((16, 16)) in its function -- the VERT_4 \ - (4, 16) refusal that closed decode_rect4_16_intrabc's else arm \ - at ss (1, 0) is gone" - ) - }); - assert!( - inter_guard < inter_writer, - "the inter (16, 16) guard sits below the 1:4 arm test -- it can never \ - observe the VERT_4 symbol that must be refused before \ - decode_rect4_16_intrabc's else arm can run at ss (1, 0)" - ); - - // (d) The shape/subsampling cells the closure is written against, - // re-executed: (4, 16) must still be BLOCK_INVALID at ss (1, 0) while - // (16, 4) stays codable there, and at ss (1, 1) BOTH are codable -- - // which is what keeps the arm live at 4:2:0 and the assertion inert - // there. At ss (0, 0) everything is codable, so `own444` (and the - // assertion) never see the else arm. - assert!( - !chroma_plane_block_codable(4, 16, 1, 0), - "(4, 16) left PLANE_BLOCK_INVALID_422 -- the else arm is now REACHABLE at \ - ss (1, 0) with the halved pair geometry, which is a real defect, not a \ - closure: re-derive the whole chain, then fix the halving instead of the \ - assert" - ); - assert!( - chroma_plane_block_codable(16, 4, 1, 0), - "(16, 4) became BLOCK_INVALID at ss (1, 0) -- the surviving HORZ_4 strip \ - takes own422, and the closure assert would fire on a legal shape; \ - re-derive" - ); - assert!( - chroma_plane_block_codable(4, 16, 1, 1) && chroma_plane_block_codable(16, 4, 1, 1), - "a 1:4 strip's plane block moved at ss (1, 1) -- the else arm is LIVE there \ - and the pair geometry is what decodes it; the assertion must stay inert at \ - 4:2:0" - ); - assert!( - chroma_plane_block_codable(4, 16, 0, 0) && chroma_plane_block_codable(16, 4, 0, 0), - "a 1:4 strip's plane block became invalid at ss (0, 0) -- the assertion sits \ - after the own444 arm and must never fire at 4:4:4; re-derive" - ); -} - /// lane-av1chrtx: [`covering_leaf_tx_type`] resolves a chroma unit's /// `tx_type` from the luma leaf covering the unit's OWN quadrant, and /// reports "no leaf there" as `None` so the caller can fall back to the @@ -2415,84 +1209,6 @@ fn an_obmc_neighbour_with_no_recorded_filter_refuses_instead_of_panicking() { ); } -/// lane-t900 r27, structural audit for "an OBMC neighbour whose switchable -/// interp filter was never recorded": the `[3, 3]` sentinel is only ever -/// PUBLISHED for a cell an OBMC blend cannot pick up. -/// -/// `Neighbours::record_inter_rect_mi` is the single writer of -/// `above_filter`/`left_filter` (every other recorder routes through it), -/// so the whole domain of published values is its call sites' 7th -/// argument. Two publications are safe: an INTRA cell (`is_inter = false`, -/// skipped by `overlappable_above`/`overlappable_left`'s own `is_inter` -/// gate) and a fixed-filter frame (`resolve_interp_filter` returns the -/// sentinel when `interp_fixed` is `Some`, which `neighbour_filter` -/// answers before ever looking at the symbols). What this scans for is the -/// third case -- an INTER cell stamped with a literal sentinel, which is -/// what the refusal actually fires on. Arguments are tokenised -/// positionally, never `contains()`d. -#[test] -fn every_inter_record_publishes_an_obmc_readable_filter() { - let src = crate::test_source::module_source("decode"); - let mut calls = 0usize; - for (start, _) in src.match_indices("record_inter_rect_mi(") { - // Skip the definition and the wrapper's own forwarding call. - let line_start = src[..start].rfind('\n').map_or(0, |i| i + 1); - let head = &src[line_start..start]; - // The definition, the wrapper's own forwarding call, and this - // test's own mentions of the name (doc comment, scan pattern, - // assert message) are not publication sites. - if head.contains("fn ") || head.contains("///") || head.ends_with('"') { - continue; - } - let mut i = start + "record_inter_rect_mi(".len(); - let (mut depth, mut arg, mut args) = (0i32, String::new(), Vec::new()); - let bytes = src.as_bytes(); - while i < bytes.len() { - let c = bytes[i] as char; - match c { - '(' | '[' => depth += 1, - ')' | ']' if depth == 0 && c == ')' => break, - ')' | ']' => depth -= 1, - ',' if depth == 0 => { - args.push(std::mem::take(&mut arg)); - i += 1; - continue; - } - _ => {} - } - arg.push(c); - i += 1; - } - if !arg.trim().is_empty() { - args.push(arg); - } - assert_eq!( - args.len(), - 8, - "record_inter_rect_mi gained an argument -- re-index this audit: {args:?}" - ); - calls += 1; - let (is_inter, filter) = (args[4].trim(), args[6].trim()); - if filter.starts_with('[') { - assert_eq!( - filter.replace(' ', ""), - "[3,3]", - "a literal filter other than the sentinel is published at call {calls}" - ); - assert_eq!( - is_inter, "false", - "an INTER cell is stamped with the [3, 3] sentinel (call {calls}): an OBMC \ - blend picking it up refuses by name. Publish the block's own resolved \ - switchable symbols instead." - ); - } - } - assert!( - calls >= 6, - "the audit found only {calls} publication sites -- it is broken, not the decoder" - ); -} - /// lane-t900 r27, negative gate for "a reference frame selected with no /// picture at this frame's own ref_frame_idx slot for it": every /// non-`LAST_FRAME` reference resolves through `ref_planes`, and an empty @@ -2842,7 +1558,6 @@ fn a_skipped_block_decodes_to_pure_prediction() { #[test] fn a_skipped_intrabc_chroma_reference_leaf_disarms_the_inherited_chroma_tx() { let fctx = &crate::decode::FrameCtx::new(); - reset_skipped_intrabc_chroma_arm_hits(); use crate::msac::SymbolEncoder; let mut cdfs = Cdfs::new(q_ctx_of(40)); let mut enc = SymbolEncoder::new(); @@ -2883,10 +1598,6 @@ fn a_skipped_intrabc_chroma_reference_leaf_disarms_the_inherited_chroma_tx() { true, fctx, ); - assert!( - skipped_intrabc_chroma_arm_hits() >= 1, - "the hand-written tile never reached the skipped-intrabc chroma-reference route" - ); assert!( fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_none(), "the inherited chroma transform slot must be disarmed when its block's chroma \ @@ -2901,7 +1612,6 @@ fn a_skipped_intrabc_chroma_reference_leaf_disarms_the_inherited_chroma_tx() { #[test] fn a_skipped_intrabc_rect_chroma_reference_leaf_disarms_the_inherited_chroma_tx() { let fctx = &crate::decode::FrameCtx::new(); - reset_skipped_intrabc_chroma_arm_hits(); use crate::msac::SymbolEncoder; let mut cdfs = Cdfs::new(q_ctx_of(40)); let mut enc = SymbolEncoder::new(); @@ -2934,10 +1644,6 @@ fn a_skipped_intrabc_rect_chroma_reference_leaf_disarms_the_inherited_chroma_tx( true, fctx, ); - assert!( - skipped_intrabc_chroma_arm_hits() >= 1, - "the hand-written tile never reached the skipped-intrabc rect chroma-reference route" - ); assert!( fctx.intrabc_chroma_tx.with(std::cell::Cell::get).is_none(), "the inherited chroma transform slot must be disarmed when its block's chroma \ @@ -3216,7 +1922,6 @@ fn a_filter_intra_key_frame_decodes_pixel_exact_through_ffmpeg() { } let encoded = crate::encode::encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap(); let (coded_w, coded_h) = ffprobe_size(&encoded.stream); - let before = filter_intra_hits(); let ours = decode_key_frame_tile_lr( &encoded.tile, encoded.mi_cols, @@ -3235,12 +1940,6 @@ fn a_filter_intra_key_frame_decodes_pixel_exact_through_ffmpeg() { fctx, ) .unwrap(); - let fired = filter_intra_hits() - before; - assert!( - fired > 0, - "no block took filter intra -- the gate is blind to the feature" - ); - eprintln!("a_filter_intra_key_frame: {fired} filter-intra blocks"); let ffmpeg_decoded = ffmpeg_decode(&encoded.stream, coded_w as usize, coded_h as usize); assert_eq!(ours.y, ffmpeg_decoded.y, "luma vs ffmpeg"); assert_eq!(ours.u, ffmpeg_decoded.u, "U vs ffmpeg"); diff --git a/crates/ec-av1/src/encode/tests.rs b/crates/ec-av1/src/encode/tests.rs index 87bb592b..078e3805 100644 --- a/crates/ec-av1/src/encode/tests.rs +++ b/crates/ec-av1/src/encode/tests.rs @@ -1130,241 +1130,6 @@ ); } - /// lane-av1paletteuv: the census for `crate::tile::palette_uv_side`, the - /// `(side / 2).max(4)` named in `lanes/av1subsizesweep.report.md` as a - /// "4:2:2/4:4:0 palette map mis-sized" site. - /// - /// **What the site computes.** libaom reads the plane-1 colour-index map - /// at `av1_get_block_dimensions(bsize, 1, xd)` (blockd.h:1512): per axis, - /// `plane_block = block >> ss`, then `+2` when that came out under 4 - /// (the chroma sub-8x8 bump, blockd.h:1533-1541). For a SQUARE 4:2:0 - /// block both axes carry `ss = 1`, so both come to `side / 2` with the - /// bump -- which is exactly `(side / 2).max(4)`. The value is right. - /// - /// **What it is not.** At 4:2:2 the correct map is `(side >> 1) x side` - /// and at 4:4:4 it is `side x side` -- neither is square. So the value is - /// 4:2:0-only BY CONSTRUCTION, and this gate is what keeps it that way: - /// if an encoder that can emit another chroma shape ever appears, this - /// reds rather than the writer silently writing a half-height map. - /// - /// The three arms are (1) the value matches libaom's own per-axis - /// formula at 4:2:0 over every side the palette syntax admits, (2) no - /// reachable writer path can be handed another chroma shape, (3) a real - /// encode really fires chroma palettes, so arm 1 is not arithmetic on a - /// function nothing calls (class `gate-blind-to-feature`). - #[test] - fn the_chroma_palette_map_side_is_the_420_plane_block_and_nothing_else_reaches_it() { - const NAME: &str = - "the_chroma_palette_map_side_is_the_420_plane_block_and_nothing_else_reaches_it"; - let encode_src = crate::test_source::module_source("encode"); - - // ---- arm 1: the value, against libaom's formula -------------------- - // blockd.h:1530-1541, transcribed. A plane_block under 4 gains 2. - let libaom_plane1 = |block: usize, ss: usize| { - let plane_block = block >> ss; - plane_block + 2 * usize::from(plane_block < 4) - }; - let mut admitted = 0usize; - for side in 4usize..=64 { - // `palette_bsize_ctx`'s own domain: both sides <= 64 and - // bw * bh >= 64 (`av1_allow_palette`). A side outside it codes no - // palette syntax at all, so its map size is unobservable. - if side > 64 || side * side < 64 { - continue; - } - admitted += 1; - let want_x = libaom_plane1(side, 1); - let want_y = libaom_plane1(side, 1); - assert_eq!(want_x, want_y, "{NAME}: 4:2:0 arms the libaom formula"); - assert_eq!( - crate::tile::palette_uv_side(side), - want_x, - "{NAME}: side {side} -- palette_uv_side disagrees with libaom's plane-1 block" - ); - } - assert_eq!( - admitted, 57, - "{NAME}: the sweep admitted {admitted} sides, expected 57 (every integer 8..=64 -- \ - `palette_bsize_ctx`'s whole square domain, not just the powers of two a real block \ - takes) -- it must cover that domain, or it is not measuring it" - ); - - // Why `.max(4)` cannot fire, stated as a measurement rather than left - // for a reader to assume: `palette_bsize_ctx` refuses `bw * bh < 64`, - // so the smallest admitted square side is 8, whose halved plane block - // is already 4. The floor's only reachable input would be a side - // under 8, and libaom's own chroma sub-8x8 bump (+2) is likewise - // unreachable there. Dropping the floor is therefore NOT a witness - // mutation for this gate -- the mutation that bites is dropping the - // halving (measured, see the lane report) -- and this arm says why, - // so nobody later mistakes a green floor mutation for coverage. - for side in [8usize, 16, 32, 64] { - assert!( - side / 2 >= 4 && libaom_plane1(side, 1) == side / 2, - "{NAME}: side {side} -- the admitted domain moved, so `.max(4)` may now be \ - reachable and the floor needs a witness mutation of its own" - ); - } - - // The claim the gate rests on, stated as arithmetic so a future - // reader cannot mistake "correct" for "correct at any shape": at - // these shapes the per-axis answer is NOT this square. - for side in [8usize, 16, 32, 64] { - let square = crate::tile::palette_uv_side(side); - let want_422 = (libaom_plane1(side, 1), libaom_plane1(side, 0)); - let want_444 = (libaom_plane1(side, 0), libaom_plane1(side, 0)); - assert_ne!( - (square, square), - want_422, - "{NAME}: side {side} -- a square map IS the 4:2:2 map, so this gate's premise \ - (the site is 4:2:0-only) is wrong" - ); - assert_ne!( - (square, square), - want_444, - "{NAME}: side {side} -- a square map IS the 4:4:4 map" - ); - } - - // ---- arm 2: nothing can hand the writer another shape -------------- - // (a) Every non-test `ColorConfig` literal in the encoder names - // subsampling (1, 1). These are the two constructors the whole - // encoder reaches its colour config through; the test-module copies - // are excluded by scanning only the pre-`mod tests` prefix. The cut - // matches an inline `mod tests {` body only, so a `mod tests;` file - // declaration does not truncate the production files after it. - fn head(src: &str) -> &str { - let cut = src.find("\nmod tests {").unwrap_or(src.len()); - &src[..cut] - } - for (label, src) in [ - ("encode.rs", head(crate::test_source::module_production_source("encode"))), - ("encoder.rs", head(crate::test_source::module_production_source("encoder"))), - ] { - // Every `subsampling_*` the non-test encoder names, counted: a - // `(0, y)` or `(1, 0)` here is a chroma shape - // `palette_uv_side` cannot express. The one value allowed is 1 - // -- 4:2:0, the shape the square map is the right size for. - let mut shapes: std::collections::BTreeSet<(usize, usize)> = Default::default(); - for (sx, _) in src.match_indices("subsampling_x:") { - let rest = &src[sx + "subsampling_x:".len()..]; - let digits = |s: &str| { - s.trim_start() - .split(|c: char| !c.is_ascii_digit()) - .next() - .and_then(|d| d.parse::().ok()) - .unwrap_or(usize::MAX) - }; - let x = digits(rest); - let y = rest - .find("subsampling_y:") - .map(|y| digits(&rest[y + "subsampling_y:".len()..])) - .unwrap_or(usize::MAX); - shapes.insert((x, y)); - } - assert_eq!( - shapes, - std::collections::BTreeSet::from([(1usize, 1usize)]), - "{NAME}: the non-test {label} names chroma shapes {shapes:?} -- any shape other \ - than 4:2:0 is one palette_uv_side's square map cannot express (at 4:2:2 the \ - map is (side >> 1) x side, at 4:4:4 side x side)" - ); - } - - // (b) `key_frame_headers_colour` is the only PUBLIC entry that takes - // a caller-chosen ColorConfig -- it is how a 4:2:2 or 4:4:4 header is - // written at all -- so it is the one door a non-4:2:0 shape comes - // through. It builds HEADERS only: no tile writer is reachable from - // its body. (Its own doc says so; this measures it.) - let headers_at = encode_src - .find("pub fn key_frame_headers_colour(") - .expect("key_frame_headers_colour is gone -- re-derive this arm's scan anchor"); - let body_end = encode_src[headers_at..] - .find("\npub fn ") - .map(|n| headers_at + n) - .unwrap_or(encode_src.len()); - let headers_body = &encode_src[headers_at..body_end]; - for writer in [ - "write_palette_syntax", - "write_color_index_map", - "encode_key_frame_inner", - "tile::", - ] { - assert!( - !headers_body.contains(writer), - "{NAME}: key_frame_headers_colour now reaches {writer} -- a caller can pair a \ - 4:2:2/4:4:4 header with a tile, and palette_uv_side writes a square map into \ - the per-axis slot libaom reads as (side >> ss_x) x (side >> ss_y)" - ); - } - - // (c) Every tile-producing entry point goes through - // `encode_key_frame_inner`, whose five non-test call sites all pass - // one of the two 4:2:0 constructors above. Counted over the - // non-test source only, so a new road is a red rather than a line - // somebody has to notice. - let inner_calls = head(crate::test_source::module_production_source("encode")).matches("encode_key_frame_inner(").count() - + head(crate::test_source::module_production_source("encoder")).matches("encode_key_frame_inner(").count() - - 1; // the definition itself - assert_eq!( - inner_calls, 5, - "{NAME}: encode_key_frame_inner has {inner_calls} non-test call sites, expected 5 -- \ - a new one must pass a colour config this gate has read" - ); - - // (d) The picture itself is 4:2:0-shaped at the door, so a 4:2:2 or - // 4:4:4 frame cannot even be handed to an encode entry. Measured by - // calling `check`, not by reading it. - for (label, divisor) in [("4:2:2", 2usize), ("4:4:4", 1)] { - let p = Picture { - width: 64, - height: 64, - y: vec![0; 64 * 64], - u: vec![0; 64 * 64 / divisor], - v: vec![0; 64 * 64 / divisor], - }; - assert!( - p.check().is_err(), - "{NAME}: Picture::check accepted a {label}-shaped picture -- if the encoder can be \ - fed one, palette_uv_side's square map is wrong by construction" - ); - } - - // ---- arm 3: the site really fires --------------------------------- - // Without this, arms 1 and 2 are arithmetic and a source scan over a - // function no encode reaches (class `gate-blind-to-feature`). - // - // The fire count is the DECODER's thread-local one, not the writer's - // process-global `tile::take_palette_uv_hits`: that one is a - // swap-to-zero, so a parallel sibling test's encode steals this test's - // count (measured: it read `[0; 9]` under `cargo test palette`, and - // passed alone). Round-tripping the stream instead also proves the - // stronger half -- the reader took the map at the extent the WRITER - // sized, which is what makes the square value right rather than merely - // unchallenged. - let _knobs = crate::speed::knob_read(); - let fctx = &crate::decode::FrameCtx::for_encoder(); - let before = crate::decode::palette_uv_hits(); - let encoded = encode_key_frame_with_ctx(&screen_card(192, 96), 100, 0.5, fctx).unwrap(); - let decoded = crate::stream::decode_stream(&encoded.stream) - .unwrap_or_else(|e| panic!("{NAME}: our own stream refused: {e}")); - let fired = crate::decode::palette_uv_hits() - before; - assert!( - fired > 0, - "{NAME}: no block took a chroma palette -- palette_uv_side was never exercised, so \ - this gate measures nothing" - ); - assert_eq!( - decoded[0].u, encoded.reconstruction.u, - "{NAME}: the decoder did not read the chroma map at the extent the writer sized it" - ); - assert_eq!( - decoded[0].v, encoded.reconstruction.v, - "{NAME}: the decoder did not read the chroma map at the extent the writer sized it" - ); - eprintln!("{NAME}: {fired} chroma palette block(s) round-tripped"); - } - /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card /// sets `allow_intrabc` (so every in-loop filter is off), blocks really /// take a block vector (fire count + DV histogram, class diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index eb83793a..7098cfa9 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -55,8 +55,6 @@ pub mod sequence; pub mod speed; pub mod stream; mod superres; -#[cfg(test)] -mod test_source; pub mod tile; mod timeline; pub mod transform; diff --git a/crates/ec-av1/src/test_source.rs b/crates/ec-av1/src/test_source.rs deleted file mode 100644 index a969374e..00000000 --- a/crates/ec-av1/src/test_source.rs +++ /dev/null @@ -1,103 +0,0 @@ -#![cfg(test)] -//! Test-only access to a crate module's SOURCE TEXT. -//! -//! The source-scanning gates used to `include_str!("decode.rs")`, which names -//! one file. Once a module is split into a directory (`decode/mod.rs` plus its -//! children) that include stops compiling, and every gate pinning it goes stale -//! on the next move. These helpers read the module's files at test run time -//! instead: `src/.rs` when it exists, then every `*.rs` under -//! `src//` recursively, concatenated in sorted path order. A file added to -//! that directory is therefore scanned without touching any gate. -//! -//! [`module_production_source`] is the same text minus the test-only files -//! (`tests.rs` and `*_tests.rs`), for gates that must not count their own test -//! fixtures. An inline `mod tests { .. }` in a single file is not removed by -//! that function; a gate that needs the production prefix cuts it itself. - -use std::collections::BTreeMap; -use std::path::{Path, PathBuf}; -use std::sync::{Mutex, OnceLock}; - -type Cache = Mutex>; -static CACHE: OnceLock = OnceLock::new(); - -/// The whole source text of module `name`: `src/.rs` and every `*.rs` -/// under `src//`, in sorted path order. -pub fn module_source(name: &str) -> &'static str { - cached(name, false) -} - -/// [`module_source`] without the test-only files (`tests.rs`, `*_tests.rs`). -pub fn module_production_source(name: &str) -> &'static str { - cached(name, true) -} - -/// Each module is read once per test process. The text is leaked, which is -/// bounded by the handful of modules the gates name and is test-only. -fn cached(name: &str, production_only: bool) -> &'static str { - let cache = CACHE.get_or_init(|| Mutex::new(BTreeMap::new())); - let mut map = cache.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); - let key = (name.to_string(), production_only); - if let Some(&text) = map.get(&key) { - return text; - } - let text: &'static str = Box::leak(read_module(name, production_only).into_boxed_str()); - map.insert(key, text); - text -} - -fn read_module(name: &str, production_only: bool) -> String { - assert!( - !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'), - "{name:?} is not a module name" - ); - let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); - let mut files: Vec = Vec::new(); - let single = src.join(format!("{name}.rs")); - if single.is_file() { - files.push(single); - } - let dir = src.join(name); - if dir.is_dir() { - collect_rs(&dir, &mut files); - } - assert!( - !files.is_empty(), - "module {name} has neither src/{name}.rs nor src/{name}/" - ); - files.sort(); - // A split moved some top-level fns to `pub(super) fn` so sibling modules can call them. The - // scanners match header text (`\nfn name(`); normalize only that visibility so they see the - // same headers as before the split. Bodies and assertions are unchanged. - let mut text = String::new(); - for path in files { - if production_only && is_test_file(&path) { - continue; - } - let body = std::fs::read_to_string(&path) - .unwrap_or_else(|e| panic!("reading {}: {e}", path.display())); - text.push_str(&body); - if !body.ends_with('\n') { - text.push('\n'); - } - } - text.replace("\npub(super) fn ", "\nfn ").replace("\n pub(super) fn ", "\n fn ") -} - -fn collect_rs(dir: &Path, out: &mut Vec) { - let entries = - std::fs::read_dir(dir).unwrap_or_else(|e| panic!("reading {}: {e}", dir.display())); - for entry in entries { - let path = entry.expect("reading a directory entry").path(); - if path.is_dir() { - collect_rs(&path, out); - } else if path.extension().is_some_and(|ext| ext == "rs") { - out.push(path); - } - } -} - -fn is_test_file(path: &Path) -> bool { - let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or(""); - stem == "tests" || stem.ends_with("_tests") -}