Skip to content

Commit 7c11533

Browse files
Merge branch 'main' into claude/cross-language-comment-aware-main
2 parents 792191b + 54da3aa commit 7c11533

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`
@@ -232,30 +263,32 @@ generation, and keep the `keep` newest older ones
232263
|*OPEN*. The model check above covers the protocol, not the Rust code;
233264
these contracts tie the implementation to P1 and P2.
234265

235-
|`strip_proof_comments` is idempotent and preserves positions outside
236-
comments and strings
237-
|Fix the implementation first; then Creusot/Pearlite and Verus
238-
|Neither property holds of the current Rust function, so neither can be
239-
proved until it changes. All three cases below were run against the
240-
function as it is on `main`:
266+
|Prove the `strip_proof_comments` properties in the ledger for all inputs
267+
|Creusot/Pearlite and Verus
268+
|The single-pass rewrite makes both properties true of the implementation;
269+
the ledger row has them `TESTED` within bounds. Pearlite contracts can
270+
state them directly: equal length, the per-byte relation, and
271+
idempotence. Three counterexamples held of the previous two-phase function
272+
and are now regression tests:
241273

242-
* Not idempotent: `a//*x*/*b*/c` gives `a/*b*/c`, and a second pass gives
274+
* Not idempotent: `a//*x*/*b*/c` gave `a/*b*/c`, and a second pass gave
243275
`ac`.
244-
* Positions move: `a/*x*/b` gives `ab`, moving `b` from offset 6 to 1.
245-
* Ordering bug: block comments are stripped before line comments, so a
246-
block opener inside a line comment swallows the code after it.
247-
`code // see /* note`, then `hidden();`, then `*/ tail`, gives `code `.
248-
The callers that pass both a line and a block marker are affected:
276+
* Positions moved: `a/*x*/b` gave `ab`, moving `b` from offset 6 to 1.
277+
* Ordering bug: block comments were stripped before line comments, so a
278+
block opener inside a line comment swallowed the code after it.
279+
`code // see /* note`, then `hidden();`, then `*/ tail`, gave `code `.
280+
The callers that pass both a line and a block marker were affected:
249281
`analyze_rust`, `is_rust_ffi_safe_wrapper`, `analyze_idris`,
250282
`analyze_lean` and `analyze_agda`. In the Idris, Lean and Agda ProofDrift
251-
detectors such a comment can hide a later `sorry`, `believe_me` or
252-
postulate. `analyze_isabelle` and `analyze_coq` pass no line marker and
253-
are not affected.
254-
255-
The Idris2 model above can guide the contracts once the function is
256-
fixed; it does not discharge them. The model's own remaining slices
257-
(block comments, strings, composition, position preservation; issue #114)
258-
are optional once the implementation proof exists.
283+
detectors such a comment could hide a later `sorry`, `believe_me` or
284+
postulate.
285+
286+
The function does not know about string literals. The Rust and Zig callers
287+
blank strings first; the Lean, Agda, Idris, Coq and Isabelle callers do
288+
not, so a comment marker inside a string literal there still starts a
289+
comment. The Idris2 model's remaining slices (block comments, strings,
290+
composition; issue #114) are optional once the implementation proof
291+
exists.
259292

260293
|Patch Bridge reachability is sound: no reachable dependency is classified
261294
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
@@ -6193,51 +6193,63 @@ fn push_line_anchored_proof_drift(
61936193
});
61946194
}
61956195
}
6196-
6197-
/// Remove proof-language comments while keeping every newline, so a line
6198-
/// number taken from the result is a line number in `content`.
6196+
/// Blank out proof-language comments in one left-to-right pass.
6197+
///
6198+
/// Every byte inside a comment becomes a space, except `'\n'`, which is
6199+
/// kept. So the result has exactly the length of `content`, every byte
6200+
/// outside a comment is unchanged, and a line or column taken from the
6201+
/// result is a line or column in `content`.
6202+
///
6203+
/// Whichever comment opens first wins: a block opener inside a line comment
6204+
/// is comment text, and so is a line marker inside a block comment. Block
6205+
/// comments nest, as they do in every caller's language (Rust, Lean, Agda,
6206+
/// Idris, Coq/Rocq and Isabelle). An unterminated block comment runs to the
6207+
/// end of `content`. An empty `line_marker`, or an empty block marker,
6208+
/// switches that kind of comment off. Markers must not contain whitespace.
6209+
///
6210+
/// The result is a fixed point: stripping it again changes nothing.
61996211
fn strip_proof_comments(content: &str, line_marker: &str, block: Option<(&str, &str)>) -> String {
6200-
// First strip block comments greedily, left-to-right.
6201-
let mut without_blocks = String::with_capacity(content.len());
6202-
if let Some((open, close)) = block {
6203-
let mut rest = content;
6204-
while let Some(start) = rest.find(open) {
6205-
without_blocks.push_str(&rest[..start]);
6206-
let after_open = &rest[start + open.len()..];
6207-
if let Some(end) = after_open.find(close) {
6208-
push_newlines_of(&mut without_blocks, &after_open[..end]);
6209-
rest = &after_open[end + close.len()..];
6212+
fn blank(out: &mut String, span: &str) {
6213+
for c in span.chars() {
6214+
if c == '\n' {
6215+
out.push('\n');
62106216
} else {
6211-
// Unterminated block comment — drop the rest, keep its lines.
6212-
push_newlines_of(&mut without_blocks, after_open);
6213-
rest = "";
6214-
break;
6217+
// One space per byte keeps byte offsets, not just columns.
6218+
out.extend(std::iter::repeat_n(' ', c.len_utf8()));
62156219
}
62166220
}
6217-
without_blocks.push_str(rest);
6218-
} else {
6219-
without_blocks.push_str(content);
62206221
}
62216222

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

0 commit comments

Comments
 (0)