From c4773e4312e2c3b2527029dc75265dc72235b60c Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 21:29:32 +0000 Subject: [PATCH] Reader predicates: first-party noncharacter and safe-integer core with contracts (not yet run) - src/ijson_core.rs: is_noncharacter (arithmetic, no bit mask), is_safe_i64, is_safe_u64, with Pearlite contracts behind cfg(creusot) and a lemma tying the arithmetic form to the Unicode list. Exhaustive test over every code point; boundary test for the safe range. - Harness: includes the new file by path; one more true and false control; the gate self-test and SCOPE follow. - verification/verus/reader_model.rs: model of the predicates, bounded traversal and duplicate-key rejection. Not run. - verification/PROOF-STATUS.adoc: reader section R-1 to R-7, A-6, A-7. No verifier has been run; every proof row stays OPEN or TESTED. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01J4QvDfneftEg71bUadt3v3 --- .proven/coverage-exclusions.tsv | 6 +- scripts/tests/proof-gate-test.sh | 6 +- src/ijson.rs | 37 +--- src/ijson_core.rs | 157 +++++++++++++++ src/lib.rs | 1 + verification/PROOF-STATUS.adoc | 115 +++++++++++ verification/creusot/SCOPE | 1 + verification/creusot/src/controls.rs | 15 ++ verification/creusot/src/lib.rs | 3 + verification/creusot/tests/contracts_parse.rs | 6 +- verification/verus/reader_model.rs | 185 ++++++++++++++++++ 11 files changed, 492 insertions(+), 40 deletions(-) create mode 100644 src/ijson_core.rs create mode 100644 verification/verus/reader_model.rs diff --git a/.proven/coverage-exclusions.tsv b/.proven/coverage-exclusions.tsv index 20b9812..b58e120 100644 --- a/.proven/coverage-exclusions.tsv +++ b/.proven/coverage-exclusions.tsv @@ -6,9 +6,9 @@ # path lines sha256 kind reason src/bin/ijson-jcs.rs 227 86afdf70a95436e883aa7fc5c06a2ab083719054438f1218d15ebdaf287b4bac unreachable implicit else of `if let Some(permissions)`: in fix mode permissions is always Some (check mode returned earlier) src/bin/ijson-jcs.rs 280 86afdf70a95436e883aa7fc5c06a2ab083719054438f1218d15ebdaf287b4bac unreachable same as line 227, in fix-jsonl -src/ijson.rs 217 2a44168318e224e1f830fe9ab620aa00dd4f7b3fb19ef4399abf59593cf0756d unreachable u64 at or below 2^53-1 is always also an i64, so the first branch takes it -src/ijson.rs 221-224 afced9dbdd974f8cf35d6d3aedbcbd87996442c0cac6277c28ebd26722862bfc unreachable serde_json::Number cannot hold a non-finite double (Number::from_f64 refuses NaN and infinities) -src/ijson.rs 234 28d86778615f6af47bb1bc4f40face756749768e5111f114cfa234a5060c25af unreachable implicit else after as_f64(): a serde_json::Number is always i64, u64 or f64 +src/ijson.rs 188 2a44168318e224e1f830fe9ab620aa00dd4f7b3fb19ef4399abf59593cf0756d unreachable u64 at or below 2^53-1 is always also an i64, so the first branch takes it +src/ijson.rs 192-195 afced9dbdd974f8cf35d6d3aedbcbd87996442c0cac6277c28ebd26722862bfc unreachable serde_json::Number cannot hold a non-finite double (Number::from_f64 refuses NaN and infinities) +src/ijson.rs 205 28d86778615f6af47bb1bc4f40face756749768e5111f114cfa234a5060c25af unreachable implicit else after as_f64(): a serde_json::Number is always i64, u64 or f64 src/jcs.rs 125-126 78794b4982c6b480eda0ee4efa87c54898f9b52aba2a31b5a38520c26e9f39ef unreachable u64 at or below 2^53-1 is always also an i64, so the first branch takes it src/jcs.rs 145 eff5313cfd9eb5a1150c6c7f8f74f8ecbdffd415cd5ed94092b960f0ce737aa3 unreachable es_number_to_string is only called with a Number's f64, which is always finite src/jcs_core.rs 49 8cf9087aa9d19bdaa3e01a4606ae1ec5607e672b8b054df2dac968c5750392ff unreachable bytes F5..FF never occur in the UTF-8 of a Rust str, which is the only input; the branch keeps the key a permutation of all byte values (unit test order_key_is_a_permutation executes it) diff --git a/scripts/tests/proof-gate-test.sh b/scripts/tests/proof-gate-test.sh index 4a82002..3b149e2 100755 --- a/scripts/tests/proof-gate-test.sh +++ b/scripts/tests/proof-gate-test.sh @@ -16,7 +16,7 @@ fail=0 fixture() { local dir=$work/$1 mkdir -p "$dir/src" "$dir/verification" - cp src/jcs_core.rs "$dir/src/" + cp src/jcs_core.rs src/ijson_core.rs "$dir/src/" cp -r verification/creusot "$dir/verification/" rm -rf "$dir/verification/creusot/target" git -C "$dir" init -q @@ -34,7 +34,7 @@ stub() { chmod +x "$path" echo "$path" } -honest=$(stub honest 'if [[ $1 == false ]]; then echo "error: false_control_ordering: goal not proved"; echo "error: false_control_literal: goal not proved"; exit 1; fi') +honest=$(stub honest 'if [[ $1 == false ]]; then echo "error: false_control_ordering: goal not proved"; echo "error: false_control_literal: goal not proved"; echo "error: false_control_noncharacter: goal not proved"; exit 1; fi') accepts_all=$(stub accepts-all 'exit 0') refuses_all=$(stub refuses-all 'echo "error: toolchain missing"; exit 1') wrong_reason=$(stub wrong-reason 'if [[ $1 == false ]]; then echo "error: could not compile"; exit 1; fi') @@ -71,7 +71,7 @@ receipt=$work/honest/target/receipt.json commit=$(git -C "$work/honest" rev-parse HEAD) digest=$(sha256sum "$work/honest/src/jcs_core.rs" | cut -d' ' -f1) for want in "\"commit\":\"$commit\"" "\"src/jcs_core.rs\":\"$digest\"" '"verifier":"stub"' \ - '"false_refused":["false_control_ordering","false_control_literal"]'; do + '"false_refused":["false_control_ordering","false_control_literal","false_control_noncharacter"]'; do grep -qF "$want" "$receipt" || { echo "FAIL receipt lacks $want" >&2; fail=1; } done diff --git a/src/ijson.rs b/src/ijson.rs index 4cc2a8e..35068b0 100644 --- a/src/ijson.rs +++ b/src/ijson.rs @@ -30,6 +30,7 @@ use serde_json::Value; use crate::error::ValidationError; +use crate::ijson_core; /// The safe integer limits for IEEE-754 binary64 /// Numbers outside this range cannot be represented exactly as doubles @@ -139,7 +140,7 @@ fn validate_string_is_i_json(s: &str, path: &str) -> Result<(), ValidationError> let code_point = ch as u32; // Check for noncharacters - if is_noncharacter(code_point) { + if ijson_core::is_noncharacter(code_point) { return Err(ValidationError::Noncharacter { location: format!("U+{:04X} at index {}", code_point, index), path: path.to_string(), @@ -155,36 +156,6 @@ fn validate_string_is_i_json(s: &str, path: &str) -> Result<(), ValidationError> Ok(()) } -/// Check if a code point is a noncharacter -/// -/// Noncharacters are code points that are explicitly defined as non-characters -/// by the Unicode standard and MUST NOT appear in interchange: -/// -/// - U+FDD0..U+FDEF (last two of each plane) -/// - U+FFFE, U+FFFF (last two of BMP) -/// - U+1FFFE, U+1FFFF, U+2FFFE, U+2FFFF, ... U+10FFFE, U+10FFFF -/// (last two of each supplementary plane) -fn is_noncharacter(code_point: u32) -> bool { - // U+FDD0..U+FDEF - if (0xFDD0..=0xFDEF).contains(&code_point) { - return true; - } - - // U+FFFE, U+FFFF - if code_point == 0xFFFE || code_point == 0xFFFF { - return true; - } - - // U+1FFFE, U+1FFFF, U+2FFFE, U+2FFFF, etc. - // These are all code points where the last 16 bits are FFFE or FFFF - // and the code point is within the valid Unicode range (U+0000..U+10FFFF) - if code_point <= 0x10FFFF && (code_point & 0xFFFF) >= 0xFFFE { - return true; - } - - false -} - /// Validate that a number is valid I-JSON /// /// I-JSON recommends that numbers be limited to those exactly representable @@ -201,7 +172,7 @@ fn validate_number_is_i_json(n: &serde_json::Number, path: &str) -> Result<(), V // Check for integer representation first (even if it can also be float) if let Some(i) = n.as_i64() { // Check safe integer range - if !(SAFE_INT_MIN..=SAFE_INT_MAX).contains(&i) { + if !ijson_core::is_safe_i64(i) { return Err(ValidationError::UnsafeInteger { value: i.to_string(), path: path.to_string(), @@ -209,7 +180,7 @@ fn validate_number_is_i_json(n: &serde_json::Number, path: &str) -> Result<(), V } } else if let Some(u) = n.as_u64() { // Check safe unsigned integer range - if u > SAFE_UINT_MAX { + if !ijson_core::is_safe_u64(u) { return Err(ValidationError::UnsafeInteger { value: u.to_string(), path: path.to_string(), diff --git a/src/ijson_core.rs b/src/ijson_core.rs new file mode 100644 index 0000000..fb777a3 --- /dev/null +++ b/src/ijson_core.rs @@ -0,0 +1,157 @@ +//! SPDX-License-Identifier: MPL-2.0 +//! Copyright (c) 2026 Hyperpolymath Estate +//! +//! First-party I-JSON predicates: Unicode noncharacters and safe integers. +// +// Like `jcs_core.rs`, this file is compiled by this crate and, from the same +// bytes, by the Creusot harness in `verification/creusot`. It depends on +// nothing but `core`, and every contract is behind `cfg(creusot)`. +// +// STATUS: the contracts have NOT been run through Creusot; the rows are +// `OPEN` in `verification/PROOF-STATUS.adoc`. The behaviour is `TESTED` by +// the exhaustive tests at the end of this file. + +// creusot-std 0.15.0 has no contract for `RangeInclusive::contains`, so range +// tests are written as two comparisons. +#![allow(clippy::manual_range_contains)] + +#[cfg(creusot)] +use creusot_std::prelude::*; + +/// 2^53 − 1: the largest integer magnitude RFC 7493 §2.2 treats as exact. +pub(crate) const SAFE_MAGNITUDE: u64 = 9_007_199_254_740_991; + +/// Whether `code_point` is a Unicode noncharacter (RFC 7493 §2.1). +/// +/// The noncharacters are U+FDD0..=U+FDEF and the last two code points of +/// each of the 17 planes: U+FFFE, U+FFFF, U+1FFFE, U+1FFFF, ... U+10FFFF. +/// A value above U+10FFFF is not a code point and is not a noncharacter. +#[cfg_attr(creusot, check(terminates))] +#[cfg_attr(creusot, ensures(result == noncharacter(code_point@)))] +pub(crate) fn is_noncharacter(code_point: u32) -> bool { + if code_point >= 0xFDD0 && code_point <= 0xFDEF { + return true; + } + code_point <= 0x10FFFF && code_point % 0x1_0000 >= 0xFFFE +} + +/// Whether a signed integer lies in the I-JSON safe range ±(2^53 − 1). +#[cfg_attr(creusot, check(terminates))] +#[cfg_attr(creusot, ensures(result == safe_integer(value@)))] +pub(crate) fn is_safe_i64(value: i64) -> bool { + value >= -(SAFE_MAGNITUDE as i64) && value <= SAFE_MAGNITUDE as i64 +} + +/// Whether an unsigned integer lies in the I-JSON safe range. +#[cfg_attr(creusot, check(terminates))] +#[cfg_attr(creusot, ensures(result == safe_integer(value@)))] +pub(crate) fn is_safe_u64(value: u64) -> bool { + value <= SAFE_MAGNITUDE +} + +// --------------------------------------------------------------------------- +// Pearlite specification (only compiled by Creusot) +// --------------------------------------------------------------------------- + +/// The noncharacters, as a predicate on integers. +#[cfg(creusot)] +#[logic(open)] +pub fn noncharacter(c: Int) -> bool { + pearlite! { + (0xFDD0 <= c && c <= 0xFDEF) + || (0 <= c && c <= 0x10FFFF && c % 0x10000 >= 0xFFFE) + } +} + +/// The same set, enumerated: 32 in the BMP block and two at the end of each +/// plane. Proving this equal to `noncharacter` ties the arithmetic form to +/// the list in the Unicode standard. +#[cfg(creusot)] +#[logic(open)] +pub fn noncharacter_listed(c: Int) -> bool { + pearlite! { + (0xFDD0 <= c && c <= 0xFDEF) + || (exists 0 <= plane && plane <= 16 + && (c == plane * 0x10000 + 0xFFFE || c == plane * 0x10000 + 0xFFFF)) + } +} + +/// The arithmetic and the enumerated definitions agree. +#[cfg(creusot)] +#[logic] +#[ensures(noncharacter(c) == noncharacter_listed(c))] +pub fn noncharacter_matches_the_list(c: Int) {} + +/// The I-JSON safe integer range. +#[cfg(creusot)] +#[logic(open)] +pub fn safe_integer(v: Int) -> bool { + pearlite! { -9007199254740991 <= v && v <= 9007199254740991 } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The definition this module replaces, with its bit mask. + fn reference_noncharacter(code_point: u32) -> bool { + if (0xFDD0..=0xFDEF).contains(&code_point) { + return true; + } + if code_point == 0xFFFE || code_point == 0xFFFF { + return true; + } + code_point <= 0x10FFFF && (code_point & 0xFFFF) >= 0xFFFE + } + + /// Every value from 0 to U+10FFFF and well beyond agrees with the old + /// definition and with the list in the Unicode standard: exactly 66. + #[test] + fn noncharacters_are_the_66_listed_ones() { + let mut listed: Vec = (0xFDD0..=0xFDEF).collect(); + for plane in 0..=16u32 { + listed.push(plane * 0x1_0000 + 0xFFFE); + listed.push(plane * 0x1_0000 + 0xFFFF); + } + listed.sort_unstable(); + assert_eq!(listed.len(), 66); + let mut found = Vec::new(); + for code_point in 0..=0x20_FFFFu32 { + let got = is_noncharacter(code_point); + assert_eq!(got, reference_noncharacter(code_point), "{code_point:#X}"); + if got { + found.push(code_point); + } + } + assert_eq!(found, listed); + for beyond in [0x11_FFFE, 0x11_FFFF, 0xFFFF_FFFE, u32::MAX] { + assert!(!is_noncharacter(beyond), "{beyond:#X}"); + } + } + + /// The safe range ends exactly at ±(2^53 − 1). + #[test] + fn safe_integer_boundaries() { + let max = (1i64 << 53) - 1; + assert_eq!(SAFE_MAGNITUDE, max as u64); + for (value, safe) in [ + (0, true), + (max, true), + (-max, true), + (max + 1, false), + (-max - 1, false), + (i64::MAX, false), + (i64::MIN, false), + ] { + assert_eq!(is_safe_i64(value), safe, "{value}"); + } + for (value, safe) in [ + (0, true), + (max as u64, true), + (max as u64 + 1, false), + (u64::MAX, false), + ] { + assert_eq!(is_safe_u64(value), safe, "{value}"); + } + } +} diff --git a/src/lib.rs b/src/lib.rs index b904831..a644867 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -68,6 +68,7 @@ mod error; mod ijson; +mod ijson_core; mod jcs; mod jcs_core; mod jsonld; diff --git a/verification/PROOF-STATUS.adoc b/verification/PROOF-STATUS.adoc index 52911e2..05c5ef6 100644 --- a/verification/PROOF-STATUS.adoc +++ b/verification/PROOF-STATUS.adoc @@ -340,4 +340,119 @@ Receipt for what was executed (2026-12-01, this section's change): Census for this section: 9 obligations. `PROVEN` 0, `PROVEN-WITH-AXIOMS` 0, `TESTED` 3 (J-3, J-5, J-9), `ASSUMED` 0, `OPEN` 6. Assumptions: 5, all `ASSUMED`. +== `src/strict.rs`, `src/ijson.rs` and `src/ijson_core.rs`: the reader + +Same state as the section above: *no verifier has been run*, every proof row +is `OPEN`, no grade is claimed. This section refines the plan table for +`parse_jcs` earlier in this file; where the two differ, this one is current. + +What exists: + +* `src/ijson_core.rs`: the noncharacter predicate and the safe-integer + predicates, dependency-free, with Pearlite contracts behind `cfg(creusot)` + and included by path in `verification/creusot`. `is_noncharacter` now uses + `% 0x10000` instead of `& 0xFFFF`, so the contract needs no bit-vector + reasoning. +* `verification/verus/reader_model.rs`: a Verus model of the predicates, of + bounded traversal and of duplicate-key rejection. A model, not the + production code, and not a second independent witness (policy §1.2). + +Why the rest is not annotated in place: `StrictVisitor` implements +`serde::de::Visitor` and is driven by `serde_json::Deserializer`, and +`validate_value` recurses over `serde_json::Value`. Creusot needs a contract +for that protocol and a logical model of `Value` and `Map` before any of those +functions can carry a meaningful postcondition. Both are trust boundaries +(A-1), so the model has to be written as `#[trusted]` specifications and +recorded as `ASSUMED`. That work is the next action for R-3 to R-6. + +[cols="3,3,3,1,3",options="header"] +|=== +|Obligation |Creusot / Pearlite scope |Verus scope |Status |Reason / evidence + +|R-1 `is_noncharacter` returns exactly the 66 noncharacters, terminates, +cannot panic +|Creusot on `src/ijson_core.rs::is_noncharacter`; Pearlite `noncharacter`, +`noncharacter_listed`, lemma `noncharacter_matches_the_list` +|`noncharacter`, `noncharacter_listed`, proof `noncharacter_matches_the_list` +|`TESTED` +|Proof not run. `noncharacters_are_the_66_listed_ones` is exhaustive over +0..=0x20FFFF, which contains every code point, plus four larger values; 3 +planted mutants fail it. + +|R-2 `is_safe_i64` and `is_safe_u64` decide ±(2^53−1) +|Creusot on both; Pearlite `safe_integer` +|`safe_integer`, proof `safe_integer_is_below_two_to_the_53` +|`TESTED` +|Proof not run. Boundary test `safe_integer_boundaries` (11 values, not +exhaustive); 2 planted mutants fail it. + +|R-3 Termination of `validate_value` with variant on the value, and the +bound: a container at depth `MAX_DEPTH` (128) is refused +|Variant and contract on `ijson::validate_value`; needs the `Value` model (A-1) +|`accepts` with `decreases tree`; the exact-bound lemma is not written +|`TESTED` +|Proof not written on the production function. Tests: +`constructed_values_are_depth_bounded_before_serialization`, +`binary64_reader_array_nesting_boundary`. + +|R-4 Duplicate rejection before insertion, at any depth +|Contract on `StrictVisitor::visit_map`: an error is returned before +`map.insert` when `map.contains_key(&key)`; needs the `MapAccess` protocol (A-1) +|`read_keys` and proof `read_keys_accepts_exactly_distinct` +|`TESTED` +|Proof not run and not written on the production function. Tests in +`strict.rs`, `tests/binary64_reader.rs` and the duplicate-key proptests. + +|R-5 Panic-freedom of `parse_jcs`, `parse_json`, the visitor and +`validate_value` +|Creusot on those entry points, relative to A-1 +|Not modelled +|`OPEN` +|Not run. `check_integer_tokens` indexes `bytes[i]` under the precondition +that the text already parsed; the precondition holds at its two call sites but +is not stated as a contract. Option: make the scan total by bounds-checking, +which removes the precondition. + +|R-6 Accepted language is the JSON grammar restricted to I-JSON and finite +binary64 +|Contract on `parse_jcs` against a grammar model +|Grammar model, not written +|`OPEN` +|Not started. The grammar is serde_json's (A-1). + +|R-7 Under a build where another crate enables `serde_json/arbitrary_precision` +the strict readers refuse to parse +|None: a property of the dependency graph, not of this code alone +|None +|`TESTED` +|`tests/feature_unification.rs`, run in both configurations (pull request +50). Without that change the readers emit a number as an object. +|=== + +Trust boundary added by this section: + +[cols="1,4,1",options="header"] +|=== +|Id |Assumption |Status +|A-6 |serde 1.x `Visitor`, `MapAccess` and `SeqAccess` protocol as driven by +serde_json 1.x: `deserialize_any` calls exactly one `visit_*`; `next_key` +yields each member name once, in order, with escapes decoded; the recursion +limit refuses the 128th nested container; `end()` refuses trailing text |`ASSUMED` +|A-7 |serde_json is built without `arbitrary_precision` (checked at run time, +see R-7) |`ASSUMED` +|=== + +Receipt for what was executed (2026-12-01): `cargo test --locked --lib +ijson_core` (2 tests pass; 5 planted mutants each fail one), `cargo test +--manifest-path verification/creusot/Cargo.toml` (pearlite-syn 0.15.0 parses +7 contract terms in `src/ijson_core.rs` and 6 in `controls.rs`), rustc 1.99.1. +No Creusot, Why3, Verus, Kani, Z3 or CVC5 was run. + +Census for this section: 7 obligations. `PROVEN` 0, `PROVEN-WITH-AXIOMS` 0, +`TESTED` 5 (R-1, R-2, R-3, R-4, R-7), `ASSUMED` 0, `OPEN` 2 (R-5, R-6). +Assumptions: 2, both `ASSUMED`. + +Whole ledger, the two sections J and R: 16 obligations. `PROVEN` 0, +`PROVEN-WITH-AXIOMS` 0, `TESTED` 8, `ASSUMED` 0, `OPEN` 8. Assumptions: 7. + Canonical policy: metadatastician/standards `3-practice/PROOF-POLICY.adoc`. diff --git a/verification/creusot/SCOPE b/verification/creusot/SCOPE index 106e542..9be0245 100644 --- a/verification/creusot/SCOPE +++ b/verification/creusot/SCOPE @@ -4,3 +4,4 @@ # listed here is missing or is not included by verification/creusot/src/lib.rs, # so the verified scope cannot silently become empty. src/jcs_core.rs +src/ijson_core.rs diff --git a/verification/creusot/src/controls.rs b/verification/creusot/src/controls.rs index 052cdc4..19c9e9e 100644 --- a/verification/creusot/src/controls.rs +++ b/verification/creusot/src/controls.rs @@ -49,3 +49,18 @@ pub fn false_control_ordering(a: &[u8], b: &[u8]) -> Ordering { pub fn false_control_literal(s: &[u8], out: &mut Vec) { write_string_literal(s, out); } + +/// TRUE control: the production contract of `is_noncharacter`, restated. +#[cfg_attr(creusot, check(terminates))] +#[cfg_attr(creusot, ensures(result == crate::ijson_core::noncharacter(code_point@)))] +pub fn true_control_noncharacter(code_point: u32) -> bool { + crate::ijson_core::is_noncharacter(code_point) +} + +/// FALSE control: claims U+FFFE is the only noncharacter. Must be refused. +#[cfg(feature = "false-control")] +#[cfg_attr(creusot, check(terminates))] +#[cfg_attr(creusot, ensures(result == (code_point@ == 0xFFFE)))] +pub fn false_control_noncharacter(code_point: u32) -> bool { + crate::ijson_core::is_noncharacter(code_point) +} diff --git a/verification/creusot/src/lib.rs b/verification/creusot/src/lib.rs index 0b5b87a..872de31 100644 --- a/verification/creusot/src/lib.rs +++ b/verification/creusot/src/lib.rs @@ -7,4 +7,7 @@ #[path = "../../../src/jcs_core.rs"] pub mod jcs_core; +#[path = "../../../src/ijson_core.rs"] +pub mod ijson_core; + pub mod controls; diff --git a/verification/creusot/tests/contracts_parse.rs b/verification/creusot/tests/contracts_parse.rs index e222cbf..fd401b7 100644 --- a/verification/creusot/tests/contracts_parse.rs +++ b/verification/creusot/tests/contracts_parse.rs @@ -89,7 +89,11 @@ fn contracts_in(relative: &str) -> Contracts { /// `verification/PROOF-STATUS.adoc`, so a contract cannot vanish unnoticed. #[test] fn every_contract_is_well_formed_pearlite() { - for (file, expected) in [("../../src/jcs_core.rs", 33), ("src/controls.rs", 4)] { + for (file, expected) in [ + ("../../src/jcs_core.rs", 33), + ("../../src/ijson_core.rs", 7), + ("src/controls.rs", 6), + ] { let contracts = contracts_in(file); assert!( contracts.failures.is_empty(), diff --git a/verification/verus/reader_model.rs b/verification/verus/reader_model.rs new file mode 100644 index 0000000..0469596 --- /dev/null +++ b/verification/verus/reader_model.rs @@ -0,0 +1,185 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Hyperpolymath Estate +// +// Verus MODEL of the I-JSON reader: predicates, bounded traversal and +// duplicate-key rejection. +// +// NOT RUN. No Verus result exists for this file; it has not been parsed by +// Verus. Every row it supports is `OPEN` in verification/PROOF-STATUS.adoc. +// +// This is a model, written separately from `src/strict.rs` and +// `src/ijson.rs`. A Verus result on it is not a proof of that code, and it is +// not a second independent witness beside the Pearlite contracts +// (PROOF-POLICY §1.2): one author, shared definitions, SMT on both sides. +// +// The production reader is a `serde::de::Visitor` driven by +// `serde_json::Deserializer`. That protocol is the trust boundary; the model +// below replaces it with plain data (a tree, a sequence of keys). + +use vstd::prelude::*; + +verus! { + +// --------------------------------------------------------------- predicates + +/// Same definition as Pearlite `noncharacter` in `src/ijson_core.rs`. +pub open spec fn noncharacter(c: int) -> bool { + (0xFDD0 <= c <= 0xFDEF) || (0 <= c <= 0x10FFFF && c % 0x10000 >= 0xFFFE) +} + +/// The Unicode standard's list: 32 in the BMP block, two per plane. +pub open spec fn noncharacter_listed(c: int) -> bool { + (0xFDD0 <= c <= 0xFDEF) || (exists|plane: int| + 0 <= plane <= 16 && (c == plane * 0x10000 + 0xFFFE || c == plane * 0x10000 + 0xFFFF)) +} + +/// R-1. The arithmetic form is the list. +pub proof fn noncharacter_matches_the_list(c: int) + ensures + noncharacter(c) == noncharacter_listed(c), +{ + if 0 <= c <= 0x10FFFF && c % 0x10000 >= 0xFFFE { + let plane = c / 0x10000; + assert(0 <= plane <= 16); + assert(c == plane * 0x10000 + c % 0x10000); + } +} + +/// Same definition as Pearlite `safe_integer`. +pub open spec fn safe_integer(v: int) -> bool { + -9007199254740991 <= v <= 9007199254740991 +} + +/// R-2. Every safe integer is exactly representable in binary64: its +/// magnitude is below 2^53. (That 2^53 integers are exact is IEEE 754, not +/// proved here.) +pub proof fn safe_integer_is_below_two_to_the_53(v: int) + requires + safe_integer(v), + ensures + -0x20000000000000 < v < 0x20000000000000, +{ +} + +// ------------------------------------------------------- bounded traversal + +/// A JSON value with only its shape: scalars and containers. +pub enum Tree { + Scalar, + Container(Seq), +} + +pub open spec const MAX_DEPTH: nat = 128; + +/// Model of `validate_value`: a container at depth `MAX_DEPTH` or deeper is +/// refused; otherwise every child is validated one level down. The +/// `decreases` clause is the termination variant the production function +/// needs: the tree gets smaller on every call. +pub open spec fn accepts(tree: Tree, depth: nat) -> bool + decreases tree, +{ + match tree { + Tree::Scalar => true, + Tree::Container(children) => depth < MAX_DEPTH && forall|i: int| + 0 <= i < children.len() ==> accepts(#[trigger] children[i], depth + 1), + } +} + +/// Nesting depth of a tree: 0 for a scalar. +pub open spec fn height(tree: Tree) -> nat + decreases tree, +{ + match tree { + Tree::Scalar => 0, + Tree::Container(children) => 1 + max_height(children), + } +} + +pub open spec fn max_height(children: Seq) -> nat + decreases children, +{ + if children.len() == 0 { + 0 + } else { + let rest = max_height(children.drop_last()); + let last = height(children.last()); + if last > rest { last } else { rest } + } +} + +// R-3 (not written): accepts(tree, 0) <==> height(tree) <= MAX_DEPTH. This is +// the statement that the bound is exactly 128 containers, as +// `constructed_values_are_depth_bounded_before_serialization` tests. + +// ------------------------------------------------ duplicate-key rejection + +/// Model of `visit_map`: read keys in order; refuse at the first key already +/// seen, before inserting it. `Some(set)` is the key set on success. +pub open spec fn read_keys(keys: Seq>) -> Option>> + decreases keys.len(), +{ + if keys.len() == 0 { + Some(Set::empty()) + } else { + match read_keys(keys.drop_last()) { + None => None, + Some(seen) => if seen.contains(keys.last()) { + None + } else { + Some(seen.insert(keys.last())) + }, + } + } +} + +pub open spec fn distinct(keys: Seq>) -> bool { + forall|i: int, j: int| 0 <= i < j < keys.len() ==> keys[i] != keys[j] +} + +/// R-4. The reader accepts exactly the key sequences with no repeat, and on +/// success the set holds exactly the keys read. +pub proof fn read_keys_accepts_exactly_distinct(keys: Seq>) + ensures + read_keys(keys).is_some() <==> distinct(keys), + read_keys(keys).is_some() ==> forall|k: Seq| + read_keys(keys).unwrap().contains(k) <==> keys.contains(k), + decreases keys.len(), +{ + if keys.len() > 0 { + let init = keys.drop_last(); + read_keys_accepts_exactly_distinct(init); + if read_keys(init).is_some() { + let seen = read_keys(init).unwrap(); + if seen.contains(keys.last()) { + let i = choose|i: int| 0 <= i < init.len() && init[i] == keys.last(); + assert(keys[i] == keys[keys.len() - 1]); + } else { + assert forall|i: int, j: int| 0 <= i < j < keys.len() implies keys[i] != keys[j] by { + if j == keys.len() - 1 { + assert(init.contains(init[i])); + } else { + assert(init[i] != init[j]); + } + } + assert forall|k: Seq| + read_keys(keys).unwrap().contains(k) <==> keys.contains(k) by { + if keys.contains(k) { + let i = choose|i: int| 0 <= i < keys.len() && keys[i] == k; + if i < init.len() { + assert(init.contains(init[i])); + } + } + if seen.contains(k) { + let i = choose|i: int| 0 <= i < init.len() && init[i] == k; + assert(keys[i] == k); + } + } + } + } else { + let (i, j) = choose|i: int, j: int| 0 <= i < j < init.len() && init[i] == init[j]; + assert(keys[i] == keys[j]); + } + } +} + +} // verus!