diff --git a/.gitignore b/.gitignore index 3a67cde..ba2d884 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ # Generated by Cargo /target +/verification/creusot/target # IDE .idea diff --git a/.proven/coverage-exclusions.tsv b/.proven/coverage-exclusions.tsv index 4ffe176..20b9812 100644 --- a/.proven/coverage-exclusions.tsv +++ b/.proven/coverage-exclusions.tsv @@ -11,6 +11,7 @@ src/ijson.rs 221-224 afced9dbdd974f8cf35d6d3aedbcbd87996442c0cac6277c28ebd267228 src/ijson.rs 234 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) src/jsonld.rs 89-92 402488d41ddef455de57876a02b952263b009c7276aad704a0651f11073670e3 unreachable JCS output is built from UTF-8 strings and ASCII escapes, so from_utf8 cannot fail src/strict.rs 45-47 10cec3347de43875134bcc80b462ce19cbe071095b3c736c864bd4d4c98ebf0e unreachable Visitor::expecting is only called for a type mismatch; serde_json's deserialize_any always picks the matching visit_* method src/strict.rs 187 1e7485fbef031241f6cabf64563ef6f5973ecf51e927241b2147bff185decac8 unreachable a comma at nesting depth 0 is impossible in text that has already parsed as JSON diff --git a/Cargo.toml b/Cargo.toml index d79dbae..c2a3bdf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -41,3 +41,7 @@ all-features = true [[bench]] name = "jcs" harness = false + +[lints.rust] +# `cfg(creusot)` is set only by the Creusot harness in verification/creusot. +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(creusot)'] } diff --git a/src/jcs.rs b/src/jcs.rs index de6f563..d4a4a26 100644 --- a/src/jcs.rs +++ b/src/jcs.rs @@ -42,10 +42,10 @@ // changing the canonical output for their manifest format. use serde_json::Value; -use std::cmp::Ordering; use crate::error::CanonicalizationError; use crate::ijson::{self, SAFE_INT_MAX, SAFE_INT_MIN, SAFE_UINT_MAX}; +use crate::jcs_core; /// Canonicalize a JSON value to JCS format (RFC 8785) /// @@ -150,16 +150,9 @@ pub(crate) fn es_number_to_string(f: f64) -> Result) { - // serde_json::to_string produces RFC 8259 compliant string escaping - // which matches JCS requirements for the code points we care about - let escaped = serde_json::to_string(s).expect("String is always serializable"); - // The escaped string will be in quotes, but we want just the content - // Actually, serde_json::to_string on a string value returns the quoted string - out.extend_from_slice(escaped.as_bytes()); + jcs_core::write_string_literal(s.as_bytes(), out); } /// Write an array in JCS format @@ -190,9 +183,7 @@ fn write_object_jcs( out.push(b','); } - // Write the key (with quotes and escaping via serde_json) - let key_str = serde_json::to_string(key).expect("Key is always serializable"); - out.extend_from_slice(key_str.as_bytes()); + write_string_jcs(key, out); out.push(b':'); // Write the value @@ -208,15 +199,10 @@ fn write_object_jcs( /// UTF-16 code unit order of their keys." /// /// This is NOT the same as simple string comparison for non-ASCII keys. -/// For ASCII-only keys (which is the common case), this behaves the same -/// as lexicographic comparison. +/// The comparison never ties on distinct keys, and the keys of one object +/// are distinct, so the result does not depend on the sort being stable. fn sort_keys_utf16(keys: &mut [&String]) { - keys.sort_by(|a, b| utf16_code_unit_cmp(a, b)); -} - -/// Compare two strings by UTF-16 code unit order -fn utf16_code_unit_cmp(a: &str, b: &str) -> Ordering { - a.encode_utf16().cmp(b.encode_utf16()) + keys.sort_by(|a, b| jcs_core::cmp_utf16(a.as_bytes(), b.as_bytes())); } #[cfg(test)] diff --git a/src/jcs_core.rs b/src/jcs_core.rs new file mode 100644 index 0000000..b379946 --- /dev/null +++ b/src/jcs_core.rs @@ -0,0 +1,478 @@ +//! SPDX-License-Identifier: MPL-2.0 +//! Copyright (c) 2026 Hyperpolymath Estate +//! +//! First-party byte-level core of JCS: key ordering and string escaping. +// +// This file is compiled twice from the same bytes: by this crate, and by the +// Creusot harness in `verification/creusot`, which includes it by path. It +// therefore depends on nothing but `core` and `Vec`, and every contract is +// behind `cfg(creusot)`, so an ordinary build sees plain Rust. +// +// STATUS: the contracts below have NOT been run through Creusot. They are +// written against creusot-std 0.15.0 and are `OPEN` in +// `verification/PROOF-STATUS.adoc` until the pinned prover image discharges +// them. The behaviour is `TESTED` by the differential tests at the end of +// this file. +// +// Both functions work on the UTF-8 bytes of a Rust `str`. That the bytes are +// well-formed UTF-8 is a Rust invariant of `str`, not something proved here. + +use core::cmp::Ordering; + +#[cfg(creusot)] +use creusot_std::prelude::*; + +// --------------------------------------------------------------------------- +// Key ordering (RFC 8785 §3.2.3: UTF-16 code-unit order) +// --------------------------------------------------------------------------- +// +// UTF-8 byte order is code-point order. UTF-16 code-unit order differs from +// it in exactly one way: a supplementary-plane character (lead surrogate +// D800..DBFF) sorts *before* U+E000..U+FFFF. In UTF-8 the supplementary +// characters have lead bytes F0..F4 and U+E000..U+FFFF have lead bytes EE and +// EF, and no continuation byte is that large. So UTF-16 order is plain +// lexicographic byte order after one permutation of the byte values EE..F4, +// which moves F0..F4 below EE and EF. + +/// The sort key of one UTF-8 byte: a permutation of `u8` that moves the +/// supplementary-plane lead bytes `F0..=F4` below `EE` and `EF`. +#[cfg_attr(creusot, check(terminates))] +#[cfg_attr(creusot, ensures(result@ == order_key(b)))] +pub(crate) fn utf16_order_key(b: u8) -> u8 { + if b < 0xEE { + b + } else if b < 0xF0 { + b + 5 + } else if b < 0xF5 { + b - 2 + } else { + b + } +} + +/// Compare two UTF-8 byte strings in UTF-16 code-unit order. +/// +/// Returns `Equal` only for identical byte strings, so distinct keys are +/// never tied and a sort by this comparison has exactly one result. +#[cfg_attr(creusot, check(terminates))] +#[cfg_attr(creusot, ensures(result == Ordering::Equal ==> a@ == b@))] +#[cfg_attr(creusot, ensures(result == Ordering::Less ==> key_less(a@, b@)))] +#[cfg_attr(creusot, ensures(result == Ordering::Greater ==> key_less(b@, a@)))] +pub(crate) fn cmp_utf16(a: &[u8], b: &[u8]) -> Ordering { + let shorter = if a.len() < b.len() { a.len() } else { b.len() }; + let mut i = 0; + #[cfg_attr(creusot, variant(shorter@ - i@))] + #[cfg_attr(creusot, invariant(i@ <= shorter@))] + #[cfg_attr(creusot, invariant(forall 0 <= j && j < i@ ==> a@[j] == b@[j]))] + while i < shorter { + let x = utf16_order_key(a[i]); + let y = utf16_order_key(b[i]); + if x < y { + return Ordering::Less; + } + if x > y { + return Ordering::Greater; + } + i += 1; + } + // One is a prefix of the other: the shorter sorts first. + a.len().cmp(&b.len()) +} + +// --------------------------------------------------------------------------- +// String escaping (RFC 8785 §3.2.2.2) +// --------------------------------------------------------------------------- + +/// The lower-case hexadecimal digit for `d`, which must be below 16. +#[cfg_attr(creusot, check(terminates))] +#[cfg_attr(creusot, requires(d@ < 16))] +#[cfg_attr(creusot, ensures(result == hex_digit(d@)))] +fn hex_digit_byte(d: u8) -> u8 { + if d < 10 { b'0' + d } else { b'a' + (d - 10) } +} + +/// Append the JCS serialisation of one string byte to `out`. +/// +/// `"` and `\` get a backslash; U+0008, U+0009, U+000A, U+000C and U+000D +/// use their two-character escapes; every other byte below 0x20 is written +/// as `\u00xx` in lower-case hexadecimal; all other bytes, including every +/// byte of a multi-byte UTF-8 sequence, are copied unchanged. +#[cfg_attr(creusot, check(terminates))] +#[cfg_attr(creusot, ensures((^out)@ == out@.concat(escaped_byte(b))))] +fn write_escaped_byte(b: u8, out: &mut Vec) { + if b == b'"' { + out.push(b'\\'); + out.push(b'"'); + } else if b == b'\\' { + out.push(b'\\'); + out.push(b'\\'); + } else if b >= 0x20 { + out.push(b); + } else if b == 0x08 { + out.push(b'\\'); + out.push(b'b'); + } else if b == 0x09 { + out.push(b'\\'); + out.push(b't'); + } else if b == 0x0A { + out.push(b'\\'); + out.push(b'n'); + } else if b == 0x0C { + out.push(b'\\'); + out.push(b'f'); + } else if b == 0x0D { + out.push(b'\\'); + out.push(b'r'); + } else { + out.push(b'\\'); + out.push(b'u'); + out.push(b'0'); + out.push(b'0'); + if b < 0x10 { + out.push(b'0'); + out.push(hex_digit_byte(b)); + } else { + out.push(b'1'); + out.push(hex_digit_byte(b - 0x10)); + } + } +} + +/// Append `s` to `out` as a JCS string literal, quotes included. +#[cfg_attr(creusot, check(terminates))] +#[cfg_attr(creusot, ensures((^out)@ == out@.concat(string_literal(s@))))] +pub(crate) fn write_string_literal(s: &[u8], out: &mut Vec) { + #[cfg(creusot)] + let before = snapshot!(out@); + out.push(b'"'); + let mut i = 0; + #[cfg_attr(creusot, variant(s@.len() - i@))] + #[cfg_attr(creusot, invariant(i@ <= s@.len()))] + #[cfg_attr(creusot, invariant( + out@ == before.snoc(0x22u8).concat(escaped_bytes(s@.subsequence(0, i@))) + ))] + while i < s.len() { + #[cfg(creusot)] + proof_assert!(s@.subsequence(0, i@ + 1) == s@.subsequence(0, i@).snoc(s@[i@])); + write_escaped_byte(s[i], out); + i += 1; + } + #[cfg(creusot)] + proof_assert!(s@.subsequence(0, i@) == s@); + out.push(b'"'); +} + +// --------------------------------------------------------------------------- +// Pearlite specification (only compiled by Creusot) +// --------------------------------------------------------------------------- + +/// Specification of [`utf16_order_key`]: a permutation of the byte values. +#[cfg(creusot)] +#[logic(open)] +pub fn order_key(b: u8) -> Int { + pearlite! { + if b@ == 0xEE || b@ == 0xEF { + b@ + 5 + } else if 0xF0 <= b@ && b@ <= 0xF4 { + b@ - 2 + } else { + b@ + } + } +} + +/// `a` is below `b` in lexicographic order of [`order_key`]: they agree on a +/// prefix of length `k`, and then `a` ends first or has the smaller key. +#[cfg(creusot)] +#[logic(open)] +pub fn key_less_at(a: Seq, b: Seq, k: Int) -> bool { + pearlite! { + 0 <= k && k <= a.len() && k <= b.len() + && (forall 0 <= j && j < k ==> a[j] == b[j]) + && ((k == a.len() && k < b.len()) + || (k < a.len() && k < b.len() && order_key(a[k]) < order_key(b[k]))) + } +} + +/// The strict order [`cmp_utf16`] decides. +#[cfg(creusot)] +#[logic(open)] +pub fn key_less(a: Seq, b: Seq) -> bool { + pearlite! { exists key_less_at(a, b, k) } +} + +/// [`order_key`] is injective, so equal keys mean equal bytes. +#[cfg(creusot)] +#[logic] +#[ensures(forall order_key(x) == order_key(y) ==> x == y)] +pub fn order_key_injective() {} + +/// The order is irreflexive: no byte string is below itself. +#[cfg(creusot)] +#[logic] +#[ensures(!key_less(a, a))] +pub fn key_less_irreflexive(a: Seq) {} + +/// The order is asymmetric, so `cmp_utf16` cannot answer both ways. +#[cfg(creusot)] +#[logic] +#[ensures(!(key_less(a, b) && key_less(b, a)))] +pub fn key_less_asymmetric(a: Seq, b: Seq) {} + +/// The order is transitive. +#[cfg(creusot)] +#[logic] +#[requires(key_less(a, b) && key_less(b, c))] +#[ensures(key_less(a, c))] +pub fn key_less_transitive(a: Seq, b: Seq, c: Seq) {} + +/// The order is total on distinct byte strings. With the three lemmas above +/// this makes it a strict total order, so a sequence of distinct keys has +/// exactly one sorted arrangement: the canonical member order is unique. +#[cfg(creusot)] +#[logic] +#[ensures(a == b || key_less(a, b) || key_less(b, a))] +pub fn key_less_total(a: Seq, b: Seq) {} + +/// Lower-case hexadecimal digit of a value below 16, as its ASCII byte. +/// Written out by cases so the specification needs no machine arithmetic +/// and no uninterpreted function. +#[cfg(creusot)] +#[logic(open)] +pub fn hex_digit(d: Int) -> u8 { + pearlite! { + if d == 0 { 0x30u8 } else if d == 1 { 0x31u8 } else if d == 2 { 0x32u8 } + else if d == 3 { 0x33u8 } else if d == 4 { 0x34u8 } else if d == 5 { 0x35u8 } + else if d == 6 { 0x36u8 } else if d == 7 { 0x37u8 } else if d == 8 { 0x38u8 } + else if d == 9 { 0x39u8 } else if d == 10 { 0x61u8 } else if d == 11 { 0x62u8 } + else if d == 12 { 0x63u8 } else if d == 13 { 0x64u8 } else if d == 14 { 0x65u8 } + else { 0x66u8 } + } +} + +/// The JCS serialisation of one string byte (RFC 8785 §3.2.2.2). +#[cfg(creusot)] +#[logic(open)] +pub fn escaped_byte(b: u8) -> Seq { + pearlite! { + if b@ == 0x22 { + Seq::singleton(0x5Cu8).snoc(0x22u8) + } else if b@ == 0x5C { + Seq::singleton(0x5Cu8).snoc(0x5Cu8) + } else if b@ >= 0x20 { + Seq::singleton(b) + } else if b@ == 0x08 { + Seq::singleton(0x5Cu8).snoc(0x62u8) + } else if b@ == 0x09 { + Seq::singleton(0x5Cu8).snoc(0x74u8) + } else if b@ == 0x0A { + Seq::singleton(0x5Cu8).snoc(0x6Eu8) + } else if b@ == 0x0C { + Seq::singleton(0x5Cu8).snoc(0x66u8) + } else if b@ == 0x0D { + Seq::singleton(0x5Cu8).snoc(0x72u8) + } else { + unicode_escape(b) + } + } +} + +/// `\u00xx` for a control byte with no two-character escape: the value is +/// below 0x20, so the first hexadecimal digit is `0` or `1`. +#[cfg(creusot)] +#[logic(open)] +pub fn unicode_escape(b: u8) -> Seq { + pearlite! { + Seq::singleton(0x5Cu8).snoc(0x75u8).snoc(0x30u8).snoc(0x30u8) + .snoc(if b@ < 0x10 { 0x30u8 } else { 0x31u8 }) + .snoc(hex_digit(if b@ < 0x10 { b@ } else { b@ - 0x10 })) + } +} + +/// The escaped bytes of a string body, without the quotes. +#[cfg(creusot)] +#[logic(open)] +pub fn escaped_bytes(s: Seq) -> Seq { + pearlite! { s.flat_map(|b: u8| escaped_byte(b)) } +} + +/// A JCS string literal: quote, escaped body, quote. +#[cfg(creusot)] +#[logic(open)] +pub fn string_literal(s: Seq) -> Seq { + pearlite! { Seq::singleton(0x22u8).concat(escaped_bytes(s)).snoc(0x22u8) } +} + +/// The literal is a function of the string alone, and no escaped body +/// contains a raw quote that is not preceded by a backslash, a raw control +/// byte, or a lone backslash. Stated here as the two facts the framing of +/// the output relies on. +#[cfg(creusot)] +#[logic] +#[ensures(forall 0 <= i && i < escaped_byte(b).len() ==> escaped_byte(b)[i]@ >= 0x20)] +#[ensures(escaped_byte(b).len() == 1 ==> escaped_byte(b)[0]@ != 0x22 && escaped_byte(b)[0]@ != 0x5C)] +pub fn escaped_byte_is_framed(b: u8) {} + +// --------------------------------------------------------------------------- +// Differential tests against the previous implementation +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + + /// The definition this module replaces: compare the UTF-16 encodings. + fn reference_cmp(a: &str, b: &str) -> Ordering { + a.encode_utf16().cmp(b.encode_utf16()) + } + + /// The definition this module replaces: serde_json's string serialiser. + fn reference_literal(s: &str) -> Vec { + serde_json::to_string(s).unwrap().into_bytes() + } + + fn literal(s: &str) -> Vec { + let mut out = Vec::new(); + write_string_literal(s.as_bytes(), &mut out); + out + } + + /// Every Unicode scalar value, each as a one-character string, escapes + /// exactly as serde_json escapes it. Exhaustive over 1,112,064 values. + #[test] + fn every_scalar_value_escapes_as_before() { + let mut checked = 0u32; + let mut buffer = [0u8; 4]; + for code in 0..=0x10FFFFu32 { + let Some(ch) = char::from_u32(code) else { + continue; + }; + let s: &str = ch.encode_utf8(&mut buffer); + assert_eq!(literal(s), reference_literal(s), "U+{code:04X}"); + checked += 1; + } + assert_eq!(checked, 0x110000 - 0x800); + } + + /// Escaping is per byte, so a string escapes as its characters do, in + /// order, inside one pair of quotes. + #[test] + fn strings_escape_as_before() { + for s in [ + "", + "plain", + "a\"b\\c\nd", + "\u{0}\u{1f}\u{20}\u{7f}\u{80}", + "\u{8}\u{9}\u{a}\u{b}\u{c}\u{d}\u{e}\u{f}\u{10}\u{1b}", + "\u{20ac}$\u{f}\nA'B\"\\\\\"/", + "\u{d7ff}\u{e000}\u{ffff}\u{10000}\u{10ffff}", + "\u{2028}\u{2029}", + ] { + assert_eq!(literal(s), reference_literal(s), "{s:?}"); + } + let mut out = b"prefix".to_vec(); + write_string_literal(b"x", &mut out); + assert_eq!(out, b"prefix\"x\""); + } + + /// The order key is a permutation of the byte values that keeps every + /// byte outside `EE..=F4` where it is. + #[test] + fn order_key_is_a_permutation() { + let mut seen = [false; 256]; + for b in 0..=255u8 { + let key = utf16_order_key(b); + assert!(!seen[key as usize], "{b:#x} collides"); + seen[key as usize] = true; + assert_eq!(key == b, !(0xEE..=0xF4).contains(&b), "{b:#x}"); + } + } + + /// Scalar values at every boundary that matters: UTF-8 length changes, + /// both sides of the surrogate gap, U+E000..U+FFFF, and the planes. + const BOUNDARY: &[u32] = &[ + 0x0, 0x1, 0x22, 0x5C, 0x7F, 0x80, 0x7FF, 0x800, 0xFFF, 0x1000, 0xCFFF, 0xD000, 0xD7FF, + 0xE000, 0xE001, 0xEFFF, 0xF000, 0xFDD0, 0xFFFD, 0xFFFF, 0x10000, 0x10001, 0x1F600, 0x3FFFF, + 0x40000, 0xFFFFF, 0x100000, 0x10FFFE, 0x10FFFF, + ]; + + /// Every scalar value against every boundary value, as one-character + /// strings, in both argument orders: 2 x 1,112,064 x 29 comparisons. + #[test] + fn every_scalar_value_orders_as_before_against_the_boundaries() { + let boundary: Vec = BOUNDARY + .iter() + .map(|code| char::from_u32(*code).unwrap().to_string()) + .collect(); + let mut buffer = [0u8; 4]; + for code in 0..=0x10FFFFu32 { + let Some(ch) = char::from_u32(code) else { + continue; + }; + let s: &str = ch.encode_utf8(&mut buffer); + for other in &boundary { + assert_eq!( + cmp_utf16(s.as_bytes(), other.as_bytes()), + reference_cmp(s, other), + "U+{code:04X} vs {other:?}" + ); + assert_eq!( + cmp_utf16(other.as_bytes(), s.as_bytes()), + reference_cmp(other, s), + "{other:?} vs U+{code:04X}" + ); + } + } + } + + /// All strings of up to three boundary characters, pairwise: prefixes, + /// shared prefixes of every length, and differences at each position. + #[test] + fn short_boundary_strings_order_as_before() { + let alphabet: Vec = [ + 0x0, 0x7F, 0x80, 0x7FF, 0x800, 0xD7FF, 0xE000, 0xFFFF, 0x10000, 0x10FFFF, + ] + .iter() + .map(|code| char::from_u32(*code).unwrap()) + .collect(); + let mut strings = vec![String::new()]; + for length in 1..=3 { + let shorter: Vec = strings + .iter() + .filter(|s| s.chars().count() == length - 1) + .cloned() + .collect(); + for prefix in shorter { + for ch in &alphabet { + let mut next = prefix.clone(); + next.push(*ch); + strings.push(next); + } + } + } + assert_eq!(strings.len(), 1 + 10 + 100 + 1000); + for a in &strings { + for b in &strings { + assert_eq!( + cmp_utf16(a.as_bytes(), b.as_bytes()), + reference_cmp(a, b), + "{a:?} vs {b:?}" + ); + } + } + } + + /// `Equal` is returned for identical byte strings and no others. + #[test] + fn equal_means_identical() { + assert_eq!(cmp_utf16(b"", b""), Ordering::Equal); + assert_eq!(cmp_utf16(b"ab", b"ab"), Ordering::Equal); + assert_eq!(cmp_utf16(b"a", b"ab"), Ordering::Less); + assert_eq!(cmp_utf16(b"ab", b"a"), Ordering::Greater); + // U+10000 (F0 90 80 80) sorts before U+FFFF (EF BF BF) in UTF-16. + assert_eq!( + cmp_utf16("\u{10000}".as_bytes(), "\u{ffff}".as_bytes()), + Ordering::Less + ); + } +} diff --git a/src/lib.rs b/src/lib.rs index 48d2ef9..b904831 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -69,6 +69,7 @@ mod error; mod ijson; mod jcs; +mod jcs_core; mod jsonld; mod profile; mod records; diff --git a/tests/proven_mutation_kills.rs b/tests/proven_mutation_kills.rs index 936aa15..1ea70a7 100644 --- a/tests/proven_mutation_kills.rs +++ b/tests/proven_mutation_kills.rs @@ -277,3 +277,41 @@ fn temporary_name_too_long_is_reported_as_the_os_error() { let _ = fs::remove_dir_all(&base); assert_eq!(outcome, (Some(2), true), "{stdout}"); } + +/// jcs_core.rs: the two-character escapes for U+0008 and U+000C, which no +/// other counted vector contains, beside every other escape class. +#[test] +fn every_escape_class_is_written() { + let value = Value::String("\u{8}\u{c}\t\n\r\u{0}\u{1f}\"\\/\u{7f}\u{e9}".into()); + assert_eq!( + text(&to_jcs(&value).unwrap()), + "\"\\b\\f\\t\\n\\r\\u0000\\u001f\\\"\\\\/\u{7f}\u{e9}\"" + ); +} + +/// jcs_core.rs `cmp_utf16`: keys that are prefixes of one another, mixed with +/// keys whose UTF-16 order differs from their UTF-8 byte order, so the sort +/// compares in both directions and decides by length as well as by byte. +#[test] +fn prefix_keys_and_reordered_keys_sort_together() { + let mut expected = Vec::new(); + // UTF-16 order of the first code unit: 'a' < U+10000 (D800) < U+FFE0. + for prefix in ["a", "\u{10000}", "\u{ffe0}"] { + for length in 0..14 { + expected.push(format!("{prefix}{}", "a".repeat(length))); + } + } + let object: serde_json::Map = expected + .iter() + .map(|key| (key.clone(), Value::Null)) + .collect(); + let want = format!( + "{{{}}}", + expected + .iter() + .map(|key| format!("\"{key}\":null")) + .collect::>() + .join(",") + ); + assert_eq!(text(&to_jcs(&Value::Object(object)).unwrap()), want); +} diff --git a/verification/PROOF-STATUS.adoc b/verification/PROOF-STATUS.adoc index 2251042..4718a41 100644 --- a/verification/PROOF-STATUS.adoc +++ b/verification/PROOF-STATUS.adoc @@ -162,4 +162,149 @@ applicable to `parse_jcs`. A bounded Kani harness on the byte scan in `check_integer_tokens` (indexing after a valid-JSON precondition) is possible later and would be `TESTED` with stated unwinding bounds. +== `src/jcs.rs` and `src/jcs_core.rs`: canonical output + +Owner ruling of 2026-12-01: beta needs real proofs. This section is the +ledger for the canonical writer. *No verifier has been run.* The owner ruled +that provers run from the estate's pinned `hyperpolymath/prover-images`, which +has no Creusot or Verus image yet, so every proof row is `OPEN`. Engineering +proofs are not PWG-graded (policy §8.1); no grade is claimed. + +What exists: + +* `src/jcs_core.rs`: first-party key ordering (`cmp_utf16`) and string + escaping (`write_string_literal`) over UTF-8 bytes. They replace + `str::encode_utf16().cmp()` and `serde_json::to_string`, so both properties + can be proved on shipped code and neither rests on a dependency. +* Pearlite contracts on those functions, behind `cfg(creusot)`, written + against creusot-std 0.15.0. +* `verification/creusot`: a harness crate that includes `src/jcs_core.rs` by + path, with two true controls and two false controls + (`src/controls.rs`, feature `false-control`). +* `verification/verus/jcs_model.rs`: a Verus model of the same definitions. + It is a separately written model, so a Verus result on it is not a proof of + the production code, and it is not a second independent witness: one author, + one specification, SMT solvers on both sides (policy §1.2). + +Statements proved or to be proved, quoted: + +* *Order.* `cmp_utf16(a, b)` returns `Equal` only if `a@ == b@`, `Less` only if + `key_less(a@, b@)`, `Greater` only if `key_less(b@, a@)`, where `key_less` is + lexicographic order on bytes after the permutation `order_key` (it moves + `F0..=F4` below `EE` and `EF`). +* *Escaping.* After `write_string_literal(s, out)`, `out` is its old value + followed by `string_literal(s@)`: a quote, each byte's `escaped_byte`, a quote. + +[cols="3,3,3,1,3",options="header"] +|=== +|Obligation |Creusot / Pearlite scope |Verus scope |Status |Reason / evidence + +|J-1 `cmp_utf16` meets its contract, terminates and cannot panic +|Creusot on `src/jcs_core.rs::cmp_utf16` and `utf16_order_key`; Pearlite +`order_key`, `key_less_at`, `key_less` +|`cmp_utf16_model` in the model (re-implementation) +|`OPEN` +|Not run: no Creusot or Verus image. Contracts parse (see receipt below). + +|J-2 `key_less` is a strict total order on byte strings (irreflexive, +asymmetric, transitive, total) +|Pearlite lemmas `order_key_injective`, `key_less_irreflexive`, +`key_less_asymmetric`, `key_less_transitive`, `key_less_total` +|Proof functions V-1a to V-1e +|`OPEN` +|Not run. Lemma bodies are empty on the Creusot side and may need proof +terms once the solver is tried. + +|J-3 `key_less` is UTF-16 code-unit order on well-formed UTF-8 (RFC 8785 §3.2.3) +|Not stated in Pearlite yet: creusot-std's `char::to_utf8` is opaque, so the +statement needs a first-party model of UTF-8 and UTF-16 encoding +|V-6, not written +|`TESTED` +|`jcs_core::tests`: every scalar value (1,112,064) against 29 boundary values +in both orders, and all 1,111 strings of up to 3 characters over 10 boundary +characters pairwise, against `encode_utf16().cmp()`. Bounded: single +characters against a boundary set, and short strings; not all pairs of strings. + +|J-4 `write_string_literal` meets its contract, terminates and cannot panic +|Creusot on `write_string_literal`, `write_escaped_byte`, `hex_digit_byte`; +Pearlite `escaped_byte`, `unicode_escape`, `hex_digit`, `escaped_bytes`, +`string_literal` +|`escaped_byte`, `escaped_bytes`, `string_literal` in the model; no executable +model of the writer +|`OPEN` +|Not run. + +|J-5 `escaped_byte` is the RFC 8785 §3.2.2.2 table +|The Pearlite definition is the specification; agreement with the RFC is by +reading +|Same definition in the model (`hex_digit` is arithmetic there, by cases in +Pearlite) +|`TESTED` +|`every_scalar_value_escapes_as_before`: exhaustive over all 1,112,064 scalar +values against serde_json 1.x, which the RFC 8785 vectors already exercised. +The domain is complete for one character; longer strings follow from the +writer being per byte, which is J-4. + +|J-6 Members are written in strictly increasing `key_less` order +|Not annotated: `write_object_jcs` works on `serde_json::Map` and calls +`slice::sort_by` +|V-5, not written +|`OPEN` +|creusot-std 0.15.0 has no contract for `sort_by`. Rests on J-2 and on +A-3. Option put to the owner: check the order after sorting (a proved linear +scan) instead of trusting the sort. + +|J-7 Byte determinism: `to_jcs` output depends only on the value, not on +map iteration order +|Follows from J-2 (one sorted arrangement of distinct keys), J-6 and A-1 +|V-3 (literal only), V-5 not written +|`OPEN` +|Not run. `TESTED` evidence: `test_insertion_order_does_not_matter`, proptests +in `tests/proven_properties.rs` (sampled). + +|J-8 Idempotence: `to_jcs(parse_jcs(to_jcs(v))) == to_jcs(v)` +|Statement over `to_jcs` and `parse_jcs`; needs A-1 and A-2 +|V-4 proves it from the round-trip hypothesis only +|`OPEN` +|Not run. `TESTED` evidence: canonical idempotence proptests on the strict +input domain (sampled). + +|J-9 Number rendering over finite binary64 +|`write_number_jcs`: integers in ±(2^53−1) through `i64::to_string`, every +other number through ryu-js. Nothing first-party to prove beyond the branch +choice +|Not modelled +|`TESTED` +|RFC 8785 Appendix B vectors and a proptest over random bit patterns +(`tests/rfc8785.rs`). Rests on A-2 and A-4. +|=== + +Trust boundaries for this section (policy §1.1): + +[cols="1,4,1",options="header"] +|=== +|Id |Assumption |Status +|A-1 |serde_json 1.x: `Value`, `Map` (distinct keys, `keys()` yields each +once), `Number::as_i64`, `as_u64`, `as_f64`; and its tokenizer for the reader |`ASSUMED` +|A-2 |ryu-js 1.0.x `Buffer::format_finite` returns ECMAScript +`Number::toString` for every finite double |`ASSUMED` +|A-3 |Rust std `slice::sort_by` returns a permutation ordered by the +comparator when the comparator is a total order |`ASSUMED` +|A-4 |Rust std `i64::to_string` is the decimal numeral |`ASSUMED` +|A-5 |A Rust `str` is well-formed UTF-8 (language invariant) |`ASSUMED` +|=== + +Receipt for what was executed (2026-12-01, this section's change): + +* `cargo test --manifest-path verification/creusot/Cargo.toml`: pearlite-syn + 0.15.0 parses all 33 contract terms in `src/jcs_core.rs` and all 4 in + `verification/creusot/src/controls.rs`; three malformed terms are refused. + This is a syntax check. It does not type-check the contracts. +* `cargo test --locked --lib jcs_core`: 6 differential tests pass; 5 planted + mutants of `src/jcs_core.rs` each fail at least one of them. +* rustc 1.99.1. No Creusot, Why3, Verus, Z3 or CVC5 was run. + +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`. + Canonical policy: metadatastician/standards `3-practice/PROOF-POLICY.adoc`. diff --git a/verification/creusot/Cargo.lock b/verification/creusot/Cargo.lock new file mode 100644 index 0000000..8899ded --- /dev/null +++ b/verification/creusot/Cargo.lock @@ -0,0 +1,235 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "creusot-std" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c258fc3bed45edeb0509fce569f66565cae19b583d24a827faaa4e1abe51d2b" +dependencies = [ + "creusot-std-proc", +] + +[[package]] +name = "creusot-std-proc" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "848b1d0c5b674f9eb80e144602ab64d8ddcef5033d60a07a5be112b1c931d029" +dependencies = [ + "pearlite-syn", + "proc-macro2", + "quote", + "syn 2.0.119", + "uuid", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", +] + +[[package]] +name = "ijson-jcs-creusot" +version = "0.0.0" +dependencies = [ + "creusot-std", + "pearlite-syn", + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "pearlite-syn" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff7afb8267bb550980a04ce048a1f1592af3741fab76d1b364678696efbe2570" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "uuid" +version = "1.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" +dependencies = [ + "getrandom", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] diff --git a/verification/creusot/Cargo.toml b/verification/creusot/Cargo.toml new file mode 100644 index 0000000..735b82c --- /dev/null +++ b/verification/creusot/Cargo.toml @@ -0,0 +1,39 @@ +# SPDX-License-Identifier: MPL-2.0 +# Creusot harness for ijson-jcs. Not part of the shipped crate and never +# published. It includes production source files by path, so the verifier +# reads the same bytes the library is built from. +# +# creusot-std is LGPL-2.1-or-later. It is a verification-only dependency of +# this harness and is not linked into ijson-jcs. + +[package] +name = "ijson-jcs-creusot" +version = "0.0.0" +edition = "2024" +publish = false +license = "MPL-2.0" + +[lib] +path = "src/lib.rs" +# The included production file carries its own unit tests, which need the +# main crate's dev-dependencies and are run there. +test = false +doctest = false + +[features] +# Adds contracts that are false. The proof gate runs the verifier once with +# this feature and requires it to refuse them. +false-control = [] + +[dependencies] +creusot-std = "=0.15.0" + +[dev-dependencies] +pearlite-syn = "=0.15.0" +proc-macro2 = "1" +syn = { version = "2", features = ["full", "visit", "extra-traits"] } + +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(creusot)'] } + +[workspace] diff --git a/verification/creusot/src/controls.rs b/verification/creusot/src/controls.rs new file mode 100644 index 0000000..052cdc4 --- /dev/null +++ b/verification/creusot/src/controls.rs @@ -0,0 +1,51 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Hyperpolymath Estate +// +// Controls for the proof gate. A gate that only ever sees goals the verifier +// accepts shows nothing, so the gate runs the verifier twice: +// +// * without `false-control`: every goal, including the true controls, must +// be discharged; +// * with `false-control`: the verifier must refuse, and the refused goals +// must be the two functions marked FALSE below and nothing else. +// +// NOT RUN: no Creusot result exists for this file yet. + +use core::cmp::Ordering; + +#[cfg(creusot)] +use creusot_std::prelude::*; + +use crate::jcs_core::{cmp_utf16, write_string_literal}; +#[cfg(creusot)] +use crate::jcs_core::{escaped_bytes, key_less, string_literal}; + +/// TRUE control: a consequence of the production contract of `cmp_utf16`. +#[cfg_attr(creusot, check(terminates))] +#[cfg_attr(creusot, ensures(result == Ordering::Less ==> key_less(a@, b@)))] +pub fn true_control_ordering(a: &[u8], b: &[u8]) -> Ordering { + cmp_utf16(a, b) +} + +/// TRUE control: the production contract of `write_string_literal`, restated. +#[cfg_attr(creusot, check(terminates))] +#[cfg_attr(creusot, ensures((^out)@ == out@.concat(string_literal(s@))))] +pub fn true_control_literal(s: &[u8], out: &mut Vec) { + write_string_literal(s, out); +} + +/// FALSE control: claims the opposite direction of the order. Must be refused. +#[cfg(feature = "false-control")] +#[cfg_attr(creusot, check(terminates))] +#[cfg_attr(creusot, ensures(result == Ordering::Less ==> key_less(b@, a@)))] +pub fn false_control_ordering(a: &[u8], b: &[u8]) -> Ordering { + cmp_utf16(a, b) +} + +/// FALSE control: claims the literal has no quotes. Must be refused. +#[cfg(feature = "false-control")] +#[cfg_attr(creusot, check(terminates))] +#[cfg_attr(creusot, ensures((^out)@ == out@.concat(escaped_bytes(s@))))] +pub fn false_control_literal(s: &[u8], out: &mut Vec) { + write_string_literal(s, out); +} diff --git a/verification/creusot/src/lib.rs b/verification/creusot/src/lib.rs new file mode 100644 index 0000000..0b5b87a --- /dev/null +++ b/verification/creusot/src/lib.rs @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Hyperpolymath Estate +// +// Creusot harness: the production module is included by path, not copied. +#![allow(dead_code)] + +#[path = "../../../src/jcs_core.rs"] +pub mod jcs_core; + +pub mod controls; diff --git a/verification/creusot/tests/contracts_parse.rs b/verification/creusot/tests/contracts_parse.rs new file mode 100644 index 0000000..e222cbf --- /dev/null +++ b/verification/creusot/tests/contracts_parse.rs @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: MPL-2.0 +// Copyright (c) 2026 Hyperpolymath Estate +// +// Syntax check only. Every contract, loop invariant, variant, `pearlite!` +// body, `proof_assert!` and `snapshot!` in the files Creusot will read is +// parsed with pearlite-syn, the parser Creusot's own macros use. This runs on +// stable Rust without the verifier. +// +// It shows that the contracts are well-formed Pearlite for this version. It +// does not type-check them and proves nothing about the code. + +use std::path::Path; + +use pearlite_syn::Term; +use proc_macro2::TokenStream; +use syn::visit::{self, Visit}; + +const SPEC_ATTRIBUTES: [&str; 4] = ["requires", "ensures", "invariant", "variant"]; +const SPEC_MACROS: [&str; 3] = ["pearlite", "proof_assert", "snapshot"]; + +#[derive(Default)] +struct Contracts { + parsed: usize, + failures: Vec, +} + +impl Contracts { + fn check(&mut self, kind: &str, tokens: TokenStream) { + let text = tokens.to_string(); + match syn::parse2::(tokens) { + Ok(_) => self.parsed += 1, + Err(error) => self.failures.push(format!("{kind}: {error}: {text}")), + } + } + + /// `#[ensures(T)]`, or `#[cfg_attr(creusot, ensures(T))]`. + fn attribute(&mut self, attribute: &syn::Attribute) { + let syn::Meta::List(list) = &attribute.meta else { + return; + }; + if list.path.is_ident("cfg_attr") { + let nested = list.parse_args_with(|input: syn::parse::ParseStream| { + let _condition: syn::Meta = input.parse()?; + let _: syn::Token![,] = input.parse()?; + input.parse::() + }); + if let Ok(syn::Meta::List(inner)) = nested { + self.spec(&inner); + } + } else { + self.spec(list); + } + } + + fn spec(&mut self, list: &syn::MetaList) { + for name in SPEC_ATTRIBUTES { + if list.path.is_ident(name) { + self.check(name, list.tokens.clone()); + } + } + } +} + +impl<'ast> Visit<'ast> for Contracts { + fn visit_attribute(&mut self, attribute: &'ast syn::Attribute) { + self.attribute(attribute); + } + + fn visit_macro(&mut self, mac: &'ast syn::Macro) { + for name in SPEC_MACROS { + if mac.path.is_ident(name) { + self.check(name, mac.tokens.clone()); + } + } + visit::visit_macro(self, mac); + } +} + +fn contracts_in(relative: &str) -> Contracts { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join(relative); + let source = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{relative}: {e}")); + let file = syn::parse_file(&source).unwrap_or_else(|e| panic!("{relative}: {e}")); + let mut contracts = Contracts::default(); + contracts.visit_file(&file); + contracts +} + +/// Each file's contracts parse, and the count is the one recorded in +/// `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)] { + let contracts = contracts_in(file); + assert!( + contracts.failures.is_empty(), + "{file}:\n{}", + contracts.failures.join("\n") + ); + assert_eq!(contracts.parsed, expected, "{file}: contract count changed"); + } +} + +/// False control for this check: malformed Pearlite is refused. +#[test] +fn malformed_pearlite_is_refused() { + for bad in [ + "forall 0 <= j ==> ==> a[j] == b[j]", + "result == ==> x", + "exists int { + if b == 0xEE || b == 0xEF { + b as int + 5 + } else if 0xF0 <= b && b <= 0xF4 { + b as int - 2 + } else { + b as int + } +} + +pub open spec fn key_less_at(a: Seq, b: Seq, k: int) -> bool { + &&& 0 <= k <= a.len() + &&& k <= b.len() + &&& forall|j: int| 0 <= j < k ==> a[j] == b[j] + &&& ((k == a.len() && k < b.len()) + || (k < a.len() && k < b.len() && order_key(a[k]) < order_key(b[k]))) +} + +pub open spec fn key_less(a: Seq, b: Seq) -> bool { + exists|k: int| key_less_at(a, b, k) +} + +/// V-1a. The key is injective on bytes. +pub proof fn order_key_injective(x: u8, y: u8) + requires + order_key(x) == order_key(y), + ensures + x == y, +{ +} + +/// V-1b. Irreflexive. +pub proof fn key_less_irreflexive(a: Seq) + ensures + !key_less(a, a), +{ +} + +/// V-1c. Asymmetric: the two witnesses cannot both exist. +pub proof fn key_less_asymmetric(a: Seq, b: Seq) + ensures + !(key_less(a, b) && key_less(b, a)), +{ + if key_less(a, b) && key_less(b, a) { + let k1 = choose|k: int| key_less_at(a, b, k); + let k2 = choose|k: int| key_less_at(b, a, k); + if k1 < k2 { + assert(b[k1] == a[k1]); + } else if k2 < k1 { + assert(a[k2] == b[k2]); + } + assert(false); + } +} + +/// V-1d. Transitive: the earlier of the two witnesses is a witness. +pub proof fn key_less_transitive(a: Seq, b: Seq, c: Seq) + requires + key_less(a, b), + key_less(b, c), + ensures + key_less(a, c), +{ + let k1 = choose|k: int| key_less_at(a, b, k); + let k2 = choose|k: int| key_less_at(b, c, k); + let k = if k1 <= k2 { k1 } else { k2 }; + assert forall|j: int| 0 <= j < k implies a[j] == c[j] by { + assert(a[j] == b[j]); + assert(b[j] == c[j]); + } + assert(key_less_at(a, c, k)); +} + +/// V-1e. Total on distinct byte strings. +pub proof fn key_less_total(a: Seq, b: Seq) + ensures + a == b || key_less(a, b) || key_less(b, a), + decreases a.len(), +{ + if a.len() == 0 || b.len() == 0 { + if a.len() == 0 && b.len() == 0 { + assert(a =~= b); + } else if a.len() == 0 { + assert(key_less_at(a, b, 0)); + } else { + assert(key_less_at(b, a, 0)); + } + } else if a[0] != b[0] { + order_key_injective(a[0], b[0]); + if order_key(a[0]) < order_key(b[0]) { + assert(key_less_at(a, b, 0)); + } else { + assert(key_less_at(b, a, 0)); + } + } else { + let at = a.subrange(1, a.len() as int); + let bt = b.subrange(1, b.len() as int); + key_less_total(at, bt); + if at == bt { + assert(a =~= b); + } else if key_less(at, bt) { + let k = choose|k: int| key_less_at(at, bt, k); + assert forall|j: int| 0 <= j < k + 1 implies a[j] == b[j] by { + if j > 0 { + assert(at[j - 1] == bt[j - 1]); + } + } + assert(key_less_at(a, b, k + 1)); + } else { + let k = choose|k: int| key_less_at(bt, at, k); + assert forall|j: int| 0 <= j < k + 1 implies b[j] == a[j] by { + if j > 0 { + assert(bt[j - 1] == at[j - 1]); + } + } + assert(key_less_at(b, a, k + 1)); + } + } +} + +/// Model of `cmp_utf16`. A re-implementation, not the production function. +pub fn cmp_utf16_model(a: &[u8], b: &[u8]) -> (result: core::cmp::Ordering) + ensures + result == core::cmp::Ordering::Equal ==> a@ == b@, + result == core::cmp::Ordering::Less ==> key_less(a@, b@), + result == core::cmp::Ordering::Greater ==> key_less(b@, a@), +{ + let shorter = if a.len() < b.len() { a.len() } else { b.len() }; + let mut i: usize = 0; + while i < shorter + invariant + i <= shorter, + shorter <= a.len(), + shorter <= b.len(), + forall|j: int| 0 <= j < i ==> a@[j] == b@[j], + decreases shorter - i, + { + let x = order_key_model(a[i]); + let y = order_key_model(b[i]); + if x < y { + assert(key_less_at(a@, b@, i as int)); + return core::cmp::Ordering::Less; + } + if x > y { + assert(key_less_at(b@, a@, i as int)); + return core::cmp::Ordering::Greater; + } + proof { + order_key_injective(a@[i as int], b@[i as int]); + } + i += 1; + } + if a.len() < b.len() { + assert(key_less_at(a@, b@, i as int)); + core::cmp::Ordering::Less + } else if a.len() > b.len() { + assert(key_less_at(b@, a@, i as int)); + core::cmp::Ordering::Greater + } else { + assert(a@ =~= b@); + core::cmp::Ordering::Equal + } +} + +pub fn order_key_model(b: u8) -> (result: u8) + ensures + result as int == order_key(b), +{ + if b < 0xEE { + b + } else if b < 0xF0 { + b + 5 + } else if b < 0xF5 { + b - 2 + } else { + b + } +} + +// ---------------------------------------------------------------- escaping + +pub open spec fn hex_digit(d: int) -> u8 { + if d < 10 { + (0x30 + d) as u8 + } else { + (0x61 + (d - 10)) as u8 + } +} + +pub open spec fn unicode_escape(b: u8) -> Seq { + seq![ + 0x5Cu8, + 0x75u8, + 0x30u8, + 0x30u8, + if b < 0x10 { 0x30u8 } else { 0x31u8 }, + hex_digit(if b < 0x10 { b as int } else { b as int - 0x10 }), + ] +} + +pub open spec fn escaped_byte(b: u8) -> Seq { + if b == 0x22 { + seq![0x5Cu8, 0x22u8] + } else if b == 0x5C { + seq![0x5Cu8, 0x5Cu8] + } else if b >= 0x20 { + seq![b] + } else if b == 0x08 { + seq![0x5Cu8, 0x62u8] + } else if b == 0x09 { + seq![0x5Cu8, 0x74u8] + } else if b == 0x0A { + seq![0x5Cu8, 0x6Eu8] + } else if b == 0x0C { + seq![0x5Cu8, 0x66u8] + } else if b == 0x0D { + seq![0x5Cu8, 0x72u8] + } else { + unicode_escape(b) + } +} + +pub open spec fn escaped_bytes(s: Seq) -> Seq + decreases s.len(), +{ + if s.len() == 0 { + Seq::::empty() + } else { + escaped_bytes(s.drop_last()) + escaped_byte(s.last()) + } +} + +pub open spec fn string_literal(s: Seq) -> Seq { + seq![0x22u8] + escaped_bytes(s) + seq![0x22u8] +} + +/// V-2. No escaped byte is a raw control character, and a byte that is +/// copied through unchanged is neither a quote nor a backslash. +pub proof fn escaped_byte_is_framed(b: u8) + ensures + forall|i: int| 0 <= i < escaped_byte(b).len() ==> escaped_byte(b)[i] >= 0x20, + escaped_byte(b).len() == 1 ==> escaped_byte(b)[0] != 0x22 && escaped_byte(b)[0] != 0x5C, +{ +} + +// ------------------------------------------------- determinism, idempotence + +/// V-3. Byte determinism of the literal: equal strings, equal bytes. Trivial +/// for a spec function, stated so the property has a named place. +pub proof fn string_literal_is_a_function(s: Seq, t: Seq) + requires + s == t, + ensures + string_literal(s) == string_literal(t), +{ +} + +/// V-4. Idempotence, relative to the reader. `canon` and `parse` are +/// uninterpreted here; the hypothesis is the round trip that +/// `PROOF-STATUS.adoc` records as `ASSUMED` (serde_json and ryu-js). +pub uninterp spec fn canon(value: int) -> Seq; + +pub uninterp spec fn parse(text: Seq) -> int; + +pub proof fn canon_is_idempotent(value: int) + requires + parse(canon(value)) == value, + ensures + canon(parse(canon(value))) == canon(value), +{ +} + +} // verus!