From cc885c2eb5c7809e163e0112bdc640940d21bb3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 29 Sep 2026 07:09:35 +0300 Subject: [PATCH] lane-av1refusalspan: bound a proving gate's body by its own closing brace 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.rs | 79 +++- crates/ec-av1/src/refusal_inventory.rs | 482 ++++++++++++++++++++++++- crates/ec-av1/src/stream.rs | 8 + 3 files changed, 543 insertions(+), 26 deletions(-) diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 04136772..331551f1 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -9903,9 +9903,7 @@ impl Neighbours { fill_span(&mut self.uv_owner, row * stride + mi_c, n, owner); } if crate::envflags::env_flag!("EC_LEFTSSY") { - eprintln!( - "EC_LEAF mi=({mi_r},{mi_c}) wh=({mi_w},{mi_h}) uv_mode={uv_mode}" - ); + eprintln!("EC_LEAF mi=({mi_r},{mi_c}) wh=({mi_w},{mi_h}) uv_mode={uv_mode}"); } } @@ -12547,6 +12545,17 @@ fn intra_in_inter_size_row(bw: usize, bh: usize) -> Option<(usize, usize)> { /// stream can present. #[test] fn every_intra_in_inter_shape_the_census_lists_has_a_size_group_row() { + // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it + // names that string exactly (placeholders included) and pins its guard + // site. The enumeration below establishes the shape domain; on its own it + // 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!( + include_str!("decode.rs").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 { @@ -12639,6 +12648,13 @@ const BLOCK_SIZES_ALL_WH: [(usize, usize); 22] = [ /// clause rejects before the lookup. #[test] fn every_shape_that_allows_motion_variation_has_a_motion_mode_cdf_row() { + // lane-av1refusalspan: this gate is the PROOF for the refusal below, so it + // names it and pins its guard site. + const REFUSAL: &str = "a motion_mode symbol for a block shape with no CDF row here"; + assert!( + crate::refusal_inventory::pins_refusal(include_str!("decode.rs"), REFUSAL), + "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs" + ); let mut rows = std::collections::BTreeSet::new(); let mut excluded = 0; for (w, h) in BLOCK_SIZES_ALL_WH { @@ -13910,8 +13926,10 @@ fn decode_intrabc_rect( // its own mi row/column on a 4:4:4 lossless frame, and // the whole block's per-unit states are stamped over // cells that belong to other blocks (or to nothing). - (mi_r + ur * ((4 << ss_y(fctx)) / MI), - mi_c + uc * ((4 << ss_x(fctx)) / MI)), + ( + mi_r + ur * ((4 << ss_y(fctx)) / MI), + mi_c + uc * ((4 << ss_x(fctx)) / MI), + ), 4 << ss_x(fctx), 4 << ss_y(fctx), plane_idx, @@ -27948,6 +27966,18 @@ fn sub_tx_size_map_matches_libaom() { /// case the refusal is guarded by. #[test] fn a_var_tx_tree_never_presents_a_leaf_larger_than_the_unit_it_entered() { + // lane-av1refusalspan: this gate is the PROOF for both var-tx refusals, so + // it names both and pins both guard sites. The walk below proves the leaf + // domain; it never said which two strings that domain was about. + for refusal in [ + "an inter var-tx tree with a leaf transform larger than 32x32", + "an inter var-tx tree with a leaf transform larger than 64x64", + ] { + assert!( + crate::refusal_inventory::pins_refusal(include_str!("decode.rs"), refusal), + "this gate proves {refusal:?}, but that string is no longer in decode.rs" + ); + } // Every leaf `read_var_tx_size` can reach from `entry`, as (depth, w, h). fn reachable(entry: (usize, usize), depth: usize, out: &mut Vec<(usize, usize, usize)>) { out.push((depth, entry.0, entry.1)); @@ -28553,6 +28583,21 @@ fn rect_scan(w: usize, h: usize) -> Result<&'static [u16]> { /// loop, which is why they are skipped below. #[test] fn every_rect_transform_shape_the_census_lists_has_a_coefficient_table_and_scan() { + // lane-av1refusalspan: this gate is the PROOF for THREE refusals, so it + // names all three and pins all three guard sites. The census below proves + // 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!( + include_str!("decode.rs").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)); @@ -28637,9 +28682,8 @@ fn read_block_tx_size_rect( let full_h_mi = bh / MI; if max_w_mi != full_w_mi || max_h_mi != full_h_mi { LOSSLESS_EDGE_CLIPPED.with(|c| c.set(c.get() + 1)); - LOSSLESS_EDGE_CLIP_UNITS.with(|c| { - c.set(c.get() + (full_w_mi * full_h_mi - max_w_mi * max_h_mi)) - }); + LOSSLESS_EDGE_CLIP_UNITS + .with(|c| c.set(c.get() + (full_w_mi * full_h_mi - max_w_mi * max_h_mi))); } let mut leaves = Vec::with_capacity(max_w_mi * max_h_mi); for row in 0..max_h_mi { @@ -54496,6 +54540,16 @@ mod tests { #[test] fn every_inter_record_publishes_an_obmc_readable_filter() { let src = include_str!("decode.rs"); + // lane-av1refusalspan: this gate is the PROOF for the refusal below, so + // it names it and pins its guard site. The sibling test + // `an_obmc_neighbour_with_no_recorded_filter_refuses_instead_of_panicking` + // carries the same string 27k lines away in this file -- exactly the + // reach a window that is not a function boundary used to have. + const REFUSAL: &str = "an OBMC neighbour whose switchable interp filter was never recorded"; + assert!( + crate::refusal_inventory::pins_refusal(&src, REFUSAL), + "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs" + ); let mut calls = 0usize; for (start, _) in src.match_indices("record_inter_rect_mi(") { // Skip the definition and the wrapper's own forwarding call. @@ -54575,8 +54629,13 @@ mod tests { /// open half of this proof. #[test] fn a_selected_reference_with_an_empty_ref_frame_idx_slot_refuses_by_name() { - const REFUSAL: &str = - "a reference frame selected with no picture at this frame's own ref_frame_idx slot"; + // lane-av1refusalspan: the FULL refusal, not a prefix of it. This gate + // is the proof for the row in `refusal_inventory`, whose anchor is the + // whole string (it carries no `(` and no `:`), and this const is what + // that anchor reads. Shortened to `...own ref_frame_idx slot` it + // stopped being a pin on the guard's text. + const REFUSAL: &str = "a reference frame selected with no picture at this frame's own \ + ref_frame_idx slot for it"; let pic = Picture { width: 4, height: 4, diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index 0d5a4ed4..66743ce6 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -627,9 +627,55 @@ const PROVEN: &[(&str, &str)] = &[ #[cfg(test)] const GATES_THAT_SKIP_ON_A_DECODE_ERROR: &[&str] = &[]; +/// Source text with Rust's line continuations dropped and every whitespace run +/// collapsed to one space -- the form rustc gives a multi-line literal -- so a +/// refusal written across three source lines is still findable in a body, and +/// a gate's quote of it still matches the guard's spelling. +#[cfg(test)] +fn squash_source(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut pending_space = false; + for (i, c) in s.char_indices() { + if c == '\\' { + let rest = &s[i + 1..]; + if rest.contains('\n') + && rest + .chars() + .take_while(|c| *c != '\n') + .all(|c| c == ' ' || c == '\t' || c == '\r') + { + continue; + } + } + if c.is_whitespace() { + pending_space = true; + continue; + } + if pending_space && !out.is_empty() { + out.push(' '); + } + pending_space = false; + out.push(c); + } + out +} + +/// Does `src` carry `refusal`? +/// +/// Lane-av1refusalspan: a proving gate quotes the refusal it proves, and this +/// is how it pins that quote to the guard that still carries the string. Both +/// sides are squashed, so a literal written over two lines with a `\` +/// continuation still matches. +#[cfg(test)] +pub(crate) fn pins_refusal(src: &str, refusal: &str) -> bool { + squash_source(src).contains(&squash_source(refusal)) +} + #[cfg(test)] mod tests { - use super::{CAPABILITY_CLAIMS, GATES_THAT_SKIP_ON_A_DECODE_ERROR, PROVEN, REFUSALS}; + use super::{ + CAPABILITY_CLAIMS, GATES_THAT_SKIP_ON_A_DECODE_ERROR, PROVEN, REFUSALS, squash_source, + }; use std::collections::BTreeSet; /// Every distinct `unsupported(...)` reason on the decode path. @@ -1134,6 +1180,13 @@ mod tests { /// comment on `read_golomb`. #[test] fn read_golomb_reads_every_value_a_conformant_stream_can_carry() { + // lane-av1refusalspan: this gate is the PROOF for the refusal below, so + // it names it and pins its guard site. + const REFUSAL: &str = "a Golomb tail longer than this decoder reads"; + assert!( + super::pins_refusal(include_str!("decode.rs"), REFUSAL), + "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs" + ); let roundtrip = |value: u32| -> ec_core::Result { let mut enc = crate::msac::SymbolEncoder::new(); crate::tile::write_golomb(&mut enc, value); @@ -1377,6 +1430,17 @@ mod tests { #[test] fn every_rect_strip_shape_the_split_path_codes_has_a_luma_and_chroma_table() { let src = include_str!("decode.rs"); + // lane-av1refusalspan: this gate is the PROOF for both refusals below, + // so it names both and pins both guard sites. + for refusal in [ + "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here", + "a split intra strip whose transform unit is {tx_w}x{tx_h} (no luma coefficient tables for that shape here)", + ] { + assert!( + super::pins_refusal(&src, refusal), + "this gate proves {refusal:?}, but that string is no longer in decode.rs" + ); + } // (1) The caller set. Each call's enclosing function is the last // top-level `fn` before it. @@ -1937,6 +2001,14 @@ mod tests { /// [`no_block_footprint_with_a_128_pixel_side_can_carry_palette_syntax`]. #[test] fn no_128_root_half_reads_a_cfl_filter_intra_or_palette_symbol() { + // lane-av1refusalspan: this gate is the PROOF for the refusal below, so + // it names it (the full leading clause, which is the whole clause the + // inventory row's anchor reads) and pins its guard site. + const REFUSAL: &str = "CfL, filter intra or a palette on a 128-root HORZ/VERT intra block"; + assert!( + include_str!("decode.rs").contains(REFUSAL), + "this gate proves {REFUSAL:?}, but that string is no longer in decode.rs" + ); let src = include_str!("decode.rs"); // The 128-root call site's own `cfl` argument, with the comment that // explains it -- the two lines are matched together so that reordering @@ -2122,34 +2194,412 @@ mod tests { ); } - /// Every entry of [`PROVEN`] must still name a live refusal and a test - /// that exists, and the count it prints is the inventory's numerator. + /// Lane-av1refusalspan: the files a proving gate may live in. + const GATE_SOURCES: [(&str, &str); 3] = [ + ("decode.rs", include_str!("decode.rs")), + ("stream.rs", include_str!("stream.rs")), + ("refusal_inventory.rs", include_str!("refusal_inventory.rs")), + ]; + + /// Lane-av1refusalspan: every offset in `src` of a line that DEFINES + /// `fn (` -- and nothing that merely names it. + /// + /// "The gate" is a function, so the first thing the anchor needs is the + /// function's own definition. The window rule this replaced took the first + /// `fn (` the file happened to contain, and a comment or a string + /// produces one. A definition is a line whose text before the keyword is + /// whitespace and qualifiers only (`pub`, `pub(crate)`, `async`, ...). + fn gate_definitions(src: &str, gate: &str) -> Vec { + src.match_indices(&format!("fn {gate}(")) + .map(|(at, _)| at) + .filter(|at| { + let line_start = src[..*at].rfind('\n').map_or(0, |i| i + 1); + src[line_start..*at].split_whitespace().all(|word| { + matches!( + word, + "pub" | "async" | "const" | "unsafe" | "extern" | "default" + ) || (word.starts_with("pub(") && word.ends_with(')')) + }) + }) + .collect() + } + + /// The number of leading-whitespace columns on the line holding `at`. + fn leading_indent(src: &str, at: usize) -> usize { + let line_start = src[..at].rfind('\n').map_or(0, |i| i + 1); + let line = &src[line_start..at]; + line.len() - line.trim_start().len() + } + + /// The offset of the `"` that closes the string literal opening at `open`. + fn closing_quote(b: &[u8], open: usize) -> Option { + let mut i = open + 1; + while i < b.len() { + match b[i] { + b'\\' => i += 2, + b'"' => return Some(i), + _ => i += 1, + } + } + None + } + + /// The offsets of the `{` that opens the body of the function defined at + /// `gate_at` and of the `}` that closes it; `None` when the body is never + /// closed. + /// + /// This walks Rust, not lines. A brace inside a string literal, a raw + /// string, a byte string, a char literal, a lifetime, a line comment or a + /// (nestable) block comment is not a brace -- counting one is exactly how a + /// "bounded" window becomes the rest of the file. + fn body_braces(src: &str, gate_at: usize) -> Option<(usize, usize)> { + let b = src.as_bytes(); + let mut i = gate_at; + let mut depth = 0usize; + let mut open = None; + while i < b.len() { + match b[i] { + b'/' if b.get(i + 1) == Some(&b'/') => { + i = src[i..].find('\n').map_or(b.len(), |n| i + n + 1); + continue; + } + b'/' if b.get(i + 1) == Some(&b'*') => { + let mut nesting = 1usize; + i += 2; + while i < b.len() && nesting > 0 { + if b[i] == b'/' && b.get(i + 1) == Some(&b'*') { + nesting += 1; + i += 2; + } else if b[i] == b'*' && b.get(i + 1) == Some(&b'/') { + nesting -= 1; + i += 2; + } else { + i += 1; + } + } + continue; + } + b'r' if b.get(i + 1) == Some(&b'"') || b.get(i + 1) == Some(&b'#') => { + let mut j = i + 1; + while b.get(j) == Some(&b'#') { + j += 1; + } + if b.get(j) != Some(&b'"') { + i += 1; + continue; + } + let hashes = j - i - 1; + let mut end = None; + for k in (j + 1..b.len()).chain(std::iter::once(b.len() - 1)) { + if b[k] == b'"' && b[k + 1..].iter().take(hashes).all(|c| *c == b'#') { + end = Some(k); + break; + } + } + i = end? + 1; + continue; + } + b'"' => { + i = closing_quote(b, i)? + 1; + continue; + } + b'b' if b.get(i + 1) == Some(&b'"') => { + i = closing_quote(b, i + 1)? + 1; + continue; + } + // A lifetime (`'a`, `'static`) is not a char literal: it has no + // closing quote on its line, and reading one as a literal would + // hide real code from the scan. + b'\'' => { + let rest = &b[i + 1..]; + let from = if rest.first() == Some(&b'\\') { 2 } else { 0 }; + match rest[from..] + .iter() + .take_while(|c| **c != b'\n') + .position(|c| *c == b'\'') + { + Some(k) => i += from + k + 2, + None => i += 1, + } + continue; + } + b'{' => { + open = open.or(Some(i)); + depth += 1; + } + b'}' => { + depth -= 1; + if depth == 0 { + return open.map(|o| (o, i)); + } + } + _ => {} + } + i += 1; + } + None + } + + /// The text of the body of the function defined at `gate_at`, or `None` + /// when that body is never closed. + fn function_body<'a>(src: &'a str, gate_at: usize) -> Option<&'a str> { + let (open, close) = body_braces(src, gate_at)?; + src.get(open..=close) + } + + /// The first line of `body` that defines another function at `indent` + /// columns of leading whitespace -- the first sign that a boundary + /// over-reached into a neighbour. + fn sibling_fn(body: &str, indent: usize) -> Option<&str> { + body.lines().skip(1).find(|line| { + let lead = line.len() - line.trim_start().len(); + lead == indent && { + let t = line.trim_start(); + t.starts_with("fn ") || t.starts_with("pub fn ") + } + }) + } + + /// Lane-av1refusalspan: the proving gate's OWN body -- the text from the + /// `{` that opens it to the `}` that closes it. + /// + /// Every failure mode here is a FAILURE (`Err`), never a wider window. The + /// rule this replaced -- "the body ends at the next `fn` at the same + /// indentation, or at end of file" -- ended at end of file constantly (a + /// top-level `#[test] fn` in `decode.rs` has its next same-indent `fn` + /// tens of thousands of lines away), and one row's 27,427-line "body" was + /// satisfied by the CHROMA sibling's string seven lines down. + fn gate_body(gate: &str) -> Result<&'static str, String> { + let mut hits: Vec<(&str, usize, &'static str)> = Vec::new(); + for (file, src) in GATE_SOURCES { + for at in gate_definitions(src, gate) { + hits.push((file, at, src)); + } + } + match hits.as_slice() { + [] => Err(format!( + "{gate} is not defined in decode.rs, stream.rs or refusal_inventory.rs" + )), + [only] => { + let (file, at, src) = *only; + let body = function_body(src, at).ok_or_else(|| { + format!( + "{file}:{at}: the body of {gate}() is never closed -- a missing \ + boundary is a FAILURE, not a window that runs on into the next \ + function" + ) + })?; + if let Some(leak) = sibling_fn(body, leading_indent(src, at)) { + return Err(format!( + "{file}:{at}: the extracted body of {gate}() still contains {} -- the \ + boundary over-reached into a neighbour", + leak.trim() + )); + } + Ok(body) + } + many => Err(format!( + "{gate} is defined {} times ({}), so 'its body' is ambiguous", + many.len(), + many.iter() + .map(|(file, at, _)| format!("{file}:{at}")) + .collect::>() + .join(", ") + )), + } + } + + /// The refusal's leading clause: what a gate may quote when it does not + /// quote the whole string -- everything up to the first `(` (the qualifier + /// that varies per call site), else up to the first `:`, else the whole + /// string. + fn leading_clause(reason: &str) -> String { + let cut = reason + .find('(') + .or_else(|| reason.find(':')) + .unwrap_or(reason.len()); + reason[..cut].trim_end().to_owned() + } + + /// Every entry of [`PROVEN`] must still name a live refusal, and the gate + /// it names must REFERENCE that refusal inside its OWN body. + /// + /// Lane-av1refusalspan: the boundary is the gate's closing brace (see + /// [`gate_body`]); a boundary that cannot be found fails the row. #[test] fn every_proven_refusal_names_a_test_that_exists() { let found = decode_path_refusals(); - let sources = [ - include_str!("stream.rs"), - include_str!("decode.rs"), - include_str!("refusal_inventory.rs"), - ]; + let mut whole = 0usize; + let mut clause = 0usize; + let mut neither: Vec<&str> = Vec::new(); + let mut unanchored: Vec = Vec::new(); + let mut unbounded: Vec = Vec::new(); for (reason, gate) in PROVEN { assert!( found.contains(*reason), - "{reason:?} is listed as proven but is no longer a decode-path refusal -- drop it from PROVEN (the capability landed) or fix the string" - ); - assert!( - sources - .iter() - .any(|src| src.contains(&format!("fn {gate}("))), - "{reason:?} names the proving test {gate}, which exists in neither stream.rs \ - nor decode.rs" + "{reason:?} is listed as proven but is no longer a decode-path refusal -- \ + drop it from PROVEN (the capability landed) or fix the string" ); + // A missing boundary is a FAILURE for the row, never a wider window. + let body = match gate_body(gate) { + Ok(body) => body, + Err(why) => { + unbounded.push(format!("{reason:?} names {gate}: {why}")); + continue; + } + }; + let flat = squash_source(body); + if flat.contains(&squash_source(reason)) { + whole += 1; + } else if flat.contains(&squash_source(&leading_clause(reason))) { + clause += 1; + } else { + neither.push(reason); + unanchored.push(format!("{reason:?} names {gate}")); + } } + // The anchor-strength line, measured over BODIES. The window rule this + // replaced made these numbers a distribution over "whatever the window + // happened to reach", which is a different question. + eprintln!( + "anchor strength: {whole} rows quote the WHOLE refusal string, {clause} quote its \ + LEADING CLAUSE, {} match neither: {neither:?}", + PROVEN.len() - whole - clause + ); eprintln!( "refusal inventory: {} refusals + {} capability claims, {} proven", REFUSALS.len(), CAPABILITY_CLAIMS.len(), PROVEN.len() ); + assert!( + unbounded.is_empty(), + "these rows name a gate whose body could not be bounded, so nothing was proved \ + about them -- a missing boundary is a failure, not a window that runs on:\n\ + {unbounded:#?}\n\ + The boundary is the gate's own closing brace. If the gate really is there, the \ + finder is wrong: fix the finder, never the verdict." + ); + assert!( + unanchored.is_empty(), + "these rows name a gate that never references the refusal inside its OWN body -- a \ + test that does not use the string it is said to prove is not a proof:\n\ + {unanchored:#?}\n\ + Name a gate that quotes the refusal (or its leading clause), or write one." + ); + } + + /// Lane-av1refusalspan, non-vacuity of the BOUNDARY (not of the anchor): + /// a neighbour's function must be unreachable from a gate's body, and a + /// body that is not closed must fail rather than run on. + #[test] + fn a_gate_body_is_bounded_by_its_own_closing_brace() { + let marker = "a rectangular chroma transform whose size has no coefficient table"; + let src = format!( + "fn this_gate() {{\n let _ = 1;\n}}\n\nfn next_gate() {{\n let _ = \"{marker}\";\n}}\n\nfn tail() {{}}\n" + ); + let this = gate_body_in(&src, "this_gate").expect("the gate has a boundary"); + assert!(this.contains("let _ = 1;"), "own text: {this:?}"); + assert!( + !this.contains(marker), + "leaked into the neighbour: {this:?}" + ); + let next = gate_body_in(&src, "next_gate").expect("the neighbour has a boundary"); + assert!(next.contains(marker)); + assert!(!next.contains("let _ = 1;")); + // The last function in a file has no following `fn` to stop at: the + // boundary must still close, exactly on its own brace. + assert_eq!(gate_body_in(&src, "tail").as_deref(), Ok("{}")); + // A brace inside a string or a char literal is not a brace. If the scan + // counted one, this body would run past its own `}` into `next_gate` + // -- the over-reach the `sibling_fn` invariant exists to catch, and the + // failure mode that made the old window 27,427 lines long. + let with_braces_in_literals = format!( + "fn this_gate() {{\n let _ = \"{{\";\n let _ = '}}';\n // {{\n /* }} */\n}}\n\nfn next_gate() {{\n let _ = \"{marker}\";\n}}\n" + ); + let bounded = gate_body_in(&with_braces_in_literals, "this_gate"); + assert!( + bounded.as_deref().is_ok_and(|b| !b.contains(marker)), + "a brace in a literal moved the boundary: {bounded:?}" + ); + // A body whose closing brace is missing (a half-finished edit) is a + // FAILURE. The rule it replaced sliced to end of file and carried on. + let truncated = + format!("fn this_gate() {{\n let _ = 1;\n\nfn next_gate() {{\n let _ = 2;\n}}\n"); + assert!(gate_body_in(&truncated, "this_gate").is_err()); + } + + /// Lane-av1refusalspan: the boundary is load-bearing on the REAL sources, + /// not only on the synthetic pair above -- every named gate resolves to + /// exactly one function whose body holds no other function, and the last + /// function in each of the three files terminates correctly. + #[test] + fn every_named_gate_body_is_bounded_in_these_files() { + let mut resolved = 0usize; + for (reason, gate) in PROVEN { + let body = + gate_body(gate).unwrap_or_else(|why| panic!("{reason:?} names {gate}: {why}")); + assert!( + body.ends_with('}'), + "{gate}'s body does not end on its closing brace" + ); + resolved += 1; + } + assert_eq!(resolved, PROVEN.len()); + for (file, src) in GATE_SOURCES { + let last = last_fn_name(src).unwrap_or_else(|| panic!("{file} has no function")); + let at = gate_definitions(src, &last) + .last() + .copied() + .unwrap_or_else(|| panic!("{file}: no definition of {last}")); + let body = function_body(src, at) + .unwrap_or_else(|| panic!("{file}: the last function {last}() has no boundary")); + assert!(sibling_fn(body, leading_indent(src, at)).is_none()); + } + } + + /// Lane-av1refusalspan: the invariant that catches a boundary that + /// over-reaches. Tested on its own text, so it cannot be satisfied by the + /// scanner happening to be right on the current sources. + #[test] + fn a_body_carrying_another_function_is_refused() { + assert!(sibling_fn("{\n let _ = 1;\n}\n\nfn neighbour() {\n}\n", 0).is_some()); + assert!(sibling_fn("{\n let _ = 1;\n}\n", 0).is_none()); + // A nested `fn` is deeper-indented and does belong to the body. + assert!(sibling_fn("{\n fn helper() {}\n}\n", 0).is_none()); + } + + /// Lane-av1refusalspan: `gate_body` over ONE file, so the boundary tests + /// above can drive it with text that cannot occur in this crate. + fn gate_body_in<'a>(src: &'a str, gate: &str) -> Result<&'a str, String> { + let defs = gate_definitions(src, gate); + match defs.as_slice() { + [] => Err(format!("{gate} is not defined here")), + [at] => { + let body = function_body(src, *at).ok_or_else(|| { + format!("the body of {gate}() is never closed -- boundary missing") + })?; + if let Some(leak) = sibling_fn(body, leading_indent(src, *at)) { + return Err(format!("boundary over-reached into {}", leak.trim())); + } + Ok(body) + } + many => Err(format!("{gate} is defined {} times", many.len())), + } + } + + /// The name of the last function defined in `src` -- the boundary rule's + /// hard case, since nothing follows it to stop at. + fn last_fn_name(src: &str) -> Option { + src.lines() + .filter_map(|line| { + let t = line.trim_start(); + if !(t.starts_with("fn ") || t.starts_with("pub fn ")) { + return None; + } + Some(t.trim_start_matches("pub fn ").trim_start_matches("fn ")) + }) + .filter_map(|head| head.split_once('(').map(|(head, _)| head.trim().to_owned())) + .last() } } diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 52b3abc3..0844bbde 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -4417,6 +4417,14 @@ pub(crate) mod tests { /// re-deriving the formula here. #[test] fn every_frame_size_a_header_can_code_has_a_mode_info_grid() { + // lane-av1refusalspan: this gate is the PROOF for the refusal below, so + // it names it and pins its guard site (the decode-path guard in + // decode.rs carries the same string). + const REFUSAL: &str = "a frame with no mode-info grid"; + assert!( + crate::refusal_inventory::pins_refusal(include_str!("stream.rs"), REFUSAL), + "this gate proves {REFUSAL:?}, but that string is no longer in stream.rs" + ); let mut sizes: Vec = (1..=1024).collect(); sizes.extend([2048, 4095, 4096, 8192, 16384, 32768, 65535, 65536]); // `mi_cols` is nondecreasing in `frame_width`, so an empty grid can