Skip to content

Commit 54da3aa

Browse files
fix(assail): strip proof comments in one pass, blanking in place (#304)
## The bug (still on `main`) `strip_proof_comments` strips block comments before line comments, so a block opener inside a line comment swallows the code after it: ```text code // see /* note hidden(); */ tail ``` This reduces to `code `. The callers that pass both markers are: * `analyze_rust` * `is_rust_ffi_safe_wrapper` * `analyze_idris` * `analyze_lean` * `analyze_agda` In the Idris, Lean and Agda ProofDrift detectors, such a comment can hide a later `sorry`, `believe_me` or `postulate`. The function also deletes block-comment text. That moves columns (`a/*x*/b` → `ab`). It is also not idempotent: `a//*x*/*b*/c` → `a/*b*/c` → `ac`. ## The fix It is now one left-to-right scan: * Whichever comment opens first wins. * Block comments nest, as they do in Rust, Lean, Agda, Idris, Coq/Rocq and Isabelle. * Comment bytes become spaces, and newlines are kept. So the output has the input's exact byte length, and every byte outside a comment is unchanged. This keeps #278's newline invariant and adds column and byte-offset preservation. The output is also a fixed point. ## Evidence * **New module `strip_proof_comments_tests`:** * regressions for the three counterexamples, plus nesting, unterminated blocks, multibyte text and empty markers; * **exhaustive bounded checks** of length preservation, per-byte preservation and idempotence, for all five marker sets the analyzers pass. Inputs: every string over a 4-letter alphabet up to length 8 (87,381), or over a 5-letter alphabet up to length 7 (97,656); * **a differential test** against a transcription of the `src/abi/Stripping.idr` equations. * **Agreement with the compiled model:** the compiled Idris2 model on `main` and the Rust function give the same output on all 349,525 strings of length ≤ 9 over `/`, newline, `x` and space. This was a local run. So the model's idempotence theorem is now about this function's behaviour on that slice; before this PR the two disagreed (`//x`). * **Planted faults**, each caught by the tests: | Planted fault | Result | |---|---| | the current two-phase function | killed | | delete instead of blank | killed | | blanking drops a newline | killed | | one space per character instead of per byte | killed | | no nesting | killed | | unterminated block keeps code | killed | | a line comment that also consumes its newline | **equivalent**: the newline is kept and the scan resumes after it | * **Checks:** * `cargo test --all-features`: 895 passed, 0 failed. * `cargo clippy --all-targets --all-features -D warnings`: clean. * `cargo fmt --check`: clean. * `scripts/ci/check-idris-abi.sh`: all four modules pass. * **Self-scan unchanged:** the same 36 unsuppressed findings on `main` and on this branch. ## Docs * **`PROOF-NEEDS.adoc`:** * New ledger row: `strip_proof_comments`, `TESTED`, with the bounds above. * The Stripping model row now records agreement instead of the mismatch. * The open obligation is now "prove for all inputs with Creusot/Pearlite and Verus". * Known limitation, recorded: the Lean, Agda, Idris, Coq and Isabelle callers do not blank string literals, so a marker inside a string still opens a comment. * **`src/abi/Stripping.idr`:** a comment-only paragraph stating which slice the model corresponds to and how that was checked. This replaces the stacked branch that was planned on top of #282. #282 was closed, and its routing work is on `main`. --- _Generated by [Claude Code](https://claude.ai/code/session_01Jma5ixtpeZyJRmfoSsC98u)_ Co-authored-by: Claude <noreply@anthropic.com>
1 parent f2c46ba commit 54da3aa

3 files changed

Lines changed: 288 additions & 61 deletions

File tree

‎PROOF-NEEDS.adoc‎

Lines changed: 59 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -107,12 +107,43 @@ definitions. A mutant that blanks with `+/+` instead of a space is rejected.
107107
Nine closed sanity theorems, including two comments on different lines and
108108
`+///+`.
109109

110-
The model does *not* match `strip_proof_comments`, so it is evidence about
111-
the model only. It replaces comment characters with spaces and keeps every
112-
newline. The Rust function deletes comment text and drops a trailing
113-
newline: on `//x` the model gives three spaces and Rust gives the empty
114-
string. The model also covers line comments only; block comments and string
115-
literals are not modelled.
110+
The model now agrees with `strip_proof_comments(s, "//", None)`, the slice
111+
it models. The compiled model and the Rust function give the same output on
112+
every string of length at most 9 over `/`, newline, `x` and space (349,525
113+
inputs, local run). In CI,
114+
`the_line_comment_slice_matches_the_idris_model` re-checks a Rust
115+
transcription of the model's equations up to length 8. Correspondence on
116+
that slice is therefore `TESTED`, with those bounds, not `ASSUMED`. Block
117+
comments, nesting and string literals are not modelled. Before the
118+
single-pass rewrite they disagreed: on `//x` the model gave three spaces and
119+
Rust gave the empty string.
120+
121+
|`strip_proof_comments` blanks comments in place. The output has the input's
122+
byte length; every byte outside a comment, and every newline, is unchanged;
123+
other comment bytes become spaces. Stripping is idempotent. Whichever
124+
comment opens first wins, and block comments nest.
125+
|`src/assail/analyzer.rs`, module `strip_proof_comments_tests`
126+
|`TESTED`
127+
|Exhaustive over bounded inputs, for the marker sets the analyzers pass:
128+
`//` with `/* */`, `--` with `/- -/`, `--` with `{- -}`, `(* *)` alone, and
129+
`//` alone. Each runs every string over a 4-letter alphabet up to length 8
130+
(87,381 inputs) or a 5-letter alphabet up to length 7 (97,656 inputs). Each
131+
alphabet spells the markers, plus a newline and an ordinary character.
132+
The three counterexamples in the open obligations are regression tests, as
133+
are nesting, unterminated blocks and multibyte text.
134+
135+
Planted faults, all caught:
136+
137+
* the previous two-phase function;
138+
* deleting comment text instead of blanking it;
139+
* blanking that drops a newline;
140+
* one space per character instead of per byte;
141+
* no nesting;
142+
* an unterminated block that keeps code.
143+
144+
One mutant, a line comment that also consumes its newline, is equivalent:
145+
the newline is kept and the scan resumes after it, so no test can tell
146+
them apart.
116147

117148
|Attestation chain: integrity, authenticity, non-repudiation
118149
|`src/abi/AttestationUnforgeability.idr`
@@ -223,30 +254,32 @@ generation, and keep the `keep` newest older ones
223254
|*OPEN*. The model check above covers the protocol, not the Rust code;
224255
these contracts tie the implementation to P1 and P2.
225256

226-
|`strip_proof_comments` is idempotent and preserves positions outside
227-
comments and strings
228-
|Fix the implementation first; then Creusot/Pearlite and Verus
229-
|Neither property holds of the current Rust function, so neither can be
230-
proved until it changes. All three cases below were run against the
231-
function as it is on `main`:
257+
|Prove the `strip_proof_comments` properties in the ledger for all inputs
258+
|Creusot/Pearlite and Verus
259+
|The single-pass rewrite makes both properties true of the implementation;
260+
the ledger row has them `TESTED` within bounds. Pearlite contracts can
261+
state them directly: equal length, the per-byte relation, and
262+
idempotence. Three counterexamples held of the previous two-phase function
263+
and are now regression tests:
232264

233-
* Not idempotent: `a//*x*/*b*/c` gives `a/*b*/c`, and a second pass gives
265+
* Not idempotent: `a//*x*/*b*/c` gave `a/*b*/c`, and a second pass gave
234266
`ac`.
235-
* Positions move: `a/*x*/b` gives `ab`, moving `b` from offset 6 to 1.
236-
* Ordering bug: block comments are stripped before line comments, so a
237-
block opener inside a line comment swallows the code after it.
238-
`code // see /* note`, then `hidden();`, then `*/ tail`, gives `code `.
239-
The callers that pass both a line and a block marker are affected:
267+
* Positions moved: `a/*x*/b` gave `ab`, moving `b` from offset 6 to 1.
268+
* Ordering bug: block comments were stripped before line comments, so a
269+
block opener inside a line comment swallowed the code after it.
270+
`code // see /* note`, then `hidden();`, then `*/ tail`, gave `code `.
271+
The callers that pass both a line and a block marker were affected:
240272
`analyze_rust`, `is_rust_ffi_safe_wrapper`, `analyze_idris`,
241273
`analyze_lean` and `analyze_agda`. In the Idris, Lean and Agda ProofDrift
242-
detectors such a comment can hide a later `sorry`, `believe_me` or
243-
postulate. `analyze_isabelle` and `analyze_coq` pass no line marker and
244-
are not affected.
245-
246-
The Idris2 model above can guide the contracts once the function is
247-
fixed; it does not discharge them. The model's own remaining slices
248-
(block comments, strings, composition, position preservation; issue #114)
249-
are optional once the implementation proof exists.
274+
detectors such a comment could hide a later `sorry`, `believe_me` or
275+
postulate.
276+
277+
The function does not know about string literals. The Rust and Zig callers
278+
blank strings first; the Lean, Agda, Idris, Coq and Isabelle callers do
279+
not, so a comment marker inside a string literal there still starts a
280+
comment. The Idris2 model's remaining slices (block comments, strings,
281+
composition; issue #114) are optional once the implementation proof
282+
exists.
250283

251284
|Patch Bridge reachability is sound: no reachable dependency is classified
252285
as phantom

‎src/abi/Stripping.idr‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,14 @@
1515
||| The model strips ALL `//` comments: `stripLineCommentBody` hands back
1616
||| to `stripLineComments` after each preserved newline (issue #113).
1717
|||
18+
||| Correspondence: the model is `strip_proof_comments(s, "//", None)`, the
19+
||| line-comment slice only. Block comments, their nesting and string
20+
||| literals are not modelled, so the theorem is about that slice. On it the
21+
||| compiled model and the Rust function agree on every string of length at
22+
||| most 9 over `/`, newline, `x` and space, and a Rust test
23+
||| (`the_line_comment_slice_matches_the_idris_model`) re-checks these
24+
||| equations up to length 8. See PROOF-NEEDS.adoc.
25+
|||
1826
||| Re-proved 2026-11-09. The previous proof (PR #111, issue #113) never
1927
||| type-checked: its `//` case relied on reductions that do not hold for a
2028
||| variable character, and it used `decEq` without importing it. The proof

‎src/assail/analyzer.rs‎

Lines changed: 221 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -6187,51 +6187,63 @@ fn push_line_anchored_proof_drift(
61876187
});
61886188
}
61896189
}
6190-
6191-
/// Remove proof-language comments while keeping every newline, so a line
6192-
/// number taken from the result is a line number in `content`.
6190+
/// Blank out proof-language comments in one left-to-right pass.
6191+
///
6192+
/// Every byte inside a comment becomes a space, except `'\n'`, which is
6193+
/// kept. So the result has exactly the length of `content`, every byte
6194+
/// outside a comment is unchanged, and a line or column taken from the
6195+
/// result is a line or column in `content`.
6196+
///
6197+
/// Whichever comment opens first wins: a block opener inside a line comment
6198+
/// is comment text, and so is a line marker inside a block comment. Block
6199+
/// comments nest, as they do in every caller's language (Rust, Lean, Agda,
6200+
/// Idris, Coq/Rocq and Isabelle). An unterminated block comment runs to the
6201+
/// end of `content`. An empty `line_marker`, or an empty block marker,
6202+
/// switches that kind of comment off. Markers must not contain whitespace.
6203+
///
6204+
/// The result is a fixed point: stripping it again changes nothing.
61936205
fn strip_proof_comments(content: &str, line_marker: &str, block: Option<(&str, &str)>) -> String {
6194-
// First strip block comments greedily, left-to-right.
6195-
let mut without_blocks = String::with_capacity(content.len());
6196-
if let Some((open, close)) = block {
6197-
let mut rest = content;
6198-
while let Some(start) = rest.find(open) {
6199-
without_blocks.push_str(&rest[..start]);
6200-
let after_open = &rest[start + open.len()..];
6201-
if let Some(end) = after_open.find(close) {
6202-
push_newlines_of(&mut without_blocks, &after_open[..end]);
6203-
rest = &after_open[end + close.len()..];
6206+
fn blank(out: &mut String, span: &str) {
6207+
for c in span.chars() {
6208+
if c == '\n' {
6209+
out.push('\n');
62046210
} else {
6205-
// Unterminated block comment — drop the rest, keep its lines.
6206-
push_newlines_of(&mut without_blocks, after_open);
6207-
rest = "";
6208-
break;
6211+
// One space per byte keeps byte offsets, not just columns.
6212+
out.extend(std::iter::repeat_n(' ', c.len_utf8()));
62096213
}
62106214
}
6211-
without_blocks.push_str(rest);
6212-
} else {
6213-
without_blocks.push_str(content);
62146215
}
62156216

6216-
// Then strip line comments. Split on '\n' (not `lines()`) so a trailing
6217-
// newline survives and the newline count is exactly preserved.
6218-
if line_marker.is_empty() {
6219-
return without_blocks;
6220-
}
6221-
let mut out = String::with_capacity(without_blocks.len());
6222-
for (i, line) in without_blocks.split('\n').enumerate() {
6223-
let kept = match line.find(line_marker) {
6224-
Some(idx) => &line[..idx],
6225-
None => line,
6217+
let block = block.filter(|(open, close)| !open.is_empty() && !close.is_empty());
6218+
let mut out = String::with_capacity(content.len());
6219+
let mut depth = 0usize;
6220+
let mut i = 0;
6221+
while let Some(rest) = content.get(i..).filter(|r| !r.is_empty()) {
6222+
let step = match block {
6223+
Some((_, close)) if depth > 0 && rest.starts_with(close) => {
6224+
depth -= 1;
6225+
close.len()
6226+
}
6227+
Some((open, _)) if rest.starts_with(open) => {
6228+
depth += 1;
6229+
open.len()
6230+
}
6231+
_ if depth > 0 => rest.chars().next().map_or(1, char::len_utf8),
6232+
_ if !line_marker.is_empty() && rest.starts_with(line_marker) => {
6233+
rest.find('\n').unwrap_or(rest.len())
6234+
}
6235+
_ => {
6236+
let len = rest.chars().next().map_or(1, char::len_utf8);
6237+
out.push_str(&rest[..len]);
6238+
i += len;
6239+
continue;
6240+
}
62266241
};
6227-
if i > 0 {
6228-
out.push('\n');
6229-
}
6230-
out.push_str(kept);
6242+
blank(&mut out, &rest[..step]);
6243+
i += step;
62316244
}
62326245
out
62336246
}
6234-
62356247
/// Strip C-family line comments (`//`, `///`, `//!`) from each line, leaving
62366248
/// the rest of the source intact. String literals are detected so a `//`
62376249
/// inside `"http://example.com"` is NOT treated as a comment.
@@ -8885,3 +8897,177 @@ mod proof_line_anchor_tests {
88858897
assert_eq!(occurrence_lines(&code, "sorry"), vec![6]);
88868898
}
88878899
}
8900+
8901+
#[cfg(test)]
8902+
mod strip_proof_comments_tests {
8903+
use super::strip_proof_comments;
8904+
8905+
type Markers = (&'static str, Option<(&'static str, &'static str)>);
8906+
8907+
/// The marker pairs the analyzers pass, each with an alphabet that can
8908+
/// spell every marker, plus a newline and an ordinary character.
8909+
const CONFIGS: [(Markers, &[char]); 5] = [
8910+
(("//", Some(("/*", "*/"))), &['/', '*', '\n', 'x']),
8911+
(("--", Some(("/-", "-/"))), &['/', '-', '\n', 'x']),
8912+
(("--", Some(("{-", "-}"))), &['{', '-', '}', '\n', 'x']),
8913+
(("", Some(("(*", "*)"))), &['(', '*', ')', '\n', 'x']),
8914+
(("//", None), &['/', '\n', 'x', ' ']),
8915+
];
8916+
8917+
/// Every string over `alphabet` of length at most `max_len`.
8918+
fn all_strings(alphabet: &[char], max_len: usize) -> Vec<String> {
8919+
let mut all = vec![String::new()];
8920+
let mut layer = vec![String::new()];
8921+
for _ in 0..max_len {
8922+
layer = layer
8923+
.iter()
8924+
.flat_map(|s| {
8925+
alphabet.iter().map(move |c| {
8926+
let mut t = s.clone();
8927+
t.push(*c);
8928+
t
8929+
})
8930+
})
8931+
.collect();
8932+
all.extend(layer.iter().cloned());
8933+
}
8934+
all
8935+
}
8936+
8937+
fn strip(s: &str, (line, block): Markers) -> String {
8938+
strip_proof_comments(s, line, block)
8939+
}
8940+
8941+
#[test]
8942+
fn a_block_opener_inside_a_line_comment_hides_nothing() {
8943+
let src = "code // see /* note\nhidden();\n*/ tail";
8944+
let out = strip(src, ("//", Some(("/*", "*/"))));
8945+
let blanked = " ".repeat("// see /* note".len());
8946+
assert_eq!(out, format!("code {blanked}\nhidden();\n*/ tail"));
8947+
}
8948+
8949+
#[test]
8950+
fn a_line_marker_inside_a_block_comment_hides_nothing() {
8951+
let src = "/- -- -/ sorry";
8952+
assert_eq!(strip(src, ("--", Some(("/-", "-/")))), " sorry");
8953+
}
8954+
8955+
#[test]
8956+
fn the_former_idempotence_counterexample_is_now_a_fixed_point() {
8957+
let markers = ("//", Some(("/*", "*/")));
8958+
let once = strip("a//*x*/*b*/c", markers);
8959+
assert_eq!(once, "a ");
8960+
assert_eq!(strip(&once, markers), once);
8961+
}
8962+
8963+
#[test]
8964+
fn text_after_a_block_comment_keeps_its_offset() {
8965+
let out = strip("a/*x*/b", ("//", Some(("/*", "*/"))));
8966+
assert_eq!(out, "a b");
8967+
assert_eq!(out.find('b'), Some(6));
8968+
}
8969+
8970+
#[test]
8971+
fn block_comments_nest() {
8972+
let src = "/- a /- b -/ sorry -/ x";
8973+
assert_eq!(
8974+
strip(src, ("--", Some(("/-", "-/")))),
8975+
" x"
8976+
);
8977+
let src = "(* (* *) sorry *) oops";
8978+
assert_eq!(
8979+
strip(src, ("", Some(("(*", "*)")))),
8980+
" oops"
8981+
);
8982+
}
8983+
8984+
#[test]
8985+
fn an_unterminated_block_comment_runs_to_the_end_keeping_newlines() {
8986+
let out = strip("a {- b\nc\n", ("--", Some(("{-", "-}"))));
8987+
assert_eq!(out, "a \n \n");
8988+
}
8989+
8990+
#[test]
8991+
fn multibyte_text_keeps_its_byte_offsets() {
8992+
let src = "/* é */x // ü\ny";
8993+
let out = strip(src, ("//", Some(("/*", "*/"))));
8994+
assert_eq!(out.len(), src.len());
8995+
assert_eq!(out.find('x'), src.find('x'));
8996+
assert_eq!(out.find('y'), src.find('y'));
8997+
assert!(!out.contains('é') && !out.contains('ü'));
8998+
}
8999+
9000+
#[test]
9001+
fn empty_markers_switch_that_comment_kind_off() {
9002+
assert_eq!(strip("a // b", ("", None)), "a // b");
9003+
assert_eq!(strip("a /* b */", ("", Some(("", "*/")))), "a /* b */");
9004+
}
9005+
9006+
/// Exhaustive over every string up to the bound, for every marker set the
9007+
/// analyzers use: the result has the input's length, keeps every byte
9008+
/// outside a comment and every newline, blanks the rest with spaces, and
9009+
/// is a fixed point.
9010+
#[test]
9011+
fn stripping_preserves_positions_and_is_idempotent_exhaustively() {
9012+
for (markers, alphabet) in CONFIGS {
9013+
let max_len = if alphabet.len() > 4 { 7 } else { 8 };
9014+
for src in all_strings(alphabet, max_len) {
9015+
let out = strip(&src, markers);
9016+
assert_eq!(out.len(), src.len(), "{markers:?} {src:?}");
9017+
for (a, b) in src.bytes().zip(out.bytes()) {
9018+
assert!(
9019+
a == b || (b == b' ' && a != b'\n'),
9020+
"{markers:?} {src:?} -> {out:?}"
9021+
);
9022+
}
9023+
assert_eq!(strip(&out, markers), out, "{markers:?} {src:?}");
9024+
}
9025+
}
9026+
}
9027+
9028+
/// The line-comment model in `src/abi/Stripping.idr`,
9029+
/// transcribed equation by equation. Idris2 proves the model idempotent.
9030+
fn idris_model(s: &[char]) -> String {
9031+
fn code(s: &[char], out: &mut String) {
9032+
match s {
9033+
[] => {}
9034+
['/', '/', rest @ ..] => {
9035+
out.push_str(" ");
9036+
body(rest, out);
9037+
}
9038+
[c, rest @ ..] => {
9039+
out.push(*c);
9040+
code(rest, out);
9041+
}
9042+
}
9043+
}
9044+
fn body(s: &[char], out: &mut String) {
9045+
match s {
9046+
[] => {}
9047+
['\n', rest @ ..] => {
9048+
out.push('\n');
9049+
code(rest, out);
9050+
}
9051+
[_, rest @ ..] => {
9052+
out.push(' ');
9053+
body(rest, out);
9054+
}
9055+
}
9056+
}
9057+
let mut out = String::new();
9058+
code(s, &mut out);
9059+
out
9060+
}
9061+
9062+
/// With only a `//` marker, the Rust function and the Idris2 model agree
9063+
/// on every input up to the bound, so the model's idempotence theorem is
9064+
/// about this function's behaviour on that slice, not about a different
9065+
/// function.
9066+
#[test]
9067+
fn the_line_comment_slice_matches_the_idris_model() {
9068+
for src in all_strings(&['/', '\n', 'x', ' '], 8) {
9069+
let chars: Vec<char> = src.chars().collect();
9070+
assert_eq!(strip(&src, ("//", None)), idris_model(&chars), "{src:?}");
9071+
}
9072+
}
9073+
}

0 commit comments

Comments
 (0)