forge
Explore
Log in

Don't you dare go Hollow

lane-av1refusalspan: bound a proving gate's body by its own closing brace

Browse files at this commit

cc885c2eb5c7809e163e0112bdc640940d21bb3dAhmet Kaan GümüşParent: 90e4e6e
The refusal inventory's anchor check needed a gate's own text, and the
window rule it used ("the body ends at the next `fn` at the same
indentation, or at end of file") is not a function boundary on this tree:
a top-level `#[test] fn` in decode.rs has its next same-indent `fn` tens
of thousands of lines away, so the window reached end of file constantly
and one row's 27,427-line "body" was satisfied by the CHROMA sibling's
string seven lines down.

`gate_body` now ends the slice at the brace that closes the gate's body,
found by a scan that walks Rust rather than lines: string, raw-string,
byte-string, char and lifetime forms, line comments and nestable block
comments are skipped, so a brace inside one cannot move the boundary.
Every failure mode is a FAILURE -- no definition, a definition that is
never closed, an ambiguous name, or a body that still carries another
same-indent `fn` -- and none of them widens the window.

Re-measured over real bodies: 26 rows quote the whole refusal string, 7
quote its leading clause, 0 match neither. Nine rows the previous
measurement counted as anchored were not (their anchor was neighbour
text), so the nine gates now name the refusal they prove and pin its
guard site through `pins_refusal`.

New tests: the boundary's own non-vacuity (neighbour isolation, a brace in
a literal, the last function in a file, an unclosed body), and the same
boundary exercised over all three real sources.
crates/ec-av1/src/decode.rsmodified+69 -10
@@ -9903,9 +9903,7 @@ impl Neighbours {
9903 fill_span(&mut self.uv_owner, row * stride + mi_c, n, owner);9903 fill_span(&mut self.uv_owner, row * stride + mi_c, n, owner);
9904 }9904 }
9905 if crate::envflags::env_flag!("EC_LEFTSSY") {9905 if crate::envflags::env_flag!("EC_LEFTSSY") {
9906- eprintln!(9906+ eprintln!("EC_LEAF mi=({mi_r},{mi_c}) wh=({mi_w},{mi_h}) uv_mode={uv_mode}");
9907- "EC_LEAF mi=({mi_r},{mi_c}) wh=({mi_w},{mi_h}) uv_mode={uv_mode}"
9908- );
9909 }9907 }
9910 }9908 }
9911 9909
@@ -12547,6 +12545,17 @@ fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> {
12547 /// stream can present.12545 /// stream can present.
12548 #[test]12546 #[test]
12549 fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() {12547 fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() {
12548+ // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it
12549+ // names that string exactly (placeholders included) and pins its guard
12550+ // site. The enumeration below establishes the shape domain; on its own it
12551+ // never said WHICH string the domain was about, so under a real function
12552+ // boundary -- rather than a window that ran into the next test -- the row
12553+ // read as unanchored.
12554+ 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)";
12555+ assert!(
12556+ include_str!("decode.rs").contains(REFUSAL),
12557+ "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
12558+ );
12550 let mut checked = 0;12559 let mut checked = 0;
12551 for &(side, w, h) in &INTER_BLOCK_SHAPES {12560 for &(side, w, h) in &INTER_BLOCK_SHAPES {
12552 if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 {12561 if (w, h) == (side, side) || w.min(h) < 8 || w.max(h) > 64 {
@@ -12639,6 +12648,13 @@ const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [
12639 /// clause rejects before the lookup.12648 /// clause rejects before the lookup.
12640 #[test]12649 #[test]
12641 fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() {12650 fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() {
12651+ // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it
12652+ // names it and pins its guard site.
12653+ const REFUSAL: &str = "a motion_mode symbol for a block shape with no CDF row here";
12654+ assert!(
12655+ crate::refusal_inventory::pins_refusal(include_str!("decode.rs"), REFUSAL),
12656+ "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
12657+ );
12642 let mut rows = std::collections::BTreeSet::new();12658 let mut rows = std::collections::BTreeSet::new();
12643 let mut excluded = 0;12659 let mut excluded = 0;
12644 for (w, h) in BLOCK_SIZES_ALL_WH {12660 for (w, h) in BLOCK_SIZES_ALL_WH {
@@ -13910,8 +13926,10 @@ fn decode_intrabc_rect(
13910 // its own mi row/column on a 4:4:4 lossless frame, and13926 // its own mi row/column on a 4:4:4 lossless frame, and
13911 // the whole block's per-unit states are stamped over13927 // the whole block's per-unit states are stamped over
13912 // cells that belong to other blocks (or to nothing).13928 // cells that belong to other blocks (or to nothing).
13913- (mi_r + ur * ((4 << ss_y(fctx)) / MI),13929+ (
13914- mi_c + uc * ((4 << ss_x(fctx)) / MI)),13930+ mi_r + ur * ((4 << ss_y(fctx)) / MI),
13931+ mi_c + uc * ((4 << ss_x(fctx)) / MI),
13932+ ),
13915 4 << ss_x(fctx),13933 4 << ss_x(fctx),
13916 4 << ss_y(fctx),13934 4 << ss_y(fctx),
13917 plane_idx,13935 plane_idx,
@@ -27948,6 +27966,18 @@ fn sub_tx_size_map_matches_libaom() {
27948 /// case the refusal is guarded by.27966 /// case the refusal is guarded by.
27949 #[test]27967 #[test]
27950 fn a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered() {27968 fn a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered() {
27969+ // lane-av1refusalspan: this gate is the PROOF for both var-tx refusals, so
27970+ // it names both and pins both guard sites. The walk below proves the leaf
27971+ // domain; it never said which two strings that domain was about.
27972+ for refusal in [
27973+ "an inter var-tx tree with a leaf transform larger than 32x32",
27974+ "an inter var-tx tree with a leaf transform larger than 64x64",
27975+ ] {
27976+ assert!(
27977+ crate::refusal_inventory::pins_refusal(include_str!("decode.rs"), refusal),
27978+ "this gate proves {refusal:?}, but that string is no longer in decode.rs"
27979+ );
27980+ }
27951 // Every leaf `read_var_tx_size` can reach from `entry`, as (depth, w, h).27981 // Every leaf `read_var_tx_size` can reach from `entry`, as (depth, w, h).
27952 fn reachable(entry: (usize, usize), depth: usize, out: &mut Vec<(usize, usize, usize)>) {27982 fn reachable(entry: (usize, usize), depth: usize, out: &mut Vec<(usize, usize, usize)>) {
27953 out.push((depth, entry.0, entry.1));27983 out.push((depth, entry.0, entry.1));
@@ -28553,6 +28583,21 @@ fn rect_scan(w: usize, h: usize) -> Result<&'static [u16]> {
28553 /// loop, which is why they are skipped below.28583 /// loop, which is why they are skipped below.
28554 #[test]28584 #[test]
28555 fn every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan() {28585 fn every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan() {
28586+ // lane-av1refusalspan: this gate is the PROOF for THREE refusals, so it
28587+ // names all three and pins all three guard sites. The census below proves
28588+ // the shape domain and, on its own, named NONE of the strings that domain
28589+ // was about -- under a real function boundary rather than a window that
28590+ // ran into the next test, all three rows read as unanchored.
28591+ for refusal in [
28592+ "a rectangular inter luma transform unit whose shape has no coefficient table set here",
28593+ "a rectangular inter chroma transform unit whose shape has no coefficient table set here",
28594+ "a rectangular transform unit whose shape has no coefficient scan table here",
28595+ ] {
28596+ assert!(
28597+ include_str!("decode.rs").contains(refusal),
28598+ "this gate proves {refusal:?}, but that string is no longer in decode.rs"
28599+ );
28600+ }
28556 let fctx = &crate::decode::FrameCtx::new();28601 let fctx = &crate::decode::FrameCtx::new();
28557 let corner_scan = |w: usize, h: usize| {28602 let corner_scan = |w: usize, h: usize| {
28558 let (cw, ch) = (w.min(32), h.min(32));28603 let (cw, ch) = (w.min(32), h.min(32));
@@ -28637,9 +28682,8 @@ fn read_block_tx_size_rect(
28637 let full_h_mi = bh / MI;28682 let full_h_mi = bh / MI;
28638 if max_w_mi != full_w_mi || max_h_mi != full_h_mi {28683 if max_w_mi != full_w_mi || max_h_mi != full_h_mi {
28639 LOSSLESS_EDGE_CLIPPED.with(|c| c.set(c.get() + 1));28684 LOSSLESS_EDGE_CLIPPED.with(|c| c.set(c.get() + 1));
28640- LOSSLESS_EDGE_CLIP_UNITS.with(|c| {28685+ LOSSLESS_EDGE_CLIP_UNITS
28641- c.set(c.get() + (full_w_mi * full_h_mi - max_w_mi * max_h_mi))28686+ .with(|c| c.set(c.get() + (full_w_mi * full_h_mi - max_w_mi * max_h_mi)));
28642- });
28643 }28687 }
28644 let mut leaves = Vec::with_capacity(max_w_mi * max_h_mi);28688 let mut leaves = Vec::with_capacity(max_w_mi * max_h_mi);
28645 for row in 0..max_h_mi {28689 for row in 0..max_h_mi {
@@ -54496,6 +54540,16 @@ mod tests {
54496 #[test]54540 #[test]
54497 fn every_inter_record_publishes_an_obmc_readable_filter() {54541 fn every_inter_record_publishes_an_obmc_readable_filter() {
54498 let src = include_str!("decode.rs");54542 let src = include_str!("decode.rs");
54543+ // lane-av1refusalspan: this gate is the PROOF for the refusal below, so
54544+ // it names it and pins its guard site. The sibling test
54545+ // `an_obmc_neighbour_with_no_recorded_filter_refuses_instead_of_panicking`
54546+ // carries the same string 27k lines away in this file -- exactly the
54547+ // reach a window that is not a function boundary used to have.
54548+ const REFUSAL: &str = "an OBMC neighbour whose switchable interp filter was never recorded";
54549+ assert!(
54550+ crate::refusal_inventory::pins_refusal(&src, REFUSAL),
54551+ "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
54552+ );
54499 let mut calls = 0usize;54553 let mut calls = 0usize;
54500 for (start, _) in src.match_indices("record_inter_rect_mi(") {54554 for (start, _) in src.match_indices("record_inter_rect_mi(") {
54501 // Skip the definition and the wrapper's own forwarding call.54555 // Skip the definition and the wrapper's own forwarding call.
@@ -54575,8 +54629,13 @@ mod tests {
54575 /// open half of this proof.54629 /// open half of this proof.
54576 #[test]54630 #[test]
54577 fn a_selected_reference_with_an_empty_ref_frame_idx_slot_refuses_by_name() {54631 fn a_selected_reference_with_an_empty_ref_frame_idx_slot_refuses_by_name() {
54578- const REFUSAL: &str =54632+ // lane-av1refusalspan: the FULL refusal, not a prefix of it. This gate
54579- "a reference frame selected with no picture at this frame's own ref_frame_idx slot";54633+ // is the proof for the row in `refusal_inventory`, whose anchor is the
54634+ // whole string (it carries no `(` and no `:`), and this const is what
54635+ // that anchor reads. Shortened to `...own ref_frame_idx slot` it
54636+ // stopped being a pin on the guard's text.
54637+ const REFUSAL: &str = "a reference frame selected with no picture at this frame's own \
54638+ ref_frame_idx slot for it";
54580 let pic = Picture {54639 let pic = Picture {
54581 width: 4,54640 width: 4,
54582 height: 4,54641 height: 4,
crates/ec-av1/src/refusal_inventory.rsmodified+466 -16
@@ -627,9 +627,55 @@ const PROVEN: &[(&str, &str)] = &[
627 #[cfg(test)]627 #[cfg(test)]
628 const GATES_THAT_SKIP_ON_A_DECODE_ERROR: &[&str] = &[];628 const GATES_THAT_SKIP_ON_A_DECODE_ERROR: &[&str] = &[];
629 629
630+/// Source text with Rust's line continuations dropped and every whitespace run
631+/// collapsed to one space -- the form rustc gives a multi-line literal -- so a
632+/// refusal written across three source lines is still findable in a body, and
633+/// a gate's quote of it still matches the guard's spelling.
634+#[cfg(test)]
635+fn squash_source(s: &str) -> String {
636+ let mut out = String::with_capacity(s.len());
637+ let mut pending_space = false;
638+ for (i, c) in s.char_indices() {
639+ if c == '\\' {
640+ let rest = &s[i + 1..];
641+ if rest.contains('\n')
642+ && rest
643+ .chars()
644+ .take_while(|c| *c != '\n')
645+ .all(|c| c == ' ' || c == '\t' || c == '\r')
646+ {
647+ continue;
648+ }
649+ }
650+ if c.is_whitespace() {
651+ pending_space = true;
652+ continue;
653+ }
654+ if pending_space && !out.is_empty() {
655+ out.push(' ');
656+ }
657+ pending_space = false;
658+ out.push(c);
659+ }
660+ out
661+}
662+
663+/// Does `src` carry `refusal`?
664+///
665+/// Lane-av1refusalspan: a proving gate quotes the refusal it proves, and this
666+/// is how it pins that quote to the guard that still carries the string. Both
667+/// sides are squashed, so a literal written over two lines with a `\`
668+/// continuation still matches.
669+#[cfg(test)]
670+pub(crate) fn pins_refusal(src: &str, refusal: &str) -> bool {
671+ squash_source(src).contains(&squash_source(refusal))
672+}
673+
630 #[cfg(test)]674 #[cfg(test)]
631 mod tests {675 mod tests {
632- use super::{CAPABILITY_CLAIMS, GATES_THAT_SKIP_ON_A_DECODE_ERROR, PROVEN, REFUSALS};676+ use super::{
677+ CAPABILITY_CLAIMS, GATES_THAT_SKIP_ON_A_DECODE_ERROR, PROVEN, REFUSALS, squash_source,
678+ };
633 use std::collections::BTreeSet;679 use std::collections::BTreeSet;
634 680
635 /// Every distinct `unsupported(...)` reason on the decode path.681 /// Every distinct `unsupported(...)` reason on the decode path.
@@ -1134,6 +1180,13 @@ mod tests {
1134 /// comment on `read_golomb`.1180 /// comment on `read_golomb`.
1135 #[test]1181 #[test]
1136 fn read_golomb_reads_every_value_a_conformant_stream_can_carry() {1182 fn read_golomb_reads_every_value_a_conformant_stream_can_carry() {
1183+ // lane-av1refusalspan: this gate is the PROOF for the refusal below, so
1184+ // it names it and pins its guard site.
1185+ const REFUSAL: &str = "a Golomb tail longer than this decoder reads";
1186+ assert!(
1187+ super::pins_refusal(include_str!("decode.rs"), REFUSAL),
1188+ "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
1189+ );
1137 let roundtrip = |value: u32| -> ec_core::Result<u32> {1190 let roundtrip = |value: u32| -> ec_core::Result<u32> {
1138 let mut enc = crate::msac::SymbolEncoder::new();1191 let mut enc = crate::msac::SymbolEncoder::new();
1139 crate::tile::write_golomb(&mut enc, value);1192 crate::tile::write_golomb(&mut enc, value);
@@ -1377,6 +1430,17 @@ mod tests {
1377 #[test]1430 #[test]
1378 fn every_rect_strip_shape_the_split_path_codes_has_a_luma_and_chroma_table() {1431 fn every_rect_strip_shape_the_split_path_codes_has_a_luma_and_chroma_table() {
1379 let src = include_str!("decode.rs");1432 let src = include_str!("decode.rs");
1433+ // lane-av1refusalspan: this gate is the PROOF for both refusals below,
1434+ // so it names both and pins both guard sites.
1435+ for refusal in [
1436+ "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
1437+ "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma coefficient tables for that shape here)",
1438+ ] {
1439+ assert!(
1440+ super::pins_refusal(&src, refusal),
1441+ "this gate proves {refusal:?}, but that string is no longer in decode.rs"
1442+ );
1443+ }
1380 1444
1381 // (1) The caller set. Each call's enclosing function is the last1445 // (1) The caller set. Each call's enclosing function is the last
1382 // top-level `fn` before it.1446 // top-level `fn` before it.
@@ -1937,6 +2001,14 @@ mod tests {
1937 /// [`no_block_footprint_with_a_128_pixel_side_can_carry_palette_syntax`].2001 /// [`no_block_footprint_with_a_128_pixel_side_can_carry_palette_syntax`].
1938 #[test]2002 #[test]
1939 fn no_128_root_half_reads_a_cfl_filter_intra_or_palette_symbol() {2003 fn no_128_root_half_reads_a_cfl_filter_intra_or_palette_symbol() {
2004+ // lane-av1refusalspan: this gate is the PROOF for the refusal below, so
2005+ // it names it (the full leading clause, which is the whole clause the
2006+ // inventory row's anchor reads) and pins its guard site.
2007+ const REFUSAL: &str = "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block";
2008+ assert!(
2009+ include_str!("decode.rs").contains(REFUSAL),
2010+ "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs"
2011+ );
1940 let src = include_str!("decode.rs");2012 let src = include_str!("decode.rs");
1941 // The 128-root call site's own `cfl` argument, with the comment that2013 // The 128-root call site's own `cfl` argument, with the comment that
1942 // explains it -- the two lines are matched together so that reordering2014 // explains it -- the two lines are matched together so that reordering
@@ -2122,34 +2194,412 @@ mod tests {
2122 );2194 );
2123 }2195 }
2124 2196
2125- /// Every entry of [`PROVEN`] must still name a live refusal and a test2197+ /// Lane-av1refusalspan: the files a proving gate may live in.
2126- /// that exists, and the count it prints is the inventory's numerator.2198+ const GATE_SOURCES: [(&str, &str); 3] = [
2199+ ("decode.rs", include_str!("decode.rs")),
2200+ ("stream.rs", include_str!("stream.rs")),
2201+ ("refusal_inventory.rs", include_str!("refusal_inventory.rs")),
2202+ ];
2203+
2204+ /// Lane-av1refusalspan: every offset in `src` of a line that DEFINES
2205+ /// `fn <gate>(` -- and nothing that merely names it.
2206+ ///
2207+ /// "The gate" is a function, so the first thing the anchor needs is the
2208+ /// function's own definition. The window rule this replaced took the first
2209+ /// `fn <gate>(` the file happened to contain, and a comment or a string
2210+ /// produces one. A definition is a line whose text before the keyword is
2211+ /// whitespace and qualifiers only (`pub`, `pub(crate)`, `async`, ...).
2212+ fn gate_definitions(src: &str, gate: &str) -> Vec<usize> {
2213+ src.match_indices(&format!("fn {gate}("))
2214+ .map(|(at, _)| at)
2215+ .filter(|at| {
2216+ let line_start = src[..*at].rfind('\n').map_or(0, |i| i + 1);
2217+ src[line_start..*at].split_whitespace().all(|word| {
2218+ matches!(
2219+ word,
2220+ "pub" | "async" | "const" | "unsafe" | "extern" | "default"
2221+ ) || (word.starts_with("pub(") && word.ends_with(')'))
2222+ })
2223+ })
2224+ .collect()
2225+ }
2226+
2227+ /// The number of leading-whitespace columns on the line holding `at`.
2228+ fn leading_indent(src: &str, at: usize) -> usize {
2229+ let line_start = src[..at].rfind('\n').map_or(0, |i| i + 1);
2230+ let line = &src[line_start..at];
2231+ line.len() - line.trim_start().len()
2232+ }
2233+
2234+ /// The offset of the `"` that closes the string literal opening at `open`.
2235+ fn closing_quote(b: &[u8], open: usize) -> Option<usize> {
2236+ let mut i = open + 1;
2237+ while i < b.len() {
2238+ match b[i] {
2239+ b'\\' => i += 2,
2240+ b'"' => return Some(i),
2241+ _ => i += 1,
2242+ }
2243+ }
2244+ None
2245+ }
2246+
2247+ /// The offsets of the `{` that opens the body of the function defined at
2248+ /// `gate_at` and of the `}` that closes it; `None` when the body is never
2249+ /// closed.
2250+ ///
2251+ /// This walks Rust, not lines. A brace inside a string literal, a raw
2252+ /// string, a byte string, a char literal, a lifetime, a line comment or a
2253+ /// (nestable) block comment is not a brace -- counting one is exactly how a
2254+ /// "bounded" window becomes the rest of the file.
2255+ fn body_braces(src: &str, gate_at: usize) -> Option<(usize, usize)> {
2256+ let b = src.as_bytes();
2257+ let mut i = gate_at;
2258+ let mut depth = 0usize;
2259+ let mut open = None;
2260+ while i < b.len() {
2261+ match b[i] {
2262+ b'/' if b.get(i + 1) == Some(&b'/') => {
2263+ i = src[i..].find('\n').map_or(b.len(), |n| i + n + 1);
2264+ continue;
2265+ }
2266+ b'/' if b.get(i + 1) == Some(&b'*') => {
2267+ let mut nesting = 1usize;
2268+ i += 2;
2269+ while i < b.len() && nesting > 0 {
2270+ if b[i] == b'/' && b.get(i + 1) == Some(&b'*') {
2271+ nesting += 1;
2272+ i += 2;
2273+ } else if b[i] == b'*' && b.get(i + 1) == Some(&b'/') {
2274+ nesting -= 1;
2275+ i += 2;
2276+ } else {
2277+ i += 1;
2278+ }
2279+ }
2280+ continue;
2281+ }
2282+ b'r' if b.get(i + 1) == Some(&b'"') || b.get(i + 1) == Some(&b'#') => {
2283+ let mut j = i + 1;
2284+ while b.get(j) == Some(&b'#') {
2285+ j += 1;
2286+ }
2287+ if b.get(j) != Some(&b'"') {
2288+ i += 1;
2289+ continue;
2290+ }
2291+ let hashes = j - i - 1;
2292+ let mut end = None;
2293+ for k in (j + 1..b.len()).chain(std::iter::once(b.len() - 1)) {
2294+ if b[k] == b'"' && b[k + 1..].iter().take(hashes).all(|c| *c == b'#') {
2295+ end = Some(k);
2296+ break;
2297+ }
2298+ }
2299+ i = end? + 1;
2300+ continue;
2301+ }
2302+ b'"' => {
2303+ i = closing_quote(b, i)? + 1;
2304+ continue;
2305+ }
2306+ b'b' if b.get(i + 1) == Some(&b'"') => {
2307+ i = closing_quote(b, i + 1)? + 1;
2308+ continue;
2309+ }
2310+ // A lifetime (`'a`, `'static`) is not a char literal: it has no
2311+ // closing quote on its line, and reading one as a literal would
2312+ // hide real code from the scan.
2313+ b'\'' => {
2314+ let rest = &b[i + 1..];
2315+ let from = if rest.first() == Some(&b'\\') { 2 } else { 0 };
2316+ match rest[from..]
2317+ .iter()
2318+ .take_while(|c| **c != b'\n')
2319+ .position(|c| *c == b'\'')
2320+ {
2321+ Some(k) => i += from + k + 2,
2322+ None => i += 1,
2323+ }
2324+ continue;
2325+ }
2326+ b'{' => {
2327+ open = open.or(Some(i));
2328+ depth += 1;
2329+ }
2330+ b'}' => {
2331+ depth -= 1;
2332+ if depth == 0 {
2333+ return open.map(|o| (o, i));
2334+ }
2335+ }
2336+ _ => {}
2337+ }
2338+ i += 1;
2339+ }
2340+ None
2341+ }
2342+
2343+ /// The text of the body of the function defined at `gate_at`, or `None`
2344+ /// when that body is never closed.
2345+ fn function_body<'a>(src: &'a str, gate_at: usize) -> Option<&'a str> {
2346+ let (open, close) = body_braces(src, gate_at)?;
2347+ src.get(open..=close)
2348+ }
2349+
2350+ /// The first line of `body` that defines another function at `indent`
2351+ /// columns of leading whitespace -- the first sign that a boundary
2352+ /// over-reached into a neighbour.
2353+ fn sibling_fn(body: &str, indent: usize) -> Option<&str> {
2354+ body.lines().skip(1).find(|line| {
2355+ let lead = line.len() - line.trim_start().len();
2356+ lead == indent && {
2357+ let t = line.trim_start();
2358+ t.starts_with("fn ") || t.starts_with("pub fn ")
2359+ }
2360+ })
2361+ }
2362+
2363+ /// Lane-av1refusalspan: the proving gate's OWN body -- the text from the
2364+ /// `{` that opens it to the `}` that closes it.
2365+ ///
2366+ /// Every failure mode here is a FAILURE (`Err`), never a wider window. The
2367+ /// rule this replaced -- "the body ends at the next `fn` at the same
2368+ /// indentation, or at end of file" -- ended at end of file constantly (a
2369+ /// top-level `#[test] fn` in `decode.rs` has its next same-indent `fn`
2370+ /// tens of thousands of lines away), and one row's 27,427-line "body" was
2371+ /// satisfied by the CHROMA sibling's string seven lines down.
2372+ fn gate_body(gate: &str) -> Result<&'static str, String> {
2373+ let mut hits: Vec<(&str, usize, &'static str)> = Vec::new();
2374+ for (file, src) in GATE_SOURCES {
2375+ for at in gate_definitions(src, gate) {
2376+ hits.push((file, at, src));
2377+ }
2378+ }
2379+ match hits.as_slice() {
2380+ [] => Err(format!(
2381+ "{gate} is not defined in decode.rs, stream.rs or refusal_inventory.rs"
2382+ )),
2383+ [only] => {
2384+ let (file, at, src) = *only;
2385+ let body = function_body(src, at).ok_or_else(|| {
2386+ format!(
2387+ "{file}:{at}: the body of {gate}() is never closed -- a missing \
2388+ boundary is a FAILURE, not a window that runs on into the next \
2389+ function"
2390+ )
2391+ })?;
2392+ if let Some(leak) = sibling_fn(body, leading_indent(src, at)) {
2393+ return Err(format!(
2394+ "{file}:{at}: the extracted body of {gate}() still contains {} -- the \
2395+ boundary over-reached into a neighbour",
2396+ leak.trim()
2397+ ));
2398+ }
2399+ Ok(body)
2400+ }
2401+ many => Err(format!(
2402+ "{gate} is defined {} times ({}), so 'its body' is ambiguous",
2403+ many.len(),
2404+ many.iter()
2405+ .map(|(file, at, _)| format!("{file}:{at}"))
2406+ .collect::<Vec<_>>()
2407+ .join(", ")
2408+ )),
2409+ }
2410+ }
2411+
2412+ /// The refusal's leading clause: what a gate may quote when it does not
2413+ /// quote the whole string -- everything up to the first `(` (the qualifier
2414+ /// that varies per call site), else up to the first `:`, else the whole
2415+ /// string.
2416+ fn leading_clause(reason: &str) -> String {
2417+ let cut = reason
2418+ .find('(')
2419+ .or_else(|| reason.find(':'))
2420+ .unwrap_or(reason.len());
2421+ reason[..cut].trim_end().to_owned()
2422+ }
2423+
2424+ /// Every entry of [`PROVEN`] must still name a live refusal, and the gate
2425+ /// it names must REFERENCE that refusal inside its OWN body.
2426+ ///
2427+ /// Lane-av1refusalspan: the boundary is the gate's closing brace (see
2428+ /// [`gate_body`]); a boundary that cannot be found fails the row.
2127 #[test]2429 #[test]
2128 fn every_proven_refusal_names_a_test_that_exists() {2430 fn every_proven_refusal_names_a_test_that_exists() {
2129 let found = decode_path_refusals();2431 let found = decode_path_refusals();
2130- let sources = [2432+ let mut whole = 0usize;
2131- include_str!("stream.rs"),2433+ let mut clause = 0usize;
2132- include_str!("decode.rs"),2434+ let mut neither: Vec<&str> = Vec::new();
2133- include_str!("refusal_inventory.rs"),2435+ let mut unanchored: Vec<String> = Vec::new();
2134- ];2436+ let mut unbounded: Vec<String> = Vec::new();
2135 for (reason, gate) in PROVEN {2437 for (reason, gate) in PROVEN {
2136 assert!(2438 assert!(
2137 found.contains(*reason),2439 found.contains(*reason),
2138- "{reason:?} is listed as proven but is no longer a decode-path refusal -- drop it from PROVEN (the capability landed) or fix the string"2440+ "{reason:?} is listed as proven but is no longer a decode-path refusal -- \
2139- );2441+ drop it from PROVEN (the capability landed) or fix the string"
2140- assert!(
2141- sources
2142- .iter()
2143- .any(|src| src.contains(&format!("fn {gate}("))),
2144- "{reason:?} names the proving test {gate}, which exists in neither stream.rs \
2145- nor decode.rs"
2146 );2442 );
2443+ // A missing boundary is a FAILURE for the row, never a wider window.
2444+ let body = match gate_body(gate) {
2445+ Ok(body) => body,
2446+ Err(why) => {
2447+ unbounded.push(format!("{reason:?} names {gate}: {why}"));
2448+ continue;
2449+ }
2450+ };
2451+ let flat = squash_source(body);
2452+ if flat.contains(&squash_source(reason)) {
2453+ whole += 1;
2454+ } else if flat.contains(&squash_source(&leading_clause(reason))) {
2455+ clause += 1;
2456+ } else {
2457+ neither.push(reason);
2458+ unanchored.push(format!("{reason:?} names {gate}"));
2459+ }
2147 }2460 }
2461+ // The anchor-strength line, measured over BODIES. The window rule this
2462+ // replaced made these numbers a distribution over "whatever the window
2463+ // happened to reach", which is a different question.
2464+ eprintln!(
2465+ "anchor strength: {whole} rows quote the WHOLE refusal string, {clause} quote its \
2466+ LEADING CLAUSE, {} match neither: {neither:?}",
2467+ PROVEN.len() - whole - clause
2468+ );
2148 eprintln!(2469 eprintln!(
2149 "refusal inventory: {} refusals + {} capability claims, {} proven",2470 "refusal inventory: {} refusals + {} capability claims, {} proven",
2150 REFUSALS.len(),2471 REFUSALS.len(),
2151 CAPABILITY_CLAIMS.len(),2472 CAPABILITY_CLAIMS.len(),
2152 PROVEN.len()2473 PROVEN.len()
2153 );2474 );
2475+ assert!(
2476+ unbounded.is_empty(),
2477+ "these rows name a gate whose body could not be bounded, so nothing was proved \
2478+ about them -- a missing boundary is a failure, not a window that runs on:\n\
2479+ {unbounded:#?}\n\
2480+ The boundary is the gate's own closing brace. If the gate really is there, the \
2481+ finder is wrong: fix the finder, never the verdict."
2482+ );
2483+ assert!(
2484+ unanchored.is_empty(),
2485+ "these rows name a gate that never references the refusal inside its OWN body -- a \
2486+ test that does not use the string it is said to prove is not a proof:\n\
2487+ {unanchored:#?}\n\
2488+ Name a gate that quotes the refusal (or its leading clause), or write one."
2489+ );
2490+ }
2491+
2492+ /// Lane-av1refusalspan, non-vacuity of the BOUNDARY (not of the anchor):
2493+ /// a neighbour's function must be unreachable from a gate's body, and a
2494+ /// body that is not closed must fail rather than run on.
2495+ #[test]
2496+ fn a_gate_body_is_bounded_by_its_own_closing_brace() {
2497+ let marker = "a rectangular chroma transform whose size has no coefficient table";
2498+ let src = format!(
2499+ "fn this_gate() {{\n let _ = 1;\n}}\n\nfn next_gate() {{\n let _ = \"{marker}\";\n}}\n\nfn tail() {{}}\n"
2500+ );
2501+ let this = gate_body_in(&src, "this_gate").expect("the gate has a boundary");
2502+ assert!(this.contains("let _ = 1;"), "own text: {this:?}");
2503+ assert!(
2504+ !this.contains(marker),
2505+ "leaked into the neighbour: {this:?}"
2506+ );
2507+ let next = gate_body_in(&src, "next_gate").expect("the neighbour has a boundary");
2508+ assert!(next.contains(marker));
2509+ assert!(!next.contains("let _ = 1;"));
2510+ // The last function in a file has no following `fn` to stop at: the
2511+ // boundary must still close, exactly on its own brace.
2512+ assert_eq!(gate_body_in(&src, "tail").as_deref(), Ok("{}"));
2513+ // A brace inside a string or a char literal is not a brace. If the scan
2514+ // counted one, this body would run past its own `}` into `next_gate`
2515+ // -- the over-reach the `sibling_fn` invariant exists to catch, and the
2516+ // failure mode that made the old window 27,427 lines long.
2517+ let with_braces_in_literals = format!(
2518+ "fn this_gate() {{\n let _ = \"{{\";\n let _ = '}}';\n // {{\n /* }} */\n}}\n\nfn next_gate() {{\n let _ = \"{marker}\";\n}}\n"
2519+ );
2520+ let bounded = gate_body_in(&with_braces_in_literals, "this_gate");
2521+ assert!(
2522+ bounded.as_deref().is_ok_and(|b| !b.contains(marker)),
2523+ "a brace in a literal moved the boundary: {bounded:?}"
2524+ );
2525+ // A body whose closing brace is missing (a half-finished edit) is a
2526+ // FAILURE. The rule it replaced sliced to end of file and carried on.
2527+ let truncated =
2528+ format!("fn this_gate() {{\n let _ = 1;\n\nfn next_gate() {{\n let _ = 2;\n}}\n");
2529+ assert!(gate_body_in(&truncated, "this_gate").is_err());
2530+ }
2531+
2532+ /// Lane-av1refusalspan: the boundary is load-bearing on the REAL sources,
2533+ /// not only on the synthetic pair above -- every named gate resolves to
2534+ /// exactly one function whose body holds no other function, and the last
2535+ /// function in each of the three files terminates correctly.
2536+ #[test]
2537+ fn every_named_gate_body_is_bounded_in_these_files() {
2538+ let mut resolved = 0usize;
2539+ for (reason, gate) in PROVEN {
2540+ let body =
2541+ gate_body(gate).unwrap_or_else(|why| panic!("{reason:?} names {gate}: {why}"));
2542+ assert!(
2543+ body.ends_with('}'),
2544+ "{gate}'s body does not end on its closing brace"
2545+ );
2546+ resolved += 1;
2547+ }
2548+ assert_eq!(resolved, PROVEN.len());
2549+ for (file, src) in GATE_SOURCES {
2550+ let last = last_fn_name(src).unwrap_or_else(|| panic!("{file} has no function"));
2551+ let at = gate_definitions(src, &last)
2552+ .last()
2553+ .copied()
2554+ .unwrap_or_else(|| panic!("{file}: no definition of {last}"));
2555+ let body = function_body(src, at)
2556+ .unwrap_or_else(|| panic!("{file}: the last function {last}() has no boundary"));
2557+ assert!(sibling_fn(body, leading_indent(src, at)).is_none());
2558+ }
2559+ }
2560+
2561+ /// Lane-av1refusalspan: the invariant that catches a boundary that
2562+ /// over-reaches. Tested on its own text, so it cannot be satisfied by the
2563+ /// scanner happening to be right on the current sources.
2564+ #[test]
2565+ fn a_body_carrying_another_function_is_refused() {
2566+ assert!(sibling_fn("{\n let _ = 1;\n}\n\nfn neighbour() {\n}\n", 0).is_some());
2567+ assert!(sibling_fn("{\n let _ = 1;\n}\n", 0).is_none());
2568+ // A nested `fn` is deeper-indented and does belong to the body.
2569+ assert!(sibling_fn("{\n fn helper() {}\n}\n", 0).is_none());
2570+ }
2571+
2572+ /// Lane-av1refusalspan: `gate_body` over ONE file, so the boundary tests
2573+ /// above can drive it with text that cannot occur in this crate.
2574+ fn gate_body_in<'a>(src: &'a str, gate: &str) -> Result<&'a str, String> {
2575+ let defs = gate_definitions(src, gate);
2576+ match defs.as_slice() {
2577+ [] => Err(format!("{gate} is not defined here")),
2578+ [at] => {
2579+ let body = function_body(src, *at).ok_or_else(|| {
2580+ format!("the body of {gate}() is never closed -- boundary missing")
2581+ })?;
2582+ if let Some(leak) = sibling_fn(body, leading_indent(src, *at)) {
2583+ return Err(format!("boundary over-reached into {}", leak.trim()));
2584+ }
2585+ Ok(body)
2586+ }
2587+ many => Err(format!("{gate} is defined {} times", many.len())),
2588+ }
2589+ }
2590+
2591+ /// The name of the last function defined in `src` -- the boundary rule's
2592+ /// hard case, since nothing follows it to stop at.
2593+ fn last_fn_name(src: &str) -> Option<String> {
2594+ src.lines()
2595+ .filter_map(|line| {
2596+ let t = line.trim_start();
2597+ if !(t.starts_with("fn ") || t.starts_with("pub fn ")) {
2598+ return None;
2599+ }
2600+ Some(t.trim_start_matches("pub fn ").trim_start_matches("fn "))
2601+ })
2602+ .filter_map(|head| head.split_once('(').map(|(head, _)| head.trim().to_owned()))
2603+ .last()
2154 }2604 }
2155 }2605 }
crates/ec-av1/src/stream.rsmodified+8 -0
@@ -4417,6 +4417,14 @@ pub(crate) mod tests {
4417 /// re-deriving the formula here.4417 /// re-deriving the formula here.
4418 #[test]4418 #[test]
4419 fn every_frame_size_a_header_can_code_has_a_mode_info_grid() {4419 fn every_frame_size_a_header_can_code_has_a_mode_info_grid() {
4420+ // lane-av1refusalspan: this gate is the PROOF for the refusal below, so
4421+ // it names it and pins its guard site (the decode-path guard in
4422+ // decode.rs carries the same string).
4423+ const REFUSAL: &str = "a frame with no mode-info grid";
4424+ assert!(
4425+ crate::refusal_inventory::pins_refusal(include_str!("stream.rs"), REFUSAL),
4426+ "this gate proves {REFUSAL:?}, but that string is no longer in stream.rs"
4427+ );
4420 let mut sizes: Vec<u32> = (1..=1024).collect();4428 let mut sizes: Vec<u32> = (1..=1024).collect();
4421 sizes.extend([2048, 4095, 4096, 8192, 16384, 32768, 65535, 65536]);4429 sizes.extend([2048, 4095, 4096, 8192, 16384, 32768, 65535, 65536]);
4422 // `mi_cols` is nondecreasing in `frame_width`, so an empty grid can4430 // `mi_cols` is nondecreasing in `frame_width`, so an empty grid can