diff --git a/.github/workflows/verus.yml b/.github/workflows/verus.yml index 496ec33b8..8c2b7abfb 100644 --- a/.github/workflows/verus.yml +++ b/.github/workflows/verus.yml @@ -37,6 +37,7 @@ jobs: echo "${z3_sha256} z3.zip" | sha256sum --check --strict unzip -q z3.zip echo "$PWD/z3-4.16.0-x64-glibc-2.39/bin" >> "$GITHUB_PATH" + echo "VERUS_Z3_PATH=$PWD/z3-4.16.0-x64-glibc-2.39/bin/z3" >> "$GITHUB_ENV" - name: Cache cargo uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: @@ -45,8 +46,8 @@ jobs: shell: bash run: | set -euxo pipefail - asset_url=https://github.com/verus-lang/verus/releases/download/release%2F0.2026.09.06.8dea4a2/verus-0.2026.09.06.8dea4a2-x86-linux.zip - asset_sha256=13d01e134c0620c3b29770874707d16c33b3d227c843a489c8ceb744d43c0a16 + asset_url=https://github.com/verus-lang/verus/releases/download/release%2F0.2026.10.04.426d8b0/verus-0.2026.10.04.426d8b0-x86-linux.zip + asset_sha256=624018662868563a7bec0dd07be5e4dd0c3d61124b4b55105765884bf2d4d1a0 test -n "$asset_url" curl -fsSL "$asset_url" -o verus.zip @@ -103,3 +104,6 @@ jobs: cargo verus --help cargo fetch --locked cargo verus verify --locked + # Regorus's history host proofs (history_host) only compile with `history`. + cargo verus verify --locked --features history + cargo verus verify --locked --no-default-features --features history,arc,std diff --git a/.gitignore b/.gitignore index 174ef0274..3c1dca9c1 100644 --- a/.gitignore +++ b/.gitignore @@ -33,6 +33,8 @@ docs/plans/ # C# build folders **bin +# Binary test fixtures are loaded with include_bytes!. +!tests/fixtures/*.bin **obj bindings/csharp/.nuget/ diff --git a/Cargo.lock b/Cargo.lock index 7f44b6b85..fad93f892 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -160,6 +160,15 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "bumpus" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4c9b8b9784c2d50bdb1bd4b79f9ffdc6c0429a25ffe037256cd290163df76ab" +dependencies = [ + "vstd", +] + [[package]] name = "bytecount" version = "0.6.9" @@ -540,6 +549,12 @@ dependencies = [ "num-bigint 0.4.8", ] +[[package]] +name = "frunk_core" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bd3c9ba2e323e8b19e77f15873f60974a7d82f89b80e50c53be44b8b92927c1" + [[package]] name = "futures-core" version = "0.3.34" @@ -638,6 +653,16 @@ dependencies = [ "foldhash", ] +[[package]] +name = "hashconsius" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21c73564712559671ce277a551b0d5259fdb883949525d6381a8e0e9a098701e" +dependencies = [ + "bumpus", + "vstd", +] + [[package]] name = "heck" version = "0.5.0" @@ -650,6 +675,42 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" +[[package]] +name = "history-semantics" +version = "0.1.0" +dependencies = [ + "history-store", + "history-syntax", + "junco-core", + "smallvec", + "thiserror", + "vstd", +] + +[[package]] +name = "history-store" +version = "0.1.0" +dependencies = [ + "bumpus", + "hashconsius", + "history-syntax", + "junco-core", + "lru", + "parking_lot 0.13.0", + "smallvec", + "spin 0.12.3", + "vstd", +] + +[[package]] +name = "history-syntax" +version = "0.1.0" +dependencies = [ + "frunk_core", + "serde", + "vstd", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -908,6 +969,19 @@ dependencies = [ "zmij", ] +[[package]] +name = "junco-core" +version = "0.1.0" +dependencies = [ + "history-syntax", + "postcard", + "serde", + "serde_json", + "smallvec", + "thiserror", + "vstd", +] + [[package]] name = "lazy_static" version = "1.5.1" @@ -964,6 +1038,9 @@ name = "lru" version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a9f71e3591c7ec44d3e563e87bf14ddc2bada8519dca046e5b0e560cd004e2d" +dependencies = [ + "hashbrown 0.17.1", +] [[package]] name = "memchr" @@ -1494,10 +1571,14 @@ dependencies = [ "data-encoding", "globset", "hashbrown 0.17.1", + "history-semantics", + "history-store", + "history-syntax", "icu_casemap", "indexmap", "ipnet", "jsonschema", + "junco-core", "lazy_static", "lru", "msvc_spectre_libs", @@ -1640,9 +1721,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.16.4" +version = "1.16.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" +checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" [[package]] name = "spin" @@ -1925,15 +2006,15 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "verus_builtin" -version = "0.0.0-2026-09-06-0133" +version = "0.0.0-2026-09-16-0054" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "856c9979b5ed3b75a2371d8667602da1839ab0cbb3720a2c1c8a182bcdb27cf7" +checksum = "5e4a9e69d45ddbe303075756d3fc2fcc965eb9dc70c80651d0e4458a6af1ed83" [[package]] name = "verus_builtin_macros" -version = "0.0.0-2026-09-06-0133" +version = "0.0.0-2026-09-20-0158" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "466bb5ed102507ccbcd002410e73716c9eb27b602980d81bbd176860ace8a89b" +checksum = "213ca3e8a80925aec251d3f1952a213d6090156b58ad81dccc3a2f1fed77c99f" dependencies = [ "convert_case", "proc-macro2 1.0.107", @@ -1985,9 +2066,9 @@ checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" [[package]] name = "vstd" -version = "0.0.0-2026-09-06-0133" +version = "0.0.0-2026-10-04-0306" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e5391d6f656ab9a485169f7e9fe87d3db1f0a6aa116fcb630dd0bef224170e7" +checksum = "f22e1cad7b5f35642a5a020b25e9b49915066d836bab77f8431bbc80228290a7" dependencies = [ "verus_builtin", "verus_builtin_macros", diff --git a/Cargo.toml b/Cargo.toml index 062e06ec9..a7e8ff97a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,10 @@ [workspace] members = [ + "src/history-semantics", + "src/history-store", + "src/history-syntax", + "src/junco-core", "tests/ensure_no_std", "xtask", ] @@ -42,6 +46,7 @@ hex = ["dep:data-encoding"] http = [] glob = ["dep:globset"] graph = [] +history = ["rvm", "arc", "dep:history-store", "dep:history-semantics", "history-store/runtime", "history-semantics/runtime"] jsonschema = ["dep:jsonschema"] jsonpatch = [] mimalloc = ["dep:mimalloc"] @@ -49,11 +54,11 @@ net = ["dep:ipnet"] no_std = ["lazy_static/spin_no_std"] opa-runtime = [] regex = ["dep:regex"] -cache = ["dep:lru"] +cache = ["dep:lru", "history-semantics?/cache"] rvm = ["dep:postcard", "dep:indexmap"] semver = ["dep:semver"] allocator-memory-limits = ["std", "mimalloc", "mimalloc/allocator-memory-limits"] -std = ["rand/std", "rand/std_rng", "serde_json/std", "indexmap?/std", "msvc_spectre_libs", "dep:parking_lot", "vstd/std" ] +std = ["rand/std", "rand/std_rng", "serde_json/std", "indexmap?/std", "msvc_spectre_libs", "dep:parking_lot", "vstd/std", "junco-core/std", "history-syntax/std", "history-store?/std", "history-semantics?/std" ] time = ["dep:chrono", "dep:chrono-tz"] uuid = ["dep:uuid"] urlquery = ["dep:url", "dep:percent-encoding"] @@ -108,6 +113,10 @@ opa-testutil = [] rand = ["dep:rand"] [dependencies] +junco-core = { path = "src/junco-core", version = "0.1.0", default-features = false, features = ["serde"] } +history-syntax = { path = "src/history-syntax", version = "0.1.0", default-features = false, features = ["serde"] } +history-store = { path = "src/history-store", version = "0.1.0", default-features = false, optional = true } +history-semantics = { path = "src/history-semantics", version = "0.1.0", default-features = false, optional = true } anyhow = { version = "1.0.102", default-features = false } serde = {version = "1.0.150", default-features = false, features = ["derive", "rc", "alloc"] } serde_json = { version = "1.0.150", default-features = false, features = ["alloc", "raw_value"] } @@ -119,7 +128,7 @@ data-encoding = { version = "2.8.0", optional = true, default-features=false, fe num-bigint = { version = "0.5", default-features = false } num-traits = { version = "0.2", default-features = false } parking_lot = { version = "0.13", optional = true } -spin = { version = "0.12.0", default-features = false, features = ["mutex", "spin_mutex"] } +spin = { version = "0.12.0", default-features = false, features = ["mutex", "spin_mutex", "rwlock"] } globset = { version = "0.4.16", features = ["simd-accel"], default-features = false, optional = true } regex = {version = "1.12.3", optional = true, default-features = false } @@ -151,9 +160,11 @@ postcard = { version = "1.1.3", default-features = false, features = ["alloc"], # Keep vstd aligned with the Verus release pinned in .github/workflows/verus.yml. # In no_std builds only the `alloc` feature is used; the crate's `std` feature # additionally enables `vstd/std` (matching vstd's default features). -vstd = { version = "=0.0.0-2026-09-06-0133", default-features = false, features = ["alloc"] } +vstd = { version = "=0.0.0-2026-10-04-0306", default-features = false, features = ["alloc"] } [dev-dependencies] +junco-core = { path = "src/junco-core", default-features = false, features = ["test-util"] } +history-semantics = { path = "src/history-semantics", default-features = false, features = ["test-util"] } anyhow = "1.0.102" cfg-if = "1.0.0" clap = { version = "4.5.53", features = ["derive"] } diff --git a/bindings/ffi/Cargo.lock b/bindings/ffi/Cargo.lock index 51afccb6d..1a22c8b58 100644 --- a/bindings/ffi/Cargo.lock +++ b/bindings/ffi/Cargo.lock @@ -416,6 +416,12 @@ dependencies = [ "num-bigint 0.4.8", ] +[[package]] +name = "frunk_core" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bd3c9ba2e323e8b19e77f15873f60974a7d82f89b80e50c53be44b8b92927c1" + [[package]] name = "futures-core" version = "0.3.34" @@ -501,6 +507,36 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "history-semantics" +version = "0.1.0" +dependencies = [ + "history-store", + "history-syntax", + "junco-core", + "thiserror", + "vstd", +] + +[[package]] +name = "history-store" +version = "0.1.0" +dependencies = [ + "history-syntax", + "junco-core", + "parking_lot 0.13.0", + "vstd", +] + +[[package]] +name = "history-syntax" +version = "0.1.0" +dependencies = [ + "frunk_core", + "serde", + "vstd", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -750,6 +786,16 @@ dependencies = [ "zmij", ] +[[package]] +name = "junco-core" +version = "0.1.0" +dependencies = [ + "history-syntax", + "serde", + "thiserror", + "vstd", +] + [[package]] name = "lazy_static" version = "1.5.1" @@ -1217,10 +1263,14 @@ dependencies = [ "data-encoding", "globset", "hashbrown 0.17.1", + "history-semantics", + "history-store", + "history-syntax", "icu_casemap", "indexmap", "ipnet", "jsonschema", + "junco-core", "lazy_static", "lru", "msvc_spectre_libs", @@ -1626,15 +1676,15 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "verus_builtin" -version = "0.0.0-2026-09-06-0133" +version = "0.0.0-2026-09-16-0054" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "856c9979b5ed3b75a2371d8667602da1839ab0cbb3720a2c1c8a182bcdb27cf7" +checksum = "5e4a9e69d45ddbe303075756d3fc2fcc965eb9dc70c80651d0e4458a6af1ed83" [[package]] name = "verus_builtin_macros" -version = "0.0.0-2026-09-06-0133" +version = "0.0.0-2026-09-20-0158" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "466bb5ed102507ccbcd002410e73716c9eb27b602980d81bbd176860ace8a89b" +checksum = "213ca3e8a80925aec251d3f1952a213d6090156b58ad81dccc3a2f1fed77c99f" dependencies = [ "convert_case", "proc-macro2", @@ -1686,9 +1736,9 @@ checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" [[package]] name = "vstd" -version = "0.0.0-2026-09-06-0133" +version = "0.0.0-2026-10-04-0306" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e5391d6f656ab9a485169f7e9fe87d3db1f0a6aa116fcb630dd0bef224170e7" +checksum = "f22e1cad7b5f35642a5a020b25e9b49915066d836bab77f8431bbc80228290a7" dependencies = [ "verus_builtin", "verus_builtin_macros", diff --git a/bindings/java/Cargo.lock b/bindings/java/Cargo.lock index 17eed7ad0..be10239db 100644 --- a/bindings/java/Cargo.lock +++ b/bindings/java/Cargo.lock @@ -294,6 +294,12 @@ dependencies = [ "num-bigint 0.4.8", ] +[[package]] +name = "frunk_core" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bd3c9ba2e323e8b19e77f15873f60974a7d82f89b80e50c53be44b8b92927c1" + [[package]] name = "futures-core" version = "0.3.34" @@ -373,6 +379,36 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "history-semantics" +version = "0.1.0" +dependencies = [ + "history-store", + "history-syntax", + "junco-core", + "thiserror", + "vstd", +] + +[[package]] +name = "history-store" +version = "0.1.0" +dependencies = [ + "history-syntax", + "junco-core", + "parking_lot 0.13.0", + "vstd", +] + +[[package]] +name = "history-syntax" +version = "0.1.0" +dependencies = [ + "frunk_core", + "serde", + "vstd", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -639,6 +675,16 @@ dependencies = [ "zmij", ] +[[package]] +name = "junco-core" +version = "0.1.0" +dependencies = [ + "history-syntax", + "serde", + "thiserror", + "vstd", +] + [[package]] name = "lazy_static" version = "1.5.1" @@ -1090,9 +1136,13 @@ dependencies = [ "chrono-tz", "data-encoding", "globset", + "history-semantics", + "history-store", + "history-syntax", "indexmap", "ipnet", "jsonschema", + "junco-core", "lazy_static", "lru", "msvc_spectre_libs", @@ -1444,15 +1494,15 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "verus_builtin" -version = "0.0.0-2026-09-06-0133" +version = "0.0.0-2026-09-16-0054" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "856c9979b5ed3b75a2371d8667602da1839ab0cbb3720a2c1c8a182bcdb27cf7" +checksum = "5e4a9e69d45ddbe303075756d3fc2fcc965eb9dc70c80651d0e4458a6af1ed83" [[package]] name = "verus_builtin_macros" -version = "0.0.0-2026-09-06-0133" +version = "0.0.0-2026-09-20-0158" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "466bb5ed102507ccbcd002410e73716c9eb27b602980d81bbd176860ace8a89b" +checksum = "213ca3e8a80925aec251d3f1952a213d6090156b58ad81dccc3a2f1fed77c99f" dependencies = [ "convert_case", "proc-macro2", @@ -1504,9 +1554,9 @@ checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" [[package]] name = "vstd" -version = "0.0.0-2026-09-06-0133" +version = "0.0.0-2026-10-04-0306" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e5391d6f656ab9a485169f7e9fe87d3db1f0a6aa116fcb630dd0bef224170e7" +checksum = "f22e1cad7b5f35642a5a020b25e9b49915066d836bab77f8431bbc80228290a7" dependencies = [ "verus_builtin", "verus_builtin_macros", diff --git a/bindings/python/Cargo.lock b/bindings/python/Cargo.lock index 4bb1ff186..69d8de57d 100644 --- a/bindings/python/Cargo.lock +++ b/bindings/python/Cargo.lock @@ -278,6 +278,12 @@ dependencies = [ "num-bigint 0.4.8", ] +[[package]] +name = "frunk_core" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bd3c9ba2e323e8b19e77f15873f60974a7d82f89b80e50c53be44b8b92927c1" + [[package]] name = "futures-core" version = "0.3.34" @@ -357,6 +363,36 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "history-semantics" +version = "0.1.0" +dependencies = [ + "history-store", + "history-syntax", + "junco-core", + "thiserror", + "vstd", +] + +[[package]] +name = "history-store" +version = "0.1.0" +dependencies = [ + "history-syntax", + "junco-core", + "parking_lot 0.13.0", + "vstd", +] + +[[package]] +name = "history-syntax" +version = "0.1.0" +dependencies = [ + "frunk_core", + "serde", + "vstd", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -574,6 +610,16 @@ dependencies = [ "zmij", ] +[[package]] +name = "junco-core" +version = "0.1.0" +dependencies = [ + "history-syntax", + "serde", + "thiserror", + "vstd", +] + [[package]] name = "lazy_static" version = "1.5.1" @@ -1098,9 +1144,13 @@ dependencies = [ "chrono-tz", "data-encoding", "globset", + "history-semantics", + "history-store", + "history-syntax", "indexmap", "ipnet", "jsonschema", + "junco-core", "lazy_static", "lru", "msvc_spectre_libs", @@ -1425,15 +1475,15 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "verus_builtin" -version = "0.0.0-2026-09-06-0133" +version = "0.0.0-2026-09-16-0054" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "856c9979b5ed3b75a2371d8667602da1839ab0cbb3720a2c1c8a182bcdb27cf7" +checksum = "5e4a9e69d45ddbe303075756d3fc2fcc965eb9dc70c80651d0e4458a6af1ed83" [[package]] name = "verus_builtin_macros" -version = "0.0.0-2026-09-06-0133" +version = "0.0.0-2026-09-20-0158" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "466bb5ed102507ccbcd002410e73716c9eb27b602980d81bbd176860ace8a89b" +checksum = "213ca3e8a80925aec251d3f1952a213d6090156b58ad81dccc3a2f1fed77c99f" dependencies = [ "convert_case", "proc-macro2", @@ -1485,9 +1535,9 @@ checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" [[package]] name = "vstd" -version = "0.0.0-2026-09-06-0133" +version = "0.0.0-2026-10-04-0306" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e5391d6f656ab9a485169f7e9fe87d3db1f0a6aa116fcb630dd0bef224170e7" +checksum = "f22e1cad7b5f35642a5a020b25e9b49915066d836bab77f8431bbc80228290a7" dependencies = [ "verus_builtin", "verus_builtin_macros", diff --git a/bindings/ruby/Cargo.lock b/bindings/ruby/Cargo.lock index dacc4d632..0aa709b92 100644 --- a/bindings/ruby/Cargo.lock +++ b/bindings/ruby/Cargo.lock @@ -301,6 +301,12 @@ dependencies = [ "num-bigint 0.4.8", ] +[[package]] +name = "frunk_core" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bd3c9ba2e323e8b19e77f15873f60974a7d82f89b80e50c53be44b8b92927c1" + [[package]] name = "futures-core" version = "0.3.34" @@ -386,6 +392,36 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "history-semantics" +version = "0.1.0" +dependencies = [ + "history-store", + "history-syntax", + "junco-core", + "thiserror", + "vstd", +] + +[[package]] +name = "history-store" +version = "0.1.0" +dependencies = [ + "history-syntax", + "junco-core", + "parking_lot 0.13.0", + "vstd", +] + +[[package]] +name = "history-syntax" +version = "0.1.0" +dependencies = [ + "frunk_core", + "serde", + "vstd", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -612,6 +648,16 @@ dependencies = [ "zmij", ] +[[package]] +name = "junco-core" +version = "0.1.0" +dependencies = [ + "history-syntax", + "serde", + "thiserror", + "vstd", +] + [[package]] name = "lazy_static" version = "1.5.1" @@ -1153,9 +1199,13 @@ dependencies = [ "chrono-tz", "data-encoding", "globset", + "history-semantics", + "history-store", + "history-syntax", "indexmap", "ipnet", "jsonschema", + "junco-core", "lazy_static", "lru", "msvc_spectre_libs", @@ -1514,15 +1564,15 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "verus_builtin" -version = "0.0.0-2026-09-06-0133" +version = "0.0.0-2026-09-16-0054" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "856c9979b5ed3b75a2371d8667602da1839ab0cbb3720a2c1c8a182bcdb27cf7" +checksum = "5e4a9e69d45ddbe303075756d3fc2fcc965eb9dc70c80651d0e4458a6af1ed83" [[package]] name = "verus_builtin_macros" -version = "0.0.0-2026-09-06-0133" +version = "0.0.0-2026-09-20-0158" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "466bb5ed102507ccbcd002410e73716c9eb27b602980d81bbd176860ace8a89b" +checksum = "213ca3e8a80925aec251d3f1952a213d6090156b58ad81dccc3a2f1fed77c99f" dependencies = [ "convert_case", "proc-macro2", @@ -1574,9 +1624,9 @@ checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" [[package]] name = "vstd" -version = "0.0.0-2026-09-06-0133" +version = "0.0.0-2026-10-04-0306" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e5391d6f656ab9a485169f7e9fe87d3db1f0a6aa116fcb630dd0bef224170e7" +checksum = "f22e1cad7b5f35642a5a020b25e9b49915066d836bab77f8431bbc80228290a7" dependencies = [ "verus_builtin", "verus_builtin_macros", diff --git a/bindings/wasm/Cargo.lock b/bindings/wasm/Cargo.lock index 72863c200..52a2a399f 100644 --- a/bindings/wasm/Cargo.lock +++ b/bindings/wasm/Cargo.lock @@ -284,6 +284,12 @@ dependencies = [ "num-bigint 0.4.8", ] +[[package]] +name = "frunk_core" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bd3c9ba2e323e8b19e77f15873f60974a7d82f89b80e50c53be44b8b92927c1" + [[package]] name = "futures-core" version = "0.3.34" @@ -378,6 +384,36 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" +[[package]] +name = "history-semantics" +version = "0.1.0" +dependencies = [ + "history-store", + "history-syntax", + "junco-core", + "thiserror", + "vstd", +] + +[[package]] +name = "history-store" +version = "0.1.0" +dependencies = [ + "history-syntax", + "junco-core", + "parking_lot 0.13.0", + "vstd", +] + +[[package]] +name = "history-syntax" +version = "0.1.0" +dependencies = [ + "frunk_core", + "serde", + "vstd", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -595,6 +631,16 @@ dependencies = [ "zmij", ] +[[package]] +name = "junco-core" +version = "0.1.0" +dependencies = [ + "history-syntax", + "serde", + "thiserror", + "vstd", +] + [[package]] name = "lazy_static" version = "1.5.1" @@ -1078,9 +1124,13 @@ dependencies = [ "chrono-tz", "data-encoding", "globset", + "history-semantics", + "history-store", + "history-syntax", "indexmap", "ipnet", "jsonschema", + "junco-core", "lazy_static", "lru", "msvc_spectre_libs", @@ -1420,15 +1470,15 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" [[package]] name = "verus_builtin" -version = "0.0.0-2026-09-06-0133" +version = "0.0.0-2026-09-16-0054" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "856c9979b5ed3b75a2371d8667602da1839ab0cbb3720a2c1c8a182bcdb27cf7" +checksum = "5e4a9e69d45ddbe303075756d3fc2fcc965eb9dc70c80651d0e4458a6af1ed83" [[package]] name = "verus_builtin_macros" -version = "0.0.0-2026-09-06-0133" +version = "0.0.0-2026-09-20-0158" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "466bb5ed102507ccbcd002410e73716c9eb27b602980d81bbd176860ace8a89b" +checksum = "213ca3e8a80925aec251d3f1952a213d6090156b58ad81dccc3a2f1fed77c99f" dependencies = [ "convert_case", "proc-macro2", @@ -1480,9 +1530,9 @@ checksum = "5c3082ca00d5a5ef149bb8b555a72ae84c9c59f7250f013ac822ac2e49b19c64" [[package]] name = "vstd" -version = "0.0.0-2026-09-06-0133" +version = "0.0.0-2026-10-04-0306" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e5391d6f656ab9a485169f7e9fe87d3db1f0a6aa116fcb630dd0bef224170e7" +checksum = "f22e1cad7b5f35642a5a020b25e9b49915066d836bab77f8431bbc80228290a7" dependencies = [ "verus_builtin", "verus_builtin_macros", diff --git a/docs/builtins.md b/docs/builtins.md index f9e04fc33..2f0c6f145 100644 --- a/docs/builtins.md +++ b/docs/builtins.md @@ -286,3 +286,130 @@ native `Value`s or using their iterative comparison and output methods. | Builtin | Feature | |----------------------------------------------------------------------------------------------|---------| | [trace](https://www.openpolicyagent.org/docs/latest/policy-reference/#builtin-tracing-trace) | _ | + +## History rules (`history.require` / `history.forbid`, RVM only) + +The opt-in `history` feature lets Rego policies constrain a typed event history. +It implies `rvm` and is not included in the default features or `full-opa`. +Only the RVM compiler lowers these calls; the tree-walking interpreter, and the +RVM compiler without `history`, report an unknown function. Language bindings do +not forward a `history` feature. + +### Rego syntax + +```rego +package approvals +import rego.v1 + +release_after_edit := history.require( + {"action": "release", "principal": actor, "resource": doc}, + [any, {principal == actor, action == "edit", resource == doc}, any], +) +no_remove_after_lock := history.forbid( + {"action": "remove", "resource": doc}, + [any, {action == "lock", resource == doc}, any], +) + +allow if { + release_after_edit + no_remove_after_lock +} +``` + +`history.require(request, language)` is `false` when the staged request matches +`request` and the history is outside `language`; `history.forbid` is `false` when +it is inside. Otherwise, including a nonmatching request, the call is `true`; it +is never undefined. Compose the Boolean with ordinary Rego. + +The request pattern is an object literal keyed by `"principal"`, `"action"`, +and `"resource"`. A string value matches those exact bytes; a variable binds the +request's coordinate for use in the language; `_` or an omitted key matches +anything. Variables may not be named `principal`, `action`, `resource`, or `any`, +and each belongs to one coordinate. + +| Language | Complete histories | +|---|---| +| `any` | All finite histories | +| `[]` | Empty history only | +| `{c == t, ...}` | One event satisfying every comparison | +| `true`, `set()` | One arbitrary event | +| `false` | No histories | +| `[a, b, ...]` | Chronological concatenation | +| `a \| b` | Union | +| `a & b` | Intersection | +| `a - b` | Difference (`a` and not `b`) | +| `star(a)` | Kleene star | + +A comparison is `principal`, `action`, or `resource` with `==` or `!=` against a +string constant or a request variable of the same coordinate. `{}` is an empty +object, not a test; use `set()`. Malformed shapes, unknown names, unbound or +cross-coordinate variables fail RVM compilation with a spanned error. + +Paths are exact raw UTF-8: case, slashes, embedded NULs, and distinct Unicode +encodings remain distinct; there is no normalization or ancestry match. + +Each call compiles to one `HistoryStep` instruction and one row of +`Program::history_tables[0]`. Programs store portable sources (string constants, +not store identifiers) and serialize as format version 7; see the +[instruction reference](rvm/instruction-set.md#history-table-instructions). + +### Native boundary + +Create an `Arc` from `regorus::languages::history_table`. Every +wrapper fronts one process-wide arity-3 store: identities and histories are +shared, so wrappers accept each other's handles and IDs and are not a tenant +isolation boundary. Intern paths per coordinate with `intern(PRINCIPAL, path)`, +`intern(ACTION, path)` and `intern(RESOURCE, path)`, then build an `Event` with +`store.event(&[principal, action, resource])`, which validates arity and domain +membership. Interned paths live for the process; IDs are not recycled. + +Use `store.new_history()`, then `store.append(&history, &events)`, +`store.truncate(&history, len)` and `store.len(&history)`. Compile the policy +with `Compiler::compile_from_policy`. After `vm.load_program(program)`, call +`vm.attach_history(store.clone())`, which interns the program's rule constants, +and `vm.set_history_input(history, request)`, then execute any entry point. +Decisions never append the request. Repeated executions retain the staged input. +Loading another program cancels any suspended execution and clears attachment +and input, not the application's histories. Executing a history rule without +attachment or staged input reports `HistoryContextMissing`; changing either +while an execution is suspended reports `HistoryExecutionActive`. + +### Evaluation + +A decision captures the history's revision and length at its first +`HistoryStep`; later appends are excluded until the next decision. Each dispatch +advances the rule's symbolic-derivative automaton by at most `batch_size` events +of that prefix and repeats at the same PC while events remain, so budgets are +charged per dispatch and suspension keeps the continuation. Intermediate +nullable prefixes do not grant. Truncation changes the revision: resume or +completion reports `HistoryChanged` rather than publishing a stale result. +Rule caching evaluates each history rule at most once per execution. + +Sources are evaluated as DAGs: shared subterms, unused nodes and non-last roots +are never unfolded. Each `HistoryStore` wrapper keeps bounded, Program-keyed +caches of compiled rule graphs and of retained per-history prefixes (keyed by +each history's immutable ID), shared by every VM attached to it. An active +continuation pins its graph, so eviction or graph replacement cannot +reinterpret it. A batch publishes its cursor only after its fallible work +completes; an error keeps the batch-entry cursor. When a lazily built graph +exceeds its 100 KiB payload budget (`HistoryError::GraphBudget`), the rule +retries once per decision on a fresh graph, replayed through bounded +dispatches. Native failures are fatal `VmError::History` errors, never rule +failures; time and memory limits keep the VM's own variants. + +### Proof boundaries + +Verus checks the history crates and Regorus's host adapter +(`cargo verus verify --features history`). Shared specifications live in +`junco-core/src/verify/history_specs.rs` and the semantic algebra in +`history-semantics/src/verify/history_algebra.rs`. Body proofs cover lowering of +owned rules, constant encoding, the numeric compiler and evaluator, the +typed/numeric history correspondence and the cached decision lifecycle: a +successful answer equals the source language's acceptance of the pinned +history prefix. Locking, allocation, clocks, arena destruction, Regorus's +Rego-to-rule lowering and byte-interning adapter, the native facade and +diagnostics, and Eq/Hash coherence of native event types are trusted, not +proved. + +The CI proof configuration (`.github/workflows/verus.yml`) is Rust 1.98.1, +Verus `0.2026.10.04.426d8b0`, Z3 4.16.0 and `vstd = 0.0.0-2026-10-04-0306`. diff --git a/docs/rvm/architecture.md b/docs/rvm/architecture.md index cfe1c149a..b85139c40 100644 --- a/docs/rvm/architecture.md +++ b/docs/rvm/architecture.md @@ -88,6 +88,7 @@ layout is deliberately split: | `needs_runtime_recursion_check: bool` | Flags when `VirtualDataDocumentLookup` requires runtime guards. | Ensures the VM short-circuits recursion before hitting the instruction budget ceiling. | | `needs_recompilation: bool` | Indicates a legacy binary format or unresolved builtin. | Signals the loader to recompile; corrupt current-version sections are errors. | | `rego_v0: bool` | Records whether the policy targeted Rego v0 semantics. | Ensures recompilation preserves language-version behaviour. | +| `history_tables: Vec` | Ordered history rule tables judged by `HistoryStep`. | Each rule is a `RuleMode` plus a portable `FlatPair` source; checked by `validate_limits`. | Binary and JSON program formats support 32 nested containers in literals, rule trees, and metadata annotations. Readers validate nesting during child @@ -100,6 +101,17 @@ Additional helpers such as `Program::add_*`, `Program::update_*`, and `Program::display_instruction_with_params` are used by the compiler and inspection tooling to populate and render the program. +History execution is layered over four in-tree, no_std + alloc crates. +`history-syntax` owns the rule DSL and event model; `junco-core` owns flat +sources, their validation and constant lowering, and the numeric kernel; +`history-store` owns interning, committed histories and graph/cache containers; +`history-semantics` owns normalization, symbolic derivatives and the +cursor-batched `RuleRuntime`. Only `history` enables the store and semantics +runtimes; source validation needs only `junco-core` and `history-syntax`. +Regorus's `rvm::vm::history_tables` adapter keeps the VM continuation, the +Program-keyed table cache (retaining `Arc`) and host clock/memory-limit +translation. + ### Serialization layout The module `src/rvm/program/serialization` writes `Program` instances into a @@ -107,7 +119,7 @@ compact binary envelope that stays forward-compatible within a major format version: 1. **Header**: magic `REGO` bytes followed by `SERIALIZATION_VERSION` (currently - `6`). + `7`). 2. **Section manifest**: four little-endian `u32` lengths for entry points, sources, literals, and the rule tree, plus a single-byte `rego_v0` flag. 3. **Preamble payloads**: each section is encoded with `postcard` using helper @@ -117,11 +129,16 @@ version: `Program` struct serialized via `postcard`; fields skipped by serde (entry points, literals, sources, rule_tree, resolved builtins) are re-inserted from the preamble when the program is reconstructed. +5. **History**: a little-endian `u32` byte length precedes the `postcard` + encoding of `history_tables` and `InstructionData::history_step_params` + (version 7 and later). Version 6 has no history section and decodes + completely with empty history; `HistoryStep` is the last `Instruction` + variant, so version-6 instruction encodings are unchanged. During deserialization the loader checks the header, section lengths, version, and boolean `rego_v0` flag before decoding each section. For the current format, -decode failures, unconsumed bytes within a section, and bytes after the program -core are errors, not empty defaults or `DeserializationResult::Partial`. +decode failures, unconsumed bytes within a section, and bytes after the last +section are errors, not empty defaults or `DeserializationResult::Partial`. The assembled program must also satisfy `Program::validate_limits`; this checks supported table bounds, not full bytecode semantic validity. diff --git a/docs/rvm/instruction-set.md b/docs/rvm/instruction-set.md index 76c1ce727..a40bc9a3f 100644 --- a/docs/rvm/instruction-set.md +++ b/docs/rvm/instruction-set.md @@ -156,6 +156,25 @@ ordering guarantees (arrays), uniqueness (sets) or key/value pairing (objects). --- +## History table instructions + +| Mnemonic | Operands / Params | Behaviour | +| :------- | :---------------- | :-------- | +| `HistoryStep` | `params_index=pN` | Advances one rule by at most `batch_size` events; repeats at the same PC while unfinished, then writes its Boolean to `dest`. Requires feature `history`, otherwise execution reports `HistoryFeatureDisabled`. Native failures are fatal and never absorbed as rule failure. | + +The RVM compiler lowers each Rego `history.require`/`history.forbid` call to one +`HistoryStep` (batch size 256) inside the calling rule's body and appends the +rule to `Program::history_tables[0]`; the listing shows +`HistoryStep table[T].rule[R] batch_size=N dest=rD`. Rules are stored as +portable sources (`RuleMode` plus `FlatPair` from `junco-core`), not +store identifiers. `Program::validate_limits` rejects invalid sources, zero +batch sizes and out-of-range table/rule/parameter references, with or without +the `history` feature. See +[history rules](../builtins.md#history-rules-historyrequire--historyforbid-rvm-only) +for the native API and decision semantics. + +--- + ## Call and return instructions | Mnemonic | Operands / Params | Behaviour | @@ -334,6 +353,9 @@ inside instructions. The VM retrieves tables via `get_*` accessors. | | `result_reg` | Register receiving the final collection. | | | `key_reg` / `value_reg` | Iteration registers (keys optional for arrays/sets). | | | `body_start` / `comprehension_end` | Instruction pointers framing comprehension body and exit. | +| `HistoryStepParams` | `table` / `rule` | Row of `Program::history_tables` judged by the step. | +| | `batch_size` | Maximum events advanced per dispatch (non-zero). | +| | `dest` | Register that receives the rule's Boolean. | All parameter structs derive `Serialize`/`Deserialize` and can be stored inside artifacts. Some contain `Vec` fields; the compiler is responsible for ensuring diff --git a/release-plz.toml b/release-plz.toml index b00b829e7..9ac80e4cf 100644 --- a/release-plz.toml +++ b/release-plz.toml @@ -22,6 +22,34 @@ name = "regorus-mimalloc-sys" publish = true changelog_update = false +[[package]] +name = "history-semantics" +publish = true +changelog_update = false +git_tag_enable = false +git_release_enable = false + +[[package]] +name = "history-store" +publish = true +changelog_update = false +git_tag_enable = false +git_release_enable = false + +[[package]] +name = "history-syntax" +publish = true +changelog_update = false +git_tag_enable = false +git_release_enable = false + +[[package]] +name = "junco-core" +publish = true +changelog_update = false +git_tag_enable = false +git_release_enable = false + [[package]] name = "xtask" release = false diff --git a/src/explain/provenance.rs b/src/explain/provenance.rs index f95656914..d7208f5bf 100644 --- a/src/explain/provenance.rs +++ b/src/explain/provenance.rs @@ -562,6 +562,10 @@ fn writes(program: &Program, instruction: &Instruction) -> [Option; 3] { .map_or([None; 3], |p| { [Some(p.key_reg), Some(p.value_reg), Some(p.result_reg)] }), + HistoryStep { params_index } => data + .history_step_params + .get(usize::from(params_index)) + .map_or([None; 3], |p| [Some(p.dest), None, None]), Return { .. } | AssertEq { .. } | Guard { .. } diff --git a/src/history-semantics/Cargo.toml b/src/history-semantics/Cargo.toml new file mode 100644 index 000000000..bf0fe39aa --- /dev/null +++ b/src/history-semantics/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "history-semantics" +description = "Verified symbolic-derivative evaluation of Regorus history rules" +version = "0.1.0" +edition = "2024" +license = "MIT" +repository = "https://github.com/microsoft/regorus" + +[package.metadata.verus] +verify = true + +[features] +default = [] +runtime = ["junco-core/runtime", "history-store/runtime", "dep:smallvec"] +std = ["junco-core/std", "history-store/std", "history-syntax/std", "vstd/std"] +cache = [] +test-util = ["runtime", "history-store/test-util", "junco-core/test-util"] + +[dependencies] +# Keep aligned with the root crate's vstd pin (.github/workflows/verus.yml). +vstd = { version = "=0.0.0-2026-10-04-0306", default-features = false, features = ["alloc"] } +thiserror = { version = "2", default-features = false } +smallvec = { version = "=1.16.2", default-features = false, optional = true } +junco-core = { path = "../junco-core", version = "0.1.0", default-features = false } +history-store = { path = "../history-store", version = "0.1.0", default-features = false } +history-syntax = { path = "../history-syntax", version = "0.1.0", default-features = false } + +[dev-dependencies] +history-store = { path = "../history-store", default-features = false, features = ["test-util"] } + +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(verus_keep_ghost)'] } diff --git a/src/history-semantics/src/compile.rs b/src/history-semantics/src/compile.rs new file mode 100644 index 000000000..17484c108 --- /dev/null +++ b/src/history-semantics/src/compile.rs @@ -0,0 +1,1540 @@ +#[cfg(verus_keep_ghost)] +use crate::normalize::verify as norm; +use crate::normalize::{RegexNormalize, TestNormalize}; +use crate::progress::CompiledPair; +use crate::runtime::RuleRuntime; +#[cfg(verus_keep_ghost)] +use crate::symbolic::verify as vocab; +use alloc::vec::Vec; +use history_store::graph::{CanonicalStore, RuntimeKernel, allocation}; +use history_store::store::Event as NumericEvent; +use history_syntax::MAX_ARITY; +#[cfg(any(verus_keep_ghost, test))] +use history_syntax::syntax::Component; +use junco_core::errors::HistoryError; +#[cfg(verus_keep_ghost)] +use junco_core::flat::verify as flat; +use junco_core::flat::{FlatHead, FlatPair, FlatRegex, FlatTerm, FlatTest}; +#[cfg(verus_keep_ghost)] +use junco_core::kernel::verify as model; +use junco_core::kernel::*; +use junco_core::limits::Limits; +use junco_core::observation::ObservationWorld; +#[cfg(verus_keep_ghost)] +use junco_core::spec::semantics::resource_error; +#[cfg(verus_keep_ghost)] +use junco_core::verify::history_assumptions::KernelStoreSpec; +#[cfg(verus_keep_ghost)] +use junco_core::verify::history_specs as language; +#[cfg(verus_keep_ghost)] +use verify::*; +use vstd::prelude::*; +#[cfg(verus_keep_ghost)] +verus! { +broadcast use {junco_core::kernel::verify::group_kernel_views, vstd::set::group_set_lemmas}; +} + +#[cfg(verus_keep_ghost)] +verus! { + pub closed spec fn bindings_match(template: FlatPair, request: NumericEvent, bindings: Bindings) -> bool { + language::head_match(head_view(template), request@, bindings@) + } + + pub closed spec fn head_rejects(template: FlatPair, request: NumericEvent) -> bool { + !exists|theta: language::Subst| language::head_match(head_view(template), request@, theta) + } + + pub(crate) proof fn lemma_bindings_match(template: FlatPair, request: NumericEvent, bindings: Bindings) + ensures bindings_match(template, request, bindings) + == language::head_match(head_view(template), request@, bindings@), + { reveal(bindings_match); } + + pub(crate) proof fn lemma_head_rejects(template: FlatPair, request: NumericEvent) + ensures head_rejects(template, request) + == !exists|theta: language::Subst| language::head_match(head_view(template), request@, theta), + { reveal(head_rejects); } +} + +#[verus_verify] +impl RuleRuntime { + /// Return coordinate bindings, or `None` for an arity or constant mismatch. + #[verus_verify] + #[verus_spec(result => ensures match result { + Some(bindings) => bindings_match(*template, *request, bindings), + None => head_rejects(*template, *request), + })] + pub fn bindings(template: &FlatPair, request: &NumericEvent) -> Option { + proof! { reveal(bindings_match); reveal(head_rejects); } + let arity = request.arity(); + if template.head.len() != arity { + return None; + } + let mut slots = [0u64; MAX_ARITY]; + let mut index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant index <= arity <= MAX_ARITY, + arity == request@.len(), template.head@.len() == arity, + forall|i: int| 0 <= i < index ==> language::head_field_match( + template.head@[i]@, request@[i], slots@[i] as nat), + decreases arity - index, + ))] + while index < arity { + let value = request.component(index); + let binding = match Self::bind_head(&template.head[index], value) { + Some(binding) => binding, + None => { + proof! { + assert forall|theta: language::Subst| !language::head_match( + head_view(*template), request@, theta) by { + if language::head_match(head_view(*template), request@, theta) { + assert(language::head_field_match(template.head@[index as int]@, + request@[index as int], theta[index as int])); + } + } + } + return None; + } + }; + slots[index] = binding; + index += 1; + } + let bindings = Bindings::new(&slots[..arity]); + proof! { + assert forall|i: int| 0 <= i < arity implies language::head_field_match( + head_view(*template)[i], request@[i], bindings@[i]) by { + assert(bindings@[i] == slots@[i] as nat); + } + } + Some(bindings) + } + + #[allow( + clippy::missing_const_for_fn, + reason = "Keep the existing operation and its Verus contract unchanged" + )] + #[verus_verify] + #[verus_spec(result => ensures match result { + Some(binding) => language::head_field_match(this@, value as nat, binding as nat), + None => !exists|binding: nat| language::head_field_match(this@, value as nat, binding), + })] + fn bind_head(this: &FlatHead, value: u64) -> Option { + match this { + FlatHead::Any => Some(0), + FlatHead::Constant(expected) if value == *expected => Some(0), + FlatHead::Constant(_) => None, + FlatHead::Bind => Some(value), + } + } +} + +#[verus_verify] +impl CompiledPair { + #[verus_verify] + #[verus_spec(result => ensures + result != Err(HistoryError::WrongHistoryOwner), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + (id as nat) < values@.len() ==> language::no_invariant_failure(result), + (id as nat) < values@.len() + ==> (result matches Err(error) ==> resource_error(error)), + result matches Ok(value) ==> (id as nat) < values@.len() && value == values@[id as int])] + #[allow( + clippy::option_if_let_else, + reason = "Explicit matches preserve the Verus proof structure" + )] + fn lookup(values: &[T], id: u32) -> KernelResult { + let index = match usize::try_from(id) { + Ok(index) => index, + Err(_) => return Err(HistoryError::invariant("source node index overflow")), + }; + proof! { assert(index as nat == id as nat); } + match values.get(index) { + Some(value) => Ok(*value), + None => Err(HistoryError::invariant("invalid source node reference")), + } + } + + #[verus_verify] + #[verus_spec(result => ensures + result != Err(HistoryError::WrongHistoryOwner), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + (forall|i: int| 0 <= i < ids@.len() ==> #[trigger] ids@[i] < values@.len()) + ==> language::no_invariant_failure(result), + (forall|i: int| 0 <= i < ids@.len() ==> #[trigger] ids@[i] < values@.len()) + ==> (result matches Err(error) ==> resource_error(error)), + result matches Ok(found) ==> { + found@.len() == ids@.len() + && forall|i: int| 0 <= i < ids@.len() + ==> #[trigger] ids@[i] < values@.len() && found@[i] == values@[ids@[i] as int] + })] + + fn references( + values: &[T], + ids: &[u32], + world: &mut ObservationWorld, + ) -> KernelResult> { + let mut found = Vec::new(); + allocation(world.try_reserve_vec_exact(&mut found, ids.len()))?; + let mut index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant index <= ids@.len(), found@.len() == index, + forall|i: int| 0 <= i < index + ==> #[trigger] ids@[i] < values@.len() && found@[i] == values@[ids@[i] as int], + decreases ids@.len() - index, + ))] + while index < ids.len() { + let id = match ids.get(index) { + Some(id) => *id, + None => return Err(HistoryError::invariant("missing source reference")), + }; + proof! { assert(id == ids@[index as int]); } + let value = Self::lookup(values, id)?; + proof_decl! { let ghost previous = found@; } + found.push(value); + proof! { + assert(index < usize::MAX); + assert forall|i: int| 0 <= i <= index implies + #[trigger] ids@[i] < values@.len() && found@[i] == values@[ids@[i] as int] by { + if i < index { + assert(found@[i] == previous[i]); + } else { + assert(i == index); + assert(found@[i] == value); + } + } + } + index = index.saturating_add(1); + } + Ok(found) + } + /// Build a fresh graph that may be charged `budget` bytes from immutable numeric source, + /// including after exhaustion. The runtime passes [`junco_core::limits::MAX_GRAPH_BYTES`]. + /// A source DAG and a layout-valid arena budget exclude internal construction errors. + #[allow( + clippy::shadow_unrelated, + reason = "Separate lowering loops retain their proof-local index bindings" + )] + #[verus_verify] + #[verus_spec(result => ensures + result != Err(HistoryError::WrongHistoryOwner), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + (source_dag_wf(*template) || flat::structural_wf(*template)) + && (budget == junco_core::limits::MAX_GRAPH_BYTES + || history_store::graph::verify::construction_layout(budget)) + ==> language::no_invariant_failure(result), + (source_dag_wf(*template) || flat::structural_wf(*template)) + && (budget == junco_core::limits::MAX_GRAPH_BYTES + || history_store::graph::verify::construction_layout(budget)) + ==> (result matches Err(error) ==> resource_error(error)), + result matches Ok(pair) ==> { + crate::progress::verify::pair_wf(pair) + && crate::verify::finite_impl::regex_nf(model::lift_regex(pair.store.graph(), pair.root@)) + && vocab::regex_primitives(model::lift_regex(pair.store.graph(), pair.root@)).subset_of(source_primitives(*template)) + && forall|theta: language::Subst, word: Seq| language::event_wf(theta, theta.len()) + ==> model::regex_lang(pair.store.graph(), theta, pair.root@, word) + == source_regex(*template, template.root as nat, theta, word) + })] + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + #[cfg_attr(verus_keep_ghost, verifier::rlimit(60))] + + pub(crate) fn compile( + template: &FlatPair, + budget: usize, + limits: &mut L, + world: &mut ObservationWorld, + ) -> KernelResult { + proof! { + if flat::structural_wf(*template) { + lemma_structural_source_dag(*template); + } + } + limits.checkpoint().map_err(HistoryError::from)?; + let mut store = if budget == junco_core::limits::MAX_GRAPH_BYTES { + CanonicalStore::new()? + } else { + CanonicalStore::with_budget(budget)? + }; + let mut tests = Vec::new(); + let mut regexes = Vec::new(); + allocation(world.try_reserve_vec_exact(&mut tests, template.tests.len()))?; + allocation(world.try_reserve_vec_exact(&mut regexes, template.regexes.len()))?; + { + let mut kernel = RuntimeKernel { + store: &mut store, + limits, + world, + }; + proof_decl! { let ghost restoration = kernel.restoration(); } + proof! { crate::verify::finite_compile::lemma_compiled_empty(kernel.graph()); assert(tests@ =~= Seq::::empty()); } + let mut index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant index <= template.tests@.len(), tests@.len() == index, + kernel.valid_store(), kernel.errors_are_non_invariant(), model::graph_wf(kernel.graph()), + kernel.errors_are_non_invalid_policy(), + kernel.errors_are_resource(), + kernel.restoration() == restoration, + test_maps(kernel.graph(), *template, tests@), + regex_maps(kernel.graph(), *template, regexes@), regexes@.len() == 0, + crate::verify::finite_compile::compiled_nf(kernel.graph(), tests@, regexes@), + tests_vocabulary(kernel.graph(), *template, tests@), regexes_vocabulary(kernel.graph(), *template, regexes@), + decreases template.tests@.len() - index, + ))] + while index < template.tests.len() { + kernel.checkpoint()?; + let test = match template.tests.get(index) { + Some(test) => test, + None => return Err(HistoryError::invariant("missing numeric test node")), + }; + proof_decl! { let ghost before = kernel.graph(); } + proof_decl! { let ghost mut selected_ids = Seq::::empty(); } + proof! { + assert(*test == template.tests@[index as int]); + if source_dag_wf(*template) { + assert(source_test_dag(*test, index as nat)); + } + } + let id = match test { + FlatTest::Bool(value) => { + if *value { + kernel.constants().test_true + } else { + kernel.constants().test_false + } + } + FlatTest::Atom { + field, + term, + positive, + } => kernel.intern_test(TestView::Atom { + primitive: Primitive::Eq { + field: *field, + term: match term { + FlatTerm::Constant(value) => Term::Constant(*value), + FlatTerm::Variable(field) => Term::Variable(*field), + }, + }, + positive: *positive, + })?, + FlatTest::And(children) => { + let selected = Self::references(&tests, children, kernel.world)?; + proof! { + selected_ids = selected@; + selected_tests_valid(kernel.graph(), *template, tests@, children@, selected@); + } + TestId::connective(&mut kernel, &selected, true)? + } + FlatTest::Or(children) => { + let selected = Self::references(&tests, children, kernel.world)?; + proof! { + selected_ids = selected@; + selected_tests_valid(kernel.graph(), *template, tests@, children@, selected@); + } + TestId::connective(&mut kernel, &selected, false)? + } + }; + proof! { + maps_extend(before, kernel.graph(), *template, tests@, regexes@); + assert(test_correct(kernel.graph(), *template, index as nat, id)) by { + reveal_with_fuel(source_test, 1); + model::lemma_graph_wf_elim(kernel.graph()); + assert forall|theta: language::Subst, event: language::EventView| + language::event_wf(theta, theta.len()) implies + norm::test_truth(kernel.graph(), theta, id@, event) + == source_test(*template, index as nat, theta, event) by { + match test { + FlatTest::Bool(_) | FlatTest::Atom { .. } => { + norm::test_lemma_truth(kernel.graph(), theta, id@, event); + } + FlatTest::And(children) => { + test_connective_transfer(kernel.graph(), *template, tests@, + children@, selected_ids, theta, event, true); + } + FlatTest::Or(children) => { + test_connective_transfer(kernel.graph(), *template, tests@, + children@, selected_ids, theta, event, false); + } + } + } + } + match test { + FlatTest::Bool(_) | FlatTest::Atom { .. } => { + crate::verify::finite_compile::lemma_test_simple_nf(kernel.graph(), id@); + } + FlatTest::And(children) => { + crate::verify::finite_compile::lemma_connective_nf(before, kernel.graph(), tests@, regexes@, + children@, selected_ids, true, id@); + } + FlatTest::Or(children) => { + crate::verify::finite_compile::lemma_connective_nf(before, kernel.graph(), tests@, regexes@, + children@, selected_ids, false, id@); + } + } + lemma_vocabulary_stable(before, kernel.graph(), *template, tests@, regexes@); + model::lemma_graph_wf_elim(kernel.graph()); + assert forall|p: model::Primitive| vocab::test_primitives(model::lift_test(kernel.graph(), id@)).contains(p) + implies source_primitives(*template).contains(p) by { + match test { + FlatTest::Bool(_) => { + reveal_with_fuel(model::lift_test, 1); + reveal_with_fuel(vocab::test_primitives, 1); + assert(!vocab::test_primitives(model::lift_test(kernel.graph(), id@)).contains(p)); + }, + FlatTest::Atom { field, term, .. } => { + reveal_with_fuel(model::lift_test, 1); + reveal_with_fuel(vocab::test_primitives, 1); + assert(p == model::Primitive::Eq(*field, term_view(*term))); + lemma_source_primitive_prefix(*template, template.tests@.len(), p); + assert(exists|j: int| #![trigger template.tests@[j]] 0 <= j < template.tests@.len() && match template.tests@[j] { + FlatTest::Atom { field, term, .. } => p == model::Primitive::Eq(field, term_view(term)), _ => false, + }); + assert(source_primitives(*template).contains(p)); + }, + FlatTest::And(children) => { + vocab::lemma_test_connective_primitives(before, kernel.graph(), selected_ids, true, id@, p); + let j = choose|j: int| 0 <= j < selected_ids.len() + && vocab::test_primitives(model::lift_test(before, selected_ids[j]@)).contains(p); + assert(selected_ids[j] == tests@[children@[j] as int]); + assert(source_primitives(*template).contains(p)); + }, + FlatTest::Or(children) => { + vocab::lemma_test_connective_primitives(before, kernel.graph(), selected_ids, false, id@, p); + let j = choose|j: int| 0 <= j < selected_ids.len() + && vocab::test_primitives(model::lift_test(before, selected_ids[j]@)).contains(p); + assert(selected_ids[j] == tests@[children@[j] as int]); + assert(source_primitives(*template).contains(p)); + }, + } + } + assert(tests_vocabulary(kernel.graph(), *template, tests@.push(id))) by { + assert forall|i: int| 0 <= i < tests@.push(id).len() implies tests@.push(id)[i]@ < kernel.graph().tests.len() + && vocab::test_primitives(model::lift_test(kernel.graph(), tests@.push(id)[i]@)).subset_of(source_primitives(*template)) by { + if i < tests@.len() { assert(tests@.push(id)[i] == tests@[i]); } + else { assert(tests@.push(id)[i] == id); } + } + } + crate::verify::finite_compile::lemma_push_test(before, kernel.graph(), tests@, regexes@, id); + test_push(kernel.graph(), *template, tests@, id); + } + tests.push(id); + index = index.saturating_add(1); + } + let mut index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant index <= template.regexes@.len(), regexes@.len() == index, + kernel.valid_store(), kernel.errors_are_non_invariant(), model::graph_wf(kernel.graph()), + kernel.errors_are_non_invalid_policy(), + kernel.errors_are_resource(), + kernel.restoration() == restoration, + test_maps(kernel.graph(), *template, tests@), tests@.len() == template.tests@.len(), + regex_maps(kernel.graph(), *template, regexes@), + crate::verify::finite_compile::compiled_nf(kernel.graph(), tests@, regexes@), + tests_vocabulary(kernel.graph(), *template, tests@), regexes_vocabulary(kernel.graph(), *template, regexes@), + decreases template.regexes@.len() - index, + ))] + while index < template.regexes.len() { + kernel.checkpoint()?; + let regex = match template.regexes.get(index) { + Some(regex) => regex, + None => return Err(HistoryError::invariant("missing numeric regex node")), + }; + proof_decl! { let ghost before = kernel.graph(); } + proof_decl! { let ghost mut selected_ids = Seq::::empty(); } + proof! { + assert(*regex == template.regexes@[index as int]); + if source_dag_wf(*template) { + assert(flat::regex_wf(*regex, index as nat, template.tests@.len())); + } + } + let id = match regex { + FlatRegex::Empty => kernel.constants().empty, + FlatRegex::All => kernel.constants().all, + FlatRegex::Epsilon => kernel.constants().epsilon, + FlatRegex::Test(test) => { + RegexId::from_test(&mut kernel, Self::lookup(&tests, *test)?)? + } + FlatRegex::Concat(children) => { + let selected = Self::references(®exes, children, kernel.world)?; + proof! { + selected_ids = selected@; + selected_regexes_valid(kernel.graph(), *template, regexes@, children@, selected@); + } + RegexId::concat(&mut kernel, &selected)? + } + FlatRegex::Union(children) => { + let selected = Self::references(®exes, children, kernel.world)?; + proof! { + selected_ids = selected@; + selected_regexes_valid(kernel.graph(), *template, regexes@, children@, selected@); + } + RegexId::set(&mut kernel, &selected, false)? + } + FlatRegex::Intersect(children) => { + let selected = Self::references(®exes, children, kernel.world)?; + proof! { + selected_ids = selected@; + selected_regexes_valid(kernel.graph(), *template, regexes@, children@, selected@); + } + RegexId::set(&mut kernel, &selected, true)? + } + FlatRegex::Star(child) => { + RegexId::star(Self::lookup(®exes, *child)?, &mut kernel)? + } + FlatRegex::Complement(child) => { + RegexId::not(Self::lookup(®exes, *child)?, &mut kernel)? + } + }; + proof! { + maps_extend(before, kernel.graph(), *template, tests@, regexes@); + assert(regex_correct(kernel.graph(), *template, index as nat, id)) by { + reveal_with_fuel(source_regex, 1); + norm::regex_constants(kernel.graph()); + assert forall|theta: language::Subst, word: Seq| + language::event_wf(theta, theta.len()) implies + model::regex_lang(kernel.graph(), theta, id@, word) + == source_regex(*template, index as nat, theta, word) by { + match regex { + FlatRegex::Test(test) => { + assert((*test as nat) < tests@.len()); + assert(test_correct(kernel.graph(), *template, *test as nat, + tests@[*test as int])); + assert(model::regex_lang(kernel.graph(), theta, id@, word) + == source_regex(*template, index as nat, theta, word)); + } + FlatRegex::Concat(children) => { + assert(selected_ids =~= Seq::new(children@.len(), + |i: int| regexes@[children@[i] as int])); + regex_concat_transfer(kernel.graph(), *template, regexes@, children@, + index as nat, theta, word); + assert(model::regex_lang(kernel.graph(), theta, id@, word) + == source_regex(*template, index as nat, theta, word)); + } + FlatRegex::Star(child) => { + regex_star_transfer(kernel.graph(), *template, regexes@, + *child as nat, theta, word); + assert(model::regex_lang(kernel.graph(), theta, id@, word) + == source_regex(*template, index as nat, theta, word)); + } + FlatRegex::Union(children) => { + regex_set_transfer(kernel.graph(), *template, regexes@, + children@, selected_ids, theta, word, false); + assert(model::regex_lang(kernel.graph(), theta, id@, word) + == source_regex(*template, index as nat, theta, word)); + } + FlatRegex::Intersect(children) => { + regex_set_transfer(kernel.graph(), *template, regexes@, + children@, selected_ids, theta, word, true); + assert(model::regex_lang(kernel.graph(), theta, id@, word) + == source_regex(*template, index as nat, theta, word)); + } + FlatRegex::Complement(child) => { + assert((*child as nat) < regexes@.len()); + assert(regex_correct(kernel.graph(), *template, *child as nat, + regexes@[*child as int])); + assert(template.regexes@[index as int] == FlatRegex::Complement(*child)); + assert(source_regex(*template, index as nat, theta, word) + == ((*child as nat) < index && !source_regex(*template, *child as nat, theta, word))); + assert(model::regex_lang(kernel.graph(), theta, id@, word) + == !model::regex_lang(kernel.graph(), theta, regexes@[*child as int]@, word)); + assert(model::regex_lang(kernel.graph(), theta, id@, word) + == source_regex(*template, index as nat, theta, word)); + } + FlatRegex::Empty | FlatRegex::All | FlatRegex::Epsilon => { + assert(model::regex_lang(kernel.graph(), theta, id@, word) + == source_regex(*template, index as nat, theta, word)); + } + } + } + } + match regex { + FlatRegex::Empty | FlatRegex::All | FlatRegex::Epsilon => { + crate::verify::finite_compile::lemma_regex_const_nf(kernel.graph(), id@); + } + FlatRegex::Test(test) => { + crate::verify::finite_compile::lemma_from_test_nf(before, kernel.graph(), tests@, regexes@, *test as int, id@); + } + FlatRegex::Concat(children) => { + crate::verify::finite_compile::lemma_concat_nf(before, kernel.graph(), tests@, regexes@, children@, selected_ids, id@); + } + FlatRegex::Union(children) => { + crate::verify::finite_compile::lemma_set_nf(before, kernel.graph(), tests@, regexes@, children@, selected_ids, false, id@); + } + FlatRegex::Intersect(children) => { + crate::verify::finite_compile::lemma_set_nf(before, kernel.graph(), tests@, regexes@, children@, selected_ids, true, id@); + } + FlatRegex::Star(child) => { + crate::verify::finite_compile::lemma_compiled_regex(before, tests@, regexes@, *child as int); + } + FlatRegex::Complement(child) => { + crate::verify::finite_compile::lemma_not_nf(before, kernel.graph(), tests@, regexes@, *child as int, id@); + } + } + lemma_vocabulary_stable(before, kernel.graph(), *template, tests@, regexes@); + lemma_regex_vocabulary(before, kernel.graph(), *template, tests@, regexes@, *regex, selected_ids, id@); + assert(regexes_vocabulary(kernel.graph(), *template, regexes@.push(id))) by { + assert forall|i: int| 0 <= i < regexes@.push(id).len() implies regexes@.push(id)[i]@ < kernel.graph().regexes.len() + && vocab::regex_primitives(model::lift_regex(kernel.graph(), regexes@.push(id)[i]@)).subset_of(source_primitives(*template)) by { + if i < regexes@.len() { assert(regexes@.push(id)[i] == regexes@[i]); } + else { assert(regexes@.push(id)[i] == id); } + } + } + crate::verify::finite_compile::lemma_push_regex(before, kernel.graph(), tests@, regexes@, id); + regex_push(kernel.graph(), *template, regexes@, id); + } + regexes.push(id); + index = index.saturating_add(1); + } + proof! { + assert(kernel.valid_store()); + assert(model::graph_wf(kernel.graph())); + assert(regex_maps(kernel.graph(), *template, regexes@)); + assert(crate::verify::finite_compile::compiled_nf(kernel.graph(), tests@, regexes@)); + assert(regexes_vocabulary(kernel.graph(), *template, regexes@)); + } + } + proof! { + assert(store.valid_store()); + assert(model::graph_wf(store.graph())); + assert(regex_maps(store.graph(), *template, regexes@)); + assert(crate::verify::finite_compile::compiled_nf(store.graph(), tests@, regexes@)); + } + let root = Self::lookup(®exes, template.root)?; + limits.checkpoint().map_err(HistoryError::from)?; + proof! { + assert(model::graph_wf(store.graph())); + assert(regex_correct(store.graph(), *template, template.root as nat, root)); + crate::verify::finite_compile::lemma_compiled_regex(store.graph(), tests@, regexes@, template.root as int); + assert(vocab::regex_primitives(model::lift_regex(store.graph(), root@)).subset_of(source_primitives(*template))); + } + Ok(CompiledPair::new(store, root)) + } + /// The hot boundary checks coordinate bounds, then performs u64 equality and a checkpoint. + #[allow( + clippy::shadow_unrelated, + reason = "Term fields mirror the matched Verus model variants" + )] + #[verus_verify] + #[verus_spec(result => ensures + result != Err(HistoryError::WrongHistoryOwner), + language::no_invariant_failure(result), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + result matches Err(error) ==> resource_error(error), + result matches Ok(answer) ==> answer == model::primitive_holds(bindings@, primitive@, event@))] + + pub(crate) fn classify( + primitive: Primitive, + event: &NumericEvent, + bindings: &Bindings, + limits: &mut L, + _world: &mut ObservationWorld, + ) -> KernelResult { + limits.checkpoint().map_err(HistoryError::from)?; + let Primitive::Eq { field, term } = primitive; + let index = field.index(); + if index >= event.arity() { + return Ok(false); + } + let left = event.component(index); + // Variables read the request substitution, not another history-event coordinate. + let right = match term { + Term::Constant(value) => value, + Term::Variable(field) => { + let index = field.index(); + if index >= bindings.arity() { + return Ok(false); + } + bindings.get(index) + } + }; + Ok(left == right) + } +} + +#[cfg(verus_keep_ghost)] +pub mod verify { + use super::*; + pub use super::{bindings_match, head_rejects}; + pub(crate) use super::{lemma_bindings_match, lemma_head_rejects}; + use junco_core::verify::history_specs::{EventView, Subst}; + verus! { + broadcast use {junco_core::kernel::verify::group_kernel_views, vstd::set::group_set_lemmas}; + /// Test references must point to earlier nodes; atoms need no head bindings + /// for compilation into a symbolic graph. + pub open spec fn source_test_dag(test: FlatTest, index: nat) -> bool { + match test { + FlatTest::And(children) | FlatTest::Or(children) => + flat::references_before(children@, index), + _ => true, + } + } + + /// Reference well-formedness sufficient for compiling a numeric source DAG. + pub open spec fn source_dag_wf(template: FlatPair) -> bool { + template.root < template.regexes@.len() + && (forall|i: int| 0 <= i < template.tests@.len() ==> + source_test_dag(#[trigger] template.tests@[i], i as nat)) + && (forall|i: int| 0 <= i < template.regexes@.len() ==> + flat::regex_wf(#[trigger] template.regexes@[i], i as nat, template.tests@.len())) + } + + pub proof fn lemma_structural_source_dag(template: FlatPair) + requires flat::structural_wf(template), + ensures source_dag_wf(template), + { + reveal(flat::structural_wf); + reveal(flat::prefix_wf); + assert forall|i: int| 0 <= i < template.tests@.len() implies + source_test_dag(template.tests@[i], i as nat) by { + assert(flat::test_wf(template.head@, template.tests@[i], i as nat)); + reveal(flat::test_wf); + } + } + + #[verifier::opaque] + pub open spec fn source_primitive_prefix(template: FlatPair, n: nat) -> Set + decreases n, + { + if 0 < n <= template.tests@.len() { + let prior = source_primitive_prefix(template, (n - 1) as nat); + match template.tests@[n - 1] { + FlatTest::Atom { field, term, .. } => prior.insert(model::Primitive::Eq(field, term_view(term))), + _ => prior, + } + } else { Set::empty() } + } + + pub open spec fn source_primitives(template: FlatPair) -> Set { + source_primitive_prefix(template, template.tests@.len()) + } + + pub open spec fn source_codes(template: FlatPair, field: Component) -> Set { + crate::symbolic_language::verify::primitive_codes(source_primitives(template), field) + } + + pub proof fn lemma_source_code_member(template: FlatPair, field: Component, value: nat) + requires source_codes(template, field).contains(value), + ensures exists|i: int| #![trigger template.tests@[i]] 0 <= i < template.tests@.len() + && match template.tests@[i] { + FlatTest::Atom { field: f, term: FlatTerm::Constant(v), .. } => f == field && v as nat == value, + _ => false, + }, + { + crate::symbolic_language::verify::lemma_primitive_codes_contains(source_primitives(template), field, value); + let p = model::Primitive::Eq(field, model::GTerm::Constant(value)); + lemma_source_primitive_prefix(template, template.tests@.len(), p); + let i = choose|i: int| #![trigger template.tests@[i]] 0 <= i < template.tests@.len() && match template.tests@[i] { + FlatTest::Atom { field: f, term, .. } => p == model::Primitive::Eq(f, term_view(term)), _ => false, + }; + assert(match template.tests@[i] { + FlatTest::Atom { field: f, term: FlatTerm::Constant(v), .. } => f == field && v as nat == value, + _ => false, + }); + } + + pub proof fn lemma_source_codes_bounded(template: FlatPair, field: Component, bound: nat) + requires forall|i: int| #![trigger template.tests@[i]] 0 <= i < template.tests@.len() ==> match template.tests@[i] { + FlatTest::Atom { field: f, term: FlatTerm::Constant(v), .. } => f != field || v as nat <= bound, + _ => true, + }, + ensures forall|value: nat| source_codes(template, field).contains(value) ==> value <= bound, + { + assert forall|value: nat| source_codes(template, field).contains(value) implies value <= bound by { + lemma_source_code_member(template, field, value); + let i = choose|i: int| #![trigger template.tests@[i]] 0 <= i < template.tests@.len() && match template.tests@[i] { + FlatTest::Atom { field: f, term: FlatTerm::Constant(v), .. } => f == field && v as nat == value, + _ => false, + }; + } + } + + pub proof fn lemma_source_primitive_prefix(template: FlatPair, n: nat, p: model::Primitive) + requires n <= template.tests@.len(), + ensures source_primitive_prefix(template, n).contains(p) == (exists|i: int| #![trigger template.tests@[i]] + 0 <= i < n && match template.tests@[i] { + FlatTest::Atom { field, term, .. } => p == model::Primitive::Eq(field, term_view(term)), + _ => false, + }), + decreases n, + { + reveal_with_fuel(source_primitive_prefix, 1); + if n > 0 { + lemma_source_primitive_prefix(template, (n - 1) as nat, p); + if exists|i: int| #![trigger template.tests@[i]] 0 <= i < n && match template.tests@[i] { + FlatTest::Atom { field, term, .. } => p == model::Primitive::Eq(field, term_view(term)), _ => false, + } { + let i = choose|i: int| #![trigger template.tests@[i]] 0 <= i < n && match template.tests@[i] { + FlatTest::Atom { field, term, .. } => p == model::Primitive::Eq(field, term_view(term)), _ => false, + }; + if i < n - 1 { + assert(exists|j: int| #![trigger template.tests@[j]] 0 <= j < n - 1 && match template.tests@[j] { + FlatTest::Atom { field, term, .. } => p == model::Primitive::Eq(field, term_view(term)), _ => false, + }); + } else { assert(i == n - 1); } + } + if source_primitive_prefix(template, (n - 1) as nat).contains(p) { + let i = choose|i: int| #![trigger template.tests@[i]] 0 <= i < n - 1 && match template.tests@[i] { + FlatTest::Atom { field, term, .. } => p == model::Primitive::Eq(field, term_view(term)), _ => false, + }; + assert(exists|j: int| #![trigger template.tests@[j]] 0 <= j < n && match template.tests@[j] { + FlatTest::Atom { field, term, .. } => p == model::Primitive::Eq(field, term_view(term)), _ => false, + }); + } + } + } + + pub(crate) open spec fn tests_vocabulary(g: model::Graph, template: FlatPair, ids: Seq) -> bool { + forall|i: int| 0 <= i < ids.len() ==> ids[i]@ < g.tests.len() + && (#[trigger] vocab::test_primitives(model::lift_test(g, ids[i]@))).subset_of(source_primitives(template)) + } + + pub(crate) open spec fn regexes_vocabulary(g: model::Graph, template: FlatPair, ids: Seq) -> bool { + forall|i: int| 0 <= i < ids.len() ==> ids[i]@ < g.regexes.len() + && (#[trigger] vocab::regex_primitives(model::lift_regex(g, ids[i]@))).subset_of(source_primitives(template)) + } + + pub(crate) proof fn lemma_vocabulary_stable(a: model::Graph, b: model::Graph, template: FlatPair, tests: Seq, regexes: Seq) + requires model::graph_wf(a), model::graph_extends(a, b), tests_vocabulary(a, template, tests), regexes_vocabulary(a, template, regexes), + ensures tests_vocabulary(b, template, tests), regexes_vocabulary(b, template, regexes), + { + model::lemma_graph_wf_elim(a); + assert forall|i: int| 0 <= i < tests.len() implies tests[i]@ < b.tests.len() + && vocab::test_primitives(model::lift_test(b, tests[i]@)).subset_of(source_primitives(template)) by { + assert(vocab::test_primitives(model::lift_test(a, tests[i]@)).subset_of(source_primitives(template))); + model::lemma_lift_test_stable(a, b, tests[i]@); + } + assert forall|i: int| 0 <= i < regexes.len() implies regexes[i]@ < b.regexes.len() + && vocab::regex_primitives(model::lift_regex(b, regexes[i]@)).subset_of(source_primitives(template)) by { + assert(vocab::regex_primitives(model::lift_regex(a, regexes[i]@)).subset_of(source_primitives(template))); + model::lemma_lift_regex_stable(a, b, regexes[i]@); + } + } + + pub(crate) proof fn lemma_selected_regexes_vocabulary(g: model::Graph, template: FlatPair, ids: Seq, children: Seq, selected: Seq) + requires regexes_vocabulary(g, template, ids), selected.len() == children.len(), + forall|i: int| 0 <= i < children.len() ==> #[trigger] children[i] < ids.len() && selected[i] == ids[children[i] as int], + ensures norm::regex_ids_valid(g, selected), + forall|i: int| 0 <= i < selected.len() ==> vocab::regex_primitives(model::lift_regex(g, selected[i]@)).subset_of(source_primitives(template)), + forall|r: language::Regex| crate::verify::finite_link::lift_set(g, selected).contains(r) ==> vocab::regex_primitives(r).subset_of(source_primitives(template)), + { + assert forall|i: int| 0 <= i < selected.len() implies selected[i]@ < g.regexes.len() + && vocab::regex_primitives(model::lift_regex(g, selected[i]@)).subset_of(source_primitives(template)) by { + assert(selected[i] == ids[children[i] as int]); + assert(vocab::regex_primitives(model::lift_regex(g, ids[children[i] as int]@)).subset_of(source_primitives(template))); + } + let rs = crate::verify::finite_link::lifts(g, selected); + rs.to_set_ensures(); + assert forall|r: language::Regex| rs.to_set().contains(r) implies vocab::regex_primitives(r).subset_of(source_primitives(template)) by { + let i = rs.lemma_contains_to_index(r); + assert(rs[i] == model::lift_regex(g, selected[i]@)); + } + } + + pub(crate) proof fn lemma_concat_vocabulary(a: model::Graph, b: model::Graph, template: FlatPair, ids: Seq, children: Seq, selected: Seq, out: nat) + requires model::graph_wf(a), model::graph_wf(b), model::graph_extends(a, b), + regexes_vocabulary(a, template, ids), selected.len() == children.len(), + forall|i: int| 0 <= i < children.len() ==> #[trigger] children[i] < ids.len() && selected[i] == ids[children[i] as int], + out < b.regexes.len(), norm::regex_concat_result(a, b, selected, out), + ensures vocab::regex_primitives(model::lift_regex(b, out)).subset_of(source_primitives(template)), + { + lemma_selected_regexes_vocabulary(a, template, ids, children, selected); + crate::verify::finite_link::lemma_concat_link(a, b, selected, out); + vocab::lemma_cat_vocab(crate::verify::finite_link::lifts(a, selected), source_primitives(template)); + } + + pub(crate) proof fn lemma_set_vocabulary(a: model::Graph, b: model::Graph, template: FlatPair, tests: Seq, ids: Seq, children: Seq, selected: Seq, inter: bool, out: nat) + requires model::graph_wf(a), model::graph_wf(b), model::graph_extends(a, b), + crate::verify::finite_compile::compiled_nf(a, tests, ids), regexes_vocabulary(a, template, ids), + selected.len() == children.len(), + forall|i: int| 0 <= i < children.len() ==> #[trigger] children[i] < ids.len() && selected[i] == ids[children[i] as int], + out < b.regexes.len(), + norm::regex_set_flat_inputs(a, selected, inter) ==> norm::regex_set_shape(a, b, selected, inter, out), + ensures vocab::regex_primitives(model::lift_regex(b, out)).subset_of(source_primitives(template)), + { + lemma_selected_regexes_vocabulary(a, template, ids, children, selected); + crate::verify::finite_compile::lemma_selected_nf(a, tests, ids, children, selected); + crate::verify::finite_link::lemma_flat_inputs(a, selected, inter); + crate::verify::finite_link::lemma_set_link(a, b, selected, inter, out); + vocab::lemma_nset_vocab(inter, crate::verify::finite_link::lift_set(a, selected), model::lift_regex(b, out), source_primitives(template)); + } + + pub(crate) open spec fn selected_regex_refs(ids: Seq, children: Seq, selected: Seq) -> bool { + selected.len() == children.len() && forall|i: int| 0 <= i < children.len() + ==> #[trigger] children[i] < ids.len() && selected[i] == ids[children[i] as int] + } + + pub(crate) proof fn lemma_regex_vocabulary(a: model::Graph, b: model::Graph, template: FlatPair, tests: Seq, ids: Seq, node: FlatRegex, selected: Seq, out: nat) + requires model::graph_wf(a), model::graph_wf(b), model::graph_extends(a, b), out < b.regexes.len(), + crate::verify::finite_compile::compiled_nf(a, tests, ids), tests_vocabulary(b, template, tests), + regexes_vocabulary(a, template, ids), regexes_vocabulary(b, template, ids), + match node { + FlatRegex::Concat(children) | FlatRegex::Union(children) | FlatRegex::Intersect(children) => + selected_regex_refs(ids, children@, selected), + _ => true, + }, + match node { + FlatRegex::Empty => out == b.constants.empty, + FlatRegex::All => out == b.constants.all, + FlatRegex::Epsilon => out == b.constants.epsilon, + FlatRegex::Test(t) => t < tests.len() && if tests[t as int]@ == b.constants.test_false { + out == b.constants.empty + } else { b.regexes[out as int].kind == model::RegexKindNode::Test(tests[t as int]@) }, + FlatRegex::Concat(_) => norm::regex_concat_result(a, b, selected, out), + FlatRegex::Union(_) => norm::regex_set_flat_inputs(a, selected, false) ==> norm::regex_set_shape(a, b, selected, false, out), + FlatRegex::Intersect(_) => norm::regex_set_flat_inputs(a, selected, true) ==> norm::regex_set_shape(a, b, selected, true, out), + FlatRegex::Complement(child) => child < ids.len() && norm::regex_not_result(b, ids[child as int]@, out), + FlatRegex::Star(child) => child < ids.len() && vocab::regex_primitives(model::lift_regex(b, out)).subset_of( + vocab::regex_primitives(model::lift_regex(b, ids[child as int]@))), + }, + ensures vocab::regex_primitives(model::lift_regex(b, out)).subset_of(source_primitives(template)), + { + norm::regex_constants(b); + reveal_with_fuel(vocab::regex_primitives, 1); + match node { + FlatRegex::Empty | FlatRegex::All | FlatRegex::Epsilon => { + norm::regex_unfold(b, out); + }, + FlatRegex::Test(t) => { + norm::regex_unfold(b, out); + assert(vocab::test_primitives(model::lift_test(b, tests[t as int]@)).subset_of(source_primitives(template))); + }, + FlatRegex::Star(child) => { + assert(vocab::regex_primitives(model::lift_regex(b, ids[child as int]@)).subset_of(source_primitives(template))); + }, + FlatRegex::Complement(child) => { + crate::verify::finite_compile::lemma_compiled_regex(a, tests, ids, child as int); + model::lemma_graph_wf_elim(a); + model::lemma_lift_regex_stable(a, b, ids[child as int]@); + crate::verify::finite_link::lemma_not_link(b, ids[child as int]@, out); + vocab::lemma_not_vocab(model::lift_regex(b, ids[child as int]@)); + assert(vocab::regex_primitives(model::lift_regex(b, ids[child as int]@)).subset_of(source_primitives(template))); + }, + FlatRegex::Concat(children) => lemma_concat_vocabulary(a, b, template, ids, children@, selected, out), + FlatRegex::Union(children) => lemma_set_vocabulary(a, b, template, tests, ids, children@, selected, false, out), + FlatRegex::Intersect(children) => lemma_set_vocabulary(a, b, template, tests, ids, children@, selected, true, out), + } + } + + pub open spec fn term_view(term: FlatTerm) -> model::GTerm { + match term { + FlatTerm::Constant(value) => model::GTerm::Constant(value as nat), + FlatTerm::Variable(field) => model::GTerm::Variable(field), + } + } + + + + pub open spec fn head_view(template: FlatPair) -> language::Head { + template.head@.map(|i: int, field: FlatHead| field@) + } + + /// Independent interpretation of a cold numeric test table. The index guard + /// makes this total even for malformed templates; executable lookup rejects + /// those references rather than treating this default as a verdict. + pub open spec fn source_test(template: FlatPair, index: nat, theta: Subst, event: EventView) -> bool + decreases index, + { + if index >= template.tests@.len() { false } + else { match template.tests@[index as int] { + FlatTest::Bool(value) => value, + FlatTest::Atom { field, term, positive } => + model::primitive_holds(theta, model::Primitive::Eq(field, term_view(term)), event) == positive, + FlatTest::And(children) => forall|i: int| 0 <= i < children@.len() + ==> children@[i] < index && source_test(template, children@[i] as nat, theta, event), + FlatTest::Or(children) => exists|i: int| 0 <= i < children@.len() + && children@[i] < index && source_test(template, children@[i] as nat, theta, event), + }} + } + + /// Independent regex language over the template's postorder nodes. + pub open spec fn source_regex(template: FlatPair, index: nat, theta: Subst, word: Seq) -> bool + decreases index, + { + if index >= template.regexes@.len() { false } + else { match template.regexes@[index as int] { + FlatRegex::Empty => false, + FlatRegex::All => true, + FlatRegex::Epsilon => word.len() == 0, + FlatRegex::Test(test) => word.len() == 1 && source_test(template, test as nat, theta, word[0]), + FlatRegex::Union(children) => exists|i: int| 0 <= i < children@.len() + && children@[i] < index && source_regex(template, children@[i] as nat, theta, word), + FlatRegex::Intersect(children) => forall|i: int| 0 <= i < children@.len() + ==> children@[i] < index && source_regex(template, children@[i] as nat, theta, word), + FlatRegex::Concat(children) => exists|parts: Seq>| + parts.len() == children@.len() && parts.flatten() == word + && forall|i: int| 0 <= i < children@.len() + ==> children@[i] < index && source_regex(template, children@[i] as nat, theta, parts[i]), + FlatRegex::Star(child) => child < index && exists|parts: Seq>| + parts.flatten() == word && forall|i: int| 0 <= i < parts.len() + ==> source_regex(template, child as nat, theta, parts[i]), + FlatRegex::Complement(child) => child < index && !source_regex(template, child as nat, theta, word), + }} + } + + pub(crate) open(crate) spec fn test_correct(g: model::Graph, template: FlatPair, index: nat, id: TestId) -> bool { + id@ < g.tests.len() && forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + ==> norm::test_truth(g, theta, id@, event) == source_test(template, index, theta, event) + } + + pub(crate) open(crate) spec fn regex_correct(g: model::Graph, template: FlatPair, index: nat, id: RegexId) -> bool { + id@ < g.regexes.len() && forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + ==> model::regex_lang(g, theta, id@, word) == source_regex(template, index, theta, word) + } + + pub(crate) open(crate) spec fn test_maps(g: model::Graph, template: FlatPair, ids: Seq) -> bool { + ids.len() <= template.tests@.len() + && forall|i: int| 0 <= i < ids.len() ==> test_correct(g, template, i as nat, ids[i]) + } + + pub(crate) open(crate) spec fn regex_maps(g: model::Graph, template: FlatPair, ids: Seq) -> bool { + ids.len() <= template.regexes@.len() + && forall|i: int| 0 <= i < ids.len() ==> regex_correct(g, template, i as nat, ids[i]) + } + + pub(crate) proof fn maps_extend(before: model::Graph, after: model::Graph, + template: FlatPair, tests: Seq, regexes: Seq) + requires model::graph_wf(before), model::graph_extends(before, after), + test_maps(before, template, tests), regex_maps(before, template, regexes), + ensures test_maps(after, template, tests), regex_maps(after, template, regexes), + { + model::lemma_graph_wf_elim(before); + model::lemma_lift_stable_under_extends(before, after); + assert forall|i: int| 0 <= i < tests.len() implies test_correct(after, template, i as nat, tests[i]) by { + assert(test_correct(before, template, i as nat, tests[i])); + } + assert forall|i: int| 0 <= i < regexes.len() implies regex_correct(after, template, i as nat, regexes[i]) by { + assert(regex_correct(before, template, i as nat, regexes[i])); + } + } + + pub(crate) proof fn test_push(g: model::Graph, template: FlatPair, tests: Seq, id: TestId) + requires test_maps(g, template, tests), tests.len() < template.tests@.len(), + test_correct(g, template, tests.len(), id), + ensures test_maps(g, template, tests.push(id)), + { + assert forall|i: int| 0 <= i < tests.push(id).len() + implies test_correct(g, template, i as nat, tests.push(id)[i]) by { + if i < tests.len() { assert(tests.push(id)[i] == tests[i]); } + else { assert(i == tests.len()); } + } + } + + pub(crate) proof fn regex_push(g: model::Graph, template: FlatPair, regexes: Seq, id: RegexId) + requires regex_maps(g, template, regexes), regexes.len() < template.regexes@.len(), + regex_correct(g, template, regexes.len(), id), + ensures regex_maps(g, template, regexes.push(id)), + { + assert forall|i: int| 0 <= i < regexes.push(id).len() + implies regex_correct(g, template, i as nat, regexes.push(id)[i]) by { + if i < regexes.len() { assert(regexes.push(id)[i] == regexes[i]); } + else { assert(i == regexes.len()); } + } + } + + pub(crate) proof fn selected_tests_valid(g: model::Graph, template: FlatPair, + ids: Seq, children: Seq, selected: Seq) + requires test_maps(g, template, ids), selected.len() == children.len(), + forall|i: int| 0 <= i < children.len() + ==> #[trigger] children[i] < ids.len() && selected[i] == ids[children[i] as int], + ensures norm::test_ids_valid(g, selected), + { + assert forall|i: int| 0 <= i < selected.len() implies selected[i]@ < g.tests.len() by { + assert(children[i] < ids.len()); + assert(test_correct(g, template, children[i] as nat, ids[children[i] as int])); + } + } + + pub(crate) proof fn selected_regexes_valid(g: model::Graph, template: FlatPair, + ids: Seq, children: Seq, selected: Seq) + requires regex_maps(g, template, ids), selected.len() == children.len(), + forall|i: int| 0 <= i < children.len() + ==> #[trigger] children[i] < ids.len() && selected[i] == ids[children[i] as int], + ensures norm::regex_ids_valid(g, selected), + { + assert forall|i: int| 0 <= i < selected.len() implies selected[i]@ < g.regexes.len() by { + assert(children[i] < ids.len()); + assert(regex_correct(g, template, children[i] as nat, ids[children[i] as int])); + } + } + + pub(crate) proof fn test_connective_transfer(g: model::Graph, template: FlatPair, + ids: Seq, children: Seq, selected: Seq, + theta: Subst, event: EventView, and: bool) + requires test_maps(g, template, ids), language::event_wf(theta, theta.len()), + selected.len() == children.len(), + forall|i: int| 0 <= i < children.len() + ==> #[trigger] children[i] < ids.len() && selected[i] == ids[children[i] as int], + ensures norm::test_combo(g, theta, selected, event, and) + == if and { + forall|i: int| 0 <= i < children.len() + ==> children[i] < ids.len() && source_test(template, children[i] as nat, theta, event) + } else { + exists|i: int| 0 <= i < children.len() + && children[i] < ids.len() && source_test(template, children[i] as nat, theta, event) + }, + { + reveal(norm::test_combo); + assert forall|i: int| 0 <= i < children.len() implies + #[trigger] model::test_holds(theta, model::lift_test(g, selected[i]@), event) + == (children[i] < ids.len() && source_test(template, children[i] as nat, theta, event)) by { + assert(children[i] < ids.len()); + assert(test_correct(g, template, children[i] as nat, ids[children[i] as int])); + } + norm::lemma_combo_pointwise(children.len(), + |i: int| model::test_holds(theta, model::lift_test(g, selected[i]@), event), + |i: int| children[i] < ids.len() && source_test(template, children[i] as nat, theta, event), and); + } + + pub(crate) proof fn regex_set_transfer(g: model::Graph, template: FlatPair, + ids: Seq, children: Seq, selected: Seq, + theta: Subst, word: Seq, intersect: bool) + requires regex_maps(g, template, ids), language::event_wf(theta, theta.len()), + selected.len() == children.len(), + forall|i: int| 0 <= i < children.len() + ==> #[trigger] children[i] < ids.len() && selected[i] == ids[children[i] as int], + ensures norm::regex_combo(g, theta, selected, word, intersect) + == if intersect { + forall|i: int| 0 <= i < children.len() + ==> children[i] < ids.len() && source_regex(template, children[i] as nat, theta, word) + } else { + exists|i: int| 0 <= i < children.len() + && children[i] < ids.len() && source_regex(template, children[i] as nat, theta, word) + }, + { + reveal(norm::regex_combo); + assert forall|i: int| 0 <= i < children.len() implies + #[trigger] model::regex_lang(g, theta, selected[i]@, word) + == (children[i] < ids.len() && source_regex(template, children[i] as nat, theta, word)) by { + assert(children[i] < ids.len()); + assert(regex_correct(g, template, children[i] as nat, ids[children[i] as int])); + } + norm::lemma_combo_pointwise(children.len(), + |i: int| model::regex_lang(g, theta, selected[i]@, word), + |i: int| children[i] < ids.len() && source_regex(template, children[i] as nat, theta, word), intersect); + } + + pub(crate) proof fn regex_concat_transfer(g: model::Graph, template: FlatPair, + ids: Seq, children: Seq, index: nat, theta: Subst, word: Seq) + requires regex_maps(g, template, ids), ids.len() == index, language::event_wf(theta, theta.len()), + forall|i: int| 0 <= i < children.len() ==> children[i] < ids.len(), + ensures norm::concat_combo(g, theta, + Seq::new(children.len(), |i: int| ids[children[i] as int]), word) + == (exists|parts: Seq>| parts.len() == children.len() && parts.flatten() == word + && forall|i: int| 0 <= i < children.len() + ==> children[i] < index && source_regex(template, children[i] as nat, theta, parts[i])), + { + let selected = Seq::new(children.len(), |i: int| ids[children[i] as int]); + let lifted = model::lift_regexes(g, model::regex_ids(selected)); + assert(lifted.len() == children.len()); + assert forall|i: int, piece: Seq| 0 <= i < children.len() implies + language::numeric_lang(model::gsem(theta), lifted[i], piece) + == source_regex(template, children[i] as nat, theta, piece) by { + assert(regex_correct(g, template, children[i] as nat, ids[children[i] as int])); + } + if norm::concat_combo(g, theta, selected, word) { + let parts = choose|parts: Seq>| parts.len() == lifted.len() && word == parts.flatten() + && forall|i: int| 0 <= i < lifted.len() + ==> language::numeric_lang(model::gsem(theta), lifted[i], parts[i]); + assert forall|i: int| 0 <= i < children.len() implies children[i] < index + && source_regex(template, children[i] as nat, theta, parts[i]) by {} + assert(exists|parts: Seq>| parts.len() == children.len() && parts.flatten() == word + && forall|i: int| 0 <= i < children.len() + ==> children[i] < index && source_regex(template, children[i] as nat, theta, parts[i])); + } + if exists|parts: Seq>| parts.len() == children.len() && parts.flatten() == word + && forall|i: int| 0 <= i < children.len() + ==> children[i] < index && source_regex(template, children[i] as nat, theta, parts[i]) { + let parts = choose|parts: Seq>| parts.len() == children.len() && parts.flatten() == word + && forall|i: int| 0 <= i < children.len() + ==> children[i] < index && source_regex(template, children[i] as nat, theta, parts[i]); + assert forall|i: int| 0 <= i < lifted.len() implies + language::numeric_lang(model::gsem(theta), lifted[i], parts[i]) by {} + assert(norm::concat_combo(g, theta, selected, word)); + } + } + + pub(crate) proof fn regex_star_transfer(g: model::Graph, template: FlatPair, + ids: Seq, child: nat, theta: Subst, word: Seq) + requires regex_maps(g, template, ids), child < ids.len(), language::event_wf(theta, theta.len()), + ensures language::numeric_lang(model::gsem(theta), language::Regex::Star( + alloc::boxed::Box::new(model::lift_regex(g, ids[child as int]@))), word) + == (exists|parts: Seq>| parts.flatten() == word + && forall|i: int| 0 <= i < parts.len() ==> source_regex(template, child, theta, parts[i])), + { + let regex = model::lift_regex(g, ids[child as int]@); + assert(regex_correct(g, template, child, ids[child as int])); + if language::numeric_lang(model::gsem(theta), language::Regex::Star(alloc::boxed::Box::new(regex)), word) { + let parts = choose|parts: Seq>| word == parts.flatten() + && forall|i: int| 0 <= i < parts.len() ==> language::numeric_lang(model::gsem(theta), regex, parts[i]); + assert forall|i: int| 0 <= i < parts.len() implies source_regex(template, child, theta, parts[i]) by {} + assert(exists|parts: Seq>| parts.flatten() == word + && forall|i: int| 0 <= i < parts.len() ==> source_regex(template, child, theta, parts[i])); + } + if exists|parts: Seq>| parts.flatten() == word + && forall|i: int| 0 <= i < parts.len() ==> source_regex(template, child, theta, parts[i]) { + let parts = choose|parts: Seq>| parts.flatten() == word + && forall|i: int| 0 <= i < parts.len() ==> source_regex(template, child, theta, parts[i]); + assert forall|i: int| 0 <= i < parts.len() implies language::numeric_lang(model::gsem(theta), regex, parts[i]) by {} + assert(language::numeric_lang(model::gsem(theta), language::Regex::Star(alloc::boxed::Box::new(regex)), word)); + } + } + + use junco_core::flat::verify as portable; + use junco_core::verify::encoding::{numeric_equality, pointwise, lemma_partition_lift, event_representation, event_relation, word_representation}; + + /// Portable head matching and the numeric substitution agree coordinate by coordinate. + pub proof fn lemma_flat_head(template: FlatPair, candidate: Seq, request: EventView) + requires event_representation(candidate, request), 1 <= template.head@.len() <= MAX_ARITY, + ensures portable::head_matches(template.head@, candidate, numeric_equality()) + == exists|theta: Subst| language::head_match(head_view(template), request, theta), + { + let theta = language::head_bindings(head_view(template), request); + if portable::head_matches(template.head@, candidate, numeric_equality()) { + assert forall|i: int| 0 <= i < template.head@.len() implies + language::head_field_match(head_view(template)[i], request[i], theta[i]) by { + assert(candidate[i] as nat == request[i]); + assert(match template.head@[i] { + FlatHead::Constant(value) => candidate[i] == value, _ => true, + }); + } + assert(language::head_match(head_view(template), request, theta)); + } + if exists|theta: Subst| language::head_match(head_view(template), request, theta) { + let witness = choose|theta: Subst| language::head_match(head_view(template), request, theta); + assert forall|i: int| 0 <= i < template.head@.len() implies match #[trigger] template.head@[i] { + FlatHead::Constant(value) => candidate[i] == value, + _ => true, + } by { + assert(language::head_field_match(head_view(template)[i], request[i], witness[i])); + assert(candidate[i] as nat == request[i]); + } + } + } + + pub proof fn lemma_flat_test(template: FlatPair, id: nat, candidate: Seq, request: EventView, + event: Seq, numeric: EventView, theta: Subst) + requires portable::structural_wf(template), id < template.tests@.len(), + event_representation(candidate, request), event_representation(event, numeric), + event.len() == candidate.len(), + language::head_match(head_view(template), request, theta), + ensures portable::test_sem(template.tests@, id, candidate, event, numeric_equality()) + == source_test(template, id, theta, numeric), + decreases id, + { + reveal_with_fuel(portable::test_sem, 1); + reveal_with_fuel(source_test, 1); + assert(portable::test_wf(template.head@, template.tests@[id as int], id)); + match template.tests@[id as int] { + FlatTest::Atom { field, term, positive } => { + assert(0 <= portable::field_index(field) < template.head@.len()); + assert(language::field_value(numeric, field) == event[portable::field_index(field)] as nat); + if let FlatTerm::Variable(variable) = term { + assert(field == variable); + assert(template.head@[portable::field_index(variable)] is Bind); + assert(language::head_field_match(head_view(template)[portable::field_index(variable)], + request[portable::field_index(variable)], theta[portable::field_index(variable)])); + assert(language::field_value(theta, variable) == candidate[portable::field_index(variable)] as nat); + } + }, + FlatTest::And(children) | FlatTest::Or(children) => { + assert(portable::references_before(children@, id)); + assert forall|i: int| 0 <= i < children@.len() implies + portable::test_sem(template.tests@, children@[i] as nat, candidate, event, numeric_equality()) + == source_test(template, children@[i] as nat, theta, numeric) by { + lemma_flat_test(template, children@[i] as nat, candidate, request, event, numeric, theta); + } + }, + _ => {}, + } + } + + /// This bridge composes the portable encoding theorem with the actual graph compiler. + pub proof fn lemma_flat_regex(template: FlatPair, id: nat, candidate: Seq, request: EventView, + word: Seq>, numeric: Seq, theta: Subst) + requires portable::structural_wf(template), id < template.regexes@.len(), + event_representation(candidate, request), word_representation(word, numeric), + forall|i: int| 0 <= i < word.len() ==> word[i].len() == candidate.len(), + language::head_match(head_view(template), request, theta), + ensures portable::flat_lang(template.tests@, template.regexes@, id, candidate, word, numeric_equality()) + == source_regex(template, id, theta, numeric), + decreases id, + { + reveal_with_fuel(portable::flat_lang, 1); + reveal_with_fuel(source_regex, 1); + assert(portable::regex_wf(template.regexes@[id as int], id, template.tests@.len())); + assert forall|i: int| 0 <= i < word.len() implies portable::event_wf(word[i], candidate.len()) by { + assert(event_representation(word[i], numeric[i])); + } + match template.regexes@[id as int] { + FlatRegex::Test(test) => { + if word.len() == 1 { + lemma_flat_test(template, test as nat, candidate, request, word[0], numeric[0], theta); + } + }, + FlatRegex::Union(children) | FlatRegex::Intersect(children) => { + assert(portable::references_before(children@, id)); + assert forall|i: int| 0 <= i < children@.len() implies + portable::flat_lang(template.tests@, template.regexes@, children@[i] as nat, candidate, word, numeric_equality()) + == source_regex(template, children@[i] as nat, theta, numeric) by { + lemma_flat_regex(template, children@[i] as nat, candidate, request, word, numeric, theta); + } + }, + FlatRegex::Concat(children) => { + if portable::flat_lang(template.tests@, template.regexes@, id, candidate, word, numeric_equality()) { + let parts = choose|parts: Seq>>| parts.len() == children@.len() && word == parts.flatten() + && (forall|i: int| 0 <= i < parts.len() ==> portable::flat_lang(template.tests@, template.regexes@, children@[i] as nat, candidate, parts[i], numeric_equality())); + junco_core::verify::flatten::lemma_partition_arity(parts, candidate.len()); + let reverse = |n: EventView, e: Seq| event_representation(e, n); + assert(pointwise(numeric, word, reverse)); + lemma_partition_lift(numeric, word, parts, reverse); + let lifted = choose|lifted: Seq>| lifted.len() == parts.len() + && numeric == lifted.flatten() + && forall|i: int| 0 <= i < parts.len() ==> pointwise(lifted[i], parts[i], reverse); + assert forall|i: int| 0 <= i < parts.len() implies + source_regex(template, children@[i] as nat, theta, lifted[i]) by { + assert(word_representation(parts[i], lifted[i])); + lemma_flat_regex(template, children@[i] as nat, candidate, request, parts[i], lifted[i], theta); + } + assert(source_regex(template, id, theta, numeric)); + } + if source_regex(template, id, theta, numeric) { + let parts = choose|parts: Seq>| parts.len() == children@.len() && numeric == parts.flatten() + && (forall|i: int| 0 <= i < parts.len() ==> source_regex(template, children@[i] as nat, theta, parts[i])); + lemma_partition_lift(word, numeric, parts, event_relation()); + let lifted = choose|lifted: Seq>>| lifted.len() == parts.len() + && word == lifted.flatten() + && forall|i: int| 0 <= i < parts.len() ==> pointwise(lifted[i], parts[i], event_relation()); + junco_core::verify::flatten::lemma_partition_arity(lifted, candidate.len()); + assert forall|i: int| 0 <= i < parts.len() implies + portable::flat_lang(template.tests@, template.regexes@, children@[i] as nat, candidate, lifted[i], numeric_equality()) by { + lemma_flat_regex(template, children@[i] as nat, candidate, request, lifted[i], parts[i], theta); + } + assert(portable::flat_lang(template.tests@, template.regexes@, id, candidate, word, numeric_equality())); + } + }, + FlatRegex::Star(child) => { + if portable::flat_lang(template.tests@, template.regexes@, id, candidate, word, numeric_equality()) { + let parts = choose|parts: Seq>>| word == parts.flatten() + && (forall|i: int| 0 <= i < parts.len() ==> portable::flat_lang(template.tests@, template.regexes@, child as nat, candidate, parts[i], numeric_equality())); + junco_core::verify::flatten::lemma_partition_arity(parts, candidate.len()); + let reverse = |n: EventView, e: Seq| event_representation(e, n); + assert(pointwise(numeric, word, reverse)); + lemma_partition_lift(numeric, word, parts, reverse); + let lifted = choose|lifted: Seq>| lifted.len() == parts.len() + && numeric == lifted.flatten() + && forall|i: int| 0 <= i < parts.len() ==> pointwise(lifted[i], parts[i], reverse); + assert forall|i: int| 0 <= i < parts.len() implies + source_regex(template, child as nat, theta, lifted[i]) by { + assert(word_representation(parts[i], lifted[i])); + lemma_flat_regex(template, child as nat, candidate, request, parts[i], lifted[i], theta); + } + assert(source_regex(template, id, theta, numeric)); + } + if source_regex(template, id, theta, numeric) { + let parts = choose|parts: Seq>| numeric == parts.flatten() + && (forall|i: int| 0 <= i < parts.len() ==> source_regex(template, child as nat, theta, parts[i])); + lemma_partition_lift(word, numeric, parts, event_relation()); + let lifted = choose|lifted: Seq>>| lifted.len() == parts.len() + && word == lifted.flatten() + && forall|i: int| 0 <= i < parts.len() ==> pointwise(lifted[i], parts[i], event_relation()); + junco_core::verify::flatten::lemma_partition_arity(lifted, candidate.len()); + assert forall|i: int| 0 <= i < parts.len() implies + portable::flat_lang(template.tests@, template.regexes@, child as nat, candidate, lifted[i], numeric_equality()) by { + lemma_flat_regex(template, child as nat, candidate, request, lifted[i], parts[i], theta); + } + assert(portable::flat_lang(template.tests@, template.regexes@, id, candidate, word, numeric_equality())); + } + }, + FlatRegex::Complement(child) => { + lemma_flat_regex(template, child as nat, candidate, request, word, numeric, theta); + }, + _ => {}, + } + } + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::indexing_slicing)] + + use super::*; + use alloc::vec; + use history_store::store::HistoryStore; + use junco_core::limits::{MAX_GRAPH_BYTES, Unmetered}; + + fn event(arity: usize, value: u8) -> NumericEvent { + let store = HistoryStore::new(arity); + let slots: Vec<_> = (0..arity) + .map(|index| { + store + .intern( + Component::new(index), + &[value], + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap() + }) + .collect(); + store.event(&slots).unwrap() + } + + fn template(head: Vec>) -> FlatPair { + FlatPair { + head, + tests: Vec::new(), + regexes: vec![FlatRegex::All], + root: 0, + } + } + + #[test] + fn head_binding_checks_every_coordinate_and_exact_arity() { + for arity in 1..=MAX_ARITY { + let request = event(arity, 17); + let other = event(arity, 18); + let mut source = template(vec![FlatHead::Bind; arity]); + let bound = RuleRuntime::bindings(&source, &request).unwrap(); + assert_eq!(bound.arity(), arity); + for index in 0..arity { + assert_eq!(bound.get(index), request.component(index)); + source.head[index] = FlatHead::Any; + assert_eq!( + RuleRuntime::bindings(&source, &request).unwrap().get(index), + 0 + ); + source.head[index] = FlatHead::Constant(request.component(index)); + assert_eq!( + RuleRuntime::bindings(&source, &request).unwrap().get(index), + 0 + ); + source.head[index] = FlatHead::Constant(other.component(index)); + assert_eq!(RuleRuntime::bindings(&source, &request), None); + source.head[index] = FlatHead::Bind; + } + let _ = source.head.pop(); + assert_eq!(RuleRuntime::bindings(&source, &request), None); + source.head.extend([FlatHead::Bind, FlatHead::Bind]); + assert_eq!(RuleRuntime::bindings(&source, &request), None); + } + } + + #[test] + fn classification_checks_event_and_substitution_bounds() { + for arity in 1..=MAX_ARITY { + let request = event(arity, 19); + let values: Vec<_> = (0..arity).map(|index| request.component(index)).collect(); + let bindings = Bindings::new(&values); + for index in 0..arity { + let field = Component::new(index); + for term in [ + Term::Constant(request.component(index)), + Term::Variable(field), + ] { + assert_eq!( + CompiledPair::classify( + Primitive::Eq { field, term }, + &request, + &bindings, + &mut Unmetered, + &mut ObservationWorld, + ), + Ok(true) + ); + } + assert_eq!( + CompiledPair::classify( + Primitive::Eq { + field, + term: Term::Constant(0) + }, + &request, + &bindings, + &mut Unmetered, + &mut ObservationWorld, + ), + Ok(false) + ); + assert_eq!( + CompiledPair::classify( + Primitive::Eq { + field, + term: Term::Variable(field) + }, + &request, + &Bindings::new(&[]), + &mut Unmetered, + &mut ObservationWorld, + ), + Ok(false) + ); + } + for invalid in [u8::try_from(arity).unwrap(), u8::MAX] { + for primitive in [ + Primitive::Eq { + field: Component(invalid), + term: Term::Constant(0), + }, + Primitive::Eq { + field: Component(0), + term: Term::Variable(Component(invalid)), + }, + ] { + assert_eq!( + CompiledPair::classify( + primitive, + &request, + &bindings, + &mut Unmetered, + &mut ObservationWorld, + ), + Ok(false) + ); + } + } + } + } + + #[test] + fn invalid_numeric_primitives_are_false_before_polarity() { + for arity in 1..=MAX_ARITY { + let request = event(arity, 20); + let bindings = Bindings::new(&vec![0; arity]); + for (field, term) in [ + (Component(u8::MAX), FlatTerm::Constant(0)), + (Component(0), FlatTerm::Variable(Component(u8::MAX))), + ] { + for positive in [false, true] { + let source = FlatPair { + head: vec![FlatHead::Any; arity], + tests: vec![FlatTest::Atom { + field, + term: term.clone(), + positive, + }], + regexes: vec![FlatRegex::Test(0)], + root: 0, + }; + let mut pair = CompiledPair::compile( + &source, + MAX_GRAPH_BYTES, + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + let residual = pair + .fold( + pair.root, + &[request], + &bindings, + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + assert_eq!( + pair.answer(residual, &mut Unmetered, &mut ObservationWorld), + Ok(!positive) + ); + } + } + } + } +} diff --git a/src/history-semantics/src/compiled_rule.rs b/src/history-semantics/src/compiled_rule.rs new file mode 100644 index 000000000..7765783d5 --- /dev/null +++ b/src/history-semantics/src/compiled_rule.rs @@ -0,0 +1,1021 @@ +//! Store-bound owned DSL compilation and retained numeric decisions. + +use crate::runtime::RuleRuntime; +use alloc::sync::Arc; +use history_store::history::History; +#[cfg(verus_keep_ghost)] +use history_store::history::StoredHistory; +use history_store::typed::Store; +use history_syntax::Event; +use history_syntax::syntax::{Rule, RuleMode}; +use junco_core::errors::{CompileError, HistoryError}; +use junco_core::flat::FlatPair; +use junco_core::flatten::flatten_rule; +use junco_core::limits::{Limits, Unmetered}; +use junco_core::observation::ObservationWorld; +use vstd::prelude::*; + +#[cfg(verus_keep_ghost)] +use crate::verify::typed_decision as decision; +#[cfg(verus_keep_ghost)] +use history_store::history::verify as raw; +#[cfg(verus_keep_ghost)] +use history_store::typed::verify as books; +#[cfg(verus_keep_ghost)] +use junco_core::spec::semantics as dsl; +#[cfg(verus_keep_ghost)] +use junco_core::verify::{ + encoding, flatten as source, + history_specs::{no_invariant_compile_failure, no_invariant_failure}, +}; +#[cfg(verus_keep_ghost)] +use verify::*; + +#[cfg(verus_keep_ghost)] +verus! { +broadcast use {vstd::std_specs::vec::group_vec_axioms, vstd::seq::group_seq_lemmas, + junco_core::kernel::verify::group_kernel_views}; +/// The result retains a structural witness, not an assumed language equivalence. +pub(crate) open spec fn compiled_source( + rule: Rule, mode: RuleMode, numeric: FlatPair, + maps: encoding::Codebook, eq: encoding::Equality, + domain: encoding::Domain, +) -> bool { + mode == rule.mode && exists|flat: junco_core::flat::FlatRule| + source::flattened::(rule, flat) + && encoding::lowering(flat.source, numeric, maps, eq) + && encoding::constants_in_domain(flat.source, domain) +} +} + +#[cfg(verus_keep_ghost)] +pub mod verify { + use super::*; + verus! { + broadcast use {vstd::std_specs::vec::group_vec_axioms, vstd::seq::group_seq_lemmas, + junco_core::kernel::verify::group_kernel_views}; + + pub tracked struct ObservedHistory { + pub(crate) snapshot: raw::Snapshot, + pub(crate) registration: books::HistoryRegistration, + } + + pub open(crate) spec fn source_rule(compiled: CompiledRule) -> Rule { + compiled.source@ + } + + /// Native store owner retained by this compiled rule. + pub open(crate) spec fn compiled_store(compiled: CompiledRule) -> Arc> { + compiled.store + } + + /// Encoding witnesses are retained without exposing their representation. + pub closed spec fn compiled_maps_frame(before: CompiledRule, after: CompiledRule) -> bool { + after.maps@ == before.maps@ + } + + /// A failed decision retains the committed numeric cursor cache. + pub closed spec fn compiled_cursor_frame(before: CompiledRule, after: CompiledRule) -> bool { + after.runtime.cursors@ == before.runtime.cursors@ + } + + pub open(crate) spec fn observation_matches(registry: vstd::resource::Loc, key: (usize, u64), + events: Seq, observation: ObservedHistory) -> bool { + observation.registration.id() == registry && observation.registration.key() == key.0 + && observation.registration.value() == observation.snapshot.id() + && observation.snapshot.value().revision == key.1 as nat + && observation.snapshot.value().events == events + } + + pub open(crate) spec fn observations_wf(registry: vstd::resource::Loc, + snapshots: crate::runtime::verify::HistorySnapshots, + observations: Map<(usize, u64), ObservedHistory>) -> bool { + snapshots.dom() == observations.dom() + && forall|key: (usize, u64)| observations.contains_key(key) ==> + observation_matches(registry, key, snapshots[key], observations[key]) + } + + /// Publishing an exact lifecycle observation also introduces closed snapshot compatibility. + pub(crate) proof fn lemma_observations_insert(registry: vstd::resource::Loc, + snapshots: crate::runtime::verify::HistorySnapshots, observations: Map<(usize, u64), ObservedHistory>, + key: (usize, u64), events: Seq, observation: ObservedHistory) + requires observations_wf(registry, snapshots, observations), + observation_matches(registry, key, events, observation), + ensures observations_wf(registry, snapshots.insert(key, events), observations.insert(key, observation)), + crate::runtime::verify::snapshot_compatible(snapshots.insert(key, events), key.0, key.1, events), + { + assert forall|k: (usize, u64)| observations.insert(key, observation).contains_key(k) implies + observation_matches(registry, k, snapshots.insert(key, events)[k], observations.insert(key, observation)[k]) by { + if k != key { + assert(observations.contains_key(k)); + assert(observation_matches(registry, k, snapshots[k], observations[k])); + } + } + crate::runtime::verify::lemma_snapshot_compatible_intro(snapshots.insert(key, events), key.0, key.1, events); + } + + pub open(crate) spec fn compiled_wf(compiled: CompiledRule) -> bool { + books::store_wf(*compiled.store) + && junco_core::flat::verify::structural_wf(compiled.template) + && decision::runtime_represents(compiled.template, compiled.runtime) + && observations_wf(books::registry_id(&compiled.store), + compiled.runtime.snapshots@, compiled.observations@) + && (junco_core::spec::hypotheses::event_obligations::() ==> books::maps_wf::(compiled.maps@) + && books::snapshot_published::(books::registry_id(&compiled.store), compiled.maps@) + && compiled_source::(compiled.source@, compiled.mode, compiled.template, + compiled.maps@, source::component_equality::(), books::domain::())) + } + + pub open(crate) spec fn constructed(compiled: CompiledRule, rule: Rule, store: Arc>) -> bool { + compiled_wf(compiled) && compiled.source@ == rule && compiled.store == store + && compiled.runtime.cursors@ == Seq::::empty() + && compiled.runtime.snapshots@ == Map::<(usize, u64), Seq>::empty() + } + + /// Introduces decision readiness from actual rule and history constructors. + pub proof fn lemma_constructed_decision(compiled: CompiledRule, rule: Rule, + store: Arc>, history: History) + requires constructed(compiled, rule, store), raw::history_wf(history), + ensures decision_requires(compiled, history), compiled_wf(compiled), + source_rule(compiled) == rule, compiled_store(compiled) == store, + books::store_wf(*store), + {} + + pub open(crate) spec fn decision_requires(compiled: CompiledRule, history: History) -> bool { + compiled_wf(compiled) && raw::history_wf(history) + } + + /// Readiness is preserved when a well-formed history is paired with a retained rule. + pub proof fn lemma_decision_requires(compiled: CompiledRule, history: History) + requires compiled_wf(compiled), raw::history_wf(history), + ensures decision_requires(compiled, history), + {} + + /// Persistent observations agree with the history's body-maintained transition ledger. + pub(crate) proof fn lemma_history_compatible(registry: vstd::resource::Loc, + history: usize, stored: StoredHistory, snapshots: crate::runtime::verify::HistorySnapshots, + tracked observations: &Map<(usize, u64), ObservedHistory>, + tracked registration: &books::HistoryRegistration, tracked lifecycle: &raw::Lifecycle) + requires observations_wf(registry, snapshots, *observations), lifecycle.wf(), + registration.id() == registry, registration.key() == history, + registration.value() == lifecycle.id(), lifecycle.state() == stored@, + ensures crate::runtime::verify::snapshot_compatible(snapshots, + history, stored.revision(), history_store::store::verify::events_view(raw::stored_events(&stored))), + { + history_store::history::lemma_stored_history_view(stored); + let key = (history, stored.revision()); + if snapshots.contains_key(key) { + assert(observations.contains_key(key)); + assert(observation_matches(registry, key, snapshots[key], observations[key])); + let tracked observation = observations.tracked_borrow(key); + books::registrations_agree(&observation.registration, registration); + assert(observation.snapshot.id() == lifecycle.id()); + lifecycle.validate(&observation.snapshot); + assert(observation.snapshot.value().revision == stored.revision() as nat); + assert(observation.snapshot.value().events.is_prefix_of( + history_store::store::verify::events_view(raw::stored_events(&stored)))); + } + crate::runtime::verify::lemma_snapshot_compatible_intro(snapshots, history, stored.revision(), + history_store::store::verify::events_view(raw::stored_events(&stored))); + } + + pub open spec fn dsl_result(rule: Rule, history: History, candidate: E, + result: Result, HistoryError>) -> bool { + result matches Ok(answer) ==> answer == dsl::rule_evaluation( + rule@, candidate, raw::raw_events(history)) + } + + /// Outcome of the ordered scan: the first violated source (`least_violation` in the semantics) or none + /// (`policy_permits`), under the event laws. + pub open spec fn ordered_result(sources: Seq>, history: History, candidate: E, + result: Result, HistoryError>) -> bool { + junco_core::spec::hypotheses::event_obligations::() ==> match result { + Ok(Some(index)) => dsl::least_violation(dsl::rule_views(sources), candidate, raw::raw_events(history), index as int), + Ok(None) => dsl::policy_permits(dsl::rule_views(sources), candidate, raw::raw_events(history)), + Err(_) => true, + } + } + + /// A scan that violated no source permits the candidate (`policy_permits` over the views). + pub proof fn lemma_no_violation_permits(sources: Seq>, candidate: E, history: Seq) + requires forall|j: int| 0 <= j < sources.len() ==> !dsl::rule_violated(sources[j]@, candidate, history), + ensures dsl::policy_permits(dsl::rule_views(sources), candidate, history), + { + assert forall|i: int| 0 <= i < dsl::rule_views(sources).len() implies + !dsl::rule_violated(dsl::rule_views(sources)[i], candidate, history) by { + assert(dsl::rule_views(sources)[i] == sources[i]@); + } + } + + pub open spec fn compiled_sources(rules: Seq>) -> Seq> { + rules.map(|i: int, rule: CompiledRule| source_rule(rule)) + } + + pub open(crate) spec fn compiled_table_wf(rules: Seq>, store: Arc>) -> bool { + books::store_wf(*store) && forall|i: int| 0 <= i < rules.len() ==> + compiled_wf(rules[i]) && rules[i].store == store + } + + pub open(crate) spec fn compiled_structure_frame(before: CompiledRule, after: CompiledRule) -> bool { + compiled_wf(after) && source_rule(after) == source_rule(before) + && after.store == before.store && after.mode == before.mode + && after.template == before.template + } + + pub open(crate) spec fn compiled_table_frame(before: Seq>, after: Seq>) -> bool { + before.len() == after.len() && forall|i: int| 0 <= i < before.len() ==> + compiled_structure_frame(before[i], after[i]) + } + + pub(crate) proof fn lemma_compiled_sources_frame(before: Seq>, after: Seq>) + requires compiled_table_frame(before, after), + ensures compiled_sources(before) == compiled_sources(after), + { + assert(compiled_sources(before) =~= compiled_sources(after)); + } + + pub(crate) proof fn lemma_compiled_mode_frame(before: Seq>, after: Seq>, index: int) + requires compiled_table_frame(before, after), 0 <= index < before.len(), + ensures after[index].mode_spec() == before[index].mode_spec(), + { reveal(CompiledRule::mode_spec); } + + pub proof fn lemma_compiled_source_mode(compiled: CompiledRule, mode: RuleMode) + requires compiled_wf(compiled), junco_core::spec::hypotheses::event_obligations::(), mode == compiled.mode_spec(), + ensures mode == source_rule(compiled).mode, + { reveal(CompiledRule::mode_spec); } + + pub proof fn lemma_dsl_violation(compiled: CompiledRule, history: History, candidate: E, + result: Result, HistoryError>, mode: RuleMode) + requires compiled_wf(compiled), junco_core::spec::hypotheses::event_obligations::(), + dsl_result(source_rule(compiled), history, candidate, result), mode == compiled.mode_spec(), + ensures result matches Ok(answer) ==> dsl::rule_violated(source_rule(compiled)@, candidate, raw::raw_events(history)) + == match answer { None => false, Some(accepted) => match mode { + RuleMode::Require => !accepted, RuleMode::Forbid => accepted, + } }, + { + reveal(CompiledRule::mode_spec); + } + + pub open(crate) spec fn decision_result(before: CompiledRule, after: CompiledRule, + history: History, candidate: E, result: Result, HistoryError>) -> bool { + compiled_structure_frame(before, after) && after.maps@ == before.maps@ + && no_invariant_failure(result) + && (result is Err ==> after.runtime.cursors@ == before.runtime.cursors@) + && (junco_core::spec::hypotheses::event_obligations::() ==> dsl_result(before.source@, history, candidate, result)) + && ((result == Err(HistoryError::WrongHistoryOwner)) + == !books::same_store_owner(before.store, raw::store_of(history))) + } + + /// Eliminates a checked decision without revealing graphs, maps, or cursors. + pub proof fn lemma_decision_result_facts( + before: CompiledRule, after: CompiledRule, history: History, + candidate: E, result: Result, HistoryError>) + requires decision_result(before, after, history, candidate, result), + ensures compiled_wf(after), compiled_structure_frame(before, after), + source_rule(after) == source_rule(before), compiled_store(after) == compiled_store(before), + compiled_maps_frame(before, after), + no_invariant_failure(result), + result is Err ==> compiled_cursor_frame(before, after), + raw::history_wf(history) ==> decision_requires(after, history), + (result == Err(HistoryError::WrongHistoryOwner)) + == !books::same_store_owner(compiled_store(before), raw::store_of(history)), + junco_core::spec::hypotheses::event_obligations::() ==> dsl_result(source_rule(before), history, candidate, result), + junco_core::spec::hypotheses::event_obligations::() ==> match result { + Ok(answer) => answer == dsl::rule_evaluation( + source_rule(before)@, candidate, raw::raw_events(history)), + Err(_) => true, + }, + {} + + pub open(crate) spec fn numeric_result(template: FlatPair, request: history_store::store::Event, + stored: StoredHistory, result: Result, HistoryError>) -> bool { + result matches Ok(answer) ==> match answer { + None => crate::compile::verify::head_rejects(template, request), + Some(accepted) => exists|bindings: junco_core::kernel::Bindings| + crate::compile::verify::bindings_match(template, request, bindings) + && junco_core::verify::history_specs::event_wf(bindings@, bindings@.len()) + && accepted == crate::compile::verify::source_regex(template, template.root as nat, + bindings@, history_store::store::verify::events_view(raw::stored_events(&stored))), + } + } + + pub(crate) proof fn lemma_typed_result(compiled: CompiledRule, history: History, candidate: E, + request: history_store::store::Event, maps: books::ComponentMaps, result: Result, HistoryError>) + requires compiled_wf(compiled), raw::history_wf(history), junco_core::spec::hypotheses::event_obligations::(), + books::maps_wf::(maps), books::maps_extend::(compiled.maps@, maps), + books::maps_extend::(raw::history_maps(history), maps), books::event_encoded::(maps, candidate, request), + numeric_result(compiled.template, request, *history.numeric(), result), + ensures dsl_result(compiled.source@, history, candidate, result), + { + raw::lemma_history_wf(history); + assert(raw::raw_word(history) =~= raw::raw_events(history).map( + |i: int, event: E| history_syntax::spec::events::event_view(event))); + let flat = choose|flat: junco_core::flat::FlatRule| + source::flattened::(compiled.source@, flat) + && encoding::lowering(flat.source, compiled.template, compiled.maps@, source::component_equality::()) + && encoding::constants_in_domain(flat.source, books::domain::()); + assert(compiled.source@.head@.len() == history_syntax::spec::events::arity::()); + assert(compiled.template.head@.len() == compiled.source@.head@.len()); + assert(history_syntax::spec::events::event_view(candidate).len() == compiled.source@.head@.len()); + let numeric_word = raw::stored_events(history.numeric()).map(|i: int, event: history_store::store::Event| books::numeric_values(event)); + assert forall|i: int| 0 <= i < raw::raw_events(history).len() implies + books::event_encoded::(maps, raw::raw_events(history)[i], raw::stored_events(history.numeric())[i]) by { + books::lemma_event_extension::(raw::history_maps(history), maps, raw::raw_events(history)[i], raw::stored_events(history.numeric())[i]); + } + assert forall|i: int| 0 <= i < numeric_word.len() implies + numeric_word[i].len() == books::numeric_values(request).len() by { + assert(books::event_encoded::(maps, raw::raw_events(history)[i], + raw::stored_events(history.numeric())[i])); + } + assert(encoding::word_encoded(maps, source::component_equality::(), books::domain::(), + raw::raw_word(history), numeric_word)); + assert(junco_core::verify::encoding::word_representation(numeric_word, + history_store::store::verify::events_view(raw::stored_events(history.numeric())))); + encoding::lemma_dsl_later_maps_preservation::(compiled.source@, flat, compiled.template, + compiled.maps@, maps, books::domain::(), history_syntax::spec::events::event_view(candidate), raw::raw_word(history), + books::numeric_values(request), numeric_word); + crate::compile::verify::lemma_flat_head(compiled.template, books::numeric_values(request), request@); + if let Ok(answer) = result { + match answer { + None => crate::compile::verify::lemma_head_rejects(compiled.template, request), + Some(accepted) => { + let bindings = choose|bindings: junco_core::kernel::Bindings| + crate::compile::verify::bindings_match(compiled.template, request, bindings) + && junco_core::verify::history_specs::event_wf(bindings@, bindings@.len()) + && accepted == crate::compile::verify::source_regex(compiled.template, + compiled.template.root as nat, bindings@, + history_store::store::verify::events_view(raw::stored_events(history.numeric()))); + crate::compile::verify::lemma_bindings_match(compiled.template, request, bindings); + crate::compile::verify::lemma_flat_regex(compiled.template, compiled.template.root as nat, + books::numeric_values(request), request@, numeric_word, + history_store::store::verify::events_view(raw::stored_events(history.numeric())), bindings@); + }, + } + } + } + } +} + +verus! { +pub(crate) type LoweredRule = (RuleMode, FlatPair, Ghost>); + +impl CompiledRule { + /// Flatten before locking; publish one finite snapshot after encoding constants. + fn lower( + store: &Store, rule: &Rule, limits: &mut L, world: &mut ObservationWorld, + ) -> (result: Result, CompileError>) + requires books::store_wf(*store), + ensures result matches Ok((mode, numeric, maps)) ==> mode == rule.mode + && junco_core::flat::verify::structural_wf(numeric) + && books::snapshot_published::(books::registry_id(store), maps@) + && (junco_core::spec::hypotheses::event_obligations::() ==> books::maps_wf::(maps@) + && compiled_source::(*rule, mode, numeric, maps@, + source::component_equality::(), books::domain::())), + junco_core::spec::hypotheses::event_obligations::() ==> no_invariant_compile_failure(result), + junco_core::spec::hypotheses::event_obligations::() && dsl::head_scoped(rule.head@) + && dsl::regex_scoped(rule.tail@, rule.head@) + ==> !(result matches Err(CompileError::VariableComponentConflict { .. })) + && !(result matches Err(CompileError::UnboundVariable { .. })) + && !(result matches Err(CompileError::Runtime(HistoryError::InvalidPolicy { .. }))), + junco_core::spec::hypotheses::event_obligations::() && dsl::rule_wf(rule@) + && rule@.head.len() == history_syntax::spec::events::arity::() + && dsl::rule_constants_tagged::(rule@) + ==> (result is Ok || (result matches Err(CompileError::Runtime(error)) && dsl::resource_error(error))), + { + let flat = flatten_rule(rule, limits, world)?; + proof_decl! { let ghost flattened = flat; } + proof! { + books::lemma_empty_snapshot::(store); + if junco_core::spec::hypotheses::event_obligations::() { + books::lemma_native_obligations_projection::(); + books::lemma_empty_maps_wf::(); + assert(encoding::constants_in_domain(flat.source, books::domain::())); + } + } + let (result, maps) = store.lower_with_snapshot(&flat.source, limits, world, + verus_exec_expr! { Ghost(books::empty_maps::()) }); + let numeric = result?; + proof! { + if junco_core::spec::hypotheses::event_obligations::() { + assert(source::flattened::(*rule, flattened)); + assert(compiled_source::(*rule, flat.mode, numeric, maps@, + source::component_equality::(), books::domain::())); + } + } + Ok((flat.mode, numeric, maps)) + } +} +} + +/// A rule owns one graph generation; all histories and constants share its store. +#[verus_verify] +pub struct CompiledRule { + pub(crate) template: FlatPair, + pub(crate) mode: RuleMode, + pub(crate) store: Arc>, + pub(crate) runtime: RuleRuntime, + #[cfg(verus_keep_ghost)] + pub(crate) source: Ghost>, + #[cfg(verus_keep_ghost)] + pub(crate) maps: Ghost>, + #[cfg(verus_keep_ghost)] + pub(crate) observations: Tracked>, +} + +#[cfg(verus_keep_ghost)] +verus! { +impl CompiledRule { + pub closed spec fn mode_spec(&self) -> RuleMode { self.mode } +} +} + +#[verus_verify] +impl CompiledRule { + // Pointer comparison relates native identity to contents, never registry equality to identity. + #[doc(hidden)] + #[verus_verify] + #[verus_verify(external_body)] + #[verus_spec(result => ensures + result == (junco_core::verify::history_assumptions::arc_identity(*left) + == junco_core::verify::history_assumptions::arc_identity(*right)), + result == books::same_store_owner(*left, *right), + result ==> *left == *right && **left == **right)] + pub fn same_owner(left: &Arc>, right: &Arc>) -> bool { + Arc::ptr_eq(left, right) + } + + /// Consume the source on every outcome using its iterative disposal path. + /// Native event laws exclude internal failures; scoped sources also exclude scope/validation diagnostics. + #[verus_spec(result => requires books::store_wf(*store), + ensures result matches Ok(compiled) ==> constructed(compiled, rule, store), + junco_core::spec::hypotheses::event_obligations::() ==> no_invariant_compile_failure(result), + junco_core::spec::hypotheses::event_obligations::() && dsl::head_scoped(rule.head@) + && dsl::regex_scoped(rule.tail@, rule.head@) + ==> !(result matches Err(CompileError::VariableComponentConflict { .. })) + && !(result matches Err(CompileError::UnboundVariable { .. })) + && !(result matches Err(CompileError::Runtime(HistoryError::InvalidPolicy { .. }))), + junco_core::spec::hypotheses::event_obligations::() && dsl::rule_wf(rule@) + && rule@.head.len() == history_syntax::spec::events::arity::() + && dsl::rule_constants_tagged::(rule@) + ==> (result is Ok || (result matches Err(CompileError::Runtime(error)) && dsl::resource_error(error))))] + pub fn new(store: Arc>, rule: Rule) -> Result { + Self::new_with_limits(store, rule, &mut Unmetered, &mut ObservationWorld) + } + + #[verus_spec(result => requires books::store_wf(*store), + ensures result matches Ok(compiled) ==> constructed(compiled, rule, store), + junco_core::spec::hypotheses::event_obligations::() ==> no_invariant_compile_failure(result), + junco_core::spec::hypotheses::event_obligations::() && dsl::head_scoped(rule.head@) + && dsl::regex_scoped(rule.tail@, rule.head@) + ==> !(result matches Err(CompileError::VariableComponentConflict { .. })) + && !(result matches Err(CompileError::UnboundVariable { .. })) + && !(result matches Err(CompileError::Runtime(HistoryError::InvalidPolicy { .. }))), + junco_core::spec::hypotheses::event_obligations::() && dsl::rule_wf(rule@) + && rule@.head.len() == history_syntax::spec::events::arity::() + && dsl::rule_constants_tagged::(rule@) + ==> (result is Ok || (result matches Err(CompileError::Runtime(error)) && dsl::resource_error(error))))] + pub(crate) fn new_with_limits( + store: Arc>, + rule: Rule, + limits: &mut L, + world: &mut ObservationWorld, + ) -> Result { + Self::construct(store, rule, cfg!(feature = "cache"), limits, world) + } + + #[verus_spec(result => requires books::store_wf(*store), + ensures result matches Ok(compiled) ==> constructed(compiled, rule, store), + junco_core::spec::hypotheses::event_obligations::() ==> no_invariant_compile_failure(result), + junco_core::spec::hypotheses::event_obligations::() && dsl::head_scoped(rule.head@) + && dsl::regex_scoped(rule.tail@, rule.head@) + ==> !(result matches Err(CompileError::VariableComponentConflict { .. })) + && !(result matches Err(CompileError::UnboundVariable { .. })) + && !(result matches Err(CompileError::Runtime(HistoryError::InvalidPolicy { .. }))), + junco_core::spec::hypotheses::event_obligations::() && dsl::rule_wf(rule@) + && rule@.head.len() == history_syntax::spec::events::arity::() + && dsl::rule_constants_tagged::(rule@) + ==> (result is Ok || (result matches Err(CompileError::Runtime(error)) && dsl::resource_error(error))))] + fn construct( + store: Arc>, + rule: Rule, + precompile: bool, + limits: &mut L, + world: &mut ObservationWorld, + ) -> Result { + proof_decl! { let ghost source = rule; } + // No `?` may bypass disposal of the caller's recursive owned source. + let owner = history_store::typed::borrow_store(&store); + let lowered = Self::lower(owner, &rule, limits, world); + rule.dispose(); + let (mode, template, _maps) = lowered?; + let runtime = + RuleRuntime::new(store.numeric_store(), &template, precompile, limits, world)?; + proof_decl! { let tracked observations = Map::<(usize, u64), ObservedHistory>::tracked_empty(); } + Ok(Self { + template, + mode, + store, + runtime, + #[cfg(verus_keep_ghost)] + source: verus_exec_expr! { Ghost(source) }, + #[cfg(verus_keep_ghost)] + maps: _maps, + #[cfg(verus_keep_ghost)] + observations: verus_exec_expr! { Tracked(observations) }, + }) + } + + #[verus_spec(result => ensures result == self.mode_spec())] + pub const fn mode(&self) -> RuleMode { + proof! { reveal(CompiledRule::mode_spec); } + self.mode + } + + /// `None` is only a head mismatch; operational errors never become verdicts. + /// Foreign native store owners yield `WrongHistoryOwner`; matching owners never do. + /// Readiness excludes internal invariant failures on both matching and foreign-owner paths. + #[verus_spec(result => requires decision_requires(*old(self), *history), + ensures decision_result(*old(self), *final(self), *history, *candidate, result), + no_invariant_failure(result), + junco_core::spec::hypotheses::event_obligations::() + && compiled_store(*old(self)) == raw::store_of(*history) + ==> (result matches Err(error) ==> dsl::resource_error(error)))] + pub fn accepts_history( + &mut self, + history: &History, + candidate: &E, + ) -> Result, HistoryError> { + self.accepts_history_with_limits(history, candidate, &mut Unmetered, &mut ObservationWorld) + } + + #[verus_spec(result => requires decision_requires(*old(self), *history), + ensures decision_result(*old(self), *final(self), *history, *candidate, result), + no_invariant_failure(result), + junco_core::spec::hypotheses::event_obligations::() + && compiled_store(*old(self)) == raw::store_of(*history) + ==> (result matches Err(error) ==> dsl::resource_error(error)))] + pub(crate) fn accepts_history_with_limits( + &mut self, + history: &History, + candidate: &E, + limits: &mut L, + world: &mut ObservationWorld, + ) -> Result, HistoryError> { + proof_decl! { let ghost entry = *self; } + // Check before projections, codebook publication, or any residual lookup. + if !Self::same_owner(&self.store, history.store()) { + return Err(HistoryError::WrongHistoryOwner); + } + proof! { + raw::lemma_history_wf(*history); + assert(history.id() == history.numeric().id()); + history_store::history::lemma_stored_history_view(*history.numeric()); + let ghost registry = books::registry_id(&self.store); + lemma_history_compatible(registry, history.id(), *history.numeric(), + self.runtime.snapshots@, self.observations.borrow(), history.registration_ref(), history.lifecycle_ref()); + let key = (history.id(), history.numeric().revision()); + let events = history_store::store::verify::events_view(raw::stored_events(history.numeric())); + crate::runtime::verify::lemma_cursor_cache_observe(self.runtime.pair, + self.runtime.cursors@, self.runtime.snapshots@, history.id(), history.numeric().revision(), events); + let tracked observation = ObservedHistory { + snapshot: history.lifecycle_ref().observe(), + registration: history.registration_ref().duplicate(), + }; + lemma_observations_insert(registry, self.runtime.snapshots@, self.observations@, key, events, observation); + self.observations.borrow_mut().tracked_insert(key, observation); + *self.runtime.snapshots = self.runtime.snapshots@.insert(key, events); + assert(compiled_wf(*self)); + } + let owner = history_store::typed::borrow_store(&self.store); + let (encoded, _maps) = owner.encode_event_with_snapshot( + candidate, + verus_exec_expr! { Ghost(self.maps@) }, + verus_exec_expr! { Ghost(raw::history_maps(*history)) }, + ); + let request = encoded?; + proof_decl! { let ghost observed = self.runtime.snapshots@; } + let first = + self.runtime + .accepts(&self.template, &request, history.numeric(), limits, world); + proof! { + let key = (history.id(), history.numeric().revision()); + let events = history_store::store::verify::events_view(raw::stored_events(history.numeric())); + assert(observed.insert(key, events) =~= observed); + assert(self.runtime.snapshots@ == observed); + assert(compiled_wf(*self)); + } + let result = match first { + Err(HistoryError::GraphBudget { .. } | HistoryError::GraphIndex) => { + // A failed replacement must not discard the old committed cursor cache. + let mut replacement = RuleRuntime::new( + self.store.numeric_store(), + &self.template, + cfg!(feature = "cache"), + limits, + world, + )?; + proof_decl! { let tracked mut replacement_observations = Map::<(usize, u64), ObservedHistory>::tracked_empty(); } + proof! { + history_store::history::lemma_stored_history_view(*history.numeric()); + let tracked observation = ObservedHistory { + snapshot: history.lifecycle_ref().observe(), + registration: history.registration_ref().duplicate(), + }; + let key = (history.id(), history.numeric().revision()); + let events = history_store::store::verify::events_view(raw::stored_events(history.numeric())); + lemma_observations_insert(books::registry_id(&self.store), replacement.snapshots@, + replacement_observations, key, events, observation); + replacement_observations.tracked_insert(key, observation); + *replacement.snapshots = replacement.snapshots@.insert(key, events); + assert(decision::runtime_represents(self.template, replacement)); + } + proof_decl! { let ghost new_snapshots = replacement.snapshots@; } + let answer = replacement.accepts( + &self.template, + &request, + history.numeric(), + limits, + world, + )?; + proof! { + let key = (history.id(), history.numeric().revision()); + let events = history_store::store::verify::events_view(raw::stored_events(history.numeric())); + assert(new_snapshots.insert(key, events) =~= new_snapshots); + assert(replacement.snapshots@ == new_snapshots); + assert(observations_wf(books::registry_id(&self.store), + replacement.snapshots@, replacement_observations)); + } + self.runtime = replacement; + proof! { + *self.observations = replacement_observations; + assert(compiled_wf(*self)); + } + Ok(answer) + } + other => other, + }; + proof! { + if junco_core::spec::hypotheses::event_obligations::() { + lemma_typed_result(entry, *history, *candidate, request, _maps@, result); + } + } + result + } +} + +#[cfg(any(test, feature = "test-util"))] +impl CompiledRule { + /// Construct the same runtime without optional precompilation for work probes. + pub fn new_lazy(store: Arc>, rule: Rule) -> Result { + Self::construct(store, rule, false, &mut Unmetered, &mut ObservationWorld) + } + + pub fn work_counters(&self) -> &crate::runtime::WorkCounters { + self.runtime.work_counters() + } + + pub fn work_events(&self) -> usize { + self.runtime.work_events() + } + + pub fn reset_work_events(&mut self) { + self.runtime.reset_work_events(); + } + + pub fn cursor_positions( + &self, + ) -> alloc::vec::Vec<(usize, junco_core::kernel::Bindings, u64, usize)> { + self.runtime.cursor_positions() + } + + pub fn replace_graph_byte_pressure(&mut self, bytes: usize) -> usize { + self.runtime.replace_graph_byte_pressure(bytes) + } + + pub fn set_answer_checkpoint_failure(&mut self, fail: bool) { + self.runtime.set_answer_checkpoint_failure(fail); + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + use history_syntax::syntax::{ + AtomPattern, Comparison, Component, ComponentPattern, Head, RegexExpr, TestExpr, + }; + use history_syntax::{Component3, N3}; + use junco_core::limits::LimitError; + + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] + struct Probe(u8, u8, u8); + + impl Event for Probe { + type Component = Component3; + type Arity = N3; + fn component(self, index: usize) -> Self::Component { + match index { + 0 => Component3::C0(self.0), + 1 => Component3::C1(self.1), + _ => Component3::C2(self.2), + } + } + fn coordinate(component: Self::Component) -> usize { + match component { + Component3::C0(_) => 0, + Component3::C1(_) => 1, + Component3::C2(_) => 2, + } + } + } + + fn head() -> Head { + Head::new([ + ComponentPattern::variable("actor"), + ComponentPattern::constant(Component3::C1(2)), + ComponentPattern::variable("resource"), + ]) + } + + fn reads() -> Rule { + Rule::new( + RuleMode::Require, + head(), + RegexExpr::star(RegexExpr::test(TestExpr::atom( + Comparison::Eq, + AtomPattern::new(Component(1), ComponentPattern::constant(Component3::C1(1))), + ))), + ) + } + + #[test] + fn consuming_constructor_disposes_deep_success_and_unbound_failure() { + let store = Arc::new(Store::new().unwrap()); + let mut valid = RegexExpr::epsilon(); + let mut invalid = RegexExpr::test(TestExpr::atom( + Comparison::Eq, + AtomPattern::new(Component(0), ComponentPattern::variable("missing")), + )); + for _ in 0..4096 { + valid = RegexExpr::star(valid); + invalid = RegexExpr::star(invalid); + } + let mut compiled = CompiledRule::new( + Arc::clone(&store), + Rule::new(RuleMode::Require, head(), valid), + ) + .unwrap(); + let history = History::new(Arc::clone(&store)).unwrap(); + assert_eq!( + compiled.accepts_history(&history, &Probe(1, 2, 1)), + Ok(Some(true)) + ); + assert!(matches!(CompiledRule::new(store, + Rule::new(RuleMode::Require, head(), invalid)), + Err(CompileError::UnboundVariable { name }) if name == "missing")); + } + + struct FailPublication; + impl Limits for FailPublication { + fn checkpoint(&mut self) -> Result<(), LimitError> { + Ok(()) + } + fn publication_checkpoint(&mut self) -> Result<(), LimitError> { + Err(LimitError::MemoryLimitExceeded { usage: 2, limit: 1 }) + } + fn enforce_memory(&mut self) -> Result<(), LimitError> { + Ok(()) + } + } + + #[test] + fn answer_and_publication_errors_preserve_committed_cursors_and_history() { + let store = Arc::new(Store::new().unwrap()); + let mut history = History::from_events(Arc::clone(&store), [Probe(1, 1, 1)]).unwrap(); + let mut compiled = CompiledRule::new_lazy(store, reads()).unwrap(); + let candidate = Probe(1, 2, 1); + assert_eq!( + compiled.accepts_history(&history, &candidate), + Ok(Some(true)) + ); + let prior = compiled.cursor_positions(); + history.push(Probe(1, 1, 1)).unwrap(); + let revision = history.numeric().revision(); + let raw = history.as_slice().to_vec(); + let numeric = history.numeric().as_slice().to_vec(); + + compiled.set_answer_checkpoint_failure(true); + assert!(matches!( + compiled.accepts_history(&history, &candidate), + Err(HistoryError::Limit(_)) + )); + compiled.set_answer_checkpoint_failure(false); + assert_eq!(compiled.cursor_positions(), prior); + assert!(matches!( + compiled.accepts_history_with_limits( + &history, + &candidate, + &mut FailPublication, + &mut ObservationWorld + ), + Err(HistoryError::Limit(_)) + )); + assert_eq!(compiled.cursor_positions(), prior); + assert_eq!(history.as_slice(), raw); + assert_eq!(history.numeric().as_slice(), numeric); + assert_eq!(history.numeric().revision(), revision); + assert_eq!( + compiled.accepts_history(&history, &candidate), + Ok(Some(true)) + ); + } + + #[test] + fn failed_graph_replacement_keeps_old_generation_cache() { + let store = Arc::new(Store::new().unwrap()); + let mut history = History::from_events(Arc::clone(&store), [Probe(1, 1, 1)]).unwrap(); + let read = || { + RegexExpr::test(TestExpr::atom( + Comparison::Eq, + AtomPattern::new(Component(1), ComponentPattern::constant(Component3::C1(1))), + )) + }; + let rule = Rule::new( + RuleMode::Require, + head(), + RegexExpr::concat([read(), RegexExpr::star(read())]), + ); + let mut compiled = CompiledRule::new_lazy(store, rule).unwrap(); + let candidate = Probe(1, 2, 1); + assert_eq!( + compiled.accepts_history(&history, &candidate), + Ok(Some(true)) + ); + let prior = compiled.cursor_positions(); + history.push(Probe(1, 1, 1)).unwrap(); + let pressure = + compiled.replace_graph_byte_pressure(junco_core::limits::MAX_GRAPH_BYTES + 1); + let request = compiled + .store + .encode_event_with_snapshot(&candidate, Ghost::assume_new(), Ghost::assume_new()) + .0 + .unwrap(); + assert!(matches!( + compiled.runtime.accepts( + &compiled.template, + &request, + history.numeric(), + &mut Unmetered, + &mut ObservationWorld + ), + Err(HistoryError::GraphBudget { .. }) + )); + assert!(matches!( + compiled.accepts_history_with_limits( + &history, + &candidate, + &mut FailPublication, + &mut ObservationWorld + ), + Err(HistoryError::Limit(_)) + )); + assert_eq!(compiled.cursor_positions(), prior); + assert_eq!( + compiled.replace_graph_byte_pressure(pressure), + junco_core::limits::MAX_GRAPH_BYTES + 1 + ); + compiled.replace_graph_byte_pressure(junco_core::limits::MAX_GRAPH_BYTES + 1); + assert_eq!( + compiled.accepts_history(&history, &candidate), + Ok(Some(true)) + ); + assert_eq!(compiled.work_events(), 2); + compiled.reset_work_events(); + assert_eq!( + compiled.accepts_history(&history, &candidate), + Ok(Some(true)) + ); + assert_eq!(compiled.work_events(), 0); + } + + #[test] + fn candidate_allocation_failure_keeps_prior_cursors_and_history() { + let store = Arc::new(Store::new().unwrap()); + let history = History::from_events(Arc::clone(&store), [Probe(1, 1, 1)]).unwrap(); + let mut compiled = CompiledRule::new(store, reads()).unwrap(); + assert_eq!( + compiled.accepts_history(&history, &Probe(1, 2, 1)), + Ok(Some(true)) + ); + let prior = compiled.cursor_positions(); + let failure = junco_core::observation::fail_reservations_after(0); + assert_eq!( + compiled.accepts_history(&history, &Probe(2, 2, 1)), + Err(HistoryError::AllocationFailed) + ); + drop(failure); + assert_eq!(compiled.cursor_positions(), prior); + assert_eq!(history.as_slice(), [Probe(1, 1, 1)]); + assert_eq!(history.numeric().len(), 1); + assert_eq!(history.numeric().revision(), 0); + assert_eq!( + compiled.accepts_history(&history, &Probe(2, 2, 1)), + Ok(Some(true)) + ); + } + + #[test] + fn foreign_owner_is_rejected_before_even_head_mismatch_projections() { + use core::sync::atomic::{AtomicUsize, Ordering}; + static PROJECTIONS: AtomicUsize = AtomicUsize::new(0); + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] + struct Counted(Probe); + impl Event for Counted { + type Component = ::Component; + type Arity = N3; + fn component(self, index: usize) -> Self::Component { + PROJECTIONS.fetch_add(1, Ordering::SeqCst); + self.0.component(index) + } + fn coordinate(component: Self::Component) -> usize { + Probe::coordinate(component) + } + } + let store = Arc::new(Store::new().unwrap()); + let foreign = Arc::new(Store::new().unwrap()); + let rule = Rule::::new( + RuleMode::Require, + Head::new([ + ComponentPattern::variable("actor"), + ComponentPattern::constant(Component3::C1(2)), + ComponentPattern::variable("resource"), + ]), + RegexExpr::epsilon(), + ); + let mut compiled = CompiledRule::new(store, rule).unwrap(); + let history = History::new(foreign).unwrap(); + assert_eq!( + compiled.accepts_history(&history, &Counted(Probe(1, 3, 1))), + Err(HistoryError::WrongHistoryOwner) + ); + assert_eq!(PROJECTIONS.load(Ordering::SeqCst), 0); + assert!(compiled.cursor_positions().is_empty()); + } + + #[test] + fn four_coordinate_decisions_bind_and_retain_the_whole_candidate() { + use history_syntax::Component4; + type Four = (u8, u8, u8, u8); + + let variable = |index, name| { + TestExpr::::atom( + Comparison::Eq, + AtomPattern::new(Component(index), ComponentPattern::variable(name)), + ) + }; + let rule = Rule::::new( + RuleMode::Require, + Head::new([ + ComponentPattern::variable("principal"), + ComponentPattern::variable("handle"), + ComponentPattern::constant(Component4::C2(3)), + ComponentPattern::variable("label"), + ]), + RegexExpr::star(RegexExpr::test(TestExpr::and([ + variable(0, "principal"), + variable(1, "handle"), + TestExpr::atom( + Comparison::Eq, + AtomPattern::new(Component(2), ComponentPattern::constant(Component4::C2(1))), + ), + variable(3, "label"), + ]))), + ); + let store = Arc::new(Store::::new().unwrap()); + let mut history = History::from_events(Arc::clone(&store), [(7, 11, 1, 9); 2]).unwrap(); + let mut compiled = CompiledRule::new(store, rule).unwrap(); + let matching = (7, 11, 3, 9); + assert_eq!( + compiled.accepts_history(&history, &matching), + Ok(Some(true)) + ); + for different in [(8, 11, 3, 9), (7, 12, 3, 9), (7, 11, 3, 8)] { + assert_eq!( + compiled.accepts_history(&history, &different), + Ok(Some(false)) + ); + } + assert_eq!(compiled.accepts_history(&history, &(7, 11, 4, 9)), Ok(None)); + history.push((7, 11, 1, 8)).unwrap(); + assert_eq!( + compiled.accepts_history(&history, &matching), + Ok(Some(false)) + ); + history.truncate(2).unwrap(); + assert_eq!( + compiled.accepts_history(&history, &matching), + Ok(Some(true)) + ); + } +} diff --git a/src/history-semantics/src/error.rs b/src/history-semantics/src/error.rs new file mode 100644 index 000000000..9fb87422e --- /dev/null +++ b/src/history-semantics/src/error.rs @@ -0,0 +1,49 @@ +use junco_core::errors::{CompileError, HistoryError}; +use vstd::prelude::*; + +/// Compilation or execution failure from a one-shot policy decision. +#[cfg(feature = "runtime")] +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum PolicyError { + /// The policy source could not be compiled. + #[error(transparent)] + Compile(CompileError), + /// The compiled policy could not complete its decision. + #[error(transparent)] + Runtime(HistoryError), +} + +#[cfg(feature = "runtime")] +#[verus_verify] +impl From for PolicyError { + #[verus_spec(result => ensures result == Self::Compile(error))] + fn from(error: CompileError) -> Self { + Self::Compile(error) + } +} + +#[cfg(feature = "runtime")] +#[verus_verify] +impl From for PolicyError { + #[verus_spec(result => ensures result == Self::Runtime(error))] + fn from(error: HistoryError) -> Self { + Self::Runtime(error) + } +} + +#[cfg(verus_keep_ghost)] +verus! { +#[cfg(feature = "runtime")] +impl vstd::std_specs::convert::FromSpecImpl for PolicyError { + open spec fn obeys_from_spec() -> bool { true } + open spec fn from_spec(error: CompileError) -> Self { Self::Compile(error) } +} + +#[cfg(feature = "runtime")] +impl vstd::std_specs::convert::FromSpecImpl for PolicyError { + open spec fn obeys_from_spec() -> bool { true } + open spec fn from_spec(error: HistoryError) -> Self { Self::Runtime(error) } +} +} diff --git a/src/history-semantics/src/graph_tests.rs b/src/history-semantics/src/graph_tests.rs new file mode 100644 index 000000000..c86aa6d52 --- /dev/null +++ b/src/history-semantics/src/graph_tests.rs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +#![allow(clippy::panic_in_result_fn)] +use crate::normalize::RegexNormalize; +use crate::progress::CompiledPair; +use crate::symbolic::{RegexDerivative, TransitionInterpret}; +use alloc::vec::Vec; +use history_store::graph::{CanonicalStore, RuntimeKernel}; +use junco_core::kernel::*; +use junco_core::observation::ObservationWorld; +#[test] +fn interned_nodes_keep_ids_bytes_and_derivative_semantics() -> KernelResult<()> { + let mut world = ObservationWorld; + let mut limits = junco_core::limits::Unmetered; + let mut graph = CanonicalStore::new()?; + let mut store = RuntimeKernel { + store: &mut graph, + limits: &mut limits, + world: &mut world, + }; + let node = TestView::Atom { + primitive: Primitive::Eq { + field: history_syntax::syntax::Component(0), + term: Term::Constant(0), + }, + positive: true, + }; + let test = store.intern_test(node)?; + let regex = store.intern_regex(RegexKindView::Test(test), false)?; + let transition_node = TransitionView::If { + test, + then_transition: store.constants().transition_epsilon, + else_transition: store.constants().transition_empty, + }; + let transition = store.intern_transition(transition_node)?; + let and = store.intern_test(TestView::And(&[test, store.constants().test_true]))?; + let lists = store.store.table_counts().map(|counts| counts.0); + let or = store.intern_test(TestView::Or(&[test, store.constants().test_true]))?; + assert_ne!(and, or); + assert_eq!(store.store.table_counts().map(|counts| counts.0), lists); + assert_eq!( + store.test(or)?, + TestView::Or(&[test, store.constants().test_true]) + ); + let bytes = store.store.charged_bytes(); + let rows = store.store.table_counts().map(|counts| counts.1); + assert_eq!(store.intern_test(node)?, test); + assert_eq!(store.intern_regex(RegexKindView::Test(test), false)?, regex); + assert_eq!(store.intern_transition(transition_node)?, transition); + assert_eq!( + store.intern_test(TestView::And(&[test, store.constants().test_true]),)?, + and + ); + assert_eq!(store.store.charged_bytes(), bytes); + assert_eq!(store.store.table_counts().map(|counts| counts.1), rows); + let mut kernel = store; + let mut derivatives = Vec::new(); + assert_eq!( + RegexId::derivative(regex, &mut kernel, &mut derivatives)?, + transition + ); + let atoms = CompiledPair::collect_atoms(&mut kernel, transition)?; + let accepted = TransitionId::interpret(transition, &mut kernel, &atoms, &[1])?; + assert!(RegexId::nullable(accepted, &kernel)?); + Ok(()) +} diff --git a/src/history-semantics/src/lib.rs b/src/history-semantics/src/lib.rs new file mode 100644 index 000000000..774a56758 --- /dev/null +++ b/src/history-semantics/src/lib.rs @@ -0,0 +1,66 @@ +#![no_std] +#![cfg_attr(not(verus_keep_ghost), forbid(unsafe_code))] +#![cfg_attr(verus_keep_ghost, feature(proc_macro_hygiene, allocator_api))] +#![cfg_attr(docsrs, feature(doc_cfg))] + +extern crate alloc; +#[cfg(any(feature = "std", test))] +extern crate std; + +#[cfg(feature = "runtime")] +pub(crate) mod compile; +#[cfg(feature = "runtime")] +#[cfg_attr(docsrs, doc(cfg(feature = "runtime")))] +pub mod compiled_rule; +#[cfg(feature = "runtime")] +#[cfg_attr(docsrs, doc(cfg(feature = "runtime")))] +mod error; +#[cfg(feature = "runtime")] +pub(crate) mod normalize; +#[cfg(feature = "runtime")] +#[cfg_attr(docsrs, doc(cfg(feature = "runtime")))] +pub mod policy; +#[cfg(feature = "runtime")] +pub(crate) mod progress; +#[cfg(feature = "runtime")] +#[cfg_attr(docsrs, doc(cfg(feature = "runtime")))] +pub mod runtime; +#[cfg(all(verus_keep_ghost, feature = "runtime"))] +pub mod spec; +#[cfg(feature = "runtime")] +pub(crate) mod symbolic; +#[cfg(feature = "runtime")] +#[cfg_attr(docsrs, doc(cfg(feature = "runtime")))] +mod symbolic_language; +#[cfg(feature = "runtime")] +#[cfg_attr(docsrs, doc(cfg(feature = "runtime")))] +pub mod validator; +#[cfg(all(verus_keep_ghost, feature = "runtime"))] +pub mod verify; +#[cfg(all(verus_keep_ghost, feature = "runtime"))] +pub use compile::verify as compile_verify; +#[cfg(all(verus_keep_ghost, feature = "runtime"))] +pub use normalize::verify as normalize_verify; +#[cfg(all(verus_keep_ghost, feature = "runtime"))] +pub use symbolic::verify as symbolic_verify; + +#[cfg(feature = "runtime")] +pub(crate) type WorkVec = smallvec::SmallVec<[T; 4]>; + +#[cfg(feature = "runtime")] +pub use compiled_rule::CompiledRule; +#[cfg(feature = "runtime")] +pub use error::PolicyError; +#[cfg(feature = "runtime")] +pub use policy::{PolicyDecision, TracePolicy, TraceRule}; +#[cfg(feature = "runtime")] +pub use runtime::RuleRuntime; +#[cfg(feature = "runtime")] +pub use symbolic_language::SymbolicLanguage; +#[cfg(all(verus_keep_ghost, feature = "runtime"))] +pub use symbolic_language::verify as symbolic_language_verify; +#[cfg(feature = "runtime")] +pub use validator::{Decision, Denial, Validator}; + +#[cfg(all(test, feature = "runtime"))] +mod graph_tests; diff --git a/src/history-semantics/src/normalize.rs b/src/history-semantics/src/normalize.rs new file mode 100644 index 000000000..a2a98ea24 --- /dev/null +++ b/src/history-semantics/src/normalize.rs @@ -0,0 +1,16458 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +use crate::WorkVec; +#[cfg(verus_keep_ghost)] +use crate::symbolic::verify as vocab; +#[cfg(verus_keep_ghost)] +use crate::verify::finite_branch as fbr; +#[cfg(verus_keep_ghost)] +use crate::verify::finite_collect as fcol; +#[cfg(verus_keep_ghost)] +use crate::verify::finite_compile as fcmp; +#[cfg(verus_keep_ghost)] +use crate::verify::finite_impl as fimpl; +#[cfg(verus_keep_ghost)] +use crate::verify::finite_link as flink; +#[cfg(verus_keep_ghost)] +use crate::verify::finite_machine as fmach; +#[cfg(verus_keep_ghost)] +use crate::verify::finite_steps as fsteps; +#[cfg(verus_keep_ghost)] +use crate::verify::finite_trans as ftr; +#[cfg(verus_keep_ghost)] +use alloc::boxed::Box; +use junco_core::errors::HistoryError; +#[cfg(verus_keep_ghost)] +use junco_core::kernel::verify as model; +use junco_core::kernel::*; +#[cfg(verus_keep_ghost)] +use junco_core::observation::SmallVecSpecFns; +#[cfg(verus_keep_ghost)] +use junco_core::spec::semantics::resource_error; +#[cfg(verus_keep_ghost)] +use junco_core::verify::history_assumptions::{KernelStoreSpec, dedup_spec}; +#[cfg(verus_keep_ghost)] +use junco_core::verify::history_specs as language; +#[cfg(verus_keep_ghost)] +use junco_core::verify::history_specs::{EventView, Subst}; +use junco_core::{loop_try, scan}; +#[cfg(verus_keep_ghost)] +use verify::*; +use vstd::prelude::*; +#[cfg(verus_keep_ghost)] +verus! { +broadcast use junco_core::kernel::verify::group_kernel_views; +} +#[cfg(verus_keep_ghost)] +use vstd::std_specs::cmp::{OrdSpec, PartialEqSpec}; + +#[verus_verify] +#[verus_spec(result => requires low < high, + ensures match result { Ok(mid) => low <= mid < high, Err(_) => false }, +)] +const fn midpoint(low: usize, high: usize) -> KernelResult { + match high.saturating_sub(low).checked_div(2) { + Some(half) => Ok(low.saturating_add(half)), + None => Err(HistoryError::normalization_invariant()), + } +} +#[allow( + clippy::option_if_let_else, + reason = "Explicit matches preserve the Verus proof structure." +)] +#[verus_verify] +#[verus_spec(result => ensures result != Err(HistoryError::WrongHistoryOwner), + index < ids@.len() ==> language::no_invariant_failure(result), match result { + Ok(id) => index < ids@.len() && id == ids@[index as int], + Err(_) => index >= ids@.len(), +})] +fn id_at(ids: &[T], index: usize) -> KernelResult { + match ids.get(index) { + Some(id) => Ok(*id), + None => Err(HistoryError::normalization_invariant()), + } +} +#[verus_verify] +#[verus_spec(result => + requires structural_eq::(), + ensures result is Ok, + final(values).view() == dedup_spec(old(values).view()), + forall|v: T| final(values).view().contains(v) <==> old(values).view().contains(v), + forall|i: int| 0 < i < final(values).view().len() + ==> final(values).view()[i - 1] != #[trigger] final(values).view()[i], +)] +fn dedup_ids(values: &mut WorkVec) -> KernelResult<()> { + proof_decl! { let ghost original = values.view(); } + proof! { assert(original.subrange(0, original.len() as int) =~= original); } + let count = values.len(); + let mut state = Ok((None, 0)); + scan!(state,index,count,state.is_ok(),prior=>{ + proof! { + if index > 0 { assert(original.subrange(0, index as int).last() == original[index as int - 1]); } + lemma_dedup_push(old(values).view().subrange(0, index as int), + old(values).view()[index as int]); + assert(old(values).view().subrange(0, index as int + 1) + =~= old(values).view().subrange(0, index as int).push(old(values).view()[index as int])); + } + { + proof_decl! { let ghost source = values.view(); } + match id_at(values, index) { + Ok(value) => { + let (previous, write) = prior; + let duplicate = match previous { Some(v) => v == value, None => false }; + if duplicate { Ok((previous, write)) } else { + if write != index { + match match values.as_mut_slice().get_mut(write) { + Some(slot) => { *slot = value; Ok(()) }, + None => Err(HistoryError::normalization_invariant()), + } { + Ok(()) => { + proof! { + assert(values.view().subrange(0, write as int + 1) + =~= source.subrange(0, write as int).push(value)); + assert(values.view().subrange(index as int + 1, source.len() as int) + =~= source.subrange(index as int + 1, source.len() as int)); + } + Ok((Some(value), write.saturating_add(1))) + } + Err(error) => Err(error), + } + } else { + proof! { + assert(values.view().subrange(0, write as int + 1) + =~= source.subrange(0, write as int).push(value)); + assert(values.view().subrange(index as int + 1, source.len() as int) + =~= source.subrange(index as int + 1, source.len() as int)); + } + Ok((Some(value), write.saturating_add(1))) + } + } + } + Err(error) => Err(error), + } + } + }; + invariant + structural_eq::(), + count == old(values).view().len(), + original == old(values).view(), + values.view().len() == count, + index <= count, + forall|j: int| index <= j < count ==> #[trigger] values.view()[j] == original[j], + match state { + Ok((previous, write)) => write <= index + && previous == (if index == 0 { None } else { Some(old(values).view()[index as int - 1]) }) + && values.view().subrange(0, write as int) + == dedup_spec(old(values).view().subrange(0, index as int)), + Err(_) => false, + }, + decreases count - index, + ); + let (_, len) = state?; + values.truncate(len); + proof! { lemma_dedup_properties(old(values).view()); } + Ok(()) +} +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy)] +struct TestMode { + and: bool, + identity: TestId, + absorber: TestId, +} + +#[verus_verify] +impl TestMode { + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + a@ < old(store).graph().tests.len(), b@ < old(store).graph().tests.len(), + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + model::graph_wf(final(store).graph()), final(store).valid_store(), + match result { Ok(found) => found ==> test_opposite(final(store).graph(), a, b), Err(_) => true }, + )] + fn opposite(store: &mut G, a: TestId, b: TestId) -> KernelResult { + let left = a.head(store)?; + let right = b.head(store)?; + match (left, right) { + (TestHead::Atom(p, x), TestHead::Atom(q, y)) => { + proof! { + assert forall|theta: Subst, event: EventView| p@ == q@ && x != y + implies test_truth(store.graph(), theta, a@, event) != test_truth(store.graph(), theta, b@, event) by { + test_lemma_truth(store.graph(), theta, a@, event); + test_lemma_truth(store.graph(), theta, b@, event); + } + } + Ok(p == q && x != y) + } + (TestHead::And(_), TestHead::Or(_)) | (TestHead::Or(_), TestHead::And(_)) => { + Ok(TestId::not(a, store)? == b) + } + (TestHead::True, TestHead::False) | (TestHead::False, TestHead::True) => { + proof! { + assert forall|theta: Subst, event: EventView| + test_truth(store.graph(), theta, a@, event) != test_truth(store.graph(), theta, b@, event) by { + test_lemma_truth(store.graph(), theta, a@, event); + test_lemma_truth(store.graph(), theta, b@, event); + } + } + Ok(true) + } + _ => Ok(false), + } + } + + #[verus_verify] + #[verus_spec(result => ensures result == test_distinct_heads(left@, right@))] + fn distinct(left: TestHead, right: TestHead) -> bool { + matches!((left,right),(TestHead::Atom(Primitive::Eq{field:p,term:Term::Constant(c)},_),TestHead::Atom(Primitive::Eq{field:q,term:Term::Constant(d)},_)) if p==q&&c!=d) + } + + #[allow( + clippy::missing_const_for_fn, + reason = "Preserve the existing Verus-verified function shape." + )] + #[verus_verify] + #[verus_spec(result => ensures result == match head@ { + model::TestHeadNode::Or(n) => if self.and { Some(n as usize) } else { None }, + model::TestHeadNode::And(n) => if !self.and { Some(n as usize) } else { None }, + _ => None, + })] + fn dual_count(self, head: TestHead) -> Option { + match head { + TestHead::Or(n) if self.and => Some(n), + TestHead::And(n) if !self.and => Some(n), + _ => None, + } + } + + #[allow( + clippy::semicolon_if_nothing_returned, + reason = "Preserve the existing Verus-verified mutation branches." + )] + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(store.graph()), test_child_count(store.graph(), parent, count as nat), + ensures store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> language::no_invariant_failure(result), + store.errors_are_non_invalid_policy() && store.valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + store.errors_are_resource() && store.valid_store() ==> (result matches Err(e) ==> resource_error(e)), + match result { + Ok(found) => found == test_children(store.graph(), parent).contains(id@), + Err(_) => true, + }, + )] + fn contains( + store: &G, + parent: TestId, + count: usize, + id: TestId, + ) -> KernelResult { + proof! { test_lemma_children(store.graph(), parent, count as nat); } + let mut low = 0; + let mut high = count; + let mut failure = None; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant + model::graph_wf(store.graph()), + test_child_count(store.graph(), parent, count as nat), + model::nondecreasing(test_children(store.graph(), parent)), + low <= high <= count, + forall|i: int| 0 <= i < low ==> #[trigger] test_children(store.graph(), parent)[i] < id@, + forall|i: int| high <= i < count ==> #[trigger] test_children(store.graph(), parent)[i] >= id@, + store.errors_are_non_owner() ==> failure != Some(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> (match failure { Some(error) => language::no_invariant_failure::<()>(Err(error)), None => true }), + store.errors_are_non_invalid_policy() && store.valid_store() ==> (match failure { Some(error) => !(error is InvalidPolicy), None => true }), + store.errors_are_resource() && store.valid_store() ==> (failure matches Some(e) ==> resource_error(e)), + ensures failure.is_none() ==> low == high, + decreases high - low, + ))] + while low < high { + let mid = loop_try!(midpoint(low, high), failure); + let child = loop_try!(parent.child(store, mid), failure); + if child < id { + proof! { + assert forall|i: int| 0 <= i <= mid + implies #[trigger] test_children(store.graph(), parent)[i] < id@ by { + assert(test_children(store.graph(), parent)[i] <= child@); + } + } + low = mid.saturating_add(1) + } else { + proof! { + assert forall|i: int| mid <= i < count + implies #[trigger] test_children(store.graph(), parent)[i] >= id@ by { + assert(test_children(store.graph(), parent)[i] >= child@); + } + } + high = mid + } + } + if let Some(error) = failure { + return Err(error); + } + if low < count { + Ok(parent.child(store, low)? == id) + } else { + Ok(false) + } + } + + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(store.graph()), + test_child_count(store.graph(), a, a_count as nat), + test_child_count(store.graph(), b, b_count as nat), + ensures store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> language::no_invariant_failure(result), + store.errors_are_non_invalid_policy() && store.valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + store.errors_are_resource() && store.valid_store() ==> (result matches Err(e) ==> resource_error(e)), + match result { + Ok(included) => included == (forall|i: int| 0 <= i < a_count + ==> test_children(store.graph(), b).contains(test_children(store.graph(), a)[i])) + && included == (forall|child: nat| test_children(store.graph(), a).contains(child) + ==> test_children(store.graph(), b).contains(child)), + Err(_) => true, + }, + )] + fn subset( + store: &G, + a: TestId, + a_count: usize, + b: TestId, + b_count: usize, + ) -> KernelResult { + proof! { + test_lemma_children(store.graph(), a, a_count as nat); + test_lemma_children(store.graph(), b, b_count as nat); + } + let mut included = true; + let mut failure = None; + let mut i = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant + model::graph_wf(store.graph()), + test_child_count(store.graph(), a, a_count as nat), + test_child_count(store.graph(), b, b_count as nat), + i <= a_count, + included == (forall|j: int| 0 <= j < i + ==> test_children(store.graph(), b).contains(test_children(store.graph(), a)[j])), + store.errors_are_non_owner() ==> failure != Some(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> (match failure { Some(error) => language::no_invariant_failure::<()>(Err(error)), None => true }), + store.errors_are_non_invalid_policy() && store.valid_store() ==> (match failure { Some(error) => !(error is InvalidPolicy), None => true }), + store.errors_are_resource() && store.valid_store() ==> (failure matches Some(e) ==> resource_error(e)), + ensures failure.is_none() ==> i == a_count, + decreases a_count - i, + ))] + while i < a_count { + let id = loop_try!(a.child(store, i), failure); + proof! { assert(id@ == test_children(store.graph(), a)[i as int]); } + included &= loop_try!(TestMode::contains(store, b, b_count, id), failure); + i = i.saturating_add(1); + } + if let Some(error) = failure { + return Err(error); + } + proof! { + assert(included == (forall|child: nat| test_children(store.graph(), a).contains(child) + ==> test_children(store.graph(), b).contains(child))) by { + if included { + assert forall|child: nat| test_children(store.graph(), a).contains(child) + implies test_children(store.graph(), b).contains(child) by { + let j = choose|j: int| 0 <= j < a_count && test_children(store.graph(), a)[j] == child; + } + } else { + let j = choose|j: int| 0 <= j < a_count + && !test_children(store.graph(), b).contains(test_children(store.graph(), a)[j]); + assert(test_children(store.graph(), a).contains(test_children(store.graph(), a)[j])); + } + } + } + Ok(included) + } + + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + a@ < old(store).graph().tests.len(), test_ids_valid(old(store).graph(), siblings@), + ensures model::graph_extends(old(store).graph(), final(store).graph()), model::graph_wf(final(store).graph()), final(store).valid_store(), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + match result { Ok(out) => out ==> test_absorbs(final(store).graph(), seq![a] + siblings@, self.and), Err(_) => true }, + )] + fn pair_collapses( + self, + store: &mut G, + a: TestId, + siblings: &[TestId], + ) -> KernelResult { + let mut state = Ok(false); + scan!(state,index,siblings.len(),state.is_ok(),prior=>{ + let mut collapse = prior; + proof_decl! { let ghost before = store.graph(); let ghost was_collapsed = collapse; } + match id_at(siblings, index) { + Ok(b) => { + match store.checkpoint() { + Ok(()) => { + match if a != b { + match a.head(store) { + Ok(av) => { + match b.head(store) { + Ok(bv) => { + collapse |= matches!((av,bv),(TestHead::Atom(_,x),TestHead::Atom(_,y)) if x==self.and&&y==self.and) + && TestMode::distinct(av, bv); + match TestMode::opposite(store, a, b) { + Ok(matched) => { + Ok(collapse | matched) + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + } else { Ok(collapse) } { + Ok(collapse) => { + proof! { + if collapse { + if was_collapsed { test_lemma_absorbs_extends(before, store.graph(), seq![a] + siblings@, self.and); } + else { + test_lemma_pair_absorbs(store.graph(), a, b, self.and); + assert(siblings@.contains(b)); + assert forall|id: TestId| seq![a, b].contains(id) implies (seq![a] + siblings@).contains(id) by { + if id == a { assert((seq![a] + siblings@)[0] == id); } + else { assert(id == b); assert((seq![a] + siblings@)[index as int + 1] == id); } + } + test_lemma_absorbs_superset(store.graph(), seq![a, b], seq![a] + siblings@, self.and); + } + } + } + Ok(collapse) + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + }; + invariant model::graph_extends(old(store).graph(), store.graph()), model::graph_wf(store.graph()), store.valid_store(), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).valid_store() ==> store.valid_store(), + old(store).errors_are_non_owner() ==> state != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(state), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(state matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (state matches Err(e) ==> resource_error(e)), + a@ < store.graph().tests.len(), test_ids_valid(store.graph(), siblings@), index <= siblings.len(), + match state { Ok(out) => out ==> test_absorbs(store.graph(), seq![a] + siblings@, self.and), Err(_) => true }, + decreases siblings.len() - index, + ); + state + } + + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + id@ < old(store).graph().tests.len(), test_ids_valid(old(store).graph(), siblings@), + ensures model::graph_extends(old(store).graph(), final(store).graph()), model::graph_wf(final(store).graph()), final(store).valid_store(), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + match result { Ok(out) => out ==> test_has_opposite(final(store).graph(), id, siblings@), Err(_) => true }, + )] + fn has_complement( + store: &mut G, + id: TestId, + siblings: &[TestId], + ) -> KernelResult { + let mut state = Ok(false); + scan!(state,index,siblings.len(),state.is_ok(),prior=>{ + let found = prior; + proof_decl! { let ghost before = store.graph(); } + match id_at(siblings, index) { + Ok(sibling) => { + match TestMode::opposite(store, id, sibling) { + Ok(matched) => { + proof! { + if found { test_lemma_has_opposite_extends(before, store.graph(), id, siblings@); } + if matched { assert(test_opposite(store.graph(), id, siblings@[index as int])); } + } + Ok(found || matched) + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + }; + invariant model::graph_extends(old(store).graph(), store.graph()), model::graph_wf(store.graph()), store.valid_store(), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).valid_store() ==> store.valid_store(), + old(store).errors_are_non_owner() ==> state != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(state), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(state matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (state matches Err(e) ==> resource_error(e)), + id@ < store.graph().tests.len(), test_ids_valid(store.graph(), siblings@), index <= siblings.len(), + match state { Ok(out) => out ==> test_has_opposite(store.graph(), id, siblings@), Err(_) => true }, + decreases siblings.len() - index, + ); + state + } + + #[allow( + clippy::option_if_let_else, + reason = "Explicit matches preserve the Verus proof structure." + )] + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + a@ < old(store).graph().tests.len(), test_ids_valid(old(store).graph(), siblings@), + ensures model::graph_extends(old(store).graph(), final(store).graph()), model::graph_wf(final(store).graph()), final(store).valid_store(), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + match result { Ok(out) => out ==> test_absorbs(final(store).graph(), seq![a] + siblings@, self.and), Err(_) => true }, + )] + fn compound_collapses( + self, + store: &mut G, + a: TestId, + siblings: &[TestId], + ) -> KernelResult { + #[allow(clippy::manual_unwrap_or, clippy::manual_unwrap_or_default)] + // Verus-verified match. + let count = match self.dual_count(a.head(store)?) { + Some(n) => n, + None => 0, + }; + proof! { if count != 0 { + test_lemma_children(store.graph(), a, count as nat); + assert(test_children(store.graph(), a).take(count as int) =~= test_children(store.graph(), a)); + } } + let mut state = Ok(count != 0); + scan!(state,index,count,state.is_ok(),prior=>{ + let all = prior; + proof_decl! { let ghost before = store.graph(); } + proof! { test_lemma_children(store.graph(), a, test_children(store.graph(), a).len()); } + match a.child(store, index) { + Ok(id) => { + match TestMode::has_complement(store, id, siblings) { + Ok(matched) => { + proof! { + if all { test_lemma_covered_extends(before, store.graph(), test_children(before, a).take(index as int), siblings@); } + if matched { assert(test_has_opposite(store.graph(), id, siblings@)); } + if all && matched { + assert(id@ == test_children(store.graph(), a)[index as int]); + assert forall|child: nat| #[trigger] test_children(store.graph(), a).take(index as int + 1).contains(child) + implies exists|j: int| 0 <= j < siblings.len() && test_opposite_nat(store.graph(), child, siblings@[j]@) by { + let k = choose|k: int| 0 <= k < index as int + 1 && test_children(store.graph(), a)[k] == child; + if k < index { + assert(test_children(store.graph(), a).take(index as int)[k] == child); + assert(test_children(store.graph(), a).take(index as int).contains(child)); + } + else { assert(child == id@); } + } + } + } + Ok(all && matched) + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + }; + invariant model::graph_extends(old(store).graph(), store.graph()), model::graph_wf(store.graph()), store.valid_store(), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).valid_store() ==> store.valid_store(), + old(store).errors_are_non_owner() ==> state != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(state), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(state matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (state matches Err(e) ==> resource_error(e)), + a@ < store.graph().tests.len(), test_ids_valid(store.graph(), siblings@), index <= count, + count != 0 ==> test_dual(store.graph(), a, self.and) && test_child_count(store.graph(), a, count as nat), + count != 0 ==> test_children(store.graph(), a).take(count as int) == test_children(store.graph(), a), + match state { Ok(out) => out ==> count != 0 && test_complement_covered(store.graph(), test_children(store.graph(), a).take(index as int), siblings@), Err(_) => true }, + ensures state is Ok ==> index == count, + match state { Ok(out) => out ==> test_dual(store.graph(), a, self.and) + && test_complement_covered(store.graph(), test_children(store.graph(), a), siblings@), Err(_) => true }, + decreases count - index, + ); + proof! { + if state is Ok && state->Ok_0 { + test_lemma_compound_absorbs(store.graph(), a, siblings@, self.and); + } + } + state + } + + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + a@ < old(store).graph().tests.len(), test_ids_valid(old(store).graph(), siblings@), + ensures final(store).graph() == old(store).graph(), final(store).valid_store(), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + match result { Ok(out) => out == test_redundant_in(final(store).graph(), a, siblings@, self.and), Err(_) => true }, + )] + fn redundant( + self, + store: &mut G, + a: TestId, + siblings: &[TestId], + ) -> KernelResult { + proof! { assert(siblings@.take(siblings@.len() as int) =~= siblings@); } + let mut state = Ok(false); + scan!(state,index,siblings.len(),state.is_ok(),prior=>{ + proof! { + test_lemma_redundant_push(store.graph(), a, siblings@.take(index as int), siblings@[index as int], self.and); + assert(siblings@.take(index as int).push(siblings@[index as int]) =~= siblings@.take(index as int + 1)); + } + { + let mut redundant = prior; + match id_at(siblings, index) { + Ok(b) => { + match store.checkpoint() { + Ok(()) => { + if a != b { + match a.head(store) { + Ok(av) => { + match b.head(store) { + Ok(bv) => { + match if let Some(n) = self.dual_count(av) { + match self.dual_count(bv) { + Some(m) => TestMode::subset(store, b, m, a, n), + None => TestMode::contains(store, a, n, b), + } + } else { Ok(false) } { + Ok(included) => { + redundant |= included; + redundant |= TestMode::distinct(av, bv) + && matches!((av,bv),(TestHead::Atom(_,x),TestHead::Atom(_,y)) if x!=self.and&&y==self.and); + Ok(redundant) + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + } else { Ok(redundant) } + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + } + }; + invariant store.graph() == old(store).graph(), store.valid_store(), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).valid_store() ==> store.valid_store(), + old(store).errors_are_non_owner() ==> state != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(state), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(state matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (state matches Err(e) ==> resource_error(e)), + model::graph_wf(store.graph()), a@ < store.graph().tests.len(), test_ids_valid(store.graph(), siblings@), + index <= siblings.len(), + siblings@.take(siblings@.len() as int) == siblings@, + match state { Ok(out) => out == test_redundant_in(store.graph(), a, siblings@.take(index as int), self.and), Err(_) => true }, + ensures state is Ok ==> index == siblings.len(), + match state { Ok(out) => out == test_redundant_in(store.graph(), a, siblings@, self.and), Err(_) => true }, + decreases siblings.len() - index, + ); + state + } + + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(store.graph()), test_child_count(store.graph(), id, count as nat), + ensures store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> language::no_invariant_failure(result), + store.errors_are_non_invalid_policy() && store.valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + store.errors_are_resource() && store.valid_store() ==> (result matches Err(e) ==> resource_error(e)), + old(flat).view().is_prefix_of(final(flat).view()), + final(flat).view().len() <= old(flat).view().len() + count, + forall|j: int| old(flat).view().len() <= j < final(flat).view().len() + ==> #[trigger] final(flat).view()[j]@ < store.graph().tests.len(), + forall|j: int| old(flat).view().len() <= j < final(flat).view().len() + ==> #[trigger] final(flat).view()[j]@ == test_children(store.graph(), id)[j - old(flat).view().len()], + match result { Ok(()) => final(flat).view().len() == old(flat).view().len() + count, Err(_) => true }, + )] + fn append_children( + store: &G, + id: TestId, + count: usize, + flat: &mut WorkVec, + ) -> KernelResult<()> { + proof! { test_lemma_children(store.graph(), id, count as nat); } + let mut failure = None; + let mut i = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant + model::graph_wf(store.graph()), test_child_count(store.graph(), id, count as nat), + i <= count, + model::bounded(test_children(store.graph(), id), id@), test_children(store.graph(), id).len() == count, + flat.view().len() == old(flat).view().len() + i, + old(flat).view().is_prefix_of(flat.view()), + forall|j: int| old(flat).view().len() <= j < flat.view().len() + ==> #[trigger] flat.view()[j]@ == test_children(store.graph(), id)[j - old(flat).view().len()], + forall|j: int| old(flat).view().len() <= j < flat.view().len() ==> #[trigger] flat.view()[j]@ < store.graph().tests.len(), + store.errors_are_non_owner() ==> failure != Some(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> (match failure { Some(error) => language::no_invariant_failure::<()>(Err(error)), None => true }), + store.errors_are_non_invalid_policy() && store.valid_store() ==> (match failure { Some(error) => !(error is InvalidPolicy), None => true }), + store.errors_are_resource() && store.valid_store() ==> (failure matches Some(e) ==> resource_error(e)), + ensures failure.is_none() ==> i == count, + decreases count - i, + ))] + while i < count { + let child = loop_try!(id.child(store, i), failure); + proof! { assert(child@ == test_children(store.graph(), id)[i as int]); } + flat.push(child); + i = i.saturating_add(1); + } + if let Some(error) = failure { + return Err(error); + } + Ok(()) + } +} + +verus! { +pub(crate) trait TestNormalize: Sized { + fn not(this: TestId, store: &mut G) -> (result: KernelResult) + requires model::graph_wf(old(store).graph()), old(store).valid_store(), this@ < old(store).graph().tests.len(), + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + model::graph_wf(final(store).graph()), final(store).valid_store(), + match result { + Ok(id) => id@ < final(store).graph().tests.len() + && vocab::test_primitives(model::lift_test(final(store).graph(), id@)) + == vocab::test_primitives(model::lift_test(final(store).graph(), this@)) + && (forall|theta: Subst, event: EventView| + test_truth(final(store).graph(), theta, id@, event) + != test_truth(final(store).graph(), theta, this@, event)), + Err(_) => true, + }, + ; + + fn connective( + store: &mut G, + children: &[TestId], + and: bool, + ) -> (result: KernelResult) + requires model::graph_wf(old(store).graph()), old(store).valid_store(), test_ids_valid(old(store).graph(), children@), + ensures model::graph_extends(old(store).graph(), final(store).graph()), model::graph_wf(final(store).graph()), final(store).valid_store(), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + match result { Ok(id) => id@ < final(store).graph().tests.len() + && test_connective_result(old(store).graph(), final(store).graph(), children@, and, id@) + && (forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + ==> test_truth(final(store).graph(), theta, id@, event) + == test_combo(final(store).graph(), theta, children@, event, and)), Err(_) => true }, + ; + + #[allow( + clippy::option_if_let_else, + reason = "Explicit matches preserve the Verus proof structure." + )] + fn schedule_children( + store: &G, + id: TestId, + count: usize, + tasks: &mut WorkVec<(TestId, bool)>, + ) -> (result: KernelResult<()>) + requires model::graph_wf(store.graph()), test_child_count(store.graph(), id, count as nat), + ensures store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> language::no_invariant_failure(result), + store.errors_are_non_invalid_policy() && store.valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + store.errors_are_resource() && store.valid_store() ==> (result matches Err(e) ==> resource_error(e)), + old(tasks).view().is_prefix_of(final(tasks).view()), + forall|j: int| old(tasks).view().len() <= j < final(tasks).view().len() + ==> #[trigger] final(tasks).view()[j].0@ < store.graph().tests.len() + && !final(tasks).view()[j].1, + match result { + Ok(()) => test_schedule_extension(store.graph(), id, old(tasks).view(), final(tasks).view()) + && final(tasks).view().len() == old(tasks).view().len() + count + && (forall|j: int| 0 <= j < count + ==> #[trigger] final(tasks).view()[old(tasks).view().len() + j].0@ + == test_children(store.graph(), id)[count as int - 1 - j]), + Err(_) => true, + }, + { + proof! { test_lemma_children(store.graph(), id, count as nat); } + let mut failure = None; + let mut remaining = count; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant + model::graph_wf(store.graph()), test_child_count(store.graph(), id, count as nat), + model::bounded(test_children(store.graph(), id), id@), test_children(store.graph(), id).len() == count, + remaining <= count, + old(tasks).view().is_prefix_of(tasks.view()), + forall|j: int| old(tasks).view().len() <= j < tasks.view().len() + ==> #[trigger] tasks.view()[j].0@ < store.graph().tests.len() && !tasks.view()[j].1, + forall|j: int| #![trigger tasks.view()[j]] old(tasks).view().len() <= j < tasks.view().len() + ==> !tasks.view()[j].1, + failure is None ==> tasks.view().len() == old(tasks).view().len() + count - remaining + && (forall|j: int| 0 <= j < count - remaining + ==> #[trigger] tasks.view()[old(tasks).view().len() + j].0@ + == test_children(store.graph(), id)[count as int - 1 - j]), + store.errors_are_non_owner() ==> failure != Some(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> (match failure { Some(error) => language::no_invariant_failure::<()>(Err(error)), None => true }), + store.errors_are_non_invalid_policy() && store.valid_store() ==> (match failure { Some(error) => !(error is InvalidPolicy), None => true }), + store.errors_are_resource() && store.valid_store() ==> (failure matches Some(e) ==> resource_error(e)), + ensures failure.is_none() ==> remaining == 0, + decreases remaining, + ))] + while remaining != 0 { + let i = loop_try!( + match remaining.checked_sub(1) { + Some(value) => Ok(value), + None => Err(HistoryError::normalization_invariant()), + }, + failure + ); + remaining = i; + let child = loop_try!(id.child(store, i), failure); + proof! { assert(child@ == test_children(store.graph(), id)[i as int]); } + tasks.push((child, false)); + } + if let Some(error) = failure { + return Err(error); + } + proof! { + assert forall|j: int| #![trigger tasks.view()[j]] old(tasks).view().len() <= j < tasks.view().len() + implies !tasks.view()[j].1 by { + assert(tasks.view()[j].0@ < store.graph().tests.len()); + } + test_lemma_schedule_extension_intro(store.graph(), id, count as nat, old(tasks).view(), tasks.view()); + } + Ok(()) + } + + fn finish_not( + store: &mut G, + count: usize, + and: bool, + values: &mut WorkVec, + ) -> (result: KernelResult<()>) + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + count <= old(values).view().len(), test_ids_valid(old(store).graph(), old(values).view()), + old(values).view().subrange(old(values).view().len() as int - count, old(values).view().len() as int).no_duplicates(), + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + model::graph_wf(final(store).graph()), final(store).valid_store(), + match result { + Ok(()) => { + let source = old(values).view().subrange(old(values).view().len() as int - count, + old(values).view().len() as int); + &&& final(values).view().len() == old(values).view().len() - count + 1 + &&& final(values).view().drop_last() == old(values).view().subrange(0, + old(values).view().len() as int - count) + &&& test_ids_valid(final(store).graph(), final(values).view()) + &&& exists|sorted: Seq| sorted.to_multiset() == source.to_multiset() + && final(store).graph().tests[final(values).view().last()@ as int] + == if and { model::TestNode::And(model::test_ids(sorted)) } + else { model::TestNode::Or(model::test_ids(sorted)) } + &&& forall|theta: Subst, event: EventView| + test_truth(final(store).graph(), theta, final(values).view().last()@, event) + == test_combo(final(store).graph(), theta, source, event, and) + }, + Err(_) => true, + }, + { + proof_decl! { let ghost original = values.view(); } + let start = match values.len().checked_sub(count) { + Some(v) => v, + None => return Err(HistoryError::normalization_invariant()), + }; + let children = match values.as_mut_slice().get_mut(start..) { + Some(v) => v, + None => return Err(HistoryError::normalization_invariant()), + }; + // De Morgan preserves every normalized reduction; only canonical ID ordering changes. + proof! { junco_core::kernel::TestId::lemma_obeys_cmp(); } + children.sort_unstable(); + proof_decl! { let ghost sorted = children@; } + proof! { + let source = original.subrange(start as int, original.len() as int); + lemma_multiset_members(source, sorted); + source.lemma_multiset_has_no_duplicates(); + assert(sorted.no_duplicates()) by { + sorted.lemma_multiset_has_no_duplicates_conv(); + } + assert forall|i: int| 0 <= i < sorted.len() implies sorted[i]@ < store.graph().tests.len() by { + assert(sorted.contains(sorted[i])); + assert(source.contains(sorted[i])); + let j = choose|j: int| 0 <= j < source.len() && source[j] == sorted[i]; + assert(original[start as int + j] == source[j]); + } + assert forall|i: int, j: int| 0 <= i < j < sorted.len() implies sorted[i]@ < sorted[j]@ by { + assert(!(sorted[i].cmp_spec(&sorted[j]) is Greater)); + assert(sorted[i] != sorted[j]); + } + assert(test_ids_valid(store.graph(), sorted)); + assert(model::strictly_increasing(model::test_ids(sorted))); + assert(model::test_node_wf(store.graph(), if and { + model::TestNode::And(model::test_ids(sorted)) + } else { model::TestNode::Or(model::test_ids(sorted)) })); + } + let out = store.intern_test(if and { + TestView::And(children) + } else { + TestView::Or(children) + })?; + proof! { + assert forall|theta: Subst, event: EventView| + test_truth(store.graph(), theta, out@, event) + == test_combo(store.graph(), theta, + original.subrange(start as int, original.len() as int), event, and) by { + test_lemma_compound_semantics(store.graph(), theta, event, out, sorted, and); + test_lemma_combo_permutation(store.graph(), theta, event, + sorted, original.subrange(start as int, original.len() as int), and); + } + } + values.truncate(start); + values.push(out); + Ok(()) + } + + fn not_step( + store: &mut G, + id: TestId, + finish: bool, + tasks: &mut WorkVec<(TestId, bool)>, + values: &mut WorkVec, + ) -> (result: KernelResult<()>) + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + test_not_ready(old(store).graph(), id, finish, old(values).view()), + forall|i: int| 0 <= i < old(tasks).view().len() ==> #[trigger] old(tasks).view()[i].0@ < old(store).graph().tests.len(), + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + model::graph_wf(final(store).graph()), final(store).valid_store(), + match result { + Ok(()) => test_ids_valid(final(store).graph(), final(values).view()) + && test_not_effect(final(store).graph(), id, finish, + old(tasks).view(), old(values).view(), final(tasks).view(), final(values).view()) + && test_not_work(final(store).graph(), final(tasks).view()) + < test_not_work(old(store).graph(), old(tasks).view().push((id, finish))) + && (forall|root: TestId| test_not_state(old(store).graph(), old(tasks).view().push((id, finish)), old(values).view(), root) + ==> test_not_state(final(store).graph(), final(tasks).view(), final(values).view(), root)), + Err(_) => true, + }, + { + proof_decl! { + let ghost before = store.graph(); + let ghost pending = tasks.view(); + let ghost prior_values = values.view(); + } + proof! { model::lemma_graph_wf_elim(store.graph()); } + store.checkpoint()?; + match id.head(store)? { + TestHead::True => { + values.push(store.constants().test_false); + proof! { + assert(values.view().drop_last() =~= prior_values); + test_lemma_not_leaf_effect(store.graph(), id, pending, prior_values, values.view(), finish); + } + } + TestHead::False => { + values.push(store.constants().test_true); + proof! { + assert(values.view().drop_last() =~= prior_values); + test_lemma_not_leaf_effect(store.graph(), id, pending, prior_values, values.view(), finish); + } + } + TestHead::Atom(primitive, positive) => { + values.push(store.intern_test(TestView::Atom { + primitive, + positive: !positive, + })?); + proof! { + assert(before.tests[id@ as int] == store.graph().tests[id@ as int]); + assert(values.view().drop_last() =~= prior_values); + test_lemma_not_leaf_effect(store.graph(), id, pending, prior_values, values.view(), finish); + } + } + TestHead::And(n) => { + if finish { + Self::finish_not(store, n, false, values)?; + proof! { + assert(before.tests[id@ as int] == store.graph().tests[id@ as int]); + test_lemma_not_finish_effect(store.graph(), id, pending, prior_values, values.view(), n as nat, false); + } + } else { + tasks.push((id, true)); + proof_decl! { let ghost scheduled_base = tasks.view(); } + Self::schedule_children(store, id, n, tasks)?; + proof! { + test_lemma_not_scheduled_extension(store.graph(), id, pending, scheduled_base, tasks.view(), prior_values); + } + } + } + TestHead::Or(n) => { + if finish { + Self::finish_not(store, n, true, values)?; + proof! { + assert(before.tests[id@ as int] == store.graph().tests[id@ as int]); + test_lemma_not_finish_effect(store.graph(), id, pending, prior_values, values.view(), n as nat, true); + } + } else { + tasks.push((id, true)); + proof_decl! { let ghost scheduled_base = tasks.view(); } + Self::schedule_children(store, id, n, tasks)?; + proof! { + test_lemma_not_scheduled_extension(store.graph(), id, pending, scheduled_base, tasks.view(), prior_values); + } + } + } + } + proof! { + test_lemma_not_step_post(before, store.graph(), id, finish, pending, prior_values, tasks.view(), values.view()); + } + Ok(()) + } + + fn not_next( + store: &mut G, + tasks: &mut WorkVec<(TestId, bool)>, + values: &mut WorkVec, + ) -> (result: KernelResult<()>) + requires model::graph_wf(old(store).graph()), old(store).valid_store(), old(tasks).view().len() > 0, + exists|root: TestId| test_not_state(old(store).graph(), old(tasks).view(), old(values).view(), root), + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + model::graph_wf(final(store).graph()), final(store).valid_store(), + match result { + Ok(()) => test_not_work(final(store).graph(), final(tasks).view()) + < test_not_work(old(store).graph(), old(tasks).view()) + && (forall|root: TestId| test_not_state(old(store).graph(), old(tasks).view(), old(values).view(), root) + ==> test_not_state(final(store).graph(), final(tasks).view(), final(values).view(), root)), + Err(_) => true, + }, + { + proof_decl! { let ghost pending = tasks.view(); } + let (id, finish) = match tasks.pop() { + Some(v) => v, + None => return Err(HistoryError::normalization_invariant()), + }; + proof! { + assert(tasks.view().push((id, finish)) =~= pending); + let root = choose|root: TestId| test_not_state(store.graph(), pending, values.view(), root); + test_lemma_not_state_ready(store.graph(), tasks.view(), id, finish, values.view(), root); + assert forall|i: int| 0 <= i < tasks.view().len() implies tasks.view()[i].0@ < store.graph().tests.len() by { + assert(tasks.view()[i] == pending[i]); + } + } + Self::not_step(store, id, finish, tasks, values) + } +} +} + +#[verus_verify] +impl TestNormalize for TestId { + #[allow( + clippy::option_if_let_else, + reason = "Explicit matches preserve the Verus proof structure." + )] + #[verus_verify] + + fn not(this: TestId, store: &mut G) -> KernelResult { + let mut tasks = WorkVec::new(); + let mut values = WorkVec::new(); + tasks.push((this, false)); + proof! { test_lemma_not_initial(store.graph(), this); } + let mut state = Ok(()); + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).valid_store() ==> store.valid_store(), + old(store).errors_are_non_owner() ==> state != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(state), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(state matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (state matches Err(e) ==> resource_error(e)), + model::graph_extends(old(store).graph(), store.graph()), model::graph_wf(store.graph()), store.valid_store(), + state is Ok ==> test_not_state(store.graph(), tasks.view(), values.view(), this), + decreases if state is Ok { test_not_work(store.graph(), tasks.view()) + 1 } else { 0 }, + ))] + while !tasks.is_empty() && state.is_ok() { + state = Self::not_next(store, &mut tasks, &mut values); + } + state?; + proof! { + test_lemma_not_done(store.graph(), values.view(), this); + vocab::lemma_test_not_done_primitives(store.graph(), values.view(), this); + } + match values.pop() { + Some(v) => Ok(v), + None => Err(HistoryError::normalization_invariant()), + } + } + + #[verus_verify] + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + + fn connective( + store: &mut G, + children: &[Self], + and: bool, + ) -> KernelResult { + proof! { test_lemma_constants_semantics(store.graph()); } + let c = store.constants(); + let identity = if and { c.test_true } else { c.test_false }; + let absorber = if and { c.test_false } else { c.test_true }; + let mode = TestMode { + and, + identity, + absorber, + }; + let mut flat = WorkVec::new(); + proof! { assert(children@.take(children@.len() as int) =~= children@); } + let mut collecting = Ok(false); + scan!(collecting,index,children.len(),matches!(collecting,Ok(false)),_prior=>{ + proof! { + assert(children@.take(index as int).push(children@[index as int]) =~= children@.take(index as int + 1)); + assert forall|theta: Subst, event: EventView| + test_combo(store.graph(), theta, flat.view().push(children@[index as int]), event, and) + == test_combo(store.graph(), theta, children@.take(index as int + 1), event, and) by { + test_lemma_combo_push(store.graph(), theta, event, flat.view(), children@[index as int], and); + test_lemma_combo_push(store.graph(), theta, event, children@.take(index as int), children@[index as int], and); + } + } + { + proof_decl! { let ghost prior = flat.view(); } + proof! { model::lemma_graph_wf_elim(store.graph()); } + match id_at(children, index) { + Ok(id) => { + match store.checkpoint() { + Ok(()) => { + if id == mode.absorber { + proof! { + test_lemma_constants_semantics(store.graph()); + assert forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + implies test_combo(store.graph(), theta, seq![id], event, mode.and) == !mode.and by { + test_lemma_combo_push(store.graph(), theta, event, Seq::empty(), id, mode.and); + } + test_lemma_absorbs_superset(store.graph(), seq![id], children@, mode.and); + } + Ok(true) + } else { + match if id != mode.identity { + match id.head(store) { + Ok(head) => { + match head { + TestHead::And(n) if mode.and => TestMode::append_children(store, id, n, &mut flat), + TestHead::Or(n) if !mode.and => TestMode::append_children(store, id, n, &mut flat), + _ => { flat.push(id); Ok(()) }, + } + } + Err(error) => Err(error), + } + } else { Ok(()) } { + Ok(()) => { + proof! { + if id != mode.identity { + match store.graph().tests[id@ as int] { + model::TestNode::And(_) => { if mode.and { test_lemma_flatten(store.graph(), prior, flat.view(), id, mode.and); } }, + model::TestNode::Or(_) => { if !mode.and { test_lemma_flatten(store.graph(), prior, flat.view(), id, mode.and); } }, + _ => {}, + } + } else { + assert forall|theta: Subst, event: EventView| + test_combo(store.graph(), theta, flat.view(), event, mode.and) + == test_combo(store.graph(), theta, prior.push(id), event, mode.and) by { + test_lemma_truth(store.graph(), theta, id@, event); + test_lemma_combo_push(store.graph(), theta, event, prior, id, mode.and); + } + } + assert forall|i: int| 0 <= i < flat.view().len() implies flat.view()[i]@ < store.graph().tests.len() by { + if i < prior.len() { assert(flat.view()[i] == prior[i]); } + else { + match store.graph().tests[id@ as int] { + model::TestNode::And(_) => { + if !mode.and { assert(flat.view()[i] == id); } + else { assert(flat.view()[i]@ < store.graph().tests.len()); } + }, + model::TestNode::Or(_) => { + if mode.and { assert(flat.view()[i] == id); } + else { assert(flat.view()[i]@ < store.graph().tests.len()); } + }, + _ => { assert(flat.view()[i] == id); }, + } + } + } + assert forall|i: int| 0 <= i < flat.view().len() + implies test_member(store.graph(), children@, and, #[trigger] flat.view()[i]@) by { + if i < prior.len() { + assert(flat.view()[i] == prior[i]); + } else { + let j = i - prior.len(); + assert(children@[index as int] == id); + match store.graph().tests[id@ as int] { + model::TestNode::And(cs) => { + if mode.and { assert(flat.view()[i]@ == cs[j]); assert(cs.contains(cs[j])); } + else { assert(flat.view()[i] == id); } + }, + model::TestNode::Or(cs) => { + if !mode.and { assert(flat.view()[i]@ == cs[j]); assert(cs.contains(cs[j])); } + else { assert(flat.view()[i] == id); } + }, + _ => { assert(flat.view()[i] == id); }, + } + assert(test_piece_contains(store.graph(), children@[index as int]@, and, flat.view()[i]@)); + } + } + } + Ok(false) + } + Err(error) => Err(error), + } + } + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + } + }; + invariant store.graph() == old(store).graph(), model::graph_wf(store.graph()), store.valid_store(), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).valid_store() ==> store.valid_store(), + old(store).errors_are_non_owner() ==> collecting != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(collecting), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(collecting matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (collecting matches Err(e) ==> resource_error(e)), + c@ == store.graph().constants, mode.and == and, mode.identity == identity, mode.absorber == absorber, + identity@ == if and { c.test_true@ } else { c.test_false@ }, absorber@ == if and { c.test_false@ } else { c.test_true@ }, + test_ids_valid(store.graph(), children@), index <= children.len(), + children@.take(children@.len() as int) == children@, + match collecting { + Ok(true) => test_absorbs(store.graph(), children@, and), + Ok(false) => test_ids_valid(store.graph(), flat.view()) + && (forall|k: int| 0 <= k < flat.view().len() + ==> test_member(store.graph(), children@, and, #[trigger] flat.view()[k]@)) + && (forall|theta: Subst, event: EventView| + test_combo(store.graph(), theta, flat.view(), event, and) + == test_combo(store.graph(), theta, children@.take(index as int), event, and)), + Err(_) => true, + }, + ensures matches!(collecting, Ok(false)) ==> index == children.len(), + match collecting { Ok(false) => test_ids_valid(store.graph(), flat.view()) + && (forall|k: int| 0 <= k < flat.view().len() + ==> test_member(store.graph(), children@, and, #[trigger] flat.view()[k]@)) + && (forall|theta: Subst, event: EventView| + test_combo(store.graph(), theta, flat.view(), event, and) == test_combo(store.graph(), theta, children@, event, and)), _ => true }, + decreases children.len() - index, + ); + if collecting? { + return Ok(absorber); + } + proof_decl! { let ghost collected = flat.view(); } + proof! { junco_core::kernel::TestId::lemma_obeys_cmp(); } + flat.as_mut_slice().sort_unstable(); + proof_decl! { let ghost sorted = flat.view(); } + dedup_ids(&mut flat)?; + proof! { + lemma_multiset_members(collected, sorted); + assert forall|i: int, j: int| 0 <= i < j < sorted.len() implies sorted[i]@ <= sorted[j]@ by { + assert(!(sorted[i].cmp_spec(&sorted[j]) is Greater)); + } + assert forall|id: TestId| flat.view().contains(id) <==> collected.contains(id) by { + assert(flat.view().contains(id) == sorted.contains(id)); + } + assert forall|i: int| 0 <= i < flat.view().len() implies flat.view()[i]@ < store.graph().tests.len() by { + assert(collected.contains(flat.view()[i])); + let j = choose|j: int| 0 <= j < collected.len() && collected[j] == flat.view()[i]; + } + lemma_dedup_strict(sorted, |id: TestId| id@); + assert forall|i: int, j: int| 0 <= i < j < flat.view().len() + implies flat.view()[i]@ < flat.view()[j]@ by { + assert(dedup_spec(sorted)[i] == flat.view()[i]); + assert(dedup_spec(sorted)[j] == flat.view()[j]); + assert((|id: TestId| id@)(dedup_spec(sorted)[i]) + < (|id: TestId| id@)(dedup_spec(sorted)[j])); + } + assert forall|i: int, j: int| 0 <= i < j < model::test_ids(flat.view()).len() + implies model::test_ids(flat.view())[i] < model::test_ids(flat.view())[j] by { + assert(model::test_ids(flat.view())[i] == flat.view()[i]@); + assert(model::test_ids(flat.view())[j] == flat.view()[j]@); + } + assert(model::strictly_increasing(model::test_ids(flat.view()))); + assert forall|theta: Subst, event: EventView| + test_combo(store.graph(), theta, flat.view(), event, and) + == test_combo(store.graph(), theta, children@, event, and) by { + test_lemma_combo_membership(store.graph(), theta, event, flat.view(), collected, and); + } + assert forall|i: int| 0 <= i < flat.view().len() + implies test_member(old(store).graph(), children@, and, #[trigger] flat.view()[i]@) by { + assert(collected.contains(flat.view()[i])); + let j = choose|j: int| 0 <= j < collected.len() && collected[j] == flat.view()[i]; + } + } + let mut collapse = Ok(false); + scan!(collapse,index,flat.len(),collapse.is_ok(),prior=>{ + proof_decl! { let ghost before = store.graph(); } + match id_at(&flat, index) { + Ok(id) => { + match mode.pair_collapses(store, id, &flat) { + Ok(pair) => { + proof_decl! { let ghost after_pair = store.graph(); } + proof! { assert(pair ==> test_absorbs(after_pair, seq![id] + flat.view(), and)); } + match mode.compound_collapses(store, id, &flat) { + Ok(compound) => { + proof! { + assert(compound ==> test_absorbs(store.graph(), seq![id] + flat.view(), and)); + if prior { test_lemma_absorbs_extends(before, store.graph(), flat.view(), and); } + if pair { + test_lemma_absorbs_extends(after_pair, store.graph(), seq![id] + flat.view(), and); + test_lemma_absorbs_superset(store.graph(), seq![id] + flat.view(), flat.view(), and); + } + if compound { test_lemma_absorbs_superset(store.graph(), seq![id] + flat.view(), flat.view(), and); } + test_lemma_combo_extends(before, store.graph(), flat.view()); + } + Ok(prior || pair || compound) + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + }; + invariant model::graph_extends(old(store).graph(), store.graph()), model::graph_wf(store.graph()), store.valid_store(), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).valid_store() ==> store.valid_store(), + old(store).errors_are_non_owner() ==> collapse != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(collapse), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(collapse matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (collapse matches Err(e) ==> resource_error(e)), + mode.and == and, + test_ids_valid(store.graph(), flat.view()), test_ids_valid(store.graph(), children@), index <= flat.len(), + model::strictly_increasing(model::test_ids(flat.view())), + forall|k: int| 0 <= k < flat.view().len() + ==> test_member(old(store).graph(), children@, and, #[trigger] flat.view()[k]@), + collapse is Ok ==> (forall|theta: Subst, event: EventView| + test_combo(store.graph(), theta, flat.view(), event, and) + == test_combo(old(store).graph(), theta, children@, event, and)), + match collapse { Ok(out) => out ==> test_absorbs(store.graph(), flat.view(), and), Err(_) => true }, + decreases flat.len() - index, + ); + proof! { + test_lemma_combo_extends(old(store).graph(), store.graph(), children@); + test_lemma_constants_semantics(store.graph()); + } + if collapse? { + return Ok(absorber); + } + let mut kept = WorkVec::new(); + let mut retaining = Ok(()); + proof! { assert(flat.view().take(flat.view().len() as int) =~= flat.view()); } + scan!(retaining,index,flat.len(),retaining.is_ok(),_prior=>{ + proof! { + flat.view().take(index as int).lemma_filter_push(flat.view()[index as int], + |id: TestId| !test_redundant_in(store.graph(), id, flat.view(), and)); + assert(flat.view().take(index as int).push(flat.view()[index as int]) =~= flat.view().take(index as int + 1)); + } + { + proof_decl! { let ghost prior_kept = kept.view(); } + match id_at(&flat, index) { + Ok(id) => { + match mode.redundant(store, id, &flat) { + Ok(redundant) => { + proof! { assert(redundant == test_redundant_in(store.graph(), id, flat.view(), and)); } + if !redundant { kept.push(id); } + proof! { + assert(kept.view() == if test_redundant_in(store.graph(), flat.view()[index as int], flat.view(), and) { + prior_kept + } else { prior_kept.push(flat.view()[index as int]) }); + } + Ok(()) + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + } + }; + invariant model::graph_extends(old(store).graph(), store.graph()), model::graph_wf(store.graph()), store.valid_store(), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).valid_store() ==> store.valid_store(), + old(store).errors_are_non_owner() ==> retaining != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(retaining), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(retaining matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (retaining matches Err(e) ==> resource_error(e)), + mode.and == and, test_ids_valid(store.graph(), children@), + test_ids_valid(store.graph(), flat.view()), index <= flat.len(), + model::strictly_increasing(model::test_ids(flat.view())), + forall|k: int| 0 <= k < flat.view().len() + ==> test_member(old(store).graph(), children@, and, #[trigger] flat.view()[k]@), + flat.view().take(flat.view().len() as int) == flat.view(), + retaining is Ok ==> kept.view() == flat.view().take(index as int).filter( + |id: TestId| !test_redundant_in(store.graph(), id, flat.view(), and)), + forall|theta: Subst, event: EventView| + test_combo(store.graph(), theta, flat.view(), event, and) + == test_combo(store.graph(), theta, children@, event, and), + ensures retaining is Ok ==> index == flat.len(), + retaining is Ok ==> kept.view() == test_retained(store.graph(), flat.view(), and), + decreases flat.len() - index, + ); + retaining?; + proof! { + test_lemma_retained_members(store.graph(), flat.view(), and); + test_lemma_retention(store.graph(), flat.view(), kept.view(), and); + test_lemma_filter_ordered(flat.view(), |id: TestId| !test_redundant_in(store.graph(), id, flat.view(), and), |id: TestId| id@); + assert(kept.view() == test_retained(store.graph(), flat.view(), and)); + assert forall|i: int| 0 <= i < kept.view().len() implies kept.view()[i]@ < store.graph().tests.len() by { + assert(kept.view().contains(kept.view()[i])); + assert(flat.view().contains(kept.view()[i])); + let j = choose|j: int| 0 <= j < flat.view().len() && flat.view()[j] == kept.view()[i]; + } + assert forall|i: int| 0 <= i < kept.view().len() + implies test_member(old(store).graph(), children@, and, #[trigger] kept.view()[i]@) by { + assert(kept.view().contains(kept.view()[i])); + assert(flat.view().contains(kept.view()[i])); + let j = choose|j: int| 0 <= j < flat.view().len() && flat.view()[j] == kept.view()[i]; + } + assert forall|i: int, j: int| 0 <= i < j < model::test_ids(kept.view()).len() + implies model::test_ids(kept.view())[i] < model::test_ids(kept.view())[j] by { + assert(model::test_ids(kept.view())[i] == kept.view()[i]@); + assert(model::test_ids(kept.view())[j] == kept.view()[j]@); + assert((|id: TestId| id@)(kept.view()[i]) < (|id: TestId| id@)(kept.view()[j])); + } + if kept.len() == 1 { + assert(kept.view() =~= seq![kept.view()[0]]); + assert forall|theta: Subst, event: EventView| + test_combo(store.graph(), theta, kept.view(), event, and) + == test_truth(store.graph(), theta, kept.view()[0]@, event) by { + test_lemma_combo_push(store.graph(), theta, event, Seq::empty(), kept.view()[0], and); + } + } + assert(test_ids_valid(store.graph(), kept.view())); + assert(model::strictly_increasing(model::test_ids(kept.view()))); + test_lemma_constants_semantics(store.graph()); + assert(identity@ == if and { store.graph().constants.test_true } else { store.graph().constants.test_false }); + assert forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + implies test_combo(store.graph(), theta, kept.view(), event, and) + == test_combo(store.graph(), theta, children@, event, and) by {} + } + if kept.is_empty() { + proof! { + assert forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + implies test_truth(store.graph(), theta, identity@, event) + == test_combo(store.graph(), theta, children@, event, and) by {} + } + Ok(identity) + } else if kept.len() == 1 { + proof! { + assert forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + implies test_truth(store.graph(), theta, kept.view()[0]@, event) + == test_combo(store.graph(), theta, children@, event, and) by {} + } + id_at(&kept, 0) + } else { + { + proof_decl! { let ghost before = store.graph(); } + match store.intern_test(if and { + TestView::And(&kept) + } else { + TestView::Or(&kept) + }) { + Ok(id) => { + proof! { + test_lemma_combo_extends(before, store.graph(), children@); + assert forall|ids: Seq, theta: Subst, event: EventView, mode: bool| + test_ids_valid(before, ids) implies test_combo(before, theta, ids, event, mode) + == test_combo(store.graph(), theta, ids, event, mode) by { + test_lemma_combo_extends(before, store.graph(), ids); + } + assert forall|i: nat| i < before.tests.len() + implies model::lift_test(before, i) == model::lift_test(store.graph(), i) by { + model::lemma_lift_test_stable(before, store.graph(), i); + } + assert forall|theta: Subst, event: EventView| + test_truth(store.graph(), theta, id@, event) + == test_combo(store.graph(), theta, kept.view(), event, and) by { + test_lemma_compound_semantics(store.graph(), theta, event, id, kept.view(), and); + } + assert forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + implies test_truth(store.graph(), theta, id@, event) + == test_combo(store.graph(), theta, children@, event, and) by { + assert(test_combo(before, theta, kept.view(), event, and) + == test_combo(before, theta, children@, event, and)); + assert(test_combo(before, theta, kept.view(), event, and) + == test_combo(store.graph(), theta, kept.view(), event, and)); + } + assert forall|k: int| 0 <= k < model::test_ids(kept.view()).len() + implies test_member(old(store).graph(), children@, and, #[trigger] model::test_ids(kept.view())[k]) by { + assert(model::test_ids(kept.view())[k] == kept.view()[k]@); + } + } + Ok(id) + } + Err(error) => Err(error), + } + } + } + } +} +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy)] +struct RegexMode { + intersect: bool, + identity: RegexId, + absorber: RegexId, +} + +#[verus_verify] +impl RegexMode { + #[allow( + clippy::missing_const_for_fn, + reason = "Preserve the existing Verus-verified function shape." + )] + #[verus_verify] + #[verus_spec(result => ensures result == match head { + RegexHead::Union(n) => if self.intersect { Some(n) } else { None }, + RegexHead::Intersect(n) => if !self.intersect { Some(n) } else { None }, + _ => None, + })] + fn dual_count(self, head: RegexHead) -> Option { + match head { + RegexHead::Union(n) if self.intersect => Some(n), + RegexHead::Intersect(n) if !self.intersect => Some(n), + _ => None, + } + } + + #[allow( + clippy::semicolon_if_nothing_returned, + reason = "Preserve the existing Verus-verified mutation branches." + )] + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(store.graph()), parent@ < store.graph().regexes.len(), + count == regex_children(store.graph(), parent@).len(), + model::strictly_increasing(regex_children(store.graph(), parent@)), + ensures store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> language::no_invariant_failure(result), + store.errors_are_non_invalid_policy() && store.valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + store.errors_are_resource() && store.valid_store() ==> (result matches Err(e) ==> resource_error(e)), + match result { + Ok(found) => found == regex_children(store.graph(), parent@).contains(id@), + Err(_) => true, + }, + )] + fn contains( + store: &G, + parent: RegexId, + count: usize, + id: RegexId, + ) -> KernelResult { + let mut low = 0; + let mut high = count; + let mut failure = None; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant low <= high <= count, + model::graph_wf(store.graph()), parent@ < store.graph().regexes.len(), + count == regex_children(store.graph(), parent@).len(), model::strictly_increasing(regex_children(store.graph(), parent@)), + forall|i: int| 0 <= i < low ==> regex_children(store.graph(), parent@)[i] < id@, + forall|i: int| high <= i < count ==> regex_children(store.graph(), parent@)[i] >= id@, + store.errors_are_non_owner() ==> failure != Some(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> (match failure { Some(error) => language::no_invariant_failure::<()>(Err(error)), None => true }), + store.errors_are_non_invalid_policy() && store.valid_store() ==> (match failure { Some(error) => !(error is InvalidPolicy), None => true }), + store.errors_are_resource() && store.valid_store() ==> (failure matches Some(e) ==> resource_error(e)), + ensures failure.is_none() ==> low == high, + decreases high - low, + ))] + while low < high { + let mid = loop_try!(midpoint(low, high), failure); + proof! { regex_lemma_child_available(store.graph(), parent@, mid as nat); } + let child = loop_try!(parent.child(store, mid), failure); + proof! { regex_child_exact(store.graph(), parent@, mid as nat, child@); } + if child < id { + low = mid.saturating_add(1) + } else { + high = mid + } + } + if let Some(error) = failure { + return Err(error); + } + if low < count { + proof! { regex_lemma_child_available(store.graph(), parent@, low as nat); } + let child = parent.child(store, low)?; + proof! { regex_child_exact(store.graph(), parent@, low as nat, child@); } + Ok(child == id) + } else { + Ok(false) + } + } + + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(store.graph()), a@ < store.graph().regexes.len(), b@ < store.graph().regexes.len(), + a_count == regex_children(store.graph(), a@).len(), b_count == regex_children(store.graph(), b@).len(), + model::strictly_increasing(regex_children(store.graph(), b@)), + ensures store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> language::no_invariant_failure(result), + store.errors_are_non_invalid_policy() && store.valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + store.errors_are_resource() && store.valid_store() ==> (result matches Err(e) ==> resource_error(e)), + match result { + Ok(included) => included == (forall|i: int| 0 <= i < a_count + ==> regex_children(store.graph(), b@).contains(regex_children(store.graph(), a@)[i])), + Err(_) => true, + }, + )] + fn subset( + store: &G, + a: RegexId, + a_count: usize, + b: RegexId, + b_count: usize, + ) -> KernelResult { + let mut included = true; + let mut failure = None; + let mut i = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant i <= a_count, + model::graph_wf(store.graph()), a@ < store.graph().regexes.len(), b@ < store.graph().regexes.len(), + a_count == regex_children(store.graph(), a@).len(), b_count == regex_children(store.graph(), b@).len(), + model::strictly_increasing(regex_children(store.graph(), b@)), + included == (forall|j: int| 0 <= j < i + ==> regex_children(store.graph(), b@).contains(regex_children(store.graph(), a@)[j])), + store.errors_are_non_owner() ==> failure != Some(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> (match failure { Some(error) => language::no_invariant_failure::<()>(Err(error)), None => true }), + store.errors_are_non_invalid_policy() && store.valid_store() ==> (match failure { Some(error) => !(error is InvalidPolicy), None => true }), + store.errors_are_resource() && store.valid_store() ==> (failure matches Some(e) ==> resource_error(e)), + ensures failure.is_none() ==> i == a_count, + decreases a_count - i, + ))] + while i < a_count { + proof! { regex_lemma_child_available(store.graph(), a@, i as nat); } + let id = loop_try!(a.child(store, i), failure); + proof! { regex_child_exact(store.graph(), a@, i as nat, id@); } + included &= loop_try!(RegexMode::contains(store, b, b_count, id), failure); + i = i.saturating_add(1); + } + if let Some(error) = failure { + return Err(error); + } + Ok(included) + } + + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), a@ < old(store).graph().regexes.len(), + old(store).valid_store(), + regex_ids_valid(old(store).graph(), siblings@), + ensures final(store).graph() == old(store).graph(), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + final(store).valid_store(), + match result { + Ok(found) => found == match old(store).graph().regexes[a@ as int].kind { + model::RegexKindNode::Not(inner) => model::regex_ids(siblings@).contains(inner), + _ => false, + }, + Err(_) => true, + }, + )] + fn has_complement( + store: &mut G, + a: RegexId, + siblings: &[RegexId], + ) -> KernelResult { + proof! { regex_unfold(store.graph(), a@); } + store.checkpoint()?; + if let RegexHead::Not(inner) = a.head(store)? { + proof! { regex_ids_contains(siblings@, inner); } + let mut state = Ok(false); + scan!(state,index,siblings.len(),state.is_ok(),prior=>{ + proof! { regex_contains_prefix(siblings@, index as int, inner); } + match store.checkpoint() { + Ok(()) => { + match id_at(siblings, index) { + Ok(id) => { + Ok(prior || id == inner) + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + }; + invariant store.graph() == old(store).graph(), index <= siblings.len(), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).valid_store() ==> store.valid_store(), + old(store).errors_are_non_owner() ==> state != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(state), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(state matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (state matches Err(e) ==> resource_error(e)), + store.valid_store(), model::graph_wf(store.graph()), regex_ids_valid(store.graph(), siblings@), + inner@ < store.graph().regexes.len(), + match state { Ok(found) => found == siblings@.subrange(0, index as int).contains(inner), Err(_) => true }, + decreases siblings.len() - index, + ); + proof! { assert(siblings@.subrange(0, siblings.len() as int) =~= siblings@); } + state + } else { + Ok(false) + } + } + + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + a@ < old(store).graph().regexes.len(), regex_ids_valid(old(store).graph(), siblings@), + ensures final(store).graph() == old(store).graph(), final(store).valid_store(), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + match result { + Ok(value) => value == (exists|i: int| 0 <= i < siblings.len() + && regex_absorbed_by(final(store).graph(), a@, siblings@[i]@, self.intersect)), + Err(_) => true, + }, + )] + fn absorbed( + self, + store: &mut G, + a: RegexId, + siblings: &[RegexId], + ) -> KernelResult { + let mut state = Ok(false); + scan!(state,index,siblings.len(),state.is_ok(),prior=>{ + let redundant = prior; + match id_at(siblings, index) { + Ok(b) => { + match store.checkpoint() { + Ok(()) => { + proof! { regex_children_count(store.graph(), a@); regex_children_count(store.graph(), b@); } + if a != b { + match a.head(store) { + Ok(av) => { + match b.head(store) { + Ok(bv) => { + if let Some(n) = self.dual_count(av) { + proof! { regex_dual_order(store.graph(), a@, self.intersect); } + match match self.dual_count(bv) { Some(m) => RegexMode::subset(store, b, m, a, n), None => RegexMode::contains(store, a, n, b) } { + Ok(included) => { + Ok(redundant | included) + } + Err(error) => Err(error), + } + } else { Ok(redundant) } + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + } else { Ok(redundant) } + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + }; + invariant store.graph() == old(store).graph(), store.valid_store(), model::graph_wf(store.graph()), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).valid_store() ==> store.valid_store(), + old(store).errors_are_non_owner() ==> state != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(state), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(state matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (state matches Err(e) ==> resource_error(e)), + a@ < store.graph().regexes.len(), regex_ids_valid(store.graph(), siblings@), index <= siblings.len(), + match state { Ok(value) => value == (exists|i: int| 0 <= i < index + && regex_absorbed_by(store.graph(), a@, siblings@[i]@, self.intersect)), Err(_) => true }, + decreases siblings.len() - index, + ); + state + } + + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(store.graph()), id@ < store.graph().regexes.len(), + count == regex_children(store.graph(), id@).len(), regex_ids_valid(store.graph(), old(flat).view()), + ensures store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> language::no_invariant_failure(result), + store.errors_are_non_invalid_policy() && store.valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + store.errors_are_resource() && store.valid_store() ==> (result matches Err(e) ==> resource_error(e)), + regex_ids_valid(store.graph(), final(flat).view()), + old(flat).view().is_prefix_of(final(flat).view()), + match result { + Ok(()) => model::regex_ids(final(flat).view()) + == model::regex_ids(old(flat).view()) + regex_children(store.graph(), id@), + Err(_) => true, + }, + )] + fn append_children( + store: &G, + id: RegexId, + count: usize, + flat: &mut WorkVec, + ) -> KernelResult<()> { + proof! { regex_children_wf(store.graph(), id@); } + let mut failure = None; + let mut i = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant i <= count, regex_ids_valid(store.graph(), flat.view()), + model::graph_wf(store.graph()), id@ < store.graph().regexes.len(), + count == regex_children(store.graph(), id@).len(), regex_ids_valid(store.graph(), old(flat).view()), + old(flat).view().is_prefix_of(flat.view()), + model::regex_ids(flat.view()) == model::regex_ids(old(flat).view()) + + regex_children(store.graph(), id@).subrange(0, i as int), + store.errors_are_non_owner() ==> failure != Some(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> (match failure { Some(error) => language::no_invariant_failure::<()>(Err(error)), None => true }), + store.errors_are_non_invalid_policy() && store.valid_store() ==> (match failure { Some(error) => !(error is InvalidPolicy), None => true }), + store.errors_are_resource() && store.valid_store() ==> (failure matches Some(e) ==> resource_error(e)), + ensures failure.is_none() ==> i == count, + decreases count - i, + ))] + while i < count { + proof_decl! { let ghost prior = flat.view(); } + proof! { regex_lemma_child_available(store.graph(), id@, i as nat); } + let child = loop_try!(id.child(store, i), failure); + proof! { regex_child_exact(store.graph(), id@, i as nat, child@); } + flat.push(child); + proof! { + regex_ids_push(flat.view().drop_last(), child); + assert(flat.view() == flat.view().drop_last().push(child)); + assert(flat.view() == prior.push(child)); + assert(model::regex_ids(flat.view()) == model::regex_ids(prior).push(child@)); + } + proof! { + assert(regex_children(store.graph(), id@).subrange(0, i as int + 1) + =~= regex_children(store.graph(), id@).subrange(0, i as int).push(regex_children(store.graph(), id@)[i as int])); + assert(model::regex_ids(prior).push(child@) + =~= model::regex_ids(old(flat).view()) + + regex_children(store.graph(), id@).subrange(0, i as int + 1)); + } + i = i.saturating_add(1); + } + if let Some(error) = failure { + return Err(error); + } + proof! { + assert(i == count); + assert(model::regex_ids(flat.view()) == model::regex_ids(old(flat).view()) + + regex_children(store.graph(), id@).subrange(0, i as int)); + assert(regex_children(store.graph(), id@).subrange(0, count as int) =~= regex_children(store.graph(), id@)); + } + Ok(()) + } +} +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy)] +struct RegexStats { + all_nullable: bool, + any_nullable: bool, + epsilon: bool, + complement: bool, + has_nonnullable: bool, +} + +#[verus_verify] +impl RegexStats { + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), old(store).valid_store(), regex_ids_valid(old(store).graph(), ids@), index < ids.len(), + ensures final(store).graph() == old(store).graph(), final(store).valid_store(), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + match result { Ok(next) => next@ == regex_stats_update(final(store).graph(), ids@, index as int, epsilon, self@, complements) + && (regex_stats_prefix(old(store).graph(), ids@, index as nat, epsilon, self@, complements) + ==> regex_stats_prefix(final(store).graph(), ids@, index as nat + 1, epsilon, next@, complements)), Err(_) => true }, + )] + fn update( + self, + store: &mut G, + ids: &[RegexId], + index: usize, + epsilon: RegexId, + complements: bool, + ) -> KernelResult { + proof! { + if regex_stats_prefix(store.graph(), ids@, index as nat, epsilon, self@, complements) { + regex_stats_prefix_step(store.graph(), ids@, index as int, epsilon, self@, complements); + } + } + let mut next = self; + store.checkpoint()?; + let id = id_at(ids, index)?; + let n = RegexId::nullable(id, store)?; + next.all_nullable &= n; + next.any_nullable |= id != epsilon && n; + next.epsilon |= id == epsilon; + let head = id.head(store)?; + if !n { + match head { + RegexHead::Not(inner) if inner == epsilon => {} + _ => next.has_nonnullable = true, + } + } + if complements { + next.complement |= RegexMode::has_complement(store, id, ids)?; + } + Ok(next) + } +} +#[verus_verify] +pub(crate) trait RegexNormalize: Sized { + #[verus_spec(result => + requires model::graph_wf(store.graph()), this@ < store.graph().regexes.len(), + ensures store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> language::no_invariant_failure(result), + store.errors_are_non_invalid_policy() && store.valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + store.errors_are_resource() && store.valid_store() ==> (result matches Err(e) ==> resource_error(e)), + match result { + Ok(value) => value == language::nullable(model::lift_regex(store.graph(), this@)), + Err(_) => true, + }, + )] + fn nullable(this: RegexId, store: &G) -> KernelResult; + + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), this@ < old(store).graph().regexes.len(), + old(store).valid_store(), + ensures model::graph_extends(old(store).graph(), final(store).graph()), model::graph_wf(final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + final(store).valid_store(), + match result { + Ok(id) => id@ < final(store).graph().regexes.len() + && (fimpl::regex_nf(model::lift_regex(old(store).graph(), this@)) + ==> fimpl::regex_nf(model::lift_regex(final(store).graph(), id@))) + && forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + ==> model::regex_lang(final(store).graph(), theta, id@, word) + == language::numeric_lang(model::gsem(theta), language::Regex::Star(Box::new( + model::lift_regex(final(store).graph(), this@))), word), + Err(_) => true, + }, + result matches Ok(id) ==> vocab::regex_primitives(model::lift_regex(final(store).graph(), id@)).subset_of( + vocab::regex_primitives(model::lift_regex(final(store).graph(), this@))), + )] + fn star(this: RegexId, store: &mut G) -> KernelResult; + + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), this@ < old(store).graph().regexes.len(), + old(store).valid_store(), + ensures model::graph_extends(old(store).graph(), final(store).graph()), model::graph_wf(final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + final(store).valid_store(), + match result { + Ok(id) => id@ < final(store).graph().regexes.len() + && regex_not_result(final(store).graph(), this@, id@) + && forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + ==> model::regex_lang(final(store).graph(), theta, id@, word) + == !model::regex_lang(final(store).graph(), theta, this@, word), + Err(_) => true, + }, + )] + fn not(this: RegexId, store: &mut G) -> KernelResult; + + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), test@ < old(store).graph().tests.len(), + old(store).valid_store(), + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + final(store).valid_store(), + model::graph_wf(final(store).graph()), + match result { + Ok(id) => id@ < final(store).graph().regexes.len() + && (if test@ == final(store).graph().constants.test_false { id@ == final(store).graph().constants.empty } + else { final(store).graph().regexes[id@ as int].kind == model::RegexKindNode::Test(test@) }) + && forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + ==> model::regex_lang(final(store).graph(), theta, id@, word) + == (word.len() == 1 && model::test_holds(theta, + model::lift_test(final(store).graph(), test@), word[0])), + Err(_) => true, + }, + )] + fn from_test(store: &mut G, test: TestId) -> KernelResult; + + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), regex_ids_valid(old(store).graph(), children@), + old(store).valid_store(), + ensures model::graph_extends(old(store).graph(), final(store).graph()), model::graph_wf(final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + final(store).valid_store(), + match result { + Ok(id) => id@ < final(store).graph().regexes.len() + && regex_concat_result(old(store).graph(), final(store).graph(), children@, id@) + && forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + ==> model::regex_lang(final(store).graph(), theta, id@, word) + == concat_combo(final(store).graph(), theta, children@, word), + Err(_) => true, + }, + )] + fn concat(store: &mut G, children: &[RegexId]) -> KernelResult; + + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + model::regex_node_wf(old(store).graph(), model::RegexNode { kind: kind@, nullable: n }), + ensures model::graph_extends(old(store).graph(), final(store).graph()), model::graph_wf(final(store).graph()), final(store).valid_store(), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + match result { + Ok(id) => id@ < final(store).graph().regexes.len() + && final(store).graph().regexes[id@ as int] == (model::RegexNode { kind: kind@, nullable: n }) + && model::lift_regex(final(store).graph(), id@) == regex_unbounded_kind(final(store).graph(), kind@), + Err(_) => true, + }, + )] + fn intern( + store: &mut G, + kind: RegexKindView<'_>, + n: bool, + ) -> KernelResult; + + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), old(store).valid_store(), regex_ids_valid(old(store).graph(), children@), + ensures model::graph_extends(old(store).graph(), final(store).graph()), model::graph_wf(final(store).graph()), final(store).valid_store(), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + match result { + Ok(id) => id@ < final(store).graph().regexes.len() + && (regex_set_flat_inputs(old(store).graph(), children@, intersect) + ==> regex_set_shape(old(store).graph(), final(store).graph(), children@, intersect, id@)) + && forall|theta: Subst, word: Seq| + language::event_wf(theta, theta.len()) ==> model::regex_lang(final(store).graph(), theta, id@, word) + == regex_combo(final(store).graph(), theta, children@, word, intersect), + Err(_) => true, + }, + )] + fn set( + store: &mut G, + children: &[RegexId], + intersect: bool, + ) -> KernelResult; +} + +#[verus_verify] +impl RegexNormalize for RegexId { + #[verus_verify] + + fn nullable(this: RegexId, store: &G) -> KernelResult { + proof! { regex_unfold(store.graph(), this@); } + Ok(store.regex(this)?.nullable) + } + + #[verus_verify] + + fn star(this: RegexId, store: &mut G) -> KernelResult { + proof! { + reveal_with_fuel(vocab::regex_primitives, 1); + regex_unfold(store.graph(), this@); + regex_constants(store.graph()); + regex_star_laws(store.graph(), this@); + fcmp::lemma_star_future(store.graph(), this@); + } + store.checkpoint()?; + let c = store.constants(); + match this.head(store)? { + RegexHead::Empty | RegexHead::Epsilon => Ok(c.epsilon), + RegexHead::All => Ok(c.all), + RegexHead::Test(t) if t == c.test_true => Ok(c.all), + RegexHead::Star(_) => Ok(this), + _ => RegexId::intern(store, RegexKindView::Star(this), true), + } + } + + #[verus_verify] + + fn not(this: RegexId, store: &mut G) -> KernelResult { + proof! { + regex_unfold(store.graph(), this@); + regex_constants(store.graph()); + } + store.checkpoint()?; + let c = store.constants(); + match this.head(store)? { + RegexHead::Empty => Ok(c.all), + RegexHead::All => Ok(c.empty), + RegexHead::Not(inner) => Ok(inner), + _ => { + let n = !RegexId::nullable(this, store)?; + RegexId::intern(store, RegexKindView::Not(this), n) + } + } + } + + #[verus_verify] + + fn from_test(store: &mut G, test: TestId) -> KernelResult { + proof! { regex_constants(store.graph()); } + store.checkpoint()?; + if test == store.constants().test_false { + Ok(store.constants().empty) + } else { + RegexId::intern(store, RegexKindView::Test(test), false) + } + } + + #[verus_verify] + + fn concat(store: &mut G, children: &[RegexId]) -> KernelResult { + let c = store.constants(); + proof! { regex_constants(store.graph()); } + let mut flat = WorkVec::new(); + let mut collecting = Ok(false); + scan!(collecting,index,children.len(),matches!(collecting,Ok(false)),_prior=>{ + proof_decl! { let ghost prior_flat = flat.view(); } + proof! { regex_concat_flat_prefix(store.graph(), children@, index as int); } + match store.checkpoint() { + Ok(()) => { + match id_at(children, index) { + Ok(id) => { + match id.head(store) { + Ok(head) => { + match head { + RegexHead::Empty => Ok(true), + RegexHead::Epsilon => Ok(false), + RegexHead::Concat(n) => { + proof! { regex_children_count(store.graph(), id@); } + match RegexMode::append_children(store, id, n, &mut flat) { + Ok(()) => { + Ok(false) + } + Err(error) => Err(error), + } + }, + _ => { flat.push(id); Ok(false) }, + } + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + }; + invariant store.graph() == old(store).graph(), index <= children.len(), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).valid_store() ==> store.valid_store(), + old(store).errors_are_non_owner() ==> collecting != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(collecting), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(collecting matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (collecting matches Err(e) ==> resource_error(e)), + store.valid_store(), + model::graph_wf(store.graph()), regex_ids_valid(store.graph(), children@), + regex_ids_valid(store.graph(), flat.view()), + match collecting { + Ok(false) => model::regex_ids(flat.view()) == regex_concat_flat(store.graph(), children@.subrange(0, index as int)) + && forall|i: int| 0 <= i < index + ==> store.graph().regexes[children@[i]@ as int].kind != model::RegexKindNode::Empty, + Ok(true) => exists|i: int| 0 <= i < index + && store.graph().regexes[children@[i]@ as int].kind == model::RegexKindNode::Empty, + Err(_) => true, + }, + decreases children.len() - index, + ); + if collecting? { + proof! { + let i = choose|i: int| 0 <= i < children.len() + && store.graph().regexes[children@[i]@ as int].kind == model::RegexKindNode::Empty; + regex_concat_absorber(store.graph(), children@, i); + } + return Ok(c.empty); + } + proof! { + assert(children@.subrange(0, children@.len() as int) =~= children@); + assert(model::regex_ids(flat.view()) == regex_concat_flat(store.graph(), children@)); + } + let mut n = Ok(true); + scan!(n,index,flat.len(),n.is_ok(),prior=>{ + proof! { regex_nullable_prefix(store.graph(), flat.view(), index as int, true); } + match id_at(&flat, index) { + Ok(id) => { + match RegexId::nullable(id, store) { + Ok(nullable) => { + Ok(if true { prior && nullable } else { prior || nullable }) + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + }; + invariant store.graph() == old(store).graph(), index <= flat.len(), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).valid_store() ==> store.valid_store(), + old(store).errors_are_non_owner() ==> n != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(n), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(n matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (n matches Err(e) ==> resource_error(e)), + store.valid_store(), + model::graph_wf(store.graph()), regex_ids_valid(store.graph(), children@), + regex_ids_valid(store.graph(), flat.view()), + model::regex_ids(flat.view()) == regex_concat_flat(store.graph(), children@), + forall|i: int| 0 <= i < children.len() + ==> store.graph().regexes[children@[i]@ as int].kind != model::RegexKindNode::Empty, + match n { Ok(value) => value == regex_nullable_combo(store.graph(), flat.view().subrange(0, index as int), true), Err(_) => true }, + decreases flat.len() - index, + ); + let n = n?; + proof! { + assert(flat.view().subrange(0, flat.view().len() as int) =~= flat.view()); + assert(n == regex_nullable_combo(store.graph(), flat.view(), true)); + regex_concat_node_wf(store.graph(), flat.view(), n); + assert forall|next: model::Graph| model::graph_extends(store.graph(), next) + implies forall|theta: Subst, word: Seq| + concat_combo(next, theta, flat.view(), word) == concat_combo(next, theta, children@, word) by { + regex_concat_normalization_extends(store.graph(), next, children@, flat.view()); + } + assert forall|theta: Subst, word: Seq| + concat_combo(store.graph(), theta, flat.view(), word) + == concat_combo(store.graph(), theta, children@, word) by { + regex_concat_flat_law(store.graph(), children@, theta, word); + } + assert(model::lift_regexes_bounded(store.graph(), model::regex_ids(flat.view()), store.graph().regexes.len()) + =~= model::lift_regexes(store.graph(), model::regex_ids(flat.view()))); + assert(model::regex_node_wf(store.graph(), model::RegexNode { kind: model::RegexKindNode::Concat(model::regex_ids(flat.view())), nullable: n })); + assert forall|theta: Subst, word: Seq| + flat.view().len() == 0 implies concat_combo(store.graph(), theta, children@, word) == (word.len() == 0) by { + regex_concat_empty::(model::gsem(theta), word); + } + assert forall|theta: Subst, word: Seq| + flat.view().len() == 1 implies concat_combo(store.graph(), theta, children@, word) + == model::regex_lang(store.graph(), theta, flat.view()[0]@, word) by { + if flat.view().len() == 1 { + assert(model::lift_regexes(store.graph(), model::regex_ids(flat.view())) =~= seq![model::lift_regex(store.graph(), flat.view()[0]@)]); + language::lemma_concat_singleton(model::gsem(theta), model::lift_regex(store.graph(), flat.view()[0]@), word); + } + } + } + if flat.is_empty() { + Ok(c.epsilon) + } else if flat.len() == 1 { + id_at(&flat, 0) + } else { + RegexId::intern(store, RegexKindView::Concat(&flat), n) + } + } + + #[verus_verify] + + fn intern( + store: &mut G, + kind: RegexKindView<'_>, + n: bool, + ) -> KernelResult { + let id = store.intern_regex(kind, n)?; + proof! { regex_unfold(store.graph(), id@); } + Ok(id) + } + + #[verus_verify] + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + // rlimit 80 was exceeded when Regorus verifies this crate under its `history` feature set. + #[cfg_attr(verus_keep_ghost, verifier::rlimit(160))] + fn set( + store: &mut G, + children: &[Self], + intersect: bool, + ) -> KernelResult { + let c = store.constants(); + proof! { regex_constants(store.graph()); } + let identity = if intersect { c.all } else { c.empty }; + let absorber = if intersect { c.empty } else { c.all }; + let mode = RegexMode { + intersect, + identity, + absorber, + }; + let mut flat = WorkVec::new(); + let mut collecting = Ok(false); + scan!(collecting,index,children.len(),matches!(collecting,Ok(false)),_prior=>{ + proof_decl! { let ghost prior_flat = flat.view(); } + match id_at(children, index) { + Ok(id) => { + match store.checkpoint() { + Ok(()) => { + proof! { regex_children_count(store.graph(), id@); } + if id == mode.absorber { Ok(true) } else { + match if id != mode.identity { + match id.head(store) { + Ok(head) => { + match head { + RegexHead::Union(n) if !mode.intersect => match RegexMode::append_children(store, id, n, &mut flat) { + Ok(()) => { + proof! { assert(regex_set_piece(store.graph(), id@, mode@) == regex_children(store.graph(), id@)); } + Ok(()) + } + Err(error) => Err(error), + }, + RegexHead::Intersect(n) if mode.intersect => match RegexMode::append_children(store, id, n, &mut flat) { + Ok(()) => { + proof! { assert(regex_set_piece(store.graph(), id@, mode@) == regex_children(store.graph(), id@)); } + Ok(()) + } + Err(error) => Err(error), + }, + _ => { + flat.push(id); + proof! { regex_ids_push(prior_flat, id); assert(regex_set_piece(store.graph(), id@, mode@) == seq![id@]); } + Ok(()) + }, + } + } + Err(error) => Err(error), + } + } else { Ok(()) } { + Ok(()) => { + proof! { + assert(model::regex_ids(prior_flat).push(id@) =~= model::regex_ids(prior_flat) + seq![id@]); + assert(model::regex_ids(prior_flat) + Seq::::empty() =~= model::regex_ids(prior_flat)); + regex_collect_preserves(store.graph(), id, prior_flat, flat.view(), mode@); + assert forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + implies regex_combo(store.graph(), theta, flat.view(), word, mode.intersect) + == regex_combo(store.graph(), theta, children@.subrange(0, index as int + 1), word, mode.intersect) by { + regex_combo_push(store.graph(), prior_flat, id, theta, word, mode.intersect); + regex_combo_prefix(store.graph(), children@, index as int, theta, word, mode.intersect); + } + let piece = regex_set_piece(store.graph(), id@, mode@); + assert(model::regex_ids(flat.view()) == model::regex_ids(prior_flat) + piece); + assert(model::regex_ids(flat.view()).len() == flat.view().len()); + assert(model::regex_ids(prior_flat).len() == prior_flat.len()); + assert forall|k: int| 0 <= k < flat.view().len() + implies regex_member(store.graph(), children@, intersect, #[trigger] flat.view()[k]@) by { + assert(model::regex_ids(flat.view())[k] == flat.view()[k]@); + if k < prior_flat.len() { + assert(model::regex_ids(prior_flat)[k] == prior_flat[k]@); + assert(model::regex_ids(flat.view())[k] == model::regex_ids(prior_flat)[k]); + } else { + assert(children@[index as int] == id); + let j = k - prior_flat.len(); + assert(model::regex_ids(flat.view())[k] == (model::regex_ids(prior_flat) + piece)[k]); + assert(model::regex_ids(flat.view())[k] == piece[j]); + assert(piece.contains(piece[j])); + assert(regex_piece_contains(store.graph(), children@[index as int]@, intersect, flat.view()[k]@)); + } + } + } + Ok(false) + } + Err(error) => Err(error), + } + } + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + }; + invariant store.graph() == old(store).graph(), store.valid_store(), model::graph_wf(store.graph()), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).valid_store() ==> store.valid_store(), + old(store).errors_are_non_owner() ==> collecting != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(collecting), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(collecting matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (collecting matches Err(e) ==> resource_error(e)), + regex_mode_wf(store.graph(), mode@), regex_ids_valid(store.graph(), children@), regex_ids_valid(store.graph(), flat.view()), index <= children.len(), + mode.intersect == intersect, mode.absorber == absorber, + match collecting { + Ok(false) => regex_equivalent(store.graph(), flat.view(), children@.subrange(0, index as int), intersect) + && forall|k: int| 0 <= k < flat.view().len() + ==> regex_member(store.graph(), children@, intersect, #[trigger] flat.view()[k]@), + Ok(true) => exists|i: int| 0 <= i < index && children@[i] == absorber, + Err(_) => true, + }, + decreases children.len() - index, + ); + if collecting? { + proof! { + let i = choose|i: int| 0 <= i < children.len() && children@[i] == absorber; + regex_absorber_member(store.graph(), children@, i, mode@); + } + return Ok(absorber); + } + proof! { assert(children@.subrange(0, children.len() as int) =~= children@); } + let mut tests = WorkVec::new(); + let mut others = WorkVec::new(); + let mut splitting = Ok(()); + scan!(splitting,index,flat.len(),splitting.is_ok(),_prior=>{ + proof_decl! { let ghost prior_tests = tests.view(); let ghost prior_others = others.view(); } + match store.checkpoint() { + Ok(()) => { + match id_at(&flat, index) { + Ok(id) => { + proof! { model::lemma_graph_regex_wf(store.graph(), id@); } + match id.head(store) { + Ok(head) => { + match head { + RegexHead::Test(t) => { tests.push(t); proof! { regex_test_ids_push(prior_tests, t); } }, + _ => others.push(id), + } + proof! { + assert forall|theta: Subst, word: Seq, intersect: bool| + regex_group_combo(store.graph(), theta, tests.view(), others.view(), word, intersect) + == regex_combo(store.graph(), theta, flat.view().subrange(0, index as int + 1), word, intersect) by { + regex_split_preserves(store.graph(), id, prior_tests, prior_others, tests.view(), others.view(), intersect); + regex_combo_prefix(store.graph(), flat.view(), index as int, theta, word, intersect); + } + assert(regex_member(store.graph(), children@, intersect, flat.view()[index as int]@)); + assert forall|k: int| 0 <= k < others.view().len() + implies regex_member(store.graph(), children@, intersect, #[trigger] others.view()[k]@) by { + if k < prior_others.len() { assert(others.view()[k] == prior_others[k]); } + else { assert(others.view()[k] == flat.view()[index as int]); } + } + assert forall|k: int| 0 <= k < tests.view().len() + implies regex_member_test(store.graph(), children@, intersect, #[trigger] tests.view()[k]@) by { + if k < prior_tests.len() { + assert(tests.view()[k] == prior_tests[k]); + } else { + assert(store.graph().regexes[flat.view()[index as int]@ as int].kind + == model::RegexKindNode::Test(tests.view()[k]@)); + } + } + } + Ok(()) + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + }; + invariant store.graph() == old(store).graph(), store.valid_store(), model::graph_wf(store.graph()), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).valid_store() ==> store.valid_store(), + old(store).errors_are_non_owner() ==> splitting != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(splitting), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(splitting matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (splitting matches Err(e) ==> resource_error(e)), + regex_ids_valid(store.graph(), flat.view()), regex_ids_valid(store.graph(), children@), + regex_equivalent(store.graph(), flat.view(), children@, intersect), + test_ids_valid(store.graph(), tests.view()), regex_ids_valid(store.graph(), others.view()), index <= flat.len(), + forall|k: int| 0 <= k < flat.view().len() + ==> regex_member(store.graph(), children@, intersect, #[trigger] flat.view()[k]@), + forall|k: int| 0 <= k < others.view().len() + ==> regex_member(store.graph(), children@, intersect, #[trigger] others.view()[k]@), + forall|k: int| 0 <= k < tests.view().len() + ==> regex_member_test(store.graph(), children@, intersect, #[trigger] tests.view()[k]@), + match splitting { Ok(()) => regex_split_prefix(store.graph(), flat.view(), tests.view(), others.view(), index as nat), Err(_) => true }, + decreases flat.len() - index, + ); + splitting?; + proof_decl! { let ghost grouped_graph = store.graph(); let ghost grouped_others = others.view(); } + proof! { + assert(flat.view().subrange(0, flat.view().len() as int) =~= flat.view()); + regex_group_equivalence_extends(grouped_graph, grouped_graph, children@, tests.view(), grouped_others, intersect); + assert forall|next: model::Graph| model::graph_extends(grouped_graph, next) + implies forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + ==> regex_group_combo(next, theta, tests.view(), grouped_others, word, intersect) + == regex_combo(next, theta, children@, word, intersect) by { + regex_group_equivalence_extends(grouped_graph, next, children@, tests.view(), grouped_others, intersect); + } + } + proof_decl! { let ghost mut chosen: nat = 0; let ghost mut chosen_graph = grouped_graph; } + if !tests.is_empty() { + let r = { + match TestId::connective(store, &tests, intersect) { + Ok(test) => { + proof_decl! { let ghost test_graph = store.graph(); } + proof! { + assert forall|next: model::Graph| model::graph_extends(test_graph, next) + implies forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + ==> model::test_holds(theta, model::lift_test(next, test@), event) + == test_combo(next, theta, tests.view(), event, intersect) by { + regex_test_connective_extends(test_graph, next, tests.view(), test, intersect); + } + } + proof! { chosen = test@; chosen_graph = test_graph; } + RegexId::from_test(store, test) + } + Err(error) => Err(error), + } + }?; + proof! { + regex_constants(store.graph()); + assert(model::graph_extends(grouped_graph, store.graph())); + regex_group_equivalence_extends(grouped_graph, store.graph(), children@, tests.view(), grouped_others, intersect); + assert forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + implies model::regex_lang(store.graph(), theta, r@, word) + == regex_test_combo(store.graph(), theta, tests.view(), word, intersect) by {}; + } + if intersect && r == c.empty { + proof! { + assert forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + implies !regex_combo(store.graph(), theta, children@, word, intersect) by { + assert(regex_group_combo(store.graph(), theta, tests.view(), grouped_others, word, intersect) + == regex_combo(store.graph(), theta, children@, word, intersect)); + assert(!model::regex_lang(store.graph(), theta, r@, word)); + } + } + return Ok(c.empty); + } + if r != c.empty { + others.push(r); + proof! { + assert forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + implies regex_combo(store.graph(), theta, others.view(), word, intersect) + == regex_combo(store.graph(), theta, children@, word, intersect) by { + regex_combo_push(store.graph(), grouped_others, r, theta, word, intersect); + assert(regex_group_combo(store.graph(), theta, tests.view(), grouped_others, word, intersect) + == regex_combo(store.graph(), theta, children@, word, intersect)); + } + } + } + proof! { + if r == c.empty { + assert forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + implies regex_combo(store.graph(), theta, others.view(), word, intersect) + == regex_combo(store.graph(), theta, children@, word, intersect) by { + assert(!intersect); + assert(!model::regex_lang(store.graph(), theta, r@, word)); + assert(regex_group_combo(store.graph(), theta, tests.view(), grouped_others, word, intersect) + == regex_combo(store.graph(), theta, children@, word, intersect)); + } + } + if r != c.empty { + test_connective_result_extends(grouped_graph, chosen_graph, store.graph(), tests.view(), intersect, chosen); + assert(store.graph().regexes[r@ as int].kind == model::RegexKindNode::Test(chosen)); + assert(regex_combined_test(old(store).graph(), store.graph(), children@, intersect, r@)); + } + assert forall|k: int| 0 <= k < others.view().len() + implies regex_set_operand_ok(old(store).graph(), store.graph(), children@, intersect, #[trigger] others.view()[k]@) by { + if k < grouped_others.len() { assert(others.view()[k] == grouped_others[k]); } + } + } + } + proof! { + assert forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + implies regex_combo(store.graph(), theta, others.view(), word, intersect) + == regex_combo(store.graph(), theta, children@, word, intersect) by { + assert(regex_group_combo(store.graph(), theta, tests.view(), grouped_others, word, intersect) + == regex_combo(store.graph(), theta, children@, word, intersect)); + } + } + proof_decl! { let ghost gt = store.graph(); } + proof! { + assert forall|k: int| 0 <= k < others.view().len() + implies regex_set_operand_ok(old(store).graph(), gt, children@, intersect, #[trigger] others.view()[k]@) by { + if tests.view().len() == 0 { assert(regex_member(old(store).graph(), children@, intersect, others.view()[k]@)); } + } + } + proof_decl! { let ghost unsorted = others.view(); } + proof! { junco_core::kernel::RegexId::lemma_obeys_cmp(); } + others.as_mut_slice().sort_unstable(); + proof! { + regex_multiset_members(unsorted, others.view()); + regex_member_ids_valid(store.graph(), unsorted, others.view()); + regex_combo_permutation(store.graph(), unsorted, others.view(), intersect); + assert forall|i: int, j: int| 0 <= i < j < others.view().len() implies others.view()[i]@ <= others.view()[j]@ by { + assert(!(OrdSpec::cmp_spec(&others.view()[i], &others.view()[j]) is Greater)); + assert(others.view()[i]@ <= others.view()[j]@); + } + } + proof_decl! { let ghost sorted = others.view(); } + dedup_ids(&mut others)?; + proof! { + regex_member_ids_valid(store.graph(), sorted, others.view()); + regex_combo_members(store.graph(), sorted, others.view(), intersect); + regex_dedup_strict(sorted, others.view()); + assert forall|k: int| 0 <= k < others.view().len() + implies regex_set_operand_ok(old(store).graph(), gt, children@, intersect, #[trigger] others.view()[k]@) by { + assert(sorted.contains(others.view()[k])); + assert(unsorted.contains(others.view()[k])); + let j = choose|j: int| 0 <= j < unsorted.len() && unsorted[j] == others.view()[k]; + } + } + let mut stats = Ok(RegexStats { + all_nullable: true, + any_nullable: false, + epsilon: false, + complement: false, + has_nonnullable: false, + }); + scan!(stats,index,others.len(),stats.is_ok(),prior=>prior.update(store,&others,index,c.epsilon,true); + invariant model::graph_extends(old(store).graph(), store.graph()), store.valid_store(), model::graph_wf(store.graph()), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).valid_store() ==> store.valid_store(), + old(store).errors_are_non_owner() ==> stats != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(stats), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(stats matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (stats matches Err(e) ==> resource_error(e)), + store.graph().constants == c@, regex_ids_valid(store.graph(), others.view()), regex_ids_valid(store.graph(), children@), + store.graph() == gt, + forall|k: int| 0 <= k < others.view().len() + ==> regex_set_operand_ok(old(store).graph(), gt, children@, intersect, #[trigger] others.view()[k]@), + regex_equivalent(store.graph(), others.view(), children@, intersect), model::strictly_increasing(model::regex_ids(others.view())), index <= others.len(), + match stats { Ok(value) => regex_stats_prefix(store.graph(), others.view(), index as nat, c.epsilon, value@, true), Err(_) => true }, + decreases others.len() - index, + ); + let stats = stats?; + proof! { + regex_constants(store.graph()); + regex_stats_decisions(store.graph(), others.view(), c.epsilon, stats@, intersect); + } + if stats.complement { + return Ok(absorber); + } + if intersect && stats.epsilon { + return Ok(if stats.all_nullable { + c.epsilon + } else { + c.empty + }); + } + let mut index = 0; + let mut failure = None; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant model::graph_extends(old(store).graph(), store.graph()), store.valid_store(), model::graph_wf(store.graph()), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).valid_store() ==> store.valid_store(), + old(store).errors_are_non_owner() ==> failure != Some(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> (match failure { Some(error) => language::no_invariant_failure::<()>(Err(error)), None => true }), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> (match failure { Some(error) => !(error is InvalidPolicy), None => true }), + old(store).errors_are_resource() && old(store).valid_store() ==> (failure matches Some(e) ==> resource_error(e)), + regex_ids_valid(store.graph(), others.view()), index <= others.len(), + store.graph() == gt, store.graph().constants == c@, + forall|k: int| 0 <= k < others.view().len() + ==> regex_set_operand_ok(old(store).graph(), gt, children@, intersect, #[trigger] others.view()[k]@), + mode.intersect == intersect, regex_ids_valid(store.graph(), children@), + forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + ==> regex_combo(store.graph(), theta, others.view(), word, intersect) + == regex_combo(store.graph(), theta, children@, word, intersect), + model::strictly_increasing(model::regex_ids(others.view())), + decreases others.len() - index, + ))] + while index < others.len() { + proof_decl! { let ghost previous = others.view(); } + let removed = loop_try!( + { + proof_decl! { let ghost prior_ids = others.view(); let ghost retention_graph = store.graph(); } + match store.checkpoint() { + Ok(()) => match id_at(&others, index) { + Ok(id) => { + let epsilon = store.constants().epsilon; + let mut stats = Ok(RegexStats { + all_nullable: true, + any_nullable: false, + epsilon: false, + complement: false, + has_nonnullable: false, + }); + scan!(stats,scan_index,others.len(),stats.is_ok(),prior=>prior.update(store,&others,scan_index,epsilon,false); + invariant store.graph() == retention_graph, store.valid_store(), model::graph_wf(store.graph()), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).valid_store() ==> store.valid_store(), + old(store).errors_are_non_owner() ==> stats != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(stats), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(stats matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (stats matches Err(e) ==> resource_error(e)), + others.view() == prior_ids, regex_ids_valid(store.graph(), others.view()), scan_index <= others.len(), + match stats { Ok(value) => regex_stats_prefix(store.graph(), others.view(), scan_index as nat, epsilon, value@, false), Err(_) => true }, + decreases others.len() - scan_index, + ); + match stats { + Ok(stats) => match id.head(store) { + Ok(head) => { + let redundant = (!mode.intersect + && id == epsilon + && stats.any_nullable) + || (mode.intersect + && stats.has_nonnullable + && matches!(head,RegexHead::Not(inner) if inner==epsilon)); + match mode.absorbed(store, id, &others) { + Ok(absorbed) => { + if redundant || absorbed { + proof! { + regex_retention_remove(store.graph(), others.view(), index as int, mode@, epsilon, stats@); + regex_remove_strict(others.view(), index as int); + assert forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + implies regex_combo(store.graph(), theta, others.view().remove(index as int), word, mode.intersect) + == regex_combo(store.graph(), theta, others.view(), word, mode.intersect) by { + assert(mode@.intersect == mode.intersect); + } + } + others.remove(index); + proof! { + assert forall|k: int| 0 <= k < others.view().len() + implies regex_set_operand_ok(old(store).graph(), gt, children@, intersect, + #[trigger] others.view()[k]@) by { + if k < index { assert(others.view()[k] == prior_ids[k]); } + else { assert(others.view()[k] == prior_ids[k + 1]); } + } + } + Ok(true) + } else { + Ok(false) + } + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + }, + Err(error) => Err(error), + } + } + Err(error) => Err(error), + }, + Err(error) => Err(error), + } + }, + failure + ); + proof! { + assert forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + implies regex_combo(store.graph(), theta, others.view(), word, intersect) + == regex_combo(store.graph(), theta, children@, word, intersect) by { + assert(regex_combo(store.graph(), theta, others.view(), word, intersect) + == regex_combo(store.graph(), theta, previous, word, intersect)); + } + } + if !removed { + index = index.saturating_add(1); + } + } + if let Some(error) = failure { + return Err(error); + } + let mut n = Ok(intersect); + scan!(n,index,others.len(),n.is_ok(),prior=>{ + proof! { regex_nullable_prefix(store.graph(), others.view(), index as int, intersect); } + match id_at(&others, index) { + Ok(id) => { + match RegexId::nullable(id, store) { + Ok(nullable) => { + Ok(if intersect { prior && nullable } else { prior || nullable }) + } + Err(error) => Err(error), + } + } + Err(error) => Err(error), + } + }; + invariant model::graph_extends(old(store).graph(), store.graph()), store.valid_store(), model::graph_wf(store.graph()), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).valid_store() ==> store.valid_store(), + old(store).errors_are_non_owner() ==> n != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(n), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(n matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (n matches Err(e) ==> resource_error(e)), + regex_ids_valid(store.graph(), others.view()), regex_ids_valid(store.graph(), children@), + store.graph() == gt, store.graph().constants == c@, + forall|k: int| 0 <= k < others.view().len() + ==> regex_set_operand_ok(old(store).graph(), gt, children@, intersect, #[trigger] others.view()[k]@), + regex_equivalent(store.graph(), others.view(), children@, intersect), model::strictly_increasing(model::regex_ids(others.view())), index <= others.len(), + match n { Ok(value) => value == regex_nullable_combo(store.graph(), others.view().subrange(0, index as int), intersect), Err(_) => true }, + decreases others.len() - index, + ); + let n = n?; + proof! { + regex_constants(store.graph()); + assert(others.view().subrange(0, others.view().len() as int) =~= others.view()); + regex_set_node_wf(store.graph(), others.view(), n, intersect); + regex_set_result(store.graph(), others.view(), children@, intersect); + assert forall|next: model::Graph| model::graph_extends(store.graph(), next) + implies regex_equivalent(next, others.view(), children@, intersect) by { + regex_equivalence_extends(store.graph(), next, others.view(), children@, intersect); + } + if others.view().len() == 1 && regex_set_flat_inputs(old(store).graph(), children@, intersect) { + let o0 = others.view()[0]@; + assert(regex_set_operand_ok(old(store).graph(), gt, children@, intersect, o0)); + if regex_member(old(store).graph(), children@, intersect, o0) { + regex_member_valid(old(store).graph(), children@, intersect, o0); + assert(!regex_is_set(old(store).graph(), o0, intersect)); + assert(old(store).graph().regexes == store.graph().regexes.subrange(0, old(store).graph().regexes.len() as int)); + assert(store.graph().regexes[o0 as int] == old(store).graph().regexes[o0 as int]); + } + assert forall|o: nat| #[trigger] regex_piece_contains(store.graph(), o0, intersect, o) + implies regex_set_operand_ok(old(store).graph(), store.graph(), children@, intersect, o) by {} + } + } + if others.is_empty() { + Ok(identity) + } else if others.len() == 1 { + id_at(&others, 0) + } else { + let id = RegexId::intern( + store, + if intersect { + RegexKindView::Intersect(&others) + } else { + RegexKindView::Union(&others) + }, + n, + )?; + proof! { + assert forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + implies model::regex_lang(store.graph(), theta, id@, word) + == regex_combo(store.graph(), theta, children@, word, intersect) by { + regex_node_language(store.graph(), id@, theta, word); + regex_combo_ids(store.graph(), others.view(), theta, word, intersect); + assert(model::regex_lang(store.graph(), theta, id@, word) + == regex_combo_nats(store.graph(), theta, model::regex_ids(others.view()), word, intersect)); + assert(regex_combo(store.graph(), theta, others.view(), word, intersect) + == regex_combo(store.graph(), theta, children@, word, intersect)); + } + assert forall|o: nat| #[trigger] regex_piece_contains(store.graph(), id@, intersect, o) + implies regex_set_operand_ok(old(store).graph(), store.graph(), children@, intersect, o) by { + let ids = model::regex_ids(others.view()); + assert(ids.contains(o)); + let k = choose|k: int| 0 <= k < ids.len() && ids[k] == o; + assert(ids[k] == others.view()[k]@); + assert(regex_set_operand_ok(old(store).graph(), gt, children@, intersect, others.view()[k]@)); + if !regex_member(old(store).graph(), children@, intersect, o) { + regex_combined_test_extends(old(store).graph(), gt, store.graph(), children@, intersect, o); + } + } + } + Ok(id) + } + } +} + +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy)] +struct TransitionMode { + intersect: bool, + identity: TransitionId, + absorber: TransitionId, +} + +#[verus_verify] +impl TransitionMode { + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), old(store).valid_store(), transition_mode_valid(old(store).graph(), self@), + transition_ids_valid(old(store).graph(), old(pending).view()), + transition_ids_valid(old(store).graph(), old(flat).view()), regex_ids_valid(old(store).graph(), old(constants).view()), + ensures final(store).graph() == old(store).graph(), model::graph_wf(final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + final(store).valid_store() == old(store).valid_store(), + transition_ids_valid(final(store).graph(), final(pending).view()), + transition_ids_valid(final(store).graph(), final(flat).view()), regex_ids_valid(final(store).graph(), final(constants).view()), + forall|i: int| old(flat).view().len() <= i < final(flat).view().len() + ==> transition_set_leaf(final(store).graph().transitions[final(flat).view()[i]@ as int], self.intersect), + match result { + Ok(collapsed) => transition_collect_effect(final(store).graph(), self@, + old(pending).view(), old(flat).view(), old(constants).view(), + final(pending).view(), final(flat).view(), final(constants).view(), collapsed) + && (!collapsed ==> final(pending).view().len() == 0) + && (!collapsed ==> collect_total(final(store).graph(), final(pending).view(), final(flat).view(), + final(constants).view(), self.intersect) + <= collect_total(old(store).graph(), old(pending).view(), old(flat).view(), + old(constants).view(), self.intersect)) + && ((old(flat).view().len() == 0 && old(constants).view().len() == 0) + ==> fcol::collect_members(final(store).graph(), model::transition_ids(old(pending).view()), + self.intersect, final(pending).view(), final(flat).view(), final(constants).view())), + Err(_) => true, + }, + )] + fn collect( + self, + store: &mut G, + pending: &mut WorkVec, + flat: &mut WorkVec, + constants: &mut WorkVec, + ) -> KernelResult { + proof_decl! { + let ghost p0 = pending.view(); + let ghost f0 = flat.view(); + let ghost rs0 = constants.view(); + let ghost orig = model::transition_ids(pending.view()); + let ghost fresh = flat.view().len() == 0 && constants.view().len() == 0; + } + proof! { + if p0.len() > 0 { transition_lemma_pending_work_pop(store.graph(), p0, self.intersect); } + if fresh { + fcol::lemma_members_start(store.graph(), p0, self.intersect); + assert(f0 =~= Seq::::empty()); + assert(rs0 =~= Seq::::empty()); + } + assert(model::bounded(orig, store.graph().transitions.len())); + } + let mut state = Ok(false); + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant store.graph() == old(store).graph(), model::graph_wf(store.graph()), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).valid_store() ==> store.valid_store(), + old(store).errors_are_non_owner() ==> state != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(state), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(state matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (state matches Err(e) ==> resource_error(e)), + store.valid_store(), transition_mode_valid(store.graph(), self@), + transition_ids_valid(store.graph(), pending.view()), transition_ids_valid(store.graph(), flat.view()), + regex_ids_valid(store.graph(), constants.view()), + flat.view().len() >= f0.len(), + forall|i: int| f0.len() <= i < flat.view().len() + ==> transition_set_leaf(store.graph().transitions[flat.view()[i]@ as int], self.intersect), + model::bounded(orig, store.graph().transitions.len()), + fresh && state.is_ok() ==> fcol::collect_members(store.graph(), orig, self.intersect, pending.view(), flat.view(), constants.view()), + match state { + Ok(collapsed) => forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_collect_combo(store.graph(), theta, p0, f0, rs0, event, word, self.intersect) + == if collapsed { !self.intersect } else { + transition_collect_combo(store.graph(), theta, pending.view(), flat.view(), constants.view(), event, word, self.intersect) + }, + Err(_) => true, + }, + match state { + Ok(false) => collect_total(store.graph(), pending.view(), flat.view(), constants.view(), self.intersect) + <= collect_total(store.graph(), p0, f0, rs0, self.intersect), + _ => true, + }, + decreases match state { Ok(false) => transition_pending_work(store.graph(), pending.view(), self.intersect) + 1, _ => 0nat }, + ))] + while !pending.is_empty() && matches!(state, Ok(false)) { + state = { + proof_decl! { + let ghost p0 = pending.view(); + let ghost f0 = flat.view(); + let ghost rs0 = constants.view(); + } + match match pending.pop() { + Some(id) => Ok(id), + None => Err(HistoryError::normalization_invariant()), + } { + Ok(id) => match store.checkpoint() { + Ok(()) => { + proof_decl! { let ghost prefix = pending.view(); } + proof! { + transition_lemma_identities(store.graph(), self@); + model::lemma_graph_transition_wf(store.graph(), id@); + assert(p0 =~= prefix.push(id)); + if fresh { fcol::lemma_members_pop(store.graph(), orig, self.intersect, prefix, id, f0, rs0); } + } + if id == self.absorber { + proof! { transition_lemma_collect_absorber(store.graph(), self@, p0, f0, rs0); } + Ok(true) + } else { + match if id != self.identity { + match id.head(store) { + Ok(head) => match head { + TransitionHead::Union(n) if !self.intersect => { + match TransitionId::collect_children( + store, id, n, pending, + ) { + Ok(()) => { + proof! { + let children = pending.view().subrange(prefix.len() as int, pending.view().len() as int); + assert(prefix + children =~= pending.view()); + assert(model::transition_ids(prefix + children) + =~= model::transition_ids(prefix) + model::transition_ids(children)); + transition_lemma_image_suffix(prefix, pending.view(), transition_children(store.graph(), id@)); + assert(model::transition_ids(children) =~= transition_children(store.graph(), id@)); + reveal(transition_children); + transition_lemma_collect_expand(store.graph(), self@, p0, f0, rs0, children); + collect_lemma_expand(store.graph(), prefix, id, children, f0, rs0, self.intersect); + if fresh { + assert(store.graph().transitions[id@ as int] + == model::TransitionNode::Union(transition_children(store.graph(), id@))); + fcol::lemma_members_expand(store.graph(), orig, self.intersect, prefix, id, + children, f0, rs0, transition_children(store.graph(), id@)); + } + } + + Ok(()) + } + Err(error) => Err(error), + } + } + TransitionHead::Intersect(n) if self.intersect => { + match TransitionId::collect_children( + store, id, n, pending, + ) { + Ok(()) => { + proof! { + let children = pending.view().subrange(prefix.len() as int, pending.view().len() as int); + assert(prefix + children =~= pending.view()); + assert(model::transition_ids(prefix + children) + =~= model::transition_ids(prefix) + model::transition_ids(children)); + transition_lemma_image_suffix(prefix, pending.view(), transition_children(store.graph(), id@)); + assert(model::transition_ids(children) =~= transition_children(store.graph(), id@)); + reveal(transition_children); + transition_lemma_collect_expand(store.graph(), self@, p0, f0, rs0, children); + collect_lemma_expand(store.graph(), prefix, id, children, f0, rs0, self.intersect); + if fresh { + assert(store.graph().transitions[id@ as int] + == model::TransitionNode::Intersect(transition_children(store.graph(), id@))); + fcol::lemma_members_expand(store.graph(), orig, self.intersect, prefix, id, + children, f0, rs0, transition_children(store.graph(), id@)); + } + } + + Ok(()) + } + Err(error) => Err(error), + } + } + TransitionHead::Const(r) if self.intersect => { + constants.push(r); + proof! { + transition_lemma_collect_constant(store.graph(), self@, p0, f0, rs0, r); + collect_lemma_constant(store.graph(), prefix, id, f0, rs0, r, self.intersect); + if fresh { + assert(store.graph().transitions[id@ as int] == model::TransitionNode::Const(r@)); + fcol::lemma_members_const(store.graph(), orig, self.intersect, prefix, id, f0, rs0, r); + } + } + + Ok(()) + } + _ => { + flat.push(id); + proof! { + transition_lemma_collect_leaf(store.graph(), self@, p0, f0, rs0); + collect_lemma_leaf(store.graph(), prefix, id, f0, rs0, self.intersect); + if fresh { + assert(fcol::flat_ok(store.graph(), self.intersect, id@)); + fcol::lemma_members_leaf(store.graph(), orig, self.intersect, prefix, id, f0, rs0); + } + } + + Ok(()) + } + }, + Err(error) => Err(error), + } + } else { + Ok(()) + } { + Ok(()) => { + proof! { + if id == self.identity { + transition_lemma_collect_identity(store.graph(), self@, p0, f0, rs0); + collect_lemma_drop(store.graph(), prefix, id, f0, rs0, self.intersect); + } + } + Ok(false) + } + Err(error) => Err(error), + } + } + } + Err(error) => Err(error), + }, + Err(error) => Err(error), + } + }; + } + state + } +} +verus! { +pub(crate) trait TransitionNormalize: Sized { + fn constant(store: &mut G, regex: RegexId) -> (result: KernelResult) + requires model::graph_wf(old(store).graph()), old(store).valid_store(), regex@ < old(store).graph().regexes.len(), + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + model::graph_wf(final(store).graph()), final(store).valid_store(), + match result { + Ok(id) => id@ < final(store).graph().transitions.len() + && final(store).graph().transitions[id@ as int] == model::TransitionNode::Const(regex@) + && forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_lang(final(store).graph(), theta, id, event, word) + == model::regex_lang(final(store).graph(), theta, regex@, word), + Err(_) => true, + }, + result matches Ok(id) ==> guard_vocab(final(store).graph(), id@) == Set::empty(), + ; + + fn if_then_else( + store: &mut G, + test: TestId, + then_id: TransitionId, + else_id: TransitionId, + ) -> (result: KernelResult) + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + test@ < old(store).graph().tests.len(), then_id@ < old(store).graph().transitions.len(), + else_id@ < old(store).graph().transitions.len(), + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + model::graph_wf(final(store).graph()), final(store).valid_store(), + match result { Ok(id) => id@ < final(store).graph().transitions.len() + && ((ftr::nf_sum(old(store).graph(), then_id@) && ftr::nf_sum(old(store).graph(), else_id@)) + ==> fsteps::ite_bound(final(store).graph(), id@, then_id@, else_id@)) + && forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_lang(final(store).graph(), theta, id, event, word) + == transition_if_combo(final(store).graph(), theta, test, then_id, else_id, event, word), Err(_) => true }, + result matches Ok(id) ==> guard_vocab(final(store).graph(), id@).subset_of( + test_vocab(final(store).graph(), test@).union(guard_vocab(final(store).graph(), then_id@)) + .union(guard_vocab(final(store).graph(), else_id@))), + ; + + fn intersect( + store: &mut G, + children: &[TransitionId], + ) -> (result: KernelResult) + requires model::graph_wf(old(store).graph()), old(store).valid_store(), transition_ids_valid(old(store).graph(), children@), + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + model::graph_wf(final(store).graph()), final(store).valid_store(), + match result { Ok(id) => id@ < final(store).graph().transitions.len() + && transition_result(final(store).graph(), ActionShape::Fold(model::transition_ids(children@), 0), id) + && (fcol::all_nf(old(store).graph(), model::transition_ids(children@)) + ==> fsteps::run_bound(final(store).graph(), ActionShape::Fold(model::transition_ids(children@), 0), id@)), Err(_) => true }, + result matches Ok(id) ==> guard_vocab(final(store).graph(), id@).subset_of( + guard_task_vocab(final(store).graph(), ActionShape::Fold(model::transition_ids(children@), 0))), + ; + + fn not(this: TransitionId, store: &mut G) -> (result: KernelResult) + requires model::graph_wf(old(store).graph()), old(store).valid_store(), this@ < old(store).graph().transitions.len(), + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + model::graph_wf(final(store).graph()), final(store).valid_store(), + match result { Ok(id) => id@ < final(store).graph().transitions.len() + && transition_result(final(store).graph(), ActionShape::Not(this@), id) + && (ftr::nf_sum(old(store).graph(), this@) ==> fsteps::run_bound(final(store).graph(), ActionShape::Not(this@), id@)), + Err(_) => true }, + result matches Ok(id) ==> guard_vocab(final(store).graph(), id@).subset_of(guard_vocab(final(store).graph(), this@)), + ; + + fn append( + this: TransitionId, + store: &mut G, + suffix: &[RegexId], + ) -> (result: KernelResult) + requires model::graph_wf(old(store).graph()), old(store).valid_store(), this@ < old(store).graph().transitions.len(), + regex_ids_valid(old(store).graph(), suffix@), + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + model::graph_wf(final(store).graph()), final(store).valid_store(), + match result { Ok(id) => id@ < final(store).graph().transitions.len() + && ((ftr::nf_sum(old(store).graph(), this@) && flink::ids_nf(old(store).graph(), suffix@)) + ==> fsteps::app_bound(final(store).graph(), id@, this@, flink::lifts(final(store).graph(), suffix@))) + && forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_lang(final(store).graph(), theta, id, event, word) + == transition_append_combo(final(store).graph(), theta, this, suffix@, event, word), + Err(_) => true }, + result matches Ok(id) ==> guard_vocab(final(store).graph(), id@).subset_of(guard_vocab(final(store).graph(), this@)), + ; + + fn intern( + store: &mut G, + node: TransitionView<'_>, + ) -> (result: KernelResult) + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + model::transition_node_wf(old(store).graph(), node@), + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + model::graph_wf(final(store).graph()), final(store).valid_store(), + match result { + Ok(id) => id@ < final(store).graph().transitions.len() + && final(store).graph().transitions[id@ as int] == node@ + && model::lift_transition(final(store).graph(), id@) + == transition_unbounded_node(final(store).graph(), node@) + && tdepth(final(store).graph(), id@) == tdepth_node(final(store).graph(), node@), + Err(_) => true, + }, + result matches Ok(id) ==> guard_vocab(final(store).graph(), id@) == guard_node_vocab(final(store).graph(), node@), + ; + + fn local_if( + store: &mut G, + test: TestId, + a: TransitionId, + b: TransitionId, + ) -> (result: KernelResult) + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + test@ < old(store).graph().tests.len(), a@ < old(store).graph().transitions.len(), b@ < old(store).graph().transitions.len(), + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + model::graph_wf(final(store).graph()), final(store).valid_store(), + match result { + Ok(id) => id@ < final(store).graph().transitions.len() + && tdepth(final(store).graph(), id@) + <= if_bound(tdepth(old(store).graph(), a@), tdepth(old(store).graph(), b@)) + && (id@ == a@ || id@ == b@ + || final(store).graph().transitions[id@ as int] == model::TransitionNode::If(test@, a@, b@)) + && forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_lang(final(store).graph(), theta, id, event, word) + == transition_if_combo(final(store).graph(), theta, test, a, b, event, word), + Err(_) => true, + }, + result matches Ok(id) ==> guard_vocab(final(store).graph(), id@).subset_of( + test_vocab(final(store).graph(), test@).union(guard_vocab(final(store).graph(), a@)) + .union(guard_vocab(final(store).graph(), b@))), + ; + + fn collect( + store: &mut G, + children: &[TransitionId], + intersect: bool, + ) -> (result: KernelResult) + requires model::graph_wf(old(store).graph()), old(store).valid_store(), transition_ids_valid(old(store).graph(), children@), + ensures model::graph_extends(old(store).graph(), final(store).graph()), model::graph_wf(final(store).graph()), final(store).valid_store(), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + match result { + Ok(id) => id@ < final(store).graph().transitions.len() + && tdepth(final(store).graph(), id@) <= collect_bound(old(store).graph(), children@, intersect) + && (match final(store).graph().transitions[id@ as int] { + model::TransitionNode::Intersect(cs) => intersect ==> cs.len() > 1, + model::TransitionNode::Union(cs) => !intersect ==> cs.len() > 1, + _ => true, + }) + && (fcol::all_nf(old(store).graph(), model::transition_ids(children@)) + ==> fcol::collect_out(final(store).graph(), model::transition_ids(children@), intersect, id@)) + && forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_lang(final(store).graph(), theta, id, event, word) + == transition_combo(final(store).graph(), theta, children@, event, word, intersect), + Err(_) => true, + }, + result matches Ok(id) ==> guard_vocab(final(store).graph(), id@).subset_of( + guard_task_vocab(final(store).graph(), ActionShape::Fold(model::transition_ids(children@), 0))), + ; + + fn collect_children( + store: &G, + id: TransitionId, + count: usize, + flat: &mut WorkVec, + ) -> (result: KernelResult<()>) + requires model::graph_wf(store.graph()), transition_child_count(store.graph(), id@, count as nat), + transition_ids_valid(store.graph(), old(flat).view()), + ensures store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> language::no_invariant_failure(result), + store.errors_are_non_invalid_policy() && store.valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + store.errors_are_resource() && store.valid_store() ==> (result matches Err(e) ==> resource_error(e)), + old(flat).view().is_prefix_of(final(flat).view()), transition_ids_valid(store.graph(), final(flat).view()), + match result { + Ok(()) => model::transition_ids(final(flat).view()) + == model::transition_ids(old(flat).view()) + transition_children(store.graph(), id@), + Err(_) => true, + }, + { + proof! { transition_lemma_children(store.graph(), id@); } + let mut failure = None; + let mut i = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant i <= count, + model::graph_wf(store.graph()), transition_child_count(store.graph(), id@, count as nat), + transition_children(store.graph(), id@).len() == count, + old(flat).view().is_prefix_of(flat.view()), transition_ids_valid(store.graph(), flat.view()), + flat.view().len() == old(flat).view().len() + i, + model::transition_ids(flat.view()) == model::transition_ids(old(flat).view()) + + transition_children(store.graph(), id@).take(i as int), + store.errors_are_non_owner() ==> failure != Some(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> (match failure { Some(error) => language::no_invariant_failure::<()>(Err(error)), None => true }), + store.errors_are_non_invalid_policy() && store.valid_store() ==> (match failure { Some(error) => !(error is InvalidPolicy), None => true }), + store.errors_are_resource() && store.valid_store() ==> (failure matches Some(e) ==> resource_error(e)), + ensures failure.is_none() ==> i == count, + decreases count - i, + ))] + while i < count { + let child = loop_try!(id.child(store, i), failure); + proof_decl! { let ghost prior = flat.view(); } + proof! { transition_lemma_child(store.graph(), id@, i as nat, child@); } + flat.push(child); + proof! { + transition_ids_push(prior, child); + assert(transition_children(store.graph(), id@).take(i as int).push(child@) + =~= transition_children(store.graph(), id@).take(i as int + 1)); + } + i = i.saturating_add(1); + } + if let Some(error) = failure { + return Err(error); + } + Ok(()) + } +} +} + +#[verus_verify] +impl TransitionNormalize for TransitionId { + #[verus_verify] + + fn constant(store: &mut G, regex: RegexId) -> KernelResult { + proof! { model::lemma_graph_wf_elim(store.graph()); } + store.checkpoint()?; + let c = store.constants(); + let result = if regex == c.empty { + Ok(c.transition_empty) + } else if regex == c.all { + Ok(c.transition_all) + } else if regex == c.epsilon { + Ok(c.transition_epsilon) + } else { + TransitionId::intern(store, TransitionView::Const(regex)) + }; + proof! { + if let Ok(id) = result { + lemma_guard_definition(store.graph(), id@); + transition_unfold(store.graph(), id@); + assert(guard_vocab(store.graph(), id@) == Set::empty()); + } + } + result + } + + #[verus_verify] + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + + fn if_then_else( + store: &mut G, + test: TestId, + then_id: TransitionId, + else_id: TransitionId, + ) -> KernelResult { + proof_decl! { let ghost entry = store.graph(); } + let id = TransitionId::local_if(store, test, then_id, else_id)?; + let path = store.constants().test_true; + proof! { + lemma_guard_constants(store.graph()); + assert(model::constants_wf(store.graph())) by { model::lemma_graph_wf_elim(store.graph()); } + machine_driver_extension_future(entry, store.graph()); + machine_driver_if_future(store.graph(), test, then_id, else_id, id); + if ftr::nf_sum(entry, then_id@) && ftr::nf_sum(entry, else_id@) { + fbr::lemma_ite_start(entry, store.graph(), test@, then_id@, else_id@, id@, path@); + } + } + proof_decl! { let ghost before_clean = store.graph(); } + let result = Action::Clean(id, path).run(store); + proof! { + lemma_guards_stable(before_clean, store.graph()); + lemma_guard_constants(store.graph()); + } + result + } + + #[verus_verify] + + fn intersect( + store: &mut G, + children: &[TransitionId], + ) -> KernelResult { + let mut xs = WorkVec::new(); + xs.extend_from_slice(children); + Action::Fold(xs, 0).run(store) + } + + #[verus_verify] + + fn not(this: TransitionId, store: &mut G) -> KernelResult { + Action::Not(this).run(store) + } + + #[verus_verify] + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + + fn append( + this: TransitionId, + store: &mut G, + suffix: &[RegexId], + ) -> KernelResult { + proof_decl! { let ghost entry = store.graph(); } + let r = RegexId::concat(store, suffix)?; + proof! { + machine_driver_extension_future(entry, store.graph()); + machine_driver_append_future(store.graph(), this, suffix@, r); + if ftr::nf_sum(entry, this@) && flink::ids_nf(entry, suffix@) { + fbr::lemma_app_future(entry, store.graph(), this@, suffix@, r@); + } + } + Action::Append(this, r).run(store) + } + + #[verus_verify] + + fn intern( + store: &mut G, + node: TransitionView<'_>, + ) -> KernelResult { + let id = store.intern_transition(node)?; + proof! { + transition_unfold(store.graph(), id@); tdepth_lemma_unfold(store.graph(), id@); + lemma_guard_node_unfold(store.graph(), id@); + } + Ok(id) + } + + #[verus_verify] + + fn local_if( + store: &mut G, + test: TestId, + a: TransitionId, + b: TransitionId, + ) -> KernelResult { + proof! { model::lemma_graph_wf_elim(store.graph()); tdepth_lemma_extends_forall(store.graph()); } + let c = store.constants(); + let result = if test == c.test_true || a == b { + Ok(a) + } else if test == c.test_false { + Ok(b) + } else { + TransitionId::intern( + store, + TransitionView::If { + test, + then_transition: a, + else_transition: b, + }, + ) + }; + proof! { + if let Ok(id) = result { lemma_guard_local_if(store.graph(), test@, a@, b@, id@); } + } + result + } + + verus! { + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + #[cfg_attr(verus_keep_ghost, verifier::rlimit(30))] + fn collect( + store: &mut G, + children: &[Self], + intersect: bool, + ) -> KernelResult { + hide(language::numeric_lang); + hide(language::interp_transition); + hide(model::test_holds); + hide(model::lift_transition); + hide(model::lift_regex); + hide(Seq::no_duplicates); + hide(model::unique_nodes); + hide(model::tables_wf); + proof_decl! { let ghost original = children@; let ghost entry = store.graph(); + let ghost cs = model::transition_ids(children@); let ghost nf = fcol::all_nf(entry, cs); } + proof_decl! { let ghost allowed = guard_task_vocab(entry, ActionShape::Fold(cs, 0)); } + proof! { + lemma_guard_constants(entry); + tdepth_lemma_constants(entry); + collect_lemma_bound(entry, original, intersect); + } + let c = store.constants(); + let identity = if intersect { + c.transition_all + } else { + c.transition_empty + }; + let absorber = if intersect { + c.transition_empty + } else { + c.transition_all + }; + let mode = TransitionMode { + intersect, + identity, + absorber, + }; + proof! { + assert(transition_mode_valid(store.graph(), mode@)); + transition_lemma_identities(store.graph(), mode@); + } + let mut flat = WorkVec::new(); + let mut constants = WorkVec::new(); + let mut pending = WorkVec::new(); + pending.extend_from_slice(children); + proof! { + assert(pending.view() == original); + assert(flat.view() == Seq::::empty()); + assert(constants.view() == Seq::::empty()); + } + if mode.collect(store, &mut pending, &mut flat, &mut constants)? { + proof! { + transition_lemma_initial_collection(store.graph(), mode@, original, + pending.view(), flat.view(), constants.view(), true); + model::lemma_graph_wf_elim(store.graph()); + if nf { fcol::lemma_const_out(store.graph(), cs, intersect, absorber@); } + } + return Ok(absorber); + } + proof! { assert forall|i: int| 0 <= i < flat.view().len() implies + transition_set_leaf(store.graph().transitions[flat.view()[i]@ as int], intersect) by {} } + proof! { + transition_lemma_initial_collection(store.graph(), mode@, original, + pending.view(), flat.view(), constants.view(), false); + collect_lemma_flat(store.graph(), original, pending.view(), flat.view(), constants.view(), intersect); + assert(model::bounded(cs, entry.transitions.len())); + lemma_guard_collected(store.graph(), cs, intersect, flat.view(), constants.view()); + if nf { + assert(pending.view() =~= Seq::::empty()); + fcol::lemma_members_elems(entry, cs, intersect, flat.view(), constants.view()); + } + } + if !constants.is_empty() { + proof_decl! { let ghost before_group = store.graph(); let ghost prior_flat = flat.view(); } + let r = RegexId::set(store, &constants, intersect)?; + proof_decl! { let ghost after_regex = store.graph(); } + proof! { + regex_combo_extends(before_group, after_regex, constants.view(), intersect); + regex_set_result(after_regex, seq![r], seq![r], intersect); + assert(regex_equivalent(after_regex, seq![r], constants.view(), intersect)); + } + let t = TransitionId::constant(store, r)?; + proof! { + transition_lemma_extends_transitive(before_group, after_regex, store.graph()); + lemma_guards_stable(before_group, store.graph()); + transition_collected_extends(before_group, store.graph(), original, prior_flat, constants.view(), intersect); + regex_equivalence_extends(after_regex, store.graph(), seq![r], constants.view(), intersect); + regex_combo_extends(after_regex, store.graph(), seq![r], intersect); + regex_set_result(store.graph(), seq![r], constants.view(), intersect); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies transition_lang(store.graph(), theta, t, event, word) + == regex_combo(store.graph(), theta, constants.view(), word, intersect) by {} + transition_lemma_group_result(store.graph(), original, prior_flat, constants.view(), mode@, t); + tdepth_lemma_constants(store.graph()); + collect_lemma_const_result(before_group, store.graph(), original, prior_flat, t, t != identity, intersect); + if nf { + fcol::lemma_elems_stable(entry, store.graph(), cs, intersect, prior_flat); + if t == absorber { fcol::lemma_const_out(store.graph(), cs, intersect, absorber@); } + if t != identity { + assert(intersect); + fcol::lemma_leaf_elem(entry, after_regex, store.graph(), cs, constants.view(), r@, t@); + } + } + } + if t == absorber { + return Ok(absorber); + } + if t != identity { + flat.push(t); + proof! { + broadcast use vstd::set::group_set_lemmas; + lemma_guard_task_stable(entry, store.graph(), ActionShape::Fold(cs, 0)); + assert(guard_vocab(store.graph(), t@).subset_of(allowed)); + assert forall|i: int| 0 <= i < flat.view().len() implies guard_vocab(store.graph(), flat.view()[i]@).subset_of(allowed) by { + if i < prior_flat.len() { assert(flat.view()[i] == prior_flat[i]); } + } + if nf { + assert forall|k: int| 0 <= k < flat.view().len() implies #[trigger] fcol::elem_flat(store.graph(), cs, intersect, flat.view()[k]@) by { + if k < prior_flat.len() { assert(flat.view()[k] == prior_flat[k]); } + } + } + } + } + proof! { + assert forall|i: int| 0 <= i < flat.view().len() implies + transition_set_leaf(store.graph().transitions[flat.view()[i]@ as int], intersect) by { + if i < prior_flat.len() { + assert(store.graph().transitions[flat.view()[i]@ as int] == before_group.transitions[prior_flat[i]@ as int]); + } + } + } + } + proof! { + if constants.view().len() == 0 { assert(transition_equivalent(store.graph(), original, flat.view(), intersect)); } + assert(transition_equivalent(store.graph(), original, flat.view(), intersect)); + assert(transition_ids_valid(store.graph(), original)); + assert(transition_ids_valid(store.graph(), flat.view())); + tdepth_lemma_extends_forall(entry); + assert(collect_weight(store.graph(), flat.view(), intersect) <= collect_weight(store.graph(), original, intersect)); + } + proof_decl! { let ghost unsorted = flat.view(); } + proof! { + lemma_guard_task_stable(entry, store.graph(), ActionShape::Fold(cs, 0)); + assert forall|i: int| #![trigger unsorted[i]] 0 <= i < unsorted.len() implies guard_vocab(store.graph(), unsorted[i]@).subset_of(allowed) by {} + } + proof! { junco_core::kernel::TransitionId::lemma_obeys_cmp(); } + flat.as_mut_slice().sort_unstable(); + proof! { + transition_multiset_members(unsorted, flat.view()); + transition_member_ids_valid(store.graph(), unsorted, flat.view()); + transition_combo_members(store.graph(), unsorted, flat.view(), intersect); + assert forall|i: int| 0 <= i < flat.view().len() implies guard_vocab(store.graph(), flat.view()[i]@).subset_of(allowed) by { + assert(unsorted.contains(flat.view()[i])); + let j = choose|j: int| 0 <= j < unsorted.len() && unsorted[j] == flat.view()[i]; + } + } + proof_decl! { let ghost sorted = flat.view(); } + dedup_ids(&mut flat)?; + proof! { + transition_member_ids_valid(store.graph(), sorted, flat.view()); + assert forall|i: int| 0 <= i < flat.view().len() implies guard_vocab(store.graph(), flat.view()[i]@).subset_of(allowed) by { + assert(sorted.contains(flat.view()[i])); + let j = choose|j: int| 0 <= j < sorted.len() && sorted[j] == flat.view()[i]; + } + transition_combo_members(store.graph(), sorted, flat.view(), intersect); + transition_dedup_strict(sorted, flat.view()); + assert(transition_equivalent(store.graph(), original, flat.view(), intersect)); + transition_lemma_set_result(store.graph(), flat.view(), original, intersect); + transition_equivalence_future(store.graph(), original, flat.view(), intersect); + transition_set_law(flat.view(), intersect); + transition_lemma_identities(store.graph(), mode@); + assert forall|id: TransitionId| flat.view().contains(id) implies unsorted.contains(id) by { + assert(sorted.contains(id)); + } + collect_lemma_subset(store.graph(), flat.view(), unsorted, intersect); + collect_lemma_final(entry, store.graph(), original, flat.view(), intersect); + tdepths_lemma_extends_forall(store.graph(), flat.view()); + assert forall|i: int| 0 <= i < flat.view().len() implies + transition_set_leaf(store.graph().transitions[flat.view()[i]@ as int], intersect) by { + assert(unsorted.contains(flat.view()[i])); + let j = choose|j: int| 0 <= j < unsorted.len() && unsorted[j] == flat.view()[i]; + } + if nf { + assert forall|k: int| 0 <= k < flat.view().len() implies #[trigger] fcol::elem_flat(store.graph(), cs, intersect, flat.view()[k]@) by { + assert(unsorted.contains(flat.view()[k])); + let j = choose|j: int| 0 <= j < unsorted.len() && unsorted[j] == flat.view()[k]; + assert(fcol::elem_flat(store.graph(), cs, intersect, unsorted[j]@)); + } + fcol::lemma_const_out(store.graph(), cs, intersect, identity@); + if flat.view().len() == 1 { + assert(fcol::elem_flat(store.graph(), cs, intersect, flat.view()[0]@)); + fcol::lemma_elem_out(store.graph(), cs, intersect, flat.view()[0]@); + } + assert forall|k: int| 0 <= k < model::transition_ids(flat.view()).len() implies + #[trigger] fcol::elem_flat(store.graph(), cs, intersect, model::transition_ids(flat.view())[k]) by { + assert(model::transition_ids(flat.view())[k] == flat.view()[k]@); + } + fcol::lemma_node_future(store.graph(), cs, intersect, model::transition_ids(flat.view())); + } + } + proof! { model::lemma_graph_wf_elim(store.graph()); } + if flat.is_empty() { + Ok(identity) + } else if flat.len() == 1 { + match flat.first() { + Some(id) => Ok(*id), + None => Err(HistoryError::normalization_invariant()), + } + } else { + proof_decl! { let ghost before_intern = store.graph(); } + let result = TransitionId::intern( + store, + if intersect { + TransitionView::Intersect(&flat) + } else { + TransitionView::Union(&flat) + }, + ); + proof! { + if let Ok(id) = result { + transition_lemma_extends_transitive(entry, before_intern, store.graph()); + lemma_guards_stable(before_intern, store.graph()); + lemma_guard_task_stable(entry, store.graph(), ActionShape::Fold(cs, 0)); + assert forall|i: int| #![trigger crate::progress::verify::transition_edges(store.graph(), id@)[i]] + 0 <= i < crate::progress::verify::transition_edges(store.graph(), id@).len() implies + guard_vocab(store.graph(), crate::progress::verify::transition_edges(store.graph(), id@)[i]).subset_of(allowed) by { + assert(flat.view()[i]@ < before_intern.transitions.len()); + assert(guard_vocab(before_intern, flat.view()[i]@).subset_of(allowed)); + assert(guard_vocab(store.graph(), flat.view()[i]@).subset_of(allowed)); + assert(crate::progress::verify::transition_edges(store.graph(), id@)[i] == flat.view()[i]@); + } + lemma_guard_node(store.graph(), id@, allowed); + } + } + result + } + } + } +} +#[verus_verify] +enum Action { + Clean(TransitionId, TestId), + Not(TransitionId), + Append(TransitionId, RegexId), + Pair(TransitionId, TransitionId), + Union(usize), + Intersect(usize), + If(TestId), + CleanIf(TestId, TestId), + Fold(WorkVec, usize), + NotResult, + AppendResult(RegexId), + SwapThen, +} +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy)] +enum ChildAction { + Clean(TestId), + Not, + Append(RegexId), + PairLeft(TransitionId), + PairRight(TransitionId), +} +#[verus_verify] +impl ChildAction { + #[allow( + clippy::option_if_let_else, + reason = "Explicit matches preserve the Verus proof structure." + )] + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(store.graph()), transition_child_count(store.graph(), id@, count as nat), + transition_child_action_valid(store.graph(), self@), + transition_tasks_valid(store.graph(), transition_action_views(old(tasks).view())), + ensures store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> language::no_invariant_failure(result), + store.errors_are_non_invalid_policy() && store.valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + store.errors_are_resource() && store.valid_store() ==> (result matches Err(e) ==> resource_error(e)), + transition_tasks_valid(store.graph(), transition_action_views(final(tasks).view())), + transition_action_views(old(tasks).view()).is_prefix_of(transition_action_views(final(tasks).view())), + match result { + Ok(()) => transition_action_views(final(tasks).view()) + == transition_action_views(old(tasks).view()) + transition_child_actions(store.graph(), id@, self@), + Err(_) => true, + }, + )] + fn schedule( + self, + store: &G, + id: TransitionId, + count: usize, + tasks: &mut WorkVec, + ) -> KernelResult<()> { + proof_decl! { let ghost base = transition_action_views(tasks.view()); } + proof! { + transition_lemma_children(store.graph(), id@); + transition_lemma_child_actions_valid(store.graph(), id@, self@); + } + let mut failure = None; + // Reverse pushes preserve source order when the LIFO work stack executes. + let mut remaining = count; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant remaining <= count, model::graph_wf(store.graph()), + transition_child_count(store.graph(), id@, count as nat), + transition_child_action_valid(store.graph(), self@), + transition_child_actions(store.graph(), id@, self@).len() == count, + transition_tasks_valid(store.graph(), transition_action_views(tasks.view())), + base.is_prefix_of(transition_action_views(tasks.view())), + failure.is_none() ==> transition_action_views(tasks.view()) + == base + transition_child_actions(store.graph(), id@, self@).take(count as int - remaining as int), + store.errors_are_non_owner() ==> failure != Some(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> (match failure { Some(error) => language::no_invariant_failure::<()>(Err(error)), None => true }), + store.errors_are_non_invalid_policy() && store.valid_store() ==> (match failure { Some(error) => !(error is InvalidPolicy), None => true }), + store.errors_are_resource() && store.valid_store() ==> (failure matches Some(e) ==> resource_error(e)), + ensures failure.is_none() ==> remaining == 0, + decreases remaining, + ))] + while remaining != 0 { + proof_decl! { let ghost prior = tasks.view(); } + let i = loop_try!( + match remaining.checked_sub(1) { + Some(value) => Ok(value), + None => Err(HistoryError::normalization_invariant()), + }, + failure + ); + remaining = i; + let child = loop_try!(id.child(store, i), failure); + proof! { transition_lemma_child(store.graph(), id@, i as nat, child@); } + tasks.push(match self { + ChildAction::Clean(path) => Action::Clean(child, path), + ChildAction::Not => Action::Not(child), + ChildAction::Append(r) => Action::Append(child, r), + ChildAction::PairLeft(other) => Action::Pair(child, other), + ChildAction::PairRight(other) => Action::Pair(other, child), + }); + proof! { + let shape = transition_child_shape(self@, child@); + transition_lemma_child_action_valid(store.graph(), self@, child@); + assert(tasks.view().last()@ == shape); + assert(tasks.view() == prior.push(tasks.view().last())); + transition_action_views_push(prior, tasks.view().last()); + let index = count as int - remaining as int - 1; + assert(0 <= index < count); + assert(transition_child_actions(store.graph(), id@, self@)[index] == shape); + assert(transition_child_actions(store.graph(), id@, self@).take(index).push(shape) + =~= transition_child_actions(store.graph(), id@, self@).take(index + 1)); + } + } + if let Some(error) = failure { + return Err(error); + } + Ok(()) + } +} + +#[verus_verify] +impl Action { + #[verus_verify] + #[verus_spec(result => ensures result != Err(HistoryError::WrongHistoryOwner), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + count <= old(values).view().len() ==> (result matches Err(e) ==> resource_error(e)), + count <= old(values).view().len() ==> language::no_invariant_failure(result), match result { + Ok(taken) => count <= old(values).view().len() + && taken.view() == old(values).view().subrange(old(values).view().len() as int - count, old(values).view().len() as int) + && final(values).view() == old(values).view().take(old(values).view().len() as int - count), + Err(_) => final(values).view() == old(values).view(), + })] + fn take_values( + values: &mut WorkVec, + count: usize, + ) -> KernelResult> { + let start = match values.len().checked_sub(count) { + Some(v) => v, + None => return Err(HistoryError::normalization_invariant()), + }; + let mut result = WorkVec::new(); + match values.get(start..) { + Some(xs) => result.extend_from_slice(xs), + None => return Err(HistoryError::normalization_invariant()), + } + values.truncate(start); + Ok(result) + } + + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(store.graph()), transition_suffix_count(store.graph(), id@, count as nat), + ensures store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> language::no_invariant_failure(result), + store.errors_are_non_invalid_policy() && store.valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + store.errors_are_resource() && store.valid_store() ==> (result matches Err(e) ==> resource_error(e)), + match result { + Ok(values) => regex_ids_valid(store.graph(), values.view()) + && model::regex_ids(values.view()) == transition_suffix(store.graph(), id@), + Err(_) => true, + }, + )] + fn suffix_values( + store: &G, + id: TransitionId, + count: usize, + ) -> KernelResult> { + proof! { transition_lemma_suffix(store.graph(), id@); } + let mut values = WorkVec::new(); + let mut failure = None; + let mut i = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant i <= count, regex_ids_valid(store.graph(), values.view()), values.view().len() == i, + model::graph_wf(store.graph()), transition_suffix_count(store.graph(), id@, count as nat), + transition_suffix(store.graph(), id@).len() == count, + model::regex_ids(values.view()) == transition_suffix(store.graph(), id@).take(i as int), + store.errors_are_non_owner() ==> failure != Some(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> (match failure { Some(error) => language::no_invariant_failure::<()>(Err(error)), None => true }), + store.errors_are_non_invalid_policy() && store.valid_store() ==> (match failure { Some(error) => !(error is InvalidPolicy), None => true }), + store.errors_are_resource() && store.valid_store() ==> (failure matches Some(e) ==> resource_error(e)), + ensures failure.is_none() ==> i == count, + decreases count - i, + ))] + while i < count { + let child = loop_try!(id.suffix_child(store, i), failure); + proof_decl! { let ghost prior = values.view(); } + proof! { transition_lemma_suffix_child(store.graph(), id@, i as nat, child@); } + values.push(child); + proof! { + regex_ids_push(prior, child); + assert(transition_suffix(store.graph(), id@).take(i as int).push(child@) + =~= transition_suffix(store.graph(), id@).take(i as int + 1)); + } + i = i.saturating_add(1); + } + if let Some(error) = failure { + return Err(error); + } + Ok(values) + } + + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(store.graph()), transition_child_count(store.graph(), id@, count as nat), path@ < store.graph().tests.len(), + transition_tasks_valid(store.graph(), transition_action_views(old(tasks).view())), + match store.graph().transitions[id@ as int] { + model::TransitionNode::Union(ids) => !intersect, + model::TransitionNode::Intersect(ids) => intersect, + _ => false, + }, + ensures store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> language::no_invariant_failure(result), + store.errors_are_non_invalid_policy() && store.valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + store.errors_are_resource() && store.valid_store() ==> (result matches Err(e) ==> resource_error(e)), + transition_tasks_valid(store.graph(), transition_action_views(final(tasks).view())), + transition_action_views(old(tasks).view()).is_prefix_of(transition_action_views(final(tasks).view())), + match result { + Ok(()) => transition_action_views(final(tasks).view()) + == transition_clean_child_tasks(store.graph(), id, path, intersect, transition_action_views(old(tasks).view())) + && forall|prior: Seq| transition_effect(store.graph(), ActionShape::Clean(id@, path@), + transition_action_views(old(tasks).view()), prior, transition_action_views(final(tasks).view()), prior), + Err(_) => true, + }, + result is Ok ==> forall|prior: Seq| guard_effect(store.graph(), + transition_action_views(old(tasks).view()), ActionShape::Clean(id@, path@), prior, + transition_action_views(final(tasks).view()), prior), + )] + fn clean_children( + store: &G, + id: TransitionId, + count: usize, + intersect: bool, + path: TestId, + tasks: &mut WorkVec, + ) -> KernelResult<()> { + proof_decl! { let ghost initial = tasks.view(); let ghost base = transition_action_views(initial); } + proof! { + transition_lemma_children(store.graph(), id@); + transition_lemma_clean_children_effect(store.graph(), id, path, intersect, base); + } + tasks.push(if intersect { + Action::Intersect(count) + } else { + Action::Union(count) + }); + proof! { + assert(tasks.view() == initial.push(tasks.view().last())); + transition_action_views_push(initial, tasks.view().last()); + assert(tasks.view().last()@ == if intersect { ActionShape::Intersect(count as nat) } else { ActionShape::Union(count as nat) }); + } + ChildAction::Clean(path).schedule(store, id, count, tasks)?; + proof! { lemma_guard_child_actions(store.graph(), id@, ChildShape::Clean(path@)); } + proof! { + assert(transition_action_views(tasks.view()) == transition_clean_child_tasks(store.graph(), id, path, intersect, base)); + assert forall|prior: Seq| transition_effect(store.graph(), ActionShape::Clean(id@, path@), + base, prior, transition_action_views(tasks.view()), prior) by { + assert(transition_effect(store.graph(), ActionShape::Clean(id@, path@), base, prior, + transition_clean_child_tasks(store.graph(), id, path, intersect, base), prior)); + } + assert forall|prior: Seq| guard_effect(store.graph(), base, + ActionShape::Clean(id@, path@), prior, transition_action_views(tasks.view()), prior) by { + assert forall|allowed: Set| guard_config(store.graph(), base, prior, allowed) + && guard_task_vocab(store.graph(), ActionShape::Clean(id@, path@)).subset_of(allowed) + implies guard_config(store.graph(), transition_action_views(tasks.view()), prior, allowed) by { + let added = transition_child_actions(store.graph(), id@, ChildShape::Clean(path@)); + assert forall|i: int| 0 <= i < transition_action_views(tasks.view()).len() implies + guard_task_vocab(store.graph(), transition_action_views(tasks.view())[i]).subset_of(allowed) by { + if i < base.len() { assert(transition_action_views(tasks.view())[i] == base[i]); } + else if i > base.len() { assert(transition_action_views(tasks.view())[i] == added[i - base.len() as int - 1]); } + } + } + } + } + Ok(()) + } + + #[verus_verify] + // The default rlimit was exceeded in the no-std configuration once `KeyHash`/`KeyedMap` specs were verified. + #[cfg_attr(verus_keep_ghost, verifier::rlimit(30))] + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + transition_configuration_valid(old(store).graph(), transition_action_views(old(tasks).view()), old(values).view()), + a@ < old(store).graph().transitions.len(), + b@ < old(store).graph().transitions.len(), + left@ == model::transition_node_head(old(store).graph().transitions[a@ as int]), + right@ == model::transition_node_head(old(store).graph().transitions[b@ as int]), + match left { TransitionHead::If(_, _, _) => true, _ => false }, + match right { TransitionHead::If(_, _, _) => true, _ => false }, + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + model::graph_wf(final(store).graph()), final(store).valid_store(), + transition_configuration_valid(final(store).graph(), transition_action_views(final(tasks).view()), final(values).view()), + transition_action_views(old(tasks).view()).is_prefix_of(transition_action_views(final(tasks).view())), + result is Ok ==> guard_effect(final(store).graph(), transition_action_views(old(tasks).view()), + ActionShape::Pair(a@, b@), old(values).view(), transition_action_views(final(tasks).view()), final(values).view()), + match result { + Ok(()) => transition_effect(final(store).graph(), ActionShape::Pair(a@, b@), + transition_action_views(old(tasks).view()), old(values).view(), + transition_action_views(final(tasks).view()), final(values).view()) + && (fsteps::xpre(old(store).graph(), ActionShape::Pair(a@, b@), transition_action_views(old(tasks).view()), old(values).view()) + ==> fsteps::xeffect(final(store).graph(), ActionShape::Pair(a@, b@), transition_action_views(old(tasks).view()), + old(values).view(), transition_action_views(final(tasks).view()), final(values).view())) + && machine_progress(old(store).graph(), transition_action_views(old(tasks).view()), + ActionShape::Pair(a@, b@), old(values).view(), + final(store).graph(), transition_action_views(final(tasks).view()), final(values).view()), + Err(_) => true, + }, + )] + fn pair_conditionals( + store: &mut G, + a: TransitionId, + b: TransitionId, + left: TransitionHead, + right: TransitionHead, + tasks: &mut WorkVec, + values: &mut WorkVec, + ) -> KernelResult<()> { + proof_decl! { let ghost p0 = transition_action_views(tasks.view()); let ghost v0 = values.view(); + let ghost entry = store.graph(); } + proof! { + assert(model::constants_wf(store.graph())) by { model::lemma_graph_wf_elim(store.graph()); } + transition_configuration_future(store.graph(), p0, v0); + model::lemma_graph_transition_wf(store.graph(), a@); + model::lemma_graph_transition_wf(store.graph(), b@); + lemma_guard_children(store.graph(), a@); + lemma_guard_children(store.graph(), b@); + graph_lemma_extends_refl(entry); + lemma_guard_constants(store.graph()); + tdepth_lemma_constants(entry); + } + let c = store.constants(); + if let (TransitionHead::If(x, xt, xe), TransitionHead::If(y, yt, ye)) = (left, right) { + proof! { + assert(store.graph().transitions[a@ as int] == model::TransitionNode::If(x@, xt@, xe@)); + assert(store.graph().transitions[b@ as int] == model::TransitionNode::If(y@, yt@, ye@)); + machine_pair_if_language(store.graph(), a, x, xt, xe); + machine_pair_if_language(store.graph(), b, y, yt, ye); + } + if xe == c.transition_empty && ye == c.transition_empty { + proof_decl! { let ghost before_guard = store.graph(); } + let guard = TestId::connective(store, &[x, y], true)?; + proof! { + broadcast use vstd::set::group_set_lemmas; + lemma_test_connective_pair(before_guard, store.graph(), x, y, true, guard@); + lemma_guards_stable(before_guard, store.graph()); + assert(test_vocab(store.graph(), guard@).subset_of(test_vocab(store.graph(), x@).union(test_vocab(store.graph(), y@)))); + assert forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + implies model::test_holds(theta, model::lift_test(store.graph(), guard@), event) + == test_combo(store.graph(), theta, seq![x, y], event, true) by { + assert(test_truth(store.graph(), theta, guard@, event) + == test_combo(store.graph(), theta, seq![x, y], event, true)); + } + machine_pair_empty_branches(store.graph(), a, b, x, xt, y, yt, c.transition_empty, guard); + tdepth_lemma_extends(entry, store.graph(), c.transition_empty@); + tdepth_lemma_pos(entry, a@); + tdepth_lemma_pos(entry, b@); + lemma_pair_bound_ge(tdepth(entry, a@), tdepth(entry, b@)); + } + if guard == c.test_false { + values.push(c.transition_empty); + proof! { + transition_lemma_push_result(store.graph(), ActionShape::Pair(a@, b@), p0, v0, c.transition_empty); + machine_value_result(entry, store.graph(), p0, ActionShape::Pair(a@, b@), v0, c.transition_empty); + if fsteps::xpre(entry, ActionShape::Pair(a@, b@), p0, v0) { + fbr::lemma_pair_keep(entry, store.graph(), p0, v0, a, b, c.transition_empty); + } + } + } else { + tasks.push(Action::CleanIf(guard, c.test_true)); + values.push(c.transition_empty); + tasks.push(Action::SwapThen); + tasks.push(Action::Pair(xt, yt)); + proof! { + machine_pair_empty_effect(store.graph(), a, b, xt, yt, guard, c.transition_empty, p0, v0); + assert(transition_action_views(tasks.view()) =~= p0.push(ActionShape::CleanIf(guard@, c.test_true@)) + .push(ActionShape::SwapThen).push(ActionShape::Pair(xt@, yt@))); + machine_pair_empty(entry, store.graph(), p0, a, b, x, xt, xe, y, yt, ye, guard, c.test_true, + c.transition_empty, v0); + if fsteps::xpre(entry, ActionShape::Pair(a@, b@), p0, v0) { + assert(values.view() == v0.push(c.transition_empty)); + fbr::lemma_pair_empty_branches(entry, store.graph(), p0, v0, a, b, x, xt, y, yt, guard, c.transition_empty); + } + } + } + } else if x == y { + tasks.push(Action::CleanIf(x, c.test_true)); + tasks.push(Action::Pair(xe, ye)); + tasks.push(Action::Pair(xt, yt)); + proof! { + machine_pair_if_effect(store.graph(), a, b, x, xt, yt, xe, ye, p0, v0); + assert(transition_action_views(tasks.view()) =~= p0.push(ActionShape::CleanIf(x@, c.test_true@)) + .push(ActionShape::Pair(xe@, ye@)).push(ActionShape::Pair(xt@, yt@))); + machine_pair_both(entry, store.graph(), p0, a, b, x, xt, xe, y, yt, ye, c.test_true, v0); + if fsteps::xpre(entry, ActionShape::Pair(a@, b@), p0, v0) { + fbr::lemma_pair_both(entry, store.graph(), p0, v0, a, b, x, xt, xe, y, yt, ye); + } + } + } else if xe == c.transition_empty || (ye != c.transition_empty && x < y) { + tasks.push(Action::CleanIf(x, c.test_true)); + tasks.push(Action::Pair(xe, b)); + tasks.push(Action::Pair(xt, b)); + proof! { + machine_pair_if_effect(store.graph(), a, b, x, xt, b, xe, b, p0, v0); + assert(transition_action_views(tasks.view()) =~= p0.push(ActionShape::CleanIf(x@, c.test_true@)) + .push(ActionShape::Pair(xe@, b@)).push(ActionShape::Pair(xt@, b@))); + machine_pair_split(entry, store.graph(), p0, a, b, x, xt, xe, c.test_true, true, v0); + if fsteps::xpre(entry, ActionShape::Pair(a@, b@), p0, v0) { + fbr::lemma_pair_split(entry, store.graph(), p0, v0, a, b, x, xt, xe, true); + } + } + } else { + tasks.push(Action::CleanIf(y, c.test_true)); + tasks.push(Action::Pair(a, ye)); + tasks.push(Action::Pair(a, yt)); + proof! { + machine_pair_if_effect(store.graph(), a, b, y, a, yt, a, ye, p0, v0); + assert(transition_action_views(tasks.view()) =~= p0.push(ActionShape::CleanIf(y@, c.test_true@)) + .push(ActionShape::Pair(a@, ye@)).push(ActionShape::Pair(a@, yt@))); + machine_pair_split(entry, store.graph(), p0, a, b, y, yt, ye, c.test_true, false, v0); + if fsteps::xpre(entry, ActionShape::Pair(a@, b@), p0, v0) { + fbr::lemma_pair_split(entry, store.graph(), p0, v0, a, b, y, yt, ye, false); + } + } + } + proof! { + lemma_guards_stable(entry, store.graph()); + assert forall|allowed: Set| guard_config(store.graph(), p0, v0, allowed) + && guard_task_vocab(store.graph(), ActionShape::Pair(a@, b@)).subset_of(allowed) + implies guard_config(store.graph(), transition_action_views(tasks.view()), values.view(), allowed) by { + broadcast use vstd::set::group_set_lemmas; + assert forall|i: int| 0 <= i < tasks.view().len() implies + guard_task_vocab(store.graph(), transition_action_views(tasks.view())[i]).subset_of(allowed) by { + if i < p0.len() { + assert(transition_action_views(tasks.view())[i] == p0[i]); + } + } + assert forall|i: int| 0 <= i < values.view().len() implies + guard_vocab(store.graph(), values.view()[i]@).subset_of(allowed) by { + if v0.contains(values.view()[i]) { + let j = choose|j: int| 0 <= j < v0.len() && v0[j] == values.view()[i]; + assert(guard_vocab(store.graph(), v0[j]@).subset_of(allowed)); + } + } + } + } + Ok(()) + } else { + Err(HistoryError::normalization_invariant()) + } + } + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + transition_configuration_valid(old(store).graph(), transition_action_views(old(tasks).view()), old(values).view()), + transition_ids_valid(old(store).graph(), xs.view()), + 0 < index < xs.view().len() ==> old(values).view().len() > 0, + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + model::graph_wf(final(store).graph()), final(store).valid_store(), + transition_configuration_valid(final(store).graph(), transition_action_views(final(tasks).view()), final(values).view()), + transition_action_views(old(tasks).view()).is_prefix_of(transition_action_views(final(tasks).view())), + result is Ok ==> guard_effect(final(store).graph(), transition_action_views(old(tasks).view()), + ActionShape::Fold(model::transition_ids(xs.view()), index as nat), old(values).view(), + transition_action_views(final(tasks).view()), final(values).view()), + match result { + Ok(()) => transition_effect(final(store).graph(), ActionShape::Fold(model::transition_ids(xs.view()), index as nat), + transition_action_views(old(tasks).view()), old(values).view(), + transition_action_views(final(tasks).view()), final(values).view()) + && (fsteps::xpre(old(store).graph(), ActionShape::Fold(model::transition_ids(xs.view()), index as nat), + transition_action_views(old(tasks).view()), old(values).view()) + ==> fsteps::xeffect(final(store).graph(), ActionShape::Fold(model::transition_ids(xs.view()), index as nat), + transition_action_views(old(tasks).view()), old(values).view(), + transition_action_views(final(tasks).view()), final(values).view())) + && machine_progress(old(store).graph(), transition_action_views(old(tasks).view()), + ActionShape::Fold(model::transition_ids(xs.view()), index as nat), old(values).view(), + final(store).graph(), transition_action_views(final(tasks).view()), final(values).view()), + Err(_) => true, + }, + )] + fn fold_step( + store: &mut G, + xs: WorkVec, + index: usize, + tasks: &mut WorkVec, + values: &mut WorkVec, + ) -> KernelResult<()> { + proof_decl! { let ghost p0 = transition_action_views(tasks.view()); let ghost v0 = values.view(); let ghost original = xs.view(); } + proof_decl! { let ghost entry = store.graph(); } + proof! { + transition_configuration_future(store.graph(), p0, v0); + graph_lemma_extends_refl(entry); + lemma_guard_union(store.graph(), model::transition_ids(original), guard_task_vocab(store.graph(), ActionShape::Fold(model::transition_ids(original), index as nat))); + assert(value_depths(entry, original) =~= tdepths(entry, model::transition_ids(original))); + } + { + if index == 0 { + let flat = TransitionId::collect(store, &xs, true)?; + proof! { model::lemma_graph_transition_wf(store.graph(), flat@); } + match flat.head(store)? { + TransitionHead::Intersect(n) => { + let mut children = WorkVec::new(); + TransitionId::collect_children(store, flat, n, &mut children)?; + proof! { transition_lemma_children(store.graph(), flat@); } + let first = match children.first() { + Some(v) => *v, + None => return Err(HistoryError::normalization_invariant()), + }; + proof_decl! { let ghost cs = children.view(); } + proof! { + assert(model::transition_ids(cs) == transition_children(store.graph(), flat@)); + lemma_guard_children(store.graph(), flat@); + lemma_guard_union(store.graph(), model::transition_ids(cs), guard_vocab(store.graph(), flat@)); + transition_lemma_children(store.graph(), flat@); + assert(store.graph().transitions[flat@ as int] == model::TransitionNode::Intersect(model::transition_ids(cs))); + machine_pair_fold_collection_effect(store.graph(), original, flat, cs, p0, v0); + machine_fold_start(entry, store.graph(), p0, model::transition_ids(original), flat, cs, v0); + } + values.push(first); + tasks.push(Action::Fold(children, 1)); + proof! { + broadcast use vstd::set::group_set_lemmas; + assert forall|i: int| 0 <= i < cs.len() implies guard_vocab(store.graph(), cs[i]@).subset_of(guard_vocab(store.graph(), flat@)) by { + assert(model::transition_ids(cs)[i] == cs[i]@); + assert(crate::progress::verify::transition_edges(store.graph(), flat@)[i] == cs[i]@); + } + assert(first == cs[0]); + assert(guard_vocab(store.graph(), first@).subset_of(guard_task_vocab(store.graph(), ActionShape::Fold(model::transition_ids(original), 0)))); + assert(guard_task_vocab(store.graph(), ActionShape::Fold(model::transition_ids(cs), 1)).subset_of(guard_task_vocab(store.graph(), ActionShape::Fold(model::transition_ids(original), 0)))); + assert(transition_action_views(tasks.view()) =~= p0.push(ActionShape::Fold(model::transition_ids(cs), 1))); + if fsteps::xpre(entry, ActionShape::Fold(model::transition_ids(original), 0), p0, v0) { + assert(first == cs[0]); + fbr::lemma_fold_start(entry, store.graph(), p0, v0, model::transition_ids(original), flat, cs); + } + } + } + _ => { + values.push(flat); + proof! { + assert(guard_vocab(store.graph(), flat@).subset_of(guard_task_vocab(store.graph(), ActionShape::Fold(model::transition_ids(original), 0)))); + machine_pair_set_result(store.graph(), original, ActionShape::Fold(model::transition_ids(original), 0), flat); + transition_lemma_push_result(store.graph(), ActionShape::Fold(model::transition_ids(original), 0), p0, v0, flat); + machine_fold_flat(entry, store.graph(), p0, model::transition_ids(original), v0, flat); + if fsteps::xpre(entry, ActionShape::Fold(model::transition_ids(original), 0), p0, v0) { + fbr::lemma_fold_flat(entry, store.graph(), p0, v0, model::transition_ids(original), flat); + } + } + } + } + } else if let Some(next) = xs.get(index) { + proof! { assert(index < xs.view().len()); assert(index < usize::MAX); } + let a = match values.pop() { + Some(v) => v, + None => return Err(HistoryError::normalization_invariant()), + }; + let b = *next; + let next_index = match index.checked_add(1) { + Some(v) => v, + None => return Err(HistoryError::normalization_invariant()), + }; + tasks.push(Action::Fold(xs, next_index)); + tasks.push(Action::Pair(a, b)); + proof! { + assert(a == v0[v0.len() - 1]); + assert(guard_vocab(store.graph(), b@).subset_of(guard_task_vocab(store.graph(), ActionShape::Fold(model::transition_ids(original), index as nat)))); + assert forall|allowed: Set| #![trigger guard_config(store.graph(), p0, v0, allowed)] + guard_config(store.graph(), p0, v0, allowed) implies guard_vocab(store.graph(), a@).subset_of(allowed) by { + assert(guard_vocab(store.graph(), v0[v0.len() - 1]@).subset_of(allowed)); + } + machine_pair_fold_next_effect(store.graph(), original, index as nat, p0, v0); + assert(transition_action_views(tasks.view()) =~= p0.push(ActionShape::Fold(model::transition_ids(original), next_index as nat)) + .push(ActionShape::Pair(a@, b@))); + assert(model::transition_ids(original)[index as int] == b@); + assert(values.view() == v0.drop_last()); + machine_fold_next(store.graph(), p0, model::transition_ids(original), index as nat, v0); + if fsteps::xpre(entry, ActionShape::Fold(model::transition_ids(original), index as nat), p0, v0) { + fbr::lemma_fold_next(entry, store.graph(), p0, v0, model::transition_ids(original), index as nat, a, b); + } + } + } + proof! { + if index != 0 && index >= original.len() { + machine_pair_fold_noop(store.graph(), original, index as nat, p0, v0); + machine_fold_noop(store.graph(), p0, model::transition_ids(original), index as nat, v0); + if fsteps::xpre(entry, ActionShape::Fold(model::transition_ids(original), index as nat), p0, v0) { + fbr::lemma_fold_noop(entry, store.graph(), p0, v0, model::transition_ids(original), index as nat); + } + } + } + } + proof! { + lemma_guards_stable(entry, store.graph()); + lemma_guard_task_stable(entry, store.graph(), ActionShape::Fold(model::transition_ids(original), index as nat)); + assert forall|allowed: Set| guard_config(store.graph(), p0, v0, allowed) + && guard_task_vocab(store.graph(), ActionShape::Fold(model::transition_ids(original), index as nat)).subset_of(allowed) + implies guard_config(store.graph(), transition_action_views(tasks.view()), values.view(), allowed) by { + broadcast use vstd::set::group_set_lemmas; + assert forall|i: int| 0 <= i < tasks.view().len() implies + guard_task_vocab(store.graph(), transition_action_views(tasks.view())[i]).subset_of(allowed) by { + if i < p0.len() { + assert(transition_action_views(tasks.view())[i] == p0[i]); + } + } + assert forall|i: int| 0 <= i < values.view().len() implies + guard_vocab(store.graph(), values.view()[i]@).subset_of(allowed) by { + if v0.contains(values.view()[i]) { + let j = choose|j: int| 0 <= j < v0.len() && v0[j] == values.view()[i]; + assert(guard_vocab(store.graph(), v0[j]@).subset_of(allowed)); + } + } + } + } + Ok(()) + } + + #[verus_verify] + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + #[cfg_attr(verus_keep_ghost, verifier::rlimit(30))] + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + transition_configuration_valid(old(store).graph(), transition_action_views(old(tasks).view()), old(values).view()), + id@ < old(store).graph().transitions.len(), + path@ < old(store).graph().tests.len(), + c@ == old(store).graph().constants, + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + model::graph_wf(final(store).graph()), final(store).valid_store(), + transition_configuration_valid(final(store).graph(), transition_action_views(final(tasks).view()), final(values).view()), + transition_action_views(old(tasks).view()).is_prefix_of(transition_action_views(final(tasks).view())), + result is Ok ==> guard_effect(final(store).graph(), transition_action_views(old(tasks).view()), + ActionShape::Clean(id@, path@), old(values).view(), transition_action_views(final(tasks).view()), final(values).view()), + match result { + Ok(()) => transition_effect(final(store).graph(), ActionShape::Clean(id@, path@), + transition_action_views(old(tasks).view()), old(values).view(), + transition_action_views(final(tasks).view()), final(values).view()) + && (fsteps::xpre(old(store).graph(), ActionShape::Clean(id@, path@), transition_action_views(old(tasks).view()), old(values).view()) + ==> fsteps::xeffect(final(store).graph(), ActionShape::Clean(id@, path@), transition_action_views(old(tasks).view()), + old(values).view(), transition_action_views(final(tasks).view()), final(values).view())) + && machine_progress(old(store).graph(), transition_action_views(old(tasks).view()), + ActionShape::Clean(id@, path@), old(values).view(), + final(store).graph(), transition_action_views(final(tasks).view()), final(values).view()), + Err(_) => true, + }, + )] + fn clean_step( + store: &mut G, + id: TransitionId, + path: TestId, + c: &Constants, + tasks: &mut WorkVec, + values: &mut WorkVec, + ) -> KernelResult<()> { + proof_decl! { let ghost p0 = transition_action_views(tasks.view()); let ghost v0 = values.view(); } + proof_decl! { let ghost entry = store.graph(); } + // Expose only constants; full table facts unfold irrelevant recursive semantics. + proof! { assert(model::constants_wf(store.graph())) by { model::lemma_graph_wf_elim(store.graph()); } model::lemma_graph_transition_wf(store.graph(), id@); } + proof! { transition_configuration_future(store.graph(), p0, v0); graph_lemma_extends_refl(entry); } + proof! { lemma_guard_children(store.graph(), id@); } + match id.head(store)? { + TransitionHead::Const(_) => { + values.push(id); + proof! { + transition_lemma_clean_identity(store.graph(), id, path); + transition_lemma_push_result(store.graph(), ActionShape::Clean(id@, path@), p0, v0, id); + machine_value_result(entry, store.graph(), p0, ActionShape::Clean(id@, path@), v0, id); + if fsteps::xpre(entry, ActionShape::Clean(id@, path@), p0, v0) { fbr::lemma_clean_self(entry, store.graph(), p0, v0, id, path); } + } + } + TransitionHead::If(test, a, b) => { + let yes = TestId::connective(store, &[path, test], true)?; + proof_decl! { let ghost after_yes = store.graph(); } + proof! { + lemma_test_connective_pair(entry, after_yes, path, test, true, yes@); + assert(test_vocab(after_yes, yes@).subset_of(test_vocab(entry, path@).union(test_vocab(entry, test@)))); + } + let neg = TestId::not(test, store)?; + proof_decl! { let ghost after_negated = store.graph(); } + proof! { + lemma_test_definition(after_negated, test@); lemma_test_definition(after_negated, neg@); + assert(test_vocab(after_negated, test@) == test_vocab(after_negated, neg@)); + } + let no = TestId::connective(store, &[path, neg], true)?; + proof! { + broadcast use vstd::set::group_set_lemmas; + lemma_test_connective_pair(after_negated, store.graph(), path, neg, true, no@); + transition_lemma_extends_transitive(after_yes, after_negated, store.graph()); + transition_lemma_extends_transitive(entry, after_yes, store.graph()); + lemma_guards_stable(entry, store.graph()); + lemma_guards_stable(after_yes, store.graph()); + lemma_guards_stable(after_negated, store.graph()); + assert(test_vocab(store.graph(), yes@).subset_of(test_vocab(store.graph(), path@).union(test_vocab(store.graph(), test@)))); + assert(test_vocab(store.graph(), no@).subset_of(test_vocab(store.graph(), path@).union(test_vocab(store.graph(), test@)))); + lemma_guard_children(store.graph(), id@); + assert(guard_task_vocab(store.graph(), ActionShape::Clean(a@, yes@)).subset_of(guard_task_vocab(store.graph(), ActionShape::Clean(id@, path@)))); + assert(guard_task_vocab(store.graph(), ActionShape::Clean(b@, no@)).subset_of(guard_task_vocab(store.graph(), ActionShape::Clean(id@, path@)))); + assert(guard_task_vocab(store.graph(), ActionShape::If(test@)).subset_of(guard_task_vocab(store.graph(), ActionShape::Clean(id@, path@)))); + regex_test_connective_extends(after_yes, store.graph(), seq![path, test], yes, true); + transition_test_not_extends(after_negated, store.graph(), test, neg); + assert forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + implies (model::test_holds(theta, model::lift_test(store.graph(), yes@), event) + == (model::test_holds(theta, model::lift_test(store.graph(), path@), event) + && model::test_holds(theta, model::lift_test(store.graph(), test@), event))) + && (model::test_holds(theta, model::lift_test(store.graph(), no@), event) + == (model::test_holds(theta, model::lift_test(store.graph(), path@), event) + && !model::test_holds(theta, model::lift_test(store.graph(), test@), event))) by { + transition_lemma_test_pair(store.graph(), theta, path, test, event); + transition_lemma_test_pair(store.graph(), theta, path, neg, event); + } + transition_lemma_clean_if_effect(store.graph(), id, path, test, a, b, yes, no, p0); + } + if yes == c.test_false { + tasks.push(Action::Clean(b, no)); + } else if no == c.test_false { + tasks.push(Action::Clean(a, yes)); + } else { + tasks.push(Action::If(test)); + tasks.push(Action::Clean(b, no)); + tasks.push(Action::Clean(a, yes)); + } + proof! { + assert(transition_action_views(tasks.view()) == transition_clean_if_tasks(store.graph(), test, a, b, yes, no, p0)); + machine_clean_if(entry, store.graph(), p0, id, path, test, a, b, yes, no, v0); + if fsteps::xpre(entry, ActionShape::Clean(id@, path@), p0, v0) { + fbr::lemma_clean_if(entry, store.graph(), p0, v0, id, path, test, a, b, yes, no); + } + } + } + TransitionHead::Union(n) => { + Self::clean_children(store, id, n, false, path, tasks)?; + proof! { + assert(guard_effect(store.graph(), p0, ActionShape::Clean(id@, path@), v0, transition_action_views(tasks.view()), v0)); + machine_clean_children(store.graph(), p0, id, path, false, v0); + if fsteps::xpre(entry, ActionShape::Clean(id@, path@), p0, v0) { + fbr::lemma_clean_children(entry, store.graph(), p0, v0, id, path, false); + } + } + } + TransitionHead::Intersect(n) => { + Self::clean_children(store, id, n, true, path, tasks)?; + proof! { + assert(guard_effect(store.graph(), p0, ActionShape::Clean(id@, path@), v0, transition_action_views(tasks.view()), v0)); + machine_clean_children(store.graph(), p0, id, path, true, v0); + if fsteps::xpre(entry, ActionShape::Clean(id@, path@), p0, v0) { + fbr::lemma_clean_children(entry, store.graph(), p0, v0, id, path, true); + } + } + } + TransitionHead::Not(inner) => { + tasks.push(Action::NotResult); + tasks.push(Action::Clean(inner, path)); + proof! { + transition_lemma_clean_not_effect(store.graph(), id, path, inner, p0); + assert(transition_action_views(tasks.view()) =~= p0.push(ActionShape::NotResult).push(ActionShape::Clean(inner@, path@))); + machine_clean_not(entry, store.graph(), p0, id, path, inner, v0); + if fsteps::xpre(entry, ActionShape::Clean(id@, path@), p0, v0) { + fbr::lemma_clean_not(entry, store.graph(), p0, v0, id, path, inner); + } + } + } + TransitionHead::Append(inner, n) => { + let xs = Self::suffix_values(store, id, n)?; + proof! { + transition_lemma_suffix(store.graph(), id@); + assert(entry.transitions[id@ as int] == model::TransitionNode::Append(inner@, model::regex_ids(xs.view()))); + } + let r = RegexId::concat(store, &xs)?; + tasks.push(Action::AppendResult(r)); + tasks.push(Action::Clean(inner, path)); + proof! { + transition_lemma_suffix(store.graph(), id@); + transition_lemma_clean_append_effect(store.graph(), id, path, inner, xs.view(), r, p0); + assert(transition_action_views(tasks.view()) =~= p0.push(ActionShape::AppendResult(r@)).push(ActionShape::Clean(inner@, path@))); + machine_clean_append(entry, store.graph(), p0, id, path, inner, r, v0); + if fsteps::xpre(entry, ActionShape::Clean(id@, path@), p0, v0) { + fbr::lemma_clean_append(entry, store.graph(), p0, v0, id, path, inner, xs.view(), r); + } + } + } + } + proof! { + lemma_guards_stable(entry, store.graph()); + lemma_guard_children(store.graph(), id@); + assert forall|allowed: Set| guard_config(store.graph(), p0, v0, allowed) + && guard_task_vocab(store.graph(), ActionShape::Clean(id@, path@)).subset_of(allowed) + implies guard_config(store.graph(), transition_action_views(tasks.view()), values.view(), allowed) by { + broadcast use vstd::set::group_set_lemmas; + assert forall|i: int| 0 <= i < tasks.view().len() implies + guard_task_vocab(store.graph(), transition_action_views(tasks.view())[i]).subset_of(allowed) by { + if i < p0.len() { + assert(transition_action_views(tasks.view())[i] == p0[i]); + } + } + assert forall|i: int| 0 <= i < values.view().len() implies + guard_vocab(store.graph(), values.view()[i]@).subset_of(allowed) by { + if v0.contains(values.view()[i]) { + let j = choose|j: int| 0 <= j < v0.len() && v0[j] == values.view()[i]; + assert(guard_vocab(store.graph(), v0[j]@).subset_of(allowed)); + } + } + } + } + Ok(()) + } + + #[verus_verify] + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + #[cfg_attr(verus_keep_ghost, verifier::rlimit(30))] + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + transition_configuration_valid(old(store).graph(), transition_action_views(old(tasks).view()), old(values).view()), + id@ < old(store).graph().transitions.len(), + c@ == old(store).graph().constants, + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + model::graph_wf(final(store).graph()), final(store).valid_store(), + transition_configuration_valid(final(store).graph(), transition_action_views(final(tasks).view()), final(values).view()), + transition_action_views(old(tasks).view()).is_prefix_of(transition_action_views(final(tasks).view())), + result is Ok ==> guard_effect(final(store).graph(), transition_action_views(old(tasks).view()), + ActionShape::Not(id@), old(values).view(), transition_action_views(final(tasks).view()), final(values).view()), + match result { + Ok(()) => transition_effect(final(store).graph(), ActionShape::Not(id@), + transition_action_views(old(tasks).view()), old(values).view(), + transition_action_views(final(tasks).view()), final(values).view()) + && (fsteps::xpre(old(store).graph(), ActionShape::Not(id@), transition_action_views(old(tasks).view()), old(values).view()) + ==> fsteps::xeffect(final(store).graph(), ActionShape::Not(id@), transition_action_views(old(tasks).view()), + old(values).view(), transition_action_views(final(tasks).view()), final(values).view())) + && machine_progress(old(store).graph(), transition_action_views(old(tasks).view()), + ActionShape::Not(id@), old(values).view(), + final(store).graph(), transition_action_views(final(tasks).view()), final(values).view()), + Err(_) => true, + }, + )] + fn not_step( + store: &mut G, + id: TransitionId, + c: &Constants, + tasks: &mut WorkVec, + values: &mut WorkVec, + ) -> KernelResult<()> { + proof_decl! { let ghost entry = store.graph(); let ghost initial = tasks.view(); + let ghost base = transition_action_views(initial); let ghost prior = values.view(); } + proof! { + assert(model::constants_wf(store.graph())) by { model::lemma_graph_wf_elim(store.graph()); } + model::lemma_graph_transition_wf(store.graph(), id@); + lemma_guard_children(store.graph(), id@); + transition_configuration_future(entry, base, prior); + graph_lemma_extends_refl(entry); + lemma_guard_constants(store.graph()); + } + match id.head(store)? { + TransitionHead::Const(r) => { + proof_decl! { let ghost head = r; } + let r = RegexId::not(r, store)?; + proof_decl! { let ghost before_const = store.graph(); } + values.push(TransitionId::constant(store, r)?); + proof! { + machine_unary_not_const_result(before_const, store.graph(), id, head, r, values.view().last()); + transition_lemma_push_result(store.graph(), ActionShape::Not(id@), base, prior, values.view().last()); + transition_lemma_extends_transitive(entry, before_const, store.graph()); + assert(values.view() == prior.push(values.view().last())); + machine_value_result(entry, store.graph(), base, ActionShape::Not(id@), prior, values.view().last()); + if fsteps::xpre(entry, ActionShape::Not(id@), base, prior) { + fbr::lemma_not_const(entry, before_const, store.graph(), base, prior, id, head, r, values.view().last()); + } + } + } + TransitionHead::Not(inner) => { + values.push(inner); + proof! { + machine_unary_double_not_result(store.graph(), id, inner); + transition_lemma_push_result(store.graph(), ActionShape::Not(id@), base, prior, inner); + machine_not_double(entry, store.graph(), base, id, inner, prior); + if fsteps::xpre(entry, ActionShape::Not(id@), base, prior) { + fbr::lemma_not_double(entry, store.graph(), base, prior, id, inner); + } + } + } + TransitionHead::Append(_, _) => { + values.push(TransitionId::intern(store, TransitionView::Not(id))?); + proof! { + reveal(guard_node_vocab); + assert(guard_vocab(store.graph(), values.view().last()@) == guard_vocab(store.graph(), id@)); + transition_lemma_result_same_term(store.graph(), ActionShape::Not(id@), values.view().last()); + transition_lemma_push_result(store.graph(), ActionShape::Not(id@), base, prior, values.view().last()); + assert(values.view() == prior.push(values.view().last())); + machine_wrap_interned(entry, store.graph(), base, ActionShape::Not(id@), prior, values.view().last()); + if fsteps::xpre(entry, ActionShape::Not(id@), base, prior) { + fbr::lemma_not_wrap(entry, store.graph(), base, prior, id, values.view().last()); + } + } + } + TransitionHead::If(test, a, b) => { + if a == c.transition_all && b == c.transition_empty { + let guard = TestId::not(test, store)?; + proof! { + lemma_test_definition(store.graph(), test@); lemma_test_definition(store.graph(), guard@); + assert(test_vocab(store.graph(), test@) == test_vocab(store.graph(), guard@)); + lemma_guards_stable(entry, store.graph()); + assert forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + implies model::test_holds(theta, model::lift_test(store.graph(), guard@), event) + == !model::test_holds(theta, model::lift_test(store.graph(), test@), event) by { + assert(test_truth(store.graph(), theta, guard@, event) + != test_truth(store.graph(), theta, test@, event)); + } + } + proof_decl! { let ghost before_if = store.graph(); } + let out = TransitionId::local_if(store, guard, a, b)?; + tasks.push(Action::Clean(out, c.test_true)); + proof! { + lemma_guards_stable(before_if, store.graph()); + lemma_guard_constants(store.graph()); + lemma_guard_children(store.graph(), id@); + machine_unary_flip_result(before_if, store.graph(), id, test, a, b, guard, out); + machine_unary_clean_result_effect(store.graph(), ActionShape::Not(id@), out, base, prior); + assert(transition_action_views(tasks.view()) =~= base.push(ActionShape::Clean(out@, c.test_true@))); + transition_lemma_extends_transitive(entry, before_if, store.graph()); + tdepth_lemma_constants(before_if); + machine_not_flip(entry, store.graph(), base, id, test, a, b, out, c.test_true, prior); + if fsteps::xpre(entry, ActionShape::Not(id@), base, prior) { + fbr::lemma_not_flip(entry, store.graph(), base, prior, id, test, a, b, guard, out); + } + } + } else { + tasks.push(Action::CleanIf(test, c.test_true)); + tasks.push(Action::Not(b)); + tasks.push(Action::Not(a)); + proof! { + machine_unary_if_effect(store.graph(), id, test, a, b, None, base, prior); + assert(transition_action_views(tasks.view()) =~= machine_unary_if_tasks(store.graph(), test, a, b, None, base)); + machine_unary_if(entry, store.graph(), base, id, test, a, b, None, prior); + if fsteps::xpre(entry, ActionShape::Not(id@), base, prior) { + fbr::lemma_unary_if(entry, store.graph(), base, prior, id, test, a, b, None); + } + } + } + } + TransitionHead::Union(n) => { + tasks.push(Action::Intersect(n)); + proof! { + transition_lemma_children(store.graph(), id@); + assert(transition_action_views(tasks.view()) =~= base.push(ActionShape::Intersect(n as nat))); + assert(transition_tasks_valid(store.graph(), transition_action_views(tasks.view()))); + } + ChildAction::Not.schedule(store, id, n, tasks)?; + proof! { broadcast use vstd::set::group_set_lemmas; lemma_guard_scheduled(store.graph(), id@, ChildShape::Not, ActionShape::Intersect(n as nat), ActionShape::Not(id@), base, prior); } + proof! { + machine_unary_children_effect(store.graph(), id, None, true, base, prior); + assert(transition_action_views(tasks.view()) =~= machine_unary_child_tasks(store.graph(), id, None, true, base)); + machine_unary_children(store.graph(), base, id, None, true, prior); + if fsteps::xpre(entry, ActionShape::Not(id@), base, prior) { + fbr::lemma_unary_children(entry, store.graph(), base, prior, id, None, true); + } + } + } + TransitionHead::Intersect(n) => { + tasks.push(Action::Union(n)); + proof! { + transition_lemma_children(store.graph(), id@); + assert(transition_action_views(tasks.view()) =~= base.push(ActionShape::Union(n as nat))); + assert(transition_tasks_valid(store.graph(), transition_action_views(tasks.view()))); + } + ChildAction::Not.schedule(store, id, n, tasks)?; + proof! { broadcast use vstd::set::group_set_lemmas; lemma_guard_scheduled(store.graph(), id@, ChildShape::Not, ActionShape::Union(n as nat), ActionShape::Not(id@), base, prior); } + proof! { + machine_unary_children_effect(store.graph(), id, None, false, base, prior); + assert(transition_action_views(tasks.view()) =~= machine_unary_child_tasks(store.graph(), id, None, false, base)); + machine_unary_children(store.graph(), base, id, None, false, prior); + if fsteps::xpre(entry, ActionShape::Not(id@), base, prior) { + fbr::lemma_unary_children(entry, store.graph(), base, prior, id, None, false); + } + } + } + } + proof! { + lemma_guards_stable(entry, store.graph()); + assert forall|allowed: Set| guard_config(store.graph(), base, prior, allowed) + && guard_task_vocab(store.graph(), ActionShape::Not(id@)).subset_of(allowed) + implies guard_config(store.graph(), transition_action_views(tasks.view()), values.view(), allowed) by { + broadcast use vstd::set::group_set_lemmas; + assert forall|i: int| 0 <= i < tasks.view().len() implies + guard_task_vocab(store.graph(), transition_action_views(tasks.view())[i]).subset_of(allowed) by { + if i < base.len() { + assert(transition_action_views(tasks.view())[i] == base[i]); + } + } + assert forall|i: int| 0 <= i < values.view().len() implies + guard_vocab(store.graph(), values.view()[i]@).subset_of(allowed) by { + if prior.contains(values.view()[i]) { + let j = choose|j: int| 0 <= j < prior.len() && prior[j] == values.view()[i]; + assert(guard_vocab(store.graph(), prior[j]@).subset_of(allowed)); + } + } + } + } + Ok(()) + } + + #[allow( + clippy::semicolon_if_nothing_returned, + reason = "Preserve the existing Verus-verified match arms." + )] + #[verus_verify] + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + #[cfg_attr(verus_keep_ghost, verifier::rlimit(30))] + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + transition_configuration_valid(old(store).graph(), transition_action_views(old(tasks).view()), old(values).view()), + id@ < old(store).graph().transitions.len(), + r@ < old(store).graph().regexes.len(), + c@ == old(store).graph().constants, + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + model::graph_wf(final(store).graph()), final(store).valid_store(), + transition_configuration_valid(final(store).graph(), transition_action_views(final(tasks).view()), final(values).view()), + transition_action_views(old(tasks).view()).is_prefix_of(transition_action_views(final(tasks).view())), + result is Ok ==> guard_effect(final(store).graph(), transition_action_views(old(tasks).view()), + ActionShape::Append(id@, r@), old(values).view(), transition_action_views(final(tasks).view()), final(values).view()), + match result { + Ok(()) => transition_effect(final(store).graph(), ActionShape::Append(id@, r@), + transition_action_views(old(tasks).view()), old(values).view(), + transition_action_views(final(tasks).view()), final(values).view()) + && (fsteps::xpre(old(store).graph(), ActionShape::Append(id@, r@), transition_action_views(old(tasks).view()), old(values).view()) + ==> fsteps::xeffect(final(store).graph(), ActionShape::Append(id@, r@), transition_action_views(old(tasks).view()), + old(values).view(), transition_action_views(final(tasks).view()), final(values).view())) + && machine_progress(old(store).graph(), transition_action_views(old(tasks).view()), + ActionShape::Append(id@, r@), old(values).view(), + final(store).graph(), transition_action_views(final(tasks).view()), final(values).view()), + Err(_) => true, + }, + )] + fn append_step( + store: &mut G, + id: TransitionId, + r: RegexId, + c: &Constants, + tasks: &mut WorkVec, + values: &mut WorkVec, + ) -> KernelResult<()> { + proof_decl! { let ghost entry = store.graph(); let ghost initial = tasks.view(); + let ghost base = transition_action_views(initial); let ghost prior = values.view(); } + proof! { + assert(model::constants_wf(store.graph())) by { model::lemma_graph_wf_elim(store.graph()); } + model::lemma_graph_transition_wf(store.graph(), id@); + lemma_guard_children(store.graph(), id@); + model::lemma_graph_regex_wf(store.graph(), r@); + transition_configuration_future(entry, base, prior); + graph_lemma_extends_refl(entry); + lemma_guard_constants(store.graph()); + tdepth_lemma_constants(entry); + } + { + if r == c.epsilon { + values.push(id); + proof! { + machine_unary_append_identity_result(store.graph(), id, r, id); + transition_lemma_push_result(store.graph(), ActionShape::Append(id@, r@), base, prior, id); + machine_value_result(entry, store.graph(), base, ActionShape::Append(id@, r@), prior, id); + if fsteps::xpre(entry, ActionShape::Append(id@, r@), base, prior) { + fbr::lemma_append_eps(entry, store.graph(), base, prior, id, r); + } + } + } else if r == c.empty { + values.push(c.transition_empty); + proof! { + machine_unary_append_identity_result(store.graph(), id, r, c.transition_empty); + transition_lemma_push_result(store.graph(), ActionShape::Append(id@, r@), base, prior, c.transition_empty); + machine_value_result(entry, store.graph(), base, ActionShape::Append(id@, r@), prior, c.transition_empty); + if fsteps::xpre(entry, ActionShape::Append(id@, r@), base, prior) { + fbr::lemma_append_empty(entry, store.graph(), base, prior, id, r, c.transition_empty); + } + } + } else { + match id.head(store)? { + TransitionHead::Const(head) => { + let out = RegexId::concat(store, &[head, r])?; + proof_decl! { let ghost before_const = store.graph(); } + values.push(TransitionId::constant(store, out)?); + proof! { + machine_unary_append_const_result(before_const, store.graph(), id, head, r, out, values.view().last()); + transition_lemma_push_result(store.graph(), ActionShape::Append(id@, r@), base, prior, values.view().last()); + transition_lemma_extends_transitive(entry, before_const, store.graph()); + assert(values.view() == prior.push(values.view().last())); + machine_value_result(entry, store.graph(), base, ActionShape::Append(id@, r@), prior, values.view().last()); + if fsteps::xpre(entry, ActionShape::Append(id@, r@), base, prior) { + fbr::lemma_append_const(entry, before_const, store.graph(), base, prior, id, r, head, out, values.view().last()); + } + } + } + TransitionHead::If(test, a, b) => { + tasks.push(Action::CleanIf(test, c.test_true)); + tasks.push(Action::Append(b, r)); + tasks.push(Action::Append(a, r)); + proof! { + machine_unary_if_effect(store.graph(), id, test, a, b, Some(r), base, prior); + assert(transition_action_views(tasks.view()) =~= machine_unary_if_tasks(store.graph(), test, a, b, Some(r), base)); + machine_unary_if(entry, store.graph(), base, id, test, a, b, Some(r), prior); + if fsteps::xpre(entry, ActionShape::Append(id@, r@), base, prior) { + fbr::lemma_unary_if(entry, store.graph(), base, prior, id, test, a, b, Some(r)); + } + } + } + TransitionHead::Union(n) => { + tasks.push(Action::Union(n)); + proof! { + transition_lemma_children(store.graph(), id@); + assert(transition_action_views(tasks.view()) =~= base.push(ActionShape::Union(n as nat))); + assert(transition_tasks_valid(store.graph(), transition_action_views(tasks.view()))); + } + ChildAction::Append(r).schedule(store, id, n, tasks)?; + proof! { broadcast use vstd::set::group_set_lemmas; lemma_guard_scheduled(store.graph(), id@, ChildShape::Append(r@), ActionShape::Union(n as nat), ActionShape::Append(id@, r@), base, prior); } + proof! { + machine_unary_children_effect(store.graph(), id, Some(r), false, base, prior); + assert(transition_action_views(tasks.view()) =~= machine_unary_child_tasks(store.graph(), id, Some(r), false, base)); + machine_unary_children(store.graph(), base, id, Some(r), false, prior); + if fsteps::xpre(entry, ActionShape::Append(id@, r@), base, prior) { + fbr::lemma_unary_children(entry, store.graph(), base, prior, id, Some(r), false); + } + } + } + TransitionHead::Append(inner, n) => { + let mut xs = Self::suffix_values(store, id, n)?; + proof_decl! { let ghost children = xs.view(); } + proof! { + transition_lemma_suffix(store.graph(), id@); + assert(entry.transitions[id@ as int] == model::TransitionNode::Append(inner@, model::regex_ids(children))); + } + xs.push(r); + let combined = RegexId::concat(store, &xs)?; + tasks.push(Action::Append(inner, combined)); + proof! { + machine_unary_append_nested_effect(store.graph(), id, inner, r, combined, children, base, prior); + assert(transition_action_views(tasks.view()) =~= base.push(ActionShape::Append(inner@, combined@))); + machine_append_nested(entry, store.graph(), base, id, r, inner, combined, prior); + if fsteps::xpre(entry, ActionShape::Append(id@, r@), base, prior) { + fbr::lemma_append_nested(entry, store.graph(), base, prior, id, r, inner, children, combined); + } + } + } + TransitionHead::Intersect(_) | TransitionHead::Not(_) => { + let mut xs = WorkVec::new(); + match r.head(store)? { + RegexHead::Concat(n) => { + proof! { regex_children_count(store.graph(), r@); } + RegexMode::append_children(store, r, n, &mut xs)? + } + _ => xs.push(r), + } + proof! { + regex_children_count(store.graph(), r@); + machine_unary_suffix_language(store.graph(), r, xs.view()); + } + proof_decl! { let ghost before_intern = store.graph(); } + values.push(TransitionId::intern( + store, + TransitionView::Append { + transition: id, + suffix: &xs, + }, + )?); + proof! { + reveal(guard_node_vocab); + assert(guard_vocab(store.graph(), values.view().last()@) == guard_vocab(store.graph(), id@)); + machine_unary_append_raw_result(before_intern, store.graph(), id, r, xs.view(), values.view().last()); + transition_lemma_push_result(store.graph(), ActionShape::Append(id@, r@), base, prior, values.view().last()); + transition_lemma_extends_transitive(entry, before_intern, store.graph()); + assert(values.view() == prior.push(values.view().last())); + machine_wrap_interned(entry, store.graph(), base, ActionShape::Append(id@, r@), prior, values.view().last()); + if fsteps::xpre(entry, ActionShape::Append(id@, r@), base, prior) { + fbr::lemma_append_raw(entry, store.graph(), base, prior, id, r, xs.view(), values.view().last()); + } + } + } + } + } + } + proof! { + lemma_guards_stable(entry, store.graph()); + assert forall|allowed: Set| guard_config(store.graph(), base, prior, allowed) + && guard_task_vocab(store.graph(), ActionShape::Append(id@, r@)).subset_of(allowed) + implies guard_config(store.graph(), transition_action_views(tasks.view()), values.view(), allowed) by { + broadcast use vstd::set::group_set_lemmas; + assert forall|i: int| 0 <= i < tasks.view().len() implies + guard_task_vocab(store.graph(), transition_action_views(tasks.view())[i]).subset_of(allowed) by { + if i < base.len() { + assert(transition_action_views(tasks.view())[i] == base[i]); + } + } + assert forall|i: int| 0 <= i < values.view().len() implies + guard_vocab(store.graph(), values.view()[i]@).subset_of(allowed) by { + if prior.contains(values.view()[i]) { + let j = choose|j: int| 0 <= j < prior.len() && prior[j] == values.view()[i]; + assert(guard_vocab(store.graph(), prior[j]@).subset_of(allowed)); + } + } + } + } + Ok(()) + } + + #[allow( + clippy::semicolon_if_nothing_returned, + reason = "Preserve the existing Verus-verified match arms." + )] + #[verus_verify] + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + // rlimit 30 was exceeded in the no-std configuration once `HistoryError` gained `GraphIndex`. + #[cfg_attr(verus_keep_ghost, verifier::rlimit(80))] + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + transition_configuration_valid(old(store).graph(), transition_action_views(old(tasks).view()), old(values).view()), + a@ < old(store).graph().transitions.len(), + b@ < old(store).graph().transitions.len(), + c@ == old(store).graph().constants, + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + model::graph_wf(final(store).graph()), final(store).valid_store(), + transition_configuration_valid(final(store).graph(), transition_action_views(final(tasks).view()), final(values).view()), + transition_action_views(old(tasks).view()).is_prefix_of(transition_action_views(final(tasks).view())), + result is Ok ==> guard_effect(final(store).graph(), transition_action_views(old(tasks).view()), + ActionShape::Pair(a@, b@), old(values).view(), transition_action_views(final(tasks).view()), final(values).view()), + match result { + Ok(()) => transition_effect(final(store).graph(), ActionShape::Pair(a@, b@), + transition_action_views(old(tasks).view()), old(values).view(), + transition_action_views(final(tasks).view()), final(values).view()) + && (fsteps::xpre(old(store).graph(), ActionShape::Pair(a@, b@), transition_action_views(old(tasks).view()), old(values).view()) + ==> fsteps::xeffect(final(store).graph(), ActionShape::Pair(a@, b@), transition_action_views(old(tasks).view()), + old(values).view(), transition_action_views(final(tasks).view()), final(values).view())) + && machine_progress(old(store).graph(), transition_action_views(old(tasks).view()), + ActionShape::Pair(a@, b@), old(values).view(), + final(store).graph(), transition_action_views(final(tasks).view()), final(values).view()), + Err(_) => true, + }, + )] + fn pair_step( + store: &mut G, + a: TransitionId, + b: TransitionId, + c: &Constants, + tasks: &mut WorkVec, + values: &mut WorkVec, + ) -> KernelResult<()> { + proof_decl! { let ghost p0 = transition_action_views(tasks.view()); let ghost v0 = values.view(); + let ghost entry = store.graph(); } + proof! { + // Expose only constants; full table facts unfold irrelevant recursive semantics. + assert(model::constants_wf(store.graph())) by { model::lemma_graph_wf_elim(store.graph()); } + transition_configuration_future(store.graph(), p0, v0); + model::lemma_graph_transition_wf(store.graph(), a@); + model::lemma_graph_transition_wf(store.graph(), b@); + lemma_guard_children(store.graph(), a@); + lemma_guard_children(store.graph(), b@); + graph_lemma_extends_refl(entry); + lemma_guard_constants(store.graph()); + tdepth_lemma_constants(entry); + tdepth_lemma_pos(entry, a@); + tdepth_lemma_pos(entry, b@); + lemma_pair_bound_ge(tdepth(entry, a@), tdepth(entry, b@)); + } + { + if a == b || b == c.transition_all { + values.push(a); + proof! { + machine_pair_identity_result(store.graph(), a, b, a, c.transition_all, c.transition_empty); + transition_lemma_push_result(store.graph(), ActionShape::Pair(a@, b@), p0, v0, a); + machine_value_result(entry, store.graph(), p0, ActionShape::Pair(a@, b@), v0, a); + if fsteps::xpre(entry, ActionShape::Pair(a@, b@), p0, v0) { fbr::lemma_pair_keep(entry, store.graph(), p0, v0, a, b, a); } + } + } else if a == c.transition_all { + values.push(b); + proof! { + machine_pair_identity_result(store.graph(), a, b, b, c.transition_all, c.transition_empty); + transition_lemma_push_result(store.graph(), ActionShape::Pair(a@, b@), p0, v0, b); + machine_value_result(entry, store.graph(), p0, ActionShape::Pair(a@, b@), v0, b); + if fsteps::xpre(entry, ActionShape::Pair(a@, b@), p0, v0) { fbr::lemma_pair_keep(entry, store.graph(), p0, v0, a, b, b); } + } + } else if a == c.transition_empty || b == c.transition_empty { + values.push(c.transition_empty); + proof! { + machine_pair_identity_result(store.graph(), a, b, c.transition_empty, c.transition_all, c.transition_empty); + transition_lemma_push_result(store.graph(), ActionShape::Pair(a@, b@), p0, v0, c.transition_empty); + machine_value_result(entry, store.graph(), p0, ActionShape::Pair(a@, b@), v0, c.transition_empty); + if fsteps::xpre(entry, ActionShape::Pair(a@, b@), p0, v0) { + fbr::lemma_pair_keep(entry, store.graph(), p0, v0, a, b, c.transition_empty); + } + } + } else { + let left = a.head(store)?; + let right = b.head(store)?; + match (left, right) { + (TransitionHead::Const(x), TransitionHead::Const(y)) => { + let r = RegexId::set(store, &[x, y], true)?; + proof_decl! { let ghost after_regex = store.graph(); } + values.push(TransitionId::constant(store, r)?); + proof! { + let out = values.view().last(); + machine_pair_constant_result(after_regex, store.graph(), a, b, x, y, r, out); + transition_lemma_push_result(store.graph(), ActionShape::Pair(a@, b@), p0, v0, out); + transition_lemma_extends_transitive(entry, after_regex, store.graph()); + machine_value_result(entry, store.graph(), p0, ActionShape::Pair(a@, b@), v0, out); + if fsteps::xpre(entry, ActionShape::Pair(a@, b@), p0, v0) { + fbr::lemma_pair_const(entry, after_regex, store.graph(), p0, v0, a, b, x, y, r, out); + } + } + } + (TransitionHead::If(_, _, _), TransitionHead::If(_, _, _)) => { + Self::pair_conditionals(store, a, b, left, right, tasks, values)? + } + (TransitionHead::Union(n), _) => { + tasks.push(Action::Union(n)); + proof! { + assert(transition_action_views(tasks.view()) =~= p0.push(ActionShape::Union(n as nat))); + assert(transition_tasks_valid(store.graph(), transition_action_views(tasks.view()))); + transition_lemma_children(store.graph(), a@); + assert(transition_children(store.graph(), a@).len() == n); + } + ChildAction::PairLeft(b).schedule(store, a, n, tasks)?; + proof! { broadcast use vstd::set::group_set_lemmas; lemma_guard_scheduled(store.graph(), a@, ChildShape::PairLeft(b@), ActionShape::Union(n as nat), ActionShape::Pair(a@, b@), p0, v0); } + proof! { + machine_pair_union_effect(store.graph(), a, b, true, p0, v0); + assert(transition_effect(store.graph(), ActionShape::Pair(a@, b@), p0, v0, + transition_action_views(tasks.view()), values.view())); + assert(transition_action_views(tasks.view()) =~= p0.push(ActionShape::Union( + transition_children(store.graph(), a@).len())) + transition_child_actions(store.graph(), a@, + ChildShape::PairLeft(b@))); + machine_pair_union(store.graph(), p0, a, b, true, v0); + if fsteps::xpre(entry, ActionShape::Pair(a@, b@), p0, v0) { + fbr::lemma_pair_union(entry, store.graph(), p0, v0, a, b, true); + } + } + } + (_, TransitionHead::Union(n)) => { + tasks.push(Action::Union(n)); + proof! { + assert(transition_action_views(tasks.view()) =~= p0.push(ActionShape::Union(n as nat))); + assert(transition_tasks_valid(store.graph(), transition_action_views(tasks.view()))); + transition_lemma_children(store.graph(), b@); + assert(transition_children(store.graph(), b@).len() == n); + } + ChildAction::PairRight(a).schedule(store, b, n, tasks)?; + proof! { broadcast use vstd::set::group_set_lemmas; lemma_guard_scheduled(store.graph(), b@, ChildShape::PairRight(a@), ActionShape::Union(n as nat), ActionShape::Pair(a@, b@), p0, v0); } + proof! { + machine_pair_union_effect(store.graph(), a, b, false, p0, v0); + assert(transition_effect(store.graph(), ActionShape::Pair(a@, b@), p0, v0, + transition_action_views(tasks.view()), values.view())); + assert(transition_action_views(tasks.view()) =~= p0.push(ActionShape::Union( + transition_children(store.graph(), b@).len())) + transition_child_actions(store.graph(), b@, + ChildShape::PairRight(a@))); + machine_pair_union(store.graph(), p0, a, b, false, v0); + if fsteps::xpre(entry, ActionShape::Pair(a@, b@), p0, v0) { + fbr::lemma_pair_union(entry, store.graph(), p0, v0, a, b, false); + } + } + } + (TransitionHead::If(test, t, e), _) => { + tasks.push(Action::CleanIf(test, c.test_true)); + tasks.push(Action::Pair(e, b)); + tasks.push(Action::Pair(t, b)); + proof! { + machine_pair_if_language(store.graph(), a, test, t, e); + machine_pair_if_effect(store.graph(), a, b, test, t, b, e, b, p0, v0); + assert(transition_action_views(tasks.view()) =~= p0.push(ActionShape::CleanIf(test@, c.test_true@)) + .push(ActionShape::Pair(e@, b@)).push(ActionShape::Pair(t@, b@))); + machine_pair_split(entry, store.graph(), p0, a, b, test, t, e, c.test_true, true, v0); + if fsteps::xpre(entry, ActionShape::Pair(a@, b@), p0, v0) { + fbr::lemma_pair_split(entry, store.graph(), p0, v0, a, b, test, t, e, true); + } + } + } + (_, TransitionHead::If(test, t, e)) => { + tasks.push(Action::CleanIf(test, c.test_true)); + tasks.push(Action::Pair(a, e)); + tasks.push(Action::Pair(a, t)); + proof! { + machine_pair_if_language(store.graph(), b, test, t, e); + machine_pair_if_effect(store.graph(), a, b, test, a, t, a, e, p0, v0); + assert(transition_action_views(tasks.view()) =~= p0.push(ActionShape::CleanIf(test@, c.test_true@)) + .push(ActionShape::Pair(a@, e@)).push(ActionShape::Pair(a@, t@))); + machine_pair_split(entry, store.graph(), p0, a, b, test, t, e, c.test_true, false, v0); + if fsteps::xpre(entry, ActionShape::Pair(a@, b@), p0, v0) { + fbr::lemma_pair_split(entry, store.graph(), p0, v0, a, b, test, t, e, false); + } + } + } + _ => { + values.push(TransitionId::collect(store, &[a, b], true)?); + proof! { + broadcast use vstd::set::group_set_lemmas; + lemma_guard_union(store.graph(), seq![a@, b@], guard_vocab(store.graph(), a@).union(guard_vocab(store.graph(), b@))); + assert(model::transition_ids(seq![a, b]) =~= seq![a@, b@]); + assert(guard_vocab(store.graph(), values.view().last()@).subset_of(guard_vocab(store.graph(), a@).union(guard_vocab(store.graph(), b@)))); + let out = values.view().last(); + machine_pair_set_result(store.graph(), seq![a, b], ActionShape::Pair(a@, b@), out); + transition_lemma_push_result(store.graph(), ActionShape::Pair(a@, b@), p0, v0, out); + collect_lemma_pair_bound(entry, a, b); + machine_value_result(entry, store.graph(), p0, ActionShape::Pair(a@, b@), v0, out); + if fsteps::xpre(entry, ActionShape::Pair(a@, b@), p0, v0) { + fbr::lemma_pair_collect(entry, store.graph(), p0, v0, a, b, out); + } + } + } + } + } + } + proof! { + lemma_guards_stable(entry, store.graph()); + assert forall|allowed: Set| guard_config(store.graph(), p0, v0, allowed) + && guard_task_vocab(store.graph(), ActionShape::Pair(a@, b@)).subset_of(allowed) + implies guard_config(store.graph(), transition_action_views(tasks.view()), values.view(), allowed) by { + broadcast use vstd::set::group_set_lemmas; + assert forall|i: int| 0 <= i < tasks.view().len() implies + guard_task_vocab(store.graph(), transition_action_views(tasks.view())[i]).subset_of(allowed) by { + if i < p0.len() { + assert(transition_action_views(tasks.view())[i] == p0[i]); + } + } + assert forall|i: int| 0 <= i < values.view().len() implies + guard_vocab(store.graph(), values.view()[i]@).subset_of(allowed) by { + if v0.contains(values.view()[i]) { + let j = choose|j: int| 0 <= j < v0.len() && v0[j] == values.view()[i]; + assert(guard_vocab(store.graph(), v0[j]@).subset_of(allowed)); + } + } + } + } + Ok(()) + } + + verus! { + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + // Keep headroom for the resource-error postcondition on every dispatcher branch. + #[cfg_attr(verus_keep_ghost, verifier::rlimit(60))] + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + transition_action_valid(old(store).graph(), self@), + transition_configuration_valid(old(store).graph(), transition_action_views(old(tasks).view()), old(values).view()), + transition_program(old(store).graph(), transition_action_views(old(tasks).view()).push(self@), old(values).view()) is Some, + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + model::graph_wf(final(store).graph()), final(store).valid_store(), + transition_configuration_valid(final(store).graph(), transition_action_views(final(tasks).view()), final(values).view()), + transition_action_views(old(tasks).view()).is_prefix_of(transition_action_views(final(tasks).view())), + result is Ok ==> guard_effect(final(store).graph(), transition_action_views(old(tasks).view()), + self@, old(values).view(), transition_action_views(final(tasks).view()), final(values).view()), + match result { + Ok(()) => transition_effect(final(store).graph(), self@, + transition_action_views(old(tasks).view()), old(values).view(), + transition_action_views(final(tasks).view()), final(values).view()) + && (fsteps::xpre(old(store).graph(), self@, transition_action_views(old(tasks).view()), old(values).view()) + ==> fsteps::xeffect(final(store).graph(), self@, transition_action_views(old(tasks).view()), old(values).view(), + transition_action_views(final(tasks).view()), final(values).view())) + && machine_progress(old(store).graph(), transition_action_views(old(tasks).view()), self@, old(values).view(), + final(store).graph(), transition_action_views(final(tasks).view()), final(values).view()), + Err(_) => true, + }, + )] + fn step( + self, + store: &mut G, + tasks: &mut WorkVec, + values: &mut WorkVec, + ) -> KernelResult<()> { + hide(transition_program); + hide(resource_error); + hide(guarded_run); + hide(guarded_apply); + hide(transition_effect); + hide(machine_run); + hide(language::numeric_lang); + hide(model::test_holds); + hide(model::lift_transition); + proof_decl! { let ghost p0 = transition_action_views(tasks.view()); let ghost v0 = values.view(); + let ghost entry = store.graph(); } + proof! { transition_configuration_future(store.graph(), p0, v0); graph_lemma_extends_refl(entry); } + proof! { lemma_guard_constants(store.graph()); } + proof! { transition_lemma_stack_ready(store.graph(), p0, self@, v0); } + store.checkpoint()?; + let c = store.constants(); + match self { + Action::Union(n) => { + let xs = Self::take_values(values, n)?; + values.push(TransitionId::collect(store, &xs, false)?); + proof! { + assert forall|allowed: Set| guard_config(store.graph(), p0, v0, allowed) + implies guard_vocab(store.graph(), values.view().last()@).subset_of(allowed) by { + broadcast use vstd::set::group_set_lemmas; + lemma_guard_union(store.graph(), model::transition_ids(xs.view()), allowed); + assert forall|i: int| 0 <= i < xs.view().len() implies guard_vocab(store.graph(), xs.view()[i]@).subset_of(allowed) by { + assert(xs.view()[i] == v0[v0.len() - n + i]); + } + } + machine_driver_union_effect(store.graph(), n as nat, p0, v0, values.view().last()); + assert(values.view() == v0.take(v0.len() as int - n as int).push(values.view().last())); + machine_driver_union(entry, store.graph(), p0, n as nat, v0, values.view().last()); + if fsteps::xpre(entry, ActionShape::Union(n as nat), p0, v0) { + fbr::lemma_step_union(entry, store.graph(), p0, v0, n as nat, values.view().last()); + } + } + } + Action::Intersect(n) => { + let xs = Self::take_values(values, n)?; + tasks.push(Action::Fold(xs, 0)); + proof! { + assert forall|allowed: Set| guard_config(store.graph(), p0, v0, allowed) + implies guard_task_vocab(store.graph(), transition_action_views(tasks.view()).last()).subset_of(allowed) by { + lemma_guard_union(store.graph(), model::transition_ids(v0.subrange(v0.len() as int - n as int, v0.len() as int)), allowed); + assert forall|i: int| #![trigger guard_vocab(store.graph(), model::transition_ids(v0.subrange(v0.len() as int - n as int, v0.len() as int))[i])] + 0 <= i < n implies guard_vocab(store.graph(), model::transition_ids(v0.subrange(v0.len() as int - n as int, v0.len() as int))[i]).subset_of(allowed) by { + assert(model::transition_ids(v0.subrange(v0.len() as int - n as int, v0.len() as int))[i] == v0[v0.len() - n + i]@); + } + } + machine_driver_intersect_effect(store.graph(), n as nat, p0, v0); + assert(transition_action_views(tasks.view()) =~= p0.push(ActionShape::Fold( + model::transition_ids(v0.subrange(v0.len() as int - n as int, v0.len() as int)), 0))); + machine_driver_intersect(store.graph(), p0, n as nat, v0); + if fsteps::xpre(entry, ActionShape::Intersect(n as nat), p0, v0) { + fbr::lemma_step_intersect(entry, store.graph(), p0, v0, n as nat); + } + } + } + Action::Fold(xs, index) => { + proof! { + assert forall|i: int| 0 <= i < xs.view().len() implies xs.view()[i]@ < store.graph().transitions.len() by { + assert(model::transition_ids(xs.view())[i] == xs.view()[i]@); + } + } + Action::fold_step(store, xs, index, tasks, values)?; + } + Action::If(test) => { + let b = match values.pop() { + Some(v) => v, + None => return Err(HistoryError::normalization_invariant()), + }; + let a = match values.pop() { + Some(v) => v, + None => return Err(HistoryError::normalization_invariant()), + }; + proof! { + assert(values.view() =~= v0.take(v0.len() as int - 2)); + assert(a == v0[v0.len() - 2] && b == v0[v0.len() - 1]); + } + values.push(TransitionId::local_if(store, test, a, b)?); + proof! { + machine_driver_if_effect(store.graph(), test, None, p0, v0, values.view().last()); + assert(values.view() == v0.take(v0.len() as int - 2).push(values.view().last())); + machine_driver_if(entry, store.graph(), p0, ActionShape::If(test@), v0, values.view().last()); + if fsteps::xpre(entry, ActionShape::If(test@), p0, v0) { + fbr::lemma_step_if(entry, store.graph(), p0, v0, test@, values.view().last()); + } + } + } + Action::CleanIf(test, path) => { + let b = match values.pop() { + Some(v) => v, + None => return Err(HistoryError::normalization_invariant()), + }; + let a = match values.pop() { + Some(v) => v, + None => return Err(HistoryError::normalization_invariant()), + }; + proof! { + assert(values.view() =~= v0.take(v0.len() as int - 2)); + assert(a == v0[v0.len() - 2] && b == v0[v0.len() - 1]); + } + let out = TransitionId::local_if(store, test, a, b)?; + tasks.push(Action::Clean(out, path)); + proof! { + machine_driver_if_effect(store.graph(), test, Some(path), p0, v0, out); + assert(transition_action_views(tasks.view()) =~= p0.push(ActionShape::Clean(out@, path@))); + machine_driver_clean_if(entry, store.graph(), p0, test, path, v0, out); + if fsteps::xpre(entry, ActionShape::CleanIf(test@, path@), p0, v0) { + fbr::lemma_step_clean_if(entry, store.graph(), p0, v0, test@, path@, out); + } + } + } + Action::Clean(id, path) => Action::clean_step(store, id, path, &c, tasks, values)?, + Action::Not(id) => Action::not_step(store, id, &c, tasks, values)?, + Action::Append(id, r) => Action::append_step(store, id, r, &c, tasks, values)?, + Action::Pair(a, b) => Action::pair_step(store, a, b, &c, tasks, values)?, + Action::NotResult => { + let id = match values.pop() { + Some(v) => v, + None => return Err(HistoryError::normalization_invariant()), + }; + proof! { assert(values.view() =~= v0.drop_last()); } + tasks.push(Action::Not(id)); + proof! { + machine_driver_result_effect(store.graph(), ActionShape::NotResult, p0, v0); + assert(transition_action_views(tasks.view()) =~= p0.push(ActionShape::Not(id@))); + machine_driver_result(store.graph(), p0, None, v0); + if fsteps::xpre(entry, ActionShape::NotResult, p0, v0) { + fbr::lemma_step_result(entry, store.graph(), p0, v0, None); + } + } + } + Action::AppendResult(r) => { + let id = match values.pop() { + Some(v) => v, + None => return Err(HistoryError::normalization_invariant()), + }; + proof! { assert(values.view() =~= v0.drop_last()); } + tasks.push(Action::Append(id, r)); + proof! { + machine_driver_result_effect(store.graph(), ActionShape::AppendResult(r@), p0, v0); + assert(transition_action_views(tasks.view()) =~= p0.push(ActionShape::Append(id@, r@))); + machine_driver_result(store.graph(), p0, Some(r@), v0); + if fsteps::xpre(entry, ActionShape::AppendResult(r@), p0, v0) { + fbr::lemma_step_result(entry, store.graph(), p0, v0, Some(r@)); + } + } + } + Action::SwapThen => { + let a = match values.pop() { + Some(v) => v, + None => return Err(HistoryError::normalization_invariant()), + }; + let b = match values.pop() { + Some(v) => v, + None => return Err(HistoryError::normalization_invariant()), + }; + proof! { assert(values.view() =~= v0.take(v0.len() as int - 2)); } + values.push(a); + values.push(b); + proof! { + machine_driver_swap_effect(store.graph(), p0, v0); + assert(values.view() =~= v0.take(v0.len() as int - 2).push(v0[v0.len() - 1]).push(v0[v0.len() - 2])); + machine_driver_swap(store.graph(), p0, v0); + if fsteps::xpre(entry, ActionShape::SwapThen, p0, v0) { + fbr::lemma_step_swap(entry, store.graph(), p0, v0); + } + } + } + } + proof! { + lemma_guards_stable(entry, store.graph()); + assert forall|allowed: Set| guard_config(store.graph(), p0, v0, allowed) + && guard_task_vocab(store.graph(), self@).subset_of(allowed) + implies guard_config(store.graph(), transition_action_views(tasks.view()), values.view(), allowed) by { + broadcast use vstd::set::group_set_lemmas; + assert forall|i: int| 0 <= i < tasks.view().len() implies + guard_task_vocab(store.graph(), transition_action_views(tasks.view())[i]).subset_of(allowed) by { + if i < p0.len() { + assert(transition_action_views(tasks.view())[i] == p0[i]); + } + } + assert forall|i: int| 0 <= i < values.view().len() implies + guard_vocab(store.graph(), values.view()[i]@).subset_of(allowed) by { + if v0.contains(values.view()[i]) { + let j = choose|j: int| 0 <= j < v0.len() && v0[j] == values.view()[i]; + assert(guard_vocab(store.graph(), v0[j]@).subset_of(allowed)); + } + } + } + } + Ok(()) + } + } + + #[verus_verify] + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + transition_configuration_valid(old(store).graph(), transition_action_views(old(tasks).view()), old(values).view()), + old(tasks).view().len() > 0, + transition_program(old(store).graph(), transition_action_views(old(tasks).view()), old(values).view()) is Some, + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + model::graph_wf(final(store).graph()), final(store).valid_store(), + transition_configuration_valid(final(store).graph(), transition_action_views(final(tasks).view()), final(values).view()), + result is Ok ==> forall|allowed: Set| + guard_config(final(store).graph(), transition_action_views(old(tasks).view()), old(values).view(), allowed) + ==> guard_config(final(store).graph(), transition_action_views(final(tasks).view()), final(values).view(), allowed), + match result { + Ok(()) => transition_program_refines( + transition_program(old(store).graph(), transition_action_views(old(tasks).view()), old(values).view()), + transition_program(final(store).graph(), transition_action_views(final(tasks).view()), final(values).view())) + && machine_cost(final(store).graph(), transition_action_views(final(tasks).view()), final(values).view()) + < machine_cost(old(store).graph(), transition_action_views(old(tasks).view()), old(values).view()) + && (fsteps::xcfg(old(store).graph(), transition_action_views(old(tasks).view()), old(values).view()) + ==> fsteps::xstep(final(store).graph(), transition_action_views(old(tasks).view()), old(values).view(), + transition_action_views(final(tasks).view()), final(values).view())), + Err(_) => true, + }, + )] + fn next( + store: &mut G, + tasks: &mut WorkVec, + values: &mut WorkVec, + ) -> KernelResult<()> { + proof_decl! { let ghost entry = store.graph(); let ghost p0 = transition_action_views(tasks.view()); let ghost v0 = values.view(); } + let task = match tasks.pop() { + Some(v) => v, + None => return Err(HistoryError::normalization_invariant()), + }; + proof_decl! { let ghost shape = task@; let ghost pending = transition_action_views(tasks.view()); } + proof! { assert(p0 =~= pending.push(shape)); } + proof! { transition_lemma_stack_ready(store.graph(), pending, shape, v0); } + proof! { + assert forall|i: int| 0 <= i < pending.len() implies transition_action_valid(store.graph(), pending[i]) by { + assert(p0[i] == pending[i]); + assert(transition_action_valid(store.graph(), p0[i])); + } + } + task.step(store, tasks, values)?; + proof! { + assert forall|allowed: Set| guard_config(store.graph(), p0, v0, allowed) + implies guard_config(store.graph(), transition_action_views(tasks.view()), values.view(), allowed) by { + assert forall|i: int| 0 <= i < pending.len() implies guard_task_vocab(store.graph(), pending[i]).subset_of(allowed) by { + assert(p0[i] == pending[i]); + } + assert(guard_config(store.graph(), pending, v0, allowed)); + assert(guard_task_vocab(store.graph(), shape).subset_of(allowed)); + } + transition_lemma_program_stable(entry, store.graph(), p0, v0); + transition_lemma_effect_frame(store.graph(), shape, pending, v0, transition_action_views(tasks.view()), values.view()); + if fsteps::xcfg(entry, p0, v0) { + fbr::lemma_next(entry, store.graph(), pending, shape, v0, transition_action_views(tasks.view()), values.view()); + } + } + Ok(()) + } + + #[allow( + clippy::option_if_let_else, + reason = "Explicit matches preserve the Verus proof structure." + )] + #[verus_verify] + // Language correctness is conditional on success; error provenance follows the store capabilities. + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + transition_action_valid(old(store).graph(), self@), transition_action_pushes(self@), + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (result matches Err(e) ==> resource_error(e)), + model::graph_wf(final(store).graph()), final(store).valid_store(), + match result { Ok(id) => id@ < final(store).graph().transitions.len() + && transition_result(final(store).graph(), self@, id) + && (fsteps::xnf_task(old(store).graph(), self@) ==> fsteps::run_bound(final(store).graph(), self@, id@)), Err(_) => true }, + result matches Ok(id) ==> guard_vocab(final(store).graph(), id@).subset_of(guard_task_vocab(final(store).graph(), self@)), + )] + fn run(self, store: &mut G) -> KernelResult { + proof_decl! { let ghost entry = store.graph(); let ghost shape = self@; + let ghost original = transition_program(entry, seq![shape], Seq::empty()); } + proof_decl! { let ghost allowed = guard_task_vocab(entry, shape); } + let mut tasks = WorkVec::new(); + let mut values = WorkVec::new(); + tasks.push(self); + proof! { + assert(tasks.view() =~= seq![self]); + assert(transition_action_views(tasks.view())[0] == shape); + assert(transition_action_views(tasks.view()) =~= seq![shape]); + assert(transition_freeze_tasks(entry, seq![shape]) =~= seq![transition_freeze_action(entry, shape)]); + assert(transition_known_values(entry, Seq::::empty()) =~= Seq::::empty()); + guarded_lemma_run_singleton(transition_context_sem(), transition_freeze_action(entry, shape), Seq::::empty()); + assert(guarded_apply(transition_context_sem(), transition_freeze_action(entry, shape), Seq::::empty()) is Some); + assert(original is Some); + assert(values.view() =~= Seq::::empty()); + if fsteps::xnf_task(entry, shape) { fbr::lemma_run_start(entry, shape); } + } + let mut state = Ok(()); + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).valid_store() ==> store.valid_store(), + old(store).errors_are_non_owner() ==> state != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(state), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(state matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_resource() && old(store).valid_store() ==> (state matches Err(e) ==> resource_error(e)), + model::graph_wf(store.graph()), store.valid_store(), model::graph_extends(entry, store.graph()), model::graph_wf(entry), + transition_action_valid(entry, shape), + transition_configuration_valid(store.graph(), transition_action_views(tasks.view()), values.view()), + state.is_ok() ==> transition_program(store.graph(), transition_action_views(tasks.view()), values.view()) is Some, + state.is_ok() ==> transition_program_refines(original, + transition_program(store.graph(), transition_action_views(tasks.view()), values.view())), + fsteps::xnf_task(entry, shape) && state.is_ok() ==> fsteps::xrun(store.graph(), shape, transition_action_views(tasks.view()), values.view()), + state.is_ok() ==> guard_config(store.graph(), transition_action_views(tasks.view()), values.view(), allowed), + decreases if state.is_ok() { + machine_cost(store.graph(), transition_action_views(tasks.view()), values.view()) + 1 + } else { 0 }, + ))] + while !tasks.is_empty() && state.is_ok() { + proof_decl! { let ghost before = store.graph(); + let ghost before_program = transition_program(before, transition_action_views(tasks.view()), values.view()); + let ghost before_tasks = transition_action_views(tasks.view()); let ghost before_values = values.view(); } + state = Action::next(store, &mut tasks, &mut values); + proof! { + lemma_guard_config_stable(before, store.graph(), before_tasks, before_values, allowed); + lemma_guard_task_stable(entry, store.graph(), shape); + } + proof! { + transition_lemma_extends_transitive(entry, before, store.graph()); + if state.is_ok() { + guarded_lemma_program_transitive(transition_context_sem(), transition_context_valid(), original, + before_program, transition_program(store.graph(), transition_action_views(tasks.view()), values.view())); + } + if fsteps::xnf_task(entry, shape) && state.is_ok() { + fbr::lemma_run_step(entry, before, store.graph(), shape, before_tasks, before_values, + transition_action_views(tasks.view()), values.view()); + } + } + } + state?; + proof! { + assert(tasks.view().len() == 0); + assert(transition_freeze_tasks(store.graph(), transition_action_views(tasks.view())) =~= Seq::::empty()); + transition_lemma_program_stable(entry, store.graph(), seq![shape], Seq::empty()); + machine_driver_complete(store.graph(), shape, values.view()); + assert(transition_action_views(tasks.view()) =~= Seq::::empty()); + if fsteps::xnf_task(entry, shape) { fbr::lemma_run_end(store.graph(), shape, values.view()); } + lemma_guard_task_stable(entry, store.graph(), shape); + assert(guard_vocab(store.graph(), values.view().last()@).subset_of(allowed)); + } + match values.pop() { + Some(v) => Ok(v), + None => Err(HistoryError::normalization_invariant()), + } + } +} + +#[cfg(verus_keep_ghost)] +pub mod verify { + use super::*; + + verus! { + broadcast use junco_core::kernel::verify::group_kernel_views; + + #[verifier::opaque] + pub open spec fn guard_vocab(g: model::Graph, t: nat) -> Set { + vocab::transition_primitives(model::lift_transition(g, t)) + } + + #[verifier::opaque] + pub open spec fn test_vocab(g: model::Graph, t: nat) -> Set { + vocab::test_primitives(model::lift_test(g, t)) + } + + #[verifier::opaque] + pub open spec fn guard_union_vocab(g: model::Graph, ids: Seq) -> Set { + vocab::transition_primitives(language::Transition::Union(ids.map_values(|t: nat| model::lift_transition(g, t)))) + } + + pub open spec fn guard_task_vocab(g: model::Graph, task: ActionShape) -> Set { + match task { + ActionShape::Clean(t, p) => guard_vocab(g, t).union(test_vocab(g, p)), + ActionShape::Not(t) | ActionShape::Append(t, _) => guard_vocab(g, t), + ActionShape::Pair(a, b) => guard_vocab(g, a).union(guard_vocab(g, b)), + ActionShape::If(t) => test_vocab(g, t), + ActionShape::CleanIf(t, p) => test_vocab(g, t).union(test_vocab(g, p)), + ActionShape::Fold(ids, _) => guard_union_vocab(g, ids), + _ => Set::empty(), + } + } + + pub open spec fn guard_config(g: model::Graph, tasks: Seq, values: Seq, allowed: Set) -> bool { + (forall|i: int| 0 <= i < tasks.len() ==> guard_task_vocab(g, tasks[i]).subset_of(allowed)) + && (forall|i: int| 0 <= i < values.len() ==> guard_vocab(g, values[i]@).subset_of(allowed)) + } + + pub open spec fn guard_effect(g: model::Graph, pending: Seq, task: ActionShape, values: Seq, + after: Seq, out: Seq) -> bool { + forall|allowed: Set| guard_config(g, pending, values, allowed) + && guard_task_vocab(g, task).subset_of(allowed) ==> guard_config(g, after, out, allowed) + } + + pub proof fn lemma_guard_task_stable(a: model::Graph, b: model::Graph, task: ActionShape) + requires model::graph_wf(a), model::graph_extends(a, b), transition_action_valid(a, task), + ensures guard_task_vocab(a, task) == guard_task_vocab(b, task), + { + reveal(guard_union_vocab); + reveal(guard_vocab); reveal(test_vocab); + model::lemma_graph_wf_elim(a); + model::lemma_lift_stable_under_extends(a, b); + match task { + ActionShape::Fold(ids, _) => { + assert(ids.map_values(|t: nat| model::lift_transition(a, t)) + =~= ids.map_values(|t: nat| model::lift_transition(b, t))); + }, + _ => {}, + } + } + + pub proof fn lemma_guard_config_stable(a: model::Graph, b: model::Graph, tasks: Seq, values: Seq, allowed: Set) + requires model::graph_wf(a), model::graph_extends(a, b), transition_tasks_valid(a, tasks), transition_ids_valid(a, values), + ensures guard_config(a, tasks, values, allowed) == guard_config(b, tasks, values, allowed), + { + reveal(guard_vocab); reveal(test_vocab); + model::lemma_graph_wf_elim(a); + model::lemma_lift_stable_under_extends(a, b); + assert forall|i: int| 0 <= i < tasks.len() implies guard_task_vocab(a, tasks[i]) == guard_task_vocab(b, tasks[i]) by { + lemma_guard_task_stable(a, b, tasks[i]); + } + } + pub proof fn lemma_guard_children(g: model::Graph, id: nat) + requires model::graph_wf(g), id < g.transitions.len(), + ensures forall|i: int| #![trigger crate::progress::verify::transition_edges(g, id)[i]] 0 <= i < crate::progress::verify::transition_edges(g, id).len() + ==> guard_vocab(g, crate::progress::verify::transition_edges(g, id)[i]).subset_of(guard_vocab(g, id)), + forall|i: int| #![trigger crate::progress::verify::transition_tests(g, id)[i]] 0 <= i < crate::progress::verify::transition_tests(g, id).len() + ==> test_vocab(g, crate::progress::verify::transition_tests(g, id)[i]).subset_of(guard_vocab(g, id)), + match g.transitions[id as int] { + model::TransitionNode::If(t, a, b) => test_vocab(g, t).subset_of(guard_vocab(g, id)) + && guard_vocab(g, a).subset_of(guard_vocab(g, id)) && guard_vocab(g, b).subset_of(guard_vocab(g, id)), + model::TransitionNode::Not(t) | model::TransitionNode::Append(t, _) => guard_vocab(g, t).subset_of(guard_vocab(g, id)), + model::TransitionNode::Union(cs) | model::TransitionNode::Intersect(cs) => forall|i: int| 0 <= i < cs.len() + ==> guard_vocab(g, cs[i]).subset_of(guard_vocab(g, id)), + _ => true, + }, + { + broadcast use vstd::set::group_set_lemmas; + reveal(guard_vocab); reveal(test_vocab); + model::lemma_graph_transition_wf(g, id); + assert forall|i: int| #![trigger crate::progress::verify::transition_edges(g, id)[i]] + 0 <= i < crate::progress::verify::transition_edges(g, id).len() implies + guard_vocab(g, crate::progress::verify::transition_edges(g, id)[i]).subset_of(guard_vocab(g, id)) by { + let child = crate::progress::verify::transition_edges(g, id)[i]; + assert forall|p: model::Primitive| guard_vocab(g, child).contains(p) implies guard_vocab(g, id).contains(p) by { + vocab::lemma_transition_primitives_lift(g, child, p); + assert(crate::progress::verify::transition_reaches_primitive(g, id, p)); + vocab::lemma_transition_primitives_lift(g, id, p); + } + } + assert forall|i: int| #![trigger crate::progress::verify::transition_tests(g, id)[i]] + 0 <= i < crate::progress::verify::transition_tests(g, id).len() implies + test_vocab(g, crate::progress::verify::transition_tests(g, id)[i]).subset_of(guard_vocab(g, id)) by { + let child = crate::progress::verify::transition_tests(g, id)[i]; + assert forall|p: model::Primitive| test_vocab(g, child).contains(p) implies guard_vocab(g, id).contains(p) by { + vocab::lemma_test_primitives_lift(g, child, p); + assert(crate::progress::verify::transition_reaches_primitive(g, id, p)); + vocab::lemma_transition_primitives_lift(g, id, p); + } + } + match g.transitions[id as int] { + model::TransitionNode::If(t, a, b) => { + assert(crate::progress::verify::transition_tests(g, id)[0] == t); + assert(crate::progress::verify::transition_edges(g, id)[0] == a); + assert(crate::progress::verify::transition_edges(g, id)[1] == b); + }, + model::TransitionNode::Not(t) | model::TransitionNode::Append(t, _) => { + assert(crate::progress::verify::transition_edges(g, id)[0] == t); + }, + model::TransitionNode::Union(cs) | model::TransitionNode::Intersect(cs) => { + assert forall|i: int| 0 <= i < cs.len() implies guard_vocab(g, cs[i]).subset_of(guard_vocab(g, id)) by { + assert(crate::progress::verify::transition_edges(g, id)[i] == cs[i]); + } + }, + _ => {}, + } + } + + pub proof fn lemma_guard_union(g: model::Graph, ids: Seq, allowed: Set) + ensures guard_union_vocab(g, ids).subset_of(allowed) + == (forall|i: int| 0 <= i < ids.len() ==> guard_vocab(g, ids[i]).subset_of(allowed)), + { + broadcast use vstd::set::group_set_lemmas; + reveal_with_fuel(vocab::transition_primitives, 2); + reveal(guard_union_vocab); + reveal(guard_vocab); + let cs = ids.map_values(|t: nat| model::lift_transition(g, t)); + let tree = language::Transition::Union(cs); + assert(vocab::transition_primitives(tree) == vocab::transition_primitive_prefix(tree, cs.len())); + assert forall|p: model::Primitive| vocab::transition_primitives(tree).contains(p) + == (exists|i: int| 0 <= i < ids.len() && guard_vocab(g, ids[i]).contains(p)) by { + vocab::lemma_transition_primitive_prefix(tree, cs.len(), p); + if vocab::transition_primitives(tree).contains(p) { + let i = choose|i: int| 0 <= i < cs.len() && vocab::transition_primitives(cs[i]).contains(p); + assert(cs[i] == model::lift_transition(g, ids[i])); + assert(exists|j: int| 0 <= j < ids.len() && guard_vocab(g, ids[j]).contains(p)); + } + if exists|i: int| 0 <= i < ids.len() && guard_vocab(g, ids[i]).contains(p) { + let i = choose|i: int| 0 <= i < ids.len() && guard_vocab(g, ids[i]).contains(p); + assert(cs[i] == model::lift_transition(g, ids[i])); + assert(exists|j: int| 0 <= j < cs.len() && vocab::transition_primitives(cs[j]).contains(p)); + } + } + if !vocab::transition_primitives(tree).subset_of(allowed) { + let p = choose|p: model::Primitive| vocab::transition_primitives(tree).contains(p) && !allowed.contains(p); + let i = choose|i: int| 0 <= i < ids.len() && guard_vocab(g, ids[i]).contains(p); + } + assert forall|i: int| 0 <= i < ids.len() implies + vocab::transition_primitives(tree).subset_of(allowed) ==> guard_vocab(g, ids[i]).subset_of(allowed) by { + assert forall|p: model::Primitive| guard_vocab(g, ids[i]).contains(p) implies vocab::transition_primitives(tree).contains(p) by {} + } + } + + pub proof fn lemma_guard_piece(g: model::Graph, root: nat, inter: bool, t: nat) + requires model::graph_wf(g), root < g.transitions.len(), fmach::tpiece(g, root, inter, t), + ensures t < g.transitions.len(), guard_vocab(g, t).subset_of(guard_vocab(g, root)), + decreases root, + { + broadcast use vstd::set::group_set_lemmas; + if t != root { + model::lemma_graph_transition_wf(g, root); + lemma_guard_children(g, root); + match g.transitions[root as int] { + model::TransitionNode::Union(cs) | model::TransitionNode::Intersect(cs) => { + let i = choose|i: int| 0 <= i < cs.len() && cs[i] < root && fmach::tpiece(g, cs[i], inter, t); + lemma_guard_piece(g, cs[i], inter, t); + assert(crate::progress::verify::transition_edges(g, root)[i] == cs[i]); + }, + _ => {}, + } + } + } + + pub proof fn lemma_guard_collected(g: model::Graph, orig: Seq, inter: bool, flat: Seq, constants: Seq) + requires model::graph_wf(g), model::bounded(orig, g.transitions.len()), + fcol::collect_members(g, orig, inter, Seq::empty(), flat, constants), + ensures forall|i: int| 0 <= i < flat.len() ==> guard_vocab(g, flat[i]@).subset_of( + guard_task_vocab(g, ActionShape::Fold(orig, 0))), + { + broadcast use vstd::set::group_set_lemmas; + let allowed = guard_task_vocab(g, ActionShape::Fold(orig, 0)); + lemma_guard_union(g, orig, allowed); + assert forall|i: int| 0 <= i < flat.len() implies guard_vocab(g, flat[i]@).subset_of(allowed) by { + let j = choose|j: int| 0 <= j < orig.len() && fmach::tpiece(g, orig[j], inter, flat[i]@); + lemma_guard_piece(g, orig[j], inter, flat[i]@); + assert(guard_vocab(g, orig[j]).subset_of(allowed)); + } + } + + pub proof fn lemma_guard_node(g: model::Graph, id: nat, allowed: Set) + requires model::graph_wf(g), id < g.transitions.len(), + forall|i: int| #![trigger crate::progress::verify::transition_edges(g, id)[i]] 0 <= i < crate::progress::verify::transition_edges(g, id).len() + ==> guard_vocab(g, crate::progress::verify::transition_edges(g, id)[i]).subset_of(allowed), + forall|i: int| #![trigger crate::progress::verify::transition_tests(g, id)[i]] 0 <= i < crate::progress::verify::transition_tests(g, id).len() + ==> test_vocab(g, crate::progress::verify::transition_tests(g, id)[i]).subset_of(allowed), + ensures guard_vocab(g, id).subset_of(allowed), + { + broadcast use vstd::set::group_set_lemmas; + reveal(guard_vocab); reveal(test_vocab); + model::lemma_graph_transition_wf(g, id); + assert forall|p: model::Primitive| guard_vocab(g, id).contains(p) implies allowed.contains(p) by { + vocab::lemma_transition_primitives_lift(g, id, p); + reveal_with_fuel(crate::progress::verify::transition_reaches_primitive, 1); + if exists|i: int| 0 <= i < crate::progress::verify::transition_tests(g, id).len() + && crate::progress::verify::test_reaches_primitive(g, crate::progress::verify::transition_tests(g, id)[i], p) { + let i = choose|i: int| 0 <= i < crate::progress::verify::transition_tests(g, id).len() + && crate::progress::verify::test_reaches_primitive(g, crate::progress::verify::transition_tests(g, id)[i], p); + vocab::lemma_test_primitives_lift(g, crate::progress::verify::transition_tests(g, id)[i], p); + } else { + let i = choose|i: int| 0 <= i < crate::progress::verify::transition_edges(g, id).len() + && crate::progress::verify::transition_edges(g, id)[i] < id + && crate::progress::verify::transition_reaches_primitive(g, crate::progress::verify::transition_edges(g, id)[i], p); + vocab::lemma_transition_primitives_lift(g, crate::progress::verify::transition_edges(g, id)[i], p); + } + } + } + + pub open spec fn guard_child_extra(g: model::Graph, action: ChildShape) -> Set { + match action { + ChildShape::Clean(path) => test_vocab(g, path), + ChildShape::PairLeft(other) | ChildShape::PairRight(other) => guard_vocab(g, other), + _ => Set::empty(), + } + } + + pub proof fn lemma_guard_child_actions(g: model::Graph, id: nat, action: ChildShape) + requires model::graph_wf(g), id < g.transitions.len(), transition_child_action_valid(g, action), + ensures forall|i: int| 0 <= i < transition_child_actions(g, id, action).len() + ==> guard_task_vocab(g, transition_child_actions(g, id, action)[i]).subset_of( + guard_vocab(g, id).union(guard_child_extra(g, action))), + { + broadcast use vstd::set::group_set_lemmas; + transition_lemma_children(g, id); + lemma_guard_children(g, id); + let cs = transition_children(g, id); + assert forall|i: int| 0 <= i < transition_child_actions(g, id, action).len() implies + guard_task_vocab(g, transition_child_actions(g, id, action)[i]).subset_of( + guard_vocab(g, id).union(guard_child_extra(g, action))) by { + let j = cs.len() as int - 1 - i; + assert(transition_child_actions(g, id, action)[i] == transition_child_shape(action, cs[j])); + assert(crate::progress::verify::transition_edges(g, id)[j] == cs[j]); + } + } + + pub proof fn lemma_guard_scheduled(g: model::Graph, id: nat, action: ChildShape, marker: ActionShape, task: ActionShape, + pending: Seq, values: Seq) + requires model::graph_wf(g), id < g.transitions.len(), transition_child_action_valid(g, action), + guard_task_vocab(g, marker) == Set::empty(), + guard_vocab(g, id).union(guard_child_extra(g, action)).subset_of(guard_task_vocab(g, task)), + ensures guard_effect(g, pending, task, values, pending.push(marker) + transition_child_actions(g, id, action), values), + { + lemma_guard_child_actions(g, id, action); + let children = transition_child_actions(g, id, action); + let after = pending.push(marker) + children; + assert forall|allowed: Set| guard_config(g, pending, values, allowed) + && guard_task_vocab(g, task).subset_of(allowed) implies guard_config(g, after, values, allowed) by { + broadcast use vstd::set::group_set_lemmas; + assert forall|i: int| 0 <= i < after.len() implies guard_task_vocab(g, after[i]).subset_of(allowed) by { + if i < pending.len() { + assert(after[i] == pending[i]); + } else if i == pending.len() { + assert(after[i] == marker); + } else { + let j = i - pending.len() - 1; + assert(after[i] == children[j]); + } + } + } + } + + pub proof fn lemma_test_connective_guards(a: model::Graph, b: model::Graph, ids: Seq, and: bool, t: nat) + requires model::graph_wf(a), model::graph_wf(b), model::graph_extends(a, b), test_ids_valid(a, ids), + t < b.tests.len(), test_connective_result(a, b, ids, and, t), + ensures test_vocab(b, t).subset_of(vocab::test_primitives(model::Test::And( + ids.map_values(|id: TestId| model::lift_test(a, id@))))), + { + broadcast use vstd::set::group_set_lemmas; + reveal(test_vocab); + let cs = ids.map_values(|id: TestId| model::lift_test(a, id@)); + let parent = model::Test::And(cs); + assert forall|p: model::Primitive| test_vocab(b, t).contains(p) implies vocab::test_primitives(parent).contains(p) by { + vocab::lemma_test_connective_primitives(a, b, ids, and, t, p); + let i = choose|i: int| 0 <= i < ids.len() && vocab::test_primitives(model::lift_test(a, ids[i]@)).contains(p); + vocab::lemma_test_primitive_prefix(parent, cs.len(), p); + assert(cs[i] == model::lift_test(a, ids[i]@)); + } + } + + pub proof fn lemma_test_connective_pair(a: model::Graph, b: model::Graph, x: TestId, y: TestId, and: bool, t: nat) + requires model::graph_wf(a), model::graph_wf(b), model::graph_extends(a, b), x@ < a.tests.len(), y@ < a.tests.len(), + t < b.tests.len(), test_connective_result(a, b, seq![x, y], and, t), + ensures test_vocab(b, t).subset_of(test_vocab(a, x@).union(test_vocab(a, y@))), + { + broadcast use vstd::set::group_set_lemmas; + lemma_test_connective_guards(a, b, seq![x, y], and, t); + let cs = seq![x, y].map_values(|id: TestId| model::lift_test(a, id@)); + assert(cs =~= seq![model::lift_test(a, x@), model::lift_test(a, y@)]); + lemma_test_definition(a, x@); lemma_test_definition(a, y@); + vocab::lemma_test_pair_vocab(model::lift_test(a, x@), model::lift_test(a, y@)); + } + + pub proof fn lemma_test_definition(g: model::Graph, id: nat) + ensures test_vocab(g, id) == vocab::test_primitives(model::lift_test(g, id)), + { reveal(test_vocab); } + + pub proof fn lemma_guard_definition(g: model::Graph, id: nat) + ensures guard_vocab(g, id) == vocab::transition_primitives(model::lift_transition(g, id)), + { reveal(guard_vocab); } + + pub proof fn lemma_guard_subset(g: model::Graph, id: nat, allowed: Set) + requires guard_vocab(g, id).subset_of(allowed), + ensures vocab::transition_primitives(model::lift_transition(g, id)).subset_of(allowed), + { reveal(guard_vocab); } + + pub proof fn lemma_guard_constants(g: model::Graph) + requires model::graph_wf(g), + ensures guard_vocab(g, g.constants.transition_empty) == Set::empty(), + guard_vocab(g, g.constants.transition_all) == Set::empty(), + guard_vocab(g, g.constants.transition_epsilon) == Set::empty(), + test_vocab(g, g.constants.test_true) == Set::empty(), + test_vocab(g, g.constants.test_false) == Set::empty(), + { + broadcast use vstd::set::group_set_lemmas; + reveal(guard_vocab); reveal(test_vocab); + model::lemma_graph_wf_elim(g); + transition_unfold(g, g.constants.transition_empty); + transition_unfold(g, g.constants.transition_all); + transition_unfold(g, g.constants.transition_epsilon); + reveal_with_fuel(vocab::transition_primitives, 1); + reveal_with_fuel(vocab::test_primitives, 1); + reveal_with_fuel(model::lift_test, 1); + } + + pub proof fn lemma_guards_stable(a: model::Graph, b: model::Graph) + requires model::graph_wf(a), model::graph_extends(a, b), + ensures forall|id: nat| id < a.transitions.len() ==> guard_vocab(a, id) == guard_vocab(b, id), + forall|id: nat| id < a.tests.len() ==> test_vocab(a, id) == test_vocab(b, id), + { + reveal(guard_vocab); reveal(test_vocab); + model::lemma_graph_wf_elim(a); + model::lemma_lift_stable_under_extends(a, b); + } + + pub proof fn lemma_guard_local_if(g: model::Graph, test: nat, a: nat, b: nat, out: nat) + requires model::graph_wf(g), test < g.tests.len(), a < g.transitions.len(), b < g.transitions.len(), out < g.transitions.len(), + out == a || out == b || g.transitions[out as int] == model::TransitionNode::If(test, a, b), + ensures guard_vocab(g, out).subset_of(test_vocab(g, test).union(guard_vocab(g, a)).union(guard_vocab(g, b))), + { + broadcast use vstd::set::group_set_lemmas; + if out != a && out != b { + let allowed = test_vocab(g, test).union(guard_vocab(g, a)).union(guard_vocab(g, b)); + lemma_guard_node(g, out, allowed); + } + } + + #[verifier::opaque] + pub open spec fn guard_node_vocab(g: model::Graph, node: model::TransitionNode) -> Set { + match node { + model::TransitionNode::Const(_) => Set::empty(), + model::TransitionNode::If(t, a, b) => test_vocab(g, t).union(guard_vocab(g, a)).union(guard_vocab(g, b)), + model::TransitionNode::Union(cs) | model::TransitionNode::Intersect(cs) => guard_task_vocab(g, ActionShape::Fold(cs, 0)), + model::TransitionNode::Not(t) | model::TransitionNode::Append(t, _) => guard_vocab(g, t), + } + } + + pub proof fn lemma_guard_node_unfold(g: model::Graph, id: nat) + requires model::graph_wf(g), id < g.transitions.len(), + ensures guard_vocab(g, id) == guard_node_vocab(g, g.transitions[id as int]), + { + reveal(guard_node_vocab); + broadcast use vstd::set::group_set_lemmas; + model::lemma_graph_transition_wf(g, id); + lemma_guard_children(g, id); + let node = g.transitions[id as int]; + let allowed = guard_node_vocab(g, node); + match node { + model::TransitionNode::Union(cs) | model::TransitionNode::Intersect(cs) => { + lemma_guard_union(g, cs, guard_vocab(g, id)); + lemma_guard_union(g, cs, allowed); + assert forall|i: int| 0 <= i < cs.len() implies + crate::progress::verify::transition_edges(g, id)[i] == cs[i] by {} + }, + model::TransitionNode::If(t, a, b) => { + assert(crate::progress::verify::transition_tests(g, id)[0] == t); + assert(crate::progress::verify::transition_edges(g, id)[0] == a); + assert(crate::progress::verify::transition_edges(g, id)[1] == b); + }, + model::TransitionNode::Not(t) | model::TransitionNode::Append(t, _) => { + assert(crate::progress::verify::transition_edges(g, id)[0] == t); + }, + _ => {}, + } + lemma_guard_node(g, id, allowed); + assert(allowed.subset_of(guard_vocab(g, id))); + assert(guard_vocab(g, id) =~= allowed); + } + + pub open spec fn test_ids_valid(g: model::Graph, ids: Seq) -> bool { + forall|i: int| 0 <= i < ids.len() ==> ids[i]@ < g.tests.len() + } + pub open spec fn regex_ids_valid(g: model::Graph, ids: Seq) -> bool { + forall|i: int| 0 <= i < ids.len() ==> ids[i]@ < g.regexes.len() + } + pub open spec fn transition_ids_valid(g: model::Graph, ids: Seq) -> bool { + forall|i: int| 0 <= i < ids.len() ==> ids[i]@ < g.transitions.len() + } + pub open spec fn test_combo( + g: model::Graph, theta: Subst, ids: Seq, e: EventView, and: bool, + ) -> bool { + if and { + forall|i: int| 0 <= i < ids.len() + ==> model::test_holds(theta, model::lift_test(g, ids[i]@), e) + } else { + exists|i: int| 0 <= i < ids.len() + && model::test_holds(theta, model::lift_test(g, ids[i]@), e) + } + } + pub open spec fn regex_combo( + g: model::Graph, theta: Subst, ids: Seq, w: Seq, intersect: bool, + ) -> bool { + if intersect { + forall|i: int| 0 <= i < ids.len() ==> model::regex_lang(g, theta, ids[i]@, w) + } else { + exists|i: int| 0 <= i < ids.len() && model::regex_lang(g, theta, ids[i]@, w) + } + } + pub open spec fn concat_combo( + g: model::Graph, theta: Subst, ids: Seq, w: Seq, + ) -> bool { + language::numeric_lang(model::gsem(theta), + language::Regex::Concat(model::lift_regexes(g, model::regex_ids(ids))), w) + } + pub open spec fn transition_lang( + g: model::Graph, theta: Subst, id: TransitionId, e: EventView, w: Seq, + ) -> bool { + language::numeric_lang(model::gsem(theta), language::interp_transition( + model::gsem(theta), e, model::lift_transition(g, id@)), w) + } + pub open spec fn transition_combo( + g: model::Graph, theta: Subst, ids: Seq, e: EventView, w: Seq, intersect: bool, + ) -> bool { + if intersect { + forall|i: int| 0 <= i < ids.len() ==> transition_lang(g, theta, ids[i], e, w) + } else { + exists|i: int| 0 <= i < ids.len() && transition_lang(g, theta, ids[i], e, w) + } + } + + // Boolean normalization proofs. + pub open spec fn test_distinct_heads(left: model::TestHeadNode, right: model::TestHeadNode) -> bool { + match (left, right) { + (model::TestHeadNode::Atom(model::Primitive::Eq(p, model::GTerm::Constant(c)), _), + model::TestHeadNode::Atom(model::Primitive::Eq(q, model::GTerm::Constant(d)), _)) + => p == q && c != d, + _ => false, + } + } + + pub proof fn test_lemma_distinct_atoms( + theta: Subst, left: model::TestHeadNode, + right: model::TestHeadNode, event: EventView, + ) + requires language::event_wf(theta, theta.len()), test_distinct_heads(left, right), + ensures match (left, right) { + (model::TestHeadNode::Atom(p, _), model::TestHeadNode::Atom(q, _)) + => !(model::primitive_holds(theta, p, event) + && model::primitive_holds(theta, q, event)), + _ => false, + }, + { + match (left, right) { + (model::TestHeadNode::Atom(model::Primitive::Eq(p, model::GTerm::Constant(c)), _), + model::TestHeadNode::Atom(model::Primitive::Eq(q, model::GTerm::Constant(d)), _)) => { + model::lemma_constant_atoms_disjoint(theta, p, c, d, event); + }, + _ => {}, + } + } + + pub open spec fn structural_eq() -> bool { + T::obeys_eq_spec() && forall|a: T, b: T| a.eq_spec(&b) == (a == b) + } + + pub proof fn lemma_dedup_push(s: Seq, value: T) + requires structural_eq::(), + ensures dedup_spec(s.push(value)) + == if s.len() != 0 && s.last() == value { + dedup_spec(s) + } else { + dedup_spec(s).push(value) + }, + { + reveal(dedup_spec); + assert(s.push(value).drop_last() =~= s); + } + + pub proof fn lemma_dedup_properties(s: Seq) + requires structural_eq::(), + ensures + dedup_spec(s).len() <= s.len(), + dedup_spec(s).len() == 0 <==> s.len() == 0, + s.len() > 0 ==> dedup_spec(s).last() == s.last(), + forall|v: T| dedup_spec(s).contains(v) <==> s.contains(v), + forall|i: int| 0 < i < dedup_spec(s).len() + ==> dedup_spec(s)[i - 1] + != #[trigger] dedup_spec(s)[i], + decreases s.len(), + { + if s.len() > 0 { + let prior = s.drop_last(); + lemma_dedup_properties(prior); + lemma_dedup_push(prior, s.last()); + assert(prior.push(s.last()) =~= s); + let dedup = dedup_spec(prior); + let out = dedup_spec(s); + assert forall|v: T| out.contains(v) <==> s.contains(v) by { + if out.contains(v) { + let i = choose|i: int| 0 <= i < out.len() && out[i] == v; + if i < dedup.len() { + assert(dedup.contains(v)); + assert(prior.contains(v)); + let j = choose|j: int| 0 <= j < prior.len() && prior[j] == v; + assert(s[j] == v); + } else { assert(s[s.len() - 1] == v); } + } + if s.contains(v) { + let i = choose|i: int| 0 <= i < s.len() && s[i] == v; + if i < prior.len() || (prior.len() > 0 && prior.last() == s.last()) { + if i < prior.len() { assert(prior[i] == v); } + else { assert(prior[prior.len() - 1] == v); } + assert(prior.contains(v)); + assert(dedup.contains(v)); + let j = choose|j: int| 0 <= j < dedup.len() && dedup[j] == v; + assert(out[j] == v); + } else { assert(out[out.len() - 1] == v); } + } + } + } + } + + pub proof fn lemma_dedup_ordered(s: Seq, relation: spec_fn(T, T) -> bool) + requires structural_eq::(), + forall|i: int, j: int| 0 <= i < j < s.len() ==> relation(s[i], s[j]), + ensures forall|i: int, j: int| + 0 <= i < j < dedup_spec(s).len() + ==> relation(dedup_spec(s)[i], + dedup_spec(s)[j]), + decreases s.len(), + { + if s.len() > 0 { + let prior = s.drop_last(); + lemma_dedup_properties(prior); + lemma_dedup_ordered(prior, relation); + lemma_dedup_push(prior, s.last()); + assert(prior.push(s.last()) =~= s); + assert forall|i: int, j: int| + 0 <= i < j < dedup_spec(s).len() + implies relation(dedup_spec(s)[i], + dedup_spec(s)[j]) by { + let dedup = dedup_spec(prior); + if j == dedup.len() { + assert(dedup.contains(dedup[i])); + assert(prior.contains(dedup[i])); + let k = choose|k: int| 0 <= k < prior.len() && prior[k] == dedup[i]; + assert(relation(s[k], s[s.len() - 1])); + } + } + } + } + + pub proof fn lemma_dedup_strict(s: Seq, key: spec_fn(T) -> nat) + requires structural_eq::(), + forall|a: T, b: T| #[trigger] key(a) == #[trigger] key(b) ==> a == b, + forall|i: int, j: int| 0 <= i < j < s.len() ==> #[trigger] key(s[i]) <= #[trigger] key(s[j]), + ensures forall|i: int, j: int| + 0 <= i < j < dedup_spec(s).len() + ==> #[trigger] key(dedup_spec(s)[i]) + < #[trigger] key(dedup_spec(s)[j]), + { + lemma_dedup_properties(s); + lemma_dedup_ordered(s, |a: T, b: T| key(a) <= key(b)); + let out = dedup_spec(s); + assert forall|i: int, j: int| 0 <= i < j < out.len() + implies key(out[i]) < key(out[j]) by { + if key(out[i]) == key(out[j]) { + assert(key(out[i]) == key(out[i + 1])); + assert(out[i] == out[i + 1]); + } + } + } + + + pub open spec fn test_children(g: model::Graph, id: TestId) -> Seq { + if id@ < g.tests.len() { + match g.tests[id@ as int] { + model::TestNode::And(cs) | model::TestNode::Or(cs) => cs, + _ => Seq::empty(), + } + } else { Seq::empty() } + } + + pub open spec fn test_child_count(g: model::Graph, id: TestId, count: nat) -> bool { + id@ < g.tests.len() && match g.tests[id@ as int] { + model::TestNode::And(cs) | model::TestNode::Or(cs) => cs.len() == count, + _ => false, + } + } + + pub proof fn test_lemma_children(g: model::Graph, id: TestId, count: nat) + requires model::graph_wf(g), test_child_count(g, id, count), + ensures test_children(g, id).len() == count, + model::nondecreasing(test_children(g, id)), + model::bounded(test_children(g, id), id@), + forall|i: int| 0 <= i < count + ==> model::test_node_child(g.tests[id@ as int], i as nat) == Some(test_children(g, id)[i]), + { + model::lemma_graph_test_wf(g, id@); + } + + pub proof fn lemma_multiset_members(left: Seq, right: Seq) + requires left.to_multiset() == right.to_multiset(), + ensures forall|v: T| left.contains(v) <==> right.contains(v), + { + assert forall|v: T| left.contains(v) <==> right.contains(v) by { + vstd::seq_lib::to_multiset_contains(left, v); + vstd::seq_lib::to_multiset_contains(right, v); + } + } + + pub(crate) proof fn lemma_combo_inclusion( + left: Seq, right: Seq, holds: spec_fn(T) -> bool, all: bool, + ) + requires forall|value: T| left.contains(value) ==> right.contains(value), + ensures if all { + (forall|i: int| 0 <= i < right.len() ==> holds(right[i])) + ==> (forall|i: int| 0 <= i < left.len() ==> holds(left[i])) + } else { + (exists|i: int| 0 <= i < left.len() && holds(left[i])) + ==> (exists|i: int| 0 <= i < right.len() && holds(right[i])) + }, + { + if all { + if forall|i: int| 0 <= i < right.len() ==> holds(right[i]) { + assert forall|i: int| 0 <= i < left.len() implies holds(left[i]) by { + assert(left.contains(left[i])); + assert(right.contains(left[i])); + let j = right.lemma_contains_to_index(left[i]); + } + } + } else if exists|i: int| 0 <= i < left.len() && holds(left[i]) { + let i = choose|i: int| 0 <= i < left.len() && holds(left[i]); + assert(left.contains(left[i])); + assert(right.contains(left[i])); + let j = right.lemma_contains_to_index(left[i]); + assert(holds(right[j])); + } + } + + pub(crate) proof fn lemma_combo_pointwise( + count: nat, left: spec_fn(int) -> bool, right: spec_fn(int) -> bool, all: bool, + ) + requires forall|i: int| #![trigger left(i)] #![trigger right(i)] + 0 <= i < count ==> left(i) == right(i), + ensures + (if all { forall|i: int| 0 <= i < count ==> #[trigger] left(i) } + else { exists|i: int| 0 <= i < count && #[trigger] left(i) }) + == + (if all { forall|i: int| 0 <= i < count ==> #[trigger] right(i) } + else { exists|i: int| 0 <= i < count && #[trigger] right(i) }), + { + if all { + if forall|i: int| 0 <= i < count ==> #[trigger] left(i) { + assert forall|i: int| 0 <= i < count implies #[trigger] right(i) by {} + } + if forall|i: int| 0 <= i < count ==> #[trigger] right(i) { + assert forall|i: int| 0 <= i < count implies #[trigger] left(i) by {} + } + } else { + if exists|i: int| 0 <= i < count && #[trigger] left(i) { + let i = choose|i: int| 0 <= i < count && #[trigger] left(i); + assert(right(i)); + } + if exists|i: int| 0 <= i < count && #[trigger] right(i) { + let i = choose|i: int| 0 <= i < count && #[trigger] right(i); + assert(left(i)); + } + } + } + + + pub proof fn test_lemma_combo_inclusion( + g: model::Graph, theta: Subst, event: EventView, + left: Seq, right: Seq, and: bool, + ) + requires forall|id: TestId| left.contains(id) ==> right.contains(id), + ensures if and { + test_combo(g, theta, right, event, and) ==> test_combo(g, theta, left, event, and) + } else { + test_combo(g, theta, left, event, and) ==> test_combo(g, theta, right, event, and) + }, + { + lemma_combo_inclusion(left, right, + |id: TestId| model::test_holds(theta, model::lift_test(g, id@), event), and); + } + + pub proof fn test_lemma_combo_membership( + g: model::Graph, theta: Subst, event: EventView, + left: Seq, right: Seq, and: bool, + ) + requires forall|id: TestId| left.contains(id) <==> right.contains(id), + ensures test_combo(g, theta, left, event, and) == test_combo(g, theta, right, event, and), + { + test_lemma_combo_inclusion(g, theta, event, left, right, and); + test_lemma_combo_inclusion(g, theta, event, right, left, and); + } + + pub proof fn test_lemma_combo_permutation( + g: model::Graph, theta: Subst, event: EventView, + left: Seq, right: Seq, and: bool, + ) + requires left.to_multiset() == right.to_multiset(), + ensures test_combo(g, theta, left, event, and) == test_combo(g, theta, right, event, and), + { + lemma_multiset_members(left, right); + test_lemma_combo_membership(g, theta, event, left, right, and); + } + + pub proof fn test_lemma_semantics_unfold(theta: Subst, event: EventView, test: model::Test) + ensures match test { + model::Test::And(cs) => model::test_holds(theta, test, event) + == (forall|i: int| 0 <= i < cs.len() ==> model::test_holds(theta, cs[i], event)), + model::Test::Or(cs) => model::test_holds(theta, test, event) + == (exists|i: int| 0 <= i < cs.len() && model::test_holds(theta, cs[i], event)), + _ => true, + }, + { + match test { model::Test::And(_) => {}, model::Test::Or(_) => {}, _ => {} } + } + + pub proof fn test_lemma_compound_child(theta: Subst, event: EventView, + children: Seq, index: int) + requires 0 <= index < children.len(), + ensures model::test_holds(theta, model::Test::And(children), event) + ==> model::test_holds(theta, children[index], event), + model::test_holds(theta, children[index], event) + ==> model::test_holds(theta, model::Test::Or(children), event), + { + test_lemma_semantics_unfold(theta, event, model::Test::And(children)); + test_lemma_semantics_unfold(theta, event, model::Test::Or(children)); + } + + pub proof fn test_lemma_compound_semantics( + g: model::Graph, theta: Subst, event: EventView, + parent: TestId, children: Seq, and: bool, + ) + requires model::graph_wf(g), parent@ < g.tests.len(), + g.tests[parent@ as int] == if and { model::TestNode::And(model::test_ids(children)) } + else { model::TestNode::Or(model::test_ids(children)) }, + ensures model::test_holds(theta, model::lift_test(g, parent@), event) + == test_combo(g, theta, children, event, and), + { + model::lemma_graph_test_wf(g, parent@); + let lifted = model::lift_tests(g, model::test_ids(children), parent@); + assert forall|i: int| 0 <= i < children.len() + implies lifted[i] == model::lift_test(g, children[i]@) by {} + assert(model::lift_test(g, parent@) == if and { model::Test::And(lifted) } else { model::Test::Or(lifted) }); + assert(lifted.len() == children.len()); + test_lemma_semantics_unfold(theta, event, model::Test::And(lifted)); + test_lemma_semantics_unfold(theta, event, model::Test::Or(lifted)); + if and { + if test_combo(g, theta, children, event, true) { + assert forall|i: int| 0 <= i < lifted.len() + implies model::test_holds(theta, lifted[i], event) by { + assert(model::test_holds(theta, model::lift_test(g, children[i]@), event)); + } + assert(model::test_holds(theta, model::Test::And(lifted), event)); + } else { + let i = choose|i: int| 0 <= i < children.len() + && !model::test_holds(theta, model::lift_test(g, children[i]@), event); + test_lemma_compound_child(theta, event, lifted, i); + assert(!model::test_holds(theta, model::Test::And(lifted), event)); + } + } else { + if test_combo(g, theta, children, event, false) { + let i = choose|i: int| 0 <= i < children.len() + && model::test_holds(theta, model::lift_test(g, children[i]@), event); + test_lemma_compound_child(theta, event, lifted, i); + assert(model::test_holds(theta, model::Test::Or(lifted), event)); + } else { + assert forall|i: int| 0 <= i < lifted.len() + implies !model::test_holds(theta, lifted[i], event) by { + assert(!model::test_holds(theta, model::lift_test(g, children[i]@), event)); + } + assert(!model::test_holds(theta, model::Test::Or(lifted), event)); + } + } + } + + pub proof fn test_lemma_strict_members_equal(left: Seq, right: Seq) + requires + forall|i: int, j: int| 0 <= i < j < left.len() ==> #[trigger] left[i] < #[trigger] left[j], + forall|i: int, j: int| 0 <= i < j < right.len() ==> #[trigger] right[i] < #[trigger] right[j], + forall|v: nat| left.contains(v) <==> right.contains(v), + ensures left == right, + { + assert(left.no_duplicates()); + assert(right.no_duplicates()); + left.lemma_multiset_has_no_duplicates(); + right.lemma_multiset_has_no_duplicates(); + assert forall|v: nat| left.to_multiset().count(v) == right.to_multiset().count(v) by { + vstd::seq_lib::to_multiset_contains(left, v); + vstd::seq_lib::to_multiset_contains(right, v); + } + assert(left.to_multiset() =~= right.to_multiset()); + vstd::seq_lib::lemma_sorted_unique(left, right, |a: nat, b: nat| a <= b); + } + + pub proof fn test_lemma_strict_subset_length(left: Seq, right: Seq) + requires + forall|i: int, j: int| 0 <= i < j < left.len() ==> #[trigger] left[i] < #[trigger] left[j], + forall|i: int, j: int| 0 <= i < j < right.len() ==> #[trigger] right[i] < #[trigger] right[j], + forall|v: nat| left.contains(v) ==> right.contains(v), + ensures left.len() <= right.len(), left != right ==> left.len() < right.len(), + { + assert(left.no_duplicates()); + assert(right.no_duplicates()); + left.unique_seq_to_set(); + right.unique_seq_to_set(); + left.to_set_ensures(); + right.to_set_ensures(); + assert(left.to_set().subset_of(right.to_set())); + vstd::set_lib::lemma_len_subset(left.to_set(), right.to_set()); + if left.len() == right.len() { + vstd::set_lib::lemma_subset_equality(left.to_set(), right.to_set()); + assert forall|v: nat| left.contains(v) <==> right.contains(v) by { + assert(left.to_set().contains(v) == right.to_set().contains(v)); + } + test_lemma_strict_members_equal(left, right); + } + } + + + pub open spec fn test_dual(g: model::Graph, id: TestId, and: bool) -> bool { + id@ < g.tests.len() && match g.tests[id@ as int] { + model::TestNode::Or(_) => and, + model::TestNode::And(_) => !and, + _ => false, + } + } + + pub open spec fn test_redundancy(g: model::Graph, a: TestId, b: TestId, and: bool) -> bool { + a != b && a@ < g.tests.len() && b@ < g.tests.len() && ( + (test_dual(g, a, and) && if test_dual(g, b, and) { + forall|child: nat| #[trigger] test_children(g, b).contains(child) + ==> test_children(g, a).contains(child) + } else { test_children(g, a).contains(b@) }) + || (test_distinct_heads(model::test_node_head(g.tests[a@ as int]), model::test_node_head(g.tests[b@ as int])) + && match (g.tests[a@ as int], g.tests[b@ as int]) { + (model::TestNode::Atom(_, x), model::TestNode::Atom(_, y)) => x != and && y == and, + _ => false, + }) + ) + } + + pub open spec fn test_redundant_in(g: model::Graph, a: TestId, siblings: Seq, and: bool) -> bool { + exists|i: int| 0 <= i < siblings.len() && test_redundancy(g, a, siblings[i], and) + } + + pub open spec fn test_redundancy_rank(g: model::Graph, id: TestId, and: bool) -> nat { + if test_dual(g, id, and) { test_children(g, id).len() + 2 } else { + if id@ < g.tests.len() && match g.tests[id@ as int] { + model::TestNode::Atom(_, positive) => positive == and, + _ => false, + } { 0 } else { 1 } + } + } + + pub open spec fn test_dominates(g: model::Graph, a: TestId, b: TestId, and: bool) -> bool { + forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + ==> if and { test_truth(g, theta, b@, event) ==> test_truth(g, theta, a@, event) } + else { test_truth(g, theta, a@, event) ==> test_truth(g, theta, b@, event) } + } + + pub proof fn test_lemma_redundancy(g: model::Graph, a: TestId, b: TestId, and: bool) + requires model::graph_wf(g), test_redundancy(g, a, b, and), + ensures test_redundancy_rank(g, b, and) < test_redundancy_rank(g, a, and), + test_dominates(g, a, b, and), + { + model::lemma_graph_wf_elim(g); + model::lemma_graph_test_wf(g, a@); + model::lemma_graph_test_wf(g, b@); + if test_dual(g, a, and) { + if test_dual(g, b, and) { + let ac = test_children(g, a); + let bc = test_children(g, b); + assert(ac != bc) by { + if ac == bc { assert(g.tests[a@ as int] == g.tests[b@ as int]); } + } + test_lemma_strict_subset_length(bc, ac); + } + } + assert forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + implies if and { test_truth(g, theta, b@, event) ==> test_truth(g, theta, a@, event) } + else { test_truth(g, theta, a@, event) ==> test_truth(g, theta, b@, event) } by { + test_lemma_truth(g, theta, a@, event); + test_lemma_truth(g, theta, b@, event); + if !test_dual(g, a, and) { + test_lemma_distinct_atoms(theta, model::test_node_head(g.tests[a@ as int]), + model::test_node_head(g.tests[b@ as int]), event); + } + } + } + + pub proof fn test_lemma_surviving_factor(g: model::Graph, siblings: Seq, a: TestId, and: bool) + requires model::graph_wf(g), test_ids_valid(g, siblings), siblings.contains(a), + ensures exists|b: TestId| siblings.contains(b) && !test_redundant_in(g, b, siblings, and) + && test_dominates(g, a, b, and), + decreases test_redundancy_rank(g, a, and), + { + if test_redundant_in(g, a, siblings, and) { + let i = choose|i: int| 0 <= i < siblings.len() && test_redundancy(g, a, siblings[i], and); + let b = siblings[i]; + test_lemma_redundancy(g, a, b, and); + assert(siblings.contains(b)); + test_lemma_surviving_factor(g, siblings, b, and); + let survivor = choose|c: TestId| siblings.contains(c) && !test_redundant_in(g, c, siblings, and) + && test_dominates(g, b, c, and); + assert(test_dominates(g, a, survivor, and)); + } else { assert(test_dominates(g, a, a, and)); } + } + + pub open spec fn test_retained(g: model::Graph, siblings: Seq, and: bool) -> Seq { + siblings.filter(|id: TestId| !test_redundant_in(g, id, siblings, and)) + } + + pub proof fn test_lemma_retention(g: model::Graph, siblings: Seq, kept: Seq, and: bool) + requires model::graph_wf(g), test_ids_valid(g, siblings), + forall|id: TestId| kept.contains(id) <==> siblings.contains(id) && !test_redundant_in(g, id, siblings, and), + ensures forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + ==> test_combo(g, theta, kept, event, and) == test_combo(g, theta, siblings, event, and), + { + assert forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + implies test_combo(g, theta, kept, event, and) == test_combo(g, theta, siblings, event, and) by { + test_lemma_combo_inclusion(g, theta, event, kept, siblings, and); + if and && test_combo(g, theta, kept, event, and) { + assert forall|i: int| 0 <= i < siblings.len() implies test_truth(g, theta, siblings[i]@, event) by { + assert(siblings.contains(siblings[i])); + test_lemma_surviving_factor(g, siblings, siblings[i], and); + let b = choose|b: TestId| siblings.contains(b) && !test_redundant_in(g, b, siblings, and) + && test_dominates(g, siblings[i], b, and); + let j = choose|j: int| 0 <= j < kept.len() && kept[j] == b; + } + } else if !and && test_combo(g, theta, siblings, event, and) { + let i = choose|i: int| 0 <= i < siblings.len() && test_truth(g, theta, siblings[i]@, event); + assert(siblings.contains(siblings[i])); + test_lemma_surviving_factor(g, siblings, siblings[i], and); + let b = choose|b: TestId| siblings.contains(b) && !test_redundant_in(g, b, siblings, and) + && test_dominates(g, siblings[i], b, and); + let j = choose|j: int| 0 <= j < kept.len() && kept[j] == b; + assert(test_truth(g, theta, kept[j]@, event)); + } + } + } + + pub open spec fn test_opposite_nat(g: model::Graph, a: nat, b: nat) -> bool { + forall|theta: Subst, event: EventView| + test_truth(g, theta, a, event) != test_truth(g, theta, b, event) + } + + pub open spec fn test_opposite(g: model::Graph, a: TestId, b: TestId) -> bool { + test_opposite_nat(g, a@, b@) + } + + pub open spec fn test_absorbs(g: model::Graph, ids: Seq, and: bool) -> bool { + forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + ==> test_combo(g, theta, ids, event, and) == !and + } + + pub open spec fn test_complement_covered(g: model::Graph, children: Seq, siblings: Seq) -> bool { + forall|child: nat| #[trigger] children.contains(child) + ==> exists|i: int| 0 <= i < siblings.len() && test_opposite_nat(g, child, siblings[i]@) + } + + pub proof fn test_lemma_combo_push(g: model::Graph, theta: Subst, event: EventView, + ids: Seq, id: TestId, and: bool) + ensures test_combo(g, theta, ids.push(id), event, and) + == if and { test_combo(g, theta, ids, event, and) && test_truth(g, theta, id@, event) } + else { test_combo(g, theta, ids, event, and) || test_truth(g, theta, id@, event) }, + { + if and { + if test_combo(g, theta, ids.push(id), event, and) { + assert(test_truth(g, theta, ids.push(id)[ids.len() as int]@, event)); + assert forall|i: int| 0 <= i < ids.len() implies test_truth(g, theta, ids[i]@, event) by { + assert(ids.push(id)[i] == ids[i]); + } + } else { + let i = choose|i: int| 0 <= i < ids.push(id).len() && !test_truth(g, theta, ids.push(id)[i]@, event); + } + } else { + if test_combo(g, theta, ids.push(id), event, and) { + let i = choose|i: int| 0 <= i < ids.push(id).len() && test_truth(g, theta, ids.push(id)[i]@, event); + } else { + assert(!test_truth(g, theta, ids.push(id)[ids.len() as int]@, event)); + assert forall|i: int| 0 <= i < ids.len() implies !test_truth(g, theta, ids[i]@, event) by { + assert(ids.push(id)[i] == ids[i]); + } + } + } + } + + pub proof fn test_lemma_combo_extends(a: model::Graph, b: model::Graph, ids: Seq) + requires model::graph_extends(a, b), test_ids_valid(a, ids), + ensures forall|theta: Subst, event: EventView, and: bool| + test_combo(a, theta, ids, event, and) == test_combo(b, theta, ids, event, and), + { + assert forall|i: int| 0 <= i < ids.len() + implies model::lift_test(a, ids[i]@) == model::lift_test(b, ids[i]@) by { + model::lemma_lift_test_stable(a, b, ids[i]@); + } + } + + pub proof fn test_lemma_opposite_extends(a: model::Graph, b: model::Graph, x: TestId, y: TestId) + requires model::graph_extends(a, b), x@ < a.tests.len(), y@ < a.tests.len(), test_opposite(a, x, y), + ensures test_opposite(b, x, y), + { + model::lemma_lift_test_stable(a, b, x@); + model::lemma_lift_test_stable(a, b, y@); + } + + pub proof fn test_lemma_absorbs_extends(a: model::Graph, b: model::Graph, ids: Seq, and: bool) + requires model::graph_extends(a, b), test_ids_valid(a, ids), test_absorbs(a, ids, and), + ensures test_absorbs(b, ids, and), + { + test_lemma_combo_extends(a, b, ids); + } + + pub proof fn test_lemma_absorbs_superset(g: model::Graph, left: Seq, right: Seq, and: bool) + requires test_absorbs(g, left, and), forall|id: TestId| left.contains(id) ==> right.contains(id), + ensures test_absorbs(g, right, and), + { + assert forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + implies test_combo(g, theta, right, event, and) == !and by { + test_lemma_combo_inclusion(g, theta, event, left, right, and); + } + } + + pub proof fn test_lemma_pair_absorbs(g: model::Graph, a: TestId, b: TestId, and: bool) + requires model::graph_wf(g), a@ < g.tests.len(), b@ < g.tests.len(), + test_opposite(g, a, b) || ( + test_distinct_heads(model::test_node_head(g.tests[a@ as int]), model::test_node_head(g.tests[b@ as int])) + && match (g.tests[a@ as int], g.tests[b@ as int]) { + (model::TestNode::Atom(_, x), model::TestNode::Atom(_, y)) => x == and && y == and, + _ => false, + }), + ensures test_absorbs(g, seq![a, b], and), + { + assert forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + implies test_combo(g, theta, seq![a, b], event, and) == !and by { + test_lemma_truth(g, theta, a@, event); + test_lemma_truth(g, theta, b@, event); + if !test_opposite(g, a, b) { + test_lemma_distinct_atoms(theta, model::test_node_head(g.tests[a@ as int]), + model::test_node_head(g.tests[b@ as int]), event); + } + } + } + + pub open spec fn test_has_opposite(g: model::Graph, id: TestId, siblings: Seq) -> bool { + exists|i: int| 0 <= i < siblings.len() && test_opposite(g, id, siblings[i]) + } + + pub proof fn test_lemma_has_opposite_extends(a: model::Graph, b: model::Graph, id: TestId, siblings: Seq) + requires model::graph_extends(a, b), id@ < a.tests.len(), test_ids_valid(a, siblings), test_has_opposite(a, id, siblings), + ensures test_has_opposite(b, id, siblings), + { + let i = choose|i: int| 0 <= i < siblings.len() && test_opposite(a, id, siblings[i]); + test_lemma_opposite_extends(a, b, id, siblings[i]); + } + + pub proof fn test_lemma_covered_extends(a: model::Graph, b: model::Graph, children: Seq, siblings: Seq) + requires model::graph_extends(a, b), model::bounded(children, a.tests.len()), test_ids_valid(a, siblings), + test_complement_covered(a, children, siblings), + ensures test_complement_covered(b, children, siblings), + { + assert forall|child: nat| children.contains(child) implies exists|i: int| 0 <= i < siblings.len() + && test_opposite_nat(b, child, siblings[i]@) by { + let j = choose|j: int| 0 <= j < children.len() && children[j] == child; + let i = choose|i: int| 0 <= i < siblings.len() && test_opposite_nat(a, child, siblings[i]@); + model::lemma_lift_test_stable(a, b, child); + model::lemma_lift_test_stable(a, b, siblings[i]@); + } + } + + pub proof fn test_lemma_compound_absorbs(g: model::Graph, a: TestId, siblings: Seq, and: bool) + requires model::graph_wf(g), a@ < g.tests.len(), test_dual(g, a, and), + test_complement_covered(g, test_children(g, a), siblings), + ensures test_absorbs(g, seq![a] + siblings, and), + { + assert forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + implies test_combo(g, theta, seq![a] + siblings, event, and) == !and by { + test_lemma_truth(g, theta, a@, event); + test_lemma_combo_concat(g, theta, event, seq![a], siblings, and); + test_lemma_combo_push(g, theta, event, Seq::empty(), a, and); + if and { + if test_combo(g, theta, siblings, event, and) { + assert forall|child: nat| test_children(g, a).contains(child) + implies !test_truth(g, theta, child, event) by { + let i = choose|i: int| 0 <= i < siblings.len() && test_opposite_nat(g, child, siblings[i]@); + } + assert(!test_truth(g, theta, a@, event)); + } + } else if !test_combo(g, theta, siblings, event, and) { + assert forall|child: nat| test_children(g, a).contains(child) + implies test_truth(g, theta, child, event) by { + let i = choose|i: int| 0 <= i < siblings.len() && test_opposite_nat(g, child, siblings[i]@); + } + assert(test_truth(g, theta, a@, event)); + } + } + } + + pub proof fn test_lemma_flatten(g: model::Graph, before: Seq, after: Seq, id: TestId, and: bool) + requires model::graph_wf(g), id@ < g.tests.len(), + g.tests[id@ as int] == if and { model::TestNode::And(test_children(g, id)) } + else { model::TestNode::Or(test_children(g, id)) }, + before.is_prefix_of(after), after.len() == before.len() + test_children(g, id).len(), + forall|i: int| 0 <= i < test_children(g, id).len() + ==> #[trigger] after[before.len() + i]@ == test_children(g, id)[i], + ensures forall|theta: Subst, event: EventView| + test_combo(g, theta, after, event, and) == test_combo(g, theta, before.push(id), event, and), + { + assert forall|theta: Subst, event: EventView| + test_combo(g, theta, after, event, and) == test_combo(g, theta, before.push(id), event, and) by { + test_lemma_truth(g, theta, id@, event); + test_lemma_combo_push(g, theta, event, before, id, and); + if and { + if test_combo(g, theta, after, event, and) { + assert forall|i: int| 0 <= i < before.len() implies test_truth(g, theta, before[i]@, event) by { + assert(after[i] == before[i]); + } + assert forall|child: nat| test_children(g, id).contains(child) implies test_truth(g, theta, child, event) by { + let i = choose|i: int| 0 <= i < test_children(g, id).len() && test_children(g, id)[i] == child; + assert(test_truth(g, theta, after[before.len() + i]@, event)); + } + } else { + let i = choose|i: int| 0 <= i < after.len() && !test_truth(g, theta, after[i]@, event); + if i < before.len() { assert(after[i] == before[i]); } + else { + let j = i - before.len() as int; + assert(0 <= j < test_children(g, id).len()); + assert(before.len() + j == i); + assert(after[before.len() + j]@ == test_children(g, id)[j]); + assert(after[i]@ == test_children(g, id)[i - before.len() as int]); + assert(test_children(g, id).contains(after[i]@)); + } + } + } else { + if test_combo(g, theta, after, event, and) { + let i = choose|i: int| 0 <= i < after.len() && test_truth(g, theta, after[i]@, event); + if i < before.len() { assert(after[i] == before[i]); } + else { + let j = i - before.len() as int; + assert(0 <= j < test_children(g, id).len()); + assert(before.len() + j == i); + assert(after[before.len() + j]@ == test_children(g, id)[j]); + assert(after[i]@ == test_children(g, id)[i - before.len() as int]); + assert(test_children(g, id).contains(after[i]@)); + } + } else { + assert forall|i: int| 0 <= i < before.len() implies !test_truth(g, theta, before[i]@, event) by { + assert(after[i] == before[i]); + } + assert forall|child: nat| test_children(g, id).contains(child) implies !test_truth(g, theta, child, event) by { + let i = choose|i: int| 0 <= i < test_children(g, id).len() && test_children(g, id)[i] == child; + assert(!test_truth(g, theta, after[before.len() + i]@, event)); + } + } + } + } + } + + pub proof fn test_lemma_filter_ordered(s: Seq, predicate: spec_fn(T) -> bool, key: spec_fn(T) -> nat) + requires forall|i: int, j: int| 0 <= i < j < s.len() ==> #[trigger] key(s[i]) < #[trigger] key(s[j]), + ensures forall|i: int, j: int| 0 <= i < j < s.filter(predicate).len() + ==> #[trigger] key(s.filter(predicate)[i]) < #[trigger] key(s.filter(predicate)[j]), + decreases s.len(), + { + if s.len() > 0 { + let prior = s.drop_last(); + test_lemma_filter_ordered(prior, predicate, key); + prior.lemma_filter_push(s.last(), predicate); + assert(prior.push(s.last()) =~= s); + assert forall|i: int, j: int| 0 <= i < j < s.filter(predicate).len() + implies key(s.filter(predicate)[i]) < key(s.filter(predicate)[j]) by { + if predicate(s.last()) && j == prior.filter(predicate).len() { + prior.lemma_filter_contains_rev(predicate, prior.filter(predicate)[i]); + let k = choose|k: int| 0 <= k < prior.len() && prior[k] == prior.filter(predicate)[i]; + assert(key(s[k]) < key(s[s.len() - 1])); + } + } + } + } + + pub proof fn test_lemma_retained_members(g: model::Graph, siblings: Seq, and: bool) + ensures forall|id: TestId| test_retained(g, siblings, and).contains(id) + <==> siblings.contains(id) && !test_redundant_in(g, id, siblings, and), + { + let predicate = |id: TestId| !test_redundant_in(g, id, siblings, and); + assert forall|id: TestId| siblings.filter(predicate).contains(id) + <==> siblings.contains(id) && predicate(id) by { + if siblings.filter(predicate).contains(id) { + siblings.lemma_filter_contains_rev(predicate, id); + let i = choose|i: int| 0 <= i < siblings.filter(predicate).len() && siblings.filter(predicate)[i] == id; + siblings.lemma_filter_pred(predicate, i); + } else if siblings.contains(id) && predicate(id) { + let i = choose|i: int| 0 <= i < siblings.len() && siblings[i] == id; + siblings.lemma_filter_contains(predicate, i); + } + } + } + + pub proof fn test_lemma_constants_semantics(g: model::Graph) + requires model::graph_wf(g), + ensures g.constants.test_true < g.tests.len(), g.constants.test_false < g.tests.len(), + forall|theta: Subst, event: EventView| + test_truth(g, theta, g.constants.test_true, event) + && !test_truth(g, theta, g.constants.test_false, event), + { + model::lemma_graph_wf_elim(g); + assert forall|theta: Subst, event: EventView| + test_truth(g, theta, g.constants.test_true, event) + && !test_truth(g, theta, g.constants.test_false, event) by { + test_lemma_truth(g, theta, g.constants.test_true, event); + test_lemma_truth(g, theta, g.constants.test_false, event); + } + } + + + #[verifier::opaque] + pub open spec fn test_negation_row(g: model::Graph, relation: Set<(nat, nat)>, left: nat, right: nat) -> bool { + left < g.tests.len() && right < g.tests.len() && match (g.tests[left as int], g.tests[right as int]) { + (model::TestNode::True, model::TestNode::False) => true, + (model::TestNode::False, model::TestNode::True) => true, + (model::TestNode::Atom(p, x), model::TestNode::Atom(q, y)) => p == q && x != y, + (model::TestNode::And(cs), model::TestNode::Or(ds)) => { + model::bounded(cs, left) && model::bounded(ds, right) + && test_negation_children(relation, cs, ds) + }, + (model::TestNode::Or(cs), model::TestNode::And(ds)) => { + model::bounded(cs, left) && model::bounded(ds, right) + && test_negation_children(relation, cs, ds) + }, + _ => false, + } + } + + pub open spec fn test_negation_functional(relation: Set<(nat, nat)>) -> bool { + forall|input: nat, a: nat, b: nat| + #[trigger] relation.contains((input, a)) && #[trigger] relation.contains((input, b)) ==> a == b + } + + pub open spec fn test_negation_injective(relation: Set<(nat, nat)>) -> bool { + forall|output: nat, a: nat, b: nat| + #[trigger] relation.contains((a, output)) && #[trigger] relation.contains((b, output)) ==> a == b + } + + pub open spec fn test_negation_children(relation: Set<(nat, nat)>, cs: Seq, ds: Seq) -> bool { + (forall|x: nat| #[trigger] cs.contains(x) ==> exists|y: nat| ds.contains(y) && relation.contains((x, y))) + && (forall|y: nat| #[trigger] ds.contains(y) ==> exists|x: nat| cs.contains(x) && relation.contains((x, y))) + } + + pub proof fn test_lemma_functional_children(relation: Set<(nat, nat)>, + cs: Seq, ds: Seq, es: Seq) + requires test_negation_functional(relation), + model::strictly_increasing(ds), model::strictly_increasing(es), + test_negation_children(relation, cs, ds), test_negation_children(relation, cs, es), + ensures ds == es, + { + assert forall|v: nat| ds.contains(v) <==> es.contains(v) by { + if ds.contains(v) { + let x = choose|x: nat| cs.contains(x) && relation.contains((x, v)); + let y = choose|y: nat| es.contains(y) && relation.contains((x, y)); + assert(v == y); + } + if es.contains(v) { + let x = choose|x: nat| cs.contains(x) && relation.contains((x, v)); + let y = choose|y: nat| ds.contains(y) && relation.contains((x, y)); + assert(v == y); + } + } + test_lemma_strict_members_equal(ds, es); + } + + pub proof fn test_lemma_negation_row_functional(g: model::Graph, + relation: Set<(nat, nat)>, pivot: nat, left: nat, right: nat) + requires model::graph_wf(g), test_negation_functional(relation), + test_negation_row(g, relation, pivot, left), test_negation_row(g, relation, pivot, right), + ensures left == right, + { + reveal(test_negation_row); + model::lemma_graph_wf_elim(g); + model::lemma_graph_test_wf(g, pivot); + model::lemma_graph_test_wf(g, left); + model::lemma_graph_test_wf(g, right); + match (g.tests[pivot as int], g.tests[left as int], g.tests[right as int]) { + (model::TestNode::And(cs), model::TestNode::Or(ds), model::TestNode::Or(es)) => { + test_lemma_functional_children(relation, cs, ds, es); + }, + (model::TestNode::Or(cs), model::TestNode::And(ds), model::TestNode::And(es)) => { + test_lemma_functional_children(relation, cs, ds, es); + }, + _ => {}, + } + assert(g.tests[left as int] == g.tests[right as int]); + } + + pub open spec fn test_negation_reverse(relation: Set<(nat, nat)>) -> Set<(nat, nat)> { + relation.map(|pair: (nat, nat)| (pair.1, pair.0)) + } + + pub proof fn test_lemma_negation_reverse(relation: Set<(nat, nat)>) + ensures forall|a: nat, b: nat| #[trigger] test_negation_reverse(relation).contains((a, b)) + <==> relation.contains((b, a)), + test_negation_injective(relation) ==> test_negation_functional(test_negation_reverse(relation)), + { + assert forall|a: nat, b: nat| test_negation_reverse(relation).contains((a, b)) + <==> relation.contains((b, a)) by { + relation.lemma_map_contains(|pair: (nat, nat)| (pair.1, pair.0), (a, b)); + } + } + + pub proof fn test_lemma_negation_row_reverse(g: model::Graph, relation: Set<(nat, nat)>, a: nat, b: nat) + requires test_negation_row(g, relation, a, b), + ensures test_negation_row(g, test_negation_reverse(relation), b, a), + { + reveal(test_negation_row); + test_lemma_negation_reverse(relation); + match (g.tests[a as int], g.tests[b as int]) { + (model::TestNode::And(cs), model::TestNode::Or(ds)) => { + assert(test_negation_children(test_negation_reverse(relation), ds, cs)); + }, + (model::TestNode::Or(cs), model::TestNode::And(ds)) => { + assert(test_negation_children(test_negation_reverse(relation), ds, cs)); + }, + _ => {}, + } + } + + #[verifier::opaque] + pub open spec fn test_negation_witness(g: model::Graph, relation: Set<(nat, nat)>) -> bool { + test_negation_functional(relation) && test_negation_injective(relation) + && forall|pair: (nat, nat)| #[trigger] relation.contains(pair) + ==> test_negation_row(g, relation, pair.0, pair.1) + } + + pub proof fn test_lemma_negation_witness_elim(g: model::Graph, relation: Set<(nat, nat)>) + requires test_negation_witness(g, relation), + ensures test_negation_functional(relation), test_negation_injective(relation), + forall|pair: (nat, nat)| #[trigger] relation.contains(pair) + ==> test_negation_row(g, relation, pair.0, pair.1), + { + reveal(test_negation_witness); + } + + pub proof fn test_lemma_negation_row_monotone(g: model::Graph, old: Set<(nat, nat)>, new: Set<(nat, nat)>, a: nat, b: nat) + requires test_negation_row(g, old, a, b), old.subset_of(new), + ensures test_negation_row(g, new, a, b), + { + reveal(test_negation_row); + match (g.tests[a as int], g.tests[b as int]) { + (model::TestNode::And(cs), model::TestNode::Or(ds)) => { + assert(test_negation_children(new, cs, ds)); + }, + (model::TestNode::Or(cs), model::TestNode::And(ds)) => { + assert(test_negation_children(new, cs, ds)); + }, + _ => {}, + } + } + + pub proof fn test_lemma_negation_insert(g: model::Graph, relation: Set<(nat, nat)>, a: nat, b: nat) + requires model::graph_wf(g), test_negation_witness(g, relation), test_negation_row(g, relation, a, b), + ensures test_negation_witness(g, relation.insert((a, b))), + { + reveal(test_negation_witness); + let next = relation.insert((a, b)); + assert forall|pivot: nat, x: nat, y: nat| + next.contains((pivot, x)) && next.contains((pivot, y)) implies x == y by { + if pivot == a { + if relation.contains((a, x)) { test_lemma_negation_row_functional(g, relation, a, x, b); } + if relation.contains((a, y)) { test_lemma_negation_row_functional(g, relation, a, y, b); } + } + } + test_lemma_negation_reverse(relation); + test_lemma_negation_row_reverse(g, relation, a, b); + assert forall|pivot: nat, x: nat, y: nat| + next.contains((x, pivot)) && next.contains((y, pivot)) implies x == y by { + if pivot == b { + if relation.contains((x, b)) { + test_lemma_negation_row_reverse(g, relation, x, b); + test_lemma_negation_row_functional(g, test_negation_reverse(relation), b, x, a); + } + if relation.contains((y, b)) { + test_lemma_negation_row_reverse(g, relation, y, b); + test_lemma_negation_row_functional(g, test_negation_reverse(relation), b, y, a); + } + } + } + assert(relation.subset_of(next)); + assert forall|pair: (nat, nat)| next.contains(pair) implies test_negation_row(g, next, pair.0, pair.1) by { + test_lemma_negation_row_monotone(g, relation, next, pair.0, pair.1); + } + } + + #[verifier::inline] + pub open spec fn test_truth(g: model::Graph, theta: Subst, id: nat, event: EventView) -> bool { + model::test_holds(theta, model::lift_test(g, id), event) + } + + pub proof fn test_lemma_truth(g: model::Graph, theta: Subst, id: nat, event: EventView) + requires model::graph_wf(g), id < g.tests.len(), + ensures test_truth(g, theta, id, event) == match g.tests[id as int] { + model::TestNode::True => true, + model::TestNode::False => false, + model::TestNode::Atom(p, b) => model::primitive_holds(theta, p, event) == b, + model::TestNode::And(cs) => forall|child: nat| #[trigger] cs.contains(child) + ==> test_truth(g, theta, child, event), + model::TestNode::Or(cs) => exists|child: nat| cs.contains(child) + && test_truth(g, theta, child, event), + }, + { + model::lemma_graph_test_wf(g, id); + match g.tests[id as int] { + model::TestNode::And(cs) => { + let lifted = model::lift_tests(g, cs, id); + test_lemma_semantics_unfold(theta, event, model::Test::And(lifted)); + assert forall|i: int| 0 <= i < cs.len() + + implies lifted[i] == model::lift_test(g, cs[i]) by {} + if test_truth(g, theta, id, event) { + assert forall|child: nat| cs.contains(child) implies test_truth(g, theta, child, event) by { + let i = choose|i: int| 0 <= i < cs.len() && cs[i] == child; + test_lemma_compound_child(theta, event, lifted, i); + } + } else { + let i = choose|i: int| 0 <= i < lifted.len() && !model::test_holds(theta, lifted[i], event); + assert(cs.contains(cs[i])); + } + }, + model::TestNode::Or(cs) => { + let lifted = model::lift_tests(g, cs, id); + test_lemma_semantics_unfold(theta, event, model::Test::Or(lifted)); + assert forall|i: int| 0 <= i < cs.len() + implies lifted[i] == model::lift_test(g, cs[i]) by {} + if test_truth(g, theta, id, event) { + let i = choose|i: int| 0 <= i < lifted.len() && model::test_holds(theta, lifted[i], event); + assert(cs.contains(cs[i])); + } else { + assert forall|child: nat| cs.contains(child) implies !test_truth(g, theta, child, event) by { + let i = choose|i: int| 0 <= i < cs.len() && cs[i] == child; + test_lemma_compound_child(theta, event, lifted, i); + } + } + }, + _ => {}, + } + } + + pub proof fn test_lemma_negation_semantics(g: model::Graph, relation: Set<(nat, nat)>, + left: nat, right: nat, theta: Subst, event: EventView) + requires model::graph_wf(g), test_negation_witness(g, relation), relation.contains((left, right)), + ensures test_truth(g, theta, left, event) != test_truth(g, theta, right, event), + decreases left, + { + test_lemma_negation_witness_elim(g, relation); + reveal(test_negation_row); + assert(test_negation_row(g, relation, left, right)); + test_lemma_truth(g, theta, left, event); + test_lemma_truth(g, theta, right, event); + match (g.tests[left as int], g.tests[right as int]) { + (model::TestNode::And(cs), model::TestNode::Or(ds)) => { + assert forall|a: nat, b: nat| cs.contains(a) && ds.contains(b) && relation.contains((a, b)) + implies test_truth(g, theta, a, event) != test_truth(g, theta, b, event) by { + let i = choose|i: int| 0 <= i < cs.len() && cs[i] == a; + test_lemma_negation_semantics(g, relation, a, b, theta, event); + } + if test_truth(g, theta, left, event) { + assert forall|b: nat| ds.contains(b) implies !test_truth(g, theta, b, event) by { + let a = choose|a: nat| cs.contains(a) && relation.contains((a, b)); + } + } else { + let a = choose|a: nat| cs.contains(a) && !test_truth(g, theta, a, event); + let b = choose|b: nat| ds.contains(b) && relation.contains((a, b)); + assert(test_truth(g, theta, b, event)); + } + }, + (model::TestNode::Or(cs), model::TestNode::And(ds)) => { + assert forall|a: nat, b: nat| cs.contains(a) && ds.contains(b) && relation.contains((a, b)) + implies test_truth(g, theta, a, event) != test_truth(g, theta, b, event) by { + let i = choose|i: int| 0 <= i < cs.len() && cs[i] == a; + test_lemma_negation_semantics(g, relation, a, b, theta, event); + } + if test_truth(g, theta, left, event) { + let a = choose|a: nat| cs.contains(a) && test_truth(g, theta, a, event); + let b = choose|b: nat| ds.contains(b) && relation.contains((a, b)); + assert(!test_truth(g, theta, b, event)); + } else { + assert forall|b: nat| ds.contains(b) implies test_truth(g, theta, b, event) by { + let a = choose|a: nat| cs.contains(a) && relation.contains((a, b)); + } + } + }, + _ => {}, + } + } + + pub open spec fn test_not_plan(g: model::Graph, tasks: Seq<(TestId, bool)>, origins: Seq) -> Option> + decreases tasks.len(), + { + if tasks.len() == 0 { Some(origins) } else { + let task = tasks.last(); + if task.0@ >= g.tests.len() { None } else if !task.1 { + test_not_plan(g, tasks.drop_last(), origins.push(task.0@)) + } else { + let cs = test_children(g, task.0); + if !test_child_count(g, task.0, cs.len()) || cs.len() > origins.len() + || origins.subrange(origins.len() as int - cs.len() as int, origins.len() as int) != cs { + None + } else { + test_not_plan(g, tasks.drop_last(), origins.subrange(0, + origins.len() as int - cs.len() as int).push(task.0@)) + } + } + } + } + + pub open spec fn test_not_state(g: model::Graph, tasks: Seq<(TestId, bool)>, values: Seq, root: TestId) -> bool { + (forall|i: int| 0 <= i < tasks.len() ==> #[trigger] tasks[i].0@ < g.tests.len()) + && exists|origins: Seq, relation: Set<(nat, nat)>| + origins.len() == values.len() && test_negation_witness(g, relation) + && (forall|i: int| 0 <= i < values.len() ==> #[trigger] relation.contains((origins[i], values[i]@))) + && test_not_plan(g, tasks, origins) == Some(seq![root@]) + } + + pub open spec fn test_not_node_work(g: model::Graph, id: nat) -> nat + decreases id, 1nat, + { + if id >= g.tests.len() { 0 } else { + match g.tests[id as int] { + model::TestNode::And(cs) => 2 + test_not_children_work(g, cs, id), + model::TestNode::Or(cs) => 2 + test_not_children_work(g, cs, id), + _ => 1, + } + } + } + + pub open spec fn test_not_children_work(g: model::Graph, children: Seq, bound: nat) -> nat + decreases bound, 0nat, children.len(), + { + if children.len() == 0 { 0 } else { + test_not_children_work(g, children.skip(1), bound) + + if children[0] < bound { test_not_node_work(g, children[0]) } else { 0 } + } + } + + pub open spec fn test_not_work(g: model::Graph, tasks: Seq<(TestId, bool)>) -> nat + decreases tasks.len(), + { + if tasks.len() == 0 { 0 } else { + test_not_work(g, tasks.drop_last()) + + if tasks.last().1 { 1 } else { test_not_node_work(g, tasks.last().0@) } + } + } + + pub proof fn test_lemma_negation_witness_extends(a: model::Graph, b: model::Graph, relation: Set<(nat, nat)>) + requires model::graph_extends(a, b), test_negation_witness(a, relation), + ensures test_negation_witness(b, relation), + { + reveal(test_negation_witness); + reveal(test_negation_row); + assert forall|pair: (nat, nat)| relation.contains(pair) implies test_negation_row(b, relation, pair.0, pair.1) by { + assert(test_negation_row(a, relation, pair.0, pair.1)); + assert(a.tests[pair.0 as int] == b.tests[pair.0 as int]); + assert(a.tests[pair.1 as int] == b.tests[pair.1 as int]); + } + } + + pub open spec fn test_not_ready(g: model::Graph, id: TestId, finish: bool, values: Seq) -> bool { + id@ < g.tests.len() && test_ids_valid(g, values) + && if finish { + let cs = test_children(g, id); + test_child_count(g, id, cs.len()) && cs.len() <= values.len() + && values.subrange(values.len() as int - cs.len() as int, values.len() as int).no_duplicates() + } else { true } + } + + pub proof fn test_lemma_not_state_ready(g: model::Graph, tasks: Seq<(TestId, bool)>, + id: TestId, finish: bool, values: Seq, root: TestId) + requires model::graph_wf(g), test_not_state(g, tasks.push((id, finish)), values, root), + ensures test_not_ready(g, id, finish, values), + { + let (origins, relation) = choose|origins: Seq, relation: Set<(nat, nat)>| + origins.len() == values.len() && test_negation_witness(g, relation) + && (forall|i: int| 0 <= i < values.len() ==> relation.contains((origins[i], values[i]@))) + && test_not_plan(g, tasks.push((id, finish)), origins) == Some(seq![root@]); + test_lemma_negation_witness_elim(g, relation); + reveal(test_negation_row); + assert forall|i: int| 0 <= i < values.len() implies values[i]@ < g.tests.len() by { + assert(test_negation_row(g, relation, origins[i], values[i]@)); + } + if finish { + reveal_with_fuel(test_not_plan, 2); + let cs = test_children(g, id); + let start = values.len() as int - cs.len() as int; + test_lemma_children(g, id, cs.len()); + model::lemma_graph_test_wf(g, id@); + let suffix = values.subrange(start, values.len() as int); + assert forall|i: int, j: int| 0 <= i < j < suffix.len() implies suffix[i] != suffix[j] by { + assert(origins[start + i] == cs[i]); + assert(origins[start + j] == cs[j]); + assert(cs[i] < cs[j]); + assert(relation.contains((cs[i], suffix[i]@))); + assert(relation.contains((cs[j], suffix[j]@))); + } + } + } + + pub open spec fn test_not_schedule(g: model::Graph, id: TestId, scheduled: Seq<(TestId, bool)>) -> bool { + let cs = test_children(g, id); + test_child_count(g, id, cs.len()) && scheduled.len() == cs.len() + && forall|i: int| 0 <= i < scheduled.len() + ==> #[trigger] scheduled[i].0@ == cs[cs.len() as int - 1 - i] && !scheduled[i].1 + } + + pub open spec fn test_not_effect(g: model::Graph, id: TestId, finish: bool, + tasks0: Seq<(TestId, bool)>, values0: Seq, tasks1: Seq<(TestId, bool)>, values1: Seq) -> bool { + if id@ >= g.tests.len() { false } else { + + match g.tests[id@ as int] { + model::TestNode::And(cs) => if finish { + tasks1 == tasks0 && cs.len() <= values0.len() + && values1.len() == values0.len() - cs.len() + 1 + && values1.drop_last() == values0.subrange(0, values0.len() as int - cs.len() as int) + && (exists|sorted: Seq| + sorted.to_multiset() == values0.subrange(values0.len() as int - cs.len() as int, + values0.len() as int).to_multiset() + && g.tests[values1.last()@ as int] == model::TestNode::Or(model::test_ids(sorted))) + } else { + values1 == values0 && tasks0.push((id, true)).is_prefix_of(tasks1) + && test_not_schedule(g, id, tasks1.subrange(tasks0.len() as int + 1, tasks1.len() as int)) + }, + model::TestNode::Or(cs) => if finish { + tasks1 == tasks0 && cs.len() <= values0.len() + && values1.len() == values0.len() - cs.len() + 1 + && values1.drop_last() == values0.subrange(0, values0.len() as int - cs.len() as int) + && (exists|sorted: Seq| + sorted.to_multiset() == values0.subrange(values0.len() as int - cs.len() as int, + values0.len() as int).to_multiset() + && g.tests[values1.last()@ as int] == model::TestNode::And(model::test_ids(sorted))) + } else { + values1 == values0 && tasks0.push((id, true)).is_prefix_of(tasks1) + && test_not_schedule(g, id, tasks1.subrange(tasks0.len() as int + 1, tasks1.len() as int)) + }, + _ => tasks1 == tasks0 && values1.len() == values0.len() + 1 + && values1.drop_last() == values0 + && test_negation_row(g, Set::empty(), id@, values1.last()@), + } + } + } + + pub proof fn test_lemma_not_plan_extends(a: model::Graph, b: model::Graph, + tasks: Seq<(TestId, bool)>, origins: Seq) + requires model::graph_extends(a, b), + forall|i: int| 0 <= i < tasks.len() ==> #[trigger] tasks[i].0@ < a.tests.len(), + ensures test_not_plan(a, tasks, origins) == test_not_plan(b, tasks, origins), + decreases tasks.len(), + { + if tasks.len() > 0 { + let task = tasks.last(); + assert(a.tests[task.0@ as int] == b.tests[task.0@ as int]); + if !task.1 { + test_lemma_not_plan_extends(a, b, tasks.drop_last(), origins.push(task.0@)); + } else { + let cs = test_children(a, task.0); + if test_child_count(a, task.0, cs.len()) && cs.len() <= origins.len() + && origins.subrange(origins.len() as int - cs.len() as int, origins.len() as int) == cs { + test_lemma_not_plan_extends(a, b, tasks.drop_last(), origins.subrange(0, + origins.len() as int - cs.len() as int).push(task.0@)); + } + } + } + } + + pub proof fn test_lemma_not_state_extends(a: model::Graph, b: model::Graph, + tasks: Seq<(TestId, bool)>, values: Seq, root: TestId) + requires model::graph_extends(a, b), test_not_state(a, tasks, values, root), + ensures test_not_state(b, tasks, values, root), + { + let (origins, relation) = choose|origins: Seq, relation: Set<(nat, nat)>| + origins.len() == values.len() && test_negation_witness(a, relation) + && (forall|i: int| 0 <= i < values.len() ==> relation.contains((origins[i], values[i]@))) + && test_not_plan(a, tasks, origins) == Some(seq![root@]); + test_lemma_negation_witness_extends(a, b, relation); + test_lemma_not_plan_extends(a, b, tasks, origins); + assert(forall|i: int| 0 <= i < tasks.len() ==> #[trigger] tasks[i].0@ < b.tests.len()); + } + + pub proof fn test_lemma_not_plan_schedule(g: model::Graph, tasks: Seq<(TestId, bool)>, + scheduled: Seq<(TestId, bool)>, origins: Seq, children: Seq) + requires scheduled.len() == children.len(), model::bounded(children, g.tests.len()), + forall|i: int| 0 <= i < scheduled.len() + ==> #[trigger] scheduled[i].0@ == children[children.len() as int - 1 - i] && !scheduled[i].1, + ensures test_not_plan(g, tasks + scheduled, origins) == test_not_plan(g, tasks, origins + children), + decreases scheduled.len(), + { + if scheduled.len() == 0 { + assert(tasks + scheduled =~= tasks); + assert(origins + children =~= origins); + } else { + assert((tasks + scheduled).last() == scheduled.last()); + assert((tasks + scheduled).drop_last() =~= tasks + scheduled.drop_last()); + test_lemma_not_plan_schedule(g, tasks, scheduled.drop_last(), origins.push(children[0]), children.skip(1)); + assert(origins.push(children[0]) + children.skip(1) =~= origins + children); + } + } + + pub proof fn test_lemma_not_parent_row(g: model::Graph, relation: Set<(nat, nat)>, + id: TestId, origins: Seq, values: Seq, sorted: Seq, out: TestId) + requires model::graph_wf(g), id@ < g.tests.len(), out@ < g.tests.len(), + origins == test_children(g, id), test_child_count(g, id, origins.len()), + origins.len() == values.len(), sorted.to_multiset() == values.to_multiset(), + forall|i: int| 0 <= i < values.len() ==> #[trigger] relation.contains((origins[i], values[i]@)), + match g.tests[id@ as int] { + model::TestNode::And(_) => g.tests[out@ as int] == model::TestNode::Or(model::test_ids(sorted)), + model::TestNode::Or(_) => g.tests[out@ as int] == model::TestNode::And(model::test_ids(sorted)), + _ => false, + }, + ensures test_negation_row(g, relation, id@, out@), + { + reveal(test_negation_row); + model::lemma_graph_test_wf(g, id@); + model::lemma_graph_test_wf(g, out@); + lemma_multiset_members(sorted, values); + let output = model::test_ids(sorted); + assert forall|x: nat| origins.contains(x) implies exists|y: nat| + output.contains(y) && relation.contains((x, y)) by { + let i = choose|i: int| 0 <= i < origins.len() && origins[i] == x; + assert(values.contains(values[i])); + assert(sorted.contains(values[i])); + let j = choose|j: int| 0 <= j < sorted.len() && sorted[j] == values[i]; + assert(output[j] == values[i]@); + assert(output.contains(values[i]@)); + } + assert forall|y: nat| output.contains(y) implies exists|x: nat| + origins.contains(x) && relation.contains((x, y)) by { + let j = choose|j: int| 0 <= j < output.len() && output[j] == y; + assert(sorted.contains(sorted[j])); + assert(values.contains(sorted[j])); + let i = choose|i: int| 0 <= i < values.len() && values[i] == sorted[j]; + assert(origins.contains(origins[i])); + assert(relation.contains((origins[i], y))); + } + match g.tests[id@ as int] { + model::TestNode::And(_) => {}, + model::TestNode::Or(_) => {}, + _ => {}, + } + } + + #[verifier::spinoff_prover] + #[verifier::rlimit(30)] + pub proof fn test_lemma_not_effect_compound(g: model::Graph, id: TestId, finish: bool, + tasks0: Seq<(TestId, bool)>, values0: Seq, tasks1: Seq<(TestId, bool)>, values1: Seq, + root: TestId, origins: Seq, relation: Set<(nat, nat)>, cs: Seq) + requires model::graph_wf(g), test_ids_valid(g, values1), + test_not_effect(g, id, finish, tasks0, values0, tasks1, values1), + id@ < g.tests.len(), test_child_count(g, id, cs.len()), cs == test_children(g, id), + origins.len() == values0.len(), test_negation_witness(g, relation), + forall|i: int| 0 <= i < values0.len() ==> #[trigger] relation.contains((origins[i], values0[i]@)), + forall|i: int| 0 <= i < tasks0.len() ==> #[trigger] tasks0[i].0@ < g.tests.len(), + test_not_plan(g, tasks0.push((id, finish)), origins) == Some(seq![root@]), + ensures test_not_state(g, tasks1, values1, root), + { + hide(test_not_plan); + match g.tests[id@ as int] { + model::TestNode::And(_) => {}, + model::TestNode::Or(_) => {}, + _ => {}, + } + if finish { + assert(tasks1 == tasks0); + assert(values1.drop_last() == values0.subrange(0, values0.len() as int - cs.len() as int)); + } else { assert(values1 == values0); } + test_lemma_not_plan_push(g, tasks0, id, finish, origins); + test_lemma_children(g, id, cs.len()); + if finish { + let start = origins.len() as int - cs.len() as int; + assert(origins.subrange(start, origins.len() as int) == cs); + let source = values0.subrange(start, values0.len() as int); + let sorted = choose|sorted: Seq| sorted.to_multiset() == source.to_multiset() + && match g.tests[id@ as int] { + model::TestNode::And(_) => g.tests[values1.last()@ as int] == model::TestNode::Or(model::test_ids(sorted)), + model::TestNode::Or(_) => g.tests[values1.last()@ as int] == model::TestNode::And(model::test_ids(sorted)), + _ => false, + }; + test_lemma_not_parent_row(g, relation, id, cs, source, sorted, values1.last()); + test_lemma_negation_insert(g, relation, id@, values1.last()@); + let next_origins = origins.subrange(0, start).push(id@); + let next_relation = relation.insert((id@, values1.last()@)); + assert forall|i: int| 0 <= i < values1.len() + implies next_relation.contains((next_origins[i], values1[i]@)) by { + if i < next_origins.len() - 1 { + assert(values1.drop_last()[i] == values0.subrange(0, start)[i]); + } + } + assert(test_not_plan(g, tasks1, next_origins) == Some(seq![root@])); + } else { + let scheduled = tasks1.subrange(tasks0.len() as int + 1, tasks1.len() as int); + assert(tasks1 =~= tasks0.push((id, true)) + scheduled); + test_lemma_not_plan_schedule(g, tasks0.push((id, true)), scheduled, origins, cs); + assert((origins + cs).subrange(origins.len() as int, origins.len() as int + cs.len() as int) =~= cs); + assert((origins + cs).subrange(0, origins.len() as int) =~= origins); + test_lemma_not_plan_push(g, tasks0, id, true, origins + cs); + test_lemma_not_plan_push(g, tasks0, id, false, origins); + assert(test_not_plan(g, tasks1, origins) == Some(seq![root@])); + assert forall|i: int| 0 <= i < tasks1.len() implies tasks1[i].0@ < g.tests.len() by { + if i >= tasks0.len() + 1 { + let j = i - tasks0.len() as int - 1; + assert(tasks1[i] == scheduled[j]); + assert(tasks1[i].0@ < id@); + } + } + } + } + + pub proof fn test_lemma_not_effect_state(g: model::Graph, id: TestId, finish: bool, + tasks0: Seq<(TestId, bool)>, values0: Seq, tasks1: Seq<(TestId, bool)>, values1: Seq, root: TestId) + + requires model::graph_wf(g), test_ids_valid(g, values1), + test_not_state(g, tasks0.push((id, finish)), values0, root), + test_not_effect(g, id, finish, tasks0, values0, tasks1, values1), + ensures test_not_state(g, tasks1, values1, root), + { + reveal_with_fuel(test_not_plan, 3); + assert forall|i: int| 0 <= i < tasks0.len() implies tasks0[i].0@ < g.tests.len() by { + assert(tasks0.push((id, finish))[i] == tasks0[i]); + } + let (origins, relation) = choose|origins: Seq, relation: Set<(nat, nat)>| + origins.len() == values0.len() && test_negation_witness(g, relation) + && (forall|i: int| 0 <= i < values0.len() ==> relation.contains((origins[i], values0[i]@))) + && test_not_plan(g, tasks0.push((id, finish)), origins) == Some(seq![root@]); + match g.tests[id@ as int] { + model::TestNode::And(cs) => { + test_lemma_not_effect_compound(g, id, finish, tasks0, values0, tasks1, values1, root, origins, relation, cs); + }, + model::TestNode::Or(cs) => { + test_lemma_not_effect_compound(g, id, finish, tasks0, values0, tasks1, values1, root, origins, relation, cs); + }, + _ => { + test_lemma_not_plan_push(g, tasks0, id, finish, origins); + assert(!finish); + assert(tasks1 == tasks0); + reveal(test_negation_row); + test_lemma_negation_row_monotone(g, Set::empty(), relation, id@, values1.last()@); + test_lemma_negation_insert(g, relation, id@, values1.last()@); + let next_origins = origins.push(id@); + let next_relation = relation.insert((id@, values1.last()@)); + assert forall|i: int| 0 <= i < values1.len() + implies next_relation.contains((next_origins[i], values1[i]@)) by { + if i < origins.len() { assert(values1[i] == values0[i]); } + } + assert(test_not_plan(g, tasks1, next_origins) == Some(seq![root@])); + }, + } + } + + pub proof fn test_lemma_not_initial(g: model::Graph, root: TestId) + requires root@ < g.tests.len(), + ensures test_not_state(g, seq![(root, false)], Seq::empty(), root), + { + reveal_with_fuel(test_not_plan, 3); + reveal(test_negation_witness); + assert(test_negation_witness(g, Set::empty())); + assert(test_not_plan(g, seq![(root, false)], Seq::empty()) == Some(seq![root@])); + } + + pub proof fn test_lemma_not_done(g: model::Graph, values: Seq, root: TestId) + requires model::graph_wf(g), test_not_state(g, Seq::empty(), values, root), + ensures values.len() == 1, values[0]@ < g.tests.len(), + forall|theta: Subst, event: EventView| + test_truth(g, theta, values[0]@, event) != test_truth(g, theta, root@, event), + { + let (origins, relation) = choose|origins: Seq, relation: Set<(nat, nat)>| + origins.len() == values.len() && test_negation_witness(g, relation) + && (forall|i: int| 0 <= i < values.len() ==> relation.contains((origins[i], values[i]@))) + && test_not_plan(g, Seq::empty(), origins) == Some(seq![root@]); + assert(origins == seq![root@]); + assert(relation.contains((origins[0], values[0]@))); + test_lemma_negation_witness_elim(g, relation); + reveal(test_negation_row); + assert(test_negation_row(g, relation, root@, values[0]@)); + assert forall|theta: Subst, event: EventView| + test_truth(g, theta, values[0]@, event) != test_truth(g, theta, root@, event) by { + test_lemma_negation_semantics(g, relation, root@, values[0]@, theta, event); + } + } + + pub proof fn test_lemma_not_plan_push(g: model::Graph, tasks: Seq<(TestId, bool)>, id: TestId, + finish: bool, origins: Seq) + requires id@ < g.tests.len(), + ensures test_not_plan(g, tasks.push((id, finish)), origins) + == if !finish { test_not_plan(g, tasks, origins.push(id@)) } else { + let cs = test_children(g, id); + if !test_child_count(g, id, cs.len()) || cs.len() > origins.len() + || origins.subrange(origins.len() as int - cs.len() as int, origins.len() as int) != cs { + None + } else { + test_not_plan(g, tasks, origins.subrange(0, origins.len() as int - cs.len() as int).push(id@)) + } + }, + { + assert(tasks.push((id, finish)).last() == (id, finish)); + assert(tasks.push((id, finish)).drop_last() =~= tasks); + reveal_with_fuel(test_not_plan, 2); + } + + pub proof fn test_lemma_not_work_schedule(g: model::Graph, tasks: Seq<(TestId, bool)>, + scheduled: Seq<(TestId, bool)>, children: Seq, bound: nat) + requires scheduled.len() == children.len(), model::bounded(children, bound), + forall|i: int| 0 <= i < scheduled.len() + ==> #[trigger] scheduled[i].0@ == children[children.len() as int - 1 - i] && !scheduled[i].1, + ensures test_not_work(g, tasks + scheduled) == test_not_work(g, tasks) + test_not_children_work(g, children, bound), + decreases scheduled.len(), + { + if scheduled.len() == 0 { + assert(tasks + scheduled =~= tasks); + } else { + assert((tasks + scheduled).drop_last() =~= tasks + scheduled.drop_last()); + assert((tasks + scheduled).last() == scheduled.last()); + test_lemma_not_work_schedule(g, tasks, scheduled.drop_last(), children.skip(1), bound); + } + } + + pub proof fn test_lemma_not_node_work_extends(a: model::Graph, b: model::Graph, id: nat) + requires model::graph_extends(a, b), id < a.tests.len(), + ensures test_not_node_work(a, id) == test_not_node_work(b, id), + decreases id, 1nat, + { + assert(a.tests[id as int] == b.tests[id as int]); + match a.tests[id as int] { + model::TestNode::And(cs) => { test_lemma_not_children_work_extends(a, b, cs, id); }, + model::TestNode::Or(cs) => { test_lemma_not_children_work_extends(a, b, cs, id); }, + _ => {}, + } + } + + pub proof fn test_lemma_not_children_work_extends(a: model::Graph, b: model::Graph, children: Seq, bound: nat) + requires model::graph_extends(a, b), bound <= a.tests.len(), + ensures test_not_children_work(a, children, bound) == test_not_children_work(b, children, bound), + decreases bound, 0nat, children.len(), + { + if children.len() > 0 { + if children[0] < bound { test_lemma_not_node_work_extends(a, b, children[0]); } + test_lemma_not_children_work_extends(a, b, children.skip(1), bound); + } + } + + pub proof fn test_lemma_not_work_extends(a: model::Graph, b: model::Graph, tasks: Seq<(TestId, bool)>) + requires model::graph_extends(a, b), + forall|i: int| 0 <= i < tasks.len() ==> #[trigger] tasks[i].0@ < a.tests.len(), + ensures test_not_work(a, tasks) == test_not_work(b, tasks), + decreases tasks.len(), + { + if tasks.len() > 0 { + if !tasks.last().1 { test_lemma_not_node_work_extends(a, b, tasks.last().0@); } + test_lemma_not_work_extends(a, b, tasks.drop_last()); + } + } + + pub proof fn test_lemma_not_effect_work(g: model::Graph, id: TestId, finish: bool, + tasks0: Seq<(TestId, bool)>, values0: Seq, tasks1: Seq<(TestId, bool)>, values1: Seq) + requires model::graph_wf(g), id@ < g.tests.len(), + test_not_effect(g, id, finish, tasks0, values0, tasks1, values1), + ensures test_not_work(g, tasks1) < test_not_work(g, tasks0.push((id, finish))), + { + model::lemma_graph_test_wf(g, id@); + assert(tasks0.push((id, finish)).drop_last() =~= tasks0); + assert(tasks0.push((id, finish)).last() == (id, finish)); + reveal_with_fuel(test_not_work, 2); + reveal_with_fuel(test_not_node_work, 2); + assert(tasks0.push((id, true)).last() == (id, true)); + assert(tasks0.push((id, true)).drop_last() =~= tasks0); + match g.tests[id@ as int] { + model::TestNode::And(cs) => { + if !finish { + let scheduled = tasks1.subrange(tasks0.len() as int + 1, tasks1.len() as int); + assert(tasks1 =~= tasks0.push((id, true)) + scheduled); + test_lemma_not_work_schedule(g, tasks0.push((id, true)), scheduled, cs, id@); + assert(test_not_work(g, tasks1) == test_not_work(g, tasks0) + 1 + test_not_children_work(g, cs, id@)); + assert(test_not_node_work(g, id@) == 2 + test_not_children_work(g, cs, id@)); + } + }, + model::TestNode::Or(cs) => { + if !finish { + let scheduled = tasks1.subrange(tasks0.len() as int + 1, tasks1.len() as int); + assert(tasks1 =~= tasks0.push((id, true)) + scheduled); + test_lemma_not_work_schedule(g, tasks0.push((id, true)), scheduled, cs, id@); + assert(test_not_work(g, tasks1) == test_not_work(g, tasks0) + 1 + test_not_children_work(g, cs, id@)); + assert(test_not_node_work(g, id@) == 2 + test_not_children_work(g, cs, id@)); + } + }, + _ => {}, + } + } + + pub proof fn test_lemma_combo_concat(g: model::Graph, theta: Subst, event: EventView, + left: Seq, right: Seq, and: bool) + ensures test_combo(g, theta, left + right, event, and) + == if and { test_combo(g, theta, left, event, and) && test_combo(g, theta, right, event, and) } + else { test_combo(g, theta, left, event, and) || test_combo(g, theta, right, event, and) }, + decreases right.len(), + { + if right.len() == 0 { assert(left + right =~= left); } + else { + test_lemma_combo_concat(g, theta, event, left, right.drop_last(), and); + test_lemma_combo_push(g, theta, event, right.drop_last(), right.last(), and); + test_lemma_combo_push(g, theta, event, left + right.drop_last(), right.last(), and); + assert(right.drop_last().push(right.last()) =~= right); + assert((left + right.drop_last()).push(right.last()) =~= left + right); + } + } + + pub proof fn test_lemma_redundant_push(g: model::Graph, a: TestId, siblings: Seq, b: TestId, and: bool) + ensures test_redundant_in(g, a, siblings.push(b), and) + == (test_redundant_in(g, a, siblings, and) || test_redundancy(g, a, b, and)), + { + if test_redundant_in(g, a, siblings.push(b), and) { + let i = choose|i: int| 0 <= i < siblings.push(b).len() && test_redundancy(g, a, siblings.push(b)[i], and); + } else { + assert(!test_redundancy(g, a, siblings.push(b)[siblings.len() as int], and)); + assert forall|i: int| 0 <= i < siblings.len() implies !test_redundancy(g, a, siblings[i], and) by { + assert(siblings.push(b)[i] == siblings[i]); + } + } + } + + // Regex normalization proofs. + pub struct RegexModeModel { + pub intersect: bool, + pub identity: RegexId, + pub absorber: RegexId, + } + pub struct RegexStatsModel { + pub all_nullable: bool, + pub any_nullable: bool, + pub epsilon: bool, + pub complement: bool, + pub has_nonnullable: bool, + } + impl View for RegexMode { + type V = RegexModeModel; + open(super) spec fn view(&self) -> RegexModeModel { + RegexModeModel { intersect: self.intersect, identity: self.identity, absorber: self.absorber } + } + } + impl View for RegexStats { + type V = RegexStatsModel; + open(super) spec fn view(&self) -> RegexStatsModel { + RegexStatsModel { all_nullable: self.all_nullable, any_nullable: self.any_nullable, + epsilon: self.epsilon, complement: self.complement, has_nonnullable: self.has_nonnullable } + } + } + + pub open spec fn regex_unbounded_kind(g: model::Graph, kind: model::RegexKindNode) -> language::Regex { + match kind { + model::RegexKindNode::Empty => language::Regex::Empty, + model::RegexKindNode::All => language::Regex::All, + model::RegexKindNode::Epsilon => language::Regex::Epsilon, + model::RegexKindNode::Test(t) => language::Regex::Test(model::lift_test(g, t)), + model::RegexKindNode::Union(cs) => language::Regex::Union(model::lift_regexes(g, cs)), + model::RegexKindNode::Intersect(cs) => language::Regex::Intersect(model::lift_regexes(g, cs)), + model::RegexKindNode::Concat(cs) => language::Regex::Concat(model::lift_regexes(g, cs)), + model::RegexKindNode::Star(r) => language::Regex::Star(Box::new(model::lift_regex(g, r))), + model::RegexKindNode::Not(r) => language::Regex::Not(Box::new(model::lift_regex(g, r))), + } + } + + pub proof fn regex_unfold(g: model::Graph, id: nat) + requires model::graph_wf(g), id < g.regexes.len(), + ensures model::lift_regex(g, id) == model::lift_regex_kind(g, g.regexes[id as int].kind), + model::lift_regex(g, id) == regex_unbounded_kind(g, g.regexes[id as int].kind), + g.regexes[id as int].nullable == language::nullable(model::lift_regex(g, id)), + model::regex_node_wf_at(g, g.regexes[id as int], id), + { + model::lemma_graph_regex_wf(g, id); + let node = g.regexes[id as int]; + assert(model::regex_node_wf_at(g, node, id)); + match node.kind { + model::RegexKindNode::Union(cs) | model::RegexKindNode::Concat(cs) | model::RegexKindNode::Intersect(cs) => { + assert(model::lift_regexes_bounded(g, cs, id) =~= model::lift_regexes(g, cs)); + assert(model::lift_regexes_bounded(g, cs, g.regexes.len()) =~= model::lift_regexes(g, cs)); + }, + _ => {}, + } + } + + pub proof fn regex_constants(g: model::Graph) + requires model::graph_wf(g), + ensures model::lift_regex(g, g.constants.empty) == language::Regex::Empty, + model::lift_regex(g, g.constants.all) == language::Regex::All, + model::lift_regex(g, g.constants.epsilon) == language::Regex::Epsilon, + model::lift_test(g, g.constants.test_true) == model::Test::True, + model::lift_test(g, g.constants.test_false) == model::Test::False, + g.constants.empty < g.regexes.len(), g.constants.all < g.regexes.len(), g.constants.epsilon < g.regexes.len(), + g.constants.test_true < g.tests.len(), g.constants.test_false < g.tests.len(), + { + model::lemma_graph_wf_elim(g); + } + + pub proof fn regex_star_nil(sem: spec_fn(L, EventView) -> bool, r: language::Regex) + ensures language::numeric_lang(sem, language::Regex::Star(Box::new(r)), Seq::empty()), + { + let parts = Seq::>::empty(); + assert(parts.flatten() == Seq::::empty()); + assert(forall|i: int| 0 <= i < parts.len() ==> language::numeric_lang(sem, r, parts[i])); + } + + pub proof fn regex_star_single(sem: spec_fn(L, EventView) -> bool, r: language::Regex, word: Seq) + requires language::numeric_lang(sem, r, word), + ensures language::numeric_lang(sem, language::Regex::Star(Box::new(r)), word), + { + let parts = seq![word]; + parts.lemma_flatten_one_element(); + assert forall|i: int| 0 <= i < parts.len() implies language::numeric_lang(sem, r, parts[i]) by { + assert(i == 0); + } + } + + pub proof fn regex_star_join(sem: spec_fn(L, EventView) -> bool, r: language::Regex, a: Seq, b: Seq) + requires language::numeric_lang(sem, language::Regex::Star(Box::new(r)), a), + language::numeric_lang(sem, language::Regex::Star(Box::new(r)), b), + ensures language::numeric_lang(sem, language::Regex::Star(Box::new(r)), a + b), + { + let ap = choose|p: Seq>| a == p.flatten() + && forall|i: int| 0 <= i < p.len() ==> language::numeric_lang(sem, r, p[i]); + let bp = choose|p: Seq>| b == p.flatten() + && forall|i: int| 0 <= i < p.len() ==> language::numeric_lang(sem, r, p[i]); + let parts = ap + bp; + vstd::seq_lib::lemma_flatten_concat(ap, bp); + assert(parts.flatten() == a + b); + assert forall|i: int| 0 <= i < parts.len() implies language::numeric_lang(sem, r, parts[i]) by { + if i < ap.len() { assert(parts[i] == ap[i]); } + else { assert(parts[i] == bp[i - ap.len()]); } + } + } + + pub proof fn regex_star_parts(sem: spec_fn(L, EventView) -> bool, r: language::Regex, parts: Seq>) + requires forall|i: int| 0 <= i < parts.len() ==> language::numeric_lang(sem, language::Regex::Star(Box::new(r)), parts[i]), + ensures language::numeric_lang(sem, language::Regex::Star(Box::new(r)), parts.flatten()), + decreases parts.len(), + { + if parts.len() == 0 { + regex_star_nil(sem, r); + } else { + assert forall|i: int| 0 <= i < parts.drop_first().len() + implies language::numeric_lang(sem, language::Regex::Star(Box::new(r)), parts.drop_first()[i]) by { + assert(parts.drop_first()[i] == parts[i + 1]); + } + regex_star_parts(sem, r, parts.drop_first()); + regex_star_join(sem, r, parts[0], parts.drop_first().flatten()); + } + } + + pub proof fn regex_star_collapse(sem: spec_fn(L, EventView) -> bool, r: language::Regex, word: Seq) + ensures language::numeric_lang(sem, language::Regex::Star(Box::new(language::Regex::Star(Box::new(r)))), word) + == language::numeric_lang(sem, language::Regex::Star(Box::new(r)), word), + { + if language::numeric_lang(sem, language::Regex::Star(Box::new(language::Regex::Star(Box::new(r)))), word) { + let parts = choose|p: Seq>| word == p.flatten() + && forall|i: int| 0 <= i < p.len() ==> language::numeric_lang(sem, language::Regex::Star(Box::new(r)), p[i]); + regex_star_parts(sem, r, parts); + } + if language::numeric_lang(sem, language::Regex::Star(Box::new(r)), word) { + regex_star_single(sem, language::Regex::Star(Box::new(r)), word); + } + } + + pub proof fn regex_star_constants(sem: spec_fn(L, EventView) -> bool, word: Seq) + ensures language::numeric_lang(sem, language::Regex::Star(Box::new(language::Regex::::Empty)), word) == (word.len() == 0), + language::numeric_lang(sem, language::Regex::Star(Box::new(language::Regex::::Epsilon)), word) == (word.len() == 0), + language::numeric_lang(sem, language::Regex::Star(Box::new(language::Regex::::All)), word), + { + if language::numeric_lang(sem, language::Regex::Star(Box::new(language::Regex::::Empty)), word) { + let parts = choose|p: Seq>| word == p.flatten() + && forall|i: int| 0 <= i < p.len() ==> language::numeric_lang(sem, language::Regex::::Empty, p[i]); + assert(parts.len() == 0) by { if parts.len() > 0 { assert(language::numeric_lang(sem, language::Regex::::Empty, parts[0])); } } + } + if language::numeric_lang(sem, language::Regex::Star(Box::new(language::Regex::::Epsilon)), word) { + let parts = choose|p: Seq>| word == p.flatten() + && forall|i: int| 0 <= i < p.len() ==> language::numeric_lang(sem, language::Regex::::Epsilon, p[i]); + language::lemma_flatten_empty(parts); + } + if word.len() == 0 { + assert(word =~= Seq::::empty()); + regex_star_nil(sem, language::Regex::::Empty); + regex_star_nil(sem, language::Regex::::Epsilon); + } + regex_star_single(sem, language::Regex::::All, word); + } + + pub proof fn regex_star_test_true(sem: spec_fn(L, EventView) -> bool, leaf: L, word: Seq) + requires forall|event: EventView| #[trigger] sem(leaf, event), + ensures language::numeric_lang(sem, language::Regex::Star(Box::new(language::Regex::Test(leaf))), word), + decreases word.len(), + { + if word.len() == 0 { + assert(word =~= Seq::::empty()); + regex_star_nil(sem, language::Regex::Test(leaf)); + } else { + let tail = word.drop_first(); + regex_star_test_true(sem, leaf, tail); + assert(language::numeric_lang(sem, language::Regex::Test(leaf), seq![word[0]])); + regex_star_single(sem, language::Regex::Test(leaf), seq![word[0]]); + regex_star_join(sem, language::Regex::Test(leaf), seq![word[0]], tail); + assert(word =~= seq![word[0]] + tail); + } + } + + pub proof fn regex_star_laws(g: model::Graph, id: nat) + requires model::graph_wf(g), id < g.regexes.len(), + ensures forall|theta: Subst, word: Seq| + #![trigger language::numeric_lang(model::gsem(theta), language::Regex::Star(Box::new(model::lift_regex(g, id))), word)] + match g.regexes[id as int].kind { + model::RegexKindNode::Empty | model::RegexKindNode::Epsilon => + language::numeric_lang(model::gsem(theta), language::Regex::Star(Box::new(model::lift_regex(g, id))), word) + == (word.len() == 0), + model::RegexKindNode::All => + language::numeric_lang(model::gsem(theta), language::Regex::Star(Box::new(model::lift_regex(g, id))), word), + model::RegexKindNode::Test(t) => t == g.constants.test_true ==> + language::numeric_lang(model::gsem(theta), language::Regex::Star(Box::new(model::lift_regex(g, id))), word), + model::RegexKindNode::Star(_) => + language::numeric_lang(model::gsem(theta), language::Regex::Star(Box::new(model::lift_regex(g, id))), word) + == model::regex_lang(g, theta, id, word), + _ => true, + }, + { + regex_unfold(g, id); + regex_constants(g); + assert forall|theta: Subst, word: Seq| + #![trigger language::numeric_lang(model::gsem(theta), language::Regex::Star(Box::new(model::lift_regex(g, id))), word)] + match g.regexes[id as int].kind { + model::RegexKindNode::Empty | model::RegexKindNode::Epsilon => + language::numeric_lang(model::gsem(theta), language::Regex::Star(Box::new(model::lift_regex(g, id))), word) + == (word.len() == 0), + model::RegexKindNode::All => + language::numeric_lang(model::gsem(theta), language::Regex::Star(Box::new(model::lift_regex(g, id))), word), + model::RegexKindNode::Test(t) => t == g.constants.test_true ==> + language::numeric_lang(model::gsem(theta), language::Regex::Star(Box::new(model::lift_regex(g, id))), word), + model::RegexKindNode::Star(_) => + language::numeric_lang(model::gsem(theta), language::Regex::Star(Box::new(model::lift_regex(g, id))), word) + == model::regex_lang(g, theta, id, word), + _ => true, + } by { + let sem = model::gsem(theta); + match g.regexes[id as int].kind { + model::RegexKindNode::Empty | model::RegexKindNode::Epsilon | model::RegexKindNode::All => { + regex_star_constants(sem, word); + }, + model::RegexKindNode::Test(t) => if t == g.constants.test_true { + assert(forall|event: EventView| #[trigger] sem(model::Test::True, event)); + regex_star_test_true(sem, model::Test::True, word); + }, + model::RegexKindNode::Star(r) => { regex_star_collapse(sem, model::lift_regex(g, r), word); }, + _ => {}, + } + } + } + + #[verifier::opaque] + pub open spec fn regex_children(g: model::Graph, id: nat) -> Seq { + match g.regexes[id as int].kind { + model::RegexKindNode::Union(cs) | model::RegexKindNode::Concat(cs) | model::RegexKindNode::Intersect(cs) => cs, + _ => Seq::empty(), + } + } + + pub open spec fn regex_concat_nats(g: model::Graph, theta: Subst, ids: Seq, word: Seq) -> bool { + language::numeric_lang(model::gsem(theta), language::Regex::Concat(model::lift_regexes(g, ids)), word) + } + + pub proof fn regex_concat_append(sem: spec_fn(L, EventView) -> bool, a: Seq>, b: Seq>, word: Seq) + ensures language::numeric_lang(sem, language::Regex::Concat(a + b), word) + == (exists|u: Seq, v: Seq| word == u + v + && language::numeric_lang(sem, language::Regex::Concat(a), u) + && language::numeric_lang(sem, language::Regex::Concat(b), v)), + { + if language::numeric_lang(sem, language::Regex::Concat(a + b), word) { + let parts = choose|p: Seq>| p.len() == (a + b).len() && word == p.flatten() + && forall|i: int| 0 <= i < (a + b).len() ==> language::numeric_lang(sem, (a + b)[i], p[i]); + let ap = parts.subrange(0, a.len() as int); + let bp = parts.subrange(a.len() as int, parts.len() as int); + assert(parts =~= ap + bp); + vstd::seq_lib::lemma_flatten_concat(ap, bp); + assert(parts.flatten() == ap.flatten() + bp.flatten()); + assert forall|i: int| 0 <= i < a.len() implies language::numeric_lang(sem, a[i], ap[i]) by { + assert(a[i] == (a + b)[i]); + } + assert forall|i: int| 0 <= i < b.len() implies language::numeric_lang(sem, b[i], bp[i]) by { + assert(b[i] == (a + b)[a.len() + i]); + assert(bp[i] == parts[a.len() + i]); + } + assert(language::numeric_lang(sem, language::Regex::Concat(a), ap.flatten())); + assert(language::numeric_lang(sem, language::Regex::Concat(b), bp.flatten())); + } + if exists|u: Seq, v: Seq| word == u + v + && language::numeric_lang(sem, language::Regex::Concat(a), u) + && language::numeric_lang(sem, language::Regex::Concat(b), v) { + let (u, v) = choose|u: Seq, v: Seq| word == u + v + && language::numeric_lang(sem, language::Regex::Concat(a), u) + && language::numeric_lang(sem, language::Regex::Concat(b), v); + let ap = choose|p: Seq>| p.len() == a.len() && u == p.flatten() + && forall|i: int| 0 <= i < a.len() ==> language::numeric_lang(sem, a[i], p[i]); + let bp = choose|p: Seq>| p.len() == b.len() && v == p.flatten() + && forall|i: int| 0 <= i < b.len() ==> language::numeric_lang(sem, b[i], p[i]); + let parts = ap + bp; + vstd::seq_lib::lemma_flatten_concat(ap, bp); + assert(parts.flatten() == word); + assert forall|i: int| 0 <= i < (a + b).len() implies language::numeric_lang(sem, (a + b)[i], parts[i]) by { + if i < a.len() { assert((a + b)[i] == a[i]); assert(parts[i] == ap[i]); } + else { assert((a + b)[i] == b[i - a.len()]); assert(parts[i] == bp[i - a.len()]); } + } + } + } + + pub proof fn regex_concat_empty(sem: spec_fn(L, EventView) -> bool, word: Seq) + ensures language::numeric_lang(sem, language::Regex::Concat(Seq::>::empty()), word) == (word.len() == 0), + { + if language::numeric_lang(sem, language::Regex::Concat(Seq::>::empty()), word) { + let parts = choose|p: Seq>| p.len() == 0 && word == p.flatten() + && forall|i: int| 0 <= i < 0 ==> language::numeric_lang(sem, Seq::>::empty()[i], p[i]); + assert(parts =~= Seq::>::empty()); + } + if word.len() == 0 { + let parts = Seq::>::empty(); + assert(word =~= parts.flatten()); + assert(forall|i: int| 0 <= i < 0 ==> language::numeric_lang(sem, Seq::>::empty()[i], parts[i])); + } + } + + pub proof fn regex_concat_replace(sem: spec_fn(L, EventView) -> bool, prefix: Seq>, tail: Seq>, r: language::Regex) + requires forall|word: Seq| language::numeric_lang(sem, language::Regex::Concat(tail), word) == language::numeric_lang(sem, r, word), + ensures forall|word: Seq| language::numeric_lang(sem, language::Regex::Concat(prefix + tail), word) + == language::numeric_lang(sem, language::Regex::Concat(prefix.push(r)), word), + { + assert forall|word: Seq| language::numeric_lang(sem, language::Regex::Concat(prefix + tail), word) + == language::numeric_lang(sem, language::Regex::Concat(prefix.push(r)), word) by { + assert(prefix.push(r) =~= prefix + seq![r]); + regex_concat_append(sem, prefix, tail, word); + regex_concat_append(sem, prefix, seq![r], word); + if language::numeric_lang(sem, language::Regex::Concat(prefix + tail), word) { + let (u, v) = choose|u: Seq, v: Seq| word == u + v + && language::numeric_lang(sem, language::Regex::Concat(prefix), u) + && language::numeric_lang(sem, language::Regex::Concat(tail), v); + assert(language::numeric_lang(sem, r, v)); + language::lemma_concat_singleton(sem, r, v); + assert(exists|u: Seq, v: Seq| word == u + v + && language::numeric_lang(sem, language::Regex::Concat(prefix), u) + && language::numeric_lang(sem, language::Regex::Concat(seq![r]), v)); + } + if language::numeric_lang(sem, language::Regex::Concat(prefix.push(r)), word) { + let (u, v) = choose|u: Seq, v: Seq| word == u + v + && language::numeric_lang(sem, language::Regex::Concat(prefix), u) + && language::numeric_lang(sem, language::Regex::Concat(seq![r]), v); + language::lemma_concat_singleton(sem, r, v); + assert(language::numeric_lang(sem, language::Regex::Concat(tail), v)); + assert(exists|u: Seq, v: Seq| word == u + v + && language::numeric_lang(sem, language::Regex::Concat(prefix), u) + && language::numeric_lang(sem, language::Regex::Concat(tail), v)); + } + } + } + + pub proof fn regex_concat_append_congruent(sem: spec_fn(L, EventView) -> bool, left: Seq>, right: Seq>, suffix: Seq>) + requires forall|word: Seq| language::numeric_lang(sem, language::Regex::Concat(left), word) + == language::numeric_lang(sem, language::Regex::Concat(right), word), + ensures forall|word: Seq| language::numeric_lang(sem, language::Regex::Concat(left + suffix), word) + == language::numeric_lang(sem, language::Regex::Concat(right + suffix), word), + { + assert forall|word: Seq| language::numeric_lang(sem, language::Regex::Concat(left + suffix), word) + == language::numeric_lang(sem, language::Regex::Concat(right + suffix), word) by { + regex_concat_append(sem, left, suffix, word); + regex_concat_append(sem, right, suffix, word); + } + } + + pub proof fn regex_concat_step_law(g: model::Graph, before: Seq, id: nat, after: Seq) + requires model::graph_wf(g), id < g.regexes.len(), + after == before + match g.regexes[id as int].kind { + model::RegexKindNode::Epsilon => Seq::empty(), + model::RegexKindNode::Concat(cs) => cs, + _ => seq![id], + }, + ensures forall|theta: Subst, word: Seq| + regex_concat_nats(g, theta, after, word) + == regex_concat_nats(g, theta, before.push(id), word), + { + hide(language::numeric_lang); + hide(model::tables_wf); + hide(model::lift_regex); + regex_unfold(g, id); + assert forall|theta: Subst, word: Seq| + regex_concat_nats(g, theta, after, word) + == regex_concat_nats(g, theta, before.push(id), word) by { + let sem = model::gsem(theta); + let lhs = model::lift_regexes(g, before); + let rhs = match g.regexes[id as int].kind { + model::RegexKindNode::Epsilon => Seq::empty(), + model::RegexKindNode::Concat(cs) => model::lift_regexes(g, cs), + _ => seq![model::lift_regex(g, id)], + }; + assert(model::lift_regexes(g, after) =~= lhs + rhs); + assert(model::lift_regexes(g, before.push(id)) =~= lhs + seq![model::lift_regex(g, id)]); + assert(lhs.push(model::lift_regex(g, id)) =~= lhs + seq![model::lift_regex(g, id)]); + assert forall|v: Seq| language::numeric_lang(sem, language::Regex::Concat(rhs), v) + == language::numeric_lang(sem, model::lift_regex(g, id), v) by { + language::lemma_concat_singleton(sem, model::lift_regex(g, id), v); + match g.regexes[id as int].kind { + model::RegexKindNode::Epsilon => { + regex_concat_empty::(sem, v); + reveal(language::numeric_lang); + }, + _ => {}, + } + } + regex_concat_replace(sem, lhs, rhs, model::lift_regex(g, id)); + } + } + + pub open spec fn regex_concat_piece(g: model::Graph, id: nat) -> Seq { + match g.regexes[id as int].kind { + model::RegexKindNode::Epsilon => Seq::empty(), + model::RegexKindNode::Concat(cs) => cs, + _ => seq![id], + } + } + + pub open spec fn regex_concat_flat(g: model::Graph, ids: Seq) -> Seq + decreases ids.len(), + { + if ids.len() == 0 { Seq::empty() } + else { regex_concat_flat(g, ids.drop_last()) + regex_concat_piece(g, ids.last()@) } + } + + pub proof fn regex_children_wf(g: model::Graph, id: nat) + requires model::graph_wf(g), id < g.regexes.len(), + ensures model::bounded(regex_children(g, id), g.regexes.len()), + { + reveal(regex_children); + model::lemma_graph_regex_wf(g, id); + assert(model::regex_node_wf_at(g, g.regexes[id as int], id)); + } + + pub proof fn regex_concat_flat_wf(g: model::Graph, ids: Seq) + requires model::graph_wf(g), regex_ids_valid(g, ids), + ensures model::bounded(regex_concat_flat(g, ids), g.regexes.len()), + decreases ids.len(), + { + if ids.len() > 0 { + regex_concat_flat_wf(g, ids.drop_last()); + regex_children_wf(g, ids.last()@); + regex_children_count(g, ids.last()@); + } + } + + pub proof fn regex_concat_flat_law(g: model::Graph, ids: Seq, theta: Subst, word: Seq) + requires model::graph_wf(g), regex_ids_valid(g, ids), + ensures regex_concat_nats(g, theta, regex_concat_flat(g, ids), word) + == concat_combo(g, theta, ids, word), + decreases ids.len(), + { + hide(language::numeric_lang); + hide(model::tables_wf); + hide(model::lift_regex); + if ids.len() > 0 { + let before = ids.drop_last(); + let id = ids.last()@; + let flat = regex_concat_flat(g, before); + regex_concat_step_law(g, flat, id, flat + regex_concat_piece(g, id)); + let sem = model::gsem(theta); + let flat_lifts = model::lift_regexes(g, flat); + let input_lifts = model::lift_regexes(g, model::regex_ids(before)); + let last_lifts = seq![model::lift_regex(g, id)]; + assert(model::lift_regexes(g, flat.push(id)) =~= flat_lifts + last_lifts); + assert(model::lift_regexes(g, model::regex_ids(ids)) =~= input_lifts + last_lifts); + assert forall|v: Seq| language::numeric_lang(sem, language::Regex::Concat(flat_lifts), v) + == language::numeric_lang(sem, language::Regex::Concat(input_lifts), v) by { + regex_concat_flat_law(g, before, theta, v); + } + regex_concat_append_congruent(sem, flat_lifts, input_lifts, last_lifts); + } else { + assert(model::regex_ids(ids) =~= regex_concat_flat(g, ids)); + } + } + + pub proof fn regex_concat_absorber(g: model::Graph, ids: Seq, index: int) + requires model::graph_wf(g), regex_ids_valid(g, ids), 0 <= index < ids.len(), + g.regexes[ids[index]@ as int].kind == model::RegexKindNode::Empty, + ensures forall|theta: Subst, word: Seq| !concat_combo(g, theta, ids, word), + { + regex_unfold(g, ids[index]@); + assert forall|theta: Subst, word: Seq| + !concat_combo(g, theta, ids, word) by { + if concat_combo(g, theta, ids, word) { + let lifts = model::lift_regexes(g, model::regex_ids(ids)); + let parts = choose|p: Seq>| p.len() == lifts.len() && word == p.flatten() + && forall|i: int| 0 <= i < lifts.len() ==> language::numeric_lang(model::gsem(theta), lifts[i], p[i]); + assert(lifts[index] == language::Regex::Empty); + assert(language::numeric_lang(model::gsem(theta), lifts[index], parts[index])); + } + } + } + + pub open spec fn regex_nullable_combo(g: model::Graph, ids: Seq, and: bool) -> bool { + if and { forall|i: int| 0 <= i < ids.len() ==> language::nullable(model::lift_regex(g, ids[i]@)) } + else { exists|i: int| 0 <= i < ids.len() && language::nullable(model::lift_regex(g, ids[i]@)) } + } + + pub proof fn regex_concat_congruent( + sem: spec_fn(L, EventView) -> bool, left: Seq>, right: Seq>, + ) + requires left.len() == right.len(), + forall|i: int, word: Seq| 0 <= i < left.len() + ==> language::numeric_lang(sem, left[i], word) == language::numeric_lang(sem, right[i], word), + ensures forall|word: Seq| language::numeric_lang(sem, language::Regex::Concat(left), word) + == language::numeric_lang(sem, language::Regex::Concat(right), word), + { + assert forall|word: Seq| language::numeric_lang(sem, language::Regex::Concat(left), word) + == language::numeric_lang(sem, language::Regex::Concat(right), word) by { + if language::numeric_lang(sem, language::Regex::Concat(left), word) { + let parts = choose|p: Seq>| p.len() == left.len() && word == p.flatten() + && forall|i: int| 0 <= i < left.len() ==> language::numeric_lang(sem, left[i], p[i]); + assert forall|i: int| 0 <= i < right.len() implies language::numeric_lang(sem, right[i], parts[i]) by { + assert(language::numeric_lang(sem, left[i], parts[i])); + } + assert(language::numeric_lang(sem, language::Regex::Concat(right), word)); + } + if language::numeric_lang(sem, language::Regex::Concat(right), word) { + let parts = choose|p: Seq>| p.len() == right.len() && word == p.flatten() + && forall|i: int| 0 <= i < right.len() ==> language::numeric_lang(sem, right[i], p[i]); + assert forall|i: int| 0 <= i < left.len() implies language::numeric_lang(sem, left[i], parts[i]) by { + assert(language::numeric_lang(sem, right[i], parts[i])); + } + assert(language::numeric_lang(sem, language::Regex::Concat(left), word)); + } + } + } + + pub proof fn regex_child_exact(g: model::Graph, id: nat, index: nat, child: nat) + requires model::graph_wf(g), id < g.regexes.len(), + model::regex_node_child(g.regexes[id as int].kind, index) == Some(child), + ensures index < regex_children(g, id).len(), regex_children(g, id)[index as int] == child, + child < g.regexes.len(), + { + reveal(regex_children); + regex_children_wf(g, id); + match g.regexes[id as int].kind { + model::RegexKindNode::Union(_) | model::RegexKindNode::Concat(_) | model::RegexKindNode::Intersect(_) => {}, + _ => {}, + } + } + + pub proof fn regex_lemma_child_available(g: model::Graph, id: nat, index: nat) + requires id < g.regexes.len(), index < regex_children(g, id).len(), + ensures model::regex_node_child(g.regexes[id as int].kind, index) is Some, + { + reveal(regex_children); + match g.regexes[id as int].kind { + model::RegexKindNode::Union(_) | model::RegexKindNode::Concat(_) | model::RegexKindNode::Intersect(_) => {}, + _ => {}, + } + } + + pub proof fn regex_ids_push(ids: Seq, id: RegexId) + ensures model::regex_ids(ids.push(id)) == model::regex_ids(ids).push(id@), + { + assert(model::regex_ids(ids.push(id)) =~= model::regex_ids(ids).push(id@)); + } + + pub proof fn regex_concat_flat_prefix(g: model::Graph, ids: Seq, index: int) + requires 0 <= index < ids.len(), + ensures regex_concat_flat(g, ids.subrange(0, index + 1)) + == regex_concat_flat(g, ids.subrange(0, index)) + regex_concat_piece(g, ids[index]@), + { + assert(ids.subrange(0, index + 1).drop_last() =~= ids.subrange(0, index)); + } + + pub proof fn regex_nullable_prefix(g: model::Graph, ids: Seq, index: int, and: bool) + requires 0 <= index < ids.len(), + ensures regex_nullable_combo(g, ids.subrange(0, index + 1), and) + == if and { regex_nullable_combo(g, ids.subrange(0, index), and) && language::nullable(model::lift_regex(g, ids[index]@)) } + else { regex_nullable_combo(g, ids.subrange(0, index), and) || language::nullable(model::lift_regex(g, ids[index]@)) }, + { + hide(model::lift_regex); + hide(language::nullable); + let prefix = ids.subrange(0, index); + let full = ids.subrange(0, index + 1); + assert(full =~= prefix.push(ids[index])); + if and { + if regex_nullable_combo(g, full, true) { + assert(language::nullable(model::lift_regex(g, full[index]@))); + assert forall|i: int| 0 <= i < prefix.len() implies language::nullable(model::lift_regex(g, prefix[i]@)) by { + assert(prefix[i] == full[i]); + } + } + if regex_nullable_combo(g, prefix, true) && language::nullable(model::lift_regex(g, ids[index]@)) { + assert forall|i: int| 0 <= i < full.len() implies language::nullable(model::lift_regex(g, full[i]@)) by { + if i < index { assert(full[i] == prefix[i]); } + else { assert(full[i] == ids[index]); } + } + } + } else { + if regex_nullable_combo(g, full, false) { + let i = choose|i: int| 0 <= i < full.len() && language::nullable(model::lift_regex(g, full[i]@)); + if i < index { + assert(prefix[i] == full[i]); + assert(regex_nullable_combo(g, prefix, false)); + } else { assert(full[i] == ids[index]); } + } + if regex_nullable_combo(g, prefix, false) { + let i = choose|i: int| 0 <= i < prefix.len() && language::nullable(model::lift_regex(g, prefix[i]@)); + assert(prefix[i] == full[i]); + assert(regex_nullable_combo(g, full, false)); + } + if language::nullable(model::lift_regex(g, ids[index]@)) { + assert(full[index] == ids[index]); + assert(regex_nullable_combo(g, full, false)); + } + } + } + + pub proof fn regex_children_count(g: model::Graph, id: nat) + requires id < g.regexes.len(), + ensures match g.regexes[id as int].kind { + model::RegexKindNode::Union(cs) | model::RegexKindNode::Concat(cs) | model::RegexKindNode::Intersect(cs) => regex_children(g, id) == cs, + _ => regex_children(g, id).len() == 0, + }, + { + reveal(regex_children); + } + + pub open spec fn regex_dual(g: model::Graph, id: nat, intersect: bool) -> bool { + match g.regexes[id as int].kind { + model::RegexKindNode::Union(_) => intersect, + model::RegexKindNode::Intersect(_) => !intersect, + _ => false, + } + } + + pub open spec fn regex_absorbed_by(g: model::Graph, a: nat, b: nat, intersect: bool) -> bool { + a != b && regex_dual(g, a, intersect) + && if regex_dual(g, b, intersect) { + forall|i: int| 0 <= i < regex_children(g, b).len() ==> regex_children(g, a).contains(regex_children(g, b)[i]) + } else { regex_children(g, a).contains(b) } + } + + pub proof fn regex_dual_order(g: model::Graph, id: nat, intersect: bool) + requires model::graph_wf(g), id < g.regexes.len(), regex_dual(g, id, intersect), + ensures model::strictly_increasing(regex_children(g, id)), + { + reveal(regex_children); + model::lemma_graph_regex_wf(g, id); + assert(model::regex_node_wf_at(g, g.regexes[id as int], id)); + } + + pub proof fn regex_ids_contains(ids: Seq, id: RegexId) + ensures model::regex_ids(ids).contains(id@) == ids.contains(id), + { + if model::regex_ids(ids).contains(id@) { + let i = choose|i: int| 0 <= i < ids.len() && model::regex_ids(ids)[i] == id@; + assert(ids[i] == id); + } + if ids.contains(id) { + let i = choose|i: int| 0 <= i < ids.len() && ids[i] == id; + assert(model::regex_ids(ids)[i] == id@); + } + } + + pub open spec fn regex_mode_wf(g: model::Graph, mode: RegexModeModel) -> bool { + mode.identity@ == (if mode.intersect { g.constants.all } else { g.constants.empty }) + && mode.absorber@ == (if mode.intersect { g.constants.empty } else { g.constants.all }) + } + + pub open spec fn regex_set_piece(g: model::Graph, id: nat, mode: RegexModeModel) -> Seq { + if id == mode.identity@ { Seq::empty() } + else { match g.regexes[id as int].kind { + model::RegexKindNode::Union(cs) => if !mode.intersect { cs } else { seq![id] }, + model::RegexKindNode::Intersect(cs) => if mode.intersect { cs } else { seq![id] }, + _ => seq![id], + } } + } + + pub open spec fn regex_nonnullable_except_not_epsilon(g: model::Graph, id: nat, epsilon: nat) -> bool { + !language::nullable(model::lift_regex(g, id)) && g.regexes[id as int].kind != model::RegexKindNode::Not(epsilon) + } + + pub open spec fn regex_has_complement_model(g: model::Graph, id: nat, siblings: Seq) -> bool { + match g.regexes[id as int].kind { + model::RegexKindNode::Not(inner) => model::regex_ids(siblings).contains(inner), + _ => false, + } + } + + pub open spec fn regex_stats_update(g: model::Graph, ids: Seq, index: int, epsilon: RegexId, prior: RegexStatsModel, complements: bool) -> RegexStatsModel { + let id = ids[index]@; + let nullable = language::nullable(model::lift_regex(g, id)); + RegexStatsModel { + all_nullable: prior.all_nullable && nullable, + any_nullable: prior.any_nullable || (id != epsilon@ && nullable), + epsilon: prior.epsilon || id == epsilon@, + complement: prior.complement || (complements && regex_has_complement_model(g, id, ids)), + has_nonnullable: prior.has_nonnullable || regex_nonnullable_except_not_epsilon(g, id, epsilon@), + } + } + + pub open spec fn regex_retained(g: model::Graph, ids: Seq, index: int, mode: RegexModeModel, stats: RegexStatsModel) -> bool { + let id = ids[index]@; + let redundant = (!mode.intersect && id == g.constants.epsilon && stats.any_nullable) + || (mode.intersect && stats.has_nonnullable && g.regexes[id as int].kind == model::RegexKindNode::Not(g.constants.epsilon)); + !redundant && !(exists|i: int| 0 <= i < ids.len() && regex_absorbed_by(g, id, ids[i]@, mode.intersect)) + } + + pub proof fn regex_nullable_concat_unfold(regex: language::Regex) + ensures match regex { + language::Regex::Concat(children) => language::nullable(regex) + == (forall|i: int| 0 <= i < children.len() ==> language::nullable(children[i])), + _ => true, + }, + { + match regex { language::Regex::Concat(_) => {}, _ => {} } + } + + pub proof fn regex_concat_node_wf(g: model::Graph, ids: Seq, nullable: bool) + requires regex_ids_valid(g, ids), nullable == regex_nullable_combo(g, ids, true), + ensures model::regex_node_wf(g, model::RegexNode { kind: model::RegexKindNode::Concat(model::regex_ids(ids)), nullable }), + { + assert(model::bounded(model::regex_ids(ids), g.regexes.len())); + assert(model::lift_regexes_bounded(g, model::regex_ids(ids), g.regexes.len()) =~= model::lift_regexes(g, model::regex_ids(ids))); + let lifts = model::lift_regexes(g, model::regex_ids(ids)); + let regex = language::Regex::Concat(lifts); + assert(model::lift_regex_kind_bounded(g, model::RegexKindNode::Concat(model::regex_ids(ids)), g.regexes.len()) == regex); + regex_nullable_concat_unfold(regex); + assert(language::nullable(regex) == (forall|i: int| 0 <= i < lifts.len() ==> language::nullable(lifts[i]))); + if regex_nullable_combo(g, ids, true) { + assert forall|i: int| 0 <= i < lifts.len() implies language::nullable(lifts[i]) by { + assert(lifts[i] == model::lift_regex(g, ids[i]@)); + } + } + if language::nullable(regex) { + assert forall|i: int| 0 <= i < ids.len() implies language::nullable(model::lift_regex(g, ids[i]@)) by { + assert(language::nullable(lifts[i])); + } + } + assert forall|i: int| 0 <= i < ids.len() implies + language::nullable(model::lift_regexes(g, model::regex_ids(ids))[i]) + == language::nullable(model::lift_regex(g, ids[i]@)) by {}; + } + + pub proof fn regex_concat_extends(a: model::Graph, b: model::Graph, ids: Seq) + requires model::graph_wf(a), model::graph_extends(a, b), regex_ids_valid(a, ids), + ensures regex_ids_valid(b, ids), + forall|theta: Subst, word: Seq| + concat_combo(a, theta, ids, word) == concat_combo(b, theta, ids, word), + { + model::lemma_graph_wf_elim(a); + model::lemma_lift_stable_under_extends(a, b); + assert(model::lift_regexes(a, model::regex_ids(ids)) =~= model::lift_regexes(b, model::regex_ids(ids))); + } + + pub proof fn regex_concat_normalization_extends(a: model::Graph, b: model::Graph, original: Seq, flat: Seq) + requires model::graph_wf(a), model::graph_extends(a, b), regex_ids_valid(a, original), regex_ids_valid(a, flat), + model::regex_ids(flat) == regex_concat_flat(a, original), + ensures forall|theta: Subst, word: Seq| + concat_combo(b, theta, flat, word) == concat_combo(b, theta, original, word), + { + regex_concat_extends(a, b, original); + regex_concat_extends(a, b, flat); + assert forall|theta: Subst, word: Seq| + concat_combo(b, theta, flat, word) == concat_combo(b, theta, original, word) by { + regex_concat_flat_law(a, original, theta, word); + } + } + + pub proof fn regex_contains_prefix(ids: Seq, index: int, id: RegexId) + requires 0 <= index < ids.len(), + ensures ids.subrange(0, index + 1).contains(id) + == (ids.subrange(0, index).contains(id) || ids[index] == id), + { + assert(ids.subrange(0, index + 1) =~= ids.subrange(0, index).push(ids[index])); + if ids.subrange(0, index + 1).contains(id) { + let i = choose|i: int| 0 <= i < index + 1 && #[trigger] ids.subrange(0, index + 1)[i] == id; + if i < index { + assert(ids.subrange(0, index)[i] == id); + assert(ids.subrange(0, index).contains(id)); + } + else { assert(ids[index] == id); } + } + if ids.subrange(0, index).contains(id) { + let i = choose|i: int| 0 <= i < index && #[trigger] ids.subrange(0, index)[i] == id; + assert(ids.subrange(0, index + 1)[i] == id); + assert(ids.subrange(0, index + 1).contains(id)); + } + if ids[index] == id { + assert(ids.subrange(0, index + 1)[index] == id); + assert(ids.subrange(0, index + 1).contains(id)); + } + } + + pub open spec fn regex_combo_nats(g: model::Graph, theta: Subst, ids: Seq, word: Seq, intersect: bool) -> bool { + if intersect { forall|i: int| 0 <= i < ids.len() ==> model::regex_lang(g, theta, ids[i], word) } + else { exists|i: int| 0 <= i < ids.len() && model::regex_lang(g, theta, ids[i], word) } + } + + pub proof fn regex_language_unfold(sem: spec_fn(L, EventView) -> bool, regex: language::Regex, word: Seq) + ensures match regex { + language::Regex::Union(cs) => language::numeric_lang(sem, regex, word) == (exists|i: int| 0 <= i < cs.len() && language::numeric_lang(sem, cs[i], word)), + language::Regex::Intersect(cs) => language::numeric_lang(sem, regex, word) == (forall|i: int| 0 <= i < cs.len() ==> language::numeric_lang(sem, cs[i], word)), + language::Regex::Test(t) => language::numeric_lang(sem, regex, word) == (word.len() == 1 && sem(t, word[0])), + language::Regex::Not(r) => language::numeric_lang(sem, regex, word) == !language::numeric_lang(sem, *r, word), + language::Regex::Epsilon => language::numeric_lang(sem, regex, word) == (word.len() == 0), + language::Regex::Empty => !language::numeric_lang(sem, regex, word), + language::Regex::All => language::numeric_lang(sem, regex, word), + _ => true, + }, + { + match regex { + language::Regex::Union(_) | language::Regex::Intersect(_) | language::Regex::Test(_) | language::Regex::Not(_) | language::Regex::Epsilon => {}, + _ => {}, + } + } + + pub proof fn regex_node_language(g: model::Graph, id: nat, theta: Subst, word: Seq) + requires model::graph_wf(g), id < g.regexes.len(), + ensures match g.regexes[id as int].kind { + model::RegexKindNode::Union(cs) => model::regex_lang(g, theta, id, word) == regex_combo_nats(g, theta, cs, word, false), + model::RegexKindNode::Intersect(cs) => model::regex_lang(g, theta, id, word) == regex_combo_nats(g, theta, cs, word, true), + model::RegexKindNode::Test(t) => model::regex_lang(g, theta, id, word) + == (word.len() == 1 && model::test_holds(theta, model::lift_test(g, t), word[0])), + model::RegexKindNode::Not(r) => model::regex_lang(g, theta, id, word) == !model::regex_lang(g, theta, r, word), + model::RegexKindNode::Empty => !model::regex_lang(g, theta, id, word), + model::RegexKindNode::All => model::regex_lang(g, theta, id, word), + model::RegexKindNode::Epsilon => model::regex_lang(g, theta, id, word) == (word.len() == 0), + _ => true, + }, + { + regex_unfold(g, id); + let sem = model::gsem(theta); + regex_language_unfold(sem, model::lift_regex(g, id), word); + match g.regexes[id as int].kind { + model::RegexKindNode::Union(cs) => { + if model::regex_lang(g, theta, id, word) { + let i = choose|i: int| 0 <= i < cs.len() && language::numeric_lang(sem, model::lift_regexes(g, cs)[i], word); + assert(model::regex_lang(g, theta, cs[i], word)); + } + if regex_combo_nats(g, theta, cs, word, false) { + let i = choose|i: int| 0 <= i < cs.len() && model::regex_lang(g, theta, cs[i], word); + assert(language::numeric_lang(sem, model::lift_regexes(g, cs)[i], word)); + } + }, + model::RegexKindNode::Intersect(cs) => { + if model::regex_lang(g, theta, id, word) { + assert forall|i: int| 0 <= i < cs.len() implies model::regex_lang(g, theta, cs[i], word) by { + assert(language::numeric_lang(sem, model::lift_regexes(g, cs)[i], word)); + } + } + if regex_combo_nats(g, theta, cs, word, true) { + assert forall|i: int| 0 <= i < cs.len() implies language::numeric_lang(sem, model::lift_regexes(g, cs)[i], word) by { + assert(model::regex_lang(g, theta, cs[i], word)); + } + } + }, + _ => {}, + } + } + + pub proof fn regex_absorption_implication(g: model::Graph, a: nat, b: nat, intersect: bool, theta: Subst, word: Seq) + requires model::graph_wf(g), a < g.regexes.len(), b < g.regexes.len(), regex_absorbed_by(g, a, b, intersect), + ensures if intersect { model::regex_lang(g, theta, b, word) ==> model::regex_lang(g, theta, a, word) } + else { model::regex_lang(g, theta, a, word) ==> model::regex_lang(g, theta, b, word) }, + { + regex_node_language(g, a, theta, word); + regex_node_language(g, b, theta, word); + regex_children_count(g, a); + regex_children_count(g, b); + let ac = regex_children(g, a); + let bc = regex_children(g, b); + if intersect && model::regex_lang(g, theta, b, word) { + if regex_dual(g, b, intersect) { + let j = choose|j: int| 0 <= j < bc.len() && model::regex_lang(g, theta, bc[j], word); + let k = choose|k: int| 0 <= k < ac.len() && ac[k] == bc[j]; + assert(model::regex_lang(g, theta, ac[k], word)); + } else { + let k = choose|k: int| 0 <= k < ac.len() && ac[k] == b; + assert(model::regex_lang(g, theta, ac[k], word)); + } + } + if !intersect && model::regex_lang(g, theta, a, word) { + if regex_dual(g, b, intersect) { + assert forall|j: int| 0 <= j < bc.len() implies model::regex_lang(g, theta, bc[j], word) by { + let k = choose|k: int| 0 <= k < ac.len() && ac[k] == bc[j]; + assert(model::regex_lang(g, theta, ac[k], word)); + } + } else { + let k = choose|k: int| 0 <= k < ac.len() && ac[k] == b; + assert(model::regex_lang(g, theta, ac[k], word)); + } + } + } + + pub open spec fn regex_stats_prefix(g: model::Graph, ids: Seq, count: nat, epsilon: RegexId, stats: RegexStatsModel, complements: bool) -> bool { + count <= ids.len() + && stats.all_nullable == regex_nullable_combo(g, ids.subrange(0, count as int), true) + && stats.any_nullable == (exists|i: int| 0 <= i < count && ids[i] != epsilon && language::nullable(model::lift_regex(g, ids[i]@))) + && stats.epsilon == (exists|i: int| 0 <= i < count && ids[i] == epsilon) + && stats.complement == (complements && exists|i: int| 0 <= i < count && regex_has_complement_model(g, ids[i]@, ids)) + && stats.has_nonnullable == (exists|i: int| 0 <= i < count && regex_nonnullable_except_not_epsilon(g, ids[i]@, epsilon@)) + } + + pub proof fn regex_exists_prefix(predicate: spec_fn(int) -> bool, index: int) + requires index >= 0, + ensures (exists|i: int| 0 <= i < index + 1 && #[trigger] predicate(i)) + == ((exists|i: int| 0 <= i < index && #[trigger] predicate(i)) || predicate(index)), + { + if exists|i: int| 0 <= i < index + 1 && #[trigger] predicate(i) { + let i = choose|i: int| 0 <= i < index + 1 && #[trigger] predicate(i); + if i < index { assert(exists|j: int| 0 <= j < index && #[trigger] predicate(j)); } + } + } + + pub proof fn regex_stats_prefix_step(g: model::Graph, ids: Seq, index: int, epsilon: RegexId, prior: RegexStatsModel, complements: bool) + requires 0 <= index < ids.len(), regex_stats_prefix(g, ids, index as nat, epsilon, prior, complements), + ensures regex_stats_prefix(g, ids, (index + 1) as nat, epsilon, regex_stats_update(g, ids, index, epsilon, prior, complements), complements), + { + regex_nullable_prefix(g, ids, index, true); + regex_exists_prefix(|i: int| ids[i] != epsilon && language::nullable(model::lift_regex(g, ids[i]@)), index); + regex_exists_prefix(|i: int| ids[i] == epsilon, index); + regex_exists_prefix(|i: int| regex_has_complement_model(g, ids[i]@, ids), index); + regex_exists_prefix(|i: int| regex_nonnullable_except_not_epsilon(g, ids[i]@, epsilon@), index); + } + + pub proof fn regex_remove_covered(g: model::Graph, ids: Seq, index: int, witness: int, intersect: bool, theta: Subst, word: Seq) + requires 0 <= index < ids.len(), 0 <= witness < ids.len(), witness != index, + if intersect { model::regex_lang(g, theta, ids[witness]@, word) ==> model::regex_lang(g, theta, ids[index]@, word) } + else { model::regex_lang(g, theta, ids[index]@, word) ==> model::regex_lang(g, theta, ids[witness]@, word) }, + ensures regex_combo(g, theta, ids.remove(index), word, intersect) == regex_combo(g, theta, ids, word, intersect), + { + let reduced = ids.remove(index); + let witness_after = if witness < index { witness } else { witness - 1 }; + assert(reduced[witness_after] == ids[witness]); + if intersect { + if regex_combo(g, theta, reduced, word, true) { + assert(model::regex_lang(g, theta, ids[witness]@, word)); + assert forall|i: int| 0 <= i < ids.len() implies model::regex_lang(g, theta, ids[i]@, word) by { + if i != index { + let j = if i < index { i } else { i - 1 }; + assert(reduced[j] == ids[i]); + assert(model::regex_lang(g, theta, reduced[j]@, word)); + } + } + } + if regex_combo(g, theta, ids, word, true) { + assert forall|j: int| 0 <= j < reduced.len() implies model::regex_lang(g, theta, reduced[j]@, word) by { + let i = if j < index { j } else { j + 1 }; + assert(reduced[j] == ids[i]); + } + } + } else { + if regex_combo(g, theta, ids, word, false) { + let i = choose|i: int| 0 <= i < ids.len() && model::regex_lang(g, theta, ids[i]@, word); + let j = if i == index { witness_after } else if i < index { i } else { i - 1 }; + assert(model::regex_lang(g, theta, reduced[j]@, word)); + } + if regex_combo(g, theta, reduced, word, false) { + let j = choose|j: int| 0 <= j < reduced.len() && model::regex_lang(g, theta, reduced[j]@, word); + let i = if j < index { j } else { j + 1 }; + assert(reduced[j] == ids[i]); + assert(model::regex_lang(g, theta, ids[i]@, word)); + } + } + } + + pub proof fn regex_retention_remove(g: model::Graph, ids: Seq, index: int, mode: RegexModeModel, epsilon: RegexId, stats: RegexStatsModel) + requires model::graph_wf(g), regex_ids_valid(g, ids), 0 <= index < ids.len(), + regex_stats_prefix(g, ids, ids.len(), epsilon, stats, false), epsilon@ == g.constants.epsilon, + !regex_retained(g, ids, index, mode, stats), + ensures regex_ids_valid(g, ids.remove(index)), + forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + ==> regex_combo(g, theta, ids.remove(index), word, mode.intersect) == regex_combo(g, theta, ids, word, mode.intersect), + { + regex_constants(g); + let a = ids[index]@; + regex_unfold(g, a); + assert forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + implies regex_combo(g, theta, ids.remove(index), word, mode.intersect) == regex_combo(g, theta, ids, word, mode.intersect) by { + let sem = model::gsem(theta); + if exists|i: int| 0 <= i < ids.len() && regex_absorbed_by(g, a, ids[i]@, mode.intersect) { + let witness = choose|i: int| 0 <= i < ids.len() && regex_absorbed_by(g, a, ids[i]@, mode.intersect); + regex_absorption_implication(g, a, ids[witness]@, mode.intersect, theta, word); + regex_remove_covered(g, ids, index, witness, mode.intersect, theta, word); + } else if !mode.intersect { + let witness = choose|i: int| 0 <= i < ids.len() && ids[i]@ != g.constants.epsilon && language::nullable(model::lift_regex(g, ids[i]@)); + language::lemma_nullable_iff_nil(sem, model::lift_regex(g, ids[witness]@)); + if model::regex_lang(g, theta, a, word) { + assert(word =~= Seq::::empty()); + } + regex_remove_covered(g, ids, index, witness, false, theta, word); + } else { + let witness = choose|i: int| 0 <= i < ids.len() && regex_nonnullable_except_not_epsilon(g, ids[i]@, g.constants.epsilon); + regex_unfold(g, ids[witness]@); + language::lemma_nullable_iff_nil(sem, model::lift_regex(g, ids[witness]@)); + regex_node_language(g, a, theta, word); + regex_language_unfold(sem, model::lift_regex(g, g.constants.epsilon), word); + if model::regex_lang(g, theta, ids[witness]@, word) { + if word.len() == 0 { assert(word =~= Seq::::empty()); } + } + regex_remove_covered(g, ids, index, witness, true, theta, word); + } + } + assert forall|i: int| 0 <= i < ids.remove(index).len() implies ids.remove(index)[i]@ < g.regexes.len() by { + let j = if i < index { i } else { i + 1 }; + assert(ids.remove(index)[i] == ids[j]); + } + } + + pub open spec fn regex_equivalent(g: model::Graph, left: Seq, right: Seq, intersect: bool) -> bool { + forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + ==> regex_combo(g, theta, left, word, intersect) == regex_combo(g, theta, right, word, intersect) + } + + pub proof fn regex_ids_shape(ids: Seq) + ensures model::regex_ids(ids).len() == ids.len(), + forall|i: int| 0 <= i < ids.len() ==> model::regex_ids(ids)[i] == ids[i]@, + {} + + pub proof fn regex_test_ids_shape(ids: Seq) + ensures model::test_ids(ids).len() == ids.len(), + forall|i: int| 0 <= i < ids.len() ==> model::test_ids(ids)[i] == ids[i]@, + {} + + pub proof fn regex_combo_members(g: model::Graph, left: Seq, right: Seq, intersect: bool) + requires forall|id: RegexId| left.contains(id) == right.contains(id), + ensures regex_equivalent(g, left, right, intersect), + { + assert forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + implies regex_combo(g, theta, left, word, intersect) == regex_combo(g, theta, right, word, intersect) by { + lemma_combo_inclusion(left, right, + |id: RegexId| model::regex_lang(g, theta, id@, word), intersect); + lemma_combo_inclusion(right, left, + |id: RegexId| model::regex_lang(g, theta, id@, word), intersect); + } + } + + pub proof fn regex_combo_permutation(g: model::Graph, left: Seq, right: Seq, intersect: bool) + requires left.to_multiset() == right.to_multiset(), + ensures regex_equivalent(g, left, right, intersect), + { + assert forall|id: RegexId| left.contains(id) == right.contains(id) by { + vstd::seq_lib::to_multiset_contains(left, id); + vstd::seq_lib::to_multiset_contains(right, id); + } + regex_combo_members(g, left, right, intersect); + } + + pub proof fn regex_combo_push(g: model::Graph, ids: Seq, id: RegexId, theta: Subst, word: Seq, intersect: bool) + ensures regex_combo(g, theta, ids.push(id), word, intersect) + == if intersect { regex_combo(g, theta, ids, word, true) && model::regex_lang(g, theta, id@, word) } + else { regex_combo(g, theta, ids, word, false) || model::regex_lang(g, theta, id@, word) }, + { + regex_exists_prefix(|i: int| model::regex_lang(g, theta, ids.push(id)[i]@, word), ids.len() as int); + if intersect { + if regex_combo(g, theta, ids.push(id), word, true) { + assert(model::regex_lang(g, theta, ids.push(id)[ids.len() as int]@, word)); + assert forall|i: int| 0 <= i < ids.len() implies model::regex_lang(g, theta, ids[i]@, word) by { + assert(ids.push(id)[i] == ids[i]); + } + } + if regex_combo(g, theta, ids, word, true) && model::regex_lang(g, theta, id@, word) { + assert forall|i: int| 0 <= i < ids.push(id).len() implies model::regex_lang(g, theta, ids.push(id)[i]@, word) by { + if i < ids.len() { assert(ids.push(id)[i] == ids[i]); } + else { assert(ids.push(id)[i] == id); } + } + } + } else { + if regex_combo(g, theta, ids.push(id), word, false) { + let i = choose|i: int| 0 <= i < ids.push(id).len() && model::regex_lang(g, theta, ids.push(id)[i]@, word); + if i < ids.len() { assert(ids.push(id)[i] == ids[i]); assert(regex_combo(g, theta, ids, word, false)); } + else { assert(ids.push(id)[i] == id); } + } + if regex_combo(g, theta, ids, word, false) { + let i = choose|i: int| 0 <= i < ids.len() && model::regex_lang(g, theta, ids[i]@, word); + assert(ids.push(id)[i] == ids[i]); assert(regex_combo(g, theta, ids.push(id), word, false)); + } + if model::regex_lang(g, theta, id@, word) { + assert(ids.push(id)[ids.len() as int] == id); assert(regex_combo(g, theta, ids.push(id), word, false)); + } + } + } + + pub proof fn regex_set_node_wf(g: model::Graph, ids: Seq, nullable: bool, intersect: bool) + requires regex_ids_valid(g, ids), model::strictly_increasing(model::regex_ids(ids)), nullable == regex_nullable_combo(g, ids, intersect), + ensures model::regex_node_wf(g, model::RegexNode { + kind: if intersect { model::RegexKindNode::Intersect(model::regex_ids(ids)) } else { model::RegexKindNode::Union(model::regex_ids(ids)) }, nullable }), + { + regex_ids_shape(ids); + assert(model::bounded(model::regex_ids(ids), g.regexes.len())); + assert(model::lift_regexes_bounded(g, model::regex_ids(ids), g.regexes.len()) =~= model::lift_regexes(g, model::regex_ids(ids))); + let cs = model::lift_regexes(g, model::regex_ids(ids)); + let sem = |test: model::Test, event: EventView| true; + let word = Seq::::empty(); + let root = if intersect { language::Regex::Intersect(cs) } else { language::Regex::Union(cs) }; + language::lemma_nullable_iff_nil(sem, root); + regex_language_unfold(sem, root, word); + assert forall|i: int| 0 <= i < ids.len() implies language::numeric_lang(sem, cs[i], word) + == language::nullable(model::lift_regex(g, ids[i]@)) by { + assert(cs[i] == model::lift_regex(g, ids[i]@)); + language::lemma_nullable_iff_nil(sem, cs[i]); + } + if intersect { + if nullable { + assert forall|i: int| 0 <= i < cs.len() implies language::numeric_lang(sem, cs[i], word) by {}; + } + if language::numeric_lang(sem, root, word) { + assert forall|i: int| 0 <= i < ids.len() implies language::nullable(model::lift_regex(g, ids[i]@)) by { + assert(language::numeric_lang(sem, cs[i], word)); + } + } + } else { + if nullable { + let i = choose|i: int| 0 <= i < ids.len() && language::nullable(model::lift_regex(g, ids[i]@)); + assert(language::numeric_lang(sem, cs[i], word)); + } + if language::numeric_lang(sem, root, word) { + let i = choose|i: int| 0 <= i < cs.len() && language::numeric_lang(sem, cs[i], word); + assert(language::nullable(model::lift_regex(g, ids[i]@))); + } + } + } + + pub open spec fn regex_test_combo(g: model::Graph, theta: Subst, tests: Seq, word: Seq, intersect: bool) -> bool { + if tests.len() == 0 { intersect } + else { word.len() == 1 && test_combo(g, theta, tests, word[0], intersect) } + } + + pub open spec fn regex_group_combo(g: model::Graph, theta: Subst, tests: Seq, others: Seq, word: Seq, intersect: bool) -> bool { + if intersect { regex_test_combo(g, theta, tests, word, true) && regex_combo(g, theta, others, word, true) } + else { regex_test_combo(g, theta, tests, word, false) || regex_combo(g, theta, others, word, false) } + } + + pub proof fn regex_split_preserves(g: model::Graph, id: RegexId, tests: Seq, others: Seq, next_tests: Seq, next_others: Seq, intersect: bool) + requires model::graph_wf(g), id@ < g.regexes.len(), + match g.regexes[id@ as int].kind { + model::RegexKindNode::Test(t) => model::test_ids(next_tests) == model::test_ids(tests).push(t) && next_others == others, + _ => next_tests == tests && next_others == others.push(id), + }, + ensures forall|theta: Subst, word: Seq| + #![trigger regex_group_combo(g, theta, next_tests, next_others, word, intersect)] + regex_group_combo(g, theta, next_tests, next_others, word, intersect) + == if intersect { regex_group_combo(g, theta, tests, others, word, true) && model::regex_lang(g, theta, id@, word) } + else { regex_group_combo(g, theta, tests, others, word, false) || model::regex_lang(g, theta, id@, word) }, + { + hide(language::numeric_lang); + hide(model::test_holds); + regex_test_ids_shape(tests); + regex_test_ids_shape(next_tests); + assert forall|theta: Subst, word: Seq| + #![trigger regex_group_combo(g, theta, next_tests, next_others, word, intersect)] + regex_group_combo(g, theta, next_tests, next_others, word, intersect) + == if intersect { regex_group_combo(g, theta, tests, others, word, true) && model::regex_lang(g, theta, id@, word) } + else { regex_group_combo(g, theta, tests, others, word, false) || model::regex_lang(g, theta, id@, word) } by { + regex_node_language(g, id@, theta, word); + match g.regexes[id@ as int].kind { + model::RegexKindNode::Test(t) => { + assert(next_tests.len() == tests.len() + 1); + assert forall|i: int| 0 <= i < tests.len() implies next_tests[i] == tests[i] by { + assert(model::test_ids(next_tests)[i] == model::test_ids(tests)[i]); + assert(next_tests[i]@ == tests[i]@); + } + assert(model::test_ids(next_tests)[tests.len() as int] == t); + assert(next_tests[tests.len() as int]@ == t); + if word.len() == 1 { + let event = word[0]; + if intersect { + if test_combo(g, theta, next_tests, event, true) { + assert(model::test_holds(theta, model::lift_test(g, next_tests[tests.len() as int]@), event)); + assert forall|i: int| 0 <= i < tests.len() implies model::test_holds(theta, model::lift_test(g, tests[i]@), event) by { + assert(next_tests[i] == tests[i]); + } + } + if test_combo(g, theta, tests, event, true) && model::test_holds(theta, model::lift_test(g, t), event) { + assert forall|i: int| 0 <= i < next_tests.len() implies model::test_holds(theta, model::lift_test(g, next_tests[i]@), event) by { + if i < tests.len() { assert(next_tests[i] == tests[i]); } + else { assert(next_tests[i]@ == t); } + } + } + } else { + regex_exists_prefix(|i: int| model::test_holds(theta, model::lift_test(g, next_tests[i]@), event), tests.len() as int); + if test_combo(g, theta, tests, event, false) { + let i = choose|i: int| 0 <= i < tests.len() && model::test_holds(theta, model::lift_test(g, tests[i]@), event); + assert(next_tests[i] == tests[i]); + assert(test_combo(g, theta, next_tests, event, false)); + } + } + } + }, + _ => { regex_combo_push(g, others, id, theta, word, intersect); }, + } + } + } + + pub proof fn regex_collect_preserves(g: model::Graph, id: RegexId, before: Seq, after: Seq, mode: RegexModeModel) + requires model::graph_wf(g), id@ < g.regexes.len(), regex_mode_wf(g, mode), id != mode.absorber, + model::regex_ids(after) == model::regex_ids(before) + regex_set_piece(g, id@, mode), + ensures forall|theta: Subst, word: Seq| + #![trigger regex_combo(g, theta, after, word, mode.intersect)] + regex_combo(g, theta, after, word, mode.intersect) + == if mode.intersect { regex_combo(g, theta, before, word, true) && model::regex_lang(g, theta, id@, word) } + else { regex_combo(g, theta, before, word, false) || model::regex_lang(g, theta, id@, word) }, + { + hide(language::numeric_lang); + hide(model::lift_regex); + regex_ids_shape(before); + regex_ids_shape(after); + regex_children_count(g, id@); + regex_constants(g); + assert(model::regex_ids(after) == model::regex_ids(before) + regex_set_piece(g, id@, mode)); + assert(model::regex_ids(after).subrange(before.len() as int, after.len() as int) == regex_set_piece(g, id@, mode)); + assert forall|i: int| before.len() <= i < after.len() implies after[i]@ == regex_set_piece(g, id@, mode)[i - before.len()] by {}; + assert(after.len() >= before.len()); + assert forall|i: int| 0 <= i < before.len() implies after[i] == before[i] by { + assert(model::regex_ids(after)[i] == model::regex_ids(before)[i]); + assert(after[i]@ == before[i]@); + } + assert forall|theta: Subst, word: Seq| + #![trigger regex_combo(g, theta, after, word, mode.intersect)] + regex_combo(g, theta, after, word, mode.intersect) + == if mode.intersect { regex_combo(g, theta, before, word, true) && model::regex_lang(g, theta, id@, word) } + else { regex_combo(g, theta, before, word, false) || model::regex_lang(g, theta, id@, word) } by { + regex_node_language(g, id@, theta, word); + regex_language_unfold(model::gsem(theta), language::Regex::Empty, word); + regex_language_unfold(model::gsem(theta), language::Regex::All, word); + let pivot = before.len() as int; + if mode.intersect { + if regex_combo(g, theta, after, word, true) { + assert forall|i: int| 0 <= i < before.len() implies model::regex_lang(g, theta, before[i]@, word) by { + assert(after[i] == before[i]); + } + if id != mode.identity { + if g.regexes[id@ as int].kind is Intersect { + let cs = regex_children(g, id@); + assert forall|i: int| 0 <= i < cs.len() implies model::regex_lang(g, theta, cs[i], word) by { + assert(after[pivot + i]@ == cs[i]); + } + } else { assert(after[pivot] == id); } + } + } + if regex_combo(g, theta, before, word, true) && model::regex_lang(g, theta, id@, word) { + assert forall|i: int| 0 <= i < after.len() implies model::regex_lang(g, theta, after[i]@, word) by { + if i < pivot { assert(after[i] == before[i]); } + else if g.regexes[id@ as int].kind is Intersect { assert(after[i]@ == regex_children(g, id@)[i - pivot]); } + else { assert(after[i] == id); } + } + } + } else { + if regex_combo(g, theta, after, word, false) { + let i = choose|i: int| 0 <= i < after.len() && model::regex_lang(g, theta, after[i]@, word); + if i < pivot { assert(after[i] == before[i]); } + else if g.regexes[id@ as int].kind is Union { assert(after[i]@ == regex_children(g, id@)[i - pivot]); } + else { assert(after[i] == id); } + } + if regex_combo(g, theta, before, word, false) { + let i = choose|i: int| 0 <= i < before.len() && model::regex_lang(g, theta, before[i]@, word); + assert(after[i] == before[i]); + assert(regex_combo(g, theta, after, word, false)); + } + if model::regex_lang(g, theta, id@, word) { + assert(id != mode.identity); + if g.regexes[id@ as int].kind is Union { + let cs = regex_children(g, id@); + assert(regex_set_piece(g, id@, mode) == cs); + let i = choose|i: int| 0 <= i < cs.len() && model::regex_lang(g, theta, cs[i], word); + assert(after[pivot + i]@ == cs[i]); + assert(regex_combo(g, theta, after, word, false)); + } else { + assert(regex_set_piece(g, id@, mode) == seq![id@]); + assert(after[pivot]@ == id@); + assert(after[pivot] == id); + assert(regex_combo(g, theta, after, word, false)); + } + } + } + } + } + + pub proof fn regex_stats_decisions(g: model::Graph, ids: Seq, epsilon: RegexId, stats: RegexStatsModel, intersect: bool) + requires model::graph_wf(g), regex_ids_valid(g, ids), epsilon@ == g.constants.epsilon, + regex_stats_prefix(g, ids, ids.len(), epsilon, stats, true), + ensures forall|theta: Subst, word: Seq| + (stats.complement ==> regex_combo(g, theta, ids, word, intersect) == !intersect) + && (intersect && stats.epsilon ==> regex_combo(g, theta, ids, word, true) == (stats.all_nullable && word.len() == 0)), + { + assert(ids.subrange(0, ids.len() as int) =~= ids); + regex_constants(g); + assert forall|theta: Subst, word: Seq| + (stats.complement ==> regex_combo(g, theta, ids, word, intersect) == !intersect) + && (intersect && stats.epsilon ==> regex_combo(g, theta, ids, word, true) == (stats.all_nullable && word.len() == 0)) by { + if stats.complement { + let i = choose|i: int| 0 <= i < ids.len() && regex_has_complement_model(g, ids[i]@, ids); + let inner = match g.regexes[ids[i]@ as int].kind { model::RegexKindNode::Not(r) => r, _ => 0nat }; + let j = choose|j: int| 0 <= j < ids.len() && ids[j]@ == inner; + regex_node_language(g, ids[i]@, theta, word); + if intersect && regex_combo(g, theta, ids, word, true) { + assert(model::regex_lang(g, theta, ids[i]@, word)); + assert(model::regex_lang(g, theta, ids[j]@, word)); + } + if !intersect { + assert(model::regex_lang(g, theta, ids[i]@, word) || model::regex_lang(g, theta, ids[j]@, word)); + } + } + if intersect && stats.epsilon { + let i = choose|i: int| 0 <= i < ids.len() && ids[i] == epsilon; + if regex_combo(g, theta, ids, word, true) { + assert(model::regex_lang(g, theta, ids[i]@, word)); + assert(word =~= Seq::::empty()); + assert forall|j: int| 0 <= j < ids.len() implies language::nullable(model::lift_regex(g, ids[j]@)) by { + language::lemma_nullable_iff_nil(model::gsem(theta), model::lift_regex(g, ids[j]@)); + } + } + if stats.all_nullable && word.len() == 0 { + assert(word =~= Seq::::empty()); + assert forall|j: int| 0 <= j < ids.len() implies model::regex_lang(g, theta, ids[j]@, word) by { + language::lemma_nullable_iff_nil(model::gsem(theta), model::lift_regex(g, ids[j]@)); + } + } + } + } + } + + pub proof fn regex_combo_extends(a: model::Graph, b: model::Graph, ids: Seq, intersect: bool) + requires model::graph_wf(a), model::graph_extends(a, b), regex_ids_valid(a, ids), + ensures regex_ids_valid(b, ids), forall|theta: Subst, word: Seq| + regex_combo(a, theta, ids, word, intersect) == regex_combo(b, theta, ids, word, intersect), + { + model::lemma_graph_wf_elim(a); + model::lemma_lift_stable_under_extends(a, b); + } + + pub proof fn regex_group_extends(a: model::Graph, b: model::Graph, tests: Seq, others: Seq, intersect: bool) + requires model::graph_wf(a), model::graph_extends(a, b), test_ids_valid(a, tests), regex_ids_valid(a, others), + ensures test_ids_valid(b, tests), regex_ids_valid(b, others), forall|theta: Subst, word: Seq| + regex_group_combo(a, theta, tests, others, word, intersect) == regex_group_combo(b, theta, tests, others, word, intersect), + { + model::lemma_graph_wf_elim(a); + model::lemma_lift_stable_under_extends(a, b); + regex_combo_extends(a, b, others, intersect); + } + + pub open spec fn regex_split_prefix(g: model::Graph, flat: Seq, tests: Seq, others: Seq, count: nat) -> bool { + count <= flat.len() && forall|theta: Subst, word: Seq, intersect: bool| + regex_group_combo(g, theta, tests, others, word, intersect) + == regex_combo(g, theta, flat.subrange(0, count as int), word, intersect) + } + + pub proof fn regex_combo_prefix(g: model::Graph, ids: Seq, index: int, theta: Subst, word: Seq, intersect: bool) + requires 0 <= index < ids.len(), + ensures regex_combo(g, theta, ids.subrange(0, index + 1), word, intersect) + == if intersect { regex_combo(g, theta, ids.subrange(0, index), word, true) && model::regex_lang(g, theta, ids[index]@, word) } + else { regex_combo(g, theta, ids.subrange(0, index), word, false) || model::regex_lang(g, theta, ids[index]@, word) }, + { + assert(ids.subrange(0, index + 1) =~= ids.subrange(0, index).push(ids[index])); + regex_combo_push(g, ids.subrange(0, index), ids[index], theta, word, intersect); + } + + pub proof fn regex_absorber_member(g: model::Graph, children: Seq, index: int, mode: RegexModeModel) + requires model::graph_wf(g), regex_ids_valid(g, children), 0 <= index < children.len(), + regex_mode_wf(g, mode), children[index] == mode.absorber, + ensures forall|theta: Subst, word: Seq| + regex_combo(g, theta, children, word, mode.intersect) == !mode.intersect, + { + regex_constants(g); + assert forall|theta: Subst, word: Seq| + regex_combo(g, theta, children, word, mode.intersect) == !mode.intersect by { + if mode.intersect && regex_combo(g, theta, children, word, true) { + assert(model::regex_lang(g, theta, children[index]@, word)); + } + if !mode.intersect { assert(model::regex_lang(g, theta, children[index]@, word)); } + } + } + + pub proof fn regex_group_equivalence_extends(g: model::Graph, next: model::Graph, original: Seq, tests: Seq, others: Seq, intersect: bool) + requires model::graph_wf(g), model::graph_extends(g, next), regex_ids_valid(g, original), test_ids_valid(g, tests), regex_ids_valid(g, others), + forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + ==> regex_group_combo(g, theta, tests, others, word, intersect) == regex_combo(g, theta, original, word, intersect), + ensures forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + ==> regex_group_combo(next, theta, tests, others, word, intersect) == regex_combo(next, theta, original, word, intersect), + { + regex_group_extends(g, next, tests, others, intersect); + regex_combo_extends(g, next, original, intersect); + } + + pub proof fn regex_equivalence_extends(g: model::Graph, next: model::Graph, original: Seq, current: Seq, intersect: bool) + requires model::graph_wf(g), model::graph_extends(g, next), regex_ids_valid(g, original), regex_ids_valid(g, current), regex_equivalent(g, original, current, intersect), + ensures regex_equivalent(next, original, current, intersect), + { + regex_combo_extends(g, next, original, intersect); + regex_combo_extends(g, next, current, intersect); + } + + pub proof fn regex_member_ids_valid(g: model::Graph, source: Seq, target: Seq) + requires regex_ids_valid(g, source), forall|id: RegexId| target.contains(id) ==> source.contains(id), + ensures regex_ids_valid(g, target), + { + assert forall|i: int| 0 <= i < target.len() implies target[i]@ < g.regexes.len() by { + assert(target.contains(target[i])); + assert(source.contains(target[i])); + let j = choose|j: int| 0 <= j < source.len() && source[j] == target[i]; + } + } + + pub proof fn regex_multiset_members(source: Seq, target: Seq) + requires source.to_multiset() == target.to_multiset(), + ensures forall|id: RegexId| source.contains(id) == target.contains(id), + { + lemma_multiset_members(source, target); + } + + pub proof fn regex_remove_strict(ids: Seq, index: int) + requires 0 <= index < ids.len(), model::strictly_increasing(model::regex_ids(ids)), + ensures model::strictly_increasing(model::regex_ids(ids.remove(index))), + { + assert forall|i: int, j: int| 0 <= i < j < ids.remove(index).len() + implies model::regex_ids(ids.remove(index))[i] < model::regex_ids(ids.remove(index))[j] by { + let a = if i < index { i } else { i + 1 }; + let b = if j < index { j } else { j + 1 }; + assert(ids.remove(index)[i] == ids[a]); + assert(ids.remove(index)[j] == ids[b]); + assert(model::regex_ids(ids)[a] < model::regex_ids(ids)[b]); + } + } + + pub proof fn regex_set_result(g: model::Graph, ids: Seq, original: Seq, intersect: bool) + requires model::graph_wf(g), regex_ids_valid(g, ids), regex_ids_valid(g, original), regex_equivalent(g, ids, original, intersect), + ensures forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) ==> + (ids.len() == 0 ==> regex_combo(g, theta, original, word, intersect) == intersect) + && (ids.len() == 1 ==> regex_combo(g, theta, original, word, intersect) == model::regex_lang(g, theta, ids[0]@, word)), + { + if ids.len() == 1 { assert(ids =~= seq![ids[0]]); } + } + + pub proof fn regex_test_ids_push(ids: Seq, id: TestId) + ensures model::test_ids(ids.push(id)) == model::test_ids(ids).push(id@), + { assert(model::test_ids(ids.push(id)) =~= model::test_ids(ids).push(id@)); } + + pub proof fn regex_test_connective_extends(g: model::Graph, next: model::Graph, tests: Seq, id: TestId, intersect: bool) + requires model::graph_wf(g), model::graph_extends(g, next), test_ids_valid(g, tests), id@ < g.tests.len(), + forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + ==> model::test_holds(theta, model::lift_test(g, id@), event) == test_combo(g, theta, tests, event, intersect), + ensures forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + ==> model::test_holds(theta, model::lift_test(next, id@), event) == test_combo(next, theta, tests, event, intersect), + { + hide(model::test_holds); + hide(language::numeric_lang); + model::lemma_lift_test_stable(g, next, id@); + assert forall|i: int| 0 <= i < tests.len() implies model::lift_test(g, tests[i]@) == model::lift_test(next, tests[i]@) by { + model::lemma_lift_test_stable(g, next, tests[i]@); + } + assert forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + implies model::test_holds(theta, model::lift_test(next, id@), event) == test_combo(next, theta, tests, event, intersect) by { + assert(model::test_holds(theta, model::lift_test(g, id@), event) == test_combo(g, theta, tests, event, intersect)); + assert forall|i: int| 0 <= i < tests.len() implies model::test_holds(theta, model::lift_test(g, tests[i]@), event) + == model::test_holds(theta, model::lift_test(next, tests[i]@), event) by {}; + assert(test_combo(g, theta, tests, event, intersect) == test_combo(next, theta, tests, event, intersect)); + } + } + + pub proof fn regex_dedup_strict(sorted: Seq, result: Seq) + requires result == dedup_spec(sorted), + forall|i: int, j: int| 0 <= i < j < sorted.len() ==> sorted[i]@ <= sorted[j]@, + ensures model::strictly_increasing(model::regex_ids(result)), + { + let key: spec_fn(RegexId) -> nat = |id: RegexId| id@; + lemma_dedup_strict::(sorted, key); + regex_ids_shape(result); + assert forall|i: int, j: int| 0 <= i < j < result.len() implies model::regex_ids(result)[i] < model::regex_ids(result)[j] by { + assert(key(dedup_spec(sorted)[i]) < key(dedup_spec(sorted)[j])); + } + } + + pub proof fn regex_combo_ids(g: model::Graph, ids: Seq, theta: Subst, word: Seq, intersect: bool) + ensures regex_combo_nats(g, theta, model::regex_ids(ids), word, intersect) + == regex_combo(g, theta, ids, word, intersect), + { + regex_ids_shape(ids); + if intersect { + if regex_combo_nats(g, theta, model::regex_ids(ids), word, true) { + assert forall|i: int| 0 <= i < ids.len() implies model::regex_lang(g, theta, ids[i]@, word) by { + assert(model::regex_lang(g, theta, model::regex_ids(ids)[i], word)); + } + } + if regex_combo(g, theta, ids, word, true) { + assert forall|i: int| 0 <= i < model::regex_ids(ids).len() implies model::regex_lang(g, theta, model::regex_ids(ids)[i], word) by { + assert(model::regex_lang(g, theta, ids[i]@, word)); + } + } + } else { + if regex_combo_nats(g, theta, model::regex_ids(ids), word, false) { + let i = choose|i: int| 0 <= i < ids.len() && model::regex_lang(g, theta, model::regex_ids(ids)[i], word); + assert(model::regex_lang(g, theta, ids[i]@, word)); + } + if regex_combo(g, theta, ids, word, false) { + let i = choose|i: int| 0 <= i < ids.len() && model::regex_lang(g, theta, ids[i]@, word); + assert(model::regex_lang(g, theta, model::regex_ids(ids)[i], word)); + } + } + } + + + + pub proof fn test_lemma_not_leaf_effect(g: model::Graph, id: TestId, + tasks: Seq<(TestId, bool)>, prior: Seq, values: Seq, finish: bool) + requires id@ < g.tests.len(), values.len() == prior.len() + 1, + values.drop_last() == prior, values.last()@ < g.tests.len(), + match g.tests[id@ as int] { + model::TestNode::True => g.tests[values.last()@ as int] == model::TestNode::False, + model::TestNode::False => g.tests[values.last()@ as int] == model::TestNode::True, + model::TestNode::Atom(p, positive) => g.tests[values.last()@ as int] == model::TestNode::Atom(p, !positive), + _ => false, + }, + ensures test_not_effect(g, id, finish, tasks, prior, tasks, values), + { + reveal(test_negation_row); + match g.tests[id@ as int] { + model::TestNode::True => {}, + model::TestNode::False => {}, + model::TestNode::Atom(_, _) => {}, + _ => {}, + } + } + + pub proof fn test_lemma_not_finish_effect(g: model::Graph, id: TestId, + tasks: Seq<(TestId, bool)>, prior: Seq, values: Seq, count: nat, and: bool) + requires id@ < g.tests.len(), count <= prior.len(), + g.tests[id@ as int] == if and { model::TestNode::Or(test_children(g, id)) } + else { model::TestNode::And(test_children(g, id)) }, + test_children(g, id).len() == count, + values.len() == prior.len() - count + 1, + values.drop_last() == prior.subrange(0, prior.len() as int - count), + exists|sorted: Seq| sorted.to_multiset() + == prior.subrange(prior.len() as int - count, prior.len() as int).to_multiset() + && g.tests[values.last()@ as int] == if and { model::TestNode::And(model::test_ids(sorted)) } + else { model::TestNode::Or(model::test_ids(sorted)) }, + ensures test_not_effect(g, id, true, tasks, prior, tasks, values), + { + if and {} else {} + } + + pub proof fn test_lemma_not_step_post(before: model::Graph, after: model::Graph, id: TestId, finish: bool, + pending: Seq<(TestId, bool)>, prior: Seq, tasks: Seq<(TestId, bool)>, values: Seq) + requires model::graph_extends(before, after), model::graph_wf(after), id@ < before.tests.len(), + forall|i: int| 0 <= i < pending.len() ==> #[trigger] pending[i].0@ < before.tests.len(), + test_ids_valid(after, values), test_not_effect(after, id, finish, pending, prior, tasks, values), + ensures test_not_work(after, tasks) < test_not_work(before, pending.push((id, finish))), + forall|root: TestId| test_not_state(before, pending.push((id, finish)), prior, root) + ==> test_not_state(after, tasks, values, root), + { + assert forall|i: int| 0 <= i < pending.push((id, finish)).len() + implies pending.push((id, finish))[i].0@ < before.tests.len() by { + if i < pending.len() { assert(pending.push((id, finish))[i] == pending[i]); } + } + test_lemma_not_work_extends(before, after, pending.push((id, finish))); + test_lemma_not_effect_work(after, id, finish, pending, prior, tasks, values); + assert forall|root: TestId| test_not_state(before, pending.push((id, finish)), prior, root) + implies test_not_state(after, tasks, values, root) by { + test_lemma_not_state_extends(before, after, pending.push((id, finish)), prior, root); + test_lemma_not_effect_state(after, id, finish, pending, prior, tasks, values, root); + } + } + + + // Guarded transition continuation semantics. + #[verifier::reject_recursive_types(C)] + pub struct GuardedTransition { + pub guard: spec_fn(C, EventView) -> bool, + pub term: language::Transition, + } + + pub open spec fn guarded_semantics( + sem: spec_fn(C, L, EventView) -> bool, ctx: C, + ) -> spec_fn(L, EventView) -> bool { + |leaf: L, event: EventView| sem(ctx, leaf, event) + } + + pub open spec fn guarded_language( + sem: spec_fn(C, L, EventView) -> bool, ctx: C, event: EventView, + value: GuardedTransition, word: Seq, + ) -> bool { + let context_sem = guarded_semantics(sem, ctx); + language::numeric_lang(context_sem, language::interp_transition(context_sem, event, value.term), word) + } + + pub open spec fn guarded_refines( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, + before: GuardedTransition, after: GuardedTransition, + ) -> bool { + forall|ctx: C, event: EventView| valid(ctx) && #[trigger] (before.guard)(ctx, event) + ==> (after.guard)(ctx, event) && forall|word: Seq| + guarded_language(sem, ctx, event, before, word) + == guarded_language(sem, ctx, event, after, word) + } + + pub open spec fn guarded_stack_refines( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, + before: Seq>, after: Seq>, + ) -> bool { + before.len() == after.len() && forall|i: int| 0 <= i < before.len() + ==> guarded_refines(sem, valid, before[i], after[i]) + } + + pub open spec fn guarded_constant(term: language::Transition) -> GuardedTransition { + GuardedTransition { guard: |ctx: C, event: EventView| true, term } + } + + pub open spec fn guarded_clean( + sem: spec_fn(C, L, EventView) -> bool, path: L, term: language::Transition, + ) -> GuardedTransition { + GuardedTransition { guard: |ctx: C, event: EventView| sem(ctx, path, event), term } + } + + pub open spec fn guarded_not(value: GuardedTransition) -> GuardedTransition { + GuardedTransition { guard: value.guard, term: language::Transition::Not(Box::new(value.term)) } + } + + pub open spec fn guarded_append( + value: GuardedTransition, suffix: language::Regex, + ) -> GuardedTransition { + GuardedTransition { + guard: value.guard, + term: language::Transition::Append(Box::new(value.term), seq![suffix]), + } + } + + pub open spec fn guarded_set( + values: Seq>, intersect: bool, + ) -> GuardedTransition { + GuardedTransition { + guard: |ctx: C, event: EventView| forall|i: int| 0 <= i < values.len() ==> #[trigger] (values[i].guard)(ctx, event), + term: if intersect { + language::Transition::Intersect(values.map(|i: int, v: GuardedTransition| v.term)) + } else { + language::Transition::Union(values.map(|i: int, v: GuardedTransition| v.term)) + }, + } + } + + pub open spec fn guarded_if( + sem: spec_fn(C, L, EventView) -> bool, test: L, + yes: GuardedTransition, no: GuardedTransition, + ) -> GuardedTransition { + GuardedTransition { + guard: |ctx: C, event: EventView| if sem(ctx, test, event) { + (yes.guard)(ctx, event) + } else { (no.guard)(ctx, event) }, + term: language::Transition::If(test, Box::new(yes.term), Box::new(no.term)), + } + } + + pub open spec fn guarded_clean_if( + sem: spec_fn(C, L, EventView) -> bool, test: L, path: L, + yes: GuardedTransition, no: GuardedTransition, + ) -> GuardedTransition { + let value = guarded_if(sem, test, yes, no); + GuardedTransition { + guard: |ctx: C, event: EventView| sem(ctx, path, event) && (value.guard)(ctx, event), + term: value.term, + } + } + + pub proof fn guarded_lemma_refines_refl( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, + value: GuardedTransition, + ) + ensures guarded_refines(sem, valid, value, value), + {} + + pub proof fn guarded_lemma_refines_transitive( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, + a: GuardedTransition, b: GuardedTransition, c: GuardedTransition, + ) + requires guarded_refines(sem, valid, a, b), guarded_refines(sem, valid, b, c), + ensures guarded_refines(sem, valid, a, c), + {} + + pub proof fn guarded_lemma_stack_transitive( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, + a: Seq>, b: Seq>, c: Seq>, + ) + requires guarded_stack_refines(sem, valid, a, b), guarded_stack_refines(sem, valid, b, c), + ensures guarded_stack_refines(sem, valid, a, c), + { + assert forall|i: int| 0 <= i < a.len() implies guarded_refines(sem, valid, a[i], c[i]) by { + guarded_lemma_refines_transitive(sem, valid, a[i], b[i], c[i]); + } + } + + pub proof fn guarded_lemma_not_congruent( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, + before: GuardedTransition, after: GuardedTransition, + ) + requires guarded_refines(sem, valid, before, after), + ensures guarded_refines(sem, valid, guarded_not(before), guarded_not(after)), + { + assert forall|ctx: C, event: EventView| valid(ctx) && #[trigger] (guarded_not(before).guard)(ctx, event) + implies (guarded_not(after).guard)(ctx, event) && forall|word: Seq| + guarded_language(sem, ctx, event, guarded_not(before), word) + == guarded_language(sem, ctx, event, guarded_not(after), word) by { + assert((before.guard)(ctx, event)); + assert((after.guard)(ctx, event)); + assert forall|word: Seq| + guarded_language(sem, ctx, event, guarded_not(before), word) + == guarded_language(sem, ctx, event, guarded_not(after), word) by { + assert(guarded_language(sem, ctx, event, before, word) + == guarded_language(sem, ctx, event, after, word)); + language::lemma_interp_not(guarded_semantics(sem, ctx), event, before.term); + language::lemma_interp_not(guarded_semantics(sem, ctx), event, after.term); + } + } + } + + pub proof fn guarded_lemma_if_congruent( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, test: L, + a0: GuardedTransition, a1: GuardedTransition, + b0: GuardedTransition, b1: GuardedTransition, + ) + requires guarded_refines(sem, valid, a0, a1), guarded_refines(sem, valid, b0, b1), + ensures guarded_refines(sem, valid, guarded_if(sem, test, a0, b0), guarded_if(sem, test, a1, b1)), + { + assert forall|ctx: C, event: EventView| valid(ctx) && #[trigger] (guarded_if(sem, test, a0, b0).guard)(ctx, event) + implies (guarded_if(sem, test, a1, b1).guard)(ctx, event) && forall|word: Seq| + guarded_language(sem, ctx, event, guarded_if(sem, test, a0, b0), word) + == guarded_language(sem, ctx, event, guarded_if(sem, test, a1, b1), word) by { + if sem(ctx, test, event) { + assert((a0.guard)(ctx, event)); + assert((a1.guard)(ctx, event)); + } else { + assert((b0.guard)(ctx, event)); + assert((b1.guard)(ctx, event)); + } + assert forall|word: Seq| + guarded_language(sem, ctx, event, guarded_if(sem, test, a0, b0), word) + == guarded_language(sem, ctx, event, guarded_if(sem, test, a1, b1), word) by { + if sem(ctx, test, event) { + assert(guarded_language(sem, ctx, event, a0, word) + == guarded_language(sem, ctx, event, a1, word)); + } else { + assert(guarded_language(sem, ctx, event, b0, word) + == guarded_language(sem, ctx, event, b1, word)); + } + language::lemma_interp_if(guarded_semantics(sem, ctx), event, test, a0.term, b0.term); + language::lemma_interp_if(guarded_semantics(sem, ctx), event, test, a1.term, b1.term); + } + } + } + + pub proof fn guarded_lemma_set_congruent( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, + before: Seq>, after: Seq>, intersect: bool, + ) + requires guarded_stack_refines(sem, valid, before, after), + ensures guarded_refines(sem, valid, guarded_set(before, intersect), guarded_set(after, intersect)), + { + assert forall|ctx: C, event: EventView| valid(ctx) + && #[trigger] (guarded_set(before, intersect).guard)(ctx, event) + implies (guarded_set(after, intersect).guard)(ctx, event) && forall|word: Seq| + guarded_language(sem, ctx, event, guarded_set(before, intersect), word) + == guarded_language(sem, ctx, event, guarded_set(after, intersect), word) by { + assert forall|i: int| 0 <= i < after.len() implies (after[i].guard)(ctx, event) by { + assert((before[i].guard)(ctx, event)); + } + let context_sem = guarded_semantics(sem, ctx); + let left = before.map(|i: int, value: GuardedTransition| value.term); + let right = after.map(|i: int, value: GuardedTransition| value.term); + assert forall|word: Seq| + guarded_language(sem, ctx, event, guarded_set(before, intersect), word) + == guarded_language(sem, ctx, event, guarded_set(after, intersect), word) by { + assert forall|i: int| 0 <= i < before.len() implies + language::numeric_lang(context_sem, language::interp_transition(context_sem, event, left[i]), word) + == language::numeric_lang(context_sem, language::interp_transition(context_sem, event, right[i]), word) by { + assert(guarded_refines(sem, valid, before[i], after[i])); + assert((before[i].guard)(ctx, event)); + assert(guarded_language(sem, ctx, event, before[i], word) + == guarded_language(sem, ctx, event, after[i], word)); + } + if intersect { + language::lemma_interp_intersect(context_sem, event, left, word); + language::lemma_interp_intersect(context_sem, event, right, word); + } else { + language::lemma_interp_union(context_sem, event, left, word); + language::lemma_interp_union(context_sem, event, right, word); + if exists|i: int| 0 <= i < left.len() + && language::numeric_lang(context_sem, language::interp_transition(context_sem, event, left[i]), word) { + let i = choose|i: int| 0 <= i < left.len() + && language::numeric_lang(context_sem, language::interp_transition(context_sem, event, left[i]), word); + assert(language::numeric_lang(context_sem, language::interp_transition(context_sem, event, right[i]), word)); + } + if exists|i: int| 0 <= i < right.len() + && language::numeric_lang(context_sem, language::interp_transition(context_sem, event, right[i]), word) { + let i = choose|i: int| 0 <= i < right.len() + && language::numeric_lang(context_sem, language::interp_transition(context_sem, event, right[i]), word); + assert(language::numeric_lang(context_sem, language::interp_transition(context_sem, event, left[i]), word)); + } + } + } + } + } + + pub proof fn guarded_lemma_append_congruent( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, + before: GuardedTransition, after: GuardedTransition, suffix: language::Regex, + ) + requires guarded_refines(sem, valid, before, after), + ensures guarded_refines(sem, valid, guarded_append(before, suffix), guarded_append(after, suffix)), + { + assert forall|ctx: C, event: EventView| valid(ctx) + && #[trigger] (guarded_append(before, suffix).guard)(ctx, event) + implies (guarded_append(after, suffix).guard)(ctx, event) && forall|word: Seq| + guarded_language(sem, ctx, event, guarded_append(before, suffix), word) + == guarded_language(sem, ctx, event, guarded_append(after, suffix), word) by { + assert((before.guard)(ctx, event)); + assert((after.guard)(ctx, event)); + let context_sem = guarded_semantics(sem, ctx); + let left = seq![language::interp_transition(context_sem, event, before.term), suffix]; + let right = seq![language::interp_transition(context_sem, event, after.term), suffix]; + assert forall|i: int, word: Seq| 0 <= i < left.len() implies + language::numeric_lang(context_sem, left[i], word) == language::numeric_lang(context_sem, right[i], word) by { + if i == 0 { + assert(guarded_language(sem, ctx, event, before, word) + == guarded_language(sem, ctx, event, after, word)); + } else { assert(i == 1); } + } + regex_concat_congruent(context_sem, left, right); + language::lemma_interp_append(context_sem, event, before.term, seq![suffix]); + language::lemma_interp_append(context_sem, event, after.term, seq![suffix]); + assert(seq![language::interp_transition(context_sem, event, before.term)] + seq![suffix] =~= left); + assert(seq![language::interp_transition(context_sem, event, after.term)] + seq![suffix] =~= right); + } + } + + pub enum GuardedAction { + Clean(language::Transition, L), + Not(language::Transition), + Append(language::Transition, language::Regex), + Pair(language::Transition, language::Transition), + Union(nat), + Intersect(nat), + If(L), + CleanIf(L, L), + Fold(Seq>, nat), + NotResult, + AppendResult(language::Regex), + SwapThen, + } + + pub open spec fn guarded_apply( + sem: spec_fn(C, L, EventView) -> bool, action: GuardedAction, + values: Seq>, + ) -> Option>> { + match action { + GuardedAction::Clean(term, path) => Some(values.push(guarded_clean(sem, path, term))), + GuardedAction::Not(term) => Some(values.push(guarded_constant(language::Transition::Not(Box::new(term))))), + GuardedAction::Append(term, suffix) => Some(values.push(guarded_constant( + language::Transition::Append(Box::new(term), seq![suffix])))), + GuardedAction::Pair(left, right) => Some(values.push(guarded_constant( + language::Transition::Intersect(seq![left, right])))), + GuardedAction::Union(count) => if count <= values.len() { + let start = values.len() as int - count as int; + Some(values.take(start).push(guarded_set(values.subrange(start, values.len() as int), false))) + } else { None }, + GuardedAction::Intersect(count) => if count <= values.len() { + let start = values.len() as int - count as int; + Some(values.take(start).push(guarded_set(values.subrange(start, values.len() as int), true))) + } else { None }, + GuardedAction::If(test) => if values.len() >= 2 { + Some(values.take(values.len() as int - 2).push(guarded_if(sem, test, + values[values.len() as int - 2], values.last()))) + } else { None }, + GuardedAction::CleanIf(test, path) => if values.len() >= 2 { + Some(values.take(values.len() as int - 2).push(guarded_clean_if(sem, test, path, + values[values.len() as int - 2], values.last()))) + } else { None }, + GuardedAction::Fold(terms, index) => if index == 0 { + Some(values.push(guarded_constant(language::Transition::Intersect(terms)))) + } else if index < terms.len() { + if values.len() > 0 { + let remaining = terms.subrange(index as int, terms.len() as int) + .map(|i: int, term: language::Transition| guarded_constant(term)); + Some(values.drop_last().push(guarded_set(seq![values.last()] + remaining, true))) + } else { None } + } else { Some(values) }, + GuardedAction::NotResult => if values.len() > 0 { + Some(values.drop_last().push(guarded_not(values.last()))) + } else { None }, + GuardedAction::AppendResult(suffix) => if values.len() > 0 { + Some(values.drop_last().push(guarded_append(values.last(), suffix))) + } else { None }, + GuardedAction::SwapThen => if values.len() >= 2 { + Some(values.take(values.len() as int - 2).push(values.last()).push(values[values.len() as int - 2])) + } else { None }, + } + } + + pub open spec fn guarded_run( + sem: spec_fn(C, L, EventView) -> bool, tasks: Seq>, + values: Seq>, + ) -> Option>> + decreases tasks.len(), + { + if tasks.len() == 0 { Some(values) } + else { + match guarded_apply(sem, tasks.last(), values) { + Some(next) => guarded_run(sem, tasks.drop_last(), next), + None => None, + } + } + } + + pub open spec fn guarded_program_refines( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, + before: Option>>, after: Option>>, + ) -> bool { + match before { + None => true, + Some(left) => match after { + Some(right) => guarded_stack_refines(sem, valid, left, right), + None => false, + }, + } + } + + pub proof fn guarded_lemma_program_transitive( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, + a: Option>>, b: Option>>, + c: Option>>, + ) + requires guarded_program_refines(sem, valid, a, b), guarded_program_refines(sem, valid, b, c), + ensures guarded_program_refines(sem, valid, a, c), + { + match a { + None => {}, + Some(left) => match (b, c) { + (Some(middle), Some(right)) => guarded_lemma_stack_transitive(sem, valid, left, middle, right), + _ => {}, + }, + } + } + + pub proof fn guarded_lemma_stack_slice( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, + before: Seq>, after: Seq>, start: int, end: int, + ) + requires guarded_stack_refines(sem, valid, before, after), 0 <= start <= end <= before.len(), + ensures guarded_stack_refines(sem, valid, before.subrange(start, end), after.subrange(start, end)), + { + assert forall|i: int| 0 <= i < before.subrange(start, end).len() implies + guarded_refines(sem, valid, before.subrange(start, end)[i], after.subrange(start, end)[i]) by { + assert(before.subrange(start, end)[i] == before[start + i]); + assert(after.subrange(start, end)[i] == after[start + i]); + } + } + + pub proof fn guarded_lemma_stack_push( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, + before: Seq>, after: Seq>, + left: GuardedTransition, right: GuardedTransition, + ) + requires guarded_stack_refines(sem, valid, before, after), guarded_refines(sem, valid, left, right), + ensures guarded_stack_refines(sem, valid, before.push(left), after.push(right)), + { + assert forall|i: int| 0 <= i < before.push(left).len() implies + guarded_refines(sem, valid, before.push(left)[i], after.push(right)[i]) by { + if i < before.len() { + assert(before.push(left)[i] == before[i]); + assert(after.push(right)[i] == after[i]); + } else { assert(i == before.len()); } + } + } + + pub proof fn guarded_lemma_run_prefix( + sem: spec_fn(C, L, EventView) -> bool, prefix: Seq>, suffix: Seq>, + values: Seq>, + ) + ensures guarded_run(sem, prefix + suffix, values) == match guarded_run(sem, suffix, values) { + Some(next) => guarded_run(sem, prefix, next), + None => None, + }, + decreases suffix.len(), + { + if suffix.len() > 0 { + assert((prefix + suffix).last() == suffix.last()); + assert((prefix + suffix).drop_last() =~= prefix + suffix.drop_last()); + match guarded_apply(sem, suffix.last(), values) { + Some(next) => guarded_lemma_run_prefix(sem, prefix, suffix.drop_last(), next), + None => {}, + } + } else { assert(prefix + suffix =~= prefix); } + } + + pub proof fn guarded_lemma_clean_if_congruent( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, test: L, path: L, + a0: GuardedTransition, a1: GuardedTransition, + b0: GuardedTransition, b1: GuardedTransition, + ) + requires guarded_refines(sem, valid, a0, a1), guarded_refines(sem, valid, b0, b1), + ensures guarded_refines(sem, valid, + guarded_clean_if(sem, test, path, a0, b0), guarded_clean_if(sem, test, path, a1, b1)), + { + guarded_lemma_if_congruent(sem, valid, test, a0, a1, b0, b1); + assert forall|ctx: C, event: EventView| valid(ctx) + && #[trigger] (guarded_clean_if(sem, test, path, a0, b0).guard)(ctx, event) + implies (guarded_clean_if(sem, test, path, a1, b1).guard)(ctx, event) && forall|word: Seq| + guarded_language(sem, ctx, event, guarded_clean_if(sem, test, path, a0, b0), word) + == guarded_language(sem, ctx, event, guarded_clean_if(sem, test, path, a1, b1), word) by { + assert((guarded_if(sem, test, a0, b0).guard)(ctx, event)); + assert((guarded_if(sem, test, a1, b1).guard)(ctx, event)); + assert forall|word: Seq| + guarded_language(sem, ctx, event, guarded_clean_if(sem, test, path, a0, b0), word) + == guarded_language(sem, ctx, event, guarded_clean_if(sem, test, path, a1, b1), word) by { + assert(guarded_language(sem, ctx, event, guarded_if(sem, test, a0, b0), word) + == guarded_language(sem, ctx, event, guarded_if(sem, test, a1, b1), word)); + } + } + } + + pub proof fn guarded_lemma_stack_refl( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, values: Seq>, + ) + ensures guarded_stack_refines(sem, valid, values, values), + { + assert forall|i: int| 0 <= i < values.len() implies guarded_refines(sem, valid, values[i], values[i]) by { + guarded_lemma_refines_refl(sem, valid, values[i]); + } + } + + pub proof fn guarded_lemma_stack_concat( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, + a0: Seq>, a1: Seq>, + b0: Seq>, b1: Seq>, + ) + requires guarded_stack_refines(sem, valid, a0, a1), guarded_stack_refines(sem, valid, b0, b1), + ensures guarded_stack_refines(sem, valid, a0 + b0, a1 + b1), + { + assert forall|i: int| 0 <= i < (a0 + b0).len() implies + guarded_refines(sem, valid, (a0 + b0)[i], (a1 + b1)[i]) by { + if i < a0.len() { + assert((a0 + b0)[i] == a0[i]); + assert((a1 + b1)[i] == a1[i]); + } else { + assert((a0 + b0)[i] == b0[i - a0.len() as int]); + assert((a1 + b1)[i] == b1[i - a1.len() as int]); + } + } + } + + pub proof fn guarded_lemma_reduce_set_congruent( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, + before: Seq>, after: Seq>, count: nat, intersect: bool, + ) + requires guarded_stack_refines(sem, valid, before, after), count <= before.len(), + ensures guarded_stack_refines(sem, valid, + before.take(before.len() as int - count as int).push(guarded_set( + before.subrange(before.len() as int - count as int, before.len() as int), intersect)), + after.take(after.len() as int - count as int).push(guarded_set( + after.subrange(after.len() as int - count as int, after.len() as int), intersect))), + { + let start = before.len() as int - count as int; + guarded_lemma_stack_slice(sem, valid, before, after, 0, start); + guarded_lemma_stack_slice(sem, valid, before, after, start, before.len() as int); + guarded_lemma_set_congruent(sem, valid, + before.subrange(start, before.len() as int), after.subrange(start, after.len() as int), intersect); + guarded_lemma_stack_push(sem, valid, before.take(start), after.take(start), + guarded_set(before.subrange(start, before.len() as int), intersect), + guarded_set(after.subrange(start, after.len() as int), intersect)); + } + + pub proof fn guarded_lemma_apply_congruent( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, action: GuardedAction, + before: Seq>, after: Seq>, + ) + requires guarded_stack_refines(sem, valid, before, after), + ensures guarded_program_refines(sem, valid, + guarded_apply(sem, action, before), guarded_apply(sem, action, after)), + { + match action { + GuardedAction::Clean(term, path) => { + let value = guarded_clean(sem, path, term); + guarded_lemma_refines_refl(sem, valid, value); + guarded_lemma_stack_push(sem, valid, before, after, value, value); + }, + GuardedAction::Not(term) => { + let value = guarded_constant(language::Transition::Not(Box::new(term))); + guarded_lemma_refines_refl(sem, valid, value); + guarded_lemma_stack_push(sem, valid, before, after, value, value); + }, + GuardedAction::Append(term, suffix) => { + let value = guarded_constant(language::Transition::Append(Box::new(term), seq![suffix])); + guarded_lemma_refines_refl(sem, valid, value); + guarded_lemma_stack_push(sem, valid, before, after, value, value); + }, + GuardedAction::Pair(left, right) => { + let value = guarded_constant(language::Transition::Intersect(seq![left, right])); + guarded_lemma_refines_refl(sem, valid, value); + guarded_lemma_stack_push(sem, valid, before, after, value, value); + }, + GuardedAction::Union(count) => { + if count <= before.len() { guarded_lemma_reduce_set_congruent(sem, valid, before, after, count, false); } + }, + GuardedAction::Intersect(count) => { + if count <= before.len() { guarded_lemma_reduce_set_congruent(sem, valid, before, after, count, true); } + }, + GuardedAction::If(test) => { + if before.len() >= 2 { + let start = before.len() as int - 2; + guarded_lemma_stack_slice(sem, valid, before, after, 0, start); + guarded_lemma_if_congruent(sem, valid, test, + before[start], after[start], before.last(), after.last()); + guarded_lemma_stack_push(sem, valid, before.take(start), after.take(start), + guarded_if(sem, test, before[start], before.last()), + guarded_if(sem, test, after[start], after.last())); + } + }, + GuardedAction::CleanIf(test, path) => { + if before.len() >= 2 { + let start = before.len() as int - 2; + guarded_lemma_stack_slice(sem, valid, before, after, 0, start); + guarded_lemma_clean_if_congruent(sem, valid, test, path, + before[start], after[start], before.last(), after.last()); + guarded_lemma_stack_push(sem, valid, before.take(start), after.take(start), + guarded_clean_if(sem, test, path, before[start], before.last()), + guarded_clean_if(sem, test, path, after[start], after.last())); + } + }, + GuardedAction::Fold(terms, index) => { + if index == 0 { + let value = guarded_constant(language::Transition::Intersect(terms)); + guarded_lemma_refines_refl(sem, valid, value); + guarded_lemma_stack_push(sem, valid, before, after, value, value); + } else if index < terms.len() && before.len() > 0 { + let start = before.len() as int - 1; + guarded_lemma_stack_slice(sem, valid, before, after, 0, start); + let remaining: Seq> = terms.subrange(index as int, terms.len() as int) + .map(|i: int, term: language::Transition| guarded_constant(term)); + guarded_lemma_stack_refl(sem, valid, remaining); + guarded_lemma_stack_push(sem, valid, Seq::empty(), Seq::empty(), before.last(), after.last()); + guarded_lemma_stack_concat(sem, valid, seq![before.last()], seq![after.last()], remaining, remaining); + guarded_lemma_set_congruent(sem, valid, seq![before.last()] + remaining, seq![after.last()] + remaining, true); + guarded_lemma_stack_push(sem, valid, before.drop_last(), after.drop_last(), + guarded_set(seq![before.last()] + remaining, true), + guarded_set(seq![after.last()] + remaining, true)); + } + }, + GuardedAction::NotResult => { + if before.len() > 0 { + guarded_lemma_stack_slice(sem, valid, before, after, 0, before.len() as int - 1); + guarded_lemma_not_congruent(sem, valid, before.last(), after.last()); + guarded_lemma_stack_push(sem, valid, before.drop_last(), after.drop_last(), + guarded_not(before.last()), guarded_not(after.last())); + } + }, + GuardedAction::AppendResult(suffix) => { + if before.len() > 0 { + guarded_lemma_stack_slice(sem, valid, before, after, 0, before.len() as int - 1); + guarded_lemma_append_congruent(sem, valid, before.last(), after.last(), suffix); + guarded_lemma_stack_push(sem, valid, before.drop_last(), after.drop_last(), + guarded_append(before.last(), suffix), guarded_append(after.last(), suffix)); + } + }, + GuardedAction::SwapThen => { + if before.len() >= 2 { + let start = before.len() as int - 2; + guarded_lemma_stack_slice(sem, valid, before, after, 0, start); + guarded_lemma_stack_push(sem, valid, before.take(start), after.take(start), before.last(), after.last()); + guarded_lemma_stack_push(sem, valid, before.take(start).push(before.last()), + after.take(start).push(after.last()), before[start], after[start]); + } + }, + } + } + + pub proof fn guarded_lemma_run_congruent( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, tasks: Seq>, + before: Seq>, after: Seq>, + ) + requires guarded_stack_refines(sem, valid, before, after), + ensures guarded_program_refines(sem, valid, guarded_run(sem, tasks, before), guarded_run(sem, tasks, after)), + decreases tasks.len(), + { + if tasks.len() > 0 { + guarded_lemma_apply_congruent(sem, valid, tasks.last(), before, after); + match (guarded_apply(sem, tasks.last(), before), guarded_apply(sem, tasks.last(), after)) { + (Some(left), Some(right)) => guarded_lemma_run_congruent(sem, valid, tasks.drop_last(), left, right), + _ => {}, + } + } + } + + // Native transition work-stack representation. + pub struct TransitionContext { + pub bindings: Subst, + } + + pub type TransitionMeaning = GuardedTransition; + pub type TransitionAction = GuardedAction; + + pub open spec fn transition_context_sem() -> spec_fn(TransitionContext, model::Test, EventView) -> bool { + |ctx: TransitionContext, test: model::Test, event: EventView| + model::test_holds(ctx.bindings, test, event) + } + + pub open spec fn transition_context_valid() -> spec_fn(TransitionContext) -> bool { + |ctx: TransitionContext| language::event_wf(ctx.bindings, ctx.bindings.len()) + } + + pub enum ActionShape { + Clean(nat, nat), Not(nat), Append(nat, nat), Pair(nat, nat), + Union(nat), Intersect(nat), If(nat), CleanIf(nat, nat), + Fold(Seq, nat), NotResult, AppendResult(nat), SwapThen, + } + + pub enum ChildShape { Clean(nat), Not, Append(nat), PairLeft(nat), PairRight(nat) } + + impl View for Action { + type V = ActionShape; + open(super) spec fn view(&self) -> ActionShape { + match self { + Action::Clean(id, path) => ActionShape::Clean(id@, path@), + Action::Not(id) => ActionShape::Not(id@), + Action::Append(id, suffix) => ActionShape::Append(id@, suffix@), + Action::Pair(a, b) => ActionShape::Pair(a@, b@), + Action::Union(count) => ActionShape::Union(*count as nat), + Action::Intersect(count) => ActionShape::Intersect(*count as nat), + Action::If(test) => ActionShape::If(test@), + Action::CleanIf(test, path) => ActionShape::CleanIf(test@, path@), + Action::Fold(ids, index) => ActionShape::Fold(model::transition_ids(ids.view()), *index as nat), + Action::NotResult => ActionShape::NotResult, + Action::AppendResult(suffix) => ActionShape::AppendResult(suffix@), + Action::SwapThen => ActionShape::SwapThen, + } + } + } + + impl View for ChildAction { + type V = ChildShape; + open(super) spec fn view(&self) -> ChildShape { + match self { + ChildAction::Clean(path) => ChildShape::Clean(path@), + ChildAction::Not => ChildShape::Not, + ChildAction::Append(suffix) => ChildShape::Append(suffix@), + ChildAction::PairLeft(other) => ChildShape::PairLeft(other@), + ChildAction::PairRight(other) => ChildShape::PairRight(other@), + } + } + } + + pub open spec fn transition_action_views>(tasks: Seq) -> Seq { + tasks.map(|i: int, task: T| task@) + } + + pub open spec fn transition_action_valid(g: model::Graph, task: ActionShape) -> bool { + match task { + ActionShape::Clean(id, path) => id < g.transitions.len() && path < g.tests.len(), + ActionShape::Not(id) => id < g.transitions.len(), + ActionShape::Append(id, suffix) => id < g.transitions.len() && suffix < g.regexes.len(), + ActionShape::Pair(a, b) => a < g.transitions.len() && b < g.transitions.len(), + ActionShape::If(test) => test < g.tests.len(), + ActionShape::CleanIf(test, path) => test < g.tests.len() && path < g.tests.len(), + ActionShape::Fold(ids, index) => model::bounded(ids, g.transitions.len()), + ActionShape::AppendResult(suffix) => suffix < g.regexes.len(), + _ => true, + } + } + + pub open spec fn transition_tasks_valid(g: model::Graph, tasks: Seq) -> bool { + forall|i: int| 0 <= i < tasks.len() ==> transition_action_valid(g, tasks[i]) + } + + pub open spec fn transition_freeze_action(g: model::Graph, task: ActionShape) -> TransitionAction { + match task { + ActionShape::Clean(id, path) => GuardedAction::Clean(model::lift_transition(g, id), model::lift_test(g, path)), + ActionShape::Not(id) => GuardedAction::Not(model::lift_transition(g, id)), + ActionShape::Append(id, suffix) => GuardedAction::Append(model::lift_transition(g, id), model::lift_regex(g, suffix)), + ActionShape::Pair(a, b) => GuardedAction::Pair(model::lift_transition(g, a), model::lift_transition(g, b)), + ActionShape::Union(count) => GuardedAction::Union(count), + ActionShape::Intersect(count) => GuardedAction::Intersect(count), + ActionShape::If(test) => GuardedAction::If(model::lift_test(g, test)), + ActionShape::CleanIf(test, path) => GuardedAction::CleanIf(model::lift_test(g, test), model::lift_test(g, path)), + ActionShape::Fold(ids, index) => GuardedAction::Fold(ids.map(|i: int, id: nat| model::lift_transition(g, id)), index), + ActionShape::NotResult => GuardedAction::NotResult, + ActionShape::AppendResult(suffix) => GuardedAction::AppendResult(model::lift_regex(g, suffix)), + ActionShape::SwapThen => GuardedAction::SwapThen, + } + } + + pub open spec fn transition_freeze_tasks(g: model::Graph, tasks: Seq) -> Seq { + tasks.map(|i: int, task: ActionShape| transition_freeze_action(g, task)) + } + + pub open spec fn transition_known(g: model::Graph, id: TransitionId) -> TransitionMeaning { + guarded_constant(model::lift_transition(g, id@)) + } + + pub open spec fn transition_known_values(g: model::Graph, values: Seq) -> Seq { + values.map(|i: int, id: TransitionId| transition_known(g, id)) + } + + pub open spec fn transition_program( + g: model::Graph, tasks: Seq, values: Seq, + ) -> Option> { + guarded_run(transition_context_sem(), transition_freeze_tasks(g, tasks), transition_known_values(g, values)) + } + + /// A defined continuation cannot consume values that have not been completed. + pub proof fn transition_lemma_stack_ready(g: model::Graph, pending: Seq, task: ActionShape, values: Seq) + requires transition_program(g, pending.push(task), values) is Some, + ensures match task { + ActionShape::Union(n) | ActionShape::Intersect(n) => n <= values.len(), + ActionShape::If(_) | ActionShape::CleanIf(_, _) | ActionShape::SwapThen => values.len() >= 2, + ActionShape::NotResult | ActionShape::AppendResult(_) => values.len() > 0, + ActionShape::Fold(ids, index) => 0 < index < ids.len() ==> values.len() > 0, + _ => true, + }, + { + let actions = transition_freeze_tasks(g, pending.push(task)); + assert(actions.last() == transition_freeze_action(g, task)); + assert(guarded_apply(transition_context_sem(), actions.last(), transition_known_values(g, values)) is Some); + match task { + ActionShape::Union(_) | ActionShape::Intersect(_) | ActionShape::If(_) + | ActionShape::CleanIf(_, _) | ActionShape::SwapThen + | ActionShape::NotResult | ActionShape::AppendResult(_) | ActionShape::Fold(_, _) => {}, + _ => {}, + } + } + + pub open spec fn transition_program_refines( + before: Option>, after: Option>, + ) -> bool { + guarded_program_refines(transition_context_sem(), transition_context_valid(), before, after) + } + + pub open spec fn transition_if_combo( + g: model::Graph, theta: Subst, test: TestId, + yes: TransitionId, no: TransitionId, event: EventView, word: Seq, + ) -> bool { + if model::test_holds(theta, model::lift_test(g, test@), event) { + transition_lang(g, theta, yes, event, word) + } else { transition_lang(g, theta, no, event, word) } + } + + pub open spec fn transition_set_leaf(node: model::TransitionNode, intersect: bool) -> bool { + match node { + model::TransitionNode::Union(_) => intersect, + model::TransitionNode::Intersect(_) => !intersect, + _ => true, + } + } + + #[verifier::opaque] + pub open spec fn transition_children(g: model::Graph, id: nat) -> Seq { + match g.transitions[id as int] { + model::TransitionNode::Union(ids) => ids, + model::TransitionNode::Intersect(ids) => ids, + _ => Seq::empty(), + } + } + + pub open spec fn transition_child_count(g: model::Graph, id: nat, count: nat) -> bool { + id < g.transitions.len() && match g.transitions[id as int] { + model::TransitionNode::Union(ids) => ids.len() == count, + model::TransitionNode::Intersect(ids) => ids.len() == count, + _ => false, + } + } + + pub proof fn transition_lemma_context_sem(ctx: TransitionContext) + ensures guarded_semantics(transition_context_sem(), ctx) == model::gsem(ctx.bindings), + { + assert(guarded_semantics(transition_context_sem(), ctx) =~= model::gsem(ctx.bindings)); + } + + pub proof fn transition_lemma_known_language( + g: model::Graph, id: TransitionId, ctx: TransitionContext, event: EventView, word: Seq, + ) + ensures guarded_language(transition_context_sem(), ctx, event, transition_known(g, id), word) + == transition_lang(g, ctx.bindings, id, event, word), + { + transition_lemma_context_sem(ctx); + } + + pub proof fn transition_lemma_action_stable(before: model::Graph, after: model::Graph, task: ActionShape) + requires model::graph_wf(before), model::graph_extends(before, after), transition_action_valid(before, task), + ensures transition_action_valid(after, task), + transition_freeze_action(before, task) == transition_freeze_action(after, task), + { + model::lemma_graph_wf_elim(before); + model::lemma_lift_stable_under_extends(before, after); + match task { + ActionShape::Fold(ids, index) => { + assert(ids.map(|i: int, id: nat| model::lift_transition(before, id)) + =~= ids.map(|i: int, id: nat| model::lift_transition(after, id))); + }, + _ => {}, + } + } + + pub proof fn transition_lemma_program_stable( + before: model::Graph, after: model::Graph, tasks: Seq, values: Seq, + ) + requires model::graph_wf(before), model::graph_extends(before, after), + transition_tasks_valid(before, tasks), transition_ids_valid(before, values), + ensures transition_tasks_valid(after, tasks), transition_ids_valid(after, values), + transition_program(before, tasks, values) == transition_program(after, tasks, values), + { + model::lemma_graph_wf_elim(before); + model::lemma_lift_stable_under_extends(before, after); + assert forall|i: int| 0 <= i < tasks.len() implies + transition_action_valid(after, tasks[i]) + && transition_freeze_action(before, tasks[i]) == transition_freeze_action(after, tasks[i]) by { + transition_lemma_action_stable(before, after, tasks[i]); + } + assert(transition_freeze_tasks(before, tasks) =~= transition_freeze_tasks(after, tasks)); + assert(transition_known_values(before, values) =~= transition_known_values(after, values)); + } + + pub struct TransitionModeModel { + pub intersect: bool, + pub identity: TransitionId, + pub absorber: TransitionId, + } + + impl View for TransitionMode { + type V = TransitionModeModel; + open(super) spec fn view(&self) -> TransitionModeModel { + TransitionModeModel { intersect: self.intersect, identity: self.identity, absorber: self.absorber } + } + } + + pub open spec fn transition_mode_valid(g: model::Graph, mode: TransitionModeModel) -> bool { + mode.identity@ == (if mode.intersect { g.constants.transition_all } else { g.constants.transition_empty }) + && mode.absorber@ == (if mode.intersect { g.constants.transition_empty } else { g.constants.transition_all }) + } + + pub proof fn transition_unfold(g: model::Graph, id: nat) + requires model::graph_wf(g), id < g.transitions.len(), + ensures match g.transitions[id as int] { + model::TransitionNode::Const(regex) => model::lift_transition(g, id) + == language::Transition::Const(model::lift_regex(g, regex)), + model::TransitionNode::If(test, yes, no) => model::lift_transition(g, id) + == language::Transition::If(model::lift_test(g, test), + Box::new(model::lift_transition(g, yes)), Box::new(model::lift_transition(g, no))), + model::TransitionNode::Union(ids) => model::lift_transition(g, id) + == language::Transition::Union(ids.map(|i: int, child: nat| model::lift_transition(g, child))), + model::TransitionNode::Intersect(ids) => model::lift_transition(g, id) + == language::Transition::Intersect(ids.map(|i: int, child: nat| model::lift_transition(g, child))), + model::TransitionNode::Not(inner) => model::lift_transition(g, id) + == language::Transition::Not(Box::new(model::lift_transition(g, inner))), + model::TransitionNode::Append(inner, suffix) => model::lift_transition(g, id) + == language::Transition::Append(Box::new(model::lift_transition(g, inner)), model::lift_regexes(g, suffix)), + }, + { + model::lemma_graph_transition_wf(g, id); + match g.transitions[id as int] { + model::TransitionNode::Union(ids) => { + assert(model::lift_transitions(g, ids, id) + =~= ids.map(|i: int, child: nat| model::lift_transition(g, child))); + }, + model::TransitionNode::Intersect(ids) => { + assert(model::lift_transitions(g, ids, id) + =~= ids.map(|i: int, child: nat| model::lift_transition(g, child))); + }, + _ => {}, + } + } + + pub open spec fn transition_unbounded_node(g: model::Graph, node: model::TransitionNode) -> language::Transition { + match node { + model::TransitionNode::Const(regex) => language::Transition::Const(model::lift_regex(g, regex)), + model::TransitionNode::If(test, yes, no) => language::Transition::If(model::lift_test(g, test), + Box::new(model::lift_transition(g, yes)), Box::new(model::lift_transition(g, no))), + model::TransitionNode::Union(ids) => language::Transition::Union( + ids.map(|i: int, child: nat| model::lift_transition(g, child))), + model::TransitionNode::Intersect(ids) => language::Transition::Intersect( + ids.map(|i: int, child: nat| model::lift_transition(g, child))), + model::TransitionNode::Not(inner) => language::Transition::Not(Box::new(model::lift_transition(g, inner))), + model::TransitionNode::Append(inner, suffix) => language::Transition::Append( + Box::new(model::lift_transition(g, inner)), model::lift_regexes(g, suffix)), + } + } + + + + pub proof fn guarded_lemma_run_result_congruent( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, tasks: Seq>, + before: Option>>, after: Option>>, + ) + requires guarded_program_refines(sem, valid, before, after), + ensures guarded_program_refines(sem, valid, + match before { Some(values) => guarded_run(sem, tasks, values), None => None }, + match after { Some(values) => guarded_run(sem, tasks, values), None => None }), + { + match (before, after) { + (Some(left), Some(right)) => guarded_lemma_run_congruent(sem, valid, tasks, left, right), + _ => {}, + } + } + + pub proof fn guarded_lemma_frame_effect( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, + prefix: Seq>, expansion: Seq>, action: GuardedAction, + before: Seq>, after: Seq>, + ) + requires guarded_program_refines(sem, valid, + guarded_apply(sem, action, before), guarded_run(sem, expansion, after)), + ensures guarded_program_refines(sem, valid, + guarded_run(sem, prefix.push(action), before), guarded_run(sem, prefix + expansion, after)), + { + guarded_lemma_run_prefix(sem, prefix, seq![action], before); + guarded_lemma_run_prefix(sem, prefix, expansion, after); + assert(prefix.push(action) =~= prefix + seq![action]); + guarded_lemma_run_singleton(sem, action, before); + assert(guarded_run(sem, seq![action], before) == guarded_apply(sem, action, before)); + guarded_lemma_run_result_congruent(sem, valid, prefix, + guarded_apply(sem, action, before), guarded_run(sem, expansion, after)); + } + + + pub open spec fn transition_effect( + g: model::Graph, task: ActionShape, pending: Seq, prior: Seq, + tasks: Seq, values: Seq, + ) -> bool { + pending.is_prefix_of(tasks) && guarded_program_refines(transition_context_sem(), transition_context_valid(), + guarded_apply(transition_context_sem(), transition_freeze_action(g, task), transition_known_values(g, prior)), + guarded_run(transition_context_sem(), transition_freeze_tasks(g, + tasks.subrange(pending.len() as int, tasks.len() as int)), transition_known_values(g, values))) + } + + pub proof fn transition_lemma_effect_frame( + g: model::Graph, task: ActionShape, pending: Seq, prior: Seq, + tasks: Seq, values: Seq, + ) + requires transition_effect(g, task, pending, prior, tasks, values), + ensures transition_program_refines( + transition_program(g, pending.push(task), prior), transition_program(g, tasks, values)), + { + let prefix = transition_freeze_tasks(g, pending); + let expansion = transition_freeze_tasks(g, tasks.subrange(pending.len() as int, tasks.len() as int)); + assert(transition_freeze_tasks(g, pending.push(task)) =~= prefix.push(transition_freeze_action(g, task))); + assert(transition_freeze_tasks(g, tasks) =~= prefix + expansion); + guarded_lemma_frame_effect(transition_context_sem(), transition_context_valid(), prefix, expansion, + transition_freeze_action(g, task), transition_known_values(g, prior), transition_known_values(g, values)); + } + + pub open spec fn transition_initial_value(g: model::Graph, task: ActionShape) -> Option { + match guarded_apply(transition_context_sem(), transition_freeze_action(g, task), Seq::empty()) { + Some(values) => if values.len() == 1 { Some(values[0]) } else { None }, + None => None, + } + } + + pub proof fn transition_lemma_children(g: model::Graph, id: nat) + requires model::graph_wf(g), id < g.transitions.len(), + ensures model::bounded(transition_children(g, id), g.transitions.len()), + match g.transitions[id as int] { + model::TransitionNode::Union(ids) => transition_children(g, id) == ids, + model::TransitionNode::Intersect(ids) => transition_children(g, id) == ids, + _ => transition_children(g, id).len() == 0, + }, + { + reveal(transition_children); + model::lemma_graph_transition_wf(g, id); + match g.transitions[id as int] { + model::TransitionNode::Union(ids) => {}, + model::TransitionNode::Intersect(ids) => {}, + _ => {}, + } + } + + pub proof fn transition_lemma_child(g: model::Graph, id: nat, index: nat, child: nat) + requires model::graph_wf(g), id < g.transitions.len(), + model::transition_node_child(g.transitions[id as int], index) == Some(child), + ensures index < transition_children(g, id).len(), transition_children(g, id)[index as int] == child, + child < g.transitions.len(), + { + transition_lemma_children(g, id); + reveal(transition_children); + match g.transitions[id as int] { + model::TransitionNode::Union(ids) => {}, + model::TransitionNode::Intersect(ids) => {}, + _ => {}, + } + } + + #[verifier::opaque] + pub open spec fn transition_suffix(g: model::Graph, id: nat) -> Seq { + match g.transitions[id as int] { + model::TransitionNode::Append(inner, suffix) => suffix, + _ => Seq::empty(), + } + } + + pub open spec fn transition_suffix_count(g: model::Graph, id: nat, count: nat) -> bool { + id < g.transitions.len() && match g.transitions[id as int] { + model::TransitionNode::Append(inner, suffix) => suffix.len() == count, + _ => false, + } + } + + pub proof fn transition_lemma_suffix(g: model::Graph, id: nat) + requires model::graph_wf(g), id < g.transitions.len(), + ensures model::bounded(transition_suffix(g, id), g.regexes.len()), + match g.transitions[id as int] { + model::TransitionNode::Append(inner, suffix) => transition_suffix(g, id) == suffix, + _ => transition_suffix(g, id).len() == 0, + }, + { + reveal(transition_suffix); + model::lemma_graph_transition_wf(g, id); + } + + pub proof fn transition_lemma_suffix_child(g: model::Graph, id: nat, index: nat, child: nat) + requires model::graph_wf(g), id < g.transitions.len(), + model::transition_node_suffix(g.transitions[id as int], index) == Some(child), + ensures index < transition_suffix(g, id).len(), transition_suffix(g, id)[index as int] == child, + child < g.regexes.len(), + { + transition_lemma_suffix(g, id); + reveal(transition_suffix); + match g.transitions[id as int] { + model::TransitionNode::Append(inner, suffix) => {}, + _ => {}, + } + } + + pub proof fn transition_ids_push(ids: Seq, id: TransitionId) + ensures model::transition_ids(ids.push(id)) == model::transition_ids(ids).push(id@), + { + assert(model::transition_ids(ids.push(id)) =~= model::transition_ids(ids).push(id@)); + } + + + pub proof fn guarded_lemma_run_singleton( + sem: spec_fn(C, L, EventView) -> bool, action: GuardedAction, values: Seq>, + ) + ensures guarded_run(sem, seq![action], values) == guarded_apply(sem, action, values), + { + reveal_with_fuel(guarded_run, 2); + } + + + pub open spec fn transition_collect_work(g: model::Graph, id: nat, intersect: bool) -> nat + decreases id, 1nat, 0nat, + { + if id >= g.transitions.len() { 1 } + else { + match g.transitions[id as int] { + model::TransitionNode::Union(ids) => if !intersect && model::bounded(ids, id) { + 1 + transition_collect_work_ids(g, ids, id, intersect) + } else { 1 }, + model::TransitionNode::Intersect(ids) => if intersect && model::bounded(ids, id) { + 1 + transition_collect_work_ids(g, ids, id, intersect) + } else { 1 }, + _ => 1, + } + } + } + + pub open spec fn transition_collect_work_ids(g: model::Graph, ids: Seq, bound: nat, intersect: bool) -> nat + decreases bound, 0nat, ids.len(), + when model::bounded(ids, bound) + { + if ids.len() == 0 { 0 } + else { + transition_collect_work_ids(g, ids.drop_last(), bound, intersect) + + transition_collect_work(g, ids.last(), intersect) + } + } + + pub open spec fn transition_pending_work(g: model::Graph, ids: Seq, intersect: bool) -> nat { + transition_collect_work_ids(g, model::transition_ids(ids), g.transitions.len(), intersect) + } + + pub proof fn transition_lemma_work_bounds(g: model::Graph, ids: Seq, a: nat, b: nat, intersect: bool) + requires model::bounded(ids, a), model::bounded(ids, b), + ensures transition_collect_work_ids(g, ids, a, intersect) == transition_collect_work_ids(g, ids, b, intersect), + decreases ids.len(), + { + if ids.len() > 0 { transition_lemma_work_bounds(g, ids.drop_last(), a, b, intersect); } + } + + pub proof fn transition_lemma_work_concat(g: model::Graph, left: Seq, right: Seq, bound: nat, intersect: bool) + requires model::bounded(left, bound), model::bounded(right, bound), + ensures transition_collect_work_ids(g, left + right, bound, intersect) + == transition_collect_work_ids(g, left, bound, intersect) + transition_collect_work_ids(g, right, bound, intersect), + decreases right.len(), + { + assert(model::bounded(left + right, bound)); + if right.len() > 0 { + assert((left + right).drop_last() =~= left + right.drop_last()); + assert((left + right).last() == right.last()); + transition_lemma_work_concat(g, left, right.drop_last(), bound, intersect); + } else { assert(left + right =~= left); } + } + + pub proof fn transition_lemma_work_positive(g: model::Graph, id: nat, intersect: bool) + ensures transition_collect_work(g, id, intersect) >= 1, + {} + + // ----- termination cost arithmetic (Action::run) ----- + pub open spec fn n4(d: nat) -> nat + decreases d, + { + if d == 0 { 1 } else { 4 * n4((d - 1) as nat) } + } + + pub open spec fn log4_floor(d: nat) -> nat + decreases d, + { + if d < 4 { 0 } else { 1 + log4_floor(d / 4) } + } + + pub open spec fn set_bound(total: nat, n: nat) -> nat { + if n == 0 { 2 } else if n == 1 { total } else { (total - 1) as nat } + } + + pub open spec fn if_bound(a: nat, b: nat) -> nat { 1 + if a >= b { a } else { b } } + + pub open spec fn pair_bound(a: nat, b: nat) -> nat { a * b + a + b } + + pub open spec fn sum_plus1(ds: Seq) -> nat + decreases ds.len(), + { + if ds.len() == 0 { 0 } else { sum_plus1(ds.drop_last()) + ds.last() + 1 } + } + + pub open spec fn prod_plus1(ds: Seq) -> nat + decreases ds.len(), + { + if ds.len() == 0 { 1 } else { prod_plus1(ds.drop_last()) * (ds.last() + 1) } + } + + pub open spec fn union_bound(ds: Seq) -> nat { set_bound(sum_plus1(ds), ds.len()) } + + pub open spec fn intersect_bound(ds: Seq) -> nat { set_bound(prod_plus1(ds), ds.len()) } + + proof fn lemma_n4_pos(d: nat) + ensures n4(d) >= 1, d < n4(d), + decreases d, + { + if d > 0 { lemma_n4_pos((d - 1) as nat); } + } + + proof fn lemma_log4_le(d: nat) + requires d >= 1, + ensures n4(log4_floor(d)) <= d, + decreases d, + { + if d >= 4 { lemma_log4_le(d / 4); } + } + + #[via_fn] + proof fn clean_cost_decreases(d: nat) { + if d > 1 { + lemma_log4_le(d); + assert(2 * (((d - 1) as nat) / 2) + 1 <= d); + } + } + + #[via_fn] + proof fn not_cost_decreases(d: nat) { + if d > 1 { + lemma_n4_pos((d - 1) as nat); + assert(n4(d) == 4 * n4((d - 1) as nat)); + lemma_n4_pos(d); + if d >= 2 { + lemma_n4_pos((d - 2) as nat); + assert(n4((d - 1) as nat) == 4 * n4((d - 2) as nat)); + } + } + } + + #[via_fn] + proof fn pair_cost_decreases(x: nat, y: nat) { + if !(x == 0 || y == 0 || (x <= 1 && y <= 1)) { + assert(x * (y + 1) < pair_bound(x, y)) by (nonlinear_arith) requires y >= 1; + assert(y * (x + 1) < pair_bound(x, y)) by (nonlinear_arith) requires x >= 1; + assert(x * y < pair_bound(x, y)) by (nonlinear_arith) requires x >= 1; + if x >= 1 { assert(pair_bound((x - 1) as nat, y) < pair_bound(x, y)) by (nonlinear_arith) requires x >= 1; } + if y >= 1 { assert(pair_bound(x, (y - 1) as nat) < pair_bound(x, y)) by (nonlinear_arith) requires y >= 1; } + if x >= 1 && y >= 1 { + assert(pair_bound((x - 1) as nat, (y - 1) as nat) < pair_bound(x, y)) by (nonlinear_arith) requires x >= 1, y >= 1; + } + } + } + + /// Cost of `Clean` on a node of depth bound `d`. + pub open spec fn clean_cost(d: nat) -> nat + decreases d, 3nat, 0nat via clean_cost_decreases + { + if d <= 1 { 1 } else { + 4 + d + 3 * clean_cost((d - 1) as nat) + pair_cost_upto(d, d) + + not_cost(log4_floor(d)) + append_cost(((d - 1) as nat) / 2) + } + } + + /// Cost of `Not` on a node of depth bound `d`. + pub open spec fn not_cost(d: nat) -> nat + decreases n4(d), 2nat, 0nat via not_cost_decreases + { + if d <= 1 { 1 } else { + 4 + n4(d) + 2 * not_cost((d - 1) as nat) + clean_cost(1 + n4((d - 1) as nat)) + clean_cost(2) + + pair_cost_upto((n4(d) - 1) as nat, (n4(d) - 1) as nat) + } + } + + /// Cost of `Append` on a node of depth bound `d`. + pub open spec fn append_cost(d: nat) -> nat + decreases 2 * d + 1, 2nat, 0nat, + { + if d <= 1 { 1 } else { 3 + 3 * append_cost((d - 1) as nat) + clean_cost(2 * d) } + } + + /// Cost of `Pair` on nodes of depth bounds `x` and `y`. + pub open spec fn pair_cost(x: nat, y: nat) -> nat + decreases pair_bound(x, y), 2nat, 0nat via pair_cost_decreases + { + if x == 0 || y == 0 || (x <= 1 && y <= 1) { 1 } else { + 6 + (if x >= 2 { 2 * pair_cost((x - 1) as nat, y) + clean_cost(x * (y + 1)) } else { 0 }) + + (if y >= 2 { 2 * pair_cost(x, (y - 1) as nat) + clean_cost(y * (x + 1)) } else { 0 }) + + (if x >= 2 && y >= 2 { pair_cost((x - 1) as nat, (y - 1) as nat) + clean_cost(x * y) } else { 0 }) + } + } + + /// Sum of `pair_cost(x, y')` over `1 <= y' <= y` with `pair_bound(x, y') <= e`. + pub open spec fn pair_cost_row(x: nat, y: nat, e: nat) -> nat + decreases e, 2nat, y + 1, + { + if y == 0 { 0 } else { + (if pair_bound(x, y) <= e { pair_cost(x, y) } else { 0 }) + pair_cost_row(x, (y - 1) as nat, e) + } + } + + /// Sum of `pair_cost_row(x', e, e)` over `1 <= x' <= x`. + pub open spec fn pair_cost_upto(x: nat, e: nat) -> nat + decreases e, 2nat, e + x + 2, + { + if x == 0 { 0 } else { pair_cost_row(x, e, e) + pair_cost_upto((x - 1) as nat, e) } + } + + pub open spec fn pair_cost_total(e: nat) -> nat { pair_cost_upto(e, e) } + + pub open spec fn sum_map(f: spec_fn(nat) -> nat, ds: Seq) -> nat decreases ds.len() { if ds.len() == 0 { 0 } else { sum_map(f, ds.drop_last()) + f(ds.last()) } } + pub open spec fn all_pos(ds: Seq) -> bool { forall|i: int| 0 <= i < ds.len() ==> #[trigger] ds[i] >= 1 } + pub open spec fn le_pointwise(a: Seq, b: Seq) -> bool { a.len() == b.len() && forall|i: int| 0 <= i < a.len() ==> #[trigger] a[i] <= b[i] } + pub open spec fn n4s(ds: Seq) -> Seq { Seq::new(ds.len(), |i: int| n4(ds[i])) } + pub open spec fn appends(ds: Seq) -> Seq { Seq::new(ds.len(), |i: int| 2 * ds[i] + 1) } + pub open spec fn pairs_left(ds: Seq, y: nat) -> Seq { Seq::new(ds.len(), |i: int| pair_bound(ds[i], y)) } + pub open spec fn pairs_right(x: nat, ds: Seq) -> Seq { Seq::new(ds.len(), |i: int| pair_bound(x, ds[i])) } + pub open spec fn clean_cost_fn() -> spec_fn(nat) -> nat { |d: nat| clean_cost(d) } + pub open spec fn not_cost_fn() -> spec_fn(nat) -> nat { |d: nat| not_cost(d) } + pub open spec fn append_cost_fn() -> spec_fn(nat) -> nat { |d: nat| append_cost(d) } + pub open spec fn pair_cost_left_fn(y: nat) -> spec_fn(nat) -> nat { |d: nat| pair_cost(d, y) } + pub open spec fn pair_cost_right_fn(x: nat) -> spec_fn(nat) -> nat { |d: nat| pair_cost(x, d) } + /// Abstract cost of the intersect fold from index k with accumulator bound acc. + pub open spec fn fold_cost(ds: Seq, k: nat, acc: nat) -> nat decreases ds.len() - k when k <= ds.len() { + if k >= ds.len() { 1 } else { 1 + pair_cost(acc, ds[k as int]) + fold_cost(ds, k + 1, pair_bound(acc, ds[k as int])) } } + pub open spec fn fold_bound(ds: Seq, k: nat, acc: nat) -> nat decreases ds.len() - k when k <= ds.len() { + if k >= ds.len() { acc } else { fold_bound(ds, k + 1, pair_bound(acc, ds[k as int])) } } + + // ---------------------------------------------------------------- n4 + + pub proof fn lemma_n4_mono(a: nat, b: nat) + requires a <= b, + ensures n4(a) <= n4(b), a < b ==> n4(a) < n4(b), + decreases b, + { + if a < b { + lemma_n4_mono(a, (b - 1) as nat); + lemma_n4_pos((b - 1) as nat); + } + } + + pub proof fn lemma_n4_add(a: nat, b: nat) + ensures n4(a + b) == n4(a) * n4(b), + decreases b, + { + if b > 0 { + lemma_n4_add(a, (b - 1) as nat); + let p = n4(a); + let q = n4((b - 1) as nat); + assert(n4(a + b) == 4 * n4((a + (b - 1)) as nat)); + assert(4 * (p * q) == p * (4 * q)) by (nonlinear_arith); + } else { + assert(n4(a) * 1 == n4(a)) by (nonlinear_arith); + } + } + + proof fn lemma_singleton(ds: Seq) + requires ds.len() == 1, + ensures sum_plus1(ds) == ds[0] + 1, prod_plus1(ds) == ds[0] + 1, ds.last() == ds[0], + { + let p = prod_plus1(ds.drop_last()); + assert(sum_plus1(ds.drop_last()) == 0); + assert(p == 1); + assert(p * (ds[0] + 1) == ds[0] + 1) by (nonlinear_arith) requires p == 1; + } + + pub proof fn lemma_log4_n4(k: nat) + ensures log4_floor(n4(k)) == k, + decreases k, + { + if k > 0 { + lemma_n4_pos((k - 1) as nat); + assert(n4(k) == 4 * n4((k - 1) as nat)); + assert(n4(k) / 4 == n4((k - 1) as nat)); + lemma_log4_n4((k - 1) as nat); + } + } + + proof fn lemma_n4_small() + ensures n4(0) == 1, n4(1) == 4, n4(2) == 16, + { + assert(n4(0) == 1); + assert(n4(1) == 4); + assert(n4(2) == 16); + } + + // ---------------------------------------------------------------- costs: positivity, steps + + pub proof fn lemma_costs_pos(d: nat) + ensures clean_cost(d) >= 1, not_cost(d) >= 1, append_cost(d) >= 1, + { + } + + proof fn lemma_pair_cost_pos(x: nat, y: nat) + ensures pair_cost(x, y) >= 1, + { + } + + proof fn lemma_clean_step(d: nat) + ensures clean_cost(d) <= clean_cost(d + 1), d >= 1 ==> 2 * clean_cost(d) <= clean_cost(d + 1), + { + lemma_costs_pos(d); + assert(((d + 1) - 1) as nat == d); + } + + proof fn lemma_not_step(d: nat) + ensures not_cost(d) <= not_cost(d + 1), d >= 1 ==> 2 * not_cost(d) <= not_cost(d + 1), + { + lemma_costs_pos(d); + assert(((d + 1) - 1) as nat == d); + } + + proof fn lemma_append_step(d: nat) + ensures append_cost(d) <= append_cost(d + 1), d >= 1 ==> 2 * append_cost(d) <= append_cost(d + 1), + { + lemma_costs_pos(d); + assert(((d + 1) - 1) as nat == d); + } + + proof fn lemma_pair_step_x(x: nat, y: nat) + ensures + pair_cost(x, y) <= pair_cost(x + 1, y), + x >= 1 && y >= 1 ==> 2 * pair_cost(x, y) <= pair_cost(x + 1, y), + { + lemma_pair_cost_pos(x, y); + lemma_pair_cost_pos(x + 1, y); + assert(((x + 1) - 1) as nat == x); + } + + proof fn lemma_pair_step_y(x: nat, y: nat) + ensures + pair_cost(x, y) <= pair_cost(x, y + 1), + x >= 1 && y >= 1 ==> 2 * pair_cost(x, y) <= pair_cost(x, y + 1), + { + lemma_pair_cost_pos(x, y); + lemma_pair_cost_pos(x, y + 1); + assert(((y + 1) - 1) as nat == y); + } + + // ---------------------------------------------------------------- generic step-function facts + + #[verifier::opaque] + pub open spec fn steps_ok(f: spec_fn(nat) -> nat) -> bool { + forall|d: nat| #[trigger] f(d) <= f(d + 1) && (d >= 1 ==> 2 * f(d) <= f(d + 1)) + } + + proof fn lemma_steps_at(f: spec_fn(nat) -> nat, d: nat) + requires steps_ok(f), + ensures f(d) <= f(d + 1), d >= 1 ==> 2 * f(d) <= f(d + 1), + { + reveal(steps_ok); + } + + proof fn lemma_f_mono(f: spec_fn(nat) -> nat, a: nat, b: nat) + requires steps_ok(f), a <= b, + ensures f(a) <= f(b), + decreases b - a, + { + if a < b { + lemma_f_mono(f, a, (b - 1) as nat); + lemma_steps_at(f, (b - 1) as nat); + } + } + + proof fn lemma_f_superadd(f: spec_fn(nat) -> nat, a: nat, b: nat) + requires steps_ok(f), a >= 1, b >= 1, + ensures f(a) + f(b) <= f(a + b), + { + let m: nat = if a >= b { a } else { b }; + lemma_f_mono(f, a, m); + lemma_f_mono(f, b, m); + lemma_steps_at(f, m); + lemma_f_mono(f, m + 1, a + b); + } + + proof fn lemma_all_pos_drop_last(ds: Seq) + requires all_pos(ds), ds.len() >= 1, + ensures all_pos(ds.drop_last()), ds.last() >= 1, + { + assert forall|i: int| 0 <= i < ds.drop_last().len() implies #[trigger] ds.drop_last()[i] >= 1 by { + assert(ds[i] >= 1); + } + assert(ds[ds.len() - 1] >= 1); + } + + proof fn lemma_f_sum(f: spec_fn(nat) -> nat, ds: Seq) + requires steps_ok(f), all_pos(ds), ds.len() >= 1, + ensures + sum_plus1(ds) >= 2 * ds.len(), + sum_map(f, ds) <= f((sum_plus1(ds) - ds.len()) as nat), + decreases ds.len(), + { + lemma_all_pos_drop_last(ds); + let p = ds.drop_last(); + if ds.len() == 1 { + assert(sum_map(f, p) == 0); + assert(sum_plus1(p) == 0); + } else { + lemma_f_sum(f, p); + let s1 = (sum_plus1(p) - p.len()) as nat; + lemma_f_superadd(f, s1, ds.last()); + assert((sum_plus1(ds) - ds.len()) as nat == s1 + ds.last()); + } + } + + proof fn lemma_sum_ge(ds: Seq) + requires all_pos(ds), + ensures sum_plus1(ds) >= 2 * ds.len(), + decreases ds.len(), + { + if ds.len() >= 1 { + lemma_all_pos_drop_last(ds); + lemma_sum_ge(ds.drop_last()); + } + } + + proof fn lemma_prod_ge(ds: Seq) + requires all_pos(ds), + ensures + prod_plus1(ds) >= ds.len() + 1, + prod_plus1(ds) >= sum_plus1(ds), + decreases ds.len(), + { + if ds.len() >= 1 { + lemma_all_pos_drop_last(ds); + let p = ds.drop_last(); + lemma_prod_ge(p); + let pp = prod_plus1(p); + let sp = sum_plus1(p); + let l = ds.last(); + let n = p.len(); + if n == 0 { + assert(pp == 1); + assert(sp == 0); + assert(pp * (l + 1) == l + 1) by (nonlinear_arith) requires pp == 1; + } else { + assert(pp * (l + 1) >= sp + l + 1 && pp * (l + 1) >= n + 2) by (nonlinear_arith) + requires pp >= sp, pp >= n + 1, n >= 1, l >= 1; + } + } + } + + proof fn lemma_prod_pos(ds: Seq) + ensures prod_plus1(ds) >= 1, + decreases ds.len(), + { + if ds.len() >= 1 { + lemma_prod_pos(ds.drop_last()); + let pp = prod_plus1(ds.drop_last()); + let l = ds.last(); + assert(pp * (l + 1) >= 1) by (nonlinear_arith) requires pp >= 1; + } + } + + proof fn lemma_f_sum_bounds(f: spec_fn(nat) -> nat, ds: Seq) + requires steps_ok(f), all_pos(ds), + ensures + sum_map(f, ds) <= f((union_bound(ds) - 1) as nat), + sum_map(f, ds) <= f((intersect_bound(ds) - 1) as nat), + { + if ds.len() == 1 { + lemma_singleton(ds); + lemma_f_sum(f, ds); + } else if ds.len() >= 2 { + lemma_f_sum(f, ds); + lemma_prod_ge(ds); + lemma_f_mono(f, (sum_plus1(ds) - ds.len()) as nat, (union_bound(ds) - 1) as nat); + lemma_f_mono(f, (sum_plus1(ds) - ds.len()) as nat, (intersect_bound(ds) - 1) as nat); + } + } + + // ---------------------------------------------------------------- monotonicity + + #[verifier::spinoff_prover] + proof fn lemma_clean_steps_ok() + ensures steps_ok(clean_cost_fn()), + { + hide(clean_cost); + reveal(steps_ok); + assert forall|d: nat| #[trigger] clean_cost_fn()(d) <= clean_cost_fn()(d + 1) + && (d >= 1 ==> 2 * clean_cost_fn()(d) <= clean_cost_fn()(d + 1)) by { + lemma_clean_step(d); + } + } + + #[verifier::spinoff_prover] + proof fn lemma_not_steps_ok() + ensures steps_ok(not_cost_fn()), + { + hide(not_cost); + reveal(steps_ok); + assert forall|d: nat| #[trigger] not_cost_fn()(d) <= not_cost_fn()(d + 1) + && (d >= 1 ==> 2 * not_cost_fn()(d) <= not_cost_fn()(d + 1)) by { + lemma_not_step(d); + } + } + + #[verifier::spinoff_prover] + proof fn lemma_append_steps_ok() + ensures steps_ok(append_cost_fn()), + { + hide(append_cost); + reveal(steps_ok); + assert forall|d: nat| #[trigger] append_cost_fn()(d) <= append_cost_fn()(d + 1) + && (d >= 1 ==> 2 * append_cost_fn()(d) <= append_cost_fn()(d + 1)) by { + lemma_append_step(d); + } + } + + proof fn lemma_pair_left_steps_ok(y: nat) + requires y >= 1, + ensures steps_ok(pair_cost_left_fn(y)), + { + reveal(steps_ok); + assert forall|d: nat| #[trigger] pair_cost_left_fn(y)(d) <= pair_cost_left_fn(y)(d + 1) + && (d >= 1 ==> 2 * pair_cost_left_fn(y)(d) <= pair_cost_left_fn(y)(d + 1)) by { + lemma_pair_step_x(d, y); + } + } + + proof fn lemma_pair_right_steps_ok(x: nat) + requires x >= 1, + ensures steps_ok(pair_cost_right_fn(x)), + { + reveal(steps_ok); + assert forall|d: nat| #[trigger] pair_cost_right_fn(x)(d) <= pair_cost_right_fn(x)(d + 1) + && (d >= 1 ==> 2 * pair_cost_right_fn(x)(d) <= pair_cost_right_fn(x)(d + 1)) by { + lemma_pair_step_y(x, d); + } + } + + pub proof fn lemma_clean_cost_mono(a: nat, b: nat) + requires a <= b, + ensures clean_cost(a) <= clean_cost(b), + { + lemma_clean_steps_ok(); + lemma_f_mono(clean_cost_fn(), a, b); + } + + pub proof fn lemma_not_cost_mono(a: nat, b: nat) + requires a <= b, + ensures not_cost(a) <= not_cost(b), + { + lemma_not_steps_ok(); + lemma_f_mono(not_cost_fn(), a, b); + } + + pub proof fn lemma_append_cost_mono(a: nat, b: nat) + requires a <= b, + ensures append_cost(a) <= append_cost(b), + { + lemma_append_steps_ok(); + lemma_f_mono(append_cost_fn(), a, b); + } + + proof fn lemma_pair_cost_mono_x(x1: nat, x2: nat, y: nat) + requires x1 <= x2, + ensures pair_cost(x1, y) <= pair_cost(x2, y), + decreases x2, + { + if x1 < x2 { + lemma_pair_cost_mono_x(x1, (x2 - 1) as nat, y); + lemma_pair_step_x((x2 - 1) as nat, y); + } + } + + proof fn lemma_pair_cost_mono_y(x: nat, y1: nat, y2: nat) + requires y1 <= y2, + ensures pair_cost(x, y1) <= pair_cost(x, y2), + decreases y2, + { + if y1 < y2 { + lemma_pair_cost_mono_y(x, y1, (y2 - 1) as nat); + lemma_pair_step_y(x, (y2 - 1) as nat); + } + } + + pub proof fn lemma_pair_cost_mono(x1: nat, y1: nat, x2: nat, y2: nat) + requires x1 <= x2, y1 <= y2, + ensures 1 <= pair_cost(x1, y1) <= pair_cost(x2, y2), + { + lemma_pair_cost_pos(x1, y1); + lemma_pair_cost_mono_x(x1, x2, y1); + lemma_pair_cost_mono_y(x2, y1, y2); + } + + proof fn lemma_row_mono_y(x: nat, y1: nat, y2: nat, e: nat) + requires y1 <= y2, + ensures pair_cost_row(x, y1, e) <= pair_cost_row(x, y2, e), + decreases y2, + { + if y1 < y2 { + lemma_row_mono_y(x, y1, (y2 - 1) as nat, e); + } + } + + proof fn lemma_row_mono_e(x: nat, y: nat, e1: nat, e2: nat) + requires e1 <= e2, + ensures pair_cost_row(x, y, e1) <= pair_cost_row(x, y, e2), + decreases y, + { + if y > 0 { + lemma_row_mono_e(x, (y - 1) as nat, e1, e2); + } + } + + proof fn lemma_upto_mono_x(x1: nat, x2: nat, e: nat) + requires x1 <= x2, + ensures pair_cost_upto(x1, e) <= pair_cost_upto(x2, e), + decreases x2, + { + if x1 < x2 { + lemma_upto_mono_x(x1, (x2 - 1) as nat, e); + } + } + + proof fn lemma_upto_mono_e(x: nat, e1: nat, e2: nat) + requires e1 <= e2, + ensures pair_cost_upto(x, e1) <= pair_cost_upto(x, e2), + decreases x, + { + if x > 0 { + lemma_upto_mono_e((x - 1) as nat, e1, e2); + lemma_row_mono_e(x, e1, e1, e2); + lemma_row_mono_y(x, e1, e2, e2); + } + } + + pub proof fn lemma_pair_cost_total_mono(a: nat, b: nat) + requires a <= b, + ensures pair_cost_total(a) <= pair_cost_total(b), + { + lemma_upto_mono_e(a, a, b); + lemma_upto_mono_x(a, b, b); + } + + pub proof fn lemma_pair_bound_mono(a1: nat, b1: nat, a2: nat, b2: nat) + requires a1 <= a2, b1 <= b2, + ensures pair_bound(a1, b1) <= pair_bound(a2, b2), + { + assert(a1 * b1 <= a2 * b2) by (nonlinear_arith) requires a1 <= a2, b1 <= b2; + } + + pub proof fn lemma_pair_bound_ge(a: nat, b: nat) + ensures a <= pair_bound(a, b), b <= pair_bound(a, b), + { + assert(a * b >= 0) by (nonlinear_arith); + } + + /// `TransitionId::collect([a, b], true)` stays within `pair_bound`. + pub proof fn collect_lemma_pair_bound(g: model::Graph, a: TransitionId, b: TransitionId) + ensures collect_bound(g, seq![a, b], true) == pair_bound(tdepth(g, a@), tdepth(g, b@)), + { + let x = tdepth(g, a@); + let y = tdepth(g, b@); + let ds = value_depths(g, seq![a, b]); + assert(ds =~= seq![x, y]); + assert(ds.drop_last() =~= seq![x]); + assert(ds.last() == y); + lemma_singleton(seq![x]); + assert(prod_plus1(ds) == (x + 1) * (y + 1)); + assert((x + 1) * (y + 1) == x * y + x + y + 1) by (nonlinear_arith); + } + + pub proof fn lemma_pair_bound_comm(a: nat, b: nat) + ensures pair_bound(a, b) == pair_bound(b, a), + { + assert(a * b == b * a) by (nonlinear_arith); + } + + // ---------------------------------------------------------------- set bounds + + proof fn lemma_le_pointwise_drop_last(a: Seq, b: Seq) + requires le_pointwise(a, b), a.len() >= 1, + ensures le_pointwise(a.drop_last(), b.drop_last()), a.last() <= b.last(), + { + assert forall|i: int| 0 <= i < a.drop_last().len() implies #[trigger] a.drop_last()[i] <= b.drop_last()[i] by { + assert(a[i] <= b[i]); + } + assert(a[a.len() - 1] <= b[a.len() - 1]); + } + + proof fn lemma_totals_mono(a: Seq, b: Seq) + requires le_pointwise(a, b), + ensures sum_plus1(a) <= sum_plus1(b), prod_plus1(a) <= prod_plus1(b), + decreases a.len(), + { + if a.len() >= 1 { + lemma_le_pointwise_drop_last(a, b); + lemma_totals_mono(a.drop_last(), b.drop_last()); + let pa = prod_plus1(a.drop_last()); + let pb = prod_plus1(b.drop_last()); + let la = a.last(); + let lb = b.last(); + assert(pa * (la + 1) <= pb * (lb + 1)) by (nonlinear_arith) requires pa <= pb, la <= lb; + } + } + + pub proof fn lemma_bounds_mono(a: Seq, b: Seq) + requires le_pointwise(a, b), + ensures union_bound(a) <= union_bound(b), intersect_bound(a) <= intersect_bound(b), + { + lemma_totals_mono(a, b); + lemma_prod_pos(a); + lemma_prod_pos(b); + assert(prod_plus1(a) <= prod_plus1(b)); + } + + pub proof fn lemma_bounds_pos(ds: Seq) + requires all_pos(ds), + ensures + union_bound(ds) >= 2, + intersect_bound(ds) >= 2, + sum_plus1(ds) <= union_bound(ds) + 1, + prod_plus1(ds) <= intersect_bound(ds) + 1, + prod_plus1(ds) >= 1, + ds.len() >= 2 ==> union_bound(ds) + 1 == sum_plus1(ds) && intersect_bound(ds) + 1 == prod_plus1(ds), + { + lemma_sum_ge(ds); + lemma_prod_ge(ds); + } + + // ---------------------------------------------------------------- sum lemmas + + pub proof fn lemma_clean_sum(ds: Seq) + requires all_pos(ds), + ensures + sum_map(clean_cost_fn(), ds) <= clean_cost((union_bound(ds) - 1) as nat), + sum_map(clean_cost_fn(), ds) <= clean_cost((intersect_bound(ds) - 1) as nat), + { + lemma_clean_steps_ok(); + lemma_f_sum_bounds(clean_cost_fn(), ds); + } + + pub proof fn lemma_not_sum(ds: Seq) + requires all_pos(ds), + ensures + sum_map(not_cost_fn(), ds) <= not_cost((union_bound(ds) - 1) as nat), + sum_map(not_cost_fn(), ds) <= not_cost((intersect_bound(ds) - 1) as nat), + { + lemma_not_steps_ok(); + lemma_f_sum_bounds(not_cost_fn(), ds); + } + + pub proof fn lemma_append_sum(ds: Seq) + requires all_pos(ds), + ensures + sum_map(append_cost_fn(), ds) <= append_cost((union_bound(ds) - 1) as nat), + sum_map(append_cost_fn(), ds) <= append_cost((intersect_bound(ds) - 1) as nat), + { + lemma_append_steps_ok(); + lemma_f_sum_bounds(append_cost_fn(), ds); + } + + pub proof fn lemma_pair_left_sum(ds: Seq, y: nat) + requires all_pos(ds), y >= 1, + ensures sum_map(pair_cost_left_fn(y), ds) <= pair_cost((union_bound(ds) - 1) as nat, y), + { + lemma_pair_left_steps_ok(y); + lemma_f_sum_bounds(pair_cost_left_fn(y), ds); + } + + pub proof fn lemma_pair_right_sum(x: nat, ds: Seq) + requires all_pos(ds), x >= 1, + ensures sum_map(pair_cost_right_fn(x), ds) <= pair_cost(x, (union_bound(ds) - 1) as nat), + { + lemma_pair_right_steps_ok(x); + lemma_f_sum_bounds(pair_cost_right_fn(x), ds); + } + + // ---------------------------------------------------------------- Not bounds + + proof fn lemma_n4s_prod(ds: Seq) + requires ds.len() >= 1, + ensures + sum_plus1(ds) >= 1, + prod_plus1(n4s(ds)) <= 2 * n4((sum_plus1(ds) - 1) as nat), + ds.len() >= 2 ==> prod_plus1(n4s(ds)) <= n4((sum_plus1(ds) - 1) as nat), + decreases ds.len(), + { + let p = ds.drop_last(); + let l = ds.last(); + assert(n4s(ds).drop_last() =~= n4s(p)); + assert(n4s(ds).last() == n4(l)); + lemma_n4_pos(l); + if ds.len() == 1 { + lemma_singleton(ds); + lemma_singleton(n4s(ds)); + } else { + lemma_n4s_prod(p); + let a = (sum_plus1(p) - 1) as nat; + let pp = prod_plus1(n4s(p)); + let m = n4(a); + let q = n4(l); + lemma_n4_add(a, l + 1); + assert(n4(l + 1) == 4 * q); + assert((sum_plus1(ds) - 1) as nat == a + (l + 1)); + assert(pp * (q + 1) <= m * (4 * q)) by (nonlinear_arith) requires pp <= 2 * m, q >= 1; + } + } + + proof fn lemma_n4s_sum(ds: Seq) + requires ds.len() >= 1, all_pos(ds), + ensures + prod_plus1(ds) >= 1, + sum_plus1(n4s(ds)) <= 2 * n4((prod_plus1(ds) - 1) as nat), + ds.len() >= 2 ==> sum_plus1(n4s(ds)) <= n4((prod_plus1(ds) - 1) as nat), + decreases ds.len(), + { + let p = ds.drop_last(); + let l = ds.last(); + lemma_all_pos_drop_last(ds); + assert(n4s(ds).drop_last() =~= n4s(p)); + assert(n4s(ds).last() == n4(l)); + lemma_n4_pos(l); + lemma_prod_pos(ds); + if ds.len() == 1 { + lemma_singleton(ds); + lemma_singleton(n4s(ds)); + } else { + lemma_n4s_sum(p); + lemma_prod_ge(p); + let pp = prod_plus1(p); + let a = (pp - 1) as nat; + let s = sum_plus1(n4s(p)); + let m = n4(a); + let q = n4(l); + lemma_n4_pos(a); + lemma_n4_add(a, l + 1); + assert(n4(l + 1) == 4 * q); + assert(pp * (l + 1) - 1 >= a + (l + 1)) by (nonlinear_arith) requires pp == a + 1, a >= 1, l >= 1; + lemma_n4_mono(a + (l + 1), (prod_plus1(ds) - 1) as nat); + assert(2 * m + q + 1 <= m * (4 * q)) by (nonlinear_arith) requires m >= 1, q >= 1; + } + } + + pub proof fn lemma_not_union(ds: Seq) + requires all_pos(ds), + ensures intersect_bound(n4s(ds)) < n4(union_bound(ds)), + { + lemma_n4_small(); + if ds.len() == 1 { + lemma_singleton(ds); + lemma_singleton(n4s(ds)); + lemma_n4_pos(ds[0]); + assert(union_bound(ds) == ds[0] + 1); + assert(n4(ds[0] + 1) == 4 * n4(ds[0])); + assert(n4s(ds)[0] == n4(ds[0])); + } else if ds.len() >= 2 { + lemma_n4s_prod(ds); + lemma_n4_pos((sum_plus1(ds) - 1) as nat); + lemma_prod_pos(n4s(ds)); + } + } + + pub proof fn lemma_not_intersect(ds: Seq) + requires all_pos(ds), + ensures union_bound(n4s(ds)) <= n4(intersect_bound(ds)), + { + lemma_n4_small(); + if ds.len() == 1 { + lemma_singleton(ds); + lemma_singleton(n4s(ds)); + lemma_n4_pos(ds[0]); + } else if ds.len() >= 2 { + lemma_n4s_sum(ds); + } + } + + // ---------------------------------------------------------------- Append / Pair over unions + + proof fn lemma_appends_sum(ds: Seq) + ensures sum_plus1(appends(ds)) == 2 * sum_plus1(ds), + decreases ds.len(), + { + if ds.len() >= 1 { + assert(appends(ds).drop_last() =~= appends(ds.drop_last())); + lemma_appends_sum(ds.drop_last()); + } + } + + pub proof fn lemma_append_union(ds: Seq) + requires all_pos(ds), + ensures union_bound(appends(ds)) <= 2 * union_bound(ds) + 1, + { + lemma_appends_sum(ds); + lemma_sum_ge(ds); + } + + proof fn lemma_pairs_left_sum(ds: Seq, y: nat) + ensures sum_plus1(pairs_left(ds, y)) == (y + 1) * sum_plus1(ds), + decreases ds.len(), + { + if ds.len() >= 1 { + assert(pairs_left(ds, y).drop_last() =~= pairs_left(ds.drop_last(), y)); + lemma_pairs_left_sum(ds.drop_last(), y); + let s = sum_plus1(ds.drop_last()); + let l = ds.last(); + assert((y + 1) * s + (l * y + l + y) + 1 == (y + 1) * (s + l + 1)) by (nonlinear_arith); + } else { + assert((y + 1) * sum_plus1(ds) == 0) by (nonlinear_arith) requires sum_plus1(ds) == 0; + } + } + + proof fn lemma_pairs_right_sum(x: nat, ds: Seq) + ensures sum_plus1(pairs_right(x, ds)) == (x + 1) * sum_plus1(ds), + decreases ds.len(), + { + if ds.len() >= 1 { + assert(pairs_right(x, ds).drop_last() =~= pairs_right(x, ds.drop_last())); + lemma_pairs_right_sum(x, ds.drop_last()); + let s = sum_plus1(ds.drop_last()); + let l = ds.last(); + assert((x + 1) * s + (x * l + x + l) + 1 == (x + 1) * (s + l + 1)) by (nonlinear_arith); + } else { + assert((x + 1) * sum_plus1(ds) == 0) by (nonlinear_arith) requires sum_plus1(ds) == 0; + } + } + + pub proof fn lemma_pair_union_left(ds: Seq, y: nat) + requires all_pos(ds), + ensures union_bound(pairs_left(ds, y)) <= pair_bound(union_bound(ds), y), + { + lemma_pairs_left_sum(ds, y); + lemma_sum_ge(ds); + let s = sum_plus1(ds); + let u = union_bound(ds); + if ds.len() == 1 { + lemma_singleton(ds); + assert((y + 1) * s <= u * y + u + y) by (nonlinear_arith) requires u == s; + } else if ds.len() >= 2 { + assert((y + 1) * s <= u * y + u + y + 1) by (nonlinear_arith) requires u + 1 == s; + } + } + + pub proof fn lemma_pair_union_right(x: nat, ds: Seq) + requires all_pos(ds), + ensures union_bound(pairs_right(x, ds)) <= pair_bound(x, union_bound(ds)), + { + lemma_pairs_right_sum(x, ds); + lemma_sum_ge(ds); + let s = sum_plus1(ds); + let u = union_bound(ds); + if ds.len() == 1 { + lemma_singleton(ds); + assert((x + 1) * s <= x * u + x + u) by (nonlinear_arith) requires u == s; + } else if ds.len() >= 2 { + assert((x + 1) * s <= x * u + x + u + 1) by (nonlinear_arith) requires u + 1 == s; + } + } + + // ---------------------------------------------------------------- intersect fold + + proof fn lemma_prod_front(ds: Seq) + requires ds.len() >= 1, + ensures prod_plus1(ds) == (ds[0] + 1) * prod_plus1(ds.subrange(1, ds.len() as int)), + decreases ds.len(), + { + let t = ds.subrange(1, ds.len() as int); + if ds.len() == 1 { + lemma_singleton(ds); + assert(prod_plus1(t) == 1); + assert((ds[0] + 1) * prod_plus1(t) == ds[0] + 1) by (nonlinear_arith) requires prod_plus1(t) == 1; + } else { + let p = ds.drop_last(); + lemma_prod_front(p); + assert(t.drop_last() =~= p.subrange(1, p.len() as int)); + assert(p[0] == ds[0]); + assert(t.last() == ds.last()); + let a = ds[0] + 1; + let b = prod_plus1(p.subrange(1, p.len() as int)); + let c = ds.last() + 1; + assert((a * b) * c == a * (b * c)) by (nonlinear_arith); + } + } + + #[verifier::spinoff_prover] + proof fn lemma_fold_bound_eq(ds: Seq, k: nat, acc: nat) + requires k <= ds.len(), + ensures + fold_bound(ds, k, acc) + 1 == (acc + 1) * prod_plus1(ds.subrange(k as int, ds.len() as int)), + fold_bound(ds, k, acc) >= acc, + decreases ds.len() - k, + { + let t = ds.subrange(k as int, ds.len() as int); + if k >= ds.len() { + assert(t.len() == 0); + assert(prod_plus1(t) == 1); + assert((acc + 1) * 1 == acc + 1) by (nonlinear_arith); + } else { + let d = ds[k as int]; + let acc2 = pair_bound(acc, d); + lemma_fold_bound_eq(ds, k + 1, acc2); + lemma_prod_front(t); + assert(t[0] == d); + assert(t.subrange(1, t.len() as int) =~= ds.subrange(k + 1 as int, ds.len() as int)); + let r = prod_plus1(ds.subrange(k + 1 as int, ds.len() as int)); + assert((acc * d + acc + d + 1) * r == (acc + 1) * ((d + 1) * r)) by (nonlinear_arith); + assert(acc * d >= 0) by (nonlinear_arith); + } + } + + proof fn lemma_row_ge(x: nat, y: nat, ye: nat, e: nat) + requires 1 <= y <= ye, pair_bound(x, y) <= e, + ensures pair_cost(x, y) <= pair_cost_row(x, ye, e), + decreases ye, + { + if y < ye { + lemma_row_ge(x, y, (ye - 1) as nat, e); + } + } + + proof fn lemma_fold_cost_bound(ds: Seq, k: nat, acc: nat, e: nat) + requires acc >= 1, k <= ds.len(), all_pos(ds), e >= fold_bound(ds, k, acc), + ensures + fold_cost(ds, k, acc) + pair_cost_upto((acc - 1) as nat, e) + <= (ds.len() - k) + 1 + pair_cost_upto((fold_bound(ds, k, acc) - 1) as nat, e), + decreases ds.len() - k, + { + if k < ds.len() { + let d = ds[k as int]; + assert(d >= 1); + let acc2 = pair_bound(acc, d); + assert(acc * d >= 1) by (nonlinear_arith) requires acc >= 1, d >= 1; + lemma_fold_bound_eq(ds, k + 1, acc2); + lemma_fold_cost_bound(ds, k + 1, acc2, e); + lemma_row_ge(acc, d, e, e); + lemma_upto_mono_x(acc, (acc2 - 1) as nat, e); + assert(pair_cost_upto(acc, e) == pair_cost_row(acc, e, e) + pair_cost_upto((acc - 1) as nat, e)); + } + } + + pub proof fn lemma_fold(ds: Seq) + requires ds.len() >= 2, all_pos(ds), + ensures + fold_bound(ds, 1, ds[0]) == intersect_bound(ds), + fold_cost(ds, 1, ds[0]) <= intersect_bound(ds) + pair_cost_total(intersect_bound(ds)), + { + let e = intersect_bound(ds); + lemma_fold_bound_eq(ds, 1, ds[0]); + lemma_prod_front(ds); + lemma_prod_ge(ds); + assert(ds[0] >= 1); + lemma_fold_cost_bound(ds, 1, ds[0], e); + lemma_upto_mono_x((e - 1) as nat, e, e); + } + + pub proof fn lemma_fold_mono(ds: Seq, k: nat, a: nat, b: nat) + requires a <= b, k <= ds.len(), + ensures fold_cost(ds, k, a) <= fold_cost(ds, k, b), fold_bound(ds, k, a) <= fold_bound(ds, k, b), + decreases ds.len() - k, + { + if k < ds.len() { + let d = ds[k as int]; + lemma_pair_bound_mono(a, d, b, d); + lemma_pair_cost_mono(a, d, b, d); + lemma_fold_mono(ds, k + 1, pair_bound(a, d), pair_bound(b, d)); + } + } + + // ===== Action::run termination: per-node depth bounds and an abstract run of the task stack ===== + + /// Depth bound of a transition node: `1 + max` at `If`, additive at `Union`, multiplicative at + /// `Intersect`, `4^d` at `Not`, `2d + 1` at `Append`. + pub open spec fn tdepth(g: model::Graph, id: nat) -> nat + decreases id, 1nat, + { + if id >= g.transitions.len() { 1 } else { + match g.transitions[id as int] { + model::TransitionNode::Const(_) => 1, + model::TransitionNode::If(_, a, b) => if_bound( + if a < id { tdepth(g, a) } else { 1 }, if b < id { tdepth(g, b) } else { 1 }), + model::TransitionNode::Union(cs) => union_bound(tdepths_bounded(g, cs, id)), + model::TransitionNode::Intersect(cs) => intersect_bound(tdepths_bounded(g, cs, id)), + model::TransitionNode::Not(c) => n4(if c < id { tdepth(g, c) } else { 1 }), + model::TransitionNode::Append(c, _) => 2 * (if c < id { tdepth(g, c) } else { 1 }) + 1, + } + } + } + + pub open spec fn tdepths_bounded(g: model::Graph, cs: Seq, bound: nat) -> Seq + decreases bound, 0nat, + { + Seq::new(cs.len(), |j: int| if 0 <= j < cs.len() && cs[j] < bound { tdepth(g, cs[j]) } else { 1 }) + } + + pub open spec fn tdepths(g: model::Graph, ids: Seq) -> Seq { + Seq::new(ids.len(), |i: int| tdepth(g, ids[i])) + } + + pub open spec fn value_depths(g: model::Graph, values: Seq) -> Seq { + Seq::new(values.len(), |i: int| tdepth(g, values[i]@)) + } + + pub open spec fn tdepth_node(g: model::Graph, node: model::TransitionNode) -> nat { + match node { + model::TransitionNode::Const(_) => 1, + model::TransitionNode::If(_, a, b) => if_bound(tdepth(g, a), tdepth(g, b)), + model::TransitionNode::Union(cs) => union_bound(tdepths(g, cs)), + model::TransitionNode::Intersect(cs) => intersect_bound(tdepths(g, cs)), + model::TransitionNode::Not(c) => n4(tdepth(g, c)), + model::TransitionNode::Append(c, _) => 2 * tdepth(g, c) + 1, + } + } + + pub proof fn tdepth_lemma_unfold(g: model::Graph, id: nat) + requires model::graph_wf(g), id < g.transitions.len(), + ensures tdepth(g, id) == tdepth_node(g, g.transitions[id as int]), + { + model::lemma_graph_transition_wf(g, id); + match g.transitions[id as int] { + model::TransitionNode::Union(cs) => { assert(tdepths_bounded(g, cs, id) =~= tdepths(g, cs)); }, + model::TransitionNode::Intersect(cs) => { assert(tdepths_bounded(g, cs, id) =~= tdepths(g, cs)); }, + _ => {}, + } + } + + pub proof fn tdepth_lemma_pos(g: model::Graph, id: nat) + ensures tdepth(g, id) >= 1, + decreases id, + { + if id < g.transitions.len() { + match g.transitions[id as int] { + model::TransitionNode::Union(cs) => { + let ds = tdepths_bounded(g, cs, id); + assert forall|j: int| 0 <= j < ds.len() implies #[trigger] ds[j] >= 1 by { + if cs[j] < id { tdepth_lemma_pos(g, cs[j]); } + } + lemma_bounds_pos(ds); + }, + model::TransitionNode::Intersect(cs) => { + let ds = tdepths_bounded(g, cs, id); + assert forall|j: int| 0 <= j < ds.len() implies #[trigger] ds[j] >= 1 by { + if cs[j] < id { tdepth_lemma_pos(g, cs[j]); } + } + lemma_bounds_pos(ds); + }, + model::TransitionNode::Not(c) => { lemma_n4_pos(if c < id { tdepth(g, c) } else { 1 }); }, + _ => {}, + } + } + } + + pub proof fn tdepths_lemma_pos(g: model::Graph, ids: Seq) + ensures all_pos(tdepths(g, ids)), + { + assert forall|i: int| 0 <= i < tdepths(g, ids).len() implies #[trigger] tdepths(g, ids)[i] >= 1 by { + tdepth_lemma_pos(g, ids[i]); + } + } + + pub proof fn value_depths_lemma_pos(g: model::Graph, values: Seq) + ensures all_pos(value_depths(g, values)), + { + assert forall|i: int| 0 <= i < value_depths(g, values).len() implies #[trigger] value_depths(g, values)[i] >= 1 by { + tdepth_lemma_pos(g, values[i]@); + } + } + + pub proof fn tdepth_lemma_extends(a: model::Graph, b: model::Graph, id: nat) + requires model::graph_extends(a, b), id < a.transitions.len(), + ensures tdepth(a, id) == tdepth(b, id), + decreases id, + { + assert(a.transitions[id as int] == b.transitions[id as int]); + match a.transitions[id as int] { + model::TransitionNode::If(_, x, y) => { + if x < id { tdepth_lemma_extends(a, b, x); } + if y < id { tdepth_lemma_extends(a, b, y); } + }, + model::TransitionNode::Union(cs) => { + assert forall|j: int| 0 <= j < cs.len() implies tdepths_bounded(a, cs, id)[j] == tdepths_bounded(b, cs, id)[j] by { + if cs[j] < id { tdepth_lemma_extends(a, b, cs[j]); } + } + assert(tdepths_bounded(a, cs, id) =~= tdepths_bounded(b, cs, id)); + }, + model::TransitionNode::Intersect(cs) => { + assert forall|j: int| 0 <= j < cs.len() implies tdepths_bounded(a, cs, id)[j] == tdepths_bounded(b, cs, id)[j] by { + if cs[j] < id { tdepth_lemma_extends(a, b, cs[j]); } + } + assert(tdepths_bounded(a, cs, id) =~= tdepths_bounded(b, cs, id)); + }, + model::TransitionNode::Not(c) => { if c < id { tdepth_lemma_extends(a, b, c); } }, + model::TransitionNode::Append(c, _) => { if c < id { tdepth_lemma_extends(a, b, c); } }, + _ => {}, + } + } + + pub proof fn tdepth_lemma_extends_forall(a: model::Graph) + ensures forall|b: model::Graph, id: nat| model::graph_extends(a, b) && id < a.transitions.len() + ==> #[trigger] tdepth(b, id) == tdepth(a, id), + { + assert forall|b: model::Graph, id: nat| model::graph_extends(a, b) && id < a.transitions.len() + implies #[trigger] tdepth(b, id) == tdepth(a, id) by { tdepth_lemma_extends(a, b, id); } + } + + pub proof fn tdepths_lemma_extends(a: model::Graph, b: model::Graph, ids: Seq) + requires model::graph_extends(a, b), model::bounded(ids, a.transitions.len()), + ensures tdepths(a, ids) == tdepths(b, ids), + { + assert forall|i: int| 0 <= i < ids.len() implies tdepths(a, ids)[i] == tdepths(b, ids)[i] by { + tdepth_lemma_extends(a, b, ids[i]); + } + assert(tdepths(a, ids) =~= tdepths(b, ids)); + } + + pub proof fn tdepths_lemma_extends_forall(a: model::Graph, values: Seq) + requires transition_ids_valid(a, values), + ensures forall|b: model::Graph| model::graph_extends(a, b) + ==> #[trigger] tdepths(b, model::transition_ids(values)) == tdepths(a, model::transition_ids(values)), + { + let ids = model::transition_ids(values); + assert(model::bounded(ids, a.transitions.len())); + assert forall|b: model::Graph| model::graph_extends(a, b) + implies #[trigger] tdepths(b, ids) == tdepths(a, ids) by { tdepths_lemma_extends(a, b, ids); } + } + + pub proof fn value_depths_lemma_extends(a: model::Graph, b: model::Graph, values: Seq) + requires model::graph_extends(a, b), transition_ids_valid(a, values), + ensures value_depths(a, values) == value_depths(b, values), + { + assert forall|i: int| 0 <= i < values.len() implies value_depths(a, values)[i] == value_depths(b, values)[i] by { + tdepth_lemma_extends(a, b, values[i]@); + } + assert(value_depths(a, values) =~= value_depths(b, values)); + } + + pub proof fn tdepth_lemma_constants(g: model::Graph) + requires model::graph_wf(g), + ensures tdepth(g, g.constants.transition_empty) == 1, tdepth(g, g.constants.transition_all) == 1, + tdepth(g, g.constants.transition_epsilon) == 1, + { + model::lemma_graph_wf_elim(g); + } + + pub proof fn tdepth_lemma_const(g: model::Graph, id: nat) + requires id < g.transitions.len(), g.transitions[id as int] is Const, + ensures tdepth(g, id) == 1, + {} + + // ----- abstract value stack ----- + + pub open spec fn abs_at(stack: Seq, j: int) -> nat { if 0 <= j < stack.len() { stack[j] } else { 1 } } + pub open spec fn abs_peek(stack: Seq, from_top: nat) -> nat { abs_at(stack, stack.len() - 1 - from_top) } + pub open spec fn abs_top(stack: Seq, k: nat) -> Seq { Seq::new(k, |i: int| abs_at(stack, stack.len() - k + i)) } + pub open spec fn abs_pop(stack: Seq, k: nat) -> Seq { + if k <= stack.len() { stack.take(stack.len() - k) } else { Seq::empty() } + } + + pub open spec fn action_cost(g: model::Graph, task: ActionShape, stack: Seq) -> nat { + match task { + ActionShape::Clean(id, _) => clean_cost(tdepth(g, id)), + ActionShape::Not(id) => not_cost(tdepth(g, id)), + ActionShape::Append(id, _) => append_cost(tdepth(g, id)), + ActionShape::Pair(a, b) => pair_cost(tdepth(g, a), tdepth(g, b)), + ActionShape::Union(_) => 1, + ActionShape::If(_) => 1, + ActionShape::SwapThen => 1, + ActionShape::Intersect(n) => + 2 + intersect_bound(abs_top(stack, n)) + pair_cost_total(intersect_bound(abs_top(stack, n))), + ActionShape::Fold(xs, k) => if k == 0 { + 1 + intersect_bound(tdepths(g, xs)) + pair_cost_total(intersect_bound(tdepths(g, xs))) + } else if k >= xs.len() { 1 } else { fold_cost(tdepths(g, xs), k, abs_peek(stack, 0)) }, + ActionShape::CleanIf(_, _) => 1 + clean_cost(if_bound(abs_peek(stack, 1), abs_peek(stack, 0))), + ActionShape::NotResult => 1 + not_cost(abs_peek(stack, 0)), + ActionShape::AppendResult(_) => 1 + append_cost(abs_peek(stack, 0)), + } + } + + pub open spec fn action_next(g: model::Graph, task: ActionShape, stack: Seq) -> Seq { + match task { + ActionShape::Clean(id, _) => stack.push(tdepth(g, id)), + ActionShape::Not(id) => stack.push(n4(tdepth(g, id))), + ActionShape::Append(id, _) => stack.push(2 * tdepth(g, id) + 1), + ActionShape::Pair(a, b) => stack.push(pair_bound(tdepth(g, a), tdepth(g, b))), + ActionShape::Union(n) => abs_pop(stack, n).push(union_bound(abs_top(stack, n))), + ActionShape::Intersect(n) => abs_pop(stack, n).push(intersect_bound(abs_top(stack, n))), + ActionShape::Fold(xs, k) => if k == 0 { stack.push(intersect_bound(tdepths(g, xs))) } + else if k >= xs.len() { stack } + else { abs_pop(stack, 1).push(fold_bound(tdepths(g, xs), k, abs_peek(stack, 0))) }, + ActionShape::If(_) => abs_pop(stack, 2).push(if_bound(abs_peek(stack, 1), abs_peek(stack, 0))), + ActionShape::CleanIf(_, _) => abs_pop(stack, 2).push(if_bound(abs_peek(stack, 1), abs_peek(stack, 0))), + ActionShape::NotResult => abs_pop(stack, 1).push(n4(abs_peek(stack, 0))), + ActionShape::AppendResult(_) => abs_pop(stack, 1).push(2 * abs_peek(stack, 0) + 1), + ActionShape::SwapThen => abs_pop(stack, 2).push(abs_peek(stack, 0)).push(abs_peek(stack, 1)), + } + } + + /// Runs `tasks` (top = last) over an abstract stack of depth bounds; returns total cost and final stack. + pub open spec fn machine_run(g: model::Graph, tasks: Seq, stack: Seq) -> (nat, Seq) + decreases tasks.len(), + { + if tasks.len() == 0 { (0, stack) } else { + let rest = machine_run(g, tasks.drop_last(), action_next(g, tasks.last(), stack)); + (action_cost(g, tasks.last(), stack) + rest.0, rest.1) + } + } + + /// Termination measure of `Action::run`. + pub open spec fn machine_cost(g: model::Graph, tasks: Seq, values: Seq) -> nat { + machine_run(g, tasks, value_depths(g, values)).0 + } + + /// One machine step strictly lowers `machine_cost`: `task` was popped from `tasks0`. + pub open spec fn machine_progress( + g0: model::Graph, tasks0: Seq, task: ActionShape, v0: Seq, + g1: model::Graph, tasks1: Seq, v1: Seq, + ) -> bool { + machine_cost(g1, tasks1, v1) < machine_cost(g0, tasks0.push(task), v0) + } + + pub proof fn le_pointwise_push(s1: Seq, s2: Seq, x: nat, y: nat) + requires le_pointwise(s1, s2), x <= y, + ensures le_pointwise(s1.push(x), s2.push(y)), + { + assert forall|i: int| 0 <= i < s1.push(x).len() implies #[trigger] s1.push(x)[i] <= s2.push(y)[i] by { + if i < s1.len() { assert(s1[i] <= s2[i]); } + } + } + + pub proof fn le_pointwise_refl(s: Seq) + ensures le_pointwise(s, s), + {} + + pub proof fn machine_lemma_stack_mono(s1: Seq, s2: Seq, k: nat) + requires le_pointwise(s1, s2), + ensures le_pointwise(abs_top(s1, k), abs_top(s2, k)), le_pointwise(abs_pop(s1, k), abs_pop(s2, k)), + abs_peek(s1, k) <= abs_peek(s2, k), + { + assert forall|i: int| 0 <= i < abs_top(s1, k).len() implies #[trigger] abs_top(s1, k)[i] <= abs_top(s2, k)[i] by { + let j = s1.len() - k + i; + if 0 <= j < s1.len() { assert(s1[j] <= s2[j]); } + } + assert forall|i: int| 0 <= i < abs_pop(s1, k).len() implies #[trigger] abs_pop(s1, k)[i] <= abs_pop(s2, k)[i] by { + assert(s1[i] <= s2[i]); + } + let j = s1.len() - 1 - k; + if 0 <= j < s1.len() { assert(s1[j] <= s2[j]); } + } + + pub proof fn machine_lemma_action_mono(g: model::Graph, task: ActionShape, s1: Seq, s2: Seq) + requires le_pointwise(s1, s2), + ensures action_cost(g, task, s1) <= action_cost(g, task, s2), + le_pointwise(action_next(g, task, s1), action_next(g, task, s2)), + { + machine_lemma_stack_mono(s1, s2, 0); + machine_lemma_stack_mono(s1, s2, 1); + machine_lemma_stack_mono(s1, s2, 2); + let p0 = abs_peek(s1, 0); + let q0 = abs_peek(s2, 0); + let p1 = abs_peek(s1, 1); + let q1 = abs_peek(s2, 1); + match task { + ActionShape::Clean(id, _) => { le_pointwise_push(s1, s2, tdepth(g, id), tdepth(g, id)); }, + ActionShape::Not(id) => { le_pointwise_push(s1, s2, n4(tdepth(g, id)), n4(tdepth(g, id))); }, + ActionShape::Append(id, _) => { le_pointwise_push(s1, s2, 2 * tdepth(g, id) + 1, 2 * tdepth(g, id) + 1); }, + ActionShape::Pair(a, b) => { + let v = pair_bound(tdepth(g, a), tdepth(g, b)); + le_pointwise_push(s1, s2, v, v); + }, + ActionShape::Union(n) => { + machine_lemma_stack_mono(s1, s2, n); + lemma_bounds_mono(abs_top(s1, n), abs_top(s2, n)); + le_pointwise_push(abs_pop(s1, n), abs_pop(s2, n), union_bound(abs_top(s1, n)), union_bound(abs_top(s2, n))); + }, + ActionShape::Intersect(n) => { + machine_lemma_stack_mono(s1, s2, n); + lemma_bounds_mono(abs_top(s1, n), abs_top(s2, n)); + lemma_pair_cost_total_mono(intersect_bound(abs_top(s1, n)), intersect_bound(abs_top(s2, n))); + le_pointwise_push(abs_pop(s1, n), abs_pop(s2, n), + intersect_bound(abs_top(s1, n)), intersect_bound(abs_top(s2, n))); + }, + ActionShape::Fold(xs, k) => { + let ds = tdepths(g, xs); + if k == 0 { + le_pointwise_push(s1, s2, intersect_bound(ds), intersect_bound(ds)); + } else if k < xs.len() { + lemma_fold_mono(ds, k, p0, q0); + le_pointwise_push(abs_pop(s1, 1), abs_pop(s2, 1), fold_bound(ds, k, p0), fold_bound(ds, k, q0)); + } + }, + ActionShape::If(_) => { + le_pointwise_push(abs_pop(s1, 2), abs_pop(s2, 2), if_bound(p1, p0), if_bound(q1, q0)); + }, + ActionShape::CleanIf(_, _) => { + lemma_clean_cost_mono(if_bound(p1, p0), if_bound(q1, q0)); + le_pointwise_push(abs_pop(s1, 2), abs_pop(s2, 2), if_bound(p1, p0), if_bound(q1, q0)); + }, + ActionShape::NotResult => { + lemma_not_cost_mono(p0, q0); + lemma_n4_mono(p0, q0); + le_pointwise_push(abs_pop(s1, 1), abs_pop(s2, 1), n4(p0), n4(q0)); + }, + ActionShape::AppendResult(_) => { + lemma_append_cost_mono(p0, q0); + le_pointwise_push(abs_pop(s1, 1), abs_pop(s2, 1), 2 * p0 + 1, 2 * q0 + 1); + }, + ActionShape::SwapThen => { + le_pointwise_push(abs_pop(s1, 2), abs_pop(s2, 2), p0, q0); + le_pointwise_push(abs_pop(s1, 2).push(p0), abs_pop(s2, 2).push(q0), p1, q1); + }, + } + } + + pub proof fn machine_lemma_run_mono(g: model::Graph, tasks: Seq, s1: Seq, s2: Seq) + requires le_pointwise(s1, s2), + ensures machine_run(g, tasks, s1).0 <= machine_run(g, tasks, s2).0, + le_pointwise(machine_run(g, tasks, s1).1, machine_run(g, tasks, s2).1), + decreases tasks.len(), + { + if tasks.len() > 0 { + machine_lemma_action_mono(g, tasks.last(), s1, s2); + machine_lemma_run_mono(g, tasks.drop_last(), action_next(g, tasks.last(), s1), action_next(g, tasks.last(), s2)); + } + } + + pub proof fn machine_lemma_run_split(g: model::Graph, pre: Seq, post: Seq, s: Seq) + ensures machine_run(g, pre + post, s).0 + == machine_run(g, post, s).0 + machine_run(g, pre, machine_run(g, post, s).1).0, + machine_run(g, pre + post, s).1 == machine_run(g, pre, machine_run(g, post, s).1).1, + decreases post.len(), + { + if post.len() == 0 { + assert(pre + post =~= pre); + } else { + assert((pre + post).drop_last() =~= pre + post.drop_last()); + assert((pre + post).last() == post.last()); + machine_lemma_run_split(g, pre, post.drop_last(), action_next(g, post.last(), s)); + } + } + + pub proof fn machine_lemma_action_extends(g0: model::Graph, g1: model::Graph, task: ActionShape, s: Seq) + requires model::graph_extends(g0, g1), transition_action_valid(g0, task), + ensures action_cost(g0, task, s) == action_cost(g1, task, s), action_next(g0, task, s) == action_next(g1, task, s), + { + match task { + ActionShape::Clean(id, _) => { tdepth_lemma_extends(g0, g1, id); }, + ActionShape::Not(id) => { tdepth_lemma_extends(g0, g1, id); }, + ActionShape::Append(id, _) => { tdepth_lemma_extends(g0, g1, id); }, + ActionShape::Pair(a, b) => { tdepth_lemma_extends(g0, g1, a); tdepth_lemma_extends(g0, g1, b); }, + ActionShape::Fold(xs, _) => { tdepths_lemma_extends(g0, g1, xs); }, + _ => {}, + } + } + + pub proof fn machine_lemma_run_extends(g0: model::Graph, g1: model::Graph, tasks: Seq, s: Seq) + requires model::graph_extends(g0, g1), transition_tasks_valid(g0, tasks), + ensures machine_run(g0, tasks, s) == machine_run(g1, tasks, s), + decreases tasks.len(), + { + if tasks.len() > 0 { + let t = tasks.last(); + assert(transition_action_valid(g0, tasks[tasks.len() - 1])); + machine_lemma_action_extends(g0, g1, t, s); + assert forall|i: int| 0 <= i < tasks.drop_last().len() implies transition_action_valid(g0, #[trigger] tasks.drop_last()[i]) by { + assert(tasks.drop_last()[i] == tasks[i]); + } + machine_lemma_run_extends(g0, g1, tasks.drop_last(), action_next(g0, t, s)); + } + } + + /// One machine step: popping `task` and pushing `added` lowers the measure when the local run of + /// `added` is cheaper than `task` and leaves a pointwise smaller stack. + pub proof fn machine_lemma_step( + g0: model::Graph, g1: model::Graph, pending: Seq, task: ActionShape, + added: Seq, v0: Seq, v1: Seq, + ) + requires model::graph_extends(g0, g1), transition_tasks_valid(g0, pending), + machine_run(g1, added, value_depths(g1, v1)).0 < action_cost(g0, task, value_depths(g0, v0)), + le_pointwise(machine_run(g1, added, value_depths(g1, v1)).1, action_next(g0, task, value_depths(g0, v0))), + ensures machine_cost(g1, pending + added, v1) < machine_cost(g0, pending.push(task), v0), + { + let s0 = value_depths(g0, v0); + let r = machine_run(g1, added, value_depths(g1, v1)); + let next = action_next(g0, task, s0); + assert(pending.push(task).drop_last() =~= pending); + machine_lemma_run_split(g1, pending, added, value_depths(g1, v1)); + machine_lemma_run_mono(g1, pending, r.1, next); + machine_lemma_run_extends(g0, g1, pending, next); + } + + /// A step that only pushes one value bounded by the task's abstract result. + pub proof fn machine_lemma_push( + g0: model::Graph, g1: model::Graph, pending: Seq, task: ActionShape, + v0: Seq, out: TransitionId, bound: nat, + ) + requires model::graph_extends(g0, g1), transition_tasks_valid(g0, pending), transition_ids_valid(g0, v0), + action_cost(g0, task, value_depths(g0, v0)) >= 1, + action_next(g0, task, value_depths(g0, v0)) == value_depths(g0, v0).push(bound), + tdepth(g1, out@) <= bound, + ensures machine_cost(g1, pending, v0.push(out)) < machine_cost(g0, pending.push(task), v0), + { + value_depths_lemma_extends(g0, g1, v0); + assert(value_depths(g1, v0.push(out)) =~= value_depths(g1, v0).push(tdepth(g1, out@))); + le_pointwise_push(value_depths(g0, v0), value_depths(g0, v0), tdepth(g1, out@), bound); + assert(pending + Seq::::empty() =~= pending); + machine_lemma_step(g0, g1, pending, task, Seq::empty(), v0, v0.push(out)); + } + + // ----- child task lists ----- + + pub open spec fn child_shapes(cs: Seq, action: ChildShape) -> Seq { + cs.reverse().map(|i: int, child: nat| transition_child_shape(action, child)) + } + + pub open spec fn child_cost_fn(g: model::Graph, action: ChildShape) -> spec_fn(nat) -> nat { + match action { + ChildShape::Clean(_) => clean_cost_fn(), + ChildShape::Not => not_cost_fn(), + ChildShape::Append(_) => append_cost_fn(), + ChildShape::PairLeft(other) => pair_cost_left_fn(tdepth(g, other)), + ChildShape::PairRight(other) => pair_cost_right_fn(tdepth(g, other)), + } + } + + pub open spec fn child_bound(g: model::Graph, action: ChildShape, d: nat) -> nat { + match action { + ChildShape::Clean(_) => d, + ChildShape::Not => n4(d), + ChildShape::Append(_) => 2 * d + 1, + ChildShape::PairLeft(other) => pair_bound(d, tdepth(g, other)), + ChildShape::PairRight(other) => pair_bound(tdepth(g, other), d), + } + } + + pub open spec fn child_bounds(g: model::Graph, action: ChildShape, ds: Seq) -> Seq { + Seq::new(ds.len(), |i: int| child_bound(g, action, ds[i])) + } + + pub proof fn lemma_sum_map_front(f: spec_fn(nat) -> nat, ds: Seq) + requires ds.len() > 0, + ensures sum_map(f, ds) == f(ds[0]) + sum_map(f, ds.drop_first()), + decreases ds.len(), + { + if ds.len() == 1 { + assert(ds.drop_last().len() == 0); + assert(ds.drop_first().len() == 0); + assert(sum_map(f, ds.drop_last()) == 0); + assert(sum_map(f, ds.drop_first()) == 0); + assert(ds.last() == ds[0]); + } else { + let init = ds.drop_last(); + lemma_sum_map_front(f, init); + assert(init[0] == ds[0]); + assert(init.drop_first() =~= ds.drop_first().drop_last()); + assert(ds.drop_first().last() == ds.last()); + assert(sum_map(f, ds.drop_first()) + == sum_map(f, ds.drop_first().drop_last()) + f(ds.drop_first().last())); + } + } + + pub proof fn machine_lemma_children_run(g: model::Graph, cs: Seq, action: ChildShape, s: Seq) + ensures machine_run(g, child_shapes(cs, action), s) + == (sum_map(child_cost_fn(g, action), tdepths(g, cs)), s + child_bounds(g, action, tdepths(g, cs))), + decreases cs.len(), + { + let shapes = child_shapes(cs, action); + let ds = tdepths(g, cs); + let f = child_cost_fn(g, action); + if cs.len() == 0 { + assert(s + child_bounds(g, action, ds) =~= s); + } else { + let rest = cs.drop_first(); + assert(shapes.last() == transition_child_shape(action, cs[0])); + assert(shapes.drop_last() =~= child_shapes(rest, action)); + let b0 = child_bound(g, action, ds[0]); + assert(action_cost(g, shapes.last(), s) == f(ds[0])); + assert(action_next(g, shapes.last(), s) == s.push(b0)); + machine_lemma_children_run(g, rest, action, s.push(b0)); + assert(tdepths(g, rest) =~= ds.drop_first()); + lemma_sum_map_front(f, ds); + assert(s.push(b0) + child_bounds(g, action, tdepths(g, rest)) =~= s + child_bounds(g, action, ds)); + } + } + + /// Running `[Union(n)/Intersect(n)] + children(action)` over `s`. + pub proof fn machine_lemma_set_run(g: model::Graph, id: nat, action: ChildShape, intersect: bool, s: Seq) + requires model::graph_wf(g), id < g.transitions.len(), + ensures ({ + let cs = transition_children(g, id); + let ds = tdepths(g, cs); + let bs = child_bounds(g, action, ds); + let marker = if intersect { ActionShape::Intersect(cs.len()) } else { ActionShape::Union(cs.len()) }; + let r = machine_run(g, seq![marker] + transition_child_actions(g, id, action), s); + &&& r.0 == sum_map(child_cost_fn(g, action), ds) + + (if intersect { 2 + intersect_bound(bs) + pair_cost_total(intersect_bound(bs)) } else { 1 }) + &&& r.1 == s.push(if intersect { intersect_bound(bs) } else { union_bound(bs) }) + }), + { + let cs = transition_children(g, id); + let ds = tdepths(g, cs); + let bs = child_bounds(g, action, ds); + let marker = if intersect { ActionShape::Intersect(cs.len()) } else { ActionShape::Union(cs.len()) }; + assert(transition_child_actions(g, id, action) =~= child_shapes(cs, action)); + machine_lemma_children_run(g, cs, action, s); + machine_lemma_run_split(g, seq![marker], child_shapes(cs, action), s); + let t = s + bs; + assert(abs_top(t, cs.len()) =~= bs); + assert(abs_pop(t, cs.len()) =~= s); + assert(seq![marker].drop_last() =~= Seq::::empty()); + assert(seq![marker].last() == marker); + let next = action_next(g, marker, t); + assert(machine_run(g, Seq::::empty(), next) == (0nat, next)); + assert(machine_run(g, seq![marker], t) == (action_cost(g, marker, t), next)); + } + + pub proof fn graph_lemma_extends_refl(g: model::Graph) + ensures model::graph_extends(g, g), + { + assert(g.tests.subrange(0, g.tests.len() as int) =~= g.tests); + assert(g.regexes.subrange(0, g.regexes.len() as int) =~= g.regexes); + assert(g.transitions.subrange(0, g.transitions.len() as int) =~= g.transitions); + } + + pub proof fn machine_lemma_run1(g: model::Graph, t: ActionShape, s: Seq) + ensures machine_run(g, seq![t], s) == (action_cost(g, t, s), action_next(g, t, s)), + { + assert(seq![t].drop_last() =~= Seq::::empty()); + assert(seq![t].last() == t); + assert(machine_run(g, Seq::::empty(), action_next(g, t, s)) == (0nat, action_next(g, t, s))); + } + + pub proof fn machine_lemma_run2(g: model::Graph, t1: ActionShape, t2: ActionShape, s: Seq) + ensures machine_run(g, seq![t1, t2], s) == (action_cost(g, t2, s) + action_cost(g, t1, action_next(g, t2, s)), + action_next(g, t1, action_next(g, t2, s))), + { + assert(seq![t1, t2].drop_last() =~= seq![t1]); + assert(seq![t1, t2].last() == t2); + machine_lemma_run1(g, t1, action_next(g, t2, s)); + } + + pub proof fn machine_lemma_run3(g: model::Graph, t1: ActionShape, t2: ActionShape, t3: ActionShape, s: Seq) + ensures ({ + let s1 = action_next(g, t3, s); + let s2 = action_next(g, t2, s1); + machine_run(g, seq![t1, t2, t3], s) + == (action_cost(g, t3, s) + action_cost(g, t2, s1) + action_cost(g, t1, s2), action_next(g, t1, s2)) + }), + { + assert(seq![t1, t2, t3].drop_last() =~= seq![t1, t2]); + assert(seq![t1, t2, t3].last() == t3); + machine_lemma_run2(g, t1, t2, action_next(g, t3, s)); + } + + pub open spec fn value_bound(g: model::Graph, task: ActionShape) -> nat { + match task { + ActionShape::Clean(id, _) => tdepth(g, id), + ActionShape::Not(id) => n4(tdepth(g, id)), + ActionShape::Append(id, _) => 2 * tdepth(g, id) + 1, + ActionShape::Pair(a, b) => pair_bound(tdepth(g, a), tdepth(g, b)), + _ => 0, + } + } + + pub open spec fn value_task(task: ActionShape) -> bool { + task is Clean || task is Not || task is Append || task is Pair + } + + /// A value-producing task (`Clean`/`Not`/`Append`/`Pair`) that directly pushes `out`. + pub proof fn machine_value_result( + g0: model::Graph, g1: model::Graph, pending: Seq, task: ActionShape, + v0: Seq, out: TransitionId, + ) + requires model::graph_extends(g0, g1), transition_tasks_valid(g0, pending), transition_ids_valid(g0, v0), + value_task(task), + tdepth(g1, out@) <= value_bound(g0, task) + || (out@ < g1.transitions.len() && g1.transitions[out@ as int] is Const), + ensures machine_cost(g1, pending, v0.push(out)) < machine_cost(g0, pending.push(task), v0), + { + match task { + ActionShape::Clean(id, _) => { lemma_costs_pos(tdepth(g0, id)); tdepth_lemma_pos(g0, id); }, + ActionShape::Not(id) => { lemma_costs_pos(tdepth(g0, id)); lemma_n4_pos(tdepth(g0, id)); }, + ActionShape::Append(id, _) => { lemma_costs_pos(tdepth(g0, id)); }, + ActionShape::Pair(a, b) => { + lemma_pair_cost_mono(tdepth(g0, a), tdepth(g0, b), tdepth(g0, a), tdepth(g0, b)); + tdepth_lemma_pos(g0, a); + assert(tdepth(g0, a) * tdepth(g0, b) >= 0) by (nonlinear_arith); + }, + _ => {}, + } + if out@ < g1.transitions.len() && g1.transitions[out@ as int] is Const { tdepth_lemma_const(g1, out@); } + machine_lemma_push(g0, g1, pending, task, v0, out, value_bound(g0, task)); + } + + // ----- Clean ----- + + pub proof fn machine_clean_if( + g0: model::Graph, g1: model::Graph, pending: Seq, id: TransitionId, path: TestId, + test: TestId, a: TransitionId, b: TransitionId, yes: TestId, no: TestId, v0: Seq, + ) + requires model::graph_wf(g0), model::graph_extends(g0, g1), transition_tasks_valid(g0, pending), + transition_ids_valid(g0, v0), id@ < g0.transitions.len(), + g0.transitions[id@ as int] == model::TransitionNode::If(test@, a@, b@), + ensures machine_cost(g1, transition_clean_if_tasks(g1, test, a, b, yes, no, pending), v0) + < machine_cost(g0, pending.push(ActionShape::Clean(id@, path@)), v0), + { + // Keep irrelevant recursive costs opaque while proving this local scheduling bound. + hide(clean_cost); + hide(not_cost); + hide(append_cost); + hide(pair_cost); + hide(pair_cost_upto); + hide(tdepth); + model::lemma_graph_transition_wf(g0, id@); + tdepth_lemma_unfold(g0, id@); + tdepth_lemma_extends(g0, g1, a@); + tdepth_lemma_extends(g0, g1, b@); + tdepth_lemma_pos(g0, a@); + tdepth_lemma_pos(g0, b@); + let da = tdepth(g0, a@); + let db = tdepth(g0, b@); + let d = tdepth(g0, id@); + let m = (d - 1) as nat; + assert(d == if_bound(da, db)); + assert(d >= 2); + assert(da <= m && db <= m); + let s0 = value_depths(g0, v0); + value_depths_lemma_extends(g0, g1, v0); + assert(value_depths(g1, v0) == s0); + let task = ActionShape::Clean(id@, path@); + assert(action_cost(g0, task, s0) == clean_cost(d)); + assert(action_next(g0, task, s0) == s0.push(d)); + assert(le_pointwise(s0, s0)); + lemma_clean_cost_mono(da, m); + lemma_clean_cost_mono(db, m); + assert(clean_cost(d) >= 4 + d + 3 * clean_cost(m)) by { + reveal_with_fuel(clean_cost, 1); + } + assert(1 + clean_cost(da) + clean_cost(db) < clean_cost(d)); + let tasks = transition_clean_if_tasks(g1, test, a, b, yes, no, pending); + if yes@ == g1.constants.test_false { + let added = seq![ActionShape::Clean(b@, no@)]; + assert(tasks =~= pending + added); + machine_lemma_run1(g1, added[0], s0); + assert(machine_run(g1, added, s0) == (clean_cost(db), s0.push(db))); + le_pointwise_push(s0, s0, db, d); + machine_lemma_step(g0, g1, pending, task, added, v0, v0); + } else if no@ == g1.constants.test_false { + let added = seq![ActionShape::Clean(a@, yes@)]; + assert(tasks =~= pending + added); + machine_lemma_run1(g1, added[0], s0); + assert(machine_run(g1, added, s0) == (clean_cost(da), s0.push(da))); + le_pointwise_push(s0, s0, da, d); + machine_lemma_step(g0, g1, pending, task, added, v0, v0); + } else { + let added = seq![ActionShape::If(test@), ActionShape::Clean(b@, no@), ActionShape::Clean(a@, yes@)]; + assert(tasks =~= pending + added); + machine_lemma_run3(g1, added[0], added[1], added[2], s0); + let s2 = s0.push(da).push(db); + assert(abs_pop(s2, 2) =~= s0); + assert(abs_peek(s2, 1) == da); + assert(abs_peek(s2, 0) == db); + assert(machine_run(g1, added, s0) == (clean_cost(da) + clean_cost(db) + 1, s0.push(d))); + le_pointwise_push(s0, s0, d, d); + machine_lemma_step(g0, g1, pending, task, added, v0, v0); + } + } + + pub proof fn machine_clean_children( + g: model::Graph, pending: Seq, id: TransitionId, path: TestId, intersect: bool, v0: Seq, + ) + requires model::graph_wf(g), transition_tasks_valid(g, pending), transition_ids_valid(g, v0), + id@ < g.transitions.len(), + match g.transitions[id@ as int] { + model::TransitionNode::Union(_) => !intersect, + model::TransitionNode::Intersect(_) => intersect, + _ => false, + }, + ensures machine_cost(g, transition_clean_child_tasks(g, id, path, intersect, pending), v0) + < machine_cost(g, pending.push(ActionShape::Clean(id@, path@)), v0), + { + transition_lemma_children(g, id@); + tdepth_lemma_unfold(g, id@); + graph_lemma_extends_refl(g); + let cs = transition_children(g, id@); + let ds = tdepths(g, cs); + tdepths_lemma_pos(g, cs); + let action = ChildShape::Clean(path@); + let marker = if intersect { ActionShape::Intersect(cs.len()) } else { ActionShape::Union(cs.len()) }; + let added = seq![marker] + transition_child_actions(g, id@, action); + assert(transition_clean_child_tasks(g, id, path, intersect, pending) =~= pending + added); + let s0 = value_depths(g, v0); + machine_lemma_set_run(g, id@, action, intersect, s0); + assert(child_bounds(g, action, ds) =~= ds); + lemma_clean_sum(ds); + lemma_bounds_pos(ds); + let d = tdepth(g, id@); + le_pointwise_push(s0, s0, d, d); + machine_lemma_step(g, g, pending, ActionShape::Clean(id@, path@), added, v0, v0); + } + + pub proof fn machine_clean_not( + g0: model::Graph, g1: model::Graph, pending: Seq, id: TransitionId, path: TestId, + inner: TransitionId, v0: Seq, + ) + requires model::graph_wf(g0), model::graph_extends(g0, g1), transition_tasks_valid(g0, pending), + transition_ids_valid(g0, v0), id@ < g0.transitions.len(), + g0.transitions[id@ as int] == model::TransitionNode::Not(inner@), + ensures machine_cost(g1, pending.push(ActionShape::NotResult).push(ActionShape::Clean(inner@, path@)), v0) + < machine_cost(g0, pending.push(ActionShape::Clean(id@, path@)), v0), + { + model::lemma_graph_transition_wf(g0, id@); + tdepth_lemma_unfold(g0, id@); + tdepth_lemma_extends(g0, g1, inner@); + tdepth_lemma_pos(g0, inner@); + let dc = tdepth(g0, inner@); + let d = tdepth(g0, id@); + lemma_n4_pos(dc); + lemma_n4_mono(1, dc); + assert(n4(1) == 4 * n4(0)); + lemma_log4_n4(dc); + lemma_clean_cost_mono(dc, (d - 1) as nat); + let s0 = value_depths(g0, v0); + value_depths_lemma_extends(g0, g1, v0); + let added = seq![ActionShape::NotResult, ActionShape::Clean(inner@, path@)]; + assert(pending.push(ActionShape::NotResult).push(ActionShape::Clean(inner@, path@)) =~= pending + added); + machine_lemma_run2(g1, added[0], added[1], s0); + assert(abs_peek(s0.push(dc), 0) == dc); + assert(abs_pop(s0.push(dc), 1) =~= s0); + le_pointwise_push(s0, s0, d, d); + machine_lemma_step(g0, g1, pending, ActionShape::Clean(id@, path@), added, v0, v0); + } + + pub proof fn machine_clean_append( + g0: model::Graph, g1: model::Graph, pending: Seq, id: TransitionId, path: TestId, + inner: TransitionId, r: RegexId, v0: Seq, + ) + requires model::graph_wf(g0), model::graph_extends(g0, g1), transition_tasks_valid(g0, pending), + transition_ids_valid(g0, v0), id@ < g0.transitions.len(), + match g0.transitions[id@ as int] { model::TransitionNode::Append(c, _) => c == inner@, _ => false }, + ensures machine_cost(g1, pending.push(ActionShape::AppendResult(r@)).push(ActionShape::Clean(inner@, path@)), v0) + < machine_cost(g0, pending.push(ActionShape::Clean(id@, path@)), v0), + { + model::lemma_graph_transition_wf(g0, id@); + tdepth_lemma_unfold(g0, id@); + tdepth_lemma_extends(g0, g1, inner@); + tdepth_lemma_pos(g0, inner@); + let dc = tdepth(g0, inner@); + let d = tdepth(g0, id@); + assert(((d - 1) as nat) / 2 == dc); + lemma_clean_cost_mono(dc, (d - 1) as nat); + let s0 = value_depths(g0, v0); + value_depths_lemma_extends(g0, g1, v0); + let added = seq![ActionShape::AppendResult(r@), ActionShape::Clean(inner@, path@)]; + assert(pending.push(ActionShape::AppendResult(r@)).push(ActionShape::Clean(inner@, path@)) =~= pending + added); + machine_lemma_run2(g1, added[0], added[1], s0); + assert(abs_peek(s0.push(dc), 0) == dc); + assert(abs_pop(s0.push(dc), 1) =~= s0); + le_pointwise_push(s0, s0, d, d); + machine_lemma_step(g0, g1, pending, ActionShape::Clean(id@, path@), added, v0, v0); + } + + // ----- Not / Append ----- + + pub proof fn machine_not_double( + g0: model::Graph, g1: model::Graph, pending: Seq, id: TransitionId, inner: TransitionId, + v0: Seq, + ) + requires model::graph_wf(g0), model::graph_extends(g0, g1), transition_tasks_valid(g0, pending), + transition_ids_valid(g0, v0), id@ < g0.transitions.len(), + g0.transitions[id@ as int] == model::TransitionNode::Not(inner@), + ensures machine_cost(g1, pending, v0.push(inner)) < machine_cost(g0, pending.push(ActionShape::Not(id@)), v0), + { + model::lemma_graph_transition_wf(g0, id@); + tdepth_lemma_unfold(g0, id@); + tdepth_lemma_extends(g0, g1, inner@); + lemma_n4_pos(tdepth(g0, inner@)); + lemma_n4_pos(tdepth(g0, id@)); + machine_value_result(g0, g1, pending, ActionShape::Not(id@), v0, inner); + } + + /// `out` is a freshly interned `Not(id)` / `Append(id, _)` node. + pub proof fn machine_wrap_interned( + g0: model::Graph, g1: model::Graph, pending: Seq, task: ActionShape, + v0: Seq, out: TransitionId, + ) + requires model::graph_wf(g1), model::graph_extends(g0, g1), transition_tasks_valid(g0, pending), + transition_ids_valid(g0, v0), transition_action_valid(g0, task), out@ < g1.transitions.len(), + match task { + ActionShape::Not(id) => g1.transitions[out@ as int] == model::TransitionNode::Not(id), + ActionShape::Append(id, _) => match g1.transitions[out@ as int] { + model::TransitionNode::Append(c, _) => c == id, + _ => false, + }, + _ => false, + }, + ensures machine_cost(g1, pending, v0.push(out)) < machine_cost(g0, pending.push(task), v0), + { + tdepth_lemma_unfold(g1, out@); + match task { + ActionShape::Not(id) => { tdepth_lemma_extends(g0, g1, id); }, + ActionShape::Append(id, _) => { tdepth_lemma_extends(g0, g1, id); }, + _ => {}, + } + machine_value_result(g0, g1, pending, task, v0, out); + } + + pub proof fn machine_not_flip( + g0: model::Graph, g1: model::Graph, pending: Seq, id: TransitionId, test: TestId, + a: TransitionId, b: TransitionId, out: TransitionId, path: TestId, v0: Seq, + ) + requires model::graph_wf(g0), model::graph_extends(g0, g1), transition_tasks_valid(g0, pending), + transition_ids_valid(g0, v0), id@ < g0.transitions.len(), + g0.transitions[id@ as int] == model::TransitionNode::If(test@, a@, b@), + a@ == g0.constants.transition_all, b@ == g0.constants.transition_empty, + out@ < g1.transitions.len(), tdepth(g1, out@) <= 2, + ensures machine_cost(g1, pending.push(ActionShape::Clean(out@, path@)), v0) + < machine_cost(g0, pending.push(ActionShape::Not(id@)), v0), + { + tdepth_lemma_unfold(g0, id@); + tdepth_lemma_constants(g0); + let d = tdepth(g0, id@); + assert(d == 2); + lemma_n4_pos(2); + lemma_clean_cost_mono(tdepth(g1, out@), 2); + let s0 = value_depths(g0, v0); + value_depths_lemma_extends(g0, g1, v0); + let added = seq![ActionShape::Clean(out@, path@)]; + assert(pending.push(ActionShape::Clean(out@, path@)) =~= pending + added); + machine_lemma_run1(g1, added[0], s0); + le_pointwise_push(s0, s0, tdepth(g1, out@), n4(d)); + machine_lemma_step(g0, g1, pending, ActionShape::Not(id@), added, v0, v0); + } + + pub open spec fn unary_task(id: TransitionId, suffix: Option) -> ActionShape { + match suffix { Some(r) => ActionShape::Append(id@, r@), None => ActionShape::Not(id@) } + } + + pub proof fn machine_unary_if( + g0: model::Graph, g1: model::Graph, pending: Seq, id: TransitionId, test: TestId, + a: TransitionId, b: TransitionId, suffix: Option, v0: Seq, + ) + requires model::graph_wf(g0), model::graph_extends(g0, g1), transition_tasks_valid(g0, pending), + transition_ids_valid(g0, v0), id@ < g0.transitions.len(), + g0.transitions[id@ as int] == model::TransitionNode::If(test@, a@, b@), + ensures machine_cost(g1, machine_unary_if_tasks(g1, test, a, b, suffix, pending), v0) + < machine_cost(g0, pending.push(unary_task(id, suffix)), v0), + { + model::lemma_graph_transition_wf(g0, id@); + tdepth_lemma_unfold(g0, id@); + tdepth_lemma_extends(g0, g1, a@); + tdepth_lemma_extends(g0, g1, b@); + tdepth_lemma_pos(g0, a@); + tdepth_lemma_pos(g0, b@); + let da = tdepth(g0, a@); + let db = tdepth(g0, b@); + let d = tdepth(g0, id@); + let m = (d - 1) as nat; + let s0 = value_depths(g0, v0); + value_depths_lemma_extends(g0, g1, v0); + let task = unary_task(id, suffix); + let added = seq![ + ActionShape::CleanIf(test@, g1.constants.test_true), + match suffix { Some(r) => ActionShape::Append(b@, r@), None => ActionShape::Not(b@) }, + match suffix { Some(r) => ActionShape::Append(a@, r@), None => ActionShape::Not(a@) }]; + assert(machine_unary_if_tasks(g1, test, a, b, suffix, pending) =~= pending + added); + machine_lemma_run3(g1, added[0], added[1], added[2], s0); + match suffix { + Some(r) => { + let s2 = s0.push(2 * da + 1).push(2 * db + 1); + assert(abs_pop(s2, 2) =~= s0); + assert(abs_peek(s2, 1) == 2 * da + 1); + assert(abs_peek(s2, 0) == 2 * db + 1); + let ib = if_bound(2 * da + 1, 2 * db + 1); + assert(ib <= 2 * d); + lemma_append_cost_mono(da, m); + lemma_append_cost_mono(db, m); + lemma_clean_cost_mono(ib, 2 * d); + le_pointwise_push(s0, s0, ib, 2 * d + 1); + }, + None => { + let s2 = s0.push(n4(da)).push(n4(db)); + assert(abs_pop(s2, 2) =~= s0); + assert(abs_peek(s2, 1) == n4(da)); + assert(abs_peek(s2, 0) == n4(db)); + let ib = if_bound(n4(da), n4(db)); + lemma_n4_mono(da, m); + lemma_n4_mono(db, m); + lemma_n4_pos(m); + assert(n4(d) == 4 * n4(m)); + lemma_not_cost_mono(da, m); + lemma_not_cost_mono(db, m); + lemma_clean_cost_mono(ib, 1 + n4(m)); + le_pointwise_push(s0, s0, ib, n4(d)); + }, + } + machine_lemma_step(g0, g1, pending, task, added, v0, v0); + } + + pub proof fn machine_unary_children( + g: model::Graph, pending: Seq, id: TransitionId, suffix: Option, intersect: bool, + v0: Seq, + ) + requires model::graph_wf(g), transition_tasks_valid(g, pending), transition_ids_valid(g, v0), + id@ < g.transitions.len(), + match g.transitions[id@ as int] { + model::TransitionNode::Union(_) => intersect == (suffix is None), + model::TransitionNode::Intersect(_) => !intersect && suffix is None, + _ => false, + }, + ensures machine_cost(g, machine_unary_child_tasks(g, id, suffix, intersect, pending), v0) + < machine_cost(g, pending.push(unary_task(id, suffix)), v0), + { + transition_lemma_children(g, id@); + tdepth_lemma_unfold(g, id@); + graph_lemma_extends_refl(g); + let cs = transition_children(g, id@); + let ds = tdepths(g, cs); + tdepths_lemma_pos(g, cs); + lemma_bounds_pos(ds); + let d = tdepth(g, id@); + let action = match suffix { Some(r) => ChildShape::Append(r@), None => ChildShape::Not }; + let marker = if intersect { ActionShape::Intersect(cs.len()) } else { ActionShape::Union(cs.len()) }; + let added = seq![marker] + transition_child_actions(g, id@, action); + assert(machine_unary_child_tasks(g, id, suffix, intersect, pending) =~= pending + added); + let s0 = value_depths(g, v0); + machine_lemma_set_run(g, id@, action, intersect, s0); + let bs = child_bounds(g, action, ds); + match suffix { + Some(r) => { + assert(bs =~= appends(ds)); + lemma_append_sum(ds); + lemma_append_union(ds); + le_pointwise_push(s0, s0, union_bound(bs), 2 * d + 1); + }, + None => { + assert(bs =~= n4s(ds)); + lemma_not_sum(ds); + if intersect { + lemma_not_union(ds); + lemma_pair_cost_total_mono(intersect_bound(bs), (n4(d) - 1) as nat); + le_pointwise_push(s0, s0, intersect_bound(bs), n4(d)); + } else { + lemma_not_intersect(ds); + le_pointwise_push(s0, s0, union_bound(bs), n4(d)); + } + }, + } + machine_lemma_step(g, g, pending, unary_task(id, suffix), added, v0, v0); + } + + pub proof fn machine_append_nested( + g0: model::Graph, g1: model::Graph, pending: Seq, id: TransitionId, r: RegexId, + inner: TransitionId, combined: RegexId, v0: Seq, + ) + requires model::graph_wf(g0), model::graph_extends(g0, g1), transition_tasks_valid(g0, pending), + transition_ids_valid(g0, v0), id@ < g0.transitions.len(), + match g0.transitions[id@ as int] { model::TransitionNode::Append(c, _) => c == inner@, _ => false }, + ensures machine_cost(g1, pending.push(ActionShape::Append(inner@, combined@)), v0) + < machine_cost(g0, pending.push(ActionShape::Append(id@, r@)), v0), + { + model::lemma_graph_transition_wf(g0, id@); + tdepth_lemma_unfold(g0, id@); + tdepth_lemma_extends(g0, g1, inner@); + tdepth_lemma_pos(g0, inner@); + let dc = tdepth(g0, inner@); + let d = tdepth(g0, id@); + lemma_append_cost_mono(dc, (d - 1) as nat); + let s0 = value_depths(g0, v0); + value_depths_lemma_extends(g0, g1, v0); + let added = seq![ActionShape::Append(inner@, combined@)]; + assert(pending.push(added[0]) =~= pending + added); + machine_lemma_run1(g1, added[0], s0); + le_pointwise_push(s0, s0, 2 * dc + 1, 2 * d + 1); + machine_lemma_step(g0, g1, pending, ActionShape::Append(id@, r@), added, v0, v0); + } + + // ----- Pair ----- + + pub proof fn machine_pair_union( + g: model::Graph, pending: Seq, a: TransitionId, b: TransitionId, left: bool, v0: Seq, + ) + requires model::graph_wf(g), transition_tasks_valid(g, pending), transition_ids_valid(g, v0), + a@ < g.transitions.len(), b@ < g.transitions.len(), + g.transitions[if left { a@ as int } else { b@ as int }] is Union, + ensures ({ + let id = if left { a@ } else { b@ }; + let action = if left { ChildShape::PairLeft(b@) } else { ChildShape::PairRight(a@) }; + machine_cost(g, pending.push(ActionShape::Union(transition_children(g, id).len())) + + transition_child_actions(g, id, action), v0) + < machine_cost(g, pending.push(ActionShape::Pair(a@, b@)), v0) + }), + { + let id = if left { a@ } else { b@ }; + let action = if left { ChildShape::PairLeft(b@) } else { ChildShape::PairRight(a@) }; + transition_lemma_children(g, id); + tdepth_lemma_unfold(g, id); + graph_lemma_extends_refl(g); + let cs = transition_children(g, id); + let ds = tdepths(g, cs); + tdepths_lemma_pos(g, cs); + lemma_bounds_pos(ds); + tdepth_lemma_pos(g, a@); + tdepth_lemma_pos(g, b@); + let x = tdepth(g, a@); + let y = tdepth(g, b@); + let marker = ActionShape::Union(cs.len()); + let added = seq![marker] + transition_child_actions(g, id, action); + assert(pending.push(marker) + transition_child_actions(g, id, action) =~= pending + added); + let s0 = value_depths(g, v0); + machine_lemma_set_run(g, id, action, false, s0); + let bs = child_bounds(g, action, ds); + if left { + assert(bs =~= pairs_left(ds, y)); + lemma_pair_left_sum(ds, y); + lemma_pair_union_left(ds, y); + } else { + assert(bs =~= pairs_right(x, ds)); + lemma_pair_right_sum(x, ds); + lemma_pair_union_right(x, ds); + } + le_pointwise_push(s0, s0, union_bound(bs), pair_bound(x, y)); + machine_lemma_step(g, g, pending, ActionShape::Pair(a@, b@), added, v0, v0); + } + + pub proof fn lemma_pair_if_bound(x: nat, y: nat, p: nat, q: nat) + requires x >= 1, p <= pair_bound((x - 1) as nat, y), q <= pair_bound((x - 1) as nat, y), + ensures if_bound(p, q) <= x * (y + 1), x * (y + 1) <= pair_bound(x, y), + { + assert(pair_bound((x - 1) as nat, y) + 1 == x * (y + 1)) by (nonlinear_arith) requires x >= 1; + assert(x * (y + 1) <= pair_bound(x, y)) by (nonlinear_arith); + } + + pub proof fn machine_pair_split( + g0: model::Graph, g1: model::Graph, pending: Seq, a: TransitionId, b: TransitionId, + test: TestId, t: TransitionId, e: TransitionId, path: TestId, left: bool, v0: Seq, + ) + requires model::graph_wf(g0), model::graph_extends(g0, g1), transition_tasks_valid(g0, pending), + transition_ids_valid(g0, v0), a@ < g0.transitions.len(), b@ < g0.transitions.len(), + g0.transitions[if left { a@ as int } else { b@ as int }] == model::TransitionNode::If(test@, t@, e@), + ensures machine_cost(g1, if left { + pending.push(ActionShape::CleanIf(test@, path@)).push(ActionShape::Pair(e@, b@)).push(ActionShape::Pair(t@, b@)) + } else { + pending.push(ActionShape::CleanIf(test@, path@)).push(ActionShape::Pair(a@, e@)).push(ActionShape::Pair(a@, t@)) + }, v0) < machine_cost(g0, pending.push(ActionShape::Pair(a@, b@)), v0), + { + if left { + machine_pair_split_left(g0, g1, pending, a, b, test, t, e, path, v0); + } else { + machine_pair_split_right(g0, g1, pending, a, b, test, t, e, path, v0); + } + } + + #[verifier::spinoff_prover] + pub proof fn machine_pair_split_left( + g0: model::Graph, g1: model::Graph, pending: Seq, a: TransitionId, b: TransitionId, + test: TestId, t: TransitionId, e: TransitionId, path: TestId, v0: Seq, + ) + requires model::graph_wf(g0), model::graph_extends(g0, g1), transition_tasks_valid(g0, pending), + transition_ids_valid(g0, v0), a@ < g0.transitions.len(), b@ < g0.transitions.len(), + g0.transitions[a@ as int] == model::TransitionNode::If(test@, t@, e@), + ensures machine_cost(g1, pending.push(ActionShape::CleanIf(test@, path@)).push(ActionShape::Pair(e@, b@)) + .push(ActionShape::Pair(t@, b@)), v0) < machine_cost(g0, pending.push(ActionShape::Pair(a@, b@)), v0), + { + model::lemma_graph_transition_wf(g0, a@); + tdepth_lemma_unfold(g0, a@); + tdepth_lemma_extends(g0, g1, b@); + tdepth_lemma_extends(g0, g1, t@); + tdepth_lemma_extends(g0, g1, e@); + tdepth_lemma_pos(g0, b@); + tdepth_lemma_pos(g0, t@); + tdepth_lemma_pos(g0, e@); + let x = tdepth(g0, a@); + let y = tdepth(g0, b@); + let dt = tdepth(g0, t@); + let de = tdepth(g0, e@); + let s0 = value_depths(g0, v0); + value_depths_lemma_extends(g0, g1, v0); + let added = seq![ActionShape::CleanIf(test@, path@), ActionShape::Pair(e@, b@), ActionShape::Pair(t@, b@)]; + assert(pending.push(added[0]).push(added[1]).push(added[2]) =~= pending + added); + machine_lemma_run3(g1, added[0], added[1], added[2], s0); + let p = pair_bound(dt, y); + let q = pair_bound(de, y); + let s2 = s0.push(p).push(q); + assert(abs_pop(s2, 2) =~= s0); + assert(abs_peek(s2, 1) == p); + assert(abs_peek(s2, 0) == q); + lemma_pair_bound_mono(dt, y, (x - 1) as nat, y); + lemma_pair_bound_mono(de, y, (x - 1) as nat, y); + lemma_pair_if_bound(x, y, p, q); + lemma_pair_cost_mono(dt, y, (x - 1) as nat, y); + lemma_pair_cost_mono(de, y, (x - 1) as nat, y); + lemma_clean_cost_mono(if_bound(p, q), x * (y + 1)); + lemma_pair_split_cost(x, y, pair_cost(dt, y) + pair_cost(de, y) + 1 + clean_cost(if_bound(p, q))); + le_pointwise_push(s0, s0, if_bound(p, q), pair_bound(x, y)); + machine_lemma_step(g0, g1, pending, ActionShape::Pair(a@, b@), added, v0, v0); + } + + #[verifier::spinoff_prover] + pub proof fn machine_pair_split_right( + g0: model::Graph, g1: model::Graph, pending: Seq, a: TransitionId, b: TransitionId, + test: TestId, t: TransitionId, e: TransitionId, path: TestId, v0: Seq, + ) + requires model::graph_wf(g0), model::graph_extends(g0, g1), transition_tasks_valid(g0, pending), + transition_ids_valid(g0, v0), a@ < g0.transitions.len(), b@ < g0.transitions.len(), + g0.transitions[b@ as int] == model::TransitionNode::If(test@, t@, e@), + ensures machine_cost(g1, pending.push(ActionShape::CleanIf(test@, path@)).push(ActionShape::Pair(a@, e@)) + .push(ActionShape::Pair(a@, t@)), v0) < machine_cost(g0, pending.push(ActionShape::Pair(a@, b@)), v0), + { + model::lemma_graph_transition_wf(g0, b@); + tdepth_lemma_unfold(g0, b@); + tdepth_lemma_extends(g0, g1, a@); + tdepth_lemma_extends(g0, g1, t@); + tdepth_lemma_extends(g0, g1, e@); + tdepth_lemma_pos(g0, a@); + tdepth_lemma_pos(g0, t@); + tdepth_lemma_pos(g0, e@); + let x = tdepth(g0, a@); + let y = tdepth(g0, b@); + let dt = tdepth(g0, t@); + let de = tdepth(g0, e@); + let s0 = value_depths(g0, v0); + value_depths_lemma_extends(g0, g1, v0); + let added = seq![ActionShape::CleanIf(test@, path@), ActionShape::Pair(a@, e@), ActionShape::Pair(a@, t@)]; + assert(pending.push(added[0]).push(added[1]).push(added[2]) =~= pending + added); + machine_lemma_run3(g1, added[0], added[1], added[2], s0); + let p = pair_bound(x, dt); + let q = pair_bound(x, de); + let s2 = s0.push(p).push(q); + assert(abs_pop(s2, 2) =~= s0); + assert(abs_peek(s2, 1) == p); + assert(abs_peek(s2, 0) == q); + lemma_pair_bound_comm(x, dt); + lemma_pair_bound_comm(x, de); + lemma_pair_bound_comm(x, y); + lemma_pair_bound_mono(dt, x, (y - 1) as nat, x); + lemma_pair_bound_mono(de, x, (y - 1) as nat, x); + lemma_pair_if_bound(y, x, p, q); + lemma_pair_cost_mono(x, dt, x, (y - 1) as nat); + lemma_pair_cost_mono(x, de, x, (y - 1) as nat); + lemma_clean_cost_mono(if_bound(p, q), y * (x + 1)); + lemma_pair_split_cost_right(x, y, pair_cost(x, dt) + pair_cost(x, de) + 1 + clean_cost(if_bound(p, q))); + le_pointwise_push(s0, s0, if_bound(p, q), pair_bound(x, y)); + machine_lemma_step(g0, g1, pending, ActionShape::Pair(a@, b@), added, v0, v0); + } + + pub proof fn lemma_pair_split_cost(x: nat, y: nat, c: nat) + requires x >= 2, y >= 1, c <= 2 * pair_cost((x - 1) as nat, y) + 1 + clean_cost(x * (y + 1)), + ensures c < pair_cost(x, y), + {} + + pub proof fn lemma_pair_split_cost_right(x: nat, y: nat, c: nat) + requires x >= 1, y >= 2, c <= 2 * pair_cost(x, (y - 1) as nat) + 1 + clean_cost(y * (x + 1)), + ensures c < pair_cost(x, y), + {} + + pub proof fn machine_pair_both( + g0: model::Graph, g1: model::Graph, pending: Seq, a: TransitionId, b: TransitionId, + x: TestId, xt: TransitionId, xe: TransitionId, y: TestId, yt: TransitionId, ye: TransitionId, + path: TestId, v0: Seq, + ) + requires model::graph_wf(g0), model::graph_extends(g0, g1), transition_tasks_valid(g0, pending), + transition_ids_valid(g0, v0), a@ < g0.transitions.len(), b@ < g0.transitions.len(), + g0.transitions[a@ as int] == model::TransitionNode::If(x@, xt@, xe@), + g0.transitions[b@ as int] == model::TransitionNode::If(y@, yt@, ye@), + ensures machine_cost(g1, pending.push(ActionShape::CleanIf(x@, path@)) + .push(ActionShape::Pair(xe@, ye@)).push(ActionShape::Pair(xt@, yt@)), v0) + < machine_cost(g0, pending.push(ActionShape::Pair(a@, b@)), v0), + { + model::lemma_graph_transition_wf(g0, a@); + model::lemma_graph_transition_wf(g0, b@); + tdepth_lemma_unfold(g0, a@); + tdepth_lemma_unfold(g0, b@); + tdepth_lemma_extends(g0, g1, xt@); + tdepth_lemma_extends(g0, g1, xe@); + tdepth_lemma_extends(g0, g1, yt@); + tdepth_lemma_extends(g0, g1, ye@); + tdepth_lemma_pos(g0, xt@); + tdepth_lemma_pos(g0, xe@); + tdepth_lemma_pos(g0, yt@); + tdepth_lemma_pos(g0, ye@); + let dx = tdepth(g0, a@); + let dy = tdepth(g0, b@); + let mx = (dx - 1) as nat; + let my = (dy - 1) as nat; + let s0 = value_depths(g0, v0); + value_depths_lemma_extends(g0, g1, v0); + let added = seq![ActionShape::CleanIf(x@, path@), ActionShape::Pair(xe@, ye@), ActionShape::Pair(xt@, yt@)]; + assert(pending.push(added[0]).push(added[1]).push(added[2]) =~= pending + added); + machine_lemma_run3(g1, added[0], added[1], added[2], s0); + let p = pair_bound(tdepth(g0, xt@), tdepth(g0, yt@)); + let q = pair_bound(tdepth(g0, xe@), tdepth(g0, ye@)); + let s2 = s0.push(p).push(q); + assert(abs_pop(s2, 2) =~= s0); + assert(abs_peek(s2, 1) == p); + assert(abs_peek(s2, 0) == q); + lemma_pair_bound_mono(tdepth(g0, xt@), tdepth(g0, yt@), mx, dy); + lemma_pair_bound_mono(tdepth(g0, xe@), tdepth(g0, ye@), mx, dy); + lemma_pair_if_bound(dx, dy, p, q); + lemma_pair_cost_mono(tdepth(g0, xt@), tdepth(g0, yt@), mx, dy); + lemma_pair_cost_mono(tdepth(g0, xe@), tdepth(g0, ye@), mx, dy); + lemma_clean_cost_mono(if_bound(p, q), dx * (dy + 1)); + le_pointwise_push(s0, s0, if_bound(p, q), pair_bound(dx, dy)); + machine_lemma_step(g0, g1, pending, ActionShape::Pair(a@, b@), added, v0, v0); + } + + pub proof fn machine_pair_empty( + g0: model::Graph, g1: model::Graph, pending: Seq, a: TransitionId, b: TransitionId, + x: TestId, xt: TransitionId, xe: TransitionId, y: TestId, yt: TransitionId, ye: TransitionId, + guard: TestId, path: TestId, empty: TransitionId, v0: Seq, + ) + requires model::graph_wf(g0), model::graph_extends(g0, g1), transition_tasks_valid(g0, pending), + transition_ids_valid(g0, v0), a@ < g0.transitions.len(), b@ < g0.transitions.len(), + g0.transitions[a@ as int] == model::TransitionNode::If(x@, xt@, xe@), + g0.transitions[b@ as int] == model::TransitionNode::If(y@, yt@, ye@), + tdepth(g1, empty@) == 1, + ensures machine_cost(g1, pending.push(ActionShape::CleanIf(guard@, path@)) + .push(ActionShape::SwapThen).push(ActionShape::Pair(xt@, yt@)), v0.push(empty)) + < machine_cost(g0, pending.push(ActionShape::Pair(a@, b@)), v0), + { + model::lemma_graph_transition_wf(g0, a@); + model::lemma_graph_transition_wf(g0, b@); + tdepth_lemma_unfold(g0, a@); + tdepth_lemma_unfold(g0, b@); + tdepth_lemma_extends(g0, g1, xt@); + tdepth_lemma_extends(g0, g1, yt@); + tdepth_lemma_pos(g0, xt@); + tdepth_lemma_pos(g0, yt@); + tdepth_lemma_pos(g0, xe@); + tdepth_lemma_pos(g0, ye@); + let dx = tdepth(g0, a@); + let dy = tdepth(g0, b@); + let mx = (dx - 1) as nat; + let my = (dy - 1) as nat; + let s0 = value_depths(g0, v0); + value_depths_lemma_extends(g0, g1, v0); + let v1 = v0.push(empty); + assert(value_depths(g1, v1) =~= s0.push(1)); + let added = seq![ActionShape::CleanIf(guard@, path@), ActionShape::SwapThen, ActionShape::Pair(xt@, yt@)]; + assert(pending.push(added[0]).push(added[1]).push(added[2]) =~= pending + added); + machine_lemma_run3(g1, added[0], added[1], added[2], s0.push(1)); + let p = pair_bound(tdepth(g0, xt@), tdepth(g0, yt@)); + let s1 = s0.push(1nat).push(p); + assert(abs_pop(s1, 2) =~= s0); + assert(abs_peek(s1, 0) == p); + assert(abs_peek(s1, 1) == 1); + let s2 = s0.push(p).push(1nat); + assert(action_next(g1, ActionShape::SwapThen, s1) =~= s2); + assert(abs_pop(s2, 2) =~= s0); + assert(abs_peek(s2, 1) == p); + assert(abs_peek(s2, 0) == 1); + lemma_pair_bound_mono(tdepth(g0, xt@), tdepth(g0, yt@), mx, my); + assert(pair_bound(mx, my) + 1 == dx * dy) by (nonlinear_arith) requires dx >= 1, dy >= 1, mx == dx - 1, my == dy - 1; + assert(dx * dy <= pair_bound(dx, dy)) by (nonlinear_arith); + assert(tdepth(g0, xt@) * tdepth(g0, yt@) >= 0) by (nonlinear_arith); + lemma_pair_cost_mono(tdepth(g0, xt@), tdepth(g0, yt@), mx, my); + lemma_clean_cost_mono(if_bound(p, 1), dx * dy); + le_pointwise_push(s0, s0, if_bound(p, 1), pair_bound(dx, dy)); + machine_lemma_step(g0, g1, pending, ActionShape::Pair(a@, b@), added, v0, v1); + } + + // ----- Fold ----- + + pub proof fn machine_fold_flat( + g0: model::Graph, g1: model::Graph, pending: Seq, xs: Seq, v0: Seq, out: TransitionId, + ) + requires model::graph_extends(g0, g1), transition_tasks_valid(g0, pending), transition_ids_valid(g0, v0), + tdepth(g1, out@) <= intersect_bound(tdepths(g0, xs)), + ensures machine_cost(g1, pending, v0.push(out)) < machine_cost(g0, pending.push(ActionShape::Fold(xs, 0)), v0), + { + machine_lemma_push(g0, g1, pending, ActionShape::Fold(xs, 0), v0, out, intersect_bound(tdepths(g0, xs))); + } + + pub proof fn machine_fold_start( + g0: model::Graph, g1: model::Graph, pending: Seq, xs: Seq, flat: TransitionId, + cs: Seq, v0: Seq, + ) + requires model::graph_wf(g1), model::graph_extends(g0, g1), transition_tasks_valid(g0, pending), + transition_ids_valid(g0, v0), flat@ < g1.transitions.len(), cs.len() >= 1, + g1.transitions[flat@ as int] == model::TransitionNode::Intersect(model::transition_ids(cs)), + tdepth(g1, flat@) <= intersect_bound(tdepths(g0, xs)), + ensures machine_cost(g1, pending.push(ActionShape::Fold(model::transition_ids(cs), 1)), v0.push(cs[0])) + < machine_cost(g0, pending.push(ActionShape::Fold(xs, 0)), v0), + { + tdepth_lemma_unfold(g1, flat@); + let ids = model::transition_ids(cs); + let ds = tdepths(g1, ids); + tdepths_lemma_pos(g1, ids); + let e = intersect_bound(tdepths(g0, xs)); + let e1 = intersect_bound(ds); + let d0 = ds[0]; + assert(d0 == tdepth(g1, cs[0]@)); + let s0 = value_depths(g0, v0); + value_depths_lemma_extends(g0, g1, v0); + let v1 = v0.push(cs[0]); + assert(value_depths(g1, v1) =~= s0.push(d0)); + let task = ActionShape::Fold(ids, 1); + let added = seq![task]; + assert(pending.push(task) =~= pending + added); + machine_lemma_run1(g1, task, s0.push(d0)); + assert(abs_peek(s0.push(d0), 0) == d0); + assert(abs_pop(s0.push(d0), 1) =~= s0); + lemma_costs_pos(0); + if ids.len() >= 2 { + lemma_fold(ds); + lemma_pair_cost_total_mono(e1, e); + le_pointwise_push(s0, s0, e1, e); + } else { + lemma_singleton(ds); + le_pointwise_push(s0, s0, d0, e); + } + machine_lemma_step(g0, g1, pending, ActionShape::Fold(xs, 0), added, v0, v1); + } + + pub proof fn machine_fold_next(g: model::Graph, pending: Seq, xs: Seq, k: nat, v0: Seq) + requires transition_tasks_valid(g, pending), 1 <= k < xs.len(), v0.len() >= 1, + ensures machine_cost(g, pending.push(ActionShape::Fold(xs, k + 1)).push(ActionShape::Pair(v0.last()@, xs[k as int])), + v0.drop_last()) + < machine_cost(g, pending.push(ActionShape::Fold(xs, k)), v0), + { + graph_lemma_extends_refl(g); + let s0 = value_depths(g, v0); + let s1 = value_depths(g, v0.drop_last()); + assert(s1 =~= abs_pop(s0, 1)); + let da = tdepth(g, v0.last()@); + assert(abs_peek(s0, 0) == da); + let ds = tdepths(g, xs); + let p = pair_bound(da, ds[k as int]); + let added = seq![ActionShape::Fold(xs, k + 1), ActionShape::Pair(v0.last()@, xs[k as int])]; + assert(pending.push(added[0]).push(added[1]) =~= pending + added); + machine_lemma_run2(g, added[0], added[1], s1); + assert(abs_peek(s1.push(p), 0) == p); + assert(abs_pop(s1.push(p), 1) =~= s1); + assert(fold_cost(ds, k, da) == 1 + pair_cost(da, ds[k as int]) + fold_cost(ds, k + 1, p)); + assert(fold_bound(ds, k, da) == fold_bound(ds, k + 1, p)); + if k + 1 >= xs.len() { + assert(fold_cost(ds, k + 1, p) == 1); + assert(fold_bound(ds, k + 1, p) == p); + } + le_pointwise_refl(action_next(g, ActionShape::Fold(xs, k), s0)); + machine_lemma_step(g, g, pending, ActionShape::Fold(xs, k), added, v0, v0.drop_last()); + } + + pub proof fn machine_fold_noop(g: model::Graph, pending: Seq, xs: Seq, k: nat, v0: Seq) + requires transition_tasks_valid(g, pending), 1 <= k, xs.len() <= k, + ensures machine_cost(g, pending, v0) < machine_cost(g, pending.push(ActionShape::Fold(xs, k)), v0), + { + graph_lemma_extends_refl(g); + let s0 = value_depths(g, v0); + assert(pending + Seq::::empty() =~= pending); + le_pointwise_refl(s0); + machine_lemma_step(g, g, pending, ActionShape::Fold(xs, k), Seq::empty(), v0, v0); + } + + // ----- driver actions ----- + + pub proof fn machine_driver_union( + g0: model::Graph, g1: model::Graph, pending: Seq, n: nat, v0: Seq, out: TransitionId, + ) + requires model::graph_extends(g0, g1), transition_tasks_valid(g0, pending), transition_ids_valid(g0, v0), + n <= v0.len(), + tdepth(g1, out@) <= union_bound(value_depths(g0, v0.subrange(v0.len() - n, v0.len() as int))), + ensures machine_cost(g1, pending, v0.take(v0.len() - n).push(out)) + < machine_cost(g0, pending.push(ActionShape::Union(n)), v0), + { + let s0 = value_depths(g0, v0); + let rest = v0.take(v0.len() - n); + assert(abs_top(s0, n) =~= value_depths(g0, v0.subrange(v0.len() - n, v0.len() as int))); + assert(abs_pop(s0, n) =~= value_depths(g0, rest)); + assert(transition_ids_valid(g0, rest)); + value_depths_lemma_extends(g0, g1, rest); + let v1 = rest.push(out); + let b = union_bound(abs_top(s0, n)); + assert(value_depths(g1, v1) =~= value_depths(g0, rest).push(tdepth(g1, out@))); + le_pointwise_push(value_depths(g0, rest), value_depths(g0, rest), tdepth(g1, out@), b); + assert(pending + Seq::::empty() =~= pending); + machine_lemma_step(g0, g1, pending, ActionShape::Union(n), Seq::empty(), v0, v1); + } + + pub proof fn machine_driver_intersect(g: model::Graph, pending: Seq, n: nat, v0: Seq) + requires transition_tasks_valid(g, pending), n <= v0.len(), + ensures machine_cost(g, pending.push(ActionShape::Fold( + model::transition_ids(v0.subrange(v0.len() - n, v0.len() as int)), 0)), v0.take(v0.len() - n)) + < machine_cost(g, pending.push(ActionShape::Intersect(n)), v0), + { + graph_lemma_extends_refl(g); + let s0 = value_depths(g, v0); + let rest = v0.take(v0.len() - n); + let xs = model::transition_ids(v0.subrange(v0.len() - n, v0.len() as int)); + assert(abs_top(s0, n) =~= tdepths(g, xs)); + assert(abs_pop(s0, n) =~= value_depths(g, rest)); + let task = ActionShape::Fold(xs, 0); + let added = seq![task]; + assert(pending.push(task) =~= pending + added); + machine_lemma_run1(g, task, value_depths(g, rest)); + le_pointwise_refl(action_next(g, ActionShape::Intersect(n), s0)); + machine_lemma_step(g, g, pending, ActionShape::Intersect(n), added, v0, rest); + } + + pub proof fn machine_driver_if( + g0: model::Graph, g1: model::Graph, pending: Seq, task: ActionShape, v0: Seq, + out: TransitionId, + ) + requires model::graph_extends(g0, g1), transition_tasks_valid(g0, pending), transition_ids_valid(g0, v0), + task is If, v0.len() >= 2, + tdepth(g1, out@) <= if_bound(tdepth(g0, v0[v0.len() - 2]@), tdepth(g0, v0[v0.len() - 1]@)), + ensures machine_cost(g1, pending, v0.take(v0.len() - 2).push(out)) < machine_cost(g0, pending.push(task), v0), + { + let s0 = value_depths(g0, v0); + let rest = v0.take(v0.len() - 2); + assert(abs_pop(s0, 2) =~= value_depths(g0, rest)); + assert(transition_ids_valid(g0, rest)); + value_depths_lemma_extends(g0, g1, rest); + let v1 = rest.push(out); + let b = if_bound(abs_peek(s0, 1), abs_peek(s0, 0)); + assert(value_depths(g1, v1) =~= value_depths(g0, rest).push(tdepth(g1, out@))); + le_pointwise_push(value_depths(g0, rest), value_depths(g0, rest), tdepth(g1, out@), b); + assert(pending + Seq::::empty() =~= pending); + machine_lemma_step(g0, g1, pending, task, Seq::empty(), v0, v1); + } + + pub proof fn machine_driver_clean_if( + g0: model::Graph, g1: model::Graph, pending: Seq, test: TestId, path: TestId, + v0: Seq, out: TransitionId, + ) + requires model::graph_extends(g0, g1), transition_tasks_valid(g0, pending), transition_ids_valid(g0, v0), + v0.len() >= 2, + tdepth(g1, out@) <= if_bound(tdepth(g0, v0[v0.len() - 2]@), tdepth(g0, v0[v0.len() - 1]@)), + ensures machine_cost(g1, pending.push(ActionShape::Clean(out@, path@)), v0.take(v0.len() - 2)) + < machine_cost(g0, pending.push(ActionShape::CleanIf(test@, path@)), v0), + { + let s0 = value_depths(g0, v0); + let rest = v0.take(v0.len() - 2); + assert(abs_pop(s0, 2) =~= value_depths(g0, rest)); + assert(transition_ids_valid(g0, rest)); + value_depths_lemma_extends(g0, g1, rest); + let b = if_bound(abs_peek(s0, 1), abs_peek(s0, 0)); + let task = ActionShape::Clean(out@, path@); + let added = seq![task]; + assert(pending.push(task) =~= pending + added); + machine_lemma_run1(g1, task, value_depths(g0, rest)); + lemma_clean_cost_mono(tdepth(g1, out@), b); + le_pointwise_push(value_depths(g0, rest), value_depths(g0, rest), tdepth(g1, out@), b); + machine_lemma_step(g0, g1, pending, ActionShape::CleanIf(test@, path@), added, v0, rest); + } + + pub proof fn machine_driver_result( + g: model::Graph, pending: Seq, suffix: Option, v0: Seq, + ) + requires transition_tasks_valid(g, pending), v0.len() >= 1, + ensures machine_cost(g, pending.push(match suffix { + Some(r) => ActionShape::Append(v0.last()@, r), None => ActionShape::Not(v0.last()@) }), v0.drop_last()) + < machine_cost(g, pending.push(match suffix { + Some(r) => ActionShape::AppendResult(r), None => ActionShape::NotResult }), v0), + { + graph_lemma_extends_refl(g); + let s0 = value_depths(g, v0); + let rest = value_depths(g, v0.drop_last()); + assert(abs_pop(s0, 1) =~= rest); + assert(abs_peek(s0, 0) == tdepth(g, v0.last()@)); + let task = match suffix { Some(r) => ActionShape::Append(v0.last()@, r), None => ActionShape::Not(v0.last()@) }; + let added = seq![task]; + assert(pending.push(task) =~= pending + added); + machine_lemma_run1(g, task, rest); + let old_task = match suffix { Some(r) => ActionShape::AppendResult(r), None => ActionShape::NotResult }; + le_pointwise_refl(action_next(g, old_task, s0)); + machine_lemma_step(g, g, pending, old_task, added, v0, v0.drop_last()); + } + + pub proof fn machine_driver_swap(g: model::Graph, pending: Seq, v0: Seq) + requires transition_tasks_valid(g, pending), v0.len() >= 2, + ensures machine_cost(g, pending, v0.take(v0.len() - 2).push(v0[v0.len() - 1]).push(v0[v0.len() - 2])) + < machine_cost(g, pending.push(ActionShape::SwapThen), v0), + { + graph_lemma_extends_refl(g); + let s0 = value_depths(g, v0); + let v1 = v0.take(v0.len() - 2).push(v0[v0.len() - 1]).push(v0[v0.len() - 2]); + assert(value_depths(g, v1) =~= action_next(g, ActionShape::SwapThen, s0)); + le_pointwise_refl(value_depths(g, v1)); + assert(pending + Seq::::empty() =~= pending); + machine_lemma_step(g, g, pending, ActionShape::SwapThen, Seq::empty(), v0, v1); + } + + // ----- set collection: depth conservation ----- + + pub open spec fn collect_bound(g: model::Graph, ids: Seq, intersect: bool) -> nat { + if intersect { intersect_bound(value_depths(g, ids)) } else { union_bound(value_depths(g, ids)) } + } + + pub open spec fn collect_weight(g: model::Graph, ids: Seq, intersect: bool) -> nat { + if intersect { prod_plus1(value_depths(g, ids)) } else { sum_plus1(value_depths(g, ids)) } + } + + pub open spec fn pow2(n: nat) -> nat + decreases n, + { + if n == 0 { 1 } else { 2 * pow2((n - 1) as nat) } + } + + /// Conserved quantity of `TransitionMode::collect`: pending, flattened, and constant children. + pub open spec fn collect_total( + g: model::Graph, pending: Seq, flat: Seq, constants: Seq, intersect: bool, + ) -> nat { + if intersect { + collect_weight(g, pending, true) * collect_weight(g, flat, true) * pow2(constants.len()) + } else { + collect_weight(g, pending, false) + collect_weight(g, flat, false) + 2 * constants.len() + } + } + + pub proof fn lemma_pow2_pos(n: nat) + ensures pow2(n) >= 1, + decreases n, + { + if n > 0 { lemma_pow2_pos((n - 1) as nat); } + } + + pub proof fn collect_lemma_push(g: model::Graph, ids: Seq, id: TransitionId, intersect: bool) + ensures collect_weight(g, ids.push(id), intersect) == if intersect { + collect_weight(g, ids, true) * (tdepth(g, id@) + 1) + } else { collect_weight(g, ids, false) + tdepth(g, id@) + 1 }, + { + let s = value_depths(g, ids); + assert(value_depths(g, ids.push(id)) =~= s.push(tdepth(g, id@))); + assert(s.push(tdepth(g, id@)).drop_last() =~= s); + } + + pub proof fn collect_lemma_concat(g: model::Graph, a: Seq, b: Seq, intersect: bool) + ensures collect_weight(g, a + b, intersect) == if intersect { + collect_weight(g, a, true) * collect_weight(g, b, true) + } else { collect_weight(g, a, false) + collect_weight(g, b, false) }, + decreases b.len(), + { + if b.len() == 0 { + assert(a + b =~= a); + assert(value_depths(g, b).len() == 0); + let wa = collect_weight(g, a, true); + assert(wa * 1 == wa) by (nonlinear_arith); + } else { + let b0 = b.drop_last(); + let x = b.last(); + collect_lemma_concat(g, a, b0, intersect); + assert(a + b =~= (a + b0).push(x)); + assert(b =~= b0.push(x)); + collect_lemma_push(g, a + b0, x, intersect); + collect_lemma_push(g, b0, x, intersect); + let wa = collect_weight(g, a, true); + let wb = collect_weight(g, b0, true); + let d = tdepth(g, x@); + assert(wa * wb * (d + 1) == wa * (wb * (d + 1))) by (nonlinear_arith); + } + } + + pub proof fn collect_lemma_remove(g: model::Graph, s: Seq, i: int, intersect: bool) + requires 0 <= i < s.len(), + ensures collect_weight(g, s, intersect) == if intersect { + collect_weight(g, s.remove(i), true) * (tdepth(g, s[i]@) + 1) + } else { collect_weight(g, s.remove(i), false) + tdepth(g, s[i]@) + 1 }, + { + let a = s.take(i); + let c = s.skip(i + 1); + assert(s =~= a.push(s[i]) + c); + assert(s.remove(i) =~= a + c); + collect_lemma_concat(g, a.push(s[i]), c, intersect); + collect_lemma_push(g, a, s[i], intersect); + collect_lemma_concat(g, a, c, intersect); + let wa = collect_weight(g, a, true); + let wc = collect_weight(g, c, true); + let d = tdepth(g, s[i]@); + assert(wa * (d + 1) * wc == wa * wc * (d + 1)) by (nonlinear_arith); + } + + pub proof fn collect_lemma_subset(g: model::Graph, sub: Seq, sup: Seq, intersect: bool) + requires sub.no_duplicates(), forall|x: TransitionId| sub.contains(x) ==> sup.contains(x), + ensures collect_weight(g, sub, intersect) <= collect_weight(g, sup, intersect), + decreases sub.len(), + { + if sub.len() == 0 { + assert(value_depths(g, sub).len() == 0); + lemma_prod_pos(value_depths(g, sup)); + } else { + let x = sub.last(); + let rest = sub.drop_last(); + assert(sub[sub.len() - 1] == x); + assert(sub.contains(x)); + let i = choose|i: int| 0 <= i < sup.len() && sup[i] == x; + let sup2 = sup.remove(i); + assert forall|y: TransitionId| rest.contains(y) implies sup2.contains(y) by { + let j = choose|j: int| 0 <= j < rest.len() && rest[j] == y; + assert(sub[j] == y); + assert(sub.contains(y)); + let k = choose|k: int| 0 <= k < sup.len() && sup[k] == y; + assert(k != i); + if k < i { assert(sup2[k] == y); } else { assert(sup2[k - 1] == y); } + } + assert(rest.no_duplicates()) by { + assert forall|p: int, q: int| 0 <= p < rest.len() && 0 <= q < rest.len() && p != q implies rest[p] != rest[q] by { + assert(sub[p] == rest[p] && sub[q] == rest[q]); + } + } + collect_lemma_subset(g, rest, sup2, intersect); + assert(sub =~= rest.push(x)); + collect_lemma_push(g, rest, x, intersect); + collect_lemma_remove(g, sup, i, intersect); + let wr = collect_weight(g, rest, true); + let ws = collect_weight(g, sup2, true); + let d = tdepth(g, x@); + if intersect { + assert(wr * (d + 1) <= ws * (d + 1)) by (nonlinear_arith) requires wr <= ws; + } + } + } + + pub proof fn collect_lemma_drop( + g: model::Graph, prefix: Seq, id: TransitionId, flat: Seq, rs: Seq, intersect: bool, + ) + ensures collect_total(g, prefix, flat, rs, intersect) <= collect_total(g, prefix.push(id), flat, rs, intersect), + { + collect_lemma_push(g, prefix, id, intersect); + let wp = collect_weight(g, prefix, true); + let wf = collect_weight(g, flat, true); + let p = pow2(rs.len()); + let d = tdepth(g, id@); + assert(wp * wf * p <= wp * (d + 1) * wf * p) by (nonlinear_arith); + } + + pub proof fn collect_lemma_leaf( + g: model::Graph, prefix: Seq, id: TransitionId, flat: Seq, rs: Seq, intersect: bool, + ) + ensures collect_total(g, prefix, flat.push(id), rs, intersect) <= collect_total(g, prefix.push(id), flat, rs, intersect), + { + collect_lemma_push(g, prefix, id, intersect); + collect_lemma_push(g, flat, id, intersect); + let wp = collect_weight(g, prefix, true); + let wf = collect_weight(g, flat, true); + let p = pow2(rs.len()); + let d = tdepth(g, id@); + assert(wp * (wf * (d + 1)) * p == wp * (d + 1) * wf * p) by (nonlinear_arith); + } + + pub proof fn collect_lemma_constant( + g: model::Graph, prefix: Seq, id: TransitionId, flat: Seq, rs: Seq, + r: RegexId, intersect: bool, + ) + requires id@ < g.transitions.len(), g.transitions[id@ as int] is Const, + ensures collect_total(g, prefix, flat, rs.push(r), intersect) <= collect_total(g, prefix.push(id), flat, rs, intersect), + { + collect_lemma_push(g, prefix, id, intersect); + tdepth_lemma_const(g, id@); + assert(pow2(rs.push(r).len()) == 2 * pow2(rs.len())); + let wp = collect_weight(g, prefix, true); + let wf = collect_weight(g, flat, true); + let p = pow2(rs.len()); + assert(wp * wf * (2 * p) == wp * 2 * wf * p) by (nonlinear_arith); + } + + pub proof fn collect_lemma_expand( + g: model::Graph, prefix: Seq, id: TransitionId, children: Seq, + flat: Seq, rs: Seq, intersect: bool, + ) + requires model::graph_wf(g), id@ < g.transitions.len(), + model::transition_ids(children) == transition_children(g, id@), + match g.transitions[id@ as int] { + model::TransitionNode::Union(_) => !intersect, + model::TransitionNode::Intersect(_) => intersect, + _ => false, + }, + ensures collect_total(g, prefix + children, flat, rs, intersect) + <= collect_total(g, prefix.push(id), flat, rs, intersect), + { + transition_lemma_children(g, id@); + tdepth_lemma_unfold(g, id@); + let cs = transition_children(g, id@); + assert(value_depths(g, children) =~= tdepths(g, cs)); + tdepths_lemma_pos(g, cs); + lemma_bounds_pos(tdepths(g, cs)); + collect_lemma_concat(g, prefix, children, intersect); + collect_lemma_push(g, prefix, id, intersect); + let wp = collect_weight(g, prefix, true); + let wc = collect_weight(g, children, true); + let wf = collect_weight(g, flat, true); + let p = pow2(rs.len()); + let d = tdepth(g, id@); + if intersect { + assert(wp * wc * wf * p <= wp * (d + 1) * wf * p) by (nonlinear_arith) requires wc <= d + 1; + } + } + + /// After `TransitionMode::collect`: the flattened children and constants fit in the original weight. + pub proof fn collect_lemma_flat( + g: model::Graph, original: Seq, pending: Seq, flat: Seq, + rs: Seq, intersect: bool, + ) + requires pending.len() == 0, + collect_total(g, pending, flat, rs, intersect) + <= collect_total(g, original, Seq::empty(), Seq::empty(), intersect), + ensures collect_weight(g, flat, intersect) <= collect_weight(g, original, intersect), + rs.len() >= 1 ==> if intersect { collect_weight(g, flat, true) * 2 <= collect_weight(g, original, true) } + else { collect_weight(g, flat, false) + 2 <= collect_weight(g, original, false) }, + { + assert(value_depths(g, pending).len() == 0); + assert(value_depths(g, Seq::::empty()).len() == 0); + let wf = collect_weight(g, flat, true); + let wo = collect_weight(g, original, true); + let p = pow2(rs.len()); + lemma_pow2_pos(rs.len()); + if rs.len() >= 1 { lemma_pow2_pos((rs.len() - 1) as nat); } + if intersect { + assert(1 * wf * p == wf * p) by (nonlinear_arith); + assert(wo * 1 * 1 == wo) by (nonlinear_arith); + assert(wf <= wf * p) by (nonlinear_arith) requires p >= 1; + if rs.len() >= 1 { assert(wf * 2 <= wf * p) by (nonlinear_arith) requires p >= 2; } + } + } + + pub proof fn collect_lemma_extends(a: model::Graph, b: model::Graph, ids: Seq, intersect: bool) + requires model::graph_extends(a, b), transition_ids_valid(a, ids), + ensures collect_weight(a, ids, intersect) == collect_weight(b, ids, intersect), + { + value_depths_lemma_extends(a, b, ids); + } + + /// `t` is the constant transition built from the collected constants. + pub proof fn collect_lemma_const_result( + a: model::Graph, b: model::Graph, original: Seq, flat: Seq, t: TransitionId, + pushed: bool, intersect: bool, + ) + requires model::graph_extends(a, b), transition_ids_valid(a, original), transition_ids_valid(a, flat), + t@ < b.transitions.len(), b.transitions[t@ as int] is Const, + if intersect { collect_weight(a, flat, true) * 2 <= collect_weight(a, original, true) } + else { collect_weight(a, flat, false) + 2 <= collect_weight(a, original, false) }, + ensures collect_weight(b, if pushed { flat.push(t) } else { flat }, intersect) <= collect_weight(b, original, intersect), + { + collect_lemma_extends(a, b, original, intersect); + collect_lemma_extends(a, b, flat, intersect); + collect_lemma_push(b, flat, t, intersect); + tdepth_lemma_const(b, t@); + let wf = collect_weight(b, flat, true); + assert(wf <= wf * 2) by (nonlinear_arith); + } + + pub proof fn collect_lemma_bound(g: model::Graph, ids: Seq, intersect: bool) + ensures collect_bound(g, ids, intersect) >= 2, + { + value_depths_lemma_pos(g, ids); + lemma_bounds_pos(value_depths(g, ids)); + } + + /// Depth of the three possible results of `TransitionId::collect`. + pub proof fn collect_lemma_final( + entry: model::Graph, g: model::Graph, original: Seq, flat: Seq, intersect: bool, + ) + requires model::graph_wf(g), model::graph_extends(entry, g), transition_ids_valid(entry, original), + transition_ids_valid(g, flat), + collect_weight(g, flat, intersect) <= collect_weight(g, original, intersect), + ensures collect_bound(entry, original, intersect) >= 2, + tdepth(g, g.constants.transition_empty) == 1, tdepth(g, g.constants.transition_all) == 1, + flat.len() == 1 ==> tdepth(g, flat[0]@) <= collect_bound(entry, original, intersect), + flat.len() >= 2 ==> tdepth_node(g, if intersect { + model::TransitionNode::Intersect(model::transition_ids(flat)) + } else { model::TransitionNode::Union(model::transition_ids(flat)) }) + <= collect_bound(entry, original, intersect), + { + tdepth_lemma_constants(g); + value_depths_lemma_extends(entry, g, original); + let ds = value_depths(entry, original); + value_depths_lemma_pos(entry, original); + lemma_bounds_pos(ds); + lemma_sum_ge(ds); + lemma_prod_ge(ds); + let fs = value_depths(g, flat); + value_depths_lemma_pos(g, flat); + lemma_sum_ge(fs); + lemma_prod_ge(fs); + assert(tdepths(g, model::transition_ids(flat)) =~= fs); + if flat.len() == 1 { + lemma_singleton(fs); + assert(fs[0] == tdepth(g, flat[0]@)); + } + } + + pub open spec fn transition_collect_combo( + g: model::Graph, theta: Subst, pending: Seq, + flat: Seq, constants: Seq, event: EventView, word: Seq, intersect: bool, + ) -> bool { + if intersect { + transition_combo(g, theta, pending, event, word, true) + && transition_combo(g, theta, flat, event, word, true) + && regex_combo(g, theta, constants, word, true) + } else { + transition_combo(g, theta, pending, event, word, false) + || transition_combo(g, theta, flat, event, word, false) + || regex_combo(g, theta, constants, word, false) + } + } + + + + pub proof fn transition_lemma_ids_bounded(g: model::Graph, ids: Seq) + requires transition_ids_valid(g, ids), + ensures model::bounded(model::transition_ids(ids), g.transitions.len()), + {} + + pub proof fn transition_lemma_pending_work_concat( + g: model::Graph, left: Seq, right: Seq, intersect: bool, + ) + requires transition_ids_valid(g, left), transition_ids_valid(g, right), + ensures transition_pending_work(g, left + right, intersect) + == transition_pending_work(g, left, intersect) + transition_pending_work(g, right, intersect), + { + transition_lemma_ids_bounded(g, left); + transition_lemma_ids_bounded(g, right); + assert(model::transition_ids(left + right) =~= model::transition_ids(left) + model::transition_ids(right)); + transition_lemma_work_concat(g, model::transition_ids(left), model::transition_ids(right), g.transitions.len(), intersect); + } + + pub proof fn transition_lemma_pending_work_push(g: model::Graph, ids: Seq, id: TransitionId, intersect: bool) + requires transition_ids_valid(g, ids), id@ < g.transitions.len(), + ensures transition_pending_work(g, ids.push(id), intersect) + == transition_pending_work(g, ids, intersect) + transition_collect_work(g, id@, intersect), + { + transition_lemma_pending_work_concat(g, ids, seq![id], intersect); + assert(ids.push(id) =~= ids + seq![id]); + assert(model::transition_ids(seq![id]) =~= seq![id@]); + transition_lemma_work_singleton(g, id, intersect); + } + + pub proof fn transition_lemma_flat_work(g: model::Graph, id: TransitionId, intersect: bool) + requires model::graph_wf(g), id@ < g.transitions.len(), + match g.transitions[id@ as int] { + model::TransitionNode::Union(ids) => !intersect, + model::TransitionNode::Intersect(ids) => intersect, + _ => false, + }, + ensures transition_collect_work(g, id@, intersect) + == 1 + transition_collect_work_ids(g, transition_children(g, id@), g.transitions.len(), intersect), + { + transition_lemma_children(g, id@); + model::lemma_graph_transition_wf(g, id@); + transition_lemma_work_bounds(g, transition_children(g, id@), id@, g.transitions.len(), intersect); + } + + pub proof fn transition_lemma_combo_concat( + g: model::Graph, theta: Subst, left: Seq, right: Seq, + event: EventView, word: Seq, intersect: bool, + ) + ensures transition_combo(g, theta, left + right, event, word, intersect) + == if intersect { + transition_combo(g, theta, left, event, word, true) + && transition_combo(g, theta, right, event, word, true) + } else { + transition_combo(g, theta, left, event, word, false) + || transition_combo(g, theta, right, event, word, false) + }, + { + if intersect { + if transition_combo(g, theta, left + right, event, word, true) { + assert forall|i: int| 0 <= i < left.len() implies transition_lang(g, theta, left[i], event, word) by { + assert((left + right)[i] == left[i]); + assert(transition_lang(g, theta, (left + right)[i], event, word)); + } + assert forall|i: int| 0 <= i < right.len() implies transition_lang(g, theta, right[i], event, word) by { + assert((left + right)[left.len() as int + i] == right[i]); + assert(transition_lang(g, theta, (left + right)[left.len() as int + i], event, word)); + } + } + if transition_combo(g, theta, left, event, word, true) + && transition_combo(g, theta, right, event, word, true) { + assert forall|i: int| 0 <= i < (left + right).len() implies + transition_lang(g, theta, (left + right)[i], event, word) by { + if i < left.len() { assert((left + right)[i] == left[i]); } + else { assert((left + right)[i] == right[i - left.len() as int]); } + } + } + } else { + if transition_combo(g, theta, left + right, event, word, false) { + let i = choose|i: int| 0 <= i < (left + right).len() + && transition_lang(g, theta, (left + right)[i], event, word); + if i < left.len() { + assert((left + right)[i] == left[i]); + assert(transition_combo(g, theta, left, event, word, false)); + } else { + assert((left + right)[i] == right[i - left.len() as int]); + assert(transition_combo(g, theta, right, event, word, false)); + } + } + if transition_combo(g, theta, left, event, word, false) { + let i = choose|i: int| 0 <= i < left.len() && transition_lang(g, theta, left[i], event, word); + assert(transition_lang(g, theta, (left + right)[i], event, word)); + assert(transition_combo(g, theta, left + right, event, word, false)); + } + if transition_combo(g, theta, right, event, word, false) { + let i = choose|i: int| 0 <= i < right.len() && transition_lang(g, theta, right[i], event, word); + assert(transition_lang(g, theta, (left + right)[left.len() as int + i], event, word)); + assert(transition_combo(g, theta, left + right, event, word, false)); + } + } + } + + pub proof fn transition_lemma_constant(g: model::Graph, id: TransitionId, regex: RegexId) + requires model::graph_wf(g), id@ < g.transitions.len(), + g.transitions[id@ as int] == model::TransitionNode::Const(regex@), + ensures forall|theta: Subst, event: EventView, word: Seq| + transition_lang(g, theta, id, event, word) == model::regex_lang(g, theta, regex@, word), + { + transition_unfold(g, id@); + assert forall|theta: Subst, event: EventView, word: Seq| + transition_lang(g, theta, id, event, word) == model::regex_lang(g, theta, regex@, word) by { + language::lemma_interp_const(model::gsem(theta), event, model::lift_regex(g, regex@)); + } + } + + pub proof fn transition_lemma_children_language( + g: model::Graph, id: TransitionId, children: Seq, intersect: bool, + ) + requires model::graph_wf(g), id@ < g.transitions.len(), + g.transitions[id@ as int] == if intersect { + model::TransitionNode::Intersect(model::transition_ids(children)) + } else { model::TransitionNode::Union(model::transition_ids(children)) }, + ensures forall|theta: Subst, event: EventView, word: Seq| + transition_lang(g, theta, id, event, word) + == transition_combo(g, theta, children, event, word, intersect), + { + transition_unfold(g, id@); + let terms = model::transition_ids(children).map(|i: int, child: nat| model::lift_transition(g, child)); + assert forall|theta: Subst, event: EventView, word: Seq| + transition_lang(g, theta, id, event, word) + == transition_combo(g, theta, children, event, word, intersect) by { + let sem = model::gsem(theta); + assert forall|i: int| 0 <= i < children.len() implies + transition_lang(g, theta, children[i], event, word) + == language::numeric_lang(sem, language::interp_transition(sem, event, terms[i]), word) by { + assert(terms[i] == model::lift_transition(g, children[i]@)); + } + if intersect { + language::lemma_interp_intersect(sem, event, terms, word); + } else { + language::lemma_interp_union(sem, event, terms, word); + if transition_lang(g, theta, id, event, word) { + let i = choose|i: int| 0 <= i < terms.len() + && language::numeric_lang(sem, language::interp_transition(sem, event, terms[i]), word); + assert(transition_lang(g, theta, children[i], event, word)); + } + if transition_combo(g, theta, children, event, word, false) { + let i = choose|i: int| 0 <= i < children.len() + && transition_lang(g, theta, children[i], event, word); + assert(language::numeric_lang(sem, language::interp_transition(sem, event, terms[i]), word)); + } + } + } + } + + pub proof fn transition_lemma_identities(g: model::Graph, mode: TransitionModeModel) + requires model::graph_wf(g), transition_mode_valid(g, mode), + ensures mode.identity@ < g.transitions.len(), mode.absorber@ < g.transitions.len(), + forall|theta: Subst, event: EventView, word: Seq| + transition_lang(g, theta, mode.identity, event, word) == mode.intersect, + forall|theta: Subst, event: EventView, word: Seq| + transition_lang(g, theta, mode.absorber, event, word) == !mode.intersect, + { + model::lemma_graph_wf_elim(g); + transition_unfold(g, mode.identity@); + transition_unfold(g, mode.absorber@); + regex_unfold(g, g.constants.empty); + regex_unfold(g, g.constants.all); + assert forall|theta: Subst, event: EventView, word: Seq| + transition_lang(g, theta, mode.identity, event, word) == mode.intersect by { + if mode.intersect { + language::lemma_interp_const(model::gsem(theta), event, model::lift_regex(g, g.constants.all)); + } else { + language::lemma_interp_const(model::gsem(theta), event, model::lift_regex(g, g.constants.empty)); + } + } + assert forall|theta: Subst, event: EventView, word: Seq| + transition_lang(g, theta, mode.absorber, event, word) == !mode.intersect by { + if mode.intersect { + language::lemma_interp_const(model::gsem(theta), event, model::lift_regex(g, g.constants.empty)); + } else { + language::lemma_interp_const(model::gsem(theta), event, model::lift_regex(g, g.constants.all)); + } + } + } + + pub open spec fn transition_collect_effect( + g: model::Graph, mode: TransitionModeModel, pending: Seq, flat: Seq, constants: Seq, + next_pending: Seq, next_flat: Seq, next_constants: Seq, collapsed: bool, + ) -> bool { + (forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_collect_combo(g, theta, pending, flat, constants, event, word, mode.intersect) + == if collapsed { !mode.intersect } else { + transition_collect_combo(g, theta, next_pending, next_flat, next_constants, event, word, mode.intersect) + }) + && (!collapsed && pending.len() > 0 ==> transition_pending_work(g, next_pending, mode.intersect) + < transition_pending_work(g, pending, mode.intersect)) + } + + pub proof fn transition_lemma_pending_work_pop(g: model::Graph, pending: Seq, intersect: bool) + requires transition_ids_valid(g, pending), pending.len() > 0, + ensures transition_pending_work(g, pending.drop_last(), intersect) < transition_pending_work(g, pending, intersect), + { + transition_lemma_pending_work_push(g, pending.drop_last(), pending.last(), intersect); + transition_lemma_work_positive(g, pending.last()@, intersect); + assert(pending.drop_last().push(pending.last()) =~= pending); + } + + pub proof fn transition_lemma_collect_identity( + g: model::Graph, mode: TransitionModeModel, pending: Seq, flat: Seq, constants: Seq, + ) + requires model::graph_wf(g), transition_mode_valid(g, mode), + transition_ids_valid(g, pending), pending.len() > 0, pending.last() == mode.identity, + ensures transition_collect_effect(g, mode, pending, flat, constants, pending.drop_last(), flat, constants, false), + { + transition_lemma_identities(g, mode); + transition_lemma_pending_work_pop(g, pending, mode.intersect); + assert(pending.drop_last() + seq![pending.last()] =~= pending); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies transition_collect_combo(g, theta, pending, flat, constants, event, word, mode.intersect) + == transition_collect_combo(g, theta, pending.drop_last(), flat, constants, event, word, mode.intersect) by { + transition_lemma_combo_concat(g, theta, pending.drop_last(), seq![pending.last()], event, word, mode.intersect); + } + } + + pub proof fn transition_lemma_collect_absorber( + g: model::Graph, mode: TransitionModeModel, pending: Seq, flat: Seq, constants: Seq, + ) + requires model::graph_wf(g), transition_mode_valid(g, mode), + pending.len() > 0, pending.last() == mode.absorber, + ensures forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_collect_combo(g, theta, pending, flat, constants, event, word, mode.intersect) == !mode.intersect, + { + transition_lemma_identities(g, mode); + assert(pending.drop_last() + seq![pending.last()] =~= pending); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies transition_collect_combo(g, theta, pending, flat, constants, event, word, mode.intersect) == !mode.intersect by { + transition_lemma_combo_concat(g, theta, pending.drop_last(), seq![pending.last()], event, word, mode.intersect); + } + } + + pub proof fn transition_lemma_collect_leaf( + g: model::Graph, mode: TransitionModeModel, pending: Seq, flat: Seq, constants: Seq, + ) + requires transition_ids_valid(g, pending), pending.len() > 0, + ensures transition_collect_effect(g, mode, pending, flat, constants, + pending.drop_last(), flat.push(pending.last()), constants, false), + { + transition_lemma_pending_work_pop(g, pending, mode.intersect); + assert(pending.drop_last() + seq![pending.last()] =~= pending); + assert(flat + seq![pending.last()] =~= flat.push(pending.last())); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies transition_collect_combo(g, theta, pending, flat, constants, event, word, mode.intersect) + == transition_collect_combo(g, theta, pending.drop_last(), flat.push(pending.last()), constants, event, word, mode.intersect) by { + transition_lemma_combo_concat(g, theta, pending.drop_last(), seq![pending.last()], event, word, mode.intersect); + transition_lemma_combo_concat(g, theta, flat, seq![pending.last()], event, word, mode.intersect); + } + } + + pub proof fn transition_lemma_collect_constant( + g: model::Graph, mode: TransitionModeModel, pending: Seq, flat: Seq, constants: Seq, regex: RegexId, + ) + requires model::graph_wf(g), transition_ids_valid(g, pending), pending.len() > 0, + g.transitions[pending.last()@ as int] == model::TransitionNode::Const(regex@), + ensures transition_collect_effect(g, mode, pending, flat, constants, + pending.drop_last(), flat, constants.push(regex), false), + { + transition_lemma_constant(g, pending.last(), regex); + transition_lemma_pending_work_pop(g, pending, mode.intersect); + assert(pending.drop_last() + seq![pending.last()] =~= pending); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies transition_collect_combo(g, theta, pending, flat, constants, event, word, mode.intersect) + == transition_collect_combo(g, theta, pending.drop_last(), flat, constants.push(regex), event, word, mode.intersect) by { + transition_lemma_combo_concat(g, theta, pending.drop_last(), seq![pending.last()], event, word, mode.intersect); + transition_lemma_regex_combo_push(g, theta, constants, regex, word, mode.intersect); + assert(regex_combo(g, theta, constants.push(regex), word, mode.intersect) + == if mode.intersect { + regex_combo(g, theta, constants, word, true) && model::regex_lang(g, theta, regex@, word) + } else { + regex_combo(g, theta, constants, word, false) || model::regex_lang(g, theta, regex@, word) + }); + } + } + + pub proof fn transition_lemma_collect_expand( + g: model::Graph, mode: TransitionModeModel, pending: Seq, flat: Seq, constants: Seq, children: Seq, + ) + requires model::graph_wf(g), transition_ids_valid(g, pending), pending.len() > 0, + transition_ids_valid(g, children), + g.transitions[pending.last()@ as int] == if mode.intersect { + model::TransitionNode::Intersect(model::transition_ids(children)) + } else { model::TransitionNode::Union(model::transition_ids(children)) }, + ensures transition_collect_effect(g, mode, pending, flat, constants, + pending.drop_last() + children, flat, constants, false), + { + let prefix = pending.drop_last(); + let id = pending.last(); + transition_lemma_pending_work_push(g, prefix, id, mode.intersect); + transition_lemma_pending_work_concat(g, prefix, children, mode.intersect); + transition_lemma_ids_bounded(g, children); + transition_lemma_flat_work(g, id, mode.intersect); + transition_lemma_children(g, id@); + assert(transition_children(g, id@) == model::transition_ids(children)); + assert(prefix.push(id) =~= pending); + transition_lemma_children_language(g, id, children, mode.intersect); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies transition_collect_combo(g, theta, pending, flat, constants, event, word, mode.intersect) + == transition_collect_combo(g, theta, prefix + children, flat, constants, event, word, mode.intersect) by { + transition_lemma_combo_concat(g, theta, prefix, seq![id], event, word, mode.intersect); + transition_lemma_combo_concat(g, theta, prefix, children, event, word, mode.intersect); + } + } + + + pub proof fn transition_lemma_work_singleton(g: model::Graph, id: TransitionId, intersect: bool) + requires id@ < g.transitions.len(), + ensures transition_pending_work(g, seq![id], intersect) == transition_collect_work(g, id@, intersect), + { + transition_lemma_ids_bounded(g, seq![id]); + assert(model::transition_ids(seq![id]) =~= seq![id@]); + reveal_with_fuel(transition_collect_work_ids, 2); + } + + pub proof fn transition_lemma_image_suffix(prefix: Seq, whole: Seq, suffix: Seq) + requires prefix.is_prefix_of(whole), + model::transition_ids(whole) == model::transition_ids(prefix) + suffix, + ensures model::transition_ids(whole.subrange(prefix.len() as int, whole.len() as int)) == suffix, + { + let tail = whole.subrange(prefix.len() as int, whole.len() as int); + assert(model::transition_ids(whole).len() == whole.len()); + assert(model::transition_ids(prefix).len() == prefix.len()); + assert((model::transition_ids(prefix) + suffix).len() == prefix.len() + suffix.len()); + assert(tail.len() == suffix.len()); + assert forall|i: int| 0 <= i < suffix.len() implies model::transition_ids(tail)[i] == suffix[i] by { + assert(tail[i] == whole[prefix.len() as int + i]); + assert(model::transition_ids(whole)[prefix.len() as int + i] == suffix[i]); + } + assert(model::transition_ids(tail) =~= suffix); + } + + pub proof fn transition_lemma_regex_combo_push( + g: model::Graph, theta: Subst, values: Seq, value: RegexId, word: Seq, intersect: bool, + ) + ensures regex_combo(g, theta, values.push(value), word, intersect) + == if intersect { + regex_combo(g, theta, values, word, true) && model::regex_lang(g, theta, value@, word) + } else { + regex_combo(g, theta, values, word, false) || model::regex_lang(g, theta, value@, word) + }, + { + if intersect { + if regex_combo(g, theta, values.push(value), word, true) { + assert(model::regex_lang(g, theta, values.push(value)[values.len() as int]@, word)); + assert forall|i: int| 0 <= i < values.len() implies model::regex_lang(g, theta, values[i]@, word) by { + assert(values.push(value)[i] == values[i]); + } + } + if regex_combo(g, theta, values, word, true) && model::regex_lang(g, theta, value@, word) { + assert forall|i: int| 0 <= i < values.push(value).len() implies + model::regex_lang(g, theta, values.push(value)[i]@, word) by { + if i < values.len() { assert(values.push(value)[i] == values[i]); } + else { assert(i == values.len()); } + } + } + } else { + if regex_combo(g, theta, values.push(value), word, false) { + let i = choose|i: int| 0 <= i < values.push(value).len() + && model::regex_lang(g, theta, values.push(value)[i]@, word); + if i < values.len() { + assert(values.push(value)[i] == values[i]); + assert(regex_combo(g, theta, values, word, false)); + } else { assert(i == values.len()); } + } + if regex_combo(g, theta, values, word, false) { + let i = choose|i: int| 0 <= i < values.len() && model::regex_lang(g, theta, values[i]@, word); + assert(model::regex_lang(g, theta, values.push(value)[i]@, word)); + assert(regex_combo(g, theta, values.push(value), word, false)); + } + if model::regex_lang(g, theta, value@, word) { + assert(model::regex_lang(g, theta, values.push(value)[values.len() as int]@, word)); + assert(regex_combo(g, theta, values.push(value), word, false)); + } + } + } + + #[verifier::opaque] + pub open spec fn test_schedule_extension(g: model::Graph, id: TestId, + base: Seq<(TestId, bool)>, tasks: Seq<(TestId, bool)>) -> bool { + base.is_prefix_of(tasks) + && test_not_schedule(g, id, tasks.subrange(base.len() as int, tasks.len() as int)) + } + + pub proof fn test_lemma_schedule_extension_intro(g: model::Graph, id: TestId, count: nat, + base: Seq<(TestId, bool)>, tasks: Seq<(TestId, bool)>) + requires test_child_count(g, id, count), base.is_prefix_of(tasks), tasks.len() == base.len() + count, + forall|j: int| #![trigger tasks[j]] base.len() <= j < tasks.len() ==> !tasks[j].1, + forall|j: int| 0 <= j < count + ==> #[trigger] tasks[base.len() + j].0@ == test_children(g, id)[count as int - 1 - j], + ensures test_schedule_extension(g, id, base, tasks), + { + reveal(test_schedule_extension); + let suffix = tasks.subrange(base.len() as int, tasks.len() as int); + assert(test_children(g, id).len() == count); + assert forall|i: int| 0 <= i < suffix.len() + implies #[trigger] suffix[i].0@ == test_children(g, id)[suffix.len() as int - 1 - i] && !suffix[i].1 by { + assert(suffix[i] == tasks[base.len() + i]); + assert(tasks[base.len() + i].0@ == test_children(g, id)[count as int - 1 - i]); + assert(!tasks[base.len() + i].1); + } + } + + pub proof fn test_lemma_not_scheduled_extension(g: model::Graph, id: TestId, + pending: Seq<(TestId, bool)>, base: Seq<(TestId, bool)>, tasks: Seq<(TestId, bool)>, values: Seq) + requires base == pending.push((id, true)), test_schedule_extension(g, id, base, tasks), + ensures test_not_effect(g, id, false, pending, values, tasks, values), + { + reveal(test_schedule_extension); + assert(base.len() == pending.len() + 1); + assert(tasks.subrange(base.len() as int, tasks.len() as int) + == tasks.subrange(pending.len() as int + 1, tasks.len() as int)); + match g.tests[id@ as int] { + model::TestNode::And(_) => {}, + model::TestNode::Or(_) => {}, + _ => {}, + } + } + + + pub open spec fn transition_equivalent(g: model::Graph, left: Seq, right: Seq, intersect: bool) -> bool { + forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_combo(g, theta, left, event, word, intersect) + == transition_combo(g, theta, right, event, word, intersect) + } + + pub proof fn transition_combo_extends(before: model::Graph, after: model::Graph, ids: Seq, intersect: bool) + requires model::graph_wf(before), model::graph_extends(before, after), transition_ids_valid(before, ids), + ensures transition_ids_valid(after, ids), + forall|theta: Subst, event: EventView, word: Seq| + transition_combo(before, theta, ids, event, word, intersect) + == transition_combo(after, theta, ids, event, word, intersect), + { + model::lemma_graph_wf_elim(before); + model::lemma_lift_stable_under_extends(before, after); + } + + pub proof fn transition_member_ids_valid(g: model::Graph, source: Seq, target: Seq) + requires transition_ids_valid(g, source), forall|id: TransitionId| target.contains(id) ==> source.contains(id), + ensures transition_ids_valid(g, target), + { + assert forall|i: int| 0 <= i < target.len() implies target[i]@ < g.transitions.len() by { + assert(target.contains(target[i])); + assert(source.contains(target[i])); + let j = choose|j: int| 0 <= j < source.len() && source[j] == target[i]; + } + } + + pub proof fn transition_multiset_members(source: Seq, target: Seq) + requires source.to_multiset() == target.to_multiset(), + ensures forall|id: TransitionId| source.contains(id) == target.contains(id), + { + lemma_multiset_members(source, target); + } + + pub proof fn transition_dedup_strict(sorted: Seq, result: Seq) + requires result == dedup_spec(sorted), + forall|i: int, j: int| 0 <= i < j < sorted.len() ==> !(sorted[i].cmp_spec(&sorted[j]) is Greater), + ensures model::strictly_increasing(model::transition_ids(result)), result.no_duplicates(), + { + assert forall|i: int, j: int| 0 <= i < j < sorted.len() implies sorted[i]@ <= sorted[j]@ by { + assert(!(sorted[i].cmp_spec(&sorted[j]) is Greater)); + } + let key: spec_fn(TransitionId) -> nat = |id: TransitionId| id@; + lemma_dedup_strict::(sorted, key); + assert forall|i: int, j: int| 0 <= i < j < result.len() implies + model::transition_ids(result)[i] < model::transition_ids(result)[j] by { + assert(key(dedup_spec(sorted)[i]) + < key(dedup_spec(sorted)[j])); + } + assert forall|i: int, j: int| 0 <= i < result.len() && 0 <= j < result.len() && i != j + implies result[i] != result[j] by { + if i < j { + assert(model::transition_ids(result)[i] < model::transition_ids(result)[j]); + } else { + assert(model::transition_ids(result)[j] < model::transition_ids(result)[i]); + } + } + } + + pub proof fn transition_combo_members(g: model::Graph, left: Seq, right: Seq, intersect: bool) + requires forall|id: TransitionId| left.contains(id) == right.contains(id), + ensures transition_equivalent(g, left, right, intersect), + { + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies transition_combo(g, theta, left, event, word, intersect) + == transition_combo(g, theta, right, event, word, intersect) by { + lemma_combo_inclusion(left, right, + |id: TransitionId| transition_lang(g, theta, id, event, word), intersect); + lemma_combo_inclusion(right, left, + |id: TransitionId| transition_lang(g, theta, id, event, word), intersect); + } + } + + pub open spec fn transition_collected( + g: model::Graph, original: Seq, flat: Seq, constants: Seq, intersect: bool, + ) -> bool { + forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_combo(g, theta, original, event, word, intersect) + == transition_collect_combo(g, theta, Seq::empty(), flat, constants, event, word, intersect) + } + + pub proof fn transition_lemma_extends_transitive(a: model::Graph, b: model::Graph, c: model::Graph) + requires model::graph_extends(a, b), model::graph_extends(b, c), + ensures model::graph_extends(a, c), + {} + + pub proof fn transition_collected_extends( + before: model::Graph, after: model::Graph, original: Seq, flat: Seq, constants: Seq, intersect: bool, + ) + requires model::graph_wf(before), model::graph_extends(before, after), + transition_ids_valid(before, original), transition_ids_valid(before, flat), regex_ids_valid(before, constants), + transition_collected(before, original, flat, constants, intersect), + ensures transition_ids_valid(after, original), transition_ids_valid(after, flat), regex_ids_valid(after, constants), + transition_collected(after, original, flat, constants, intersect), + { + transition_combo_extends(before, after, original, intersect); + transition_combo_extends(before, after, flat, intersect); + regex_combo_extends(before, after, constants, intersect); + } + + pub proof fn transition_lemma_group_result( + g: model::Graph, original: Seq, flat: Seq, constants: Seq, mode: TransitionModeModel, grouped: TransitionId, + ) + requires model::graph_wf(g), transition_mode_valid(g, mode), + transition_collected(g, original, flat, constants, mode.intersect), + forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_lang(g, theta, grouped, event, word) == regex_combo(g, theta, constants, word, mode.intersect), + ensures + transition_equivalent(g, original, flat.push(grouped), mode.intersect), + grouped == mode.identity ==> transition_equivalent(g, original, flat, mode.intersect), + grouped == mode.absorber ==> forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_combo(g, theta, original, event, word, mode.intersect) + == transition_lang(g, theta, mode.absorber, event, word), + { + hide(transition_lang); + hide(transition_combo); + hide(regex_combo); + transition_lemma_identities(g, mode); + assert(flat + seq![grouped] =~= flat.push(grouped)); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies transition_combo(g, theta, original, event, word, mode.intersect) + == transition_combo(g, theta, flat.push(grouped), event, word, mode.intersect) by { + transition_lemma_combo_concat(g, theta, flat, seq![grouped], event, word, mode.intersect); + transition_lemma_singleton_combo(g, grouped, theta, event, word, mode.intersect); + transition_lemma_empty_combos(g, theta, event, word, mode.intersect); + assert(transition_combo(g, theta, original, event, word, mode.intersect) + == transition_collect_combo(g, theta, Seq::empty(), flat, constants, event, word, mode.intersect)); + assert(transition_lang(g, theta, grouped, event, word) + == regex_combo(g, theta, constants, word, mode.intersect)); + } + if grouped == mode.identity { + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies transition_combo(g, theta, original, event, word, mode.intersect) + == transition_combo(g, theta, flat, event, word, mode.intersect) by { + transition_lemma_combo_concat(g, theta, flat, seq![grouped], event, word, mode.intersect); + transition_lemma_singleton_combo(g, grouped, theta, event, word, mode.intersect); + assert(transition_combo(g, theta, original, event, word, mode.intersect) + == transition_combo(g, theta, flat.push(grouped), event, word, mode.intersect)); + assert(transition_lang(g, theta, grouped, event, word) == mode.intersect); + } + } + } + + pub proof fn transition_lemma_set_result(g: model::Graph, ids: Seq, original: Seq, intersect: bool) + requires transition_equivalent(g, ids, original, intersect), + ensures forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> (ids.len() == 0 ==> transition_combo(g, theta, original, event, word, intersect) == intersect) + && (ids.len() == 1 ==> transition_combo(g, theta, original, event, word, intersect) + == transition_lang(g, theta, ids[0], event, word)), + { + if ids.len() == 1 { assert(ids =~= seq![ids[0]]); } + } + + pub proof fn transition_equivalence_extends( + before: model::Graph, after: model::Graph, original: Seq, current: Seq, intersect: bool, + ) + requires model::graph_wf(before), model::graph_extends(before, after), + transition_ids_valid(before, original), transition_ids_valid(before, current), + transition_equivalent(before, original, current, intersect), + ensures transition_equivalent(after, original, current, intersect), + { + transition_combo_extends(before, after, original, intersect); + transition_combo_extends(before, after, current, intersect); + } + + pub proof fn transition_equivalence_future( + g: model::Graph, original: Seq, current: Seq, intersect: bool, + ) + requires model::graph_wf(g), transition_ids_valid(g, original), transition_ids_valid(g, current), + transition_equivalent(g, original, current, intersect), + ensures forall|next: model::Graph| model::graph_extends(g, next) + ==> transition_equivalent(next, original, current, intersect), + { + assert forall|next: model::Graph| model::graph_extends(g, next) + implies transition_equivalent(next, original, current, intersect) by { + transition_equivalence_extends(g, next, original, current, intersect); + } + } + + pub proof fn transition_set_law(ids: Seq, intersect: bool) + ensures forall|g: model::Graph, theta: Subst, event: EventView, word: Seq| + language::numeric_lang(model::gsem(theta), language::interp_transition(model::gsem(theta), event, + transition_unbounded_node(g, if intersect { model::TransitionNode::Intersect(model::transition_ids(ids)) } + else { model::TransitionNode::Union(model::transition_ids(ids)) })), word) + == transition_combo(g, theta, ids, event, word, intersect), + { + assert forall|g: model::Graph, theta: Subst, event: EventView, word: Seq| + language::numeric_lang(model::gsem(theta), language::interp_transition(model::gsem(theta), event, + transition_unbounded_node(g, if intersect { model::TransitionNode::Intersect(model::transition_ids(ids)) } + else { model::TransitionNode::Union(model::transition_ids(ids)) })), word) + == transition_combo(g, theta, ids, event, word, intersect) by { + let sem = model::gsem(theta); + let terms = model::transition_ids(ids).map(|i: int, id: nat| model::lift_transition(g, id)); + assert forall|i: int| 0 <= i < ids.len() implies + language::numeric_lang(sem, language::interp_transition(sem, event, terms[i]), word) + == transition_lang(g, theta, ids[i], event, word) by { + assert(terms[i] == model::lift_transition(g, ids[i]@)); + } + if intersect { + language::lemma_interp_intersect(sem, event, terms, word); + } else { + language::lemma_interp_union(sem, event, terms, word); + if exists|i: int| 0 <= i < terms.len() + && language::numeric_lang(sem, language::interp_transition(sem, event, terms[i]), word) { + let i = choose|i: int| 0 <= i < terms.len() + && language::numeric_lang(sem, language::interp_transition(sem, event, terms[i]), word); + assert(transition_lang(g, theta, ids[i], event, word)); + } + if transition_combo(g, theta, ids, event, word, false) { + let i = choose|i: int| 0 <= i < ids.len() && transition_lang(g, theta, ids[i], event, word); + assert(language::numeric_lang(sem, language::interp_transition(sem, event, terms[i]), word)); + } + } + } + } + + + pub open spec fn transition_child_action_valid(g: model::Graph, action: ChildShape) -> bool { + match action { + ChildShape::Clean(path) => path < g.tests.len(), + ChildShape::Not => true, + ChildShape::Append(suffix) => suffix < g.regexes.len(), + ChildShape::PairLeft(other) => other < g.transitions.len(), + ChildShape::PairRight(other) => other < g.transitions.len(), + } + } + + pub open spec fn transition_child_shape(action: ChildShape, child: nat) -> ActionShape { + match action { + ChildShape::Clean(path) => ActionShape::Clean(child, path), + ChildShape::Not => ActionShape::Not(child), + ChildShape::Append(suffix) => ActionShape::Append(child, suffix), + ChildShape::PairLeft(other) => ActionShape::Pair(child, other), + ChildShape::PairRight(other) => ActionShape::Pair(other, child), + } + } + + pub open spec fn transition_child_actions(g: model::Graph, id: nat, action: ChildShape) -> Seq { + transition_children(g, id).reverse().map(|i: int, child: nat| transition_child_shape(action, child)) + } + + pub proof fn transition_lemma_child_action_valid(g: model::Graph, action: ChildShape, child: nat) + requires transition_child_action_valid(g, action), child < g.transitions.len(), + ensures transition_action_valid(g, transition_child_shape(action, child)), + {} + + pub proof fn transition_lemma_empty_combos( + g: model::Graph, theta: Subst, event: EventView, word: Seq, intersect: bool, + ) + ensures transition_combo(g, theta, Seq::empty(), event, word, intersect) == intersect, + regex_combo(g, theta, Seq::empty(), word, intersect) == intersect, + {} + + + pub proof fn transition_lemma_singleton_combo( + g: model::Graph, id: TransitionId, theta: Subst, event: EventView, word: Seq, intersect: bool, + ) + ensures transition_combo(g, theta, seq![id], event, word, intersect) + == transition_lang(g, theta, id, event, word), + { + hide(transition_lang); + if intersect { + if transition_combo(g, theta, seq![id], event, word, true) { + assert(transition_lang(g, theta, seq![id][0], event, word)); + } + if transition_lang(g, theta, id, event, word) { + assert forall|i: int| 0 <= i < 1 implies transition_lang(g, theta, seq![id][i], event, word) by { assert(i == 0); } + } + } else { + if transition_combo(g, theta, seq![id], event, word, false) { + let i = choose|i: int| 0 <= i < 1 && transition_lang(g, theta, seq![id][i], event, word); + assert(i == 0); + } + if transition_lang(g, theta, id, event, word) { + assert(transition_lang(g, theta, seq![id][0], event, word)); + } + } + } + + pub proof fn transition_lemma_initial_collection( + g: model::Graph, mode: TransitionModeModel, original: Seq, + pending: Seq, flat: Seq, constants: Seq, collapsed: bool, + ) + requires model::graph_wf(g), transition_mode_valid(g, mode), + transition_collect_effect(g, mode, original, Seq::empty(), Seq::empty(), pending, flat, constants, collapsed), + !collapsed ==> pending.len() == 0, + ensures + !collapsed ==> transition_collected(g, original, flat, constants, mode.intersect), + collapsed ==> forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_combo(g, theta, original, event, word, mode.intersect) + == transition_lang(g, theta, mode.absorber, event, word), + { + hide(transition_lang); + hide(transition_combo); + hide(regex_combo); + transition_lemma_identities(g, mode); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies transition_combo(g, theta, original, event, word, mode.intersect) + == if collapsed { transition_lang(g, theta, mode.absorber, event, word) } + else { transition_collect_combo(g, theta, Seq::empty(), flat, constants, event, word, mode.intersect) } by { + transition_lemma_empty_combos(g, theta, event, word, mode.intersect); + assert(transition_collect_combo(g, theta, original, Seq::empty(), Seq::empty(), event, word, mode.intersect) + == if collapsed { !mode.intersect } else { + transition_collect_combo(g, theta, pending, flat, constants, event, word, mode.intersect) + }); + if !collapsed { assert(pending =~= Seq::::empty()); } + } + } + + + pub proof fn transition_action_views_push>(tasks: Seq, task: T) + ensures transition_action_views(tasks.push(task)) == transition_action_views(tasks).push(task@), + { + assert(transition_action_views(tasks.push(task)) =~= transition_action_views(tasks).push(task@)); + } + + pub proof fn transition_lemma_child_actions_valid(g: model::Graph, id: nat, action: ChildShape) + requires model::graph_wf(g), id < g.transitions.len(), transition_child_action_valid(g, action), + ensures transition_tasks_valid(g, transition_child_actions(g, id, action)), + { + transition_lemma_children(g, id); + assert forall|i: int| 0 <= i < transition_child_actions(g, id, action).len() implies + transition_action_valid(g, transition_child_actions(g, id, action)[i]) by { + let child = transition_children(g, id).reverse()[i]; + assert(child < g.transitions.len()); + transition_lemma_child_action_valid(g, action, child); + } + } + + + pub open spec fn guarded_action_pushes(action: GuardedAction) -> bool { + match action { + GuardedAction::Clean(_, _) | GuardedAction::Not(_) | GuardedAction::Append(_, _) | GuardedAction::Pair(_, _) => true, + GuardedAction::Fold(_, index) => index == 0, + _ => false, + } + } + + pub open spec fn guarded_atomic_value( + sem: spec_fn(C, L, EventView) -> bool, action: GuardedAction, + ) -> Option> { + match guarded_apply(sem, action, Seq::empty()) { + Some(values) => if values.len() == 1 { Some(values[0]) } else { None }, + None => None, + } + } + + pub open spec fn guarded_atomic_values( + sem: spec_fn(C, L, EventView) -> bool, actions: Seq>, + ) -> Seq> { + actions.map(|i: int, action: GuardedAction| guarded_atomic_value(sem, action).unwrap()) + } + + pub proof fn guarded_lemma_apply_push( + sem: spec_fn(C, L, EventView) -> bool, action: GuardedAction, values: Seq>, + ) + requires guarded_action_pushes(action), + ensures guarded_atomic_value(sem, action) is Some, + guarded_apply(sem, action, values) == Some(values.push(guarded_atomic_value(sem, action).unwrap())), + { + match action { + GuardedAction::Clean(_, _) => {}, + GuardedAction::Not(_) => {}, + GuardedAction::Append(_, _) => {}, + GuardedAction::Pair(_, _) => {}, + GuardedAction::Fold(_, index) => {}, + _ => {}, + } + } + + pub proof fn guarded_lemma_push_sequence( + sem: spec_fn(C, L, EventView) -> bool, actions: Seq>, values: Seq>, + ) + requires forall|i: int| 0 <= i < actions.len() ==> guarded_action_pushes(actions[i]), + ensures guarded_run(sem, actions.reverse(), values) == Some(values + guarded_atomic_values(sem, actions)), + decreases actions.len(), + { + if actions.len() > 0 { + let first = actions[0]; + let rest = actions.skip(1); + guarded_lemma_apply_push(sem, first, values); + let value = guarded_atomic_value(sem, first).unwrap(); + assert(actions.reverse().last() == first); + assert(actions.reverse().drop_last() =~= rest.reverse()); + guarded_lemma_push_sequence(sem, rest, values.push(value)); + assert(guarded_atomic_values(sem, actions) =~= seq![value] + guarded_atomic_values(sem, rest)); + assert(values.push(value) + guarded_atomic_values(sem, rest) =~= values + guarded_atomic_values(sem, actions)); + } else { + assert(actions.reverse() =~= Seq::>::empty()); + assert(guarded_atomic_values(sem, actions) =~= Seq::>::empty()); + } + } + + pub proof fn guarded_lemma_same_term( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, + before: GuardedTransition, after: GuardedTransition, + ) + requires before.term == after.term, + forall|ctx: C, event: EventView| valid(ctx) && #[trigger] (before.guard)(ctx, event) ==> (after.guard)(ctx, event), + ensures guarded_refines(sem, valid, before, after), + {} + + pub proof fn guarded_lemma_clean_set( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, + terms: Seq>, path: L, intersect: bool, + ) + ensures guarded_refines(sem, valid, + guarded_clean(sem, path, if intersect { language::Transition::Intersect(terms) } else { language::Transition::Union(terms) }), + guarded_set(guarded_atomic_values(sem, terms.map(|i: int, term: language::Transition| GuardedAction::Clean(term, path))), intersect)), + { + let actions = terms.map(|i: int, term: language::Transition| GuardedAction::Clean(term, path)); + let values = guarded_atomic_values(sem, actions); + assert(values.map(|i: int, value: GuardedTransition| value.term) =~= terms); + let before = guarded_clean(sem, path, + if intersect { language::Transition::Intersect(terms) } else { language::Transition::Union(terms) }); + let after = guarded_set(values, intersect); + assert forall|ctx: C, event: EventView| valid(ctx) && #[trigger] (before.guard)(ctx, event) + implies (after.guard)(ctx, event) by { + assert forall|i: int| 0 <= i < values.len() implies (values[i].guard)(ctx, event) by { + assert(values[i] == guarded_clean(sem, path, terms[i])); + } + } + guarded_lemma_same_term(sem, valid, before, after); + } + + pub proof fn guarded_lemma_apply_set_suffix( + sem: spec_fn(C, L, EventView) -> bool, prefix: Seq>, values: Seq>, intersect: bool, + ) + ensures guarded_apply(sem, if intersect { GuardedAction::Intersect(values.len()) } else { GuardedAction::Union(values.len()) }, + prefix + values) == Some(prefix.push(guarded_set(values, intersect))), + { + assert((prefix + values).take(prefix.len() as int) =~= prefix); + assert((prefix + values).subrange(prefix.len() as int, (prefix + values).len() as int) =~= values); + } + + + pub open spec fn transition_action_pushes(task: ActionShape) -> bool { + match task { + ActionShape::Clean(_, _) | ActionShape::Not(_) | ActionShape::Append(_, _) | ActionShape::Pair(_, _) => true, + ActionShape::Fold(_, index) => index == 0, + _ => false, + } + } + + pub open spec fn transition_result(g: model::Graph, task: ActionShape, id: TransitionId) -> bool { + match transition_initial_value(g, task) { + Some(expected) => forall|theta: Subst, event: EventView, word: Seq| + language::event_wf(theta, theta.len()) && (expected.guard)(TransitionContext { bindings: theta }, event) + ==> guarded_language(transition_context_sem(), TransitionContext { bindings: theta }, event, expected, word) + == transition_lang(g, theta, id, event, word), + None => false, + } + } + + pub proof fn transition_lemma_known_push(g: model::Graph, values: Seq, id: TransitionId) + ensures transition_known_values(g, values.push(id)) == transition_known_values(g, values).push(transition_known(g, id)), + { + assert(transition_known_values(g, values.push(id)) =~= transition_known_values(g, values).push(transition_known(g, id))); + } + + pub proof fn transition_lemma_result_refines(g: model::Graph, task: ActionShape, id: TransitionId) + requires transition_result(g, task, id), + ensures transition_initial_value(g, task) matches Some(expected) + && guarded_refines(transition_context_sem(), transition_context_valid(), expected, transition_known(g, id)), + { + let expected = transition_initial_value(g, task).unwrap(); + assert forall|ctx: TransitionContext, event: EventView| transition_context_valid()(ctx) + && #[trigger] (expected.guard)(ctx, event) + implies (transition_known(g, id).guard)(ctx, event) && forall|word: Seq| + guarded_language(transition_context_sem(), ctx, event, expected, word) + == guarded_language(transition_context_sem(), ctx, event, transition_known(g, id), word) by { + assert(ctx == (TransitionContext { bindings: ctx.bindings })); + assert forall|word: Seq| guarded_language(transition_context_sem(), ctx, event, expected, word) + == guarded_language(transition_context_sem(), ctx, event, transition_known(g, id), word) by { + transition_lemma_known_language(g, id, ctx, event, word); + assert(guarded_language(transition_context_sem(), ctx, event, expected, word) + == transition_lang(g, ctx.bindings, id, event, word)); + } + } + } + + pub proof fn transition_lemma_push_result( + g: model::Graph, task: ActionShape, pending: Seq, prior: Seq, id: TransitionId, + ) + requires transition_action_pushes(task), transition_result(g, task, id), + ensures transition_effect(g, task, pending, prior, pending, prior.push(id)), + { + transition_lemma_result_refines(g, task, id); + let expected = transition_initial_value(g, task).unwrap(); + let known = transition_known_values(g, prior); + guarded_lemma_stack_refl(transition_context_sem(), transition_context_valid(), known); + guarded_lemma_stack_push(transition_context_sem(), transition_context_valid(), known, known, expected, transition_known(g, id)); + transition_lemma_known_push(g, prior, id); + match task { + ActionShape::Clean(_, _) => {}, + ActionShape::Not(_) => {}, + ActionShape::Append(_, _) => {}, + ActionShape::Pair(_, _) => {}, + ActionShape::Fold(_, index) => {}, + _ => {}, + } + } + + pub proof fn transition_lemma_clean_children_effect( + g: model::Graph, id: TransitionId, path: TestId, intersect: bool, base: Seq, + ) + requires model::graph_wf(g), id@ < g.transitions.len(), path@ < g.tests.len(), + match g.transitions[id@ as int] { + model::TransitionNode::Union(ids) => !intersect, + model::TransitionNode::Intersect(ids) => intersect, + _ => false, + }, + ensures forall|prior: Seq| #[trigger] transition_effect(g, ActionShape::Clean(id@, path@), base, prior, + transition_clean_child_tasks(g, id, path, intersect, base), prior), + { + transition_unfold(g, id@); + transition_lemma_children(g, id@); + let sem = transition_context_sem(); + let valid = transition_context_valid(); + let children = transition_children(g, id@); + let terms = children.map(|i: int, child: nat| model::lift_transition(g, child)); + let path_term = model::lift_test(g, path@); + let actions = terms.map(|i: int, term: language::Transition| GuardedAction::Clean(term, path_term)); + let count = children.len(); + let set_shape = if intersect { ActionShape::Intersect(count) } else { ActionShape::Union(count) }; + let set_action = if intersect { GuardedAction::Intersect(count) } else { GuardedAction::Union(count) }; + let suffix = transition_child_actions(g, id@, ChildShape::Clean(path@)); + assert(transition_freeze_tasks(g, suffix) =~= actions.reverse()); + let values = guarded_atomic_values(sem, actions); + guarded_lemma_clean_set(sem, valid, terms, path_term, intersect); + assert forall|prior: Seq| #[trigger] transition_effect(g, ActionShape::Clean(id@, path@), base, prior, + transition_clean_child_tasks(g, id, path, intersect, base), prior) by { + let known = transition_known_values(g, prior); + guarded_lemma_push_sequence(sem, actions, known); + guarded_lemma_run_prefix(sem, seq![set_action], actions.reverse(), known); + guarded_lemma_run_singleton(sem, set_action, known + values); + guarded_lemma_apply_set_suffix(sem, known, values, intersect); + let expected = guarded_clean(sem, path_term, model::lift_transition(g, id@)); + let result = guarded_set(values, intersect); + guarded_lemma_stack_refl(sem, valid, known); + guarded_lemma_stack_push(sem, valid, known, known, expected, result); + let tasks = base.push(set_shape) + suffix; + assert(tasks.subrange(base.len() as int, tasks.len() as int) =~= seq![set_shape] + suffix); + assert(transition_freeze_tasks(g, seq![set_shape] + suffix) =~= seq![set_action] + actions.reverse()); + } + } + + + pub open spec fn transition_clean_child_tasks( + g: model::Graph, id: TransitionId, path: TestId, intersect: bool, base: Seq, + ) -> Seq { + base.push(if intersect { ActionShape::Intersect(transition_children(g, id@).len()) } + else { ActionShape::Union(transition_children(g, id@).len()) }) + + transition_child_actions(g, id@, ChildShape::Clean(path@)) + } + + + pub open spec fn transition_configuration_valid(g: model::Graph, tasks: Seq, values: Seq) -> bool { + transition_tasks_valid(g, tasks) && transition_ids_valid(g, values) + } + + + pub proof fn transition_lemma_refines_result(g: model::Graph, task: ActionShape, id: TransitionId) + requires transition_initial_value(g, task) matches Some(expected) + && guarded_refines(transition_context_sem(), transition_context_valid(), expected, transition_known(g, id)), + ensures transition_result(g, task, id), + { + let expected = transition_initial_value(g, task).unwrap(); + assert forall|theta: Subst, event: EventView, word: Seq| + language::event_wf(theta, theta.len()) && (expected.guard)(TransitionContext { bindings: theta }, event) + implies #[trigger] guarded_language(transition_context_sem(), TransitionContext { bindings: theta }, event, expected, word) + == transition_lang(g, theta, id, event, word) by { + let ctx = TransitionContext { bindings: theta }; + transition_lemma_known_language(g, id, ctx, event, word); + assert(guarded_language(transition_context_sem(), ctx, event, expected, word) + == guarded_language(transition_context_sem(), ctx, event, transition_known(g, id), word)); + } + } + + pub proof fn transition_lemma_result_same_term(g: model::Graph, task: ActionShape, id: TransitionId) + requires transition_initial_value(g, task) matches Some(expected) + && expected.term == model::lift_transition(g, id@), + ensures transition_result(g, task, id), + { + let expected = transition_initial_value(g, task).unwrap(); + guarded_lemma_same_term(transition_context_sem(), transition_context_valid(), expected, transition_known(g, id)); + transition_lemma_refines_result(g, task, id); + } + + pub proof fn transition_lemma_clean_identity(g: model::Graph, id: TransitionId, path: TestId) + ensures transition_result(g, ActionShape::Clean(id@, path@), id), + { + transition_lemma_result_same_term(g, ActionShape::Clean(id@, path@), id); + } + + + + pub open spec fn guarded_clean_branch( + sem: spec_fn(C, L, EventView) -> bool, test: L, path: L, yes: L, no: L, + left: language::Transition, right: language::Transition, yes_false: bool, no_false: bool, + ) -> GuardedTransition { + if yes_false { guarded_clean(sem, no, right) } + else if no_false { guarded_clean(sem, yes, left) } + else { guarded_if(sem, test, guarded_clean(sem, yes, left), guarded_clean(sem, no, right)) } + } + + pub proof fn guarded_lemma_clean_branches( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, test: L, path: L, yes: L, no: L, + left: language::Transition, right: language::Transition, yes_false: bool, no_false: bool, + ) + requires + forall|ctx: C, event: EventView| valid(ctx) ==> #[trigger] sem(ctx, yes, event) == (sem(ctx, path, event) && sem(ctx, test, event)), + forall|ctx: C, event: EventView| valid(ctx) ==> #[trigger] sem(ctx, no, event) == (sem(ctx, path, event) && !sem(ctx, test, event)), + yes_false ==> forall|ctx: C, event: EventView| valid(ctx) ==> #[trigger] sem(ctx, yes, event) == false, + no_false ==> forall|ctx: C, event: EventView| valid(ctx) ==> #[trigger] sem(ctx, no, event) == false, + ensures guarded_refines(sem, valid, + guarded_clean(sem, path, language::Transition::If(test, Box::new(left), Box::new(right))), + guarded_clean_branch(sem, test, path, yes, no, left, right, yes_false, no_false)), + { + let before = guarded_clean(sem, path, language::Transition::If(test, Box::new(left), Box::new(right))); + let after = guarded_clean_branch(sem, test, path, yes, no, left, right, yes_false, no_false); + assert forall|ctx: C, event: EventView| valid(ctx) && #[trigger] (before.guard)(ctx, event) + implies (after.guard)(ctx, event) && forall|word: Seq| + guarded_language(sem, ctx, event, before, word) == guarded_language(sem, ctx, event, after, word) by { + assert(sem(ctx, path, event)); + assert(sem(ctx, yes, event) == sem(ctx, test, event)); + assert(sem(ctx, no, event) == !sem(ctx, test, event)); + if yes_false { assert(!sem(ctx, test, event)); } + else if no_false { assert(sem(ctx, test, event)); } + assert forall|word: Seq| guarded_language(sem, ctx, event, before, word) + == guarded_language(sem, ctx, event, after, word) by { + let context_sem = guarded_semantics(sem, ctx); + language::lemma_interp_if(context_sem, event, test, left, right); + if !yes_false && !no_false { + language::lemma_interp_if(context_sem, event, test, left, right); + } + } + } + } + + pub open spec fn guarded_clean_branch_tasks( + test: L, yes: L, no: L, left: language::Transition, right: language::Transition, yes_false: bool, no_false: bool, + ) -> Seq> { + if yes_false { seq![GuardedAction::Clean(right, no)] } + else if no_false { seq![GuardedAction::Clean(left, yes)] } + else { seq![GuardedAction::If(test), GuardedAction::Clean(right, no), GuardedAction::Clean(left, yes)] } + } + + pub proof fn guarded_lemma_clean_branch_run( + sem: spec_fn(C, L, EventView) -> bool, test: L, path: L, yes: L, no: L, + left: language::Transition, right: language::Transition, yes_false: bool, no_false: bool, + prefix: Seq>, + ) + ensures guarded_run(sem, guarded_clean_branch_tasks(test, yes, no, left, right, yes_false, no_false), prefix) + == Some(prefix.push(guarded_clean_branch(sem, test, path, yes, no, left, right, yes_false, no_false))), + { + reveal_with_fuel(guarded_run, 5); + if !yes_false && !no_false { + let a = guarded_clean(sem, yes, left); + let b = guarded_clean(sem, no, right); + assert(prefix.push(a).push(b).take(prefix.len() as int) =~= prefix); + } + } + + + pub proof fn transition_test_not_extends(before: model::Graph, after: model::Graph, root: TestId, negated: TestId) + requires model::graph_wf(before), model::graph_extends(before, after), root@ < before.tests.len(), negated@ < before.tests.len(), + forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + ==> model::test_holds(theta, model::lift_test(before, negated@), event) + == !model::test_holds(theta, model::lift_test(before, root@), event), + ensures forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + ==> model::test_holds(theta, model::lift_test(after, negated@), event) + == !model::test_holds(theta, model::lift_test(after, root@), event), + { + hide(model::test_holds); + model::lemma_graph_wf_elim(before); + model::lemma_lift_stable_under_extends(before, after); + } + + pub proof fn transition_lemma_test_pair( + g: model::Graph, theta: Subst, left: TestId, right: TestId, event: EventView, + ) + ensures test_combo(g, theta, seq![left, right], event, true) + == (model::test_holds(theta, model::lift_test(g, left@), event) + && model::test_holds(theta, model::lift_test(g, right@), event)), + { + hide(model::test_holds); + if test_combo(g, theta, seq![left, right], event, true) { + assert(model::test_holds(theta, model::lift_test(g, seq![left, right][0]@), event)); + assert(model::test_holds(theta, model::lift_test(g, seq![left, right][1]@), event)); + } + if model::test_holds(theta, model::lift_test(g, left@), event) + && model::test_holds(theta, model::lift_test(g, right@), event) { + assert forall|i: int| 0 <= i < 2 implies + model::test_holds(theta, model::lift_test(g, seq![left, right][i]@), event) by { + if i == 0 {} else { assert(i == 1); } + } + } + } + + pub proof fn transition_lemma_test_constants(g: model::Graph) + requires model::graph_wf(g), + ensures forall|theta: Subst, event: EventView| + model::test_holds(theta, model::lift_test(g, g.constants.test_true), event) + && !model::test_holds(theta, model::lift_test(g, g.constants.test_false), event), + { + assert(model::constants_wf(g)) by { model::lemma_graph_wf_elim(g); } + assert(model::lift_test(g, g.constants.test_true) == model::Test::True); + assert(model::lift_test(g, g.constants.test_false) == model::Test::False); + } + + pub open spec fn transition_path_tests(g: model::Graph, path: TestId, test: TestId, yes: TestId, no: TestId) -> bool { + forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) ==> + (model::test_holds(theta, model::lift_test(g, yes@), event) + == (model::test_holds(theta, model::lift_test(g, path@), event) + && model::test_holds(theta, model::lift_test(g, test@), event))) + && (model::test_holds(theta, model::lift_test(g, no@), event) + == (model::test_holds(theta, model::lift_test(g, path@), event) + && !model::test_holds(theta, model::lift_test(g, test@), event))) + } + + pub open spec fn transition_clean_if_tasks( + g: model::Graph, test: TestId, left: TransitionId, right: TransitionId, yes: TestId, no: TestId, base: Seq, + ) -> Seq { + if yes@ == g.constants.test_false { base.push(ActionShape::Clean(right@, no@)) } + else if no@ == g.constants.test_false { base.push(ActionShape::Clean(left@, yes@)) } + else { base.push(ActionShape::If(test@)).push(ActionShape::Clean(right@, no@)).push(ActionShape::Clean(left@, yes@)) } + } + + pub proof fn transition_lemma_clean_if_effect( + g: model::Graph, id: TransitionId, path: TestId, test: TestId, + left: TransitionId, right: TransitionId, yes: TestId, no: TestId, base: Seq, + ) + requires model::graph_wf(g), id@ < g.transitions.len(), + g.transitions[id@ as int] == model::TransitionNode::If(test@, left@, right@), + transition_path_tests(g, path, test, yes, no), + ensures forall|prior: Seq| #[trigger] transition_effect(g, ActionShape::Clean(id@, path@), base, prior, + transition_clean_if_tasks(g, test, left, right, yes, no, base), prior), + { + transition_unfold(g, id@); + transition_lemma_test_constants(g); + let sem = transition_context_sem(); + let valid = transition_context_valid(); + let condition = model::lift_test(g, test@); + let path_term = model::lift_test(g, path@); + let yes_term = model::lift_test(g, yes@); + let no_term = model::lift_test(g, no@); + let a = model::lift_transition(g, left@); + let b = model::lift_transition(g, right@); + let yes_false = yes@ == g.constants.test_false; + let no_false = no@ == g.constants.test_false; + assert forall|ctx: TransitionContext, event: EventView| valid(ctx) implies + #[trigger] sem(ctx, yes_term, event) == (sem(ctx, path_term, event) && sem(ctx, condition, event)) by { + assert(model::test_holds(ctx.bindings, yes_term, event) + == (model::test_holds(ctx.bindings, path_term, event) + && model::test_holds(ctx.bindings, condition, event))); + } + assert forall|ctx: TransitionContext, event: EventView| valid(ctx) implies + #[trigger] sem(ctx, no_term, event) == (sem(ctx, path_term, event) && !sem(ctx, condition, event)) by { + assert(model::test_holds(ctx.bindings, no_term, event) + == (model::test_holds(ctx.bindings, path_term, event) + && !model::test_holds(ctx.bindings, condition, event))); + } + guarded_lemma_clean_branches(sem, valid, condition, path_term, yes_term, no_term, a, b, yes_false, no_false); + let expansion = guarded_clean_branch_tasks(condition, yes_term, no_term, a, b, yes_false, no_false); + let next_tasks = transition_clean_if_tasks(g, test, left, right, yes, no, base); + assert(transition_freeze_tasks(g, next_tasks.subrange(base.len() as int, next_tasks.len() as int)) =~= expansion); + assert forall|prior: Seq| #[trigger] transition_effect(g, ActionShape::Clean(id@, path@), base, prior, + next_tasks, prior) by { + let known = transition_known_values(g, prior); + guarded_lemma_clean_branch_run(sem, condition, path_term, yes_term, no_term, a, b, yes_false, no_false, known); + guarded_lemma_stack_refl(sem, valid, known); + guarded_lemma_stack_push(sem, valid, known, known, + guarded_clean(sem, path_term, model::lift_transition(g, id@)), + guarded_clean_branch(sem, condition, path_term, yes_term, no_term, a, b, yes_false, no_false)); + } + } + + pub proof fn transition_configuration_extends( + before: model::Graph, after: model::Graph, tasks: Seq, values: Seq, + ) + requires model::graph_wf(before), model::graph_extends(before, after), transition_configuration_valid(before, tasks, values), + ensures transition_configuration_valid(after, tasks, values), + { + assert forall|i: int| 0 <= i < tasks.len() implies transition_action_valid(after, tasks[i]) by { + transition_lemma_action_stable(before, after, tasks[i]); + } + } + + pub proof fn transition_configuration_future(g: model::Graph, tasks: Seq, values: Seq) + requires model::graph_wf(g), transition_configuration_valid(g, tasks, values), + ensures forall|next: model::Graph| model::graph_extends(g, next) ==> transition_configuration_valid(next, tasks, values), + { + assert forall|next: model::Graph| model::graph_extends(g, next) implies transition_configuration_valid(next, tasks, values) by { + transition_configuration_extends(g, next, tasks, values); + } + } + + + pub proof fn machine_pair_binary_language( + sem: spec_fn(L, EventView) -> bool, event: EventView, + a: language::Transition, b: language::Transition, word: Seq, + ) + ensures language::numeric_lang(sem, language::interp_transition(sem, event, + language::Transition::Intersect(seq![a, b])), word) + == (language::numeric_lang(sem, language::interp_transition(sem, event, a), word) + && language::numeric_lang(sem, language::interp_transition(sem, event, b), word)), + { + language::lemma_interp_intersect(sem, event, seq![a, b], word); + assert((forall|i: int| 0 <= i < 2 ==> language::numeric_lang(sem, + language::interp_transition(sem, event, seq![a, b][i]), word)) + == (language::numeric_lang(sem, language::interp_transition(sem, event, a), word) + && language::numeric_lang(sem, language::interp_transition(sem, event, b), word))) by { + assert forall|i: int| 0 <= i < 2 implies language::numeric_lang(sem, + language::interp_transition(sem, event, seq![a, b][i]), word) + == if i == 0 { language::numeric_lang(sem, language::interp_transition(sem, event, a), word) } + else { language::numeric_lang(sem, language::interp_transition(sem, event, b), word) } by {} + } + } + + pub proof fn machine_pair_effect_intro( + g: model::Graph, task: ActionShape, pending: Seq, prior: Seq, + expansion: Seq, values: Seq, result: TransitionMeaning, + ) + requires transition_action_pushes(task), + guarded_run(transition_context_sem(), transition_freeze_tasks(g, expansion), transition_known_values(g, values)) + == Some(transition_known_values(g, prior).push(result)), + guarded_refines(transition_context_sem(), transition_context_valid(), + transition_initial_value(g, task).unwrap(), result), + ensures transition_effect(g, task, pending, prior, pending + expansion, values), + { + let sem = transition_context_sem(); + let valid = transition_context_valid(); + let known = transition_known_values(g, prior); + guarded_lemma_apply_push(sem, transition_freeze_action(g, task), known); + assert(guarded_atomic_value(sem, transition_freeze_action(g, task)) == transition_initial_value(g, task)); + guarded_lemma_stack_refl(sem, valid, known); + guarded_lemma_stack_push(sem, valid, known, known, transition_initial_value(g, task).unwrap(), result); + assert((pending + expansion).subrange(pending.len() as int, (pending + expansion).len() as int) =~= expansion); + } + + pub proof fn machine_pair_set_result( + g: model::Graph, ids: Seq, task: ActionShape, out: TransitionId, + ) + requires task == ActionShape::Fold(model::transition_ids(ids), 0) + || (ids.len() == 2 && task == ActionShape::Pair(ids[0]@, ids[1]@)), + forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_lang(g, theta, out, event, word) + == transition_combo(g, theta, ids, event, word, true), + ensures transition_result(g, task, out), + { + let terms = model::transition_ids(ids).map(|i: int, id: nat| model::lift_transition(g, id)); + let expected = transition_initial_value(g, task).unwrap(); + if ids.len() == 2 && task == ActionShape::Pair(ids[0]@, ids[1]@) { + assert(terms =~= seq![model::lift_transition(g, ids[0]@), model::lift_transition(g, ids[1]@)]); + } + assert(expected.term == language::Transition::Intersect(terms)); + assert forall|theta: Subst, event: EventView, word: Seq| + language::event_wf(theta, theta.len()) && (expected.guard)(TransitionContext { bindings: theta }, event) + implies guarded_language(transition_context_sem(), TransitionContext { bindings: theta }, event, expected, word) + == transition_lang(g, theta, out, event, word) by { + let ctx = TransitionContext { bindings: theta }; + transition_lemma_context_sem(ctx); + language::lemma_interp_intersect(model::gsem(theta), event, terms, word); + assert forall|i: int| 0 <= i < ids.len() implies + language::numeric_lang(model::gsem(theta), language::interp_transition(model::gsem(theta), event, terms[i]), word) + == transition_lang(g, theta, ids[i], event, word) by { + assert(terms[i] == model::lift_transition(g, ids[i]@)); + } + assert(transition_lang(g, theta, out, event, word) + == transition_combo(g, theta, ids, event, word, true)); + } + } + + pub proof fn machine_pair_identity_result( + g: model::Graph, a: TransitionId, b: TransitionId, out: TransitionId, all: TransitionId, empty: TransitionId, + ) + requires model::graph_wf(g), all@ == g.constants.transition_all, empty@ == g.constants.transition_empty, + (a == b && out == a) + || (b@ == g.constants.transition_all && out == a) + || (a@ == g.constants.transition_all && out == b) + || ((a@ == g.constants.transition_empty || b@ == g.constants.transition_empty) + && out@ == g.constants.transition_empty), + ensures transition_result(g, ActionShape::Pair(a@, b@), out), + { + // Expose only constants; full table facts unfold irrelevant recursive semantics. + assert(model::constants_wf(g)) by { model::lemma_graph_wf_elim(g); } + transition_lemma_identities(g, TransitionModeModel { intersect: true, identity: all, absorber: empty }); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies transition_lang(g, theta, out, event, word) + == transition_combo(g, theta, seq![a, b], event, word, true) by { + assert(transition_lang(g, theta, all, event, word)); + assert(!transition_lang(g, theta, empty, event, word)); + } + machine_pair_set_result(g, seq![a, b], ActionShape::Pair(a@, b@), out); + } + + pub proof fn machine_pair_if_run( + sem: spec_fn(C, L, EventView) -> bool, test: L, path: L, + at: language::Transition, bt: language::Transition, + ae: language::Transition, be: language::Transition, prefix: Seq>, + ) + ensures guarded_run(sem, seq![GuardedAction::CleanIf(test, path), GuardedAction::Pair(ae, be), GuardedAction::Pair(at, bt)], prefix) + == Some(prefix.push(guarded_clean_if(sem, test, path, + guarded_constant(language::Transition::Intersect(seq![at, bt])), + guarded_constant(language::Transition::Intersect(seq![ae, be]))))), + { + reveal_with_fuel(guarded_run, 5); + let yes = guarded_constant(language::Transition::Intersect(seq![at, bt])); + let no = guarded_constant(language::Transition::Intersect(seq![ae, be])); + assert(prefix.push(yes).push(no).take(prefix.len() as int) =~= prefix); + } + + pub proof fn machine_pair_if_refines( + g: model::Graph, a: TransitionId, b: TransitionId, test: TestId, + at: TransitionId, bt: TransitionId, ae: TransitionId, be: TransitionId, + ) + requires model::graph_wf(g), + forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> (transition_lang(g, theta, a, event, word) && transition_lang(g, theta, b, event, word)) + == if model::test_holds(theta, model::lift_test(g, test@), event) { + transition_lang(g, theta, at, event, word) && transition_lang(g, theta, bt, event, word) + } else { transition_lang(g, theta, ae, event, word) && transition_lang(g, theta, be, event, word) }, + ensures guarded_refines(transition_context_sem(), transition_context_valid(), + transition_initial_value(g, ActionShape::Pair(a@, b@)).unwrap(), + guarded_clean_if(transition_context_sem(), model::lift_test(g, test@), model::lift_test(g, g.constants.test_true), + guarded_constant(language::Transition::Intersect(seq![model::lift_transition(g, at@), model::lift_transition(g, bt@)])), + guarded_constant(language::Transition::Intersect(seq![model::lift_transition(g, ae@), model::lift_transition(g, be@)])))), + { + // Expose only constants; full table facts unfold irrelevant recursive semantics. + assert(model::constants_wf(g)) by { model::lemma_graph_wf_elim(g); } + let before = transition_initial_value(g, ActionShape::Pair(a@, b@)).unwrap(); + let yes = guarded_constant(language::Transition::Intersect(seq![model::lift_transition(g, at@), model::lift_transition(g, bt@)])); + let no = guarded_constant(language::Transition::Intersect(seq![model::lift_transition(g, ae@), model::lift_transition(g, be@)])); + let after = guarded_clean_if(transition_context_sem(), model::lift_test(g, test@), model::lift_test(g, g.constants.test_true), yes, no); + assert forall|ctx: TransitionContext, event: EventView| transition_context_valid()(ctx) && #[trigger] (before.guard)(ctx, event) + implies (after.guard)(ctx, event) && forall|word: Seq| + guarded_language(transition_context_sem(), ctx, event, before, word) + == guarded_language(transition_context_sem(), ctx, event, after, word) by { + transition_lemma_context_sem(ctx); + assert forall|word: Seq| guarded_language(transition_context_sem(), ctx, event, before, word) + == guarded_language(transition_context_sem(), ctx, event, after, word) by { + let sem = model::gsem(ctx.bindings); + machine_pair_binary_language(sem, event, model::lift_transition(g, a@), model::lift_transition(g, b@), word); + machine_pair_binary_language(sem, event, model::lift_transition(g, at@), model::lift_transition(g, bt@), word); + machine_pair_binary_language(sem, event, model::lift_transition(g, ae@), model::lift_transition(g, be@), word); + language::lemma_interp_if(sem, event, model::lift_test(g, test@), yes.term, no.term); + assert((transition_lang(g, ctx.bindings, a, event, word) + && transition_lang(g, ctx.bindings, b, event, word)) + == if model::test_holds(ctx.bindings, model::lift_test(g, test@), event) { + transition_lang(g, ctx.bindings, at, event, word) && transition_lang(g, ctx.bindings, bt, event, word) + } else { transition_lang(g, ctx.bindings, ae, event, word) && transition_lang(g, ctx.bindings, be, event, word) }); + } + } + } + + pub proof fn machine_pair_if_effect( + g: model::Graph, a: TransitionId, b: TransitionId, test: TestId, + at: TransitionId, bt: TransitionId, ae: TransitionId, be: TransitionId, + pending: Seq, prior: Seq, + ) + requires model::graph_wf(g), + forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> (transition_lang(g, theta, a, event, word) && transition_lang(g, theta, b, event, word)) + == if model::test_holds(theta, model::lift_test(g, test@), event) { + transition_lang(g, theta, at, event, word) && transition_lang(g, theta, bt, event, word) + } else { transition_lang(g, theta, ae, event, word) && transition_lang(g, theta, be, event, word) }, + ensures transition_effect(g, ActionShape::Pair(a@, b@), pending, prior, + pending.push(ActionShape::CleanIf(test@, g.constants.test_true)) + .push(ActionShape::Pair(ae@, be@)).push(ActionShape::Pair(at@, bt@)), prior), + { + let expansion = seq![ActionShape::CleanIf(test@, g.constants.test_true), ActionShape::Pair(ae@, be@), ActionShape::Pair(at@, bt@)]; + machine_pair_if_run(transition_context_sem(), model::lift_test(g, test@), model::lift_test(g, g.constants.test_true), + model::lift_transition(g, at@), model::lift_transition(g, bt@), model::lift_transition(g, ae@), model::lift_transition(g, be@), transition_known_values(g, prior)); + assert(transition_freeze_tasks(g, expansion) =~= seq![GuardedAction::CleanIf(model::lift_test(g, test@), model::lift_test(g, g.constants.test_true)), + GuardedAction::Pair(model::lift_transition(g, ae@), model::lift_transition(g, be@)), + GuardedAction::Pair(model::lift_transition(g, at@), model::lift_transition(g, bt@))]); + machine_pair_if_refines(g, a, b, test, at, bt, ae, be); + let result = guarded_clean_if(transition_context_sem(), model::lift_test(g, test@), model::lift_test(g, g.constants.test_true), + guarded_constant(language::Transition::Intersect(seq![model::lift_transition(g, at@), model::lift_transition(g, bt@)])), + guarded_constant(language::Transition::Intersect(seq![model::lift_transition(g, ae@), model::lift_transition(g, be@)]))); + machine_pair_effect_intro(g, ActionShape::Pair(a@, b@), pending, prior, expansion, prior, result); + assert(pending + expansion =~= pending.push(expansion[0]).push(expansion[1]).push(expansion[2])); + } + + pub proof fn machine_pair_if_language( + g: model::Graph, id: TransitionId, test: TestId, yes: TransitionId, no: TransitionId, + ) + requires model::graph_wf(g), id@ < g.transitions.len(), + g.transitions[id@ as int] == model::TransitionNode::If(test@, yes@, no@), + ensures forall|theta: Subst, event: EventView, word: Seq| + transition_lang(g, theta, id, event, word) + == if model::test_holds(theta, model::lift_test(g, test@), event) { + transition_lang(g, theta, yes, event, word) + } else { transition_lang(g, theta, no, event, word) }, + { + transition_unfold(g, id@); + assert forall|theta: Subst, event: EventView, word: Seq| + transition_lang(g, theta, id, event, word) + == if model::test_holds(theta, model::lift_test(g, test@), event) { + transition_lang(g, theta, yes, event, word) + } else { transition_lang(g, theta, no, event, word) } by { + language::lemma_interp_if(model::gsem(theta), event, model::lift_test(g, test@), + model::lift_transition(g, yes@), model::lift_transition(g, no@)); + } + } + + pub proof fn machine_pair_empty_run( + sem: spec_fn(C, L, EventView) -> bool, test: L, path: L, + a: language::Transition, b: language::Transition, empty: GuardedTransition, + prefix: Seq>, + ) + ensures guarded_run(sem, seq![GuardedAction::CleanIf(test, path), GuardedAction::SwapThen, GuardedAction::Pair(a, b)], prefix.push(empty)) + == Some(prefix.push(guarded_clean_if(sem, test, path, + guarded_constant(language::Transition::Intersect(seq![a, b])), empty))), + { + reveal_with_fuel(guarded_run, 5); + let pair = guarded_constant(language::Transition::Intersect(seq![a, b])); + assert(prefix.push(empty).push(pair).take(prefix.len() as int) =~= prefix); + assert(prefix.push(pair).push(empty).take(prefix.len() as int) =~= prefix); + } + + pub proof fn machine_pair_empty_effect( + g: model::Graph, a: TransitionId, b: TransitionId, xt: TransitionId, yt: TransitionId, + guard: TestId, empty: TransitionId, pending: Seq, prior: Seq, + ) + requires model::graph_wf(g), empty@ == g.constants.transition_empty, + forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> (transition_lang(g, theta, a, event, word) && transition_lang(g, theta, b, event, word)) + == (model::test_holds(theta, model::lift_test(g, guard@), event) + && transition_lang(g, theta, xt, event, word) && transition_lang(g, theta, yt, event, word)), + ensures transition_effect(g, ActionShape::Pair(a@, b@), pending, prior, + pending.push(ActionShape::CleanIf(guard@, g.constants.test_true)).push(ActionShape::SwapThen) + .push(ActionShape::Pair(xt@, yt@)), prior.push(empty)), + { + // Expose only constants; full table facts unfold irrelevant recursive semantics. + assert(model::constants_wf(g)) by { model::lemma_graph_wf_elim(g); } + transition_unfold(g, empty@); + regex_unfold(g, g.constants.empty); + let sem = transition_context_sem(); + let valid = transition_context_valid(); + let yes = guarded_constant(language::Transition::Intersect(seq![model::lift_transition(g, xt@), model::lift_transition(g, yt@)])); + let no = transition_known(g, empty); + let result = guarded_clean_if(sem, model::lift_test(g, guard@), model::lift_test(g, g.constants.test_true), yes, no); + let expected = transition_initial_value(g, ActionShape::Pair(a@, b@)).unwrap(); + assert forall|ctx: TransitionContext, event: EventView| valid(ctx) && #[trigger] (expected.guard)(ctx, event) + implies (result.guard)(ctx, event) && forall|word: Seq| + guarded_language(sem, ctx, event, expected, word) == guarded_language(sem, ctx, event, result, word) by { + transition_lemma_context_sem(ctx); + assert forall|word: Seq| guarded_language(sem, ctx, event, expected, word) + == guarded_language(sem, ctx, event, result, word) by { + let context_sem = model::gsem(ctx.bindings); + machine_pair_binary_language(context_sem, event, model::lift_transition(g, a@), model::lift_transition(g, b@), word); + machine_pair_binary_language(context_sem, event, model::lift_transition(g, xt@), model::lift_transition(g, yt@), word); + language::lemma_interp_if(context_sem, event, model::lift_test(g, guard@), yes.term, no.term); + language::lemma_interp_const(context_sem, event, language::Regex::Empty); + assert((transition_lang(g, ctx.bindings, a, event, word) + && transition_lang(g, ctx.bindings, b, event, word)) + == (model::test_holds(ctx.bindings, model::lift_test(g, guard@), event) + && transition_lang(g, ctx.bindings, xt, event, word) + && transition_lang(g, ctx.bindings, yt, event, word))); + } + } + let expansion = seq![ActionShape::CleanIf(guard@, g.constants.test_true), ActionShape::SwapThen, ActionShape::Pair(xt@, yt@)]; + assert(transition_freeze_tasks(g, expansion) =~= seq![GuardedAction::CleanIf(model::lift_test(g, guard@), model::lift_test(g, g.constants.test_true)), + GuardedAction::SwapThen, GuardedAction::Pair(model::lift_transition(g, xt@), model::lift_transition(g, yt@))]); + transition_lemma_known_push(g, prior, empty); + machine_pair_empty_run(sem, model::lift_test(g, guard@), model::lift_test(g, g.constants.test_true), + model::lift_transition(g, xt@), model::lift_transition(g, yt@), no, transition_known_values(g, prior)); + machine_pair_effect_intro(g, ActionShape::Pair(a@, b@), pending, prior, expansion, prior.push(empty), result); + assert(pending + expansion =~= pending.push(expansion[0]).push(expansion[1]).push(expansion[2])); + } + + pub proof fn machine_pair_fold_noop( + g: model::Graph, ids: Seq, index: nat, pending: Seq, prior: Seq, + ) + requires index > 0, index >= ids.len(), + ensures transition_effect(g, ActionShape::Fold(model::transition_ids(ids), index), pending, prior, pending, prior), + { + guarded_lemma_stack_refl(transition_context_sem(), transition_context_valid(), transition_known_values(g, prior)); + assert(pending.subrange(pending.len() as int, pending.len() as int) =~= Seq::::empty()); + assert(transition_freeze_tasks(g, Seq::empty()) =~= Seq::::empty()); + } + + #[verifier::spinoff_prover] + pub proof fn machine_pair_union_effect( + g: model::Graph, a: TransitionId, b: TransitionId, left: bool, + pending: Seq, prior: Seq, + ) + requires model::graph_wf(g), a@ < g.transitions.len(), b@ < g.transitions.len(), + match g.transitions[(if left { a@ } else { b@ }) as int] { model::TransitionNode::Union(_) => true, _ => false }, + ensures transition_effect(g, ActionShape::Pair(a@, b@), pending, prior, + pending.push(ActionShape::Union(transition_children(g, if left { a@ } else { b@ }).len())) + + transition_child_actions(g, if left { a@ } else { b@ }, + if left { ChildShape::PairLeft(b@) } else { ChildShape::PairRight(a@) }), prior), + { + hide(language::event_wf); + hide(model::test_holds); + hide(model::lift_regex); + hide(model::lift_transition); + hide(language::numeric_lang); + hide(language::interp_transition); + let root = if left { a } else { b }; + transition_unfold(g, root@); + transition_lemma_children(g, root@); + let children = transition_children(g, root@); + let terms = children.map(|i: int, child: nat| model::lift_transition(g, child)); + let actions = children.map(|i: int, child: nat| if left { + GuardedAction::Pair(model::lift_transition(g, child), model::lift_transition(g, b@)) + } else { GuardedAction::Pair(model::lift_transition(g, a@), model::lift_transition(g, child)) }); + let sem = transition_context_sem(); + let valid = transition_context_valid(); + let values = guarded_atomic_values(sem, actions); + let expected = transition_initial_value(g, ActionShape::Pair(a@, b@)).unwrap(); + let result = guarded_set(values, false); + assert forall|ctx: TransitionContext, event: EventView| valid(ctx) && #[trigger] (expected.guard)(ctx, event) + implies (result.guard)(ctx, event) && forall|word: Seq| + guarded_language(sem, ctx, event, expected, word) == guarded_language(sem, ctx, event, result, word) by { + assert forall|i: int| 0 <= i < values.len() implies (values[i].guard)(ctx, event) by { + assert(actions[i] == if left { + GuardedAction::Pair(terms[i], model::lift_transition(g, b@)) + } else { GuardedAction::Pair(model::lift_transition(g, a@), terms[i]) }); + } + transition_lemma_context_sem(ctx); + assert forall|word: Seq| guarded_language(sem, ctx, event, expected, word) + == guarded_language(sem, ctx, event, result, word) by { + let context_sem = model::gsem(ctx.bindings); + let outputs = values.map(|i: int, value: TransitionMeaning| value.term); + machine_pair_binary_language(context_sem, event, model::lift_transition(g, a@), model::lift_transition(g, b@), word); + language::lemma_interp_union(context_sem, event, terms, word); + language::lemma_interp_union(context_sem, event, outputs, word); + assert forall|i: int| 0 <= i < children.len() implies + language::numeric_lang(context_sem, language::interp_transition(context_sem, event, outputs[i]), word) + == if left { + language::numeric_lang(context_sem, language::interp_transition(context_sem, event, terms[i]), word) + && transition_lang(g, ctx.bindings, b, event, word) + } else { transition_lang(g, ctx.bindings, a, event, word) + && language::numeric_lang(context_sem, language::interp_transition(context_sem, event, terms[i]), word) } by { + if left { machine_pair_binary_language(context_sem, event, terms[i], model::lift_transition(g, b@), word); } + else { machine_pair_binary_language(context_sem, event, model::lift_transition(g, a@), terms[i], word); } + } + if guarded_language(sem, ctx, event, expected, word) { + let i = choose|i: int| 0 <= i < terms.len() + && language::numeric_lang(context_sem, language::interp_transition(context_sem, event, terms[i]), word); + assert(language::numeric_lang(context_sem, language::interp_transition(context_sem, event, outputs[i]), word)); + } + if guarded_language(sem, ctx, event, result, word) { + let i = choose|i: int| 0 <= i < outputs.len() + && language::numeric_lang(context_sem, language::interp_transition(context_sem, event, outputs[i]), word); + assert(language::numeric_lang(context_sem, language::interp_transition(context_sem, event, terms[i]), word)); + assert(language::numeric_lang(context_sem, language::interp_transition(context_sem, event, language::Transition::Union(terms)), word)); + } + } + } + let suffix = transition_child_actions(g, root@, if left { ChildShape::PairLeft(b@) } else { ChildShape::PairRight(a@) }); + assert(transition_freeze_tasks(g, suffix) =~= actions.reverse()); + guarded_lemma_push_sequence(sem, actions, transition_known_values(g, prior)); + guarded_lemma_run_prefix(sem, seq![GuardedAction::Union(children.len())], actions.reverse(), transition_known_values(g, prior)); + guarded_lemma_run_singleton(sem, GuardedAction::Union(children.len()), transition_known_values(g, prior) + values); + guarded_lemma_apply_set_suffix(sem, transition_known_values(g, prior), values, false); + let expansion = seq![ActionShape::Union(children.len())] + suffix; + assert(transition_freeze_tasks(g, expansion) =~= seq![GuardedAction::Union(children.len())] + actions.reverse()); + machine_pair_effect_intro(g, ActionShape::Pair(a@, b@), pending, prior, expansion, prior, result); + assert(pending + expansion =~= pending.push(ActionShape::Union(children.len())) + suffix); + } + + pub proof fn machine_pair_fold_schedule( + sem: spec_fn(C, L, EventView) -> bool, valid: spec_fn(C) -> bool, + terms: Seq>, index: nat, head: language::Transition, prefix: Seq>, + ) + requires 0 < index < terms.len(), + ensures guarded_program_refines(sem, valid, + guarded_apply(sem, GuardedAction::Fold(terms, index), prefix.push(guarded_constant(head))), + guarded_run(sem, seq![GuardedAction::Fold(terms, index + 1), GuardedAction::Pair(head, terms[index as int])], prefix)), + { + reveal_with_fuel(guarded_run, 4); + let remaining = terms.subrange(index as int, terms.len() as int).map(|i: int, term: language::Transition| guarded_constant(term)); + let later = terms.subrange(index as int + 1, terms.len() as int).map(|i: int, term: language::Transition| guarded_constant(term)); + let pair = guarded_constant(language::Transition::Intersect(seq![head, terms[index as int]])); + let before = guarded_set(seq![guarded_constant(head)] + remaining, true); + let after = if index + 1 < terms.len() { guarded_set(seq![pair] + later, true) } else { pair }; + assert(prefix.push(guarded_constant(head)).drop_last() =~= prefix); + assert(prefix.push(pair).drop_last() =~= prefix); + assert forall|ctx: C, event: EventView| valid(ctx) && #[trigger] (before.guard)(ctx, event) + implies (after.guard)(ctx, event) && forall|word: Seq| + guarded_language(sem, ctx, event, before, word) == guarded_language(sem, ctx, event, after, word) by { + assert forall|i: int| 0 <= i < later.len() implies (later[i].guard)(ctx, event) by {}; + assert forall|word: Seq| guarded_language(sem, ctx, event, before, word) + == guarded_language(sem, ctx, event, after, word) by { + let context_sem = guarded_semantics(sem, ctx); + let bs = (seq![guarded_constant(head)] + remaining).map(|i: int, value: GuardedTransition| value.term); + let ats = (seq![pair] + later).map(|i: int, value: GuardedTransition| value.term); + language::lemma_interp_intersect(context_sem, event, bs, word); + if index + 1 < terms.len() { language::lemma_interp_intersect(context_sem, event, ats, word); } + machine_pair_binary_language(context_sem, event, head, terms[index as int], word); + if guarded_language(sem, ctx, event, before, word) { + assert(language::numeric_lang(context_sem, language::interp_transition(context_sem, event, bs[0]), word)); + assert(language::numeric_lang(context_sem, language::interp_transition(context_sem, event, bs[1]), word)); + assert forall|i: int| 0 <= i < ats.len() implies + language::numeric_lang(context_sem, language::interp_transition(context_sem, event, ats[i]), word) by { + if i > 0 { + assert(ats[i] == bs[i + 1]); + assert(language::numeric_lang(context_sem, language::interp_transition(context_sem, event, bs[i + 1]), word)); + } + } + } + if guarded_language(sem, ctx, event, after, word) { + if index + 1 < terms.len() { + assert(after.term == language::Transition::Intersect(ats)); + assert(language::numeric_lang(context_sem, language::interp_transition(context_sem, event, ats[0]), word)); + assert(ats[0] == pair.term); + } + assert(language::numeric_lang(context_sem, language::interp_transition(context_sem, event, pair.term), word)); + assert forall|i: int| 0 <= i < bs.len() implies + language::numeric_lang(context_sem, language::interp_transition(context_sem, event, bs[i]), word) by { + if i > 1 { + assert(index + 1 < terms.len()); + assert(bs[i] == ats[i - 1]); + assert(language::numeric_lang(context_sem, language::interp_transition(context_sem, event, ats[i - 1]), word)); + } + } + } + } + } + guarded_lemma_stack_refl(sem, valid, prefix); + guarded_lemma_stack_push(sem, valid, prefix, prefix, before, after); + } + + pub proof fn machine_pair_fold_next_effect( + g: model::Graph, ids: Seq, index: nat, pending: Seq, prior: Seq, + ) + requires 0 < index < ids.len(), prior.len() > 0, + ensures transition_effect(g, ActionShape::Fold(model::transition_ids(ids), index), pending, prior, + pending.push(ActionShape::Fold(model::transition_ids(ids), index + 1)) + .push(ActionShape::Pair(prior.last()@, ids[index as int]@)), prior.drop_last()), + { + let terms = model::transition_ids(ids).map(|i: int, id: nat| model::lift_transition(g, id)); + let expansion = seq![ActionShape::Fold(model::transition_ids(ids), index + 1), ActionShape::Pair(prior.last()@, ids[index as int]@)]; + let prefix = transition_known_values(g, prior.drop_last()); + assert(transition_known_values(g, prior) =~= prefix.push(transition_known(g, prior.last()))); + assert(transition_freeze_tasks(g, expansion) =~= seq![GuardedAction::Fold(terms, index + 1), + GuardedAction::Pair(model::lift_transition(g, prior.last()@), terms[index as int])]); + machine_pair_fold_schedule(transition_context_sem(), transition_context_valid(), terms, index, + model::lift_transition(g, prior.last()@), prefix); + assert(pending.push(expansion[0]).push(expansion[1]) =~= pending + expansion); + assert((pending + expansion).subrange(pending.len() as int, (pending + expansion).len() as int) =~= expansion); + } + + pub proof fn machine_pair_fold_first_run( + sem: spec_fn(C, L, EventView) -> bool, terms: Seq>, prefix: Seq>, + ) + requires terms.len() > 0, + ensures guarded_run(sem, seq![GuardedAction::Fold(terms, 1)], prefix.push(guarded_constant(terms[0]))) + == Some(prefix.push(if terms.len() == 1 { guarded_constant(terms[0]) } else { + guarded_set(terms.map(|i: int, term: language::Transition| guarded_constant(term)), true) })), + { + guarded_lemma_run_singleton(sem, GuardedAction::Fold(terms, 1), prefix.push(guarded_constant(terms[0]))); + if terms.len() > 1 { + assert(seq![guarded_constant::(terms[0])] + terms.subrange(1, terms.len() as int) + .map(|i: int, term: language::Transition| guarded_constant::(term)) + =~= terms.map(|i: int, term: language::Transition| guarded_constant::(term))); + assert(prefix.push(guarded_constant(terms[0])).drop_last() =~= prefix); + } + } + + pub proof fn machine_pair_fold_first_effect( + g: model::Graph, ids: Seq, children: Seq, pending: Seq, prior: Seq, + ) + requires children.len() > 0, + forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_combo(g, theta, ids, event, word, true) + == transition_combo(g, theta, children, event, word, true), + ensures transition_effect(g, ActionShape::Fold(model::transition_ids(ids), 0), pending, prior, + pending.push(ActionShape::Fold(model::transition_ids(children), 1)), prior.push(children[0])), + { + let sem = transition_context_sem(); + let valid = transition_context_valid(); + let terms = model::transition_ids(children).map(|i: int, id: nat| model::lift_transition(g, id)); + let expected = transition_initial_value(g, ActionShape::Fold(model::transition_ids(ids), 0)).unwrap(); + let result = if terms.len() == 1 { guarded_constant(terms[0]) } else { + guarded_set(terms.map(|i: int, term: language::Transition| guarded_constant(term)), true) }; + let input_terms = model::transition_ids(ids).map(|i: int, id: nat| model::lift_transition(g, id)); + assert forall|ctx: TransitionContext, event: EventView| valid(ctx) && #[trigger] (expected.guard)(ctx, event) + implies (result.guard)(ctx, event) && forall|word: Seq| + guarded_language(sem, ctx, event, expected, word) == guarded_language(sem, ctx, event, result, word) by { + transition_lemma_context_sem(ctx); + assert forall|i: int| 0 <= i < terms.len() implies + (guarded_constant::(terms[i]).guard)(ctx, event) by {}; + assert forall|word: Seq| guarded_language(sem, ctx, event, expected, word) + == guarded_language(sem, ctx, event, result, word) by { + let context_sem = model::gsem(ctx.bindings); + language::lemma_interp_intersect(context_sem, event, input_terms, word); + if terms.len() != 1 { + assert(terms.map(|i: int, term: language::Transition| guarded_constant::(term)) + .map(|i: int, value: TransitionMeaning| value.term) =~= terms); + assert(result.term == language::Transition::Intersect(terms)); + language::lemma_interp_intersect(context_sem, event, terms, word); + } + assert forall|i: int| 0 <= i < ids.len() implies + language::numeric_lang(context_sem, language::interp_transition(context_sem, event, input_terms[i]), word) + == transition_lang(g, ctx.bindings, ids[i], event, word) by {}; + assert forall|i: int| 0 <= i < children.len() implies + language::numeric_lang(context_sem, language::interp_transition(context_sem, event, terms[i]), word) + == transition_lang(g, ctx.bindings, children[i], event, word) by {}; + assert(transition_combo(g, ctx.bindings, ids, event, word, true) + == transition_combo(g, ctx.bindings, children, event, word, true)); + } + } + let expansion = seq![ActionShape::Fold(model::transition_ids(children), 1)]; + assert(transition_freeze_tasks(g, expansion) =~= seq![GuardedAction::Fold(terms, 1)]); + transition_lemma_known_push(g, prior, children[0]); + machine_pair_fold_first_run(sem, terms, transition_known_values(g, prior)); + machine_pair_effect_intro(g, ActionShape::Fold(model::transition_ids(ids), 0), pending, prior, + expansion, prior.push(children[0]), result); + assert(pending + expansion =~= pending.push(expansion[0])); + } + + pub proof fn machine_pair_empty_branches( + g: model::Graph, a: TransitionId, b: TransitionId, x: TestId, xt: TransitionId, + y: TestId, yt: TransitionId, empty: TransitionId, guard: TestId, + ) + requires model::graph_wf(g), a@ < g.transitions.len(), b@ < g.transitions.len(), + empty@ == g.constants.transition_empty, + g.transitions[a@ as int] == model::TransitionNode::If(x@, xt@, empty@), + g.transitions[b@ as int] == model::TransitionNode::If(y@, yt@, empty@), + forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + ==> model::test_holds(theta, model::lift_test(g, guard@), event) + == test_combo(g, theta, seq![x, y], event, true), + ensures + forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> (transition_lang(g, theta, a, event, word) && transition_lang(g, theta, b, event, word)) + == (model::test_holds(theta, model::lift_test(g, guard@), event) + && transition_lang(g, theta, xt, event, word) && transition_lang(g, theta, yt, event, word)), + guard@ == g.constants.test_false ==> transition_result(g, ActionShape::Pair(a@, b@), empty), + { + machine_pair_if_language(g, a, x, xt, empty); + machine_pair_if_language(g, b, y, yt, empty); + // Expose only constants; full table facts unfold irrelevant recursive semantics. + assert(model::constants_wf(g)) by { model::lemma_graph_wf_elim(g); } + transition_unfold(g, empty@); + regex_unfold(g, g.constants.empty); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies (transition_lang(g, theta, a, event, word) && transition_lang(g, theta, b, event, word)) + == (model::test_holds(theta, model::lift_test(g, guard@), event) + && transition_lang(g, theta, xt, event, word) && transition_lang(g, theta, yt, event, word)) by { + language::lemma_interp_const(model::gsem(theta), event, language::Regex::Empty); + assert(model::test_holds(theta, model::lift_test(g, guard@), event) + == test_combo(g, theta, seq![x, y], event, true)); + } + if guard@ == g.constants.test_false { + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies transition_lang(g, theta, empty, event, word) + == transition_combo(g, theta, seq![a, b], event, word, true) by { + assert((transition_lang(g, theta, a, event, word) && transition_lang(g, theta, b, event, word)) + == (model::test_holds(theta, model::lift_test(g, guard@), event) + && transition_lang(g, theta, xt, event, word) && transition_lang(g, theta, yt, event, word))); + } + machine_pair_set_result(g, seq![a, b], ActionShape::Pair(a@, b@), empty); + } + } + + + pub proof fn transition_lemma_clean_not_effect( + g: model::Graph, id: TransitionId, path: TestId, inner: TransitionId, base: Seq, + ) + requires model::graph_wf(g), id@ < g.transitions.len(), + g.transitions[id@ as int] == model::TransitionNode::Not(inner@), + ensures forall|prior: Seq| #[trigger] transition_effect(g, ActionShape::Clean(id@, path@), base, prior, + base.push(ActionShape::NotResult).push(ActionShape::Clean(inner@, path@)), prior), + { + transition_unfold(g, id@); + let sem = transition_context_sem(); + let valid = transition_context_valid(); + let before = guarded_clean(sem, model::lift_test(g, path@), model::lift_transition(g, id@)); + let after = guarded_not(guarded_clean(sem, model::lift_test(g, path@), model::lift_transition(g, inner@))); + guarded_lemma_same_term(sem, valid, before, after); + assert forall|prior: Seq| #[trigger] transition_effect(g, ActionShape::Clean(id@, path@), base, prior, + base.push(ActionShape::NotResult).push(ActionShape::Clean(inner@, path@)), prior) by { + let known = transition_known_values(g, prior); + guarded_lemma_stack_refl(sem, valid, known); + guarded_lemma_stack_push(sem, valid, known, known, before, after); + let tasks = base.push(ActionShape::NotResult).push(ActionShape::Clean(inner@, path@)); + assert(transition_freeze_tasks(g, tasks.subrange(base.len() as int, tasks.len() as int)) + =~= seq![GuardedAction::NotResult, GuardedAction::Clean(model::lift_transition(g, inner@), model::lift_test(g, path@))]); + reveal_with_fuel(guarded_run, 3); + } + } + + pub proof fn transition_lemma_clean_append_effect( + g: model::Graph, id: TransitionId, path: TestId, inner: TransitionId, + suffix: Seq, combined: RegexId, base: Seq, + ) + requires model::graph_wf(g), id@ < g.transitions.len(), + g.transitions[id@ as int] == model::TransitionNode::Append(inner@, model::regex_ids(suffix)), + forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + ==> model::regex_lang(g, theta, combined@, word) == concat_combo(g, theta, suffix, word), + ensures forall|prior: Seq| #[trigger] transition_effect(g, ActionShape::Clean(id@, path@), base, prior, + base.push(ActionShape::AppendResult(combined@)).push(ActionShape::Clean(inner@, path@)), prior), + { + transition_unfold(g, id@); + let sem = transition_context_sem(); + let valid = transition_context_valid(); + let path_term = model::lift_test(g, path@); + let term = model::lift_transition(g, inner@); + let combined_term = model::lift_regex(g, combined@); + let before = guarded_clean(sem, path_term, model::lift_transition(g, id@)); + let after = guarded_append(guarded_clean(sem, path_term, term), combined_term); + assert forall|ctx: TransitionContext, event: EventView| valid(ctx) && #[trigger] (before.guard)(ctx, event) + implies (after.guard)(ctx, event) && forall|word: Seq| + guarded_language(sem, ctx, event, before, word) == guarded_language(sem, ctx, event, after, word) by { + transition_lemma_context_sem(ctx); + let context_sem = model::gsem(ctx.bindings); + let suffix_terms = model::lift_regexes(g, model::regex_ids(suffix)); + language::lemma_interp_append(context_sem, event, term, suffix_terms); + language::lemma_interp_append(context_sem, event, term, seq![combined_term]); + assert forall|word: Seq| language::numeric_lang(context_sem, language::Regex::Concat(suffix_terms), word) + == language::numeric_lang(context_sem, combined_term, word) by { + assert(model::regex_lang(g, ctx.bindings, combined@, word) + == concat_combo(g, ctx.bindings, suffix, word)); + } + regex_concat_replace(context_sem, seq![language::interp_transition(context_sem, event, term)], suffix_terms, combined_term); + } + assert forall|prior: Seq| #[trigger] transition_effect(g, ActionShape::Clean(id@, path@), base, prior, + base.push(ActionShape::AppendResult(combined@)).push(ActionShape::Clean(inner@, path@)), prior) by { + let known = transition_known_values(g, prior); + guarded_lemma_stack_refl(sem, valid, known); + guarded_lemma_stack_push(sem, valid, known, known, before, after); + let tasks = base.push(ActionShape::AppendResult(combined@)).push(ActionShape::Clean(inner@, path@)); + assert(transition_freeze_tasks(g, tasks.subrange(base.len() as int, tasks.len() as int)) + =~= seq![GuardedAction::AppendResult(combined_term), GuardedAction::Clean(term, path_term)]); + reveal_with_fuel(guarded_run, 3); + } + } + + pub proof fn machine_unary_not_result(g: model::Graph, id: TransitionId, out: TransitionId) + requires forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_lang(g, theta, out, event, word) == !transition_lang(g, theta, id, event, word), + ensures transition_result(g, ActionShape::Not(id@), out), + { + let expected = transition_initial_value(g, ActionShape::Not(id@)).unwrap(); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + && (expected.guard)(TransitionContext { bindings: theta }, event) + implies guarded_language(transition_context_sem(), TransitionContext { bindings: theta }, event, expected, word) + == transition_lang(g, theta, out, event, word) by { + transition_lemma_context_sem(TransitionContext { bindings: theta }); + language::lemma_interp_not(model::gsem(theta), event, model::lift_transition(g, id@)); + } + } + + pub open spec fn machine_unary_append_language( + g: model::Graph, theta: Subst, id: TransitionId, suffix: RegexId, + event: EventView, word: Seq, + ) -> bool { + language::numeric_lang(model::gsem(theta), language::Regex::Concat(seq![ + language::interp_transition(model::gsem(theta), event, model::lift_transition(g, id@)), + model::lift_regex(g, suffix@), + ]), word) + } + + pub proof fn machine_unary_append_result(g: model::Graph, id: TransitionId, suffix: RegexId, out: TransitionId) + requires forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_lang(g, theta, out, event, word) + == machine_unary_append_language(g, theta, id, suffix, event, word), + ensures transition_result(g, ActionShape::Append(id@, suffix@), out), + { + let expected = transition_initial_value(g, ActionShape::Append(id@, suffix@)).unwrap(); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + && (expected.guard)(TransitionContext { bindings: theta }, event) + implies guarded_language(transition_context_sem(), TransitionContext { bindings: theta }, event, expected, word) + == transition_lang(g, theta, out, event, word) by { + transition_lemma_context_sem(TransitionContext { bindings: theta }); + language::lemma_interp_append(model::gsem(theta), event, model::lift_transition(g, id@), seq![model::lift_regex(g, suffix@)]); + assert(seq![language::interp_transition(model::gsem(theta), event, model::lift_transition(g, id@))] + + seq![model::lift_regex(g, suffix@)] =~= seq![ + language::interp_transition(model::gsem(theta), event, model::lift_transition(g, id@)), model::lift_regex(g, suffix@)]); + } + } + + pub proof fn machine_unary_append_identity(sem: spec_fn(L, EventView) -> bool, head: language::Regex, word: Seq) + ensures language::numeric_lang(sem, language::Regex::Concat(seq![head, language::Regex::Epsilon]), word) == language::numeric_lang(sem, head, word), + !language::numeric_lang(sem, language::Regex::Concat(seq![head, language::Regex::Empty]), word), + { + language::lemma_concat_pair(sem, head, language::Regex::Epsilon, word); + language::lemma_concat_pair(sem, head, language::Regex::Empty, word); + if language::numeric_lang(sem, head, word) { + let empty = Seq::::empty(); + assert(word == word + empty); + assert(language::numeric_lang(sem, language::Regex::Epsilon, empty)); + } + } + + pub proof fn machine_unary_append_reassociate( + sem: spec_fn(L, EventView) -> bool, head: language::Regex, suffix: Seq>, last: language::Regex, + ) + ensures forall|word: Seq| language::numeric_lang(sem, + language::Regex::Concat(seq![language::Regex::Concat(seq![head] + suffix), last]), word) + == language::numeric_lang(sem, language::Regex::Concat(seq![head, language::Regex::Concat(suffix.push(last))]), word), + { + let flat = seq![head] + suffix; + assert forall|word: Seq| language::numeric_lang(sem, language::Regex::Concat(seq![language::Regex::Concat(flat)]), word) + == language::numeric_lang(sem, language::Regex::Concat(flat), word) by { + language::lemma_concat_singleton(sem, language::Regex::Concat(flat), word); + } + regex_concat_append_congruent(sem, seq![language::Regex::Concat(flat)], flat, seq![last]); + let tail = suffix.push(last); + regex_concat_replace(sem, seq![head], tail, language::Regex::Concat(tail)); + assert(flat + seq![last] =~= seq![head] + tail); + assert(seq![language::Regex::Concat(flat)] + seq![last] =~= seq![language::Regex::Concat(flat), last]); + assert(seq![head].push(language::Regex::Concat(tail)) =~= seq![head, language::Regex::Concat(tail)]); + assert forall|word: Seq| language::numeric_lang(sem, + language::Regex::Concat(seq![language::Regex::Concat(flat), last]), word) + == language::numeric_lang(sem, language::Regex::Concat(seq![head, language::Regex::Concat(tail)]), word) by { + assert(language::numeric_lang(sem, language::Regex::Concat(seq![language::Regex::Concat(flat)] + seq![last]), word) + == language::numeric_lang(sem, language::Regex::Concat(flat + seq![last]), word)); + assert(language::numeric_lang(sem, language::Regex::Concat(seq![head] + tail), word) + == language::numeric_lang(sem, language::Regex::Concat(seq![head].push(language::Regex::Concat(tail))), word)); + } + } + + pub proof fn machine_unary_demorgan( + sem: spec_fn(L, EventView) -> bool, event: EventView, terms: Seq>, intersect: bool, word: Seq, + ) + ensures language::numeric_lang(sem, language::interp_transition(sem, event, language::Transition::Not(Box::new( + if intersect { language::Transition::Intersect(terms) } else { language::Transition::Union(terms) }))), word) + == language::numeric_lang(sem, language::interp_transition(sem, event, + if intersect { language::Transition::Union(terms.map(|i: int, term: language::Transition| language::Transition::Not(Box::new(term)))) } + else { language::Transition::Intersect(terms.map(|i: int, term: language::Transition| language::Transition::Not(Box::new(term)))) }), word), + { + let negated = terms.map(|i: int, term: language::Transition| language::Transition::Not(Box::new(term))); + assert forall|i: int| 0 <= i < terms.len() implies + language::numeric_lang(sem, language::interp_transition(sem, event, negated[i]), word) + == !language::numeric_lang(sem, language::interp_transition(sem, event, terms[i]), word) by { + language::lemma_interp_not(sem, event, terms[i]); + } + if intersect { + language::lemma_interp_not(sem, event, language::Transition::Intersect(terms)); + language::lemma_interp_intersect(sem, event, terms, word); + language::lemma_interp_union(sem, event, negated, word); + if !(forall|i: int| 0 <= i < terms.len() ==> language::numeric_lang(sem, language::interp_transition(sem, event, terms[i]), word)) { + let i = choose|i: int| 0 <= i < terms.len() && !language::numeric_lang(sem, language::interp_transition(sem, event, terms[i]), word); + assert(language::numeric_lang(sem, language::interp_transition(sem, event, negated[i]), word)); + } + } else { + language::lemma_interp_not(sem, event, language::Transition::Union(terms)); + language::lemma_interp_union(sem, event, terms, word); + language::lemma_interp_intersect(sem, event, negated, word); + if !(exists|i: int| 0 <= i < terms.len() && language::numeric_lang(sem, language::interp_transition(sem, event, terms[i]), word)) { + assert forall|i: int| 0 <= i < terms.len() implies language::numeric_lang(sem, language::interp_transition(sem, event, negated[i]), word) by {} + } + } + } + + pub proof fn machine_unary_append_union( + sem: spec_fn(L, EventView) -> bool, event: EventView, terms: Seq>, suffix: language::Regex, word: Seq, + ) + ensures language::numeric_lang(sem, language::interp_transition(sem, event, + language::Transition::Append(Box::new(language::Transition::Union(terms)), seq![suffix])), word) + == language::numeric_lang(sem, language::interp_transition(sem, event, language::Transition::Union( + terms.map(|i: int, term: language::Transition| language::Transition::Append(Box::new(term), seq![suffix])))), word), + { + let head = language::interp_transition(sem, event, language::Transition::Union(terms)); + let appended = terms.map(|i: int, term: language::Transition| language::Transition::Append(Box::new(term), seq![suffix])); + language::lemma_interp_append(sem, event, language::Transition::Union(terms), seq![suffix]); + assert(seq![head] + seq![suffix] =~= seq![head, suffix]); + language::lemma_concat_pair(sem, head, suffix, word); + language::lemma_interp_union(sem, event, appended, word); + assert forall|i: int| 0 <= i < terms.len() implies + language::numeric_lang(sem, language::interp_transition(sem, event, appended[i]), word) + == (exists|u: Seq, v: Seq| word == u + v + && language::numeric_lang(sem, language::interp_transition(sem, event, terms[i]), u) && language::numeric_lang(sem, suffix, v)) by { + language::lemma_interp_append(sem, event, terms[i], seq![suffix]); + let r = language::interp_transition(sem, event, terms[i]); + assert(seq![r] + seq![suffix] =~= seq![r, suffix]); + language::lemma_concat_pair(sem, r, suffix, word); + } + if language::numeric_lang(sem, language::Regex::Concat(seq![head, suffix]), word) { + let (u, v) = choose|u: Seq, v: Seq| word == u + v && language::numeric_lang(sem, head, u) && language::numeric_lang(sem, suffix, v); + language::lemma_interp_union(sem, event, terms, u); + let i = choose|i: int| 0 <= i < terms.len() && language::numeric_lang(sem, language::interp_transition(sem, event, terms[i]), u); + assert(language::numeric_lang(sem, language::interp_transition(sem, event, appended[i]), word)); + } + if language::numeric_lang(sem, language::interp_transition(sem, event, language::Transition::Union(appended)), word) { + let i = choose|i: int| 0 <= i < appended.len() && language::numeric_lang(sem, language::interp_transition(sem, event, appended[i]), word); + let (u, v) = choose|u: Seq, v: Seq| word == u + v + && language::numeric_lang(sem, language::interp_transition(sem, event, terms[i]), u) && language::numeric_lang(sem, suffix, v); + language::lemma_interp_union(sem, event, terms, u); + assert(language::numeric_lang(sem, head, u)); + assert(language::numeric_lang(sem, language::Regex::Concat(seq![head, suffix]), word)); + } + } + + pub open spec fn machine_unary_child_tasks( + g: model::Graph, id: TransitionId, suffix: Option, intersect: bool, base: Seq, + ) -> Seq { + base.push(if intersect { ActionShape::Intersect(transition_children(g, id@).len()) } + else { ActionShape::Union(transition_children(g, id@).len()) }) + + transition_child_actions(g, id@, match suffix { Some(r) => ChildShape::Append(r@), None => ChildShape::Not }) + } + + pub proof fn machine_unary_children_effect( + g: model::Graph, id: TransitionId, suffix: Option, intersect: bool, base: Seq, prior: Seq, + ) + requires model::graph_wf(g), id@ < g.transitions.len(), + match suffix { + Some(r) => r@ < g.regexes.len() && !intersect && g.transitions[id@ as int] matches model::TransitionNode::Union(_), + None => match g.transitions[id@ as int] { + model::TransitionNode::Union(_) => intersect, + model::TransitionNode::Intersect(_) => !intersect, + _ => false, + }, + }, + ensures transition_effect(g, match suffix { Some(r) => ActionShape::Append(id@, r@), None => ActionShape::Not(id@) }, + base, prior, machine_unary_child_tasks(g, id, suffix, intersect, base), prior), + { + transition_unfold(g, id@); + transition_lemma_children(g, id@); + let sem = transition_context_sem(); + let valid = transition_context_valid(); + let children = transition_children(g, id@); + let terms = children.map(|i: int, child: nat| model::lift_transition(g, child)); + let actions = terms.map(|i: int, term: language::Transition| match suffix { + Some(r) => GuardedAction::Append(term, model::lift_regex(g, r@)), None => GuardedAction::Not(term), + }); + let count = children.len(); + let set_shape = if intersect { ActionShape::Intersect(count) } else { ActionShape::Union(count) }; + let set_action = if intersect { GuardedAction::Intersect(count) } else { GuardedAction::Union(count) }; + let child_shape = match suffix { Some(r) => ChildShape::Append(r@), None => ChildShape::Not }; + let expansion = transition_child_actions(g, id@, child_shape); + assert(transition_freeze_tasks(g, expansion) =~= actions.reverse()); + let mapped = guarded_atomic_values(sem, actions); + let task = match suffix { Some(r) => ActionShape::Append(id@, r@), None => ActionShape::Not(id@) }; + let expected = transition_initial_value(g, task).unwrap(); + let result = guarded_set(mapped, intersect); + assert(result.term == if intersect { language::Transition::Intersect(mapped.map(|i: int, value: TransitionMeaning| value.term)) } + else { language::Transition::Union(mapped.map(|i: int, value: TransitionMeaning| value.term)) }); + assert forall|ctx: TransitionContext, event: EventView| valid(ctx) && #[trigger] (expected.guard)(ctx, event) + implies (result.guard)(ctx, event) && forall|word: Seq| guarded_language(sem, ctx, event, expected, word) + == guarded_language(sem, ctx, event, result, word) by { + assert forall|i: int| 0 <= i < mapped.len() implies (mapped[i].guard)(ctx, event) by { + match suffix { Some(r) => {}, None => {} } + } + let context_sem = guarded_semantics(sem, ctx); + match suffix { + Some(r) => { + assert(mapped.map(|i: int, value: TransitionMeaning| value.term) =~= terms.map(|i: int, term: language::Transition| + language::Transition::Append(Box::new(term), seq![model::lift_regex(g, r@)]))); + assert forall|word: Seq| guarded_language(sem, ctx, event, expected, word) + == guarded_language(sem, ctx, event, result, word) by { + machine_unary_append_union(context_sem, event, terms, model::lift_regex(g, r@), word); + } + }, + None => { + assert(mapped.map(|i: int, value: TransitionMeaning| value.term) =~= terms.map(|i: int, term: language::Transition| + language::Transition::Not(Box::new(term)))); + assert forall|word: Seq| guarded_language(sem, ctx, event, expected, word) + == guarded_language(sem, ctx, event, result, word) by { + machine_unary_demorgan(context_sem, event, terms, !intersect, word); + } + }, + } + } + let known = transition_known_values(g, prior); + guarded_lemma_push_sequence(sem, actions, known); + guarded_lemma_run_prefix(sem, seq![set_action], actions.reverse(), known); + guarded_lemma_run_singleton(sem, set_action, known + mapped); + guarded_lemma_apply_set_suffix(sem, known, mapped, intersect); + guarded_lemma_stack_refl(sem, valid, known); + guarded_lemma_stack_push(sem, valid, known, known, expected, result); + let tasks = machine_unary_child_tasks(g, id, suffix, intersect, base); + assert(tasks.subrange(base.len() as int, tasks.len() as int) =~= seq![set_shape] + expansion); + assert(transition_freeze_tasks(g, seq![set_shape] + expansion) =~= seq![set_action] + actions.reverse()); + } + + pub proof fn machine_unary_replace_effect( + g: model::Graph, task: ActionShape, next: ActionShape, base: Seq, prior: Seq, + ) + requires transition_action_pushes(task), transition_action_pushes(next), + guarded_refines(transition_context_sem(), transition_context_valid(), + transition_initial_value(g, task).unwrap(), transition_initial_value(g, next).unwrap()), + ensures transition_effect(g, task, base, prior, base.push(next), prior), + { + let sem = transition_context_sem(); + let valid = transition_context_valid(); + let known = transition_known_values(g, prior); + guarded_lemma_apply_push(sem, transition_freeze_action(g, task), known); + guarded_lemma_apply_push(sem, transition_freeze_action(g, next), known); + guarded_lemma_run_singleton(sem, transition_freeze_action(g, next), known); + guarded_lemma_stack_refl(sem, valid, known); + guarded_lemma_stack_push(sem, valid, known, known, + transition_initial_value(g, task).unwrap(), transition_initial_value(g, next).unwrap()); + assert(base.push(next).subrange(base.len() as int, base.len() as int + 1) =~= seq![next]); + assert(transition_freeze_tasks(g, seq![next]) =~= seq![transition_freeze_action(g, next)]); + } + + pub proof fn machine_unary_clean_result_effect( + g: model::Graph, task: ActionShape, out: TransitionId, base: Seq, prior: Seq, + ) + requires model::graph_wf(g), transition_action_pushes(task), transition_result(g, task, out), + ensures transition_effect(g, task, base, prior, base.push(ActionShape::Clean(out@, g.constants.test_true)), prior), + { + assert(model::constants_wf(g)) by { model::lemma_graph_wf_elim(g); } + transition_lemma_result_refines(g, task, out); + let sem = transition_context_sem(); + let valid = transition_context_valid(); + let clean = transition_initial_value(g, ActionShape::Clean(out@, g.constants.test_true)).unwrap(); + let known = transition_known(g, out); + assert(model::lift_test(g, g.constants.test_true) == model::Test::True); + assert forall|ctx: TransitionContext, event: EventView| valid(ctx) && #[trigger] (known.guard)(ctx, event) + implies (clean.guard)(ctx, event) by {} + guarded_lemma_same_term(sem, valid, known, clean); + guarded_lemma_refines_transitive(sem, valid, transition_initial_value(g, task).unwrap(), known, clean); + machine_unary_replace_effect(g, task, ActionShape::Clean(out@, g.constants.test_true), base, prior); + } + + pub open spec fn machine_unary_if_tasks( + g: model::Graph, test: TestId, yes: TransitionId, no: TransitionId, suffix: Option, base: Seq, + ) -> Seq { + base.push(ActionShape::CleanIf(test@, g.constants.test_true)) + .push(match suffix { Some(r) => ActionShape::Append(no@, r@), None => ActionShape::Not(no@) }) + .push(match suffix { Some(r) => ActionShape::Append(yes@, r@), None => ActionShape::Not(yes@) }) + } + + pub proof fn machine_unary_if_effect( + g: model::Graph, id: TransitionId, test: TestId, yes: TransitionId, no: TransitionId, + suffix: Option, base: Seq, prior: Seq, + ) + requires model::graph_wf(g), id@ < g.transitions.len(), + g.transitions[id@ as int] == model::TransitionNode::If(test@, yes@, no@), + ensures transition_effect(g, match suffix { Some(r) => ActionShape::Append(id@, r@), None => ActionShape::Not(id@) }, + base, prior, machine_unary_if_tasks(g, test, yes, no, suffix, base), prior), + { + transition_unfold(g, id@); + // Expose only constants; full table facts unfold irrelevant recursive semantics. + assert(model::constants_wf(g)) by { model::lemma_graph_wf_elim(g); } + let sem = transition_context_sem(); + let valid = transition_context_valid(); + let task = match suffix { Some(r) => ActionShape::Append(id@, r@), None => ActionShape::Not(id@) }; + let a = match suffix { Some(r) => ActionShape::Append(yes@, r@), None => ActionShape::Not(yes@) }; + let b = match suffix { Some(r) => ActionShape::Append(no@, r@), None => ActionShape::Not(no@) }; + let av = transition_initial_value(g, a).unwrap(); + let bv = transition_initial_value(g, b).unwrap(); + let expected = transition_initial_value(g, task).unwrap(); + let result = guarded_clean_if(sem, model::lift_test(g, test@), model::lift_test(g, g.constants.test_true), av, bv); + assert(model::lift_test(g, g.constants.test_true) == model::Test::True); + assert forall|ctx: TransitionContext, event: EventView| valid(ctx) && #[trigger] (expected.guard)(ctx, event) + implies (result.guard)(ctx, event) && forall|word: Seq| guarded_language(sem, ctx, event, expected, word) + == guarded_language(sem, ctx, event, result, word) by { + let context_sem = guarded_semantics(sem, ctx); + let test_term = model::lift_test(g, test@); + language::lemma_interp_if(context_sem, event, test_term, av.term, bv.term); + language::lemma_interp_if(context_sem, event, test_term, model::lift_transition(g, yes@), model::lift_transition(g, no@)); + match suffix { + Some(r) => { + language::lemma_interp_append(context_sem, event, model::lift_transition(g, id@), seq![model::lift_regex(g, r@)]); + language::lemma_interp_append(context_sem, event, model::lift_transition(g, yes@), seq![model::lift_regex(g, r@)]); + language::lemma_interp_append(context_sem, event, model::lift_transition(g, no@), seq![model::lift_regex(g, r@)]); + }, + None => { + language::lemma_interp_not(context_sem, event, model::lift_transition(g, id@)); + language::lemma_interp_not(context_sem, event, model::lift_transition(g, yes@)); + language::lemma_interp_not(context_sem, event, model::lift_transition(g, no@)); + }, + } + } + let known = transition_known_values(g, prior); + let expansion = seq![ActionShape::CleanIf(test@, g.constants.test_true), b, a]; + let frozen = transition_freeze_tasks(g, expansion); + assert(frozen =~= seq![GuardedAction::CleanIf(model::lift_test(g, test@), model::lift_test(g, g.constants.test_true)), + transition_freeze_action(g, b), transition_freeze_action(g, a)]); + reveal_with_fuel(guarded_run, 4); + assert(guarded_run(sem, frozen, known) == Some(known.push(result))); + guarded_lemma_stack_refl(sem, valid, known); + guarded_lemma_stack_push(sem, valid, known, known, expected, result); + let tasks = machine_unary_if_tasks(g, test, yes, no, suffix, base); + assert(tasks.subrange(base.len() as int, tasks.len() as int) =~= expansion); + } + + pub proof fn machine_unary_not_const_result( + before: model::Graph, after: model::Graph, id: TransitionId, head: RegexId, negated: RegexId, out: TransitionId, + ) + requires model::graph_wf(before), model::graph_wf(after), model::graph_extends(before, after), + id@ < before.transitions.len(), before.transitions[id@ as int] == model::TransitionNode::Const(head@), + negated@ < before.regexes.len(), + forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + ==> model::regex_lang(before, theta, negated@, word) == !model::regex_lang(before, theta, head@, word), + forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_lang(after, theta, out, event, word) == model::regex_lang(after, theta, negated@, word), + ensures transition_result(after, ActionShape::Not(id@), out), + { + model::lemma_graph_wf_elim(before); + model::lemma_graph_transition_wf(before, id@); + model::lemma_lift_stable_under_extends(before, after); + transition_unfold(after, id@); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies transition_lang(after, theta, out, event, word) == !transition_lang(after, theta, id, event, word) by { + language::lemma_interp_const(model::gsem(theta), event, model::lift_regex(after, head@)); + assert(model::regex_lang(before, theta, negated@, word) == !model::regex_lang(before, theta, head@, word)); + } + machine_unary_not_result(after, id, out); + } + + pub proof fn machine_unary_double_not_result(g: model::Graph, id: TransitionId, inner: TransitionId) + requires model::graph_wf(g), id@ < g.transitions.len(), g.transitions[id@ as int] == model::TransitionNode::Not(inner@), + ensures transition_result(g, ActionShape::Not(id@), inner), + { + transition_unfold(g, id@); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies transition_lang(g, theta, inner, event, word) == !transition_lang(g, theta, id, event, word) by { + language::lemma_interp_not(model::gsem(theta), event, model::lift_transition(g, inner@)); + } + machine_unary_not_result(g, id, inner); + } + + pub proof fn machine_unary_append_identity_result(g: model::Graph, id: TransitionId, suffix: RegexId, out: TransitionId) + requires model::graph_wf(g), + (suffix@ == g.constants.epsilon && out == id) + || (suffix@ == g.constants.empty && out@ == g.constants.transition_empty), + ensures transition_result(g, ActionShape::Append(id@, suffix@), out), + { + assert(model::constants_wf(g)) by { model::lemma_graph_wf_elim(g); } + transition_unfold(g, g.constants.transition_empty); + regex_unfold(g, g.constants.empty); + regex_unfold(g, g.constants.epsilon); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies transition_lang(g, theta, out, event, word) + == machine_unary_append_language(g, theta, id, suffix, event, word) by { + machine_unary_append_identity(model::gsem(theta), + language::interp_transition(model::gsem(theta), event, model::lift_transition(g, id@)), word); + language::lemma_interp_const(model::gsem(theta), event, language::Regex::Empty); + } + machine_unary_append_result(g, id, suffix, out); + } + + pub proof fn machine_unary_append_const_language( + before: model::Graph, after: model::Graph, id: TransitionId, head: RegexId, suffix: RegexId, + theta: Subst, event: EventView, word: Seq, + ) + requires model::graph_wf(before), model::graph_wf(after), model::graph_extends(before, after), + id@ < before.transitions.len(), before.transitions[id@ as int] == model::TransitionNode::Const(head@), + suffix@ < before.regexes.len(), + ensures machine_unary_append_language(after, theta, id, suffix, event, word) + == concat_combo(before, theta, seq![head, suffix], word), + { + hide(language::numeric_lang); + hide(model::test_holds); + hide(model::lift_regex); + hide(model::lift_transition); + model::lemma_graph_transition_wf(before, id@); + model::lemma_graph_wf_elim(before); + model::lemma_lift_regex_stable(before, after, head@); + model::lemma_lift_regex_stable(before, after, suffix@); + transition_unfold(after, id@); + language::lemma_interp_const(model::gsem(theta), event, model::lift_regex(after, head@)); + assert(model::lift_regexes(before, model::regex_ids(seq![head, suffix])) + =~= seq![model::lift_regex(before, head@), model::lift_regex(before, suffix@)]); + } + + #[verifier::spinoff_prover] + pub proof fn machine_unary_append_const_result( + before: model::Graph, after: model::Graph, id: TransitionId, head: RegexId, suffix: RegexId, combined: RegexId, out: TransitionId, + ) + requires model::graph_wf(before), model::graph_wf(after), model::graph_extends(before, after), + id@ < before.transitions.len(), before.transitions[id@ as int] == model::TransitionNode::Const(head@), + suffix@ < before.regexes.len(), combined@ < before.regexes.len(), + forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + ==> model::regex_lang(before, theta, combined@, word) == concat_combo(before, theta, seq![head, suffix], word), + forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_lang(after, theta, out, event, word) == model::regex_lang(after, theta, combined@, word), + ensures transition_result(after, ActionShape::Append(id@, suffix@), out), + { + hide(model::test_holds); + hide(language::numeric_lang); + hide(language::event_wf); + hide(model::lift_regex); + hide(model::lift_transition); + hide(language::interp_transition); + hide(transition_result); + model::lemma_graph_wf_elim(before); + model::lemma_lift_regex_stable(before, after, combined@); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies transition_lang(after, theta, out, event, word) + == machine_unary_append_language(after, theta, id, suffix, event, word) by { + machine_unary_append_const_language(before, after, id, head, suffix, theta, event, word); + assert(model::regex_lang(before, theta, combined@, word) == concat_combo(before, theta, seq![head, suffix], word)); + } + machine_unary_append_result(after, id, suffix, out); + } + + pub proof fn machine_unary_flip_result( + before: model::Graph, after: model::Graph, id: TransitionId, test: TestId, + yes: TransitionId, no: TransitionId, negated: TestId, out: TransitionId, + ) + requires model::graph_wf(before), model::graph_wf(after), model::graph_extends(before, after), + id@ < before.transitions.len(), before.transitions[id@ as int] == model::TransitionNode::If(test@, yes@, no@), + yes@ == before.constants.transition_all, no@ == before.constants.transition_empty, negated@ < before.tests.len(), + forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + ==> model::test_holds(theta, model::lift_test(before, negated@), event) + == !model::test_holds(theta, model::lift_test(before, test@), event), + forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_lang(after, theta, out, event, word) == transition_if_combo(after, theta, negated, yes, no, event, word), + ensures transition_result(after, ActionShape::Not(id@), out), + { + model::lemma_graph_wf_elim(before); + model::lemma_graph_transition_wf(before, id@); + model::lemma_lift_stable_under_extends(before, after); + assert(model::constants_wf(after)) by { model::lemma_graph_wf_elim(after); } + transition_unfold(after, id@); + transition_unfold(after, yes@); + transition_unfold(after, no@); + regex_unfold(after, after.constants.empty); + regex_unfold(after, after.constants.all); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies transition_lang(after, theta, out, event, word) == !transition_lang(after, theta, id, event, word) by { + let sem = model::gsem(theta); + language::lemma_interp_if(sem, event, model::lift_test(after, test@), model::lift_transition(after, yes@), model::lift_transition(after, no@)); + language::lemma_interp_const(sem, event, language::Regex::Empty); + language::lemma_interp_const(sem, event, language::Regex::All); + assert(model::test_holds(theta, model::lift_test(before, negated@), event) + == !model::test_holds(theta, model::lift_test(before, test@), event)); + } + machine_unary_not_result(after, id, out); + } + + pub proof fn machine_unary_append_nested_effect( + g: model::Graph, id: TransitionId, inner: TransitionId, suffix: RegexId, combined: RegexId, + children: Seq, base: Seq, prior: Seq, + ) + requires model::graph_wf(g), id@ < g.transitions.len(), + g.transitions[id@ as int] == model::TransitionNode::Append(inner@, model::regex_ids(children)), + forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + ==> model::regex_lang(g, theta, combined@, word) == concat_combo(g, theta, children.push(suffix), word), + ensures transition_effect(g, ActionShape::Append(id@, suffix@), base, prior, + base.push(ActionShape::Append(inner@, combined@)), prior), + { + transition_unfold(g, id@); + let sem = transition_context_sem(); + let valid = transition_context_valid(); + let task = ActionShape::Append(id@, suffix@); + let next = ActionShape::Append(inner@, combined@); + let expected = transition_initial_value(g, task).unwrap(); + let result = transition_initial_value(g, next).unwrap(); + let tail = model::lift_regexes(g, model::regex_ids(children)); + assert(model::lift_regexes(g, model::regex_ids(children.push(suffix))) =~= tail.push(model::lift_regex(g, suffix@))); + assert forall|ctx: TransitionContext, event: EventView| valid(ctx) && #[trigger] (expected.guard)(ctx, event) + implies (result.guard)(ctx, event) && forall|word: Seq| guarded_language(sem, ctx, event, expected, word) + == guarded_language(sem, ctx, event, result, word) by { + transition_lemma_context_sem(ctx); + let context_sem = model::gsem(ctx.bindings); + let head = language::interp_transition(context_sem, event, model::lift_transition(g, inner@)); + let last = model::lift_regex(g, suffix@); + let combined_term = model::lift_regex(g, combined@); + language::lemma_interp_append(context_sem, event, model::lift_transition(g, inner@), tail); + language::lemma_interp_append(context_sem, event, model::lift_transition(g, id@), seq![last]); + language::lemma_interp_append(context_sem, event, model::lift_transition(g, inner@), seq![combined_term]); + machine_unary_append_reassociate(context_sem, head, tail, last); + assert forall|word: Seq| language::numeric_lang(context_sem, language::Regex::Concat(tail.push(last)), word) + == language::numeric_lang(context_sem, combined_term, word) by { + assert(model::regex_lang(g, ctx.bindings, combined@, word) + == concat_combo(g, ctx.bindings, children.push(suffix), word)); + } + regex_concat_replace(context_sem, seq![head], tail.push(last), combined_term); + regex_concat_replace(context_sem, seq![head], tail.push(last), language::Regex::Concat(tail.push(last))); + assert(seq![head].push(language::Regex::Concat(tail.push(last))) =~= seq![head, language::Regex::Concat(tail.push(last))]); + assert(seq![head] + tail.push(last) =~= (seq![head] + tail).push(last)); + assert(seq![head].push(combined_term) =~= seq![head, combined_term]); + assert(seq![language::Regex::Concat(seq![head] + tail)] + seq![last] =~= seq![language::Regex::Concat(seq![head] + tail), last]); + assert(seq![head] + seq![combined_term] =~= seq![head, combined_term]); + assert forall|word: Seq| guarded_language(sem, ctx, event, expected, word) + == guarded_language(sem, ctx, event, result, word) by { + assert(language::numeric_lang(context_sem, language::Regex::Concat(seq![language::Regex::Concat(seq![head] + tail), last]), word) + == language::numeric_lang(context_sem, language::Regex::Concat(seq![head, language::Regex::Concat(tail.push(last))]), word)); + assert(language::numeric_lang(context_sem, language::Regex::Concat(seq![head] + tail.push(last)), word) + == language::numeric_lang(context_sem, language::Regex::Concat(seq![head, language::Regex::Concat(tail.push(last))]), word)); + assert(language::numeric_lang(context_sem, language::Regex::Concat(seq![head] + tail.push(last)), word) + == language::numeric_lang(context_sem, language::Regex::Concat(seq![head, combined_term]), word)); + } + } + machine_unary_replace_effect(g, task, next, base, prior); + } + + pub proof fn machine_unary_suffix_language(g: model::Graph, suffix: RegexId, children: Seq) + requires model::graph_wf(g), suffix@ < g.regexes.len(), + children == seq![suffix] || g.regexes[suffix@ as int].kind == model::RegexKindNode::Concat(model::regex_ids(children)), + ensures forall|theta: Subst, word: Seq| + model::regex_lang(g, theta, suffix@, word) == concat_combo(g, theta, children, word), + { + if children == seq![suffix] { + assert(model::lift_regexes(g, model::regex_ids(children)) =~= seq![model::lift_regex(g, suffix@)]); + assert forall|theta: Subst, word: Seq| + model::regex_lang(g, theta, suffix@, word) == concat_combo(g, theta, children, word) by { + language::lemma_concat_singleton(model::gsem(theta), model::lift_regex(g, suffix@), word); + } + } else { regex_unfold(g, suffix@); } + } + + #[verifier::spinoff_prover] + pub proof fn machine_unary_append_raw_result( + before: model::Graph, after: model::Graph, id: TransitionId, suffix: RegexId, children: Seq, out: TransitionId, + ) + requires model::graph_wf(before), model::graph_wf(after), model::graph_extends(before, after), + id@ < before.transitions.len(), suffix@ < before.regexes.len(), regex_ids_valid(before, children), + forall|theta: Subst, word: Seq| + model::regex_lang(before, theta, suffix@, word) == concat_combo(before, theta, children, word), + model::lift_transition(after, out@) == transition_unbounded_node(after, + model::TransitionNode::Append(id@, model::regex_ids(children))), + ensures transition_result(after, ActionShape::Append(id@, suffix@), out), + { + // Only the table facts: `unique_nodes` adds a quadratic `no_duplicates` matching loop. + assert(model::tables_wf(before)) by { model::lemma_graph_wf_elim(before); } + model::lemma_lift_stable_under_extends(before, after); + assert(model::lift_regexes(before, model::regex_ids(children)) =~= model::lift_regexes(after, model::regex_ids(children))); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies transition_lang(after, theta, out, event, word) + == machine_unary_append_language(after, theta, id, suffix, event, word) by { + let sem = model::gsem(theta); + let head = language::interp_transition(sem, event, model::lift_transition(after, id@)); + let tail = model::lift_regexes(after, model::regex_ids(children)); + let last = model::lift_regex(after, suffix@); + language::lemma_interp_append(sem, event, model::lift_transition(after, id@), tail); + assert forall|w: Seq| language::numeric_lang(sem, language::Regex::Concat(tail), w) == language::numeric_lang(sem, last, w) by { + assert(model::regex_lang(before, theta, suffix@, w) == concat_combo(before, theta, children, w)); + } + regex_concat_replace(sem, seq![head], tail, last); + assert(seq![head].push(last) =~= seq![head, last]); + } + machine_unary_append_result(after, id, suffix, out); + } + + + pub proof fn machine_pair_constant_result( + before: model::Graph, after: model::Graph, a: TransitionId, b: TransitionId, + x: RegexId, y: RegexId, regex: RegexId, out: TransitionId, + ) + requires model::graph_wf(before), model::graph_wf(after), model::graph_extends(before, after), + a@ < after.transitions.len(), b@ < after.transitions.len(), + x@ < before.regexes.len(), y@ < before.regexes.len(), regex@ < before.regexes.len(), + after.transitions[a@ as int] == model::TransitionNode::Const(x@), + after.transitions[b@ as int] == model::TransitionNode::Const(y@), + forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + ==> model::regex_lang(before, theta, regex@, word) == regex_combo(before, theta, seq![x, y], word, true), + forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_lang(after, theta, out, event, word) == model::regex_lang(after, theta, regex@, word), + ensures transition_result(after, ActionShape::Pair(a@, b@), out), + { + regex_combo_extends(before, after, seq![regex], true); + regex_combo_extends(before, after, seq![x, y], true); + transition_lemma_constant(after, a, x); + transition_lemma_constant(after, b, y); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies transition_lang(after, theta, out, event, word) + == transition_combo(after, theta, seq![a, b], event, word, true) by { + assert(model::regex_lang(before, theta, regex@, word) + == regex_combo(before, theta, seq![x, y], word, true)); + regex_combo_push(before, Seq::empty(), regex, theta, word, true); + regex_combo_push(after, Seq::empty(), regex, theta, word, true); + assert(Seq::::empty().push(regex) =~= seq![regex]); + assert(regex_combo(before, theta, seq![regex], word, true) + == model::regex_lang(before, theta, regex@, word)); + assert(regex_combo(after, theta, seq![regex], word, true) + == model::regex_lang(after, theta, regex@, word)); + assert(transition_lang(after, theta, out, event, word) + == model::regex_lang(after, theta, regex@, word)); + } + machine_pair_set_result(after, seq![a, b], ActionShape::Pair(a@, b@), out); + } + + pub proof fn machine_pair_fold_collection_effect( + g: model::Graph, ids: Seq, flat: TransitionId, children: Seq, + pending: Seq, prior: Seq, + ) + requires model::graph_wf(g), flat@ < g.transitions.len(), children.len() > 0, + g.transitions[flat@ as int] == model::TransitionNode::Intersect(model::transition_ids(children)), + forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_lang(g, theta, flat, event, word) == transition_combo(g, theta, ids, event, word, true), + ensures transition_effect(g, ActionShape::Fold(model::transition_ids(ids), 0), pending, prior, + pending.push(ActionShape::Fold(model::transition_ids(children), 1)), prior.push(children[0])), + { + transition_lemma_children_language(g, flat, children, true); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies transition_combo(g, theta, ids, event, word, true) + == transition_combo(g, theta, children, event, word, true) by { + assert(transition_lang(g, theta, flat, event, word) + == transition_combo(g, theta, ids, event, word, true)); + assert(transition_lang(g, theta, flat, event, word) + == transition_combo(g, theta, children, event, word, true)); + } + machine_pair_fold_first_effect(g, ids, children, pending, prior); + } + + pub proof fn machine_driver_union_effect( + g: model::Graph, count: nat, pending: Seq, prior: Seq, out: TransitionId, + ) + requires count <= prior.len(), + forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_lang(g, theta, out, event, word) + == transition_combo(g, theta, prior.subrange(prior.len() as int - count as int, prior.len() as int), event, word, false), + ensures transition_effect(g, ActionShape::Union(count), pending, prior, pending, + prior.take(prior.len() as int - count as int).push(out)), + { + let sem = transition_context_sem(); + let valid = transition_context_valid(); + let start = prior.len() as int - count as int; + let ids = prior.subrange(start, prior.len() as int); + let prefix = transition_known_values(g, prior.take(start)); + let children = transition_known_values(g, ids); + assert(transition_known_values(g, prior) =~= prefix + children); + let expected = guarded_set(children, false); + let result = transition_known(g, out); + assert forall|ctx: TransitionContext, event: EventView| valid(ctx) && #[trigger] (expected.guard)(ctx, event) + implies (result.guard)(ctx, event) && forall|word: Seq| + guarded_language(sem, ctx, event, expected, word) == guarded_language(sem, ctx, event, result, word) by { + transition_lemma_context_sem(ctx); + assert forall|word: Seq| guarded_language(sem, ctx, event, expected, word) + == guarded_language(sem, ctx, event, result, word) by { + let terms = children.map(|i: int, value: TransitionMeaning| value.term); + language::lemma_interp_union(model::gsem(ctx.bindings), event, terms, word); + assert forall|i: int| 0 <= i < ids.len() implies language::numeric_lang(model::gsem(ctx.bindings), + language::interp_transition(model::gsem(ctx.bindings), event, terms[i]), word) + == transition_lang(g, ctx.bindings, ids[i], event, word) by {} + if guarded_language(sem, ctx, event, expected, word) { + let i = choose|i: int| 0 <= i < terms.len() && language::numeric_lang(model::gsem(ctx.bindings), + language::interp_transition(model::gsem(ctx.bindings), event, terms[i]), word); + assert(transition_combo(g, ctx.bindings, ids, event, word, false)); + } + if transition_combo(g, ctx.bindings, ids, event, word, false) { + let i = choose|i: int| 0 <= i < ids.len() && transition_lang(g, ctx.bindings, ids[i], event, word); + assert(language::numeric_lang(model::gsem(ctx.bindings), + language::interp_transition(model::gsem(ctx.bindings), event, terms[i]), word)); + } + transition_lemma_known_language(g, out, ctx, event, word); + assert(transition_lang(g, ctx.bindings, out, event, word) + == transition_combo(g, ctx.bindings, ids, event, word, false)); + } + } + guarded_lemma_apply_set_suffix(sem, prefix, children, false); + guarded_lemma_stack_refl(sem, valid, prefix); + guarded_lemma_stack_push(sem, valid, prefix, prefix, expected, result); + transition_lemma_known_push(g, prior.take(start), out); + assert(pending.subrange(pending.len() as int, pending.len() as int) =~= Seq::::empty()); + } + + pub proof fn machine_driver_intersect_effect( + g: model::Graph, count: nat, pending: Seq, prior: Seq, + ) + requires count <= prior.len(), + ensures transition_effect(g, ActionShape::Intersect(count), pending, prior, + pending.push(ActionShape::Fold(model::transition_ids(prior.subrange(prior.len() as int - count as int, prior.len() as int)), 0)), + prior.take(prior.len() as int - count as int)), + { + let sem = transition_context_sem(); + let valid = transition_context_valid(); + let start = prior.len() as int - count as int; + let ids = prior.subrange(start, prior.len() as int); + let prefix = transition_known_values(g, prior.take(start)); + let children = transition_known_values(g, ids); + let expected = guarded_set(children, true); + let terms = model::transition_ids(ids).map(|i: int, id: nat| model::lift_transition(g, id)); + let result = guarded_constant(language::Transition::Intersect(terms)); + assert(expected.term == result.term) by { + assert(children.map(|i: int, value: TransitionMeaning| value.term) =~= terms); + } + guarded_lemma_same_term(sem, valid, expected, result); + assert(transition_known_values(g, prior) =~= prefix + children); + guarded_lemma_apply_set_suffix(sem, prefix, children, true); + guarded_lemma_stack_refl(sem, valid, prefix); + guarded_lemma_stack_push(sem, valid, prefix, prefix, expected, result); + let task = ActionShape::Fold(model::transition_ids(ids), 0); + assert(pending.push(task).subrange(pending.len() as int, pending.len() as int + 1) =~= seq![task]); + assert(transition_freeze_tasks(g, seq![task]) =~= seq![GuardedAction::Fold(terms, 0)]); + guarded_lemma_run_singleton(sem, GuardedAction::Fold(terms, 0), prefix); + } + + pub proof fn machine_driver_if_effect( + g: model::Graph, test: TestId, path: Option, pending: Seq, prior: Seq, out: TransitionId, + ) + requires prior.len() >= 2, + forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_lang(g, theta, out, event, word) + == transition_if_combo(g, theta, test, prior[prior.len() as int - 2], prior.last(), event, word), + ensures match path { + None => transition_effect(g, ActionShape::If(test@), pending, prior, pending, + prior.take(prior.len() as int - 2).push(out)), + Some(path) => transition_effect(g, ActionShape::CleanIf(test@, path@), pending, prior, + pending.push(ActionShape::Clean(out@, path@)), prior.take(prior.len() as int - 2)), + }, + { + let sem = transition_context_sem(); + let valid = transition_context_valid(); + let start = prior.len() as int - 2; + let prefix_ids = prior.take(start); + let prefix = transition_known_values(g, prefix_ids); + let a = prior[start]; + let b = prior.last(); + let yes = transition_known(g, a); + let no = transition_known(g, b); + assert(transition_known_values(g, prior) =~= prefix.push(yes).push(no)); + let expected = match path { + None => guarded_if(sem, model::lift_test(g, test@), yes, no), + Some(path) => guarded_clean_if(sem, model::lift_test(g, test@), model::lift_test(g, path@), yes, no), + }; + let result = match path { + None => transition_known(g, out), + Some(path) => guarded_clean(sem, model::lift_test(g, path@), model::lift_transition(g, out@)), + }; + assert forall|ctx: TransitionContext, event: EventView| valid(ctx) && #[trigger] (expected.guard)(ctx, event) + implies (result.guard)(ctx, event) && forall|word: Seq| + guarded_language(sem, ctx, event, expected, word) == guarded_language(sem, ctx, event, result, word) by { + transition_lemma_context_sem(ctx); + language::lemma_interp_if(model::gsem(ctx.bindings), event, model::lift_test(g, test@), yes.term, no.term); + assert forall|word: Seq| guarded_language(sem, ctx, event, expected, word) + == guarded_language(sem, ctx, event, result, word) by { + assert(transition_lang(g, ctx.bindings, out, event, word) + == transition_if_combo(g, ctx.bindings, test, a, b, event, word)); + } + } + guarded_lemma_stack_refl(sem, valid, prefix); + guarded_lemma_stack_push(sem, valid, prefix, prefix, expected, result); + assert(prefix.push(yes).push(no).take(start) =~= prefix); + match path { + None => { + transition_lemma_known_push(g, prefix_ids, out); + assert(pending.subrange(pending.len() as int, pending.len() as int) =~= Seq::::empty()); + }, + Some(path) => { + let task = ActionShape::Clean(out@, path@); + assert(pending.push(task).subrange(pending.len() as int, pending.len() as int + 1) =~= seq![task]); + assert(transition_freeze_tasks(g, seq![task]) =~= seq![GuardedAction::Clean(model::lift_transition(g, out@), model::lift_test(g, path@))]); + guarded_lemma_run_singleton(sem, transition_freeze_action(g, task), prefix); + }, + } + } + + pub open spec fn machine_driver_result_action(task: ActionShape, id: TransitionId) -> ActionShape { + match task { + ActionShape::NotResult => ActionShape::Not(id@), + ActionShape::AppendResult(suffix) => ActionShape::Append(id@, suffix), + _ => task, + } + } + + pub proof fn machine_driver_result_effect(g: model::Graph, task: ActionShape, pending: Seq, prior: Seq) + requires prior.len() > 0, task is NotResult || task is AppendResult, + ensures transition_effect(g, task, pending, prior, pending.push(machine_driver_result_action(task, prior.last())), prior.drop_last()), + { + let sem = transition_context_sem(); + let valid = transition_context_valid(); + let next = machine_driver_result_action(task, prior.last()); + let prefix = transition_known_values(g, prior.drop_last()); + let last = transition_known(g, prior.last()); + assert(transition_known_values(g, prior) =~= prefix.push(last)); + let before = guarded_apply(sem, transition_freeze_action(g, task), transition_known_values(g, prior)); + let after = guarded_apply(sem, transition_freeze_action(g, next), prefix); + assert(before == after) by { + assert(prefix.push(last).drop_last() =~= prefix); + match task { ActionShape::NotResult => {}, ActionShape::AppendResult(suffix) => {}, _ => {} } + } + guarded_lemma_stack_refl(sem, valid, after.unwrap()); + guarded_lemma_run_singleton(sem, transition_freeze_action(g, next), prefix); + assert(pending.push(next).subrange(pending.len() as int, pending.len() as int + 1) =~= seq![next]); + assert(transition_freeze_tasks(g, seq![next]) =~= seq![transition_freeze_action(g, next)]); + } + + pub proof fn machine_driver_swap_effect(g: model::Graph, pending: Seq, prior: Seq) + requires prior.len() >= 2, + ensures transition_effect(g, ActionShape::SwapThen, pending, prior, pending, + prior.take(prior.len() as int - 2).push(prior.last()).push(prior[prior.len() as int - 2])), + { + let next = prior.take(prior.len() as int - 2).push(prior.last()).push(prior[prior.len() as int - 2]); + let known = transition_known_values(g, prior); + assert(transition_known_values(g, next) =~= known.take(known.len() as int - 2).push(known.last()).push(known[known.len() as int - 2])); + guarded_lemma_stack_refl(transition_context_sem(), transition_context_valid(), transition_known_values(g, next)); + assert(pending.subrange(pending.len() as int, pending.len() as int) =~= Seq::::empty()); + } + + pub proof fn machine_driver_complete(g: model::Graph, task: ActionShape, values: Seq) + requires transition_action_pushes(task), + transition_program_refines(transition_program(g, seq![task], Seq::empty()), Some(transition_known_values(g, values))), + ensures values.len() == 1, transition_result(g, task, values.last()), + { + let sem = transition_context_sem(); + let valid = transition_context_valid(); + assert(transition_freeze_tasks(g, seq![task]) =~= seq![transition_freeze_action(g, task)]); + assert(transition_known_values(g, Seq::empty()) =~= Seq::::empty()); + guarded_lemma_run_singleton(sem, transition_freeze_action(g, task), Seq::::empty()); + let expected = transition_initial_value(g, task).unwrap(); + assert(guarded_apply(sem, transition_freeze_action(g, task), Seq::::empty()) == Some(seq![expected])); + assert(transition_program(g, seq![task], Seq::empty()) == Some(seq![expected])); + assert(values.len() == 1); + assert(guarded_refines(sem, valid, expected, transition_known(g, values.last()))); + transition_lemma_refines_result(g, task, values.last()); + } + + + pub open spec fn transition_append_combo( + g: model::Graph, theta: Subst, root: TransitionId, suffix: Seq, event: EventView, word: Seq, + ) -> bool { + let sem = model::gsem(theta); + language::numeric_lang(sem, language::Regex::Concat(seq![language::interp_transition(sem, event, model::lift_transition(g, root@))] + + model::lift_regexes(g, model::regex_ids(suffix))), word) + } + + pub proof fn machine_driver_extension_future(before: model::Graph, middle: model::Graph) + requires model::graph_extends(before, middle), + ensures forall|after: model::Graph| model::graph_extends(middle, after) ==> model::graph_extends(before, after), + { + assert forall|after: model::Graph| model::graph_extends(middle, after) implies model::graph_extends(before, after) by { + transition_lemma_extends_transitive(before, middle, after); + } + } + + pub proof fn machine_driver_if_future( + before: model::Graph, test: TestId, yes: TransitionId, no: TransitionId, local: TransitionId, + ) + requires model::graph_wf(before), test@ < before.tests.len(), + yes@ < before.transitions.len(), no@ < before.transitions.len(), local@ < before.transitions.len(), + forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_lang(before, theta, local, event, word) == transition_if_combo(before, theta, test, yes, no, event, word), + ensures forall|after: model::Graph, out: TransitionId| model::graph_extends(before, after) && model::graph_wf(after) + && #[trigger] transition_result(after, ActionShape::Clean(local@, before.constants.test_true), out) + ==> forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_lang(after, theta, out, event, word) == transition_if_combo(after, theta, test, yes, no, event, word), + { + model::lemma_graph_wf_elim(before); + assert forall|after: model::Graph, out: TransitionId| model::graph_extends(before, after) && model::graph_wf(after) + && #[trigger] transition_result(after, ActionShape::Clean(local@, before.constants.test_true), out) + implies forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_lang(after, theta, out, event, word) == transition_if_combo(after, theta, test, yes, no, event, word) by { + model::lemma_lift_test_stable(before, after, test@); + model::lemma_lift_transition_stable(before, after, yes@); + model::lemma_lift_transition_stable(before, after, no@); + model::lemma_lift_transition_stable(before, after, local@); + transition_lemma_test_constants(after); + let expected = transition_initial_value(after, ActionShape::Clean(local@, before.constants.test_true)).unwrap(); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies transition_lang(after, theta, out, event, word) == transition_if_combo(after, theta, test, yes, no, event, word) by { + let ctx = TransitionContext { bindings: theta }; + transition_lemma_context_sem(ctx); + assert((expected.guard)(ctx, event)); + assert(guarded_language(transition_context_sem(), ctx, event, expected, word) + == transition_lang(after, theta, out, event, word)); + assert(transition_lang(before, theta, local, event, word) + == transition_if_combo(before, theta, test, yes, no, event, word)); + } + } + } + + pub proof fn machine_driver_append_future( + before: model::Graph, root: TransitionId, suffix: Seq, combined: RegexId, + ) + requires model::graph_wf(before), combined@ < before.regexes.len(), regex_ids_valid(before, suffix), + forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + ==> model::regex_lang(before, theta, combined@, word) == concat_combo(before, theta, suffix, word), + ensures forall|after: model::Graph, out: TransitionId| model::graph_extends(before, after) && model::graph_wf(after) + && #[trigger] transition_result(after, ActionShape::Append(root@, combined@), out) + ==> forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_lang(after, theta, out, event, word) == transition_append_combo(after, theta, root, suffix, event, word), + { + model::lemma_graph_wf_elim(before); + assert forall|after: model::Graph, out: TransitionId| model::graph_extends(before, after) && model::graph_wf(after) + && #[trigger] transition_result(after, ActionShape::Append(root@, combined@), out) + implies forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> transition_lang(after, theta, out, event, word) == transition_append_combo(after, theta, root, suffix, event, word) by { + model::lemma_lift_regex_stable(before, after, combined@); + regex_concat_extends(before, after, suffix); + let expected = transition_initial_value(after, ActionShape::Append(root@, combined@)).unwrap(); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies transition_lang(after, theta, out, event, word) == transition_append_combo(after, theta, root, suffix, event, word) by { + let ctx = TransitionContext { bindings: theta }; + transition_lemma_context_sem(ctx); + let sem = model::gsem(theta); + let head = language::interp_transition(sem, event, model::lift_transition(after, root@)); + let tail = model::lift_regexes(after, model::regex_ids(suffix)); + let combined_term = model::lift_regex(after, combined@); + language::lemma_interp_append(sem, event, model::lift_transition(after, root@), seq![combined_term]); + assert forall|w: Seq| language::numeric_lang(sem, language::Regex::Concat(tail), w) == language::numeric_lang(sem, combined_term, w) by { + assert(model::regex_lang(before, theta, combined@, w) == concat_combo(before, theta, suffix, w)); + assert(concat_combo(before, theta, suffix, w) == concat_combo(after, theta, suffix, w)); + } + regex_concat_replace(sem, seq![head], tail, combined_term); + assert((expected.guard)(ctx, event)); + assert(guarded_language(transition_context_sem(), ctx, event, expected, word) + == transition_lang(after, theta, out, event, word)); + assert(seq![head] + seq![combined_term] =~= seq![head].push(combined_term)); + } + } + } + + } + + verus! { + // ----- Structural contract of the normalizer ((N0)–(N5) of `verify::finite_states::Model::contract`) ----- + + /// Interning: in a well-formed graph, a regex kind determines its id. In particular a union, + /// intersection, or list state is determined by its operands, and a complement by its body. + pub proof fn regex_kind_unique(g: model::Graph, a: nat, b: nat) + requires model::graph_wf(g), a < g.regexes.len(), b < g.regexes.len(), + g.regexes[a as int].kind == g.regexes[b as int].kind, + ensures a == b, + { + regex_unfold(g, a); + regex_unfold(g, b); + model::lemma_graph_wf_elim(g); + assert(g.regexes[a as int] == g.regexes[b as int]); + } + + /// (N3), exactly: the result `r` of `N(¬x)`. + pub open spec fn regex_not_result(g: model::Graph, x: nat, r: nat) -> bool { + match g.regexes[x as int].kind { + model::RegexKindNode::Empty => r == g.constants.all, + model::RegexKindNode::All => r == g.constants.empty, + model::RegexKindNode::Not(inner) => r == inner, + _ => r < g.regexes.len() && g.regexes[r as int].kind == model::RegexKindNode::Not(x), + } + } + + /// (N4), exactly: the result `r` of `N(x₁⋯xₖ)` absorbs `∅`, flattens concatenations, drops + /// `ε`, and returns `ε`, the single remaining factor, or the list of the factors. Factors are + /// read in `before`, the interned list in `after`. + pub open spec fn regex_concat_result(before: model::Graph, after: model::Graph, children: Seq, r: nat) -> bool { + let f = regex_concat_flat(before, children); + if exists|i: int| 0 <= i < children.len() && before.regexes[children[i]@ as int].kind == model::RegexKindNode::Empty { + r == before.constants.empty + } else if f.len() == 0 { + r == before.constants.epsilon + } else if f.len() == 1 { + r == f[0] + } else { + r < after.regexes.len() && after.regexes[r as int].kind == model::RegexKindNode::Concat(f) + } + } + + /// `t` is in the piece contributed by the test `c` to a flattened `∧` (`and`) or `∨`. + pub open spec fn test_piece_contains(g: model::Graph, c: nat, and: bool, t: nat) -> bool { + match g.tests[c as int] { + model::TestNode::And(cs) => if and { cs.contains(t) } else { t == c }, + model::TestNode::Or(cs) => if !and { cs.contains(t) } else { t == c }, + _ => t == c, + } + } + + /// `t` is an operand of the flattened connective over `children`. + pub open spec fn test_member(g: model::Graph, children: Seq, and: bool, t: nat) -> bool { + exists|i: int| 0 <= i < children.len() && #[trigger] test_piece_contains(g, children[i]@, and, t) + } + + /// Shape of the test connective (the basis of (N5)): the result `r` is `⊤`, `⊥`, an operand of + /// the flattened input, or an interned `∧`/`∨` node over such operands. Operands are read in + /// `before`, the result node in `after`. + pub open spec fn test_connective_result(before: model::Graph, after: model::Graph, children: Seq, and: bool, r: nat) -> bool { + ||| r == before.constants.test_true + ||| r == before.constants.test_false + ||| test_member(before, children, and, r) + ||| r < after.tests.len() && match after.tests[r as int] { + model::TestNode::And(ks) => and && forall|k: int| 0 <= k < ks.len() ==> test_member(before, children, and, #[trigger] ks[k]), + model::TestNode::Or(ks) => !and && forall|k: int| 0 <= k < ks.len() ==> test_member(before, children, and, #[trigger] ks[k]), + _ => false, + } + } + + pub proof fn test_connective_result_extends(before: model::Graph, a: model::Graph, b: model::Graph, + children: Seq, and: bool, r: nat) + requires test_connective_result(before, a, children, and, r), model::graph_extends(a, b), + ensures test_connective_result(before, b, children, and, r), + { + if r < a.tests.len() { + assert(a.tests == b.tests.subrange(0, a.tests.len() as int)); + assert(b.tests[r as int] == a.tests[r as int]); + } + } + + /// `o` is in the piece contributed by the regex `c` to a flattened `+` (`&` for `intersect`): + /// the operands of a union (intersection), otherwise `c` itself. + pub open spec fn regex_piece_contains(g: model::Graph, c: nat, intersect: bool, o: nat) -> bool { + match g.regexes[c as int].kind { + model::RegexKindNode::Union(cs) => if !intersect { cs.contains(o) } else { o == c }, + model::RegexKindNode::Intersect(cs) => if intersect { cs.contains(o) } else { o == c }, + _ => o == c, + } + } + + /// `o ∈ ops₊(X)` (`ops_&(X)` for `intersect`). + pub open spec fn regex_member(g: model::Graph, children: Seq, intersect: bool, o: nat) -> bool { + exists|i: int| 0 <= i < children.len() && #[trigger] regex_piece_contains(g, children[i]@, intersect, o) + } + + pub open spec fn regex_is_set(g: model::Graph, o: nat, intersect: bool) -> bool { + match g.regexes[o as int].kind { + model::RegexKindNode::Union(_) => !intersect, + model::RegexKindNode::Intersect(_) => intersect, + _ => false, + } + } + + pub proof fn regex_member_valid(g: model::Graph, children: Seq, intersect: bool, o: nat) + requires model::graph_wf(g), regex_ids_valid(g, children), regex_member(g, children, intersect, o), + ensures o < g.regexes.len(), + { + let i = choose|i: int| 0 <= i < children.len() && #[trigger] regex_piece_contains(g, children[i]@, intersect, o); + let c = children[i]@; + model::lemma_graph_regex_wf(g, c); + match g.regexes[c as int].kind { + model::RegexKindNode::Union(cs) | model::RegexKindNode::Intersect(cs) => { + if cs.contains(o) { let j = choose|j: int| 0 <= j < cs.len() && cs[j] == o; } + }, + _ => {}, + } + } + + /// The inputs are normalized for this connective: `ops₊(X)` contains no unions (resp. + /// `ops_&(X)` no intersections), as holds when `X` consists of states. + pub open spec fn regex_set_flat_inputs(g: model::Graph, children: Seq, intersect: bool) -> bool { + forall|o: nat| regex_member(g, children, intersect, o) ==> !regex_is_set(g, o, intersect) + } + + /// `t` is the test of some member of `ops₊(X)` (`ops_&(X)`). + pub open spec fn regex_member_test(g: model::Graph, children: Seq, intersect: bool, t: nat) -> bool { + exists|o: nat| #[trigger] regex_member(g, children, intersect, o) + && o < g.regexes.len() && g.regexes[o as int].kind == model::RegexKindNode::Test(t) + } + + /// `o` is a test combined by the test connective from tests of `ops₊(X)` (`ops_&(X)`). + pub open spec fn regex_combined_test(before: model::Graph, after: model::Graph, children: Seq, intersect: bool, o: nat) -> bool { + o < after.regexes.len() && exists|t: nat, ts: Seq| + after.regexes[o as int].kind == model::RegexKindNode::Test(t) + && (forall|k: int| 0 <= k < ts.len() ==> regex_member_test(before, children, intersect, #[trigger] ts[k]@)) + && #[trigger] test_connective_result(before, after, ts, intersect, t) + } + + /// A legal operand of `N(ΣX)` (`N(&X)`): a member of `ops₊(X)` or a combined test. + pub open spec fn regex_set_operand_ok(before: model::Graph, after: model::Graph, children: Seq, intersect: bool, o: nat) -> bool { + regex_member(before, children, intersect, o) || regex_combined_test(before, after, children, intersect, o) + } + + /// (N1)/(N2): the result `r` of `N(ΣX)` (`N(&X)`) is a constant, or its operands are members of + /// `ops₊(X)` (`ops_&(X)`) or tests combined from the tests among them. Inputs are read in + /// `before`, the result in `after`. + pub open spec fn regex_set_shape(before: model::Graph, after: model::Graph, children: Seq, intersect: bool, r: nat) -> bool { + ||| r == before.constants.empty + ||| r == before.constants.all + ||| r == before.constants.epsilon + ||| r < after.regexes.len() && forall|o: nat| #[trigger] regex_piece_contains(after, r, intersect, o) + ==> regex_member(before, children, intersect, o) || regex_combined_test(before, after, children, intersect, o) + } + + pub proof fn regex_combined_test_extends(before: model::Graph, a: model::Graph, b: model::Graph, + children: Seq, intersect: bool, o: nat) + requires regex_combined_test(before, a, children, intersect, o), model::graph_extends(a, b), + ensures regex_combined_test(before, b, children, intersect, o), + { + let (t, ts) = choose|t: nat, ts: Seq| + a.regexes[o as int].kind == model::RegexKindNode::Test(t) + && (forall|k: int| 0 <= k < ts.len() ==> regex_member_test(before, children, intersect, #[trigger] ts[k]@)) + && #[trigger] test_connective_result(before, a, ts, intersect, t); + assert(a.regexes == b.regexes.subrange(0, a.regexes.len() as int)); + assert(b.regexes[o as int] == a.regexes[o as int]); + test_connective_result_extends(before, a, b, ts, intersect, t); + } + + /// (N0) for complements: `N(¬p) = ¬p` whenever `¬p` is a state. + pub proof fn regex_not_fixpoint(g: model::Graph, x: nat, p: nat, r: nat) + requires model::graph_wf(g), x < g.regexes.len(), p < g.regexes.len(), + g.regexes[x as int].kind == model::RegexKindNode::Not(p), + !(g.regexes[p as int].kind is Empty || g.regexes[p as int].kind is All || g.regexes[p as int].kind is Not), + regex_not_result(g, p, r), + ensures r == x, + { + regex_kind_unique(g, r, x); + } + + /// (N3) involution: `N(¬N(¬x)) = x` for every node `x` that is not the complement of `∅`, + /// `Univ`, or a complement; in particular for every state. + pub proof fn regex_not_involution(g: model::Graph, x: nat, r: nat, r2: nat) + requires model::graph_wf(g), x < g.regexes.len(), + forall|p: nat| #[trigger] g.regexes[x as int].kind == model::RegexKindNode::Not(p) + ==> !(g.regexes[p as int].kind is Empty || g.regexes[p as int].kind is All || g.regexes[p as int].kind is Not), + regex_not_result(g, x, r), regex_not_result(g, r, r2), + ensures r2 == x, + { + regex_constants(g); + regex_unfold(g, g.constants.empty); + regex_unfold(g, g.constants.all); + regex_unfold(g, x); + match g.regexes[x as int].kind { + model::RegexKindNode::Empty => { + assert(g.regexes[g.constants.all as int].kind is All); + assert(g.regexes[g.constants.empty as int].kind is Empty); + regex_kind_unique(g, x, g.constants.empty); + }, + model::RegexKindNode::All => { + assert(g.regexes[g.constants.empty as int].kind is Empty); + assert(g.regexes[g.constants.all as int].kind is All); + regex_kind_unique(g, x, g.constants.all); + }, + model::RegexKindNode::Not(p) => { + assert(r == p); + assert(p < g.regexes.len()); + regex_not_fixpoint(g, x, p, r2); + }, + _ => { + assert(g.regexes[r as int].kind == model::RegexKindNode::Not(x)); + }, + } + } + + /// Factors that are neither `∅`, `ε`, nor concatenations flatten to themselves. + pub proof fn regex_concat_flat_atoms(g: model::Graph, children: Seq) + requires forall|i: int| 0 <= i < children.len() ==> !(#[trigger] g.regexes[children[i]@ as int].kind is Empty + || g.regexes[children[i]@ as int].kind is Epsilon || g.regexes[children[i]@ as int].kind is Concat), + ensures regex_concat_flat(g, children) == model::regex_ids(children), + decreases children.len(), + { + if children.len() > 0 { + let init = children.drop_last(); + assert forall|i: int| 0 <= i < init.len() implies !(#[trigger] g.regexes[init[i]@ as int].kind is Empty + || g.regexes[init[i]@ as int].kind is Epsilon || g.regexes[init[i]@ as int].kind is Concat) by { + assert(init[i] == children[i]); + } + regex_concat_flat_atoms(g, init); + assert(g.regexes[children.last()@ as int].kind == g.regexes[children[children.len() - 1]@ as int].kind); + assert(model::regex_ids(children) =~= model::regex_ids(init) + seq![children.last()@]); + } + } + + /// (N0) for lists: applied to the elements of a list state, `N` returns that state. + pub proof fn regex_concat_fixpoint(before: model::Graph, after: model::Graph, q: nat, children: Seq, r: nat) + requires model::graph_wf(after), model::graph_extends(before, after), q < before.regexes.len(), + before.regexes[q as int].kind == model::RegexKindNode::Concat(model::regex_ids(children)), children.len() >= 2, + forall|i: int| 0 <= i < children.len() ==> !(#[trigger] before.regexes[children[i]@ as int].kind is Empty + || before.regexes[children[i]@ as int].kind is Epsilon || before.regexes[children[i]@ as int].kind is Concat), + regex_concat_result(before, after, children, r), + ensures r == q, + { + regex_concat_flat_atoms(before, children); + assert(!exists|i: int| 0 <= i < children.len() && before.regexes[children[i]@ as int].kind == model::RegexKindNode::Empty); + assert(before.regexes == after.regexes.subrange(0, before.regexes.len() as int)); + assert(after.regexes[q as int] == before.regexes[q as int]); + regex_kind_unique(after, r, q); + } + } +} diff --git a/src/history-semantics/src/policy/atoms.rs b/src/history-semantics/src/policy/atoms.rs new file mode 100644 index 000000000..8979fa8d4 --- /dev/null +++ b/src/history-semantics/src/policy/atoms.rs @@ -0,0 +1,92 @@ +//! One-event [`TestExpr`] building blocks over policy-selected coordinates. +//! +//! The named principal/action/resource helpers use the three-coordinate convention of +//! `LockPolicy` and `AgentPolicy`. Other event layouts use the indexed helpers. + +use alloc::string::String; +#[cfg(verus_keep_ghost)] +use history_syntax::spec::events::{AtomView, PatternView, TestView}; +use history_syntax::{AtomPattern, Comparison, Component, ComponentPattern, Event, TestExpr}; +use vstd::prelude::*; + +/// Name of a head variable. +pub type HeadVariable = &'static str; + +verus! { +/// Head variable bound to the acting principal (`"p"`), coordinate 0 in the three-coordinate +/// convention. +pub const PRINCIPAL_VAR: HeadVariable = "p"; +/// Head variable bound to the candidate's resource (`"r"`), coordinate 2 in the three-coordinate +/// convention. +pub const RESOURCE_VAR: HeadVariable = "r"; +} + +/// Compares a coordinate with its head-bound variable. +#[verus_verify] +#[verus_spec(result => ensures result@ == (TestView::Atom { + comparison, pattern: AtomView { + component: component.0 as nat, pattern: PatternView::Variable(variable@), + }, +}))] +pub fn component_is( + component: Component, + variable: &'static str, + comparison: Comparison, +) -> TestExpr { + TestExpr::atom( + comparison, + AtomPattern::new( + component, + ComponentPattern::Variable(String::from_str(variable)), + ), + ) +} + +/// Compares a coordinate with a tagged constant from that coordinate. +#[verus_verify] +#[verus_spec(result => ensures result@ == (TestView::Atom { + comparison, pattern: AtomView { + component: component.0 as nat, pattern: PatternView::Constant(constant), + }, +}))] +pub fn component_equals( + component: Component, + constant: E::Component, + comparison: Comparison, +) -> TestExpr { + TestExpr::atom( + comparison, + AtomPattern::new(component, ComponentPattern::Constant(constant)), + ) +} + +/// Compares coordinate 0 with `p` in the three-ary `(principal, action, resource)` convention. +#[verus_verify] +#[verus_spec(result => requires history_syntax::spec::events::arity::() == 3, + ensures result@ == (TestView::Atom { + comparison, pattern: AtomView { component: 0, pattern: PatternView::Variable(seq!['p']) }, +}))] +pub fn principal_is(comparison: Comparison) -> TestExpr { + proof! { reveal_strlit("p"); assert(PRINCIPAL_VAR@ == seq!['p']); } + component_is(Component(0), PRINCIPAL_VAR, comparison) +} + +/// Compares coordinate 2 with `r` in the three-ary `(principal, action, resource)` convention. +#[verus_verify] +#[verus_spec(result => requires history_syntax::spec::events::arity::() == 3, + ensures result@ == (TestView::Atom { + comparison, pattern: AtomView { component: 2, pattern: PatternView::Variable(seq!['r']) }, +}))] +pub fn resource_is(comparison: Comparison) -> TestExpr { + proof! { reveal_strlit("r"); assert(RESOURCE_VAR@ == seq!['r']); } + component_is(Component(2), RESOURCE_VAR, comparison) +} + +/// Compares coordinate 1 with a tagged action in the three-ary `(principal, action, resource)` convention. +#[verus_verify] +#[verus_spec(result => ensures result@ == (TestView::Atom { + comparison, pattern: AtomView { component: 1, pattern: PatternView::Constant(action) }, +}))] +pub fn action_is(action: E::Component, comparison: Comparison) -> TestExpr { + component_equals(Component(1), action, comparison) +} diff --git a/src/history-semantics/src/policy/decision.rs b/src/history-semantics/src/policy/decision.rs new file mode 100644 index 000000000..58fc59818 --- /dev/null +++ b/src/history-semantics/src/policy/decision.rs @@ -0,0 +1,21 @@ +//! The verdict a policy's entry point returns. + +use alloc::{string::String, vec::Vec}; +use vstd::prelude::*; + +/// The verdict a policy returns for one candidate event: grant, or a single collapsed soft-error +/// carrying the precondition it failed and the fixes that would unblock it. +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Debug, PartialEq, Eq)] +pub enum PolicyDecision { + /// Request is legal under the policy. + Grant, + /// Request is denied with the precondition it violated and the fixes that would unblock it. + Deny { + /// Human-readable precondition the request failed. + failed_precondition: String, + /// Ordered list of state-changing fixes that would make the request legal. + allowed_fixes: Vec, + }, +} diff --git a/src/history-semantics/src/policy/evaluate.rs b/src/history-semantics/src/policy/evaluate.rs new file mode 100644 index 000000000..e44dad51a --- /dev/null +++ b/src/history-semantics/src/policy/evaluate.rs @@ -0,0 +1,657 @@ +//! Checked ordered construction and first-violation selection for trace-policy tables. +//! Native leaves unpack source/callback fields and invoke only the selected diagnostic. + +use alloc::{sync::Arc, vec::Vec}; + +#[cfg(verus_keep_ghost)] +use self::verify::*; +use super::decision::PolicyDecision; +#[cfg(verus_keep_ghost)] +use super::rule::verify::{diagnostic_output, policy_rule_diagnostic, policy_rule_source}; +use super::rule::{NativeDiagnostic, PolicyRule}; +use crate::CompiledRule; +#[cfg(verus_keep_ghost)] +use crate::compiled_rule::verify as compiled; +#[cfg(verus_keep_ghost)] +use history_store::typed::verify as books; +use history_store::{History, Store}; +use history_syntax::{Event, Rule, RuleMode}; +use junco_core::limits::{Limits, Unmetered}; +use junco_core::observation::ObservationWorld; +#[cfg(verus_keep_ghost)] +use junco_core::spec::semantics as sem; +#[cfg(verus_keep_ghost)] +use junco_core::verify::history_specs::{no_invariant_compile_failure, no_invariant_failure}; +use junco_core::{CompileError, HistoryError}; +use vstd::prelude::*; +#[cfg(verus_keep_ghost)] +use vstd::std_specs::iter::IteratorSpec; +#[cfg(verus_keep_ghost)] +use vstd::view::DeepView; + +#[cfg(verus_keep_ghost)] +verus! { +broadcast use {vstd::std_specs::vec::group_vec_axioms, vstd::seq::group_seq_lemmas}; +} + +#[cfg(not(verus_keep_ghost))] +type DiagnosticTrace = core::marker::PhantomData; + +#[cfg(verus_keep_ghost)] +vstd::prelude::verus! { +pub(crate) struct DiagnosticCall { + pub index: nat, + pub source: history_syntax::Rule, + pub diagnostic_id: int, + pub failed_precondition: Seq, + pub allowed_fixes: Seq>, +} + +pub(crate) tracked struct DiagnosticTrace { + pub ghost context_calls: nat, + pub ghost diagnostic_calls: nat, + pub ghost calls: Seq>, +} + +impl DiagnosticTrace { + pub(crate) open spec fn wf(self) -> bool { + self.context_calls == self.calls.len() && self.diagnostic_calls == self.calls.len() + } + pub(crate) proof fn empty() -> (tracked trace: Self) + ensures trace.wf(), trace.calls == Seq::>::empty(), + { + DiagnosticTrace { context_calls: 0, diagnostic_calls: 0, calls: Seq::empty() } + } +} +} + +#[verus_verify] +#[verus_verify(external_body)] +#[verus_spec(result => requires mut_ref_current(_trace@).wf(), _diagnostic_id@ == diagnostic.id(), + call_requires(context, ()), + ensures result is Deny, mut_ref_future(_trace@).wf(), + mut_ref_future(_trace@).context_calls == mut_ref_current(_trace@).context_calls + 1, + mut_ref_future(_trace@).diagnostic_calls == mut_ref_current(_trace@).diagnostic_calls + 1, + result matches PolicyDecision::Deny { failed_precondition, allowed_fixes } ==> + mut_ref_future(_trace@).calls == mut_ref_current(_trace@).calls.push(DiagnosticCall { + index: _index@, source: _source@, diagnostic_id: _diagnostic_id@, + failed_precondition: failed_precondition@, allowed_fixes: allowed_fixes.deep_view(), + }) && exists|value: C| call_ensures(context, (), value) + && diagnostic_output(_diagnostic_id@, value, failed_precondition@, allowed_fixes.deep_view()))] +fn render_denial C>( + diagnostic: &super::rule::NativeDiagnostic, + context: F, + _index: vstd::prelude::Ghost, + _source: vstd::prelude::Ghost>, + _diagnostic_id: vstd::prelude::Ghost, + _trace: vstd::prelude::Tracked<&mut DiagnosticTrace>, +) -> PolicyDecision { + let context = context(); + let (failed_precondition, allowed_fixes) = (diagnostic.inner)(&context); + PolicyDecision::Deny { + failed_precondition, + allowed_fixes, + } +} + +#[cfg(verus_keep_ghost)] +verus! { +pub open(crate) spec fn policy_decision_result(before: CompiledPolicy, after: CompiledPolicy, + history: History, candidate: E, result: Result) -> bool { + verify::policy_wf(after) && verify::policy_frame(before, after) + && no_invariant_failure(result) + && ((result == Err(HistoryError::WrongHistoryOwner)) + == !books::same_store_owner(before.store, history_store::history::verify::store_of(history))) + && match result { + Err(_) => after.callback_trace@ == before.callback_trace@, + Ok(PolicyDecision::Grant) => after.callback_trace@ == before.callback_trace@ + && crate::compiled_rule::verify::ordered_result(verify::policy_sources(before), history, candidate, Ok(None)), + Ok(PolicyDecision::Deny { failed_precondition, allowed_fixes }) => { + let call = after.callback_trace@.calls.last(); + let index = call.index as int; + after.callback_trace@.calls.len() == before.callback_trace@.calls.len() + 1 + && 0 <= index < verify::policy_sources(before).len() + && (junco_core::spec::hypotheses::event_obligations::() ==> + sem::least_violation(sem::rule_views(verify::policy_sources(before)), candidate, + history_store::history::verify::raw_events(history), index)) + && after.callback_trace@.calls == before.callback_trace@.calls.push(DiagnosticCall { + index: call.index, source: verify::policy_sources(before)[index], + diagnostic_id: verify::policy_diagnostic_ids(before)[index], + failed_precondition: failed_precondition@, allowed_fixes: allowed_fixes.deep_view(), + }) + }, + } +} + +// The value here is the actual context returned at the selected callback invocation. +// Outputs are observations, never a deterministic function of a callback identity. +pub open(crate) spec fn policy_context_result C>( + after: CompiledPolicy, context: F, result: Result, +) -> bool { + result matches Ok(PolicyDecision::Deny { failed_precondition, allowed_fixes }) ==> + exists|value: C| call_ensures(context, (), value) + && diagnostic_output(after.callback_trace@.calls.last().diagnostic_id, + value, failed_precondition@, allowed_fixes.deep_view()) +} +} + +/// One compiled runtime rule paired with the diagnostic rendered when it is violated. +#[verus_verify] +#[cfg_attr(verus_keep_ghost, verifier::reject_recursive_types(C))] +pub(crate) struct CompiledPolicyRule { + pub(crate) runtime: CompiledRule, + pub(crate) diagnostic: NativeDiagnostic, +} + +/// A policy table whose compiled rules and caches survive successive decisions. +/// +/// Construction checks source order and physical diagnostic pairing. Native field projection +/// and arbitrary diagnostic invocation remain explicit leaves, not callback content laws. +#[verus_verify] +#[cfg_attr(verus_keep_ghost, verifier::reject_recursive_types(C))] +pub struct CompiledPolicy { + pub(crate) store: Arc>, + pub(crate) rules: Vec>, + #[cfg(verus_keep_ghost)] + pub(crate) callback_trace: Tracked>, +} + +// Move the two native fields together; this leaf asserts no constructor or iterator law. +#[verus_verify] +#[verus_verify(external_body)] +#[verus_spec(result => ensures result.0 == policy_rule_source(item), + result.1.id() == policy_rule_diagnostic(item))] +fn unpack_policy_rule(item: PolicyRule) -> (Rule, NativeDiagnostic) { + let PolicyRule { rule, diagnostic } = item; + #[cfg(verus_keep_ghost)] + { + (rule, diagnostic) + } + #[cfg(not(verus_keep_ghost))] + { + (rule, NativeDiagnostic { inner: diagnostic }) + } +} + +#[cfg(verus_keep_ghost)] +pub mod verify { + use super::*; + verus! { + broadcast use {vstd::std_specs::vec::group_vec_axioms, vstd::seq::group_seq_lemmas}; + + pub open(crate) spec fn entry_sources(entries: Seq>) -> Seq> { + entries.map(|i: int, entry: CompiledPolicyRule| compiled::source_rule(entry.runtime)) + } + pub open(crate) spec fn entry_diagnostic_ids(entries: Seq>) -> Seq { + entries.map(|i: int, entry: CompiledPolicyRule| entry.diagnostic.id()) + } + pub open(crate) spec fn policy_entries_wf(entries: Seq>, store: Arc>) -> bool { + books::store_wf(*store) && forall|i: int| 0 <= i < entries.len() ==> + compiled::compiled_wf(entries[i].runtime) && entries[i].runtime.store == store + } + pub open(crate) spec fn policy_entries_frame(before: Seq>, after: Seq>) -> bool { + before.len() == after.len() && entry_diagnostic_ids(before) == entry_diagnostic_ids(after) + && forall|i: int| 0 <= i < before.len() ==> + compiled::compiled_structure_frame(before[i].runtime, after[i].runtime) + } + pub(crate) proof fn lemma_policy_entries_frame_facts( + before: Seq>, after: Seq>) + requires policy_entries_frame(before, after), + ensures entry_sources(before) == entry_sources(after), + entry_diagnostic_ids(before) == entry_diagnostic_ids(after), + { + assert(entry_sources(before) =~= entry_sources(after)); + } + pub open(crate) spec fn policy_store(policy: CompiledPolicy) -> Arc> { policy.store } + pub open(crate) spec fn policy_trace(policy: CompiledPolicy) -> DiagnosticTrace { policy.callback_trace@ } + pub open(crate) spec fn policy_trace_empty(policy: CompiledPolicy) -> bool { + policy.callback_trace@.calls == Seq::>::empty() + } + pub open(crate) spec fn policy_sources(policy: CompiledPolicy) -> Seq> { + entry_sources(policy.rules@) + } + pub open(crate) spec fn policy_diagnostic_ids(policy: CompiledPolicy) -> Seq { + entry_diagnostic_ids(policy.rules@) + } + pub open(crate) spec fn policy_wf(policy: CompiledPolicy) -> bool { + policy_entries_wf(policy.rules@, policy.store) && policy.callback_trace@.wf() + } + pub open(crate) spec fn policy_frame(before: CompiledPolicy, after: CompiledPolicy) -> bool { + policy_wf(after) && before.store == after.store && policy_entries_frame(before.rules@, after.rules@) + } + + /// Callback observations expose selection and cardinality, not the native log representation. + pub open(crate) spec fn policy_context_calls(policy: CompiledPolicy) -> nat { + policy.callback_trace@.context_calls + } + pub open(crate) spec fn policy_diagnostic_calls(policy: CompiledPolicy) -> nat { + policy.callback_trace@.diagnostic_calls + } + pub open(crate) spec fn policy_selected_index(policy: CompiledPolicy) -> nat { + policy.callback_trace@.calls.last().index + } + pub open(crate) spec fn policy_selected_source(policy: CompiledPolicy) -> Rule { + policy.callback_trace@.calls.last().source + } + pub open(crate) spec fn policy_selected_diagnostic_id(policy: CompiledPolicy) -> int { + policy.callback_trace@.calls.last().diagnostic_id + } + pub open(crate) spec fn policy_callbacks_frame(before: CompiledPolicy, after: CompiledPolicy) -> bool { + after.callback_trace@ == before.callback_trace@ + } + + /// Constructor and retained-state facts needed by public decision clients. + pub proof fn lemma_policy_wf(policy: CompiledPolicy) + requires policy_wf(policy), + ensures books::store_wf(*policy_store(policy)), + policy_sources(policy).len() == policy_diagnostic_ids(policy).len(), + policy_context_calls(policy) == policy_diagnostic_calls(policy), + policy_trace_empty(policy) ==> policy_context_calls(policy) == 0 && policy_diagnostic_calls(policy) == 0, + {} + + /// Eliminates ordered decisions while keeping compiled entries and callback logs private. + pub proof fn lemma_policy_decision_result_facts( + before: CompiledPolicy, after: CompiledPolicy, + history: History, candidate: E, result: Result) + requires policy_decision_result(before, after, history, candidate, result), + ensures policy_wf(after), policy_frame(before, after), + policy_store(after) == policy_store(before), + policy_sources(after) == policy_sources(before), + policy_diagnostic_ids(after) == policy_diagnostic_ids(before), + no_invariant_failure(result), + (result == Err(HistoryError::WrongHistoryOwner)) + == !books::same_store_owner(policy_store(before), history_store::history::verify::store_of(history)), + match result { + Err(_) => policy_callbacks_frame(before, after) + && policy_context_calls(after) == policy_context_calls(before) + && policy_diagnostic_calls(after) == policy_diagnostic_calls(before), + Ok(PolicyDecision::Grant) => policy_callbacks_frame(before, after) + && policy_context_calls(after) == policy_context_calls(before) + && policy_diagnostic_calls(after) == policy_diagnostic_calls(before) + && compiled::ordered_result(policy_sources(before), history, candidate, Ok(None)) + && (junco_core::spec::hypotheses::event_obligations::() ==> sem::policy_permits( + sem::rule_views(policy_sources(before)), candidate, history_store::history::verify::raw_events(history))), + Ok(PolicyDecision::Deny { .. }) => policy_selected_index(after) < policy_sources(before).len() + && policy_selected_source(after) == policy_sources(before)[policy_selected_index(after) as int] + && policy_selected_diagnostic_id(after) == policy_diagnostic_ids(before)[policy_selected_index(after) as int] + && (junco_core::spec::hypotheses::event_obligations::() ==> sem::least_violation(sem::rule_views(policy_sources(before)), + candidate, history_store::history::verify::raw_events(history), policy_selected_index(after) as int)) + && (policy_wf(before) ==> policy_context_calls(after) == policy_context_calls(before) + 1 + && policy_diagnostic_calls(after) == policy_diagnostic_calls(before) + 1), + }, + { + lemma_policy_entries_frame_facts(before.rules@, after.rules@); + if let Ok(PolicyDecision::Deny { failed_precondition, allowed_fixes }) = result { + let call = after.callback_trace@.calls.last(); + let appended = DiagnosticCall { + index: call.index, source: policy_sources(before)[call.index as int], + diagnostic_id: policy_diagnostic_ids(before)[call.index as int], + failed_precondition: failed_precondition@, allowed_fixes: allowed_fixes.deep_view(), + }; + assert(after.callback_trace@.calls == before.callback_trace@.calls.push(appended)); + assert(call == appended); + } + } + + /// Retains the actual context/output observation separately from the five-argument result API. + pub proof fn lemma_policy_context_result_facts C>( + after: CompiledPolicy, context: F, result: Result) + requires policy_context_result(after, context, result), + ensures result matches Ok(PolicyDecision::Deny { failed_precondition, allowed_fixes }) ==> + exists|value: C| call_ensures(context, (), value) + && diagnostic_output(policy_selected_diagnostic_id(after), value, + failed_precondition@, allowed_fixes.deep_view()), + { + reveal(policy_context_result); + reveal(policy_selected_diagnostic_id); + if let Ok(PolicyDecision::Deny { .. }) = result { + assert(policy_selected_diagnostic_id(after) == after.callback_trace@.calls.last().diagnostic_id); + } + } + // Iterator identity conversion lets the map caller observe actual constructor completion. + pub(crate) proof fn lemma_completed_iterator_conversion(iterator: I) + requires iterator.obeys_prophetic_iter_laws(), + exists|actual: I| call_ensures(I::into_iter, (iterator,), actual) + && (actual.obeys_prophetic_iter_laws() ==> actual.will_return_none()), + ensures iterator.will_return_none(), + { + let actual = choose|actual: I| call_ensures(I::into_iter, (iterator,), actual) + && (actual.obeys_prophetic_iter_laws() ==> actual.will_return_none()); + assert(actual == iterator); + } + } +} + +#[verus_verify] +impl CompiledPolicy { + /// Keeps arbitrary conversions streaming; exact input facts require their conversion law. + /// Native event laws exclude internal invariant failures while preserving resource errors. + #[verus_spec(result => requires books::store_wf(*store), + ensures junco_core::spec::hypotheses::event_obligations::() ==> no_invariant_compile_failure(result), + result matches Ok(policy) ==> policy_wf(policy) && policy_store(policy) == store + && policy_trace_empty(policy) + && forall|items: Seq>| + junco_core::verify::history_specs::into_iter_yields(rules, items) ==> + policy_sources(policy) == items.map(|i: int, item: PolicyRule| policy_rule_source(item)) + && policy_diagnostic_ids(policy) == items.map(|i: int, item: PolicyRule| policy_rule_diagnostic(item)), + result is Ok ==> exists|converted: I::IntoIter| + call_ensures(I::into_iter, (rules,), converted) + && (converted.obeys_prophetic_iter_laws() ==> converted.will_return_none()))] + pub fn from_rules>>( + store: Arc>, + rules: I, + ) -> Result { + proof_decl! { let ghost input = rules; } + let convert = I::into_iter; + let iterator = convert(rules); + proof_decl! { let ghost converted = iterator; } + proof! { assert(call_ensures(convert, (input,), converted)); } + let result = Self::from_iterator(store, iterator); + proof! { + if let Ok(ref policy) = result { + assert(exists|actual: I::IntoIter| call_ensures(I::into_iter, (input,), actual) + && (actual.obeys_prophetic_iter_laws() ==> actual.will_return_none())); + assert forall|items: Seq>| + junco_core::verify::history_specs::into_iter_yields(input, items) implies + policy_sources(*policy) == items.map(|i: int, item: PolicyRule| policy_rule_source(item)) + && policy_diagnostic_ids(*policy) == items.map(|i: int, item: PolicyRule| policy_rule_diagnostic(item)) by { + assert(converted.obeys_prophetic_iter_laws()); + assert(converted.remaining() == items); + } + } + } + result + } +} + +#[verus_verify] +impl CompiledPolicy { + /// Compiles every source rule in order and preserves its paired diagnostic. + #[verus_verify] + #[verus_spec(result => requires books::store_wf(*store), + ensures junco_core::spec::hypotheses::event_obligations::() ==> no_invariant_compile_failure(result), + result matches Ok(policy) ==> policy_wf(policy) && policy_store(policy) == store + && policy_sources(policy) == rules@.map(|i: int, item: PolicyRule| policy_rule_source(item)) + && policy_diagnostic_ids(policy) == rules@.map(|i: int, item: PolicyRule| policy_rule_diagnostic(item)) + && policy_trace_empty(policy))] + pub fn new(store: Arc>, rules: Vec>) -> Result { + Self::from_iterator(store, rules.into_iter()) + } + + // Arbitrary iterators may diverge; actual yields are paired even without prophetic laws. + #[verus_verify] + #[cfg_attr(verus_keep_ghost, verifier::exec_allows_no_decreases_clause)] + #[verus_spec(result => requires books::store_wf(*store), + ensures junco_core::spec::hypotheses::event_obligations::() ==> no_invariant_compile_failure(result), + result matches Ok(policy) ==> policy_wf(policy) && policy.store == store + && policy.callback_trace@.calls == Seq::>::empty() + && (iterator.obeys_prophetic_iter_laws() ==> + policy_sources(policy) == iterator.remaining().map(|i: int, item: PolicyRule| policy_rule_source(item)) + && policy_diagnostic_ids(policy) == iterator.remaining().map(|i: int, item: PolicyRule| policy_rule_diagnostic(item)) + && iterator.will_return_none()))] + fn from_iterator>>( + store: Arc>, + iterator: I, + ) -> Result { + proof_decl! { let ghost original_iterator = iterator; } + proof_decl! { let ghost mut yielded: Seq> = Seq::empty(); } + let mut compiled = Vec::new(); + let mut remaining = iterator; + let mut world = ObservationWorld; + #[cfg_attr(verus_keep_ghost, verus_spec(invariant + books::store_wf(*store), policy_entries_wf(compiled@, store), + compiled@.len() == yielded.len(), + entry_sources(compiled@) == yielded.map(|i: int, item: PolicyRule| policy_rule_source(item)), + entry_diagnostic_ids(compiled@) == yielded.map(|i: int, item: PolicyRule| policy_rule_diagnostic(item)), + original_iterator == iterator, + remaining.obeys_prophetic_iter_laws() == original_iterator.obeys_prophetic_iter_laws(), + remaining.obeys_prophetic_iter_laws() ==> remaining.will_return_none() == original_iterator.will_return_none(), + remaining.obeys_prophetic_iter_laws() ==> yielded + remaining.remaining() == original_iterator.remaining()))] + loop { + let item = match remaining.next() { + Some(item) => item, + None => { + proof! { + if original_iterator.obeys_prophetic_iter_laws() { + assert(remaining.remaining().len() == 0); + assert(yielded =~= original_iterator.remaining()); + assert(original_iterator.will_return_none()); + } + } + return Ok(Self { + store, + rules: compiled, + #[cfg(verus_keep_ghost)] + callback_trace: verus_exec_expr! { Tracked(DiagnosticTrace::empty()) }, + }); + } + }; + proof_decl! { let ghost current_item = item; } + proof_decl! { let ghost previous_entries = compiled@; } + proof_decl! { let ghost previous_yielded = yielded; } + let (rule, diagnostic) = unpack_policy_rule(item); + if world.try_reserve_vec(&mut compiled, 1).is_err() { + rule.dispose(); + #[cfg_attr(verus_keep_ghost, verus_spec(invariant books::store_wf(*store)))] + loop { + match remaining.next() { + Some(pending) => { + let (source, _diagnostic) = unpack_policy_rule(pending); + source.dispose(); + } + None => return Err(CompileError::Runtime(HistoryError::AllocationFailed)), + } + } + } + let runtime = match CompiledRule::new(history_store::typed::share_store(&store), rule) { + Ok(runtime) => runtime, + Err(error) => + { + #[cfg_attr(verus_keep_ghost, verus_spec(invariant books::store_wf(*store), + junco_core::spec::hypotheses::event_obligations::() ==> no_invariant_compile_failure::>(Err(error))))] + loop { + match remaining.next() { + Some(pending) => { + let (source, _diagnostic) = unpack_policy_rule(pending); + source.dispose(); + } + None => return Err(error), + } + } + } + }; + compiled.push(CompiledPolicyRule { + runtime, + diagnostic, + }); + proof! { + yielded = yielded.push(current_item); + assert forall|i: int| 0 <= i < compiled@.len() implies + compiled::compiled_wf(compiled@[i].runtime) && compiled@[i].runtime.store == store by { + if i < previous_entries.len() { + assert(compiled@[i] == previous_entries[i]); + } + } + assert forall|i: int| 0 <= i < yielded.len() implies + compiled::source_rule(compiled@[i].runtime) == policy_rule_source(yielded[i]) + && compiled@[i].diagnostic.id() == policy_rule_diagnostic(yielded[i]) by { + if i < previous_yielded.len() { + assert(compiled@[i] == previous_entries[i]); + assert(yielded[i] == previous_yielded[i]); + assert(entry_sources(previous_entries)[i] == previous_yielded.map(|j: int, item: PolicyRule| policy_rule_source(item))[i]); + assert(entry_diagnostic_ids(previous_entries)[i] == previous_yielded.map(|j: int, item: PolicyRule| policy_rule_diagnostic(item))[i]); + } else { assert(yielded[i] == current_item); } + } + assert(entry_sources(compiled@) =~= yielded.map(|i: int, item: PolicyRule| policy_rule_source(item))); + assert(entry_diagnostic_ids(compiled@) =~= yielded.map(|i: int, item: PolicyRule| policy_rule_diagnostic(item))); + } + } + } + + /// Returns the first violation without appending to the caller's history. + /// + /// `context` and the selected diagnostic run once on denial only. Foreign histories are + /// rejected even by an empty table, before callbacks or candidate encoding. + /// Matching native store owners cannot return `WrongHistoryOwner`. + /// Operational errors cannot be internal invariant failures. + #[verus_verify] + #[verus_spec(result => requires verify::policy_wf(*old(self)), history_store::history::verify::history_wf(*history), + call_requires(context, ()), + ensures policy_decision_result(*old(self), *final(self), *history, *probe, result), + policy_context_result(*final(self), context, result), + no_invariant_failure(result))] + pub fn decide( + &mut self, + history: &History, + probe: &E, + context: impl FnOnce() -> C, + ) -> Result { + self.decide_with_limits( + history, + probe, + context, + &mut Unmetered, + &mut ObservationWorld, + ) + } + + #[verus_verify] + #[verus_spec(result => requires verify::policy_wf(*old(self)), history_store::history::verify::history_wf(*history), + call_requires(context, ()), + ensures policy_decision_result(*old(self), *final(self), *history, *probe, result), + policy_context_result(*final(self), context, result), + no_invariant_failure(result))] + pub(super) fn decide_with_limits( + &mut self, + history: &History, + probe: &E, + context: impl FnOnce() -> C, + limits: &mut L, + world: &mut ObservationWorld, + ) -> Result { + proof_decl! { let ghost entry = *self; } + proof_decl! { let ghost original_context = context; } + let index = self.first_violation_with(history, probe, limits, world)?; + proof! { + assert(verify::policy_sources(*self) =~= verify::policy_sources(entry)); + assert(verify::policy_diagnostic_ids(*self) == verify::policy_diagnostic_ids(entry)); + } + match index { + None => Ok(PolicyDecision::Grant), + Some(index) => { + let rule = &self.rules[index]; + let decision = render_denial::( + &rule.diagnostic, + context, + verus_exec_expr! { Ghost(index as nat) }, + verus_exec_expr! { Ghost(crate::compiled_rule::verify::source_rule(rule.runtime)) }, + verus_exec_expr! { Ghost(rule.diagnostic.id()) }, + verus_exec_expr! { Tracked(self.callback_trace.borrow_mut()) }, + ); + proof! { + assert(compiled::source_rule(rule.runtime) == verify::policy_sources(entry)[index as int]); + assert(rule.diagnostic.id() == verify::policy_diagnostic_ids(entry)[index as int]); + assert(verify::policy_wf(*self)); + assert(verify::policy_frame(entry, *self)); + assert(index < verify::policy_sources(entry).len()); + assert(junco_core::spec::hypotheses::event_obligations::() ==> sem::least_violation( + sem::rule_views(verify::policy_sources(entry)), *probe, + history_store::history::verify::raw_events(*history), index as int)); + let ghost observed_decision = decision; + if let PolicyDecision::Deny { failed_precondition, allowed_fixes } = observed_decision { + assert(self.callback_trace@.calls == entry.callback_trace@.calls.push(DiagnosticCall { + index: index as nat, source: verify::policy_sources(entry)[index as int], + diagnostic_id: verify::policy_diagnostic_ids(entry)[index as int], + failed_precondition: failed_precondition@, allowed_fixes: allowed_fixes.deep_view(), + })); + } + assert(self.callback_trace@.calls.last().diagnostic_id == rule.diagnostic.id()); + if let PolicyDecision::Deny { ref failed_precondition, ref allowed_fixes } = decision { + let value = choose|value: C| call_ensures(original_context, (), value) + && diagnostic_output(rule.diagnostic.id(), value, failed_precondition@, allowed_fixes.deep_view()); + assert(diagnostic_output(self.callback_trace@.calls.last().diagnostic_id, + value, failed_precondition@, allowed_fixes.deep_view())); + } + assert(policy_decision_result(entry, *self, *history, *probe, Ok(decision))); + assert(policy_context_result(*self, original_context, Ok(decision))); + } + Ok(decision) + } + } + } + + #[verus_verify] + #[verus_spec(result => requires verify::policy_wf(*old(self)), history_store::history::verify::history_wf(*history), + ensures no_invariant_failure(result), + verify::policy_wf(*final(self)), verify::policy_frame(*old(self), *final(self)), + final(self).callback_trace@ == old(self).callback_trace@, + (result == Err(HistoryError::WrongHistoryOwner)) + == !books::same_store_owner(old(self).store, history_store::history::verify::store_of(*history)), + result matches Ok(Some(index)) ==> index < final(self).rules@.len(), + crate::compiled_rule::verify::ordered_result(verify::policy_sources(*old(self)), *history, *probe, result))] + fn first_violation_with( + &mut self, + history: &History, + probe: &E, + limits: &mut L, + world: &mut ObservationWorld, + ) -> Result, HistoryError> { + proof_decl! { let ghost entry = *self; } + if !CompiledRule::same_owner(&self.store, history.store()) { + return Err(HistoryError::WrongHistoryOwner); + } + let mut index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec(invariant + index <= self.rules@.len(), verify::policy_wf(*self), verify::policy_frame(entry, *self), + entry == *old(self), + self.callback_trace@ == entry.callback_trace@, + history_store::history::verify::history_wf(*history), + books::same_store_owner(entry.store, history_store::history::verify::store_of(*history)), + junco_core::spec::hypotheses::event_obligations::() ==> + forall|j: int| 0 <= j < index ==> !sem::rule_violated( + verify::policy_sources(entry)[j]@, *probe, history_store::history::verify::raw_events(*history)), + decreases self.rules@.len() - index))] + while index < self.rules.len() { + proof_decl! { let ghost before = *self; } + let rule = &mut self.rules[index]; + let answer = rule + .runtime + .accepts_history_with_limits(history, probe, limits, world); + let mode = rule.runtime.mode(); + proof! { + if junco_core::spec::hypotheses::event_obligations::() { + crate::compiled_rule::verify::lemma_dsl_violation(rule.runtime, *history, *probe, answer, mode); + } + verify::lemma_policy_entries_frame_facts(entry.rules@, before.rules@); + assert forall|j: int| 0 <= j < entry.rules@.len() implies + compiled::compiled_structure_frame(entry.rules@[j].runtime, self.rules@[j].runtime) + && self.rules@[j].diagnostic.id() == entry.rules@[j].diagnostic.id() by { + if j != index as int { assert(self.rules@[j] == before.rules@[j]); } + assert(verify::entry_diagnostic_ids(before.rules@)[j] == verify::entry_diagnostic_ids(entry.rules@)[j]); + } + assert(verify::entry_diagnostic_ids(self.rules@) =~= verify::entry_diagnostic_ids(entry.rules@)); + verify::lemma_policy_entries_frame_facts(entry.rules@, self.rules@); + assert(verify::policy_wf(*self)); + assert(verify::policy_frame(entry, *self)); + } + let violated = match answer? { + None => false, + Some(inside) => match mode { + RuleMode::Forbid => inside, + RuleMode::Require => !inside, + }, + }; + if violated { + return Ok(Some(index)); + } + index += 1; + } + proof! { + if junco_core::spec::hypotheses::event_obligations::() { + crate::compiled_rule::verify::lemma_no_violation_permits( + verify::policy_sources(entry), *probe, history_store::history::verify::raw_events(*history)); + } + } + Ok(None) + } +} diff --git a/src/history-semantics/src/policy/language.rs b/src/history-semantics/src/policy/language.rs new file mode 100644 index 000000000..cf02a1759 --- /dev/null +++ b/src/history-semantics/src/policy/language.rs @@ -0,0 +1,33 @@ +//! The tail shape a state-machine policy classifies a resource's history with. + +#[cfg(verus_keep_ghost)] +use alloc::boxed::Box; +use alloc::vec; +#[cfg(verus_keep_ghost)] +use history_syntax::spec::events::RegexView; +use history_syntax::{Event, RegexExpr, TestExpr}; +use vstd::prelude::*; + +/// A setter event followed only by stable events, with any preceding history. +/// +/// Setter and stable tests may overlap; this does not assert a unique last setter. +#[verus_verify] +#[verus_spec(result => ensures result@ == RegexView::Concat(seq![ + RegexView::All, RegexView::Test(setter@), + RegexView::Star(Box::new(RegexView::Test(stable@))), +]))] +pub fn last_state_change(setter: TestExpr, stable: TestExpr) -> RegexExpr { + proof_decl! { let ghost expected = seq![RegexView::All, RegexView::Test(setter@), + RegexView::Star(Box::new(RegexView::Test(stable@)))]; } + let result = RegexExpr::Concat(vec![ + RegexExpr::all(), + RegexExpr::test(setter), + RegexExpr::star(RegexExpr::test(stable)), + ]); + proof! { + reveal_with_fuel(history_syntax::spec::events::regex_view, 3); + broadcast use {vstd::std_specs::vec::group_vec_axioms, vstd::seq::group_seq_lemmas}; + assert(match result@ { RegexView::Concat(parts) => parts =~= expected, _ => false }); + } + result +} diff --git a/src/history-semantics/src/policy/mod.rs b/src/history-semantics/src/policy/mod.rs new file mode 100644 index 000000000..0e7d6cb9d --- /dev/null +++ b/src/history-semantics/src/policy/mod.rs @@ -0,0 +1,25 @@ +//! Ordered declarative trace policies over externally owned histories. +//! +//! Checked construction preserves source/diagnostic order; checked selection uses the +//! shared compiled-rule contracts. Field unpacking and context/diagnostic invocation +//! are native leaves. Arbitrary callbacks need not be pure, deterministic, or terminating. + +mod atoms; +mod decision; +pub mod evaluate; +mod language; +pub mod rule; +pub mod trace; + +pub use atoms::{ + PRINCIPAL_VAR, RESOURCE_VAR, action_is, component_equals, component_is, principal_is, + resource_is, +}; +pub use decision::PolicyDecision; +pub use evaluate::CompiledPolicy; +pub use language::last_state_change; +pub use rule::{Diagnostic, PolicyRule, forbid}; +pub use trace::{TraceDiagnostic, TracePolicy, TraceRule}; + +#[cfg(test)] +mod tests; diff --git a/src/history-semantics/src/policy/rule.rs b/src/history-semantics/src/policy/rule.rs new file mode 100644 index 000000000..65bbd60d1 --- /dev/null +++ b/src/history-semantics/src/policy/rule.rs @@ -0,0 +1,135 @@ +//! The rule/diagnostic pairing a policy table is built from, generalized over the per-policy +//! context a denial renders from. + +use alloc::{boxed::Box, string::String, vec::Vec}; + +#[cfg(verus_keep_ghost)] +use self::verify::{diagnostic_identity, policy_rule_diagnostic, policy_rule_source}; +use super::atoms::{PRINCIPAL_VAR, RESOURCE_VAR}; +#[cfg(verus_keep_ghost)] +use history_syntax::spec::events::PatternView; +use history_syntax::{ComponentPattern, Event, Head, RegexExpr, Rule, RuleMode}; +use vstd::prelude::*; +#[cfg(verus_keep_ghost)] +use vstd::view::DeepView; + +/// Renders a violated rule's `(failed_precondition, allowed_fixes)` from the policy's context. +#[cfg(not(verus_keep_ghost))] +pub type Diagnostic = Box (String, Vec)>; +#[cfg(verus_keep_ghost)] +pub type Diagnostic = NativeDiagnostic; + +/// One trace-policy rule paired with the diagnostic its violation surfaces. +#[verus_verify(external_body)] +#[cfg_attr(verus_keep_ghost, verifier::reject_recursive_types(E))] +#[cfg_attr(verus_keep_ghost, verifier::reject_recursive_types(C))] +pub struct PolicyRule { + pub rule: Rule, + pub diagnostic: Diagnostic, +} + +type DiagnosticRenderer = dyn Fn(&C) -> (String, Vec); + +// Only callback storage is opaque; the raw payload avoids a recursive ghost alias. +#[doc(hidden)] +#[verus_verify(external_body)] +#[cfg_attr(verus_keep_ghost, verifier::reject_recursive_types(C))] +pub struct NativeDiagnostic { + pub(crate) inner: Box>, +} + +#[cfg(verus_keep_ghost)] +verus! { +impl NativeDiagnostic { + // Equality witness only: no freshness or uniqueness is assumed. + pub uninterp spec fn id(&self) -> int; +} + +pub mod verify { + use super::*; + + pub uninterp spec fn policy_rule_source(item: PolicyRule) -> Rule; + pub uninterp spec fn policy_rule_diagnostic(item: PolicyRule) -> int; + + // Identity of the supplied native Box only; no freshness or output law. + pub open spec fn diagnostic_identity(diagnostic: Diagnostic) -> int { + diagnostic.id() + } + + pub uninterp spec fn diagnostic_output(id: int, context: C, + failed: Seq, fixes: Seq>) -> bool; +} +} + +/// Stores the supplied callback in the same single Box used by native diagnostics. +#[doc(hidden)] +#[verus_verify] +#[verus_verify(external_body)] +#[verus_spec(result => requires + forall|argument: &C| call_requires(diagnostic, (argument,)), + ensures forall|value: C, output: (String, Vec)| + verify::diagnostic_output(diagnostic_identity(result), value, + output.0@, output.1.deep_view()) ==> + exists|argument: &C| *argument == value + && call_ensures(diagnostic, (argument,), output))] +pub fn diagnostic_from_fn (String, Vec) + 'static>( + diagnostic: F, +) -> Diagnostic { + #[cfg(verus_keep_ghost)] + { + NativeDiagnostic { + inner: Box::new(diagnostic), + } + } + #[cfg(not(verus_keep_ghost))] + { + Box::new(diagnostic) + } +} + +// The sole trusted constructor operation is native source/callback field storage. +#[verus_verify] +#[verus_verify(external_body)] +#[verus_spec(result => ensures policy_rule_source(result) == rule, + policy_rule_diagnostic(result) == diagnostic_identity(diagnostic))] +pub(crate) fn pack_policy_rule( + rule: Rule, + diagnostic: Diagnostic, +) -> PolicyRule { + PolicyRule { rule, diagnostic } +} + +/// Builds a `Forbid` rule using the three-ary `(principal, action, resource)` convention. +#[verus_verify] +#[verus_spec(result => requires history_syntax::spec::events::arity::() == 3, + ensures + policy_rule_source(result).mode == RuleMode::Forbid, + policy_rule_source(result).head@ == seq![ + PatternView::Variable(seq!['p']), PatternView::Constant(action), PatternView::Variable(seq!['r']), + ], + policy_rule_source(result).tail == tail, + policy_rule_diagnostic(result) == diagnostic_identity(diagnostic), +)] +// The iterator proof below needs a Vec built by pushes, not vec!. +#[allow(clippy::vec_init_then_push)] +pub fn forbid( + action: E::Component, + tail: RegexExpr, + diagnostic: Diagnostic, +) -> PolicyRule { + proof! { + reveal_strlit("p"); + reveal_strlit("r"); + assert(PRINCIPAL_VAR@ == seq!['p']); + assert(RESOURCE_VAR@ == seq!['r']); + } + let mut slots = Vec::with_capacity(3); + slots.push(ComponentPattern::Variable(String::from_str(PRINCIPAL_VAR))); + slots.push(ComponentPattern::Constant(action)); + slots.push(ComponentPattern::Variable(String::from_str(RESOURCE_VAR))); + let iter = slots.into_iter(); + proof! { vstd::std_specs::iter::axiom_from_iterator_ensures(iter); } + let head = Head::new(iter); + let rule = Rule::new(RuleMode::Forbid, head, tail); + pack_policy_rule(rule, diagnostic) +} diff --git a/src/history-semantics/src/policy/tests.rs b/src/history-semantics/src/policy/tests.rs new file mode 100644 index 000000000..fac6f43a5 --- /dev/null +++ b/src/history-semantics/src/policy/tests.rs @@ -0,0 +1,509 @@ +//! A miniature non-lock policy, assembled only from kernel pieces. +//! +//! The lock table is not the contract under test here: this file exists to pin that [`super::atoms`], +//! [`super::language`], [`super::rule`] and [`super::evaluate`] carry no lock assumptions, by +//! building a policy over a different vocabulary and running it through the same loop. + +use alloc::{ + boxed::Box, + format, + rc::Rc, + string::{String, ToString}, + sync::Arc, + vec, + vec::Vec, +}; +use core::{cell::Cell, fmt}; + +use super::CompiledPolicy; +use super::atoms::{action_is, principal_is, resource_is}; +use super::decision::PolicyDecision; +use super::language::last_state_change; +use super::rule::{PolicyRule, forbid}; +use history_store::{History, Store}; +use history_syntax::{Comparison, Component, Event, N3, TestExpr}; + +/// Principals of the miniature policy. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +enum Editor { + Alice, + Bob, +} + +impl fmt::Display for Editor { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(match self { + Self::Alice => "alice", + Self::Bob => "bob", + }) + } +} + +/// The one resource the miniature policy guards. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +struct SrcX; + +impl fmt::Display for SrcX { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("src/x") + } +} + +/// Operations of the miniature policy; deliberately distinct from a lock-policy vocabulary. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +enum DocAction { + Read, + Edit, +} + +/// One event of the miniature policy. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +struct DocEvent { + principal: Editor, + action: DocAction, + resource: SrcX, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +enum DocComponent { + Principal(Editor), + Action(DocAction), + Resource(SrcX), +} + +// Unverified glue: `hash_respects_eq` is a hypothesis for this type (as `event_laws` already is). +impl history_syntax::KeyHash for DocComponent { + fn key_hash(&self) -> u64 { + history_syntax::key_hash::hash_via_std(self) + } +} + +impl Event for DocEvent { + type Component = DocComponent; + type Arity = N3; + + fn component(self, index: usize) -> DocComponent { + match index { + 0 => DocComponent::Principal(self.principal), + 1 => DocComponent::Action(self.action), + _ => DocComponent::Resource(self.resource), + } + } + + fn coordinate(component: DocComponent) -> usize { + match component { + DocComponent::Principal(_) => 0, + DocComponent::Action(_) => 1, + DocComponent::Resource(_) => 2, + } + } +} + +/// Context of the miniature policy: the resource and who last edited it. +struct LastEditor { + resource: String, + editor: String, +} + +/// The whole table: reading a resource whose last state change was a foreign edit is forbidden. +fn rules() -> Vec> { + let setter = TestExpr::and([ + resource_is(Comparison::Eq), + action_is(DocComponent::Action(DocAction::Edit), Comparison::Eq), + principal_is(Comparison::Neq), + ]); + let stable = TestExpr::or([ + resource_is(Comparison::Neq), + action_is(DocComponent::Action(DocAction::Read), Comparison::Eq), + ]); + vec![forbid( + DocComponent::Action(DocAction::Read), + last_state_change(setter, stable), + Box::new(|context| { + let LastEditor { resource, editor } = context; + ( + format!("{resource} was last edited by {editor}"), + vec![format!("{editor} release {resource}")], + ) + }), + )] +} + +/// Builds the context for `candidate`: the last principal to edit its resource, or `"nobody"`. +fn context(history: &[DocEvent], candidate: &DocEvent) -> LastEditor { + let editor = history + .iter() + .rfind(|event| event.resource == candidate.resource && event.action == DocAction::Edit) + .map_or_else(|| "nobody".to_string(), |event| event.principal.to_string()); + LastEditor { + resource: candidate.resource.to_string(), + editor, + } +} + +#[test] +fn a_non_lock_policy_reuses_the_kernel_loop() { + let candidate = DocEvent { + principal: Editor::Bob, + action: DocAction::Read, + resource: SrcX, + }; + + let store = Arc::new(Store::new().unwrap()); + let mut policy = CompiledPolicy::new(Arc::clone(&store), rules()).unwrap(); + let history = History::new(Arc::clone(&store)).unwrap(); + assert_eq!( + policy + .decide(&history, &candidate, || context( + history.as_slice(), + &candidate + )) + .unwrap(), + PolicyDecision::Grant, + ); + + let history = History::from_events( + store, + [DocEvent { + principal: Editor::Alice, + action: DocAction::Edit, + resource: SrcX, + }], + ) + .unwrap(); + assert_eq!( + policy + .decide(&history, &candidate, || context( + history.as_slice(), + &candidate + )) + .unwrap(), + PolicyDecision::Deny { + failed_precondition: "src/x was last edited by alice".to_string(), + allowed_fixes: vec!["alice release src/x".to_string()], + }, + ); +} + +fn candidate(action: DocAction) -> DocEvent { + DocEvent { + principal: Editor::Bob, + action, + resource: SrcX, + } +} + +fn counted_rule( + mode: history_syntax::RuleMode, + tail: history_syntax::RegexExpr, + calls: Rc>, + label: &'static str, +) -> PolicyRule { + let mut rule = forbid( + DocComponent::Action(DocAction::Read), + tail, + Box::new(move |context| { + assert_eq!(*context, 7); + calls.set(calls.get() + 1); + (label.into(), vec![label.into()]) + }), + ); + rule.rule.mode = mode; + rule +} + +#[test] +fn empty_tables_check_owner_before_context() { + let store = Arc::new(Store::new().unwrap()); + let mut policy = CompiledPolicy::::new(Arc::clone(&store), vec![]).unwrap(); + let history = History::new(store).unwrap(); + let foreign = History::new(Arc::new(Store::new().unwrap())).unwrap(); + let probe = candidate(DocAction::Read); + assert_eq!( + policy.decide(&history, &probe, || panic!("grant has no context")), + Ok(PolicyDecision::Grant) + ); + assert_eq!( + policy.decide(&foreign, &probe, || panic!( + "foreign history has no context" + )), + Err(junco_core::HistoryError::WrongHistoryOwner) + ); + assert!(history.is_empty()); + assert!(foreign.is_empty()); +} + +#[test] +fn callbacks_run_once_for_the_first_actual_violation_only() { + use history_syntax::{RegexExpr, RuleMode}; + let store = Arc::new(Store::new().unwrap()); + let history = History::from_events(Arc::clone(&store), [candidate(DocAction::Edit)]).unwrap(); + let original = history.as_slice().to_vec(); + let first = Rc::new(Cell::new(0)); + let second = Rc::new(Cell::new(0)); + let contexts = Cell::new(0); + let mut policy = CompiledPolicy::new( + Arc::clone(&store), + vec![ + counted_rule( + RuleMode::Require, + RegexExpr::all(), + Rc::clone(&first), + "grant", + ), + counted_rule( + RuleMode::Forbid, + RegexExpr::empty(), + Rc::clone(&second), + "grant", + ), + ], + ) + .unwrap(); + assert_eq!( + policy.decide(&history, &candidate(DocAction::Read), || panic!( + "grant has no context" + )), + Ok(PolicyDecision::Grant) + ); + assert_eq!( + policy.decide(&history, &candidate(DocAction::Edit), || panic!( + "head mismatch has no context" + )), + Ok(PolicyDecision::Grant) + ); + assert_eq!((first.get(), second.get()), (0, 0)); + + for mode in [RuleMode::Require, RuleMode::Forbid] { + let tail = match mode { + RuleMode::Require => RegexExpr::empty(), + RuleMode::Forbid => RegexExpr::all(), + }; + let mut policy = CompiledPolicy::new( + Arc::clone(&store), + vec![ + counted_rule(mode, tail, Rc::clone(&first), "first"), + counted_rule( + RuleMode::Forbid, + RegexExpr::all(), + Rc::clone(&second), + "second", + ), + ], + ) + .unwrap(); + assert_eq!( + policy.decide(&history, &candidate(DocAction::Read), || { + contexts.set(contexts.get() + 1); + 7 + }), + Ok(PolicyDecision::Deny { + failed_precondition: "first".into(), + allowed_fixes: vec!["first".into()], + }) + ); + } + assert_eq!((contexts.get(), first.get(), second.get()), (2, 2, 0)); + assert_eq!(history.as_slice(), original); +} + +struct FailPublication; + +impl junco_core::limits::Limits for FailPublication { + fn checkpoint(&mut self) -> Result<(), junco_core::limits::LimitError> { + Ok(()) + } + fn publication_checkpoint(&mut self) -> Result<(), junco_core::limits::LimitError> { + Err(junco_core::limits::LimitError::MemoryLimitExceeded { usage: 1, limit: 0 }) + } + fn enforce_memory(&mut self) -> Result<(), junco_core::limits::LimitError> { + Ok(()) + } +} + +#[test] +fn runtime_errors_never_render_denials_or_change_history() { + use history_syntax::{RegexExpr, RuleMode}; + use junco_core::HistoryError; + let store = Arc::new(Store::new().unwrap()); + let mut history = History::new(Arc::clone(&store)).unwrap(); + let calls = Rc::new(Cell::new(0)); + let mut policy = CompiledPolicy::new( + store, + vec![counted_rule( + RuleMode::Forbid, + RegexExpr::all(), + Rc::clone(&calls), + "denied", + )], + ) + .unwrap(); + let probe = candidate(DocAction::Read); + assert!(matches!( + policy.decide(&history, &probe, || 7), + Ok(PolicyDecision::Deny { .. }) + )); + calls.set(0); + history.push(candidate(DocAction::Edit)).unwrap(); + let raw = history.as_slice().to_vec(); + let numeric = history.numeric().as_slice().to_vec(); + let revision = history.numeric().revision(); + assert!(matches!( + policy.decide_with_limits( + &history, + &probe, + || panic!("runtime error has no context"), + &mut FailPublication, + &mut junco_core::observation::ObservationWorld + ), + Err(HistoryError::Limit(_)) + )); + assert_eq!(calls.get(), 0); + assert_eq!(history.as_slice(), raw); + assert_eq!(history.numeric().as_slice(), numeric); + assert_eq!(history.numeric().revision(), revision); + + let failure = junco_core::observation::fail_reservations_after(0); + let new_probe = DocEvent { + principal: Editor::Alice, + ..probe + }; + assert_eq!( + policy.decide(&history, &new_probe, || panic!( + "allocation error has no context" + )), + Err(HistoryError::AllocationFailed) + ); + drop(failure); + assert_eq!(calls.get(), 0); + assert_eq!(history.as_slice(), raw); + assert_eq!(history.numeric().as_slice(), numeric); + assert_eq!(history.numeric().revision(), revision); + assert!(matches!( + policy.decide(&history, &probe, || 7), + Ok(PolicyDecision::Deny { .. }) + )); + assert_eq!(calls.get(), 1); +} + +fn deep_rule() -> history_syntax::Rule { + let mut tail = history_syntax::RegexExpr::all(); + for _ in 0..4096 { + tail = history_syntax::RegexExpr::star(tail); + } + forbid( + DocComponent::Action(DocAction::Read), + tail, + Box::new(|_: &()| (String::new(), vec![])), + ) + .rule +} + +fn invalid_rule() -> history_syntax::Rule { + forbid( + DocComponent::Action(DocAction::Read), + history_syntax::RegexExpr::test(TestExpr::atom( + Comparison::Eq, + history_syntax::AtomPattern::new( + Component(0), + history_syntax::ComponentPattern::variable("missing"), + ), + )), + Box::new(|_: &()| (String::new(), vec![])), + ) + .rule +} + +#[test] +fn failed_constructors_drain_deep_remaining_source_rules() { + use super::{TracePolicy, TraceRule}; + let store = Arc::new(Store::::new().unwrap()); + let rules = vec![deep_rule(), deep_rule()] + .into_iter() + .map(|rule| PolicyRule { + rule, + diagnostic: Box::new(|_: &()| (String::new(), vec![])), + }) + .collect(); + let failure = junco_core::observation::fail_reservations_after(0); + assert!(matches!( + CompiledPolicy::new(Arc::clone(&store), rules), + Err(junco_core::CompileError::Runtime( + junco_core::HistoryError::AllocationFailed + )) + )); + drop(failure); + + let rules = vec![invalid_rule(), deep_rule(), deep_rule()] + .into_iter() + .map(|rule| PolicyRule { + rule, + diagnostic: Box::new(|_: &()| (String::new(), vec![])), + }) + .collect(); + assert!(matches!( + CompiledPolicy::new(Arc::clone(&store), rules), + Err(junco_core::CompileError::UnboundVariable { .. }) + )); + + let rules = [deep_rule(), deep_rule()] + .into_iter() + .map(|rule| TraceRule::new(rule, |_| (String::new(), vec![]))); + let failure = junco_core::observation::fail_reservations_after(0); + assert!(matches!( + TracePolicy::new(Arc::clone(&store), rules), + Err(junco_core::CompileError::Runtime( + junco_core::HistoryError::AllocationFailed + )) + )); + drop(failure); + let rules = [invalid_rule(), deep_rule(), deep_rule()] + .into_iter() + .map(|rule| TraceRule::new(rule, |_| (String::new(), vec![]))); + assert!(matches!( + TracePolicy::new(store, rules), + Err(junco_core::CompileError::UnboundVariable { .. }) + )); +} + +#[test] +fn trace_policy_uses_the_same_store_without_mutating_external_history() { + use super::{TracePolicy, TraceRule}; + let store = Arc::new(Store::new().unwrap()); + let history = History::new(Arc::clone(&store)).unwrap(); + let rule = forbid( + DocComponent::Action(DocAction::Read), + history_syntax::RegexExpr::all(), + Box::new(|_: &()| (String::new(), vec![])), + ) + .rule; + let calls = Arc::new(core::sync::atomic::AtomicUsize::new(0)); + let diagnostic_calls = Arc::clone(&calls); + let rule = TraceRule::new(rule, move |event: &DocEvent| { + diagnostic_calls.fetch_add(1, core::sync::atomic::Ordering::SeqCst); + (event.principal.to_string(), vec![]) + }); + let cloned = rule.clone(); + assert!(format!("{cloned:?}").starts_with("TraceRule")); + let mut policy = TracePolicy::new(store, [cloned]).unwrap(); + assert_eq!( + policy.decide(&history, &candidate(DocAction::Edit)), + Ok(PolicyDecision::Grant) + ); + assert_eq!(calls.load(core::sync::atomic::Ordering::SeqCst), 0); + assert_eq!( + policy.decide(&history, &candidate(DocAction::Read)), + Ok(PolicyDecision::Deny { + failed_precondition: "bob".into(), + allowed_fixes: vec![], + }) + ); + assert_eq!(calls.load(core::sync::atomic::Ordering::SeqCst), 1); + let foreign = History::new(Arc::new(Store::new().unwrap())).unwrap(); + assert_eq!( + policy.decide(&foreign, &candidate(DocAction::Read)), + Err(junco_core::HistoryError::WrongHistoryOwner) + ); + assert_eq!(calls.load(core::sync::atomic::Ordering::SeqCst), 1); + assert!(history.is_empty()); +} diff --git a/src/history-semantics/src/policy/trace.rs b/src/history-semantics/src/policy/trace.rs new file mode 100644 index 000000000..df6915de2 --- /dev/null +++ b/src/history-semantics/src/policy/trace.rs @@ -0,0 +1,425 @@ +//! A caller-assembled trace policy whose history stays with the caller. + +use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec}; +use core::fmt; + +#[cfg(verus_keep_ghost)] +use self::verify::*; +use super::decision::PolicyDecision; +use super::evaluate::CompiledPolicy; +#[cfg(verus_keep_ghost)] +use super::rule::verify::{ + diagnostic_identity, diagnostic_output, policy_rule_diagnostic, policy_rule_source, +}; +use super::rule::{Diagnostic, PolicyRule, pack_policy_rule}; +use history_store::{History, Store}; +use history_syntax::{Event, Rule}; +#[cfg(verus_keep_ghost)] +use junco_core::spec::semantics as sem; +#[cfg(verus_keep_ghost)] +use junco_core::verify::history_specs::{no_invariant_compile_failure, no_invariant_failure}; +use junco_core::{CompileError, HistoryError}; +use vstd::prelude::*; +#[cfg(verus_keep_ghost)] +use vstd::std_specs::iter::IteratorSpec; +#[cfg(verus_keep_ghost)] +use vstd::view::DeepView; + +/// Renders a violated rule's `(failed_precondition, allowed_fixes)` from the candidate event. +#[cfg(not(verus_keep_ghost))] +pub type TraceDiagnostic = Arc (String, Vec) + Send + Sync>; + +// Verus cannot model a dyn Fn with auto-trait bounds; retain the same native Arc payload. +#[cfg(verus_keep_ghost)] +pub type TraceDiagnostic = NativeTraceDiagnostic; + +#[cfg(verus_keep_ghost)] +#[doc(hidden)] +#[verus_verify(external_body)] +#[cfg_attr(verus_keep_ghost, verifier::reject_recursive_types(E))] +pub struct NativeTraceDiagnostic { + inner: Arc (String, Vec) + Send + Sync>, +} + +#[cfg(verus_keep_ghost)] +pub mod verify { + use super::*; + verus! { + broadcast use {vstd::std_specs::vec::group_vec_axioms, vstd::seq::group_seq_lemmas}; + + // Callback identities describe physical selection, not freshness or deterministic outputs. + pub uninterp spec fn trace_callback_identity(diagnostic: D) -> int; + pub uninterp spec fn trace_diagnostic_identity(diagnostic: TraceDiagnostic) -> int; + // One observed invocation of the stored Arc Fn, retaining its actual argument reference. + pub uninterp spec fn trace_arc_call(diagnostic: TraceDiagnostic, argument: &E, + output: (String, Vec)) -> bool; + pub uninterp spec fn trace_rule_source(item: TraceRule) -> Rule; + pub uninterp spec fn trace_rule_diagnostic(item: TraceRule) -> TraceDiagnostic; + pub open spec fn trace_rule_diagnostic_id(item: TraceRule) -> int { + trace_diagnostic_identity(trace_rule_diagnostic(item)) + } + pub open(super) spec fn trace_wf(policy: TracePolicy) -> bool { + super::super::evaluate::verify::policy_wf(policy.compiled) + } + pub open(super) spec fn trace_store(policy: TracePolicy) -> Arc> { + super::super::evaluate::verify::policy_store(policy.compiled) + } + pub open(super) spec fn trace_sources(policy: TracePolicy) -> Seq> { + super::super::evaluate::verify::policy_sources(policy.compiled) + } + pub open(super) spec fn trace_diagnostic_ids(policy: TracePolicy) -> Seq { + super::super::evaluate::verify::policy_diagnostic_ids(policy.compiled) + } + pub open(super) spec fn trace_context_calls(policy: TracePolicy) -> nat { + super::super::evaluate::verify::policy_context_calls(policy.compiled) + } + pub open(super) spec fn trace_diagnostic_calls(policy: TracePolicy) -> nat { + super::super::evaluate::verify::policy_diagnostic_calls(policy.compiled) + } + pub open(super) spec fn trace_selected_index(policy: TracePolicy) -> nat { + super::super::evaluate::verify::policy_selected_index(policy.compiled) + } + pub open(super) spec fn trace_selected_diagnostic_id(policy: TracePolicy) -> int { + super::super::evaluate::verify::policy_selected_diagnostic_id(policy.compiled) + } + pub open(super) spec fn trace_selected_source(policy: TracePolicy) -> Rule { + super::super::evaluate::verify::policy_selected_source(policy.compiled) + } + pub closed spec fn trace_frame(before: TracePolicy, after: TracePolicy) -> bool { + super::super::evaluate::verify::policy_frame(before.compiled, after.compiled) + } + pub closed spec fn trace_callbacks_frame(before: TracePolicy, after: TracePolicy) -> bool { + super::super::evaluate::verify::policy_callbacks_frame(before.compiled, after.compiled) + } + + /// Exposes constructor readiness without exposing the compiled policy field. + pub proof fn lemma_trace_wf(policy: TracePolicy) + requires trace_wf(policy), + ensures history_store::typed::verify::store_wf(*trace_store(policy)), + trace_sources(policy).len() == trace_diagnostic_ids(policy).len(), + trace_context_calls(policy) == trace_diagnostic_calls(policy), + { + super::super::evaluate::verify::lemma_policy_wf(policy.compiled); + } + pub open(super) spec fn trace_decision_result( + before: TracePolicy, after: TracePolicy, history: History, candidate: E, + result: Result, + ) -> bool { + super::super::evaluate::policy_decision_result(before.compiled, after.compiled, history, candidate, result) + && no_invariant_failure(result) + && trace_wf(after) && trace_store(after) == trace_store(before) + && trace_sources(after) == trace_sources(before) + && trace_diagnostic_ids(after) == trace_diagnostic_ids(before) + && ((result == Err(HistoryError::WrongHistoryOwner)) + == !history_store::typed::verify::same_store_owner(trace_store(before), history_store::history::verify::store_of(history))) + && match result { + Err(_) => trace_context_calls(after) == trace_context_calls(before) + && trace_diagnostic_calls(after) == trace_diagnostic_calls(before), + Ok(PolicyDecision::Grant) => trace_context_calls(after) == trace_context_calls(before) + && trace_diagnostic_calls(after) == trace_diagnostic_calls(before) + && (junco_core::spec::hypotheses::event_obligations::() ==> + sem::policy_permits(sem::rule_views(trace_sources(before)), candidate, + history_store::history::verify::raw_events(history))), + Ok(PolicyDecision::Deny { failed_precondition, allowed_fixes }) => + trace_context_calls(after) == trace_context_calls(before) + 1 + && trace_diagnostic_calls(after) == trace_diagnostic_calls(before) + 1 + && trace_selected_index(after) < trace_sources(before).len() + && trace_selected_diagnostic_id(after) == trace_diagnostic_ids(before)[trace_selected_index(after) as int] + && (junco_core::spec::hypotheses::event_obligations::() ==> + sem::least_violation(sem::rule_views(trace_sources(before)), candidate, + history_store::history::verify::raw_events(history), trace_selected_index(after) as int)) + && diagnostic_output(super::super::evaluate::verify::policy_trace(after.compiled).calls.last().diagnostic_id, + candidate, failed_precondition@, allowed_fixes.deep_view()), + } + } + + // Eliminate the compiled frame and callback log before repackaging the facade result. + pub(super) proof fn lemma_trace_decision_result( + before: TracePolicy, after: TracePolicy, history: History, candidate: E, + result: Result, + ) + requires trace_wf(before), + super::super::evaluate::policy_decision_result( + before.compiled, after.compiled, history, candidate, result), + result matches Ok(PolicyDecision::Deny { failed_precondition, allowed_fixes }) ==> + diagnostic_output(super::super::evaluate::verify::policy_trace(after.compiled).calls.last().diagnostic_id, + candidate, failed_precondition@, allowed_fixes.deep_view()), + ensures trace_decision_result(before, after, history, candidate, result), + { + super::super::evaluate::verify::lemma_policy_decision_result_facts( + before.compiled, after.compiled, history, candidate, result); + } + + /// Eliminates facade outcomes using public source, owner, and callback observations only. + pub proof fn lemma_trace_decision_result_facts( + before: TracePolicy, after: TracePolicy, history: History, candidate: E, + result: Result) + requires trace_decision_result(before, after, history, candidate, result), + ensures trace_wf(after), trace_frame(before, after), + trace_store(after) == trace_store(before), trace_sources(after) == trace_sources(before), + trace_diagnostic_ids(after) == trace_diagnostic_ids(before), + no_invariant_failure(result), + (result == Err(HistoryError::WrongHistoryOwner)) + == !history_store::typed::verify::same_store_owner(trace_store(before), history_store::history::verify::store_of(history)), + match result { + Err(_) => trace_callbacks_frame(before, after) + && trace_context_calls(after) == trace_context_calls(before) + && trace_diagnostic_calls(after) == trace_diagnostic_calls(before), + Ok(PolicyDecision::Grant) => trace_callbacks_frame(before, after) + && trace_context_calls(after) == trace_context_calls(before) + && trace_diagnostic_calls(after) == trace_diagnostic_calls(before) + && (junco_core::spec::hypotheses::event_obligations::() ==> + sem::policy_permits(sem::rule_views(trace_sources(before)), candidate, + history_store::history::verify::raw_events(history))), + Ok(PolicyDecision::Deny { failed_precondition, allowed_fixes }) => + trace_context_calls(after) == trace_context_calls(before) + 1 + && trace_diagnostic_calls(after) == trace_diagnostic_calls(before) + 1 + && trace_selected_index(after) < trace_sources(before).len() + && trace_selected_source(after) == trace_sources(before)[trace_selected_index(after) as int] + && trace_selected_diagnostic_id(after) == trace_diagnostic_ids(before)[trace_selected_index(after) as int] + && (junco_core::spec::hypotheses::event_obligations::() ==> + sem::least_violation(sem::rule_views(trace_sources(before)), candidate, + history_store::history::verify::raw_events(history), trace_selected_index(after) as int)) + && diagnostic_output(trace_selected_diagnostic_id(after), candidate, + failed_precondition@, allowed_fixes.deep_view()), + }, + { + super::super::evaluate::verify::lemma_policy_decision_result_facts( + before.compiled, after.compiled, history, candidate, result); + } + } +} + +// Only native Arc allocation and storage of the supplied Fn are opaque. +#[verus_verify] +#[verus_verify(external_body)] +#[verus_spec(result => requires forall|argument: &E| call_requires(diagnostic, (argument,)), + ensures trace_diagnostic_identity(result) == trace_callback_identity(diagnostic), + forall|value: E, output: (String, Vec)| + diagnostic_output(trace_diagnostic_identity(result), value, output.0@, output.1.deep_view()) ==> + exists|argument: &E| *argument == value && call_ensures(diagnostic, (argument,), output), + forall|argument: &E, output: (String, Vec)| + trace_arc_call(result, argument, output) ==> call_ensures(diagnostic, (argument,), output))] +fn store_trace_diagnostic (String, Vec) + Send + Sync + 'static>( + diagnostic: D, +) -> TraceDiagnostic { + #[cfg(not(verus_keep_ghost))] + { + Arc::new(diagnostic) + } + #[cfg(verus_keep_ghost)] + { + NativeTraceDiagnostic { + inner: Arc::new(diagnostic), + } + } +} + +// Native field movement retains the actual Arc, not just a source-language approximation. +#[verus_verify] +#[verus_verify(external_body)] +#[verus_spec(result => ensures trace_rule_source(result) == rule, + trace_rule_diagnostic(result) == diagnostic)] +fn pack_trace_rule(rule: Rule, diagnostic: TraceDiagnostic) -> TraceRule { + TraceRule { rule, diagnostic } +} + +#[verus_verify] +#[verus_verify(external_body)] +#[verus_spec(result => ensures result.0 == trace_rule_source(item), + result.1 == trace_rule_diagnostic(item))] +fn unpack_trace_rule(item: TraceRule) -> (Rule, TraceDiagnostic) { + let TraceRule { rule, diagnostic } = item; + (rule, diagnostic) +} + +// One Box stores a closure that makes exactly one call to the original Arc Fn, +// with the very reference the box receives. The identity denotes that original callback. +#[verus_verify] +#[verus_verify(external_body)] +#[verus_spec(result => ensures diagnostic_identity(result) == trace_diagnostic_identity(diagnostic), + forall|value: E, output: (String, Vec)| + diagnostic_output(diagnostic_identity(result), value, output.0@, output.1.deep_view()) ==> + exists|argument: &E| *argument == value && trace_arc_call(diagnostic, argument, output))] +fn forward_trace_diagnostic(diagnostic: TraceDiagnostic) -> Diagnostic { + #[cfg(not(verus_keep_ghost))] + { + Box::new(move |event: &E| diagnostic(event)) + } + #[cfg(verus_keep_ghost)] + { + super::rule::NativeDiagnostic { + inner: Box::new(move |event: &E| (diagnostic.inner)(event)), + } + } +} + +/// Converts one trace entry without changing its source or diagnostic selection. +#[verus_verify] +#[verus_spec(result => ensures policy_rule_source(result) == trace_rule_source(item), + policy_rule_diagnostic(result) == trace_rule_diagnostic_id(item), + forall|value: E, output: (String, Vec)| + diagnostic_output(policy_rule_diagnostic(result), value, output.0@, output.1.deep_view()) ==> + exists|argument: &E| *argument == value && trace_arc_call(trace_rule_diagnostic(item), argument, output))] +pub(crate) fn trace_rule_into_policy_rule( + item: TraceRule, +) -> PolicyRule { + let (rule, diagnostic) = unpack_trace_rule(item); + let diagnostic = forward_trace_diagnostic(diagnostic); + pack_policy_rule(rule, diagnostic) +} + +/// One caller-supplied rule paired with the diagnostic its violation surfaces. +#[verus_verify(external_body)] +#[cfg_attr(verus_keep_ghost, verifier::reject_recursive_types(E))] +pub struct TraceRule { + /// The past-regex rule. + pub rule: Rule, + /// Renders the denial when `rule` is violated. + pub diagnostic: TraceDiagnostic, +} + +#[verus_verify] +impl TraceRule { + /// Pairs `rule` with `diagnostic`, retaining the supplied Fn's observed outputs. + #[verus_spec(result => requires forall|argument: &E| call_requires(diagnostic, (argument,)), + ensures trace_rule_source(result) == rule, + trace_rule_diagnostic_id(result) == trace_callback_identity(diagnostic), + forall|value: E, output: (String, Vec)| + diagnostic_output(trace_rule_diagnostic_id(result), value, output.0@, output.1.deep_view()) ==> + exists|argument: &E| *argument == value && call_ensures(diagnostic, (argument,), output))] + pub fn new( + rule: Rule, + diagnostic: impl Fn(&E) -> (String, Vec) + Send + Sync + 'static, + ) -> Self { + let diagnostic = store_trace_diagnostic(diagnostic); + pack_trace_rule(rule, diagnostic) + } +} + +#[verus_verify] +impl Clone for TraceRule { + // Only the diagnostic's identity is promised: the rule's source equality would assume that + // the component type's `Clone` is the identity, which Rust does not guarantee. + #[verus_verify(external_body)] + #[verus_spec(result => ensures trace_rule_diagnostic_id(result) == trace_rule_diagnostic_id(*self))] + fn clone(&self) -> Self { + Self { + rule: self.rule.clone(), + #[cfg(not(verus_keep_ghost))] + diagnostic: Arc::clone(&self.diagnostic), + #[cfg(verus_keep_ghost)] + diagnostic: NativeTraceDiagnostic { + inner: Arc::clone(&self.diagnostic.inner), + }, + } + } +} + +impl fmt::Debug for TraceRule { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("TraceRule") + .field("rule", &self.rule) + .finish_non_exhaustive() + } +} + +/// A caller-assembled rule table compiled once and decided against external histories. +#[verus_verify] +#[cfg_attr(verus_keep_ghost, verifier::reject_recursive_types(E))] +pub struct TracePolicy { + compiled: CompiledPolicy, +} + +#[verus_verify] +impl TracePolicy { + /// Compiles the streaming input in order and drains its remaining rules on failure. + /// Exact source and diagnostic order require the input's `into_iter_yields` law. + /// Native event laws exclude internal invariant failures, not ordinary compile/resource errors. + #[verus_spec(result => requires history_store::typed::verify::store_wf(*store), + ensures junco_core::spec::hypotheses::event_obligations::() ==> no_invariant_compile_failure(result), + result matches Ok(policy) ==> trace_wf(policy) && trace_store(policy) == store + && trace_context_calls(policy) == 0 && trace_diagnostic_calls(policy) == 0 + && forall|items: Seq>| junco_core::verify::history_specs::into_iter_yields(rules, items) ==> + trace_sources(policy) == items.map(|i: int, item: TraceRule| trace_rule_source(item)) + && trace_diagnostic_ids(policy) == items.map(|i: int, item: TraceRule| trace_rule_diagnostic_id(item)))] + pub fn new>>( + store: Arc>, + rules: I, + ) -> Result { + proof_decl! { let ghost input = rules; } + let convert = I::into_iter; + let iterator = convert(rules); + proof_decl! { let ghost converted = iterator; } + proof! { assert(call_ensures(convert, (input,), converted)); } + let conversion = trace_rule_into_policy_rule::; + let mapped = iterator.map(conversion); + proof_decl! { let ghost mapped_input = mapped; } + proof! { + if converted.obeys_prophetic_iter_laws() { + vstd::std_specs::iter::map_postcondition(converted, conversion, mapped_input); + junco_core::verify::history_specs::lemma_iterator_into_iter_yields(mapped_input); + } + } + let compiled = CompiledPolicy::from_rules(store, mapped)?; + proof! { + assert forall|items: Seq>| + junco_core::verify::history_specs::into_iter_yields(input, items) implies + super::evaluate::verify::policy_sources(compiled) + == items.map(|i: int, item: TraceRule| trace_rule_source(item)) + && super::evaluate::verify::policy_diagnostic_ids(compiled) + == items.map(|i: int, item: TraceRule| trace_rule_diagnostic_id(item)) by { + assert(converted.obeys_prophetic_iter_laws()); + assert(converted.remaining() == items); + vstd::std_specs::iter::map_postcondition(converted, conversion, mapped_input); + super::evaluate::verify::lemma_completed_iterator_conversion(mapped_input); + assert(mapped_input.will_return_none()); + vstd::std_specs::iter::map_postcondition(converted, conversion, mapped_input); + assert(mapped_input.remaining().len() == items.len()); + assert forall|i: int| 0 <= i < items.len() implies + policy_rule_source(mapped_input.remaining()[i]) == trace_rule_source(items[i]) + && policy_rule_diagnostic(mapped_input.remaining()[i]) == trace_rule_diagnostic_id(items[i]) by { + assert(call_ensures(conversion, (items[i],), mapped_input.remaining()[i])); + } + assert(super::evaluate::verify::policy_sources(compiled) + =~= items.map(|i: int, item: TraceRule| trace_rule_source(item))); + assert(super::evaluate::verify::policy_diagnostic_ids(compiled) + =~= items.map(|i: int, item: TraceRule| trace_rule_diagnostic_id(item))); + } + } + Ok(Self { compiled }) + } + + /// Decides against the unchanged external history, using the candidate as the actual context. + /// Grant/error invokes no diagnostic; denial invokes only the least violating rule's Fn once. + /// Retained runtime structure and callback identities survive every outcome. + /// Operational errors cannot be internal invariant failures. + #[verus_spec(result => requires trace_wf(*old(self)), history_store::history::verify::history_wf(*history), + ensures trace_decision_result(*old(self), *final(self), *history, *candidate, result), + no_invariant_failure(result))] + pub fn decide( + &mut self, + history: &History, + candidate: &E, + ) -> Result { + proof_decl! { let ghost before = *self; } + let context = + verus_exec_expr! { || -> (value: E) ensures value == *candidate { *candidate } }; + proof_decl! { let ghost actual_context = context; } + proof! { assert(call_requires(context, ())); } + let result = self.compiled.decide(history, candidate, context); + proof! { + if let Ok(PolicyDecision::Deny { ref failed_precondition, ref allowed_fixes }) = result { + let value = choose|value: E| call_ensures(actual_context, (), value) + && diagnostic_output(super::evaluate::verify::policy_trace(self.compiled).calls.last().diagnostic_id, + value, failed_precondition@, allowed_fixes.deep_view()); + assert(value == *candidate); + assert(diagnostic_output(super::evaluate::verify::policy_trace(self.compiled).calls.last().diagnostic_id, + *candidate, failed_precondition@, allowed_fixes.deep_view())); + } + lemma_trace_decision_result(before, *self, *history, *candidate, result); + } + result + } +} diff --git a/src/history-semantics/src/progress.rs b/src/history-semantics/src/progress.rs new file mode 100644 index 000000000..7fd9859be --- /dev/null +++ b/src/history-semantics/src/progress.rs @@ -0,0 +1,3004 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#[cfg(verus_keep_ghost)] +use super::normalize::verify as norm; +#[cfg(verus_keep_ghost)] +use super::symbolic; +use crate::WorkVec; +use crate::normalize::RegexNormalize; +use crate::symbolic::{AtomTruth, RegexDerivative, TransitionInterpret}; +#[cfg(verus_keep_ghost)] +use crate::verify::finite_interp as fint; +use alloc::{collections::BTreeSet, vec::Vec}; +#[cfg(feature = "cache")] +use history_store::cache::SUCCESSOR_CAPACITY; +#[cfg(verus_keep_ghost)] +use history_store::cache::verify::*; +use history_store::cache::{EventClass, GraphCaches, Guard}; +use history_store::graph::{CanonicalStore, RuntimeKernel, allocation, sequence_bytes}; +use history_store::store::Event; +use junco_core::bits::checked_shl; +#[cfg(verus_keep_ghost)] +use junco_core::kernel::verify as model; +use junco_core::limits::Limits; +use junco_core::loop_try; +use junco_core::observation::ObservationWorld; +#[cfg(verus_keep_ghost)] +use junco_core::observation::SmallVecSpecFns; +#[cfg(verus_keep_ghost)] +use junco_core::spec::semantics::resource_error; +#[cfg(verus_keep_ghost)] +use junco_core::verify::history_assumptions::*; +#[cfg(verus_keep_ghost)] +use junco_core::verify::history_specs as language; +#[cfg(verus_keep_ghost)] +use junco_core::verify::history_specs::{EventView, Subst}; +use junco_core::{errors::HistoryError, kernel::*}; +use smallvec::SmallVec; +#[cfg(verus_keep_ghost)] +use verify::*; +use vstd::prelude::*; +#[cfg(verus_keep_ghost)] +use vstd::std_specs::cmp::OrdSpec; +#[cfg(verus_keep_ghost)] +verus! { +broadcast use junco_core::kernel::verify::group_kernel_views; +} + +/// Atoms per transition the guard enumeration accepts: 2^8 = 256 `TransitionId::interpret` runs, +/// one truth word, the same ceiling `precompile` uses. +// ponytail: 8 atoms = 256 interpretations per residual; raise if wider transitions show up hot. +#[verus_verify] +const GUARD_MAX_ATOMS: usize = 8; + +#[cfg(any(test, feature = "test-util"))] +#[derive(Debug, Default)] +pub struct WorkCounters { + pub events: usize, + pub derivative_misses: usize, + pub event_classes: usize, + pub successor_hits: usize, + pub successor_misses: usize, + pub guard_hits: usize, + pub(crate) skip_guards: bool, + pub(crate) fail_answer_checkpoint: bool, +} + +/// Residual states `precompile` explores before leaving the rest to the lazy path. +#[cfg(feature = "cache")] +#[verus_verify] +const PRECOMPILE_STATES: usize = 64; + +/// Hash-consed graph and graph-local derivative, primitive, guard and successor caches. +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Debug)] +pub(crate) struct CompiledPair { + pub(crate) store: CanonicalStore, + pub(crate) root: RegexId, + pub(crate) caches: GraphCaches, + #[cfg(any(test, feature = "test-util"))] + pub(crate) work: WorkCounters, +} +#[verus_verify] +impl CompiledPair { + // Individually representable byte counts can overflow when combined. + #[verus_verify] + #[verus_spec(result => ensures language::no_invariant_failure(result), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + result matches Err(error) ==> error is AllocationFailed || error is GraphIndex, + result matches Err(error) ==> resource_error(error), + result matches Ok(bytes) ==> bytes as int == + growth * vstd::layout::size_of::>() + + count * vstd::layout::size_of::())] + fn atom_payload_bytes(growth: usize, count: usize) -> KernelResult { + sequence_bytes::>(growth)? + .checked_add(sequence_bytes::(count)?) + .ok_or(HistoryError::AllocationFailed) + } + + // Borrow only the atom slice so callers can mutate the disjoint graph store. + #[verus_verify] + #[verus_spec(result => + ensures result != Err(HistoryError::WrongHistoryOwner), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + transition@ < atoms@.len() && atoms@[transition@ as int] is Some + ==> language::no_invariant_failure(result), + transition@ < atoms@.len() && atoms@[transition@ as int] is Some + ==> (result matches Err(error) ==> resource_error(error)), + result matches Ok(set) ==> transition@ < atoms@.len() && atoms@[transition@ as int] == Some(*set), + )] + pub(crate) fn cached_atoms( + atoms: &[Option], + transition: TransitionId, + ) -> KernelResult<&AtomSet> { + match atoms.get(transition.index()?) { + Some(Some(set)) => Ok(set), + _ => Err(HistoryError::invariant("missing transition atoms")), + } + } + + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(store.graph()), store.valid_store(), root@ < store.graph().regexes.len(), + ensures pair_wf(result), result.store.graph() == store.graph(), result.root == root, + )] + pub(crate) const fn new(store: CanonicalStore, root: RegexId) -> Self { + let pair = Self { + store, + root, + caches: GraphCaches::new(), + #[cfg(any(test, feature = "test-util"))] + work: WorkCounters { + events: 0, + derivative_misses: 0, + event_classes: 0, + successor_hits: 0, + successor_misses: 0, + guard_hits: 0, + skip_guards: false, + fail_answer_checkpoint: false, + }, + }; + proof! { + assert(pair.store.graph() == store.graph()); + assert(pair.store.valid_store()); + assert(model::graph_wf(pair.store.graph())); + assert(pair.root@ < pair.store.graph().regexes.len()); + assert(symbolic::verify::derivative_cache_wf(pair.store.graph(), pair.caches.derivatives@)); + assert(atom_cache_wf(pair.store.graph(), pair.caches.atoms@)); + assert(guard_cache_wf(pair.store.graph(), pair.caches.atoms@, pair.caches.guards@)); + assert(pair_wf(pair)); + } + pair + } + #[verus_verify] + #[verus_spec(result => + requires pair_wf(*old(self)), residual@ < (*old(self)).store.graph().regexes.len(), + ensures pair_wf(*final(self)), pair_frame(*old(self), *final(self)), + result != Err(HistoryError::WrongHistoryOwner), + language::no_invariant_failure(result), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + result matches Err(error) ==> resource_error(error), + (*final(self)).store.graph() == (*old(self)).store.graph(), + result matches Ok(answer) ==> answer == language::nullable(model::lift_regex((*final(self)).store.graph(), residual@)), + )] + pub(crate) fn answer( + &mut self, + residual: RegexId, + limits: &mut L, + world: &mut ObservationWorld, + ) -> KernelResult { + let kernel = RuntimeKernel { + store: &mut self.store, + limits, + world, + }; + let answer = RegexId::nullable(residual, &kernel)?; + #[cfg(any(test, feature = "test-util"))] + if self.work.fail_answer_checkpoint { + return Err(HistoryError::Limit( + junco_core::limits::LimitError::TimeLimitExceeded { + elapsed: core::time::Duration::from_secs(2), + limit: core::time::Duration::from_secs(1), + }, + )); + } + kernel.limits.checkpoint().map_err(HistoryError::from)?; + Ok(answer) + } + verus! { + /// Folds `events` into `residual`: the result denotes `events⁻¹ L(residual)` + /// under `bindings`. Errors publish no residual. + #[allow( + clippy::indexing_slicing, + reason = "The loop condition and invariant bound the event index." + )] + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + #[verus_spec(result => + requires pair_wf(*old(self)), + residual@ < (*old(self)).store.graph().regexes.len(), + ensures pair_wf(*final(self)), pair_frame(*old(self), *final(self)), + result != Err(HistoryError::WrongHistoryOwner), + language::no_invariant_failure(result), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + result matches Err(error) ==> resource_error(error), + result matches Ok(out) ==> residual_folds(*final(self), bindings@, residual, history_store::store::verify::events_view(events@), out), + )] + pub(crate) fn fold( + &mut self, + residual: RegexId, + events: &[Event], + bindings: &Bindings, + limits: &mut L, + world: &mut ObservationWorld, + ) -> KernelResult { + hide(language::numeric_lang); + hide(model::regex_lang); + hide(model::lift_regex); + hide(model::lift_transition); + hide(model::test_holds); + proof_decl! { let ghost entry = *self; let ghost from = residual; } + let mut residual = residual; + proof! { + lemma_fold_start(*self, bindings@, from); + assert(history_store::store::verify::events_view(events@).take(0) =~= Seq::::empty()); + assert(history_store::store::verify::events_view(events@).take(events@.len() as int) =~= history_store::store::verify::events_view(events@)); + } + let mut failure = None; + let mut index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant pair_wf(entry), pair_wf(*self), pair_frame(entry, *self), + failure matches Some(error) ==> error != HistoryError::WrongHistoryOwner + && !(error is Invariant) && !(error is InvalidPolicy), + failure matches Some(error) ==> resource_error(error), + index <= events@.len(), + residual_folds(*self, bindings@, from, history_store::store::verify::events_view(events@).take(index as int), residual), + history_store::store::verify::events_view(events@).take(events@.len() as int) == history_store::store::verify::events_view(events@), + ensures pair_wf(*self), pair_frame(entry, *self), + failure matches Some(error) ==> error != HistoryError::WrongHistoryOwner + && !(error is Invariant) && !(error is InvalidPolicy), + failure matches Some(error) ==> resource_error(error), + failure is Some || residual_folds(*self, bindings@, from, history_store::store::verify::events_view(events@), residual), + decreases events@.len() - index, + ))] + while index < events.len() { + let event = &events[index]; + proof_decl! { + let ghost before = *self; + let ghost done = history_store::store::verify::events_view(events@).take(index as int); + } + proof! { + model::lemma_graph_wf_elim(entry.store.graph()); + model::lemma_lift_stable_under_extends(entry.store.graph(), before.store.graph()); + assert(history_store::store::verify::events_view(events@).take(index as int + 1) =~= done.push(event@)); + } + loop_try!(limits.checkpoint().map_err(HistoryError::from), failure); + let constants = self.store.constants(); + if residual == constants.all || residual == constants.empty { + proof! { + lemma_fold_absorbing(*self, bindings@, from, done, history_store::store::verify::events_view(events@).skip(index as int), residual); + assert(done + history_store::store::verify::events_view(events@).skip(index as int) =~= history_store::store::verify::events_view(events@)); + } + break; + } + #[cfg(any(test, feature = "test-util"))] + { + self.work.events = self.work.events.saturating_add(1); + if self + .caches + .derivatives + .get(residual.index()?) + .copied() + .flatten() + .is_none() + { + self.work.derivative_misses = self.work.derivative_misses.saturating_add(1); + } + } + proof! { + self.store.lemma_node_count_bounds(); + assert(residual@ < usize::MAX); + } + let derivative_result = { + let mut kernel = RuntimeKernel { + store: &mut self.store, + limits, + world, + }; + RegexId::derivative(residual, &mut kernel, &mut self.caches.derivatives) + }; + proof! { lemma_pair_symbolic_frame(before, *self); lemma_fold_frame(before, *self, bindings@, from, done, residual); } + let transition = loop_try!(derivative_result, failure); + #[cfg(any(test, feature = "test-util"))] + let guards_enabled = !self.work.skip_guards; + #[cfg(not(any(test, feature = "test-util")))] + let guards_enabled = true; + if guards_enabled { + proof_decl! { let ghost before_guard = *self; } + let ensured = self.ensure_guard(residual, transition, limits, world); + proof! { lemma_fold_frame(before_guard, *self, bindings@, from, done, residual); symbolic::verify::derivative_correct_stable(before_guard.store.graph(), self.store.graph(), residual@, transition); } + loop_try!(ensured, failure); + proof_decl! { let ghost before_hit = *self; } + let hit = self.guard_hit(residual, transition, event, bindings, limits, world); + proof! { lemma_fold_frame(before_hit, *self, bindings@, from, done, residual); symbolic::verify::derivative_correct_stable(before_hit.store.graph(), self.store.graph(), residual@, transition); } + if loop_try!(hit, failure) { + #[cfg(any(test, feature = "test-util"))] + { + self.work.guard_hits = self.work.guard_hits.saturating_add(1); + } + proof! { lemma_fold_step(*self, bindings@, from, done, residual, transition, *event, residual); } + index = index.saturating_add(1); + continue; + } + } + proof_decl! { let ghost before_instantiate = *self; } + let successor_result = self.instantiate(transition, event, bindings, limits, world); + proof! { lemma_fold_frame(before_instantiate, *self, bindings@, from, done, residual); symbolic::verify::derivative_correct_stable(before_instantiate.store.graph(), self.store.graph(), residual@, transition); } + let successor = loop_try!(successor_result, failure); + proof! { lemma_fold_step(*self, bindings@, from, done, residual, transition, *event, successor); } + residual = successor; + index = index.saturating_add(1); + } + if let Some(error) = failure { + return Err(error); + } + Ok(residual) + } + } + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + #[verus_verify] + #[verus_spec(result => + requires pair_wf(*old(self)), transition@ < old(self).store.graph().transitions.len(), + ensures pair_wf(*final(self)), pair_frame(*old(self), *final(self)), + result != Err(HistoryError::WrongHistoryOwner), + language::no_invariant_failure(result), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + result matches Err(error) ==> resource_error(error), + result is Ok ==> has_atoms(*final(self), transition), + final(self).caches.derivatives@ == old(self).caches.derivatives@, + successor_entries(final(self).caches.successors) == successor_entries(old(self).caches.successors), + forall|i: int| 0 <= i < old(self).caches.atoms@.len() && old(self).caches.atoms@[i] is Some + ==> i < final(self).caches.atoms@.len() + && final(self).caches.atoms@[i] == old(self).caches.atoms@[i], + )] + pub(crate) fn ensure_atoms( + &mut self, + transition: TransitionId, + limits: &mut L, + world: &mut ObservationWorld, + ) -> KernelResult<()> { + proof_decl! { let ghost entry = *self; } + let index = transition.index()?; + if matches!(self.caches.atoms.get(index), Some(Some(_))) { + return Ok(()); + } + let atoms = { + let mut kernel = RuntimeKernel { + store: &mut self.store, + limits, + world, + }; + Self::collect_atoms(&mut kernel, transition) + }; + proof! { + symbolic::verify::derivative_extends(entry.store.graph(), self.store.graph()); + lemma_pair_symbolic_frame(entry, *self); + } + let atoms = atoms?; + proof! { + self.store.lemma_node_count_bounds(); + assert(index == transition@); + assert(index < usize::MAX); + } + let needed = index.checked_add(1).ok_or_else(verus_exec_expr! { + || -> (error: HistoryError) + ensures error is Invariant, + { HistoryError::invariant("atom table length overflow") } + })?; + let growth = needed.saturating_sub(self.caches.atoms.len()); + let bytes = Self::atom_payload_bytes(growth, atoms.ids().len())?; + let projected = self.store.projected(bytes)?; + proof_decl! { let ghost reserved_pair = *self; } + let reserved = world.try_reserve_vec(&mut self.caches.atoms, growth); + proof! { lemma_pair_symbolic_frame(reserved_pair, *self); } + allocation(reserved)?; + limits.checkpoint().map_err(HistoryError::from)?; + proof_decl! { let ghost prior_atoms = self.caches.atoms@; } + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant pair_wf(*self), pair_frame(entry, *self), + self.store.graph() == old(self).store.graph() || model::graph_extends(old(self).store.graph(), self.store.graph()), + prior_atoms.is_prefix_of(self.caches.atoms@), + self.caches.derivatives@ == entry.caches.derivatives@, + forall|i: int| 0 <= i < entry.caches.atoms@.len() && entry.caches.atoms@[i] is Some + ==> i < self.caches.atoms@.len() && self.caches.atoms@[i] == entry.caches.atoms@[i], + forall|i: int| prior_atoms.len() <= i < self.caches.atoms@.len() ==> self.caches.atoms@[i] is None, + index == transition@, transition@ < self.store.graph().transitions.len(), + needed == index + 1, + atoms_wf(self.store.graph(), transition@, atoms@), + atoms_contained(self.store.graph(), transition@, atoms@), + successor_entries((*self).caches.successors) == successor_entries(entry.caches.successors), + self.caches.atoms@.len() <= needed || self.caches.atoms@ == prior_atoms, + decreases needed - self.caches.atoms@.len(), + ))] + while self.caches.atoms.len() < needed { + proof_decl! { let ghost before_push = *self; } + self.caches.atoms.push(None); + proof! { + assert(atom_cache_wf(self.store.graph(), self.caches.atoms@)); + assert(successor_entries_wf(self.store.graph(), self.caches.atoms@, successor_entries((*self).caches.successors))); + assert(symbolic::verify::derivative_cache_wf(self.store.graph(), self.caches.derivatives@)); + assert forall|key: ClassKey| successor_entries((*self).caches.successors).contains_key(key) implies + key.transition@ < before_push.caches.atoms@.len() && self.caches.atoms@[key.transition@ as int] == before_push.caches.atoms@[key.transition@ as int] by { + assert(successor_entries(before_push.caches.successors).contains_key(key)); + } + assert forall|r: int| 0 <= r < self.caches.guards@.len() && self.caches.guards@[r] is Some + implies guard_wf(self.store.graph(), self.caches.atoms@, r, self.caches.guards@[r].unwrap()) by { + let guard = self.caches.guards@[r].unwrap(); + assert(guard_wf(before_push.store.graph(), before_push.caches.atoms@, r, guard)); + if guard.mask != 0 { + assert(self.caches.atoms@[guard.transition@ as int] == before_push.caches.atoms@[guard.transition@ as int]); + } + } + assert(guard_cache_wf(self.store.graph(), self.caches.atoms@, self.caches.guards@)); + assert(model::graph_wf(self.store.graph())); + assert(self.store.valid_store()); + assert(self.root@ < self.store.graph().regexes.len()); + assert(match self.caches.successors { Some(cache) => successor_entries_wf(self.store.graph(), self.caches.atoms@, successor_cache_view(cache)), None => true }); + assert(pair_wf(*self)); + } + } + proof_decl! { let ghost before_slot = *self; } + proof! { + if index < prior_atoms.len() { assert(prior_atoms[index as int] == entry.caches.atoms@[index as int]); } + assert(before_slot.caches.atoms@[index as int] is None); + } + let atom_slots = self.caches.atoms.as_mut_slice(); + let slot = atom_slots.get_mut(index).ok_or_else(verus_exec_expr! { + || -> (error: HistoryError) + ensures error is Invariant, + { HistoryError::invariant("invalid atom table slot") } + })?; + *slot = Some(atoms); + proof! { + assert forall|key: ClassKey| successor_entries((*self).caches.successors).contains_key(key) implies + self.caches.atoms@[key.transition@ as int] == entry.caches.atoms@[key.transition@ as int] by { + assert(entry.caches.atoms@[key.transition@ as int] is Some); + assert(key.transition != transition); + } + assert forall|r: int| 0 <= r < self.caches.guards@.len() && self.caches.guards@[r] is Some + implies guard_wf(self.store.graph(), self.caches.atoms@, r, self.caches.guards@[r].unwrap()) by { + let guard = self.caches.guards@[r].unwrap(); + assert(guard_wf(before_slot.store.graph(), before_slot.caches.atoms@, r, guard)); + if guard.mask != 0 { + assert(guard.transition@ != index); + assert(self.caches.atoms@[guard.transition@ as int] == before_slot.caches.atoms@[guard.transition@ as int]); + } + } + assert(guard_cache_wf(self.store.graph(), self.caches.atoms@, self.caches.guards@)); + assert(pair_wf(*self)); + } + proof_decl! { let ghost before_charge = *self; } + self.store.set_charged_bytes(projected); + proof! { lemma_pair_symbolic_frame(before_charge, *self); } + limits.checkpoint().map_err(HistoryError::from) + } + #[verus_verify] + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + #[verus_spec(result => + requires pair_wf(*old(self)), transition@ < old(self).store.graph().transitions.len(), + residual@ < old(self).store.graph().regexes.len(), + ensures pair_wf(*final(self)), pair_frame(*old(self), *final(self)), + result != Err(HistoryError::WrongHistoryOwner), + language::no_invariant_failure(result), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + result matches Err(error) ==> resource_error(error), + result is Ok ==> has_guard(*final(self), residual), + )] + /// Stores `residual`'s self-loop guard for `transition` once per residual. + fn ensure_guard( + &mut self, + residual: RegexId, + transition: TransitionId, + limits: &mut L, + world: &mut ObservationWorld, + ) -> KernelResult<()> { + proof_decl! { let ghost entry = *self; } + let index = residual.index()?; + if matches!(self.caches.guards.get(index), Some(Some(_))) { + return Ok(()); + } + let constant = { + let kernel = RuntimeKernel { + store: &mut self.store, + limits, + world, + }; + match kernel.transition(transition) { + Ok(TransitionView::Const(_)) => Ok(true), + Ok(_) => Ok(false), + Err(error) => Err(error), + } + }; + proof! { + assert(self.store.graph() == entry.store.graph()); + assert(self.store.valid_store()); + assert(pair_frame(entry, *self)); + lemma_pair_symbolic_frame(entry, *self); + } + let constant = constant?; + let mask = if constant { + 0 + } else { + self.ensure_atoms(transition, limits, world)?; + self.guard_mask(residual, transition, limits, world)? + }; + proof_decl! { let ghost guard = Guard { transition, mask }; let ghost certified = *self; } + proof! { assert(guard_wf(self.store.graph(), self.caches.atoms@, index as int, guard)); } + proof! { + self.store.lemma_node_count_bounds(); + assert(index == residual@); + assert(index < usize::MAX); + } + let needed = index.checked_add(1).ok_or_else(verus_exec_expr! { + || -> (error: HistoryError) + ensures error is Invariant, + { HistoryError::invariant("guard table length overflow") } + })?; + let growth = needed.saturating_sub(self.caches.guards.len()); + let projected = self + .store + .projected(sequence_bytes::>(growth)?)?; + let reserved = world.try_reserve_vec(&mut self.caches.guards, growth); + proof! { lemma_pair_guard_update(certified, *self); } + allocation(reserved)?; + limits.checkpoint().map_err(HistoryError::from)?; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant pair_wf(*self), pair_frame(entry, *self), + self.store == certified.store, self.caches.atoms@ == certified.caches.atoms@, + guard_wf(self.store.graph(), self.caches.atoms@, index as int, guard), + index == residual@, needed == index + 1, + decreases needed - self.caches.guards@.len(), + ))] + while self.caches.guards.len() < needed { + proof_decl! { let ghost before_push = *self; } + self.caches.guards.push(None); + proof! { + assert forall|r: int| 0 <= r < self.caches.guards@.len() && self.caches.guards@[r] is Some + implies guard_wf(self.store.graph(), self.caches.atoms@, r, self.caches.guards@[r].unwrap()) by { + assert(self.caches.guards@[r] == before_push.caches.guards@[r]); + } + lemma_pair_guard_update(before_push, *self); + } + } + proof_decl! { let ghost before_slot = *self; } + let guard_slots = self.caches.guards.as_mut_slice(); + let slot = guard_slots.get_mut(index).ok_or_else(verus_exec_expr! { + || -> (error: HistoryError) + ensures error is Invariant, + { HistoryError::invariant("invalid guard table slot") } + })?; + *slot = Some(Guard { transition, mask }); + proof! { + assert forall|r: int| 0 <= r < self.caches.guards@.len() && self.caches.guards@[r] is Some + implies guard_wf(self.store.graph(), self.caches.atoms@, r, self.caches.guards@[r].unwrap()) by { + if r != index { assert(self.caches.guards@[r] == before_slot.caches.guards@[r]); } + } + lemma_pair_guard_update(before_slot, *self); + } + proof_decl! { let ghost before_charge = *self; } + self.store.set_charged_bytes(projected); + proof! { lemma_pair_symbolic_frame(before_charge, *self); } + limits.checkpoint().map_err(HistoryError::from) + } + #[allow( + clippy::arithmetic_side_effects, + reason = "The bounded nonzero atom count makes the class count at least two." + )] + #[verus_verify] + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + #[verus_spec(result => + requires pair_wf(*old(self)), has_atoms(*old(self), transition), + transition@ < old(self).store.graph().transitions.len(), + residual@ < old(self).store.graph().regexes.len(), + ensures pair_wf(*final(self)), pair_frame(*old(self), *final(self)), + result != Err(HistoryError::WrongHistoryOwner), + language::no_invariant_failure(result), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + result matches Err(error) ==> resource_error(error), + final(self).caches.atoms@ == old(self).caches.atoms@, final(self).caches.guards@ == old(self).caches.guards@, + result matches Ok(mask) ==> guard_wf(final(self).store.graph(), final(self).caches.atoms@, residual@ as int, Guard { transition, mask }), + )] + /// Atoms true in every truth word whose successor leaves `residual`: each of the 2^k words + /// is interpreted once and the leaving words are intersected. A graph budget or index error yields mask 0. + fn guard_mask( + &mut self, + residual: RegexId, + transition: TransitionId, + limits: &mut L, + world: &mut ObservationWorld, + ) -> KernelResult { + proof_decl! { let ghost entry = *self; } + let atoms = Self::cached_atoms(self.caches.atoms.as_slice(), transition)?; + let count = atoms.ids().len(); + if count == 0 || count > GUARD_MAX_ATOMS { + return Ok(0); + } + let shift = u32::try_from(count) + .map_err(|_| HistoryError::invariant("invalid guard atom count"))?; + let classes = checked_shl(1, shift) + .ok_or_else(|| HistoryError::invariant("invalid guard class count"))?; + proof! { assert(classes >= 2) by(bit_vector) requires classes == (1u64 << shift), 1 <= shift <= 8; } + let mut mask = classes - 1; + let mut minterm = 0_u64; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant pair_wf(*self), entry == *old(self), pair_frame(entry, *self), + self.caches.atoms@ == entry.caches.atoms@, self.caches.guards@ == entry.caches.guards@, + has_atoms(*self, transition), atoms@ == self.caches.atoms@[transition@ as int].unwrap()@, + transition@ < self.store.graph().transitions.len(), residual@ < self.store.graph().regexes.len(), + count == atoms@.len(), 1 <= count <= 8, classes == (1u64 << (count as u32)), minterm <= classes, + atoms_wf(self.store.graph(), transition@, atoms@), + mask == 0 || forall|w: u64| w < minterm && (w & mask) != mask + ==> #[trigger] guard_class_covered(self.store.graph(), atoms@, residual, transition, w), + ensures mask == 0 || minterm == classes, + decreases classes - minterm, + ))] + while minterm < classes { + limits.checkpoint().map_err(HistoryError::from)?; + let words = [minterm]; + proof_decl! { let ghost before = *self; } + proof! { + lemma_single_truth_word(count, minterm); + assert(words@ =~= seq![minterm]); + } + let successor = { + let mut kernel = RuntimeKernel { + store: &mut self.store, + limits, + world, + }; + TransitionId::interpret(transition, &mut kernel, atoms, words.as_slice()) + }; + proof! { + symbolic::verify::derivative_extends(before.store.graph(), self.store.graph()); + lemma_pair_symbolic_frame(before, *self); + symbolic::verify::truth_words_realize_extends(before.store.graph(), self.store.graph(), atoms@, seq![minterm]); + assert(words@ =~= seq![minterm]); + if mask != 0 { + assert forall|w: u64| w < minterm && (w & mask) != mask + implies #[trigger] guard_class_covered(self.store.graph(), atoms@, residual, transition, w) by { + lemma_guard_class_covered_frame(before.store.graph(), self.store.graph(), atoms@, residual, transition, w); + } + } + } + let successor = match successor { + Ok(successor) => successor, + Err(HistoryError::GraphBudget { .. } | HistoryError::GraphIndex) => { + mask = 0; + break; + } + Err(error) => return Err(error), + }; + if successor != residual { + proof! { + let next = mask & minterm; + if next != 0 { + assert((minterm & next) == next) by(bit_vector) requires next == mask & minterm; + assert forall|w: u64| w <= minterm && (w & next) != next + implies #[trigger] guard_class_covered(self.store.graph(), atoms@, residual, transition, w) by { + lemma_mask_shrink(w, mask, minterm); + assert(mask != 0) by(bit_vector) requires next == mask & minterm, next != 0; + } + } + } + mask &= minterm; + } else if mask != 0 { + proof! { + assert(guard_class_covered(self.store.graph(), atoms@, residual, transition, minterm)); + assert forall|w: u64| w <= minterm && (w & mask) != mask + implies #[trigger] guard_class_covered(self.store.graph(), atoms@, residual, transition, w) by { + if w == minterm {} else { assert(w < minterm); } + } + } + } + proof! { assert(minterm < classes); } + minterm = minterm.saturating_add(1); + } + proof! { + let g = self.store.graph(); + if mask != 0 { + assert forall|theta: Subst, event: EventView, word: Seq| + language::event_wf(theta, theta.len()) && guard_blocks(g, atoms@, mask, theta, event) + implies model::regex_lang(g, theta, residual@, word) + == norm::transition_lang(g, theta, transition, event, word) by { + lemma_guard_blocks_word(g, atoms@, mask, theta, event); + let w = realized_word(g, atoms@, theta, event, atoms@.len()); + assert(guard_class_covered(g, atoms@, residual, transition, w)); + } + } + } + Ok(mask) + } + #[verus_verify] + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + #[verus_spec(result => + requires pair_wf(*old(self)), has_guard(*old(self), residual), + transition@ < old(self).store.graph().transitions.len(), + ensures pair_wf(*final(self)), pair_frame(*old(self), *final(self)), + result != Err(HistoryError::WrongHistoryOwner), + language::no_invariant_failure(result), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + result matches Err(error) ==> resource_error(error), + final(self).caches.atoms@ == old(self).caches.atoms@, final(self).caches.guards@ == old(self).caches.guards@, + successor_entries((*final(self)).caches.successors) == successor_entries((*old(self)).caches.successors), + result matches Ok(true) ==> instantiation_result(*final(self), transition, bindings@, *event, residual), + )] + /// `Ok(true)` when the stored guard for `residual` names `transition` and one of its masked + /// atoms is false on `event`, i.e. the event is a certified self-loop. + fn guard_hit( + &mut self, + residual: RegexId, + transition: TransitionId, + event: &Event, + bindings: &Bindings, + limits: &mut L, + world: &mut ObservationWorld, + ) -> KernelResult { + proof_decl! { let ghost entry = *self; } + let guard = match self.caches.guards.get(residual.index()?) { + Some(Some(guard)) => *guard, + _ => return Err(HistoryError::invariant("missing progress guard")), + }; + if guard.transition != transition || guard.mask == 0 { + return Ok(false); + } + let atoms = Self::cached_atoms(self.caches.atoms.as_slice(), transition)?; + let masks = [guard.mask]; + proof! { assert(masks@ =~= seq![guard.mask]); } + let mut hit = false; + let mut failure = None; + let mut index = 0_usize; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant pair_wf(*self), pair_frame(entry, *self), + failure matches Some(error) ==> error != HistoryError::WrongHistoryOwner + && !(error is Invariant) && !(error is InvalidPolicy), + failure matches Some(error) ==> resource_error(error), + self.store.graph() == entry.store.graph(), self.caches.derivatives@ == entry.caches.derivatives@, + successor_entries((*self).caches.successors) == successor_entries(entry.caches.successors), self.caches.atoms@ == entry.caches.atoms@, self.caches.guards@ == entry.caches.guards@, + index <= atoms@.len(), has_atoms(*self, transition), atoms@ == self.caches.atoms@[transition@ as int].unwrap()@, + atoms_wf(self.store.graph(), transition@, atoms@), + has_guard(*self, residual), self.caches.guards@[residual@ as int] == Some(guard), guard.transition == transition, guard.mask != 0, + masks@ == seq![guard.mask], + hit ==> instantiation_result(*self, transition, bindings@, *event, residual), + decreases atoms@.len() - index, + ))] + while index < atoms.ids().len() { + let masked = match AtomSet::truth(masks.as_slice(), index) { + Ok(masked) => masked, + Err(_) => break, + }; + if masked { + let id = loop_try!( + atoms + .ids() + .get(index) + .ok_or_else(|| HistoryError::invariant("invalid primitive atom index")), + failure + ); + proof! { + assert(*id == atoms@[index as int]); + assert(self.store.graph().tests[id@ as int] matches model::TestNode::Atom(_, true)); + } + let primitive = { + let kernel = RuntimeKernel { + store: &mut self.store, + limits, + world, + }; + match kernel.test(*id) { + Ok(TestView::Atom { + primitive, + positive: true, + }) => Ok(primitive), + Ok(_) => Err(HistoryError::invalid_atom_set()), + Err(error) => Err(error), + } + }; + let primitive = loop_try!(primitive, failure); + let classified = Self::classify(primitive, event, bindings, limits, world); + if !loop_try!(classified, failure) { + proof! { + let g = self.store.graph(); + assert(symbolic::verify::truth_word_bit(seq![guard.mask], index as nat)); + assert(atoms@[index as int] == *id); + assert(g.tests[id@ as int] == model::TestNode::Atom(primitive@, true)); + assert(model::lift_test(g, atoms@[index as int]@) == model::Test::Atom(primitive@, true)); + assert(!model::test_holds(bindings@, + model::lift_test(g, atoms@[index as int]@), event@)); + let i = index as int; + assert(i as nat == index as nat); + assert(self.caches.atoms@[guard.transition@ as int].unwrap()@ == atoms@); + assert(0 <= i < atoms@.len() && symbolic::verify::truth_word_bit(seq![guard.mask], i as nat) + && !model::test_holds(bindings@, + model::lift_test(g, atoms@[i]@), event@)); + assert(guard_blocks(g, self.caches.atoms@[guard.transition@ as int].unwrap()@, guard.mask, + bindings@, event@)); + lemma_guard_hit(*self, residual, guard, bindings@, *event); + } + hit = true; + break; + } + } + index = index.saturating_add(1); + } + if let Some(error) = failure { + return Err(error); + } + Ok(hit) + } + #[verus_verify] + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + #[verus_spec(result => + requires pair_wf(*old(self)), transition@ < old(self).store.graph().transitions.len(), + ensures pair_wf(*final(self)), pair_frame(*old(self), *final(self)), + result != Err(HistoryError::WrongHistoryOwner), + language::no_invariant_failure(result), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + result matches Err(error) ==> resource_error(error), + result matches Ok(id) ==> instantiation_result(*final(self), transition, bindings@, *event, id), + )] + fn instantiate( + &mut self, + transition: TransitionId, + event: &Event, + bindings: &Bindings, + limits: &mut L, + world: &mut ObservationWorld, + ) -> KernelResult { + proof_decl! { let ghost entry = *self; } + { + let kernel = RuntimeKernel { + store: &mut self.store, + limits, + world, + }; + if let TransitionView::Const(regex) = kernel.transition(transition)? { + proof! { + model::lemma_graph_transition_wf(self.store.graph(), transition@); + norm::transition_unfold(self.store.graph(), transition@); + assert(instantiation_result(*self, transition, bindings@, *event, regex)); + } + return Ok(regex); + } + } + self.ensure_atoms(transition, limits, world)?; + proof_decl! { let ghost classified = *self; } + #[cfg(any(test, feature = "test-util"))] + { + self.work.event_classes = self.work.event_classes.saturating_add(1); + } + let atoms = Self::cached_atoms(self.caches.atoms.as_slice(), transition)?; + proof! { + self.store.lemma_node_count_bounds(); + lemma_atom_count_bound(self.store.graph(), atoms@); + assert(atoms@.len() + 63 <= usize::MAX); + } + let word_count = atoms + .ids() + .len() + .checked_add(63) + .ok_or_else(verus_exec_expr! { + || -> (error: HistoryError) + ensures error is Invariant, + { HistoryError::invariant("truth word length overflow") } + })? + .checked_div(64) + .ok_or_else(verus_exec_expr! { + || -> (error: HistoryError) + ensures error is Invariant, + { HistoryError::invariant("invalid truth word divisor") } + })?; + let mut words: SmallVec<[u64; 2]> = SmallVec::new(); + allocation(world.try_reserve_words(&mut words, word_count))?; + words.resize(word_count, 0); + proof! { + lemma_zero_truth_words(words.view(), atoms@.len()); + } + let mut failure = None; + let mut index = 0_usize; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant pair_wf(*self), pair_frame(entry, *self), + failure matches Some(error) ==> error != HistoryError::WrongHistoryOwner + && !(error is Invariant) && !(error is InvalidPolicy), + failure matches Some(error) ==> resource_error(error), + index <= atoms@.len(), words.view().len() == word_count, + atoms@.len() + 63 <= usize::MAX, word_count == (atoms@.len() + 63) / 64, + symbolic::verify::assignment_valid(atoms@.len(), words.view()), + self.store.graph() == classified.store.graph(), self.caches.derivatives@ == classified.caches.derivatives@, + successor_entries((*self).caches.successors) == successor_entries(classified.caches.successors), self.caches.atoms@ == classified.caches.atoms@, + has_atoms(*self, transition), atom_cache_wf(self.store.graph(), self.caches.atoms@), + atoms@ == self.caches.atoms@[transition@ as int].unwrap()@, + atoms_wf(self.store.graph(), transition@, atoms@), + forall|j: int| 0 <= j < index ==> symbolic::verify::truth_word_bit(words.view(), j as nat) + == model::test_holds(bindings@, model::lift_test(self.store.graph(), atoms@[j]@), event@), + forall|j: nat| index <= j ==> !symbolic::verify::truth_word_bit(words.view(), j), + ensures failure is None ==> index == atoms@.len(), + decreases atoms@.len() - index, + ))] + while index < atoms.ids().len() { + proof! { + assert(index / 64 < word_count); + assert(index % 64 < 64); + assert(index < usize::MAX); + } + let id = loop_try!( + atoms.ids().get(index).ok_or_else(verus_exec_expr! { + || -> (error: HistoryError) + ensures error is Invariant, + { HistoryError::invariant("invalid primitive atom index") } + }), + failure + ); + proof! { + assert(*id == atoms@[index as int]); + assert(self.store.graph().tests[id@ as int] matches model::TestNode::Atom(_, true)); + } + proof_decl! { let ghost before_words = words.view(); } + loop_try!(limits.checkpoint().map_err(HistoryError::from), failure); + let primitive = { + let kernel = RuntimeKernel { + store: &mut self.store, + limits, + world, + }; + match kernel.test(*id) { + Ok(TestView::Atom { + primitive, + positive: true, + }) => Ok(primitive), + Ok(_) => Err(HistoryError::invalid_atom_set()), + Err(error) => Err(error), + } + }; + let primitive = loop_try!(primitive, failure); + let classified = Self::classify(primitive, event, bindings, limits, world); + if loop_try!(classified, failure) { + let word_index = loop_try!( + index.checked_div(64).ok_or_else(verus_exec_expr! { + || -> (error: HistoryError) + ensures error is Invariant, + { HistoryError::invariant("invalid truth word divisor") } + }), + failure + ); + let bit = loop_try!( + u32::try_from(loop_try!( + index.checked_rem(64).ok_or_else(verus_exec_expr! { + || -> (error: HistoryError) + ensures error is Invariant, + { HistoryError::invariant("invalid truth bit divisor") } + }), + failure + ),) + .map_err(|_| HistoryError::invariant("invalid truth bit")), + failure + ); + let truth_word = loop_try!( + words + .as_mut_slice() + .get_mut(word_index) + .ok_or_else(verus_exec_expr! { + || -> (error: HistoryError) + ensures error is Invariant, + { HistoryError::invariant("invalid truth word index") } + }), + failure + ); + *truth_word |= loop_try!( + checked_shl(1, bit).ok_or_else(verus_exec_expr! { + || -> (error: HistoryError) + ensures error is Invariant, + { HistoryError::invariant("invalid truth bit") } + }), + failure + ); + proof! { + lemma_truth_word_set(before_words, words.view(), index as nat); + lemma_assignment_set(atoms@.len(), before_words, words.view(), index as nat); + } + } + index = index.saturating_add(1); + } + if let Some(error) = failure { + return Err(error); + } + proof! { + assert(index == atoms@.len()); + assert(symbolic::verify::truth_words_realize(self.store.graph(), atoms@, words.view(), bindings@, event@)); + } + proof_decl! { let ghost words_view = words.view(); let ghost atoms_view = atoms@; } + let successor = self.successor(EventClass { transition, words }, limits, world)?; + proof! { + assert(successor_entries((*self).caches.successors).contains_key(ClassKey { transition, words: words_view })); + symbolic::verify::truth_words_realize_extends(classified.store.graph(), self.store.graph(), atoms_view, words_view); + assert(instantiation_result(*self, transition, bindings@, *event, successor)); + } + Ok(successor) + } + #[verus_verify] + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + #[verus_spec(result => + requires pair_wf(*old(self)), has_atoms(*old(self), key.transition), + ensures pair_wf(*final(self)), pair_frame(*old(self), *final(self)), + result != Err(HistoryError::WrongHistoryOwner), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + symbolic::verify::assignment_valid(old(self).caches.atoms@[key.transition@ as int].unwrap()@.len(), key.words.view()) + ==> language::no_invariant_failure(result), + symbolic::verify::assignment_valid(old(self).caches.atoms@[key.transition@ as int].unwrap()@.len(), key.words.view()) + ==> (result matches Err(error) ==> resource_error(error)), + final(self).caches.atoms@ == old(self).caches.atoms@, + final(self).caches.derivatives@ == old(self).caches.derivatives@, + result matches Ok(id) ==> successor_entries((*final(self)).caches.successors).contains_key(class_key(key)) + && successor_entries((*final(self)).caches.successors)[class_key(key)] == id + && fint::entry_val(final(self).store.graph(), key.transition@, id@), + )] + /// Cached or freshly interpreted successor of `key`; every entry it publishes is covered by + /// `successor_entries_wf`, so callers read the language equivalence from `pair_wf`. + pub(crate) fn successor( + &mut self, + key: EventClass, + limits: &mut L, + world: &mut ObservationWorld, + ) -> KernelResult { + proof_decl! { let ghost entry = *self; } + let atoms = Self::cached_atoms(self.caches.atoms.as_slice(), key.transition)?; + if let Some(successor) = GraphCaches::successor_get(&mut self.caches.successors, &key) { + #[cfg(any(test, feature = "test-util"))] + { + self.work.successor_hits = self.work.successor_hits.saturating_add(1); + } + return Ok(successor); + } + #[cfg(any(test, feature = "test-util"))] + { + self.work.successor_misses = self.work.successor_misses.saturating_add(1); + } + let successor = { + let mut kernel = RuntimeKernel { + store: &mut self.store, + limits, + world, + }; + TransitionId::interpret(key.transition, &mut kernel, atoms, &key.words) + }; + proof! { + symbolic::verify::derivative_extends(entry.store.graph(), self.store.graph()); + lemma_pair_symbolic_frame(entry, *self); + symbolic::verify::truth_words_realize_extends(entry.store.graph(), self.store.graph(), atoms@, key.words.view()); + } + let successor = successor?; + proof! { + assert forall|theta: Subst, current: EventView, word: Seq| + language::event_wf(theta, theta.len()) && symbolic::verify::truth_words_realize(self.store.graph(), atoms@, key.words.view(), theta, current) + implies model::regex_lang(self.store.graph(), theta, successor@, word) + == norm::transition_lang(self.store.graph(), theta, key.transition, current, word) by {} + fint::lemma_entry_val_intro(entry.store.graph(), self.store.graph(), key.transition@, successor@); + } + if self.caches.successors.is_none() { + let cache = GraphCaches::successor_cache().ok_or_else(verus_exec_expr! { + || -> (error: HistoryError) + ensures error is Invariant, + { HistoryError::invariant("invalid successor cache capacity") } + })?; + self.caches.successors = Some(cache); + } + proof_decl! { let ghost entries = successor_entries((*self).caches.successors); } + limits.checkpoint().map_err(HistoryError::from)?; + GraphCaches::successor_put(&mut self.caches.successors, key, successor); + proof! { + assert(successor_entries(self.caches.successors).contains_key(class_key(key))); + assert(successor_entries(self.caches.successors)[class_key(key)] == successor); + assert forall|other: ClassKey| successor_entries(self.caches.successors).contains_key(other) implies + other == class_key(key) || entries.contains_key(other) by {} + assert forall|other: ClassKey| successor_entries((*self).caches.successors).contains_key(other) implies { + let i = other.transition@ as int; + other.transition@ < self.store.graph().transitions.len() && 0 <= i < self.caches.atoms@.len() && self.caches.atoms@[i] is Some + && successor_entries((*self).caches.successors)[other]@ < self.store.graph().regexes.len() + && fint::entry_val(self.store.graph(), other.transition@, successor_entries((*self).caches.successors)[other]@) + && forall|theta: Subst, current: EventView, word: Seq| + language::event_wf(theta, theta.len()) && symbolic::verify::truth_words_realize(self.store.graph(), self.caches.atoms@[i].unwrap()@, other.words, theta, current) + ==> model::regex_lang(self.store.graph(), theta, successor_entries((*self).caches.successors)[other]@, word) + == norm::transition_lang(self.store.graph(), theta, other.transition, current, word) + } by { + if other == class_key(key) { assert(other.transition == key.transition); } + else { assert(entries.contains_key(other)); } + } + } + limits.checkpoint().map_err(HistoryError::from)?; + Ok(successor) + } + #[cfg(feature = "cache")] + #[verus_verify] + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + #[verus_spec(result => + requires pair_wf(*old(self)), + ensures pair_wf(*final(self)), pair_frame(*old(self), *final(self)), + result != Err(HistoryError::WrongHistoryOwner), + language::no_invariant_failure(result), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + result matches Err(error) ==> resource_error(error), + )] + /// Eagerly builds derivatives, atom sets and successor classes for up to `PRECOMPILE_STATES` + /// residual states reachable from `root`, depth-first, within the successor cache's capacity; + /// anything beyond the budget is left to the lazy path. Errors leave the pair well-formed; + /// a graph budget or index error means the caller should discard it. + pub(crate) fn precompile( + &mut self, + limits: &mut L, + world: &mut ObservationWorld, + ) -> KernelResult<()> { + proof_decl! { let ghost entry = *self; } + proof! { lemma_graph_ids_obey_cmp(); } + let mut pending: WorkVec = WorkVec::new(); + pending.push(self.root); + let mut seen = BTreeSet::new(); + let mut states: usize = 0; + let mut used: u64 = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant pair_wf(*self), pair_frame(entry, *self), + entry == *old(self), + forall|j: int| 0 <= j < pending.view().len() ==> pending.view()[j]@ < self.store.graph().regexes.len(), + states <= PRECOMPILE_STATES, used <= SUCCESSOR_CAPACITY, + ensures pair_wf(*self), pair_frame(entry, *self), + decreases pending.view().len() + 2 * (SUCCESSOR_CAPACITY - used) + 2 * (PRECOMPILE_STATES - states), + ))] + while let Some(residual) = pending.pop() { + if states >= PRECOMPILE_STATES { + break; + } + proof! { lemma_graph_ids_obey_cmp(); } + limits.checkpoint().map_err(HistoryError::from)?; + if !seen.insert(residual) { + continue; + } + states = states.saturating_add(1); + proof_decl! { let ghost before = *self; } + proof! { + self.store.lemma_node_count_bounds(); + assert(residual@ < usize::MAX); + } + let derivative = { + let mut kernel = RuntimeKernel { + store: &mut self.store, + limits, + world, + }; + RegexId::derivative(residual, &mut kernel, &mut self.caches.derivatives) + }; + proof! { lemma_pair_symbolic_frame(before, *self); } + let transition = derivative?; + let constant = { + let kernel = RuntimeKernel { + store: &mut self.store, + limits, + world, + }; + match kernel.transition(transition) { + Ok(TransitionView::Const(regex)) => { + proof! { + model::lemma_graph_transition_wf(self.store.graph(), transition@); + norm::transition_unfold(self.store.graph(), transition@); + } + Ok(Some(regex)) + } + Ok(_) => Ok(None), + Err(error) => Err(error), + } + }; + if let Some(regex) = constant? { + pending.push(regex); + continue; + } + self.ensure_atoms(transition, limits, world)?; + let atom_count = Self::cached_atoms(self.caches.atoms.as_slice(), transition)? + .ids() + .len(); + // 2^atoms classes; transitions whose classes overflow the budget stay lazy. + let shift = match u32::try_from(atom_count) { + Ok(shift) => shift, + Err(_) => continue, + }; + let classes = match checked_shl(1, shift) { + Some(classes) => classes, + None => continue, + }; + used = match used.checked_add(classes) { + Some(total) if total <= SUCCESSOR_CAPACITY => total, + _ => continue, + }; + proof_decl! { let ghost base_len = pending.view().len(); } + proof! { + assert(shift < 64); + assert(classes <= 256); + assert(shift <= 8) by(bit_vector) + requires classes == (1u64 << shift), shift < 64, classes <= 256; + assert(atom_count <= 8); + } + let mut minterm: u64 = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant pair_wf(*self), pair_frame(entry, *self), + entry == *old(self), has_atoms(*self, transition), + atom_count == self.caches.atoms@[transition@ as int].unwrap()@.len(), atom_count <= 8, + classes == (1u64 << (atom_count as u32)), + forall|j: int| 0 <= j < pending.view().len() ==> pending.view()[j]@ < self.store.graph().regexes.len(), + minterm <= classes, pending.view().len() == base_len + minterm, + states <= PRECOMPILE_STATES, used <= SUCCESSOR_CAPACITY, + decreases classes - minterm, + ))] + while minterm < classes { + limits.checkpoint().map_err(HistoryError::from)?; + // The class budget admits at most 8 atoms: one truth word, as `instantiate` lays out. + let mut words: SmallVec<[u64; 2]> = SmallVec::new(); + if atom_count > 0 { + words.push(minterm); + } + proof! { + if atom_count == 0 { + assert(words.view() =~= Seq::::empty()); + assert(symbolic::verify::assignment_valid(0, words.view())); + } else { + lemma_single_truth_word(atom_count, minterm); + assert(words.view() =~= seq![minterm]); + } + } + let key = EventClass { transition, words }; + proof_decl! { let ghost class = class_key(key); } + let successor = self.successor(key, limits, world)?; + proof! { assert(successor_entries((*self).caches.successors).contains_key(class)); } + pending.push(successor); + minterm = minterm.saturating_add(1); + } + } + Ok(()) + } +} + +#[verus_verify] +enum Walk { + Transition(TransitionId), + TransitionChildren(TransitionId, usize), + Test(TestId), + TestChildren(TestId, usize), +} + +#[verus_verify] +impl CompiledPair { + /// Collect every unsigned base primitive read anywhere in the transition DAG. + /// Branches are deliberately not pruned using an event or request substitution. + #[allow( + clippy::semicolon_if_nothing_returned, + reason = "Preserve the existing Verus-verified match arms." + )] + #[verus_verify] + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + #[cfg_attr(verus_keep_ghost, verifier::rlimit(30))] + #[verus_spec(result => + requires old(store).valid_store(), model::graph_wf(old(store).graph()), root@ < old(store).graph().transitions.len(), + ensures final(store).valid_store(), model::graph_wf(final(store).graph()), + model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_resource() && old(store).valid_store() + ==> (result matches Err(error) ==> resource_error(error)), + old(store).errors_are_non_invalid_policy() + ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_invariant() ==> language::no_invariant_failure(result), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + result matches Ok(atoms) ==> atoms_wf(final(store).graph(), root@, atoms@), + result matches Ok(atoms) ==> atoms_contained(final(store).graph(), root@, atoms@), + )] + pub(crate) fn collect_atoms( + store: &mut G, + root: TransitionId, + ) -> KernelResult { + proof_decl! { let ghost base = store.graph(); } + proof! { lemma_graph_ids_obey_cmp(); } + let mut work: WorkVec = WorkVec::new(); + work.push(Walk::Transition(root)); + let mut transitions = BTreeSet::new(); + let mut tests = BTreeSet::new(); + let mut primitives = Vec::new(); + proof! { + reveal(collector); + lemma_frontier_push(base, Seq::empty(), Walk::Transition(root)); + assert(visited(transitions@, tests@) =~= ISet::empty()); + assert(collector(base, root@, visited(transitions@, tests@), frontier(base, work.view()), found(store.graph(), primitives@))); + } + proof_decl! { let ghost mut pending_work = work.view(); } + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant + store.valid_store(), model::graph_wf(store.graph()), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + forall|j: int| 0 <= j < primitives@.len() ==> primitives@[j]@ < store.graph().tests.len() + && #[trigger] store.graph().tests[primitives@[j]@ as int] matches model::TestNode::Atom(_, true), + forall|j: int| #![trigger primitives@[j]] 0 <= j < primitives@.len() ==> match store.graph().tests[primitives@[j]@ as int] { + model::TestNode::Atom(p, _) => transition_reaches_primitive(base, root@, p), + _ => false, + }, + model::graph_extends(base, store.graph()), + base == old(store).graph(), + work.view() == pending_work, + model::graph_wf(base), + forall|j: int| 0 <= j < work.view().len() ==> walk_wf(base, work.view()[j]), + forall|j: int| 0 <= j < work.view().len() ==> walk_supported(base, root@, work.view()[j]), + collector(base, root@, visited(transitions@, tests@), frontier(base, work.view()), found(store.graph(), primitives@)), + ensures work.view().len() == 0, + store.valid_store(), model::graph_wf(store.graph()), model::graph_extends(base, store.graph()), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + forall|j: int| 0 <= j < primitives@.len() ==> primitives@[j]@ < store.graph().tests.len() + && #[trigger] store.graph().tests[primitives@[j]@ as int] matches model::TestNode::Atom(_, true), + forall|j: int| #![trigger primitives@[j]] 0 <= j < primitives@.len() ==> match store.graph().tests[primitives@[j]@ as int] { + model::TestNode::Atom(p, _) => transition_reaches_primitive(base, root@, p), + _ => false, + }, + collector(base, root@, visited(transitions@, tests@), frontier(base, work.view()), found(store.graph(), primitives@)), + decreases transition_atoms_work(base, work.view()), + ))] + while let Some(task) = work.pop() { + proof_decl! { + let ghost before_work = pending_work; + let ghost rest = work.view(); + let ghost before_graph = store.graph(); + let ghost before_ids = primitives@; + let ghost before_transitions = transitions@; + let ghost before_tests = tests@; + let ghost before_done = visited(transitions@, tests@); + let ghost before_pending = frontier(base, before_work); + let ghost before_atoms = found(store.graph(), primitives@); + } + proof! { + lemma_frontier_push(base, work.view(), task); + assert(work.view().push(task) =~= pending_work); + assert(collector(base, root@, before_done, before_pending, before_atoms)); + assert(walk_wf(base, task)); + assert(walk_supported(base, root@, task)); + lemma_walk_supported_children(base, root@, task); + assert forall|j: int| 0 <= j < rest.len() implies + walk_supported(base, root@, rest[j]) by { assert(rest[j] == before_work[j]); } + lemma_graph_ids_obey_cmp(); + lemma_walk_work_push(base); + } + store.checkpoint()?; + match task { + Walk::Transition(id) => { + if !transitions.insert(id) { + proof! { + lemma_visited_insert_transition(before_transitions, before_tests, id); + lemma_frontier_discharge(base, rest, task, work.view(), visited(transitions@, tests@)); + lemma_collector_advance(base, root@, before_done, before_pending, before_atoms, + visited(transitions@, tests@), frontier(base, work.view()), found(store.graph(), primitives@)); + pending_work = work.view(); + } + continue; + } + proof! { + lemma_visited_insert_transition(before_transitions, before_tests, id); + model::lemma_graph_transition_wf(base, id@); + if base.transitions[id@ as int] is Union || base.transitions[id@ as int] is Intersect { + lemma_transition_walk_start(base, id); + } + } + match store.transition(id)? { + TransitionView::Const(_) => {} + TransitionView::If { + test, + then_transition, + else_transition, + } => { + work.push(Walk::Test(test)); + work.push(Walk::Transition(then_transition)); + work.push(Walk::Transition(else_transition)); + proof! { + assert(transition_tests(base, id@)[0] == test@); + assert(transition_edges(base, id@)[0] == then_transition@); + assert(transition_edges(base, id@)[1] == else_transition@); + assert(walk_supported(base, root@, Walk::Test(test))); + assert(walk_supported(base, root@, Walk::Transition(then_transition))); + assert(walk_supported(base, root@, Walk::Transition(else_transition))); + } + } + TransitionView::Union(_) | TransitionView::Intersect(_) => { + work.push(Walk::TransitionChildren(id, 0)); + proof! { assert(walk_supported(base, root@, work.view().last())); } + } + TransitionView::Not(child) + | TransitionView::Append { + transition: child, .. + } => { + work.push(Walk::Transition(child)); + proof! { assert(walk_supported(base, root@, work.view().last())); } + } + } + } + Walk::TransitionChildren(id, index) => { + proof! { model::lemma_graph_transition_wf(base, id@); } + let child = match store.transition(id)? { + TransitionView::Union(children) | TransitionView::Intersect(children) => { + let child = children.get(index).copied(); + proof! { + vstd::slice::axiom_spec_len(children); + if child is Some { + assert(index < children@.len()); + assert(index < usize::MAX); + } + } + child + } + _ => return Err(HistoryError::invariant("invalid transition traversal")), + }; + if let Some(child) = child { + proof! { + assert(model::transition_node_child(base.transitions[id@ as int], index as nat) == Some(child@)); + assert(child@ < base.transitions.len()); + } + let next = index.checked_add(1).ok_or_else(verus_exec_expr! { + || -> (error: HistoryError) + ensures error is Invariant, + { HistoryError::invariant("transition child index overflow") } + })?; + work.push(Walk::TransitionChildren(id, next)); + work.push(Walk::Transition(child)); + proof! { lemma_transition_children_walk(base, id, index, child, next); } + proof! { + assert(transition_edges(base, id@)[index as int] == child@); + assert(walk_supported(base, root@, Walk::Transition(child))); + assert(walk_supported(base, root@, Walk::TransitionChildren(id, next))); + } + } + } + Walk::Test(id) => { + if !tests.insert(id) { + proof! { + lemma_visited_insert_test(before_transitions, before_tests, id); + lemma_frontier_discharge(base, rest, task, work.view(), visited(transitions@, tests@)); + lemma_collector_advance(base, root@, before_done, before_pending, before_atoms, + visited(transitions@, tests@), frontier(base, work.view()), found(store.graph(), primitives@)); + pending_work = work.view(); + } + continue; + } + proof! { lemma_visited_insert_test(before_transitions, before_tests, id); } + proof! { + model::lemma_graph_test_wf(base, id@); + if base.tests[id@ as int] is And || base.tests[id@ as int] is Or { + lemma_test_walk_start(base, id); + } + } + match store.test(id)? { + TestView::True | TestView::False => {} + TestView::Atom { primitive, .. } => { + let positive = store.intern_test(TestView::Atom { + primitive, + positive: true, + })?; + store.reserve_atoms(&mut primitives, 1)?; + primitives.push(positive); + proof! { + lemma_found_inclusion(before_graph, store.graph(), before_ids, before_ids); + norm::graph_lemma_extends_refl(store.graph()); + assert forall|id: TestId| before_ids.contains(id) implies before_ids.push(positive).contains(id) by { + let j = before_ids.lemma_contains_to_index(id); + assert(before_ids.push(positive)[j] == id); + } + lemma_found_inclusion(store.graph(), store.graph(), before_ids, before_ids.push(positive)); + assert(primitives@[before_ids.len() as int] == positive); + assert(store.graph().tests[positive@ as int] == model::TestNode::Atom(primitive@, true)); + assert(has_positive(store.graph(), primitives@, primitive@)); + assert(base.tests[id@ as int] == model::TestNode::Atom(primitive@, match base.tests[id@ as int] { + model::TestNode::Atom(_, polarity) => polarity, _ => true, + })); + assert(test_reaches_primitive(base, id@, primitive@)); + assert(transition_reaches_primitive(base, root@, primitive@)); + assert forall|j: int| #![trigger primitives@[j]] 0 <= j < primitives@.len() implies match store.graph().tests[primitives@[j]@ as int] { + model::TestNode::Atom(p, _) => transition_reaches_primitive(base, root@, p), + _ => false, + } by { + if j < before_ids.len() { assert(primitives@[j] == before_ids[j]); } + else { assert(j == before_ids.len()); } + } + assert forall|j: int| 0 <= j < primitives@.len() implies + primitives@[j]@ < store.graph().tests.len() + && #[trigger] store.graph().tests[primitives@[j]@ as int] matches model::TestNode::Atom(_, true) by { + if j < before_ids.len() { + assert(primitives@[j] == before_ids[j]); + assert(before_graph.tests[before_ids[j]@ as int] matches model::TestNode::Atom(_, true)); + } else { assert(j == before_ids.len()); } + } + } + } + TestView::And(_) | TestView::Or(_) => { + work.push(Walk::TestChildren(id, 0)); + proof! { assert(walk_supported(base, root@, work.view().last())); } + } + } + } + Walk::TestChildren(id, index) => { + proof! { model::lemma_graph_test_wf(base, id@); } + let child = match store.test(id)? { + TestView::And(children) | TestView::Or(children) => { + let child = children.get(index).copied(); + proof! { + vstd::slice::axiom_spec_len(children); + if child is Some { + assert(index < children@.len()); + assert(index < usize::MAX); + } + } + child + } + _ => return Err(HistoryError::invariant("invalid test traversal")), + }; + if let Some(child) = child { + proof! { + assert(model::test_node_child(base.tests[id@ as int], index as nat) == Some(child@)); + assert(child@ < base.tests.len()); + } + let next = index.checked_add(1).ok_or_else(verus_exec_expr! { + || -> (error: HistoryError) + ensures error is Invariant, + { HistoryError::invariant("test child index overflow") } + })?; + work.push(Walk::TestChildren(id, next)); + work.push(Walk::Test(child)); + proof! { lemma_test_children_walk(base, id, index, child, next); } + proof! { + assert(test_edges(base, id@)[index as int] == child@); + assert(walk_supported(base, root@, Walk::Test(child))); + assert(walk_supported(base, root@, Walk::TestChildren(id, next))); + } + } + } + } + proof! { + assert forall|j: int| 0 <= j < work.view().len() implies + walk_supported(base, root@, work.view()[j]) by { + if j < rest.len() { assert(work.view()[j] == rest[j]); } + } + lemma_work_tail_wf(base, rest, work.view()); + lemma_frontier_tail(base, work.view()); + lemma_frontier_discharge(base, rest, task, work.view(), visited(transitions@, tests@)); + lemma_collector_advance(base, root@, before_done, before_pending, before_atoms, + visited(transitions@, tests@), frontier(base, work.view()), found(store.graph(), primitives@)); + pending_work = work.view(); + } + } + proof! { + assert(frontier(base, work.view()) =~= ISet::empty()); + lemma_collector_complete(base, root@, visited(transitions@, tests@), found(store.graph(), primitives@)); + assert forall|p: model::Primitive| transition_reaches_primitive(store.graph(), root@, p) + implies has_positive(store.graph(), primitives@, p) by { + lemma_transition_reaches_stable(base, store.graph(), root@, p); + assert(transition_reaches_primitive(base, root@, p)); + assert(found(store.graph(), primitives@).contains(p)); + } + } + store.checkpoint()?; + proof_decl! { let ghost collected = primitives@; } + proof! { + assert forall|j: int| #![trigger collected[j]] 0 <= j < collected.len() implies match store.graph().tests[collected[j]@ as int] { + model::TestNode::Atom(p, _) => transition_reaches_primitive(base, root@, p), + _ => false, + } by {} + } + proof! { junco_core::kernel::TestId::lemma_obeys_cmp(); } + let primitive_slice = primitives.as_mut_slice(); + primitive_slice.sort_unstable(); + proof_decl! { let ghost sorted = primitives@; } + proof! { + norm::lemma_multiset_members(collected, sorted); + lemma_found_membership(store.graph(), collected, sorted); + assert forall|i: int, j: int| 0 <= i < j < sorted.len() implies sorted[i]@ <= sorted[j]@ by { + assert(!(sorted[i].cmp_spec(&sorted[j]) is Greater)); + } + assert forall|j: int| 0 <= j < sorted.len() implies sorted[j]@ < store.graph().tests.len() + && #[trigger] store.graph().tests[sorted[j]@ as int] matches model::TestNode::Atom(_, true) by { + assert(collected.contains(sorted[j])); + let i = choose|i: int| 0 <= i < collected.len() && collected[i] == sorted[j]; + } + assert forall|j: int| #![trigger sorted[j]] 0 <= j < sorted.len() implies match store.graph().tests[sorted[j]@ as int] { + model::TestNode::Atom(p, _) => transition_reaches_primitive(base, root@, p), + _ => false, + } by { + assert(collected.contains(sorted[j])); + let i = choose|i: int| 0 <= i < collected.len() && collected[i] == sorted[j]; + assert(collected[i] == sorted[j]); + assert(match store.graph().tests[collected[i]@ as int] { + model::TestNode::Atom(p, _) => transition_reaches_primitive(base, root@, p), _ => false, + }); + } + } + primitives.dedup(); + proof! { + norm::lemma_dedup_properties(sorted); + lemma_found_membership(store.graph(), sorted, primitives@); + norm::lemma_dedup_strict(sorted, |id: TestId| id@); + assert forall|i: int, j: int| 0 <= i < j < model::test_ids(primitives@).len() + implies model::test_ids(primitives@)[i] < model::test_ids(primitives@)[j] by { + assert(model::test_ids(primitives@)[i] == primitives@[i]@); + assert(model::test_ids(primitives@)[j] == primitives@[j]@); + assert((|id: TestId| id@)(primitives@[i]) < (|id: TestId| id@)(primitives@[j])); + } + assert(model::strictly_increasing(model::test_ids(primitives@))); + assert forall|j: int| 0 <= j < primitives@.len() implies primitives@[j]@ < store.graph().tests.len() + && #[trigger] store.graph().tests[primitives@[j]@ as int] matches model::TestNode::Atom(_, true) by { + assert(sorted.contains(primitives@[j])); + let i = choose|i: int| 0 <= i < sorted.len() && sorted[i] == primitives@[j]; + } + assert(model::atom_ids_wf(store.graph(), primitives@)); + assert forall|p: model::Primitive| transition_reaches_primitive(store.graph(), root@, p) + implies has_positive(store.graph(), primitives@, p) by { + assert(found(store.graph(), sorted).contains(p)); + assert(found(store.graph(), primitives@).contains(p)); + } + assert forall|p: model::Primitive| has_positive(store.graph(), primitives@, p) implies + transition_reaches_primitive(store.graph(), root@, p) by { + let j = choose|j: int| 0 <= j < primitives@.len() && primitives@[j]@ < store.graph().tests.len() + && store.graph().tests[primitives@[j]@ as int] == model::TestNode::Atom(p, true); + assert(sorted.contains(primitives@[j])); + let i = choose|i: int| 0 <= i < sorted.len() && sorted[i] == primitives@[j]; + assert(sorted[i] == primitives@[j]); + assert(match store.graph().tests[sorted[i]@ as int] { + model::TestNode::Atom(q, _) => transition_reaches_primitive(base, root@, q), _ => false, + }); + assert(transition_reaches_primitive(base, root@, p)); + lemma_transition_reaches_stable(base, store.graph(), root@, p); + } + } + store.checkpoint()?; + AtomSet::new(store, primitives) + } +} + +#[cfg(verus_keep_ghost)] +pub(crate) mod verify { + use super::*; + + verus! { + broadcast use junco_core::kernel::verify::group_kernel_views; + pub enum Vertex { Transition(nat), Test(nat) } + + pub open spec fn test_edges(g: model::Graph, id: nat) -> Seq { + if id < g.tests.len() { match g.tests[id as int] { + model::TestNode::And(cs) | model::TestNode::Or(cs) => cs, + _ => Seq::empty(), + } } else { Seq::empty() } + } + pub open spec fn transition_edges(g: model::Graph, id: nat) -> Seq { + if id < g.transitions.len() { match g.transitions[id as int] { + model::TransitionNode::If(_, a, b) => seq![a, b], + model::TransitionNode::Union(cs) | model::TransitionNode::Intersect(cs) => cs, + model::TransitionNode::Not(t) | model::TransitionNode::Append(t, _) => seq![t], + _ => Seq::empty(), + } } else { Seq::empty() } + } + pub open spec fn transition_tests(g: model::Graph, id: nat) -> Seq { + if id < g.transitions.len() { match g.transitions[id as int] { + model::TransitionNode::If(t, _, _) => seq![t], _ => Seq::empty(), + } } else { Seq::empty() } + } + pub open spec fn test_reaches_primitive(g: model::Graph, id: nat, p: model::Primitive) -> bool + decreases id, + { + id < g.tests.len() && (g.tests[id as int] matches model::TestNode::Atom(q, _) && q == p + || exists|j: int| 0 <= j < test_edges(g, id).len() + && test_edges(g, id)[j] < id + && test_reaches_primitive(g, test_edges(g, id)[j], p)) + } + pub open spec fn transition_reaches_primitive(g: model::Graph, id: nat, p: model::Primitive) -> bool + decreases id, + { + id < g.transitions.len() && ( + (exists|j: int| 0 <= j < transition_tests(g, id).len() + && test_reaches_primitive(g, transition_tests(g, id)[j], p)) + || exists|j: int| 0 <= j < transition_edges(g, id).len() + && transition_edges(g, id)[j] < id + && transition_reaches_primitive(g, transition_edges(g, id)[j], p)) + } + pub open spec fn has_positive(g: model::Graph, ids: Seq, p: model::Primitive) -> bool { + exists|j: int| 0 <= j < ids.len() && ids[j]@ < g.tests.len() + && g.tests[ids[j]@ as int] == model::TestNode::Atom(p, true) + } + pub open spec fn atoms_wf(g: model::Graph, root: nat, ids: Seq) -> bool { + model::atom_ids_wf(g, ids) && forall|p: model::Primitive| + transition_reaches_primitive(g, root, p) ==> has_positive(g, ids, p) + } + + pub open spec fn atoms_contained(g: model::Graph, root: nat, ids: Seq) -> bool { + forall|p: model::Primitive| has_positive(g, ids, p) + ==> transition_reaches_primitive(g, root, p) + } + + pub(super) open spec fn walk_supported(g: model::Graph, root: nat, task: Walk) -> bool { + match task { + Walk::Transition(id) => forall|p: model::Primitive| + transition_reaches_primitive(g, id@, p) ==> transition_reaches_primitive(g, root, p), + Walk::Test(id) => forall|p: model::Primitive| + test_reaches_primitive(g, id@, p) ==> transition_reaches_primitive(g, root, p), + Walk::TransitionChildren(id, _) => forall|p: model::Primitive| + transition_reaches_primitive(g, id@, p) ==> transition_reaches_primitive(g, root, p), + Walk::TestChildren(id, _) => forall|p: model::Primitive| + test_reaches_primitive(g, id@, p) ==> transition_reaches_primitive(g, root, p), + } + } + + pub(super) proof fn lemma_walk_supported_children(g: model::Graph, root: nat, task: Walk) + requires model::graph_wf(g), walk_wf(g, task), walk_supported(g, root, task), + ensures match task { + Walk::Transition(id) | Walk::TransitionChildren(id, _) => + (forall|j: int| #![trigger transition_edges(g, id@)[j]] 0 <= j < transition_edges(g, id@).len() + ==> forall|p: model::Primitive| + transition_reaches_primitive(g, transition_edges(g, id@)[j], p) + ==> transition_reaches_primitive(g, root, p)) + && (forall|j: int| #![trigger transition_tests(g, id@)[j]] 0 <= j < transition_tests(g, id@).len() + ==> forall|p: model::Primitive| + test_reaches_primitive(g, transition_tests(g, id@)[j], p) + ==> transition_reaches_primitive(g, root, p)), + Walk::Test(id) | Walk::TestChildren(id, _) => + forall|j: int| #![trigger test_edges(g, id@)[j]] 0 <= j < test_edges(g, id@).len() + ==> forall|p: model::Primitive| + test_reaches_primitive(g, test_edges(g, id@)[j], p) + ==> transition_reaches_primitive(g, root, p), + }, + { + match task { + Walk::Transition(id) | Walk::TransitionChildren(id, _) => { + model::lemma_graph_transition_wf(g, id@); + assert forall|j: int| #![trigger transition_edges(g, id@)[j]] 0 <= j < transition_edges(g, id@).len() implies + forall|p: model::Primitive| + transition_reaches_primitive(g, transition_edges(g, id@)[j], p) + ==> transition_reaches_primitive(g, root, p) by { + assert(transition_edges(g, id@)[j] < id@); + assert forall|p: model::Primitive| + transition_reaches_primitive(g, transition_edges(g, id@)[j], p) implies + transition_reaches_primitive(g, root, p) by { + assert(transition_reaches_primitive(g, id@, p)); + } + } + assert forall|j: int| #![trigger transition_tests(g, id@)[j]] 0 <= j < transition_tests(g, id@).len() implies + forall|p: model::Primitive| + test_reaches_primitive(g, transition_tests(g, id@)[j], p) + ==> transition_reaches_primitive(g, root, p) by { + assert forall|p: model::Primitive| + test_reaches_primitive(g, transition_tests(g, id@)[j], p) implies + transition_reaches_primitive(g, root, p) by { + assert(transition_reaches_primitive(g, id@, p)); + } + } + }, + Walk::Test(id) | Walk::TestChildren(id, _) => { + model::lemma_graph_test_wf(g, id@); + assert forall|j: int| #![trigger test_edges(g, id@)[j]] 0 <= j < test_edges(g, id@).len() implies + forall|p: model::Primitive| + test_reaches_primitive(g, test_edges(g, id@)[j], p) + ==> transition_reaches_primitive(g, root, p) by { + assert(test_edges(g, id@)[j] < id@); + assert forall|p: model::Primitive| + test_reaches_primitive(g, test_edges(g, id@)[j], p) implies + transition_reaches_primitive(g, root, p) by { + assert(test_reaches_primitive(g, id@, p)); + } + } + }, + } + } + + proof fn lemma_atom_id_index(ids: Seq, index: int) + requires model::strictly_increasing(model::test_ids(ids)), 0 <= index < ids.len(), + ensures index <= ids[index]@, + decreases index, + { + if index > 0 { + lemma_atom_id_index(ids, index - 1); + assert(model::test_ids(ids)[index - 1] < model::test_ids(ids)[index]); + assert(model::test_ids(ids)[index - 1] == ids[index - 1]@); + assert(model::test_ids(ids)[index] == ids[index]@); + assert(ids[index - 1]@ < ids[index]@); + } + } + + pub(crate) proof fn lemma_atom_count_bound(g: model::Graph, ids: Seq) + requires model::atom_ids_wf(g, ids), + ensures ids.len() <= u32::MAX as nat + 1, ids.len() <= g.tests.len(), + { + if ids.len() > 0 { + let last = ids.len() as int - 1; + lemma_atom_id_index(ids, last); + TestId::lemma_view(ids[last]); + assert(ids.len() <= u32::MAX as nat + 1); + assert(ids[last]@ < g.tests.len() + && g.tests[ids[last]@ as int] matches model::TestNode::Atom(_, true)); + } + } + + pub(super) proof fn lemma_single_truth_word(count: usize, word: u64) + requires 1 <= count <= 8, word < (1u64 << (count as u32)), + ensures symbolic::verify::assignment_valid(count as nat, seq![word]), + { + let shift = count as u32; + assert((word >> shift) == 0u64) by(bit_vector) + requires word < (1u64 << shift), 1 <= shift <= 8; + } + + pub proof fn lemma_assignment_set(count: nat, before: Seq, after: Seq, index: nat) + requires symbolic::verify::assignment_valid(count, before), index < count, + after == before.update((index / 64) as int, + before[(index / 64) as int] | (1u64 << ((index % 64) as u32))), + ensures symbolic::verify::assignment_valid(count, after), + { + assert(index / 64 < before.len()); + if count % 64 != 0 { + let last = before.len() as int - 1; + if index / 64 == last { + let value = before[last]; + let bit = (index % 64) as u32; + let shift = (count % 64) as u32; + assert(bit < shift); + assert(((value | (1u64 << bit)) >> shift) == 0u64) by(bit_vector) + requires (value >> shift) == 0u64, bit < shift, shift < 64; + } else { + assert(after[last] == before[last]); + } + } + } + pub open spec fn found(g: model::Graph, ids: Seq) -> ISet { + ISet::new(|p: model::Primitive| has_positive(g, ids, p)) + } + pub open spec fn visited(ts: Set, es: Set) -> ISet { + ISet::new(|v: Vertex| match v { + Vertex::Transition(n) => exists|id: TransitionId| ts.contains(id) && id@ == n, + Vertex::Test(n) => exists|id: TestId| es.contains(id) && id@ == n, + }) + } + pub open spec fn successors(g: model::Graph, v: Vertex) -> ISet { + ISet::new(|c: Vertex| match (v, c) { + (Vertex::Transition(n), Vertex::Transition(k)) => transition_edges(g, n).contains(k), + (Vertex::Transition(n), Vertex::Test(k)) => transition_tests(g, n).contains(k), + (Vertex::Test(n), Vertex::Test(k)) => test_edges(g, n).contains(k), + _ => false, + }) + } + pub open spec fn primitive_at(g: model::Graph, v: Vertex, p: model::Primitive) -> bool { + match v { Vertex::Test(n) => n < g.tests.len() && (g.tests[n as int] matches model::TestNode::Atom(q, _) && q == p), + _ => false } + } + pub(super) open spec fn frame(g: model::Graph, task: Walk) -> ISet { + match task { + Walk::Transition(id) => ISet::empty().insert(Vertex::Transition(id@)), + Walk::Test(id) => ISet::empty().insert(Vertex::Test(id@)), + Walk::TransitionChildren(id, start) => ISet::new(|v: Vertex| exists|j: int| + start <= j < transition_edges(g, id@).len() && v == Vertex::Transition(transition_edges(g, id@)[j])), + Walk::TestChildren(id, start) => ISet::new(|v: Vertex| exists|j: int| + start <= j < test_edges(g, id@).len() && v == Vertex::Test(test_edges(g, id@)[j])), + } + } + pub(super) open spec fn frontier(g: model::Graph, work: Seq) -> ISet { + ISet::new(|v: Vertex| exists|j: int| 0 <= j < work.len() && frame(g, work[j]).contains(v)) + } + #[verifier::opaque] + // Visiting records only immediate obligations. Recursive coverage is concluded + // below only after the frontier is empty, by induction over acyclic graph IDs. + pub open spec fn collector(g: model::Graph, root: nat, done: ISet, pending: ISet, atoms: ISet) -> bool { + done.union(pending).contains(Vertex::Transition(root)) + && (forall|v: Vertex| done.contains(v) ==> successors(g, v).subset_of(done.union(pending))) + && (forall|v: Vertex, p: model::Primitive| done.contains(v) && primitive_at(g, v, p) ==> atoms.contains(p)) + } + pub(super) proof fn lemma_frontier_push(g: model::Graph, work: Seq, task: Walk) + ensures frontier(g, work.push(task)) == frontier(g, work).union(frame(g, task)), + { + assert forall|v: Vertex| frontier(g, work.push(task)).contains(v) == frontier(g, work).union(frame(g, task)).contains(v) by { + if frontier(g, work.push(task)).contains(v) { + let j = choose|j: int| 0 <= j < work.push(task).len() && frame(g, work.push(task)[j]).contains(v); + if j < work.len() { assert(frame(g, work[j]).contains(v)); } + } + if frontier(g, work).contains(v) { + let j = choose|j: int| 0 <= j < work.len() && frame(g, work[j]).contains(v); + assert(frame(g, work.push(task)[j]).contains(v)); + } + if frame(g, task).contains(v) { assert(frame(g, work.push(task)[work.len() as int]).contains(v)); } + } + assert(frontier(g, work.push(task)) =~= frontier(g, work).union(frame(g, task))); + } + pub proof fn lemma_visited_insert_transition(ts: Set, es: Set, id: TransitionId) + ensures visited(ts.insert(id), es) == visited(ts, es).insert(Vertex::Transition(id@)), + { + assert forall|v: Vertex| visited(ts.insert(id), es).contains(v) == visited(ts, es).insert(Vertex::Transition(id@)).contains(v) by { + match v { Vertex::Transition(n) => { + if visited(ts.insert(id), es).contains(v) { + let x = choose|x: TransitionId| ts.insert(id).contains(x) && x@ == n; + } + if visited(ts, es).contains(v) { let x = choose|x: TransitionId| ts.contains(x) && x@ == n; } + }, Vertex::Test(n) => {} } + } + assert(visited(ts.insert(id), es) =~= visited(ts, es).insert(Vertex::Transition(id@))); + } + pub proof fn lemma_visited_insert_test(ts: Set, es: Set, id: TestId) + ensures visited(ts, es.insert(id)) == visited(ts, es).insert(Vertex::Test(id@)), + { + assert forall|v: Vertex| visited(ts, es.insert(id)).contains(v) == visited(ts, es).insert(Vertex::Test(id@)).contains(v) by { + match v { Vertex::Test(n) => { + if visited(ts, es.insert(id)).contains(v) { let x = choose|x: TestId| es.insert(id).contains(x) && x@ == n; } + if visited(ts, es).contains(v) { let x = choose|x: TestId| es.contains(x) && x@ == n; } + }, Vertex::Transition(n) => {} } + } + assert(visited(ts, es.insert(id)) =~= visited(ts, es).insert(Vertex::Test(id@))); + } + pub proof fn lemma_collector_advance(g: model::Graph, root: nat, d0: ISet, p0: ISet, a0: ISet, d1: ISet, p1: ISet, a1: ISet) + requires collector(g, root, d0, p0, a0), d0.subset_of(d1), + d0.union(p0).subset_of(d1.union(p1)), a0.subset_of(a1), + forall|v: Vertex| d1.contains(v) && !d0.contains(v) ==> successors(g, v).subset_of(d1.union(p1)), + forall|v: Vertex, p: model::Primitive| d1.contains(v) && !d0.contains(v) && primitive_at(g, v, p) ==> a1.contains(p), + ensures collector(g, root, d1, p1, a1), + { + reveal(collector); + assert forall|v: Vertex| d1.contains(v) implies successors(g, v).subset_of(d1.union(p1)) by { + if d0.contains(v) { assert(successors(g, v).subset_of(d0.union(p0))); } + } + } + pub proof fn lemma_test_closed(g: model::Graph, done: ISet, atoms: ISet, id: nat, p: model::Primitive) + requires done.contains(Vertex::Test(id)), test_reaches_primitive(g, id, p), + forall|v: Vertex| done.contains(v) ==> successors(g, v).subset_of(done), + forall|v: Vertex, p: model::Primitive| done.contains(v) && primitive_at(g, v, p) ==> atoms.contains(p), + ensures atoms.contains(p), + decreases id, + { + if !(g.tests[id as int] matches model::TestNode::Atom(q, _) && q == p) { + let j = choose|j: int| 0 <= j < test_edges(g, id).len() && test_edges(g, id)[j] < id + && test_reaches_primitive(g, test_edges(g, id)[j], p); + assert(test_edges(g, id).contains(test_edges(g, id)[j])); + assert(successors(g, Vertex::Test(id)).contains(Vertex::Test(test_edges(g, id)[j]))); + lemma_test_closed(g, done, atoms, test_edges(g, id)[j], p); + } else { + assert(primitive_at(g, Vertex::Test(id), p)); + } + } + pub proof fn lemma_transition_closed(g: model::Graph, done: ISet, atoms: ISet, id: nat, p: model::Primitive) + requires done.contains(Vertex::Transition(id)), transition_reaches_primitive(g, id, p), + forall|v: Vertex| done.contains(v) ==> successors(g, v).subset_of(done), + forall|v: Vertex, p: model::Primitive| done.contains(v) && primitive_at(g, v, p) ==> atoms.contains(p), + ensures atoms.contains(p), + decreases id, + { + if exists|j: int| 0 <= j < transition_tests(g, id).len() && test_reaches_primitive(g, transition_tests(g, id)[j], p) { + let j = choose|j: int| 0 <= j < transition_tests(g, id).len() && test_reaches_primitive(g, transition_tests(g, id)[j], p); + assert(transition_tests(g, id).contains(transition_tests(g, id)[j])); + assert(successors(g, Vertex::Transition(id)).contains(Vertex::Test(transition_tests(g, id)[j]))); + lemma_test_closed(g, done, atoms, transition_tests(g, id)[j], p); + } else { + let j = choose|j: int| 0 <= j < transition_edges(g, id).len() && transition_edges(g, id)[j] < id + && transition_reaches_primitive(g, transition_edges(g, id)[j], p); + assert(transition_edges(g, id).contains(transition_edges(g, id)[j])); + assert(successors(g, Vertex::Transition(id)).contains(Vertex::Transition(transition_edges(g, id)[j]))); + lemma_transition_closed(g, done, atoms, transition_edges(g, id)[j], p); + } + } + pub proof fn lemma_collector_complete(g: model::Graph, root: nat, done: ISet, atoms: ISet) + requires collector(g, root, done, ISet::empty(), atoms), + ensures forall|p: model::Primitive| transition_reaches_primitive(g, root, p) ==> atoms.contains(p), + { + reveal(collector); + assert forall|p: model::Primitive| transition_reaches_primitive(g, root, p) implies atoms.contains(p) by { + lemma_transition_closed(g, done, atoms, root, p); + } + } + + pub proof fn lemma_graph_ids_obey_cmp() + ensures vstd::laws_cmp::obeys_cmp::(), vstd::laws_cmp::obeys_cmp::(), + vstd::laws_cmp::obeys_cmp::(), + { + reveal(vstd::laws_eq::obeys_eq_spec_properties); + reveal(vstd::laws_cmp::obeys_partial_cmp_spec_properties); + reveal(vstd::laws_cmp::obeys_cmp_partial_ord); + reveal(vstd::laws_cmp::obeys_cmp_ord); + } + + pub(crate) proof fn lemma_found_inclusion(a: model::Graph, b: model::Graph, left: Seq, right: Seq) + requires model::graph_extends(a, b), + forall|id: TestId| left.contains(id) ==> right.contains(id), + ensures found(a, left).subset_of(found(b, right)), + { + assert forall|p: model::Primitive| found(a, left).contains(p) implies found(b, right).contains(p) by { + let j = choose|j: int| 0 <= j < left.len() && left[j]@ < a.tests.len() + && a.tests[left[j]@ as int] == model::TestNode::Atom(p, true); + assert(left.contains(left[j])); + assert(right.contains(left[j])); + let k = right.lemma_contains_to_index(left[j]); + assert(b.tests[right[k]@ as int] == model::TestNode::Atom(p, true)); + } + } + + + pub(super) open spec fn walk_wf(g: model::Graph, task: Walk) -> bool { + match task { + Walk::Transition(id) => id@ < g.transitions.len(), + Walk::Test(id) => id@ < g.tests.len(), + Walk::TransitionChildren(id, _) => id@ < g.transitions.len() + && (g.transitions[id@ as int] is Union || g.transitions[id@ as int] is Intersect), + Walk::TestChildren(id, _) => id@ < g.tests.len() + && (g.tests[id@ as int] is And || g.tests[id@ as int] is Or), + } + } + + // Termination measure for `CompiledPair::collect_atoms`: the tree-unfolded size of the walk + // over `base`. A children frame pays 1 for each continuation that pops it. + pub open spec fn test_walk_node_work(g: model::Graph, id: nat) -> nat + decreases id, 1nat, + { + if id >= g.tests.len() { 1 } else { + match g.tests[id as int] { + model::TestNode::And(cs) | model::TestNode::Or(cs) => 1 + test_walk_children_work(g, cs, id), + _ => 1, + } + } + } + pub open spec fn test_walk_children_work(g: model::Graph, children: Seq, bound: nat) -> nat + decreases bound, 0nat, children.len(), + { + if children.len() == 0 { 1 } else { + 1 + (if children[0] < bound { test_walk_node_work(g, children[0]) } else { 0 }) + + test_walk_children_work(g, children.skip(1), bound) + } + } + pub open spec fn transition_walk_node_work(g: model::Graph, id: nat) -> nat + decreases id, 1nat, + { + if id >= g.transitions.len() { 1 } else { + match g.transitions[id as int] { + model::TransitionNode::If(t, a, b) => 1 + test_walk_node_work(g, t) + + (if a < id { transition_walk_node_work(g, a) } else { 0 }) + + (if b < id { transition_walk_node_work(g, b) } else { 0 }), + model::TransitionNode::Union(cs) | model::TransitionNode::Intersect(cs) => + 1 + transition_walk_children_work(g, cs, id), + model::TransitionNode::Not(c) | model::TransitionNode::Append(c, _) => + 1 + (if c < id { transition_walk_node_work(g, c) } else { 0 }), + _ => 1, + } + } + } + pub open spec fn transition_walk_children_work(g: model::Graph, children: Seq, bound: nat) -> nat + decreases bound, 0nat, children.len(), + { + if children.len() == 0 { 1 } else { + 1 + (if children[0] < bound { transition_walk_node_work(g, children[0]) } else { 0 }) + + transition_walk_children_work(g, children.skip(1), bound) + } + } + pub(super) open spec fn walk_task_work(g: model::Graph, task: Walk) -> nat { + match task { + Walk::Transition(id) => transition_walk_node_work(g, id@), + Walk::Test(id) => test_walk_node_work(g, id@), + Walk::TransitionChildren(id, i) => if i < transition_edges(g, id@).len() { + transition_walk_children_work(g, transition_edges(g, id@).skip(i as int), id@) + } else { 1 }, + Walk::TestChildren(id, i) => if i < test_edges(g, id@).len() { + test_walk_children_work(g, test_edges(g, id@).skip(i as int), id@) + } else { 1 }, + } + } + pub(super) open spec fn transition_atoms_work(g: model::Graph, work: Seq) -> nat + decreases work.len(), + { + if work.len() == 0 { 0 } else { + transition_atoms_work(g, work.drop_last()) + walk_task_work(g, work.last()) + } + } + + pub(super) proof fn lemma_walk_work_push(g: model::Graph) + ensures forall|work: Seq, task: Walk| #[trigger] transition_atoms_work(g, work.push(task)) + == transition_atoms_work(g, work) + walk_task_work(g, task), + { + assert forall|work: Seq, task: Walk| #[trigger] transition_atoms_work(g, work.push(task)) + == transition_atoms_work(g, work) + walk_task_work(g, task) by { + assert(work.push(task).drop_last() =~= work); + } + } + + /// Entering a composite pops `1 + children` and pushes the `*Children(id, 0)` frame. + pub(super) proof fn lemma_transition_walk_start(g: model::Graph, id: TransitionId) + requires id@ < g.transitions.len(), g.transitions[id@ as int] is Union || g.transitions[id@ as int] is Intersect, + ensures walk_task_work(g, Walk::Transition(id)) == 1 + walk_task_work(g, Walk::TransitionChildren(id, 0)), + { + assert(transition_edges(g, id@).skip(0) =~= transition_edges(g, id@)); + } + + pub(super) proof fn lemma_test_walk_start(g: model::Graph, id: TestId) + requires id@ < g.tests.len(), g.tests[id@ as int] is And || g.tests[id@ as int] is Or, + ensures walk_task_work(g, Walk::Test(id)) == 1 + walk_task_work(g, Walk::TestChildren(id, 0)), + { + assert(test_edges(g, id@).skip(0) =~= test_edges(g, id@)); + } + + /// A live continuation pops `1 + child + rest` and pushes `child` and `rest`. + pub(super) proof fn lemma_transition_children_walk(g: model::Graph, id: TransitionId, index: usize, child: TransitionId, next: usize) + requires model::graph_wf(g), id@ < g.transitions.len(), index < transition_edges(g, id@).len(), + (g.transitions[id@ as int] is Union || g.transitions[id@ as int] is Intersect), + child@ == transition_edges(g, id@)[index as int], next == index + 1, + ensures walk_task_work(g, Walk::TransitionChildren(id, index)) + == 1 + walk_task_work(g, Walk::Transition(child)) + walk_task_work(g, Walk::TransitionChildren(id, next)), + { + model::lemma_graph_transition_wf(g, id@); + let cs = transition_edges(g, id@); + assert(cs[index as int] < id@); + assert(cs.skip(index as int)[0] == cs[index as int]); + assert(cs.skip(index as int).skip(1) =~= cs.skip(next as int)); + assert(transition_walk_children_work(g, cs.skip(index as int), id@) + == 1 + transition_walk_node_work(g, cs[index as int]) + transition_walk_children_work(g, cs.skip(next as int), id@)); + if next >= cs.len() { + assert(cs.skip(next as int).len() == 0); + assert(transition_walk_children_work(g, cs.skip(next as int), id@) == 1); + } + } + + pub(super) proof fn lemma_test_children_walk(g: model::Graph, id: TestId, index: usize, child: TestId, next: usize) + requires model::graph_wf(g), id@ < g.tests.len(), index < test_edges(g, id@).len(), + (g.tests[id@ as int] is And || g.tests[id@ as int] is Or), + child@ == test_edges(g, id@)[index as int], next == index + 1, + ensures walk_task_work(g, Walk::TestChildren(id, index)) + == 1 + walk_task_work(g, Walk::Test(child)) + walk_task_work(g, Walk::TestChildren(id, next)), + { + model::lemma_graph_test_wf(g, id@); + let cs = test_edges(g, id@); + assert(cs[index as int] < id@); + assert(cs.skip(index as int)[0] == cs[index as int]); + assert(cs.skip(index as int).skip(1) =~= cs.skip(next as int)); + assert(test_walk_children_work(g, cs.skip(index as int), id@) + == 1 + test_walk_node_work(g, cs[index as int]) + test_walk_children_work(g, cs.skip(next as int), id@)); + if next >= cs.len() { + assert(cs.skip(next as int).len() == 0); + assert(test_walk_children_work(g, cs.skip(next as int), id@) == 1); + } + } + + pub(super) proof fn lemma_frontier_prefix(g: model::Graph, a: Seq, b: Seq) + requires a.is_prefix_of(b), + ensures frontier(g, a).subset_of(frontier(g, b)), + { + assert forall|v: Vertex| frontier(g, a).contains(v) implies frontier(g, b).contains(v) by { + let j = choose|j: int| 0 <= j < a.len() && frame(g, a[j]).contains(v); + assert(frame(g, b[j]).contains(v)); + } + } + + pub(super) proof fn lemma_frontier_discharge(g: model::Graph, rest: Seq, task: Walk, after: Seq, done: ISet) + requires rest.is_prefix_of(after), frame(g, task).subset_of(done.union(frontier(g, after))), + ensures frontier(g, rest.push(task)).subset_of(done.union(frontier(g, after))), + { + lemma_frontier_push(g, rest, task); + lemma_frontier_prefix(g, rest, after); + } + + pub(super) proof fn lemma_frontier_index(g: model::Graph, work: Seq, index: int) + requires 0 <= index < work.len(), + ensures frame(g, work[index]).subset_of(frontier(g, work)), + { + assert forall|v: Vertex| frame(g, work[index]).contains(v) implies frontier(g, work).contains(v) by {} + } + + pub(super) proof fn lemma_frontier_tail(g: model::Graph, work: Seq) + ensures + work.len() > 0 ==> frame(g, work[work.len() - 1]).subset_of(frontier(g, work)), + work.len() > 1 ==> frame(g, work[work.len() - 2]).subset_of(frontier(g, work)), + work.len() > 2 ==> frame(g, work[work.len() - 3]).subset_of(frontier(g, work)), + { + if work.len() > 0 { lemma_frontier_index(g, work, work.len() - 1); } + if work.len() > 1 { lemma_frontier_index(g, work, work.len() - 2); } + if work.len() > 2 { lemma_frontier_index(g, work, work.len() - 3); } + } + + pub proof fn lemma_test_reaches_stable(a: model::Graph, b: model::Graph, id: nat, p: model::Primitive) + requires model::graph_extends(a, b), id < a.tests.len(), + ensures test_reaches_primitive(a, id, p) == test_reaches_primitive(b, id, p), + decreases id, + { + assert(test_edges(a, id) == test_edges(b, id)); + assert forall|j: int| 0 <= j < test_edges(a, id).len() && test_edges(a, id)[j] < id + implies test_reaches_primitive(a, test_edges(a, id)[j], p) + == test_reaches_primitive(b, test_edges(a, id)[j], p) by { + lemma_test_reaches_stable(a, b, test_edges(a, id)[j], p); + } + } + + pub proof fn lemma_transition_reaches_stable(a: model::Graph, b: model::Graph, id: nat, p: model::Primitive) + requires model::graph_wf(a), model::graph_extends(a, b), id < a.transitions.len(), + ensures transition_reaches_primitive(a, id, p) == transition_reaches_primitive(b, id, p), + decreases id, + { + model::lemma_graph_transition_wf(a, id); + assert(transition_edges(a, id) == transition_edges(b, id)); + assert(transition_tests(a, id) == transition_tests(b, id)); + assert forall|j: int| 0 <= j < transition_tests(a, id).len() + implies test_reaches_primitive(a, transition_tests(a, id)[j], p) + == test_reaches_primitive(b, transition_tests(a, id)[j], p) by { + lemma_test_reaches_stable(a, b, transition_tests(a, id)[j], p); + } + assert forall|j: int| 0 <= j < transition_edges(a, id).len() && transition_edges(a, id)[j] < id + implies transition_reaches_primitive(a, transition_edges(a, id)[j], p) + == transition_reaches_primitive(b, transition_edges(a, id)[j], p) by { + lemma_transition_reaches_stable(a, b, transition_edges(a, id)[j], p); + } + } + + pub proof fn lemma_found_membership(g: model::Graph, a: Seq, b: Seq) + requires forall|id: TestId| a.contains(id) <==> b.contains(id), + ensures found(g, a) == found(g, b), + { + norm::graph_lemma_extends_refl(g); + lemma_found_inclusion(g, g, a, b); + lemma_found_inclusion(g, g, b, a); + assert(found(g, a) =~= found(g, b)); + } + + pub(super) proof fn lemma_work_tail_wf(g: model::Graph, rest: Seq, after: Seq) + requires rest.is_prefix_of(after), after.len() <= rest.len() + 3, + forall|j: int| 0 <= j < rest.len() ==> walk_wf(g, rest[j]), + after.len() > rest.len() ==> walk_wf(g, after[after.len() - 1]), + after.len() > rest.len() + 1 ==> walk_wf(g, after[after.len() - 2]), + after.len() > rest.len() + 2 ==> walk_wf(g, after[after.len() - 3]), + ensures forall|j: int| 0 <= j < after.len() ==> walk_wf(g, after[j]), + { + assert forall|j: int| 0 <= j < after.len() implies walk_wf(g, after[j]) by { + if j < rest.len() { assert(after[j] == rest[j]); } + } + } + + pub proof fn lemma_atoms_contained_extends(a: model::Graph, b: model::Graph, root: nat, ids: Seq) + requires model::graph_wf(a), model::graph_extends(a, b), root < a.transitions.len(), + model::atom_ids_wf(a, ids), atoms_contained(a, root, ids), + ensures atoms_contained(b, root, ids), + { + assert forall|p: model::Primitive| has_positive(b, ids, p) implies + transition_reaches_primitive(b, root, p) by { + let j = choose|j: int| 0 <= j < ids.len() && ids[j]@ < b.tests.len() + && b.tests[ids[j]@ as int] == model::TestNode::Atom(p, true); + assert(a.tests[ids[j]@ as int] == b.tests[ids[j]@ as int]); + assert(has_positive(a, ids, p)); + lemma_transition_reaches_stable(a, b, root, p); + } + } + + pub proof fn lemma_atoms_wf_extends(a: model::Graph, b: model::Graph, root: nat, ids: Seq) + requires model::graph_wf(a), model::graph_extends(a, b), root < a.transitions.len(), atoms_wf(a, root, ids), + ensures atoms_wf(b, root, ids), + { + lemma_found_inclusion(a, b, ids, ids); + assert forall|j: int| 0 <= j < ids.len() implies ids[j]@ < b.tests.len() + && (b.tests[ids[j]@ as int] matches model::TestNode::Atom(_, true)) by { + assert(a.tests[ids[j]@ as int] == b.tests[ids[j]@ as int]); + } + assert forall|p: model::Primitive| transition_reaches_primitive(b, root, p) implies has_positive(b, ids, p) by { + lemma_transition_reaches_stable(a, b, root, p); + assert(has_positive(a, ids, p)); + assert(found(a, ids).contains(p)); + assert(found(b, ids).contains(p)); + } + } + + + pub open(crate) spec fn atom_cache_wf(g: model::Graph, atoms: Seq>) -> bool { + forall|i: int| 0 <= i < atoms.len() && atoms[i] is Some ==> i < g.transitions.len() + && atoms_wf(g, i as nat, atoms[i].unwrap()@) + && atoms_contained(g, i as nat, atoms[i].unwrap()@) + } + + pub open(crate) spec fn successor_entries_wf( + g: model::Graph, atoms: Seq>, entries: Map, + ) -> bool { + forall|key: ClassKey| entries.contains_key(key) ==> { + let index = key.transition@ as int; + key.transition@ < g.transitions.len() && 0 <= index < atoms.len() && atoms[index] is Some + && entries[key]@ < g.regexes.len() + && fint::entry_val(g, key.transition@, entries[key]@) + && forall|theta: Subst, event: EventView, word: Seq| + language::event_wf(theta, theta.len()) && symbolic::verify::truth_words_realize(g, atoms[index].unwrap()@, key.words, theta, event) + ==> model::regex_lang(g, theta, entries[key]@, word) + == norm::transition_lang(g, theta, key.transition, event, word) + } + } + + /// Some masked atom of `atoms` is false on `event`. + pub open(crate) spec fn guard_blocks( + g: model::Graph, atoms: Seq, mask: u64, theta: Subst, event: EventView, + ) -> bool { + exists|i: int| 0 <= i < atoms.len() && #[trigger] symbolic::verify::truth_word_bit(seq![mask], i as nat) + && !model::test_holds(theta, model::lift_test(g, atoms[i]@), event) + } + + pub open(crate) spec fn guard_wf(g: model::Graph, atoms_cache: Seq>, residual: int, guard: Guard) -> bool { + guard.mask == 0 || { + let t = guard.transition@ as int; + 0 <= residual < g.regexes.len() && guard.transition@ < g.transitions.len() + && 0 <= t < atoms_cache.len() && atoms_cache[t] is Some + && forall|theta: Subst, event: EventView, word: Seq| + language::event_wf(theta, theta.len()) && guard_blocks(g, atoms_cache[t].unwrap()@, guard.mask, theta, event) + ==> model::regex_lang(g, theta, residual as nat, word) + == norm::transition_lang(g, theta, guard.transition, event, word) + } + } + + pub open(crate) spec fn guard_cache_wf(g: model::Graph, atoms_cache: Seq>, guards: Seq>) -> bool { + forall|r: int| 0 <= r < guards.len() && guards[r] is Some ==> guard_wf(g, atoms_cache, r, guards[r].unwrap()) + } + + pub(super) open spec fn has_guard(pair: CompiledPair, residual: RegexId) -> bool { + residual@ < pair.caches.guards@.len() && pair.caches.guards@[residual@ as int] is Some + } + + /// Every (theta, event) realising truth word `w` of `atoms` maps `transition` to `residual`. + pub(super) open spec fn guard_class_covered( + g: model::Graph, atoms: Seq, residual: RegexId, transition: TransitionId, w: u64, + ) -> bool { + forall|theta: Subst, event: EventView, word: Seq| + language::event_wf(theta, theta.len()) && symbolic::verify::truth_words_realize(g, atoms, seq![w], theta, event) + ==> model::regex_lang(g, theta, residual@, word) == norm::transition_lang(g, theta, transition, event, word) + } + + /// Truth word of the first `n` atoms on (theta, event). + pub(super) open spec fn realized_word( + g: model::Graph, atoms: Seq, theta: Subst, event: EventView, n: nat, + ) -> u64 + decreases n, + { + if n == 0 { 0 } else { + let m = (n - 1) as nat; + realized_word(g, atoms, theta, event, m) + | (if model::test_holds(theta, model::lift_test(g, atoms[m as int]@), event) { 1u64 << (m as u32) } else { 0u64 }) + } + } + + + + pub open(crate) spec fn pair_wf(pair: CompiledPair) -> bool { + model::graph_wf(pair.store.graph()) && pair.store.valid_store() + && pair.root@ < pair.store.graph().regexes.len() + && symbolic::verify::derivative_cache_wf(pair.store.graph(), pair.caches.derivatives@) + && atom_cache_wf(pair.store.graph(), pair.caches.atoms@) + && (match pair.caches.successors { Some(cache) => successor_entries_wf(pair.store.graph(), pair.caches.atoms@, successor_cache_view(cache)), None => true }) + && guard_cache_wf(pair.store.graph(), pair.caches.atoms@, pair.caches.guards@) + } + + + + pub open(crate) spec fn pair_frame(before: CompiledPair, after: CompiledPair) -> bool { + model::graph_extends(before.store.graph(), after.store.graph()) && after.root == before.root + } + + + pub open(crate) spec fn has_atoms(pair: CompiledPair, transition: TransitionId) -> bool { + transition@ < pair.caches.atoms@.len() && pair.caches.atoms@[transition@ as int] is Some + } + + pub open(crate) spec fn instantiation_result( + pair: CompiledPair, transition: TransitionId, bindings: Subst, event: Event, result: RegexId, + ) -> bool { + result@ < pair.store.graph().regexes.len() + && forall|word: Seq| model::regex_lang(pair.store.graph(), bindings, result@, word) + == norm::transition_lang(pair.store.graph(), bindings, transition, event@, word) + } + + pub open(crate) spec fn residual_after_prefix( + pair: CompiledPair, history: Seq, bindings: Subst, count: nat, residual: RegexId, + ) -> bool { + count <= history.len() && residual@ < pair.store.graph().regexes.len() + && forall|word: Seq| model::regex_lang(pair.store.graph(), bindings, residual@, word) + == model::regex_lang(pair.store.graph(), bindings, pair.root@, + history.take(count as int) + word) + } + + pub(crate) proof fn lemma_residual_after_prefix_frame( + before: CompiledPair, after: CompiledPair, history: Seq, + bindings: Subst, count: nat, residual: RegexId, + ) + requires pair_wf(before), pair_wf(after), pair_frame(before, after), + residual_after_prefix(before, history, bindings, count, residual), + ensures residual_after_prefix(after, history, bindings, count, residual), + { + hide(language::numeric_lang); hide(model::lift_regex); hide(model::lift_transition); hide(model::test_holds); + model::lemma_graph_wf_elim(before.store.graph()); + model::lemma_lift_regex_stable(before.store.graph(), after.store.graph(), before.root@); + model::lemma_lift_regex_stable(before.store.graph(), after.store.graph(), residual@); + assert forall|word: Seq| model::regex_lang(after.store.graph(), bindings, residual@, word) + == model::regex_lang(after.store.graph(), bindings, after.root@, + history.take(count as int) + word) by { + assert(model::regex_lang(before.store.graph(), bindings, residual@, word) + == model::regex_lang(before.store.graph(), bindings, before.root@, + history.take(count as int) + word)); + } + } + + pub(crate) proof fn lemma_residual_after_prefix_history_extends( + pair: CompiledPair, before: Seq, after: Seq, + bindings: Subst, count: nat, residual: RegexId, + ) + requires before.is_prefix_of(after), + residual_after_prefix(pair, before, bindings, count, residual), + ensures residual_after_prefix(pair, after, bindings, count, residual), + { + hide(language::numeric_lang); hide(model::lift_regex); hide(model::lift_transition); hide(model::test_holds); + assert(before.take(count as int) =~= after.take(count as int)); + } + + + + + + pub proof fn lemma_zero_truth_words(words: Seq, count: nat) + requires forall|i: int| 0 <= i < words.len() ==> words[i] == 0, + count + 63 <= usize::MAX, words.len() == (count + 63) / 64, + ensures forall|j: nat| !symbolic::verify::truth_word_bit(words, j), + symbolic::verify::assignment_valid(count, words), + { + if count % 64 != 0 { + assert(words.len() > 0); + assert(words.last() == 0u64); + let shift = (count % 64) as u32; + assert((0u64 >> shift) == 0u64) by(bit_vector); + } + assert forall|j: nat| !symbolic::verify::truth_word_bit(words, j) by { + if j / 64 < words.len() { + let bit = (j % 64) as u32; + assert(((0u64 >> bit) & 1u64) == 0) by(bit_vector); + } + } + } + + pub(super) proof fn lemma_truth_word_set(before: Seq, after: Seq, index: nat) + requires index / 64 < before.len(), + after == before.update((index / 64) as int, before[(index / 64) as int] | (1u64 << ((index % 64) as u32))), + ensures symbolic::verify::truth_word_bit(after, index), + forall|j: nat| j != index ==> symbolic::verify::truth_word_bit(after, j) == symbolic::verify::truth_word_bit(before, j), + { + let bit = (index % 64) as u32; + let value = before[(index / 64) as int]; + assert(bit < 64); + assert((((value | (1u64 << bit)) >> bit) & 1u64) != 0) by(bit_vector) + requires bit < 64; + assert forall|j: nat| j != index implies symbolic::verify::truth_word_bit(after, j) == symbolic::verify::truth_word_bit(before, j) by { + if j / 64 < before.len() && j / 64 == index / 64 { + let other = (j % 64) as u32; + assert(other < 64); + assert(other != bit); + assert((((value | (1u64 << bit)) >> other) & 1u64) == ((value >> other) & 1u64)) by(bit_vector) + requires bit < 64, other < 64, other != bit; + } + } + } + + #[verifier::spinoff_prover] + #[verifier::rlimit(30)] + pub(super) proof fn lemma_successor_entries_frame(a: model::Graph, b: model::Graph, atoms: Seq>, entries: Map) + requires model::graph_wf(a), model::graph_extends(a, b), atom_cache_wf(a, atoms), successor_entries_wf(a, atoms, entries), + ensures successor_entries_wf(b, atoms, entries), + { + hide(language::numeric_lang); + hide(language::interp_transition); + hide(model::test_holds); + hide(model::lift_regex); + hide(model::lift_transition); + model::lemma_graph_wf_elim(a); + assert forall|key: ClassKey| entries.contains_key(key) implies { + let index = key.transition@ as int; + key.transition@ < b.transitions.len() && 0 <= index < atoms.len() && atoms[index] is Some + && entries[key]@ < b.regexes.len() + && fint::entry_val(b, key.transition@, entries[key]@) + && forall|theta: Subst, event: EventView, word: Seq| + language::event_wf(theta, theta.len()) && symbolic::verify::truth_words_realize(b, atoms[index].unwrap()@, key.words, theta, event) + ==> model::regex_lang(b, theta, entries[key]@, word) + == norm::transition_lang(b, theta, key.transition, event, word) + } by { + let index = key.transition@ as int; + symbolic::verify::truth_words_realize_extends(a, b, atoms[index].unwrap()@, key.words); + model::lemma_lift_regex_stable(a, b, entries[key]@); + fint::lemma_entry_val_stable(a, b, key.transition@, entries[key]@); + model::lemma_lift_transition_stable(a, b, key.transition@); + assert forall|theta: Subst, event: EventView, word: Seq| + language::event_wf(theta, theta.len()) && symbolic::verify::truth_words_realize(b, atoms[index].unwrap()@, key.words, theta, event) + implies model::regex_lang(b, theta, entries[key]@, word) + == norm::transition_lang(b, theta, key.transition, event, word) by { + assert(symbolic::verify::truth_words_realize(a, atoms[index].unwrap()@, key.words, theta, event)); + assert(model::regex_lang(a, theta, entries[key]@, word) == norm::transition_lang(a, theta, key.transition, event, word)); + } + } + } + + pub(crate) proof fn lemma_pair_symbolic_frame(before: CompiledPair, after: CompiledPair) + requires pair_wf(before), after.store.valid_store(), model::graph_wf(after.store.graph()), + pair_frame(before, after), + after.caches.atoms@ == before.caches.atoms@, after.caches.guards@ == before.caches.guards@, successor_entries(after.caches.successors) == successor_entries(before.caches.successors), + symbolic::verify::derivative_cache_wf(after.store.graph(), after.caches.derivatives@), + ensures pair_wf(after), + { + symbolic::verify::derivative_extends(before.store.graph(), after.store.graph()); + assert forall|i: int| 0 <= i < after.caches.atoms@.len() && after.caches.atoms@[i] is Some implies i < after.store.graph().transitions.len() + && atoms_wf(after.store.graph(), i as nat, after.caches.atoms@[i].unwrap()@) + && atoms_contained(after.store.graph(), i as nat, after.caches.atoms@[i].unwrap()@) by { + lemma_atoms_wf_extends(before.store.graph(), after.store.graph(), i as nat, before.caches.atoms@[i].unwrap()@); + lemma_atoms_contained_extends(before.store.graph(), after.store.graph(), i as nat, before.caches.atoms@[i].unwrap()@); + } + lemma_successor_entries_frame(before.store.graph(), after.store.graph(), before.caches.atoms@, successor_entries(before.caches.successors)); + lemma_guard_cache_frame(before.store.graph(), after.store.graph(), before.caches.atoms@, before.caches.guards@); + } + + /// `pair_wf` survives an update of the guard table alone. + pub(super) proof fn lemma_pair_guard_update(before: CompiledPair, after: CompiledPair) + requires pair_wf(before), after.store == before.store, + after.root == before.root, after.caches.derivatives@ == before.caches.derivatives@, + after.caches.atoms@ == before.caches.atoms@, successor_entries(after.caches.successors) == successor_entries(before.caches.successors), + guard_cache_wf(after.store.graph(), after.caches.atoms@, after.caches.guards@), + ensures pair_wf(after), pair_frame(before, after), + { + } + + pub(super) proof fn lemma_guard_cache_frame(a: model::Graph, b: model::Graph, atoms_cache: Seq>, guards: Seq>) + requires model::graph_wf(a), model::graph_extends(a, b), atom_cache_wf(a, atoms_cache), guard_cache_wf(a, atoms_cache, guards), + ensures guard_cache_wf(b, atoms_cache, guards), + { + assert forall|r: int| 0 <= r < guards.len() && guards[r] is Some implies guard_wf(b, atoms_cache, r, guards[r].unwrap()) by { + lemma_guard_wf_frame(a, b, atoms_cache, r, guards[r].unwrap()); + } + } + + #[verifier::spinoff_prover] + #[verifier::rlimit(30)] + pub(super) proof fn lemma_guard_wf_frame(a: model::Graph, b: model::Graph, atoms_cache: Seq>, r: int, guard: Guard) + requires model::graph_wf(a), model::graph_extends(a, b), atom_cache_wf(a, atoms_cache), guard_wf(a, atoms_cache, r, guard), + ensures guard_wf(b, atoms_cache, r, guard), + { + hide(language::numeric_lang); + hide(language::interp_transition); + hide(model::test_holds); + hide(model::lift_test); + hide(model::lift_regex); + hide(model::lift_transition); + if guard.mask != 0 { + let t = guard.transition@ as int; + let atoms = atoms_cache[t].unwrap()@; + assert(model::atom_ids_wf(a, atoms)); + model::lemma_graph_wf_elim(a); + model::lemma_lift_regex_stable(a, b, r as nat); + model::lemma_lift_transition_stable(a, b, guard.transition@); + assert forall|theta: Subst, event: EventView, word: Seq| + language::event_wf(theta, theta.len()) && guard_blocks(b, atoms, guard.mask, theta, event) + implies model::regex_lang(b, theta, r as nat, word) + == norm::transition_lang(b, theta, guard.transition, event, word) by { + lemma_guard_blocks_frame(a, b, atoms, guard.mask, theta, event); + assert(model::regex_lang(a, theta, r as nat, word) == norm::transition_lang(a, theta, guard.transition, event, word)); + } + } + } + + pub(super) proof fn lemma_guard_blocks_frame(a: model::Graph, b: model::Graph, atoms: Seq, mask: u64, theta: Subst, event: EventView) + requires model::graph_extends(a, b), model::atom_ids_wf(a, atoms), guard_blocks(b, atoms, mask, theta, event), + ensures guard_blocks(a, atoms, mask, theta, event), + { + hide(model::test_holds); + let i = choose|i: int| 0 <= i < atoms.len() && #[trigger] symbolic::verify::truth_word_bit(seq![mask], i as nat) + && !model::test_holds(theta, model::lift_test(b, atoms[i]@), event); + model::lemma_lift_test_stable(a, b, atoms[i]@); + } + + pub(super) proof fn lemma_guard_class_covered_frame( + before: model::Graph, after: model::Graph, atoms: Seq, residual: RegexId, transition: TransitionId, w: u64, + ) + requires model::graph_extends(before, after), model::graph_wf(before), model::atom_ids_wf(before, atoms), + residual@ < before.regexes.len(), transition@ < before.transitions.len(), + guard_class_covered(before, atoms, residual, transition, w), + ensures guard_class_covered(after, atoms, residual, transition, w), + { + hide(language::numeric_lang); + hide(language::interp_transition); + hide(model::test_holds); + hide(model::lift_regex); + hide(model::lift_transition); + model::lemma_graph_wf_elim(before); + symbolic::verify::truth_words_realize_extends(before, after, atoms, seq![w]); + model::lemma_lift_regex_stable(before, after, residual@); + model::lemma_lift_transition_stable(before, after, transition@); + assert forall|theta: Subst, event: EventView, word: Seq| + language::event_wf(theta, theta.len()) && symbolic::verify::truth_words_realize(after, atoms, seq![w], theta, event) + implies model::regex_lang(after, theta, residual@, word) == norm::transition_lang(after, theta, transition, event, word) by { + assert(symbolic::verify::truth_words_realize(before, atoms, seq![w], theta, event)); + assert(model::regex_lang(before, theta, residual@, word) == norm::transition_lang(before, theta, transition, event, word)); + } + } + + pub(super) proof fn lemma_word_bit(w: u64, i: nat) + requires i < 64, + ensures symbolic::verify::truth_word_bit(seq![w], i) == (((w >> (i as u32)) & 1u64) != 0u64), + { + assert(i / 64 == 0); + assert(i % 64 == i); + assert(seq![w][0] == w); + } + + pub(super) proof fn lemma_realized_word(g: model::Graph, atoms: Seq, theta: Subst, event: EventView, n: nat) + requires n <= atoms.len(), n <= 8, + ensures realized_word(g, atoms, theta, event, n) < (1u64 << (n as u32)), + forall|i: nat| i < n ==> #[trigger] symbolic::verify::truth_word_bit(seq![realized_word(g, atoms, theta, event, n)], i) + == model::test_holds(theta, model::lift_test(g, atoms[i as int]@), event), + forall|i: nat| n <= i ==> !#[trigger] symbolic::verify::truth_word_bit(seq![realized_word(g, atoms, theta, event, n)], i), + decreases n, + { + let w = realized_word(g, atoms, theta, event, n); + if n == 0 { + assert(w == 0u64); + assert((1u64 << 0u32) == 1u64) by(bit_vector); + assert forall|i: nat| n <= i implies !#[trigger] symbolic::verify::truth_word_bit(seq![w], i) by { + if i < 64 { + lemma_word_bit(w, i); + let j = i as u32; + assert(((0u64 >> j) & 1u64) == 0u64) by(bit_vector); + } + } + } else { + let m = (n - 1) as nat; + lemma_realized_word(g, atoms, theta, event, m); + let prev = realized_word(g, atoms, theta, event, m); + let s = m as u32; + let t = n as u32; + assert(t == s + 1); + assert(!symbolic::verify::truth_word_bit(seq![prev], m)); + if model::test_holds(theta, model::lift_test(g, atoms[m as int]@), event) { + assert(w == prev | (1u64 << s)); + assert((prev | (1u64 << s)) < (1u64 << t)) by(bit_vector) + requires prev < (1u64 << s), s < 8, t == s + 1; + assert forall|i: nat| i < 64 implies #[trigger] symbolic::verify::truth_word_bit(seq![w], i) + == (i == m || symbolic::verify::truth_word_bit(seq![prev], i)) by { + lemma_word_bit(w, i); + lemma_word_bit(prev, i); + let j = i as u32; + if i == m { + assert((((prev | (1u64 << s)) >> s) & 1u64) != 0u64) by(bit_vector) requires s < 64; + } else { + assert((((prev | (1u64 << s)) >> j) & 1u64) == ((prev >> j) & 1u64)) by(bit_vector) + requires s < 64, j < 64, j != s; + } + } + } else { + assert(w == prev | 0u64); + assert((prev | 0u64) == prev) by(bit_vector); + assert(prev < (1u64 << t)) by(bit_vector) + requires prev < (1u64 << s), s < 8, t == s + 1; + } + } + } + + pub(super) proof fn lemma_guard_blocks_word(g: model::Graph, atoms: Seq, mask: u64, theta: Subst, event: EventView) + requires atoms.len() <= 8, guard_blocks(g, atoms, mask, theta, event), + ensures ({ + let w = realized_word(g, atoms, theta, event, atoms.len()); + w < (1u64 << (atoms.len() as u32)) + && symbolic::verify::truth_words_realize(g, atoms, seq![w], theta, event) + && (w & mask) != mask + }), + { + let w = realized_word(g, atoms, theta, event, atoms.len()); + lemma_realized_word(g, atoms, theta, event, atoms.len()); + let i = choose|i: int| 0 <= i < atoms.len() && #[trigger] symbolic::verify::truth_word_bit(seq![mask], i as nat) + && !model::test_holds(theta, model::lift_test(g, atoms[i]@), event); + assert(symbolic::verify::truth_word_bit(seq![w], i as nat) == model::test_holds(theta, model::lift_test(g, atoms[i]@), event)); + lemma_word_bit(w, i as nat); + lemma_word_bit(mask, i as nat); + let j = i as u32; + assert(((mask >> j) & 1u64) != 0u64 && ((w >> j) & 1u64) == 0u64 ==> (w & mask) != mask) by(bit_vector) + requires j < 64; + assert forall|k: int| 0 <= k < atoms.len() implies #[trigger] symbolic::verify::truth_word_bit(seq![w], k as nat) + == model::test_holds(theta, model::lift_test(g, atoms[k]@), event) by {} + } + + pub(super) proof fn lemma_mask_shrink(w: u64, old_mask: u64, m: u64) + ensures (w & (old_mask & m)) != (old_mask & m) ==> (w & old_mask) != old_mask, + { + assert((w & (old_mask & m)) != (old_mask & m) ==> (w & old_mask) != old_mask) by(bit_vector); + } + + + pub(super) proof fn lemma_guard_hit(pair: CompiledPair, residual: RegexId, guard: Guard, bindings: Subst, event: Event) + requires pair_wf(pair), has_guard(pair, residual), pair.caches.guards@[residual@ as int] == Some(guard), guard.mask != 0, + language::event_wf(bindings, bindings.len()), + guard_blocks(pair.store.graph(), pair.caches.atoms@[guard.transition@ as int].unwrap()@, guard.mask, + bindings, event@), + ensures instantiation_result(pair, guard.transition, bindings, event, residual), + { + assert(guard_wf(pair.store.graph(), pair.caches.atoms@, residual@ as int, guard)); + } + + + + pub(super) proof fn lemma_absorbing_language(pair: CompiledPair, bindings: Subst, residual: RegexId) + requires model::graph_wf(pair.store.graph()), residual@ == pair.store.graph().constants.all || residual@ == pair.store.graph().constants.empty, + ensures forall|word: Seq| model::regex_lang(pair.store.graph(), bindings, residual@, word) + == (residual@ == pair.store.graph().constants.all), + { + model::lemma_graph_wf_elim(pair.store.graph()); + assert forall|word: Seq| model::regex_lang(pair.store.graph(), bindings, residual@, word) + == (residual@ == pair.store.graph().constants.all) by { + if residual@ == pair.store.graph().constants.all { + assert(model::lift_regex(pair.store.graph(), residual@) == language::Regex::All); + } else { + assert(model::lift_regex(pair.store.graph(), residual@) == language::Regex::Empty); + } + } + } + + + + + /// `to` denotes the quotient of `from` by `events`, under `bindings`. + pub open(crate) spec fn residual_folds( + pair: CompiledPair, bindings: Subst, from: RegexId, events: Seq, to: RegexId, + ) -> bool { + from@ < pair.store.graph().regexes.len() && to@ < pair.store.graph().regexes.len() + && forall|word: Seq| model::regex_lang(pair.store.graph(), bindings, to@, word) + == model::regex_lang(pair.store.graph(), bindings, from@, events + word) + } + + pub(super) proof fn lemma_fold_start(pair: CompiledPair, bindings: Subst, from: RegexId) + requires from@ < pair.store.graph().regexes.len(), + ensures residual_folds(pair, bindings, from, Seq::empty(), from), + { + assert forall|word: Seq| model::regex_lang(pair.store.graph(), bindings, from@, word) + == model::regex_lang(pair.store.graph(), bindings, from@, Seq::::empty() + word) by { + assert(Seq::::empty() + word =~= word); + } + } + + pub(super) proof fn lemma_fold_frame(before: CompiledPair, after: CompiledPair, bindings: Subst, from: RegexId, events: Seq, to: RegexId) + requires pair_wf(before), pair_frame(before, after), residual_folds(before, bindings, from, events, to), + ensures residual_folds(after, bindings, from, events, to), + { + hide(language::numeric_lang); hide(model::lift_regex); hide(model::lift_transition); hide(model::test_holds); + model::lemma_graph_wf_elim(before.store.graph()); + model::lemma_lift_regex_stable(before.store.graph(), after.store.graph(), from@); + model::lemma_lift_regex_stable(before.store.graph(), after.store.graph(), to@); + assert forall|word: Seq| model::regex_lang(after.store.graph(), bindings, to@, word) + == model::regex_lang(after.store.graph(), bindings, from@, events + word) by { + assert(model::regex_lang(before.store.graph(), bindings, to@, word) + == model::regex_lang(before.store.graph(), bindings, from@, events + word)); + } + } + + pub(super) proof fn lemma_fold_step(pair: CompiledPair, bindings: Subst, from: RegexId, events: Seq, residual: RegexId, transition: TransitionId, event: Event, successor: RegexId) + requires pair_wf(pair), residual_folds(pair, bindings, from, events, residual), + language::event_wf(bindings, bindings.len()), + symbolic::verify::derivative_correct(pair.store.graph(), residual@, transition), + instantiation_result(pair, transition, bindings, event, successor), + ensures residual_folds(pair, bindings, from, events.push(event@), successor), + { + assert forall|word: Seq| model::regex_lang(pair.store.graph(), bindings, successor@, word) + == model::regex_lang(pair.store.graph(), bindings, from@, events.push(event@) + word) by { + assert(events.push(event@) + word =~= events + (seq![event@] + word)); + } + } + + pub(super) proof fn lemma_fold_absorbing(pair: CompiledPair, bindings: Subst, from: RegexId, events: Seq, rest: Seq, residual: RegexId) + requires pair_wf(pair), residual_folds(pair, bindings, from, events, residual), + residual@ == pair.store.graph().constants.all || residual@ == pair.store.graph().constants.empty, + ensures residual_folds(pair, bindings, from, events + rest, residual), + { + // Keep recursive semantics opaque: absorption only needs their established equalities. + hide(pair_wf); hide(model::regex_lang); + hide(language::numeric_lang); hide(model::lift_regex); hide(model::test_holds); hide(model::lift_transition); + assert(model::graph_wf(pair.store.graph())) by { reveal(pair_wf); } + lemma_absorbing_language(pair, bindings, residual); + assert forall|word: Seq| model::regex_lang(pair.store.graph(), bindings, residual@, word) + == model::regex_lang(pair.store.graph(), bindings, from@, (events + rest) + word) by { + assert(model::regex_lang(pair.store.graph(), bindings, residual@, word) + == (residual@ == pair.store.graph().constants.all)); + assert(model::regex_lang(pair.store.graph(), bindings, residual@, rest + word) + == (residual@ == pair.store.graph().constants.all)); + assert(model::regex_lang(pair.store.graph(), bindings, residual@, rest + word) + == model::regex_lang(pair.store.graph(), bindings, from@, events + (rest + word))); + vstd::seq_lib::lemma_concat_associative(events, rest, word); + } + } + + + + } +} + +#[cfg(any(test, feature = "test-util"))] +impl CompiledPair { + #[cfg(test)] + pub(crate) fn reset_work_counters(&mut self) { + self.work = WorkCounters::default(); + } + + pub(crate) fn reset_work_events(&mut self) { + self.work.events = 0; + } + + pub(crate) fn work_events(&self) -> usize { + self.work.events + } + + pub(crate) fn set_answer_checkpoint_failure(&mut self, fail: bool) { + self.work.fail_answer_checkpoint = fail; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use alloc::vec; + use history_store::store::HistoryStore; + use history_syntax::syntax::Component; + use junco_core::flat::{FlatHead, FlatPair, FlatRegex, FlatTerm, FlatTest}; + use junco_core::limits::{MAX_GRAPH_BYTES, Unmetered}; + + #[test] + fn atom_payload_byte_sum_overflow_is_allocation_failure() { + let growth = usize::MAX / core::mem::size_of::>(); + let count = usize::MAX / core::mem::size_of::(); + assert!(matches!( + CompiledPair::atom_payload_bytes(growth, count), + Err(HistoryError::AllocationFailed) + )); + assert_eq!(CompiledPair::atom_payload_bytes(0, 0), Ok(0)); + } + + fn template(regexes: Vec) -> FlatPair { + FlatPair { + head: vec![FlatHead::Bind, FlatHead::Any, FlatHead::Any], + tests: vec![FlatTest::Atom { + field: Component(0), + term: FlatTerm::Variable(Component(0)), + positive: true, + }], + root: u32::try_from(regexes.len().checked_sub(1).unwrap()).unwrap(), + regexes, + } + } + + fn events() -> (Event, Event) { + let store = HistoryStore::new(3); + let mut limits = Unmetered; + let mut world = ObservationWorld; + let action = store + .intern(Component(1), b"read", &mut limits, &mut world) + .unwrap(); + let resource = store + .intern(Component(2), b"doc", &mut limits, &mut world) + .unwrap(); + let alice = store + .intern(Component(0), b"alice", &mut limits, &mut world) + .unwrap(); + let bob = store + .intern(Component(0), b"bob", &mut limits, &mut world) + .unwrap(); + let alice = store.event(&[alice, action, resource]).unwrap(); + let bob = store.event(&[bob, action, resource]).unwrap(); + (alice, bob) + } + + fn decide(pair: &mut CompiledPair, word: &[Event], bindings: &Bindings) -> bool { + let mut limits = Unmetered; + let mut world = ObservationWorld; + let out = pair + .fold(pair.root, word, bindings, &mut limits, &mut world) + .unwrap(); + pair.answer(out, &mut limits, &mut world).unwrap() + } + + #[test] + fn fixed_bindings_share_classes_only_when_truth_words_match() { + let source = template(vec![FlatRegex::Test(0), FlatRegex::Star(0)]); + let mut pair = CompiledPair::compile( + &source, + MAX_GRAPH_BYTES, + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + pair.work.skip_guards = true; + let (alice, bob) = events(); + let alice_bindings = crate::runtime::RuleRuntime::bindings(&source, &alice).unwrap(); + let bob_bindings = crate::runtime::RuleRuntime::bindings(&source, &bob).unwrap(); + assert!(decide(&mut pair, &[alice, alice], &alice_bindings)); + assert_eq!(pair.work.successor_misses, 1); + assert_eq!(pair.work.successor_hits, 1); + assert!(decide(&mut pair, &[bob], &bob_bindings)); + assert_eq!(pair.work.successor_hits, 2); + assert!(!decide(&mut pair, &[bob], &alice_bindings)); + assert_eq!(pair.work.successor_misses, 2); + assert_eq!( + pair.caches.successors.as_ref().map(|cache| cache.len()), + Some(2) + ); + } + + #[test] + fn self_loop_guards_skip_full_event_classes() { + let source = template(vec![ + FlatRegex::All, + FlatRegex::Test(0), + FlatRegex::Concat(vec![0, 1]), + ]); + let (alice, bob) = events(); + let bindings = crate::runtime::RuleRuntime::bindings(&source, &alice).unwrap(); + for (skip_guards, hits, classes) in [(false, 3, 1), (true, 0, 4)] { + let mut pair = CompiledPair::compile( + &source, + MAX_GRAPH_BYTES, + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + pair.work.skip_guards = skip_guards; + assert!(decide(&mut pair, &[bob, bob, bob, alice], &bindings)); + assert_eq!(pair.work.guard_hits, hits); + assert_eq!(pair.work.event_classes, classes); + assert_eq!(pair.work_events(), 4); + pair.reset_work_events(); + assert_eq!(pair.work_events(), 0); + } + } + + #[cfg(feature = "cache")] + #[test] + fn precompile_keeps_the_typed_lazy_language() { + let source = template(vec![ + FlatRegex::All, + FlatRegex::Test(0), + FlatRegex::Star(1), + FlatRegex::Concat(vec![0, 1, 2]), + ]); + let mut eager = CompiledPair::compile( + &source, + MAX_GRAPH_BYTES, + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + let mut lazy = CompiledPair::compile( + &source, + MAX_GRAPH_BYTES, + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + eager + .precompile(&mut Unmetered, &mut ObservationWorld) + .unwrap(); + eager.reset_work_counters(); + let (alice, bob) = events(); + let bindings = crate::runtime::RuleRuntime::bindings(&source, &alice).unwrap(); + for (word, expected) in [ + (&[][..], false), + (&[alice][..], true), + (&[bob, alice, alice][..], true), + (&[alice, bob][..], false), + ] { + assert_eq!(decide(&mut eager, word, &bindings), expected); + assert_eq!(decide(&mut lazy, word, &bindings), expected); + } + assert_eq!(eager.work.derivative_misses, 0); + assert_eq!(eager.work.successor_misses, 0); + } + + #[test] + fn answer_checkpoint_failure_is_not_a_verdict() { + let source = template(vec![FlatRegex::Epsilon]); + let mut pair = CompiledPair::compile( + &source, + MAX_GRAPH_BYTES, + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + let root = pair.root; + pair.set_answer_checkpoint_failure(true); + assert!(matches!( + pair.answer(root, &mut Unmetered, &mut ObservationWorld), + Err(HistoryError::Limit( + junco_core::limits::LimitError::TimeLimitExceeded { .. } + )) + )); + pair.set_answer_checkpoint_failure(false); + assert!( + pair.answer(root, &mut Unmetered, &mut ObservationWorld) + .unwrap() + ); + } +} diff --git a/src/history-semantics/src/runtime.rs b/src/history-semantics/src/runtime.rs new file mode 100644 index 000000000..909c9b2ed --- /dev/null +++ b/src/history-semantics/src/runtime.rs @@ -0,0 +1,1356 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +//! Revision-bound retained cursors and failure-atomic numeric batch evaluation. +//! Graph construction and evaluation never report `WrongHistoryOwner`; typed facades check ownership. + +#[cfg(verus_keep_ghost)] +use crate::compiled_rule::verify::numeric_result; +use crate::progress::CompiledPair; +#[cfg(any(test, feature = "test-util"))] +pub use crate::progress::WorkCounters; +#[cfg(verus_keep_ghost)] +use crate::progress::verify as progress; +#[cfg(verus_keep_ghost)] +use crate::verify::history_algebra; +#[cfg(verus_keep_ghost)] +use crate::verify::typed_decision as decision; +use alloc::sync::Arc; +#[cfg(any(test, feature = "test-util"))] +use alloc::vec::Vec; +#[cfg(verus_keep_ghost)] +use history_store::cache::HISTORY_CACHE_CAPACITY; +#[cfg(verus_keep_ghost)] +use history_store::cache::verify::{cursor_key_eq, longer_cached_prefix}; +use history_store::cache::{CursorCache, HistoryCursor}; +use history_store::history::StoredHistory; +#[cfg(verus_keep_ghost)] +use history_store::history::verify as raw; +use history_store::store::{Event, HistoryStore}; +use junco_core::errors::HistoryError; +use junco_core::flat::FlatPair; +use junco_core::kernel::Bindings; +#[cfg(verus_keep_ghost)] +use junco_core::kernel::verify as model; +use junco_core::kernel::{KernelResult, RegexId}; +use junco_core::limits::Limits; +use junco_core::observation::ObservationWorld; +#[cfg(verus_keep_ghost)] +use junco_core::spec::semantics::resource_error; +#[cfg(verus_keep_ghost)] +use junco_core::verify::history_specs as language; +#[cfg(verus_keep_ghost)] +use verify::*; +use vstd::prelude::*; +#[cfg(verus_keep_ghost)] +verus! { +broadcast use junco_core::kernel::verify::group_kernel_views; +} + +#[cfg(verus_keep_ghost)] +verus! { +pub mod verify { + use super::*; + broadcast use junco_core::kernel::verify::group_kernel_views; + /// Read-only public predicates keep graph IDs and writable runtime state private. + pub open(crate) spec fn runtime_wf(runtime: RuleRuntime) -> bool { + cursor_cache_wf(runtime.pair, runtime.cursors@, runtime.snapshots@) + } + + pub open(crate) spec fn constructor_result( + result: Result, store: Arc, + template: junco_core::flat::FlatPair, + ) -> bool { + result != Err(HistoryError::WrongHistoryOwner) + && (junco_core::flat::verify::structural_wf(template) ==> language::no_invariant_failure(result)) + && (junco_core::flat::verify::structural_wf(template) + ==> !(result matches Err(HistoryError::InvalidPolicy { .. }))) + && (junco_core::flat::verify::structural_wf(template) + ==> (result matches Err(error) ==> resource_error(error))) + && (result matches Ok(runtime) ==> runtime_wf(runtime) + && runtime.store == store + && runtime.cursors@ == Seq::::empty() + && runtime.snapshots@ == HistorySnapshots::empty() + && crate::compile::verify::regex_correct( + runtime.pair.store.graph(), template, template.root as nat, runtime.pair.root)) + } + + /// The retained root language, without exposing graph nodes or cache state. + pub closed spec fn runtime_accepts( + runtime: RuleRuntime, bindings: language::EventView, events: Seq, + ) -> bool { + model::regex_lang(runtime.pair.store.graph(), bindings, runtime.pair.root@, events) + } + + pub open(crate) spec fn resume_requires( + runtime: RuleRuntime, bindings: Bindings, stored: StoredHistory, target_len: usize, + ) -> bool { + runtime_wf(runtime) + && snapshot_compatible(runtime.snapshots@, stored.id(), stored.revision(), history_store::store::verify::events_view(history_store::history::verify::stored_events(&stored))) + && language::event_wf(bindings@, bindings@.len()) && target_len <= history_store::history::verify::stored_events(&stored).len() + } + + pub open(crate) spec fn resume_ensures( + before: RuleRuntime, after: RuleRuntime, result: BatchCursor, + bindings: Bindings, stored: StoredHistory, target_len: usize, + ) -> bool { + after.store == before.store && after.pair == before.pair && after.cursors@ == before.cursors@ + && after.snapshots@ == before.snapshots@.insert((stored.id(), stored.revision()), history_store::store::verify::events_view(history_store::history::verify::stored_events(&stored))) + && runtime_wf(after) && result.consumed <= target_len + && progress::residual_after_prefix(after.pair, history_store::store::verify::events_view(history_store::history::verify::stored_events(&stored)), + bindings@, result.consumed as nat, result.residual) + && batch_matches_snapshot(after.pair, result, stored.id(), stored.revision(), bindings, after.snapshots@) + } + + pub open(crate) spec fn advance_requires( + runtime: RuleRuntime, cursor: BatchCursor, bindings: Bindings, stored: StoredHistory, + ) -> bool { + runtime_wf(runtime) + && snapshot_compatible(runtime.snapshots@, stored.id(), stored.revision(), history_store::store::verify::events_view(history_store::history::verify::stored_events(&stored))) + && batch_matches_snapshot(runtime.pair, cursor, stored.id(), stored.revision(), bindings, runtime.snapshots@) + } + + pub open(crate) spec fn advance_ensures( + before: RuleRuntime, after: RuleRuntime, start: BatchCursor, cursor: BatchCursor, + bindings: Bindings, stored: StoredHistory, + target_len: usize, batch_size: usize, result: Result, HistoryError>, + ) -> bool { + result != Err(HistoryError::WrongHistoryOwner) + && (batch_size > 0 && start.consumed <= target_len + && target_len <= stored@.events.len() ==> language::no_invariant_failure(result)) + && (batch_size > 0 && start.consumed <= target_len + && target_len <= stored@.events.len() + ==> (result matches Err(error) ==> resource_error(error))) + && runtime_wf(after) && after.store == before.store && progress::pair_frame(before.pair, after.pair) + && after.snapshots@ == before.snapshots@.insert((stored.id(), stored.revision()), history_store::store::verify::events_view(history_store::history::verify::stored_events(&stored))) + && batch_matches_snapshot(after.pair, cursor, stored.id(), stored.revision(), bindings, after.snapshots@) + && progress::residual_after_prefix(after.pair, history_store::store::verify::events_view(history_store::history::verify::stored_events(&stored)), + bindings@, cursor.consumed as nat, cursor.residual) + && (result is Err ==> cursor.consumed == start.consumed + && cursor.residual == start.residual && after.cursors@ == before.cursors@) + && (result is Ok ==> start.consumed <= cursor.consumed <= target_len + && cursor.consumed == language::selected_end(start.consumed as nat, target_len as nat, batch_size as nat)) + && (result matches Ok(None) ==> cursor.consumed < target_len) + && (result matches Ok(Some(answer)) ==> cursor.consumed == target_len + && answer == model::regex_lang(before.pair.store.graph(), bindings@, before.pair.root@, + history_store::store::verify::events_view(history_store::history::verify::stored_events(&stored)).take(target_len as int))) + } + + /// Logical graph IDs and the retained numeric store survive every transaction. + pub open(crate) spec fn runtime_frame(before: RuleRuntime, after: RuleRuntime) -> bool { + after.store == before.store && progress::pair_frame(before.pair, after.pair) + } + + /// Retained graph growth does not change the root language of an earlier runtime. + pub proof fn lemma_runtime_frame_accepts( + before: RuleRuntime, after: RuleRuntime, + bindings: language::EventView, events: Seq, + ) + requires runtime_wf(before), runtime_frame(before, after), + ensures runtime_accepts(before, bindings, events) == runtime_accepts(after, bindings, events), + { + hide(language::numeric_lang); + hide(model::lift_regex); + reveal(runtime_wf); + reveal(runtime_frame); + reveal(runtime_accepts); + model::lemma_graph_wf_elim(before.pair.store.graph()); + model::lemma_lift_regex_stable(before.pair.store.graph(), after.pair.store.graph(), before.pair.root@); + } + + /// A failed transaction preserves every previously retained cursor. + pub open(crate) spec fn cursor_cache_unchanged(before: RuleRuntime, after: RuleRuntime) -> bool { + after.cursors@ == before.cursors@ + } + + pub proof fn lemma_constructor_runtime_wf(runtime: RuleRuntime, store: Arc, + template: junco_core::flat::FlatPair) + requires constructor_result(Ok(runtime), store, template), + ensures runtime_wf(runtime), runtime.spec_store() == store, + runtime.spec_snapshots() == HistorySnapshots::empty(), + { + reveal(constructor_result); + } + + /// A newly constructed runtime has not observed any history revision yet. + pub proof fn lemma_constructor_snapshot_compatible( + runtime: RuleRuntime, store: Arc, template: FlatPair, stored: StoredHistory, + ) + requires constructor_result(Ok(runtime), store, template), + ensures snapshot_compatible(runtime.spec_snapshots(), stored.id(), stored.revision(), stored@.events), + { + lemma_constructor_runtime_wf(runtime, store, template); + lemma_snapshot_compatible_intro(runtime.spec_snapshots(), stored.id(), stored.revision(), stored@.events); + } + + /// Introduce readiness from public observations, not from readiness itself. + pub proof fn lemma_resume_requires( + runtime: RuleRuntime, bindings: Bindings, stored: StoredHistory, target_len: usize, + ) + requires runtime_wf(runtime), + snapshot_compatible(runtime.spec_snapshots(), stored.id(), stored.revision(), stored@.events), + language::event_wf(bindings@, bindings@.len()), target_len <= stored@.events.len(), + ensures resume_requires(runtime, bindings, stored, target_len), + { + history_store::history::lemma_stored_history_view(stored); + reveal(resume_requires); + } + + pub proof fn lemma_resume_can_advance( + before: RuleRuntime, after: RuleRuntime, cursor: BatchCursor, + bindings: Bindings, stored: StoredHistory, target_len: usize, + ) + requires resume_ensures(before, after, cursor, bindings, stored, target_len), + ensures advance_requires(after, cursor, bindings, stored), runtime_wf(after), + runtime_frame(before, after), cursor_cache_unchanged(before, after), + after.spec_store() == before.spec_store(), cursor_consumed(cursor) <= target_len, + after.spec_snapshots() == before.spec_snapshots().insert( + (stored.id(), stored.revision()), stored@.events), + snapshot_compatible(after.spec_snapshots(), stored.id(), stored.revision(), stored@.events), + { + history_store::history::lemma_stored_history_view(stored); + reveal(resume_ensures); + reveal(advance_requires); + reveal(snapshot_compatible); + reveal(runtime_frame); + reveal(cursor_cache_unchanged); + reveal(cursor_consumed); + } + + pub proof fn lemma_advance_result_facts( + before: RuleRuntime, after: RuleRuntime, start: BatchCursor, cursor: BatchCursor, + bindings: Bindings, stored: StoredHistory, + target_len: usize, batch_size: usize, result: Result, HistoryError>, + ) + requires advance_ensures(before, after, start, cursor, bindings, stored, + target_len, batch_size, result), + ensures runtime_wf(after), runtime_frame(before, after), + result != Err(HistoryError::WrongHistoryOwner), + batch_size > 0 && cursor_consumed(start) <= target_len && target_len <= stored@.events.len() + ==> language::no_invariant_failure(result), + batch_size > 0 && cursor_consumed(start) <= target_len && target_len <= stored@.events.len() + ==> (result matches Err(error) ==> resource_error(error)), + after.spec_store() == before.spec_store(), + after.spec_snapshots() == before.spec_snapshots().insert( + (stored.id(), stored.revision()), stored@.events), + snapshot_compatible(after.spec_snapshots(), stored.id(), stored.revision(), stored@.events), + advance_requires(after, cursor, bindings, stored), + result is Err ==> cursor_consumed(cursor) == cursor_consumed(start) + && cursor_cache_unchanged(before, after), + result matches Ok(None) ==> cursor_consumed(cursor) < target_len, + result matches Ok(Some(answer)) ==> cursor_consumed(cursor) == target_len + && answer == runtime_accepts(before, bindings@, stored@.events.take(target_len as int)), + { + history_store::history::lemma_stored_history_view(stored); + reveal(advance_ensures); + reveal(runtime_frame); + reveal(cursor_cache_unchanged); + reveal(cursor_consumed); + reveal(advance_requires); + reveal(snapshot_compatible); + reveal(runtime_accepts); + } + + pub open(crate) spec fn root_cursor_matches(runtime: RuleRuntime, cursor: BatchCursor) -> bool { + cursor.consumed == 0 && cursor.residual == runtime.pair.root + } + + pub open(crate) spec fn cursor_consumed(cursor: BatchCursor) -> nat { + cursor.consumed as nat + } + + /// Numeric event snapshots keyed by immutable history identity and revision. + pub type HistorySnapshots = Map<(usize, u64), Seq>; + + /// Reobserving a revision may extend, but cannot replace, its retained prefix. + pub closed spec fn snapshot_compatible( + snapshots: HistorySnapshots, history: usize, revision: u64, events: Seq, + ) -> bool { + !snapshots.contains_key((history, revision)) + || snapshots[(history, revision)].is_prefix_of(events) + } + + pub proof fn lemma_snapshot_compatible_intro( + snapshots: HistorySnapshots, history: usize, revision: u64, events: Seq, + ) + requires !snapshots.contains_key((history, revision)) + || snapshots[(history, revision)].is_prefix_of(events), + ensures snapshot_compatible(snapshots, history, revision, events), + { + reveal(snapshot_compatible); + } + + pub proof fn lemma_snapshot_compatible_elim( + snapshots: HistorySnapshots, history: usize, revision: u64, events: Seq, + ) + requires snapshot_compatible(snapshots, history, revision, events), + ensures !snapshots.contains_key((history, revision)) + || snapshots[(history, revision)].is_prefix_of(events), + { + reveal(snapshot_compatible); + } + + /// Actual lifecycle receipts justify reuse even when other writers intervene. + pub proof fn lemma_snapshot_compatible_lifecycle( + snapshots: HistorySnapshots, stored: StoredHistory, + tracked snapshot: &raw::Snapshot, tracked lifecycle: &raw::Lifecycle, + ) + requires lifecycle.wf(), lifecycle.state() == stored@, snapshot.id() == lifecycle.id(), + snapshots.contains_key((stored.id(), stored.revision())) ==> + snapshot.value().revision == stored@.revision + && snapshot.value().events == snapshots[(stored.id(), stored.revision())], + ensures snapshot_compatible(snapshots, stored.id(), stored.revision(), stored@.events), + { + history_store::history::lemma_stored_history_view(stored); + if snapshots.contains_key((stored.id(), stored.revision())) { + lifecycle.validate(snapshot); + } + lemma_snapshot_compatible_intro(snapshots, stored.id(), stored.revision(), stored@.events); + } + + pub(crate) open spec fn cursor_matches_snapshot( + pair: CompiledPair, cursor: HistoryCursor, snapshots: HistorySnapshots, + ) -> bool { + language::event_wf(cursor.bindings@, cursor.bindings@.len()) + && snapshots.contains_key((cursor.history, cursor.revision)) + && progress::residual_after_prefix(pair, snapshots[(cursor.history, cursor.revision)], + cursor.bindings@, cursor.consumed as nat, cursor.residual) + } + + pub(crate) open spec fn batch_matches_snapshot( + pair: CompiledPair, cursor: BatchCursor, history: usize, revision: u64, + bindings: Bindings, snapshots: HistorySnapshots, + ) -> bool { + language::event_wf(bindings@, bindings@.len()) + && ((cursor.consumed == 0 && cursor.residual == pair.root) + || (snapshots.contains_key((history, revision)) + && progress::residual_after_prefix(pair, snapshots[(history, revision)], + bindings@, cursor.consumed as nat, cursor.residual))) + } + + pub(crate) open spec fn cursor_cache_wf( + pair: CompiledPair, cursors: Seq, snapshots: HistorySnapshots, + ) -> bool { + crate::progress::verify::pair_wf(pair) + && cursors.len() <= HISTORY_CACHE_CAPACITY + && (forall|i: int| 0 <= i < cursors.len() ==> cursor_matches_snapshot(pair, cursors[i], snapshots)) + && (forall|i: int, j: int| 0 <= i < j < cursors.len() + ==> !cursor_key_eq(cursors[i], cursors[j])) + } + + + pub(super) proof fn lemma_cursor_remove( + pair: crate::progress::CompiledPair, + cursors: Seq, index: int, cursor: HistoryCursor, snapshots: HistorySnapshots, + ) + requires cursor_cache_wf(pair, cursors, snapshots), 0 <= index < cursors.len(), + cursor_key_eq(cursors[index], cursor), + ensures cursor_cache_wf(pair, cursors.remove(index), snapshots), + cursors.remove(index).len() < HISTORY_CACHE_CAPACITY, + forall|i: int| 0 <= i < cursors.remove(index).len() + ==> !cursor_key_eq(cursors.remove(index)[i], cursor) + && cursors.contains(cursors.remove(index)[i]), + { + cursors.remove_ensures(index); + let kept = cursors.remove(index); + assert forall|i: int| 0 <= i < kept.len() implies cursor_matches_snapshot(pair, kept[i], snapshots) + && !cursor_key_eq(kept[i], cursor) && cursors.contains(kept[i]) by { + let original = if i < index { i } else { i + 1 }; + assert(0 <= original < cursors.len()); + assert(kept[i] == cursors[original]); + assert(original != index); + assert(cursor_matches_snapshot(pair, cursors[original], snapshots)); + if original < index { + assert(!cursor_key_eq(cursors[original], cursors[index])); + } else { + assert(!cursor_key_eq(cursors[index], cursors[original])); + } + assert(!cursor_key_eq(cursors[original], cursor)); + assert(cursors.contains(cursors[original])); + } + assert forall|i: int, j: int| 0 <= i < j < kept.len() + implies !cursor_key_eq(kept[i], kept[j]) by { + let left = if i < index { i } else { i + 1 }; + let right = if j < index { j } else { j + 1 }; + assert(0 <= left < right < cursors.len()); + assert(left < right); + assert(kept[i] == cursors[left]); + assert(kept[j] == cursors[right]); + } + } + + pub(super) proof fn lemma_cursor_drop_last( + pair: CompiledPair, cursors: Seq, snapshots: HistorySnapshots, + ) + requires cursor_cache_wf(pair, cursors, snapshots), cursors.len() > 0, + ensures cursor_cache_wf(pair, cursors.drop_last(), snapshots), + forall|i: int| 0 <= i < cursors.drop_last().len() + ==> cursors.drop_last()[i] == cursors[i] && cursors.contains(cursors.drop_last()[i]), + { + assert forall|i: int| 0 <= i < cursors.drop_last().len() + implies cursors.drop_last()[i] == cursors[i] && cursors.contains(cursors.drop_last()[i]) by {} + assert forall|i: int, j: int| 0 <= i < j < cursors.drop_last().len() + implies !cursor_key_eq(cursors.drop_last()[i], cursors.drop_last()[j]) by { + assert(cursors.drop_last()[i] == cursors[i]); + assert(cursors.drop_last()[j] == cursors[j]); + } + } + + pub(super) proof fn lemma_cursor_prepend( + pair: CompiledPair, cursors: Seq, cursor: HistoryCursor, snapshots: HistorySnapshots, + ) + requires cursor_cache_wf(pair, cursors, snapshots), cursors.len() < HISTORY_CACHE_CAPACITY, + cursor_matches_snapshot(pair, cursor, snapshots), + forall|i: int| 0 <= i < cursors.len() ==> !cursor_key_eq(cursors[i], cursor), + ensures cursor_cache_wf(pair, seq![cursor] + cursors, snapshots), + { + let after = seq![cursor] + cursors; + assert forall|i: int| 0 <= i < after.len() implies cursor_matches_snapshot(pair, after[i], snapshots) by { + if i == 0 { assert(after[i] == cursor); } + else { assert(after[i] == cursors[i - 1]); } + } + assert forall|i: int, j: int| 0 <= i < j < after.len() + implies !cursor_key_eq(after[i], after[j]) by { + assert(after[j] == cursors[j - 1]); + if i == 0 { assert(after[i] == cursor); } + else { assert(after[i] == cursors[i - 1]); } + } + } + + pub(crate) proof fn lemma_cursor_cache_frame( + before: CompiledPair, after: CompiledPair, cursors: Seq, snapshots: HistorySnapshots, + ) + requires cursor_cache_wf(before, cursors, snapshots), progress::pair_wf(after), + progress::pair_frame(before, after), + ensures cursor_cache_wf(after, cursors, snapshots), + { + assert forall|i: int| 0 <= i < cursors.len() + implies cursor_matches_snapshot(after, cursors[i], snapshots) by { + let cursor = cursors[i]; + progress::lemma_residual_after_prefix_frame(before, after, + snapshots[(cursor.history, cursor.revision)], cursor.bindings@, + cursor.consumed as nat, cursor.residual); + } + } + + pub(crate) proof fn lemma_cursor_cache_observe( + pair: CompiledPair, cursors: Seq, snapshots: HistorySnapshots, + history: usize, revision: u64, events: Seq, + ) + requires cursor_cache_wf(pair, cursors, snapshots), + snapshot_compatible(snapshots, history, revision, events), + ensures cursor_cache_wf(pair, cursors, snapshots.insert((history, revision), events)), + { + let updated = snapshots.insert((history, revision), events); + assert forall|i: int| 0 <= i < cursors.len() + implies cursor_matches_snapshot(pair, cursors[i], updated) by { + let cursor = cursors[i]; + if (cursor.history, cursor.revision) == (history, revision) { + progress::lemma_residual_after_prefix_history_extends(pair, + snapshots[(history, revision)], events, cursor.bindings@, + cursor.consumed as nat, cursor.residual); + } + } + } +} +} + +#[verus_verify] +pub struct RuleRuntime { + pub(crate) pair: crate::progress::CompiledPair, + pub(crate) cursors: CursorCache, + pub(crate) store: Arc, + #[cfg(verus_keep_ghost)] + pub(crate) snapshots: Ghost, +} + +impl core::fmt::Debug for RuleRuntime { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("RuleRuntime") + .field("pair", &self.pair) + .field("cursors", &self.cursors) + .finish() + } +} + +#[verus_verify] +impl RuleRuntime { + #[cfg(verus_keep_ghost)] + verus! { + pub open(crate) spec fn spec_store(&self) -> Arc { self.store } + + /// Read-only observations used to establish compatibility before evaluation. + pub open(crate) spec fn spec_snapshots(&self) -> verify::HistorySnapshots { self.snapshots@ } + } + + /// The numeric store whose records name this runtime's cursor keys. + #[verus_spec(result => ensures *result == self.spec_store())] + pub fn store(&self) -> &Arc { + &self.store + } + + /// Start a replacement graph generation without exposing or fabricating graph IDs. + #[verus_spec(result => ensures root_cursor_matches(*self, result))] + pub fn root_cursor(&self) -> BatchCursor { + proof! { reveal(root_cursor_matches); } + BatchCursor { + consumed: 0, + residual: self.pair.root, + } + } + + #[verus_spec(result => ensures constructor_result(result, *store, *template), + result != Err(HistoryError::WrongHistoryOwner), + junco_core::flat::verify::structural_wf(*template) ==> language::no_invariant_failure(result) + && !(result matches Err(HistoryError::InvalidPolicy { .. })) + && (result matches Err(error) ==> resource_error(error))) ] + pub fn new( + store: &Arc, + template: &junco_core::flat::FlatPair, + precompile: bool, + limits: &mut L, + world: &mut ObservationWorld, + ) -> Result { + proof! { reveal(constructor_result); reveal(runtime_wf); } + #[cfg_attr(not(feature = "cache"), allow(unused_mut))] + let mut pair = + CompiledPair::compile(template, junco_core::limits::MAX_GRAPH_BYTES, limits, world)?; + #[cfg(feature = "cache")] + if precompile { + proof_decl! { let ghost compiled = pair; } + if let Err(error) = pair.precompile(limits, world) { + if !matches!( + error, + HistoryError::GraphBudget { .. } | HistoryError::GraphIndex + ) { + return Err(error); + } + drop(pair); + pair = CompiledPair::compile( + template, + junco_core::limits::MAX_GRAPH_BYTES, + limits, + world, + )?; + } + proof! { + if progress::pair_frame(compiled, pair) { + model::lemma_graph_wf_elim(compiled.store.graph()); + model::lemma_lift_regex_stable(compiled.store.graph(), pair.store.graph(), compiled.root@); + } + } + } + #[cfg(not(feature = "cache"))] + let _ = precompile; + let cursors = CursorCache::new(limits, world)?; + // The expression macro also supplies the ghost field during Verus's erased Rust check. + let runtime = Self { + pair, + cursors, + store: Arc::clone(store), + #[cfg(verus_keep_ghost)] + snapshots: verus_exec_expr! { Ghost(Map::empty()) }, + }; + Ok(runtime) + } + + /// Bind the candidate and commit one complete-prefix answer/publication transaction. + #[verus_verify] + #[verus_spec(result => + requires decision::runtime_represents(*template, *old(self)), + junco_core::flat::verify::structural_wf(*template), + snapshot_compatible(old(self).snapshots@, stored.id(), stored.revision(), + history_store::store::verify::events_view(raw::stored_events(&stored))), + ensures decision::runtime_represents(*template, *final(self)), + runtime_wf(*final(self)), + progress::pair_frame(old(self).pair, final(self).pair), + final(self).spec_store() == old(self).spec_store(), + result != Err(HistoryError::WrongHistoryOwner), + language::no_invariant_failure(result), + result matches Err(error) ==> resource_error(error), + result is Err ==> final(self).cursors@ == old(self).cursors@, + final(self).snapshots@ == old(self).snapshots@ + || final(self).snapshots@ == old(self).snapshots@.insert((stored.id(), stored.revision()), + history_store::store::verify::events_view(raw::stored_events(&stored))), + result != Ok(None) ==> final(self).snapshots@ == old(self).snapshots@.insert( + (stored.id(), stored.revision()), + history_store::store::verify::events_view(raw::stored_events(&stored))), + numeric_result(*template, *request, *stored, result), + result matches Ok(Some(answer)) ==> exists|bindings: Bindings| + crate::compile::verify::bindings_match(*template, *request, bindings) + && language::event_wf(bindings@, bindings@.len()) + && answer == model::regex_lang(old(self).pair.store.graph(), bindings@, + old(self).pair.root@, + history_store::store::verify::events_view(raw::stored_events(&stored))), + )] + pub(crate) fn accepts( + &mut self, + template: &FlatPair, + request: &Event, + stored: &StoredHistory, + limits: &mut L, + world: &mut ObservationWorld, + ) -> Result, HistoryError> { + proof_decl! { let ghost entry = *self; } + let bindings = match Self::bindings(template, request) { + Some(bindings) => bindings, + None => return Ok(None), + }; + proof! { + crate::compile::verify::lemma_bindings_match(*template, *request, bindings); + history_store::history::lemma_stored_history_view(*stored); + reveal(runtime_wf); + reveal(resume_requires); + reveal(resume_ensures); + reveal(advance_requires); + reveal(advance_ensures); + } + proof_decl! { let ghost initial_snapshots = self.snapshots@; } + let target = stored.len(); + let mut cursor = self.resume_cursor(&bindings, stored, target); + proof! { + lemma_resume_can_advance(entry, *self, cursor, bindings, *stored, target); + assert(self.snapshots@ == initial_snapshots.insert((stored.id(), stored.revision()), + history_store::store::verify::events_view(raw::stored_events(&stored)))); + } + proof_decl! { let ghost start = cursor; } + let result = self.advance_cursor( + &mut cursor, + &bindings, + stored, + target, + usize::MAX, + limits, + world, + ); + proof! { + let key = (stored.id(), stored.revision()); + let events = history_store::store::verify::events_view(raw::stored_events(&stored)); + assert(self.snapshots@ == initial_snapshots.insert(key, events).insert(key, events)); + assert(initial_snapshots.insert(key, events).insert(key, events) =~= initial_snapshots.insert(key, events)); + language::lemma_selected_end(start.consumed as nat, target as nat, usize::MAX as nat); + assert(history_store::store::verify::events_view(raw::stored_events(&stored)).take(target as int) + =~= history_store::store::verify::events_view(raw::stored_events(&stored))); + decision::lemma_runtime_frame(*template, entry, *self); + } + match result { + Err(error) => Err(error), + Ok(Some(answer)) => { + proof! { + assert(exists|witness: Bindings| + crate::compile::verify::bindings_match(*template, *request, witness) + && language::event_wf(witness@, witness@.len()) + && answer == crate::compile::verify::source_regex(*template, + template.root as nat, witness@, + history_store::store::verify::events_view(raw::stored_events(&stored)))) by { + assert(crate::compile::verify::bindings_match(*template, *request, bindings)); + } + assert(exists|witness: Bindings| + crate::compile::verify::bindings_match(*template, *request, witness) + && language::event_wf(witness@, witness@.len()) + && answer == model::regex_lang(entry.pair.store.graph(), witness@, + entry.pair.root@, + history_store::store::verify::events_view(raw::stored_events(&stored)))) by { + assert(crate::compile::verify::bindings_match(*template, *request, bindings)); + } + } + Ok(Some(answer)) + } + Ok(None) => { + proof! { assert(false); } + Err(HistoryError::invariant( + "complete history batch returned no answer", + )) + } + } + } + + /// Public so hosts can drive bounded batches (Regorus HistoryStep). + #[expect( + clippy::collapsible_if, + reason = "Pinned Verus does not support let-chain expressions" + )] + #[verus_spec(result => + requires resume_requires(*old(self), *bindings, *stored, target_len), + ensures resume_ensures(*old(self), *final(self), result, *bindings, *stored, target_len), + )] + pub fn resume_cursor( + &mut self, + bindings: &Bindings, + stored: &StoredHistory, + target_len: usize, + ) -> BatchCursor { + proof! { reveal(resume_requires); reveal(resume_ensures); reveal(runtime_wf); } + let history = stored.id(); + proof_decl! { let ghost entry = *self; } + proof! { + lemma_cursor_cache_observe(self.pair, self.cursors@, self.snapshots@, + history, stored.revision(), history_store::store::verify::events_view(history_store::history::verify::stored_events(&stored))); + *self.snapshots = self.snapshots@.insert((history, stored.revision()), history_store::store::verify::events_view(history_store::history::verify::stored_events(&stored))); + } + let mut index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant index <= self.cursors@.len(), + entry == *old(self), history == stored.id(), + self.pair == entry.pair, self.cursors@ == entry.cursors@, self.store == entry.store, + self.snapshots@ == entry.snapshots@.insert((history, stored.revision()), history_store::store::verify::events_view(history_store::history::verify::stored_events(&stored))), + cursor_cache_wf(self.pair, self.cursors@, self.snapshots@), + self.snapshots@.contains_key((history, stored.revision())), + self.snapshots@[(history, stored.revision())] == history_store::store::verify::events_view(history_store::history::verify::stored_events(&stored)), + decreases self.cursors@.len() - index, + ))] + while index < self.cursors.entries().len() { + if let Some(cursor) = self.cursors.entries().get(index) { + if cursor.history == history + && cursor.bindings == *bindings + && cursor.revision == stored.revision() + && cursor.consumed <= target_len + { + proof! { + assert(cursor_matches_snapshot(self.pair, *cursor, self.snapshots@)); + assert(cursor.bindings@ == bindings@); + assert(progress::residual_after_prefix(self.pair, history_store::store::verify::events_view(history_store::history::verify::stored_events(&stored)), + bindings@, cursor.consumed as nat, cursor.residual)); + } + return BatchCursor { + consumed: cursor.consumed, + residual: cursor.residual, + }; + } + } + index = index.saturating_add(1); + } + proof! { + assert(history_store::store::verify::events_view(history_store::history::verify::stored_events(&stored)).take(0) =~= Seq::::empty()); + assert forall|word: Seq| model::regex_lang(self.pair.store.graph(), bindings@, self.pair.root@, word) + == model::regex_lang(self.pair.store.graph(), bindings@, self.pair.root@, + history_store::store::verify::events_view(history_store::history::verify::stored_events(&stored)).take(0) + word) by { + assert(Seq::::empty() + word =~= word); + } + } + BatchCursor { + consumed: 0, + residual: self.pair.root, + } + } + + /// Public so hosts can drive bounded batches (Regorus HistoryStep). + #[expect( + clippy::too_many_arguments, + reason = "Keep the locked history transaction inputs explicit." + )] + #[verus_spec(result => + requires advance_requires(*old(self), *old(cursor), *bindings, *stored), + ensures advance_ensures(*old(self), *final(self), *old(cursor), *final(cursor), + *bindings, *stored, target_len, batch_size, result), + result != Err(HistoryError::WrongHistoryOwner), + )] + pub fn advance_cursor( + &mut self, + cursor: &mut BatchCursor, + bindings: &Bindings, + stored: &StoredHistory, + target_len: usize, + batch_size: usize, + limits: &mut L, + world: &mut ObservationWorld, + ) -> Result, HistoryError> { + proof! { reveal(advance_requires); reveal(advance_ensures); reveal(runtime_wf); } + let history = stored.id(); + proof_decl! { let ghost entry = self.pair; let ghost entry_cursors = self.cursors@; let ghost start = *cursor; } + proof! { + let events = history_store::store::verify::events_view(history_store::history::verify::stored_events(&stored)); + lemma_snapshot_compatible_elim(self.snapshots@, history, stored.revision(), events); + if cursor.consumed == 0 && cursor.residual == self.pair.root { + assert(events.take(0) =~= Seq::::empty()); + assert forall|word: Seq| model::regex_lang(self.pair.store.graph(), bindings@, cursor.residual@, word) + == model::regex_lang(self.pair.store.graph(), bindings@, self.pair.root@, events.take(0) + word) by { + assert(events.take(0) + word =~= word); + } + } else { + progress::lemma_residual_after_prefix_history_extends(self.pair, + self.snapshots@[(history, stored.revision())], events, bindings@, cursor.consumed as nat, cursor.residual); + } + lemma_cursor_cache_observe(self.pair, self.cursors@, self.snapshots@, history, stored.revision(), events); + *self.snapshots = self.snapshots@.insert((history, stored.revision()), events); + } + let result = cursor.advance( + &mut self.pair, + stored.as_slice(), + bindings, + target_len, + batch_size, + limits, + world, + ); + proof! { + lemma_cursor_cache_frame(entry, self.pair, entry_cursors, self.snapshots@); + if result is Err { + progress::lemma_residual_after_prefix_frame(entry, self.pair, history_store::store::verify::events_view(history_store::history::verify::stored_events(&stored)), + bindings@, start.consumed as nat, start.residual); + } + } + match result { + Err(error) => Err(error), + Ok(answer) => { + let published = HistoryCursor { + history, + bindings: *bindings, + revision: stored.revision(), + consumed: cursor.consumed, + residual: cursor.residual, + }; + proof! { assert(cursor_matches_snapshot(self.pair, published, self.snapshots@)); } + self.publish(published); + Ok(answer) + } + } + } + + /// Called only after all fallible batch work, while its history is read-locked. + #[verus_verify] + #[verus_spec( + requires cursor_cache_wf(old(self).pair, old(self).cursors@, old(self).snapshots@), + cursor_matches_snapshot(old(self).pair, cursor, old(self).snapshots@), + ensures + final(self).pair == old(self).pair, final(self).store == old(self).store, + final(self).snapshots@ == old(self).snapshots@, + cursor_cache_wf(final(self).pair, final(self).cursors@, final(self).snapshots@), + longer_cached_prefix(old(self).cursors@, cursor) ==> final(self).cursors@ == old(self).cursors@, + !longer_cached_prefix(old(self).cursors@, cursor) ==> final(self).cursors@.len() > 0 + && final(self).cursors@[0] == cursor, + forall|i: int| 0 <= i < final(self).cursors@.len() + ==> final(self).cursors@[i] == cursor || old(self).cursors@.contains(final(self).cursors@[i]), + )] + pub(crate) fn publish(&mut self, cursor: HistoryCursor) { + proof_decl! { let ghost entry = self.cursors@; } + self.cursors.publish(cursor); + proof! { + assert forall|i: int| 0 <= i < self.cursors@.len() + implies cursor_matches_snapshot(self.pair, self.cursors@[i], self.snapshots@) by { + if self.cursors@[i] != cursor { + assert(entry.contains(self.cursors@[i])); + let original = choose|j: int| 0 <= j < entry.len() && entry[j] == self.cursors@[i]; + assert(cursor_matches_snapshot(self.pair, entry[original], self.snapshots@)); + } + } + } + } +} + +#[cfg(any(test, feature = "test-util"))] +impl RuleRuntime { + /// Read the existing engine counters without exposing mutable graph state. + pub fn work_counters(&self) -> &WorkCounters { + &self.pair.work + } + + pub fn reset_work_events(&mut self) { + self.pair.reset_work_events(); + } + + pub fn work_events(&self) -> usize { + self.pair.work_events() + } + + /// Return keys and committed positions, never graph-local residual IDs. + pub fn cursor_positions(&self) -> Vec<(usize, Bindings, u64, usize)> { + self.cursors + .entries() + .iter() + .map(|cursor| { + ( + cursor.history, + cursor.bindings, + cursor.revision, + cursor.consumed, + ) + }) + .collect() + } + + /// Exchange only byte pressure so replacement tests can restore an old generation. + pub fn replace_graph_byte_pressure(&mut self, bytes: usize) -> usize { + self.pair.store.replace_graph_byte_pressure(bytes) + } + + pub fn set_answer_checkpoint_failure(&mut self, fail: bool) { + self.pair.set_answer_checkpoint_failure(fail); + } +} + +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy, Debug)] +pub struct BatchCursor { + pub(crate) consumed: usize, + pub(crate) residual: RegexId, +} + +impl BatchCursor { + /// Return the committed prefix length. + #[verus_verify] + #[verus_spec(result => ensures result == cursor_consumed(*self))] + pub const fn consumed(&self) -> usize { + proof! { reveal(cursor_consumed); } + self.consumed + } + + /// The same executable transaction is used under the runtime/history locks. + /// No cursor changes until fold, final answer, and publication checks all succeed. + #[expect( + clippy::too_many_arguments, + reason = "Keep explicit transaction inputs aligned with its verified contract." + )] + #[verus_verify] + #[verus_spec(result => + requires + crate::progress::verify::pair_wf(*old(pair)), + crate::progress::verify::residual_after_prefix( + *old(pair), history_store::store::verify::events_view(events@), bindings@, + old(self).consumed as nat, old(self).residual), + ensures + crate::progress::verify::pair_wf(*final(pair)), + crate::progress::verify::pair_frame(*old(pair), *final(pair)), + result != Err(HistoryError::WrongHistoryOwner), + batch_size > 0 && old(self).consumed <= target_len && target_len <= events@.len() + ==> language::no_invariant_failure(result), + batch_size > 0 && old(self).consumed <= target_len && target_len <= events@.len() + ==> (result matches Err(error) ==> resource_error(error)), + result is Err ==> final(self).consumed == old(self).consumed + && final(self).residual == old(self).residual, + result is Ok ==> old(self).consumed <= final(self).consumed + && final(self).consumed <= target_len + && final(self).consumed == junco_core::verify::history_specs::selected_end(old(self).consumed as nat, target_len as nat, batch_size as nat), + result matches Ok(Some(_)) ==> final(self).consumed == target_len, + result matches Ok(None) ==> final(self).consumed < target_len, + result is Ok ==> crate::progress::verify::residual_folds( + *final(pair), bindings@, old(self).residual, + history_store::store::verify::events_view(events@).subrange(old(self).consumed as int, final(self).consumed as int), + final(self).residual), + result matches Ok(Some(answer)) ==> answer == junco_core::kernel::verify::regex_lang( + (*final(pair)).store.graph(), bindings@, + old(self).residual@, history_store::store::verify::events_view(events@).subrange(old(self).consumed as int, target_len as int)), + result is Ok ==> crate::progress::verify::residual_after_prefix( + *final(pair), history_store::store::verify::events_view(events@), bindings@, + final(self).consumed as nat, final(self).residual), + result matches Ok(Some(answer)) ==> answer == junco_core::kernel::verify::regex_lang( + (*old(pair)).store.graph(), bindings@, + old(pair).root@, history_store::store::verify::events_view(events@).take(target_len as int)), + )] + pub(crate) fn advance( + &mut self, + pair: &mut CompiledPair, + events: &[Event], + bindings: &Bindings, + target_len: usize, + batch_size: usize, + limits: &mut L, + world: &mut ObservationWorld, + ) -> KernelResult> { + proof_decl! { let ghost entry = *pair; let ghost entry_cursor = *self; } + if batch_size == 0 || self.consumed > target_len || target_len > events.len() { + return Err(HistoryError::invariant("invalid history batch bounds")); + } + let remaining = target_len + .checked_sub(self.consumed) + .ok_or(HistoryError::invariant("invalid history remaining length"))?; + let count = if batch_size < remaining { + batch_size + } else { + remaining + }; + let end = self + .consumed + .checked_add(count) + .ok_or(HistoryError::invariant("invalid history batch end"))?; + proof! { + language::lemma_selected_end(self.consumed as nat, target_len as nat, batch_size as nat); + assert(end == language::selected_end(self.consumed as nat, target_len as nat, batch_size as nat)); + } + let suffix = events + .get(self.consumed..end) + .ok_or(HistoryError::invariant("invalid history batch slice"))?; + proof! { + assert(history_store::store::verify::events_view(suffix@) =~= history_store::store::verify::events_view(events@).subrange(self.consumed as int, end as int)); + } + let residual = pair.fold(self.residual, suffix, bindings, limits, world)?; + let answer = if end == target_len { + let answer = pair.answer(residual, limits, world)?; + proof! { + language::lemma_nullable_iff_nil(model::gsem(bindings@), model::lift_regex((*pair).store.graph(), residual@)); + assert(history_store::store::verify::events_view(suffix@) + Seq::::empty() =~= history_store::store::verify::events_view(suffix@)); + assert(model::regex_lang((*pair).store.graph(), bindings@, residual@, Seq::empty()) + == model::regex_lang((*pair).store.graph(), bindings@, entry_cursor.residual@, history_store::store::verify::events_view(suffix@))); + } + Some(answer) + } else { + None + }; + limits.publication_checkpoint()?; + proof! { + model::lemma_graph_wf_elim(entry.store.graph()); + model::lemma_lift_regex_stable(entry.store.graph(), (*pair).store.graph(), entry.root@); + history_algebra::lemma_batch_extends_pinned_prefix( + entry.store.graph(), (*pair).store.graph(), bindings@, + entry.root@, entry_cursor.residual@, residual@, history_store::store::verify::events_view(events@), + entry_cursor.consumed as nat, end as nat, + ); + } + // Commit the cursor last so every fallible operation leaves it unchanged. + self.consumed = end; + self.residual = residual; + Ok(answer) + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::indexing_slicing)] + + use super::*; + use alloc::vec; + use history_syntax::syntax::Component; + use junco_core::flat::{FlatHead, FlatPair, FlatRegex, FlatTerm, FlatTest}; + use junco_core::limits::Unmetered; + + fn runtime(regex: FlatRegex) -> RuleRuntime { + let store = HistoryStore::new(3); + let runtime = RuleRuntime::new( + &store, + &FlatPair { + head: vec![FlatHead::Any, FlatHead::Any, FlatHead::Any], + tests: Vec::new(), + regexes: vec![regex], + root: 0, + }, + false, + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + assert!(Arc::ptr_eq(runtime.store(), &store)); + runtime + } + + fn event(store: &HistoryStore) -> Event { + let principal = store + .intern( + Component(0), + b"alice", + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + let action = store + .intern(Component(1), b"edit", &mut Unmetered, &mut ObservationWorld) + .unwrap(); + let resource = store + .intern(Component(2), b"doc", &mut Unmetered, &mut ObservationWorld) + .unwrap(); + store.event(&[principal, action, resource]).unwrap() + } + + #[test] + fn compiled_pair_uses_send_dependencies() { + fn assert_send() {} + assert_send::(); + assert_send::(); + } + + #[test] + fn batch_cursor_ends_and_retained_prefix_are_exact() { + let store = HistoryStore::new(3); + let history = store + .new_history(&mut Unmetered, &mut ObservationWorld) + .unwrap(); + store + .append( + &history, + &[event(&store); 7], + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + let record = store.history_record(&history).unwrap(); + let stored = record.read(); + let mut runtime = runtime(FlatRegex::All); + let bindings = Bindings::new(&[0; 3]); + let mut cursor = runtime.root_cursor(); + for expected in [3, 6, 7] { + let answer = runtime + .advance_cursor( + &mut cursor, + &bindings, + &stored, + 7, + 3, + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + assert_eq!(answer, if expected == 7 { Some(true) } else { None }); + assert_eq!(cursor.consumed(), expected); + assert_eq!(runtime.cursors.entries()[0].consumed, expected); + } + let latest = runtime.cursors.entries()[0]; + runtime.publish(HistoryCursor { + consumed: 1, + residual: runtime.pair.root, + ..latest + }); + assert_eq!(runtime.cursors.entries()[0].consumed, 7); + assert_eq!(runtime.cursors.entries()[0].residual, latest.residual); + let warm = runtime.resume_cursor(&bindings, &stored, 7); + assert_eq!(warm.consumed(), 7); + } + + #[test] + fn failed_batch_and_final_answer_never_publish() { + let mut empty = runtime(FlatRegex::Epsilon); + let mut cursor = empty.root_cursor(); + let before = cursor; + let error = cursor + .advance( + &mut empty.pair, + &[], + &Bindings::new(&[0; 3]), + 1, + 3, + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap_err(); + assert!(matches!(error, HistoryError::Invariant { .. })); + assert_eq!(cursor.consumed, before.consumed); + assert_eq!(cursor.residual, before.residual); + assert!(empty.cursors.entries().is_empty()); + + let store = HistoryStore::new(3); + let history = store + .new_history(&mut Unmetered, &mut ObservationWorld) + .unwrap(); + store + .append( + &history, + &[event(&store); 2], + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + let record = store.history_record(&history).unwrap(); + let stored = record.read(); + let bindings = Bindings::new(&[0; 3]); + let mut runtime = runtime(FlatRegex::All); + let mut cursor = runtime.root_cursor(); + assert_eq!( + runtime + .advance_cursor( + &mut cursor, + &bindings, + &stored, + 2, + 1, + &mut Unmetered, + &mut ObservationWorld + ) + .unwrap(), + None + ); + let entry = cursor; + let retained = runtime.cursors.entries()[0]; + runtime.set_answer_checkpoint_failure(true); + assert!(matches!( + runtime.advance_cursor( + &mut cursor, + &bindings, + &stored, + 2, + 1, + &mut Unmetered, + &mut ObservationWorld + ), + Err(HistoryError::Limit(_)) + )); + assert_eq!(cursor.consumed, entry.consumed); + assert_eq!(cursor.residual, entry.residual); + assert_eq!(runtime.cursors.entries()[0].consumed, retained.consumed); + assert_eq!(runtime.cursors.entries()[0].residual, retained.residual); + runtime.set_answer_checkpoint_failure(false); + assert_eq!( + runtime + .advance_cursor( + &mut cursor, + &bindings, + &stored, + 2, + 1, + &mut Unmetered, + &mut ObservationWorld + ) + .unwrap(), + Some(true) + ); + assert_eq!(runtime.cursors.entries()[0].consumed, 2); + } + + #[test] + fn publication_failure_preserves_cursor_and_retained_prefix() { + struct FailPublication; + impl Limits for FailPublication { + fn checkpoint(&mut self) -> Result<(), junco_core::limits::LimitError> { + Ok(()) + } + fn enforce_memory(&mut self) -> Result<(), junco_core::limits::LimitError> { + Ok(()) + } + fn publication_checkpoint(&mut self) -> Result<(), junco_core::limits::LimitError> { + Err(junco_core::limits::LimitError::MemoryLimitExceeded { usage: 1, limit: 0 }) + } + } + let store = HistoryStore::new(3); + let history = store + .new_history(&mut Unmetered, &mut ObservationWorld) + .unwrap(); + let record = store.history_record(&history).unwrap(); + let stored = record.read(); + let mut runtime = runtime(FlatRegex::All); + let mut cursor = runtime.root_cursor(); + let entry = cursor; + assert!(matches!( + runtime.advance_cursor( + &mut cursor, + &Bindings::new(&[0; 3]), + &stored, + 0, + 1, + &mut FailPublication, + &mut ObservationWorld + ), + Err(HistoryError::Limit(_)) + )); + assert_eq!(cursor.consumed, entry.consumed); + assert_eq!(cursor.residual, entry.residual); + assert!(runtime.cursors.entries().is_empty()); + } + + #[test] + fn retained_cursor_lru_is_bounded_and_keeps_recent_histories() { + let store = HistoryStore::new(3); + let mut runtime = runtime(FlatRegex::All); + let mut keys = Vec::new(); + for _ in 0..17 { + let history = store + .new_history(&mut Unmetered, &mut ObservationWorld) + .unwrap(); + let record = store.history_record(&history).unwrap(); + let stored = record.read(); + assert_eq!(stored.id(), history.index()); + keys.push(history.index()); + let mut cursor = runtime.root_cursor(); + assert_eq!( + runtime + .advance_cursor( + &mut cursor, + &Bindings::new(&[0; 3]), + &stored, + 0, + 3, + &mut Unmetered, + &mut ObservationWorld + ) + .unwrap(), + Some(true) + ); + } + assert_eq!(runtime.cursors.entries().len(), 16); + assert_eq!(runtime.cursors.entries()[0].history, keys[16]); + assert_eq!(runtime.cursors.entries()[15].history, keys[1]); + assert!( + runtime + .cursors + .entries() + .iter() + .all(|cursor| cursor.bindings == Bindings::new(&[0; 3])) + ); + } + + #[test] + fn equal_shape_records_never_share_residuals() { + let store = HistoryStore::new(3); + let event = |action: &str| { + let principal = store + .intern( + Component(0), + b"alice", + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + let action = store + .intern( + Component(1), + action.as_bytes(), + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + let resource = store + .intern(Component(2), b"doc", &mut Unmetered, &mut ObservationWorld) + .unwrap(); + store.event(&[principal, action, resource]).unwrap() + }; + let read = event("read"); + let mut runtime = RuleRuntime::new( + &store, + &FlatPair { + head: vec![FlatHead::Any, FlatHead::Any, FlatHead::Any], + tests: vec![FlatTest::Atom { + field: Component(1), + term: FlatTerm::Constant(read.component(1)), + positive: true, + }], + regexes: vec![FlatRegex::Test(0), FlatRegex::Star(0)], + root: 1, + }, + false, + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + let mut histories = Vec::new(); + for (event, expected) in [(read, true), (event("edit"), false)] { + let history = store + .new_history(&mut Unmetered, &mut ObservationWorld) + .unwrap(); + store + .append(&history, &[event], &mut Unmetered, &mut ObservationWorld) + .unwrap(); + histories.push((history, expected)); + } + assert_ne!(histories[0].0.index(), histories[1].0.index()); + let bindings = Bindings::new(&[0; 3]); + // Cold then warm, in both orders: same length, revision and bindings, distinct keys. + for order in [[0, 1], [1, 0], [0, 1], [1, 0]] { + for index in order { + let (history, expected) = &histories[index]; + let record = store.history_record(history).unwrap(); + let stored = record.read(); + let mut cursor = runtime.resume_cursor(&bindings, &stored, 1); + let answer = runtime + .advance_cursor( + &mut cursor, + &bindings, + &stored, + 1, + 1, + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + assert_eq!(answer, Some(*expected)); + } + } + assert_eq!(runtime.cursors.entries().len(), 2); + } +} diff --git a/src/history-semantics/src/spec/mod.rs b/src/history-semantics/src/spec/mod.rs new file mode 100644 index 000000000..e1046b3f2 --- /dev/null +++ b/src/history-semantics/src/spec/mod.rs @@ -0,0 +1,3 @@ +//! Reviewer-facing specification of this crate: what the monitor (`Validator`) guarantees. + +pub mod monitor; diff --git a/src/history-semantics/src/spec/monitor.rs b/src/history-semantics/src/spec/monitor.rs new file mode 100644 index 000000000..924be0c82 --- /dev/null +++ b/src/history-semantics/src/spec/monitor.rs @@ -0,0 +1,82 @@ +//! The monitor's guarantees (Theorem `thm:matcher` at the level of `Validator`). +//! +//! A `Validator` is read through `ValidatorView`: the rules passed to `add_rule`, in order, and +//! the committed history (oldest first). `check_step` is the meaning of one `check` against the +//! state before it, `check_frame` what it does to the state; `trace_safe` is the invariant they +//! preserve. All three are stated with the semantics' (`junco_core::spec::semantics`) `policy_permits` and `least_violation` over events. +//! The guarantee is conditional on the hypotheses' (`junco_core::spec::hypotheses`) `event_obligations::()` where the contracts say so: +//! the compiled rules' hash containers are trusted only for faithful keys. + +use crate::validator::Decision; +use history_syntax::Event; +use history_syntax::spec::events::RuleView; +use junco_core::HistoryError; +use junco_core::event::Request; +use junco_core::spec::semantics::{least_violation, policy_permits, resource_error}; +use vstd::prelude::*; + +verus! { + +/// What a reviewer needs of a `Validator`: the rules passed to `add_rule`, in order, and the +/// committed history (oldest first). +pub struct ValidatorView { + pub rules: Seq>, + pub history: Seq, +} + +/// Frame of one `check`: rules unchanged; a grant appends exactly the candidate; a denial or an +/// error leaves the history as it was. +pub open spec fn check_frame( + before: ValidatorView, after: ValidatorView, request: Request, + result: Result, HistoryError>, +) -> bool { + after.rules == before.rules && match result { + Ok(Decision::Grant(grant)) => grant.event == request.event && grant.metadata == request.metadata + && after.history == before.history.push(request.event), + Ok(Decision::Denied(denial)) => denial.event == request.event && after.history == before.history, + Err(_) => after.history == before.history, + } +} + +/// Meaning of one `check` against the state before it (`thm:matcher`): Grant iff no rule is +/// violated; Denied identifies the least violated rule and its mode; errors are operational resource failures. +pub open spec fn check_step( + before: ValidatorView, request: Request, result: Result, HistoryError>, +) -> bool { + match result { + Ok(Decision::Grant(_)) => policy_permits(before.rules, request.event, before.history), + Ok(Decision::Denied(denial)) => + least_violation(before.rules, request.event, before.history, denial.index as int) + && denial.mode == before.rules[denial.index as int].mode, + Err(error) => resource_error(error), + } +} + +/// Meaning of `permits`: the answer is whether the policy permits the candidate after the +/// committed history, without committing anything. +pub open spec fn permits_result( + v: ValidatorView, candidate: E, result: Result, +) -> bool { + match result { + Ok(permitted) => permitted == policy_permits(v.rules, candidate, v.history), + Err(error) => resource_error(error), + } +} + +/// `rollback` only truncates to a prefix; on error nothing changes. +pub open spec fn rollback_step( + before: ValidatorView, after: ValidatorView, result: Result<(), HistoryError>, +) -> bool { + after.rules == before.rules && match result { + Ok(()) => after.history.is_prefix_of(before.history), + Err(_) => after.history == before.history, + } +} + +/// Trace safety: every committed event was permitted by every rule against its prefix. +pub open spec fn trace_safe(v: ValidatorView) -> bool { + forall|j: int| 0 <= j < v.history.len() + ==> policy_permits(v.rules, #[trigger] v.history[j], v.history.take(j)) +} + +} // verus! diff --git a/src/history-semantics/src/symbolic.rs b/src/history-semantics/src/symbolic.rs new file mode 100644 index 000000000..e3fedd960 --- /dev/null +++ b/src/history-semantics/src/symbolic.rs @@ -0,0 +1,5324 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +//! Exact numeric symbolic derivatives and iterative transition-DAG interpretation. +//! Existing ID extension traits own cache lookup and branch execution; finish tasks +//! precede reverse child scheduling so each LIFO traversal preserves source order. +//! Error provenance is conditional on store capabilities; finishing tasks require completed dependencies. + +use crate::WorkVec; +#[cfg(verus_keep_ghost)] +use crate::normalize::verify as norm; +use crate::normalize::{RegexNormalize, TransitionNormalize}; +#[cfg(verus_keep_ghost)] +use crate::progress::verify as reach; +#[cfg(verus_keep_ghost)] +use crate::verify::finite_deriv as fder; +#[cfg(verus_keep_ghost)] +use crate::verify::finite_interp as fint; +#[cfg(verus_keep_ghost)] +use crate::verify::finite_trans as ftr; +#[cfg(verus_keep_ghost)] +use crate::verify::history_algebra as algebra; +#[cfg(verus_keep_ghost)] +use alloc::boxed::Box; +use alloc::vec::Vec; +use junco_core::bits::checked_shr; +use junco_core::errors::HistoryError; +#[cfg(verus_keep_ghost)] +use junco_core::kernel::verify as model; +use junco_core::kernel::*; +#[cfg(verus_keep_ghost)] +use junco_core::observation::SmallVecSpecFns; +#[cfg(verus_keep_ghost)] +use junco_core::spec::semantics::resource_error; +#[cfg(verus_keep_ghost)] +use junco_core::verify::history_assumptions::KernelStoreSpec; +#[cfg(verus_keep_ghost)] +use junco_core::verify::history_specs as language; +#[cfg(verus_keep_ghost)] +use junco_core::verify::history_specs::{EventView, Subst}; +use junco_core::{loop_try, scan}; +#[cfg(verus_keep_ghost)] +use verify::*; +use vstd::prelude::*; +#[cfg(verus_keep_ghost)] +verus! { +broadcast use junco_core::kernel::verify::group_kernel_views; +} + +#[verus_verify] +#[verus_spec(result => ensures language::no_invariant_failure(result), !(result matches Err(HistoryError::InvalidPolicy { .. })), + result matches Err(error) ==> resource_error(error), + match result { + Ok(bytes) => bytes as int == count * vstd::layout::size_of::>(), + Err(error) => error is AllocationFailed && count * vstd::layout::size_of::>() > usize::MAX, + })] +fn derivative_cache_bytes(count: usize) -> KernelResult { + vstd::layout::layout_for_type_is_valid::>(); + match count.checked_mul(core::mem::size_of::>()) { + Some(bytes) => Ok(bytes), + None => Err(HistoryError::AllocationFailed), + } +} + +#[cfg(test)] +#[test] +fn derivative_cache_byte_overflow_is_allocation_failure() { + let width = core::mem::size_of::>(); + assert!(width > 1); + let largest = usize::MAX / width; + assert_eq!(derivative_cache_bytes(largest), Ok(largest * width)); + assert_eq!( + derivative_cache_bytes(largest + 1), + Err(HistoryError::AllocationFailed) + ); +} + +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy)] +struct DerivativeFactors { + root: RegexId, + count: usize, + concat: bool, +} +impl DerivativeFactors { + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(store.graph()), derivative_factors_wf(store.graph(), self.root, self.count as nat, self.concat), + derivative_tasks_wf(store.graph(), old(tasks).view()), + ensures derivative_tasks_wf(store.graph(), final(tasks).view()), + store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> language::no_invariant_failure(result), + store.errors_are_resource() && store.valid_store() ==> (result matches Err(error) ==> resource_error(error)), + store.errors_are_non_invalid_policy() && store.valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(tasks).view().is_prefix_of(final(tasks).view()), + final(tasks).view().len() <= old(tasks).view().len() + self.count, + result is Ok && !self.concat ==> final(tasks).view().len() == old(tasks).view().len() + self.count, + result is Ok ==> forall|i: nat| i < self.count && (!self.concat || #[trigger] derivative_prefix(store.graph(), self.root, i)) + ==> old(tasks).view().len() + i < final(tasks).view().len(), + forall|j: int| #![trigger final(tasks).view()[j]] old(tasks).view().len() <= j < final(tasks).view().len() ==> final(tasks).view()[j].0@ + == derivative_children_ids(store.graph(), self.root)[j - old(tasks).view().len()] && !final(tasks).view()[j].1, + )] + fn schedule( + self, + store: &G, + tasks: &mut WorkVec<(RegexId, bool)>, + ) -> KernelResult<()> { + proof! { model::lemma_graph_regex_wf(store.graph(), self.root@); } + let mut prefix = true; + let mut failure = None; + let mut i = 0; + proof_decl! { let ghost start = tasks.view(); } + #[cfg_attr(verus_keep_ghost, verus_spec(invariant i <= self.count, derivative_tasks_wf(store.graph(), tasks.view()), + model::graph_wf(store.graph()), derivative_factors_wf(store.graph(), self.root, self.count as nat, self.concat), + store.errors_are_non_owner() ==> failure != Some(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> (failure matches Some(error) ==> language::no_invariant_failure::<()>(Err(error))), + store.errors_are_resource() && store.valid_store() ==> (failure matches Some(error) ==> resource_error(error)), + store.errors_are_non_invalid_policy() && store.valid_store() ==> !(failure matches Some(HistoryError::InvalidPolicy { .. })), + model::regex_node_wf_at(store.graph(), store.graph().regexes[self.root@ as int], self.root@), + prefix == derivative_prefix(store.graph(), self.root, i as nat), + start == old(tasks).view(), start.is_prefix_of(tasks.view()), + tasks.view().len() <= start.len() + self.count, + forall|j: int| #![trigger tasks.view()[j]] start.len() <= j < tasks.view().len() ==> tasks.view()[j].0@ + == derivative_children_ids(store.graph(), self.root)[j - start.len()] && !tasks.view()[j].1, + forall|j: nat| j < i && (!self.concat || #[trigger] derivative_prefix(store.graph(), self.root, j)) + ==> start.len() + j < tasks.view().len(), + invariant_except_break failure is None, tasks.view().len() <= start.len() + i, + (!self.concat || prefix) ==> tasks.view().len() == start.len() + i, + ensures failure is None ==> i == self.count + && tasks.view().len() <= start.len() + self.count, + failure is None && !self.concat ==> tasks.view().len() == start.len() + self.count, + failure is None ==> forall|j: nat| j < self.count + && (!self.concat || #[trigger] derivative_prefix(store.graph(), self.root, j)) + ==> start.len() + j < tasks.view().len(), + decreases self.count - i))] + while i < self.count { + let child = loop_try!(self.root.child(store, i), failure); + proof_decl! { let ghost prior = tasks.view(); } + if !self.concat || prefix { + tasks.push((child, false)); + } + proof! { + assert forall|j: int| #![trigger tasks.view()[j]] start.len() <= j < tasks.view().len() implies tasks.view()[j].0@ + == derivative_children_ids(store.graph(), self.root)[j - start.len()] && !tasks.view()[j].1 by { + if j < prior.len() { assert(tasks.view()[j] == prior[j]); } else { + assert(j == start.len() + i); + assert(child@ == derivative_children_ids(store.graph(), self.root)[i as int]); + } + } + } + let n = loop_try!(RegexId::nullable(child, store), failure); + prefix &= n; + i = i.saturating_add(1); + } + if let Some(error) = failure { + return Err(error); + } + proof! { + assert(start == old(tasks).view()); + assert(i == self.count); + if !self.concat { assert(tasks.view().len() == start.len() + self.count); } + assert forall|j: nat| j < self.count + && (!self.concat || #[trigger] derivative_prefix(store.graph(), self.root, j)) + implies old(tasks).view().len() + j < tasks.view().len() by {} + } + Ok(()) + } + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(store.graph()), start <= self.count, + self.root@ < store.graph().regexes.len(), self.count == derivative_children_ids(store.graph(), self.root).len(), + ensures store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> language::no_invariant_failure(result), + store.errors_are_resource() && store.valid_store() ==> (result matches Err(error) ==> resource_error(error)), + store.errors_are_non_invalid_policy() && store.valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + match result { Ok(suffix) => + norm::regex_ids_valid(store.graph(), suffix.view()) + && model::regex_ids(suffix.view()) == derivative_children_ids(store.graph(), self.root).subrange(start as int, self.count as int), + Err(_) => true }, + )] + fn suffix(self, store: &G, start: usize) -> KernelResult> { + proof! { model::lemma_graph_regex_wf(store.graph(), self.root@); } + let mut suffix = WorkVec::new(); + let mut failure = None; + let mut i = start; + #[cfg_attr(verus_keep_ghost, verus_spec(invariant start <= i <= self.count, + model::graph_wf(store.graph()), self.root@ < store.graph().regexes.len(), + store.errors_are_non_owner() ==> failure != Some(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> (failure matches Some(error) ==> language::no_invariant_failure::<()>(Err(error))), + store.errors_are_resource() && store.valid_store() ==> (failure matches Some(error) ==> resource_error(error)), + store.errors_are_non_invalid_policy() && store.valid_store() ==> !(failure matches Some(HistoryError::InvalidPolicy { .. })), + self.count == derivative_children_ids(store.graph(), self.root).len(), + model::regex_node_wf_at(store.graph(), store.graph().regexes[self.root@ as int], self.root@), + norm::regex_ids_valid(store.graph(), suffix.view()), + suffix.view().len() == i - start, + forall|j: int| 0 <= j < suffix.view().len() ==> suffix.view()[j]@ == derivative_children_ids(store.graph(), self.root)[start as int + j], + ensures failure.is_none() ==> i == self.count, decreases self.count - i))] + while i < self.count { + proof_decl! { let ghost prior_suffix = suffix.view(); } + let child = loop_try!(self.root.child(store, i), failure); + suffix.push(child); + proof! { + assert(child@ == derivative_children_ids(store.graph(), self.root)[i as int]); + assert(suffix.view() == prior_suffix.push(child)); + assert forall|j: int| 0 <= j < suffix.view().len() implies + model::regex_ids(suffix.view())[j] == derivative_children_ids(store.graph(), self.root)[start as int + j] by { + if j < prior_suffix.len() { + assert(suffix.view()[j] == prior_suffix[j]); + assert(prior_suffix[j]@ == derivative_children_ids(store.graph(), self.root)[start as int + j]); + } else { assert(suffix.view()[j] == child); assert(start + j == i); } + } + assert(model::regex_ids(suffix.view()) =~= derivative_children_ids(store.graph(), self.root).subrange(start as int, i as int + 1)); + } + i = i.saturating_add(1); + } + if let Some(error) = failure { + return Err(error); + } + proof! { + assert(model::regex_ids(suffix.view()) =~= derivative_children_ids(store.graph(), self.root).subrange(start as int, self.count as int)); + } + Ok(suffix) + } + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + derivative_cache_wf(old(store).graph(), cache@), + derivative_factors_wf(old(store).graph(), self.root, self.count as nat, self.concat), index < self.count, + derivative_results(old(store).graph(), self.root, self.concat, index as nat, old(results).view()), + prefix == derivative_prefix(old(store).graph(), self.root, index as nat), + fder::results_bound(old(store).graph(), self.root@, old(results).view()), + derivative_results_vocab(old(store).graph(), self.root@, old(results).view()), + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_invalid_policy() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_invariant() && derivative_dependencies_complete(old(store).graph(), self.root, cache@) ==> language::no_invariant_failure(result), + old(store).errors_are_resource() && old(store).valid_store() + && derivative_dependencies_complete(old(store).graph(), self.root, cache@) + ==> (result matches Err(error) ==> resource_error(error)), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + model::graph_wf(final(store).graph()), final(store).valid_store(), + derivative_cache_wf(final(store).graph(), cache@), + derivative_dependencies_complete(old(store).graph(), self.root, cache@) + == derivative_dependencies_complete(final(store).graph(), self.root, cache@), + match result { Ok(next) => next == derivative_prefix(final(store).graph(), self.root, index as nat + 1) + && derivative_results(final(store).graph(), self.root, self.concat, index as nat + 1, final(results).view()) + && fder::results_bound(final(store).graph(), self.root@, final(results).view()), Err(_) => true }, + result is Ok ==> derivative_results_vocab(final(store).graph(), self.root@, final(results).view()), + )] + fn child_step( + self, + store: &mut G, + cache: &[Option], + index: usize, + results: &mut WorkVec, + prefix: bool, + ) -> KernelResult { + proof_decl! { let ghost before = store.graph(); let ghost prior_results = results.view(); } + proof! { derivative_frame(store.graph()); model::lemma_graph_regex_wf(store.graph(), self.root@); } + proof! { derivative_dependency_frame(store.graph(), self.root); } + store.checkpoint()?; + let child = self.root.child(store, index)?; + if !self.concat || prefix { + proof! { + assert(derivative_children_ids(store.graph(), self.root)[index as int] == child@); + assert(derivative_dependency(store.graph(), self.root, child@)); + } + let d = RegexId::cached(cache, child)?; + proof! { + derivative_cached_bound(store.graph(), cache@, child, d); + lemma_regex_graph_child_vocab(store.graph(), self.root@, child@); + } + if self.concat { + let start = match index.checked_add(1) { + Some(v) => v, + None => return Err(HistoryError::symbolic_invariant()), + }; + let suffix = self.suffix(store, start)?; + proof_decl! { let ghost mid = store.graph(); } + results.push(TransitionId::append(d, store, &suffix)?); + proof! { + derivative_append_factor(store.graph(), self.root, index as int, d, suffix.view(), results.view().last()); + derivative_results_push(store.graph(), self.root, true, index as nat, prior_results, results.view().last()); + fder::lemma_factor_concat2(mid, store.graph(), self.root@, index as int, d@, suffix.view(), results.view().last()@); + fder::lemma_results_stable(before, store.graph(), self.root@, prior_results); + fder::lemma_results_push(store.graph(), self.root@, prior_results, results.view().last()); + lemma_derivative_vocab_stable(mid, store.graph(), child@, d@); + lemma_regex_graph_child_vocab(store.graph(), self.root@, child@); + norm::lemma_guard_definition(store.graph(), d@); + norm::lemma_guard_definition(store.graph(), results.view().last()@); + assert(derivative_vocab(store.graph(), self.root@, results.view().last()@)); + lemma_derivative_results_vocab_stable(before, store.graph(), self.root@, prior_results); + assert(derivative_results_vocab(store.graph(), self.root@, results.view())); + } + } else { + results.push(d); + proof! { + derivative_results_push(store.graph(), self.root, false, index as nat, prior_results, d); + fder::lemma_factor_set(store.graph(), self.root@, index as int, d@); + fder::lemma_results_stable(before, store.graph(), self.root@, prior_results); + fder::lemma_results_push(store.graph(), self.root@, prior_results, d); + assert(derivative_vocab(store.graph(), self.root@, d@)); + assert(derivative_results_vocab(store.graph(), self.root@, results.view())); + } + } + } + proof! { + if self.concat && !prefix { + derivative_results_skip(store.graph(), self.root, index as nat, results.view()); + fder::lemma_results_stable(before, store.graph(), self.root@, results.view()); + lemma_derivative_results_vocab_stable(before, store.graph(), self.root@, results.view()); + } + } + let n = RegexId::nullable(child, store)?; + Ok(prefix && n) + } + verus! { + #[verus_verify] + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + #[cfg_attr(verus_keep_ghost, verifier::rlimit(120))] + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + derivative_cache_wf(old(store).graph(), cache@), + derivative_factors_wf(old(store).graph(), self.root, self.count as nat, self.concat), + match old(store).graph().regexes[self.root@ as int].kind { + model::RegexKindNode::Union(_) => !self.concat && !intersect, + model::RegexKindNode::Intersect(_) => !self.concat && intersect, + model::RegexKindNode::Concat(_) => self.concat && !intersect, + _ => false, + }, + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_invalid_policy() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_invariant() && derivative_dependencies_complete(old(store).graph(), self.root, cache@) ==> language::no_invariant_failure(result), + old(store).errors_are_resource() && old(store).valid_store() + && derivative_dependencies_complete(old(store).graph(), self.root, cache@) + ==> (result matches Err(error) ==> resource_error(error)), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + model::graph_wf(final(store).graph()), final(store).valid_store(), + derivative_cache_wf(final(store).graph(), cache@), + match result { Ok(out) => derivative_correct(final(store).graph(), self.root@, out) + && fder::dbound(final(store).graph(), self.root@, out@) + && derivative_vocab(final(store).graph(), self.root@, out@), Err(_) => true }, + )] + fn derive( + self, + store: &mut G, + cache: &[Option], + intersect: bool, + ) -> KernelResult { + hide(Seq::<_>::no_duplicates); + hide(model::unique_nodes); + hide(model::tables_wf); + proof_decl! { let ghost entry = store.graph(); } + proof! { derivative_frame(store.graph()); fder::lemma_results_empty(store.graph(), self.root@); } + proof! { derivative_dependency_frame(entry, self.root); } + let mut results = WorkVec::new(); + let mut state = Ok(true); + scan!(state,index,self.count,state.is_ok(),prior=>self.child_step(store,cache,index,&mut results,prior); + invariant index <= self.count, model::graph_extends(entry, store.graph()), model::graph_wf(store.graph()), store.valid_store(), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_invalid_policy() ==> !(state matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_invariant() && derivative_dependencies_complete(entry, self.root, cache@) ==> language::no_invariant_failure(state), + old(store).errors_are_resource() && old(store).valid_store() + && derivative_dependencies_complete(entry, self.root, cache@) + ==> (state matches Err(error) ==> resource_error(error)), + old(store).errors_are_non_owner() ==> state != Err(HistoryError::WrongHistoryOwner), + model::graph_wf(entry), self.root@ < entry.regexes.len(), + derivative_cache_wf(store.graph(), cache@), derivative_factors_wf(store.graph(), self.root, self.count as nat, self.concat), + store.graph().regexes[self.root@ as int] == entry.regexes[self.root@ as int], + derivative_dependencies_complete(entry, self.root, cache@) == derivative_dependencies_complete(store.graph(), self.root, cache@), + match state { Ok(prefix) => prefix == derivative_prefix(store.graph(), self.root, index as nat) + && derivative_results(store.graph(), self.root, self.concat, index as nat, results.view()) + && fder::results_bound(store.graph(), self.root@, results.view()), Err(_) => true }, + state is Ok ==> derivative_results_vocab(store.graph(), self.root@, results.view()), + decreases self.count - index); + state?; + proof! { + derivative_frame(store.graph()); + derivative_result_future(store.graph(), self.root, self.concat, intersect, results.view()); + fder::lemma_derive_future(store.graph(), self.root@, results.view(), intersect); + } + proof! { + assert forall|i: int| 0 <= i < results.view().len() implies norm::guard_vocab(store.graph(), results.view()[i]@).subset_of( + regex_primitives(model::lift_regex(store.graph(), self.root@))) by { + norm::lemma_guard_definition(store.graph(), results.view()[i]@); + } + norm::lemma_guard_union(store.graph(), model::transition_ids(results.view()), regex_primitives(model::lift_regex(store.graph(), self.root@))); + } + proof_decl! { let ghost before_collect = store.graph(); } + let out = if intersect { + TransitionId::intersect(store, &results) + } else { + TransitionId::collect(store, &results, false) + }?; + proof! { + model::lemma_graph_wf_elim(entry); + model::lemma_lift_regex_stable(entry, store.graph(), self.root@); + model::lemma_graph_wf_elim(before_collect); + model::lemma_lift_regex_stable(before_collect, store.graph(), self.root@); + norm::lemma_guard_task_stable(before_collect, store.graph(), + norm::ActionShape::Fold(model::transition_ids(results.view()), 0)); + norm::lemma_guard_subset(store.graph(), out@, regex_primitives(model::lift_regex(store.graph(), self.root@))); + } + Ok(out) + } + } + // `cache@` is specified as a `Vec` view; a slice parameter would change every caller's contract. + #[allow(clippy::ptr_arg)] + #[verus_verify] + #[verus_spec(result => + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + derivative_cache_wf(old(store).graph(), old(cache)@), derivative_tasks_wf(old(store).graph(), old(tasks).view()), + self.root@ < old(store).graph().regexes.len(), + match old(store).graph().regexes[self.root@ as int].kind { + model::RegexKindNode::Union(cs) => !self.concat && !intersect && cs.len() == self.count, + model::RegexKindNode::Intersect(cs) => !self.concat && intersect && cs.len() == self.count, + model::RegexKindNode::Concat(cs) => self.concat && !intersect && cs.len() == self.count, + _ => false, + }, + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_invalid_policy() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_invariant() && (!finish || derivative_dependencies_complete(old(store).graph(), self.root, old(cache)@)) ==> language::no_invariant_failure(result), + old(store).errors_are_resource() && old(store).valid_store() + && (!finish || derivative_dependencies_complete(old(store).graph(), self.root, old(cache)@)) + ==> (result matches Err(error) ==> resource_error(error)), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + model::graph_wf(final(store).graph()), final(store).valid_store(), final(cache)@ == old(cache)@, + derivative_cache_wf(final(store).graph(), final(cache)@), derivative_tasks_wf(final(store).graph(), final(tasks).view()), + match result { Ok(Some(out)) => derivative_correct(final(store).graph(), self.root@, out) + && out@ < final(store).graph().transitions.len() + && fder::dbound(final(store).graph(), self.root@, out@) + && derivative_vocab(final(store).graph(), self.root@, out@), _ => true }, + result matches Ok(Some(_)) ==> final(tasks).view() == old(tasks).view(), + old(tasks).view().is_prefix_of(final(tasks).view()), + forall|bound: nat| self.root@ <= bound && derivative_tasks_bounded(old(tasks).view(), bound) + ==> derivative_tasks_bounded(final(tasks).view(), bound), + result == Ok(None) ==> derivative_scheduled(old(store).graph(), self.root, old(tasks).view(), final(tasks).view()), + result is Ok ==> final(tasks).view() == old(tasks).view() + || (derivative_tasks_wf(old(store).graph(), final(tasks).view()) + && derivative_work(old(store).graph(), final(tasks).view()) + < derivative_work(old(store).graph(), old(tasks).view().push((self.root, finish)))), + )] + fn branch( + self, + store: &mut G, + cache: &mut Vec>, + intersect: bool, + finish: bool, + tasks: &mut WorkVec<(RegexId, bool)>, + ) -> KernelResult> { + proof! { derivative_frame(store.graph()); model::lemma_graph_regex_wf(store.graph(), self.root@); } + if finish { + Ok(Some(self.derive(store, cache, intersect)?)) + } else { + tasks.push((self.root, true)); + proof_decl! { let ghost scheduled_from = tasks.view(); } + proof! { assert(scheduled_from == old(tasks).view().push((self.root, true))); } + let scheduled = self.schedule(store, tasks); + proof! { + broadcast use vstd::seq::group_seq_lemmas; + assert(scheduled_from.is_prefix_of(tasks.view())); + assert forall|j: int| 0 <= j < scheduled_from.len() + implies tasks.view()[j] == scheduled_from[j] by {} + assert forall|bound: nat| self.root@ <= bound && derivative_tasks_bounded(old(tasks).view(), bound) + implies derivative_tasks_bounded(tasks.view(), bound) by { + assert forall|j: int| 0 <= j < tasks.view().len() implies tasks.view()[j].0@ <= bound by { + if j < old(tasks).view().len() { + assert(scheduled_from[j] == old(tasks).view()[j]); + assert(tasks.view()[j] == scheduled_from[j]); + assert(tasks.view()[j] == old(tasks).view()[j]); + } else if j == old(tasks).view().len() { + assert(scheduled_from[j] == (self.root, true)); + assert(tasks.view()[j] == scheduled_from[j]); + assert(tasks.view()[j].0 == self.root); + } else { + let i = j - old(tasks).view().len() - 1; + assert(0 <= i < self.count); + assert(i < derivative_children_ids(store.graph(), self.root).len()); + assert(tasks.view()[j].0@ == derivative_children_ids(store.graph(), self.root)[i]); + } + } + } + } + scheduled?; + proof! { + broadcast use vstd::seq::group_seq_lemmas; + derivative_lemma_work_branch(store.graph(), self.root, old(tasks).view(), tasks.view()); + assert(old(tasks).view() =~= tasks.view().take(old(tasks).view().len() as int)); + assert(scheduled_from[old(tasks).view().len() as int] == (self.root, true)); + assert(tasks.view()[old(tasks).view().len() as int] + == scheduled_from[old(tasks).view().len() as int]); + assert(tasks.view()[old(tasks).view().len() as int] == (self.root, true)); + assert forall|i: int| old(tasks).view().len() < i < tasks.view().len() + implies !tasks.view()[i].1 by {} + assert forall|child: nat| derivative_dependency(store.graph(), self.root, child) + implies exists|j: int| old(tasks).view().len() < j < tasks.view().len() && tasks.view()[j].0@ == child by { + let i = choose|i: int| 0 <= i < self.count && derivative_children_ids(store.graph(), self.root)[i] == child + && (!self.concat || derivative_prefix(store.graph(), self.root, i as nat)); + let j = old(tasks).view().len() + 1 + i; + if self.concat { + assert(derivative_prefix(store.graph(), self.root, i as nat)); + assert(scheduled_from.len() + (i as nat) < tasks.view().len()); + } else { + assert(tasks.view().len() == scheduled_from.len() + self.count); + } + assert(scheduled_from.len() + i < tasks.view().len()); + assert(tasks.view()[j].0@ == derivative_children_ids(store.graph(), self.root)[i]); + assert(tasks.view()[j].0@ == child); + } + } + Ok(None) + } + } +} +verus! { +pub(crate) trait RegexDerivative: Sized { + fn cached(cache: &[Option], id: RegexId) -> (result: KernelResult) + ensures match result { + Ok(out) => id@ < cache@.len() && cache@[id@ as int] == Some(out), Err(_) => true, + }, + result != Err(HistoryError::WrongHistoryOwner), + cache_complete(cache@, id@) ==> language::no_invariant_failure(result), + cache_complete(cache@, id@) ==> (result matches Err(error) ==> resource_error(error)), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + { + match cache.get(id.index()?) { + Some(Some(value)) => Ok(*value), + _ => Err(HistoryError::symbolic_invariant()), + } + } + + fn derivative_step( + this: RegexId, + store: &mut G, + cache: &mut Vec>, + finish: bool, + tasks: &mut WorkVec<(RegexId, bool)>, + ) -> (result: KernelResult<()>) + requires model::graph_wf(old(store).graph()), old(store).valid_store(), this@ < old(store).graph().regexes.len(), + derivative_cache_wf(old(store).graph(), old(cache)@), derivative_tasks_wf(old(store).graph(), old(tasks).view()), + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_invalid_policy() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_invariant() && this@ < usize::MAX && (!finish || derivative_dependencies_complete(old(store).graph(), this, old(cache)@)) ==> language::no_invariant_failure(result), + old(store).errors_are_resource() && old(store).valid_store() && this@ < usize::MAX + && (!finish || derivative_dependencies_complete(old(store).graph(), this, old(cache)@)) + ==> (result matches Err(error) ==> resource_error(error)), + cache_completions_preserved(old(cache)@, final(cache)@), + old(cache)@.len() <= final(cache)@.len(), + forall|i: int| #![trigger final(cache)@[i]] + 0 <= i < old(cache)@.len() && old(cache)@[i] is Some + ==> i < final(cache)@.len() && final(cache)@[i] == old(cache)@[i], + old(tasks).view().is_prefix_of(final(tasks).view()), + forall|bound: nat| this@ <= bound && derivative_tasks_bounded(old(tasks).view(), bound) + ==> derivative_tasks_bounded(final(tasks).view(), bound), + result is Ok ==> cache_complete(final(cache)@, this@) || tasks_contain(final(tasks).view(), this@), + derivative_tasks_ready(old(store).graph(), old(tasks).view().push((this, finish)), old(cache)@) && result is Ok + ==> derivative_tasks_ready(final(store).graph(), final(tasks).view(), final(cache)@), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + model::graph_wf(final(store).graph()), final(store).valid_store(), + derivative_cache_wf(final(store).graph(), final(cache)@), derivative_tasks_wf(final(store).graph(), final(tasks).view()), + result is Ok ==> derivative_work(final(store).graph(), final(tasks).view()) + < derivative_work(old(store).graph(), old(tasks).view().push((this, finish))); + + fn derivative( + this: RegexId, + store: &mut G, + cache: &mut Vec>, + ) -> (result: KernelResult) + requires model::graph_wf(old(store).graph()), old(store).valid_store(), this@ < old(store).graph().regexes.len(), + derivative_cache_wf(old(store).graph(), old(cache)@), + ensures model::graph_extends(old(store).graph(), final(store).graph()), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_invalid_policy() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_invariant() && this@ < usize::MAX ==> language::no_invariant_failure(result), + old(store).errors_are_resource() && old(store).valid_store() && this@ < usize::MAX + ==> (result matches Err(error) ==> resource_error(error)), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + model::graph_wf(final(store).graph()), final(store).valid_store(), + derivative_cache_wf(final(store).graph(), final(cache)@), + old(cache)@.len() <= final(cache)@.len(), + forall|i: int| #![trigger final(cache)@[i]] + 0 <= i < old(cache)@.len() && old(cache)@[i] is Some + ==> i < final(cache)@.len() && final(cache)@[i] == old(cache)@[i], + result matches Ok(out) ==> this@ < final(cache)@.len() && final(cache)@[this@ as int] == Some(out), + match result { Ok(out) => derivative_correct(final(store).graph(), this@, out) + && fder::dbound(final(store).graph(), this@, out@), Err(_) => true }; +} +} + +verus! { +fn grow_derivative_cache( + this: RegexId, store: &mut G, cache: &mut Vec>, +) -> (result: KernelResult<()>) + requires model::graph_wf(old(store).graph()), old(store).valid_store(), + derivative_cache_wf(old(store).graph(), old(cache)@), + ensures final(store).graph() == old(store).graph(), final(store).valid_store(), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invalid_policy() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_invariant() && this@ < usize::MAX ==> language::no_invariant_failure(result), + old(store).errors_are_resource() && old(store).valid_store() && this@ < usize::MAX + ==> (result matches Err(error) ==> resource_error(error)), + derivative_cache_wf(final(store).graph(), final(cache)@), + old(cache)@.is_prefix_of(final(cache)@), + forall|i: int| 0 <= i < old(cache)@.len() ==> final(cache)@[i] == old(cache)@[i], + forall|i: int| old(cache)@.len() <= i < final(cache)@.len() ==> final(cache)@[i] is None, + result is Err ==> final(cache)@ == old(cache)@, + result is Ok ==> this@ < final(cache)@.len() + && final(cache)@.len() == if old(cache)@.len() > this@ { old(cache)@.len() } else { this@ + 1 }, +{ + hide(derivative_cache_wf); hide(derivative_correct); + let ghost before = cache@; + store.checkpoint()?; + let required = match this.index()?.checked_add(1) { + Some(value) => value, + None => return Err(HistoryError::symbolic_invariant()), + }; + if required > cache.len() { + let extra = match required.checked_sub(cache.len()) { + Some(value) => value, + None => return Err(HistoryError::symbolic_invariant()), + }; + let bytes = derivative_cache_bytes(extra)?; + store.reserve_derivatives(cache, extra)?; + store.charge_aux(bytes)?; + cache.resize(required, None); + } + proof { + derivative_cache_prefix_facts(before, cache@); + reveal(derivative_cache_wf); + assert forall|i: int| 0 <= i < cache@.len() implies match #[trigger] cache@[i] { + Some(out) => derivative_correct(store.graph(), i as nat, out) && fder::dbound(store.graph(), i as nat, out@) + && derivative_vocab(store.graph(), i as nat, out@), None => true, + } by { + if i < before.len() { assert(cache@[i] == before[i]); } + else { assert(cache@[i] is None); } + } + } + Ok(()) +} + +impl RegexDerivative for RegexId { + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + #[cfg_attr(verus_keep_ghost, verifier::rlimit(160))] + fn derivative_step( + this: RegexId, + store: &mut G, + cache: &mut Vec>, + finish: bool, + tasks: &mut WorkVec<(RegexId, bool)>, + ) -> KernelResult<()> { + hide(Seq::<_>::no_duplicates); + hide(resource_error); + hide(derivative_cache_wf); hide(derivative_tasks_wf); + hide(derivative_correct); + hide(derivative_tasks_ready); hide(derivative_scheduled); + hide(derivative_dependencies_complete); hide(derivative_dependency); + hide(vstd::seq::lemma_seq_subrange_index); + hide(vstd::seq::lemma_seq_two_subranges_index); + proof_decl! { let ghost before = store.graph(); let ghost prior_tasks = tasks.view(); } + proof! { + assert forall|i: int| 0 <= i < prior_tasks.len() implies prior_tasks.subrange(0, prior_tasks.len() as int)[i] == prior_tasks[i] by { + vstd::seq::lemma_seq_subrange_index(prior_tasks, 0, prior_tasks.len() as int, i); + } + assert(prior_tasks =~= prior_tasks.subrange(0, prior_tasks.len() as int)); + assert(prior_tasks.is_prefix_of(prior_tasks)); + } + proof! { norm::graph_lemma_extends_refl(store.graph()); } + proof! { + derivative_frame(store.graph()); model::lemma_graph_regex_wf(store.graph(), this@); derivative_constants(store.graph()); + } + proof_decl! { let ghost cache_before = cache@; let ghost growth_graph = store.graph(); } + grow_derivative_cache(this, store, cache)?; + proof! { + if derivative_dependencies_complete(before, this, cache_before) { + derivative_cache_extend_dependencies(before, this, cache_before, cache@); + } + } + let index = this.index()?; + let pending = match cache.get(index) { + Some(None) => true, + Some(Some(_)) => false, + None => return Err(HistoryError::symbolic_invariant()), + }; + if pending { + let c = store.constants(); + proof! { + fder::lemma_native_future(store.graph(), this, cache@); + } + let out = match this.head(store)? { + RegexHead::Empty | RegexHead::Epsilon => { + proof! { + norm::lemma_guard_constants(store.graph()); + norm::lemma_guard_definition(store.graph(), c.transition_empty@); + assert(derivative_vocab(store.graph(), this@, c.transition_empty@)); + } + proof! { derivative_native_correct(store.graph(), this, cache@, c.transition_empty); } + Some(c.transition_empty) + } + RegexHead::All => { + proof! { + norm::lemma_guard_constants(store.graph()); + norm::lemma_guard_definition(store.graph(), c.transition_all@); + assert(derivative_vocab(store.graph(), this@, c.transition_all@)); + } + proof! { derivative_native_correct(store.graph(), this, cache@, c.transition_all); } + Some(c.transition_all) + } + RegexHead::Test(test) => { + let out = TransitionId::if_then_else(store, test, c.transition_epsilon, c.transition_empty)?; + proof! { derivative_graph_frame(growth_graph, store.graph(), this); } + proof! { + norm::lemma_guard_constants(store.graph()); + norm::lemma_test_definition(store.graph(), test@); + norm::lemma_guard_definition(store.graph(), out@); + norm::regex_unfold(store.graph(), this@); + assert(derivative_vocab(store.graph(), this@, out@)); + } + proof! { derivative_test_correct(store.graph(), this, test, cache@, out, c.transition_epsilon, c.transition_empty); } + Some(out) + } + RegexHead::Star(inner) => { + if finish { + proof! { + if derivative_dependencies_complete(before, this, cache_before) { + derivative_unary_complete(before, this, inner, cache@); + } + } + let d = Self::cached(cache, inner)?; + proof_decl! { let ghost before_append = store.graph(); } + proof! { derivative_cached_bound(store.graph(), cache@, inner, d); } + let out = TransitionId::append(d, store, &[this])?; + proof! { derivative_graph_frame(growth_graph, store.graph(), this); } + proof! { + lemma_derivative_vocab_stable(before_append, store.graph(), inner@, d@); + lemma_regex_graph_child_vocab(store.graph(), this@, inner@); + norm::lemma_guard_definition(store.graph(), d@); + norm::lemma_guard_definition(store.graph(), out@); + assert(derivative_vocab(store.graph(), this@, out@)); + } + proof! { derivative_native_correct(store.graph(), this, cache@, out); } + Some(out) + } else { + tasks.push((this, true)); + proof! { derivative_unary_scheduled(before, this, prior_tasks, inner); } + tasks.push((inner, false)); + proof! { derivative_lemma_work_unary(store.graph(), this, prior_tasks, inner); } + None + } + } + RegexHead::Not(inner) => { + if finish { + proof! { + if derivative_dependencies_complete(before, this, cache_before) { + derivative_unary_complete(before, this, inner, cache@); + } + } + let d = Self::cached(cache, inner)?; + proof_decl! { let ghost before_not = store.graph(); } + proof! { derivative_cached_bound(store.graph(), cache@, inner, d); } + let out = TransitionId::not(d, store)?; + proof! { derivative_graph_frame(growth_graph, store.graph(), this); } + proof! { + lemma_derivative_vocab_stable(before_not, store.graph(), inner@, d@); + lemma_regex_graph_child_vocab(store.graph(), this@, inner@); + norm::lemma_guard_definition(store.graph(), d@); + norm::lemma_guard_definition(store.graph(), out@); + assert(derivative_vocab(store.graph(), this@, out@)); + } + proof! { derivative_native_correct(store.graph(), this, cache@, out); } + Some(out) + } else { + tasks.push((this, true)); + proof! { derivative_unary_scheduled(before, this, prior_tasks, inner); } + tasks.push((inner, false)); + proof! { derivative_lemma_work_unary(store.graph(), this, prior_tasks, inner); } + None + } + } + RegexHead::Union(n) => DerivativeFactors { + root: this, + count: n, + concat: false, + } + .branch(store, cache, false, finish, tasks)?, + RegexHead::Intersect(n) => DerivativeFactors { + root: this, + count: n, + concat: false, + } + .branch(store, cache, true, finish, tasks)?, + RegexHead::Concat(n) => DerivativeFactors { + root: this, + count: n, + concat: true, + } + .branch(store, cache, false, finish, tasks)?, + }; + if let Some(out) = out { + proof! { + assert(derivative_correct(store.graph(), this@, out)); + derivative_graph_frame(growth_graph, store.graph(), this); + match growth_graph.regexes[this@ as int].kind { + model::RegexKindNode::Star(inner) => { + assert(inner < cache@.len() && cache@[inner as int] is Some); + assert(vstd::array::spec_array_as_slice(&[this])@ =~= seq![this]); + assert(fder::native_bound(growth_graph, store.graph(), this, cache@, out@)); + }, + model::RegexKindNode::Not(inner) => { + assert(inner < cache@.len() && cache@[inner as int] is Some); + assert(fder::native_bound(growth_graph, store.graph(), this, cache@, out@)); + }, + model::RegexKindNode::Test(_) => { + assert(fder::native_bound(growth_graph, store.graph(), this, cache@, out@)); + }, + _ => { + assert(fder::native_bound(growth_graph, store.graph(), this, cache@, out@)); + }, + } + assert(fder::dbound(store.graph(), this@, out@)); + assert(derivative_vocab(store.graph(), this@, out@)); + } + let slots = cache.as_mut_slice(); + match slots.get_mut(index) { + Some(slot) => *slot = Some(out), + None => return Err(HistoryError::symbolic_invariant()), + } + proof! { + assert(derivative_cache_wf(store.graph(), cache@)) by { + reveal(derivative_cache_wf); + assert forall|i: int| 0 <= i < cache@.len() implies match #[trigger] cache@[i] { + Some(t) => derivative_correct(store.graph(), i as nat, t) && fder::dbound(store.graph(), i as nat, t@) + && derivative_vocab(store.graph(), i as nat, t@), None => true, + } by { if i == index { assert(cache@[i] == Some(out)); } } + } + } + } + } + proof! { + derivative_lemma_step_post(before, store.graph(), this, finish, prior_tasks, tasks.view()); + assert(cache_completions_preserved(cache_before, cache@)); + assert forall|i: int| #![trigger cache@[i]] + 0 <= i < cache_before.len() && cache_before[i] is Some implies + i < cache@.len() && cache@[i] == cache_before[i] by {} + assert(tasks.view() == prior_tasks && cache_complete(cache@, this@) || derivative_scheduled(before, this, prior_tasks, tasks.view())); + if derivative_scheduled(before, this, prior_tasks, tasks.view()) { + derivative_scheduled_facts(before, this, prior_tasks, tasks.view()); + } + if derivative_tasks_ready(before, prior_tasks.push((this, finish)), cache_before) { + derivative_ready_after_step(before, store.graph(), this, finish, prior_tasks, tasks.view(), cache_before, cache@); + } + } + Ok(()) + } + + fn derivative( + this: RegexId, + store: &mut G, + cache: &mut Vec>, + ) -> KernelResult { + proof_decl! { let ghost entry = store.graph(); } + let mut tasks = WorkVec::new(); + tasks.push((this, false)); + let mut state = Ok(()); + proof! { assert(tasks.view()[0].0 == this); assert(tasks_contain(tasks.view(), this@)); } + #[cfg_attr(verus_keep_ghost, verus_spec(invariant model::graph_extends(entry, store.graph()), model::graph_wf(entry), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_invalid_policy() ==> !(state matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_invariant() && this@ < usize::MAX ==> language::no_invariant_failure(state), + old(store).errors_are_resource() && old(store).valid_store() && this@ < usize::MAX + ==> (state matches Err(error) ==> resource_error(error)), + state is Ok ==> derivative_tasks_ready(store.graph(), tasks.view(), cache@), + state is Ok ==> cache_complete(cache@, this@) || tasks_contain(tasks.view(), this@), + old(store).errors_are_non_owner() ==> state != Err(HistoryError::WrongHistoryOwner), + model::graph_wf(store.graph()), store.valid_store(), this@ < store.graph().regexes.len(), + derivative_cache_wf(store.graph(), cache@), derivative_tasks_wf(store.graph(), tasks.view()), + old(cache)@.len() <= cache@.len(), + forall|i: int| 0 <= i < old(cache)@.len() && old(cache)@[i] is Some + ==> i < cache@.len() && cache@[i] == old(cache)@[i], + derivative_tasks_bounded(tasks.view(), this@), + decreases if state is Ok { derivative_work(store.graph(), tasks.view()) + 1 } else { 0 }))] + while !tasks.is_empty() && state.is_ok() { + proof! { derivative_extends(entry, store.graph()); } + proof_decl! { let ghost pending = tasks.view(); } + state = match tasks.pop() { + Some((id, finish)) => { + proof! { + assert(pending =~= tasks.view().push((id, finish))); + derivative_ready_top(store.graph(), pending, cache@); + } + RegexId::derivative_step(id, store, cache, finish, &mut tasks) + } + None => Err(HistoryError::symbolic_invariant()), + }; + } + state?; + Self::cached(cache, this) + } +} +} +#[verus_verify] +pub(crate) trait AtomTruth: Sized { + #[verus_spec(result => ensures result.is_ok() == assignment_valid(this@.len(), words@), + result != Err(HistoryError::WrongHistoryOwner), assignment_valid(this@.len(), words@) ==> language::no_invariant_failure(result), + assignment_valid(this@.len(), words@) ==> (result matches Err(error) ==> resource_error(error)), + !(result matches Err(HistoryError::InvalidPolicy { .. })))] + fn validate_assignment(this: &AtomSet, words: &[u64]) -> KernelResult<()>; + + #[verus_spec(result => + requires model::atom_ids_wf(old(store).graph(), this@), + match previous { Some(i) => positive_atom_at(old(store).graph(), this@, primitive@, i), None => true }, + ensures final(store).graph() == old(store).graph(), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_invariant() && old(store).valid_store() && index < this@.len() ==> language::no_invariant_failure(result), + old(store).errors_are_resource() && old(store).valid_store() && index < this@.len() + ==> (result matches Err(error) ==> resource_error(error)), + result == Ok(None) ==> previous is None && !positive_atom_at(final(store).graph(), this@, primitive@, index), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + final(store).valid_store() == old(store).valid_store(), + match result { Ok(Some(i)) => positive_atom_at(final(store).graph(), this@, primitive@, i), _ => true }, + )] + fn positive_step( + this: &AtomSet, + store: &mut G, + primitive: Primitive, + index: usize, + previous: Option, + ) -> KernelResult>; + + #[verus_spec(result => + requires model::atom_ids_wf(old(store).graph(), this@), + id@ < old(store).graph().tests.len(), + old(store).graph().tests[id@ as int] == model::TestNode::Atom(primitive@, positive), + ensures final(store).graph() == old(store).graph(), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_invariant() && old(store).valid_store() && model::graph_wf(old(store).graph()) + && reach::has_positive(old(store).graph(), this@, primitive@) ==> language::no_invariant_failure(result), + old(store).errors_are_resource() && old(store).valid_store() && model::graph_wf(old(store).graph()) + && reach::has_positive(old(store).graph(), this@, primitive@) + ==> (result matches Err(error) ==> resource_error(error)), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + final(store).valid_store() == old(store).valid_store(), + match result { Ok(i) => positive_atom_at(final(store).graph(), this@, primitive@, i), Err(_) => true }, + )] + fn positive_index( + this: &AtomSet, + store: &mut G, + id: TestId, + primitive: Primitive, + positive: bool, + ) -> KernelResult; + + #[verus_spec(result => ensures match result { + Ok(value) => index / 64 < words@.len() && value == truth_word_bit(words@, index as nat), + Err(_) => index / 64 >= words@.len(), + }, result != Err(HistoryError::WrongHistoryOwner), index / 64 < words@.len() ==> language::no_invariant_failure(result), + index / 64 < words@.len() ==> (result matches Err(error) ==> resource_error(error)), + !(result matches Err(HistoryError::InvalidPolicy { .. })))] + fn truth(words: &[u64], index: usize) -> KernelResult; +} + +#[verus_verify] +impl AtomTruth for AtomSet { + #[verus_verify] + + fn validate_assignment(this: &AtomSet, words: &[u64]) -> KernelResult<()> { + let count = this.ids().len(); + let rounded = match count.checked_add(63) { + Some(v) => v, + None => return Err(HistoryError::invalid_truth_assignment()), + }; + let required = match rounded.checked_div(64) { + Some(v) => v, + None => return Err(HistoryError::invalid_truth_assignment()), + }; + if words.len() != required { + return Err(HistoryError::invalid_truth_assignment()); + } + let remainder = match count.checked_rem(64) { + Some(v) => v, + None => return Err(HistoryError::invalid_truth_assignment()), + }; + if remainder != 0 { + let shift = match u32::try_from(remainder) { + Ok(v) => v, + Err(_) => return Err(HistoryError::invalid_truth_assignment()), + }; + let last = match words.last() { + Some(v) => *v, + None => return Err(HistoryError::invalid_truth_assignment()), + }; + let high = match checked_shr(last, shift) { + Some(v) => v, + None => return Err(HistoryError::invalid_truth_assignment()), + }; + if high != 0 { + return Err(HistoryError::invalid_truth_assignment()); + } + } + Ok(()) + } + #[verus_verify] + + fn positive_step( + this: &AtomSet, + store: &mut G, + primitive: Primitive, + index: usize, + previous: Option, + ) -> KernelResult> { + store.checkpoint()?; + let base = match this.ids().get(index) { + Some(v) => *v, + None => return Err(HistoryError::missing_transition_atom()), + }; + let head = base.head(store)?; + if matches!(head,TestHead::Atom(p,true) if p==primitive) { + Ok(Some(index)) + } else { + Ok(previous) + } + } + #[allow( + clippy::option_if_let_else, + reason = "Explicit matches preserve the Verus proof structure." + )] + #[verus_verify] + + fn positive_index( + this: &AtomSet, + store: &mut G, + id: TestId, + primitive: Primitive, + positive: bool, + ) -> KernelResult { + if positive { + proof! { + assert forall|i: int, j: int| 0 <= i < j < this@.len() + implies vstd::std_specs::cmp::OrdSpec::cmp_spec(&this@[i], &this@[j]) is Less by { + assert(model::test_ids(this@)[i] == this@[i]@); + assert(model::test_ids(this@)[j] == this@[j]@); + } + if model::graph_wf(store.graph()) && reach::has_positive(store.graph(), this@, primitive@) { + model::lemma_graph_wf_elim(store.graph()); + let i = choose|i: int| 0 <= i < this@.len() && this@[i]@ < store.graph().tests.len() + && store.graph().tests[this@[i]@ as int] == model::TestNode::Atom(primitive@, true); + assert(store.graph().tests[this@[i]@ as int] == store.graph().tests[id@ as int]); + assert(this@[i]@ == id@); + assert(this@[i] == id); + assert(this@.contains(id)); + } + } + proof! { junco_core::kernel::TestId::lemma_obeys_cmp(); } + return match this.ids().binary_search(&id) { + Ok(index) => Ok(index), + Err(_) => Err(HistoryError::missing_transition_atom()), + }; + } + let mut state = Ok(None); + let count = this.ids().len(); + scan!(state,index,count,state.is_ok(),previous=>AtomSet::positive_step(this,store,primitive,index,previous); + invariant count == this@.len(), store.graph() == old(store).graph(), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(state matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_invariant() && old(store).valid_store() ==> language::no_invariant_failure(state), + old(store).errors_are_resource() && old(store).valid_store() + ==> (state matches Err(error) ==> resource_error(error)), + index <= this@.len(), state == Ok(None) ==> forall|j: usize| j < index ==> !positive_atom_at(store.graph(), this@, primitive@, j), + old(store).errors_are_non_owner() ==> state != Err(HistoryError::WrongHistoryOwner), + store.valid_store() == old(store).valid_store(), model::atom_ids_wf(store.graph(), this@), + match state { Ok(Some(i)) => positive_atom_at(store.graph(), this@, primitive@, i), _ => true }, + ensures state == Ok(None) ==> forall|j: usize| j < this@.len() ==> !positive_atom_at(store.graph(), this@, primitive@, j), + decreases this@.len() - index, + ); + let selected = state?; + proof! { + if selected is None && reach::has_positive(store.graph(), this@, primitive@) { + let i = choose|i: int| 0 <= i < this@.len() && this@[i]@ < store.graph().tests.len() + && store.graph().tests[this@[i]@ as int] == model::TestNode::Atom(primitive@, true); + assert(i <= usize::MAX); + let index = i as usize; + assert(index as int == i); + assert(positive_atom_at(store.graph(), this@, primitive@, index)); + assert(state == Ok(None)); + assert(false); + } + } + match selected { + Some(index) => Ok(index), + None => Err(HistoryError::missing_transition_atom()), + } + } + #[verus_verify] + + fn truth(words: &[u64], index: usize) -> KernelResult { + let word = match index.checked_div(64) { + Some(v) => v, + None => return Err(HistoryError::invalid_truth_assignment()), + }; + let bit = match index.checked_rem(64) { + Some(v) => v, + None => return Err(HistoryError::invalid_truth_assignment()), + }; + let shift = match u32::try_from(bit) { + Ok(v) => v, + Err(_) => return Err(HistoryError::invalid_truth_assignment()), + }; + let value = match words.get(word) { + Some(v) => *v, + None => return Err(HistoryError::invalid_truth_assignment()), + }; + let shifted = match checked_shr(value, shift) { + Some(v) => v, + None => return Err(HistoryError::invalid_truth_assignment()), + }; + Ok(shifted & 1 != 0) + } +} +verus! { +pub(crate) trait TestEvaluate: Sized { + #[allow( + clippy::option_if_let_else, + clippy::semicolon_if_nothing_returned, + reason = "Preserve the existing Verus-verified matches and mutation branches." + )] + fn evaluate_branch( + store: &G, + id: TestId, + count: usize, + and: bool, + finish: bool, + tasks: &mut WorkVec<(TestId, bool)>, + values: &mut WorkVec, + ) -> (result: KernelResult<()>) + requires model::graph_wf(store.graph()), id@ < store.graph().tests.len(), + store.graph().tests[id@ as int] == (if and { model::TestNode::And(test_children(store.graph(), id)) } else { model::TestNode::Or(test_children(store.graph(), id)) }), + count == test_children(store.graph(), id).len(), test_tasks_wf(store.graph(), old(tasks).view()), + ensures test_tasks_wf(store.graph(), final(tasks).view()), + store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() && (!finish || count <= old(values).view().len()) ==> language::no_invariant_failure(result), + store.errors_are_resource() && store.valid_store() && (!finish || count <= old(values).view().len()) + ==> (result matches Err(error) ==> resource_error(error)), + store.errors_are_non_invalid_policy() && store.valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + result is Ok ==> test_stack_result(store.graph(), old(tasks).view().push((id, finish)), old(values).view().len()) + == test_stack_result(store.graph(), final(tasks).view(), final(values).view().len()), + forall|atoms: Seq| test_tasks_covered(store.graph(), old(tasks).view().push((id, finish)), atoms) && result is Ok + ==> test_tasks_covered(store.graph(), final(tasks).view(), atoms), + result.is_ok() ==> forall|theta: Subst, event: EventView| + test_run(store.graph(), old(tasks).view().push((id, finish)), old(values).view(), theta, event) + == test_run(store.graph(), final(tasks).view(), final(values).view(), theta, event), + result.is_ok() ==> final(tasks).view() == old(tasks).view() + || norm::test_not_work(store.graph(), final(tasks).view()) + < norm::test_not_work(store.graph(), old(tasks).view().push((id, finish))), + { + if finish { + let mut out = and; + let mut failure = None; + let mut i = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant i <= count, i <= old(values).view().len(), + store.errors_are_non_owner() ==> failure != Some(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() && count <= old(values).view().len() + ==> (failure matches Some(error) ==> language::no_invariant_failure::<()>(Err(error))), + store.errors_are_resource() && store.valid_store() && count <= old(values).view().len() + ==> (failure matches Some(error) ==> resource_error(error)), + store.errors_are_non_invalid_policy() && store.valid_store() ==> !(failure matches Some(HistoryError::InvalidPolicy { .. })), + values.view() == old(values).view().take(old(values).view().len() - i), + out == bool_fold(old(values).view().skip(old(values).view().len() - i), and), + ensures failure.is_none() ==> i == count, + decreases count - i, + ))] + while i < count { + let value = loop_try!( + match values.pop() { + Some(v) => Ok(v), + None => Err(HistoryError::symbolic_invariant()), + }, + failure + ); + proof! { + let suffix = old(values).view().skip(old(values).view().len() - i); + bool_fold_prepend(value, suffix, and); + assert(old(values).view().skip(old(values).view().len() - i - 1) =~= seq![value] + suffix); + } + if and { + out &= value + } else { + out |= value + } + i = i.saturating_add(1); + } + if let Some(error) = failure { + return Err(error); + } + values.push(out); + proof! { + test_stack_task(store.graph(), old(tasks).view(), (id, true), old(values).view().len()); + assert(values.view().len() == old(values).view().len() - count + 1); + assert(old(tasks).view().push((id, finish)).drop_last() =~= old(tasks).view()); + assert forall|theta: Subst, event: EventView| + test_run(store.graph(), old(tasks).view().push((id, finish)), old(values).view(), theta, event) + == test_run(store.graph(), tasks.view(), values.view(), theta, event) by { + test_run_unfold(store.graph(), old(tasks).view().push((id, finish)), old(values).view(), theta, event); + } + } + } else { + tasks.push((id, true)); + proof_decl! { let ghost scheduled_base = tasks.view(); } + proof! { model::lemma_graph_test_wf(store.graph(), id@); } + let mut failure = None; + let mut remaining = count; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant remaining <= count, model::graph_wf(store.graph()), id@ < store.graph().tests.len(), + store.errors_are_non_owner() ==> failure != Some(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() ==> (failure matches Some(error) ==> language::no_invariant_failure::<()>(Err(error))), + store.errors_are_resource() && store.valid_store() ==> (failure matches Some(error) ==> resource_error(error)), + store.errors_are_non_invalid_policy() && store.valid_store() ==> !(failure matches Some(HistoryError::InvalidPolicy { .. })), + count == test_children(store.graph(), id).len(), test_tasks_wf(store.graph(), scheduled_base), + test_tasks_wf(store.graph(), tasks.view()), + failure.is_none() ==> tasks.view() == scheduled_base + child_test_tasks(store.graph(), id, remaining as nat), + ensures failure.is_none() ==> remaining == 0, + decreases remaining, + ))] + // Reverse pushes preserve source order when the LIFO task stack executes children. + while remaining != 0 { + let i = loop_try!( + match remaining.checked_sub(1) { + Some(value) => Ok(value), + None => Err(HistoryError::symbolic_invariant()), + }, + failure + ); + remaining = i; + let child = loop_try!(id.child(store, i), failure); + proof! { + assert(child@ == test_children(store.graph(), id)[i as int]); + model::lemma_graph_test_wf(store.graph(), id@); + assert(child@ < store.graph().tests.len()); + assert(child_test_tasks(store.graph(), id, i as nat) + =~= child_test_tasks(store.graph(), id, i as nat + 1).push((child, false))); + } + tasks.push((child, false)); + } + if let Some(error) = failure { + return Err(error); + } + proof! { + test_stack_children(store.graph(), id, 0, old(tasks).view().push((id, true)), old(values).view().len()); + test_stack_task(store.graph(), old(tasks).view(), (id, false), old(values).view().len()); + test_stack_task(store.graph(), old(tasks).view(), (id, true), (old(values).view().len() + count) as nat); + assert(tasks.view() == old(tasks).view().push((id, true)) + child_test_tasks(store.graph(), id, 0)); + assert forall|theta: Subst, event: EventView| + test_run(store.graph(), old(tasks).view().push((id, finish)), old(values).view(), theta, event) + == test_run(store.graph(), tasks.view(), values.view(), theta, event) by { + test_expand(store.graph(), id, old(tasks).view(), old(values).view(), theta, event); + } + test_lemma_eval_branch_work(store.graph(), id, old(tasks).view()); + } + } + proof! { + assert forall|atoms: Seq| test_tasks_covered(store.graph(), old(tasks).view().push((id, finish)), atoms) + implies test_tasks_covered(store.graph(), tasks.view(), atoms) by { + assert(old(tasks).view().push((id, finish))[old(tasks).view().len() as int] == (id, finish)); + assert(test_atoms_covered(store.graph(), id@, atoms)); + test_coverage_children(store.graph(), id, atoms); + assert forall|i: int| 0 <= i < tasks.view().len() implies test_atoms_covered(store.graph(), tasks.view()[i].0@, atoms) by { + if i < old(tasks).view().len() { + assert(tasks.view()[i] == old(tasks).view()[i]); + assert(old(tasks).view().push((id, finish))[i] == old(tasks).view()[i]); + } else if i == old(tasks).view().len() { + assert(tasks.view()[i].0 == id); + } else { + let j = test_children(store.graph(), id).len() - 1 - (i - old(tasks).view().len() - 1); + assert(tasks.view()[i].0@ == test_children(store.graph(), id)[j]); + } + } + } + } + Ok(()) + } + + fn evaluate_step( + this: TestId, + store: &mut G, + finish: bool, + atoms: &AtomSet, + words: &[u64], + tasks: &mut WorkVec<(TestId, bool)>, + values: &mut WorkVec, + ) -> (result: KernelResult<()>) + requires model::graph_wf(old(store).graph()), this@ < old(store).graph().tests.len(), + model::atom_ids_wf(old(store).graph(), atoms@), test_tasks_wf(old(store).graph(), old(tasks).view()), + ensures final(store).graph() == old(store).graph(), final(store).valid_store() == old(store).valid_store(), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_invariant() && old(store).valid_store() && test_atoms_covered(old(store).graph(), this@, atoms@) + && assignment_valid(atoms@.len(), words@) + && test_stack_result(old(store).graph(), old(tasks).view().push((this, finish)), old(values).view().len()) is Some + ==> language::no_invariant_failure(result), + old(store).errors_are_resource() && old(store).valid_store() && test_atoms_covered(old(store).graph(), this@, atoms@) + && assignment_valid(atoms@.len(), words@) + && test_stack_result(old(store).graph(), old(tasks).view().push((this, finish)), old(values).view().len()) is Some + ==> (result matches Err(error) ==> resource_error(error)), + result is Ok ==> test_stack_result(old(store).graph(), old(tasks).view().push((this, finish)), old(values).view().len()) + == test_stack_result(final(store).graph(), final(tasks).view(), final(values).view().len()), + test_tasks_covered(old(store).graph(), old(tasks).view().push((this, finish)), atoms@) && result is Ok + ==> test_tasks_covered(final(store).graph(), final(tasks).view(), atoms@), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + test_tasks_wf(final(store).graph(), final(tasks).view()), + result.is_ok() ==> forall|theta: Subst, event: EventView| + truth_words_realize(final(store).graph(), atoms@, words@, theta, event) ==> + test_run(final(store).graph(), old(tasks).view().push((this, finish)), old(values).view(), theta, event) + == test_run(final(store).graph(), final(tasks).view(), final(values).view(), theta, event), + result.is_ok() ==> norm::test_not_work(final(store).graph(), final(tasks).view()) + < norm::test_not_work(old(store).graph(), old(tasks).view().push((this, finish))); + + fn evaluate( + this: TestId, + store: &mut G, + atoms: &AtomSet, + words: &[u64], + ) -> (result: KernelResult) + requires model::graph_wf(old(store).graph()), this@ < old(store).graph().tests.len(), + model::atom_ids_wf(old(store).graph(), atoms@), + ensures final(store).graph() == old(store).graph(), final(store).valid_store() == old(store).valid_store(), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_invariant() && old(store).valid_store() && test_atoms_covered(old(store).graph(), this@, atoms@) + && assignment_valid(atoms@.len(), words@) ==> language::no_invariant_failure(result), + old(store).errors_are_resource() && old(store).valid_store() && test_atoms_covered(old(store).graph(), this@, atoms@) + && assignment_valid(atoms@.len(), words@) ==> (result matches Err(error) ==> resource_error(error)), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + result matches Ok(value) ==> forall|theta: Subst, event: EventView| + truth_words_realize(final(store).graph(), atoms@, words@, theta, event) ==> + value == model::test_holds(theta, model::lift_test(final(store).graph(), this@), event); +} +} + +#[verus_verify] +impl TestEvaluate for TestId { + #[verus_verify] + + fn evaluate_step( + this: TestId, + store: &mut G, + finish: bool, + atoms: &AtomSet, + words: &[u64], + tasks: &mut WorkVec<(TestId, bool)>, + values: &mut WorkVec, + ) -> KernelResult<()> { + store.checkpoint()?; + match this.head(store)? { + TestHead::True => values.push(true), + TestHead::False => values.push(false), + TestHead::Atom(primitive, positive) => { + proof! { + if test_atoms_covered(store.graph(), this@, atoms@) { + assert(reach::test_reaches_primitive(store.graph(), this@, primitive@)); + assert(reach::has_positive(store.graph(), atoms@, primitive@)); + } + } + let index = AtomSet::positive_index(atoms, store, this, primitive, positive)?; + proof! { + if assignment_valid(atoms@.len(), words@) { assignment_index_bound(atoms@.len(), words@, index); } + } + let value = AtomSet::truth(words, index)?; + values.push(if positive { value } else { !value }); + proof! { + realized_atom_value(store.graph(), atoms@, words@, this, primitive@, positive, index, value); + } + } + TestHead::And(n) => Self::evaluate_branch(store, this, n, true, finish, tasks, values)?, + TestHead::Or(n) => Self::evaluate_branch(store, this, n, false, finish, tasks, values)?, + } + proof! { + assert(old(tasks).view().push((this, finish)).drop_last() =~= old(tasks).view()); + assert forall|theta: Subst, event: EventView| + truth_words_realize(store.graph(), atoms@, words@, theta, event) implies + test_run(store.graph(), old(tasks).view().push((this, finish)), old(values).view(), theta, event) + == test_run(store.graph(), tasks.view(), values.view(), theta, event) by { + test_run_unfold(store.graph(), old(tasks).view().push((this, finish)), old(values).view(), theta, event); + } + test_lemma_eval_step_work(store.graph(), this, finish, old(tasks).view(), tasks.view()); + } + Ok(()) + } + #[allow( + clippy::option_if_let_else, + reason = "Explicit matches preserve the Verus proof structure." + )] + #[verus_verify] + + fn evaluate( + this: TestId, + store: &mut G, + atoms: &AtomSet, + words: &[u64], + ) -> KernelResult { + let mut tasks = WorkVec::new(); + let mut values = WorkVec::new(); + tasks.push((this, false)); + let mut state = Ok(()); + proof! { + test_stack_task(store.graph(), Seq::empty(), (this, false), 0); + assert(test_stack_result(store.graph(), Seq::empty(), 1) == Some(1)); + assert(tasks.view() == seq![(this, false)]); + assert(test_stack_result(store.graph(), tasks.view(), 0) == Some(1)); + assert forall|theta: Subst, event: EventView| + test_run(store.graph(), tasks.view(), values.view(), theta, event) + == Some(seq![model::test_holds(theta, model::lift_test(store.graph(), this@), event)]) by { + test_run_unfold(store.graph(), tasks.view(), values.view(), theta, event); + test_run_unfold(store.graph(), Seq::empty(), seq![model::test_holds(theta, model::lift_test(store.graph(), this@), event)], theta, event); + } + } + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant store.graph() == old(store).graph(), store.valid_store() == old(store).valid_store(), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() ==> !(state matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_invariant() && old(store).valid_store() && test_atoms_covered(store.graph(), this@, atoms@) + && assignment_valid(atoms@.len(), words@) ==> language::no_invariant_failure(state), + old(store).errors_are_resource() && old(store).valid_store() && test_atoms_covered(store.graph(), this@, atoms@) + && assignment_valid(atoms@.len(), words@) ==> (state matches Err(error) ==> resource_error(error)), + state is Ok ==> test_stack_result(store.graph(), tasks.view(), values.view().len()) == Some(1), + test_atoms_covered(store.graph(), this@, atoms@) && state is Ok ==> test_tasks_covered(store.graph(), tasks.view(), atoms@), + old(store).errors_are_non_owner() ==> state != Err(HistoryError::WrongHistoryOwner), + model::graph_wf(store.graph()), model::atom_ids_wf(store.graph(), atoms@), test_tasks_wf(store.graph(), tasks.view()), + this@ < store.graph().tests.len(), + state.is_ok() ==> forall|theta: Subst, event: EventView| + truth_words_realize(store.graph(), atoms@, words@, theta, event) ==> + test_run(store.graph(), tasks.view(), values.view(), theta, event) + == Some(seq![model::test_holds(theta, model::lift_test(store.graph(), this@), event)]), + decreases if state is Ok { norm::test_not_work(store.graph(), tasks.view()) + 1 } else { 0 }, + ))] + while !tasks.is_empty() && state.is_ok() { + proof_decl! { let ghost pending = tasks.view(); } + state = match tasks.pop() { + Some((id, finish)) => { + proof! { assert(pending =~= tasks.view().push((id, finish))); } + TestId::evaluate_step(id, store, finish, atoms, words, &mut tasks, &mut values) + } + None => Err(HistoryError::symbolic_invariant()), + }; + } + state?; + match values.pop() { + Some(v) => Ok(v), + None => Err(HistoryError::symbolic_invariant()), + } + } +} +verus! { +fn collect_append_factors( + store: &G, root: TransitionId, head: RegexId, count: usize, xs: &mut WorkVec, +) -> (result: KernelResult<()>) + requires model::graph_wf(store.graph()), store.valid_store(), root@ < store.graph().transitions.len(), + store.graph().transitions[root@ as int] is Append, head@ < store.graph().regexes.len(), + count == transition_suffix(store.graph(), root).len(), old(xs).view().len() == 0, + ensures norm::regex_ids_valid(store.graph(), final(xs).view()), + store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() ==> language::no_invariant_failure(result), + store.errors_are_resource() && store.valid_store() ==> (result matches Err(error) ==> resource_error(error)), + store.errors_are_non_invalid_policy() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + result is Ok ==> model::regex_ids(final(xs).view()) == seq![head@] + transition_suffix(store.graph(), root), +{ + proof { model::lemma_graph_transition_wf(store.graph(), root@); } + xs.push(head); + let mut failure = None; + let mut i = 0; + while i < count + invariant i <= count, model::graph_wf(store.graph()), store.valid_store(), + root@ < store.graph().transitions.len(), store.graph().transitions[root@ as int] is Append, + head@ < store.graph().regexes.len(), count == transition_suffix(store.graph(), root).len(), + model::transition_node_wf_at(store.graph(), store.graph().transitions[root@ as int], root@), + store.errors_are_non_owner() ==> failure != Some(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() ==> (failure matches Some(error) ==> language::no_invariant_failure::<()>(Err(error))), + store.errors_are_resource() && store.valid_store() ==> (failure matches Some(error) ==> resource_error(error)), + store.errors_are_non_invalid_policy() ==> !(failure matches Some(HistoryError::InvalidPolicy { .. })), + norm::regex_ids_valid(store.graph(), xs.view()), + model::regex_ids(xs.view()) == seq![head@] + transition_suffix(store.graph(), root).take(i as int), + ensures failure is None ==> i == count, + decreases count - i, + { + let child = loop_try!(root.suffix_child(store, i), failure); + proof { + assert(child@ == transition_suffix(store.graph(), root)[i as int]); + assert(child@ < store.graph().regexes.len()); + } + let ghost previous = xs.view(); + xs.push(child); + proof { + norm::regex_ids_push(previous, child); + assert(transition_suffix(store.graph(), root).take(i as int + 1) + =~= transition_suffix(store.graph(), root).take(i as int).push(child@)); + } + i = i.saturating_add(1); + } + if let Some(error) = failure { return Err(error); } + proof { assert(transition_suffix(store.graph(), root).take(count as int) =~= transition_suffix(store.graph(), root)); } + Ok(()) +} + +#[verifier::spinoff_prover] +fn interpret_not( + store: &mut G, root: TransitionId, inner: TransitionId, finish: bool, + tasks: &mut WorkVec<(TransitionId, bool)>, values: &mut WorkVec, +) -> (result: KernelResult<()>) + requires model::graph_wf(old(store).graph()), old(store).valid_store(), root@ < old(store).graph().transitions.len(), + old(store).graph().transitions[root@ as int] == model::TransitionNode::Not(inner@), + interp_tasks_wf(old(store).graph(), old(tasks).view()), norm::regex_ids_valid(old(store).graph(), old(values).view()), + ensures model::graph_extends(old(store).graph(), final(store).graph()), model::graph_wf(final(store).graph()), final(store).valid_store(), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + old(store).errors_are_non_invalid_policy() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_invariant() && (!finish || old(values).view().len() > 0) ==> language::no_invariant_failure(result), + old(store).errors_are_resource() && old(store).valid_store() && (!finish || old(values).view().len() > 0) + ==> (result matches Err(error) ==> resource_error(error)), + interp_tasks_wf(final(store).graph(), final(tasks).view()), norm::regex_ids_valid(final(store).graph(), final(values).view()), + result is Ok ==> (if finish { + final(tasks).view() == old(tasks).view() && final(values).view().len() == old(values).view().len() + } else { + final(tasks).view() == old(tasks).view().push((root, true)).push((inner, false)) && final(values).view() == old(values).view() + }), + result is Ok ==> interp_work(final(store).graph(), final(tasks).view()) + < interp_work(old(store).graph(), old(tasks).view().push((root, finish))), + result is Ok ==> final(tasks).view() == old(tasks).view() + || (interp_tasks_wf(old(store).graph(), final(tasks).view()) + && interp_work(old(store).graph(), final(tasks).view()) + < interp_work(old(store).graph(), old(tasks).view().push((root, finish)))), + result is Ok ==> interp_stack_result(old(store).graph(), old(tasks).view().push((root, finish)), old(values).view().len()) + == interp_stack_result(final(store).graph(), final(tasks).view(), final(values).view().len()), + forall|atoms: Seq| interp_tasks_covered(old(store).graph(), old(tasks).view().push((root, finish)), atoms) && result is Ok + ==> interp_tasks_covered(final(store).graph(), final(tasks).view(), atoms), + result is Ok ==> forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + ==> interp_results_equiv(model::gsem(theta), + interp_run(old(store).graph(), old(tasks).view().push((root, finish)), lifted_values(old(store).graph(), old(values).view()), theta, event), + interp_run(final(store).graph(), final(tasks).view(), lifted_values(final(store).graph(), final(values).view()), theta, event)), + result is Ok ==> (fint::ipre(old(store).graph(), old(tasks).view().push((root, finish)), old(values).view()) + ==> fint::istep(final(store).graph(), old(tasks).view().push((root, finish)), final(tasks).view(), old(values).view(), final(values).view())), +{ + hide(interp_run); hide(interp_stack_result); hide(interp_tasks_covered); + hide(reach::atoms_wf); hide(test_atoms_covered); + hide(language::numeric_lang); hide(language::interp_transition); + hide(model::test_holds); hide(model::lift_transition); hide(model::lift_regex); + let ghost before = store.graph(); + let ghost pending = tasks.view(); + let ghost prior = values.view(); + proof { + norm::graph_lemma_extends_refl(before); + model::lemma_graph_transition_wf(before, root@); + interp_stack_task(before, pending, (root, finish), prior.len()); + } + if finish { + let value = match values.pop() { + Some(value) => value, + None => return Err(HistoryError::symbolic_invariant()), + }; + values.push(RegexId::not(value, store)?); + proof { + lifted_values_stable(before, store.graph(), prior); + store.graph().transitions.lemma_prefix_index_eq(before.transitions); + assert forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) implies + interp_results_equiv(model::gsem(theta), + interp_run(store.graph(), pending.push((root, finish)), lifted_values(store.graph(), prior), theta, event), + interp_run(store.graph(), tasks.view(), lifted_values(store.graph(), values.view()), theta, event)) by { + assert forall|word: Seq| language::numeric_lang(model::gsem(theta), language::Regex::Not(Box::new(model::lift_regex(store.graph(), value@))), word) + == model::regex_lang(store.graph(), theta, values.view().last()@, word) by { + norm::regex_language_unfold(model::gsem(theta), language::Regex::Not(Box::new(model::lift_regex(store.graph(), value@))), word); + } + assert(lifted_values(store.graph(), values.view()) =~= lifted_values(store.graph(), prior).drop_last().push(model::lift_regex(store.graph(), values.view().last()@))); + interp_value_reduction(store.graph(), root, finish, pending, lifted_values(store.graph(), prior), lifted_values(store.graph(), values.view()), theta, event); + } + assert(before.transitions[root@ as int] == store.graph().transitions[root@ as int]); + if fint::ipre(before, pending.push((root, finish)), prior) { + fint::lemma_istep_not(before, store.graph(), root, pending, prior, values.view().last()); + } + } + } else { + tasks.push((root, true)); + tasks.push((inner, false)); + proof { + interp_stack_task(store.graph(), pending.push((root, true)), (inner, false), prior.len()); + interp_stack_task(store.graph(), pending, (root, true), prior.len() + 1); + assert forall|theta: Subst, event: EventView| interp_run(store.graph(), pending.push((root, finish)), lifted_values(store.graph(), prior), theta, event) + == interp_run(store.graph(), tasks.view(), lifted_values(store.graph(), values.view()), theta, event) by { + interp_expand_unary(store.graph(), root, inner, pending, lifted_values(store.graph(), prior), theta, event); + } + interp_lemma_work_unary(store.graph(), root, pending, inner); + assert(before.transitions[root@ as int] == store.graph().transitions[root@ as int]); + if fint::ipre(before, pending.push((root, finish)), prior) { + fint::lemma_istep_unary(before, store.graph(), root, finish, pending, prior, inner); + } + } + } + proof { + interp_lemma_step_post(before, store.graph(), root, finish, pending, tasks.view()); + interp_stack_stable(before, store.graph(), pending.push((root, finish)), prior.len()); + interp_stack_task(store.graph(), pending, (root, finish), prior.len()); + assert forall|atoms: Seq| interp_tasks_covered(before, pending.push((root, finish)), atoms) + implies interp_tasks_covered(store.graph(), tasks.view(), atoms) by { + interp_coverage_pop(before, pending, (root, finish), atoms); + interp_coverage_stable(before, store.graph(), pending, atoms); + if !finish { + transition_coverage_children(before, root, atoms); + assert(reach::transition_edges(before, root@) == seq![inner@]); + assert(reach::transition_edges(before, root@)[0] == inner@); + assert(reach::atoms_wf(before, inner@, atoms)); + interp_coverage_push(before, pending, (root, true), atoms); + interp_coverage_push(before, pending.push((root, true)), (inner, false), atoms); + } + } + assert forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) implies + interp_results_equiv(model::gsem(theta), + interp_run(before, pending.push((root, finish)), lifted_values(before, prior), theta, event), + interp_run(store.graph(), tasks.view(), lifted_values(store.graph(), values.view()), theta, event)) by { + interp_same_configuration_extends(before, store.graph(), pending.push((root, finish)), prior, theta, event); + } + } + Ok(()) +} + +pub(crate) trait TransitionInterpret: Sized { + #[allow( + clippy::option_if_let_else, + reason = "Explicit matches preserve the Verus proof structure." + )] + fn interpret_branch( + store: &mut G, + id: TransitionId, + count: usize, + intersect: bool, + finish: bool, + tasks: &mut WorkVec<(TransitionId, bool)>, + values: &mut WorkVec, + ) -> (result: KernelResult<()>) + requires model::graph_wf(old(store).graph()), old(store).valid_store(), id@ < old(store).graph().transitions.len(), + old(store).graph().transitions[id@ as int] == (if intersect { model::TransitionNode::Intersect(transition_children(old(store).graph(), id)) } else { model::TransitionNode::Union(transition_children(old(store).graph(), id)) }), + count == transition_children(old(store).graph(), id).len(), interp_tasks_wf(old(store).graph(), old(tasks).view()), + norm::regex_ids_valid(old(store).graph(), old(values).view()), + ensures model::graph_extends(old(store).graph(), final(store).graph()), model::graph_wf(final(store).graph()), final(store).valid_store(), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_invalid_policy() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_invariant() && (!finish || count <= old(values).view().len()) ==> language::no_invariant_failure(result), + old(store).errors_are_resource() && old(store).valid_store() && (!finish || count <= old(values).view().len()) + ==> (result matches Err(error) ==> resource_error(error)), + result is Ok ==> interp_stack_result(old(store).graph(), old(tasks).view().push((id, finish)), old(values).view().len()) + == interp_stack_result(final(store).graph(), final(tasks).view(), final(values).view().len()), + forall|atoms: Seq| interp_tasks_covered(old(store).graph(), old(tasks).view().push((id, finish)), atoms) && result is Ok + ==> interp_tasks_covered(final(store).graph(), final(tasks).view(), atoms), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + interp_tasks_wf(final(store).graph(), final(tasks).view()), norm::regex_ids_valid(final(store).graph(), final(values).view()), + result.is_ok() ==> forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) ==> + interp_results_equiv(model::gsem(theta), + interp_run(old(store).graph(), old(tasks).view().push((id, finish)), lifted_values(old(store).graph(), old(values).view()), theta, event), + interp_run(final(store).graph(), final(tasks).view(), lifted_values(final(store).graph(), final(values).view()), theta, event)), + result.is_ok() ==> final(tasks).view() == old(tasks).view() + || (interp_tasks_wf(old(store).graph(), final(tasks).view()) + && interp_work(old(store).graph(), final(tasks).view()) + < interp_work(old(store).graph(), old(tasks).view().push((id, finish)))), + result.is_ok() ==> (fint::ipre(old(store).graph(), old(tasks).view().push((id, finish)), old(values).view()) + ==> fint::istep(final(store).graph(), old(tasks).view().push((id, finish)), final(tasks).view(), old(values).view(), final(values).view())), + { + proof_decl! { let ghost before = store.graph(); } + if finish { + let start = match values.len().checked_sub(count) { + Some(v) => v, + None => return Err(HistoryError::symbolic_invariant()), + }; + let children = match values.get(start..) { + Some(xs) => xs, + None => return Err(HistoryError::symbolic_invariant()), + }; + proof_decl! { let ghost selected = children@; } + let out = RegexId::set(store, children, intersect)?; + proof! { lifted_values_stable(before, store.graph(), old(values).view()); } + values.truncate(start); + values.push(out); + proof! { + interp_stack_task(store.graph(), old(tasks).view(), (id, true), old(values).view().len()); + assert(values.view().len() == old(values).view().len() - count + 1); + assert forall|theta: Subst| language::event_wf(theta, theta.len()) implies + regex_stack_equiv(model::gsem(theta), lifted_values(store.graph(), values.view()), + lifted_values(store.graph(), old(values).view().take(old(values).view().len() - count)).push( + regex_fold(lifted_values(store.graph(), old(values).view().skip(old(values).view().len() - count)), intersect))) by { + assert forall|word: Seq| model::regex_lang(store.graph(), theta, out@, word) + == language::numeric_lang(model::gsem(theta), regex_fold(lifted_values(store.graph(), selected), intersect), word) by { + regex_fold_ids(store.graph(), selected, intersect, theta, word); + } + assert(lifted_values(store.graph(), values.view()) + =~= lifted_values(store.graph(), old(values).view().take(start as int)).push(model::lift_regex(store.graph(), out@))); + assert(selected =~= old(values).view().skip(start as int)); + assert forall|i: int, word: Seq| 0 <= i < values.view().len() implies + language::numeric_lang(model::gsem(theta), lifted_values(store.graph(), values.view())[i], word) + == language::numeric_lang(model::gsem(theta), lifted_values(store.graph(), old(values).view().take(start as int)).push( + regex_fold(lifted_values(store.graph(), selected), intersect))[i], word) by { + if i == start { + assert(model::regex_lang(store.graph(), theta, out@, word) + == language::numeric_lang(model::gsem(theta), regex_fold(lifted_values(store.graph(), selected), intersect), word)); + } + } + } + assert(interp_set_result(store.graph(), old(values).view(), values.view(), count as nat, intersect)); + assert forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) implies + interp_results_equiv(model::gsem(theta), + interp_run(before, old(tasks).view().push((id, finish)), lifted_values(before, old(values).view()), theta, event), + interp_run(store.graph(), tasks.view(), lifted_values(store.graph(), values.view()), theta, event)) by { + let pending = old(tasks).view().push((id, finish)); + interp_same_configuration_extends(before, store.graph(), pending, old(values).view(), theta, event); + assert(pending.drop_last() =~= old(tasks).view()); + interp_run_unfold(store.graph(), pending, lifted_values(store.graph(), old(values).view()), theta, event); + let reduced = lifted_values(store.graph(), old(values).view()).take(old(values).view().len() - count).push( + regex_fold(lifted_values(store.graph(), old(values).view()).skip(old(values).view().len() - count), intersect)); + assert(lifted_values(store.graph(), old(values).view().take(old(values).view().len() - count)) + =~= lifted_values(store.graph(), old(values).view()).take(old(values).view().len() - count)); + assert(lifted_values(store.graph(), old(values).view().skip(old(values).view().len() - count)) + =~= lifted_values(store.graph(), old(values).view()).skip(old(values).view().len() - count)); + interp_run_congruent(store.graph(), tasks.view(), reduced, lifted_values(store.graph(), values.view()), theta, event); + } + assert(values.view() =~= old(values).view().take(start as int).push(out)); + if fint::ipre(before, old(tasks).view().push((id, finish)), old(values).view()) { + fint::lemma_istep_set(before, store.graph(), id, intersect, old(tasks).view(), old(values).view(), start as int, out); + } + } + } else { + tasks.push((id, true)); + proof_decl! { let ghost scheduled_base = tasks.view(); } + proof! { model::lemma_graph_transition_wf(store.graph(), id@); } + let mut failure = None; + let mut remaining = count; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant remaining <= count, model::graph_wf(store.graph()), id@ < store.graph().transitions.len(), + store.graph() == before, store.valid_store(), store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_invalid_policy() ==> !(failure matches Some(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_invariant() ==> (failure matches Some(error) ==> language::no_invariant_failure::<()>(Err(error))), + old(store).errors_are_resource() && old(store).valid_store() + ==> (failure matches Some(error) ==> resource_error(error)), + old(store).errors_are_non_owner() ==> failure != Some(HistoryError::WrongHistoryOwner), + norm::regex_ids_valid(store.graph(), values.view()), + count == transition_children(store.graph(), id).len(), interp_tasks_wf(store.graph(), scheduled_base), + interp_tasks_wf(store.graph(), tasks.view()), + failure.is_none() ==> tasks.view() == scheduled_base + child_interp_tasks(store.graph(), id, remaining as nat), + ensures failure.is_none() ==> remaining == 0, + decreases remaining, + ))] + // Reverse pushes preserve source order when the LIFO task stack executes children. + while remaining != 0 { + let i = loop_try!( + match remaining.checked_sub(1) { + Some(value) => Ok(value), + None => Err(HistoryError::symbolic_invariant()), + }, + failure + ); + remaining = i; + let child = loop_try!(id.child(store, i), failure); + proof! { + model::lemma_graph_transition_wf(store.graph(), id@); + assert(child@ == transition_children(store.graph(), id)[i as int]); + assert(child@ < store.graph().transitions.len()); + assert(child_interp_tasks(store.graph(), id, i as nat) + =~= child_interp_tasks(store.graph(), id, i as nat + 1).push((child, false))); + } + tasks.push((child, false)); + } + if let Some(error) = failure { + return Err(error); + } + proof! { + interp_stack_children(store.graph(), id, 0, old(tasks).view().push((id, true)), old(values).view().len()); + interp_stack_task(store.graph(), old(tasks).view(), (id, false), old(values).view().len()); + interp_stack_task(store.graph(), old(tasks).view(), (id, true), (old(values).view().len() + count) as nat); + assert(tasks.view() == old(tasks).view().push((id, true)) + child_interp_tasks(store.graph(), id, 0)); + assert forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) implies + interp_results_equiv(model::gsem(theta), + interp_run(before, old(tasks).view().push((id, finish)), lifted_values(before, old(values).view()), theta, event), + interp_run(store.graph(), tasks.view(), lifted_values(store.graph(), values.view()), theta, event)) by { + interp_expand_set(store.graph(), id, old(tasks).view(), lifted_values(store.graph(), old(values).view()), theta, event); + } + interp_lemma_work_branch(store.graph(), id, old(tasks).view()); + if fint::ipre(before, old(tasks).view().push((id, finish)), old(values).view()) { + fint::lemma_istep_expand(before, store.graph(), id, finish, old(tasks).view(), old(values).view()); + } + } + } + proof! { + interp_stack_stable(before, store.graph(), old(tasks).view().push((id, finish)), old(values).view().len()); + assert forall|atoms: Seq| interp_tasks_covered(before, old(tasks).view().push((id, finish)), atoms) + implies interp_tasks_covered(store.graph(), tasks.view(), atoms) by { + interp_coverage_stable(before, store.graph(), old(tasks).view().push((id, finish)), atoms); + assert(old(tasks).view().push((id, finish))[old(tasks).view().len() as int] == (id, finish)); + assert(reach::atoms_wf(store.graph(), id@, atoms)); + transition_coverage_children(store.graph(), id, atoms); + assert forall|i: int| 0 <= i < tasks.view().len() implies reach::atoms_wf(store.graph(), tasks.view()[i].0@, atoms) by { + if i < old(tasks).view().len() { + assert(tasks.view()[i] == old(tasks).view()[i]); + assert(old(tasks).view().push((id, finish))[i] == old(tasks).view()[i]); + } else if i == old(tasks).view().len() { + assert(tasks.view()[i].0 == id); + } else { + let j = transition_children(store.graph(), id).len() - 1 - (i - old(tasks).view().len() - 1); + assert(tasks.view()[i].0@ == transition_children(store.graph(), id)[j]); + } + } + } + } + Ok(()) + } + + fn interpret_step( + this: TransitionId, + store: &mut G, + finish: bool, + atoms: &AtomSet, + words: &[u64], + tasks: &mut WorkVec<(TransitionId, bool)>, + values: &mut WorkVec, + ) -> (result: KernelResult<()>) + requires model::graph_wf(old(store).graph()), old(store).valid_store(), this@ < old(store).graph().transitions.len(), + model::atom_ids_wf(old(store).graph(), atoms@), interp_tasks_wf(old(store).graph(), old(tasks).view()), + norm::regex_ids_valid(old(store).graph(), old(values).view()), + ensures model::graph_extends(old(store).graph(), final(store).graph()), model::graph_wf(final(store).graph()), final(store).valid_store(), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_invalid_policy() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_invariant() && reach::atoms_wf(old(store).graph(), this@, atoms@) + && assignment_valid(atoms@.len(), words@) + && interp_stack_result(old(store).graph(), old(tasks).view().push((this, finish)), old(values).view().len()) is Some + ==> language::no_invariant_failure(result), + old(store).errors_are_resource() && old(store).valid_store() && reach::atoms_wf(old(store).graph(), this@, atoms@) + && assignment_valid(atoms@.len(), words@) + && interp_stack_result(old(store).graph(), old(tasks).view().push((this, finish)), old(values).view().len()) is Some + ==> (result matches Err(error) ==> resource_error(error)), + result is Ok ==> interp_stack_result(old(store).graph(), old(tasks).view().push((this, finish)), old(values).view().len()) + == interp_stack_result(final(store).graph(), final(tasks).view(), final(values).view().len()), + interp_tasks_covered(old(store).graph(), old(tasks).view().push((this, finish)), atoms@) && result is Ok + ==> interp_tasks_covered(final(store).graph(), final(tasks).view(), atoms@), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + interp_tasks_wf(final(store).graph(), final(tasks).view()), norm::regex_ids_valid(final(store).graph(), final(values).view()), + result.is_ok() ==> interp_machine_relation(old(store).graph(), final(store).graph(), old(tasks).view().push((this, finish)), final(tasks).view(), old(values).view(), final(values).view(), atoms@, words@), + result.is_ok() ==> interp_work(final(store).graph(), final(tasks).view()) + < interp_work(old(store).graph(), old(tasks).view().push((this, finish))), + result.is_ok() ==> (fint::ipre(old(store).graph(), old(tasks).view().push((this, finish)), old(values).view()) + ==> fint::istep(final(store).graph(), old(tasks).view().push((this, finish)), final(tasks).view(), old(values).view(), final(values).view())); + + fn interpret( + this: TransitionId, + store: &mut G, + atoms: &AtomSet, + truth_words: &[u64], + ) -> (result: KernelResult) + requires model::graph_wf(old(store).graph()), old(store).valid_store(), this@ < old(store).graph().transitions.len(), + model::atom_ids_wf(old(store).graph(), atoms@), + ensures model::graph_extends(old(store).graph(), final(store).graph()), model::graph_wf(final(store).graph()), final(store).valid_store(), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_invalid_policy() ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_invariant() && reach::atoms_wf(old(store).graph(), this@, atoms@) + && assignment_valid(atoms@.len(), truth_words@) ==> language::no_invariant_failure(result), + old(store).errors_are_resource() && old(store).valid_store() && reach::atoms_wf(old(store).graph(), this@, atoms@) + && assignment_valid(atoms@.len(), truth_words@) ==> (result matches Err(error) ==> resource_error(error)), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + result matches Ok(id) ==> id@ < final(store).graph().regexes.len() + && forall|theta: Subst, event: EventView, word: Seq| + language::event_wf(theta, theta.len()) && truth_words_realize(old(store).graph(), atoms@, truth_words@, theta, event) ==> + model::regex_lang(final(store).graph(), theta, id@, word) + == norm::transition_lang(final(store).graph(), theta, this, event, word), + result matches Ok(id) ==> (ftr::nf_sum(old(store).graph(), this@) + ==> ftr::tval(final(store).graph(), this@, model::lift_regex(final(store).graph(), id@))); +} +} + +#[verus_verify] +impl TransitionInterpret for TransitionId { + verus! { + #[verifier::spinoff_prover] + fn interpret_step( + this: TransitionId, + store: &mut G, + finish: bool, + atoms: &AtomSet, + words: &[u64], + tasks: &mut WorkVec<(TransitionId, bool)>, + values: &mut WorkVec, + ) -> KernelResult<()> { + hide(interp_stack_result); hide(interp_tasks_covered); + hide(interp_run); + hide(reach::atoms_wf); hide(test_atoms_covered); + hide(language::numeric_lang); hide(language::interp_transition); + hide(model::test_holds); hide(model::lift_transition); hide(model::lift_regex); + proof_decl! { let ghost before = store.graph(); let ghost pending = tasks.view(); let ghost prior = values.view(); } + proof! { model::lemma_graph_transition_wf(store.graph(), this@); } + proof! { + interp_stack_task(before, pending, (this, finish), prior.len()); + if interp_tasks_covered(before, pending.push((this, finish)), atoms@) { + interp_coverage_pop(before, pending, (this, finish), atoms@); + } + if reach::atoms_wf(store.graph(), this@, atoms@) { transition_coverage_children(store.graph(), this, atoms@); } + } + store.checkpoint()?; + match this.head(store)? { + TransitionHead::Const(r) => { + values.push(r); + proof! { + assert forall|theta: Subst, event: EventView| + interp_results_equiv(model::gsem(theta), + interp_run(store.graph(), pending.push((this, finish)), lifted_values(store.graph(), prior), theta, event), + interp_run(store.graph(), tasks.view(), lifted_values(store.graph(), values.view()), theta, event)) by { + norm::transition_unfold(store.graph(), this@); + language::lemma_interp_const(model::gsem(theta), event, model::lift_regex(store.graph(), r@)); + interp_value_reduction(store.graph(), this, finish, pending, lifted_values(store.graph(), prior), lifted_values(store.graph(), values.view()), theta, event); + } + assert(before.transitions[this@ as int] == store.graph().transitions[this@ as int]); + if fint::ipre(before, pending.push((this, finish)), prior) { + fint::lemma_istep_const(before, store.graph(), this, finish, pending, prior, r); + } + } + } + TransitionHead::If(test, a, b) => { + proof! { + if reach::atoms_wf(before, this@, atoms@) { + assert(reach::transition_tests(before, this@) == seq![test@]); + assert(reach::transition_tests(before, this@)[0] == test@); + assert(test_atoms_covered(before, test@, atoms@)); + } + } + let chosen = if TestId::evaluate(test, store, atoms, words)? { + a + } else { + b + }; + tasks.push((chosen, false)); + proof! { + interp_stack_task(store.graph(), pending, (chosen, false), prior.len()); + if interp_tasks_covered(before, pending.push((this, finish)), atoms@) { + assert(reach::transition_edges(before, this@) == seq![a@, b@]); + if chosen == a { assert(reach::transition_edges(before, this@)[0] == chosen@); } + else { assert(reach::transition_edges(before, this@)[1] == chosen@); } + assert(reach::atoms_wf(before, chosen@, atoms@)); + interp_coverage_push(before, pending, (chosen, false), atoms@); + } + assert forall|theta: Subst, event: EventView| + language::event_wf(theta, theta.len()) && truth_words_realize(before, atoms@, words@, theta, event) implies + interp_results_equiv(model::gsem(theta), + interp_run(before, pending.push((this, finish)), lifted_values(before, prior), theta, event), + interp_run(store.graph(), tasks.view(), lifted_values(store.graph(), values.view()), theta, event)) by { + interp_choose(store.graph(), this, finish, test, a, b, chosen, pending, lifted_values(store.graph(), prior), theta, event); + } + interp_lemma_work_if(store.graph(), this, finish, pending, chosen); + assert(before.transitions[this@ as int] == store.graph().transitions[this@ as int]); + if fint::ipre(before, pending.push((this, finish)), prior) { + fint::lemma_istep_if(before, store.graph(), this, finish, pending, prior, test@, a, b, chosen); + } + } + } + TransitionHead::Union(n) => { + Self::interpret_branch(store, this, n, false, finish, tasks, values)? + } + TransitionHead::Intersect(n) => { + Self::interpret_branch(store, this, n, true, finish, tasks, values)? + } + TransitionHead::Not(inner) => interpret_not(store, this, inner, finish, tasks, values)?, + TransitionHead::Append(inner, n) => { + if finish { + let head = match values.pop() { + Some(v) => v, + None => return Err(HistoryError::symbolic_invariant()), + }; + proof! { model::lemma_graph_transition_wf(store.graph(), this@); } + let mut xs = WorkVec::new(); + collect_append_factors(store, this, head, n, &mut xs)?; + values.push(RegexId::concat(store, &xs)?); + proof! { + interp_append_finish(before, store.graph(), this, pending, prior, head, xs.view(), values.view()); + if fint::ipre(before, pending.push((this, finish)), prior) { + fint::lemma_istep_append(before, store.graph(), this, pending, prior, xs.view(), values.view().last()); + } + } + } else { + tasks.push((this, true)); + tasks.push((inner, false)); + proof! { + interp_stack_task(store.graph(), pending.push((this, true)), (inner, false), prior.len()); + interp_stack_task(store.graph(), pending, (this, true), prior.len() + 1); + if interp_tasks_covered(before, pending.push((this, finish)), atoms@) { + assert(reach::transition_edges(before, this@) == seq![inner@]); + assert(reach::transition_edges(before, this@)[0] == inner@); + assert(reach::atoms_wf(before, inner@, atoms@)); + interp_coverage_push(before, pending, (this, true), atoms@); + interp_coverage_push(before, pending.push((this, true)), (inner, false), atoms@); + } + assert forall|theta: Subst, event: EventView| + interp_run(store.graph(), pending.push((this, finish)), lifted_values(store.graph(), prior), theta, event) + == interp_run(store.graph(), tasks.view(), lifted_values(store.graph(), values.view()), theta, event) by { + interp_expand_unary(store.graph(), this, inner, pending, lifted_values(store.graph(), prior), theta, event); + } + interp_lemma_work_unary(store.graph(), this, pending, inner); + assert(before.transitions[this@ as int] == store.graph().transitions[this@ as int]); + if fint::ipre(before, pending.push((this, finish)), prior) { + fint::lemma_istep_unary(before, store.graph(), this, finish, pending, prior, inner); + } + } + } + } + } + proof! { + assert forall|theta: Subst, event: EventView| + language::event_wf(theta, theta.len()) && truth_words_realize(before, atoms@, words@, theta, event) implies + interp_results_equiv(model::gsem(theta), + interp_run(before, pending.push((this, finish)), lifted_values(before, prior), theta, event), + interp_run(store.graph(), tasks.view(), lifted_values(store.graph(), values.view()), theta, event)) by { + interp_same_configuration_extends(before, store.graph(), pending.push((this, finish)), prior, theta, event); + } + interp_lemma_step_post(before, store.graph(), this, finish, pending, tasks.view()); + interp_stack_stable(before, store.graph(), pending.push((this, finish)), prior.len()); + interp_stack_task(store.graph(), pending, (this, finish), prior.len()); + if interp_tasks_covered(before, pending.push((this, finish)), atoms@) { + interp_coverage_stable(before, store.graph(), pending.push((this, finish)), atoms@); + interp_coverage_stable(before, store.graph(), pending, atoms@); + assert(interp_tasks_covered(store.graph(), tasks.view(), atoms@)); + } + } + Ok(()) + } + } + #[allow( + clippy::option_if_let_else, + reason = "Explicit matches preserve the Verus proof structure." + )] + #[verus_verify] + #[cfg_attr(verus_keep_ghost, verifier::rlimit(30))] + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + + fn interpret( + this: TransitionId, + store: &mut G, + atoms: &AtomSet, + truth_words: &[u64], + ) -> KernelResult { + proof_decl! { let ghost entry = store.graph(); } + AtomSet::validate_assignment(atoms, truth_words)?; + let mut tasks = WorkVec::new(); + let mut values = WorkVec::new(); + tasks.push((this, false)); + let mut state = Ok(()); + proof! { + assert(tasks.view() == seq![(this, false)]); + assert(values.view().len() == 0); + assert(interp_stack_needed(store.graph(), (this, false)) == 0); + assert(interp_stack_result(store.graph(), Seq::empty(), 1) == Some(1)); + interp_stack_task(store.graph(), Seq::empty(), (this, false), 0); + assert(interp_stack_result(store.graph(), tasks.view(), 0) == Some(1)); + assert forall|theta: Subst, event: EventView| + interp_results_equiv(model::gsem(theta), + interp_run(store.graph(), tasks.view(), lifted_values(store.graph(), values.view()), theta, event), + Some(seq![interpreted(entry, this, theta, event)])) by { + interp_run_unfold(store.graph(), tasks.view(), lifted_values(store.graph(), values.view()), theta, event); + interp_run_unfold(store.graph(), Seq::empty(), seq![interpreted(entry, this, theta, event)], theta, event); + } + if ftr::nf_sum(entry, this@) { + assert(values.view() =~= Seq::::empty()); + assert(tasks.view() =~= seq![(this, false)]); + fint::lemma_iinit(store.graph(), this); + } + } + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant model::graph_extends(entry, store.graph()), model::graph_wf(store.graph()), store.valid_store(), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_non_invalid_policy() ==> !(state matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_invariant() && reach::atoms_wf(entry, this@, atoms@) ==> language::no_invariant_failure(state), + old(store).errors_are_resource() && old(store).valid_store() && reach::atoms_wf(entry, this@, atoms@) + ==> (state matches Err(error) ==> resource_error(error)), + assignment_valid(atoms@.len(), truth_words@), + state is Ok ==> interp_stack_result(store.graph(), tasks.view(), values.view().len()) == Some(1), + reach::atoms_wf(entry, this@, atoms@) && state is Ok ==> interp_tasks_covered(store.graph(), tasks.view(), atoms@), + old(store).errors_are_non_owner() ==> state != Err(HistoryError::WrongHistoryOwner), + model::graph_wf(entry), model::atom_ids_wf(entry, atoms@), this@ < entry.transitions.len(), + model::atom_ids_wf(store.graph(), atoms@), interp_tasks_wf(store.graph(), tasks.view()), norm::regex_ids_valid(store.graph(), values.view()), + state.is_ok() ==> forall|theta: Subst, event: EventView| + language::event_wf(theta, theta.len()) && truth_words_realize(entry, atoms@, truth_words@, theta, event) ==> + interp_results_equiv(model::gsem(theta), + interp_run(store.graph(), tasks.view(), lifted_values(store.graph(), values.view()), theta, event), + Some(seq![interpreted(entry, this, theta, event)])), + state.is_ok() && ftr::nf_sum(entry, this@) ==> fint::iinv(store.graph(), this@, tasks.view(), values.view()), + decreases if state is Ok { interp_work(store.graph(), tasks.view()) + 1 } else { 0 }, + ))] + while !tasks.is_empty() && state.is_ok() { + proof_decl! { let ghost before = store.graph(); let ghost pending = tasks.view(); let ghost prior = values.view(); } + state = match tasks.pop() { + Some((id, finish)) => { + proof! { assert(pending =~= tasks.view().push((id, finish))); } + TransitionId::interpret_step( + id, + store, + finish, + atoms, + truth_words, + &mut tasks, + &mut values, + ) + } + None => Err(HistoryError::symbolic_invariant()), + }; + proof! { + norm::transition_lemma_extends_transitive(entry, before, store.graph()); + truth_words_realize_extends(entry, store.graph(), atoms@, truth_words@); + assert forall|theta: Subst, event: EventView| + state.is_ok() && language::event_wf(theta, theta.len()) && truth_words_realize(entry, atoms@, truth_words@, theta, event) implies + interp_results_equiv(model::gsem(theta), + interp_run(store.graph(), tasks.view(), lifted_values(store.graph(), values.view()), theta, event), + Some(seq![interpreted(entry, this, theta, event)])) by { + truth_words_realize_extends(entry, before, atoms@, truth_words@); + interp_results_equiv_trans(model::gsem(theta), + interp_run(store.graph(), tasks.view(), lifted_values(store.graph(), values.view()), theta, event), + interp_run(before, pending, lifted_values(before, prior), theta, event), + Some(seq![interpreted(entry, this, theta, event)])); + } + if state.is_ok() && ftr::nf_sum(entry, this@) { + fint::lemma_iloop(before, store.graph(), this@, pending, prior, tasks.view(), values.view()); + } + } + } + state?; + proof! { + interp_root_stable(entry, store.graph(), this); + if ftr::nf_sum(entry, this@) { + assert(tasks.view() =~= Seq::<(TransitionId, bool)>::empty()); + fint::lemma_ifinal(store.graph(), this@, values.view()); + assert(values.view().last() == values.view()[0]); + } + } + match values.pop() { + Some(v) => Ok(v), + None => Err(HistoryError::symbolic_invariant()), + } + } +} + +#[cfg(verus_keep_ghost)] +pub mod verify { + use super::*; + verus! { + broadcast use {junco_core::kernel::verify::group_kernel_views, vstd::set::group_set_lemmas}; + + pub open spec fn test_primitives(t: model::Test) -> Set + decreases t, 1nat, 0nat, + { + match t { + model::Test::Atom(p, _) => Set::empty().insert(p), + model::Test::And(cs) | model::Test::Or(cs) => test_primitive_prefix(t, cs.len()), + _ => Set::empty(), + } + } + + pub open spec fn test_primitive_prefix(t: model::Test, n: nat) -> Set + decreases t, 0nat, n, + { + match t { + model::Test::And(cs) | model::Test::Or(cs) => if 0 < n <= cs.len() { + test_primitive_prefix(t, (n - 1) as nat).union(test_primitives(cs[n - 1])) + } else { Set::empty() }, + _ => Set::empty(), + } + } + + pub open spec fn regex_primitives(r: language::Regex) -> Set + decreases r, 1nat, 0nat, + { + match r { + language::Regex::Test(t) => test_primitives(t), + language::Regex::Union(cs) | language::Regex::Intersect(cs) + | language::Regex::Concat(cs) => regex_primitive_prefix(r, cs.len()), + language::Regex::Star(b) | language::Regex::Not(b) => regex_primitives(*b), + _ => Set::empty(), + } + } + + pub open spec fn regex_primitive_prefix(r: language::Regex, n: nat) -> Set + decreases r, 0nat, n, + { + match r { + language::Regex::Union(cs) | language::Regex::Intersect(cs) + | language::Regex::Concat(cs) => if 0 < n <= cs.len() { + regex_primitive_prefix(r, (n - 1) as nat).union(regex_primitives(cs[n - 1])) + } else { Set::empty() }, + _ => Set::empty(), + } + } + + pub proof fn lemma_test_primitive_prefix(t: model::Test, n: nat, p: model::Primitive) + requires t is And || t is Or, n <= crate::verify::finite_impl::test_kids(t).len(), + ensures test_primitive_prefix(t, n).contains(p) + == (exists|i: int| 0 <= i < n && test_primitives(crate::verify::finite_impl::test_kids(t)[i]).contains(p)), + decreases n, + { + let cs = crate::verify::finite_impl::test_kids(t); + reveal_with_fuel(test_primitive_prefix, 1); + if n > 0 { + lemma_test_primitive_prefix(t, (n - 1) as nat, p); + assert(test_primitive_prefix(t, (n - 1) as nat).contains(p) + == (exists|i: int| 0 <= i < n - 1 && test_primitives(cs[i]).contains(p))); + if exists|i: int| 0 <= i < n && test_primitives(cs[i]).contains(p) { + let i = choose|i: int| 0 <= i < n && test_primitives(cs[i]).contains(p); + if i < n - 1 { + assert(exists|j: int| 0 <= j < n - 1 && test_primitives(cs[j]).contains(p)); + } else { assert(i == n - 1); } + } + if test_primitive_prefix(t, (n - 1) as nat).contains(p) { + let j = choose|j: int| 0 <= j < n - 1 && test_primitives(cs[j]).contains(p); + assert(exists|i: int| 0 <= i < n && test_primitives(cs[i]).contains(p)); + } + if test_primitives(cs[n - 1]).contains(p) { + assert(exists|i: int| 0 <= i < n && test_primitives(cs[i]).contains(p)); + } + } + } + + pub proof fn lemma_test_pair_vocab(a: model::Test, b: model::Test) + ensures test_primitives(model::Test::And(seq![a, b])) == test_primitives(a).union(test_primitives(b)), + { + reveal_with_fuel(test_primitive_prefix, 3); + reveal_with_fuel(test_primitives, 3); + assert(test_primitives(model::Test::And(seq![a, b])) =~= test_primitives(a).union(test_primitives(b))); + } + + pub open spec fn regex_kids(r: language::Regex) -> Seq> { + match r { + language::Regex::Union(cs) | language::Regex::Intersect(cs) | language::Regex::Concat(cs) => cs, + _ => Seq::empty(), + } + } + + pub proof fn lemma_regex_primitive_prefix(r: language::Regex, n: nat, p: model::Primitive) + requires r is Union || r is Intersect || r is Concat, n <= regex_kids(r).len(), + ensures regex_primitive_prefix(r, n).contains(p) + == (exists|i: int| 0 <= i < n && regex_primitives(regex_kids(r)[i]).contains(p)), + decreases n, + { + let cs = regex_kids(r); + reveal_with_fuel(regex_primitive_prefix, 1); + if n > 0 { + lemma_regex_primitive_prefix(r, (n - 1) as nat, p); + assert(regex_primitive_prefix(r, (n - 1) as nat).contains(p) + == (exists|i: int| 0 <= i < n - 1 && regex_primitives(cs[i]).contains(p))); + if exists|i: int| 0 <= i < n && regex_primitives(cs[i]).contains(p) { + let i = choose|i: int| 0 <= i < n && regex_primitives(cs[i]).contains(p); + if i < n - 1 { assert(exists|j: int| 0 <= j < n - 1 && regex_primitives(cs[j]).contains(p)); } + else { assert(i == n - 1); } + } + if regex_primitive_prefix(r, (n - 1) as nat).contains(p) { + let j = choose|j: int| 0 <= j < n - 1 && regex_primitives(cs[j]).contains(p); + assert(exists|i: int| 0 <= i < n && regex_primitives(cs[i]).contains(p)); + } + if regex_primitives(cs[n - 1]).contains(p) { + assert(exists|i: int| 0 <= i < n && regex_primitives(cs[i]).contains(p)); + } + } + } + + pub proof fn lemma_test_primitives_lift(g: model::Graph, id: nat, p: model::Primitive) + requires model::graph_wf(g), id < g.tests.len(), + ensures test_primitives(model::lift_test(g, id)).contains(p) + == reach::test_reaches_primitive(g, id, p), + decreases id, + { + model::lemma_graph_test_wf(g, id); + reveal_with_fuel(model::lift_test, 1); + reveal_with_fuel(model::lift_tests, 1); + reveal_with_fuel(test_primitives, 1); + reveal_with_fuel(reach::test_reaches_primitive, 1); + match g.tests[id as int] { + model::TestNode::And(cs) | model::TestNode::Or(cs) => { + let t = model::lift_test(g, id); + lemma_test_primitive_prefix(t, cs.len(), p); + assert forall|i: int| 0 <= i < cs.len() implies + test_primitives(model::lift_tests(g, cs, id)[i]).contains(p) + == reach::test_reaches_primitive(g, cs[i], p) by { + lemma_test_primitives_lift(g, cs[i], p); + } + if test_primitives(t).contains(p) { + let i = choose|i: int| 0 <= i < cs.len() && test_primitives(model::lift_tests(g, cs, id)[i]).contains(p); + assert(reach::test_edges(g, id)[i] == cs[i]); + assert(cs[i] < id); + assert(reach::test_reaches_primitive(g, id, p)); + } + if reach::test_reaches_primitive(g, id, p) { + let i = choose|i: int| 0 <= i < cs.len() && cs[i] < id && reach::test_reaches_primitive(g, cs[i], p); + assert(test_primitives(model::lift_tests(g, cs, id)[i]).contains(p)); + assert(test_primitives(crate::verify::finite_impl::test_kids(t)[i]).contains(p)); + } + }, + _ => {}, + } + } + + pub proof fn lemma_regex_primitives_stable(a: model::Graph, b: model::Graph, q: nat) + requires model::graph_wf(a), model::graph_extends(a, b), q < a.regexes.len(), + ensures regex_primitives(model::lift_regex(a, q)) == regex_primitives(model::lift_regex(b, q)), + { + model::lemma_graph_wf_elim(a); + model::lemma_lift_regex_stable(a, b, q); + } + + pub proof fn lemma_test_primitive_code(t: model::Test, c: history_syntax::Component, v: nat) + ensures test_primitives(t).contains(model::Primitive::Eq(c, model::GTerm::Constant(v))) + == crate::verify::refinement::encoding::test_mentions(t, c, v), + decreases t, + { + reveal_with_fuel(test_primitives, 1); + reveal_with_fuel(crate::verify::refinement::encoding::test_mentions, 1); + reveal(crate::verify::refinement::encoding::test_mention_child); + let p = model::Primitive::Eq(c, model::GTerm::Constant(v)); + match t { + model::Test::And(cs) => { + lemma_test_primitive_prefix(t, cs.len(), p); + assert forall|i: int| #![trigger cs[i]] 0 <= i < cs.len() implies + test_primitives(cs[i]).contains(p) == crate::verify::refinement::encoding::test_mentions(cs[i], c, v) by { + lemma_test_primitive_code(cs[i], c, v); + } + if test_primitives(t).contains(p) { + let i = choose|i: int| 0 <= i < cs.len() && test_primitives(cs[i]).contains(p); + lemma_test_primitive_code(cs[i], c, v); + assert(crate::verify::refinement::encoding::test_mention_child(t, i) == Some(cs[i])); + assert(exists|j: int| #![trigger crate::verify::refinement::encoding::test_mention_child(t, j)] + 0 <= j < cs.len() && crate::verify::refinement::encoding::test_mentions(cs[j], c, v)); + } + if crate::verify::refinement::encoding::test_mentions(t, c, v) { + let i = choose|i: int| #![trigger crate::verify::refinement::encoding::test_mention_child(t, i)] + 0 <= i < cs.len() && crate::verify::refinement::encoding::test_mentions(cs[i], c, v); + lemma_test_primitive_code(cs[i], c, v); + assert(test_primitives(cs[i]).contains(p)); + } + }, + model::Test::Or(cs) => { + lemma_test_primitive_prefix(t, cs.len(), p); + assert forall|i: int| #![trigger cs[i]] 0 <= i < cs.len() implies + test_primitives(cs[i]).contains(p) == crate::verify::refinement::encoding::test_mentions(cs[i], c, v) by { + lemma_test_primitive_code(cs[i], c, v); + } + if test_primitives(t).contains(p) { + let i = choose|i: int| 0 <= i < cs.len() && test_primitives(cs[i]).contains(p); + lemma_test_primitive_code(cs[i], c, v); + assert(crate::verify::refinement::encoding::test_mention_child(t, i) == Some(cs[i])); + assert(exists|j: int| #![trigger crate::verify::refinement::encoding::test_mention_child(t, j)] + 0 <= j < cs.len() && crate::verify::refinement::encoding::test_mentions(cs[j], c, v)); + } + if crate::verify::refinement::encoding::test_mentions(t, c, v) { + let i = choose|i: int| #![trigger crate::verify::refinement::encoding::test_mention_child(t, i)] + 0 <= i < cs.len() && crate::verify::refinement::encoding::test_mentions(cs[i], c, v); + lemma_test_primitive_code(cs[i], c, v); + assert(test_primitives(cs[i]).contains(p)); + } + }, + _ => {}, + } + } + + pub proof fn lemma_regex_primitive_code(r: language::Regex, c: history_syntax::Component, v: nat) + ensures regex_primitives(r).contains(model::Primitive::Eq(c, model::GTerm::Constant(v))) + == crate::verify::refinement::encoding::regex_mentions(r, c, v), + decreases r, + { + reveal_with_fuel(regex_primitives, 1); + reveal_with_fuel(crate::verify::refinement::encoding::regex_mentions, 2); + reveal(crate::verify::refinement::encoding::regex_mention_child); + let p = model::Primitive::Eq(c, model::GTerm::Constant(v)); + match r { + language::Regex::Test(t) => { lemma_test_primitive_code(t, c, v); }, + language::Regex::Star(b) | language::Regex::Not(b) => { + lemma_regex_primitive_code(*b, c, v); + }, + language::Regex::Union(cs) | language::Regex::Intersect(cs) | language::Regex::Concat(cs) => { + lemma_regex_primitive_prefix(r, cs.len(), p); + assert forall|i: int| 0 <= i < cs.len() implies + regex_primitives(cs[i]).contains(p) + == crate::verify::refinement::encoding::regex_mentions(cs[i], c, v) by { + lemma_regex_primitive_code(cs[i], c, v); + } + if regex_primitives(r).contains(p) { + let i = choose|i: int| 0 <= i < cs.len() && regex_primitives(cs[i]).contains(p); + lemma_regex_primitive_code(cs[i], c, v); + assert(crate::verify::refinement::encoding::regex_mentions(cs[i], c, v)); + assert(crate::verify::refinement::encoding::regex_mention_child(r, i) == Some(cs[i])); + assert(exists|j: int| #![trigger crate::verify::refinement::encoding::regex_mention_child(r, j)] + 0 <= j < regex_kids(r).len() && crate::verify::refinement::encoding::regex_mentions(regex_kids(r)[j], c, v)); + assert(crate::verify::refinement::encoding::regex_mentions(r, c, v)); + } + if crate::verify::refinement::encoding::regex_mentions(r, c, v) { + let i = choose|i: int| 0 <= i < cs.len() && crate::verify::refinement::encoding::regex_mentions(cs[i], c, v); + lemma_regex_primitive_code(cs[i], c, v); + assert(regex_primitives(regex_kids(r)[i]).contains(p)); + } + }, + _ => {}, + } + } + + /// Primitives tested now; tests in constant residuals and append suffixes are tested later. + pub open spec fn transition_primitives(t: language::Transition) -> Set + decreases t, 1nat, 0nat, + { + match t { + language::Transition::Const(_) => Set::empty(), + language::Transition::If(test, a, b) => test_primitives(test) + .union(transition_primitives(*a)).union(transition_primitives(*b)), + language::Transition::Union(cs) | language::Transition::Intersect(cs) => + transition_primitive_prefix(t, cs.len()), + language::Transition::Not(b) | language::Transition::Append(b, _) => transition_primitives(*b), + } + } + + pub open spec fn transition_primitive_prefix(t: language::Transition, n: nat) -> Set + decreases t, 0nat, n, + { + match t { + language::Transition::Union(cs) | language::Transition::Intersect(cs) => if 0 < n <= cs.len() { + transition_primitive_prefix(t, (n - 1) as nat).union(transition_primitives(cs[n - 1])) + } else { Set::empty() }, + _ => Set::empty(), + } + } + + pub open spec fn transition_kids(t: language::Transition) -> Seq> { + match t { language::Transition::Union(cs) | language::Transition::Intersect(cs) => cs, _ => Seq::empty() } + } + + pub proof fn lemma_transition_primitive_prefix(t: language::Transition, n: nat, p: model::Primitive) + requires t is Union || t is Intersect, n <= transition_kids(t).len(), + ensures transition_primitive_prefix(t, n).contains(p) + == (exists|i: int| 0 <= i < n && transition_primitives(transition_kids(t)[i]).contains(p)), + decreases n, + { + let cs = transition_kids(t); + reveal_with_fuel(transition_primitive_prefix, 1); + if n > 0 { + lemma_transition_primitive_prefix(t, (n - 1) as nat, p); + assert(transition_primitive_prefix(t, (n - 1) as nat).contains(p) + == (exists|i: int| 0 <= i < n - 1 && transition_primitives(cs[i]).contains(p))); + if exists|i: int| 0 <= i < n && transition_primitives(cs[i]).contains(p) { + let i = choose|i: int| 0 <= i < n && transition_primitives(cs[i]).contains(p); + if i < n - 1 { assert(exists|j: int| 0 <= j < n - 1 && transition_primitives(cs[j]).contains(p)); } + else { assert(i == n - 1); } + } + if transition_primitive_prefix(t, (n - 1) as nat).contains(p) { + let j = choose|j: int| 0 <= j < n - 1 && transition_primitives(cs[j]).contains(p); + assert(exists|i: int| 0 <= i < n && transition_primitives(cs[i]).contains(p)); + } + if transition_primitives(cs[n - 1]).contains(p) { + assert(exists|i: int| 0 <= i < n && transition_primitives(cs[i]).contains(p)); + } + } + } + + pub proof fn lemma_transition_primitives_lift(g: model::Graph, id: nat, p: model::Primitive) + requires model::graph_wf(g), id < g.transitions.len(), + ensures transition_primitives(model::lift_transition(g, id)).contains(p) + == reach::transition_reaches_primitive(g, id, p), + decreases id, + { + model::lemma_graph_transition_wf(g, id); + norm::transition_unfold(g, id); + reveal_with_fuel(transition_primitives, 1); + reveal_with_fuel(reach::transition_reaches_primitive, 1); + assert forall|j: int| #![trigger reach::transition_edges(g, id)[j]] + 0 <= j < reach::transition_edges(g, id).len() implies + transition_primitives(model::lift_transition(g, reach::transition_edges(g, id)[j])).contains(p) + == reach::transition_reaches_primitive(g, reach::transition_edges(g, id)[j], p) by { + lemma_transition_primitives_lift(g, reach::transition_edges(g, id)[j], p); + } + match g.transitions[id as int] { + model::TransitionNode::If(t, a, b) => { + lemma_test_primitives_lift(g, t, p); + lemma_transition_primitives_lift(g, a, p); + lemma_transition_primitives_lift(g, b, p); + assert(reach::transition_tests(g, id) == seq![t]); + assert(reach::transition_edges(g, id) == seq![a, b]); + if reach::test_reaches_primitive(g, t, p) || reach::transition_reaches_primitive(g, a, p) + || reach::transition_reaches_primitive(g, b, p) { + if reach::test_reaches_primitive(g, t, p) { + assert(reach::transition_tests(g, id)[0] == t); + } else if reach::transition_reaches_primitive(g, a, p) { + assert(reach::transition_edges(g, id)[0] == a); + } else { assert(reach::transition_edges(g, id)[1] == b); } + assert(reach::transition_reaches_primitive(g, id, p)); + } + assert(reach::transition_reaches_primitive(g, id, p) == (reach::test_reaches_primitive(g, t, p) + || reach::transition_reaches_primitive(g, a, p) || reach::transition_reaches_primitive(g, b, p))); + }, + model::TransitionNode::Union(cs) | model::TransitionNode::Intersect(cs) => { + let lifted = model::lift_transition(g, id); + lemma_transition_primitive_prefix(lifted, cs.len(), p); + reveal_with_fuel(model::lift_transitions, 1); + assert(transition_kids(lifted) == model::lift_transitions(g, cs, id)); + assert forall|j: int| 0 <= j < cs.len() implies + model::lift_transitions(g, cs, id)[j] == model::lift_transition(g, cs[j]) by {} + if transition_primitives(lifted).contains(p) { + let i = choose|i: int| 0 <= i < cs.len() && transition_primitives(model::lift_transitions(g, cs, id)[i]).contains(p); + assert(reach::transition_edges(g, id)[i] == cs[i]); + assert(cs[i] < id); + assert(reach::transition_reaches_primitive(g, id, p)); + } + if reach::transition_reaches_primitive(g, id, p) { + let i = choose|i: int| 0 <= i < cs.len() && cs[i] < id && reach::transition_reaches_primitive(g, cs[i], p); + assert(transition_primitives(transition_kids(lifted)[i]).contains(p)); + } + }, + model::TransitionNode::Not(child) | model::TransitionNode::Append(child, _) => { + lemma_transition_primitives_lift(g, child, p); + assert(reach::transition_tests(g, id) == Seq::::empty()); + assert(reach::transition_edges(g, id) == seq![child]); + assert(reach::transition_edges(g, id)[0] == child); + assert(reach::transition_reaches_primitive(g, id, p) + == reach::transition_reaches_primitive(g, child, p)); + }, + _ => {}, + } + } + + pub open spec fn derivative_vocab(g: model::Graph, q: nat, t: nat) -> bool { + transition_primitives(model::lift_transition(g, t)).subset_of(regex_primitives(model::lift_regex(g, q))) + } + + pub proof fn lemma_derivative_vocab_stable(a: model::Graph, b: model::Graph, q: nat, t: nat) + requires model::graph_wf(a), model::graph_extends(a, b), q < a.regexes.len(), t < a.transitions.len(), + derivative_vocab(a, q, t), + ensures derivative_vocab(b, q, t), + { + model::lemma_graph_wf_elim(a); + model::lemma_lift_stable_under_extends(a, b); + } + + pub proof fn lemma_test_negation_primitives(g: model::Graph, relation: Set<(nat, nat)>, a: nat, b: nat, p: model::Primitive) + requires model::graph_wf(g), norm::test_negation_witness(g, relation), relation.contains((a, b)), + ensures reach::test_reaches_primitive(g, a, p) == reach::test_reaches_primitive(g, b, p), + decreases a, + { + norm::test_lemma_negation_witness_elim(g, relation); + reveal(norm::test_negation_row); + reveal_with_fuel(reach::test_reaches_primitive, 1); + match (g.tests[a as int], g.tests[b as int]) { + (model::TestNode::And(cs), model::TestNode::Or(ds)) + | (model::TestNode::Or(cs), model::TestNode::And(ds)) => { + if reach::test_reaches_primitive(g, a, p) { + let i = choose|i: int| 0 <= i < cs.len() && cs[i] < a && reach::test_reaches_primitive(g, cs[i], p); + assert(cs.contains(cs[i])); + let d = choose|d: nat| ds.contains(d) && relation.contains((cs[i], d)); + lemma_test_negation_primitives(g, relation, cs[i], d, p); + let j = ds.lemma_contains_to_index(d); + assert(d < b); + assert(reach::test_edges(g, b) == ds); + assert(ds[j] == d); + assert(exists|k: int| 0 <= k < reach::test_edges(g, b).len() + && reach::test_edges(g, b)[k] < b && reach::test_reaches_primitive(g, reach::test_edges(g, b)[k], p)); + assert(reach::test_reaches_primitive(g, b, p)); + } + if reach::test_reaches_primitive(g, b, p) { + let j = choose|j: int| 0 <= j < ds.len() && ds[j] < b && reach::test_reaches_primitive(g, ds[j], p); + assert(ds.contains(ds[j])); + let c = choose|c: nat| cs.contains(c) && relation.contains((c, ds[j])); + let i = cs.lemma_contains_to_index(c); + assert(c < a); + lemma_test_negation_primitives(g, relation, c, ds[j], p); + assert(reach::test_edges(g, a) == cs); + assert(cs[i] == c); + assert(exists|k: int| 0 <= k < reach::test_edges(g, a).len() + && reach::test_edges(g, a)[k] < a && reach::test_reaches_primitive(g, reach::test_edges(g, a)[k], p)); + assert(reach::test_reaches_primitive(g, a, p)); + } + }, + _ => {}, + } + } + + pub proof fn lemma_test_not_done_primitives(g: model::Graph, values: Seq, root: TestId) + requires model::graph_wf(g), norm::test_not_state(g, Seq::empty(), values, root), + ensures values.len() == 1, + test_primitives(model::lift_test(g, values[0]@)) == test_primitives(model::lift_test(g, root@)), + { + let (origins, relation) = choose|origins: Seq, relation: Set<(nat, nat)>| + origins.len() == values.len() && norm::test_negation_witness(g, relation) + && (forall|i: int| 0 <= i < values.len() ==> relation.contains((origins[i], values[i]@))) + && norm::test_not_plan(g, Seq::empty(), origins) == Some(seq![root@]); + assert(origins == seq![root@]); + assert(values.len() == 1); + assert(0 <= 0 < values.len()); + assert(origins[0] == root@); + assert(relation.contains((origins[0], values[0]@))); + assert(relation.contains((root@, values[0]@))); + norm::test_lemma_negation_witness_elim(g, relation); + reveal(norm::test_negation_row); + assert forall|p: model::Primitive| test_primitives(model::lift_test(g, values[0]@)).contains(p) + == test_primitives(model::lift_test(g, root@)).contains(p) by { + lemma_test_primitives_lift(g, values[0]@, p); + lemma_test_primitives_lift(g, root@, p); + lemma_test_negation_primitives(g, relation, root@, values[0]@, p); + } + assert(test_primitives(model::lift_test(g, values[0]@)) =~= test_primitives(model::lift_test(g, root@))); + } + + pub proof fn lemma_test_member_bound(g: model::Graph, children: Seq, and: bool, t: nat) + requires model::graph_wf(g), norm::test_ids_valid(g, children), norm::test_member(g, children, and, t), + ensures t < g.tests.len(), + { + let i = choose|i: int| 0 <= i < children.len() && norm::test_piece_contains(g, children[i]@, and, t); + crate::verify::finite_link::lemma_test_piece_link(g, children[i]@, and, t); + } + + pub proof fn lemma_test_member_primitives(g: model::Graph, children: Seq, and: bool, t: nat, p: model::Primitive) + requires model::graph_wf(g), norm::test_ids_valid(g, children), norm::test_member(g, children, and, t), + reach::test_reaches_primitive(g, t, p), + ensures exists|i: int| 0 <= i < children.len() && reach::test_reaches_primitive(g, children[i]@, p), + { + let i = choose|i: int| 0 <= i < children.len() && norm::test_piece_contains(g, children[i]@, and, t); + let c = children[i]@; + model::lemma_graph_test_wf(g, c); + match g.tests[c as int] { + model::TestNode::And(cs) => if and { + let j = cs.lemma_contains_to_index(t); + assert(cs[j] < c); + assert(reach::test_edges(g, c) == cs); + assert(reach::test_reaches_primitive(g, c, p)); + }, + model::TestNode::Or(cs) => if !and { + let j = cs.lemma_contains_to_index(t); + assert(cs[j] < c); + assert(reach::test_edges(g, c) == cs); + assert(reach::test_reaches_primitive(g, c, p)); + }, + _ => {}, + } + assert(reach::test_reaches_primitive(g, children[i]@, p)); + } + + pub proof fn lemma_test_connective_primitives(a: model::Graph, b: model::Graph, children: Seq, and: bool, t: nat, p: model::Primitive) + requires model::graph_wf(a), model::graph_wf(b), model::graph_extends(a, b), + norm::test_ids_valid(a, children), t < b.tests.len(), + norm::test_connective_result(a, b, children, and, t), + test_primitives(model::lift_test(b, t)).contains(p), + ensures exists|i: int| 0 <= i < children.len() + && test_primitives(model::lift_test(a, children[i]@)).contains(p), + { + lemma_test_primitives_lift(b, t, p); + model::lemma_graph_wf_elim(a); + if t == a.constants.test_true || t == a.constants.test_false { + assert(b.tests[t as int] == a.tests[t as int]); + assert(!reach::test_reaches_primitive(b, t, p)); + } else if norm::test_member(a, children, and, t) { + lemma_test_member_bound(a, children, and, t); + reach::lemma_test_reaches_stable(a, b, t, p); + lemma_test_member_primitives(a, children, and, t, p); + let i = choose|i: int| 0 <= i < children.len() && reach::test_reaches_primitive(a, children[i]@, p); + lemma_test_primitives_lift(a, children[i]@, p); + } else { + model::lemma_graph_test_wf(b, t); + let j = choose|j: int| 0 <= j < reach::test_edges(b, t).len() + && reach::test_edges(b, t)[j] < t && reach::test_reaches_primitive(b, reach::test_edges(b, t)[j], p); + let c = reach::test_edges(b, t)[j]; + assert(norm::test_member(a, children, and, c)); + lemma_test_member_bound(a, children, and, c); + reach::lemma_test_reaches_stable(a, b, c, p); + lemma_test_member_primitives(a, children, and, c, p); + let i = choose|i: int| 0 <= i < children.len() && reach::test_reaches_primitive(a, children[i]@, p); + lemma_test_primitives_lift(a, children[i]@, p); + } + } + + pub proof fn lemma_test_piece_vocab(inter: bool, psi: model::Test, phi: model::Test) + requires crate::verify::finite_impl::test_piece(inter, psi, phi), + ensures test_primitives(phi).subset_of(test_primitives(psi)), + { + assert forall|p: model::Primitive| test_primitives(phi).contains(p) implies + test_primitives(psi).contains(p) by { + match psi { + model::Test::And(cs) | model::Test::Or(cs) => { + if phi != psi { + let i = cs.lemma_contains_to_index(phi); + lemma_test_primitive_prefix(psi, cs.len(), p); + assert(test_primitives(cs[i]).contains(p)); + } + }, + _ => {}, + } + } + } + + pub proof fn lemma_test_combo_vocab(inter: bool, xs: Set>, phi: model::Test, allowed: Set) + requires crate::verify::finite_impl::test_combo(inter, xs, phi), + forall|r: language::Regex| xs.contains(r) ==> regex_primitives(r).subset_of(allowed), + ensures test_primitives(phi).subset_of(allowed), + { + assert forall|psi: model::Test| crate::verify::finite_impl::piece_of(inter, xs, psi) implies + test_primitives(psi).subset_of(allowed) by { + let parent = choose|parent: model::Test| xs.contains(language::Regex::Test(parent)) + && crate::verify::finite_impl::test_piece(inter, parent, psi); + lemma_test_piece_vocab(inter, parent, psi); + assert(regex_primitives(language::Regex::Test(parent)) == test_primitives(parent)); + } + assert forall|p: model::Primitive| test_primitives(phi).contains(p) implies allowed.contains(p) by { + if !crate::verify::finite_impl::piece_of(inter, xs, phi) { + match phi { + model::Test::And(cs) | model::Test::Or(cs) => { + lemma_test_primitive_prefix(phi, cs.len(), p); + let i = choose|i: int| 0 <= i < cs.len() && test_primitives(cs[i]).contains(p); + assert(crate::verify::finite_impl::test_kids(phi)[i] == cs[i]); + assert(crate::verify::finite_impl::piece_of(inter, xs, cs[i])); + assert(test_primitives(cs[i]).subset_of(allowed)); + }, + _ => {}, + } + } + } + } + + pub proof fn lemma_sops_vocab(inter: bool, r: language::Regex, allowed: Set) + requires regex_primitives(r).subset_of(allowed), + ensures forall|o: language::Regex| + crate::verify::finite_impl::pre().sops(inter, r).contains(o) ==> regex_primitives(o).subset_of(allowed), + { + assert forall|o: language::Regex| + crate::verify::finite_impl::pre().sops(inter, r).contains(o) implies regex_primitives(o).subset_of(allowed) by { + match r { + language::Regex::Union(cs) | language::Regex::Intersect(cs) => { + if o != r { + let i = cs.lemma_contains_to_index(o); + assert forall|p: model::Primitive| regex_primitives(o).contains(p) implies allowed.contains(p) by { + lemma_regex_primitive_prefix(r, cs.len(), p); + assert(regex_primitives(cs[i]).contains(p)); + assert(regex_primitives(r).contains(p)); + } + } + }, + _ => {}, + } + } + } + + pub proof fn lemma_nset_vocab(inter: bool, xs: Set>, out: language::Regex, allowed: Set) + requires (crate::verify::finite_impl::core().nset)(inter, xs, out), + forall|r: language::Regex| xs.contains(r) ==> regex_primitives(r).subset_of(allowed), + ensures regex_primitives(out).subset_of(allowed), + { + reveal(crate::verify::finite_states::Model::combo_from); + reveal(crate::verify::finite_states::Model::in_sops_of); + let m = crate::verify::finite_impl::pre(); + assert(m.nset_shape(inter, xs, out)); + assert forall|r: language::Regex| xs.contains(r) implies + forall|o: language::Regex| m.sops(inter, r).contains(o) ==> regex_primitives(o).subset_of(allowed) by { + lemma_sops_vocab(inter, r, allowed); + } + assert forall|o: language::Regex| m.sops(inter, out).contains(o) implies + regex_primitives(o).subset_of(allowed) by { + if m.in_sops_of(inter, xs, o) { + let r = choose|r: language::Regex| xs.contains(r) && m.sops(inter, r).contains(o); + } else if !m.is_const(out) { + let ts = choose|ts: Set>| m.combo_from(inter, xs, ts, o); + assert(m.combo_from(inter, xs, ts, o)); + assert(forall|r: language::Regex| #![trigger ts.contains(r)] ts.contains(r) ==> m.is_test(r) && m.in_sops_of(inter, xs, r)); + assert forall|r: language::Regex| ts.contains(r) implies regex_primitives(r).subset_of(allowed) by { + assert(m.in_sops_of(inter, xs, r)); + let parent = choose|parent: language::Regex| xs.contains(parent) && m.sops(inter, parent).contains(r); + } + match o { + language::Regex::Test(phi) => { lemma_test_combo_vocab(inter, ts, phi, allowed); }, + _ => {}, + } + } + } + assert forall|p: model::Primitive| regex_primitives(out).contains(p) implies allowed.contains(p) by { + match out { + language::Regex::Union(cs) | language::Regex::Intersect(cs) => { + if m.is_set(inter, out) { + lemma_regex_primitive_prefix(out, cs.len(), p); + let i = choose|i: int| 0 <= i < cs.len() && regex_primitives(cs[i]).contains(p); + assert(m.sops(inter, out).contains(cs[i])); + } + }, + _ => {}, + } + if !m.is_set(inter, out) { assert(m.sops(inter, out).contains(out)); } + } + } + + pub proof fn lemma_built_vocab(inter: bool, base: spec_fn(language::Regex) -> bool, + out: language::Regex, allowed: Set) + requires crate::verify::finite_impl::m_impl().built(inter, base, out), + forall|r: language::Regex| base(r) ==> regex_primitives(r).subset_of(allowed), + ensures regex_primitives(out).subset_of(allowed), + { + broadcast use vstd::iset::lemma_iset_new; + crate::verify::finite_impl::lemma_models_agree(); + let m = crate::verify::finite_impl::m_impl(); + let carrier = ISet::new(|r: language::Regex| regex_primitives(r).subset_of(allowed)); + assert(m.has_consts(carrier)); + assert(m.nset_closed(inter, carrier)) by { + assert forall|xs: Set>, r: language::Regex| + (forall|x: language::Regex| xs.contains(x) ==> carrier.contains(x)) + && #[trigger] (m.nset)(inter, xs, r) implies carrier.contains(r) by { + assert forall|x: language::Regex| xs.contains(x) implies regex_primitives(x).subset_of(allowed) by { + assert(carrier.contains(x)); + } + lemma_nset_vocab(inter, xs, r, allowed); + } + } + assert(carrier.contains(out)); + } + + pub proof fn lemma_not_vocab(r: language::Regex) + ensures regex_primitives(crate::verify::finite_impl::r_not(r)).subset_of(regex_primitives(r)), + { + match r { language::Regex::Not(b) => {}, _ => {} } + } + + pub proof fn lemma_flat_vocab(xs: Seq>, allowed: Set) + requires forall|i: int| 0 <= i < xs.len() ==> regex_primitives(xs[i]).subset_of(allowed), + ensures forall|r: language::Regex| crate::verify::finite_impl::pre().flat(xs).contains(r) + ==> regex_primitives(r).subset_of(allowed), + decreases xs.len(), + { + if xs.len() > 0 { + let m = crate::verify::finite_impl::pre(); + lemma_flat_vocab(xs.drop_last(), allowed); + assert forall|r: language::Regex| m.flat(xs).contains(r) implies + regex_primitives(r).subset_of(allowed) by { + if !m.flat(xs.drop_last()).contains(r) { + assert(m.piece(xs.last()).contains(r)); + match xs.last() { + language::Regex::Concat(cs) => { + let i = cs.lemma_contains_to_index(r); + assert forall|p: model::Primitive| regex_primitives(r).contains(p) implies allowed.contains(p) by { + lemma_regex_primitive_prefix(xs.last(), cs.len(), p); + assert(regex_primitives(cs[i]).contains(p)); + assert(exists|j: int| 0 <= j < cs.len() && regex_primitives(regex_kids(xs.last())[j]).contains(p)); + assert(regex_primitives(xs.last()).contains(p)); + } + }, + _ => {}, + } + } + } + } + } + + pub proof fn lemma_cat_vocab(xs: Seq>, allowed: Set) + requires forall|i: int| 0 <= i < xs.len() ==> regex_primitives(xs[i]).subset_of(allowed), + ensures regex_primitives(crate::verify::finite_impl::r_cat(xs)).subset_of(allowed), + { + let m = crate::verify::finite_impl::pre(); + let f = m.flat(xs); + lemma_flat_vocab(xs, allowed); + if !m.has_empty(xs) && f.len() > 1 { + let out = language::Regex::Concat(f); + assert forall|p: model::Primitive| regex_primitives(out).contains(p) implies allowed.contains(p) by { + lemma_regex_primitive_prefix(out, f.len(), p); + let i = choose|i: int| 0 <= i < f.len() && regex_primitives(f[i]).contains(p); + assert(f.contains(f[i])); + } + } + if !m.has_empty(xs) && f.len() == 1 { assert(f.contains(f[0])); } + } + + pub proof fn lemma_regex_child_vocab(r: language::Regex, i: int) + requires r is Union || r is Intersect || r is Concat, 0 <= i < regex_kids(r).len(), + ensures regex_primitives(regex_kids(r)[i]).subset_of(regex_primitives(r)), + { + assert forall|p: model::Primitive| regex_primitives(regex_kids(r)[i]).contains(p) implies regex_primitives(r).contains(p) by { + lemma_regex_primitive_prefix(r, regex_kids(r).len(), p); + assert(exists|j: int| 0 <= j < regex_kids(r).len() && regex_primitives(regex_kids(r)[j]).contains(p)); + } + } + + pub proof fn lemma_model_constant_vocab(r: language::Regex) + requires crate::verify::finite_impl::m_impl().is_const(r), + ensures regex_primitives(r) == Set::empty(), + { + crate::verify::finite_impl::lemma_models_agree(); + match r { language::Regex::Empty | language::Regex::Epsilon | language::Regex::All => {}, _ => {} } + } + + pub proof fn lemma_model_literal_vocab(r: language::Regex, out: language::Regex) + requires crate::verify::finite_impl::regex_nf(r), (crate::verify::finite_impl::m_impl().lit)(r, out), + ensures regex_primitives(out).subset_of(regex_primitives(r)), + decreases crate::verify::finite_impl::r_size(r), 0nat, + { + let m = crate::verify::finite_impl::m_impl(); + let allowed = regex_primitives(r); + crate::verify::finite_impl::theorem_impl_contract(); + crate::verify::finite_impl::lemma_models_agree(); + if !m.base_kind(r) { + match r { + language::Regex::Union(cs) | language::Regex::Intersect(cs) => { + lemma_sops_vocab(r is Intersect, r, allowed); + assert forall|w: language::Regex| m.ops_lit(r, w) implies regex_primitives(w).subset_of(allowed) by { + let o = choose|o: language::Regex| (m.ops)(r).contains(o) && #[trigger] (m.lit)(o, w); + cs.to_set_ensures(); + assert(cs.contains(o)); + let i = cs.lemma_contains_to_index(o); + lemma_regex_child_vocab(r, i); + assert(m.st(o)); + assert((m.size)(o) < (m.size)(r)); + lemma_model_literal_vocab(o, w); + assert(m.sops(r is Intersect, r).contains(o)); + } + lemma_built_vocab(r is Intersect, |w: language::Regex| m.ops_lit(r, w), out, allowed); + }, + language::Regex::Not(b) => { + assert forall|w: language::Regex| m.not_lit(r, w) implies regex_primitives(w).subset_of(allowed) by { + let v = choose|v: language::Regex| #[trigger] (m.lit)(*b, v) && w == (m.nnot)(v); + lemma_model_literal_vocab(*b, v); + lemma_not_vocab(v); + } + lemma_built_vocab(true, |w: language::Regex| m.not_lit(r, w), out, allowed); + }, + language::Regex::Star(b) => { + assert forall|w: language::Regex| m.star_lit(r, w) implies regex_primitives(w).subset_of(allowed) by { + let v = choose|v: language::Regex| #[trigger] (m.prod)(*b, v) && w == m.cat2(v, r); + lemma_model_product_vocab(*b, v); + lemma_cat_vocab(seq![v, r], allowed); + } + lemma_built_vocab(false, |w: language::Regex| m.star_lit(r, w), out, allowed); + }, + language::Regex::Concat(cs) => { + assert forall|i: int| 0 <= i < cs.len() implies regex_primitives(cs[i]).subset_of(allowed) by { + lemma_regex_child_vocab(r, i); + } + assert forall|w: language::Regex| m.list_lit(r, w) implies regex_primitives(w).subset_of(allowed) by { + if exists|i: int, v: language::Regex| 0 <= i < cs.len() - 1 && #[trigger] (m.prod)(cs[i], v) + && w == (m.ncat)(seq![v] + cs.skip(i + 1)) { + let (i, v) = choose|i: int, v: language::Regex| 0 <= i < cs.len() - 1 + && #[trigger] (m.prod)(cs[i], v) && w == (m.ncat)(seq![v] + cs.skip(i + 1)); + lemma_model_product_vocab(cs[i], v); + let inputs = seq![v] + cs.skip(i + 1); + assert forall|j: int| 0 <= j < inputs.len() implies regex_primitives(inputs[j]).subset_of(allowed) by { + if j == 0 { assert(inputs[j] == v); } + else { assert(inputs[j] == cs[i + j]); } + } + lemma_cat_vocab(inputs, allowed); + } else { + assert((m.lit)(cs.last(), w)); + lemma_model_literal_vocab(cs.last(), w); + assert(regex_primitives(cs.last()).subset_of(allowed)); + } + } + lemma_built_vocab(false, |w: language::Regex| m.list_lit(r, w), out, allowed); + }, + _ => {}, + } + } else { lemma_model_constant_vocab(out); } + } + + pub proof fn lemma_model_product_vocab(r: language::Regex, out: language::Regex) + requires crate::verify::finite_impl::regex_nf(r), (crate::verify::finite_impl::m_impl().prod)(r, out), + ensures regex_primitives(out).subset_of(regex_primitives(r)), + decreases crate::verify::finite_impl::r_size(r), 1nat, + { + let m = crate::verify::finite_impl::m_impl(); + let allowed = regex_primitives(r); + crate::verify::finite_impl::theorem_impl_contract(); + crate::verify::finite_impl::lemma_models_agree(); + if !m.base_kind(r) { + match r { + language::Regex::Union(cs) => { + if exists|o: language::Regex| (m.ops)(r).contains(o) && #[trigger] (m.prod)(o, out) { + let o = choose|o: language::Regex| (m.ops)(r).contains(o) && #[trigger] (m.prod)(o, out); + cs.to_set_ensures(); + assert(cs.contains(o)); + let i = cs.lemma_contains_to_index(o); + lemma_regex_child_vocab(r, i); + lemma_model_product_vocab(o, out); + lemma_sops_vocab(false, r, allowed); + } else { lemma_model_literal_vocab(r, out); } + }, + language::Regex::Intersect(_) | language::Regex::Not(_) => { + assert forall|w: language::Regex| (m.lit)(r, w) implies regex_primitives(w).subset_of(allowed) by { + lemma_model_literal_vocab(r, w); + } + lemma_built_vocab(true, |w: language::Regex| (m.lit)(r, w), out, allowed); + }, + language::Regex::Star(_) => { lemma_model_literal_vocab(r, out); }, + language::Regex::Concat(cs) => { + if (m.lit)(r, out) { lemma_model_literal_vocab(r, out); } + else { + lemma_model_product_vocab(cs.last(), out); + lemma_regex_child_vocab(r, cs.len() as int - 1); + } + }, + _ => {}, + } + } else { lemma_model_constant_vocab(out); } + } + + pub proof fn lemma_model_successor_vocab(r: language::Regex, out: language::Regex) + requires crate::verify::finite_impl::regex_nf(r), (crate::verify::finite_impl::m_impl().succ)(r, out), + ensures regex_primitives(out).subset_of(regex_primitives(r)), + { + let m = crate::verify::finite_impl::m_impl(); + let allowed = regex_primitives(r); + crate::verify::finite_impl::theorem_impl_contract(); + crate::verify::finite_impl::lemma_models_agree(); + if !m.base_kind(r) { + assert forall|w: language::Regex| (m.prod)(r, w) implies regex_primitives(w).subset_of(allowed) by { + lemma_model_product_vocab(r, w); + } + lemma_built_vocab(false, |w: language::Regex| (m.prod)(r, w), out, allowed); + } else { lemma_model_constant_vocab(out); } + } + + /// Stack availability is independent of whether a truth word has a realizing event. + pub open spec fn test_stack_result(g: model::Graph, tasks: Seq<(TestId, bool)>, depth: nat) -> Option + decreases tasks.len(), + { + if tasks.len() == 0 { Some(depth) } else { + let task = tasks.last(); + let needed = if task.1 { test_children(g, task.0).len() } else { 0 }; + if depth < needed { None } + else { test_stack_result(g, tasks.drop_last(), (depth - needed + 1) as nat) } + } + } + + pub proof fn test_stack_task(g: model::Graph, pending: Seq<(TestId, bool)>, task: (TestId, bool), depth: nat) + ensures test_stack_result(g, pending.push(task), depth) == { + let needed = if task.1 { test_children(g, task.0).len() } else { 0 }; + if depth < needed { None } else { test_stack_result(g, pending, (depth - needed + 1) as nat) } + }, + { + assert(pending.push(task).drop_last() =~= pending); + } + + pub open spec fn interp_stack_needed(g: model::Graph, task: (TransitionId, bool)) -> nat { + if !task.1 { 0 } else { + match g.transitions[task.0@ as int] { + model::TransitionNode::Union(cs) | model::TransitionNode::Intersect(cs) => cs.len(), + model::TransitionNode::Not(_) | model::TransitionNode::Append(_, _) => 1, + _ => 0, + } + } + } + + pub open spec fn interp_stack_result(g: model::Graph, tasks: Seq<(TransitionId, bool)>, depth: nat) -> Option + decreases tasks.len(), + { + if tasks.len() == 0 { Some(depth) } else { + let needed = interp_stack_needed(g, tasks.last()); + if depth < needed { None } + else { interp_stack_result(g, tasks.drop_last(), (depth - needed + 1) as nat) } + } + } + + pub proof fn interp_stack_task(g: model::Graph, pending: Seq<(TransitionId, bool)>, task: (TransitionId, bool), depth: nat) + ensures interp_stack_result(g, pending.push(task), depth) == { + let needed = interp_stack_needed(g, task); + if depth < needed { None } else { interp_stack_result(g, pending, (depth - needed + 1) as nat) } + }, + { + assert(pending.push(task).drop_last() =~= pending); + } + + pub proof fn test_stack_children(g: model::Graph, id: TestId, remaining: nat, pending: Seq<(TestId, bool)>, depth: nat) + requires remaining <= test_children(g, id).len(), + ensures test_stack_result(g, pending + child_test_tasks(g, id, remaining), depth) + == test_stack_result(g, pending, (depth + test_children(g, id).len() - remaining) as nat), + decreases test_children(g, id).len() - remaining, + { + let children = child_test_tasks(g, id, remaining); + if remaining < test_children(g, id).len() { + assert(children.drop_last() =~= child_test_tasks(g, id, remaining + 1)); + assert(!children.last().1); + assert((pending + children).drop_last() =~= pending + children.drop_last()); + test_stack_children(g, id, remaining + 1, pending, depth + 1); + } else { assert(children =~= Seq::empty()); } + } + + pub proof fn interp_stack_children(g: model::Graph, id: TransitionId, remaining: nat, pending: Seq<(TransitionId, bool)>, depth: nat) + requires remaining <= transition_children(g, id).len(), + ensures interp_stack_result(g, pending + child_interp_tasks(g, id, remaining), depth) + == interp_stack_result(g, pending, (depth + transition_children(g, id).len() - remaining) as nat), + decreases transition_children(g, id).len() - remaining, + { + let children = child_interp_tasks(g, id, remaining); + if remaining < transition_children(g, id).len() { + assert(children.drop_last() =~= child_interp_tasks(g, id, remaining + 1)); + assert(!children.last().1); + assert((pending + children).drop_last() =~= pending + children.drop_last()); + interp_stack_children(g, id, remaining + 1, pending, depth + 1); + } else { assert(children =~= Seq::empty()); } + } + + pub proof fn interp_stack_stable(before: model::Graph, after: model::Graph, tasks: Seq<(TransitionId, bool)>, depth: nat) + requires model::graph_extends(before, after), interp_tasks_wf(before, tasks), + ensures interp_stack_result(before, tasks, depth) == interp_stack_result(after, tasks, depth), + tasks.len() > 0 ==> interp_stack_needed(before, tasks.last()) == interp_stack_needed(after, tasks.last()), + decreases tasks.len(), + { + if tasks.len() > 0 { + let needed = interp_stack_needed(before, tasks.last()); + assert(before.transitions[tasks.last().0@ as int] == after.transitions[tasks.last().0@ as int]); + if needed <= depth { interp_stack_stable(before, after, tasks.drop_last(), (depth - needed + 1) as nat); } + } + } + + pub open spec fn test_atoms_covered(g: model::Graph, root: nat, atoms: Seq) -> bool { + forall|p: model::Primitive| reach::test_reaches_primitive(g, root, p) ==> reach::has_positive(g, atoms, p) + } + + pub open spec fn test_tasks_covered(g: model::Graph, tasks: Seq<(TestId, bool)>, atoms: Seq) -> bool { + forall|i: int| 0 <= i < tasks.len() ==> test_atoms_covered(g, tasks[i].0@, atoms) + } + + pub open spec fn interp_tasks_covered(g: model::Graph, tasks: Seq<(TransitionId, bool)>, atoms: Seq) -> bool { + forall|i: int| 0 <= i < tasks.len() ==> reach::atoms_wf(g, tasks[i].0@, atoms) + } + + pub proof fn test_coverage_children(g: model::Graph, root: TestId, atoms: Seq) + requires model::graph_wf(g), root@ < g.tests.len(), test_atoms_covered(g, root@, atoms), + ensures forall|i: int| 0 <= i < test_children(g, root).len() + ==> test_atoms_covered(g, test_children(g, root)[i], atoms), + { + model::lemma_graph_test_wf(g, root@); + assert forall|i: int| 0 <= i < test_children(g, root).len() + implies test_atoms_covered(g, test_children(g, root)[i], atoms) by { + assert forall|p: model::Primitive| reach::test_reaches_primitive(g, test_children(g, root)[i], p) + implies reach::has_positive(g, atoms, p) by { + assert(reach::test_edges(g, root@)[i] == test_children(g, root)[i]); + assert(reach::test_reaches_primitive(g, root@, p)); + } + } + } + + pub proof fn transition_coverage_children(g: model::Graph, root: TransitionId, atoms: Seq) + requires model::graph_wf(g), root@ < g.transitions.len(), reach::atoms_wf(g, root@, atoms), + ensures (forall|i: int| 0 <= i < reach::transition_edges(g, root@).len() + ==> reach::atoms_wf(g, reach::transition_edges(g, root@)[i], atoms)), + forall|i: int| 0 <= i < reach::transition_tests(g, root@).len() + ==> test_atoms_covered(g, reach::transition_tests(g, root@)[i], atoms), + { + model::lemma_graph_transition_wf(g, root@); + assert forall|i: int| 0 <= i < reach::transition_edges(g, root@).len() + implies reach::atoms_wf(g, reach::transition_edges(g, root@)[i], atoms) by { + assert forall|p: model::Primitive| reach::transition_reaches_primitive(g, reach::transition_edges(g, root@)[i], p) + implies reach::has_positive(g, atoms, p) by { + assert(reach::transition_reaches_primitive(g, root@, p)); + } + } + assert forall|i: int| 0 <= i < reach::transition_tests(g, root@).len() + implies test_atoms_covered(g, reach::transition_tests(g, root@)[i], atoms) by { + assert forall|p: model::Primitive| reach::test_reaches_primitive(g, reach::transition_tests(g, root@)[i], p) + implies reach::has_positive(g, atoms, p) by { + assert(reach::transition_reaches_primitive(g, root@, p)); + } + } + } + + pub proof fn interp_coverage_stable(before: model::Graph, after: model::Graph, tasks: Seq<(TransitionId, bool)>, atoms: Seq) + requires model::graph_wf(before), model::graph_extends(before, after), interp_tasks_wf(before, tasks), + interp_tasks_covered(before, tasks, atoms), + ensures interp_tasks_covered(after, tasks, atoms), + { + assert forall|i: int| 0 <= i < tasks.len() implies reach::atoms_wf(after, tasks[i].0@, atoms) by { + reach::lemma_atoms_wf_extends(before, after, tasks[i].0@, atoms); + } + } + + pub proof fn interp_coverage_push(g: model::Graph, tasks: Seq<(TransitionId, bool)>, task: (TransitionId, bool), atoms: Seq) + requires interp_tasks_covered(g, tasks, atoms), reach::atoms_wf(g, task.0@, atoms), + ensures interp_tasks_covered(g, tasks.push(task), atoms), + { + assert forall|i: int| 0 <= i < tasks.push(task).len() implies reach::atoms_wf(g, tasks.push(task)[i].0@, atoms) by { + if i < tasks.len() { assert(tasks.push(task)[i] == tasks[i]); } + else { assert(tasks.push(task)[i] == task); } + } + } + + pub proof fn interp_coverage_pop(g: model::Graph, tasks: Seq<(TransitionId, bool)>, task: (TransitionId, bool), atoms: Seq) + requires interp_tasks_covered(g, tasks.push(task), atoms), + ensures interp_tasks_covered(g, tasks, atoms), reach::atoms_wf(g, task.0@, atoms), + { + assert(tasks.push(task)[tasks.len() as int] == task); + assert forall|i: int| 0 <= i < tasks.len() implies reach::atoms_wf(g, tasks[i].0@, atoms) by { + assert(tasks.push(task)[i] == tasks[i]); + } + } + + pub proof fn assignment_index_bound(count: nat, words: Seq, index: usize) + requires assignment_valid(count, words), index < count, + ensures index / 64 < words.len(), + { + vstd::arithmetic::div_mod::lemma_fundamental_div_mod(index as int, 64); + vstd::arithmetic::div_mod::lemma_fundamental_div_mod((count + 63) as int, 64); + assert(index / 64 * 64 <= index); + assert((count + 63) / 64 * 64 > count - 1); + } + pub open spec fn truth_word_bit(words: Seq, index: nat) -> bool { + index / 64 < words.len() + && ((words[(index / 64) as int] >> ((index % 64) as u32)) & 1u64) != 0 + } + + pub open spec fn truth_words_realize( + g: model::Graph, atoms: Seq, words: Seq, theta: Subst, event: EventView, + ) -> bool { + forall|i: int| 0 <= i < atoms.len() ==> #[trigger] truth_word_bit(words, i as nat) + == model::test_holds(theta, model::lift_test(g, atoms[i]@), event) + } + + pub proof fn truth_words_realize_extends( + before: model::Graph, after: model::Graph, atoms: Seq, words: Seq, + ) + requires model::graph_extends(before, after), model::atom_ids_wf(before, atoms), + ensures model::atom_ids_wf(after, atoms), + forall|theta: Subst, event: EventView| + truth_words_realize(before, atoms, words, theta, event) + == truth_words_realize(after, atoms, words, theta, event), + { + assert forall|i: int| 0 <= i < atoms.len() implies atoms[i]@ < after.tests.len() + && #[trigger] after.tests[atoms[i]@ as int] matches model::TestNode::Atom(_, true) by { + assert(after.tests[atoms[i]@ as int] == before.tests[atoms[i]@ as int]); + } + assert forall|i: int| 0 <= i < atoms.len() implies + model::lift_test(before, atoms[i]@) == model::lift_test(after, atoms[i]@) by { + model::lemma_lift_test_stable(before, after, atoms[i]@); + } + } + + pub proof fn symbolic_not_result(g: model::Graph, root: TransitionId, out: TransitionId) + requires norm::transition_result(g, norm::ActionShape::Not(root@), out), + ensures forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> norm::transition_lang(g, theta, out, event, word) == !norm::transition_lang(g, theta, root, event, word), + { + let task = norm::ActionShape::Not(root@); + let expected = norm::transition_initial_value(g, task).unwrap(); + norm::transition_lemma_result_refines(g, task, out); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies norm::transition_lang(g, theta, out, event, word) == !norm::transition_lang(g, theta, root, event, word) by { + let ctx = norm::TransitionContext { bindings: theta }; + norm::transition_lemma_context_sem(ctx); + language::lemma_interp_not(model::gsem(theta), event, model::lift_transition(g, root@)); + assert((expected.guard)(ctx, event)); + assert(norm::guarded_language(norm::transition_context_sem(), ctx, event, expected, word) + == norm::guarded_language(norm::transition_context_sem(), ctx, event, norm::transition_known(g, out), word)); + norm::transition_lemma_known_language(g, out, ctx, event, word); + } + } + + pub proof fn symbolic_intersect_result(g: model::Graph, ids: Seq, out: TransitionId) + requires norm::transition_result(g, norm::ActionShape::Fold(model::transition_ids(ids), 0), out), + ensures forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> norm::transition_lang(g, theta, out, event, word) == norm::transition_combo(g, theta, ids, event, word, true), + { + let task = norm::ActionShape::Fold(model::transition_ids(ids), 0); + let expected = norm::transition_initial_value(g, task).unwrap(); + let terms = model::transition_ids(ids).map(|i: int, id: nat| model::lift_transition(g, id)); + norm::transition_lemma_result_refines(g, task, out); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies norm::transition_lang(g, theta, out, event, word) == norm::transition_combo(g, theta, ids, event, word, true) by { + let ctx = norm::TransitionContext { bindings: theta }; + norm::transition_lemma_context_sem(ctx); + language::lemma_interp_intersect(model::gsem(theta), event, terms, word); + assert forall|i: int| 0 <= i < ids.len() implies language::numeric_lang(model::gsem(theta), + language::interp_transition(model::gsem(theta), event, terms[i]), word) + == norm::transition_lang(g, theta, ids[i], event, word) by { + assert(terms[i] == model::lift_transition(g, ids[i]@)); + } + assert((expected.guard)(ctx, event)); + assert(norm::guarded_language(norm::transition_context_sem(), ctx, event, expected, word) + == norm::guarded_language(norm::transition_context_sem(), ctx, event, norm::transition_known(g, out), word)); + norm::transition_lemma_known_language(g, out, ctx, event, word); + } + } + + + pub open spec fn derivative_correct(g: model::Graph, root: nat, out: TransitionId) -> bool { + root < g.regexes.len() && out@ < g.transitions.len() + && forall|theta: Subst, event: EventView, word: Seq| + language::event_wf(theta, theta.len()) ==> norm::transition_lang(g, theta, out, event, word) + == model::regex_lang(g, theta, root, seq![event] + word) + } + + /// The runtime derivative agrees, modulo language, with the independent δ. + pub proof fn lemma_derivative_correct_is_symbolic_derivative(g: model::Graph, root: nat, out: TransitionId, theta: Subst, event: EventView, word: Seq) + requires derivative_correct(g, root, out), language::event_wf(theta, theta.len()), + ensures norm::transition_lang(g, theta, out, event, word) + == language::numeric_lang(model::gsem(theta), language::interp_transition(model::gsem(theta), event, algebra::symbolic_derivative(model::lift_regex(g, root))), word), + { + algebra::lemma_symbolic_derivative_correct(model::gsem(theta), event, model::lift_regex(g, root), word); + } + + pub proof fn lemma_regex_graph_child_vocab(g: model::Graph, root: nat, child: nat) + requires model::graph_wf(g), root < g.regexes.len(), + match g.regexes[root as int].kind { + model::RegexKindNode::Star(c) | model::RegexKindNode::Not(c) => child == c, + model::RegexKindNode::Union(cs) | model::RegexKindNode::Intersect(cs) | model::RegexKindNode::Concat(cs) => cs.contains(child), + _ => false, + }, + ensures child < g.regexes.len(), regex_primitives(model::lift_regex(g, child)).subset_of(regex_primitives(model::lift_regex(g, root))), + { + model::lemma_graph_regex_wf(g, root); + norm::regex_unfold(g, root); + match g.regexes[root as int].kind { + model::RegexKindNode::Union(cs) | model::RegexKindNode::Intersect(cs) | model::RegexKindNode::Concat(cs) => { + let i = cs.lemma_contains_to_index(child); + lemma_regex_child_vocab(model::lift_regex(g, root), i); + }, + _ => {}, + } + } + + pub open spec fn derivative_results_vocab(g: model::Graph, root: nat, results: Seq) -> bool { + forall|i: int| 0 <= i < results.len() ==> derivative_vocab(g, root, results[i]@) + } + + pub proof fn lemma_derivative_results_vocab_stable(a: model::Graph, b: model::Graph, root: nat, results: Seq) + requires model::graph_wf(a), model::graph_extends(a, b), root < a.regexes.len(), + norm::transition_ids_valid(a, results), derivative_results_vocab(a, root, results), + ensures derivative_results_vocab(b, root, results), + { + assert forall|i: int| 0 <= i < results.len() implies derivative_vocab(b, root, results[i]@) by { + lemma_derivative_vocab_stable(a, b, root, results[i]@); + } + } + + /// Every cached derivative is correct and has the class bound of its state + /// (`verify::finite_deriv::dbound`). + pub open spec fn derivative_cache_wf(g: model::Graph, cache: Seq>) -> bool { + forall|i: int| 0 <= i < cache.len() ==> match #[trigger] cache[i] { + Some(out) => derivative_correct(g, i as nat, out) && fder::dbound(g, i as nat, out@) + && derivative_vocab(g, i as nat, out@), None => true, + } + } + + pub proof fn derivative_cached_bound(g: model::Graph, cache: Seq>, id: RegexId, out: TransitionId) + requires derivative_cache_wf(g, cache), id@ < cache.len(), cache[id@ as int] == Some(out), + ensures out@ < g.transitions.len(), derivative_vocab(g, id@, out@), + {} + + pub proof fn derivative_cache_prefix_facts(before: Seq>, after: Seq>) + requires before.len() <= after.len(), before == after || before == after.subrange(0, before.len() as int), + ensures before.is_prefix_of(after), + forall|i: int| 0 <= i < before.len() ==> after[i] == before[i], + {} + + pub proof fn derivative_test_correct(g: model::Graph, root: RegexId, test: TestId, cache: Seq>, out: TransitionId, + then_id: TransitionId, else_id: TransitionId) + requires model::graph_wf(g), root@ < g.regexes.len(), derivative_cache_wf(g, cache), out@ < g.transitions.len(), + g.regexes[root@ as int].kind == model::RegexKindNode::Test(test@), + then_id@ == g.constants.transition_epsilon, else_id@ == g.constants.transition_empty, + forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> norm::transition_lang(g, theta, out, event, word) == norm::transition_if_combo(g, theta, test, + then_id, else_id, event, word), + ensures derivative_correct(g, root@, out), + { + derivative_constants(g); + assert(derivative_native_result(g, root, cache, out)); + derivative_native_correct(g, root, cache, out); + } + + pub proof fn derivative_graph_frame(before: model::Graph, after: model::Graph, root: RegexId) + requires model::graph_extends(before, after), root@ < before.regexes.len(), + ensures root@ < after.regexes.len(), after.regexes[root@ as int] == before.regexes[root@ as int], + after.constants == before.constants, + {} + + pub proof fn derivative_correct_bounds(g: model::Graph, root: nat, out: TransitionId) + requires derivative_correct(g, root, out), + ensures root < g.regexes.len(), out@ < g.transitions.len(), + {} + + pub open spec fn derivative_tasks_wf(g: model::Graph, tasks: Seq<(RegexId, bool)>) -> bool { + forall|i: int| 0 <= i < tasks.len() ==> #[trigger] tasks[i].0@ < g.regexes.len() + } + + pub open spec fn derivative_tasks_bounded(tasks: Seq<(RegexId, bool)>, bound: nat) -> bool { + forall|i: int| 0 <= i < tasks.len() ==> tasks[i].0@ <= bound + } + + pub open spec fn cache_complete(cache: Seq>, id: nat) -> bool { + id < cache.len() && cache[id as int] is Some + } + + pub open spec fn cache_completions_preserved(before: Seq>, after: Seq>) -> bool { + forall|id: nat| cache_complete(before, id) ==> cache_complete(after, id) + } + + pub open spec fn tasks_contain(tasks: Seq<(RegexId, bool)>, id: nat) -> bool { + exists|i: int| 0 <= i < tasks.len() && tasks[i].0@ == id + } + + pub open spec fn derivative_dependency(g: model::Graph, root: RegexId, child: nat) -> bool { + match g.regexes[root@ as int].kind { + model::RegexKindNode::Star(id) | model::RegexKindNode::Not(id) => child == id, + model::RegexKindNode::Union(cs) | model::RegexKindNode::Intersect(cs) => cs.contains(child), + model::RegexKindNode::Concat(cs) => exists|i: int| 0 <= i < cs.len() && cs[i] == child + && derivative_prefix(g, root, i as nat), + _ => false, + } + } + + pub open spec fn derivative_dependencies_complete(g: model::Graph, root: RegexId, cache: Seq>) -> bool { + forall|child: nat| derivative_dependency(g, root, child) ==> cache_complete(cache, child) + } + + pub proof fn derivative_cache_extend_dependencies(g: model::Graph, root: RegexId, + before: Seq>, after: Seq>) + requires before.is_prefix_of(after), derivative_dependencies_complete(g, root, before), + ensures derivative_dependencies_complete(g, root, after), + { + after.lemma_prefix_index_eq(before); + assert forall|child: nat| derivative_dependency(g, root, child) implies cache_complete(after, child) by { + assert(cache_complete(before, child)); + assert(after[child as int] == before[child as int]); + } + } + + pub proof fn derivative_unary_complete(g: model::Graph, root: RegexId, inner: RegexId, cache: Seq>) + requires derivative_dependencies_complete(g, root, cache), + g.regexes[root@ as int].kind == model::RegexKindNode::Star(inner@) + || g.regexes[root@ as int].kind == model::RegexKindNode::Not(inner@), + ensures cache_complete(cache, inner@), + { + assert(derivative_dependency(g, root, inner@)); + } + + pub proof fn derivative_unary_scheduled(g: model::Graph, root: RegexId, pending: Seq<(RegexId, bool)>, inner: RegexId) + requires g.regexes[root@ as int].kind == model::RegexKindNode::Star(inner@) + || g.regexes[root@ as int].kind == model::RegexKindNode::Not(inner@), + ensures derivative_scheduled(g, root, pending, pending.push((root, true)).push((inner, false))), + { + let tasks = pending.push((root, true)).push((inner, false)); + assert(pending =~= tasks.subrange(0, pending.len() as int)); + assert forall|child: nat| derivative_dependency(g, root, child) + implies exists|j: int| pending.len() < j < tasks.len() && tasks[j].0@ == child by { + assert(child == inner@); + assert(tasks[pending.len() as int + 1].0@ == child); + } + } + + pub proof fn derivative_scheduled_facts(g: model::Graph, root: RegexId, pending: Seq<(RegexId, bool)>, tasks: Seq<(RegexId, bool)>) + requires derivative_scheduled(g, root, pending, tasks), + ensures pending.is_prefix_of(tasks), tasks_contain(tasks, root@), + { + assert(tasks[pending.len() as int] == (root, true)); + } + + /// A finishing task may rely only on a completed cache entry or work above it. + pub open spec fn derivative_tasks_ready(g: model::Graph, tasks: Seq<(RegexId, bool)>, cache: Seq>) -> bool { + forall|i: int, child: nat| 0 <= i < tasks.len() && tasks[i].1 + && derivative_dependency(g, tasks[i].0, child) ==> cache_complete(cache, child) + || exists|j: int| i < j < tasks.len() && tasks[j].0@ == child + } + + pub open spec fn derivative_scheduled(g: model::Graph, root: RegexId, + pending: Seq<(RegexId, bool)>, tasks: Seq<(RegexId, bool)>) -> bool { + pending.is_prefix_of(tasks) && pending.len() < tasks.len() && tasks[pending.len() as int] == (root, true) + && (forall|i: int| pending.len() < i < tasks.len() ==> !tasks[i].1) + && forall|child: nat| derivative_dependency(g, root, child) + ==> exists|j: int| pending.len() < j < tasks.len() && tasks[j].0@ == child + } + + pub proof fn derivative_ready_top(g: model::Graph, tasks: Seq<(RegexId, bool)>, cache: Seq>) + requires tasks.len() > 0, derivative_tasks_ready(g, tasks, cache), + ensures tasks.last().1 ==> derivative_dependencies_complete(g, tasks.last().0, cache), + { + assert forall|child: nat| tasks.last().1 && derivative_dependency(g, tasks.last().0, child) + implies cache_complete(cache, child) by { + assert(tasks[tasks.len() - 1] == tasks.last()); + } + } + + pub proof fn derivative_ready_after_step(before: model::Graph, after: model::Graph, root: RegexId, finish: bool, + pending: Seq<(RegexId, bool)>, tasks: Seq<(RegexId, bool)>, cache0: Seq>, cache1: Seq>) + requires model::graph_wf(before), model::graph_extends(before, after), root@ < before.regexes.len(), + derivative_tasks_wf(before, pending), derivative_tasks_ready(before, pending.push((root, finish)), cache0), + cache_completions_preserved(cache0, cache1), + tasks == pending && cache_complete(cache1, root@) || derivative_scheduled(before, root, pending, tasks), + ensures derivative_tasks_ready(after, tasks, cache1), + { + let queued = pending.push((root, finish)); + after.regexes.lemma_prefix_index_eq(before.regexes); + if tasks != pending { tasks.lemma_prefix_index_eq(pending); } + assert forall|i: int, child: nat| 0 <= i < tasks.len() && tasks[i].1 + && derivative_dependency(after, tasks[i].0, child) implies cache_complete(cache1, child) + || exists|j: int| i < j < tasks.len() && tasks[j].0@ == child by { + if i < pending.len() { + assert(tasks[i] == pending[i]); + assert(queued[i] == pending[i]); + assert(queued[i].1); + derivative_factor_stable(before, after, pending[i].0); + assert(before.regexes[pending[i].0@ as int] == after.regexes[pending[i].0@ as int]); + assert(derivative_dependency(before, queued[i].0, child)); + if cache_complete(cache0, child) { + assert(cache_complete(cache1, child)); + } else { + assert(exists|j: int| i < j < queued.len() && queued[j].0@ == child); + let j = choose|j: int| i < j < queued.len() && queued[j].0@ == child; + if j < pending.len() { + assert(queued[j] == pending[j]); + assert(tasks[j] == pending[j]); + assert(exists|k: int| i < k < tasks.len() && tasks[k].0@ == child); + } else { + assert(j == pending.len()); + assert(child == root@); + if tasks == pending { assert(cache_complete(cache1, child)); } + else { + assert(tasks[pending.len() as int] == (root, true)); + assert(exists|k: int| i < k < tasks.len() && tasks[k].0@ == child); + } + } + } + } else { + assert(tasks != pending); + assert(i == pending.len()); + assert(tasks[i] == (root, true)); + derivative_factor_stable(before, after, root); + assert(before.regexes[root@ as int] == after.regexes[root@ as int]); + assert(derivative_dependency(before, root, child)); + let j = choose|j: int| pending.len() < j < tasks.len() && tasks[j].0@ == child; + assert(i < j); + } + } + } + + pub open spec fn derivative_node_work(g: model::Graph, id: nat) -> nat + decreases id, 1nat, + { + if id >= g.regexes.len() { 0 } else { + match g.regexes[id as int].kind { + model::RegexKindNode::Union(cs) | model::RegexKindNode::Intersect(cs) | model::RegexKindNode::Concat(cs) => + 2 + derivative_children_work(g, cs, id), + model::RegexKindNode::Star(c) | model::RegexKindNode::Not(c) => + 2 + if c < id { derivative_node_work(g, c) } else { 0 }, + _ => 1, + } + } + } + + pub open spec fn derivative_children_work(g: model::Graph, children: Seq, bound: nat) -> nat + decreases bound, 0nat, children.len(), + { + if children.len() == 0 { 0 } else { + derivative_children_work(g, children.skip(1), bound) + + if children[0] < bound { derivative_node_work(g, children[0]) } else { 0 } + } + } + + pub open spec fn derivative_work(g: model::Graph, tasks: Seq<(RegexId, bool)>) -> nat + decreases tasks.len(), + { + if tasks.len() == 0 { 0 } else { + derivative_work(g, tasks.drop_last()) + + if tasks.last().1 { 1 } else { derivative_node_work(g, tasks.last().0@) } + } + } + + pub proof fn derivative_lemma_node_work_extends(a: model::Graph, b: model::Graph, id: nat) + requires model::graph_extends(a, b), id < a.regexes.len(), + ensures derivative_node_work(a, id) == derivative_node_work(b, id), + decreases id, 1nat, + { + assert(a.regexes[id as int] == b.regexes[id as int]); + match a.regexes[id as int].kind { + model::RegexKindNode::Union(cs) => { derivative_lemma_children_work_extends(a, b, cs, id); }, + model::RegexKindNode::Intersect(cs) => { derivative_lemma_children_work_extends(a, b, cs, id); }, + model::RegexKindNode::Concat(cs) => { derivative_lemma_children_work_extends(a, b, cs, id); }, + model::RegexKindNode::Star(c) => { if c < id { derivative_lemma_node_work_extends(a, b, c); } }, + model::RegexKindNode::Not(c) => { if c < id { derivative_lemma_node_work_extends(a, b, c); } }, + _ => {}, + } + } + + pub proof fn derivative_lemma_children_work_extends(a: model::Graph, b: model::Graph, children: Seq, bound: nat) + requires model::graph_extends(a, b), bound <= a.regexes.len(), + ensures derivative_children_work(a, children, bound) == derivative_children_work(b, children, bound), + decreases bound, 0nat, children.len(), + { + if children.len() > 0 { + if children[0] < bound { derivative_lemma_node_work_extends(a, b, children[0]); } + derivative_lemma_children_work_extends(a, b, children.skip(1), bound); + } + } + + pub proof fn derivative_lemma_work_extends(a: model::Graph, b: model::Graph, tasks: Seq<(RegexId, bool)>) + requires model::graph_extends(a, b), derivative_tasks_wf(a, tasks), + ensures derivative_work(a, tasks) == derivative_work(b, tasks), + decreases tasks.len(), + { + if tasks.len() > 0 { + assert(tasks.last() == tasks[tasks.len() - 1]); + if !tasks.last().1 { derivative_lemma_node_work_extends(a, b, tasks.last().0@); } + assert forall|i: int| 0 <= i < tasks.drop_last().len() implies #[trigger] tasks.drop_last()[i].0@ < a.regexes.len() by { + assert(tasks.drop_last()[i] == tasks[i]); + } + derivative_lemma_work_extends(a, b, tasks.drop_last()); + } + } + + pub proof fn derivative_lemma_work_push(g: model::Graph, tasks: Seq<(RegexId, bool)>, task: (RegexId, bool)) + ensures derivative_work(g, tasks.push(task)) + == derivative_work(g, tasks) + if task.1 { 1 } else { derivative_node_work(g, task.0@) }, + { + assert(tasks.push(task).drop_last() =~= tasks); + } + + /// Concat schedules only its nullable prefix, so the scheduled tasks are a prefix of the children. + pub proof fn derivative_lemma_work_schedule_prefix(g: model::Graph, tasks: Seq<(RegexId, bool)>, + scheduled: Seq<(RegexId, bool)>, children: Seq, bound: nat) + requires scheduled.len() <= children.len(), model::bounded(children, bound), + forall|i: int| 0 <= i < scheduled.len() ==> #[trigger] scheduled[i].0@ == children[i] && !scheduled[i].1, + ensures derivative_work(g, tasks + scheduled) <= derivative_work(g, tasks) + derivative_children_work(g, children, bound), + decreases scheduled.len(), + { + if scheduled.len() == 0 { + assert(tasks + scheduled =~= tasks); + } else { + let rest = scheduled.skip(1); + assert(tasks + scheduled =~= tasks.push(scheduled[0]) + rest); + assert(children[0] < bound); + assert forall|i: int| 0 <= i < rest.len() implies #[trigger] rest[i].0@ == children.skip(1)[i] && !rest[i].1 by { + assert(rest[i] == scheduled[i + 1]); + } + assert forall|i: int| 0 <= i < children.skip(1).len() implies #[trigger] children.skip(1)[i] < bound by { + assert(children.skip(1)[i] == children[i + 1]); + } + derivative_lemma_work_schedule_prefix(g, tasks.push(scheduled[0]), rest, children.skip(1), bound); + derivative_lemma_work_push(g, tasks, scheduled[0]); + } + } + + pub proof fn derivative_lemma_work_unary(g: model::Graph, id: RegexId, pending: Seq<(RegexId, bool)>, inner: RegexId) + requires model::graph_wf(g), id@ < g.regexes.len(), derivative_tasks_wf(g, pending), + g.regexes[id@ as int].kind == model::RegexKindNode::Star(inner@) + || g.regexes[id@ as int].kind == model::RegexKindNode::Not(inner@), + ensures derivative_tasks_wf(g, pending.push((id, true)).push((inner, false))), + derivative_work(g, pending.push((id, true)).push((inner, false))) < derivative_work(g, pending.push((id, false))), + { + model::lemma_graph_regex_wf(g, id@); + derivative_lemma_work_push(g, pending, (id, true)); + derivative_lemma_work_push(g, pending.push((id, true)), (inner, false)); + derivative_lemma_work_push(g, pending, (id, false)); + let all = pending.push((id, true)).push((inner, false)); + assert forall|i: int| 0 <= i < all.len() implies #[trigger] all[i].0@ < g.regexes.len() by { + if i < pending.len() { assert(all[i] == pending[i]); } + } + } + + pub proof fn derivative_lemma_work_branch(g: model::Graph, id: RegexId, pending: Seq<(RegexId, bool)>, tasks: Seq<(RegexId, bool)>) + requires model::graph_wf(g), id@ < g.regexes.len(), derivative_tasks_wf(g, pending), + g.regexes[id@ as int].kind is Union || g.regexes[id@ as int].kind is Intersect + || g.regexes[id@ as int].kind is Concat, + pending.push((id, true)).is_prefix_of(tasks), + tasks.len() <= pending.len() + 1 + derivative_children_ids(g, id).len(), + forall|j: int| pending.len() + 1 <= j < tasks.len() ==> #[trigger] tasks[j].0@ + == derivative_children_ids(g, id)[j - pending.len() - 1] && !tasks[j].1, + ensures derivative_tasks_wf(g, tasks), + derivative_work(g, tasks) < derivative_work(g, pending.push((id, false))), + { + model::lemma_graph_regex_wf(g, id@); + let cs = derivative_children_ids(g, id); + let base = pending.push((id, true)); + let scheduled = tasks.subrange(base.len() as int, tasks.len() as int); + assert(tasks =~= base + scheduled); + assert forall|i: int| 0 <= i < scheduled.len() implies #[trigger] scheduled[i].0@ == cs[i] && !scheduled[i].1 by { + assert(scheduled[i] == tasks[base.len() + i]); + } + derivative_lemma_work_schedule_prefix(g, base, scheduled, cs, id@); + derivative_lemma_work_push(g, pending, (id, true)); + derivative_lemma_work_push(g, pending, (id, false)); + assert forall|i: int| 0 <= i < tasks.len() implies #[trigger] tasks[i].0@ < g.regexes.len() by { + if i < pending.len() { assert(tasks[i] == base[i]); assert(base[i] == pending[i]); } + else if i > pending.len() { assert(tasks[i].0@ == cs[i - pending.len() - 1]); } + else { assert(tasks[i] == base[i]); } + } + } + + pub proof fn derivative_lemma_step_post(before: model::Graph, after: model::Graph, id: RegexId, finish: bool, + pending: Seq<(RegexId, bool)>, tasks: Seq<(RegexId, bool)>) + requires model::graph_extends(before, after), id@ < before.regexes.len(), derivative_tasks_wf(before, pending), + tasks == pending || (derivative_tasks_wf(before, tasks) + && derivative_work(before, tasks) < derivative_work(before, pending.push((id, finish)))), + ensures derivative_work(after, tasks) < derivative_work(before, pending.push((id, finish))), + { + derivative_lemma_work_push(before, pending, (id, finish)); + derivative_lemma_work_extends(before, after, tasks); + } + + pub open spec fn derivative_children_ids(g: model::Graph, root: RegexId) -> Seq { + match g.regexes[root@ as int].kind { + model::RegexKindNode::Union(cs) | model::RegexKindNode::Intersect(cs) | model::RegexKindNode::Concat(cs) => cs, + _ => Seq::empty(), + } + } + + pub open spec fn derivative_factors_wf(g: model::Graph, root: RegexId, count: nat, concat: bool) -> bool { + root@ < g.regexes.len() && match g.regexes[root@ as int].kind { + model::RegexKindNode::Concat(cs) => concat && cs.len() == count, + model::RegexKindNode::Union(cs) | model::RegexKindNode::Intersect(cs) => !concat && cs.len() == count, + _ => false, + } + } + + pub open spec fn derivative_prefix(g: model::Graph, root: RegexId, index: nat) -> bool { + forall|i: int| 0 <= i < index ==> language::nullable(model::lift_regex(g, derivative_children_ids(g, root)[i])) + } + + pub open spec fn derivative_factor_language( + g: model::Graph, root: RegexId, concat: bool, index: int, + theta: Subst, event: EventView, word: Seq, + ) -> bool { + let cs = derivative_children_ids(g, root); + let sem = model::gsem(theta); + if concat { + language::numeric_lang(sem, language::Regex::Concat(seq![language::derivative(sem, event, model::lift_regex(g, cs[index]))] + + model::lift_regexes(g, cs.subrange(index + 1, cs.len() as int))), word) + } else { model::regex_lang(g, theta, cs[index], seq![event] + word) } + } + + pub open spec fn derivative_factor_combo( + g: model::Graph, root: RegexId, concat: bool, count: nat, intersect: bool, + theta: Subst, event: EventView, word: Seq, + ) -> bool { + if intersect { + forall|i: int| 0 <= i < count && (!concat || derivative_prefix(g, root, i as nat)) + ==> derivative_factor_language(g, root, concat, i, theta, event, word) + } else { + exists|i: int| 0 <= i < count && (!concat || derivative_prefix(g, root, i as nat)) + && derivative_factor_language(g, root, concat, i, theta, event, word) + } + } + + pub open spec fn derivative_results( + g: model::Graph, root: RegexId, concat: bool, count: nat, results: Seq, + ) -> bool { + norm::transition_ids_valid(g, results) + && forall|theta: Subst, event: EventView, word: Seq, intersect: bool| + language::event_wf(theta, theta.len()) ==> norm::transition_combo(g, theta, results, event, word, intersect) + == derivative_factor_combo(g, root, concat, count, intersect, theta, event, word) + } + + pub proof fn derivative_factor_stable(a: model::Graph, b: model::Graph, root: RegexId) + requires model::graph_wf(a), model::graph_extends(a, b), root@ < a.regexes.len(), + ensures derivative_children_ids(a, root) == derivative_children_ids(b, root), + forall|n: nat| n <= derivative_children_ids(a, root).len() ==> derivative_prefix(a, root, n) == derivative_prefix(b, root, n), + forall|concat: bool, i: int, theta: Subst, event: EventView, word: Seq| + 0 <= i < derivative_children_ids(a, root).len() + ==> derivative_factor_language(a, root, concat, i, theta, event, word) + == derivative_factor_language(b, root, concat, i, theta, event, word), + { + hide(language::numeric_lang); hide(language::derivative); hide(language::interp_transition); + model::lemma_graph_wf_elim(a); + model::lemma_graph_regex_wf(a, root@); + model::lemma_lift_stable_under_extends(a, b); + let cs = derivative_children_ids(a, root); + assert forall|i: int| 0 <= i < cs.len() implies cs[i] < a.regexes.len() by {} + assert forall|i: int| 0 <= i < cs.len() implies + #[trigger] model::lift_regexes(a, cs.subrange(i + 1, cs.len() as int)) == model::lift_regexes(b, cs.subrange(i + 1, cs.len() as int)) by { + assert(model::lift_regexes(a, cs.subrange(i + 1, cs.len() as int)) =~= model::lift_regexes(b, cs.subrange(i + 1, cs.len() as int))); + } + } + + pub proof fn derivative_results_stable(a: model::Graph, b: model::Graph, root: RegexId, concat: bool, count: nat, results: Seq) + requires model::graph_wf(a), model::graph_extends(a, b), root@ < a.regexes.len(), + count <= derivative_children_ids(a, root).len(), derivative_results(a, root, concat, count, results), + ensures derivative_results(b, root, concat, count, results), + { + hide(language::numeric_lang); hide(language::derivative); hide(language::interp_transition); + hide(derivative_factor_language); hide(derivative_prefix); + derivative_factor_stable(a, b, root); + model::lemma_graph_wf_elim(a); + model::lemma_lift_stable_under_extends(a, b); + assert forall|theta: Subst, event: EventView, word: Seq, intersect: bool| + language::event_wf(theta, theta.len()) implies norm::transition_combo(b, theta, results, event, word, intersect) + == derivative_factor_combo(b, root, concat, count, intersect, theta, event, word) by { + assert forall|i: int| 0 <= i < results.len() implies + norm::transition_lang(a, theta, results[i], event, word) + == norm::transition_lang(b, theta, results[i], event, word) by {} + assert(norm::transition_combo(a, theta, results, event, word, intersect) + == norm::transition_combo(b, theta, results, event, word, intersect)); + assert(derivative_factor_combo(a, root, concat, count, intersect, theta, event, word) + == derivative_factor_combo(b, root, concat, count, intersect, theta, event, word)); + } + } + + pub proof fn derivative_correct_stable(a: model::Graph, b: model::Graph, root: nat, out: TransitionId) + requires model::graph_wf(a), model::graph_extends(a, b), derivative_correct(a, root, out), + ensures derivative_correct(b, root, out), + { + hide(language::numeric_lang); hide(language::interp_transition); hide(model::lift_regex); hide(model::lift_transition); + model::lemma_graph_wf_elim(a); + model::lemma_lift_regex_stable(a, b, root); + model::lemma_lift_transition_stable(a, b, out@); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies norm::transition_lang(b, theta, out, event, word) + == model::regex_lang(b, theta, root, seq![event] + word) by { + assert(norm::transition_lang(a, theta, out, event, word) + == model::regex_lang(a, theta, root, seq![event] + word)); + } + } + + #[verifier::spinoff_prover] + pub proof fn derivative_extends(a: model::Graph, b: model::Graph) + requires model::graph_wf(a), model::graph_extends(a, b), + ensures + forall|c: model::Graph| model::graph_extends(b, c) ==> model::graph_extends(a, c), + forall|root: nat, out: TransitionId| derivative_correct(a, root, out) ==> derivative_correct(b, root, out), + forall|cache: Seq>| derivative_cache_wf(a, cache) ==> derivative_cache_wf(b, cache), + forall|tasks: Seq<(RegexId, bool)>| derivative_tasks_wf(a, tasks) ==> derivative_tasks_wf(b, tasks), + forall|root: RegexId, count: nat, concat: bool| derivative_factors_wf(a, root, count, concat) ==> derivative_factors_wf(b, root, count, concat), + forall|root: RegexId, index: nat| root@ < a.regexes.len() && index <= derivative_children_ids(a, root).len() + ==> derivative_prefix(a, root, index) == derivative_prefix(b, root, index), + forall|root: RegexId, concat: bool, count: nat, results: Seq| + root@ < a.regexes.len() && count <= derivative_children_ids(a, root).len() && derivative_results(a, root, concat, count, results) + ==> derivative_results(b, root, concat, count, results), + { + hide(language::numeric_lang); hide(language::derivative); hide(language::interp_transition); + hide(model::test_holds); hide(model::lift_regex); hide(model::lift_transition); + hide(derivative_correct); hide(derivative_results); hide(derivative_prefix); hide(derivative_factor_language); + model::lemma_graph_wf_elim(a); + model::lemma_lift_stable_under_extends(a, b); + assert forall|c: model::Graph| model::graph_extends(b, c) implies model::graph_extends(a, c) by { + assert(a.tests.is_prefix_of(c.tests)); + assert(a.regexes.is_prefix_of(c.regexes)); + assert(a.transitions.is_prefix_of(c.transitions)); + } + assert forall|root: nat, out: TransitionId| derivative_correct(a, root, out) implies derivative_correct(b, root, out) by { + derivative_correct_stable(a, b, root, out); + } + assert forall|cache: Seq>| derivative_cache_wf(a, cache) implies derivative_cache_wf(b, cache) by { + assert forall|i: int| 0 <= i < cache.len() implies match #[trigger] cache[i] { + Some(out) => derivative_correct(b, i as nat, out) && fder::dbound(b, i as nat, out@) + && derivative_vocab(b, i as nat, out@), None => true, + } by { + if let Some(out) = cache[i] { + derivative_correct_bounds(a, i as nat, out); + fder::lemma_dbound_stable(a, b, i as nat, out@); + lemma_derivative_vocab_stable(a, b, i as nat, out@); + } + } + } + assert forall|root: RegexId, index: nat| root@ < a.regexes.len() && index <= derivative_children_ids(a, root).len() + implies derivative_prefix(a, root, index) == derivative_prefix(b, root, index) by { + derivative_factor_stable(a, b, root); + } + assert forall|root: RegexId, concat: bool, count: nat, results: Seq| + root@ < a.regexes.len() && count <= derivative_children_ids(a, root).len() && derivative_results(a, root, concat, count, results) + implies derivative_results(b, root, concat, count, results) by { + derivative_results_stable(a, b, root, concat, count, results); + } + } + + pub proof fn derivative_frame(g: model::Graph) + requires model::graph_wf(g), + ensures forall|next: model::Graph| model::graph_extends(g, next) ==> ( + (forall|cache: Seq>| derivative_cache_wf(g, cache) ==> derivative_cache_wf(next, cache)) + && (forall|tasks: Seq<(RegexId, bool)>| derivative_tasks_wf(g, tasks) ==> derivative_tasks_wf(next, tasks)) + && (forall|root: nat, out: TransitionId| derivative_correct(g, root, out) ==> derivative_correct(next, root, out)) + && (forall|root: RegexId, count: nat, concat: bool| derivative_factors_wf(g, root, count, concat) ==> derivative_factors_wf(next, root, count, concat)) + && (forall|root: RegexId, index: nat| root@ < g.regexes.len() && index <= derivative_children_ids(g, root).len() + ==> derivative_prefix(g, root, index) == derivative_prefix(next, root, index)) + && (forall|root: RegexId, concat: bool, count: nat, results: Seq| + root@ < g.regexes.len() && count <= derivative_children_ids(g, root).len() && derivative_results(g, root, concat, count, results) + ==> derivative_results(next, root, concat, count, results)) + && (forall|after: model::Graph| model::graph_extends(next, after) ==> model::graph_extends(g, after))), + { + hide(derivative_correct); hide(derivative_results); hide(derivative_prefix); hide(derivative_factor_language); + hide(derivative_cache_wf); hide(derivative_factors_wf); hide(derivative_tasks_wf); + assert forall|next: model::Graph| model::graph_extends(g, next) implies ( + (forall|cache: Seq>| derivative_cache_wf(g, cache) ==> derivative_cache_wf(next, cache)) + && (forall|tasks: Seq<(RegexId, bool)>| derivative_tasks_wf(g, tasks) ==> derivative_tasks_wf(next, tasks)) + && (forall|root: nat, out: TransitionId| derivative_correct(g, root, out) ==> derivative_correct(next, root, out)) + && (forall|root: RegexId, count: nat, concat: bool| derivative_factors_wf(g, root, count, concat) ==> derivative_factors_wf(next, root, count, concat)) + && (forall|root: RegexId, index: nat| root@ < g.regexes.len() && index <= derivative_children_ids(g, root).len() + ==> derivative_prefix(g, root, index) == derivative_prefix(next, root, index)) + && (forall|root: RegexId, concat: bool, count: nat, results: Seq| + root@ < g.regexes.len() && count <= derivative_children_ids(g, root).len() && derivative_results(g, root, concat, count, results) + ==> derivative_results(next, root, concat, count, results)) + && (forall|after: model::Graph| model::graph_extends(next, after) ==> model::graph_extends(g, after))) by { + derivative_extends(g, next); + } + } + + pub proof fn derivative_dependency_frame(g: model::Graph, root: RegexId) + requires model::graph_wf(g), root@ < g.regexes.len(), + ensures forall|next: model::Graph, cache: Seq>| model::graph_extends(g, next) + ==> derivative_dependencies_complete(g, root, cache) == derivative_dependencies_complete(next, root, cache), + { + assert forall|next: model::Graph, cache: Seq>| model::graph_extends(g, next) + implies derivative_dependencies_complete(g, root, cache) == derivative_dependencies_complete(next, root, cache) by { + derivative_factor_stable(g, next, root); + assert(g.regexes[root@ as int] == next.regexes[root@ as int]); + assert forall|child: nat| derivative_dependency(g, root, child) == derivative_dependency(next, root, child) by {} + } + } + + pub proof fn derivative_results_push( + g: model::Graph, root: RegexId, concat: bool, index: nat, prior: Seq, out: TransitionId, + ) + requires derivative_results(g, root, concat, index, prior), out@ < g.transitions.len(), + !concat || derivative_prefix(g, root, index), + forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> norm::transition_lang(g, theta, out, event, word) + == derivative_factor_language(g, root, concat, index as int, theta, event, word), + ensures derivative_results(g, root, concat, index + 1, prior.push(out)), + { + hide(language::numeric_lang); hide(language::derivative); hide(language::interp_transition); + hide(norm::transition_lang); hide(derivative_factor_language); + assert forall|theta: Subst, event: EventView, word: Seq, intersect: bool| + language::event_wf(theta, theta.len()) implies norm::transition_combo(g, theta, prior.push(out), event, word, intersect) + == derivative_factor_combo(g, root, concat, index + 1, intersect, theta, event, word) by { + if intersect { + assert forall|i: int| 0 <= i < prior.push(out).len() implies + norm::transition_lang(g, theta, prior.push(out)[i], event, word) + == if i < prior.len() { norm::transition_lang(g, theta, prior[i], event, word) } + else { norm::transition_lang(g, theta, out, event, word) } by {} + assert(prior.push(out)[prior.len() as int] == out); + if norm::transition_combo(g, theta, prior.push(out), event, word, true) { + assert forall|i: int| 0 <= i < prior.len() implies + norm::transition_lang(g, theta, prior[i], event, word) by { + assert(prior.push(out)[i] == prior[i]); + } + } + if norm::transition_combo(g, theta, prior, event, word, true) + && norm::transition_lang(g, theta, out, event, word) { + assert forall|i: int| 0 <= i < prior.push(out).len() implies + norm::transition_lang(g, theta, prior.push(out)[i], event, word) by { + if i < prior.len() { assert(prior.push(out)[i] == prior[i]); } else { assert(prior.push(out)[i] == out); } + } + } + assert(norm::transition_combo(g, theta, prior.push(out), event, word, true) + == (norm::transition_combo(g, theta, prior, event, word, true) + && norm::transition_lang(g, theta, out, event, word))); + } else { + if norm::transition_combo(g, theta, prior.push(out), event, word, false) { + let i = choose|i: int| 0 <= i < prior.push(out).len() + && norm::transition_lang(g, theta, prior.push(out)[i], event, word); + if i < prior.len() { assert(norm::transition_combo(g, theta, prior, event, word, false)); } + } + if norm::transition_combo(g, theta, prior, event, word, false) { + let i = choose|i: int| 0 <= i < prior.len() + && norm::transition_lang(g, theta, prior[i], event, word); + assert(prior.push(out)[i] == prior[i]); + } + assert(prior.push(out)[prior.len() as int] == out); + assert(norm::transition_combo(g, theta, prior.push(out), event, word, false) + == (norm::transition_combo(g, theta, prior, event, word, false) + || norm::transition_lang(g, theta, out, event, word))); + } + } + } + + pub proof fn derivative_results_skip(g: model::Graph, root: RegexId, index: nat, results: Seq) + requires derivative_results(g, root, true, index, results), !derivative_prefix(g, root, index), + ensures derivative_results(g, root, true, index + 1, results), + {} + + pub proof fn derivative_append_factor( + g: model::Graph, root: RegexId, index: int, d: TransitionId, suffix: Seq, out: TransitionId, + ) + requires 0 <= index < derivative_children_ids(g, root).len(), + derivative_correct(g, derivative_children_ids(g, root)[index], d), + model::regex_ids(suffix) == derivative_children_ids(g, root).subrange(index + 1, derivative_children_ids(g, root).len() as int), + forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> norm::transition_lang(g, theta, out, event, word) + == norm::transition_append_combo(g, theta, d, suffix, event, word), + ensures forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> norm::transition_lang(g, theta, out, event, word) + == derivative_factor_language(g, root, true, index, theta, event, word), + { + hide(language::numeric_lang); hide(language::derivative); hide(language::interp_transition); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies norm::transition_lang(g, theta, out, event, word) + == derivative_factor_language(g, root, true, index, theta, event, word) by { + let sem = model::gsem(theta); + let child = model::lift_regex(g, derivative_children_ids(g, root)[index]); + let actual = language::interp_transition(sem, event, model::lift_transition(g, d@)); + let expected = language::derivative(sem, event, child); + let tail = model::lift_regexes(g, model::regex_ids(suffix)); + language::lemma_concat_prepend(sem, actual, tail, word); + language::lemma_concat_prepend(sem, expected, tail, word); + assert forall|w: Seq| language::numeric_lang(sem, actual, w) == language::numeric_lang(sem, expected, w) by { + language::lemma_derivative_correct(sem, event, child, w); + assert(norm::transition_lang(g, theta, d, event, w) + == model::regex_lang(g, theta, derivative_children_ids(g, root)[index], seq![event] + w)); + } + } + } + + pub open spec fn derivative_sum(sem: spec_fn(L, EventView) -> bool, event: EventView, cs: Seq>, word: Seq) -> bool { + exists|i: int| 0 <= i < cs.len() + && (forall|j: int| 0 <= j < i ==> language::nullable(cs[j])) + && language::numeric_lang(sem, language::Regex::Concat(seq![language::derivative(sem, event, cs[i])] + + cs.subrange(i + 1, cs.len() as int)), word) + } + + pub proof fn derivative_concat_sum(sem: spec_fn(L, EventView) -> bool, event: EventView, bound: language::Regex, cs: Seq>, word: Seq) + requires forall|i: int| 0 <= i < cs.len() ==> is_smaller_than(cs[i], bound), + ensures language::numeric_lang(sem, language::derivative_concat(sem, event, bound, cs), word) == derivative_sum(sem, event, cs, word), + decreases cs.len(), + { + if cs.len() > 0 { + let rest = cs.drop_first(); + assert forall|i: int| 0 <= i < rest.len() implies is_smaller_than(rest[i], bound) by { assert(rest[i] == cs[i + 1]); } + derivative_concat_sum(sem, event, bound, rest, word); + let head = language::Regex::Concat(seq![language::derivative(sem, event, cs[0])] + rest); + language::lemma_union_optional(sem, head, language::derivative_concat(sem, event, bound, rest), language::nullable(cs[0]), word); + assert(cs.subrange(1, cs.len() as int) =~= rest); + if derivative_sum(sem, event, cs, word) { + let i = choose|i: int| 0 <= i < cs.len() + && (forall|j: int| 0 <= j < i ==> language::nullable(cs[j])) + && language::numeric_lang(sem, language::Regex::Concat(seq![language::derivative(sem, event, cs[i])] + + cs.subrange(i + 1, cs.len() as int)), word); + if i > 0 { + assert(rest[i - 1] == cs[i]); + assert(rest.subrange(i, rest.len() as int) =~= cs.subrange(i + 1, cs.len() as int)); + assert forall|j: int| 0 <= j < i - 1 implies language::nullable(rest[j]) by { assert(rest[j] == cs[j + 1]); } + assert(derivative_sum(sem, event, rest, word)); + } + } + if language::numeric_lang(sem, head, word) { assert(derivative_sum(sem, event, cs, word)); } + if language::nullable(cs[0]) && derivative_sum(sem, event, rest, word) { + let i = choose|i: int| 0 <= i < rest.len() + && (forall|j: int| 0 <= j < i ==> language::nullable(rest[j])) + && language::numeric_lang(sem, language::Regex::Concat(seq![language::derivative(sem, event, rest[i])] + + rest.subrange(i + 1, rest.len() as int)), word); + assert(cs[i + 1] == rest[i]); + assert(cs.subrange(i + 2, cs.len() as int) =~= rest.subrange(i + 1, rest.len() as int)); + assert forall|j: int| 0 <= j < i + 1 implies language::nullable(cs[j]) by { if j > 0 { assert(cs[j] == rest[j - 1]); } } + assert(derivative_sum(sem, event, cs, word)); + } + } + } + + pub proof fn derivative_sum_correct(sem: spec_fn(L, EventView) -> bool, event: EventView, root: language::Regex, word: Seq) + requires root is Concat, + ensures derivative_sum(sem, event, root->Concat_0, word) == language::numeric_lang(sem, root, seq![event] + word), + { + hide(language::numeric_lang); + match root { + language::Regex::Concat(cs) => { + assert forall|i: int| 0 <= i < cs.len() implies is_smaller_than(cs[i], root) by {} + derivative_concat_sum(sem, event, root, cs, word); + language::lemma_derivative_correct(sem, event, root, word); + }, + _ => {}, + } + } + + pub proof fn derivative_children_complete(g: model::Graph, root: RegexId, concat: bool, intersect: bool, out: TransitionId) + requires model::graph_wf(g), root@ < g.regexes.len(), + match g.regexes[root@ as int].kind { + model::RegexKindNode::Union(_) => !concat && !intersect, + model::RegexKindNode::Intersect(_) => !concat && intersect, + model::RegexKindNode::Concat(_) => concat && !intersect, + _ => false, + }, out@ < g.transitions.len(), + forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> norm::transition_lang(g, theta, out, event, word) + == derivative_factor_combo(g, root, concat, derivative_children_ids(g, root).len(), intersect, theta, event, word), + ensures derivative_correct(g, root@, out), + { + hide(language::numeric_lang); hide(language::derivative); hide(language::interp_transition); + hide(model::lift_regex); hide(model::lift_transition); + hide(language::nullable); + norm::regex_unfold(g, root@); + let cs = derivative_children_ids(g, root); + let rs = model::lift_regexes(g, cs); + assert(rs.len() == cs.len()); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies norm::transition_lang(g, theta, out, event, word) + == model::regex_lang(g, theta, root@, seq![event] + word) by { + let sem = model::gsem(theta); + assert(norm::transition_lang(g, theta, out, event, word) + == derivative_factor_combo(g, root, concat, cs.len(), intersect, theta, event, word)); + assert forall|i: int| 0 <= i < cs.len() implies + #[trigger] derivative_factor_language(g, root, false, i, theta, event, word) + == language::numeric_lang(sem, rs[i], seq![event] + word) by { + assert(rs[i] == model::lift_regex(g, cs[i])); + } + if concat { + assert(!intersect); + derivative_sum_correct(sem, event, language::Regex::Concat(rs), word); + assert(model::lift_regex(g, root@) == language::Regex::Concat(rs)); + assert forall|i: int| 0 <= i < cs.len() implies + #[trigger] model::lift_regexes(g, cs.subrange(i + 1, cs.len() as int)) == rs.subrange(i + 1, rs.len() as int) by { + assert(model::lift_regexes(g, cs.subrange(i + 1, cs.len() as int)) =~= rs.subrange(i + 1, rs.len() as int)); + } + assert forall|i: int| 0 <= i < cs.len() implies + #[trigger] derivative_prefix(g, root, i as nat) == (forall|j: int| 0 <= j < i ==> language::nullable(rs[j])) by { + assert forall|j: int| 0 <= j < i implies rs[j] == model::lift_regex(g, cs[j]) by {} + if derivative_prefix(g, root, i as nat) { + assert forall|j: int| 0 <= j < i implies language::nullable(rs[j]) by { + assert(rs[j] == model::lift_regex(g, cs[j])); + } + } + if forall|j: int| 0 <= j < i ==> language::nullable(rs[j]) { + assert forall|j: int| 0 <= j < i implies language::nullable(model::lift_regex(g, cs[j])) by { + assert(rs[j] == model::lift_regex(g, cs[j])); + } + } + } + assert forall|i: int| 0 <= i < cs.len() implies + #[trigger] derivative_factor_language(g, root, true, i, theta, event, word) + == language::numeric_lang(sem, language::Regex::Concat(seq![language::derivative(sem, event, rs[i])] + + rs.subrange(i + 1, rs.len() as int)), word) by { + assert(rs[i] == model::lift_regex(g, cs[i])); + assert(model::lift_regexes(g, cs.subrange(i + 1, cs.len() as int)) == rs.subrange(i + 1, rs.len() as int)); + } + if derivative_factor_combo(g, root, concat, cs.len(), intersect, theta, event, word) { + let i = choose|i: int| 0 <= i < cs.len() && derivative_prefix(g, root, i as nat) + && derivative_factor_language(g, root, true, i, theta, event, word); + assert(0 <= i < rs.len()); + assert(derivative_sum(sem, event, rs, word)); + } + if derivative_sum(sem, event, rs, word) { + let i = choose|i: int| 0 <= i < rs.len() + && (forall|j: int| 0 <= j < i ==> language::nullable(rs[j])) + && language::numeric_lang(sem, language::Regex::Concat(seq![language::derivative(sem, event, rs[i])] + + rs.subrange(i + 1, rs.len() as int)), word); + assert(0 <= i < cs.len()); + assert(derivative_prefix(g, root, i as nat)); + assert(derivative_factor_language(g, root, true, i, theta, event, word)); + assert(derivative_factor_combo(g, root, concat, cs.len(), intersect, theta, event, word)); + } + assert(derivative_factor_combo(g, root, concat, cs.len(), intersect, theta, event, word) + == derivative_sum(sem, event, rs, word)); + assert(norm::transition_lang(g, theta, out, event, word) + == model::regex_lang(g, theta, root@, seq![event] + word)); + } else if intersect { + language::lemma_lang_intersect(sem, rs, seq![event] + word); + assert(model::lift_regex(g, root@) == language::Regex::Intersect(rs)); + assert(derivative_factor_combo(g, root, false, cs.len(), true, theta, event, word) + == (forall|i: int| 0 <= i < cs.len() ==> derivative_factor_language(g, root, false, i, theta, event, word))); + if derivative_factor_combo(g, root, false, cs.len(), true, theta, event, word) { + assert forall|i: int| 0 <= i < rs.len() implies language::numeric_lang(sem, rs[i], seq![event] + word) by { + assert(derivative_factor_language(g, root, false, i, theta, event, word)); + } + } + if forall|i: int| 0 <= i < rs.len() ==> language::numeric_lang(sem, rs[i], seq![event] + word) { + assert forall|i: int| 0 <= i < cs.len() implies derivative_factor_language(g, root, false, i, theta, event, word) by { + assert(language::numeric_lang(sem, rs[i], seq![event] + word)); + } + } + assert(derivative_factor_combo(g, root, false, cs.len(), true, theta, event, word) + == (forall|i: int| 0 <= i < rs.len() ==> language::numeric_lang(sem, rs[i], seq![event] + word))); + assert(norm::transition_lang(g, theta, out, event, word) + == model::regex_lang(g, theta, root@, seq![event] + word)); + } else { + language::lemma_lang_union(sem, rs, seq![event] + word); + assert(model::lift_regex(g, root@) == language::Regex::Union(rs)); + if derivative_factor_combo(g, root, false, cs.len(), false, theta, event, word) { + let i = choose|i: int| 0 <= i < cs.len() && derivative_factor_language(g, root, false, i, theta, event, word); + assert(language::numeric_lang(sem, rs[i], seq![event] + word)); + } + if exists|i: int| 0 <= i < rs.len() && language::numeric_lang(sem, rs[i], seq![event] + word) { + let i = choose|i: int| 0 <= i < rs.len() && language::numeric_lang(sem, rs[i], seq![event] + word); + assert(derivative_factor_language(g, root, false, i, theta, event, word)); + assert(derivative_factor_combo(g, root, false, cs.len(), false, theta, event, word)); + } + assert(derivative_factor_combo(g, root, false, cs.len(), false, theta, event, word) + == (exists|i: int| 0 <= i < rs.len() && language::numeric_lang(sem, rs[i], seq![event] + word))); + assert(norm::transition_lang(g, theta, out, event, word) + == model::regex_lang(g, theta, root@, seq![event] + word)); + } + } + } + + pub proof fn derivative_constants(g: model::Graph) + requires model::graph_wf(g), + ensures g.constants.transition_empty < g.transitions.len(), + g.constants.transition_all < g.transitions.len(), g.constants.transition_epsilon < g.transitions.len(), + model::lift_transition(g, g.constants.transition_empty) == language::Transition::Const(language::Regex::Empty), + model::lift_transition(g, g.constants.transition_all) == language::Transition::Const(language::Regex::All), + model::lift_transition(g, g.constants.transition_epsilon) == language::Transition::Const(language::Regex::Epsilon), + { + model::lemma_graph_wf_elim(g); + } + + pub open spec fn derivative_native_result(g: model::Graph, root: RegexId, cache: Seq>, out: TransitionId) -> bool { + match g.regexes[root@ as int].kind { + model::RegexKindNode::Empty | model::RegexKindNode::Epsilon => out@ == g.constants.transition_empty, + model::RegexKindNode::All => out@ == g.constants.transition_all, + model::RegexKindNode::Test(test) => forall|theta: Subst, event: EventView, word: Seq| + language::event_wf(theta, theta.len()) ==> norm::transition_lang(g, theta, out, event, word) + == if model::test_holds(theta, model::lift_test(g, test), event) { word.len() == 0 } else { false }, + model::RegexKindNode::Star(inner) => exists|d: TransitionId| inner < cache.len() && cache[inner as int] == Some(d) + && forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> norm::transition_lang(g, theta, out, event, word) + == norm::transition_append_combo(g, theta, d, seq![root], event, word), + model::RegexKindNode::Not(inner) => exists|d: TransitionId| inner < cache.len() && cache[inner as int] == Some(d) + && norm::transition_result(g, norm::ActionShape::Not(d@), out), + _ => derivative_correct(g, root@, out), + } + } + + pub proof fn derivative_native_correct(g: model::Graph, root: RegexId, cache: Seq>, out: TransitionId) + requires model::graph_wf(g), root@ < g.regexes.len(), derivative_cache_wf(g, cache), + out@ < g.transitions.len(), derivative_native_result(g, root, cache, out), + ensures derivative_correct(g, root@, out), + { + hide(language::numeric_lang); hide(language::derivative); hide(language::interp_transition); + hide(model::lift_regex); hide(model::lift_transition); + norm::regex_unfold(g, root@); + derivative_constants(g); + match g.regexes[root@ as int].kind { + model::RegexKindNode::Star(inner) => { + assert(model::lift_regex(g, root@) == language::Regex::Star(alloc::boxed::Box::new(model::lift_regex(g, inner)))); + let d = choose|d: TransitionId| inner < cache.len() && cache[inner as int] == Some(d) + && forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> norm::transition_lang(g, theta, out, event, word) + == norm::transition_append_combo(g, theta, d, seq![root], event, word); + assert(derivative_correct(g, inner, d)); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies norm::transition_lang(g, theta, out, event, word) + == model::regex_lang(g, theta, root@, seq![event] + word) by { + let sem = model::gsem(theta); + let actual = language::interp_transition(sem, event, model::lift_transition(g, d@)); + let expected = language::derivative(sem, event, model::lift_regex(g, inner)); + let tail = seq![model::lift_regex(g, root@)]; + assert(model::lift_regexes(g, model::regex_ids(seq![root])) =~= tail); + language::lemma_concat_prepend(sem, actual, tail, word); + language::lemma_concat_prepend(sem, expected, tail, word); + assert forall|w: Seq| language::numeric_lang(sem, actual, w) == language::numeric_lang(sem, expected, w) by { + language::lemma_derivative_correct(sem, event, model::lift_regex(g, inner), w); + assert(norm::transition_lang(g, theta, d, event, w) + == model::regex_lang(g, theta, inner, seq![event] + w)); + } + language::lemma_derivative_correct(sem, event, model::lift_regex(g, root@), word); + reveal(language::derivative); + assert(seq![expected] + tail =~= seq![expected, model::lift_regex(g, root@)]); + assert(language::derivative(sem, event, model::lift_regex(g, root@)) + == language::Regex::Concat(seq![expected] + tail)); + } + }, + model::RegexKindNode::Not(inner) => { + let d = choose|d: TransitionId| inner < cache.len() && cache[inner as int] == Some(d) + && norm::transition_result(g, norm::ActionShape::Not(d@), out); + symbolic_not_result(g, d, out); + assert(derivative_correct(g, inner, d)); + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies norm::transition_lang(g, theta, out, event, word) + == model::regex_lang(g, theta, root@, seq![event] + word) by { + reveal(language::numeric_lang); + } + }, + model::RegexKindNode::Empty | model::RegexKindNode::All | model::RegexKindNode::Epsilon | model::RegexKindNode::Test(_) => { + assert forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + implies norm::transition_lang(g, theta, out, event, word) + == model::regex_lang(g, theta, root@, seq![event] + word) by { + reveal(language::numeric_lang); reveal(language::interp_transition); + assert((seq![event] + word).len() == 1 + word.len()); + assert((seq![event] + word)[0] == event); + } + }, + _ => {}, + } + } + + pub proof fn derivative_step_future(g: model::Graph, root: RegexId, cache: Seq>) + requires model::graph_wf(g), root@ < g.regexes.len(), derivative_cache_wf(g, cache), + ensures forall|next: model::Graph, out: TransitionId| model::graph_extends(g, next) && model::graph_wf(next) + && out@ < next.transitions.len() && derivative_native_result(next, root, cache, out) ==> derivative_correct(next, root@, out), + { + assert forall|next: model::Graph, out: TransitionId| model::graph_extends(g, next) && model::graph_wf(next) + && out@ < next.transitions.len() && derivative_native_result(next, root, cache, out) implies derivative_correct(next, root@, out) by { + derivative_extends(g, next); + derivative_native_correct(next, root, cache, out); + } + } + + pub proof fn derivative_result_future(g: model::Graph, root: RegexId, concat: bool, intersect: bool, results: Seq) + requires model::graph_wf(g), derivative_results(g, root, concat, derivative_children_ids(g, root).len(), results), root@ < g.regexes.len(), + match g.regexes[root@ as int].kind { + model::RegexKindNode::Union(_) => !concat && !intersect, + model::RegexKindNode::Intersect(_) => !concat && intersect, + model::RegexKindNode::Concat(_) => concat && !intersect, + _ => false, + }, + ensures forall|next: model::Graph, out: TransitionId| model::graph_extends(g, next) && model::graph_wf(next) + && out@ < next.transitions.len() + && (if intersect { norm::transition_result(next, norm::ActionShape::Fold(model::transition_ids(results), 0), out) } + else { forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> norm::transition_lang(next, theta, out, event, word) + == norm::transition_combo(next, theta, results, event, word, false) }) + ==> derivative_correct(next, root@, out), + { + assert forall|next: model::Graph, out: TransitionId| model::graph_extends(g, next) && model::graph_wf(next) + && out@ < next.transitions.len() + && (if intersect { norm::transition_result(next, norm::ActionShape::Fold(model::transition_ids(results), 0), out) } + else { forall|theta: Subst, event: EventView, word: Seq| language::event_wf(theta, theta.len()) + ==> norm::transition_lang(next, theta, out, event, word) + == norm::transition_combo(next, theta, results, event, word, false) }) + implies derivative_correct(next, root@, out) by { + derivative_extends(g, next); + if intersect { symbolic_intersect_result(next, results, out); } + derivative_children_complete(next, root, concat, intersect, out); + } + } + + pub open spec fn assignment_valid(count: nat, words: Seq) -> bool { + count + 63 <= usize::MAX + && words.len() == (count + 63) / 64 + && (count % 64 != 0 ==> words.len() > 0 + && (words.last() >> ((count % 64) as u32)) == 0u64) + } + + pub open spec fn positive_atom_at(g: model::Graph, atoms: Seq, primitive: model::Primitive, index: usize) -> bool { + index < atoms.len() && atoms[index as int]@ < g.tests.len() + && g.tests[atoms[index as int]@ as int] == model::TestNode::Atom(primitive, true) + } + + pub open spec fn bool_fold(values: Seq, and: bool) -> bool { + if and { forall|i: int| 0 <= i < values.len() ==> values[i] } + else { exists|i: int| 0 <= i < values.len() && values[i] } + } + + pub open spec fn test_children(g: model::Graph, id: TestId) -> Seq { + match g.tests[id@ as int] { model::TestNode::And(cs) | model::TestNode::Or(cs) => cs, _ => Seq::empty() } + } + + pub open spec fn test_tasks_wf(g: model::Graph, tasks: Seq<(TestId, bool)>) -> bool { + forall|i: int| 0 <= i < tasks.len() ==> tasks[i].0@ < g.tests.len() + } + + /// `TestId::evaluate` reuses the `TestId::not` measure: both worklists schedule the same nodes. + pub proof fn test_lemma_eval_branch_work(g: model::Graph, id: TestId, pending: Seq<(TestId, bool)>) + requires model::graph_wf(g), id@ < g.tests.len(), + g.tests[id@ as int] is And || g.tests[id@ as int] is Or, + ensures norm::test_not_work(g, pending.push((id, true)) + child_test_tasks(g, id, 0)) + < norm::test_not_work(g, pending.push((id, false))), + { + model::lemma_graph_test_wf(g, id@); + let cs = test_children(g, id); + let scheduled = child_test_tasks(g, id, 0); + assert forall|i: int| 0 <= i < scheduled.len() + implies #[trigger] scheduled[i].0@ == cs[cs.len() as int - 1 - i] && !scheduled[i].1 by { + assert(cs[cs.len() as int - 1 - i] < id@); + } + norm::test_lemma_not_work_schedule(g, pending.push((id, true)), scheduled, cs, id@); + assert(pending.push((id, true)).drop_last() =~= pending); + assert(pending.push((id, false)).drop_last() =~= pending); + } + + pub proof fn test_lemma_eval_step_work(g: model::Graph, id: TestId, finish: bool, + pending: Seq<(TestId, bool)>, tasks: Seq<(TestId, bool)>) + requires id@ < g.tests.len(), + tasks == pending || norm::test_not_work(g, tasks) < norm::test_not_work(g, pending.push((id, finish))), + ensures norm::test_not_work(g, tasks) < norm::test_not_work(g, pending.push((id, finish))), + { + assert(pending.push((id, finish)).drop_last() =~= pending); + } + + pub open(crate) spec fn child_test_tasks(g: model::Graph, id: TestId, remaining: nat) -> Seq<(TestId, bool)> { + Seq::new((test_children(g, id).len() - remaining) as nat, |i: int| (TestId::from_view(test_children(g, id)[test_children(g, id).len() - 1 - i] as u32), false)) + } + + pub open spec fn test_action(g: model::Graph, task: (TestId, bool), values: Seq, theta: Subst, event: EventView) -> Option> { + if task.1 { + match g.tests[task.0@ as int] { + model::TestNode::And(cs) | model::TestNode::Or(cs) => { + if cs.len() > values.len() { None } + else { Some(values.take(values.len() - cs.len()).push(bool_fold(values.skip(values.len() - cs.len()), g.tests[task.0@ as int] is And))) } + }, + _ => Some(values.push(model::test_holds(theta, model::lift_test(g, task.0@), event))), + } + } else { Some(values.push(model::test_holds(theta, model::lift_test(g, task.0@), event))) } + } + + pub open spec fn test_run(g: model::Graph, tasks: Seq<(TestId, bool)>, values: Seq, theta: Subst, event: EventView) -> Option> + decreases tasks.len(), + { + if tasks.len() == 0 { Some(values) } + else { match test_action(g, tasks.last(), values, theta, event) { + Some(next) => test_run(g, tasks.drop_last(), next, theta, event), None => None, + } } + } + + pub proof fn test_run_concat(g: model::Graph, prefix: Seq<(TestId, bool)>, suffix: Seq<(TestId, bool)>, values: Seq, theta: Subst, event: EventView) + ensures test_run(g, prefix + suffix, values, theta, event) == match test_run(g, suffix, values, theta, event) { + Some(next) => test_run(g, prefix, next, theta, event), None => None, + }, + decreases suffix.len(), + { + if suffix.len() > 0 { + assert((prefix + suffix).last() == suffix.last()); + assert((prefix + suffix).drop_last() =~= prefix + suffix.drop_last()); + if let Some(next) = test_action(g, suffix.last(), values, theta, event) { + test_run_concat(g, prefix, suffix.drop_last(), next, theta, event); + } + } else { assert(prefix + suffix =~= prefix); } + } + + pub open spec fn child_test_values(g: model::Graph, id: TestId, count: nat, theta: Subst, event: EventView) -> Seq { + Seq::new(count, |i: int| model::test_holds(theta, model::lift_test(g, test_children(g, id)[i]), event)) + } + + pub proof fn child_test_run(g: model::Graph, id: TestId, remaining: nat, values: Seq, theta: Subst, event: EventView) + requires model::graph_wf(g), id@ < g.tests.len(), remaining <= test_children(g, id).len(), + ensures test_run(g, child_test_tasks(g, id, remaining), values, theta, event) + == Some(values + child_test_values(g, id, test_children(g, id).len(), theta, event).skip(remaining as int)), + decreases test_children(g, id).len() - remaining, + { + model::lemma_graph_test_wf(g, id@); + let tasks = child_test_tasks(g, id, remaining); + let vals = child_test_values(g, id, test_children(g, id).len(), theta, event); + if remaining < test_children(g, id).len() { + let child = TestId::from_view(test_children(g, id)[remaining as int] as u32); + assert(child@ == test_children(g, id)[remaining as int]); + assert(tasks.last() == (child, false)); + assert(tasks.drop_last() =~= child_test_tasks(g, id, remaining + 1)); + child_test_run(g, id, remaining + 1, values.push(vals[remaining as int]), theta, event); + assert(values.push(vals[remaining as int]) + vals.skip(remaining as int + 1) + =~= values + vals.skip(remaining as int)); + } else { + assert(tasks =~= Seq::empty()); + assert(vals.skip(remaining as int) =~= Seq::empty()); + assert(values + vals.skip(remaining as int) =~= values); + } + } + + #[verifier::spinoff_prover] + #[verifier::rlimit(30)] + pub proof fn test_expand(g: model::Graph, id: TestId, tasks: Seq<(TestId, bool)>, values: Seq, theta: Subst, event: EventView) + requires model::graph_wf(g), id@ < g.tests.len(), + g.tests[id@ as int] is And || g.tests[id@ as int] is Or, + ensures test_run(g, tasks.push((id, true)) + child_test_tasks(g, id, 0), values, theta, event) + == test_run(g, tasks.push((id, false)), values, theta, event), + { + reveal_with_fuel(model::test_holds, 2); + reveal_with_fuel(model::lift_test, 2); + reveal_with_fuel(test_run, 2); + model::lemma_graph_test_wf(g, id@); + let vals = child_test_values(g, id, test_children(g, id).len(), theta, event); + child_test_run(g, id, 0, values, theta, event); + test_run_concat(g, tasks.push((id, true)), child_test_tasks(g, id, 0), values, theta, event); + assert(vals.skip(0) =~= vals); + assert((values + vals).take(values.len() as int) =~= values); + assert((values + vals).skip(values.len() as int) =~= vals); + assert(bool_fold(vals, g.tests[id@ as int] is And) + == model::test_holds(theta, model::lift_test(g, id@), event)) by { + match g.tests[id@ as int] { + model::TestNode::And(cs) => { + assert(model::lift_test(g, id@) == model::Test::And(model::lift_tests(g, cs, id@))); + assert forall|i: int| 0 <= i < cs.len() implies + vals[i] == model::test_holds(theta, model::lift_tests(g, cs, id@)[i], event) by { + assert(model::lift_tests(g, cs, id@)[i] == model::lift_test(g, cs[i])); + } + bool_fold_tests(vals, model::lift_tests(g, cs, id@), true, theta, event); + }, + model::TestNode::Or(cs) => { + assert(model::lift_test(g, id@) == model::Test::Or(model::lift_tests(g, cs, id@))); + assert forall|i: int| 0 <= i < cs.len() implies + vals[i] == model::test_holds(theta, model::lift_tests(g, cs, id@)[i], event) by { + assert(model::lift_tests(g, cs, id@)[i] == model::lift_test(g, cs[i])); + } + bool_fold_tests(vals, model::lift_tests(g, cs, id@), false, theta, event); + }, + _ => {}, + } + } + assert(test_action(g, (id, true), values + vals, theta, event) + == Some(values.push(model::test_holds(theta, model::lift_test(g, id@), event)))); + assert(tasks.push((id, true)).drop_last() =~= tasks); + assert(tasks.push((id, false)).drop_last() =~= tasks); + } + + pub proof fn bool_fold_tests(vals: Seq, tests: Seq, and: bool, theta: Subst, event: EventView) + requires vals.len() == tests.len(), forall|i: int| 0 <= i < vals.len() ==> vals[i] == model::test_holds(theta, tests[i], event), + ensures bool_fold(vals, and) == model::test_holds(theta, if and { model::Test::And(tests) } else { model::Test::Or(tests) }, event), + { + norm::test_lemma_semantics_unfold(theta, event, model::Test::And(tests)); + norm::test_lemma_semantics_unfold(theta, event, model::Test::Or(tests)); + if and { + if bool_fold(vals, true) { + assert forall|i: int| 0 <= i < tests.len() implies model::test_holds(theta, tests[i], event) by { assert(vals[i]); } + } + if model::test_holds(theta, model::Test::And(tests), event) { + assert forall|i: int| 0 <= i < vals.len() implies vals[i] by { assert(model::test_holds(theta, tests[i], event)); } + } + } else { + if bool_fold(vals, false) { + let i = choose|i: int| 0 <= i < vals.len() && vals[i]; + assert(model::test_holds(theta, tests[i], event)); + } + if model::test_holds(theta, model::Test::Or(tests), event) { + let i = choose|i: int| 0 <= i < tests.len() && model::test_holds(theta, tests[i], event); + assert(vals[i]); + } + } + } + + pub proof fn bool_fold_prepend(value: bool, values: Seq, and: bool) + ensures bool_fold(seq![value] + values, and) == (if and { value && bool_fold(values, and) } else { value || bool_fold(values, and) }), + { + if and { + if bool_fold(seq![value] + values, true) { + assert((seq![value] + values)[0]); + assert forall|i: int| 0 <= i < values.len() implies values[i] by { assert((seq![value] + values)[i + 1]); } + } + if value && bool_fold(values, true) { + assert forall|i: int| 0 <= i < (seq![value] + values).len() implies (seq![value] + values)[i] by { + if i > 0 { assert(values[i - 1]); } + } + } + } else { + if bool_fold(seq![value] + values, false) { + let i = choose|i: int| 0 <= i < (seq![value] + values).len() && (seq![value] + values)[i]; + if i > 0 { assert(values[i - 1]); } + } + if bool_fold(values, false) { + let i = choose|i: int| 0 <= i < values.len() && values[i]; + assert((seq![value] + values)[i + 1]); + } + if value { assert((seq![value] + values)[0]); } + } + } + + pub proof fn test_run_unfold(g: model::Graph, tasks: Seq<(TestId, bool)>, values: Seq, theta: Subst, event: EventView) + ensures test_run(g, tasks, values, theta, event) == if tasks.len() == 0 { Some(values) } + else { match test_action(g, tasks.last(), values, theta, event) { + Some(next) => test_run(g, tasks.drop_last(), next, theta, event), None => None, + } }, + { + if tasks.len() == 0 {} else {} + } + + pub proof fn realized_atom_value(g: model::Graph, atoms: Seq, words: Seq, id: TestId, primitive: model::Primitive, positive: bool, index: usize, value: bool) + requires id@ < g.tests.len(), g.tests[id@ as int] == model::TestNode::Atom(primitive, positive), + positive_atom_at(g, atoms, primitive, index), value == truth_word_bit(words, index as nat), + ensures forall|theta: Subst, event: EventView| + truth_words_realize(g, atoms, words, theta, event) ==> + (if positive { value } else { !value }) == model::test_holds(theta, model::lift_test(g, id@), event), + { + assert forall|theta: Subst, event: EventView| + truth_words_realize(g, atoms, words, theta, event) implies + (if positive { value } else { !value }) == model::test_holds(theta, model::lift_test(g, id@), event) by { + assert(0 <= (index as int) < atoms.len()); + reveal(truth_words_realize); + assert forall|i: int| 0 <= i < atoms.len() implies + truth_word_bit(words, i as nat) == model::test_holds(theta, model::lift_test(g, atoms[i]@), event) by {} + assert(truth_word_bit(words, (index as int) as nat) + == model::test_holds(theta, model::lift_test(g, atoms[index as int]@), event)); + assert(model::lift_test(g, atoms[index as int]@) == model::Test::Atom(primitive, true)); + assert(model::lift_test(g, id@) == model::Test::Atom(primitive, positive)); + } + } + + pub type InterpRegex = language::Regex; + + pub open spec fn interpreted(g: model::Graph, id: TransitionId, theta: Subst, event: EventView) -> InterpRegex { + language::interp_transition(model::gsem(theta), event, model::lift_transition(g, id@)) + } + + pub open spec fn lifted_values(g: model::Graph, ids: Seq) -> Seq { + Seq::new(ids.len(), |i: int| model::lift_regex(g, ids[i]@)) + } + + pub open spec fn interp_tasks_wf(g: model::Graph, tasks: Seq<(TransitionId, bool)>) -> bool { + forall|i: int| 0 <= i < tasks.len() ==> tasks[i].0@ < g.transitions.len() + } + + pub open spec fn interp_node_work(g: model::Graph, id: nat) -> nat + decreases id, 1nat, + { + if id >= g.transitions.len() { 0 } else { + match g.transitions[id as int] { + model::TransitionNode::Const(_) => 1, + model::TransitionNode::If(_, a, b) => 1 + (if a < id { interp_node_work(g, a) } else { 0 }) + + (if b < id { interp_node_work(g, b) } else { 0 }), + model::TransitionNode::Union(cs) | model::TransitionNode::Intersect(cs) => 2 + interp_children_work(g, cs, id), + model::TransitionNode::Not(c) | model::TransitionNode::Append(c, _) => + 2 + if c < id { interp_node_work(g, c) } else { 0 }, + } + } + } + + pub open spec fn interp_children_work(g: model::Graph, children: Seq, bound: nat) -> nat + decreases bound, 0nat, children.len(), + { + if children.len() == 0 { 0 } else { + interp_children_work(g, children.skip(1), bound) + + if children[0] < bound { interp_node_work(g, children[0]) } else { 0 } + } + } + + /// `interpret_step` ignores `finish` on `If` nodes, so an `If` task always weighs its whole node. + pub open spec fn interp_task_work(g: model::Graph, task: (TransitionId, bool)) -> nat { + if task.1 && !(task.0@ < g.transitions.len() && g.transitions[task.0@ as int] is If) { 1 } + else { interp_node_work(g, task.0@) } + } + + pub open spec fn interp_work(g: model::Graph, tasks: Seq<(TransitionId, bool)>) -> nat + decreases tasks.len(), + { + if tasks.len() == 0 { 0 } else { interp_work(g, tasks.drop_last()) + interp_task_work(g, tasks.last()) } + } + + pub proof fn interp_lemma_node_work_extends(a: model::Graph, b: model::Graph, id: nat) + requires model::graph_extends(a, b), id < a.transitions.len(), + ensures interp_node_work(a, id) == interp_node_work(b, id), + decreases id, 1nat, + { + assert(a.transitions[id as int] == b.transitions[id as int]); + match a.transitions[id as int] { + model::TransitionNode::If(_, x, y) => { + if x < id { interp_lemma_node_work_extends(a, b, x); } + if y < id { interp_lemma_node_work_extends(a, b, y); } + }, + model::TransitionNode::Union(cs) => { interp_lemma_children_work_extends(a, b, cs, id); }, + model::TransitionNode::Intersect(cs) => { interp_lemma_children_work_extends(a, b, cs, id); }, + model::TransitionNode::Not(c) => { if c < id { interp_lemma_node_work_extends(a, b, c); } }, + model::TransitionNode::Append(c, _) => { if c < id { interp_lemma_node_work_extends(a, b, c); } }, + _ => {}, + } + } + + pub proof fn interp_lemma_children_work_extends(a: model::Graph, b: model::Graph, children: Seq, bound: nat) + requires model::graph_extends(a, b), bound <= a.transitions.len(), + ensures interp_children_work(a, children, bound) == interp_children_work(b, children, bound), + decreases bound, 0nat, children.len(), + { + if children.len() > 0 { + if children[0] < bound { interp_lemma_node_work_extends(a, b, children[0]); } + interp_lemma_children_work_extends(a, b, children.skip(1), bound); + } + } + + pub proof fn interp_lemma_work_extends(a: model::Graph, b: model::Graph, tasks: Seq<(TransitionId, bool)>) + requires model::graph_extends(a, b), interp_tasks_wf(a, tasks), + ensures interp_work(a, tasks) == interp_work(b, tasks), + decreases tasks.len(), + { + if tasks.len() > 0 { + let last = tasks.last(); + assert(last.0@ < a.transitions.len()); + assert(a.transitions[last.0@ as int] == b.transitions[last.0@ as int]); + interp_lemma_node_work_extends(a, b, last.0@); + assert forall|i: int| 0 <= i < tasks.drop_last().len() implies tasks.drop_last()[i].0@ < a.transitions.len() by { + assert(tasks.drop_last()[i] == tasks[i]); + } + interp_lemma_work_extends(a, b, tasks.drop_last()); + } + } + + pub proof fn interp_lemma_work_schedule(g: model::Graph, tasks: Seq<(TransitionId, bool)>, + scheduled: Seq<(TransitionId, bool)>, children: Seq, bound: nat) + requires scheduled.len() == children.len(), model::bounded(children, bound), + forall|i: int| 0 <= i < scheduled.len() + ==> #[trigger] scheduled[i].0@ == children[children.len() as int - 1 - i] && !scheduled[i].1, + ensures interp_work(g, tasks + scheduled) == interp_work(g, tasks) + interp_children_work(g, children, bound), + decreases scheduled.len(), + { + if scheduled.len() == 0 { + assert(tasks + scheduled =~= tasks); + } else { + assert((tasks + scheduled).drop_last() =~= tasks + scheduled.drop_last()); + assert((tasks + scheduled).last() == scheduled.last()); + interp_lemma_work_schedule(g, tasks, scheduled.drop_last(), children.skip(1), bound); + } + } + + pub proof fn interp_lemma_work_push(g: model::Graph, tasks: Seq<(TransitionId, bool)>, task: (TransitionId, bool)) + ensures interp_work(g, tasks.push(task)) == interp_work(g, tasks) + interp_task_work(g, task), + { + assert(tasks.push(task).drop_last() =~= tasks); + } + + pub proof fn interp_lemma_work_if(g: model::Graph, id: TransitionId, finish: bool, + pending: Seq<(TransitionId, bool)>, chosen: TransitionId) + requires model::graph_wf(g), id@ < g.transitions.len(), interp_tasks_wf(g, pending), + match g.transitions[id@ as int] { model::TransitionNode::If(_, a, b) => chosen@ == a || chosen@ == b, _ => false }, + ensures interp_tasks_wf(g, pending.push((chosen, false))), + interp_work(g, pending.push((chosen, false))) < interp_work(g, pending.push((id, finish))), + { + model::lemma_graph_transition_wf(g, id@); + interp_lemma_work_push(g, pending, (chosen, false)); + interp_lemma_work_push(g, pending, (id, finish)); + } + + pub proof fn interp_lemma_work_unary(g: model::Graph, id: TransitionId, pending: Seq<(TransitionId, bool)>, inner: TransitionId) + requires model::graph_wf(g), id@ < g.transitions.len(), interp_tasks_wf(g, pending), + match g.transitions[id@ as int] { + model::TransitionNode::Not(c) => inner@ == c, + model::TransitionNode::Append(c, _) => inner@ == c, + _ => false, + }, + ensures interp_tasks_wf(g, pending.push((id, true)).push((inner, false))), + interp_work(g, pending.push((id, true)).push((inner, false))) < interp_work(g, pending.push((id, false))), + { + model::lemma_graph_transition_wf(g, id@); + interp_lemma_work_push(g, pending, (id, true)); + interp_lemma_work_push(g, pending.push((id, true)), (inner, false)); + interp_lemma_work_push(g, pending, (id, false)); + } + + pub proof fn interp_lemma_work_branch(g: model::Graph, id: TransitionId, pending: Seq<(TransitionId, bool)>) + requires model::graph_wf(g), id@ < g.transitions.len(), interp_tasks_wf(g, pending), + g.transitions[id@ as int] is Union || g.transitions[id@ as int] is Intersect, + ensures interp_tasks_wf(g, pending.push((id, true)) + child_interp_tasks(g, id, 0)), + interp_work(g, pending.push((id, true)) + child_interp_tasks(g, id, 0)) < interp_work(g, pending.push((id, false))), + { + model::lemma_graph_transition_wf(g, id@); + let cs = transition_children(g, id); + let scheduled = child_interp_tasks(g, id, 0); + assert forall|i: int| 0 <= i < scheduled.len() + implies #[trigger] scheduled[i].0@ == cs[cs.len() as int - 1 - i] && !scheduled[i].1 by { + assert(cs[cs.len() as int - 1 - i] < id@); + } + interp_lemma_work_schedule(g, pending.push((id, true)), scheduled, cs, id@); + interp_lemma_work_push(g, pending, (id, true)); + interp_lemma_work_push(g, pending, (id, false)); + let all = pending.push((id, true)) + scheduled; + assert forall|i: int| 0 <= i < all.len() implies all[i].0@ < g.transitions.len() by { + if i < pending.len() { assert(all[i] == pending[i]); } + else if i > pending.len() { assert(all[i] == scheduled[i - pending.len() - 1]); } + } + } + + pub proof fn interp_lemma_step_post(before: model::Graph, after: model::Graph, id: TransitionId, finish: bool, + pending: Seq<(TransitionId, bool)>, tasks: Seq<(TransitionId, bool)>) + requires model::graph_extends(before, after), id@ < before.transitions.len(), interp_tasks_wf(before, pending), + tasks == pending || (interp_tasks_wf(before, tasks) + && interp_work(before, tasks) < interp_work(before, pending.push((id, finish)))), + ensures interp_work(after, tasks) < interp_work(before, pending.push((id, finish))), + { + interp_lemma_work_push(before, pending, (id, finish)); + interp_lemma_work_extends(before, after, tasks); + } + + pub open spec fn transition_children(g: model::Graph, id: TransitionId) -> Seq { + match g.transitions[id@ as int] { model::TransitionNode::Union(cs) | model::TransitionNode::Intersect(cs) => cs, _ => Seq::empty() } + } + + pub open spec fn transition_suffix(g: model::Graph, id: TransitionId) -> Seq { + match g.transitions[id@ as int] { model::TransitionNode::Append(_, cs) => cs, _ => Seq::empty() } + } + + pub open(crate) spec fn child_interp_tasks(g: model::Graph, id: TransitionId, remaining: nat) -> Seq<(TransitionId, bool)> { + Seq::new((transition_children(g, id).len() - remaining) as nat, |i: int| (TransitionId::from_view(transition_children(g, id)[transition_children(g, id).len() - 1 - i] as u32), false)) + } + + pub open spec fn regex_stack_equiv(sem: spec_fn(model::Test, EventView) -> bool, left: Seq, right: Seq) -> bool { + left.len() == right.len() && forall|i: int, word: Seq| 0 <= i < left.len() ==> + language::numeric_lang(sem, left[i], word) == language::numeric_lang(sem, right[i], word) + } + + pub open spec fn interp_results_equiv(sem: spec_fn(model::Test, EventView) -> bool, left: Option>, right: Option>) -> bool { + match (left, right) { (Some(a), Some(b)) => regex_stack_equiv(sem, a, b), (None, None) => true, _ => false } + } + + pub open spec fn interp_action(g: model::Graph, task: (TransitionId, bool), values: Seq, theta: Subst, event: EventView) -> Option> { + if !task.1 { Some(values.push(interpreted(g, task.0, theta, event))) } + else { + match g.transitions[task.0@ as int] { + model::TransitionNode::Union(cs) | model::TransitionNode::Intersect(cs) => { + if cs.len() > values.len() { None } + else { Some(values.take(values.len() - cs.len()).push( + if g.transitions[task.0@ as int] is Intersect { language::Regex::Intersect(values.skip(values.len() - cs.len())) } + else { language::Regex::Union(values.skip(values.len() - cs.len())) })) } + }, + model::TransitionNode::Not(_) => if values.len() == 0 { None } + else { Some(values.drop_last().push(language::Regex::Not(Box::new(values.last())))) }, + model::TransitionNode::Append(_, cs) => if values.len() == 0 { None } + else { Some(values.drop_last().push(language::Regex::Concat(seq![values.last()] + model::lift_regexes(g, cs)))) }, + _ => Some(values.push(interpreted(g, task.0, theta, event))), + } + } + } + + pub open spec fn interp_run(g: model::Graph, tasks: Seq<(TransitionId, bool)>, values: Seq, theta: Subst, event: EventView) -> Option> + decreases tasks.len(), + { + if tasks.len() == 0 { Some(values) } + else { match interp_action(g, tasks.last(), values, theta, event) { + Some(next) => interp_run(g, tasks.drop_last(), next, theta, event), None => None, + } } + } + + pub proof fn interp_run_unfold(g: model::Graph, tasks: Seq<(TransitionId, bool)>, values: Seq, theta: Subst, event: EventView) + ensures interp_run(g, tasks, values, theta, event) == if tasks.len() == 0 { Some(values) } + else { match interp_action(g, tasks.last(), values, theta, event) { + Some(next) => interp_run(g, tasks.drop_last(), next, theta, event), None => None, + } }, + { if tasks.len() == 0 {} else {} } + + pub proof fn regex_stack_equiv_trans(sem: spec_fn(model::Test, EventView) -> bool, a: Seq, b: Seq, c: Seq) + requires regex_stack_equiv(sem, a, b), regex_stack_equiv(sem, b, c), + ensures regex_stack_equiv(sem, a, c), + {} + + pub proof fn interp_results_equiv_trans(sem: spec_fn(model::Test, EventView) -> bool, a: Option>, b: Option>, c: Option>) + requires interp_results_equiv(sem, a, b), interp_results_equiv(sem, b, c), + ensures interp_results_equiv(sem, a, c), + { + match (a,b,c) { (Some(x),Some(y),Some(z)) => regex_stack_equiv_trans(sem,x,y,z), _ => {} } + } + + pub open spec fn regex_fold(values: Seq, intersect: bool) -> InterpRegex { + if intersect { language::Regex::Intersect(values) } else { language::Regex::Union(values) } + } + + pub proof fn regex_stack_fold_congruent(sem: spec_fn(model::Test, EventView) -> bool, left: Seq, right: Seq, intersect: bool) + requires regex_stack_equiv(sem, left, right), + ensures forall|word: Seq| language::numeric_lang(sem, regex_fold(left, intersect), word) + == language::numeric_lang(sem, regex_fold(right, intersect), word), + { + assert forall|word: Seq| language::numeric_lang(sem, regex_fold(left, intersect), word) + == language::numeric_lang(sem, regex_fold(right, intersect), word) by { + regex_fold_semantics(sem, left, intersect, word); + regex_fold_semantics(sem, right, intersect, word); + if !intersect { + if exists|i: int| 0 <= i < left.len() && language::numeric_lang(sem, left[i], word) { + let i = choose|i: int| 0 <= i < left.len() && language::numeric_lang(sem, left[i], word); + assert(language::numeric_lang(sem, right[i], word)); + } + if exists|i: int| 0 <= i < right.len() && language::numeric_lang(sem, right[i], word) { + let i = choose|i: int| 0 <= i < right.len() && language::numeric_lang(sem, right[i], word); + assert(language::numeric_lang(sem, left[i], word)); + } + } else { + if language::numeric_lang(sem, regex_fold(left, true), word) { + assert forall|i: int| 0 <= i < right.len() implies language::numeric_lang(sem, right[i], word) by { + assert(language::numeric_lang(sem, left[i], word)); + } + } + if language::numeric_lang(sem, regex_fold(right, true), word) { + assert forall|i: int| 0 <= i < left.len() implies language::numeric_lang(sem, left[i], word) by { + assert(language::numeric_lang(sem, right[i], word)); + } + } + } + } + } + + pub proof fn interp_action_congruent(g: model::Graph, task: (TransitionId, bool), left: Seq, right: Seq, theta: Subst, event: EventView) + requires regex_stack_equiv(model::gsem(theta), left, right), + ensures interp_results_equiv(model::gsem(theta), interp_action(g, task, left, theta, event), interp_action(g, task, right, theta, event)), + { + let sem = model::gsem(theta); + if task.1 { + match g.transitions[task.0@ as int] { + model::TransitionNode::Union(cs) | model::TransitionNode::Intersect(cs) => { + if cs.len() <= left.len() { + assert(regex_stack_equiv(sem, left.skip(left.len()-cs.len()), right.skip(right.len()-cs.len()))); + regex_stack_fold_congruent(sem, left.skip(left.len()-cs.len()), right.skip(right.len()-cs.len()), g.transitions[task.0@ as int] is Intersect); + } + }, + model::TransitionNode::Not(_) => { + if left.len() > 0 { + assert forall|word: Seq| language::numeric_lang(sem, language::Regex::Not(Box::new(left.last())), word) + == language::numeric_lang(sem, language::Regex::Not(Box::new(right.last())), word) by { + norm::regex_language_unfold(sem, language::Regex::Not(Box::new(left.last())), word); + norm::regex_language_unfold(sem, language::Regex::Not(Box::new(right.last())), word); + } + } + }, + model::TransitionNode::Append(_, cs) => { + if left.len() > 0 { + norm::regex_concat_congruent(sem, seq![left.last()] + model::lift_regexes(g, cs), seq![right.last()] + model::lift_regexes(g, cs)); + } + }, + _ => {}, + } + } + } + + pub proof fn interp_run_congruent(g: model::Graph, tasks: Seq<(TransitionId, bool)>, left: Seq, right: Seq, theta: Subst, event: EventView) + requires regex_stack_equiv(model::gsem(theta), left, right), + ensures interp_results_equiv(model::gsem(theta), interp_run(g, tasks, left, theta, event), interp_run(g, tasks, right, theta, event)), + decreases tasks.len(), + { + if tasks.len() > 0 { + interp_action_congruent(g, tasks.last(), left, right, theta, event); + match (interp_action(g, tasks.last(), left, theta, event), interp_action(g, tasks.last(), right, theta, event)) { + (Some(a),Some(b)) => interp_run_congruent(g, tasks.drop_last(), a, b, theta, event), _ => {}, + } + } + } + + pub proof fn interp_run_concat(g: model::Graph, prefix: Seq<(TransitionId, bool)>, suffix: Seq<(TransitionId, bool)>, values: Seq, theta: Subst, event: EventView) + ensures interp_run(g, prefix + suffix, values, theta, event) == match interp_run(g, suffix, values, theta, event) { + Some(next) => interp_run(g, prefix, next, theta, event), None => None, + }, + decreases suffix.len(), + { + if suffix.len() > 0 { + assert((prefix + suffix).last() == suffix.last()); + assert((prefix + suffix).drop_last() =~= prefix + suffix.drop_last()); + if let Some(next) = interp_action(g, suffix.last(), values, theta, event) { + interp_run_concat(g, prefix, suffix.drop_last(), next, theta, event); + } + } else { assert(prefix + suffix =~= prefix); } + } + + pub proof fn regex_fold_semantics(sem: spec_fn(model::Test, EventView) -> bool, values: Seq, intersect: bool, word: Seq) + ensures language::numeric_lang(sem, regex_fold(values, intersect), word) == if intersect { + forall|i: int| 0 <= i < values.len() ==> language::numeric_lang(sem, values[i], word) + } else { exists|i: int| 0 <= i < values.len() && language::numeric_lang(sem, values[i], word) }, + { + reveal(regex_fold); + if intersect { + language::lemma_lang_intersect::(sem, values, word); + } else { + language::lemma_lang_union::(sem, values, word); + } + } + + + pub open(crate) spec fn child_interp_values(g: model::Graph, id: TransitionId, theta: Subst, event: EventView) -> Seq { + Seq::new(transition_children(g, id).len(), |i: int| interpreted(g, TransitionId::from_view(transition_children(g, id)[i] as u32), theta, event)) + } + + pub proof fn child_interp_run(g: model::Graph, id: TransitionId, remaining: nat, values: Seq, theta: Subst, event: EventView) + requires model::graph_wf(g), id@ < g.transitions.len(), remaining <= transition_children(g, id).len(), + ensures interp_run(g, child_interp_tasks(g, id, remaining), values, theta, event) + == Some(values + child_interp_values(g, id, theta, event).skip(remaining as int)), + decreases transition_children(g, id).len() - remaining, + { + model::lemma_graph_transition_wf(g, id@); + let tasks = child_interp_tasks(g, id, remaining); + let vals = child_interp_values(g, id, theta, event); + if remaining < transition_children(g, id).len() { + let child = TransitionId::from_view(transition_children(g, id)[remaining as int] as u32); + assert(child@ == transition_children(g, id)[remaining as int]); + assert(tasks.last() == (child, false)); + assert(tasks.drop_last() =~= child_interp_tasks(g, id, remaining + 1)); + child_interp_run(g, id, remaining + 1, values.push(vals[remaining as int]), theta, event); + assert(values.push(vals[remaining as int]) + vals.skip(remaining as int + 1) =~= values + vals.skip(remaining as int)); + } else { + assert(tasks =~= Seq::empty()); + assert(vals.skip(remaining as int) =~= Seq::empty()); + assert(values + vals.skip(remaining as int) =~= values); + } + } + + pub proof fn interpreted_fold(g: model::Graph, id: TransitionId, theta: Subst, event: EventView) + requires model::graph_wf(g), id@ < g.transitions.len(), + g.transitions[id@ as int] is Union || g.transitions[id@ as int] is Intersect, + ensures forall|word: Seq| language::numeric_lang(model::gsem(theta), interpreted(g, id, theta, event), word) + == language::numeric_lang(model::gsem(theta), regex_fold(child_interp_values(g, id, theta, event), g.transitions[id@ as int] is Intersect), word), + { + model::lemma_graph_transition_wf(g, id@); + let children = Seq::new(transition_children(g, id).len(), |i: int| TransitionId::from_view(transition_children(g, id)[i] as u32)); + assert(model::transition_ids(children) =~= transition_children(g, id)); + norm::transition_lemma_children_language(g, id, children, g.transitions[id@ as int] is Intersect); + let vals = child_interp_values(g, id, theta, event); + assert forall|word: Seq| language::numeric_lang(model::gsem(theta), interpreted(g, id, theta, event), word) + == language::numeric_lang(model::gsem(theta), regex_fold(vals, g.transitions[id@ as int] is Intersect), word) by { + let sem = model::gsem(theta); + reveal(norm::transition_combo); + assert(norm::transition_lang(g, theta, id, event, word) + == language::numeric_lang(sem, interpreted(g, id, theta, event), word)); + assert forall|i: int| 0 <= i < children.len() implies + norm::transition_lang(g, theta, children[i], event, word) == language::numeric_lang(sem, vals[i], word) by {} + regex_fold_semantics(sem, vals, g.transitions[id@ as int] is Intersect, word); + if !(g.transitions[id@ as int] is Intersect) { + if norm::transition_lang(g, theta, id, event, word) { + let i = choose|i: int| 0 <= i < children.len() && norm::transition_lang(g, theta, children[i], event, word); + assert(language::numeric_lang(sem, vals[i], word)); + } + if language::numeric_lang(sem, regex_fold(vals, false), word) { + let i = choose|i: int| 0 <= i < vals.len() && language::numeric_lang(sem, vals[i], word); + assert(norm::transition_lang(g, theta, children[i], event, word)); + } + } else { + if norm::transition_lang(g, theta, id, event, word) { + assert forall|i: int| 0 <= i < vals.len() implies language::numeric_lang(sem, vals[i], word) by { + assert(norm::transition_lang(g, theta, children[i], event, word)); + } + } + if language::numeric_lang(sem, regex_fold(vals, true), word) { + assert forall|i: int| 0 <= i < children.len() implies norm::transition_lang(g, theta, children[i], event, word) by { + assert(language::numeric_lang(sem, vals[i], word)); + } + } + } + } + } + + pub proof fn interp_expand_set(g: model::Graph, id: TransitionId, tasks: Seq<(TransitionId, bool)>, values: Seq, theta: Subst, event: EventView) + requires model::graph_wf(g), id@ < g.transitions.len(), + g.transitions[id@ as int] is Union || g.transitions[id@ as int] is Intersect, + ensures interp_results_equiv(model::gsem(theta), + interp_run(g, tasks.push((id, false)), values, theta, event), + interp_run(g, tasks.push((id, true)) + child_interp_tasks(g, id, 0), values, theta, event)), + { + let vals = child_interp_values(g, id, theta, event); + child_interp_run(g, id, 0, values, theta, event); + interp_run_concat(g, tasks.push((id, true)), child_interp_tasks(g, id, 0), values, theta, event); + interpreted_fold(g, id, theta, event); + assert(vals.skip(0) =~= vals); + assert((values + vals).take(values.len() as int) =~= values); + assert((values + vals).skip(values.len() as int) =~= vals); + assert(tasks.push((id, true)).drop_last() =~= tasks); + assert(tasks.push((id, false)).drop_last() =~= tasks); + interp_run_unfold(g, tasks.push((id, true)), values + vals, theta, event); + interp_run_unfold(g, tasks.push((id, false)), values, theta, event); + interp_run_congruent(g, tasks, values.push(interpreted(g, id, theta, event)), values.push(regex_fold(vals, g.transitions[id@ as int] is Intersect)), theta, event); + } + + pub proof fn interp_action_stable(before: model::Graph, after: model::Graph, task: (TransitionId, bool), values: Seq, theta: Subst, event: EventView) + requires model::graph_wf(before), model::graph_extends(before, after), task.0@ < before.transitions.len(), + ensures interp_action(before, task, values, theta, event) == interp_action(after, task, values, theta, event), + { + model::lemma_graph_wf_elim(before); + model::lemma_lift_transition_stable(before, after, task.0@); + assert(before.transitions[task.0@ as int] == after.transitions[task.0@ as int]); + if let model::TransitionNode::Append(_, cs) = before.transitions[task.0@ as int] { + model::lemma_graph_transition_wf(before, task.0@); + assert(model::lift_regexes(before, cs) =~= model::lift_regexes(after, cs)) by { + assert forall|i: int| 0 <= i < cs.len() implies + model::lift_regexes(before, cs)[i] == model::lift_regexes(after, cs)[i] by { + model::lemma_lift_regex_stable(before, after, cs[i]); + } + } + } + } + + pub proof fn interp_run_stable(before: model::Graph, after: model::Graph, tasks: Seq<(TransitionId, bool)>, values: Seq, theta: Subst, event: EventView) + requires model::graph_wf(before), model::graph_extends(before, after), interp_tasks_wf(before, tasks), + ensures interp_run(before, tasks, values, theta, event) == interp_run(after, tasks, values, theta, event), + decreases tasks.len(), + { + if tasks.len() > 0 { + interp_action_stable(before, after, tasks.last(), values, theta, event); + if let Some(next) = interp_action(before, tasks.last(), values, theta, event) { + interp_run_stable(before, after, tasks.drop_last(), next, theta, event); + } + } + } + + pub proof fn lifted_values_stable(before: model::Graph, after: model::Graph, ids: Seq) + requires model::graph_wf(before), model::graph_extends(before, after), norm::regex_ids_valid(before, ids), + ensures norm::regex_ids_valid(after, ids), lifted_values(before, ids) == lifted_values(after, ids), + { + model::lemma_graph_wf_elim(before); + assert(lifted_values(before, ids) =~= lifted_values(after, ids)) by { + assert forall|i: int| 0 <= i < ids.len() implies model::lift_regex(before, ids[i]@) == model::lift_regex(after, ids[i]@) by { + model::lemma_lift_regex_stable(before, after, ids[i]@); + } + } + } + + pub open spec fn interp_set_result(g: model::Graph, before: Seq, after: Seq, count: nat, intersect: bool) -> bool { + count <= before.len() && forall|theta: Subst| language::event_wf(theta, theta.len()) ==> + regex_stack_equiv(model::gsem(theta), lifted_values(g, after), + lifted_values(g, before.take(before.len() - count)).push(regex_fold(lifted_values(g, before.skip(before.len() - count)), intersect))) + } + + pub open spec fn interp_machine_relation(before: model::Graph, after: model::Graph, + tasks0: Seq<(TransitionId, bool)>, tasks1: Seq<(TransitionId, bool)>, values0: Seq, values1: Seq, atoms: Seq, words: Seq) -> bool { + forall|theta: Subst, event: EventView| + language::event_wf(theta, theta.len()) && truth_words_realize(before, atoms, words, theta, event) ==> + interp_results_equiv(model::gsem(theta), + interp_run(before, tasks0, lifted_values(before, values0), theta, event), + interp_run(after, tasks1, lifted_values(after, values1), theta, event)) + } + + pub proof fn interp_same_configuration_extends(before: model::Graph, after: model::Graph, + tasks: Seq<(TransitionId, bool)>, values: Seq, theta: Subst, event: EventView) + requires model::graph_wf(before), model::graph_extends(before, after), interp_tasks_wf(before, tasks), norm::regex_ids_valid(before, values), + ensures interp_tasks_wf(after, tasks), + interp_run(before, tasks, lifted_values(before, values), theta, event) + == interp_run(after, tasks, lifted_values(after, values), theta, event), + { + lifted_values_stable(before, after, values); + interp_run_stable(before, after, tasks, lifted_values(before, values), theta, event); + } + + pub proof fn regex_fold_ids(g: model::Graph, ids: Seq, intersect: bool, theta: Subst, word: Seq) + ensures norm::regex_combo(g, theta, ids, word, intersect) + == language::numeric_lang(model::gsem(theta), regex_fold(lifted_values(g, ids), intersect), word), + { + let sem = model::gsem(theta); + let vals = lifted_values(g, ids); + reveal(norm::regex_combo); + regex_fold_semantics(sem, vals, intersect, word); + assert forall|i: int| 0 <= i < ids.len() implies + model::regex_lang(g, theta, ids[i]@, word) == language::numeric_lang(sem, vals[i], word) by {} + if !intersect { + if norm::regex_combo(g, theta, ids, word, false) { + let i = choose|i: int| 0 <= i < ids.len() && model::regex_lang(g, theta, ids[i]@, word); + assert(language::numeric_lang(sem, vals[i], word)); + } + if language::numeric_lang(sem, regex_fold(vals, false), word) { + let i = choose|i: int| 0 <= i < vals.len() && language::numeric_lang(sem, vals[i], word); + assert(model::regex_lang(g, theta, ids[i]@, word)); + } + } else { + if norm::regex_combo(g, theta, ids, word, true) { + assert forall|i: int| 0 <= i < vals.len() implies language::numeric_lang(sem, vals[i], word) by { + assert(model::regex_lang(g, theta, ids[i]@, word)); + } + } + if language::numeric_lang(sem, regex_fold(vals, true), word) { + assert forall|i: int| 0 <= i < ids.len() implies model::regex_lang(g, theta, ids[i]@, word) by { + assert(language::numeric_lang(sem, vals[i], word)); + } + } + } + } + + pub proof fn interp_value_reduction(g: model::Graph, id: TransitionId, finish: bool, tasks: Seq<(TransitionId, bool)>, before: Seq, after: Seq, theta: Subst, event: EventView) + requires interp_action(g, (id, finish), before, theta, event) is Some, + regex_stack_equiv(model::gsem(theta), interp_action(g, (id, finish), before, theta, event)->Some_0, after), + ensures interp_results_equiv(model::gsem(theta), + interp_run(g, tasks.push((id, finish)), before, theta, event), interp_run(g, tasks, after, theta, event)), + { + assert(tasks.push((id, finish)).drop_last() =~= tasks); + interp_run_unfold(g, tasks.push((id, finish)), before, theta, event); + interp_run_congruent(g, tasks, interp_action(g, (id, finish), before, theta, event)->Some_0, after, theta, event); + } + + pub proof fn interp_expand_unary(g: model::Graph, id: TransitionId, inner: TransitionId, tasks: Seq<(TransitionId, bool)>, values: Seq, theta: Subst, event: EventView) + requires model::graph_wf(g), id@ < g.transitions.len(), + g.transitions[id@ as int] == model::TransitionNode::Not(inner@) + || g.transitions[id@ as int] == model::TransitionNode::Append(inner@, transition_suffix(g, id)), + ensures interp_run(g, tasks.push((id, false)), values, theta, event) + == interp_run(g, tasks.push((id, true)).push((inner, false)), values, theta, event), + { + norm::transition_unfold(g, id@); + let sem = model::gsem(theta); + let term = model::lift_transition(g, inner@); + match g.transitions[id@ as int] { + model::TransitionNode::Not(_) => language::lemma_interp_not(sem, event, term), + model::TransitionNode::Append(_, cs) => language::lemma_interp_append(sem, event, term, model::lift_regexes(g, cs)), + _ => {}, + } + assert(tasks.push((id, false)).drop_last() =~= tasks); + assert(tasks.push((id, true)).push((inner, false)).drop_last() =~= tasks.push((id, true))); + assert(tasks.push((id, true)).drop_last() =~= tasks); + assert(values.push(interpreted(g, inner, theta, event)).drop_last() =~= values); + interp_run_unfold(g, tasks.push((id, false)), values, theta, event); + interp_run_unfold(g, tasks.push((id, true)).push((inner, false)), values, theta, event); + interp_run_unfold(g, tasks.push((id, true)), values.push(interpreted(g, inner, theta, event)), theta, event); + } + + pub proof fn interp_choose(g: model::Graph, id: TransitionId, finish: bool, test: TestId, a: TransitionId, b: TransitionId, chosen: TransitionId, tasks: Seq<(TransitionId, bool)>, values: Seq, theta: Subst, event: EventView) + requires model::graph_wf(g), id@ < g.transitions.len(), g.transitions[id@ as int] == model::TransitionNode::If(test@, a@, b@), + chosen == if model::test_holds(theta, model::lift_test(g, test@), event) { a } else { b }, + ensures interp_run(g, tasks.push((id, finish)), values, theta, event) + == interp_run(g, tasks.push((chosen, false)), values, theta, event), + { + norm::transition_unfold(g, id@); + language::lemma_interp_if(model::gsem(theta), event, model::lift_test(g, test@), model::lift_transition(g, a@), model::lift_transition(g, b@)); + assert(tasks.push((id, finish)).drop_last() =~= tasks); + assert(tasks.push((chosen, false)).drop_last() =~= tasks); + interp_run_unfold(g, tasks.push((id, finish)), values, theta, event); + interp_run_unfold(g, tasks.push((chosen, false)), values, theta, event); + } + + pub proof fn interp_append_ids(g: model::Graph, ids: Seq, head: RegexId, suffix: Seq) + requires model::regex_ids(ids) == seq![head@] + suffix, + ensures lifted_values(g, ids) == seq![model::lift_regex(g, head@)] + model::lift_regexes(g, suffix), + { + reveal(model::regex_ids); + assert(model::regex_ids(ids).len() == ids.len()); + assert(ids.len() == 1 + suffix.len()); + assert forall|i: int| 0 <= i < ids.len() implies lifted_values(g, ids)[i] + == (seq![model::lift_regex(g, head@)] + model::lift_regexes(g, suffix))[i] by { + assert(model::regex_ids(ids)[i] == ids[i]@); + if i == 0 { assert(ids[i]@ == head@); } + else { assert(ids[i]@ == suffix[i - 1]); } + } + assert(lifted_values(g, ids) =~= seq![model::lift_regex(g, head@)] + model::lift_regexes(g, suffix)); + } + + + pub proof fn regex_concat_ids(g: model::Graph, ids: Seq) + ensures model::lift_regexes(g, model::regex_ids(ids)) == lifted_values(g, ids), + { assert(model::lift_regexes(g, model::regex_ids(ids)) =~= lifted_values(g, ids)); } + + #[verifier::spinoff_prover] + pub proof fn interp_append_finish( + before: model::Graph, after: model::Graph, root: TransitionId, + pending: Seq<(TransitionId, bool)>, prior: Seq, head: RegexId, + xs: Seq, values: Seq, + ) + requires model::graph_wf(before), model::graph_wf(after), model::graph_extends(before, after), + root@ < before.transitions.len(), before.transitions[root@ as int] is Append, + interp_tasks_wf(before, pending), norm::regex_ids_valid(before, prior), + prior.len() > 0, prior.last() == head, values.len() == prior.len(), + values == prior.drop_last().push(values.last()), values.last()@ < after.regexes.len(), + model::regex_ids(xs) == seq![head@] + transition_suffix(before, root), + forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + ==> #[trigger] model::regex_lang(after, theta, values.last()@, word) == norm::concat_combo(after, theta, xs, word), + ensures norm::regex_ids_valid(after, values), + interp_stack_result(before, pending.push((root, true)), prior.len()) + == interp_stack_result(after, pending, values.len()), + forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) + ==> interp_results_equiv(model::gsem(theta), + interp_run(before, pending.push((root, true)), lifted_values(before, prior), theta, event), + interp_run(after, pending, lifted_values(after, values), theta, event)), + { + hide(language::numeric_lang); hide(language::interp_transition); hide(interp_run); + hide(model::test_holds); hide(model::lift_transition); hide(model::lift_regex); + after.transitions.lemma_prefix_index_eq(before.transitions); + assert(before.transitions[root@ as int] == after.transitions[root@ as int]); + assert(transition_suffix(before, root) == transition_suffix(after, root)); + lifted_values_stable(before, after, prior); + interp_append_ids(after, xs, head, transition_suffix(after, root)); + regex_concat_ids(after, xs); + assert forall|i: int| 0 <= i < values.len() implies values[i]@ < after.regexes.len() by { + if i < prior.len() - 1 { assert(values[i] == prior[i]); } + else { assert(values[i] == values.last()); } + } + assert(interp_tasks_wf(before, pending.push((root, true)))); + interp_stack_stable(before, after, pending.push((root, true)), prior.len()); + interp_stack_task(after, pending, (root, true), prior.len()); + assert forall|theta: Subst, event: EventView| language::event_wf(theta, theta.len()) implies + interp_results_equiv(model::gsem(theta), + interp_run(before, pending.push((root, true)), lifted_values(before, prior), theta, event), + interp_run(after, pending, lifted_values(after, values), theta, event)) by { + interp_same_configuration_extends(before, after, pending.push((root, true)), prior, theta, event); + assert forall|word: Seq| model::regex_lang(after, theta, values.last()@, word) + == language::numeric_lang(model::gsem(theta), language::Regex::Concat(seq![model::lift_regex(after, head@)] + + model::lift_regexes(after, transition_suffix(after, root))), word) by { + reveal(norm::concat_combo); + assert(model::regex_lang(after, theta, values.last()@, word) == norm::concat_combo(after, theta, xs, word)); + assert(model::lift_regexes(after, model::regex_ids(xs)) == lifted_values(after, xs)); + assert(lifted_values(after, xs) == seq![model::lift_regex(after, head@)] + model::lift_regexes(after, transition_suffix(after, root))); + } + assert(lifted_values(after, values) =~= lifted_values(after, prior).drop_last().push(model::lift_regex(after, values.last()@))); + assert(lifted_values(after, prior).last() == model::lift_regex(after, head@)); + assert forall|i: int, word: Seq| 0 <= i < prior.len() implies + language::numeric_lang(model::gsem(theta), interp_action(after, (root, true), lifted_values(after, prior), theta, event)->Some_0[i], word) + == language::numeric_lang(model::gsem(theta), lifted_values(after, values)[i], word) by { + if i == prior.len() - 1 { + assert(model::regex_lang(after, theta, values.last()@, word) + == language::numeric_lang(model::gsem(theta), language::Regex::Concat(seq![model::lift_regex(after, head@)] + + model::lift_regexes(after, transition_suffix(after, root))), word)); + } + } + interp_value_reduction(after, root, true, pending, lifted_values(after, prior), lifted_values(after, values), theta, event); + } + } + + + pub proof fn interp_root_stable(before: model::Graph, after: model::Graph, root: TransitionId) + requires model::graph_wf(before), model::graph_extends(before, after), root@ < before.transitions.len(), + ensures model::lift_transition(before, root@) == model::lift_transition(after, root@), + { + model::lemma_graph_wf_elim(before); + model::lemma_lift_transition_stable(before, after, root@); + } + } +} diff --git a/src/history-semantics/src/symbolic_language.rs b/src/history-semantics/src/symbolic_language.rs new file mode 100644 index 000000000..ab467148e --- /dev/null +++ b/src/history-semantics/src/symbolic_language.rs @@ -0,0 +1,921 @@ +//! A compiled tail stepped by classes of events instead of events. +//! +//! The runtime steps a residual by one event in three parts: it derives the residual +//! symbolically, evaluates the derivative's atoms on the event under the rule's bindings, and +//! interprets the derivative under those truth values. [`SymbolicLanguage`] exposes the first and +//! last parts, so a caller that knows only which atoms hold, such as a static analysis over +//! classes of events, follows exactly the runtime's derivatives and successors. It also reads the +//! nodes of residuals and their tests, so such a caller can compare residuals by the shape of their +//! normal forms. +//! +//! The facade's contracts retain the runtime's language equivalences and graph-class bounds. +//! It preserves the shared precondition, a well-formed compiled pair, by owning the pair and +//! rejecting identifiers that do not belong to its graph. Read callbacks receive the exact node +//! view without changing the pair. +//! Error guarantees are conditional on graph membership for reads and derivatives, and on a +//! cached atom set with a correctly sized, zero-padded truth assignment for successors. + +use alloc::vec::Vec; +use history_store::cache::EventClass; +use history_store::graph::RuntimeKernel; +use junco_core::errors::HistoryError; +use junco_core::flat::FlatPair; +use junco_core::kernel::{ + KernelStore, Primitive, RegexId, RegexView, TestId, TestView, TransitionId, +}; +use junco_core::limits::Unmetered; +use junco_core::observation::ObservationWorld; +#[cfg(verus_keep_ghost)] +use junco_core::spec::semantics::resource_error; +use smallvec::SmallVec; + +#[cfg(verus_keep_ghost)] +use crate::compile::verify as numeric; +#[cfg(verus_keep_ghost)] +use crate::normalize::verify as norm; +use crate::progress::CompiledPair; +#[cfg(verus_keep_ghost)] +use crate::progress::verify as reach; +use crate::symbolic::RegexDerivative; +#[cfg(verus_keep_ghost)] +use crate::symbolic::verify as symbolic; +#[cfg(verus_keep_ghost)] +use crate::verify::{finite_deriv as fder, finite_impl, finite_interp as fint}; +#[cfg(verus_keep_ghost)] +use history_store::cache::verify::*; +#[cfg(verus_keep_ghost)] +use junco_core::kernel::verify as model; +#[cfg(verus_keep_ghost)] +use junco_core::observation::SmallVecSpecFns; +#[cfg(verus_keep_ghost)] +use junco_core::verify::history_assumptions::*; +#[cfg(verus_keep_ghost)] +use junco_core::verify::history_specs::{self as language, EventView, Regex, Subst}; +#[cfg(verus_keep_ghost)] +use verify::*; +use vstd::prelude::*; + +#[cfg(verus_keep_ghost)] +verus! { +broadcast use junco_core::kernel::verify::group_kernel_views; +} + +/// A compiled tail whose residuals are stepped by classes of events. +/// +/// A class is given by the truth values of the positive atoms that a residual's derivative +/// tests: every event with those truth values has the same successor, under any bindings that +/// realize them. Residuals are canonical within one language, so equal identifiers denote equal +/// normal forms. +/// +/// The graph may be charged the budget given at compilation; an operation that would exceed it +/// fails with [`HistoryError::GraphBudget`]. The runtime's budget is +/// [`junco_core::limits::MAX_GRAPH_BYTES`] per compiled rule. +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Debug)] +pub struct SymbolicLanguage { + pub(crate) pair: CompiledPair, +} + +#[verus_verify] +impl SymbolicLanguage { + /// Compiles a numeric tail into a fresh graph, as the runtime does, that may be charged + /// `budget` bytes. Each of the graph's six arenas reserves `budget` bytes of address space, + /// which is committed as it fills. `budget` must be a multiple of 16. + /// With a layout-valid arena budget, a source with in-range backward references and a valid + /// root cannot fail internally; this does not require a binding head for symbolic variables. + #[verus_verify] + #[verus_spec(result => ensures + numeric::source_dag_wf(*template) && compile_budget_valid(budget) + ==> language::no_invariant_failure(result), + numeric::source_dag_wf(*template) && compile_budget_valid(budget) + ==> (result matches Err(error) ==> resource_error(error)), + result matches Ok(l) ==> language_wf(l) + && finite_impl::regex_nf(model::lift_regex(graph(l), root(l))) + && symbolic::regex_primitives(model::lift_regex(graph(l), root(l))).subset_of(numeric::source_primitives(*template)) + && forall|theta: Subst, word: Seq| language::event_wf(theta, theta.len()) + ==> model::regex_lang(graph(l), theta, root(l), word) + == numeric::source_regex(*template, template.root as nat, theta, word))] + pub fn compile(template: &FlatPair, budget: usize) -> Result { + proof! { reveal(language_wf); reveal(graph); reveal(root); } + let pair = CompiledPair::compile(template, budget, &mut Unmetered, &mut ObservationWorld)?; + Ok(Self { pair }) + } + + /// The residual of the empty history: the tail itself. + #[verus_verify] + #[verus_spec(result => requires language_wf(*self), + ensures result@ == root(*self), result@ < graph(*self).regexes.len())] + pub fn root(&self) -> RegexId { + proof! { reveal(language_wf); reveal(graph); reveal(root); } + self.pair.root + } + + /// Whether `residual` is the canonical empty language. A residual whose language is empty + /// need not be. + #[verus_verify] + #[verus_spec(result => requires language_wf(*self), + ensures result ==> abs(*self, residual) == Regex::Empty)] + pub fn is_empty(&self, residual: RegexId) -> bool { + proof! { reveal(language_wf); reveal(graph); norm::regex_constants(graph(*self)); } + residual == self.pair.store.constants().empty + } + + /// Whether `residual` accepts the empty history. + #[verus_verify] + #[verus_spec(result => requires language_wf(*old(self)), + ensures *final(self) == *old(self), + residual@ < graph(*old(self)).regexes.len() ==> language::no_invariant_failure(result), + residual@ < graph(*old(self)).regexes.len() + ==> (result matches Err(error) ==> resource_error(error)), + result matches Ok(value) ==> residual@ < graph(*final(self)).regexes.len() + && value == language::nullable(abs(*final(self), residual)))] + pub fn nullable(&mut self, residual: RegexId) -> Result { + self.read_regex( + residual, + verus_exec_expr! { + |node: RegexView<'_>| -> (value: bool) + ensures value == node.nullable, + { node.nullable } + }, + ) + } + + /// Reads the node of `residual`: its kind with its children, and its nullability. Unions and + /// intersections list their children in increasing identifier order. + #[verus_verify] + #[verus_spec(result => requires language_wf(*old(self)), + forall|view: RegexView<'_>| residual@ < graph(*old(self)).regexes.len() + && view@ == graph(*old(self)).regexes[residual@ as int] + ==> call_requires(read, (view,)), + ensures *final(self) == *old(self), + residual@ < graph(*old(self)).regexes.len() ==> language::no_invariant_failure(result), + residual@ < graph(*old(self)).regexes.len() + ==> (result matches Err(error) ==> resource_error(error)), + result matches Ok(value) ==> exists|view: RegexView<'_>| + residual@ < graph(*final(self)).regexes.len() + && view@ == graph(*final(self)).regexes[residual@ as int] + && abs(*final(self), residual) == model::lift_regex_kind(graph(*final(self)), view@.kind) + && view.nullable == language::nullable(abs(*final(self), residual)) + && call_ensures(read, (view,), value))] + pub fn read_regex( + &mut self, + residual: RegexId, + read: impl FnOnce(RegexView<'_>) -> R, + ) -> Result { + proof! { reveal(language_wf); reveal(graph); } + let (mut limits, mut world) = (Unmetered, ObservationWorld); + let kernel = RuntimeKernel { + store: &mut self.pair.store, + limits: &mut limits, + world: &mut world, + }; + let view = kernel.regex(residual)?; + proof! { norm::regex_unfold(kernel.graph(), residual@); } + Ok(read(view)) + } + + /// Reads the node of `test`: an atom, a constant, or the conjunction or disjunction of its + /// children, which are listed in increasing identifier order. + #[verus_verify] + #[verus_spec(result => requires language_wf(*old(self)), + forall|view: TestView<'_>| test@ < graph(*old(self)).tests.len() + && view@ == graph(*old(self)).tests[test@ as int] ==> call_requires(read, (view,)), + ensures *final(self) == *old(self), + test@ < graph(*old(self)).tests.len() ==> language::no_invariant_failure(result), + test@ < graph(*old(self)).tests.len() + ==> (result matches Err(error) ==> resource_error(error)), + result matches Ok(value) ==> exists|view: TestView<'_>| + test@ < graph(*final(self)).tests.len() + && view@ == graph(*final(self)).tests[test@ as int] + && call_ensures(read, (view,), value))] + pub fn read_test( + &mut self, + test: TestId, + read: impl FnOnce(TestView<'_>) -> R, + ) -> Result { + proof! { reveal(language_wf); reveal(graph); } + let (mut limits, mut world) = (Unmetered, ObservationWorld); + let kernel = RuntimeKernel { + store: &mut self.pair.store, + limits: &mut limits, + world: &mut world, + }; + Ok(read(kernel.test(test)?)) + } + + /// The derivative of `residual`, with the primitives of the positive atoms it tests in the + /// order of the truth bits that [`SymbolicLanguage::successor`] takes. + #[verus_verify] + #[verus_spec(result => requires language_wf(*old(self)), + ensures language_wf(*final(self)), frame(*old(self), *final(self)), + residual@ < graph(*old(self)).regexes.len() ==> language::no_invariant_failure(result), + residual@ < graph(*old(self)).regexes.len() + ==> (result matches Err(error) ==> resource_error(error)), + forall|i: int| 0 <= i < derivatives(*old(self)).len() && derivatives(*old(self))[i] is Some + ==> i < derivatives(*final(self)).len() && derivatives(*final(self))[i] == derivatives(*old(self))[i], + forall|t: TransitionId| has_atoms(*old(self), t) ==> has_atoms(*final(self), t) + && atom_ids(*final(self), t) == atom_ids(*old(self), t), + result matches Ok((t, prims)) ==> residual@ < graph(*old(self)).regexes.len() + && symbolic::derivative_correct(graph(*final(self)), residual@, t) + && fder::dbound(graph(*final(self)), residual@, t@) + && has_atoms(*final(self), t) + && reach::atoms_wf(graph(*final(self)), t@, atom_ids(*final(self), t)) + && residual@ < derivatives(*final(self)).len() + && derivatives(*final(self))[residual@ as int] == Some(t) + && prims@.len() == atom_ids(*final(self), t).len() + && prims@.len() <= u32::MAX as nat + 1 + && prims@.len() + 63 <= usize::MAX + && crate::verify::refinement::search::atoms_complete(abs(*final(self), residual), atom_primitives(*final(self), t)) + && atom_primitives(*final(self), t) == prims@.map_values(|p: Primitive| p@).to_set() + && atom_primitives(*final(self), t).subset_of(residual_primitives(*final(self), residual)) + && forall|i: int| 0 <= i < prims@.len() + ==> model::lift_test(graph(*final(self)), atom_ids(*final(self), t)[i]@) + == model::Test::Atom(prims@[i]@, true))] + pub fn derive( + &mut self, + residual: RegexId, + ) -> Result<(TransitionId, Vec), HistoryError> { + proof! { reveal(language_wf); reveal(graph); reveal(root); reveal(has_atoms); reveal(atom_ids); reveal(derivatives); } + proof! { self.pair.store.lemma_node_count_bounds(); } + proof_decl! { let ghost entry = self.pair; } + let (mut limits, mut world) = (Unmetered, ObservationWorld); + let transition = { + let mut kernel = RuntimeKernel { + store: &mut self.pair.store, + limits: &mut limits, + world: &mut world, + }; + kernel.regex(residual)?; + let result = + RegexId::derivative(residual, &mut kernel, &mut self.pair.caches.derivatives); + proof! { + reveal(frame); + reach::lemma_pair_symbolic_frame(entry, self.pair); + assert forall|i: int| 0 <= i < entry.caches.derivatives@.len() + && entry.caches.derivatives@[i] is Some implies + i < self.pair.caches.derivatives@.len() + && self.pair.caches.derivatives@[i] == entry.caches.derivatives@[i] by {} + } + result? + }; + proof_decl! { let ghost derived = self.pair.store.graph(); } + self.pair + .ensure_atoms(transition, &mut limits, &mut world)?; + proof! { + symbolic::derivative_correct_stable(derived, self.pair.store.graph(), residual@, transition); + fder::lemma_dbound_stable(derived, self.pair.store.graph(), residual@, transition@); + symbolic::derivative_extends(entry.store.graph(), self.pair.store.graph()); + } + proof_decl! { let ghost collected = self.pair; } + let atoms = CompiledPair::cached_atoms(self.pair.caches.atoms.as_slice(), transition)?; + let kernel = RuntimeKernel { + store: &mut self.pair.store, + limits: &mut limits, + world: &mut world, + }; + let mut primitives: Vec = Vec::with_capacity(atoms.ids().len()); + let ids = atoms.ids(); + let mut index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant index <= ids@.len(), primitives@.len() == index, + reach::pair_wf(collected), reach::pair_frame(entry, collected), + residual@ < entry.store.graph().regexes.len(), + reach::has_atoms(collected, transition), + self.pair.caches == collected.caches, self.pair.root == collected.root, + *kernel.store == collected.store, + ids@ == collected.caches.atoms@[transition@ as int].unwrap()@, + kernel.graph() == collected.store.graph(), + reach::atoms_wf(kernel.graph(), transition@, ids@), + symbolic::derivative_correct(kernel.graph(), residual@, transition), + fder::dbound(kernel.graph(), residual@, transition@), + forall|i: int| 0 <= i < primitives@.len() + ==> model::lift_test(kernel.graph(), ids@[i]@) == model::Test::Atom(primitives@[i]@, true), + decreases ids@.len() - index, + ))] + while index < ids.len() { + let id = ids[index]; + match kernel.test(id)? { + TestView::Atom { + primitive, + positive: true, + } => primitives.push(primitive), + _ => return Err(HistoryError::invalid_atom_set()), + } + index += 1; + } + proof! { + self.pair.store.lemma_node_count_bounds(); + reach::lemma_atom_count_bound(graph(*self), ids@); + assert forall|i: int| 0 <= i < primitives@.len() implies + graph(*self).tests[ids@[i]@ as int] == model::TestNode::Atom(primitives@[i]@, true) by { + reveal_with_fuel(model::lift_test, 1); + } + assert(atom_ids(*self, transition).map_values(|id: TestId| match graph(*self).tests[id@ as int] { + model::TestNode::Atom(p, _) => p, + _ => model::Primitive::Eq(history_syntax::Component(0), model::GTerm::Constant(0)), + }) =~= primitives@.map_values(|p: Primitive| p@)); + lemma_atoms_complete(*self, residual, transition); + lemma_atoms_vocabulary(*self, residual, transition); + } + Ok((transition, primitives)) + } + + /// The residual after one event of the class whose atom truths are `truth`: bit `i % 64` of + /// word `i / 64` is the truth of atom `i` of [`SymbolicLanguage::derive`]'s list. + #[verus_verify] + #[verus_spec(result => requires language_wf(*old(self)), + ensures language_wf(*final(self)), frame(*old(self), *final(self)), + has_atoms(*old(self), transition) + && symbolic::assignment_valid(atom_ids(*old(self), transition).len(), truth@) + ==> language::no_invariant_failure(result), + has_atoms(*old(self), transition) + && symbolic::assignment_valid(atom_ids(*old(self), transition).len(), truth@) + ==> (result matches Err(error) ==> resource_error(error)), + derivatives(*final(self)) == derivatives(*old(self)), + forall|t: TransitionId| has_atoms(*old(self), t) ==> has_atoms(*final(self), t) + && atom_ids(*final(self), t) == atom_ids(*old(self), t), + has_atoms(*old(self), transition) ==> atom_ids(*final(self), transition) == atom_ids(*old(self), transition), + result matches Ok(v) ==> has_atoms(*final(self), transition) + && v@ < graph(*final(self)).regexes.len() + && fint::entry_val(graph(*final(self)), transition@, v@) + && successors(*final(self)).contains_key(ClassKey { transition, words: truth@ }) + && successors(*final(self))[ClassKey { transition, words: truth@ }] == v + && forall|theta: Subst, e: EventView, w: Seq| + language::event_wf(theta, theta.len()) + && symbolic::truth_words_realize(graph(*final(self)), atom_ids(*final(self), transition), truth@, theta, e) + ==> model::regex_lang(graph(*final(self)), theta, v@, w) + == norm::transition_lang(graph(*final(self)), theta, transition, e, w))] + pub fn successor( + &mut self, + transition: TransitionId, + truth: &[u64], + ) -> Result { + proof! { reveal(language_wf); reveal(graph); reveal(root); reveal(has_atoms); reveal(atom_ids); reveal(successors); reveal(derivatives); } + proof_decl! { let ghost entry = self.pair; } + let (mut limits, mut world) = (Unmetered, ObservationWorld); + { + let kernel = RuntimeKernel { + store: &mut self.pair.store, + limits: &mut limits, + world: &mut world, + }; + kernel.transition(transition)?; + } + self.pair + .ensure_atoms(transition, &mut limits, &mut world)?; + let mut words = SmallVec::new(); + words.extend_from_slice(truth); + let key = EventClass { transition, words }; + let result = self.pair.successor(key, &mut limits, &mut world); + proof! { symbolic::derivative_extends(entry.store.graph(), self.pair.store.graph()); } + result + } +} + +#[cfg(verus_keep_ghost)] +pub mod verify { + use super::*; + pub use crate::progress::verify::{lemma_assignment_set, lemma_zero_truth_words}; + use crate::verify::refinement::encoding as enc; + use history_syntax::Component; + + verus! { + broadcast use junco_core::kernel::verify::group_kernel_views; + + /// Exact arena layout readiness, retaining the runtime's established default budget case. + pub open spec fn compile_budget_valid(budget: usize) -> bool { + budget == junco_core::limits::MAX_GRAPH_BYTES + || history_store::graph::verify::construction_layout(budget) + } + + #[cfg(target_pointer_width = "64")] + pub proof fn lemma_aligned_compile_budget(budget: usize) + requires budget as int % 16 == 0, + ensures compile_budget_valid(budget), + { + history_store::graph::verify::lemma_aligned_budget_layout(budget); + } + + pub open(crate) spec fn language_wf(l: SymbolicLanguage) -> bool { reach::pair_wf(l.pair) } + pub open(crate) spec fn graph(l: SymbolicLanguage) -> model::Graph { l.pair.store.graph() } + pub open(crate) spec fn root(l: SymbolicLanguage) -> nat { l.pair.root@ } + pub open spec fn abs(l: SymbolicLanguage, id: RegexId) -> Regex { + model::lift_regex(graph(l), id@) + } + pub open(crate) spec fn atom_ids(l: SymbolicLanguage, t: TransitionId) -> Seq { + l.pair.caches.atoms@[t@ as int].unwrap()@ + } + pub open(crate) spec fn has_atoms(l: SymbolicLanguage, t: TransitionId) -> bool { + reach::has_atoms(l.pair, t) + } + pub open(crate) spec fn derivatives(l: SymbolicLanguage) -> Seq> { + l.pair.caches.derivatives@ + } + pub open(crate) spec fn successors(l: SymbolicLanguage) -> Map { + successor_entries(l.pair.caches.successors) + } + pub open spec fn frame(a: SymbolicLanguage, b: SymbolicLanguage) -> bool { + model::graph_extends(graph(a), graph(b)) && root(a) == root(b) + } + + pub open spec fn residual_primitives(l: SymbolicLanguage, q: RegexId) -> Set { + symbolic::regex_primitives(abs(l, q)) + } + + /// Primitive payloads that the analyzer can represent without an invariant error. + pub open spec fn primitives_search_safe(ps: Set) -> bool { + forall|p: model::Primitive| #[trigger] ps.contains(p) ==> match p { + model::Primitive::Eq(_, model::GTerm::Constant(code)) => code <= u32::MAX, + model::Primitive::Eq(field, model::GTerm::Variable(variable)) => field == variable, + } + } + + pub open spec fn residual_search_safe(l: SymbolicLanguage, q: RegexId) -> bool { + primitives_search_safe(residual_primitives(l, q)) + } + + pub proof fn lemma_compiled_search_safe(template: FlatPair, l: SymbolicLanguage, q: RegexId) + requires q@ == root(l), + residual_primitives(l, q).subset_of(numeric::source_primitives(template)), + forall|i: int| #![trigger template.tests@[i]] 0 <= i < template.tests@.len() + ==> match template.tests@[i] { + junco_core::flat::FlatTest::Atom { field, term, .. } => match term { + junco_core::flat::FlatTerm::Constant(code) => code <= u32::MAX, + junco_core::flat::FlatTerm::Variable(variable) => field == variable, + }, + _ => true, + }, + ensures residual_search_safe(l, q), + { + assert forall|p: model::Primitive| residual_primitives(l, q).contains(p) + implies match p { + model::Primitive::Eq(_, model::GTerm::Constant(code)) => code <= u32::MAX, + model::Primitive::Eq(field, model::GTerm::Variable(variable)) => field == variable, + } by { + numeric::lemma_source_primitive_prefix(template, template.tests@.len(), p); + let i = choose|i: int| #![trigger template.tests@[i]] 0 <= i < template.tests@.len() + && match template.tests@[i] { + junco_core::flat::FlatTest::Atom { field, term, .. } => + p == model::Primitive::Eq(field, numeric::term_view(term)), + _ => false, + }; + } + } + + pub open spec fn primitive_codes(ps: Set, c: Component) -> Set { + ps.filter(|p: model::Primitive| match p { + model::Primitive::Eq(field, model::GTerm::Constant(_)) => field == c, + _ => false, + }).map(|p: model::Primitive| match p { + model::Primitive::Eq(_, model::GTerm::Constant(v)) => v, + _ => 0nat, + }) + } + + pub open spec fn residual_codes(l: SymbolicLanguage, q: RegexId, c: Component) -> Set { + primitive_codes(residual_primitives(l, q), c) + } + + pub proof fn lemma_residual_vocabulary_frame(a: SymbolicLanguage, b: SymbolicLanguage, q: RegexId) + requires language_wf(a), frame(a, b), q@ < graph(a).regexes.len(), + ensures residual_primitives(a, q) == residual_primitives(b, q), + forall|c: Component| residual_codes(a, q, c) == residual_codes(b, q, c), + { + lemma_language_wf(a); + symbolic::lemma_regex_primitives_stable(graph(a), graph(b), q@); + } + + pub proof fn lemma_primitive_codes_contains(ps: Set, c: Component, v: nat) + ensures primitive_codes(ps, c).contains(v) + == ps.contains(model::Primitive::Eq(c, model::GTerm::Constant(v))), + { + broadcast use vstd::set::group_set_lemmas; + let selected = ps.filter(|p: model::Primitive| match p { + model::Primitive::Eq(field, model::GTerm::Constant(_)) => field == c, + _ => false, + }); + let code = |p: model::Primitive| match p { + model::Primitive::Eq(_, model::GTerm::Constant(v)) => v, + _ => 0nat, + }; + selected.lemma_map_contains(code, v); + if primitive_codes(ps, c).contains(v) { + let p = choose|p: model::Primitive| selected.contains(p) && code(p) == v; + assert(p == model::Primitive::Eq(c, model::GTerm::Constant(v))); + } else if ps.contains(model::Primitive::Eq(c, model::GTerm::Constant(v))) { + assert(selected.contains(model::Primitive::Eq(c, model::GTerm::Constant(v)))); + } + } + + pub proof fn lemma_primitive_codes_mono(a: Set, b: Set) + requires a.subset_of(b), + ensures forall|c: Component| primitive_codes(a, c).subset_of(primitive_codes(b, c)), + { + assert forall|c: Component| primitive_codes(a, c).subset_of(primitive_codes(b, c)) by { + assert forall|v: nat| primitive_codes(a, c).contains(v) implies primitive_codes(b, c).contains(v) by { + lemma_primitive_codes_contains(a, c, v); + lemma_primitive_codes_contains(b, c, v); + } + } + } + + pub proof fn lemma_compiled_source_codes(l: SymbolicLanguage, q: RegexId, template: FlatPair) + requires residual_primitives(l, q).subset_of(numeric::source_primitives(template)), + ensures forall|c: Component| residual_codes(l, q, c).subset_of(numeric::source_codes(template, c)), + { + lemma_primitive_codes_mono(residual_primitives(l, q), numeric::source_primitives(template)); + } + + pub proof fn lemma_residual_code_mentions(l: SymbolicLanguage, q: RegexId, c: Component, v: nat) + ensures residual_codes(l, q, c).contains(v) == enc::regex_mentions(abs(l, q), c, v), + { + lemma_primitive_codes_contains(residual_primitives(l, q), c, v); + symbolic::lemma_regex_primitive_code(abs(l, q), c, v); + } + + pub proof fn lemma_successor_vocabulary(before: SymbolicLanguage, after: SymbolicLanguage, + q: RegexId, t: TransitionId, v: RegexId) + requires language_wf(before), language_wf(after), frame(before, after), + q@ < graph(before).regexes.len(), crate::verify::finite_impl::regex_nf(abs(before, q)), + fder::dbound(graph(before), q@, t@), fint::entry_val(graph(after), t@, v@), + ensures residual_primitives(after, v).subset_of(residual_primitives(before, q)), + forall|c: Component| residual_codes(after, v, c).subset_of(residual_codes(before, q, c)), + { + lemma_language_wf(before); + crate::verify::refinement::finiteness::lemma_impl_successor_abstracts( + graph(before), q@, t@, graph(after), v@); + if abs(after, v) != abs(before, q) { + symbolic::lemma_model_successor_vocab(abs(before, q), abs(after, v)); + } + assert forall|c: Component| residual_codes(after, v, c).subset_of(residual_codes(before, q, c)) by { + assert forall|k: nat| residual_codes(after, v, c).contains(k) implies residual_codes(before, q, c).contains(k) by { + lemma_primitive_codes_contains(residual_primitives(after, v), c, k); + lemma_primitive_codes_contains(residual_primitives(before, q), c, k); + } + } + } + + pub proof fn lemma_language_wf(l: SymbolicLanguage) + requires language_wf(l), + ensures model::graph_wf(graph(l)), root(l) < graph(l).regexes.len(), + forall|t: TransitionId| has_atoms(l, t) ==> t@ < graph(l).transitions.len() + && reach::atoms_wf(graph(l), t@, atom_ids(l, t)), + {} + + proof fn lemma_test_holds_atoms(g: model::Graph, id: nat, theta: Subst, e1: EventView, e2: EventView) + requires model::graph_wf(g), id < g.tests.len(), + forall|p: model::Primitive| reach::test_reaches_primitive(g, id, p) + ==> model::primitive_holds(theta, p, e1) == model::primitive_holds(theta, p, e2), + ensures model::test_holds(theta, model::lift_test(g, id), e1) + == model::test_holds(theta, model::lift_test(g, id), e2), + decreases id, + { + model::lemma_graph_test_wf(g, id); + reveal_with_fuel(model::lift_test, 1); + reveal_with_fuel(reach::test_reaches_primitive, 1); + match g.tests[id as int] { + model::TestNode::Atom(p, _) => { + assert(reach::test_reaches_primitive(g, id, p)); + }, + model::TestNode::And(cs) | model::TestNode::Or(cs) => { + assert forall|j: int| 0 <= j < cs.len() implies + model::test_holds(theta, model::lift_test(g, cs[j]), e1) + == model::test_holds(theta, model::lift_test(g, cs[j]), e2) by { + assert forall|p: model::Primitive| reach::test_reaches_primitive(g, cs[j], p) implies + model::primitive_holds(theta, p, e1) == model::primitive_holds(theta, p, e2) by { + assert(reach::test_edges(g, id) == cs); + assert(cs[j] < id); + assert(reach::test_edges(g, id)[j] == cs[j]); + assert(reach::test_reaches_primitive(g, id, p)); + } + lemma_test_holds_atoms(g, cs[j], theta, e1, e2); + } + }, + _ => {}, + } + } + + proof fn lemma_interp_transition_atoms(g: model::Graph, id: nat, theta: Subst, e1: EventView, e2: EventView) + requires model::graph_wf(g), id < g.transitions.len(), + forall|p: model::Primitive| reach::transition_reaches_primitive(g, id, p) + ==> model::primitive_holds(theta, p, e1) == model::primitive_holds(theta, p, e2), + ensures language::interp_transition(model::gsem(theta), e1, model::lift_transition(g, id)) + == language::interp_transition(model::gsem(theta), e2, model::lift_transition(g, id)), + decreases id, + { + model::lemma_graph_transition_wf(g, id); + reveal_with_fuel(model::lift_transition, 1); + reveal_with_fuel(language::interp_transition, 2); + reveal_with_fuel(model::lift_transitions, 1); + reveal_with_fuel(reach::transition_reaches_primitive, 1); + assert forall|j: int| #![trigger reach::transition_edges(g, id)[j]] + 0 <= j < reach::transition_edges(g, id).len() implies { + let child = reach::transition_edges(g, id)[j]; + language::interp_transition(model::gsem(theta), e1, model::lift_transition(g, child)) + == language::interp_transition(model::gsem(theta), e2, model::lift_transition(g, child)) + } by { + let child = reach::transition_edges(g, id)[j]; + assert(child < id); + assert forall|p: model::Primitive| reach::transition_reaches_primitive(g, child, p) implies + model::primitive_holds(theta, p, e1) == model::primitive_holds(theta, p, e2) by { + assert(reach::transition_reaches_primitive(g, id, p)); + } + lemma_interp_transition_atoms(g, child, theta, e1, e2); + } + match g.transitions[id as int] { + model::TransitionNode::If(t, a, b) => { + assert forall|p: model::Primitive| reach::test_reaches_primitive(g, t, p) implies + model::primitive_holds(theta, p, e1) == model::primitive_holds(theta, p, e2) by { + assert(reach::transition_tests(g, id) == seq![t]); + assert(reach::transition_tests(g, id)[0] == t); + assert(reach::transition_reaches_primitive(g, id, p)); + } + lemma_test_holds_atoms(g, t, theta, e1, e2); + assert(model::gsem(theta)(model::lift_test(g, t), e1) + == model::gsem(theta)(model::lift_test(g, t), e2)); + assert(reach::transition_edges(g, id)[0] == a); + assert(reach::transition_edges(g, id)[1] == b); + assert(language::interp_transition(model::gsem(theta), e1, model::lift_transition(g, a)) + == language::interp_transition(model::gsem(theta), e2, model::lift_transition(g, a))); + assert(language::interp_transition(model::gsem(theta), e1, model::lift_transition(g, b)) + == language::interp_transition(model::gsem(theta), e2, model::lift_transition(g, b))); + assert(language::interp_transition(model::gsem(theta), e1, model::lift_transition(g, id)) + == language::interp_transition(model::gsem(theta), e2, model::lift_transition(g, id))); + }, + model::TransitionNode::Union(cs) | model::TransitionNode::Intersect(cs) => { + let left = Seq::new(cs.len(), |j: int| + language::interp_transition(model::gsem(theta), e1, model::lift_transitions(g, cs, id)[j])); + let right = Seq::new(cs.len(), |j: int| + language::interp_transition(model::gsem(theta), e2, model::lift_transitions(g, cs, id)[j])); + assert(left =~= right) by { + assert forall|j: int| 0 <= j < cs.len() implies left[j] == right[j] by { + assert(reach::transition_edges(g, id)[j] == cs[j]); + } + } + let l = language::interp_transition(model::gsem(theta), e1, model::lift_transition(g, id)); + let r = language::interp_transition(model::gsem(theta), e2, model::lift_transition(g, id)); + if g.transitions[id as int] is Union { + assert(l is Union && r is Union); + assert(l->Union_0 =~= left); + assert(r->Union_0 =~= right); + } else { + assert(l is Intersect && r is Intersect); + assert(l->Intersect_0 =~= left); + assert(r->Intersect_0 =~= right); + } + assert(language::interp_transition(model::gsem(theta), e1, model::lift_transition(g, id)) + == language::interp_transition(model::gsem(theta), e2, model::lift_transition(g, id))); + }, + model::TransitionNode::Not(child) | model::TransitionNode::Append(child, _) => { + assert(reach::transition_edges(g, id)[0] == child); + assert(language::interp_transition(model::gsem(theta), e1, model::lift_transition(g, child)) + == language::interp_transition(model::gsem(theta), e2, model::lift_transition(g, child))); + assert(language::interp_transition(model::gsem(theta), e1, model::lift_transition(g, id)) + == language::interp_transition(model::gsem(theta), e2, model::lift_transition(g, id))); + }, + _ => {}, + } + } + + pub proof fn lemma_transition_lang_atoms(g: model::Graph, t: TransitionId, theta: Subst, + e1: EventView, e2: EventView, w: Seq) + requires model::graph_wf(g), t@ < g.transitions.len(), + forall|p: model::Primitive| reach::transition_reaches_primitive(g, t@, p) + ==> model::primitive_holds(theta, p, e1) == model::primitive_holds(theta, p, e2), + ensures norm::transition_lang(g, theta, t, e1, w) == norm::transition_lang(g, theta, t, e2, w), + { + lemma_interp_transition_atoms(g, t@, theta, e1, e2); + } + + spec fn node_code(n: model::TestNode) -> nat { + match n { + model::TestNode::Atom(model::Primitive::Eq(_, model::GTerm::Constant(v)), _) => v, + _ => 0, + } + } + spec fn graph_codes(g: model::Graph) -> Set { + g.tests.map_values(|n: model::TestNode| node_code(n)).to_set() + } + + proof fn lemma_test_codes(g: model::Graph, id: nat) + requires model::graph_wf(g), id < g.tests.len(), + ensures forall|c: Component, v: nat| + enc::test_mentions(model::lift_test(g, id), c, v) ==> graph_codes(g).contains(v), + decreases id, + { + model::lemma_graph_test_wf(g, id); + reveal_with_fuel(model::lift_test, 1); + reveal_with_fuel(enc::test_mentions, 1); + let codes = g.tests.map_values(|n: model::TestNode| node_code(n)); + codes.to_set_ensures(); + assert(codes[id as int] == node_code(g.tests[id as int])); + assert(codes.to_set().contains(codes[id as int])); + assert(graph_codes(g) == codes.to_set()); + assert forall|c: Component, v: nat| enc::test_mentions(model::lift_test(g, id), c, v) + implies graph_codes(g).contains(v) by { + match g.tests[id as int] { + model::TestNode::And(cs) | model::TestNode::Or(cs) => { + let ts = model::lift_tests(g, cs, id); + let j = choose|j: int| 0 <= j < ts.len() && enc::test_mentions(ts[j], c, v); + assert(ts[j] == model::lift_test(g, cs[j])); + lemma_test_codes(g, cs[j]); + }, + _ => {}, + } + } + } + + proof fn lemma_regex_codes(g: model::Graph, id: nat) + requires model::graph_wf(g), id < g.regexes.len(), + ensures forall|c: Component, v: nat| + enc::regex_mentions(model::lift_regex(g, id), c, v) ==> graph_codes(g).contains(v), + decreases id, + { + norm::regex_unfold(g, id); + reveal_with_fuel(enc::regex_mentions, 1); + assert forall|c: Component, v: nat| enc::regex_mentions(model::lift_regex(g, id), c, v) + implies graph_codes(g).contains(v) by { + match g.regexes[id as int].kind { + model::RegexKindNode::Test(t) => { + assert(enc::test_mentions(model::lift_test(g, t), c, v)); + lemma_test_codes(g, t); + assert(graph_codes(g).contains(v)); + }, + model::RegexKindNode::Union(cs) | model::RegexKindNode::Concat(cs) + | model::RegexKindNode::Intersect(cs) => { + let rs = model::lift_regexes(g, cs); + let j = choose|j: int| 0 <= j < rs.len() && enc::regex_mentions(rs[j], c, v); + assert(rs[j] == model::lift_regex(g, cs[j])); + lemma_regex_codes(g, cs[j]); + assert(graph_codes(g).contains(v)); + }, + model::RegexKindNode::Not(r) | model::RegexKindNode::Star(r) => { + lemma_regex_codes(g, r); + assert(enc::regex_mentions(model::lift_regex(g, r), c, v)); + assert(graph_codes(g).contains(v)); + }, + _ => { assert(!enc::regex_mentions(model::lift_regex(g, id), c, v)); }, + } + } + } + + proof fn lemma_bounded_renaming(fixed: Set, values: Set) -> (f: spec_fn(nat) -> nat) + requires fixed.len() + values.len() + 4 <= u64::MAX, + forall|x: nat| fixed.contains(x) ==> x <= u64::MAX, + ensures forall|x: nat, y: nat| #![trigger f(x), f(y)] f(x) == f(y) <==> x == y, + forall|x: nat| fixed.contains(x) ==> f(x) == x, + forall|x: nat| values.contains(x) ==> f(x) <= u64::MAX, + decreases values.len(), + { + broadcast use vstd::set::group_set_lemmas; + if values.len() == 0 { + values.lemma_len0_is_empty(); + |x: nat| x + } else { + let x = values.choose(); + if x <= u64::MAX { + let f = lemma_bounded_renaming(fixed.insert(x), values.remove(x)); + assert forall|z: nat| fixed.contains(z) implies f(z) == z by { + assert(fixed.insert(x).contains(z)); + } + assert forall|z: nat| values.contains(z) implies f(z) <= u64::MAX by { + if z == x { assert(fixed.insert(x).contains(x)); } + else { assert(values.remove(x).contains(z)); } + } + f + } else { + let forbidden = fixed.union(values); + vstd::set_lib::lemma_len_union(fixed, values); + let candidates = Set::::range(0, forbidden.len() + 1); + vstd::set_lib::range_set_properties(0nat, forbidden.len() + 1); + assert(exists|y: nat| candidates.contains(y) && !forbidden.contains(y)) by { + if !exists|y: nat| candidates.contains(y) && !forbidden.contains(y) { + assert(candidates.subset_of(forbidden)); + vstd::set_lib::lemma_len_subset(candidates, forbidden); + } + } + let y = choose|y: nat| candidates.contains(y) && !forbidden.contains(y); + let rest = lemma_bounded_renaming(fixed.insert(y), values.remove(x)); + let swap = |z: nat| if z == x { y } else if z == y { x } else { z }; + let f = |z: nat| rest(swap(z)); + assert forall|a: nat, b: nat| #![trigger f(a), f(b)] f(a) == f(b) <==> a == b by { + assert(swap(a) == swap(b) <==> a == b); + } + assert forall|z: nat| fixed.contains(z) implies f(z) == z by { + assert(z != x && z != y); + assert(fixed.insert(y).contains(z)); + } + assert forall|z: nat| values.contains(z) implies f(z) <= u64::MAX by { + if z == x { assert(fixed.insert(y).contains(y)); } + else { assert(z != y); assert(values.remove(x).contains(z)); } + } + f + } + } + } + + pub open spec fn atom_primitives(l: SymbolicLanguage, t: TransitionId) -> Set { + atom_ids(l, t).map_values(|id: TestId| match graph(l).tests[id@ as int] { + model::TestNode::Atom(p, _) => p, + _ => model::Primitive::Eq(history_syntax::Component(0), model::GTerm::Constant(0)), + }).to_set() + } + + pub proof fn lemma_atoms_vocabulary(l: SymbolicLanguage, q: RegexId, t: TransitionId) + requires language_wf(l), has_atoms(l, t), q@ < derivatives(l).len(), derivatives(l)[q@ as int] == Some(t), + ensures atom_primitives(l, t).subset_of(residual_primitives(l, q)), + { + broadcast use vstd::set::group_set_lemmas; + reveal(language_wf); reveal(graph); reveal(has_atoms); reveal(atom_ids); reveal(derivatives); + lemma_language_wf(l); + symbolic::derivative_cached_bound(graph(l), derivatives(l), q, t); + let ids = atom_ids(l, t); + let ps = ids.map_values(|id: TestId| match graph(l).tests[id@ as int] { + model::TestNode::Atom(p, _) => p, + _ => model::Primitive::Eq(Component(0), model::GTerm::Constant(0)), + }); + ps.to_set_ensures(); + assert forall|p: model::Primitive| atom_primitives(l, t).contains(p) implies residual_primitives(l, q).contains(p) by { + let i = ps.lemma_contains_to_index(p); + assert(graph(l).tests[ids[i]@ as int] == model::TestNode::Atom(p, true)); + assert(reach::has_positive(graph(l), ids, p)); + assert(reach::transition_reaches_primitive(graph(l), t@, p)); + symbolic::lemma_transition_primitives_lift(graph(l), t@, p); + } + } + + /// Renaming only candidate values permits the frozen all-`nat` completeness quantifier. + pub proof fn lemma_atoms_complete(l: SymbolicLanguage, q: RegexId, t: TransitionId) + requires language_wf(l), has_atoms(l, t), symbolic::derivative_correct(graph(l), q@, t), + ensures crate::verify::refinement::search::atoms_complete(abs(l, q), atom_primitives(l, t)), + { + let g = graph(l); + let fixed = graph_codes(g); + lemma_language_wf(l); + l.pair.store.lemma_constant_bounds(); + l.pair.store.lemma_node_count_bounds(); + g.tests.map_values(|n: model::TestNode| node_code(n)).lemma_cardinality_of_set(); + g.tests.map_values(|n: model::TestNode| node_code(n)).to_set_ensures(); + let primitives = atom_ids(l, t).map_values(|id: TestId| match g.tests[id@ as int] { + model::TestNode::Atom(p, _) => p, + _ => model::Primitive::Eq(Component(0), model::GTerm::Constant(0)), + }); + primitives.to_set_ensures(); + assert(primitives.to_set() == atom_primitives(l, t)); + assert forall|v: nat| fixed.contains(v) implies v <= u64::MAX by { + let i = choose|i: int| 0 <= i < g.tests.len() && node_code(g.tests[i]) == v; + match g.tests[i] { + model::TestNode::Atom(model::Primitive::Eq(c, model::GTerm::Constant(k)), positive) => { + assert(k <= u64::MAX); + }, + _ => {}, + } + } + lemma_regex_codes(g, q@); + assert forall|theta: Subst, e1: EventView, e2: EventView, w: Seq| + theta.len() <= history_syntax::MAX_ARITY + && (forall|p: model::Primitive| atom_primitives(l, t).contains(p) + ==> model::primitive_holds(theta, p, e1) == model::primitive_holds(theta, p, e2)) + implies language::numeric_lang(model::gsem(theta), abs(l, q), seq![e1] + w) + == language::numeric_lang(model::gsem(theta), abs(l, q), seq![e2] + w) by { + theta.lemma_cardinality_of_set(); + theta.to_set_ensures(); + let values = theta.to_set(); + let f = lemma_bounded_renaming(fixed, values); + let ft = enc::n_rename_event(f, theta); + let fe1 = enc::n_rename_event(f, e1); + let fe2 = enc::n_rename_event(f, e2); + let fw = enc::n_rename_history(f, w); + assert forall|i: int| 0 <= i < ft.len() implies ft[i] <= u64::MAX by { + assert(values.contains(theta[i])); + } + assert(language::event_wf(ft, ft.len())); + assert(enc::n_renaming_ok(f, fixed.to_iset(), ISet::full())); + assert forall|p: model::Primitive| reach::transition_reaches_primitive(g, t@, p) implies + model::primitive_holds(ft, p, fe1) == model::primitive_holds(ft, p, fe2) by { + assert(reach::has_positive(g, atom_ids(l, t), p)); + let i = choose|i: int| 0 <= i < atom_ids(l, t).len() + && atom_ids(l, t)[i]@ < g.tests.len() + && g.tests[atom_ids(l, t)[i]@ as int] == model::TestNode::Atom(p, true); + assert(primitives[i] == p); + assert(primitives.to_set().contains(primitives[i])); + assert(atom_primitives(l, t).contains(p)); + let id = atom_ids(l, t)[i]@; + lemma_test_codes(g, id); + enc::lemma_test_rename(model::lift_test(g, id), theta, f, fixed.to_iset(), ISet::full(), e1); + enc::lemma_test_rename(model::lift_test(g, id), theta, f, fixed.to_iset(), ISet::full(), e2); + } + lemma_transition_lang_atoms(g, t, ft, fe1, fe2, fw); + let u1 = seq![e1] + w; + let u2 = seq![e2] + w; + let v1 = seq![fe1] + fw; + let v2 = seq![fe2] + fw; + assert(junco_core::verify::encoding::pointwise(u1, v1, enc::n_renamed(f, ISet::full()))); + assert(junco_core::verify::encoding::pointwise(u2, v2, enc::n_renamed(f, ISet::full()))); + enc::lemma_lang_rename(abs(l, q), theta, f, fixed.to_iset(), ISet::full(), u1, v1); + enc::lemma_lang_rename(abs(l, q), theta, f, fixed.to_iset(), ISet::full(), u2, v2); + } + } + } +} diff --git a/src/history-semantics/src/validator.rs b/src/history-semantics/src/validator.rs new file mode 100644 index 000000000..3b50cf76c --- /dev/null +++ b/src/history-semantics/src/validator.rs @@ -0,0 +1,743 @@ +//! Ordered authorization and append-on-grant request handling. +//! +//! Checked ordered selection composes the rule evaluator with atomic history transactions. +//! Numeric residual caches retain their existing native boundary. + +use alloc::{borrow::ToOwned, string::String, sync::Arc, vec::Vec}; + +use crate::compiled_rule::CompiledRule; +#[cfg(verus_keep_ghost)] +use crate::spec::monitor::{ValidatorView, check_frame, check_step, permits_result, rollback_step}; +#[cfg(verus_keep_ghost)] +use history_store::history::verify as raw; +use history_store::history::{Checkpoint, History}; +use history_store::typed::Store; +use history_syntax::Event; +#[cfg(verus_keep_ghost)] +use history_syntax::event::specs::EventSpec; +#[cfg(verus_keep_ghost)] +use history_syntax::spec::events::RuleView; +use history_syntax::syntax::{Rule, RuleMode}; +use junco_core::errors::{CompileError, HistoryError}; +use junco_core::event::{Grant, Request}; +use junco_core::limits::{Limits, Unmetered}; +use junco_core::observation::ObservationWorld; +#[cfg(verus_keep_ghost)] +use junco_core::spec::hypotheses::event_obligations; +#[cfg(verus_keep_ghost)] +use junco_core::spec::semantics as sem; +#[cfg(verus_keep_ghost)] +use junco_core::verify::history_specs::{no_invariant_compile_failure, no_invariant_failure}; +use vstd::prelude::*; + +/// Diagnostic returned when the first matching rule is violated. +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Denial { + /// Zero-based source-order index of the first violated rule. + pub index: usize, + /// Whether the violated rule required or forbade its tail language. + pub mode: RuleMode, + /// Candidate event that was denied and was not appended to history. + pub event: E, + /// Human-readable explanation of the failed history relation. + pub message: String, +} + +/// Result of checking one capability request. +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Decision { + /// Request was accepted and appended to committed history. + Grant(Grant), + /// Request was rejected atomically; committed history is unchanged. + Denied(Denial), +} + +#[verus_verify] +impl Decision { + /// Returns `true` exactly for [`Decision::Grant`]. + #[verus_spec(result => ensures result == (self is Grant))] + pub fn is_grant(&self) -> bool { + matches!(self, Self::Grant(_)) + } +} + +/// Compiles an ordered rule set sharing one typed store. +#[verus_verify] +pub struct ValidatorBuilder { + pub(crate) store: Arc>, + pub(crate) rules: Vec>, +} + +#[cfg(verus_keep_ghost)] +verus! { +impl ValidatorBuilder { + /// Opaque well-formedness: every compiled rule lives in the builder's store. + pub closed spec fn wf(&self) -> bool { verify::builder_wf(*self) } + /// Views of the rules passed to `add_rule`, in order. + pub closed spec fn rules(&self) -> Seq> { + sem::rule_views(verify::builder_sources(*self)) + } +} + +impl View for Validator { + type V = ValidatorView; + /// Monitor-specification view: the rules passed to `add_rule`, in order, and the committed history. + closed spec fn view(&self) -> ValidatorView { + ValidatorView { + rules: sem::rule_views(verify::validator_sources(*self)), + history: raw::raw_events(self.history), + } + } +} + +impl Validator { + /// Opaque well-formedness: committed history and compiled table share one store. + pub closed spec fn wf(&self) -> bool { verify::validator_wf(*self) } +} +} + +#[verus_verify] +impl ValidatorBuilder { + /// Creates an empty builder in `store`. + #[verus_spec(result => requires history_store::typed::verify::store_wf(*store), + ensures result.wf(), result.rules() == Seq::>::empty())] + pub fn new(store: Arc>) -> Self { + let builder = Self { + store, + rules: Vec::new(), + }; + proof! { assert(builder.rules() =~= Seq::>::empty()); } + builder + } + + /// Compiles and appends one complete source rule. + /// Under the event laws, a well-formed, correctly tagged rule of the event arity has only resource-error exits. + #[verus_spec(result => requires old(self).wf(), + ensures event_obligations::() ==> no_invariant_compile_failure(result), + event_obligations::() && sem::rule_wf(source@) + && source@.head.len() == history_syntax::spec::events::arity::() + && sem::rule_constants_tagged::(source@) + ==> (result is Ok || (result matches Err(CompileError::Runtime(error)) && sem::resource_error(error))), + match result { + Err(_) => final(self).wf() && final(self).rules() == old(self).rules(), + Ok(borrow) => mut_ref_current(borrow).wf() + && mut_ref_current(borrow).rules() == old(self).rules().push(source@) + && (event_obligations::() ==> junco_core::spec::semantics::rule_wf(source@) + && source@.head.len() == history_syntax::spec::events::arity::() + && junco_core::verify::flatten::head_coordinates_wf::(source@.head)) + && mut_ref_future(borrow) == *final(self), + })] + pub fn add_rule(&mut self, source: Rule) -> Result<&mut Self, CompileError> { + proof_decl! { let ghost before = *self; let ghost supplied = source; } + if ObservationWorld + .try_reserve_vec(&mut self.rules, 1) + .is_err() + { + source.dispose(); + return Err(HistoryError::AllocationFailed.into()); + } + let runtime = CompiledRule::new(self.store.clone(), source)?; + proof! { + if event_obligations::() { + let flat = choose|flat: junco_core::flat::FlatRule| + junco_core::verify::flatten::flattened::(supplied, flat) + && junco_core::verify::encoding::lowering(flat.source, runtime.template, + runtime.maps@, junco_core::verify::flatten::component_equality::()) + && junco_core::verify::encoding::constants_in_domain(flat.source, + history_store::typed::verify::domain::()); + assert forall|i: int| 0 <= i < supplied@.head.len() implies + match #[trigger] supplied@.head[i] { + history_syntax::spec::events::PatternView::Constant(value) => E::coordinate_spec(value) == i, + _ => true, + } by { + assert(junco_core::verify::flatten::head_slot_represents(flat.source.head@[i], supplied@.head[i])); + assert(junco_core::verify::encoding::head_in_domain(flat.source.head@[i], + junco_core::verify::encoding::field_at(i), history_store::typed::verify::domain::())); + } + } + } + self.rules.push(runtime); + proof! { + assert(verify::builder_sources(*self) =~= verify::builder_sources(before).push(supplied)); + assert(self.rules() =~= before.rules().push(supplied@)); + assert forall|i: int| 0 <= i < self.rules@.len() implies + crate::compiled_rule::verify::compiled_wf(self.rules@[i]) && self.rules@[i].store == self.store by { + if i < before.rules@.len() { assert(self.rules@[i] == before.rules@[i]); } + } + } + Ok(self) + } + + /// Creates the validator with the empty committed history in the rules' store. + #[verus_spec(result => requires self.wf(), + ensures event_obligations::() ==> no_invariant_failure(result), + result matches Ok(validator) ==> validator.wf() + && validator@.rules == self.rules() && validator@.history == Seq::::empty())] + pub fn finish(self) -> Result, HistoryError> { + let history = History::new(self.store)?; + proof! { raw::lemma_empty_history(history, self.store); } + Ok(Validator { + rules: self.rules, + history, + }) + } +} + +/// Stateful validator for a fixed ordered rule set. +#[verus_verify] +pub struct Validator { + pub(crate) rules: Vec>, + pub(crate) history: History, +} + +#[verus_verify] +impl Validator { + /// Starts compiling a validator in `store`. + #[verus_spec(result => requires history_store::typed::verify::store_wf(*store), + ensures result.wf(), result.rules() == Seq::>::empty())] + pub fn builder(store: Arc>) -> ValidatorBuilder { + ValidatorBuilder::new(store) + } + + /// Authorizes a request, appending its exact event only after successful evaluation + /// (`check_frame`); under the event laws the decision means `check_step`. + #[verus_spec(result => requires old(self).wf(), + ensures final(self).wf(), + check_frame(old(self)@, final(self)@, request, result), + event_obligations::() ==> check_step(old(self)@, request, result), + event_obligations::() ==> (result matches Err(error) ==> sem::resource_error(error)), + result matches Ok(Decision::Denied(denial)) ==> verify::denial_message(denial), + raw::owner_frame(verify::validator_history(*old(self)), verify::validator_history(*final(self))))] + pub fn check(&mut self, request: Request) -> Result, HistoryError> { + self.check_with(request, &mut Unmetered, &mut ObservationWorld) + } + + #[verus_spec(result => requires old(self).wf(), + ensures final(self).wf(), + check_frame(old(self)@, final(self)@, request, result), + event_obligations::() ==> check_step(old(self)@, request, result), + event_obligations::() ==> (result matches Err(error) ==> sem::resource_error(error)), + result matches Ok(Decision::Denied(denial)) ==> verify::denial_message(denial), + raw::owner_frame(verify::validator_history(*old(self)), verify::validator_history(*final(self))))] + fn check_with( + &mut self, + request: Request, + limits: &mut L, + world: &mut ObservationWorld, + ) -> Result, HistoryError> { + proof_decl! { let ghost entry = *self; } + let first = self.first_violation_with(&request.event, limits, world); + proof! { + crate::compiled_rule::verify::lemma_compiled_sources_frame(entry.rules@, self.rules@); + assert(self@.rules == entry@.rules); + } + if let Some(index) = first? { + let mode = self.rules[index].mode(); + let message = match mode { + RuleMode::Require => { + "committed history does not satisfy required past-regex rule".to_owned() + } + RuleMode::Forbid => { + "committed history satisfies forbidden past-regex rule".to_owned() + } + }; + proof! { + crate::compiled_rule::verify::lemma_compiled_mode_frame(entry.rules@, self.rules@, index as int); + assert(crate::compiled_rule::verify::compiled_structure_frame(entry.rules@[index as int], self.rules@[index as int])); + if event_obligations::() { + crate::compiled_rule::verify::lemma_compiled_source_mode(self.rules@[index as int], mode); + assert(mode == entry@.rules[index as int].mode); + assert(sem::least_violation(entry@.rules, request.event, entry@.history, index as int)); + } + } + let denial = Denial { + index, + mode, + event: request.event, + message, + }; + return Ok(Decision::Denied(denial)); + } + let appended = self.history.push_with(request.event, limits, world); + proof! { + raw::lemma_push_result(entry.history, self.history, request.event, appended); + raw::lemma_history_frame_facts(entry.history, self.history); + assert(verify::validator_wf(*self)); + assert(self@.rules == entry@.rules); + } + appended?; + Ok(Decision::Grant(Grant { + event: request.event, + metadata: request.metadata, + })) + } + + /// Evaluates without committing: the state is unchanged and, under the event laws, the + /// answer is `permits_result`; errors are operational resource failures. + #[verus_spec(result => requires old(self).wf(), + ensures final(self).wf(), final(self)@ == old(self)@, no_invariant_failure(result), + event_obligations::() ==> permits_result(old(self)@, *candidate, result), + event_obligations::() ==> (result matches Err(error) ==> sem::resource_error(error)), + raw::owner_frame(verify::validator_history(*old(self)), verify::validator_history(*final(self))))] + pub fn permits(&mut self, candidate: &E) -> Result { + proof_decl! { let ghost entry = *self; } + let first = self.first_violation(candidate); + proof! { + crate::compiled_rule::verify::lemma_compiled_sources_frame(entry.rules@, self.rules@); + assert(self@ == entry@); + if event_obligations::() { + if let Ok(Some(index)) = first { + assert(sem::rule_violated(entry@.rules[index as int], *candidate, entry@.history)); + assert(sem::policy_denies(entry@.rules, *candidate, entry@.history)); + } + } + } + Ok(first?.is_none()) + } + + #[verus_spec(result => requires verify::validator_wf(*old(self)), + ensures no_invariant_failure(result), + event_obligations::() ==> (result matches Err(error) ==> sem::resource_error(error)), + verify::validator_frame(*old(self), *final(self)), final(self).history == old(self).history, + result matches Ok(Some(index)) ==> index < final(self).rules@.len(), + crate::compiled_rule::verify::ordered_result(verify::validator_sources(*old(self)), old(self).history, *candidate, result))] + fn first_violation(&mut self, candidate: &E) -> Result, HistoryError> { + self.first_violation_with(candidate, &mut Unmetered, &mut ObservationWorld) + } + + #[verus_spec(result => requires verify::validator_wf(*old(self)), + ensures no_invariant_failure(result), + event_obligations::() ==> (result matches Err(error) ==> sem::resource_error(error)), + verify::validator_frame(*old(self), *final(self)), final(self).history == old(self).history, + result matches Ok(Some(index)) ==> index < final(self).rules@.len(), + crate::compiled_rule::verify::ordered_result(verify::validator_sources(*old(self)), old(self).history, *candidate, result))] + fn first_violation_with( + &mut self, + candidate: &E, + limits: &mut L, + world: &mut ObservationWorld, + ) -> Result, HistoryError> { + proof_decl! { let ghost entry = *self; } + proof! { history_store::history::verify::lemma_history_frame_facts(entry.history, entry.history); } + let mut index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec(invariant + index <= self.rules@.len(), verify::validator_wf(*self), verify::validator_frame(entry, *self), + entry == *old(self), self.history == entry.history, + junco_core::spec::hypotheses::event_obligations::() ==> + forall|j: int| 0 <= j < index ==> !sem::rule_violated( + verify::validator_sources(entry)[j]@, *candidate, history_store::history::verify::raw_events(entry.history)), + decreases self.rules@.len() - index))] + while index < self.rules.len() { + proof_decl! { let ghost before = *self; } + let rule = &mut self.rules[index]; + let answer = rule.accepts_history_with_limits(&self.history, candidate, limits, world); + let mode = rule.mode(); + proof! { + if junco_core::spec::hypotheses::event_obligations::() { + crate::compiled_rule::verify::lemma_dsl_violation(*rule, self.history, *candidate, answer, mode); + } + assert forall|j: int| 0 <= j < entry.rules@.len() implies + crate::compiled_rule::verify::compiled_structure_frame(entry.rules@[j], self.rules@[j]) by { + if j != index as int { assert(self.rules@[j] == before.rules@[j]); } + } + crate::compiled_rule::verify::lemma_compiled_sources_frame(entry.rules@, self.rules@); + assert(verify::validator_wf(*self)); + assert(verify::validator_frame(entry, *self)); + } + let violated = match answer? { + None => false, + Some(inside) => match mode { + RuleMode::Require => !inside, + RuleMode::Forbid => inside, + }, + }; + if violated { + return Ok(Some(index)); + } + index += 1; + } + proof! { + if event_obligations::() { + crate::compiled_rule::verify::lemma_no_violation_permits( + verify::validator_sources(entry), *candidate, raw::raw_events(entry.history)); + } + } + Ok(None) + } + + /// Returns committed grants' events in exact acceptance order. + #[verus_spec(result => ensures result@ == self@.history)] + pub fn history(&self) -> &[E] { + self.history.as_slice() + } + + /// Captures the current committed-history position. + #[verus_spec(result => ensures raw::checkpoint_matches(verify::validator_history(*self), result))] + pub fn checkpoint(&self) -> Checkpoint { + self.history.checkpoint() + } + + /// Rolls back a checkpoint of this validator's history: `rollback_step`, plus the + /// underlying history's checkpoint-ownership outcome. + #[verus_spec(result => requires old(self).wf(), + ensures final(self).wf(), rollback_step(old(self)@, final(self)@, result), + raw::owner_frame(verify::validator_history(*old(self)), verify::validator_history(*final(self))), + raw::rollback_result(verify::validator_history(*old(self)), verify::validator_history(*final(self)), checkpoint, result))] + pub fn rollback(&mut self, checkpoint: Checkpoint) -> Result<(), HistoryError> { + proof_decl! { let ghost entry = *self; } + let result = self.history.rollback(checkpoint); + proof! { + raw::lemma_rollback_result(entry.history, self.history, checkpoint, result); + raw::lemma_history_frame_facts(entry.history, self.history); + crate::compiled_rule::verify::lemma_compiled_sources_frame(entry.rules@, self.rules@); + assert(verify::validator_wf(*self)); + let before = raw::raw_events(entry.history); + let after = raw::raw_events(self.history); + if raw::state_frame(entry.history, self.history) { + assert(after =~= before.subrange(0, after.len() as int)); + } + } + result + } +} + +impl Validator { + /// Resets the existing per-rule numeric event-work counters. + #[cfg(feature = "test-util")] + pub fn reset_work_events(&mut self) { + for rule in &mut self.rules { + rule.reset_work_events(); + } + } + + /// Returns the saturating sum of existing per-rule numeric event-work counters. + #[cfg(feature = "test-util")] + pub fn work_events(&self) -> usize { + self.rules.iter().fold(0usize, |total, rule| { + total.saturating_add(rule.work_events()) + }) + } +} + +/// Crate-internal frame predicates over the compiled entries, and the trace-safety lemmas of the monitor specification. +#[cfg(verus_keep_ghost)] +pub mod verify { + use super::*; + use crate::compiled_rule::verify as compiled; + use crate::spec::monitor::trace_safe; + use history_store::history::verify as raw; + verus! { + pub open(crate) spec fn builder_store(builder: ValidatorBuilder) -> Arc> { builder.store } + pub open(crate) spec fn builder_rules(builder: ValidatorBuilder) -> Seq> { builder.rules@ } + pub open(crate) spec fn builder_sources(builder: ValidatorBuilder) -> Seq> { + compiled::compiled_sources(builder.rules@) + } + pub open(crate) spec fn builder_wf(builder: ValidatorBuilder) -> bool { + compiled::compiled_table_wf(builder.rules@, builder.store) + } + pub open(crate) spec fn validator_history(validator: Validator) -> History { validator.history } + pub open(crate) spec fn validator_sources(validator: Validator) -> Seq> { + compiled::compiled_sources(validator.rules@) + } + pub open(crate) spec fn validator_wf(validator: Validator) -> bool { + raw::history_wf(validator.history) + && compiled::compiled_table_wf(validator.rules@, raw::store_of(validator.history)) + } + + pub open(crate) spec fn validator_frame(before: Validator, after: Validator) -> bool { + validator_wf(after) && compiled::compiled_table_frame(before.rules@, after.rules@) + && validator_sources(after) == validator_sources(before) + && raw::owner_frame(before.history, after.history) + } + + /// The denial's explanation names the violated rule's mode. + pub open spec fn denial_message(denial: Denial) -> bool { + denial.message@ == match denial.mode { + RuleMode::Require => "committed history does not satisfy required past-regex rule"@, + RuleMode::Forbid => "committed history satisfies forbidden past-regex rule"@, + } + } + + /// A `check` keeps the trace safe: a grant appends an event the policy permitted + /// (`check_step`), every other outcome leaves the history as it was (`check_frame`). + pub proof fn lemma_check_preserves_trace_safe( + before: ValidatorView, after: ValidatorView, request: Request, + result: Result, HistoryError>) + requires trace_safe(before), check_frame(before, after, request, result), + check_step(before, request, result), + ensures trace_safe(after), + { + assert forall|j: int| 0 <= j < after.history.len() implies + sem::policy_permits(after.rules, #[trigger] after.history[j], after.history.take(j)) by { + if j < before.history.len() { + assert(sem::policy_permits(before.rules, before.history[j], before.history.take(j))); + assert(after.history.take(j) =~= before.history.take(j)); + } else { + assert(after.history.take(j) =~= before.history); + } + } + } + + /// A `rollback` keeps the trace safe: a prefix of a safe trace is safe. + pub proof fn lemma_rollback_preserves_trace_safe( + before: ValidatorView, after: ValidatorView, result: Result<(), HistoryError>) + requires trace_safe(before), rollback_step(before, after, result), + ensures trace_safe(after), + { + assert forall|j: int| 0 <= j < after.history.len() implies + sem::policy_permits(after.rules, #[trigger] after.history[j], after.history.take(j)) by { + assert(sem::policy_permits(before.rules, before.history[j], before.history.take(j))); + assert(after.history.take(j) =~= before.history.take(j)); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use history_syntax::{ + AtomPattern, Comparison, Component, Component3, ComponentPattern as P, Head, N3, + RegexExpr as R, TestExpr as T, + }; + use junco_core::limits::LimitError; + + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] + struct Document { + principal: u8, + action: u8, + resource: u8, + payload: u16, + } + impl Event for Document { + type Component = Component3; + type Arity = N3; + + fn component(self, index: usize) -> Self::Component { + match index { + 0 => Component3::C0(self.principal), + 1 => Component3::C1(self.action), + _ => Component3::C2(self.resource), + } + } + + fn coordinate(component: Self::Component) -> usize { + match component { + Component3::C0(_) => 0, + Component3::C1(_) => 1, + Component3::C2(_) => 2, + } + } + } + fn edit() -> Document { + Document { + principal: 7, + action: 1, + resource: 9, + payload: 42, + } + } + fn release() -> Document { + Document { + action: 2, + payload: 21, + ..edit() + } + } + fn store() -> Arc> { + Arc::new(Store::new().unwrap()) + } + fn any_head() -> Head { + Head::new([ + P::variable("principal"), + P::variable("action"), + P::variable("resource"), + ]) + } + fn prior_edit() -> Rule { + Rule::new( + RuleMode::Require, + Head::new([ + P::variable("actor"), + P::constant(Component3::C1(2)), + P::variable("resource"), + ]), + R::concat([ + R::all(), + R::test(T::and([ + T::atom( + Comparison::Eq, + AtomPattern::new(Component(0), P::variable("actor")), + ), + T::atom( + Comparison::Eq, + AtomPattern::new(Component(1), P::constant(Component3::C1(1))), + ), + T::atom( + Comparison::Eq, + AtomPattern::new(Component(2), P::variable("resource")), + ), + ])), + R::all(), + ]), + ) + } + + #[test] + fn grants_preserve_event_metadata_and_append_exactly_once() { + let mut builder = Validator::builder(store()); + builder.add_rule(prior_edit()).unwrap(); + let mut validator = builder.finish().unwrap(); + assert!( + validator + .check(Request::new(edit(), ())) + .unwrap() + .is_grant() + ); + assert_eq!(validator.history(), &[edit()]); + let checkpoint = validator.checkpoint(); + let metadata = alloc::vec![3u8, 1, 4]; + let Decision::Grant(grant) = validator + .check(Request::new(release(), metadata.clone())) + .unwrap() + else { + panic!("matching prior edit must grant") + }; + assert_eq!(grant.event, release()); + assert_eq!(grant.metadata, metadata); + assert_eq!(validator.history(), &[edit(), release()]); + let other = Document { + principal: 8, + ..release() + }; + assert!( + matches!(validator.check(Request::new(other, ())).unwrap(), Decision::Denied(Denial { mode: RuleMode::Require, event, .. }) if event == other) + ); + assert_eq!(validator.history(), &[edit(), release()]); + assert!(validator.permits(&release()).unwrap()); + assert_eq!(validator.history(), &[edit(), release()]); + validator.rollback(checkpoint).unwrap(); + assert_eq!(validator.history(), &[edit()]); + } + + #[test] + fn first_violation_order_and_empty_tables_are_preserved() { + for first in [RuleMode::Require, RuleMode::Forbid] { + let mut builder = Validator::builder(store()); + for mode in [ + first, + if first == RuleMode::Require { + RuleMode::Forbid + } else { + RuleMode::Require + }, + ] { + builder + .add_rule(Rule::new( + mode, + any_head(), + if mode == RuleMode::Require { + R::empty() + } else { + R::all() + }, + )) + .unwrap(); + } + let mut validator = builder.finish().unwrap(); + assert!( + matches!(validator.check(Request::new(release(), ())).unwrap(), Decision::Denied(Denial { index: 0, mode, .. }) if mode == first) + ); + assert!(validator.history().is_empty()); + } + // The index must distinguish violations with the same mode, after a nonviolating rule. + let mut builder = Validator::builder(store()); + builder + .add_rule(Rule::new(RuleMode::Require, any_head(), R::all())) + .unwrap(); + builder + .add_rule(Rule::new(RuleMode::Forbid, any_head(), R::all())) + .unwrap(); + builder + .add_rule(Rule::new(RuleMode::Forbid, any_head(), R::all())) + .unwrap(); + let mut validator = builder.finish().unwrap(); + assert!(matches!( + validator.check(Request::new(release(), ())).unwrap(), + Decision::Denied(Denial { + index: 1, + mode: RuleMode::Forbid, + .. + }) + )); + assert!(validator.history().is_empty()); + let mut empty = Validator::::builder(store()).finish().unwrap(); + assert!(empty.permits(&release()).unwrap()); + assert!(empty.check(Request::new(release(), ())).unwrap().is_grant()); + assert_eq!(empty.history(), &[release()]); + } + + #[test] + fn append_allocation_error_is_not_a_denial_or_a_grant() { + let mut validator = Validator::::builder(store()).finish().unwrap(); + let _failure = junco_core::observation::fail_reservations_after(0); + assert!(matches!( + validator.check(Request::new(edit(), ())), + Err(HistoryError::AllocationFailed) + )); + assert!(validator.history().is_empty()); + } + + struct PublicationFailure; + impl Limits for PublicationFailure { + fn checkpoint(&mut self) -> Result<(), LimitError> { + Ok(()) + } + fn enforce_memory(&mut self) -> Result<(), LimitError> { + Ok(()) + } + fn publication_checkpoint(&mut self) -> Result<(), LimitError> { + Err(LimitError::RegexSizeLimitExceeded { limit: 0 }) + } + } + + #[test] + fn evaluation_error_does_not_append_or_become_a_denial() { + let mut builder = Validator::builder(store()); + builder + .add_rule(Rule::new(RuleMode::Require, any_head(), R::epsilon())) + .unwrap(); + let mut validator = builder.finish().unwrap(); + assert!(matches!( + validator.check_with( + Request::new(release(), ()), + &mut PublicationFailure, + &mut ObservationWorld + ), + Err(HistoryError::Limit(_)) + )); + assert!(validator.history().is_empty()); + } + + #[test] + fn failed_builder_reservation_drains_a_deep_owned_rule() { + let mut tail = R::::epsilon(); + for _ in 0..4096 { + tail = R::star(tail); + } + let source = Rule::new(RuleMode::Require, any_head(), tail); + let mut builder = Validator::builder(store()); + { + let _failure = junco_core::observation::fail_reservations_after(0); + assert!(matches!( + builder.add_rule(source), + Err(CompileError::Runtime(HistoryError::AllocationFailed)) + )); + } + assert!(builder.finish().unwrap().permits(&release()).unwrap()); + } +} diff --git a/src/history-semantics/src/verify/finite_branch.rs b/src/history-semantics/src/verify/finite_branch.rs new file mode 100644 index 000000000..f65bb4794 --- /dev/null +++ b/src/history-semantics/src/verify/finite_branch.rs @@ -0,0 +1,1468 @@ +//! The steps of the transition normalizer's action machine (`normalize.rs` `Action::*_step`) +//! satisfy the machine typing invariant `verify::finite_steps::xeffect`, one lemma per branch. +use crate::normalize::verify::{self as norm, ActionShape, ChildShape}; +use crate::verify::finite_collect::*; +use crate::verify::finite_impl::*; +use crate::verify::finite_link::*; +use crate::verify::finite_machine::*; +use crate::verify::finite_steps::*; +use crate::verify::finite_trans::*; +use junco_core::kernel::verify as model; +use junco_core::kernel::{RegexId, TestId, TransitionId}; +use junco_core::verify::history_specs::Regex; +use vstd::prelude::*; + +verus! { + +broadcast use junco_core::kernel::verify::group_kernel_views; + +// ===== abstract operations ===== + +pub proof fn lemma_if_le(a: AV, b: AV, c: AV) + requires av_le(a, c), av_le(b, c), + ensures av_le(av_if(a, b), c), +{} +/// `av_le` between node values, stated on classes. +pub proof fn lemma_av_le_cls(g: model::Graph, s: nat, t: nat) + requires av_le(av_of(g, s), av_of(g, t)), + ensures forall|v: R| #[trigger] tcls(g, s, v) ==> tcls(g, t, v), forall|v: R| #[trigger] ycls(g, s, v) ==> ycls(g, t, v), +{ + assert forall|v: R| #[trigger] tcls(g, s, v) implies tcls(g, t, v) by { assert((av_of(g, s).x)(v)); } + assert forall|v: R| #[trigger] ycls(g, s, v) implies ycls(g, t, v) by { assert((av_of(g, s).y)(v)); } +} + + +/// A union of values below `t` is below `t`, when `t` contains the constants. +pub proof fn lemma_union_le(xs: Seq, t: AV) + requires forall|i: int| 0 <= i < xs.len() ==> #[trigger] av_le(xs[i], t), + forall|v: R| rconst(v) ==> #[trigger] (t.x)(v), forall|v: R| #[trigger] (t.y)(v), + ensures av_le(av_union(xs), t), +{ + assert forall|v: R| #[trigger] (av_union(xs).x)(v) implies (t.x)(v) by { + if any_x(xs, v) { + let i = choose|i: int| #![trigger xs[i]] 0 <= i < xs.len() && (xs[i].x)(v); + assert(av_le(xs[i], t)); + } + } +} + +/// A meet of values whose classes lie in the closure of `base` lies in it. +pub proof fn lemma_meet_le_cl(xs: Seq, base: spec_fn(R) -> bool) + requires forall|i: int, w: R| 0 <= i < xs.len() && #[trigger] (xs[i].x)(w) ==> cl(true, base, w), + ensures forall|v: R| #[trigger] (av_meet(xs).x)(v) ==> cl(true, base, v), +{ + assert forall|v: R| #[trigger] (av_meet(xs).x)(v) implies cl(true, base, v) by { + assert forall|w: R| #[trigger] any_x(xs, w) implies cl(true, base, w) by { + let i = choose|i: int| #![trigger xs[i]] 0 <= i < xs.len() && (xs[i].x)(w); + } + lemma_cl_mono(true, |w: R| any_x(xs, w), |w: R| cl(true, base, w), v); + lemma_cl_idem(true, base, v); + } +} + +/// `t`'s class is in the closure of the pair `(a, b)` when it is in `a`'s or `b`'s. +pub proof fn lemma_pair_base(g: model::Graph, a: nat, b: nat, t: nat) + requires (forall|v: R| #[trigger] tcls(g, t, v) ==> tcls(g, a, v)) || (forall|v: R| #[trigger] tcls(g, t, v) ==> tcls(g, b, v)), + ensures forall|v: R| #[trigger] tcls(g, t, v) ==> cl(true, |w: R| any_x(seq![av_of(g, a), av_of(g, b)], w), v), +{ + let s = seq![av_of(g, a), av_of(g, b)]; + assert forall|v: R| #[trigger] tcls(g, t, v) implies cl(true, |w: R| any_x(s, w), v) by { + if tcls(g, a, v) { assert(s[0] == av_of(g, a)); assert(any_x(s, v)); } + else { assert(s[1] == av_of(g, b)); assert(any_x(s, v)); } + lemma_cl_base(true, |w: R| any_x(s, w), v); + } +} + +/// A meet over `(l, r)` is below the meet over `(a, b)` when `l ≤ a` and `r ≤ b`. +pub proof fn lemma_meet_pair_le(g: model::Graph, l: nat, r: nat, a: nat, b: nat) + requires forall|v: R| #[trigger] tcls(g, l, v) ==> tcls(g, a, v), forall|v: R| #[trigger] tcls(g, r, v) ==> tcls(g, b, v), + ensures av_le(av_meet(seq![av_of(g, l), av_of(g, r)]), av_meet(seq![av_of(g, a), av_of(g, b)])), +{ + let s = seq![av_of(g, l), av_of(g, r)]; + let base = |w: R| any_x(seq![av_of(g, a), av_of(g, b)], w); + lemma_pair_base(g, a, b, l); + lemma_pair_base(g, a, b, r); + assert forall|i: int, w: R| 0 <= i < s.len() && #[trigger] (s[i].x)(w) implies cl(true, base, w) by { + if i == 0 { assert(tcls(g, l, w)); } else { assert(tcls(g, r, w)); } + } + lemma_meet_le_cl(s, base); +} + +pub proof fn lemma_meet_pair_const(g: model::Graph, a: nat, b: nat, v: R) + requires rconst(v), + ensures (av_meet(seq![av_of(g, a), av_of(g, b)]).x)(v), +{ + lemma_cl_const(true, |w: R| any_x(seq![av_of(g, a), av_of(g, b)], w), v); +} + +// ===== children ===== + +pub open spec fn ctasks(cs: Seq, f: ChildShape) -> Seq { + cs.reverse().map(|i: int, c: nat| norm::transition_child_shape(f, c)) +} + +pub open spec fn child_avs(g: model::Graph, cs: Seq, f: ChildShape) -> Seq { + cs.map(|i: int, c: nat| push_av(g, norm::transition_child_shape(f, c))) +} + +pub proof fn lemma_child_actions(g: model::Graph, id: nat, f: ChildShape) + ensures norm::transition_child_actions(g, id, f) == ctasks(norm::transition_children(g, id), f), +{ + assert(norm::transition_child_actions(g, id, f) =~= ctasks(norm::transition_children(g, id), f)); +} + +/// Child actions run in source order, each pushing its value. +pub proof fn lemma_arun_children(g: model::Graph, cs: Seq, f: ChildShape, s: Seq) + ensures arun(g, ctasks(cs, f), s) == Some(s + child_avs(g, cs, f)), + decreases cs.len(), +{ + let acts = ctasks(cs, f); + if cs.len() == 0 { + assert(acts =~= Seq::::empty()); + assert(s + child_avs(g, cs, f) =~= s); + } else { + let rest = cs.drop_first(); + let t = norm::transition_child_shape(f, cs[0]); + assert(acts.last() == t); + assert(acts.drop_last() =~= ctasks(rest, f)); + lemma_aapply_push(g, t, s); + lemma_arun_children(g, rest, f, s.push(push_av(g, t))); + assert(s.push(push_av(g, t)) + child_avs(g, rest, f) =~= s + child_avs(g, cs, f)); + } +} + +/// A set action over the children's actions pushes the union or meet of their values. +pub proof fn lemma_arun_set_children(g: model::Graph, cs: Seq, f: ChildShape, s: Seq, inter: bool) + ensures arun(g, seq![if inter { ActionShape::Intersect(cs.len()) } else { ActionShape::Union(cs.len()) }] + ctasks(cs, f), s) + == Some(s.push(if inter { av_meet(child_avs(g, cs, f)) } else { av_union(child_avs(g, cs, f)) })), +{ + let u = if inter { ActionShape::Intersect(cs.len()) } else { ActionShape::Union(cs.len()) }; + lemma_arun_prefix(g, seq![u], ctasks(cs, f), s); + lemma_arun_children(g, cs, f, s); + let n = s + child_avs(g, cs, f); + lemma_arun_one(g, u, n); + assert(n.take(s.len() as int) =~= s); + assert(n.subrange(s.len() as int, n.len() as int) =~= child_avs(g, cs, f)); +} + +pub proof fn lemma_xnf_children(g: model::Graph, cs: Seq, f: ChildShape) + requires all_nf(g, cs), match f { + ChildShape::Clean(_) => true, ChildShape::Not => true, + ChildShape::Append(r) => r < g.regexes.len() && regex_nf(model::lift_regex(g, r)), + ChildShape::PairLeft(o) => nf_sum(g, o), ChildShape::PairRight(o) => nf_sum(g, o), + }, + ensures xnf_tasks(g, ctasks(cs, f)), +{ + assert forall|i: int| 0 <= i < ctasks(cs, f).len() implies #[trigger] xnf_task(g, ctasks(cs, f)[i]) by { + assert(cs.reverse()[i] == cs[cs.len() - 1 - i]); + assert(nf_sum(g, cs[cs.len() - 1 - i])); + } +} + +/// The child tasks of a set node after `p0`. +pub proof fn lemma_child_effect(e: model::Graph, g: model::Graph, task: ActionShape, p0: Seq, v0: Seq, + id: nat, f: ChildShape, inter: bool, y: AV) + requires xctx(e, g, task, p0, v0), norm::transition_action_pushes(task), id < g.transitions.len(), + all_nf(g, norm::transition_children(g, id)), match f { + ChildShape::Clean(_) => true, ChildShape::Not => true, + ChildShape::Append(r) => r < g.regexes.len() && regex_nf(model::lift_regex(g, r)), + ChildShape::PairLeft(o) => nf_sum(g, o), ChildShape::PairRight(o) => nf_sum(g, o), + }, + y == (if inter { av_meet(child_avs(g, norm::transition_children(g, id), f)) } + else { av_union(child_avs(g, norm::transition_children(g, id), f)) }), + av_le(y, push_av(g, task)), + ensures xeffect(g, task, p0, v0, p0.push(if inter { ActionShape::Intersect(norm::transition_children(g, id).len()) } + else { ActionShape::Union(norm::transition_children(g, id).len()) }) + norm::transition_child_actions(g, id, f), v0), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let cs = norm::transition_children(g, id); + let u = if inter { ActionShape::Intersect(cs.len()) } else { ActionShape::Union(cs.len()) }; + lemma_child_actions(g, id, f); + let exp = seq![u] + ctasks(cs, f); + lemma_arun_set_children(g, cs, f, vavs(g, v0), inter); + lemma_xnf_children(g, cs, f); + lemma_xnf1(g, u); + lemma_xnf_tasks_append(g, seq![u], ctasks(cs, f)); + lemma_xpre_stable(e, g, task, p0, v0); + lemma_effect(e, g, task, p0, v0, exp, v0, y); + assert(p0 + exp =~= p0.push(u) + ctasks(cs, f)); +} + +/// `arun([c, t2, t1], s)` for a conditional `c` over two pushing tasks. +pub proof fn lemma_arun_cond(g: model::Graph, c: ActionShape, t2: ActionShape, t1: ActionShape, s: Seq) + requires c is If || c is CleanIf, norm::transition_action_pushes(t1), norm::transition_action_pushes(t2), + ensures arun(g, seq![c, t2, t1], s) == Some(s.push(av_if(push_av(g, t1), push_av(g, t2)))), +{ + let s1 = s.push(push_av(g, t1)); + let s2 = s1.push(push_av(g, t2)); + assert(seq![c, t2, t1] =~= seq![c, t2].push(t1)); + assert(seq![c, t2] =~= seq![c].push(t2)); + lemma_arun_push(g, seq![c, t2], t1, s); + lemma_aapply_push(g, t1, s); + lemma_arun_push(g, seq![c], t2, s1); + lemma_aapply_push(g, t2, s1); + lemma_arun_one(g, c, s2); + assert(s2.take(s2.len() as int - 2) =~= s); + assert(s2[s2.len() as int - 2] == push_av(g, t1)); +} + +/// A conditional expansion `p0 ++ [c, t2, t1]` whose join is below the action's effect. +pub proof fn lemma_cond_effect(e: model::Graph, g: model::Graph, task: ActionShape, p0: Seq, v0: Seq, + c: ActionShape, t2: ActionShape, t1: ActionShape) + requires xctx(e, g, task, p0, v0), norm::transition_action_pushes(task), c is If || c is CleanIf, + norm::transition_action_pushes(t1), norm::transition_action_pushes(t2), xnf_task(g, t1), xnf_task(g, t2), + av_le(push_av(g, t1), push_av(g, task)), av_le(push_av(g, t2), push_av(g, task)), + ensures xeffect(g, task, p0, v0, p0.push(c).push(t2).push(t1), v0), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let exp = seq![c, t2, t1]; + lemma_arun_cond(g, c, t2, t1, vavs(g, v0)); + lemma_xnf3(g, c, t2, t1); + lemma_xpre_stable(e, g, task, p0, v0); + lemma_if_le(push_av(g, t1), push_av(g, t2), push_av(g, task)); + lemma_effect(e, g, task, p0, v0, exp, v0, av_if(push_av(g, t1), push_av(g, t2))); + assert(p0 + exp =~= p0.push(c).push(t2).push(t1)); +} + +/// A single pushing task replaces the action. +pub proof fn lemma_replace_effect(e: model::Graph, g: model::Graph, task: ActionShape, p0: Seq, v0: Seq, + t: ActionShape) + requires xctx(e, g, task, p0, v0), norm::transition_action_pushes(task), norm::transition_action_pushes(t), xnf_task(g, t), + av_le(push_av(g, t), push_av(g, task)), + ensures xeffect(g, task, p0, v0, p0.push(t), v0), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + lemma_arun_one(g, t, vavs(g, v0)); + lemma_aapply_push(g, t, vavs(g, v0)); + lemma_xnf1(g, t); + lemma_xpre_stable(e, g, task, p0, v0); + lemma_effect(e, g, task, p0, v0, seq![t], v0, push_av(g, t)); + assert(p0 + seq![t] =~= p0.push(t)); +} + +/// A local conditional is one of its branches or a conditional node over them. +pub proof fn lemma_local_if(g: model::Graph, test: nat, a: nat, b: nat, out: nat) + requires model::graph_wf(g), a < g.transitions.len(), b < g.transitions.len(), nf_sum(g, a), nf_sum(g, b), + out == a || out == b || (out < g.transitions.len() && g.transitions[out as int] == model::TransitionNode::If(test, a, b)), + ensures out < g.transitions.len(), nf_sum(g, out), av_le(av_of(g, out), av_if(av_of(g, a), av_of(g, b))), +{ + if out != a && out != b { + lemma_if_cls(g, out, test, a, b); + } +} + +// ===== clean_step ===== + +pub proof fn lemma_clean_self(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + id: TransitionId, path: TestId) + requires xctx(e, g, ActionShape::Clean(id@, path@), p0, v0), + ensures xeffect(g, ActionShape::Clean(id@, path@), p0, v0, p0, v0.push(id)), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + lemma_nf_sum_stable(e, g, id@); + lemma_av_le_refl(av_of(g, id@)); + lemma_effect_value(e, g, ActionShape::Clean(id@, path@), p0, v0, id); +} + +pub proof fn lemma_clean_if(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + id: TransitionId, path: TestId, test: TestId, a: TransitionId, b: TransitionId, yes: TestId, no: TestId) + requires xctx(e, g, ActionShape::Clean(id@, path@), p0, v0), + e.transitions[id@ as int] == model::TransitionNode::If(test@, a@, b@), + ensures xeffect(g, ActionShape::Clean(id@, path@), p0, v0, norm::transition_clean_if_tasks(g, test, a, b, yes, no, p0), v0), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Clean(id@, path@); + lemma_nf_sum_stable(e, g, id@); + lemma_if_cls(g, id@, test@, a@, b@); + lemma_nf_children(g, id@); + let ta = ActionShape::Clean(a@, yes@); + let tb = ActionShape::Clean(b@, no@); + if yes@ == g.constants.test_false { + lemma_replace_effect(e, g, task, p0, v0, tb); + } else if no@ == g.constants.test_false { + lemma_replace_effect(e, g, task, p0, v0, ta); + } else { + lemma_cond_effect(e, g, task, p0, v0, ActionShape::If(test@), tb, ta); + } +} + +pub proof fn lemma_clean_children(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + id: TransitionId, path: TestId, inter: bool) + requires xctx(e, g, ActionShape::Clean(id@, path@), p0, v0), id@ < e.transitions.len(), + match e.transitions[id@ as int] { + model::TransitionNode::Union(_) => !inter, + model::TransitionNode::Intersect(_) => inter, + _ => false, + }, + ensures xeffect(g, ActionShape::Clean(id@, path@), p0, v0, norm::transition_clean_child_tasks(g, id, path, inter, p0), v0), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Clean(id@, path@); + lemma_nf_sum_stable(e, g, id@); + lemma_nf_children(g, id@); + norm::transition_lemma_children(g, id@); + let cs = norm::transition_children(g, id@); + let f = ChildShape::Clean(path@); + assert(child_avs(g, cs, f) =~= avs(g, cs)); + if inter { + lemma_inter_cls(g, id@, cs); + lemma_child_effect(e, g, task, p0, v0, id@, f, inter, av_meet(avs(g, cs))); + } else { + lemma_union_cls(g, id@, cs); + lemma_child_effect(e, g, task, p0, v0, id@, f, inter, av_union(avs(g, cs))); + } +} + +pub proof fn lemma_clean_not(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + id: TransitionId, path: TestId, inner: TransitionId) + requires xctx(e, g, ActionShape::Clean(id@, path@), p0, v0), + e.transitions[id@ as int] == model::TransitionNode::Not(inner@), + ensures xeffect(g, ActionShape::Clean(id@, path@), p0, v0, + p0.push(ActionShape::NotResult).push(ActionShape::Clean(inner@, path@)), v0), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Clean(id@, path@); + lemma_nf_sum_stable(e, g, id@); + lemma_nf_children(g, id@); + lemma_not_cls(g, id@, inner@); + let s = vavs(g, v0); + let t1 = ActionShape::Clean(inner@, path@); + let exp = seq![ActionShape::NotResult, t1]; + assert(exp =~= seq![ActionShape::NotResult].push(t1)); + lemma_arun_push(g, seq![ActionShape::NotResult], t1, s); + lemma_arun_one(g, ActionShape::NotResult, s.push(av_of(g, inner@))); + assert(s.push(av_of(g, inner@)).drop_last() =~= s); + lemma_xnf2(g, ActionShape::NotResult, t1); + lemma_xpre_stable(e, g, task, p0, v0); + lemma_effect(e, g, task, p0, v0, exp, v0, av_neg(av_of(g, inner@))); + assert(p0 + exp =~= p0.push(ActionShape::NotResult).push(t1)); +} + +/// `N(w N(ys))` is in the class of an append node over `ys`. +pub proof fn lemma_app_link(g: model::Graph, t: nat, k: nat, rs: Seq, w: R) + requires model::graph_wf(g), t < g.transitions.len(), g.transitions[t as int] == model::TransitionNode::Append(k, rs), + nf_sum(g, t), tcls(g, k, w), + ensures tcls(g, t, cat_r(w, r_cat(model::lift_regexes(g, rs)))), regex_nf(w), +{ + lemma_append_cls(g, t, k, rs); + lemma_nf_children(g, t); + lemma_cls_nf(g, k, w); + let ys = model::lift_regexes(g, rs); + assert(all_rnf(ys)) by { + assert forall|i: int| 0 <= i < ys.len() implies regex_nf(#[trigger] ys[i]) by {} + } + lemma_cat_nest(w, ys); + assert(tcls(g, t, ccat(g, w, rs))); +} + +pub proof fn lemma_lifts_ids(e: model::Graph, g: model::Graph, xs: Seq) + requires model::graph_wf(e), model::graph_extends(e, g), norm::regex_ids_valid(e, xs), + ensures lifts(e, xs) == model::lift_regexes(g, model::regex_ids(xs)), lifts(e, xs) == lifts(g, xs), + model::bounded(model::regex_ids(xs), e.regexes.len()), +{ + assert forall|i: int| 0 <= i < xs.len() implies #[trigger] model::lift_regex(e, xs[i]@) == model::lift_regex(g, xs[i]@) by { + lemma_regex_nf_stable(e, g, xs[i]@); + } + assert(lifts(e, xs) =~= model::lift_regexes(g, model::regex_ids(xs))); + assert(lifts(e, xs) =~= lifts(g, xs)); + assert forall|i: int| 0 <= i < model::regex_ids(xs).len() implies #[trigger] model::regex_ids(xs)[i] < e.regexes.len() by {} +} + +pub proof fn lemma_clean_append(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + id: TransitionId, path: TestId, inner: TransitionId, xs: Seq, r: RegexId) + requires xctx(e, g, ActionShape::Clean(id@, path@), p0, v0), + e.transitions[id@ as int] == model::TransitionNode::Append(inner@, model::regex_ids(xs)), + norm::regex_ids_valid(e, xs), r@ < g.regexes.len(), norm::regex_concat_result(e, g, xs, r@), + ensures xeffect(g, ActionShape::Clean(id@, path@), p0, v0, + p0.push(ActionShape::AppendResult(r@)).push(ActionShape::Clean(inner@, path@)), v0), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Clean(id@, path@); + let rs = model::regex_ids(xs); + lemma_nf_sum_stable(e, g, id@); + lemma_nf_children(g, id@); + lemma_append_cls(g, id@, inner@, rs); + lemma_lifts_ids(e, g, xs); + lemma_concat_link(e, g, xs, r@); + let ys = model::lift_regexes(g, rs); + assert(all_rnf(ys)) by { assert forall|i: int| 0 <= i < ys.len() implies regex_nf(#[trigger] ys[i]) by {} } + lemma_cat_nf(ys); + let z = model::lift_regex(g, r@); + let y = av_app(av_of(g, inner@), z); + assert forall|v: R| #[trigger] (y.x)(v) implies tcls(g, id@, v) by { + if app_of(av_of(g, inner@), z, v) { + let w = choose|w: R| (av_of(g, inner@).x)(w) && v == #[trigger] cat_r(w, z); + lemma_app_link(g, id@, inner@, rs, w); + } + } + assert forall|v: R| #[trigger] (y.y)(v) implies ycls(g, id@, v) by {} + let s = vavs(g, v0); + let t1 = ActionShape::Clean(inner@, path@); + let t2 = ActionShape::AppendResult(r@); + let exp = seq![t2, t1]; + assert(exp =~= seq![t2].push(t1)); + lemma_arun_push(g, seq![t2], t1, s); + lemma_arun_one(g, t2, s.push(av_of(g, inner@))); + assert(s.push(av_of(g, inner@)).drop_last() =~= s); + lemma_xnf2(g, t2, t1); + lemma_xpre_stable(e, g, task, p0, v0); + lemma_effect(e, g, task, p0, v0, exp, v0, y); + assert(p0 + exp =~= p0.push(t2).push(t1)); +} + +// ===== not_step ===== + +pub proof fn lemma_not_const(e: model::Graph, g1: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + id: TransitionId, head: RegexId, r: RegexId, out: TransitionId) + requires xctx(e, g, ActionShape::Not(id@), p0, v0), model::graph_wf(g1), model::graph_extends(e, g1), model::graph_extends(g1, g), + e.transitions[id@ as int] == model::TransitionNode::Const(head@), + r@ < g1.regexes.len(), norm::regex_not_result(g1, head@, r@), + out@ < g.transitions.len(), g.transitions[out@ as int] == model::TransitionNode::Const(r@), + ensures xeffect(g, ActionShape::Not(id@), p0, v0, p0, v0.push(out)), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Not(id@); + lemma_nf_sum_stable(e, g, id@); + lemma_nf_children(e, id@); + lemma_regex_nf_stable(e, g1, head@); + lemma_not_link(g1, head@, r@); + lemma_regex_nf_stable(g1, g, r@); + lemma_regex_nf_stable(e, g, head@); + lemma_const_cls(g, id@, head@); + lemma_const_cls(g, out@, r@); + let x = model::lift_regex(g, head@); + let base = |w: R| neg_of(av_of(g, id@), w); + assert((av_of(g, id@).x)(x)); + assert(base(r_not(x))); + assert forall|v: R| #[trigger] tcls(g, out@, v) implies (av_neg(av_of(g, id@)).x)(v) by { + if rconst(v) { lemma_cl_const(true, base, v); } else { lemma_cl_base(true, base, v); } + } + lemma_nf_weaken(g, out@); + lemma_effect_value(e, g, task, p0, v0, out); +} + +pub proof fn lemma_not_double(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + id: TransitionId, inner: TransitionId) + requires xctx(e, g, ActionShape::Not(id@), p0, v0), e.transitions[id@ as int] == model::TransitionNode::Not(inner@), + ensures xeffect(g, ActionShape::Not(id@), p0, v0, p0, v0.push(inner)), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Not(id@); + lemma_nf_sum_stable(e, g, id@); + lemma_nf_children(g, id@); + lemma_not_cls(g, id@, inner@); + let base = |w: R| neg_of(av_of(g, id@), w); + let nb = |w: R| neg_of(av_of(g, inner@), w); + assert forall|v: R| #[trigger] tcls(g, inner@, v) implies cl(true, base, v) by { + lemma_cls_nf(g, inner@, v); + lemma_not_not(v); + assert(nb(r_not(v))); + lemma_cl_base(true, nb, r_not(v)); + assert((av_neg(av_of(g, inner@)).x)(r_not(v))); + assert(tcls(g, id@, r_not(v))); + assert(base(r_not(r_not(v)))); + lemma_cl_base(true, base, v); + } + lemma_effect_value(e, g, task, p0, v0, inner); +} + +pub proof fn lemma_not_wrap(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + id: TransitionId, out: TransitionId) + requires xctx(e, g, ActionShape::Not(id@), p0, v0), e.transitions[id@ as int] is Append, + out@ < g.transitions.len(), g.transitions[out@ as int] == model::TransitionNode::Not(id@), + ensures xeffect(g, ActionShape::Not(id@), p0, v0, p0, v0.push(out)), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Not(id@); + lemma_nf_sum_stable(e, g, id@); + lemma_not_cls(g, out@, id@); + assert(nf_prod(g, id@)); + assert(nf_lit(g, id@)); + assert(nf_lit(g, out@)); + lemma_nf_weaken(g, out@); + lemma_effect_value(e, g, task, p0, v0, out); +} + +pub proof fn lemma_not_flip(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + id: TransitionId, test: TestId, a: TransitionId, b: TransitionId, guard: TestId, out: TransitionId) + requires xctx(e, g, ActionShape::Not(id@), p0, v0), e.transitions[id@ as int] == model::TransitionNode::If(test@, a@, b@), + a@ == e.constants.transition_all, b@ == e.constants.transition_empty, + out@ == a@ || out@ == b@ || (out@ < g.transitions.len() && g.transitions[out@ as int] == model::TransitionNode::If(guard@, a@, b@)), + ensures xeffect(g, ActionShape::Not(id@), p0, v0, p0.push(ActionShape::Clean(out@, g.constants.test_true)), v0), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Not(id@); + lemma_const_transitions(g); + lemma_local_if(g, guard@, a@, b@, out@); + let t = ActionShape::Clean(out@, g.constants.test_true); + assert forall|v: R| #[trigger] (av_of(g, out@).x)(v) implies (av_neg(av_of(g, id@)).x)(v) by { + lemma_cl_const(true, |w: R| neg_of(av_of(g, id@), w), v); + } + lemma_replace_effect(e, g, task, p0, v0, t); +} + +/// Not or Append over a conditional: the action on both branches under the test. +pub proof fn lemma_unary_if(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + id: TransitionId, test: TestId, a: TransitionId, b: TransitionId, suffix: Option) + requires xctx(e, g, match suffix { Some(r) => ActionShape::Append(id@, r@), None => ActionShape::Not(id@) }, p0, v0), + e.transitions[id@ as int] == model::TransitionNode::If(test@, a@, b@), + ensures xeffect(g, match suffix { Some(r) => ActionShape::Append(id@, r@), None => ActionShape::Not(id@) }, p0, v0, + norm::machine_unary_if_tasks(g, test, a, b, suffix, p0), v0), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = match suffix { Some(r) => ActionShape::Append(id@, r@), None => ActionShape::Not(id@) }; + lemma_xpre_stable(e, g, task, p0, v0); + lemma_nf_sum_stable(e, g, id@); + lemma_if_cls(g, id@, test@, a@, b@); + lemma_nf_children(g, id@); + let ta = match suffix { Some(r) => ActionShape::Append(a@, r@), None => ActionShape::Not(a@) }; + let tb = match suffix { Some(r) => ActionShape::Append(b@, r@), None => ActionShape::Not(b@) }; + match suffix { + Some(r) => { + lemma_app_mono(av_of(g, a@), av_of(g, id@), model::lift_regex(g, r@)); + lemma_app_mono(av_of(g, b@), av_of(g, id@), model::lift_regex(g, r@)); + }, + None => { + lemma_neg_mono(av_of(g, a@), av_of(g, id@)); + lemma_neg_mono(av_of(g, b@), av_of(g, id@)); + }, + } + lemma_cond_effect(e, g, task, p0, v0, ActionShape::CleanIf(test@, g.constants.test_true), tb, ta); +} + +/// Not or Append over a set node: the action on each child, combined by the dual or same set action. +pub proof fn lemma_unary_children(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + id: TransitionId, suffix: Option, inter: bool) + requires xctx(e, g, match suffix { Some(r) => ActionShape::Append(id@, r@), None => ActionShape::Not(id@) }, p0, v0), + id@ < e.transitions.len(), + match suffix { + Some(r) => !inter && e.transitions[id@ as int] is Union, + None => match e.transitions[id@ as int] { + model::TransitionNode::Union(_) => inter, + model::TransitionNode::Intersect(_) => !inter, + _ => false, + }, + }, + ensures xeffect(g, match suffix { Some(r) => ActionShape::Append(id@, r@), None => ActionShape::Not(id@) }, p0, v0, + norm::machine_unary_child_tasks(g, id, suffix, inter, p0), v0), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = match suffix { Some(r) => ActionShape::Append(id@, r@), None => ActionShape::Not(id@) }; + let f = match suffix { Some(r) => ChildShape::Append(r@), None => ChildShape::Not }; + lemma_xpre_stable(e, g, task, p0, v0); + lemma_nf_sum_stable(e, g, id@); + lemma_nf_children(g, id@); + norm::transition_lemma_children(g, id@); + let cs = norm::transition_children(g, id@); + let xs = child_avs(g, cs, f); + let t = push_av(g, task); + // every child is below the node + assert forall|i: int| 0 <= i < cs.len() implies #[trigger] av_le(av_of(g, cs[i]), av_of(g, id@)) by { + match g.transitions[id@ as int] { + model::TransitionNode::Union(ds) => { lemma_union_cls(g, id@, ds); }, + model::TransitionNode::Intersect(ds) => { + lemma_inter_cls(g, id@, ds); + assert forall|v: R| #[trigger] tcls(g, cs[i], v) implies tcls(g, id@, v) by {} + }, + _ => {}, + } + } + assert forall|i: int| 0 <= i < xs.len() implies #[trigger] av_le(xs[i], t) by { + assert(xs[i] == push_av(g, norm::transition_child_shape(f, cs[i]))); + assert(av_le(av_of(g, cs[i]), av_of(g, id@))); + match suffix { + Some(r) => { lemma_app_mono(av_of(g, cs[i]), av_of(g, id@), model::lift_regex(g, r@)); }, + None => { lemma_neg_mono(av_of(g, cs[i]), av_of(g, id@)); }, + } + } + assert forall|v: R| rconst(v) implies #[trigger] (t.x)(v) by { + match suffix { + Some(r) => {}, + None => { lemma_cl_const(true, |w: R| neg_of(av_of(g, id@), w), v); }, + } + } + let y = if inter { av_meet(xs) } else { av_union(xs) }; + if inter { + let base = |w: R| neg_of(av_of(g, id@), w); + assert forall|i: int, w: R| 0 <= i < xs.len() && #[trigger] (xs[i].x)(w) implies cl(true, base, w) by { + assert(av_le(xs[i], t)); + } + lemma_meet_le_cl(xs, base); + } else { + lemma_union_le(xs, t); + } + lemma_child_effect(e, g, task, p0, v0, id@, f, inter, y); +} + +// ===== append_step ===== + +/// Pushing a constant transition below an action whose class contains the constants. +pub proof fn lemma_push_const(e: model::Graph, g: model::Graph, task: ActionShape, p0: Seq, v0: Seq, + out: TransitionId) + requires xctx(e, g, task, p0, v0), norm::transition_action_pushes(task), out@ == g.constants.transition_empty, + forall|v: R| rconst(v) ==> #[trigger] (push_av(g, task).x)(v), forall|v: R| #[trigger] (push_av(g, task).y)(v), + ensures xeffect(g, task, p0, v0, p0, v0.push(out)), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + lemma_const_transitions(g); + lemma_effect_value(e, g, task, p0, v0, out); +} + +pub proof fn lemma_append_eps(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + id: TransitionId, r: RegexId) + requires xctx(e, g, ActionShape::Append(id@, r@), p0, v0), r@ == e.constants.epsilon, + ensures xeffect(g, ActionShape::Append(id@, r@), p0, v0, p0, v0.push(id)), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Append(id@, r@); + lemma_nf_sum_stable(e, g, id@); + norm::regex_constants(g); + let s = model::lift_regex(g, r@); + assert forall|v: R| #[trigger] tcls(g, id@, v) implies (av_app(av_of(g, id@), s).x)(v) by { + lemma_cls_nf(g, id@, v); + lemma_cat_eps(v); + assert(v == cat_r(v, s)); + } + lemma_effect_value(e, g, task, p0, v0, id); +} + +pub proof fn lemma_append_empty(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + id: TransitionId, r: RegexId, out: TransitionId) + requires xctx(e, g, ActionShape::Append(id@, r@), p0, v0), out@ == g.constants.transition_empty, + ensures xeffect(g, ActionShape::Append(id@, r@), p0, v0, p0, v0.push(out)), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + lemma_push_const(e, g, ActionShape::Append(id@, r@), p0, v0, out); +} + +pub proof fn lemma_append_const(e: model::Graph, g1: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + id: TransitionId, r: RegexId, head: RegexId, out_r: RegexId, out: TransitionId) + requires xctx(e, g, ActionShape::Append(id@, r@), p0, v0), model::graph_wf(g1), model::graph_extends(e, g1), model::graph_extends(g1, g), + e.transitions[id@ as int] == model::TransitionNode::Const(head@), + out_r@ < g1.regexes.len(), norm::regex_concat_result(e, g1, seq![head, r], out_r@), + out@ < g.transitions.len(), g.transitions[out@ as int] == model::TransitionNode::Const(out_r@), + ensures xeffect(g, ActionShape::Append(id@, r@), p0, v0, p0, v0.push(out)), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Append(id@, r@); + lemma_xpre_stable(e, g, task, p0, v0); + lemma_nf_sum_stable(e, g, id@); + lemma_nf_children(e, id@); + let hs = seq![head, r]; + assert(norm::regex_ids_valid(e, hs)) by { + assert forall|i: int| 0 <= i < hs.len() implies hs[i]@ < e.regexes.len() by {} + } + lemma_concat_link(e, g1, hs, out_r@); + lemma_regex_nf_stable(e, g, head@); + lemma_regex_nf_stable(e, g, r@); + lemma_regex_nf_stable(g1, g, out_r@); + let x = model::lift_regex(g, head@); + let s = model::lift_regex(g, r@); + assert(lifts(e, hs) =~= seq![x, s]); + assert(seq![x, s] =~= seq![x] + seq![s]); + lemma_rnf_seq2(seq![x, s]); + lemma_cat_nf(seq![x, s]); + lemma_const_cls(g, id@, head@); + lemma_const_cls(g, out@, out_r@); + assert((av_of(g, id@).x)(x)); + assert(app_of(av_of(g, id@), s, cat_r(x, s))); + lemma_nf_weaken(g, out@); + lemma_effect_value(e, g, task, p0, v0, out); +} + +pub proof fn lemma_append_nested(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + id: TransitionId, r: RegexId, inner: TransitionId, children: Seq, combined: RegexId) + requires xctx(e, g, ActionShape::Append(id@, r@), p0, v0), + e.transitions[id@ as int] == model::TransitionNode::Append(inner@, model::regex_ids(children)), + norm::regex_ids_valid(e, children), combined@ < g.regexes.len(), + norm::regex_concat_result(e, g, children.push(r), combined@), + ensures xeffect(g, ActionShape::Append(id@, r@), p0, v0, p0.push(ActionShape::Append(inner@, combined@)), v0), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Append(id@, r@); + lemma_xpre_stable(e, g, task, p0, v0); + lemma_nf_sum_stable(e, g, id@); + lemma_nf_children(g, id@); + let rs = model::regex_ids(children); + lemma_append_cls(g, id@, inner@, rs); + let cr = children.push(r); + assert(norm::regex_ids_valid(e, cr)) by { + assert forall|i: int| 0 <= i < cr.len() implies cr[i]@ < e.regexes.len() by { + if i < children.len() { assert(cr[i] == children[i]); } + } + } + lemma_concat_link(e, g, cr, combined@); + lemma_lifts_ids(e, g, children); + lemma_regex_nf_stable(e, g, r@); + let ys = model::lift_regexes(g, rs); + let z = model::lift_regex(g, r@); + assert(lifts(e, cr) =~= ys.push(z)); + assert(all_rnf(ys)) by { assert forall|i: int| 0 <= i < ys.len() implies regex_nf(#[trigger] ys[i]) by {} } + assert(all_rnf(ys.push(z))) by { + assert forall|i: int| 0 <= i < ys.push(z).len() implies regex_nf(#[trigger] ys.push(z)[i]) by { + if i < ys.len() { assert(ys.push(z)[i] == ys[i]); } + } + } + lemma_cat_nf(ys.push(z)); + let lc = model::lift_regex(g, combined@); + let t = ActionShape::Append(inner@, combined@); + assert forall|v: R| #[trigger] (push_av(g, t).x)(v) implies (av_app(av_of(g, id@), z).x)(v) by { + if app_of(av_of(g, inner@), lc, v) { + let w = choose|w: R| (av_of(g, inner@).x)(w) && v == #[trigger] cat_r(w, lc); + lemma_cls_nf(g, inner@, w); + lemma_cat_shift(w, ys, z); + let w2 = ccat(g, w, rs); + assert(tcls(g, id@, w2)); + assert(v == cat_r(w2, z)); + } + } + lemma_replace_effect(e, g, task, p0, v0, t); +} + +pub proof fn lemma_append_raw(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + id: TransitionId, r: RegexId, xs: Seq, out: TransitionId) + requires xctx(e, g, ActionShape::Append(id@, r@), p0, v0), + e.transitions[id@ as int] is Intersect || e.transitions[id@ as int] is Not, + xs == seq![r] || e.regexes[r@ as int].kind == model::RegexKindNode::Concat(model::regex_ids(xs)), + norm::regex_ids_valid(e, xs), + out@ < g.transitions.len(), g.transitions[out@ as int] == model::TransitionNode::Append(id@, model::regex_ids(xs)), + ensures xeffect(g, ActionShape::Append(id@, r@), p0, v0, p0, v0.push(out)), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Append(id@, r@); + lemma_xpre_stable(e, g, task, p0, v0); + lemma_nf_sum_stable(e, g, id@); + let rs = model::regex_ids(xs); + let ls = model::lift_regexes(g, rs); + let z = model::lift_regex(g, r@); + lemma_lifts_ids(e, g, xs); + lemma_regex_nf_stable(e, g, r@); + if xs == seq![r] { + assert(ls =~= seq![z]); + assert(all_rnf(ls)) by { assert forall|i: int| 0 <= i < 1 implies regex_nf(#[trigger] ls[i]) by {} } + assert forall|w: R| #[trigger] ccat(g, w, rs) == cat_r(w, z) by { assert(seq![w] + ls =~= seq![w, z]); } + } else { + lemma_regex_lift(e, r@); + assert(model::lift_regexes(e, rs) =~= ls) by { + assert forall|i: int| 0 <= i < rs.len() implies #[trigger] model::lift_regex(e, rs[i]) == model::lift_regex(g, rs[i]) by { + assert(lifts(e, xs)[i] == model::lift_regex(e, xs[i]@)); + } + } + assert(z == Regex::::Concat(ls)); + lemma_cat_list(ls); + assert forall|w: R| regex_nf(w) implies #[trigger] ccat(g, w, rs) == cat_r(w, z) by { lemma_cat_nest(w, ls); } + } + lemma_append_cls(g, out@, id@, rs); + assert forall|v: R| #[trigger] tcls(g, out@, v) implies (av_app(av_of(g, id@), z).x)(v) by { + if !rconst(v) { + let w = choose|w: R| tcls(g, id@, w) && v == #[trigger] ccat(g, w, rs); + lemma_cls_nf(g, id@, w); + assert(v == cat_r(w, z)); + } + } + assert(nf_prod(g, id@)); + assert(nats_nf(g, rs)) by { + assert forall|i: int| 0 <= i < rs.len() implies regex_nf(#[trigger] model::lift_regex(g, rs[i])) by { assert(ls[i] == model::lift_regex(g, rs[i])); } + } + assert(model::bounded(rs, g.regexes.len())) by { + assert forall|i: int| 0 <= i < rs.len() implies #[trigger] rs[i] < g.regexes.len() by {} + } + assert(nf_lit(g, out@)); + lemma_nf_weaken(g, out@); + lemma_effect_value(e, g, task, p0, v0, out); +} + +// ===== pair_step ===== + +pub proof fn lemma_pair_keep(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + a: TransitionId, b: TransitionId, out: TransitionId) + requires xctx(e, g, ActionShape::Pair(a@, b@), p0, v0), + out@ == a@ || out@ == b@ || out@ == g.constants.transition_empty, + ensures xeffect(g, ActionShape::Pair(a@, b@), p0, v0, p0, v0.push(out)), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Pair(a@, b@); + lemma_nf_sum_stable(e, g, a@); + lemma_nf_sum_stable(e, g, b@); + lemma_const_transitions(g); + if out@ == a@ || out@ == b@ { + lemma_pair_base(g, a@, b@, out@); + lemma_effect_value(e, g, task, p0, v0, out); + } else { + assert forall|v: R| rconst(v) implies #[trigger] (push_av(g, task).x)(v) by { lemma_meet_pair_const(g, a@, b@, v); } + lemma_push_const(e, g, task, p0, v0, out); + } +} + +pub proof fn lemma_pair_const(e: model::Graph, g1: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + a: TransitionId, b: TransitionId, x: RegexId, y: RegexId, r: RegexId, out: TransitionId) + requires xctx(e, g, ActionShape::Pair(a@, b@), p0, v0), model::graph_wf(g1), model::graph_extends(e, g1), model::graph_extends(g1, g), + e.transitions[a@ as int] == model::TransitionNode::Const(x@), e.transitions[b@ as int] == model::TransitionNode::Const(y@), + r@ < g1.regexes.len(), + norm::regex_set_flat_inputs(e, seq![x, y], true) ==> norm::regex_set_shape(e, g1, seq![x, y], true, r@), + out@ < g.transitions.len(), g.transitions[out@ as int] == model::TransitionNode::Const(r@), + ensures xeffect(g, ActionShape::Pair(a@, b@), p0, v0, p0, v0.push(out)), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Pair(a@, b@); + lemma_nf_sum_stable(e, g, a@); + lemma_nf_sum_stable(e, g, b@); + lemma_nf_children(e, a@); + lemma_nf_children(e, b@); + let xy = seq![x, y]; + assert(norm::regex_ids_valid(e, xy)) by { assert forall|i: int| 0 <= i < xy.len() implies xy[i]@ < e.regexes.len() by {} } + assert(ids_nf(e, xy)) by { + assert forall|i: int| 0 <= i < xy.len() implies regex_nf(#[trigger] model::lift_regex(e, xy[i]@)) by {} + } + lemma_flat_inputs(e, xy, true); + lemma_set_link(e, g1, xy, true, r@); + lemma_regex_nf_stable(g1, g, r@); + lemma_regex_nf_stable(e, g, x@); + lemma_regex_nf_stable(e, g, y@); + lemma_const_cls(g, a@, x@); + lemma_const_cls(g, b@, y@); + lemma_const_cls(g, out@, r@); + let s = seq![av_of(g, a@), av_of(g, b@)]; + let base = |w: R| any_x(s, w); + assert forall|z: R| lift_set(e, xy).contains(z) implies cl(true, base, z) by { + broadcast use vstd::prelude::Seq::to_set_ensures; + let k = choose|k: int| 0 <= k < lifts(e, xy).len() && lifts(e, xy)[k] == z; + if k == 0 { assert(s[0].x == av_of(g, a@).x); assert((s[0].x)(z)); } + else { assert(s[1].x == av_of(g, b@).x); assert((s[1].x)(z)); } + lemma_cl_base(true, base, z); + } + lemma_cl_nset(true, base, lift_set(e, xy), model::lift_regex(g1, r@)); + assert forall|v: R| #[trigger] tcls(g, out@, v) implies cl(true, base, v) by { + if rconst(v) { lemma_cl_const(true, base, v); } + } + lemma_nf_weaken(g, out@); + lemma_effect_value(e, g, task, p0, v0, out); +} + +pub proof fn lemma_pair_union(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + a: TransitionId, b: TransitionId, left: bool) + requires xctx(e, g, ActionShape::Pair(a@, b@), p0, v0), + left ==> e.transitions[a@ as int] is Union, !left ==> e.transitions[b@ as int] is Union, + ensures xeffect(g, ActionShape::Pair(a@, b@), p0, v0, + p0.push(ActionShape::Union(norm::transition_children(g, if left { a@ } else { b@ }).len())) + + norm::transition_child_actions(g, if left { a@ } else { b@ }, if left { ChildShape::PairLeft(b@) } else { ChildShape::PairRight(a@) }), + v0), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Pair(a@, b@); + let id = if left { a@ } else { b@ }; + let f = if left { ChildShape::PairLeft(b@) } else { ChildShape::PairRight(a@) }; + lemma_xpre_stable(e, g, task, p0, v0); + lemma_nf_sum_stable(e, g, a@); + lemma_nf_sum_stable(e, g, b@); + lemma_nf_children(g, id); + norm::transition_lemma_children(g, id); + let cs = norm::transition_children(g, id); + match g.transitions[id as int] { model::TransitionNode::Union(ds) => { lemma_union_cls(g, id, ds); }, _ => {} } + let xs = child_avs(g, cs, f); + let t = push_av(g, task); + assert forall|i: int| 0 <= i < xs.len() implies #[trigger] av_le(xs[i], t) by { + assert(xs[i] == push_av(g, norm::transition_child_shape(f, cs[i]))); + assert(av_le(av_of(g, cs[i]), av_of(g, id))); + lemma_av_le_cls(g, cs[i], id); + if left { lemma_meet_pair_le(g, cs[i], b@, a@, b@); } else { lemma_meet_pair_le(g, a@, cs[i], a@, b@); } + } + assert forall|v: R| rconst(v) implies #[trigger] (t.x)(v) by { lemma_meet_pair_const(g, a@, b@, v); } + lemma_union_le(xs, t); + lemma_child_effect(e, g, task, p0, v0, id, f, false, av_union(xs)); +} + +/// A pair split on a test: pairs `(l1, r1)` and `(l2, r2)` of members below `a` and `b`. +pub proof fn lemma_pair_ifs(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + a: nat, b: nat, test: nat, l1: nat, r1: nat, l2: nat, r2: nat) + requires xctx(e, g, ActionShape::Pair(a, b), p0, v0), + nf_sum(g, l1), nf_sum(g, r1), nf_sum(g, l2), nf_sum(g, r2), + forall|v: R| #[trigger] tcls(g, l1, v) ==> tcls(g, a, v), forall|v: R| #[trigger] tcls(g, l2, v) ==> tcls(g, a, v), + forall|v: R| #[trigger] tcls(g, r1, v) ==> tcls(g, b, v), forall|v: R| #[trigger] tcls(g, r2, v) ==> tcls(g, b, v), + ensures xeffect(g, ActionShape::Pair(a, b), p0, v0, + p0.push(ActionShape::CleanIf(test, g.constants.test_true)).push(ActionShape::Pair(l2, r2)).push(ActionShape::Pair(l1, r1)), v0), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Pair(a, b); + lemma_meet_pair_le(g, l1, r1, a, b); + lemma_meet_pair_le(g, l2, r2, a, b); + lemma_cond_effect(e, g, task, p0, v0, ActionShape::CleanIf(test, g.constants.test_true), + ActionShape::Pair(l2, r2), ActionShape::Pair(l1, r1)); +} + +pub proof fn lemma_pair_split(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + a: TransitionId, b: TransitionId, test: TestId, t: TransitionId, el: TransitionId, left: bool) + requires xctx(e, g, ActionShape::Pair(a@, b@), p0, v0), + e.transitions[(if left { a@ } else { b@ }) as int] == model::TransitionNode::If(test@, t@, el@), + ensures xeffect(g, ActionShape::Pair(a@, b@), p0, v0, + p0.push(ActionShape::CleanIf(test@, g.constants.test_true)) + .push(if left { ActionShape::Pair(el@, b@) } else { ActionShape::Pair(a@, el@) }) + .push(if left { ActionShape::Pair(t@, b@) } else { ActionShape::Pair(a@, t@) }), v0), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let id = if left { a@ } else { b@ }; + lemma_nf_sum_stable(e, g, a@); + lemma_nf_sum_stable(e, g, b@); + lemma_if_cls(g, id, test@, t@, el@); + lemma_nf_children(g, id); + lemma_av_le_cls(g, t@, id); + lemma_av_le_cls(g, el@, id); + if left { + lemma_pair_ifs(e, g, p0, v0, a@, b@, test@, t@, b@, el@, b@); + } else { + lemma_pair_ifs(e, g, p0, v0, a@, b@, test@, a@, t@, a@, el@); + } +} + +pub proof fn lemma_pair_both(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + a: TransitionId, b: TransitionId, x: TestId, xt: TransitionId, xe: TransitionId, y: TestId, yt: TransitionId, ye: TransitionId) + requires xctx(e, g, ActionShape::Pair(a@, b@), p0, v0), + e.transitions[a@ as int] == model::TransitionNode::If(x@, xt@, xe@), + e.transitions[b@ as int] == model::TransitionNode::If(y@, yt@, ye@), + ensures xeffect(g, ActionShape::Pair(a@, b@), p0, v0, + p0.push(ActionShape::CleanIf(x@, g.constants.test_true)).push(ActionShape::Pair(xe@, ye@)).push(ActionShape::Pair(xt@, yt@)), v0), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + lemma_nf_sum_stable(e, g, a@); + lemma_nf_sum_stable(e, g, b@); + lemma_if_cls(g, a@, x@, xt@, xe@); + lemma_if_cls(g, b@, y@, yt@, ye@); + lemma_nf_children(g, a@); + lemma_nf_children(g, b@); + lemma_av_le_cls(g, xt@, a@); + lemma_av_le_cls(g, xe@, a@); + lemma_av_le_cls(g, yt@, b@); + lemma_av_le_cls(g, ye@, b@); + lemma_pair_ifs(e, g, p0, v0, a@, b@, x@, xt@, yt@, xe@, ye@); +} + +pub proof fn lemma_pair_empty_branches(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + a: TransitionId, b: TransitionId, x: TestId, xt: TransitionId, y: TestId, yt: TransitionId, guard: TestId, emp: TransitionId) + requires xctx(e, g, ActionShape::Pair(a@, b@), p0, v0), + e.transitions[a@ as int] == model::TransitionNode::If(x@, xt@, emp@), + e.transitions[b@ as int] == model::TransitionNode::If(y@, yt@, emp@), + emp@ == e.constants.transition_empty, + ensures xeffect(g, ActionShape::Pair(a@, b@), p0, v0, + p0.push(ActionShape::CleanIf(guard@, g.constants.test_true)).push(ActionShape::SwapThen).push(ActionShape::Pair(xt@, yt@)), + v0.push(emp)), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Pair(a@, b@); + lemma_xpre_stable(e, g, task, p0, v0); + lemma_nf_sum_stable(e, g, a@); + lemma_nf_sum_stable(e, g, b@); + lemma_if_cls(g, a@, x@, xt@, emp@); + lemma_if_cls(g, b@, y@, yt@, emp@); + lemma_nf_children(g, a@); + lemma_nf_children(g, b@); + lemma_const_transitions(g); + lemma_av_le_cls(g, xt@, a@); + lemma_av_le_cls(g, yt@, b@); + let m = av_meet(seq![av_of(g, xt@), av_of(g, yt@)]); + let ev = av_of(g, emp@); + let tp = push_av(g, task); + lemma_meet_pair_le(g, xt@, yt@, a@, b@); + assert forall|v: R| #[trigger] (ev.x)(v) implies (tp.x)(v) by { lemma_meet_pair_const(g, a@, b@, v); } + let yv = av_if(m, ev); + let s = vavs(g, v0); + let s1 = s.push(ev); + lemma_vavs_push(g, v0, emp); + let tc0 = ActionShape::CleanIf(guard@, g.constants.test_true); + let tpair = ActionShape::Pair(xt@, yt@); + let exp = seq![tc0, ActionShape::SwapThen, tpair]; + assert(exp =~= seq![tc0, ActionShape::SwapThen].push(tpair)); + assert(seq![tc0, ActionShape::SwapThen] =~= seq![tc0].push(ActionShape::SwapThen)); + lemma_arun_push(g, seq![tc0, ActionShape::SwapThen], tpair, s1); + let s2 = s1.push(m); + lemma_arun_push(g, seq![tc0], ActionShape::SwapThen, s2); + let s3 = s.push(m).push(ev); + assert(s2.take(s2.len() as int - 2).push(s2.last()).push(s2[s2.len() as int - 2]) =~= s3); + lemma_arun_one(g, tc0, s3); + assert(s3.take(s3.len() as int - 2) =~= s); + assert(s3[s3.len() as int - 2] == m); + lemma_xnf3(g, tc0, ActionShape::SwapThen, tpair); + lemma_xnf_values_push(g, v0, emp); + lemma_effect(e, g, task, p0, v0, exp, v0.push(emp), yv); + assert(p0 + exp =~= p0.push(tc0).push(ActionShape::SwapThen).push(tpair)); +} + +pub proof fn lemma_pair_collect(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + a: TransitionId, b: TransitionId, out: TransitionId) + requires xctx(e, g, ActionShape::Pair(a@, b@), p0, v0), + !(e.transitions[a@ as int] is If) && !(e.transitions[a@ as int] is Union), + !(e.transitions[b@ as int] is If) && !(e.transitions[b@ as int] is Union), + all_nf(e, model::transition_ids(seq![a, b])) ==> collect_out(g, model::transition_ids(seq![a, b]), true, out@), + ensures xeffect(g, ActionShape::Pair(a@, b@), p0, v0, p0, v0.push(out)), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Pair(a@, b@); + let ts = model::transition_ids(seq![a, b]); + assert(ts =~= seq![a@, b@]); + assert(all_nf(e, ts)) by { assert forall|k: int| 0 <= k < ts.len() implies nf_sum(e, #[trigger] ts[k]) by {} } + lemma_nf_sum_stable(e, g, a@); + lemma_nf_sum_stable(e, g, b@); + let cs = seq![a@, b@]; + assert(avs(g, cs) =~= seq![av_of(g, a@), av_of(g, b@)]); + assert(nf_prod(g, a@)); + assert(nf_prod(g, b@)); + assert(all_prod(g, cs)) by { assert forall|k: int| 0 <= k < cs.len() implies nf_prod(g, #[trigger] cs[k]) by {} } + assert(nf_prod(g, out@)); + lemma_nf_weaken(g, out@); + assert forall|v: R| #[trigger] tcls(g, out@, v) implies (push_av(g, task).x)(v) by { assert(cbound(g, cs, true, v)); } + lemma_effect_value(e, g, task, p0, v0, out); +} + +// ===== fold_step ===== + +pub proof fn lemma_effect_raw(e: model::Graph, g: model::Graph, task: ActionShape, p0: Seq, v0: Seq, + exp: Seq, v1: Seq) + requires xctx(e, g, task, p0, v0), xnf_tasks(g, exp), xnf_values(g, v1), + aref(aapply(g, task, vavs(g, v0)), arun(g, exp, vavs(g, v1))), + ensures xeffect(g, task, p0, v0, p0 + exp, v1), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + lemma_xpre_stable(e, g, task, p0, v0); + lemma_xnf_tasks_append(g, p0, exp); + assert((p0 + exp).subrange(p0.len() as int, (p0 + exp).len() as int) =~= exp); + assert(p0.is_prefix_of(p0 + exp)) by { assert((p0 + exp).subrange(0, p0.len() as int) =~= p0); } +} + +pub proof fn lemma_fold_start(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + terms: Seq, flat: TransitionId, cs: Seq) + requires xctx(e, g, ActionShape::Fold(terms, 0), p0, v0), all_nf(e, terms) ==> collect_out(g, terms, true, flat@), + g.transitions[flat@ as int] == model::TransitionNode::Intersect(model::transition_ids(cs)), cs.len() > 0, + ensures xeffect(g, ActionShape::Fold(terms, 0), p0, v0, + p0.push(ActionShape::Fold(model::transition_ids(cs), 1)), v0.push(cs[0])), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Fold(terms, 0); + lemma_xpre_stable(e, g, task, p0, v0); + let ds = model::transition_ids(cs); + assert(ds[0] == cs[0]@); + let base = |w: R| any_x(avs(g, terms), w); + assert(g.transitions[flat@ as int] == model::TransitionNode::Intersect(ds)); + let ds2 = g.transitions[flat@ as int]->Intersect_0; + assert(ds2 == ds); + assert(forall|j: int| 0 <= j < ds2.len() ==> #[trigger] elem_ok(g, terms, true, ds2[j])); + assert forall|j: int| 0 <= j < ds.len() implies #[trigger] elem_ok(g, terms, true, ds[j]) by { assert(ds2[j] == ds[j]); } + assert forall|j: int, w: R| 0 <= j < avs(g, ds).len() && #[trigger] (avs(g, ds)[j].x)(w) implies cl(true, base, w) by { + assert(elem_ok(g, terms, true, ds[j])); + assert(tcls(g, ds[j], w)); + } + assert(all_nf(g, ds)) by { + assert forall|k: int| 0 <= k < ds.len() implies nf_sum(g, #[trigger] ds[k]) by { assert(elem_ok(g, terms, true, ds[k])); } + } + assert(elem_ok(g, terms, true, ds[0])); + let s = vavs(g, v0); + lemma_vavs_push(g, v0, cs[0]); + let s1 = s.push(av_of(g, ds[0])); + let t = ActionShape::Fold(ds, 1); + lemma_arun_one(g, t, s1); + let tp = push_av(g, task); + let y = if 1 < ds.len() { av_meet(avs(g, ds)) } else { av_of(g, ds[0]) }; + if 1 < ds.len() { + assert(seq![s1.last()] + avs(g, ds.subrange(1, ds.len() as int)) =~= avs(g, ds)); + assert(s1.drop_last() =~= s); + lemma_meet_le_cl(avs(g, ds), base); + } else { + assert forall|w: R| #[trigger] tcls(g, ds[0], w) implies (tp.x)(w) by {} + } + assert(arun(g, seq![t], vavs(g, v0.push(cs[0]))) == Some(s.push(y))); + lemma_aref_push(s, tp, y); + lemma_aapply_push(g, task, s); + lemma_xnf1(g, t); + lemma_xnf_values_push(g, v0, cs[0]); + lemma_effect_raw(e, g, task, p0, v0, seq![t], v0.push(cs[0])); + assert(p0 + seq![t] =~= p0.push(t)); +} + +pub proof fn lemma_fold_flat(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + terms: Seq, flat: TransitionId) + requires xctx(e, g, ActionShape::Fold(terms, 0), p0, v0), all_nf(e, terms) ==> collect_out(g, terms, true, flat@), + !(g.transitions[flat@ as int] is Intersect), + ensures xeffect(g, ActionShape::Fold(terms, 0), p0, v0, p0, v0.push(flat)), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Fold(terms, 0); + assert(nf_sum(g, flat@)); + assert forall|v: R| #[trigger] tcls(g, flat@, v) implies (push_av(g, task).x)(v) by { assert(cbound(g, terms, true, v)); } + lemma_effect_value(e, g, task, p0, v0, flat); +} + +pub proof fn lemma_fold_next(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + terms: Seq, index: nat, a: TransitionId, b: TransitionId) + requires xctx(e, g, ActionShape::Fold(terms, index), p0, v0), 0 < index < terms.len(), + v0.len() > 0, a == v0.last(), b@ == terms[index as int], + ensures xeffect(g, ActionShape::Fold(terms, index), p0, v0, + p0.push(ActionShape::Fold(terms, index + 1)).push(ActionShape::Pair(a@, b@)), v0.drop_last()), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Fold(terms, index); + lemma_xpre_stable(e, g, task, p0, v0); + let s = vavs(g, v0); + let n = v0.len() as int; + lemma_vavs_take(g, v0, n - 1); + assert(v0.drop_last() == v0.take(n - 1)); + lemma_vavs_index(g, v0, n - 1); + let s0 = vavs(g, v0.drop_last()); + assert(s0 =~= s.drop_last()); + assert(s.last() == av_of(g, a@)); + let rest = avs(g, terms.subrange(index as int, terms.len() as int)); + let tl = seq![s.last()] + rest; + let tgt = av_meet(tl); + let base = |w: R| any_x(tl, w); + assert(rest[0] == av_of(g, b@)); + assert(tl[0] == av_of(g, a@)); + assert(tl[1] == av_of(g, b@)); + let mab = av_meet(seq![av_of(g, a@), av_of(g, b@)]); + // `mab` is below the target + lemma_any_x_pair(seq![av_of(g, a@), av_of(g, b@)], tl); + assert forall|w: R| #[trigger] (mab.x)(w) implies cl(true, base, w) by { + lemma_cl_mono(true, |u: R| any_x(seq![av_of(g, a@), av_of(g, b@)], u), base, w); + } + let tpair = ActionShape::Pair(a@, b@); + let tfold = ActionShape::Fold(terms, index + 1); + let exp = seq![tfold, tpair]; + assert(exp =~= seq![tfold].push(tpair)); + lemma_arun_push(g, seq![tfold], tpair, s0); + lemma_aapply_push(g, tpair, s0); + let s1 = s0.push(mab); + lemma_arun_one(g, tfold, s1); + let y = if index + 1 < terms.len() { + av_meet(seq![mab] + avs(g, terms.subrange((index + 1) as int, terms.len() as int))) + } else { mab }; + if index + 1 < terms.len() { + assert(s1.drop_last() =~= s0); + let rest2 = avs(g, terms.subrange((index + 1) as int, terms.len() as int)); + let l2 = seq![mab] + rest2; + assert forall|j: int, w: R| 0 <= j < l2.len() && #[trigger] (l2[j].x)(w) implies cl(true, base, w) by { + if j == 0 { assert(l2[0] == mab); } else { + assert(l2[j] == rest2[j - 1]); + assert(rest2[j - 1] == tl[j + 1]); + assert(base(w)); + lemma_cl_base(true, base, w); + } + } + lemma_meet_le_cl(l2, base); + } + assert(av_le(y, tgt)); + assert(aapply(g, task, s) == Some(s.drop_last().push(tgt))); + lemma_aref_push(s0, tgt, y); + lemma_vavs_take(g, v0, n - 1); + lemma_xnf_values_sub(g, v0, 0, n - 1); + assert(xnf_values(g, v0.drop_last())); + assert(nf_sum(g, a@)) by { assert(v0[n - 1] == a); } + lemma_xnf2(g, tfold, tpair); + lemma_effect_raw(e, g, task, p0, v0, exp, v0.drop_last()); + assert(p0 + exp =~= p0.push(tfold).push(tpair)); +} + +pub proof fn lemma_fold_noop(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + terms: Seq, index: nat) + requires xctx(e, g, ActionShape::Fold(terms, index), p0, v0), index != 0, index >= terms.len(), + ensures xeffect(g, ActionShape::Fold(terms, index), p0, v0, p0, v0), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Fold(terms, index); + lemma_xpre_stable(e, g, task, p0, v0); + lemma_aref_refl(vavs(g, v0)); + assert(xnf_tasks(g, Seq::::empty())); + lemma_effect_raw(e, g, task, p0, v0, Seq::empty(), v0); + assert(p0 + Seq::::empty() =~= p0); +} + +// ===== step ===== + +pub proof fn lemma_step_union(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, n: nat, out: TransitionId) + requires xctx(e, g, ActionShape::Union(n), p0, v0), n <= v0.len(), + all_nf(e, model::transition_ids(v0.subrange(v0.len() - n, v0.len() as int))) + ==> collect_out(g, model::transition_ids(v0.subrange(v0.len() - n, v0.len() as int)), false, out@), + ensures xeffect(g, ActionShape::Union(n), p0, v0, p0, v0.take(v0.len() - n).push(out)), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Union(n); + lemma_xpre_stable(e, g, task, p0, v0); + let start = v0.len() - n; + lemma_xnf_values_sub(e, v0, start, v0.len() as int); + let s = vavs(g, v0); + lemma_vavs_sub(g, v0, start, v0.len() as int); + lemma_vavs_take(g, v0, start); + let cs = model::transition_ids(v0.subrange(start, v0.len() as int)); + let y = av_union(avs(g, cs)); + assert(av_le(av_of(g, out@), y)) by { + assert forall|v: R| #[trigger] tcls(g, out@, v) implies (y.x)(v) by { assert(cbound(g, cs, false, v)); } + } + let v1 = v0.take(start).push(out); + lemma_vavs_push(g, v0.take(start), out); + lemma_aref_push(s.take(start), y, av_of(g, out@)); + lemma_xnf_values_sub(g, v0, 0, start); + lemma_xnf_values_push(g, v0.take(start), out); + assert(xnf_tasks(g, Seq::::empty())); + lemma_effect_raw(e, g, task, p0, v0, Seq::empty(), v1); + assert(p0 + Seq::::empty() =~= p0); +} + +pub proof fn lemma_step_intersect(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, n: nat) + requires xctx(e, g, ActionShape::Intersect(n), p0, v0), n <= v0.len(), + ensures xeffect(g, ActionShape::Intersect(n), p0, v0, + p0.push(ActionShape::Fold(model::transition_ids(v0.subrange(v0.len() - n, v0.len() as int)), 0)), v0.take(v0.len() - n)), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::Intersect(n); + lemma_xpre_stable(e, g, task, p0, v0); + let start = v0.len() - n; + let s = vavs(g, v0); + lemma_vavs_sub(g, v0, start, v0.len() as int); + lemma_vavs_take(g, v0, start); + let cs = model::transition_ids(v0.subrange(start, v0.len() as int)); + let t = ActionShape::Fold(cs, 0); + lemma_arun_one(g, t, s.take(start)); + lemma_aref_refl(s.take(start).push(av_meet(avs(g, cs)))); + lemma_xnf_values_sub(g, v0, start, v0.len() as int); + lemma_xnf_values_sub(g, v0, 0, start); + lemma_xnf1(g, t); + lemma_effect_raw(e, g, task, p0, v0, seq![t], v0.take(start)); + assert(p0 + seq![t] =~= p0.push(t)); +} + +pub proof fn lemma_step_if(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, test: nat, out: TransitionId) + requires xctx(e, g, ActionShape::If(test), p0, v0), v0.len() >= 2, + out@ == v0[v0.len() - 2]@ || out@ == v0.last()@ + || (out@ < g.transitions.len() && g.transitions[out@ as int] == model::TransitionNode::If(test, v0[v0.len() - 2]@, v0.last()@)), + ensures xeffect(g, ActionShape::If(test), p0, v0, p0, v0.take(v0.len() - 2).push(out)), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::If(test); + lemma_xpre_stable(e, g, task, p0, v0); + let n = v0.len() as int; + let a = v0[n - 2]; + let b = v0[n - 1]; + lemma_values_stable(e, g, v0); + lemma_local_if(g, test, a@, b@, out@); + let s = vavs(g, v0); + lemma_vavs_index(g, v0, n - 2); + lemma_vavs_index(g, v0, n - 1); + lemma_vavs_take(g, v0, n - 2); + lemma_vavs_push(g, v0.take(n - 2), out); + lemma_aref_push(s.take(n - 2), av_if(av_of(g, a@), av_of(g, b@)), av_of(g, out@)); + lemma_xnf_values_sub(g, v0, 0, n - 2); + lemma_xnf_values_push(g, v0.take(n - 2), out); + assert(xnf_tasks(g, Seq::::empty())); + lemma_effect_raw(e, g, task, p0, v0, Seq::empty(), v0.take(n - 2).push(out)); + assert(p0 + Seq::::empty() =~= p0); +} + +pub proof fn lemma_step_clean_if(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, + test: nat, path: nat, out: TransitionId) + requires xctx(e, g, ActionShape::CleanIf(test, path), p0, v0), v0.len() >= 2, + out@ == v0[v0.len() - 2]@ || out@ == v0.last()@ + || (out@ < g.transitions.len() && g.transitions[out@ as int] == model::TransitionNode::If(test, v0[v0.len() - 2]@, v0.last()@)), + ensures xeffect(g, ActionShape::CleanIf(test, path), p0, v0, p0.push(ActionShape::Clean(out@, path)), v0.take(v0.len() - 2)), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::CleanIf(test, path); + lemma_xpre_stable(e, g, task, p0, v0); + let n = v0.len() as int; + let a = v0[n - 2]; + let b = v0[n - 1]; + lemma_values_stable(e, g, v0); + lemma_local_if(g, test, a@, b@, out@); + let s = vavs(g, v0); + lemma_vavs_index(g, v0, n - 2); + lemma_vavs_index(g, v0, n - 1); + lemma_vavs_take(g, v0, n - 2); + let t = ActionShape::Clean(out@, path); + lemma_arun_one(g, t, s.take(n - 2)); + lemma_aref_push(s.take(n - 2), av_if(av_of(g, a@), av_of(g, b@)), av_of(g, out@)); + lemma_xnf_values_sub(g, v0, 0, n - 2); + lemma_xnf1(g, t); + lemma_effect_raw(e, g, task, p0, v0, seq![t], v0.take(n - 2)); + assert(p0 + seq![t] =~= p0.push(t)); +} + +/// `NotResult` and `AppendResult(r)`: the unary action on the last value. +pub proof fn lemma_step_result(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq, suffix: Option) + requires xctx(e, g, match suffix { Some(r) => ActionShape::AppendResult(r), None => ActionShape::NotResult }, p0, v0), v0.len() > 0, + ensures xeffect(g, match suffix { Some(r) => ActionShape::AppendResult(r), None => ActionShape::NotResult }, p0, v0, + p0.push(match suffix { Some(r) => ActionShape::Append(v0.last()@, r), None => ActionShape::Not(v0.last()@) }), v0.drop_last()), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = match suffix { Some(r) => ActionShape::AppendResult(r), None => ActionShape::NotResult }; + lemma_xpre_stable(e, g, task, p0, v0); + let n = v0.len() as int; + let s = vavs(g, v0); + lemma_vavs_index(g, v0, n - 1); + lemma_vavs_take(g, v0, n - 1); + assert(v0.drop_last() == v0.take(n - 1)); + assert(s.drop_last() =~= s.take(n - 1)); + let t = match suffix { Some(r) => ActionShape::Append(v0.last()@, r), None => ActionShape::Not(v0.last()@) }; + lemma_arun_one(g, t, s.take(n - 1)); + lemma_aref_refl(s.take(n - 1).push(push_av(g, t))); + lemma_xnf_values_sub(g, v0, 0, n - 1); + assert(nf_sum(g, v0.last()@)) by { assert(v0[n - 1] == v0.last()); } + lemma_xnf1(g, t); + lemma_effect_raw(e, g, task, p0, v0, seq![t], v0.drop_last()); + assert(p0 + seq![t] =~= p0.push(t)); +} + +pub proof fn lemma_step_swap(e: model::Graph, g: model::Graph, p0: Seq, v0: Seq) + requires xctx(e, g, ActionShape::SwapThen, p0, v0), v0.len() >= 2, + ensures xeffect(g, ActionShape::SwapThen, p0, v0, p0, v0.take(v0.len() - 2).push(v0[v0.len() - 1]).push(v0[v0.len() - 2])), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + let task = ActionShape::SwapThen; + lemma_xpre_stable(e, g, task, p0, v0); + let n = v0.len() as int; + let v1 = v0.take(n - 2).push(v0[n - 1]).push(v0[n - 2]); + let s = vavs(g, v0); + lemma_vavs_index(g, v0, n - 2); + lemma_vavs_index(g, v0, n - 1); + lemma_vavs_take(g, v0, n - 2); + lemma_vavs_push(g, v0.take(n - 2), v0[n - 1]); + lemma_vavs_push(g, v0.take(n - 2).push(v0[n - 1]), v0[n - 2]); + lemma_aref_refl(vavs(g, v1)); + lemma_xnf_values_sub(g, v0, 0, n - 2); + lemma_xnf_values_push(g, v0.take(n - 2), v0[n - 1]); + lemma_xnf_values_push(g, v0.take(n - 2).push(v0[n - 1]), v0[n - 2]); + assert(xnf_tasks(g, Seq::::empty())); + lemma_effect_raw(e, g, task, p0, v0, Seq::empty(), v1); + assert(p0 + Seq::::empty() =~= p0); +} + +// ===== next and run ===== + +/// One machine step keeps the typing and lowers the abstract run (frame rule). +pub proof fn lemma_next(e: model::Graph, g: model::Graph, pending: Seq, shape: ActionShape, v0: Seq, + tasks: Seq, values: Seq) + requires xcfg(e, pending.push(shape), v0), + xpre(e, shape, pending, v0) ==> xeffect(g, shape, pending, v0, tasks, values), + ensures xnf_tasks(g, tasks), xnf_values(g, values), + aref(arun(g, pending.push(shape), vavs(g, v0)), arun(g, tasks, vavs(g, values))), + xstep(g, pending.push(shape), v0, tasks, values), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + lemma_xnf_tasks_pop(e, pending, shape); + let exp = tasks.subrange(pending.len() as int, tasks.len() as int); + lemma_frame(g, pending, exp, shape, vavs(g, v0), vavs(g, values)); + assert(pending + exp =~= tasks) by { + assert(tasks.subrange(0, pending.len() as int) =~= pending); + } +} + +pub proof fn lemma_run_start(g: model::Graph, shape: ActionShape) + requires xnf_task(g, shape), + ensures xrun(g, shape, seq![shape], Seq::empty()), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + lemma_xnf1(g, shape); + assert(vavs(g, Seq::::empty()) =~= Seq::::empty()); + match arun(g, seq![shape], Seq::empty()) { + Some(s) => lemma_stack_le_refl(s), + None => {}, + } +} + +pub proof fn lemma_run_step(e: model::Graph, b: model::Graph, g: model::Graph, shape: ActionShape, t0: Seq, v0: Seq, + t1: Seq, v1: Seq) + requires model::graph_wf(e), model::graph_extends(e, b), norm::transition_action_valid(e, shape), + model::graph_wf(b), model::graph_extends(b, g), + norm::transition_configuration_valid(b, t0, v0), xrun(b, shape, t0, v0), + xcfg(b, t0, v0) ==> xstep(g, t0, v0, t1, v1), + ensures xrun(g, shape, t1, v1), +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + lemma_tasks_valid1(e, seq![shape], shape); + lemma_tasks_valid_stable(e, b, seq![shape]); + lemma_arun_stable(b, g, seq![shape], Seq::empty()); + lemma_values_stable(b, g, v0); + lemma_arun_stable(b, g, t0, vavs(b, v0)); + lemma_aref_trans(arun(g, seq![shape], Seq::empty()), arun(g, t0, vavs(g, v0)), arun(g, t1, vavs(g, v1))); +} + +pub proof fn lemma_run_end(g: model::Graph, shape: ActionShape, values: Seq) + requires xrun(g, shape, Seq::empty(), values), norm::transition_action_pushes(shape), + ensures values.len() == 1, run_bound(g, shape, values[0]@), values.last() == values[0], +{ + reveal(xpre); reveal(xeffect); reveal(xrun); reveal(xcfg); reveal(xstep); + lemma_arun_one(g, shape, Seq::empty()); + lemma_aapply_push(g, shape, Seq::empty()); + let s = vavs(g, values); + assert(arun(g, Seq::::empty(), s) == Some(s)); + let l = Seq::::empty().push(push_av(g, shape)); + assert(l[0] == push_av(g, shape)); + assert(stack_le(s, l)); + assert(s.len() == 1); + assert(av_le(s[0], l[0])); + lemma_vavs_index(g, values, 0); + assert(nf_sum(g, values[0]@)); +} + +// ===== entry points ===== + +/// After `local_if`, cleaning its result gives the class bound of `if_then_else`. +pub proof fn lemma_ite_future(g1: model::Graph, a: nat, b: nat, id1: nat, path: nat) + requires model::graph_wf(g1), a < g1.transitions.len(), b < g1.transitions.len(), id1 < g1.transitions.len(), + av_le(av_of(g1, id1), av_if(av_of(g1, a), av_of(g1, b))), + ensures forall|h: model::Graph, out: nat| model::graph_extends(g1, h) && #[trigger] run_bound(h, ActionShape::Clean(id1, path), out) + ==> ite_bound(h, out, a, b), +{ + assert forall|h: model::Graph, out: nat| model::graph_extends(g1, h) && #[trigger] run_bound(h, ActionShape::Clean(id1, path), out) + implies ite_bound(h, out, a, b) by { + lemma_av_stable(g1, h, id1); + lemma_av_stable(g1, h, a); + lemma_av_stable(g1, h, b); + lemma_av_le_trans(av_of(h, out), av_of(h, id1), av_if(av_of(h, a), av_of(h, b))); + } +} + +/// `if_then_else` before running the clean action: the local conditional is typed and bounded. +pub proof fn lemma_ite_start(e: model::Graph, g1: model::Graph, test: nat, a: nat, b: nat, id1: nat, path: nat) + requires model::graph_wf(e), model::graph_wf(g1), model::graph_extends(e, g1), a < e.transitions.len(), b < e.transitions.len(), + nf_sum(e, a), nf_sum(e, b), + id1 == a || id1 == b || (id1 < g1.transitions.len() && g1.transitions[id1 as int] == model::TransitionNode::If(test, a, b)), + ensures xnf_task(g1, ActionShape::Clean(id1, path)), + forall|h: model::Graph, out: nat| model::graph_extends(g1, h) && #[trigger] run_bound(h, ActionShape::Clean(id1, path), out) + ==> ite_bound(h, out, a, b), +{ + lemma_nf_sum_stable(e, g1, a); + lemma_nf_sum_stable(e, g1, b); + lemma_local_if(g1, test, a, b, id1); + lemma_ite_future(g1, a, b, id1, path); +} + +/// `append` before running the append action: the action is typed, and its run bound is the +/// class bound of `append` over the lifted suffix. +pub proof fn lemma_app_future(e: model::Graph, g1: model::Graph, this: nat, suffix: Seq, r: nat) + requires model::graph_wf(e), model::graph_wf(g1), model::graph_extends(e, g1), this < e.transitions.len(), + nf_sum(e, this), ids_nf(e, suffix), norm::regex_ids_valid(e, suffix), + r < g1.regexes.len(), norm::regex_concat_result(e, g1, suffix, r), + ensures xnf_task(g1, ActionShape::Append(this, r)), + forall|h: model::Graph, out: nat| model::graph_extends(g1, h) && #[trigger] run_bound(h, ActionShape::Append(this, r), out) + ==> app_bound(h, out, this, lifts(h, suffix)), +{ + lemma_nf_sum_stable(e, g1, this); + lemma_concat_link(e, g1, suffix, r); + let ys = lifts(e, suffix); + assert(all_rnf(ys)) by { + assert forall|i: int| 0 <= i < ys.len() implies regex_nf(#[trigger] ys[i]) by {} + } + lemma_cat_nf(ys); + assert forall|h: model::Graph, out: nat| model::graph_extends(g1, h) && #[trigger] run_bound(h, ActionShape::Append(this, r), out) + implies app_bound(h, out, this, lifts(h, suffix)) by { + lemma_regex_nf_stable(g1, h, r); + lemma_lifts_ids(e, h, suffix); + lemma_nf_sum_stable(g1, h, this); + norm::transition_lemma_extends_transitive(e, g1, h); + let z = model::lift_regex(h, r); + assert forall|v: R| #[trigger] tcls(h, out, v) implies rconst(v) || exists|w: R| tcls(h, this, w) && v == #[trigger] cat_front(w, ys) by { + assert((av_of(h, out).x)(v)); + if !rconst(v) { + let w = choose|w: R| (av_of(h, this).x)(w) && v == #[trigger] cat_r(w, z); + lemma_cls_nf(h, this, w); + lemma_cat_nest(w, ys); + assert(tcls(h, this, w) && v == cat_front(w, ys)); + } + } + } +} +} // verus! diff --git a/src/history-semantics/src/verify/finite_collect.rs b/src/history-semantics/src/verify/finite_collect.rs new file mode 100644 index 000000000..5b4980045 --- /dev/null +++ b/src/history-semantics/src/verify/finite_collect.rs @@ -0,0 +1,416 @@ +//! Classes of the outputs of `TransitionId::collect` (flattened unions and intersections of +//! transitions): the work lists of `TransitionMode::collect` hold members of the inputs +//! ([`collect_members`]), and the output's class is bounded by the union (intersection) of the +//! inputs' classes ([`collect_out`]). +use crate::normalize::verify as norm; +use crate::verify::finite_impl::*; +use crate::verify::finite_link::*; +use crate::verify::finite_machine::piece_of; +use crate::verify::finite_machine::*; +use crate::verify::finite_trans::*; +use junco_core::kernel::verify as model; +use junco_core::kernel::{RegexId, TransitionId}; +use vstd::prelude::*; + +verus! { + +broadcast use junco_core::kernel::verify::group_kernel_views; + +pub open spec fn tids(ids: Seq) -> Seq { + model::transition_ids(ids) +} + +/// A flattened (non-constant) element: not a set of the connective's kind, and not a leaf of an +/// intersection (those are merged). +pub open spec fn flat_ok(g: model::Graph, inter: bool, x: nat) -> bool { + x < g.transitions.len() && if inter { + !(g.transitions[x as int] is Intersect) && !(g.transitions[x as int] is Const) + } else { + !(g.transitions[x as int] is Union) + } +} + +pub open spec fn const_piece(g: model::Graph, orig: Seq, inter: bool, r: nat) -> bool { + exists|x: nat| #[trigger] piece_of(g, orig, inter, x) && x < g.transitions.len() + && g.transitions[x as int] == model::TransitionNode::Const(r) +} + +/// The work lists of `TransitionMode::collect` hold members of the inputs `orig`. +pub open spec fn collect_members(g: model::Graph, orig: Seq, inter: bool, + pending: Seq, flat: Seq, constants: Seq) -> bool { + &&& forall|k: int| #![trigger pending[k]] 0 <= k < pending.len() ==> piece_of(g, orig, inter, pending[k]@) + &&& forall|k: int| #![trigger flat[k]] 0 <= k < flat.len() ==> piece_of(g, orig, inter, flat[k]@) && flat_ok(g, inter, flat[k]@) + &&& forall|k: int| #![trigger constants[k]] 0 <= k < constants.len() ==> const_piece(g, orig, inter, constants[k]@) + &&& !inter ==> constants.len() == 0 +} + +pub proof fn lemma_members_start(g: model::Graph, pending: Seq, inter: bool) + ensures collect_members(g, tids(pending), inter, pending, Seq::empty(), Seq::empty()), +{ + assert forall|k: int| 0 <= k < pending.len() implies #[trigger] piece_of(g, tids(pending), inter, pending[k]@) by { + assert(tids(pending)[k] == pending[k]@); + assert(tpiece(g, tids(pending)[k], inter, pending[k]@)); + } +} + +pub proof fn lemma_members_pop(g: model::Graph, orig: Seq, inter: bool, + prefix: Seq, id: TransitionId, flat: Seq, constants: Seq) + requires collect_members(g, orig, inter, prefix.push(id), flat, constants), + ensures collect_members(g, orig, inter, prefix, flat, constants), piece_of(g, orig, inter, id@), +{ + assert(prefix.push(id)[prefix.len() as int] == id); + assert forall|k: int| 0 <= k < prefix.len() implies #[trigger] piece_of(g, orig, inter, prefix[k]@) by { + assert(prefix.push(id)[k] == prefix[k]); + } +} + +pub proof fn lemma_members_expand(g: model::Graph, orig: Seq, inter: bool, + prefix: Seq, id: TransitionId, children: Seq, flat: Seq, constants: Seq, + cs: Seq) + requires model::graph_wf(g), model::bounded(orig, g.transitions.len()), id@ < g.transitions.len(), + collect_members(g, orig, inter, prefix, flat, constants), piece_of(g, orig, inter, id@), + g.transitions[id@ as int] == (if inter { model::TransitionNode::Intersect(cs) } else { model::TransitionNode::Union(cs) }), + tids(children) == cs, + ensures collect_members(g, orig, inter, prefix + children, flat, constants), +{ + let i = choose|i: int| #![trigger orig[i]] 0 <= i < orig.len() && tpiece(g, orig[i], inter, id@); + assert forall|k: int| 0 <= k < (prefix + children).len() implies #[trigger] piece_of(g, orig, inter, (prefix + children)[k]@) by { + if k < prefix.len() { + assert((prefix + children)[k] == prefix[k]); + } else { + let j = k - prefix.len(); + assert((prefix + children)[k] == children[j]); + assert(tids(children)[j] == children[j]@); + lemma_tpiece_child(g, orig[i], inter, id@, cs, j); + } + } +} + +pub proof fn lemma_members_const(g: model::Graph, orig: Seq, inter: bool, + prefix: Seq, id: TransitionId, flat: Seq, constants: Seq, r: RegexId) + requires inter, collect_members(g, orig, inter, prefix, flat, constants), piece_of(g, orig, inter, id@), + id@ < g.transitions.len(), g.transitions[id@ as int] == model::TransitionNode::Const(r@), + ensures collect_members(g, orig, inter, prefix, flat, constants.push(r)), +{ + assert forall|k: int| 0 <= k < constants.push(r).len() implies #[trigger] const_piece(g, orig, inter, constants.push(r)[k]@) by { + if k < constants.len() { assert(constants.push(r)[k] == constants[k]); } + else { assert(constants.push(r)[k] == r); assert(piece_of(g, orig, inter, id@)); } + } +} + +pub proof fn lemma_members_leaf(g: model::Graph, orig: Seq, inter: bool, + prefix: Seq, id: TransitionId, flat: Seq, constants: Seq) + requires collect_members(g, orig, inter, prefix, flat, constants), piece_of(g, orig, inter, id@), flat_ok(g, inter, id@), + ensures collect_members(g, orig, inter, prefix, flat.push(id), constants), +{ + assert forall|k: int| 0 <= k < flat.push(id).len() implies #[trigger] piece_of(g, orig, inter, flat.push(id)[k]@) + && flat_ok(g, inter, flat.push(id)[k]@) by { + if k < flat.len() { assert(flat.push(id)[k] == flat[k]); } + } +} + +// ===== outputs ===== + +pub open spec fn all_nf(g: model::Graph, cs: Seq) -> bool { + forall|k: int| 0 <= k < cs.len() ==> nf_sum(g, #[trigger] cs[k]) +} + +pub open spec fn all_prod(g: model::Graph, cs: Seq) -> bool { + forall|k: int| 0 <= k < cs.len() ==> nf_prod(g, #[trigger] cs[k]) +} + +/// Class bound of an output of the collection of `cs`. +pub open spec fn cbound(g: model::Graph, cs: Seq, inter: bool, v: R) -> bool { + if inter { cl(true, |w: R| any_x(avs(g, cs), w), v) } else { any_x(avs(g, cs), v) || rconst(v) } +} + +/// An element allowed in the output of the collection of `cs`. +pub open spec fn elem_ok(g: model::Graph, cs: Seq, inter: bool, x: nat) -> bool { + &&& x < g.transitions.len() + &&& forall|v: R| #[trigger] tcls(g, x, v) ==> cbound(g, cs, inter, v) + &&& !inter ==> forall|v: R| #[trigger] ycls(g, x, v) ==> cl(false, |w: R| any_y(avs(g, cs), w), v) + &&& nf_sum(g, x) + &&& inter && all_prod(g, cs) ==> nf_lit(g, x) +} + +/// The output of the collection of normal-form `cs`: its class (and, for unions, its sum class) +/// is bounded by the inputs'; it is a normal form, except that an intersection of sums is an +/// intersection node whose children are allowed elements. +pub open spec fn collect_out(g: model::Graph, cs: Seq, inter: bool, out: nat) -> bool { + &&& out < g.transitions.len() + &&& forall|v: R| #[trigger] tcls(g, out, v) ==> cbound(g, cs, inter, v) + &&& !inter ==> forall|v: R| #[trigger] ycls(g, out, v) ==> cl(false, |w: R| any_y(avs(g, cs), w), v) + &&& !inter ==> nf_sum(g, out) + &&& inter && all_prod(g, cs) ==> nf_prod(g, out) + &&& inter ==> match g.transitions[out as int] { + model::TransitionNode::Intersect(ds) => forall|j: int| 0 <= j < ds.len() ==> #[trigger] elem_ok(g, cs, inter, ds[j]), + _ => nf_sum(g, out), + } +} + +/// An allowed element is an allowed output. +pub proof fn lemma_elem_out(g: model::Graph, cs: Seq, inter: bool, x: nat) + requires elem_ok(g, cs, inter, x), inter ==> !(g.transitions[x as int] is Intersect), + ensures collect_out(g, cs, inter, x), +{ + if inter && all_prod(g, cs) { + assert(nf_lit(g, x)); + assert(nf_prod(g, x)); + } +} + +/// Constant leaves are allowed elements. +pub proof fn lemma_const_elem(g: model::Graph, cs: Seq, inter: bool, x: nat, r: nat) + requires model::graph_wf(g), x < g.transitions.len(), g.transitions[x as int] == model::TransitionNode::Const(r), + r < g.regexes.len(), rconst(model::lift_regex(g, r)), + ensures elem_ok(g, cs, inter, x), +{ + assert forall|v: R| #[trigger] tcls(g, x, v) implies cbound(g, cs, inter, v) by { + lemma_tcls(g, x, v); + if inter { lemma_cl_const(true, |w: R| any_x(avs(g, cs), w), v); } + } + assert forall|v: R| #[trigger] ycls(g, x, v) implies cl(false, |w: R| any_y(avs(g, cs), w), v) by { + lemma_ycls(g, x, v); + lemma_cl_const(false, |w: R| any_y(avs(g, cs), w), v); + } + assert(regex_nf(model::lift_regex(g, r))); +} + +/// Members of normal-form inputs that are flattened elements are allowed elements in any +/// extension of the graph. +pub proof fn lemma_member_elem(g0: model::Graph, g: model::Graph, cs: Seq, inter: bool, x: nat) + requires model::graph_wf(g0), model::graph_extends(g0, g), model::bounded(cs, g0.transitions.len()), + all_nf(g0, cs), piece_of(g0, cs, inter, x), flat_ok(g0, inter, x), + ensures elem_ok(g, cs, inter, x), +{ + let i = choose|i: int| #![trigger cs[i]] 0 <= i < cs.len() && tpiece(g0, cs[i], inter, x); + lemma_tpiece_class(g0, cs[i], inter, x); + lemma_trans_stable(g0, g, x); + lemma_trans_stable(g0, g, cs[i]); + lemma_avs_stable(g0, g, cs); + assert(avs(g, cs)[i] == av_of(g, cs[i])); + assert forall|v: R| #[trigger] tcls(g, x, v) implies cbound(g, cs, inter, v) by { + assert(tcls(g0, x, v)); + assert(tcls(g0, cs[i], v)); + assert(tcls(g, cs[i], v)); + assert(any_x(avs(g, cs), v)); + if inter { lemma_cl_base(true, |w: R| any_x(avs(g, cs), w), v); } + } + if !inter { + assert forall|v: R| #[trigger] ycls(g, x, v) implies cl(false, |w: R| any_y(avs(g, cs), w), v) by { + assert(ycls(g0, x, v)); + assert(ycls(g0, cs[i], v)); + assert(ycls(g, cs[i], v)); + assert(any_y(avs(g, cs), v)); + lemma_cl_base(false, |w: R| any_y(avs(g, cs), w), v); + } + } + assert(nf_sum(g0, cs[i])); + if inter && all_prod(g, cs) { + lemma_trans_stable(g0, g, cs[i]); + assert(nf_prod(g, cs[i])); + assert(nf_prod(g0, cs[i])); + if x == cs[i] { + assert(nf_lit(g0, x)); + } + } +} + +/// The regexes of constant members are normal forms in the class of the inputs. +pub proof fn lemma_const_piece(g0: model::Graph, cs: Seq, inter: bool, r: nat) + requires model::graph_wf(g0), model::bounded(cs, g0.transitions.len()), all_nf(g0, cs), const_piece(g0, cs, inter, r), + ensures r < g0.regexes.len(), regex_nf(model::lift_regex(g0, r)), any_x(avs(g0, cs), model::lift_regex(g0, r)), +{ + let x = choose|x: nat| #[trigger] piece_of(g0, cs, inter, x) && x < g0.transitions.len() + && g0.transitions[x as int] == model::TransitionNode::Const(r); + let i = choose|i: int| #![trigger cs[i]] 0 <= i < cs.len() && tpiece(g0, cs[i], inter, x); + lemma_tpiece_class(g0, cs[i], inter, x); + assert(nf_sum(g0, cs[i])); + assert(nf_lit(g0, x)); + let v = model::lift_regex(g0, r); + lemma_tcls(g0, x, v); + assert(tcls(g0, cs[i], v)); + assert(avs(g0, cs)[i] == av_of(g0, cs[i])); +} + +/// The merged leaf of an intersection is an allowed element. +pub proof fn lemma_leaf_elem(g0: model::Graph, g1: model::Graph, g: model::Graph, cs: Seq, + constants: Seq, r: nat, t: nat) + requires model::graph_wf(g0), model::graph_wf(g1), model::graph_wf(g), model::graph_extends(g0, g1), model::graph_extends(g1, g), + model::bounded(cs, g0.transitions.len()), all_nf(g0, cs), + forall|k: int| 0 <= k < constants.len() ==> #[trigger] const_piece(g0, cs, true, constants[k]@), + norm::regex_ids_valid(g0, constants), r < g1.regexes.len(), + norm::regex_set_flat_inputs(g0, constants, true) ==> norm::regex_set_shape(g0, g1, constants, true, r), + t < g.transitions.len(), g.transitions[t as int] == model::TransitionNode::Const(r), + ensures elem_ok(g, cs, true, t), +{ + assert(ids_nf(g0, constants)) by { + assert forall|k: int| 0 <= k < constants.len() implies regex_nf(#[trigger] model::lift_regex(g0, constants[k]@)) by { + lemma_const_piece(g0, cs, true, constants[k]@); + } + } + lemma_flat_inputs(g0, constants, true); + lemma_set_link(g0, g1, constants, true, r); + model::lemma_graph_wf_elim(g1); + model::lemma_lift_regex_stable(g1, g, r); + lemma_avs_stable(g0, g, cs); + let base = |w: R| any_x(avs(g, cs), w); + assert forall|x: R| lift_set(g0, constants).contains(x) implies cl(true, base, x) by { + broadcast use vstd::prelude::Seq::to_set_ensures; + let k = choose|k: int| 0 <= k < lifts(g0, constants).len() && lifts(g0, constants)[k] == x; + lemma_const_piece(g0, cs, true, constants[k]@); + lemma_cl_base(true, base, x); + } + let m = model::lift_regex(g, r); + lemma_cl_nset(true, base, lift_set(g0, constants), m); + assert forall|v: R| #[trigger] tcls(g, t, v) implies cbound(g, cs, true, v) by { + lemma_tcls(g, t, v); + if rconst(v) { lemma_cl_const(true, base, v); } + } +} + +/// A union node of allowed elements is an allowed output. +pub proof fn lemma_union_node(g: model::Graph, cs: Seq, out: nat, flat: Seq) + requires model::graph_wf(g), out < g.transitions.len(), g.transitions[out as int] == model::TransitionNode::Union(flat), + forall|k: int| 0 <= k < flat.len() ==> #[trigger] elem_ok(g, cs, false, flat[k]), + ensures collect_out(g, cs, false, out), +{ + model::lemma_graph_transition_wf(g, out); + assert forall|v: R| #[trigger] tcls(g, out, v) implies cbound(g, cs, false, v) by { + lemma_tcls(g, out, v); + if !rconst(v) { + let k = choose|k: int| #![trigger flat[k]] 0 <= k < flat.len() && flat[k] < out && (tc(g))(flat[k], v); + assert(elem_ok(g, cs, false, flat[k])); + assert(tcls(g, flat[k], v)); + } + } + let yb = |w: R| any_y(avs(g, cs), w); + assert forall|v: R| #[trigger] ycls(g, out, v) implies cl(false, yb, v) by { + lemma_ycls(g, out, v); + assert forall|w: R| #[trigger] kids(yc(g), out, flat, w) implies cl(false, yb, w) by { + let k = choose|k: int| #![trigger flat[k]] 0 <= k < flat.len() && flat[k] < out && (yc(g))(flat[k], w); + assert(elem_ok(g, cs, false, flat[k])); + assert(ycls(g, flat[k], w)); + } + lemma_cl_mono(false, |w: R| kids(yc(g), out, flat, w), |w: R| cl(false, yb, w), v); + lemma_cl_idem(false, yb, v); + } + assert forall|k: int| 0 <= k < flat.len() implies flat[k] < out && nf_sum(g, #[trigger] flat[k]) by { + assert(elem_ok(g, cs, false, flat[k])); + } +} + +/// An intersection node of allowed elements is an allowed output. +pub proof fn lemma_inter_node(g: model::Graph, cs: Seq, out: nat, flat: Seq) + requires model::graph_wf(g), out < g.transitions.len(), g.transitions[out as int] == model::TransitionNode::Intersect(flat), + forall|k: int| 0 <= k < flat.len() ==> #[trigger] elem_ok(g, cs, true, flat[k]), + ensures collect_out(g, cs, true, out), +{ + model::lemma_graph_transition_wf(g, out); + let xb = |w: R| any_x(avs(g, cs), w); + assert forall|v: R| #[trigger] tcls(g, out, v) implies cbound(g, cs, true, v) by { + lemma_tcls(g, out, v); + assert forall|w: R| #[trigger] kids(tc(g), out, flat, w) implies cl(true, xb, w) by { + let k = choose|k: int| #![trigger flat[k]] 0 <= k < flat.len() && flat[k] < out && (tc(g))(flat[k], w); + assert(elem_ok(g, cs, true, flat[k])); + assert(tcls(g, flat[k], w)); + } + lemma_cl_mono(true, |w: R| kids(tc(g), out, flat, w), |w: R| cl(true, xb, w), v); + lemma_cl_idem(true, xb, v); + } + if all_prod(g, cs) { + assert forall|k: int| 0 <= k < flat.len() implies flat[k] < out && nf_lit(g, #[trigger] flat[k]) by { + assert(elem_ok(g, cs, true, flat[k])); + } + } +} + +/// Allowed elements stay allowed in graph extensions. +pub proof fn lemma_elem_stable(g: model::Graph, h: model::Graph, cs: Seq, inter: bool, x: nat) + requires model::graph_wf(g), model::graph_extends(g, h), model::bounded(cs, g.transitions.len()), elem_ok(g, cs, inter, x), + ensures elem_ok(h, cs, inter, x), h.transitions[x as int] == g.transitions[x as int], +{ + lemma_trans_stable(g, h, x); + lemma_avs_stable(g, h, cs); + assert(h.transitions[x as int] == g.transitions[x as int]) by { + assert(g.transitions == h.transitions.subrange(0, g.transitions.len() as int)); + } + assert forall|v: R| #[trigger] tcls(h, x, v) implies cbound(h, cs, inter, v) by { assert(tcls(g, x, v)); } + assert forall|v: R| #[trigger] ycls(h, x, v) && !inter implies cl(false, |w: R| any_y(avs(h, cs), w), v) by { + assert(ycls(g, x, v)); + } + if inter && all_prod(h, cs) { + assert(all_prod(g, cs)) by { + assert forall|k: int| 0 <= k < cs.len() implies nf_prod(g, #[trigger] cs[k]) by { + lemma_trans_stable(g, h, cs[k]); + } + } + } +} + +/// An allowed element that is not an intersection node. +pub open spec fn elem_flat(g: model::Graph, cs: Seq, inter: bool, x: nat) -> bool { + elem_ok(g, cs, inter, x) && (inter ==> !(g.transitions[x as int] is Intersect)) +} + +pub open spec fn set_tnode(inter: bool, ids: Seq) -> model::TransitionNode { + if inter { model::TransitionNode::Intersect(ids) } else { model::TransitionNode::Union(ids) } +} + +/// A set node interned later over allowed elements is an allowed output. +pub proof fn lemma_node_future(g: model::Graph, cs: Seq, inter: bool, ids: Seq) + requires model::graph_wf(g), model::bounded(cs, g.transitions.len()), + forall|k: int| 0 <= k < ids.len() ==> #[trigger] elem_flat(g, cs, inter, ids[k]), + ensures forall|h: model::Graph, out: nat| model::graph_wf(h) && model::graph_extends(g, h) && out < h.transitions.len() + && h.transitions[out as int] == set_tnode(inter, ids) ==> #[trigger] collect_out(h, cs, inter, out), +{ + assert forall|h: model::Graph, out: nat| model::graph_wf(h) && model::graph_extends(g, h) && out < h.transitions.len() + && h.transitions[out as int] == set_tnode(inter, ids) implies #[trigger] collect_out(h, cs, inter, out) by { + assert forall|k: int| 0 <= k < ids.len() implies #[trigger] elem_ok(h, cs, inter, ids[k]) by { + assert(elem_flat(g, cs, inter, ids[k])); + lemma_elem_stable(g, h, cs, inter, ids[k]); + } + if inter { lemma_inter_node(h, cs, out, ids); } else { lemma_union_node(h, cs, out, ids); } + } +} + +/// Allowed elements of a list stay allowed in graph extensions. +pub proof fn lemma_elems_stable(g: model::Graph, h: model::Graph, cs: Seq, inter: bool, ids: Seq) + requires model::graph_wf(g), model::graph_extends(g, h), model::bounded(cs, g.transitions.len()), + forall|k: int| 0 <= k < ids.len() ==> #[trigger] elem_flat(g, cs, inter, ids[k]@), + ensures forall|k: int| 0 <= k < ids.len() ==> #[trigger] elem_flat(h, cs, inter, ids[k]@), +{ + assert forall|k: int| 0 <= k < ids.len() implies #[trigger] elem_flat(h, cs, inter, ids[k]@) by { + assert(elem_flat(g, cs, inter, ids[k]@)); + lemma_elem_stable(g, h, cs, inter, ids[k]@); + } +} + +/// The flattened members of `TransitionMode::collect` are allowed elements. +pub proof fn lemma_members_elems(g: model::Graph, cs: Seq, inter: bool, flat: Seq, constants: Seq) + requires model::graph_wf(g), model::bounded(cs, g.transitions.len()), all_nf(g, cs), + collect_members(g, cs, inter, Seq::empty(), flat, constants), + ensures forall|k: int| 0 <= k < flat.len() ==> #[trigger] elem_flat(g, cs, inter, flat[k]@), +{ + assert forall|k: int| 0 <= k < flat.len() implies #[trigger] elem_flat(g, cs, inter, flat[k]@) by { + assert(piece_of(g, cs, inter, flat[k]@) && flat_ok(g, inter, flat[k]@)); + lemma_member_elem(g, g, cs, inter, flat[k]@); + } +} + +/// The constant transitions are allowed outputs. +pub proof fn lemma_const_out(g: model::Graph, cs: Seq, inter: bool, x: nat) + requires model::graph_wf(g), + x == g.constants.transition_empty || x == g.constants.transition_all || x == g.constants.transition_epsilon, + ensures collect_out(g, cs, inter, x), elem_flat(g, cs, inter, x), +{ + model::lemma_graph_wf_elim(g); + crate::normalize::verify::regex_constants(g); + let c = g.constants; + let r = if x == c.transition_empty { c.empty } else if x == c.transition_all { c.all } else { c.epsilon }; + assert(g.transitions[x as int] == model::TransitionNode::Const(r)); + lemma_const_elem(g, cs, inter, x, r); + lemma_elem_out(g, cs, inter, x); +} + +} // verus! diff --git a/src/history-semantics/src/verify/finite_compile.rs b/src/history-semantics/src/verify/finite_compile.rs new file mode 100644 index 000000000..b0013ff04 --- /dev/null +++ b/src/history-semantics/src/verify/finite_compile.rs @@ -0,0 +1,253 @@ +//! Compiled tails are hereditary normal forms: every test and regex `CompiledPair::compile` +//! (`compile.rs`) builds from a flat rule lifts to a normal form (`finite_impl::test_nf`, +//! `finite_impl::regex_nf`), so the lifted root of a compiled pair is a state of +//! `finite_impl::m_impl` (the `instantiation_ok` obligation of `refinement::finiteness`). +//! One lemma per constructor used by `compile`: constants and atoms, `TestId::connective` +//! ([`lemma_connective_nf`]), `RegexId::from_test`, `concat`, `set`, `not` (via the +//! `finite_link` lemmas), and `star` (its own ensures, [`lemma_star_future`]). +use crate::normalize::verify as norm; +use crate::verify::finite_impl::*; +use crate::verify::finite_link::*; +use crate::verify::finite_trans::lemma_cat_nf; +use alloc::boxed::Box; +use junco_core::kernel::verify as model; +use junco_core::kernel::{RegexId, TestId}; +use junco_core::verify::history_specs::Regex; +use vstd::prelude::*; + +verus! { + +broadcast use junco_core::kernel::verify::group_kernel_views; + +pub open spec fn tests_nf(g: model::Graph, ts: Seq) -> bool { + forall|k: int| #![trigger ts[k]] 0 <= k < ts.len() ==> ts[k]@ < g.tests.len() && test_nf(model::lift_test(g, ts[k]@)) +} + +/// The tests and regexes built so far by `compile` are normal forms. +#[verifier::opaque] +pub open spec fn compiled_nf(g: model::Graph, ts: Seq, rs: Seq) -> bool { + tests_nf(g, ts) && norm::regex_ids_valid(g, rs) && ids_nf(g, rs) +} + +pub proof fn lemma_compiled_empty(g: model::Graph) + ensures compiled_nf(g, Seq::empty(), Seq::empty()), +{ + reveal(compiled_nf); +} + +pub proof fn lemma_compiled_stable(a: model::Graph, b: model::Graph, ts: Seq, rs: Seq) + requires model::graph_wf(a), model::graph_extends(a, b), compiled_nf(a, ts, rs), + ensures compiled_nf(b, ts, rs), +{ + reveal(compiled_nf); + model::lemma_graph_wf_elim(a); + assert forall|k: int| #![trigger ts[k]] 0 <= k < ts.len() implies ts[k]@ < b.tests.len() && test_nf(model::lift_test(b, ts[k]@)) by { + model::lemma_lift_test_stable(a, b, ts[k]@); + } + assert forall|k: int| 0 <= k < rs.len() implies rs[k]@ < b.regexes.len() by {} + assert forall|k: int| 0 <= k < rs.len() implies regex_nf(#[trigger] model::lift_regex(b, rs[k]@)) by { + assert(rs[k]@ < a.regexes.len()); + model::lemma_lift_regex_stable(a, b, rs[k]@); + } +} + +/// The `k`-th compiled regex. +pub proof fn lemma_compiled_regex(g: model::Graph, ts: Seq, rs: Seq, k: int) + requires compiled_nf(g, ts, rs), 0 <= k < rs.len(), + ensures rs[k]@ < g.regexes.len(), regex_nf(model::lift_regex(g, rs[k]@)), +{ + reveal(compiled_nf); +} + +pub proof fn lemma_compiled_test(g: model::Graph, ts: Seq, rs: Seq, k: int) + requires compiled_nf(g, ts, rs), 0 <= k < ts.len(), + ensures ts[k]@ < g.tests.len(), test_nf(model::lift_test(g, ts[k]@)), +{ + reveal(compiled_nf); +} + +pub proof fn lemma_push_test(before: model::Graph, after: model::Graph, ts: Seq, rs: Seq, id: TestId) + requires model::graph_wf(before), model::graph_extends(before, after), compiled_nf(before, ts, rs), + id@ < after.tests.len(), test_nf(model::lift_test(after, id@)), + ensures compiled_nf(after, ts.push(id), rs), +{ + lemma_compiled_stable(before, after, ts, rs); + reveal(compiled_nf); + assert forall|k: int| #![trigger ts.push(id)[k]] 0 <= k < ts.push(id).len() + implies ts.push(id)[k]@ < after.tests.len() && test_nf(model::lift_test(after, ts.push(id)[k]@)) by { + if k < ts.len() { assert(ts.push(id)[k] == ts[k]); } + } +} + +pub proof fn lemma_push_regex(before: model::Graph, after: model::Graph, ts: Seq, rs: Seq, id: RegexId) + requires model::graph_wf(before), model::graph_extends(before, after), compiled_nf(before, ts, rs), + id@ < after.regexes.len(), regex_nf(model::lift_regex(after, id@)), + ensures compiled_nf(after, ts, rs.push(id)), +{ + lemma_compiled_stable(before, after, ts, rs); + reveal(compiled_nf); + assert forall|k: int| 0 <= k < rs.push(id).len() implies rs.push(id)[k]@ < after.regexes.len() by { + if k < rs.len() { assert(rs.push(id)[k] == rs[k]); } + } + assert forall|k: int| 0 <= k < rs.push(id).len() implies regex_nf(#[trigger] model::lift_regex(after, rs.push(id)[k]@)) by { + if k < rs.len() { assert(rs.push(id)[k] == rs[k]); } + } +} + +// ===== tests ===== + +/// Constants and atoms are normal forms. +pub proof fn lemma_test_simple_nf(g: model::Graph, id: nat) + requires model::graph_wf(g), + id == g.constants.test_true || id == g.constants.test_false || (id < g.tests.len() && g.tests[id as int] is Atom), + ensures id < g.tests.len(), test_nf(model::lift_test(g, id)), +{ + norm::regex_constants(g); + if id < g.tests.len() { lemma_test_lift(g, id); } +} + +/// `TestId::connective` on normal-form operands (`test_connective_result`) is a normal form. +pub proof fn lemma_connective_nf(before: model::Graph, after: model::Graph, ts: Seq, rs: Seq, + children: Seq, selected: Seq, and: bool, r: nat) + requires model::graph_wf(before), model::graph_wf(after), model::graph_extends(before, after), compiled_nf(before, ts, rs), + selected.len() == children.len(), + forall|i: int| 0 <= i < children.len() ==> #[trigger] children[i] < ts.len() && selected[i] == ts[children[i] as int], + r < after.tests.len(), norm::test_connective_result(before, after, selected, and, r), + ensures test_nf(model::lift_test(after, r)), +{ + reveal(compiled_nf); + norm::regex_constants(before); + model::lemma_graph_wf_elim(before); + assert forall|k: int| 0 <= k < selected.len() implies #[trigger] selected[k]@ < before.tests.len() + && test_nf(model::lift_test(before, selected[k]@)) by { + assert(children[k] < ts.len()); + assert(selected[k] == ts[children[k] as int]); + } + if r == before.constants.test_true || r == before.constants.test_false { + model::lemma_lift_test_stable(before, after, r); + } else if norm::test_member(before, selected, and, r) { + lemma_test_member_link(before, selected, and, r); + model::lemma_lift_test_stable(before, after, r); + } else { + lemma_test_lift(after, r); + match after.tests[r as int] { + model::TestNode::And(ks) => { lemma_connective_kids(before, after, selected, and, r, ks); }, + model::TestNode::Or(ks) => { lemma_connective_kids(before, after, selected, and, r, ks); }, + _ => {}, + } + } +} + +// ===== regexes ===== + +pub proof fn lemma_regex_const_nf(g: model::Graph, id: nat) + requires model::graph_wf(g), id == g.constants.empty || id == g.constants.all || id == g.constants.epsilon, + ensures id < g.regexes.len(), regex_nf(model::lift_regex(g, id)), +{ + norm::regex_constants(g); +} + +/// `RegexId::from_test` on a compiled test. +pub proof fn lemma_from_test_nf(before: model::Graph, after: model::Graph, ts: Seq, rs: Seq, k: int, id: nat) + requires model::graph_wf(before), model::graph_wf(after), model::graph_extends(before, after), compiled_nf(before, ts, rs), + 0 <= k < ts.len(), id < after.regexes.len(), + if ts[k]@ == after.constants.test_false { id == after.constants.empty } + else { after.regexes[id as int].kind == model::RegexKindNode::Test(ts[k]@) }, + ensures regex_nf(model::lift_regex(after, id)), +{ + lemma_compiled_test(before, ts, rs, k); + norm::regex_constants(after); + model::lemma_graph_wf_elim(before); + if ts[k]@ != after.constants.test_false { + lemma_regex_lift(after, id); + model::lemma_lift_test_stable(before, after, ts[k]@); + } +} + +pub proof fn lemma_selected_nf(g: model::Graph, ts: Seq, rs: Seq, children: Seq, selected: Seq) + requires compiled_nf(g, ts, rs), selected.len() == children.len(), + forall|i: int| 0 <= i < children.len() ==> #[trigger] children[i] < rs.len() && selected[i] == rs[children[i] as int], + ensures norm::regex_ids_valid(g, selected), ids_nf(g, selected), +{ + reveal(compiled_nf); + assert forall|i: int| 0 <= i < selected.len() implies selected[i]@ < g.regexes.len() by { + assert(children[i] < rs.len()); + assert(selected[i] == rs[children[i] as int]); + } + assert forall|i: int| 0 <= i < selected.len() implies regex_nf(#[trigger] model::lift_regex(g, selected[i]@)) by { + assert(children[i] < rs.len()); + assert(selected[i] == rs[children[i] as int]); + } +} + +/// `RegexId::concat` on compiled regexes. +pub proof fn lemma_concat_nf(before: model::Graph, after: model::Graph, ts: Seq, rs: Seq, + children: Seq, selected: Seq, id: nat) + requires model::graph_wf(before), model::graph_wf(after), model::graph_extends(before, after), compiled_nf(before, ts, rs), + selected.len() == children.len(), + forall|i: int| 0 <= i < children.len() ==> #[trigger] children[i] < rs.len() && selected[i] == rs[children[i] as int], + id < after.regexes.len(), norm::regex_concat_result(before, after, selected, id), + ensures regex_nf(model::lift_regex(after, id)), +{ + lemma_selected_nf(before, ts, rs, children, selected); + lemma_concat_link(before, after, selected, id); + let xs = lifts(before, selected); + assert forall|i: int| 0 <= i < xs.len() implies regex_nf(#[trigger] xs[i]) by { + assert(xs[i] == model::lift_regex(before, selected[i]@)); + } + lemma_cat_nf(xs); +} + +/// `RegexId::set` on compiled regexes. +pub proof fn lemma_set_nf(before: model::Graph, after: model::Graph, ts: Seq, rs: Seq, + children: Seq, selected: Seq, inter: bool, id: nat) + requires model::graph_wf(before), model::graph_wf(after), model::graph_extends(before, after), compiled_nf(before, ts, rs), + selected.len() == children.len(), + forall|i: int| 0 <= i < children.len() ==> #[trigger] children[i] < rs.len() && selected[i] == rs[children[i] as int], + id < after.regexes.len(), + norm::regex_set_flat_inputs(before, selected, inter) ==> norm::regex_set_shape(before, after, selected, inter, id), + ensures regex_nf(model::lift_regex(after, id)), +{ + lemma_selected_nf(before, ts, rs, children, selected); + lemma_flat_inputs(before, selected, inter); + lemma_set_link(before, after, selected, inter, id); +} + +/// `RegexId::not` on a compiled regex. +pub proof fn lemma_not_nf(before: model::Graph, after: model::Graph, ts: Seq, rs: Seq, k: int, id: nat) + requires model::graph_wf(before), model::graph_wf(after), model::graph_extends(before, after), compiled_nf(before, ts, rs), + 0 <= k < rs.len(), id < after.regexes.len(), norm::regex_not_result(after, rs[k]@, id), + ensures regex_nf(model::lift_regex(after, id)), +{ + lemma_compiled_regex(before, ts, rs, k); + model::lemma_graph_wf_elim(before); + model::lemma_lift_regex_stable(before, after, rs[k]@); + lemma_not_link(after, rs[k]@, id); +} + +/// Before `RegexId::star`'s head match: each of its outputs is a normal form when its operand is. +pub proof fn lemma_star_future(g0: model::Graph, this: nat) + requires model::graph_wf(g0), this < g0.regexes.len(), + ensures forall|g1: model::Graph, id: nat| model::graph_extends(g0, g1) && model::graph_wf(g1) + && (id == g0.constants.epsilon || id == g0.constants.all || id == this + || (id < g1.regexes.len() && g1.regexes[id as int].kind == model::RegexKindNode::Star(this))) + && regex_nf(model::lift_regex(g0, this)) + ==> regex_nf(#[trigger] model::lift_regex(g1, id)), +{ + assert forall|g1: model::Graph, id: nat| model::graph_extends(g0, g1) && model::graph_wf(g1) + && (id == g0.constants.epsilon || id == g0.constants.all || id == this + || (id < g1.regexes.len() && g1.regexes[id as int].kind == model::RegexKindNode::Star(this))) + && regex_nf(model::lift_regex(g0, this)) + implies regex_nf(#[trigger] model::lift_regex(g1, id)) by { + model::lemma_graph_wf_elim(g0); + norm::regex_constants(g1); + model::lemma_lift_regex_stable(g0, g1, this); + if id == g0.constants.epsilon || id == g0.constants.all || id == this { + } else { + lemma_regex_lift(g1, id); + assert(model::lift_regex(g1, id) == Regex::::Star(Box::new(model::lift_regex(g1, this)))); + } + } +} + +} // verus! diff --git a/src/history-semantics/src/verify/finite_deriv.rs b/src/history-semantics/src/verify/finite_deriv.rs new file mode 100644 index 000000000..9387afe9d --- /dev/null +++ b/src/history-semantics/src/verify/finite_deriv.rs @@ -0,0 +1,575 @@ +//! Class bounds of the implemented derivative (`symbolic.rs` `RegexId::derivative`): the +//! transition built for a normal-form state `p` is a normal form whose class consists of literals +//! and products of `p` in `verify::finite_impl::m_impl` ([`dbound`], i.e. `finite_trans::dclass`). +//! The derivative cache carries [`dbound`] for every entry (`symbolic::verify::derivative_cache_wf`). +//! Per regex kind: constants and tests ([`lemma_dbound_const`], [`lemma_dbound_test`]), stars +//! ([`lemma_dbound_star`], via `star_lit`), complements ([`lemma_dbound_not`], via `not_lit`), and +//! sets and lists from the bounds of their factors ([`fbound`], [`lemma_factor_set`], +//! [`lemma_factor_concat`], [`lemma_derive_future`]). +use crate::normalize::verify::{self as norm, ActionShape}; +use crate::symbolic::verify::{derivative_cache_wf, derivative_constants, derivative_correct}; +use crate::verify::finite_branch::*; +use crate::verify::finite_collect::*; +use crate::verify::finite_impl::*; +use crate::verify::finite_link::*; +use crate::verify::finite_machine::*; +use crate::verify::finite_states::*; +use crate::verify::finite_steps::*; +use crate::verify::finite_trans::*; +use alloc::boxed::Box; +use junco_core::kernel::verify as model; +use junco_core::kernel::{RegexId, TransitionId}; +use junco_core::verify::history_specs::Regex; +use vstd::prelude::*; + +verus! { + +broadcast use junco_core::kernel::verify::group_kernel_views; + +/// The derivative `t` of the regex id `root` has the class bound of its lifted state, when that +/// state is a normal form. +#[verifier::opaque] +pub open spec fn dbound(g: model::Graph, root: nat, t: nat) -> bool { + regex_nf(model::lift_regex(g, root)) ==> dclass(g, t, model::lift_regex(g, root)) +} + +/// `v` is a literal and a product of `p`. +pub open spec fn lp(p: R, v: R) -> bool { + (m_impl().lit)(p, v) && (m_impl().prod)(p, v) +} + +/// A factor result of the derivative of `root`: a normal form whose class consists of literals +/// and products of `root`'s state. +pub open spec fn fbound(g: model::Graph, root: nat, t: nat) -> bool { + nf_sum(g, t) && forall|v: R| #[trigger] tcls(g, t, v) ==> lp(model::lift_regex(g, root), v) +} + +#[verifier::opaque] +pub open spec fn results_bound(g: model::Graph, root: nat, results: Seq) -> bool { + regex_nf(model::lift_regex(g, root)) ==> forall|k: int| 0 <= k < results.len() ==> #[trigger] fbound(g, root, results[k]@) +} + +// ===== literals and products ===== + +/// Constants are literals and products of every state. +pub proof fn lemma_const_lp(p: R, v: R) + requires regex_nf(p), rconst(v), + ensures lp(p, v), +{ + let m = m_impl(); + lemma_models_agree(); + assert(regex_nf(v)); + assert(m.lit_shape(p, v)) by { + if !m.base_kind(p) { + if m.k(p) == Kind::Union { lemma_cl_const(false, |w: R| m.ops_lit(p, w), v); } + else if m.k(p) == Kind::Intersect { lemma_cl_const(true, |w: R| m.ops_lit(p, w), v); } + else if m.k(p) == Kind::Not { lemma_cl_const(true, |w: R| m.not_lit(p, w), v); } + else if m.k(p) == Kind::Star { lemma_cl_const(false, |w: R| m.star_lit(p, w), v); } + else { lemma_cl_const(false, |w: R| m.list_lit(p, w), v); } + } + } + lemma_lit_fold(p, v); + assert(m.prod_shape(p, v)) by { + if m.k(p) == Kind::Intersect || m.k(p) == Kind::Not { lemma_cl_const(true, |w: R| (m.lit)(p, w), v); } + } + lemma_prod_fold(p, v); +} + +/// A literal `v` of `p` built by the literal shape is a literal and a product. +pub proof fn lemma_lit_to_lp(p: R, v: R) + requires regex_nf(p), regex_nf(v), m_impl().lit_shape(p, v), !m_impl().base_kind(p), m_impl().k(p) != Kind::Union, + ensures lp(p, v), +{ + let m = m_impl(); + lemma_lit_fold(p, v); + assert(m.prod_shape(p, v)) by { + if m.k(p) == Kind::Intersect || m.k(p) == Kind::Not { lemma_cl_base(true, |w: R| (m.lit)(p, w), v); } + } + lemma_prod_fold(p, v); +} + +pub proof fn lemma_dclass_from(g: model::Graph, t: nat, p: R) + requires nf_sum(g, t), forall|v: R| #[trigger] tcls(g, t, v) ==> lp(p, v), !m_impl().base_kind(p), + ensures dclass(g, t, p), +{} + +// ===== stability ===== + +pub proof fn lemma_dbound_stable(a: model::Graph, b: model::Graph, root: nat, t: nat) + requires model::graph_wf(a), model::graph_extends(a, b), root < a.regexes.len(), t < a.transitions.len(), dbound(a, root, t), + ensures dbound(b, root, t), +{ + reveal(dbound); + lemma_regex_nf_stable(a, b, root); + lemma_trans_stable(a, b, t); + let p = model::lift_regex(a, root); + if regex_nf(p) { + assert forall|w: R| #[trigger] tcls(b, t, w) implies (m_impl().lit)(p, w) && (m_impl().prod)(p, w) by { assert(tcls(a, t, w)); } + assert forall|w: R| #[trigger] ycls(b, t, w) && m_impl().base_kind(p) implies rconst(w) by { assert(ycls(a, t, w)); } + } +} + +pub proof fn lemma_fbound_stable(a: model::Graph, b: model::Graph, root: nat, t: nat) + requires model::graph_wf(a), model::graph_extends(a, b), root < a.regexes.len(), fbound(a, root, t), + ensures fbound(b, root, t), +{ + lemma_regex_nf_stable(a, b, root); + lemma_trans_stable(a, b, t); + assert forall|v: R| #[trigger] tcls(b, t, v) implies lp(model::lift_regex(b, root), v) by { assert(tcls(a, t, v)); } +} + +pub proof fn lemma_results_stable(a: model::Graph, b: model::Graph, root: nat, results: Seq) + requires model::graph_wf(a), model::graph_extends(a, b), root < a.regexes.len(), results_bound(a, root, results), + ensures results_bound(b, root, results), +{ + reveal(results_bound); + lemma_regex_nf_stable(a, b, root); + if regex_nf(model::lift_regex(b, root)) { + assert forall|k: int| 0 <= k < results.len() implies #[trigger] fbound(b, root, results[k]@) by { + assert(fbound(a, root, results[k]@)); + lemma_fbound_stable(a, b, root, results[k]@); + } + } +} + +pub proof fn lemma_results_push(g: model::Graph, root: nat, results: Seq, t: TransitionId) + requires results_bound(g, root, results), regex_nf(model::lift_regex(g, root)) ==> fbound(g, root, t@), + ensures results_bound(g, root, results.push(t)), +{ + reveal(results_bound); + if regex_nf(model::lift_regex(g, root)) { + assert forall|k: int| 0 <= k < results.push(t).len() implies #[trigger] fbound(g, root, results.push(t)[k]@) by { + if k < results.len() { assert(results.push(t)[k] == results[k]); } + } + } +} + +pub proof fn lemma_results_empty(g: model::Graph, root: nat) + ensures results_bound(g, root, Seq::empty()), +{ reveal(results_bound); } + +// ===== constants and tests ===== + +pub proof fn lemma_dbound_const(g: model::Graph, root: nat, out: nat) + requires model::graph_wf(g), root < g.regexes.len(), + match g.regexes[root as int].kind { + model::RegexKindNode::Empty => out == g.constants.transition_empty, + model::RegexKindNode::Epsilon => out == g.constants.transition_empty, + model::RegexKindNode::All => out == g.constants.transition_all, + _ => false, + }, + ensures dbound(g, root, out), +{ + reveal(dbound); + lemma_regex_lift(g, root); + lemma_const_transitions(g); + model::lemma_graph_wf_elim(g); + norm::regex_constants(g); + let p = model::lift_regex(g, root); + if regex_nf(p) { + let c = g.constants; + lemma_const_cls(g, c.transition_all, c.all); + assert forall|w: R| #[trigger] tcls(g, out, w) implies (m_impl().lit)(p, w) && (m_impl().prod)(p, w) by { + lemma_const_lp(p, w); + } + assert forall|w: R| #[trigger] ycls(g, out, w) && m_impl().base_kind(p) implies rconst(w) by {} + } +} + +pub proof fn lemma_dbound_test(g0: model::Graph, g: model::Graph, root: nat, t: nat, out: nat) + requires model::graph_wf(g0), model::graph_wf(g), model::graph_extends(g0, g), root < g0.regexes.len(), + g0.regexes[root as int].kind == model::RegexKindNode::Test(t), + (nf_sum(g0, g0.constants.transition_epsilon) && nf_sum(g0, g0.constants.transition_empty)) + ==> ite_bound(g, out, g0.constants.transition_epsilon, g0.constants.transition_empty), + ensures dbound(g, root, out), +{ + reveal(dbound); + lemma_const_transitions(g0); + lemma_regex_lift(g0, root); + lemma_regex_nf_stable(g0, g, root); + lemma_const_transitions(g); + let c = g.constants; + let p = model::lift_regex(g, root); + lemma_av_le_cls(g, out, out); + if regex_nf(p) { + assert forall|w: R| #[trigger] tcls(g, out, w) implies (m_impl().lit)(p, w) && (m_impl().prod)(p, w) by { + assert((av_of(g, out).x)(w)); + assert(tcls(g, c.transition_epsilon, w) || tcls(g, c.transition_empty, w)); + lemma_const_lp(p, w); + } + assert forall|w: R| #[trigger] ycls(g, out, w) implies rconst(w) by { + assert((av_of(g, out).y)(w)); + assert(ycls(g, c.transition_epsilon, w) || ycls(g, c.transition_empty, w)); + } + } +} + +// ===== stars and complements ===== + +pub proof fn lemma_ids_nf1(g: model::Graph, s: Seq, r: RegexId) + requires s.len() == 1, s[0] == r, regex_nf(model::lift_regex(g, r@)), + ensures ids_nf(g, s), +{ + assert forall|i: int| 0 <= i < s.len() implies regex_nf(#[trigger] model::lift_regex(g, s[i]@)) by { assert(i == 0); } +} + +pub proof fn lemma_dbound_star(g0: model::Graph, g: model::Graph, root: RegexId, inner: nat, d: nat, out: nat) + requires model::graph_wf(g0), model::graph_wf(g), model::graph_extends(g0, g), root@ < g0.regexes.len(), + g0.regexes[root@ as int].kind == model::RegexKindNode::Star(inner), d < g0.transitions.len(), + dbound(g0, inner, d), (nf_sum(g0, d) && ids_nf(g0, seq![root])) ==> app_bound(g, out, d, lifts(g, seq![root])), + ensures dbound(g, root@, out), +{ + reveal(dbound); + lemma_regex_lift(g0, root@); + lemma_regex_nf_stable(g0, g, root@); + let p = model::lift_regex(g, root@); + if regex_nf(p) { + let m = m_impl(); + lemma_models_agree(); + let b = model::lift_regex(g0, inner); + assert(p == Regex::::Star(Box::new(b))); + assert(regex_nf(b)); + assert(dclass(g0, d, b)); + lemma_ids_nf1(g0, seq![root], root); + lemma_trans_stable(g0, g, d); + assert(lifts(g, seq![root]) =~= seq![p]); + assert forall|v: R| #[trigger] tcls(g, out, v) implies lp(p, v) by { + lemma_cls_nf(g, out, v); + if rconst(v) { lemma_const_lp(p, v); } else { + let w = choose|w: R| tcls(g, d, w) && v == #[trigger] cat_front(w, lifts(g, seq![root])); + assert(tcls(g0, d, w)); + assert((m.prod)(b, w)); + assert(seq![w] + seq![p] =~= seq![w, p]); + assert(v == m.cat2(w, p)); + assert((m.body)(p) == b); + assert(m.star_lit(p, v)); + lemma_cl_base(false, |x: R| m.star_lit(p, x), v); + assert(m.lit_shape(p, v)); + lemma_lit_to_lp(p, v); + } + } + lemma_dclass_from(g, out, p); + } +} + +pub proof fn lemma_dbound_not(g0: model::Graph, g: model::Graph, root: nat, inner: nat, d: nat, out: nat) + requires model::graph_wf(g0), model::graph_wf(g), model::graph_extends(g0, g), root < g0.regexes.len(), + g0.regexes[root as int].kind == model::RegexKindNode::Not(inner), d < g0.transitions.len(), + dbound(g0, inner, d), nf_sum(g0, d) ==> run_bound(g, ActionShape::Not(d), out), + ensures dbound(g, root, out), +{ + reveal(dbound); + lemma_regex_lift(g0, root); + lemma_regex_nf_stable(g0, g, root); + let p = model::lift_regex(g, root); + if regex_nf(p) { + let m = m_impl(); + lemma_models_agree(); + let b = model::lift_regex(g0, inner); + assert(p == Regex::::Not(Box::new(b))); + assert(regex_nf(b)); + assert(dclass(g0, d, b)); + lemma_trans_stable(g0, g, d); + lemma_av_stable(g0, g, d); + let nb = |w: R| neg_of(av_of(g, d), w); + let lb = |w: R| m.not_lit(p, w); + assert forall|w: R| #[trigger] nb(w) implies lb(w) by { + let x = choose|x: R| (av_of(g, d).x)(x) && w == #[trigger] r_not(x); + assert(tcls(g0, d, x)); + assert((m.lit)(b, x)); + assert((m.body)(p) == b); + assert(w == (m.nnot)(x)); + } + assert forall|v: R| #[trigger] tcls(g, out, v) implies lp(p, v) by { + lemma_cls_nf(g, out, v); + assert((av_of(g, out).x)(v)); + lemma_cl_mono(true, nb, lb, v); + assert(m.lit_shape(p, v)); + lemma_lit_to_lp(p, v); + } + lemma_dclass_from(g, out, p); + } +} + +// ===== sets and lists ===== + +/// The derivative of a member of a set state is a factor of the set's derivative. +pub proof fn lemma_factor_set(g: model::Graph, root: nat, i: int, d: nat) + requires model::graph_wf(g), root < g.regexes.len(), d < g.transitions.len(), + match g.regexes[root as int].kind { + model::RegexKindNode::Union(cs) => 0 <= i < cs.len() && dbound(g, cs[i], d), + model::RegexKindNode::Intersect(cs) => 0 <= i < cs.len() && dbound(g, cs[i], d), + _ => false, + }, + ensures regex_nf(model::lift_regex(g, root)) ==> fbound(g, root, d), +{ + reveal(dbound); + lemma_regex_lift(g, root); + let p = model::lift_regex(g, root); + if regex_nf(p) { + let m = m_impl(); + lemma_models_agree(); + let cs = match g.regexes[root as int].kind { + model::RegexKindNode::Union(cs) => cs, model::RegexKindNode::Intersect(cs) => cs, _ => Seq::empty(), + }; + let ls = model::lift_regexes(g, cs); + let o = ls[i]; + assert(o == model::lift_regex(g, cs[i])); + assert(regex_nf(o)); + assert(dclass(g, d, o)); + assert((m.ops)(p).contains(o)) by { + broadcast use vstd::prelude::Seq::to_set_ensures; + assert(ls.contains(o)); + } + let inter = g.regexes[root as int].kind is Intersect; + assert forall|v: R| #[trigger] tcls(g, d, v) implies lp(p, v) by { + lemma_cls_nf(g, d, v); + assert((m.lit)(o, v) && (m.prod)(o, v)); + assert(m.ops_lit(p, v)); + lemma_cl_base(inter, |w: R| m.ops_lit(p, w), v); + assert(m.lit_shape(p, v)); + lemma_lit_fold(p, v); + assert(m.prod_shape(p, v)) by { + if inter { lemma_cl_base(true, |w: R| (m.lit)(p, w), v); } + } + lemma_prod_fold(p, v); + } + } +} + +/// The append of the derivative of a list element to the following elements is a factor of the +/// list's derivative. +pub proof fn lemma_factor_concat(g: model::Graph, root: nat, i: int, d: nat, suffix: Seq, out: nat) + requires model::graph_wf(g), root < g.regexes.len(), d < g.transitions.len(), + match g.regexes[root as int].kind { + model::RegexKindNode::Concat(cs) => 0 <= i < cs.len() && dbound(g, cs[i], d) + && model::regex_ids(suffix) == cs.subrange(i + 1, cs.len() as int), + _ => false, + }, + norm::regex_ids_valid(g, suffix), + (nf_sum(g, d) && ids_nf(g, suffix)) ==> app_bound(g, out, d, lifts(g, suffix)), + ensures regex_nf(model::lift_regex(g, root)) ==> fbound(g, root, out), +{ + reveal(dbound); + lemma_regex_lift(g, root); + let p = model::lift_regex(g, root); + if regex_nf(p) { + let m = m_impl(); + lemma_models_agree(); + theorem_impl_contract(); + let cs = g.regexes[root as int].kind->Concat_0; + let es = model::lift_regexes(g, cs); + assert((m.elems)(p) == es); + let o = es[i]; + assert(o == model::lift_regex(g, cs[i])); + assert(regex_nf(o)); + assert(dclass(g, d, o)); + let ys = lifts(g, suffix); + let sub = cs.subrange(i + 1, cs.len() as int); + assert(model::regex_ids(suffix).len() == suffix.len()); + assert(ys.len() == es.skip(i + 1).len()); + assert forall|j: int| 0 <= j < ys.len() implies ys[j] == es.skip(i + 1)[j] && regex_nf(#[trigger] model::lift_regex(g, suffix[j]@)) by { + assert(model::regex_ids(suffix)[j] == suffix[j]@); + assert(model::regex_ids(suffix)[j] == sub[j]); + assert(sub[j] == cs[i + 1 + j]); + assert(es.skip(i + 1)[j] == es[i + 1 + j]); + assert(es[i + 1 + j] == model::lift_regex(g, cs[i + 1 + j])); + assert(ys[j] == model::lift_regex(g, suffix[j]@)); + } + assert(ys =~= es.skip(i + 1)); + assert(ids_nf(g, suffix)); + assert forall|v: R| #[trigger] tcls(g, out, v) implies lp(p, v) by { + lemma_cls_nf(g, out, v); + if rconst(v) { lemma_const_lp(p, v); } else { + let w = choose|w: R| tcls(g, d, w) && v == #[trigger] cat_front(w, ys); + assert((m.prod)(o, w) && (m.lit)(o, w)); + lemma_cls_nf(g, d, w); + if i < es.len() - 1 { + assert(v == (m.ncat)(seq![w] + es.skip(i + 1))); + assert(m.list_lit(p, v)); + } else { + assert(es.skip(i + 1) =~= Seq::::empty()); + assert(seq![w] + es.skip(i + 1) =~= seq![w]); + lemma_cat_single(m, w); + assert(v == w); + assert(es.last() == o); + assert(m.list_lit(p, v)); + } + lemma_cl_base(false, |x: R| m.list_lit(p, x), v); + assert(m.lit_shape(p, v)); + lemma_lit_to_lp(p, v); + } + } + } +} + +/// `lemma_factor_concat` with the cache and suffix read in the graph `g0` before the append. +pub proof fn lemma_factor_concat2(g0: model::Graph, g: model::Graph, root: nat, i: int, d: nat, suffix: Seq, out: nat) + requires model::graph_wf(g0), model::graph_wf(g), model::graph_extends(g0, g), root < g0.regexes.len(), d < g0.transitions.len(), + match g0.regexes[root as int].kind { + model::RegexKindNode::Concat(cs) => 0 <= i < cs.len() && dbound(g0, cs[i], d) + && model::regex_ids(suffix) == cs.subrange(i + 1, cs.len() as int), + _ => false, + }, + norm::regex_ids_valid(g0, suffix), + (nf_sum(g0, d) && ids_nf(g0, suffix)) ==> app_bound(g, out, d, lifts(g, suffix)), + ensures regex_nf(model::lift_regex(g, root)) ==> fbound(g, root, out), +{ + lemma_regex_nf_stable(g0, g, root); + assert(g.regexes[root as int] == g0.regexes[root as int]) by { + assert(g0.regexes == g.regexes.subrange(0, g0.regexes.len() as int)); + } + model::lemma_graph_regex_wf(g0, root); + assert(g0.regexes[root as int].kind is Concat); + let cs = g0.regexes[root as int].kind->Concat_0; + assert(0 <= i < cs.len()); + assert(cs[i] < g0.regexes.len()); + lemma_dbound_stable(g0, g, cs[i], d); + lemma_nf_sum_stable(g0, g, d); + lemma_lifts_ids(g0, g, suffix); + if ids_nf(g, suffix) { + assert forall|j: int| 0 <= j < suffix.len() implies regex_nf(#[trigger] model::lift_regex(g0, suffix[j]@)) by { + assert(lifts(g0, suffix)[j] == lifts(g, suffix)[j]); + assert(regex_nf(model::lift_regex(g, suffix[j]@))); + } + assert(ids_nf(g0, suffix)); + } + assert(norm::regex_ids_valid(g, suffix)) by { + assert forall|j: int| 0 <= j < suffix.len() implies suffix[j]@ < g.regexes.len() by {} + } + lemma_factor_concat(g, root, i, d, suffix, out); +} + +/// A closure of literals and products of an intersection state consists of literals and +/// products. +pub proof fn lemma_inter_closed(p: R, v: R) + requires regex_nf(p), p is Intersect, cl(true, |w: R| lp(p, w), v), regex_nf(v), + ensures lp(p, v), +{ + let m = m_impl(); + theorem_impl_contract(); + lemma_models_agree(); + let ob = |w: R| m.ops_lit(p, w); + assert forall|w: R| #[trigger] lp(p, w) implies cl(true, ob, w) by { + assert(m.lit_shape(p, w)); + } + lemma_cl_mono(true, |w: R| lp(p, w), |w: R| cl(true, ob, w), v); + lemma_cl_idem(true, ob, v); + assert(m.lit_shape(p, v)); + lemma_lit_to_lp(p, v); +} + +/// Before the final set constructor of `derive`: whatever the constructor returns in a later graph +/// has the class bound of the root. +pub proof fn lemma_derive_future(g0: model::Graph, root: nat, results: Seq, inter: bool) + requires model::graph_wf(g0), root < g0.regexes.len(), norm::transition_ids_valid(g0, results), + results_bound(g0, root, results), + match g0.regexes[root as int].kind { + model::RegexKindNode::Union(_) => !inter, + model::RegexKindNode::Concat(_) => !inter, + model::RegexKindNode::Intersect(_) => inter, + _ => false, + }, + ensures + forall|h: model::Graph, out: nat| model::graph_extends(g0, h) && (all_nf(g0, model::transition_ids(results)) ==> if inter { + run_bound(h, ActionShape::Fold(model::transition_ids(results), 0), out) + } else { collect_out(h, model::transition_ids(results), false, out) }) ==> #[trigger] dbound(h, root, out), +{ + reveal(dbound); + reveal(results_bound); + let ts = model::transition_ids(results); + assert forall|h: model::Graph, out: nat| model::graph_extends(g0, h) && (all_nf(g0, ts) ==> if inter { + run_bound(h, ActionShape::Fold(ts, 0), out) + } else { collect_out(h, ts, false, out) }) implies #[trigger] dbound(h, root, out) by { + lemma_regex_nf_stable(g0, h, root); + let p = model::lift_regex(h, root); + lemma_regex_lift(g0, root); + if regex_nf(p) { + assert(all_nf(g0, ts)) by { + assert forall|k: int| 0 <= k < ts.len() implies nf_sum(g0, #[trigger] ts[k]) by { + assert(ts[k] == results[k]@); + assert(fbound(g0, root, results[k]@)); + } + } + lemma_all_nf_stable(g0, h, ts); + // every result's class consists of literals and products of `p` + let base = |w: R| lp(p, w); + assert forall|k: int, w: R| 0 <= k < avs(h, ts).len() && #[trigger] (avs(h, ts)[k].x)(w) implies lp(p, w) && cl(true, base, w) by { + assert(ts[k] == results[k]@); + assert(fbound(g0, root, results[k]@)); + lemma_fbound_stable(g0, h, root, results[k]@); + assert(tcls(h, ts[k], w)); + lemma_cl_base(true, base, w); + } + if inter { + assert forall|k: int, w: R| 0 <= k < avs(h, ts).len() && #[trigger] (avs(h, ts)[k].x)(w) implies cl(true, base, w) by {} + lemma_meet_le_cl(avs(h, ts), base); + assert forall|v: R| #[trigger] tcls(h, out, v) implies lp(p, v) by { + assert((av_of(h, out).x)(v)); + lemma_cls_nf(h, out, v); + lemma_inter_closed(p, v); + } + } else { + assert forall|v: R| #[trigger] tcls(h, out, v) implies lp(p, v) by { + assert(cbound(h, ts, false, v)); + if rconst(v) { lemma_const_lp(p, v); } else { + let k = choose|k: int| #![trigger avs(h, ts)[k]] 0 <= k < avs(h, ts).len() && (avs(h, ts)[k].x)(v); + } + } + } + lemma_dclass_from(h, out, p); + } + } +} + +/// What `RegexId::derivative_step` establishes for the transition `out` it builds for `root` +/// (`g0` is the graph before the constructors, `cache` the derivative cache): constants, the +/// conditional of a test, the class bounds of `append`/`not` on the cached derivative of the +/// body, and [`dbound`] itself for sets and lists (from `DerivativeFactors::derive`). +pub open spec fn native_bound(g0: model::Graph, g: model::Graph, root: RegexId, cache: Seq>, out: nat) -> bool { + match g0.regexes[root@ as int].kind { + model::RegexKindNode::Empty => out == g0.constants.transition_empty, + model::RegexKindNode::Epsilon => out == g0.constants.transition_empty, + model::RegexKindNode::All => out == g0.constants.transition_all, + model::RegexKindNode::Test(_) => (nf_sum(g0, g0.constants.transition_epsilon) && nf_sum(g0, g0.constants.transition_empty)) + ==> ite_bound(g, out, g0.constants.transition_epsilon, g0.constants.transition_empty), + model::RegexKindNode::Star(inner) => inner < cache.len() && cache[inner as int] is Some + && ((nf_sum(g0, cache[inner as int]->Some_0@) && ids_nf(g0, seq![root])) + ==> app_bound(g, out, cache[inner as int]->Some_0@, lifts(g, seq![root]))), + model::RegexKindNode::Not(inner) => inner < cache.len() && cache[inner as int] is Some + && (nf_sum(g0, cache[inner as int]->Some_0@) ==> run_bound(g, ActionShape::Not(cache[inner as int]->Some_0@), out)), + _ => dbound(g, root@, out), + } +} + +/// Before the head match of `derivative_step`: whatever the match builds in a later graph has +/// the class bound of `root`. +pub proof fn lemma_native_future(g0: model::Graph, root: RegexId, cache: Seq>) + requires model::graph_wf(g0), root@ < g0.regexes.len(), derivative_cache_wf(g0, cache), + ensures forall|g: model::Graph, out: nat| model::graph_extends(g0, g) && model::graph_wf(g) + && #[trigger] native_bound(g0, g, root, cache, out) ==> dbound(g, root@, out), +{ + assert forall|g: model::Graph, out: nat| model::graph_extends(g0, g) && model::graph_wf(g) + && #[trigger] native_bound(g0, g, root, cache, out) implies dbound(g, root@, out) by { + derivative_constants(g0); + match g0.regexes[root@ as int].kind { + model::RegexKindNode::Empty => { lemma_dbound_const(g0, root@, out); lemma_dbound_stable(g0, g, root@, out); }, + model::RegexKindNode::Epsilon => { lemma_dbound_const(g0, root@, out); lemma_dbound_stable(g0, g, root@, out); }, + model::RegexKindNode::All => { lemma_dbound_const(g0, root@, out); lemma_dbound_stable(g0, g, root@, out); }, + model::RegexKindNode::Test(t) => { lemma_dbound_test(g0, g, root@, t, out); }, + model::RegexKindNode::Star(inner) => { + let d = cache[inner as int]->Some_0; + assert(derivative_correct(g0, inner, d) && dbound(g0, inner, d@)); + lemma_dbound_star(g0, g, root, inner, d@, out); + }, + model::RegexKindNode::Not(inner) => { + let d = cache[inner as int]->Some_0; + assert(derivative_correct(g0, inner, d) && dbound(g0, inner, d@)); + lemma_dbound_not(g0, g, root@, inner, d@, out); + }, + _ => {}, + } + } +} + +} // verus! diff --git a/src/history-semantics/src/verify/finite_impl.rs b/src/history-semantics/src/verify/finite_impl.rs new file mode 100644 index 000000000..aff1acb28 --- /dev/null +++ b/src/history-semantics/src/verify/finite_impl.rs @@ -0,0 +1,963 @@ +//! The finiteness model instantiated with the implementation's states (see `finiteness::instantiation_ok`). +//! +//! States are lifted trees `Regex` in *hereditary normal form* ([`regex_nf`]): set +//! operands are duplicate-free and not sets of the same kind, lists have at least two atoms, +//! complements wrap neither constants nor complements, and connective tests are flat and +//! duplicate-free. The constructors are the tree-level counterparts of the implemented ones: +//! `N(¬·)` is [`r_not`] (`normalize::verify::regex_not_result`), `N(x₁⋯xₖ)` is [`r_cat`] +//! (`regex_concat_result`), and since the implementation orders set operands by interning order, +//! `N(ΣX)`/`N(&X)` is the relation of all outputs allowed by (N1)/(N2) (`regex_set_shape`), and the +//! test combinations are all outputs allowed by `test_connective_result`. Literals, products, and +//! successors are the *largest* relations allowed by (S0)–(S6): `lit`/`prod` are the greatest +//! fixpoint of the successor equations ([`g_lit`], [`g_prod`]), characterized by +//! [`lemma_lit_fold`]/[`lemma_prod_fold`], and `succ` is every state allowed by (S0)/(S1). +//! [`theorem_impl_contract`] proves the contract. +use crate::verify::finite_states::*; +use alloc::boxed::Box; +use junco_core::kernel::verify as model; +use junco_core::verify::history_specs::Regex; +use vstd::iset_lib::lemma_iset_subset_finite; +use vstd::prelude::*; + +verus! { + +pub type R = Regex; + +// ===== hereditary normal forms ===== + +/// `phi` is in the piece contributed by `psi` to a flattened `∧` (`inter`) or `∨`. +pub open spec fn test_piece(inter: bool, psi: model::Test, phi: model::Test) -> bool { + match psi { + model::Test::And(cs) => if inter { cs.contains(phi) } else { phi == psi }, + model::Test::Or(cs) => if !inter { cs.contains(phi) } else { phi == psi }, + _ => phi == psi, + } +} + +pub open spec fn is_conn(inter: bool, t: model::Test) -> bool { + if inter { t is And } else { t is Or } +} + +pub open spec fn test_kids(t: model::Test) -> Seq { + match t { model::Test::And(cs) => cs, model::Test::Or(cs) => cs, _ => seq![] } +} + +pub open spec fn test_nf(t: model::Test) -> bool + decreases t, +{ + match t { + model::Test::And(cs) => cs.no_duplicates() + && forall|i: int| 0 <= i < cs.len() ==> test_nf(#[trigger] cs[i]) && !(cs[i] is And), + model::Test::Or(cs) => cs.no_duplicates() + && forall|i: int| 0 <= i < cs.len() ==> test_nf(#[trigger] cs[i]) && !(cs[i] is Or), + _ => true, + } +} + +pub open spec fn regex_nf(r: R) -> bool + decreases r, +{ + match r { + Regex::Test(t) => test_nf(t), + Regex::Union(cs) => cs.no_duplicates() + && forall|i: int| 0 <= i < cs.len() ==> regex_nf(#[trigger] cs[i]) && !(cs[i] is Union), + Regex::Intersect(cs) => cs.no_duplicates() + && forall|i: int| 0 <= i < cs.len() ==> regex_nf(#[trigger] cs[i]) && !(cs[i] is Intersect), + Regex::Concat(cs) => cs.len() >= 2 + && forall|i: int| 0 <= i < cs.len() ==> regex_nf(#[trigger] cs[i]) + && !(cs[i] is Concat || cs[i] is Epsilon || cs[i] is Empty), + Regex::Star(b) => regex_nf(*b), + Regex::Not(b) => regex_nf(*b) && !(*b is Empty || *b is All || *b is Not), + _ => true, + } +} + +pub open spec fn r_kind(r: R) -> Kind { + match r { + Regex::Empty => Kind::Empty, Regex::Epsilon => Kind::Epsilon, Regex::All => Kind::Universal, + Regex::Test(_) => Kind::Test, Regex::Union(_) => Kind::Union, Regex::Intersect(_) => Kind::Intersect, + Regex::Not(_) => Kind::Not, Regex::Star(_) => Kind::Star, Regex::Concat(_) => Kind::List, + } +} + +pub open spec fn r_ops(r: R) -> Set { + match r { Regex::Union(cs) => cs.to_set(), Regex::Intersect(cs) => cs.to_set(), _ => Set::empty() } +} + +pub open spec fn r_body(r: R) -> R { + match r { Regex::Star(b) => *b, Regex::Not(b) => *b, _ => Regex::Empty } +} + +pub open spec fn r_elems(r: R) -> Seq { + match r { Regex::Concat(cs) => cs, _ => seq![] } +} + +pub open spec fn r_size(r: R) -> nat + decreases r, 1nat, 0nat, +{ + match r { + Regex::Union(cs) => 1 + r_sum(r, cs.len()), + Regex::Intersect(cs) => 1 + r_sum(r, cs.len()), + Regex::Concat(cs) => 1 + r_sum(r, cs.len()), + Regex::Star(b) => 1 + r_size(*b), + Regex::Not(b) => 1 + r_size(*b), + _ => 1, + } +} + +/// Sum of the sizes of the first `n` children of a set or list. +pub open spec fn r_sum(r: R, n: nat) -> nat + decreases r, 0nat, n, +{ + match r { + Regex::Union(cs) => if 0 < n <= cs.len() { r_sum(r, (n - 1) as nat) + r_size(cs[n - 1]) } else { 0 }, + Regex::Intersect(cs) => if 0 < n <= cs.len() { r_sum(r, (n - 1) as nat) + r_size(cs[n - 1]) } else { 0 }, + Regex::Concat(cs) => if 0 < n <= cs.len() { r_sum(r, (n - 1) as nat) + r_size(cs[n - 1]) } else { 0 }, + _ => 0, + } +} + +/// `N(¬x)` (`regex_not_result`). +pub open spec fn r_not(x: R) -> R { + match x { Regex::Empty => Regex::All, Regex::All => Regex::Empty, Regex::Not(b) => *b, _ => Regex::Not(Box::new(x)) } +} + +/// `phi` is a piece of the test of some member of `us`. +pub open spec fn piece_of(inter: bool, us: Set, phi: model::Test) -> bool { + exists|psi: model::Test| us.contains(Regex::Test(psi)) && #[trigger] test_piece(inter, psi, phi) +} + +/// Test combinations allowed by `test_connective_result`: `⊤`, `⊥`, a piece of an input, or a +/// connective over pieces of the inputs. +pub open spec fn test_combo(inter: bool, us: Set, phi: model::Test) -> bool { + ||| phi == model::Test::True + ||| phi == model::Test::False + ||| piece_of(inter, us, phi) + ||| is_conn(inter, phi) && forall|k: int| 0 <= k < test_kids(phi).len() ==> piece_of(inter, us, #[trigger] test_kids(phi)[k]) +} + +pub open spec fn r_combo(inter: bool, us: Set, t: R) -> bool { + regex_nf(t) && match t { Regex::Test(phi) => test_combo(inter, us, phi), _ => false } +} + +/// The model without its relations (placeholders), used to define them. +pub open spec fn pre() -> Model { + Model { + state: |x: R| regex_nf(x), + kind: |x: R| r_kind(x), + ops: |x: R| r_ops(x), + body: |x: R| r_body(x), + elems: |x: R| r_elems(x), + size: |x: R| r_size(x), + empty: Regex::Empty, + epsilon: Regex::Epsilon, + universal: Regex::All, + nset: |inter: bool, xs: Set, u: R| false, + nnot: |x: R| r_not(x), + ncat: |xs: Seq| Regex::Empty, + combo: |inter: bool, us: Set, t: R| r_combo(inter, us, t), + succ: |p: R, v: R| false, + lit: |p: R, v: R| false, + prod: |p: R, v: R| false, + } +} + +/// `N(x₁⋯xₖ)` (`regex_concat_result`), defined by (N4). +pub open spec fn r_cat(xs: Seq) -> R { + let f = pre().flat(xs); + if pre().has_empty(xs) { Regex::Empty } else if f.len() == 0 { Regex::Epsilon } else if f.len() == 1 { f[0] } else { Regex::Concat(f) } +} + +/// Normal forms and constructors; the set constructor relates `X` to every output allowed by (N1)/(N2). +pub open spec fn core() -> Model { + Model { + nset: |inter: bool, xs: Set, u: R| pre().nset_shape(inter, xs, u), + ncat: |xs: Seq| r_cat(xs), + ..pre() + } +} + +pub open spec fn with_rel(l: spec_fn(R, R) -> bool, p: spec_fn(R, R) -> bool) -> Model { + Model { lit: l, prod: p, ..core() } +} + +/// `(l, p)` satisfies the successor equations (S1)–(S6): a post-fixpoint. +pub open spec fn consistent(l: spec_fn(R, R) -> bool, p: spec_fn(R, R) -> bool) -> bool { + &&& forall|a: R, v: R| regex_nf(a) && #[trigger] l(a, v) ==> regex_nf(v) && with_rel(l, p).lit_shape(a, v) + &&& forall|a: R, v: R| regex_nf(a) && #[trigger] p(a, v) ==> regex_nf(v) && with_rel(l, p).prod_shape(a, v) +} + +/// The largest literal relation allowed by (S1)–(S6). +pub open spec fn g_lit(a: R, v: R) -> bool { + exists|l: spec_fn(R, R) -> bool, p: spec_fn(R, R) -> bool| #[trigger] consistent(l, p) && l(a, v) +} + +/// The largest product relation allowed by (S1)–(S6). +pub open spec fn g_prod(a: R, v: R) -> bool { + exists|l: spec_fn(R, R) -> bool, p: spec_fn(R, R) -> bool| #[trigger] consistent(l, p) && p(a, v) +} + +pub open spec fn m_gfp() -> Model { + with_rel(|a: R, v: R| g_lit(a, v), |a: R, v: R| g_prod(a, v)) +} + +/// The largest successor relation allowed by (S0)/(S1). +pub open spec fn g_succ(a: R, v: R) -> bool { + regex_nf(v) && m_gfp().succ_shape(a, v) +} + +/// The implementation's model. +pub open spec fn m_impl() -> Model { + Model { succ: |a: R, v: R| g_succ(a, v), ..m_gfp() } +} + +// ===== sizes ===== + +pub proof fn lemma_sum_ge(r: R, n: nat, i: int) + requires 0 <= i < n, n <= r_elems_or_ops(r).len(), + ensures r_size(r_elems_or_ops(r)[i]) <= r_sum(r, n), + decreases n, +{ + if i < n - 1 { lemma_sum_ge(r, (n - 1) as nat, i); } +} + +pub open spec fn r_elems_or_ops(r: R) -> Seq { + match r { Regex::Union(cs) => cs, Regex::Intersect(cs) => cs, Regex::Concat(cs) => cs, _ => seq![] } +} + +pub proof fn lemma_child_smaller(r: R, i: int) + requires 0 <= i < r_elems_or_ops(r).len(), + ensures r_size(r_elems_or_ops(r)[i]) < r_size(r), +{ + lemma_sum_ge(r, r_elems_or_ops(r).len(), i); +} + +// ===== sequences over a finite set ===== + +pub open spec fn seqs_over(d: Set, n: nat) -> ISet> { + ISet::new(|s: Seq| s.len() <= n && forall|i: int| 0 <= i < s.len() ==> d.contains(#[trigger] s[i])) +} + +pub open spec fn pusher(base: ISet>) -> spec_fn(A) -> ISet> { + |x: A| base.map(|s: Seq| s.push(x)) +} + +pub proof fn lemma_seqs_over_finite(d: Set, n: nat) + ensures seqs_over(d, n).finite(), + decreases n, +{ + broadcast use vstd::iset::lemma_iset_union_finite, vstd::iset::lemma_iset_empty_finite, vstd::iset::lemma_iset_insert_finite; + if n == 0 { + assert(seqs_over(d, 0) =~= ISet::empty().insert(Seq::::empty())) by { + assert forall|s: Seq| seqs_over(d, 0).contains(s) implies s == Seq::::empty() by { + assert(s =~= Seq::::empty()); + } + } + } else { + let base = seqs_over(d, (n - 1) as nat); + lemma_seqs_over_finite(d, (n - 1) as nat); + let mk = pusher(base); + assert forall|x: A| d.contains(x) implies #[trigger] mk(x).finite() by { + base.lemma_map_finite(|s: Seq| s.push(x)); + } + lemma_big_union_finite(d, mk); + let big = ISet::new(|s: Seq| exists|x: A| d.contains(x) && #[trigger] mk(x).contains(s)); + assert forall|s: Seq| seqs_over(d, n).contains(s) implies base.union(big).contains(s) by { + if s.len() > 0 { + let init = s.drop_last(); + let x = s.last(); + assert(base.contains(init)) by { + assert forall|i: int| 0 <= i < init.len() implies d.contains(#[trigger] init[i]) by { assert(init[i] == s[i]); } + } + assert(init.push(x) =~= s); + assert(d.contains(s[s.len() - 1])); + assert(mk(x).contains(s)); + } else { + assert(base.contains(s)); + } + } + lemma_iset_subset_finite(base.union(big), seqs_over(d, n)); + } +} + +/// A duplicate-free sequence over `d` is no longer than `d`. +pub proof fn lemma_nodup_len(s: Seq, d: Set) + requires s.no_duplicates(), forall|i: int| 0 <= i < s.len() ==> d.contains(#[trigger] s[i]), + ensures s.len() <= d.len(), +{ + broadcast use vstd::prelude::Seq::to_set_ensures; + s.unique_seq_to_set(); + assert(s.to_set().subset_of(d)) by { + assert forall|a: A| s.to_set().contains(a) implies d.contains(a) by { + let i = choose|i: int| 0 <= i < s.len() && s[i] == a; + } + } + vstd::set_lib::lemma_len_subset(s.to_set(), d); +} + +// ===== the contract ===== + +pub proof fn lemma_models_agree() + ensures + m_impl().state == pre().state, m_impl().kind == pre().kind, m_impl().ops == pre().ops, + m_impl().body == pre().body, m_impl().elems == pre().elems, m_impl().size == pre().size, + m_impl().empty == pre().empty, m_impl().epsilon == pre().epsilon, m_impl().universal == pre().universal, + m_impl().nnot == pre().nnot, m_impl().combo == pre().combo, + m_impl().nset == core().nset, m_impl().ncat == core().ncat, + m_impl().lit == m_gfp().lit, m_impl().prod == m_gfp().prod, +{} + +/// `flat` reads only kinds, list elements, and `ε`. +pub proof fn lemma_flat_agree(m1: Model, m2: Model, xs: Seq) + requires m1.kind == m2.kind, m1.elems == m2.elems, m1.epsilon == m2.epsilon, + ensures m1.flat(xs) == m2.flat(xs), + decreases xs.len(), +{ + if xs.len() > 0 { lemma_flat_agree(m1, m2, xs.drop_last()); } +} + +/// Without `∅`, the flattening of states consists of atoms. +pub proof fn lemma_pre_flat_atoms(xs: Seq) + requires forall|i: int| 0 <= i < xs.len() ==> regex_nf(#[trigger] xs[i]), !pre().has_empty(xs), + ensures pre().atoms(pre().flat(xs)), + decreases xs.len(), +{ + let m = pre(); + if xs.len() > 0 { + let init = xs.drop_last(); + let x = xs.last(); + assert(!m.has_empty(init)) by { + if m.has_empty(init) { + let i = choose|i: int| 0 <= i < init.len() && init[i] == m.empty; + assert(xs[i] == m.empty); + } + } + assert forall|i: int| 0 <= i < init.len() implies regex_nf(#[trigger] init[i]) by { assert(init[i] == xs[i]); } + lemma_pre_flat_atoms(init); + assert(regex_nf(xs[xs.len() - 1])); + assert(x != m.empty) by { assert(xs[xs.len() - 1] == x); } + assert(m.atoms(m.piece(x))) by { + if m.k(x) == Kind::List { + let es = r_elems(x); + assert forall|i: int| 0 <= i < es.len() implies m.atom(#[trigger] es[i]) by {} + } + } + let f = m.flat(xs); + assert(f == m.flat(init) + m.piece(x)); + assert forall|i: int| 0 <= i < f.len() implies m.atom(#[trigger] f[i]) by { + if i < m.flat(init).len() { + assert(f[i] == m.flat(init)[i]); + } else { + assert(f[i] == m.piece(x)[i - m.flat(init).len()]); + } + } + } +} + +pub proof fn lemma_impl_substates() + ensures m_impl().substates_ok(), +{ + let m = m_impl(); + lemma_models_agree(); + broadcast use vstd::prelude::Seq::to_set_ensures; + assert forall|x: R, o: R| m.st(x) && (m.k(x) == Kind::Union || m.k(x) == Kind::Intersect) + && #[trigger] (m.ops)(x).contains(o) implies m.st(o) && (m.size)(o) < (m.size)(x) by { + let cs = r_elems_or_ops(x); + assert(cs.contains(o)); + let i = choose|i: int| 0 <= i < cs.len() && cs[i] == o; + lemma_child_smaller(x, i); + } + assert forall|x: R| m.st(x) && (m.k(x) == Kind::Not || m.k(x) == Kind::Star) + implies m.st(#[trigger] (m.body)(x)) && (m.size)((m.body)(x)) < (m.size)(x) by {} + assert forall|x: R| m.st(x) && m.k(x) == Kind::List implies { + let es = #[trigger] (m.elems)(x); + es.len() >= 2 && forall|i: int| 0 <= i < es.len() ==> m.atom(#[trigger] es[i]) && (m.size)(es[i]) < (m.size)(x) + } by { + let es = r_elems(x); + assert forall|i: int| 0 <= i < es.len() implies m.atom(#[trigger] es[i]) && (m.size)(es[i]) < (m.size)(x) by { + lemma_child_smaller(x, i); + } + } +} + +pub proof fn lemma_impl_fixpoints() + ensures m_impl().fixpoints_ok(), +{ + let m = m_impl(); + lemma_models_agree(); + assert forall|x: R| m.st(x) && m.k(x) == Kind::List implies (m.ncat)(#[trigger] (m.elems)(x)) == x by { + let es = r_elems(x); + assert(pre().atoms(es)) by { + assert forall|i: int| 0 <= i < es.len() implies pre().atom(#[trigger] es[i]) by {} + } + lemma_flat_atoms(pre(), es); + assert(!pre().has_empty(es)) by { + if pre().has_empty(es) { + let i = choose|i: int| 0 <= i < es.len() && es[i] == pre().empty; + assert(pre().atom(es[i])); + } + } + } + assert forall|x: R| m.st(x) && m.k(x) == Kind::Not implies (m.nnot)(#[trigger] (m.body)(x)) == x by {} +} + +pub proof fn lemma_impl_not() + ensures m_impl().not_ok(), +{ + let m = m_impl(); + lemma_models_agree(); + assert forall|x: R| m.st(x) implies #[trigger] m.not_shape(x) by {} +} + +pub proof fn lemma_impl_cat() + ensures m_impl().cat_ok(), +{ + let m = m_impl(); + lemma_models_agree(); + assert forall|xs: Seq| m.states(xs) implies #[trigger] m.cat_shape(xs) by { + lemma_flat_agree(m, pre(), xs); + assert(m.has_empty(xs) == pre().has_empty(xs)); + if !pre().has_empty(xs) { + assert forall|i: int| 0 <= i < xs.len() implies regex_nf(#[trigger] xs[i]) by { assert(m.st(xs[i])); } + lemma_pre_flat_atoms(xs); + let f = pre().flat(xs); + if f.len() == 1 { + assert(pre().atom(f[0])); + } else if f.len() >= 2 { + assert forall|i: int| 0 <= i < f.len() implies regex_nf(#[trigger] f[i]) + && !(f[i] is Concat || f[i] is Epsilon || f[i] is Empty) by { + assert(pre().atom(f[i])); + } + assert(regex_nf(Regex::Concat(f))); + } + } + } +} + +pub proof fn lemma_impl_nset() + ensures m_impl().nset_ok(), +{ + let m = m_impl(); + lemma_models_agree(); + assert forall|inter: bool, xs: Set, u: R| (forall|x: R| xs.contains(x) ==> m.st(x)) + && #[trigger] (m.nset)(inter, xs, u) implies m.nset_shape(inter, xs, u) by { + assert(pre().nset_shape(inter, xs, u)); + lemma_nset_shape_agree(pre(), m, inter, xs, u); + } + assert forall|inter: bool, f: Set| #[trigger] m.has_set_bound(inter, f) by { + lemma_set_bound(inter, f); + } +} + +pub open spec fn set_node(inter: bool, cs: Seq) -> R { + if inter { Regex::Intersect(cs) } else { Regex::Union(cs) } +} + +pub proof fn lemma_set_bound(inter: bool, f: Set) + ensures m_impl().has_set_bound(inter, f), +{ + broadcast use vstd::prelude::Seq::to_set_ensures, vstd::set::lemma_set_new_from_iset; + let m = m_impl(); + lemma_models_agree(); + let sq = seqs_over(f, f.len()); + lemma_seqs_over_finite(f, f.len()); + let img = sq.map(|cs: Seq| set_node(inter, cs)); + sq.lemma_map_finite(|cs: Seq| set_node(inter, cs)); + let g = Set::new_from_iset(img).unwrap(); + assert(g.to_iset() == img); + assert forall|x: R| m.st(x) && m.is_set(inter, x) && (m.ops)(x).subset_of(f) implies #[trigger] g.contains(x) by { + let cs = r_elems_or_ops(x); + assert forall|i: int| 0 <= i < cs.len() implies f.contains(#[trigger] cs[i]) by { + assert(cs.to_set().contains(cs[i])); + } + lemma_nodup_len(cs, f); + assert(sq.contains(cs)); + assert(set_node(inter, cs) == x); + assert(img.contains(x)); + } + assert(m.set_states_within(inter, f, g)); +} + +// ----- (N5) ----- + +/// Pieces of the tests of `ts`, with `⊤` and `⊥`. +pub open spec fn piece_set(inter: bool, ts: ISet) -> ISet { + ISet::new(|phi: model::Test| phi == model::Test::True || phi == model::Test::False + || exists|psi: model::Test| ts.contains(Regex::Test(psi)) && #[trigger] test_piece(inter, psi, phi)) +} + +pub open spec fn test_closure(inter: bool, ts: ISet) -> ISet { + ISet::new(|t: R| regex_nf(t) && match t { + Regex::Test(phi) => ts.contains(t) || piece_set(inter, ts).contains(phi) + || (is_conn(inter, phi) && forall|k: int| 0 <= k < test_kids(phi).len() + ==> piece_set(inter, ts).contains(#[trigger] test_kids(phi)[k])), + _ => false, + }) +} + +pub open spec fn test_pieces_of(inter: bool, psi: model::Test) -> ISet { + ISet::new(|phi: model::Test| test_piece(inter, psi, phi)) +} + +pub proof fn lemma_test_pieces_finite(inter: bool, psi: model::Test) + ensures test_pieces_of(inter, psi).finite(), +{ + broadcast use vstd::prelude::Seq::to_set_ensures, vstd::set::lemma_to_iset_finite, + vstd::iset::lemma_iset_insert_finite, vstd::iset::lemma_iset_empty_finite; + let k = test_kids(psi).to_set().to_iset(); + let one = ISet::::empty().insert(psi); + assert forall|phi: model::Test| test_pieces_of(inter, psi).contains(phi) implies k.union(one).contains(phi) by { + match psi { + model::Test::And(cs) => { if inter { assert(test_kids(psi).contains(phi)); } }, + model::Test::Or(cs) => { if !inter { assert(test_kids(psi).contains(phi)); } }, + _ => {}, + } + } + vstd::iset::lemma_iset_union_finite(k, one); + lemma_iset_subset_finite(k.union(one), test_pieces_of(inter, psi)); +} + +pub open spec fn regex_test_of(t: R) -> model::Test { + match t { Regex::Test(phi) => phi, _ => model::Test::False } +} + +pub proof fn lemma_piece_set_finite(inter: bool, ts: ISet) + requires ts.finite(), + ensures piece_set(inter, ts).finite(), +{ + broadcast use vstd::set::lemma_set_new_from_iset, vstd::iset::lemma_iset_union_finite, + vstd::iset::lemma_iset_insert_finite, vstd::iset::lemma_iset_empty_finite; + let tset = Set::new_from_iset(ts).unwrap(); + assert(tset.to_iset() == ts); + let mk = |t: R| test_pieces_of(inter, regex_test_of(t)); + assert forall|t: R| tset.contains(t) implies #[trigger] mk(t).finite() by { + lemma_test_pieces_finite(inter, regex_test_of(t)); + } + lemma_big_union_finite(tset, mk); + let big = ISet::new(|phi: model::Test| exists|t: R| tset.contains(t) && #[trigger] mk(t).contains(phi)); + let consts = ISet::::empty().insert(model::Test::True).insert(model::Test::False); + assert forall|phi: model::Test| piece_set(inter, ts).contains(phi) implies big.union(consts).contains(phi) by { + if phi != model::Test::True && phi != model::Test::False { + let psi = choose|psi: model::Test| ts.contains(Regex::Test(psi)) && #[trigger] test_piece(inter, psi, phi); + let t = Regex::Test(psi); + assert(tset.contains(t)); + assert(mk(t).contains(phi)); + } + } + lemma_iset_subset_finite(big.union(consts), piece_set(inter, ts)); +} + +pub open spec fn conn_node(inter: bool, ks: Seq) -> R { + Regex::Test(if inter { model::Test::And(ks) } else { model::Test::Or(ks) }) +} + +pub proof fn lemma_test_closure_finite(inter: bool, ts: ISet) + requires ts.finite(), + ensures test_closure(inter, ts).finite(), +{ + broadcast use vstd::set::lemma_set_new_from_iset, vstd::iset::lemma_iset_union_finite; + lemma_piece_set_finite(inter, ts); + let ps = piece_set(inter, ts); + let pset = Set::new_from_iset(ps).unwrap(); + assert(pset.to_iset() == ps); + let singles = ps.map(|phi: model::Test| Regex::Test(phi)); + ps.lemma_map_finite(|phi: model::Test| Regex::Test(phi)); + lemma_seqs_over_finite(pset, pset.len()); + let sq = seqs_over(pset, pset.len()); + let conns = sq.map(|ks: Seq| conn_node(inter, ks)); + sq.lemma_map_finite(|ks: Seq| conn_node(inter, ks)); + let all = ts.union(singles).union(conns); + assert forall|t: R| test_closure(inter, ts).contains(t) implies all.contains(t) by { + let phi = regex_test_of(t); + assert(t == Regex::Test(phi)); + if ts.contains(t) { + } else if ps.contains(phi) { + assert(singles.contains(t)); + } else { + let ks = test_kids(phi); + assert forall|i: int| 0 <= i < ks.len() implies pset.contains(#[trigger] ks[i]) by {} + assert(test_nf(phi)); + assert(ks.no_duplicates()); + lemma_nodup_len(ks, pset); + assert(sq.contains(ks)); + assert(conn_node(inter, ks) == t); + assert(conns.contains(t)); + } + } + lemma_iset_subset_finite(all, test_closure(inter, ts)); +} + +/// A piece of a member of the closure is in the piece set. +pub proof fn lemma_closure_pieces(inter: bool, ts: ISet, psi: model::Test, phi: model::Test) + requires + forall|t: R| ts.contains(t) ==> m_impl().is_test(t), + test_closure(inter, ts).contains(Regex::Test(psi)), + test_piece(inter, psi, phi), + ensures piece_set(inter, ts).contains(phi), +{ + lemma_models_agree(); + let ps = piece_set(inter, ts); + let t = Regex::Test(psi); + if ts.contains(t) { + } else if ps.contains(psi) { + // `psi` is ⊤, ⊥, or a piece of a test of `ts`; its own pieces are itself. + if psi != model::Test::True && psi != model::Test::False { + let psi0 = choose|psi0: model::Test| ts.contains(Regex::Test(psi0)) && #[trigger] test_piece(inter, psi0, psi); + assert(m_impl().is_test(Regex::Test(psi0))); + assert(regex_nf(Regex::Test(psi0))); + assert(test_nf(psi0)); + match psi0 { + model::Test::And(cs) => { + if inter { + let i = choose|i: int| 0 <= i < cs.len() && cs[i] == psi; + assert(!(cs[i] is And)); + } + }, + model::Test::Or(cs) => { + if !inter { + let i = choose|i: int| 0 <= i < cs.len() && cs[i] == psi; + assert(!(cs[i] is Or)); + } + }, + _ => {}, + } + assert(phi == psi); + } + } else { + assert(is_conn(inter, psi)); + let ks = test_kids(psi); + assert(ks.contains(phi)); + let k = choose|k: int| 0 <= k < ks.len() && ks[k] == phi; + assert(ps.contains(ks[k])); + } +} + +pub proof fn lemma_impl_tests() + ensures m_impl().tests_ok(), +{ + let m = m_impl(); + lemma_models_agree(); + assert forall|inter: bool, ts: ISet| ts.finite() && (forall|t: R| ts.contains(t) ==> m.is_test(t)) + implies #[trigger] m.has_closure(inter, ts) by { + let c = test_closure(inter, ts); + lemma_test_closure_finite(inter, ts); + let ps = piece_set(inter, ts); + assert(ts.subset_of(c)) by { + assert forall|t: R| ts.contains(t) implies c.contains(t) by { assert(m.is_test(t)); } + } + assert forall|t: R| c.contains(t) implies m.is_test(t) by {} + assert forall|us: Set, t: R| (forall|u: R| us.contains(u) ==> c.contains(u)) + && #[trigger] (m.combo)(inter, us, t) implies c.contains(t) by { + assert(r_combo(inter, us, t)); + let phi = regex_test_of(t); + assert(t == Regex::Test(phi)); + assert(test_combo(inter, us, phi)); + if phi == model::Test::True || phi == model::Test::False { + assert(ps.contains(phi)); + } else if exists|psi: model::Test| us.contains(Regex::Test(psi)) && #[trigger] test_piece(inter, psi, phi) { + let psi = choose|psi: model::Test| us.contains(Regex::Test(psi)) && #[trigger] test_piece(inter, psi, phi); + lemma_closure_pieces(inter, ts, psi, phi); + } else { + let ks = test_kids(phi); + assert forall|k: int| 0 <= k < ks.len() implies ps.contains(#[trigger] ks[k]) by { + let psi = choose|psi: model::Test| us.contains(Regex::Test(psi)) && #[trigger] test_piece(inter, psi, test_kids(phi)[k]); + lemma_closure_pieces(inter, ts, psi, ks[k]); + } + } + } + assert(m.closure_for(inter, ts, c)); + } +} + +// ----- the greatest fixpoint ----- + +pub proof fn lemma_built_mono(m1: Model, m2: Model, inter: bool, b1: spec_fn(R) -> bool, b2: spec_fn(R) -> bool, v: R) + requires + m1.nset == m2.nset, m1.empty == m2.empty, m1.epsilon == m2.epsilon, m1.universal == m2.universal, + forall|w: R| #[trigger] b1(w) ==> b2(w), + m1.built(inter, b1, v), + ensures m2.built(inter, b2, v), +{ + assert forall|u: ISet| m2.has_consts(u) && (forall|w: R| #[trigger] b2(w) ==> u.contains(w)) + && m2.nset_closed(inter, u) implies #[trigger] u.contains(v) by { + assert(m1.has_consts(u)); + assert(m1.nset_closed(inter, u)); + assert forall|w: R| #[trigger] b1(w) implies u.contains(w) by { assert(b2(w)); } + } +} + +/// Two models with the same states and constructors. +pub open spec fn core_same(m1: Model, m2: Model) -> bool { + &&& m1.state == m2.state && m1.kind == m2.kind && m1.ops == m2.ops && m1.body == m2.body + &&& m1.elems == m2.elems && m1.size == m2.size + &&& m1.empty == m2.empty && m1.epsilon == m2.epsilon && m1.universal == m2.universal + &&& m1.nset == m2.nset && m1.nnot == m2.nnot && m1.ncat == m2.ncat && m1.combo == m2.combo +} + +/// The shapes are monotone in the literal and product relations. +pub proof fn lemma_shapes_mono_m(m1: Model, m2: Model, a: R, v: R) + requires core_same(m1, m2), + forall|x: R, y: R| #[trigger] (m1.lit)(x, y) ==> (m2.lit)(x, y), + forall|x: R, y: R| #[trigger] (m1.prod)(x, y) ==> (m2.prod)(x, y), + ensures + m1.lit_shape(a, v) ==> m2.lit_shape(a, v), + m1.prod_shape(a, v) ==> m2.prod_shape(a, v), + m1.succ_shape(a, v) ==> m2.succ_shape(a, v), +{ + assert(m1.k(a) == m2.k(a) && m1.base_kind(a) == m2.base_kind(a) && m1.is_const(v) == m2.is_const(v)); + if m1.lit_shape(a, v) && !m1.base_kind(a) { + if m1.k(a) == Kind::Union || m1.k(a) == Kind::Intersect { + assert forall|w: R| #[trigger] m1.ops_lit(a, w) implies m2.ops_lit(a, w) by { + let o = choose|o: R| (m1.ops)(a).contains(o) && #[trigger] (m1.lit)(o, w); + assert((m2.lit)(o, w)); + } + if m1.k(a) == Kind::Union { + lemma_built_mono(m1, m2, false, |w: R| m1.ops_lit(a, w), |w: R| m2.ops_lit(a, w), v); + } else { + lemma_built_mono(m1, m2, true, |w: R| m1.ops_lit(a, w), |w: R| m2.ops_lit(a, w), v); + } + } else if m1.k(a) == Kind::Not { + assert forall|w: R| #[trigger] m1.not_lit(a, w) implies m2.not_lit(a, w) by { + let l = choose|l: R| #[trigger] (m1.lit)((m1.body)(a), l) && w == (m1.nnot)(l); + assert((m2.lit)((m2.body)(a), l)); + } + lemma_built_mono(m1, m2, true, |w: R| m1.not_lit(a, w), |w: R| m2.not_lit(a, w), v); + } else if m1.k(a) == Kind::Star { + assert forall|w: R| #[trigger] m1.star_lit(a, w) implies m2.star_lit(a, w) by { + let b = choose|b: R| #[trigger] (m1.prod)((m1.body)(a), b) && w == m1.cat2(b, a); + assert((m2.prod)((m2.body)(a), b)); + assert(m1.cat2(b, a) == m2.cat2(b, a)); + } + lemma_built_mono(m1, m2, false, |w: R| m1.star_lit(a, w), |w: R| m2.star_lit(a, w), v); + } else { + assert forall|w: R| #[trigger] m1.list_lit(a, w) implies m2.list_lit(a, w) by { + let es = (m1.elems)(a); + assert(es == (m2.elems)(a)); + if exists|i: int, b: R| 0 <= i < es.len() - 1 && #[trigger] (m1.prod)(es[i], b) + && w == (m1.ncat)(seq![b] + es.skip(i + 1)) { + let (i, b) = choose|i: int, b: R| 0 <= i < es.len() - 1 && #[trigger] (m1.prod)(es[i], b) + && w == (m1.ncat)(seq![b] + es.skip(i + 1)); + assert((m2.prod)(es[i], b)); + } else { + assert((m1.lit)(es.last(), w)); + assert((m2.lit)(es.last(), w)); + } + } + lemma_built_mono(m1, m2, false, |w: R| m1.list_lit(a, w), |w: R| m2.list_lit(a, w), v); + } + } + if m1.prod_shape(a, v) && !m1.base_kind(a) { + if m1.k(a) == Kind::Intersect || m1.k(a) == Kind::Not { + lemma_built_mono(m1, m2, true, |w: R| (m1.lit)(a, w), |w: R| (m2.lit)(a, w), v); + } else if m1.k(a) == Kind::Union { + if exists|o: R| (m1.ops)(a).contains(o) && #[trigger] (m1.prod)(o, v) { + let o = choose|o: R| (m1.ops)(a).contains(o) && #[trigger] (m1.prod)(o, v); + assert((m2.prod)(o, v)); + } else { + assert((m1.lit)(a, v)); + } + } else if m1.k(a) == Kind::Star { + assert((m1.lit)(a, v)); + } else { + if (m1.lit)(a, v) { + } else { + assert((m1.prod)((m1.elems)(a).last(), v)); + assert((m2.prod)((m2.elems)(a).last(), v)); + } + } + } + if m1.succ_shape(a, v) && !m1.base_kind(a) { + lemma_built_mono(m1, m2, false, |w: R| (m1.prod)(a, w), |w: R| (m2.prod)(a, w), v); + } +} + +pub proof fn lemma_shapes_mono(l1: spec_fn(R, R) -> bool, p1: spec_fn(R, R) -> bool, + l2: spec_fn(R, R) -> bool, p2: spec_fn(R, R) -> bool, a: R, v: R) + requires forall|x: R, y: R| #[trigger] l1(x, y) ==> l2(x, y), forall|x: R, y: R| #[trigger] p1(x, y) ==> p2(x, y), + ensures + with_rel(l1, p1).lit_shape(a, v) ==> with_rel(l2, p2).lit_shape(a, v), + with_rel(l1, p1).prod_shape(a, v) ==> with_rel(l2, p2).prod_shape(a, v), +{ + lemma_shapes_mono_m(with_rel(l1, p1), with_rel(l2, p2), a, v); +} + +/// `m_impl` and `m_gfp` have the same shapes. +pub proof fn lemma_impl_gfp_shapes(a: R, v: R) + ensures + m_impl().lit_shape(a, v) == m_gfp().lit_shape(a, v), + m_impl().prod_shape(a, v) == m_gfp().prod_shape(a, v), + m_impl().succ_shape(a, v) == m_gfp().succ_shape(a, v), +{ + lemma_models_agree(); + lemma_shapes_mono_m(m_impl(), m_gfp(), a, v); + lemma_shapes_mono_m(m_gfp(), m_impl(), a, v); +} + +/// `nset_shape` reads only states, kinds, operands, constants, and test combinations. +pub proof fn lemma_nset_shape_agree(m1: Model, m2: Model, inter: bool, xs: Set, u: R) + requires m1.state == m2.state, m1.kind == m2.kind, m1.ops == m2.ops, m1.combo == m2.combo, + m1.empty == m2.empty, m1.epsilon == m2.epsilon, m1.universal == m2.universal, + ensures m1.nset_shape(inter, xs, u) == m2.nset_shape(inter, xs, u), +{ + assert forall|x: R| m1.sops(inter, x) == m2.sops(inter, x) by {} + assert forall|o: R| m1.in_sops_of(inter, xs, o) == m2.in_sops_of(inter, xs, o) by { + if m1.in_sops_of(inter, xs, o) { + let x = choose|x: R| xs.contains(x) && #[trigger] m1.sops(inter, x).contains(o); + assert(m2.sops(inter, x).contains(o)); + } + if m2.in_sops_of(inter, xs, o) { + let x = choose|x: R| xs.contains(x) && #[trigger] m2.sops(inter, x).contains(o); + assert(m1.sops(inter, x).contains(o)); + } + } + assert forall|ts: Set, o: R| #[trigger] m1.combo_from(inter, xs, ts, o) == m2.combo_from(inter, xs, ts, o) by { + if m1.combo_from(inter, xs, ts, o) { lemma_combo_from_transfer(m1, m2, inter, xs, ts, o); } + if m2.combo_from(inter, xs, ts, o) { lemma_combo_from_transfer(m2, m1, inter, xs, ts, o); } + } + assert(m1.is_const(u) == m2.is_const(u)); + assert forall|o: R| (m1.is_test(o) && exists|ts: Set| #[trigger] m1.combo_from(inter, xs, ts, o)) + == (m2.is_test(o) && exists|ts: Set| #[trigger] m2.combo_from(inter, xs, ts, o)) by { + if exists|ts: Set| #[trigger] m1.combo_from(inter, xs, ts, o) { + let ts = choose|ts: Set| #[trigger] m1.combo_from(inter, xs, ts, o); + assert(m2.combo_from(inter, xs, ts, o)); + } + if exists|ts: Set| #[trigger] m2.combo_from(inter, xs, ts, o) { + let ts = choose|ts: Set| #[trigger] m2.combo_from(inter, xs, ts, o); + assert(m1.combo_from(inter, xs, ts, o)); + } + } +} + +pub proof fn lemma_combo_from_transfer(m1: Model, m2: Model, inter: bool, xs: Set, ts: Set, o: R) + requires m1.state == m2.state, m1.kind == m2.kind, m1.ops == m2.ops, m1.combo == m2.combo, + m1.combo_from(inter, xs, ts, o), + ensures m2.combo_from(inter, xs, ts, o), +{ + assert forall|t: R| ts.contains(t) implies #[trigger] m1.is_test(t) by { + assert(m1.combo_from(inter, xs, ts, o)); + } + assert forall|t: R| ts.contains(t) implies m2.is_test(t) && m2.in_sops_of(inter, xs, t) by { + assert(m1.is_test(t)); + assert(m1.in_sops_of(inter, xs, t)); + let x = choose|x: R| xs.contains(x) && #[trigger] m1.sops(inter, x).contains(t); + assert(m2.sops(inter, x) == m1.sops(inter, x)); + } +} + +pub proof fn lemma_gfp_consistent() + ensures consistent(|a: R, v: R| g_lit(a, v), |a: R, v: R| g_prod(a, v)), +{ + let gl = |a: R, v: R| g_lit(a, v); + let gp = |a: R, v: R| g_prod(a, v); + assert forall|a: R, v: R| regex_nf(a) && #[trigger] gl(a, v) implies regex_nf(v) && with_rel(gl, gp).lit_shape(a, v) by { + let (l, p) = choose|l: spec_fn(R, R) -> bool, p: spec_fn(R, R) -> bool| #[trigger] consistent(l, p) && l(a, v); + lemma_rel_in_gfp(l, p); + lemma_shapes_mono(l, p, gl, gp, a, v); + } + assert forall|a: R, v: R| regex_nf(a) && #[trigger] gp(a, v) implies regex_nf(v) && with_rel(gl, gp).prod_shape(a, v) by { + let (l, p) = choose|l: spec_fn(R, R) -> bool, p: spec_fn(R, R) -> bool| #[trigger] consistent(l, p) && p(a, v); + lemma_rel_in_gfp(l, p); + lemma_shapes_mono(l, p, gl, gp, a, v); + } +} + +pub proof fn lemma_rel_in_gfp(l: spec_fn(R, R) -> bool, p: spec_fn(R, R) -> bool) + requires consistent(l, p), + ensures + forall|x: R, y: R| #[trigger] l(x, y) ==> g_lit(x, y), + forall|x: R, y: R| #[trigger] p(x, y) ==> g_prod(x, y), +{} + +/// Folding: a literal allowed by (S1)–(S6) with respect to `lit`/`prod` is a literal. +pub proof fn lemma_lit_fold(a: R, v: R) + requires regex_nf(a), regex_nf(v), m_impl().lit_shape(a, v), + ensures (m_impl().lit)(a, v), +{ + lemma_models_agree(); + let gl = |x: R, y: R| g_lit(x, y); + let gp = |x: R, y: R| g_prod(x, y); + let l2 = |x: R, y: R| g_lit(x, y) || (x == a && y == v); + lemma_impl_gfp_shapes(a, v); + lemma_gfp_consistent(); + assert forall|x: R, y: R| #[trigger] gl(x, y) implies l2(x, y) by {} + assert forall|x: R, y: R| #[trigger] gp(x, y) implies gp(x, y) by {} + assert(consistent(l2, gp)) by { + assert forall|x: R, y: R| regex_nf(x) && #[trigger] l2(x, y) implies regex_nf(y) && with_rel(l2, gp).lit_shape(x, y) by { + if g_lit(x, y) { + assert(gl(x, y)); + } + lemma_shapes_mono(gl, gp, l2, gp, x, y); + } + assert forall|x: R, y: R| regex_nf(x) && #[trigger] gp(x, y) implies regex_nf(y) && with_rel(l2, gp).prod_shape(x, y) by { + lemma_shapes_mono(gl, gp, l2, gp, x, y); + } + } + assert(l2(a, v)); +} + +/// Folding for products. +pub proof fn lemma_prod_fold(a: R, v: R) + requires regex_nf(a), regex_nf(v), m_impl().prod_shape(a, v), + ensures (m_impl().prod)(a, v), +{ + lemma_models_agree(); + let gl = |x: R, y: R| g_lit(x, y); + let gp = |x: R, y: R| g_prod(x, y); + let p2 = |x: R, y: R| g_prod(x, y) || (x == a && y == v); + lemma_impl_gfp_shapes(a, v); + lemma_gfp_consistent(); + assert forall|x: R, y: R| #[trigger] gl(x, y) implies gl(x, y) by {} + assert forall|x: R, y: R| #[trigger] gp(x, y) implies p2(x, y) by {} + assert(consistent(gl, p2)) by { + assert forall|x: R, y: R| regex_nf(x) && #[trigger] gl(x, y) implies regex_nf(y) && with_rel(gl, p2).lit_shape(x, y) by { + lemma_shapes_mono(gl, gp, gl, p2, x, y); + } + assert forall|x: R, y: R| regex_nf(x) && #[trigger] p2(x, y) implies regex_nf(y) && with_rel(gl, p2).prod_shape(x, y) by { + if g_prod(x, y) { + assert(gp(x, y)); + } + lemma_shapes_mono(gl, gp, gl, p2, x, y); + } + } + assert(p2(a, v)); +} + +pub proof fn lemma_impl_succ() + ensures m_impl().succ_ok(), +{ + let m = m_impl(); + lemma_models_agree(); + lemma_gfp_consistent(); + let gl = |x: R, y: R| g_lit(x, y); + let gp = |x: R, y: R| g_prod(x, y); + assert forall|p: R, v: R| m.st(p) && #[trigger] (m.succ)(p, v) implies m.st(v) && m.succ_shape(p, v) by { + lemma_impl_gfp_shapes(p, v); + } + assert forall|p: R, v: R| m.st(p) && #[trigger] (m.lit)(p, v) implies m.st(v) && m.lit_shape(p, v) by { + assert(gl(p, v)); + assert(with_rel(gl, gp).lit_shape(p, v)); + lemma_impl_gfp_shapes(p, v); + } + assert forall|p: R, v: R| m.st(p) && #[trigger] (m.prod)(p, v) implies m.st(v) && m.prod_shape(p, v) by { + assert(gp(p, v)); + assert(with_rel(gl, gp).prod_shape(p, v)); + lemma_impl_gfp_shapes(p, v); + } +} + +/// The implementation's model satisfies the contract (N0)–(N5), (S0)–(S6). +pub proof fn theorem_impl_contract() + ensures m_impl().contract(), +{ + lemma_models_agree(); + assert(m_impl().constants_ok()); + lemma_impl_substates(); + lemma_impl_fixpoints(); + lemma_impl_nset(); + lemma_impl_not(); + lemma_impl_cat(); + lemma_impl_tests(); + lemma_impl_succ(); +} + +} // verus! diff --git a/src/history-semantics/src/verify/finite_interp.rs b/src/history-semantics/src/verify/finite_interp.rs new file mode 100644 index 000000000..25ed5e9d9 --- /dev/null +++ b/src/history-semantics/src/verify/finite_interp.rs @@ -0,0 +1,913 @@ +//! Values of the implemented interpretation (`symbolic.rs` `TransitionId::interpret`): for a +//! normal-form transition `t` (`finite_trans::nf_sum`), the regex returned by `interpret` lifts to +//! a value of `t` (`finite_trans::tval`), i.e. a value under some selection of the branches of +//! its conditionals. +//! +//! The proof mirrors `symbolic::verify::interp_action`/`interp_run` with abstract stacks of value +//! sets ([`iapply`], [`irun`]; a stack entry is a `finite_machine::AV` whose `x` component is the +//! set): an unfinished task pushes the values of its transition ([`vav`]), a finished set node +//! applies the model's set constructor to members of its operands ([`set_av`]), `Not` applies +//! `r_not` ([`not_av`]) and `Append` applies `ccat` ([`cat_av`]). The concrete stack is the +//! stack of singletons of the lifted values ([`lits`]). Every concrete step stays below +//! (`finite_machine::aref`) the abstract run of the configuration it came from ([`istep`]), so +//! the loop keeps the abstract run below the values of the root ([`iinv`]). +use crate::normalize::verify as norm; +use crate::symbolic::verify::{ + child_interp_tasks, interp_append_ids, interp_tasks_wf, transition_children, transition_suffix, +}; +use crate::verify::finite_collect::*; +use crate::verify::finite_impl::*; +use crate::verify::finite_link::*; +use crate::verify::finite_machine::*; +use crate::verify::finite_steps::*; +use crate::verify::finite_trans::*; +use junco_core::kernel::verify as model; +use junco_core::kernel::{RegexId, TransitionId}; +use vstd::prelude::*; + +verus! { + +broadcast use junco_core::kernel::verify::group_kernel_views; + +pub type Task = (TransitionId, bool); + +/// The values of transition `t`. +pub open spec fn vav(g: model::Graph, t: nat) -> AV { + AV { x: |v: R| tval(g, t, v), y: top_cls() } +} + +/// The single value `v`. +pub open spec fn lit_av(v: R) -> AV { + AV { x: |w: R| w == v, y: top_cls() } +} + +pub open spec fn vavs(g: model::Graph, cs: Seq) -> Seq { + Seq::new(cs.len(), |i: int| vav(g, cs[i])) +} + +/// `vs` picks a member of every entry of `s`. +pub open spec fn members(s: Seq, vs: Seq) -> bool { + vs.len() == s.len() && forall|i: int| #![trigger vs[i]] 0 <= i < s.len() ==> (s[i].x)(vs[i]) +} + +pub open spec fn set_av(s: Seq, inter: bool) -> AV { + AV { x: |v: R| exists|vs: Seq| #[trigger] members(s, vs) && (core().nset)(inter, vs.to_set(), v), y: top_cls() } +} + +pub open spec fn not_av(a: AV) -> AV { + AV { x: |v: R| exists|x: R| (a.x)(x) && v == #[trigger] r_not(x), y: top_cls() } +} + +pub open spec fn cat_av(g: model::Graph, a: AV, rs: Seq) -> AV { + AV { x: |v: R| exists|w: R| (a.x)(w) && v == #[trigger] ccat(g, w, rs), y: top_cls() } +} + +/// Abstract `interp_action`. +pub open spec fn iapply(g: model::Graph, task: Task, s: Seq) -> Option> { + if !task.1 { Some(s.push(vav(g, task.0@))) } else { + match g.transitions[task.0@ as int] { + model::TransitionNode::Union(cs) => if cs.len() > s.len() { None } + else { Some(s.take(s.len() - cs.len()).push(set_av(s.skip(s.len() - cs.len()), false))) }, + model::TransitionNode::Intersect(cs) => if cs.len() > s.len() { None } + else { Some(s.take(s.len() - cs.len()).push(set_av(s.skip(s.len() - cs.len()), true))) }, + model::TransitionNode::Not(_) => if s.len() == 0 { None } else { Some(s.drop_last().push(not_av(s.last()))) }, + model::TransitionNode::Append(_, rs) => if s.len() == 0 { None } + else { Some(s.drop_last().push(cat_av(g, s.last(), rs))) }, + _ => Some(s.push(vav(g, task.0@))), + } + } +} + +/// Abstract `interp_run`. +pub open spec fn irun(g: model::Graph, tasks: Seq, s: Seq) -> Option> + decreases tasks.len(), +{ + if tasks.len() == 0 { Some(s) } else { + match iapply(g, tasks.last(), s) { + Some(n) => irun(g, tasks.drop_last(), n), + None => None, + } + } +} + +/// The concrete stack: singletons of the lifted values. +pub open spec fn lits(g: model::Graph, values: Seq) -> Seq { + Seq::new(values.len(), |i: int| lit_av(model::lift_regex(g, values[i]@))) +} + +pub open spec fn itasks(g: model::Graph, tasks: Seq) -> bool { + forall|i: int| #![trigger tasks[i]] 0 <= i < tasks.len() ==> nf_sum(g, tasks[i].0@) +} + +pub open spec fn ivalues(g: model::Graph, values: Seq) -> bool { + forall|i: int| #![trigger values[i]] 0 <= i < values.len() + ==> values[i]@ < g.regexes.len() && regex_nf(model::lift_regex(g, values[i]@)) +} + +/// A typed configuration: normal-form tasks and values. +#[verifier::opaque] +pub open spec fn ipre(g: model::Graph, tasks: Seq, values: Seq) -> bool { + itasks(g, tasks) && ivalues(g, values) +} + +/// One step from `(tasks0, values0)` to the typed `(tasks1, values1)`, below its abstract run. +#[verifier::opaque] +pub open spec fn istep(g: model::Graph, tasks0: Seq, tasks1: Seq, values0: Seq, values1: Seq) -> bool { + &&& itasks(g, tasks1) && ivalues(g, values1) + &&& aref(irun(g, tasks0, lits(g, values0)), irun(g, tasks1, lits(g, values1))) +} + +/// The loop invariant of `interpret`: the abstract run is below the values of the root `this`. +#[verifier::opaque] +pub open spec fn iinv(g: model::Graph, this: nat, tasks: Seq, values: Seq) -> bool { + &&& itasks(g, tasks) && ivalues(g, values) + &&& aref(Some(seq![vav(g, this)]), irun(g, tasks, lits(g, values))) +} + +// ===== the abstract machine ===== + +pub proof fn lemma_irun_push(g: model::Graph, tasks: Seq, task: Task, s: Seq) + ensures irun(g, tasks.push(task), s) == match iapply(g, task, s) { + Some(n) => irun(g, tasks, n), + None => None, + }, +{ + assert(tasks.push(task).drop_last() =~= tasks); + assert(tasks.push(task).last() == task); +} + +pub proof fn lemma_irun_prefix(g: model::Graph, prefix: Seq, suffix: Seq, s: Seq) + ensures irun(g, prefix + suffix, s) == match irun(g, suffix, s) { + Some(next) => irun(g, prefix, next), + None => None, + }, + decreases suffix.len(), +{ + if suffix.len() > 0 { + assert((prefix + suffix).last() == suffix.last()); + assert((prefix + suffix).drop_last() =~= prefix + suffix.drop_last()); + match iapply(g, suffix.last(), s) { + Some(next) => lemma_irun_prefix(g, prefix, suffix.drop_last(), next), + None => {}, + } + } else { + assert(prefix + suffix =~= prefix); + } +} + +pub proof fn lemma_set_mono(s1: Seq, s2: Seq, inter: bool) + requires stack_le(s1, s2), + ensures av_le(set_av(s1, inter), set_av(s2, inter)), +{ + assert forall|v: R| #[trigger] (set_av(s1, inter).x)(v) implies (set_av(s2, inter).x)(v) by { + let vs = choose|vs: Seq| #[trigger] members(s1, vs) && (core().nset)(inter, vs.to_set(), v); + assert forall|i: int| #![trigger vs[i]] 0 <= i < s2.len() implies (s2[i].x)(vs[i]) by { + assert(av_le(s1[i], s2[i])); + } + assert(members(s2, vs)); + } +} + +pub proof fn lemma_not_mono(a: AV, b: AV) + requires av_le(a, b), + ensures av_le(not_av(a), not_av(b)), +{ + assert forall|v: R| #[trigger] (not_av(a).x)(v) implies (not_av(b).x)(v) by { + let x = choose|x: R| (a.x)(x) && v == #[trigger] r_not(x); + assert((b.x)(x)); + } +} + +pub proof fn lemma_cat_mono(g: model::Graph, a: AV, b: AV, rs: Seq) + requires av_le(a, b), + ensures av_le(cat_av(g, a, rs), cat_av(g, b, rs)), +{ + assert forall|v: R| #[trigger] (cat_av(g, a, rs).x)(v) implies (cat_av(g, b, rs).x)(v) by { + let w = choose|w: R| (a.x)(w) && v == #[trigger] ccat(g, w, rs); + assert((b.x)(w)); + } +} + +pub proof fn lemma_set_step_mono(s1: Seq, s2: Seq, k: nat, inter: bool) + requires stack_le(s1, s2), k <= s2.len(), + ensures stack_le(s1.take(s1.len() - k).push(set_av(s1.skip(s1.len() - k), inter)), + s2.take(s2.len() - k).push(set_av(s2.skip(s2.len() - k), inter))), +{ + let start = s2.len() - k; + lemma_stack_le_sub(s1, s2, 0, start); + lemma_stack_le_sub(s1, s2, start, s2.len() as int); + assert(s1.take(start) == s1.subrange(0, start)); + assert(s2.take(start) == s2.subrange(0, start)); + assert(s1.skip(start) == s1.subrange(start, s1.len() as int)); + assert(s2.skip(start) == s2.subrange(start, s2.len() as int)); + lemma_set_mono(s1.skip(start), s2.skip(start), inter); + lemma_stack_le_push(s1.take(start), s2.take(start), set_av(s1.skip(start), inter), set_av(s2.skip(start), inter)); +} + +pub proof fn lemma_iapply_mono(g: model::Graph, task: Task, s1: Seq, s2: Seq) + requires stack_le(s1, s2), + ensures aref(iapply(g, task, s2), iapply(g, task, s1)), +{ + let t = task.0@; + lemma_av_le_refl(vav(g, t)); + if !task.1 { + lemma_stack_le_push(s1, s2, vav(g, t), vav(g, t)); + } else { + match g.transitions[t as int] { + model::TransitionNode::Union(cs) => { if cs.len() <= s2.len() { lemma_set_step_mono(s1, s2, cs.len(), false); } }, + model::TransitionNode::Intersect(cs) => { if cs.len() <= s2.len() { lemma_set_step_mono(s1, s2, cs.len(), true); } }, + model::TransitionNode::Not(_) => { + if s2.len() > 0 { + let n = s1.len() as int; + assert(av_le(s1[n - 1], s2[n - 1])); + lemma_not_mono(s1.last(), s2.last()); + lemma_stack_le_sub(s1, s2, 0, n - 1); + assert(s1.drop_last() == s1.subrange(0, n - 1)); + assert(s2.drop_last() == s2.subrange(0, n - 1)); + lemma_stack_le_push(s1.drop_last(), s2.drop_last(), not_av(s1.last()), not_av(s2.last())); + } + }, + model::TransitionNode::Append(_, rs) => { + if s2.len() > 0 { + let n = s1.len() as int; + assert(av_le(s1[n - 1], s2[n - 1])); + lemma_cat_mono(g, s1.last(), s2.last(), rs); + lemma_stack_le_sub(s1, s2, 0, n - 1); + assert(s1.drop_last() == s1.subrange(0, n - 1)); + assert(s2.drop_last() == s2.subrange(0, n - 1)); + lemma_stack_le_push(s1.drop_last(), s2.drop_last(), cat_av(g, s1.last(), rs), cat_av(g, s2.last(), rs)); + } + }, + _ => { lemma_stack_le_push(s1, s2, vav(g, t), vav(g, t)); }, + } + } +} + +pub proof fn lemma_irun_mono(g: model::Graph, tasks: Seq, s1: Seq, s2: Seq) + requires stack_le(s1, s2), + ensures aref(irun(g, tasks, s2), irun(g, tasks, s1)), + decreases tasks.len(), +{ + if tasks.len() > 0 { + lemma_iapply_mono(g, tasks.last(), s1, s2); + match iapply(g, tasks.last(), s2) { + Some(n2) => { + let n1 = iapply(g, tasks.last(), s1).unwrap(); + lemma_irun_mono(g, tasks.drop_last(), n1, n2); + }, + None => {}, + } + } +} + +/// Frame rule: replacing a task by an expansion whose abstract run is below the task's abstract +/// action keeps the whole run below. +pub proof fn lemma_iframe(g: model::Graph, prefix: Seq, expansion: Seq, task: Task, before: Seq, after: Seq) + requires aref(iapply(g, task, before), irun(g, expansion, after)), + ensures aref(irun(g, prefix.push(task), before), irun(g, prefix + expansion, after)), +{ + lemma_irun_push(g, prefix, task, before); + lemma_irun_prefix(g, prefix, expansion, after); + match iapply(g, task, before) { + Some(n) => { + let m = irun(g, expansion, after).unwrap(); + lemma_irun_mono(g, prefix, m, n); + }, + None => {}, + } +} + +/// The unfinished children tasks of a set node push the values of the children in order. +pub proof fn lemma_child_irun(g: model::Graph, id: TransitionId, remaining: nat, s: Seq) + requires model::graph_wf(g), id@ < g.transitions.len(), remaining <= transition_children(g, id).len(), + ensures irun(g, child_interp_tasks(g, id, remaining), s) == Some(s + vavs(g, transition_children(g, id)).skip(remaining as int)), + decreases transition_children(g, id).len() - remaining, +{ + model::lemma_graph_transition_wf(g, id@); + let tasks = child_interp_tasks(g, id, remaining); + let vals = vavs(g, transition_children(g, id)); + if remaining < transition_children(g, id).len() { + let child = TransitionId::from_view(transition_children(g, id)[remaining as int] as u32); + assert(child@ == transition_children(g, id)[remaining as int]); + assert(tasks.last() == (child, false)); + assert(tasks.drop_last() =~= child_interp_tasks(g, id, remaining + 1)); + assert(vav(g, child@) == vals[remaining as int]); + lemma_child_irun(g, id, remaining + 1, s.push(vals[remaining as int])); + assert(s.push(vals[remaining as int]) + vals.skip(remaining as int + 1) =~= s + vals.skip(remaining as int)); + } else { + assert(tasks =~= Seq::::empty()); + assert(s + vals.skip(remaining as int) =~= s); + } +} + +// ===== stability ===== + +pub proof fn lemma_vav_stable(a: model::Graph, b: model::Graph, t: nat) + requires model::graph_wf(a), model::graph_extends(a, b), t < a.transitions.len(), + ensures vav(a, t) == vav(b, t), +{ + lemma_trans_stable(a, b, t); + assert(vav(a, t).x =~= vav(b, t).x); +} + +pub proof fn lemma_node_stable(a: model::Graph, b: model::Graph, t: nat) + requires model::graph_extends(a, b), t < a.transitions.len(), + ensures t < b.transitions.len(), a.transitions[t as int] == b.transitions[t as int], +{ + assert(a.transitions == b.transitions.subrange(0, a.transitions.len() as int)); +} + +#[verifier::spinoff_prover] +pub proof fn lemma_cat_av_stable(a: model::Graph, b: model::Graph, x: AV, rs: Seq) + requires model::graph_wf(a), model::graph_extends(a, b), model::bounded(rs, a.regexes.len()), + ensures cat_av(a, x, rs) == cat_av(b, x, rs), +{ + hide(r_cat); + model::lemma_graph_wf_elim(a); + assert(model::lift_regexes(a, rs) =~= model::lift_regexes(b, rs)) by { + assert forall|i: int| 0 <= i < rs.len() implies model::lift_regexes(a, rs)[i] == model::lift_regexes(b, rs)[i] by { + model::lemma_lift_regex_stable(a, b, rs[i]); + } + } + let la = model::lift_regexes(a, rs); + assert forall|w: R| #[trigger] ccat(a, w, rs) == ccat(b, w, rs) by { + assert(ccat(a, w, rs) == r_cat(seq![w] + la)); + assert(ccat(b, w, rs) == r_cat(seq![w] + la)); + } + assert forall|v: R| #[trigger] (cat_av(a, x, rs).x)(v) == (cat_av(b, x, rs).x)(v) by { + if (cat_av(a, x, rs).x)(v) { + let w = choose|w: R| (x.x)(w) && v == #[trigger] ccat(a, w, rs); + assert(v == ccat(b, w, rs)); + } + if (cat_av(b, x, rs).x)(v) { + let w = choose|w: R| (x.x)(w) && v == #[trigger] ccat(b, w, rs); + assert(v == ccat(a, w, rs)); + } + } + assert(cat_av(a, x, rs).x =~= cat_av(b, x, rs).x); +} + +#[verifier::spinoff_prover] +pub proof fn lemma_iapply_stable(a: model::Graph, b: model::Graph, task: Task, s: Seq) + requires model::graph_wf(a), model::graph_extends(a, b), task.0@ < a.transitions.len(), + ensures iapply(a, task, s) == iapply(b, task, s), +{ + let t = task.0@; + lemma_node_stable(a, b, t); + lemma_vav_stable(a, b, t); + if let model::TransitionNode::Append(_, rs) = a.transitions[t as int] { + model::lemma_graph_transition_wf(a, t); + if s.len() > 0 { lemma_cat_av_stable(a, b, s.last(), rs); } + } +} + +pub proof fn lemma_irun_stable(a: model::Graph, b: model::Graph, tasks: Seq, s: Seq) + requires model::graph_wf(a), model::graph_extends(a, b), interp_tasks_wf(a, tasks), + ensures irun(a, tasks, s) == irun(b, tasks, s), + decreases tasks.len(), +{ + if tasks.len() > 0 { + assert(tasks.last() == tasks[tasks.len() - 1]); + lemma_iapply_stable(a, b, tasks.last(), s); + assert(interp_tasks_wf(a, tasks.drop_last())) by { + assert forall|i: int| 0 <= i < tasks.drop_last().len() implies tasks.drop_last()[i].0@ < a.transitions.len() by { + assert(tasks.drop_last()[i] == tasks[i]); + } + } + match iapply(a, tasks.last(), s) { + Some(n) => lemma_irun_stable(a, b, tasks.drop_last(), n), + None => {}, + } + } +} + +pub proof fn lemma_lits_stable(a: model::Graph, b: model::Graph, values: Seq) + requires model::graph_wf(a), model::graph_extends(a, b), norm::regex_ids_valid(a, values), + ensures lits(a, values) == lits(b, values), +{ + model::lemma_graph_wf_elim(a); + assert forall|i: int| 0 <= i < values.len() implies #[trigger] lits(a, values)[i] == lits(b, values)[i] by { + model::lemma_lift_regex_stable(a, b, values[i]@); + } + assert(lits(a, values) =~= lits(b, values)); +} + +pub proof fn lemma_itasks_valid(g: model::Graph, tasks: Seq) + requires itasks(g, tasks), + ensures interp_tasks_wf(g, tasks), +{ + assert forall|i: int| 0 <= i < tasks.len() implies tasks[i].0@ < g.transitions.len() by { + assert(nf_sum(g, tasks[i].0@)); + } +} + +/// A typed configuration stays typed under graph extension, with the same abstract run. +pub proof fn lemma_ipre_stable(a: model::Graph, b: model::Graph, tasks: Seq, values: Seq) + requires model::graph_wf(a), model::graph_extends(a, b), itasks(a, tasks), ivalues(a, values), + ensures itasks(b, tasks), ivalues(b, values), interp_tasks_wf(a, tasks), norm::regex_ids_valid(a, values), + lits(a, values) == lits(b, values), + forall|s: Seq| #[trigger] irun(a, tasks, s) == irun(b, tasks, s), +{ + model::lemma_graph_wf_elim(a); + lemma_itasks_valid(a, tasks); + assert forall|i: int| #![trigger tasks[i]] 0 <= i < tasks.len() implies nf_sum(b, tasks[i].0@) by { + lemma_trans_stable(a, b, tasks[i].0@); + } + assert forall|i: int| #![trigger values[i]] 0 <= i < values.len() + implies values[i]@ < b.regexes.len() && regex_nf(model::lift_regex(b, values[i]@)) by { + model::lemma_lift_regex_stable(a, b, values[i]@); + } + assert(norm::regex_ids_valid(a, values)) by { + assert forall|i: int| 0 <= i < values.len() implies values[i]@ < a.regexes.len() by { assert(values[i]@ < a.regexes.len()); } + } + lemma_lits_stable(a, b, values); + assert forall|s: Seq| #[trigger] irun(a, tasks, s) == irun(b, tasks, s) by { + lemma_irun_stable(a, b, tasks, s); + } +} + +// ===== stack helpers ===== + +pub proof fn lemma_lits_push(g: model::Graph, values: Seq, r: RegexId) + ensures lits(g, values.push(r)) == lits(g, values).push(lit_av(model::lift_regex(g, r@))), +{ + assert(lits(g, values.push(r)) =~= lits(g, values).push(lit_av(model::lift_regex(g, r@)))); +} + +pub proof fn lemma_lits_split(g: model::Graph, values: Seq, start: int) + requires 0 <= start <= values.len(), + ensures lits(g, values.take(start)) == lits(g, values).take(start), + lits(g, values.skip(start)) == lits(g, values).skip(start), + start == values.len() - 1 ==> values.take(start) == values.drop_last(), +{ + assert(lits(g, values.take(start)) =~= lits(g, values).take(start)); + assert(lits(g, values.skip(start)) =~= lits(g, values).skip(start)); + if start == values.len() - 1 { assert(values.take(start) =~= values.drop_last()); } +} + +pub proof fn lemma_lit_le(v: R, a: AV) + requires (a.x)(v), a.y == top_cls(), + ensures av_le(lit_av(v), a), +{} + +pub proof fn lemma_itasks_sub(g: model::Graph, pending: Seq, task: Task) + requires itasks(g, pending.push(task)), + ensures itasks(g, pending), nf_sum(g, task.0@), +{ + assert forall|i: int| #![trigger pending[i]] 0 <= i < pending.len() implies nf_sum(g, pending[i].0@) by { + assert(pending.push(task)[i] == pending[i]); + } + assert(pending.push(task)[pending.len() as int] == task); +} + +pub proof fn lemma_itasks_push(g: model::Graph, pending: Seq, task: Task) + requires itasks(g, pending), nf_sum(g, task.0@), + ensures itasks(g, pending.push(task)), +{ + assert forall|i: int| #![trigger pending.push(task)[i]] 0 <= i < pending.push(task).len() implies nf_sum(g, pending.push(task)[i].0@) by { + if i < pending.len() { assert(pending.push(task)[i] == pending[i]); } + } +} + +pub proof fn lemma_ivalues_replace(g: model::Graph, values: Seq, start: int, r: RegexId) + requires ivalues(g, values), 0 <= start <= values.len(), r@ < g.regexes.len(), regex_nf(model::lift_regex(g, r@)), + ensures ivalues(g, values.take(start).push(r)), +{ + let n = values.take(start).push(r); + assert forall|i: int| #![trigger n[i]] 0 <= i < n.len() implies n[i]@ < g.regexes.len() && regex_nf(model::lift_regex(g, n[i]@)) by { + if i < start { assert(n[i] == values[i]); } + } +} + +/// Shared tail of the step lemmas: the frame rule with the typing of the new configuration. +pub proof fn lemma_istep_close(g: model::Graph, pending: Seq, task: Task, prior: Seq, + expansion: Seq, values: Seq) + requires aref(iapply(g, task, lits(g, prior)), irun(g, expansion, lits(g, values))), + itasks(g, pending + expansion), ivalues(g, values), + ensures istep(g, pending.push(task), pending + expansion, prior, values), +{ + reveal(istep); + lemma_iframe(g, pending, expansion, task, lits(g, prior), lits(g, values)); +} + +// ===== the steps of `interpret_step` and `interpret_branch` ===== + +/// `Const(r)`: push `r`. +pub proof fn lemma_istep_const(b: model::Graph, a: model::Graph, this: TransitionId, finish: bool, + pending: Seq, prior: Seq, r: RegexId) + requires model::graph_wf(b), model::graph_wf(a), model::graph_extends(b, a), this@ < b.transitions.len(), + b.transitions[this@ as int] == model::TransitionNode::Const(r@), + ipre(b, pending.push((this, finish)), prior), + ensures istep(a, pending.push((this, finish)), pending, prior, prior.push(r)), +{ + reveal(ipre); + let t = this@; + lemma_ipre_stable(b, a, pending.push((this, finish)), prior); + lemma_itasks_sub(a, pending, (this, finish)); + lemma_node_stable(b, a, t); + lemma_nf_children(a, t); + let l = lits(a, prior); + let x = model::lift_regex(a, r@); + lemma_tval(a, t, x); + lemma_lit_le(x, vav(a, t)); + lemma_stack_le_refl(l); + lemma_stack_le_push(l, l, lit_av(x), vav(a, t)); + lemma_lits_push(a, prior, r); + assert(irun(a, Seq::::empty(), lits(a, prior.push(r))) == Some(lits(a, prior.push(r)))); + assert(pending + Seq::::empty() =~= pending); + lemma_ivalues_replace(a, prior, prior.len() as int, r); + assert(prior.take(prior.len() as int) =~= prior); + lemma_istep_close(a, pending, (this, finish), prior, Seq::empty(), prior.push(r)); +} + +/// `If(test, x, y)`: schedule the chosen branch. +pub proof fn lemma_istep_if(b: model::Graph, a: model::Graph, this: TransitionId, finish: bool, + pending: Seq, prior: Seq, test: nat, x: TransitionId, y: TransitionId, chosen: TransitionId) + requires model::graph_wf(b), model::graph_wf(a), model::graph_extends(b, a), this@ < b.transitions.len(), + b.transitions[this@ as int] == model::TransitionNode::If(test, x@, y@), chosen == x || chosen == y, + ipre(b, pending.push((this, finish)), prior), + ensures istep(a, pending.push((this, finish)), pending.push((chosen, false)), prior, prior), +{ + reveal(ipre); + let t = this@; + lemma_ipre_stable(b, a, pending.push((this, finish)), prior); + lemma_itasks_sub(a, pending, (this, finish)); + lemma_node_stable(b, a, t); + model::lemma_graph_transition_wf(b, t); + lemma_nf_children(a, t); + let l = lits(a, prior); + assert(av_le(vav(a, chosen@), vav(a, t))) by { + assert forall|v: R| #[trigger] (vav(a, chosen@).x)(v) implies (vav(a, t).x)(v) by { + assert((tv(a))(chosen@, v) == tval(a, chosen@, v)); + lemma_tval(a, t, v); + } + } + lemma_stack_le_refl(l); + lemma_stack_le_push(l, l, vav(a, chosen@), vav(a, t)); + let e = seq![(chosen, false)]; + lemma_irun_push(a, Seq::::empty(), (chosen, false), l); + assert(Seq::::empty().push((chosen, false)) == e); + assert(pending + e =~= pending.push((chosen, false))); + lemma_itasks_push(a, pending, (chosen, false)); + lemma_istep_close(a, pending, (this, finish), prior, e, prior); +} + +/// Unfinished `Not(k)` / `Append(k, rs)`: finish task, then `k`. +pub proof fn lemma_istep_unary(b: model::Graph, a: model::Graph, this: TransitionId, finish: bool, + pending: Seq, prior: Seq, inner: TransitionId) + requires model::graph_wf(b), model::graph_wf(a), model::graph_extends(b, a), this@ < b.transitions.len(), !finish, + b.transitions[this@ as int] == model::TransitionNode::Not(inner@) + || b.transitions[this@ as int] == model::TransitionNode::Append(inner@, transition_suffix(b, this)), + ipre(b, pending.push((this, finish)), prior), + ensures istep(a, pending.push((this, finish)), pending.push((this, true)).push((inner, false)), prior, prior), +{ + reveal(ipre); + let t = this@; + let k = inner@; + lemma_ipre_stable(b, a, pending.push((this, finish)), prior); + lemma_itasks_sub(a, pending, (this, finish)); + lemma_node_stable(b, a, t); + model::lemma_graph_transition_wf(b, t); + lemma_nf_children(a, t); + let l = lits(a, prior); + let e1 = Seq::::empty().push((this, true)); + let e = e1.push((inner, false)); + lemma_irun_push(a, e1, (inner, false), l); + lemma_irun_push(a, Seq::::empty(), (this, true), l.push(vav(a, k))); + assert(l.push(vav(a, k)).drop_last() =~= l); + assert(l.push(vav(a, k)).last() == vav(a, k)); + let pushed = match a.transitions[t as int] { + model::TransitionNode::Not(_) => not_av(vav(a, k)), + model::TransitionNode::Append(_, rs) => cat_av(a, vav(a, k), rs), + _ => vav(a, t), + }; + assert(irun(a, e, l) == Some(l.push(pushed))); + assert(av_le(pushed, vav(a, t))) by { + assert forall|v: R| #[trigger] (pushed.x)(v) implies (vav(a, t).x)(v) by { + lemma_tval(a, t, v); + match a.transitions[t as int] { + model::TransitionNode::Not(_) => { + let w = choose|w: R| (vav(a, k).x)(w) && v == #[trigger] r_not(w); + assert((tv(a))(k, w) == tval(a, k, w)); + assert(negs(tv(a), t, k, v)); + }, + model::TransitionNode::Append(_, rs) => { + let w = choose|w: R| (vav(a, k).x)(w) && v == #[trigger] ccat(a, w, rs); + assert((tv(a))(k, w) == tval(a, k, w)); + assert(apps(a, tv(a), t, k, rs, v)); + }, + _ => {}, + } + } + } + lemma_stack_le_refl(l); + lemma_stack_le_push(l, l, pushed, vav(a, t)); + assert(pending + e =~= pending.push((this, true)).push((inner, false))); + lemma_itasks_push(a, pending, (this, true)); + lemma_itasks_push(a, pending.push((this, true)), (inner, false)); + lemma_istep_close(a, pending, (this, finish), prior, e, prior); +} + +/// Finished `Not`: replace the top value `x` by `N(¬x)`. +pub proof fn lemma_istep_not(b: model::Graph, a: model::Graph, this: TransitionId, + pending: Seq, prior: Seq, out: RegexId) + requires model::graph_wf(b), model::graph_wf(a), model::graph_extends(b, a), this@ < b.transitions.len(), + b.transitions[this@ as int] is Not, prior.len() > 0, out@ < a.regexes.len(), + norm::regex_not_result(a, prior.last()@, out@), + ipre(b, pending.push((this, true)), prior), + ensures istep(a, pending.push((this, true)), pending, prior, prior.drop_last().push(out)), +{ + reveal(ipre); + let t = this@; + lemma_ipre_stable(b, a, pending.push((this, true)), prior); + lemma_itasks_sub(a, pending, (this, true)); + lemma_node_stable(b, a, t); + let l = lits(a, prior); + let n = prior.len() as int; + let inner = prior.last(); + assert(prior[n - 1] == inner); + lemma_not_link(a, inner@, out@); + let x = model::lift_regex(a, inner@); + let o = model::lift_regex(a, out@); + lemma_lits_split(a, prior, n - 1); + assert(l.last() == lit_av(x)); + assert(l.drop_last() =~= l.take(n - 1)); + let v1 = prior.drop_last().push(out); + lemma_lits_push(a, prior.drop_last(), out); + assert((not_av(lit_av(x)).x)(o)); + lemma_lit_le(o, not_av(lit_av(x))); + lemma_stack_le_refl(l.drop_last()); + lemma_stack_le_push(l.drop_last(), l.drop_last(), lit_av(o), not_av(lit_av(x))); + assert(iapply(a, (this, true), l) == Some(l.drop_last().push(not_av(l.last())))); + assert(pending + Seq::::empty() =~= pending); + lemma_ivalues_replace(a, prior, n - 1, out); + lemma_istep_close(a, pending, (this, true), prior, Seq::empty(), v1); +} + +/// Finished `Append(k, rs)`: replace the top value `w` by `N(w rs)`. +pub proof fn lemma_istep_append(b: model::Graph, a: model::Graph, this: TransitionId, + pending: Seq, prior: Seq, xs: Seq, out: RegexId) + requires model::graph_wf(b), model::graph_wf(a), model::graph_extends(b, a), this@ < b.transitions.len(), + b.transitions[this@ as int] is Append, prior.len() > 0, + norm::regex_ids_valid(b, xs), model::regex_ids(xs) == seq![prior.last()@] + transition_suffix(b, this), + out@ < a.regexes.len(), norm::regex_concat_result(b, a, xs, out@), + ipre(b, pending.push((this, true)), prior), + ensures istep(a, pending.push((this, true)), pending, prior, prior.drop_last().push(out)), +{ + reveal(ipre); + let t = this@; + model::lemma_graph_wf_elim(b); + lemma_ipre_stable(b, a, pending.push((this, true)), prior); + lemma_itasks_sub(a, pending, (this, true)); + lemma_node_stable(b, a, t); + lemma_nf_children(a, t); + model::lemma_graph_transition_wf(b, t); + let rs = transition_suffix(b, this); + let l = lits(a, prior); + let n = prior.len() as int; + let head = prior.last(); + assert(prior[n - 1] == head); + lemma_concat_link(b, a, xs, out@); + interp_append_ids(b, xs, head, rs); + assert(lifts(b, xs) =~= crate::symbolic::verify::lifted_values(b, xs)); + model::lemma_lift_regex_stable(b, a, head@); + assert(model::lift_regexes(b, rs) =~= model::lift_regexes(a, rs)) by { + assert forall|i: int| 0 <= i < rs.len() implies model::lift_regexes(b, rs)[i] == model::lift_regexes(a, rs)[i] by { + model::lemma_lift_regex_stable(b, a, rs[i]); + } + } + let w = model::lift_regex(a, head@); + let o = model::lift_regex(a, out@); + assert(o == ccat(a, w, rs)); + lemma_ccat_nf(a, w, rs); + lemma_lits_split(a, prior, n - 1); + assert(l.last() == lit_av(w)); + assert(l.drop_last() =~= l.take(n - 1)); + let v1 = prior.drop_last().push(out); + lemma_lits_push(a, prior.drop_last(), out); + assert((cat_av(a, lit_av(w), rs).x)(o)); + lemma_lit_le(o, cat_av(a, lit_av(w), rs)); + lemma_stack_le_refl(l.drop_last()); + lemma_stack_le_push(l.drop_last(), l.drop_last(), lit_av(o), cat_av(a, lit_av(w), rs)); + assert(iapply(a, (this, true), l) == Some(l.drop_last().push(cat_av(a, l.last(), rs)))); + assert(pending + Seq::::empty() =~= pending); + lemma_ivalues_replace(a, prior, n - 1, out); + lemma_istep_close(a, pending, (this, true), prior, Seq::empty(), v1); +} + +/// Unfinished set node: finish task, then the children in source order. +pub proof fn lemma_istep_expand(b: model::Graph, a: model::Graph, id: TransitionId, finish: bool, + pending: Seq, prior: Seq) + requires model::graph_wf(b), model::graph_wf(a), model::graph_extends(b, a), id@ < b.transitions.len(), !finish, + b.transitions[id@ as int] is Union || b.transitions[id@ as int] is Intersect, + ipre(b, pending.push((id, finish)), prior), + ensures istep(a, pending.push((id, finish)), pending.push((id, true)) + child_interp_tasks(b, id, 0), prior, prior), +{ + reveal(ipre); + model::lemma_graph_wf_elim(a); + let t = id@; + lemma_ipre_stable(b, a, pending.push((id, finish)), prior); + lemma_itasks_sub(a, pending, (id, finish)); + lemma_node_stable(b, a, t); + model::lemma_graph_transition_wf(b, t); + lemma_nf_children(a, t); + let cs = transition_children(a, id); + assert(transition_children(b, id) == cs); + assert(child_interp_tasks(b, id, 0) =~= child_interp_tasks(a, id, 0)); + let c = child_interp_tasks(a, id, 0); + let l = lits(a, prior); + let vals = vavs(a, cs); + lemma_child_irun(a, id, 0, l); + assert(vals.skip(0) =~= vals); + let e0 = Seq::::empty().push((id, true)); + let e = e0 + c; + lemma_irun_prefix(a, e0, c, l); + lemma_irun_push(a, Seq::::empty(), (id, true), l + vals); + let inter = a.transitions[t as int] is Intersect; + assert((l + vals).take(l.len() as int) =~= l); + assert((l + vals).skip(l.len() as int) =~= vals); + assert(irun(a, e, l) == Some(l.push(set_av(vals, inter)))); + assert(av_le(set_av(vals, inter), vav(a, t))) by { + assert forall|v: R| #[trigger] (set_av(vals, inter).x)(v) implies (vav(a, t).x)(v) by { + let vs = choose|vs: Seq| #[trigger] members(vals, vs) && (core().nset)(inter, vs.to_set(), v); + lemma_tval(a, t, v); + assert(kid_vals(tv(a), t, cs, vs)) by { + assert forall|i: int| 0 <= i < cs.len() implies #[trigger] cs[i] < t && (tv(a))(cs[i], vs[i]) by { + assert((vals[i].x)(vs[i])); + assert((tv(a))(cs[i], vs[i]) == tval(a, cs[i], vs[i])); + } + } + } + } + lemma_stack_le_refl(l); + lemma_stack_le_push(l, l, set_av(vals, inter), vav(a, t)); + assert(pending + e =~= pending.push((id, true)) + c); + assert(itasks(a, pending + e)) by { + let all = pending + e; + assert forall|i: int| #![trigger all[i]] 0 <= i < all.len() implies nf_sum(a, all[i].0@) by { + if i < pending.len() { assert(all[i] == pending[i]); } + else if i == pending.len() { assert(all[i] == (id, true)); } + else { + let j = i - pending.len() - 1; + assert(all[i] == c[j]); + assert(c[j].0@ == cs[cs.len() - 1 - j]); + assert(nf_sum(a, cs[cs.len() - 1 - j])); + } + } + } + lemma_istep_close(a, pending, (id, finish), prior, e, prior); +} + +/// The output of the set constructor is a member of the abstract set of its operands. +#[verifier::spinoff_prover] +pub proof fn lemma_set_value(b: model::Graph, a: model::Graph, inter: bool, prior: Seq, start: int, out: RegexId) + requires model::graph_wf(b), model::graph_wf(a), model::graph_extends(b, a), ivalues(b, prior), + 0 <= start <= prior.len(), out@ < a.regexes.len(), + norm::regex_set_flat_inputs(b, prior.skip(start), inter) ==> norm::regex_set_shape(b, a, prior.skip(start), inter, out@), + ensures regex_nf(model::lift_regex(a, out@)), + av_le(lit_av(model::lift_regex(a, out@)), set_av(lits(a, prior.skip(start)), inter)), +{ + let ch = prior.skip(start); + model::lemma_graph_wf_elim(b); + assert(norm::regex_ids_valid(b, ch)) by { + assert forall|i: int| 0 <= i < ch.len() implies ch[i]@ < b.regexes.len() by { + assert(ch[i] == prior[start + i]); + } + } + assert(ids_nf(b, ch)) by { + assert forall|i: int| 0 <= i < ch.len() implies regex_nf(#[trigger] model::lift_regex(b, ch[i]@)) by { + assert(ch[i] == prior[start + i]); + } + } + lemma_flat_inputs(b, ch, inter); + lemma_set_link(b, a, ch, inter, out@); + let o = model::lift_regex(a, out@); + let vs = lifts(a, ch); + assert(lifts(b, ch) =~= vs) by { + assert forall|i: int| 0 <= i < ch.len() implies lifts(b, ch)[i] == vs[i] by { + assert(ch[i] == prior[start + i]); + model::lemma_lift_regex_stable(b, a, ch[i]@); + } + } + let s = lits(a, ch); + assert(members(s, vs)) by { + assert forall|i: int| #![trigger vs[i]] 0 <= i < s.len() implies (s[i].x)(vs[i]) by {} + } + assert((set_av(s, inter).x)(o)); + lemma_lit_le(o, set_av(s, inter)); +} + +/// Finished set node: replace the operands by the set constructor's output. +#[verifier::spinoff_prover] +pub proof fn lemma_istep_set(b: model::Graph, a: model::Graph, id: TransitionId, inter: bool, + pending: Seq, prior: Seq, start: int, out: RegexId) + requires model::graph_wf(b), model::graph_wf(a), model::graph_extends(b, a), id@ < b.transitions.len(), + b.transitions[id@ as int] == (if inter { model::TransitionNode::Intersect(transition_children(b, id)) } + else { model::TransitionNode::Union(transition_children(b, id)) }), + 0 <= start <= prior.len(), prior.len() - start == transition_children(b, id).len(), + out@ < a.regexes.len(), + norm::regex_set_flat_inputs(b, prior.skip(start), inter) ==> norm::regex_set_shape(b, a, prior.skip(start), inter, out@), + ipre(b, pending.push((id, true)), prior), + ensures istep(a, pending.push((id, true)), pending, prior, prior.take(start).push(out)), +{ + reveal(ipre); + let t = id@; + lemma_ipre_stable(b, a, pending.push((id, true)), prior); + lemma_itasks_sub(a, pending, (id, true)); + lemma_node_stable(b, a, t); + lemma_set_value(b, a, inter, prior, start, out); + let l = lits(a, prior); + let o = model::lift_regex(a, out@); + lemma_lits_split(a, prior, start); + lemma_stack_le_refl(l.take(start)); + lemma_stack_le_push(l.take(start), l.take(start), lit_av(o), set_av(l.skip(start), inter)); + lemma_lits_push(a, prior.take(start), out); + assert(iapply(a, (id, true), l) == Some(l.take(start).push(set_av(l.skip(start), inter)))); + assert(pending + Seq::::empty() =~= pending); + lemma_ivalues_replace(a, prior, start, out); + lemma_istep_close(a, pending, (id, true), prior, Seq::empty(), prior.take(start).push(out)); +} + +// ===== the loop of `interpret` ===== + +pub proof fn lemma_iinit(g: model::Graph, this: TransitionId) + requires nf_sum(g, this@), + ensures iinv(g, this@, seq![(this, false)], Seq::empty()), +{ + reveal(iinv); + let ts = seq![(this, false)]; + assert(itasks(g, ts)) by { + assert forall|i: int| #![trigger ts[i]] 0 <= i < ts.len() implies nf_sum(g, ts[i].0@) by { assert(ts[i] == (this, false)); } + } + lemma_irun_push(g, Seq::::empty(), (this, false), lits(g, Seq::empty())); + assert(Seq::::empty().push((this, false)) == ts); + assert(lits(g, Seq::::empty()) =~= Seq::::empty()); + assert(Seq::::empty().push(vav(g, this@)) == seq![vav(g, this@)]); + lemma_stack_le_refl(seq![vav(g, this@)]); +} + +/// One iteration of the loop of `interpret` keeps the invariant. +pub proof fn lemma_iloop(b: model::Graph, a: model::Graph, this: nat, pending: Seq, prior: Seq, + tasks: Seq, values: Seq) + requires model::graph_wf(b), model::graph_extends(b, a), this < b.transitions.len(), + iinv(b, this, pending, prior), + ipre(b, pending, prior) ==> istep(a, pending, tasks, prior, values), + ensures iinv(a, this, tasks, values), +{ + reveal(iinv); + reveal(ipre); + reveal(istep); + lemma_ipre_stable(b, a, pending, prior); + lemma_vav_stable(b, a, this); + lemma_aref_trans(Some(seq![vav(a, this)]), irun(a, pending, lits(a, prior)), irun(a, tasks, lits(a, values))); +} + +/// At the end of the loop, the single value is a value of the root. +pub proof fn lemma_ifinal(g: model::Graph, this: nat, values: Seq) + requires iinv(g, this, Seq::empty(), values), + ensures values.len() == 1, tval(g, this, model::lift_regex(g, values[0]@)), +{ + reveal(iinv); + let s = lits(g, values); + assert(irun(g, Seq::::empty(), s) == Some(s)); + assert(stack_le(s, seq![vav(g, this)])); + assert(av_le(s[0], seq![vav(g, this)][0])); + assert((s[0].x)(model::lift_regex(g, values[0]@))); +} + +// ===== successor cache entries ===== + +/// A successor-cache entry `r` for transition `t` is a value of `t` when `t` is a normal form +/// (`progress::verify::successor_entries_wf`). +#[verifier::opaque] +pub open spec fn entry_val(g: model::Graph, t: nat, r: nat) -> bool { + nf_sum(g, t) ==> tval(g, t, model::lift_regex(g, r)) +} + +pub proof fn lemma_entry_val_intro(a: model::Graph, b: model::Graph, t: nat, r: nat) + requires model::graph_wf(a), model::graph_extends(a, b), t < a.transitions.len(), + nf_sum(a, t) ==> tval(b, t, model::lift_regex(b, r)), + ensures entry_val(b, t, r), +{ + reveal(entry_val); + lemma_trans_stable(a, b, t); +} + +pub proof fn lemma_entry_val_stable(a: model::Graph, b: model::Graph, t: nat, r: nat) + requires model::graph_wf(a), model::graph_extends(a, b), t < a.transitions.len(), r < a.regexes.len(), entry_val(a, t, r), + ensures entry_val(b, t, r), +{ + reveal(entry_val); + model::lemma_graph_wf_elim(a); + lemma_trans_stable(a, b, t); + model::lemma_lift_regex_stable(a, b, r); +} + +pub proof fn lemma_entry_val_elim(g: model::Graph, t: nat, r: nat) + requires entry_val(g, t, r), nf_sum(g, t), + ensures tval(g, t, model::lift_regex(g, r)), +{ + reveal(entry_val); +} + +} // verus! diff --git a/src/history-semantics/src/verify/finite_link.rs b/src/history-semantics/src/verify/finite_link.rs new file mode 100644 index 000000000..b70dbe68c --- /dev/null +++ b/src/history-semantics/src/verify/finite_link.rs @@ -0,0 +1,572 @@ +//! Link between the implemented regex constructors and the model `verify::finite_impl::m_impl`. +//! +//! The constructors' postconditions in `normalize::verify` (`regex_not_result`, +//! `regex_concat_result`, `regex_set_shape`, `test_connective_result`) are stated on graph ids. +//! Lifted to trees, they say that the implementation's outputs are outputs of the model's +//! constructors applied to the lifted inputs ((N1)–(N4) and the combined tests of (N5)), and that +//! hereditary normal forms are preserved ((N0)): [`lemma_not_link`], [`lemma_concat_link`], +//! [`lemma_set_link`]. +use crate::normalize::verify as norm; +use crate::verify::finite_impl::*; +use crate::verify::finite_states::*; +use crate::verify::refinement::finiteness::{ + lemma_lift_regex_injective, lemma_lift_test_injective, +}; +use junco_core::kernel::verify as model; +use junco_core::kernel::{RegexId, TestId}; +use junco_core::verify::history_specs::Regex; +use vstd::prelude::*; + +verus! { + +broadcast use junco_core::kernel::verify::group_kernel_views; + +/// The lifted trees of `ids`. +pub open spec fn lifts(g: model::Graph, ids: Seq) -> Seq { + Seq::new(ids.len(), |i: int| model::lift_regex(g, ids[i]@)) +} + +pub open spec fn lift_set(g: model::Graph, ids: Seq) -> Set { + lifts(g, ids).to_set() +} + +pub open spec fn ids_nf(g: model::Graph, ids: Seq) -> bool { + forall|i: int| 0 <= i < ids.len() ==> regex_nf(#[trigger] model::lift_regex(g, ids[i]@)) +} + +pub open spec fn nats_nf(g: model::Graph, ids: Seq) -> bool { + forall|i: int| 0 <= i < ids.len() ==> regex_nf(#[trigger] model::lift_regex(g, ids[i])) +} + +// ===== lifting single nodes ===== + +/// The lift of a regex node, read off its kind. +pub proof fn lemma_regex_lift(g: model::Graph, id: nat) + requires model::graph_wf(g), id < g.regexes.len(), + ensures + model::lift_regex(g, id) == norm::regex_unbounded_kind(g, g.regexes[id as int].kind), + model::regex_kind_wf_at(g, g.regexes[id as int].kind, id), + r_kind(model::lift_regex(g, id)) == node_kind(g.regexes[id as int].kind), +{ + norm::regex_unfold(g, id); +} + +pub open spec fn node_kind(k: model::RegexKindNode) -> Kind { + match k { + model::RegexKindNode::Empty => Kind::Empty, model::RegexKindNode::Epsilon => Kind::Epsilon, + model::RegexKindNode::All => Kind::Universal, model::RegexKindNode::Test(_) => Kind::Test, + model::RegexKindNode::Union(_) => Kind::Union, model::RegexKindNode::Intersect(_) => Kind::Intersect, + model::RegexKindNode::Not(_) => Kind::Not, model::RegexKindNode::Star(_) => Kind::Star, + model::RegexKindNode::Concat(_) => Kind::List, + } +} + +/// The lift of a test node, read off the node. +pub proof fn lemma_test_lift(g: model::Graph, id: nat) + requires model::graph_wf(g), id < g.tests.len(), + ensures + match g.tests[id as int] { + model::TestNode::And(cs) => model::bounded(cs, id) && model::strictly_increasing(cs) + && model::lift_test(g, id) == model::Test::And(Seq::new(cs.len(), |j: int| model::lift_test(g, cs[j]))), + model::TestNode::Or(cs) => model::bounded(cs, id) && model::strictly_increasing(cs) + && model::lift_test(g, id) == model::Test::Or(Seq::new(cs.len(), |j: int| model::lift_test(g, cs[j]))), + model::TestNode::True => model::lift_test(g, id) == model::Test::True, + model::TestNode::False => model::lift_test(g, id) == model::Test::False, + model::TestNode::Atom(p, b) => model::lift_test(g, id) == model::Test::Atom(p, b), + }, +{ + model::lemma_graph_test_wf(g, id); + match g.tests[id as int] { + model::TestNode::And(cs) => { + assert(model::lift_tests(g, cs, id) =~= Seq::new(cs.len(), |j: int| model::lift_test(g, cs[j]))); + }, + model::TestNode::Or(cs) => { + assert(model::lift_tests(g, cs, id) =~= Seq::new(cs.len(), |j: int| model::lift_test(g, cs[j]))); + }, + _ => {}, + } +} + +/// Distinct ids lift to distinct trees, so strictly increasing children lift without duplicates. +pub proof fn lemma_regex_lifts_nodup(g: model::Graph, cs: Seq) + requires model::graph_wf(g), model::bounded(cs, g.regexes.len()), model::strictly_increasing(cs), + ensures model::lift_regexes(g, cs).no_duplicates(), +{ + let ls = model::lift_regexes(g, cs); + assert forall|i: int, j: int| 0 <= i < ls.len() && 0 <= j < ls.len() && i != j implies ls[i] != ls[j] by { + if ls[i] == ls[j] { + lemma_lift_regex_injective(g, cs[i], cs[j]); + if i < j { assert(cs[i] < cs[j]); } else { assert(cs[j] < cs[i]); } + } + } +} + +pub proof fn lemma_test_lifts_nodup(g: model::Graph, cs: Seq) + requires model::graph_wf(g), model::bounded(cs, g.tests.len()), model::strictly_increasing(cs), + ensures Seq::new(cs.len(), |j: int| model::lift_test(g, cs[j])).no_duplicates(), +{ + let ls = Seq::new(cs.len(), |j: int| model::lift_test(g, cs[j])); + assert forall|i: int, j: int| 0 <= i < ls.len() && 0 <= j < ls.len() && i != j implies ls[i] != ls[j] by { + if ls[i] == ls[j] { + lemma_lift_test_injective(g, cs[i], cs[j]); + if i < j { assert(cs[i] < cs[j]); } else { assert(cs[j] < cs[i]); } + } + } +} + +// ===== (N3) ===== + +/// `N(¬x)` of the implementation lifts to `r_not` of the lifted operand. +pub proof fn lemma_not_link(g: model::Graph, x: nat, r: nat) + requires model::graph_wf(g), x < g.regexes.len(), r < g.regexes.len(), regex_nf(model::lift_regex(g, x)), + norm::regex_not_result(g, x, r), + ensures model::lift_regex(g, r) == r_not(model::lift_regex(g, x)), regex_nf(model::lift_regex(g, r)), +{ + norm::regex_constants(g); + lemma_regex_lift(g, x); + lemma_regex_lift(g, r); + match g.regexes[x as int].kind { + model::RegexKindNode::Empty => {}, + model::RegexKindNode::All => {}, + model::RegexKindNode::Not(inner) => {}, + _ => { + assert(g.regexes[r as int].kind == model::RegexKindNode::Not(x)); + }, + } +} + +// ===== (N4) ===== + +/// The implementation's flattening lifts to the model's. +pub proof fn lemma_flat_link(g: model::Graph, ids: Seq) + requires model::graph_wf(g), norm::regex_ids_valid(g, ids), + ensures + model::lift_regexes(g, norm::regex_concat_flat(g, ids)) == pre().flat(lifts(g, ids)), + model::bounded(norm::regex_concat_flat(g, ids), g.regexes.len()), + (exists|i: int| 0 <= i < ids.len() && g.regexes[ids[i]@ as int].kind == model::RegexKindNode::Empty) + == pre().has_empty(lifts(g, ids)), + decreases ids.len(), +{ + norm::regex_constants(g); + if ids.len() > 0 { + let init = ids.drop_last(); + let x = ids.last()@; + lemma_flat_link(g, init); + lemma_regex_lift(g, x); + let ls = lifts(g, ids); + assert(ls.drop_last() =~= lifts(g, init)); + assert(ls.last() == model::lift_regex(g, x)); + let fi = norm::regex_concat_flat(g, init); + let px = norm::regex_concat_piece(g, x); + assert(norm::regex_concat_flat(g, ids) == fi + px); + assert(model::lift_regexes(g, fi + px) =~= model::lift_regexes(g, fi) + model::lift_regexes(g, px)); + assert(model::lift_regexes(g, px) =~= pre().piece(model::lift_regex(g, x))) by { + match g.regexes[x as int].kind { + model::RegexKindNode::Concat(cs) => {}, + model::RegexKindNode::Epsilon => {}, + _ => {}, + } + } + assert(model::bounded(px, g.regexes.len())) by { + match g.regexes[x as int].kind { + model::RegexKindNode::Concat(cs) => { + assert forall|j: int| 0 <= j < cs.len() implies #[trigger] cs[j] < g.regexes.len() by { assert(cs[j] < x); } + }, + _ => {}, + } + } + assert(model::bounded(fi + px, g.regexes.len())) by { + assert forall|j: int| 0 <= j < (fi + px).len() implies #[trigger] (fi + px)[j] < g.regexes.len() by { + if j < fi.len() { assert((fi + px)[j] == fi[j]); } else { assert((fi + px)[j] == px[j - fi.len()]); } + } + } + let e_ids = exists|i: int| 0 <= i < ids.len() && g.regexes[ids[i]@ as int].kind == model::RegexKindNode::Empty; + let e_init = exists|i: int| 0 <= i < init.len() && g.regexes[init[i]@ as int].kind == model::RegexKindNode::Empty; + assert(e_ids == (e_init || g.regexes[x as int].kind == model::RegexKindNode::Empty)) by { + if e_ids { + let i = choose|i: int| 0 <= i < ids.len() && g.regexes[ids[i]@ as int].kind == model::RegexKindNode::Empty; + if i < init.len() { assert(init[i] == ids[i]); } + } + if e_init { + let i = choose|i: int| 0 <= i < init.len() && g.regexes[init[i]@ as int].kind == model::RegexKindNode::Empty; + assert(init[i] == ids[i]); + } + } + assert(pre().has_empty(ls) == (pre().has_empty(lifts(g, init)) || ls.last() == Regex::::Empty)) by { + if pre().has_empty(ls) { + let i = choose|i: int| 0 <= i < ls.len() && ls[i] == pre().empty; + if i < init.len() { assert(lifts(g, init)[i] == ls[i]); } + } + if pre().has_empty(lifts(g, init)) { + let i = choose|i: int| 0 <= i < lifts(g, init).len() && lifts(g, init)[i] == pre().empty; + assert(lifts(g, init)[i] == ls[i]); + } + } + } else { + assert(lifts(g, ids) =~= Seq::::empty()); + assert(model::lift_regexes(g, Seq::::empty()) =~= Seq::::empty()); + } +} + +/// `N(x₁⋯xₖ)` of the implementation lifts to `r_cat` of the lifted factors. +pub proof fn lemma_concat_link(before: model::Graph, after: model::Graph, children: Seq, r: nat) + requires model::graph_wf(before), model::graph_wf(after), model::graph_extends(before, after), + norm::regex_ids_valid(before, children), r < after.regexes.len(), + norm::regex_concat_result(before, after, children, r), + ensures model::lift_regex(after, r) == r_cat(lifts(before, children)), +{ + norm::regex_constants(before); + norm::regex_constants(after); + lemma_flat_link(before, children); + let f = norm::regex_concat_flat(before, children); + model::lemma_graph_wf_elim(before); + if exists|i: int| 0 <= i < children.len() && before.regexes[children[i]@ as int].kind == model::RegexKindNode::Empty { + } else if f.len() == 0 { + } else if f.len() == 1 { + model::lemma_lift_regex_stable(before, after, f[0]); + } else { + lemma_regex_lift(after, r); + assert forall|j: int| 0 <= j < f.len() implies #[trigger] model::lift_regex(after, f[j]) == model::lift_regex(before, f[j]) by { + model::lemma_lift_regex_stable(before, after, f[j]); + } + assert(model::lift_regexes(after, f) =~= model::lift_regexes(before, f)); + } +} + +// ===== (N1), (N2), (N5) ===== + +/// Pieces lift to pieces: `regex_piece_contains` is `sops` on lifted trees. +pub proof fn lemma_piece_link(g: model::Graph, c: nat, inter: bool, o: nat) + requires model::graph_wf(g), c < g.regexes.len(), norm::regex_piece_contains(g, c, inter, o), + ensures o < g.regexes.len(), pre().sops(inter, model::lift_regex(g, c)).contains(model::lift_regex(g, o)), + regex_nf(model::lift_regex(g, c)) ==> regex_nf(model::lift_regex(g, o)) && !pre().is_set(inter, model::lift_regex(g, o)), +{ + broadcast use vstd::prelude::Seq::to_set_ensures; + lemma_regex_lift(g, c); + match g.regexes[c as int].kind { + model::RegexKindNode::Union(cs) => { + if !inter { + let j = choose|j: int| 0 <= j < cs.len() && cs[j] == o; + assert(cs[j] < c); + assert(model::lift_regexes(g, cs)[j] == model::lift_regex(g, o)); + if regex_nf(model::lift_regex(g, c)) { + assert(regex_nf(model::lift_regexes(g, cs)[j])); + } + } + }, + model::RegexKindNode::Intersect(cs) => { + if inter { + let j = choose|j: int| 0 <= j < cs.len() && cs[j] == o; + assert(cs[j] < c); + assert(model::lift_regexes(g, cs)[j] == model::lift_regex(g, o)); + if regex_nf(model::lift_regex(g, c)) { + assert(regex_nf(model::lift_regexes(g, cs)[j])); + } + } + }, + _ => {}, + } +} + +/// Test pieces lift to `test_piece`. +pub proof fn lemma_test_piece_link(g: model::Graph, c: nat, and: bool, t: nat) + requires model::graph_wf(g), c < g.tests.len(), norm::test_piece_contains(g, c, and, t), + ensures t < g.tests.len(), test_piece(and, model::lift_test(g, c), model::lift_test(g, t)), + test_nf(model::lift_test(g, c)) ==> test_nf(model::lift_test(g, t)) && !is_conn(and, model::lift_test(g, t)), +{ + lemma_test_lift(g, c); + match g.tests[c as int] { + model::TestNode::And(cs) => { + if and { + let j = choose|j: int| 0 <= j < cs.len() && cs[j] == t; + assert(cs[j] < c); + let ks = Seq::new(cs.len(), |j: int| model::lift_test(g, cs[j])); + assert(ks[j] == model::lift_test(g, t)); + assert(ks.contains(model::lift_test(g, t))); + } + }, + model::TestNode::Or(cs) => { + if !and { + let j = choose|j: int| 0 <= j < cs.len() && cs[j] == t; + assert(cs[j] < c); + let ks = Seq::new(cs.len(), |j: int| model::lift_test(g, cs[j])); + assert(ks[j] == model::lift_test(g, t)); + assert(ks.contains(model::lift_test(g, t))); + } + }, + _ => {}, + } +} + +/// Members of `ops₊(X)` lift into `in_sops_of`, and are normal forms that are not sets. +pub proof fn lemma_member_link(g: model::Graph, children: Seq, inter: bool, o: nat) + requires model::graph_wf(g), norm::regex_ids_valid(g, children), ids_nf(g, children), + norm::regex_member(g, children, inter, o), + ensures o < g.regexes.len(), pre().in_sops_of(inter, lift_set(g, children), model::lift_regex(g, o)), + regex_nf(model::lift_regex(g, o)), !pre().is_set(inter, model::lift_regex(g, o)), +{ + broadcast use vstd::prelude::Seq::to_set_ensures; + let i = choose|i: int| 0 <= i < children.len() && #[trigger] norm::regex_piece_contains(g, children[i]@, inter, o); + lemma_piece_link(g, children[i]@, inter, o); + assert(regex_nf(model::lift_regex(g, children[i]@))); + assert(lifts(g, children)[i] == model::lift_regex(g, children[i]@)); + assert(lift_set(g, children).contains(model::lift_regex(g, children[i]@))); +} + +/// Normal-form inputs are flat for the set constructor (its precondition `regex_set_flat_inputs`). +pub proof fn lemma_flat_inputs(g: model::Graph, children: Seq, inter: bool) + requires model::graph_wf(g), norm::regex_ids_valid(g, children), ids_nf(g, children), + ensures norm::regex_set_flat_inputs(g, children, inter), +{ + assert forall|o: nat| norm::regex_member(g, children, inter, o) implies !norm::regex_is_set(g, o, inter) by { + lemma_member_link(g, children, inter, o); + lemma_regex_lift(g, o); + } +} + +/// The member tests of `ts`, as regex states. +pub open spec fn test_states(g: model::Graph, ts: Seq) -> Set { + Seq::new(ts.len(), |k: int| Regex::Test(model::lift_test(g, ts[k]@))).to_set() +} + +/// Every test of `ts` is the test of a member: its regex is a test state among the operands. +pub proof fn lemma_member_tests(g: model::Graph, children: Seq, inter: bool, ts: Seq) + requires model::graph_wf(g), norm::regex_ids_valid(g, children), ids_nf(g, children), + forall|k: int| 0 <= k < ts.len() ==> norm::regex_member_test(g, children, inter, #[trigger] ts[k]@), + ensures + forall|u: R| #[trigger] test_states(g, ts).contains(u) ==> pre().is_test(u) && pre().in_sops_of(inter, lift_set(g, children), u), + forall|k: int| 0 <= k < ts.len() ==> #[trigger] ts[k]@ < g.tests.len() && test_nf(model::lift_test(g, ts[k]@)), +{ + broadcast use vstd::prelude::Seq::to_set_ensures; + let s = Seq::new(ts.len(), |k: int| Regex::Test(model::lift_test(g, ts[k]@))); + assert forall|k: int| 0 <= k < ts.len() implies #[trigger] ts[k]@ < g.tests.len() && test_nf(model::lift_test(g, ts[k]@)) + && pre().is_test(s[k]) && pre().in_sops_of(inter, lift_set(g, children), s[k]) by { + let o = choose|o: nat| #[trigger] norm::regex_member(g, children, inter, o) + && o < g.regexes.len() && g.regexes[o as int].kind == model::RegexKindNode::Test(ts[k]@); + lemma_member_link(g, children, inter, o); + lemma_regex_lift(g, o); + assert(model::lift_regex(g, o) == s[k]); + } + assert forall|u: R| #[trigger] test_states(g, ts).contains(u) implies pre().is_test(u) && pre().in_sops_of(inter, lift_set(g, children), u) by { + let k = choose|k: int| 0 <= k < s.len() && s[k] == u; + assert(ts[k]@ < g.tests.len()); + } +} + +/// A piece of a member test of `ts` lifts to a piece of a test state. +pub proof fn lemma_test_member_link(g: model::Graph, ts: Seq, and: bool, t: nat) + requires model::graph_wf(g), forall|k: int| 0 <= k < ts.len() ==> #[trigger] ts[k]@ < g.tests.len() && test_nf(model::lift_test(g, ts[k]@)), + norm::test_member(g, ts, and, t), + ensures t < g.tests.len(), piece_of(and, test_states(g, ts), model::lift_test(g, t)), + test_nf(model::lift_test(g, t)), !is_conn(and, model::lift_test(g, t)), +{ + broadcast use vstd::prelude::Seq::to_set_ensures; + let k = choose|k: int| 0 <= k < ts.len() && #[trigger] norm::test_piece_contains(g, ts[k]@, and, t); + lemma_test_piece_link(g, ts[k]@, and, t); + let s = Seq::new(ts.len(), |k: int| Regex::Test(model::lift_test(g, ts[k]@))); + assert(s[k] == Regex::Test(model::lift_test(g, ts[k]@))); + assert(test_states(g, ts).contains(Regex::Test(model::lift_test(g, ts[k]@)))); +} + +/// A combined test (`regex_combined_test`) lifts to a test combination of the model. +pub proof fn lemma_combined_link(before: model::Graph, after: model::Graph, children: Seq, inter: bool, o: nat) + requires model::graph_wf(before), model::graph_wf(after), model::graph_extends(before, after), + norm::regex_ids_valid(before, children), ids_nf(before, children), + norm::regex_combined_test(before, after, children, inter, o), + ensures pre().is_test(model::lift_regex(after, o)), + exists|us: Set| #[trigger] pre().combo_from(inter, lift_set(before, children), us, model::lift_regex(after, o)), +{ + let (t, ts) = choose|t: nat, ts: Seq| + after.regexes[o as int].kind == model::RegexKindNode::Test(t) + && (forall|k: int| 0 <= k < ts.len() ==> norm::regex_member_test(before, children, inter, #[trigger] ts[k]@)) + && #[trigger] norm::test_connective_result(before, after, ts, inter, t); + lemma_member_tests(before, children, inter, ts); + let us = test_states(before, ts); + lemma_regex_lift(after, o); + assert(t < after.tests.len()); + let phi = model::lift_test(after, t); + assert(model::lift_regex(after, o) == Regex::Test(phi)); + norm::regex_constants(before); + norm::regex_constants(after); + model::lemma_graph_wf_elim(before); + assert(test_nf(phi) && test_combo(inter, us, phi)) by { + if t == before.constants.test_true || t == before.constants.test_false { + } else if norm::test_member(before, ts, inter, t) { + lemma_test_member_link(before, ts, inter, t); + model::lemma_lift_test_stable(before, after, t); + } else { + lemma_test_lift(after, t); + match after.tests[t as int] { + model::TestNode::And(ks) => { + lemma_connective_kids(before, after, ts, inter, t, ks); + }, + model::TestNode::Or(ks) => { + lemma_connective_kids(before, after, ts, inter, t, ks); + }, + _ => {}, + } + } + } + assert(r_combo(inter, us, model::lift_regex(after, o))); + assert(pre().combo_from(inter, lift_set(before, children), us, model::lift_regex(after, o))); +} + +/// The children of a combined connective lift to duplicate-free pieces of the member tests. +pub proof fn lemma_connective_kids(before: model::Graph, after: model::Graph, ts: Seq, inter: bool, t: nat, ks: Seq) + requires model::graph_wf(before), model::graph_wf(after), model::graph_extends(before, after), + forall|k: int| 0 <= k < ts.len() ==> #[trigger] ts[k]@ < before.tests.len() && test_nf(model::lift_test(before, ts[k]@)), + t < after.tests.len(), + after.tests[t as int] == (if inter { model::TestNode::And(ks) } else { model::TestNode::Or(ks) }), + forall|k: int| 0 <= k < ks.len() ==> norm::test_member(before, ts, inter, #[trigger] ks[k]), + ensures ({ + let phi = model::lift_test(after, t); + test_nf(phi) && is_conn(inter, phi) + && forall|k: int| 0 <= k < test_kids(phi).len() ==> piece_of(inter, test_states(before, ts), #[trigger] test_kids(phi)[k]) + }), +{ + lemma_test_lift(after, t); + model::lemma_graph_wf_elim(before); + let kids = Seq::new(ks.len(), |j: int| model::lift_test(after, ks[j])); + assert forall|j: int| 0 <= j < ks.len() implies #[trigger] kids[j] == model::lift_test(before, ks[j]) + && piece_of(inter, test_states(before, ts), kids[j]) && test_nf(kids[j]) && !is_conn(inter, kids[j]) by { + lemma_test_member_link(before, ts, inter, ks[j]); + model::lemma_lift_test_stable(before, after, ks[j]); + } + lemma_test_lifts_nodup(after, ks); + let phi = model::lift_test(after, t); + assert(test_kids(phi) == kids); + if inter { + assert(phi == model::Test::And(kids)); + assert forall|j: int| 0 <= j < kids.len() implies test_nf(#[trigger] kids[j]) && !(kids[j] is And) by {} + } else { + assert(phi == model::Test::Or(kids)); + assert forall|j: int| 0 <= j < kids.len() implies test_nf(#[trigger] kids[j]) && !(kids[j] is Or) by {} + } +} + +/// A legal operand of `N(ΣX)` (`N(&X)`) lifts to an operand allowed by (N1)/(N2), is a normal +/// form, and is not a set of the same kind. +pub proof fn lemma_operand_link(before: model::Graph, after: model::Graph, children: Seq, inter: bool, o: nat) + requires model::graph_wf(before), model::graph_wf(after), model::graph_extends(before, after), + norm::regex_ids_valid(before, children), ids_nf(before, children), + norm::regex_set_operand_ok(before, after, children, inter, o), o < after.regexes.len(), + ensures ({ + let x = model::lift_regex(after, o); + &&& regex_nf(x) && !pre().is_set(inter, x) + &&& pre().in_sops_of(inter, lift_set(before, children), x) + || (pre().is_test(x) && exists|us: Set| #[trigger] pre().combo_from(inter, lift_set(before, children), us, x)) + }), +{ + model::lemma_graph_wf_elim(before); + if norm::regex_member(before, children, inter, o) { + lemma_member_link(before, children, inter, o); + model::lemma_lift_regex_stable(before, after, o); + } else { + lemma_combined_link(before, after, children, inter, o); + } +} + +/// (N1)/(N2), (N5) for the implementation: the output of `RegexId::set` on normal-form inputs is +/// an output of the model's set constructor on the lifted inputs (in particular a normal form). +pub proof fn lemma_set_link(before: model::Graph, after: model::Graph, children: Seq, inter: bool, r: nat) + requires model::graph_wf(before), model::graph_wf(after), model::graph_extends(before, after), + norm::regex_ids_valid(before, children), ids_nf(before, children), r < after.regexes.len(), + norm::regex_set_shape(before, after, children, inter, r), + ensures (core().nset)(inter, lift_set(before, children), model::lift_regex(after, r)), + regex_nf(model::lift_regex(after, r)), +{ + norm::regex_constants(before); + norm::regex_constants(after); + model::lemma_graph_wf_elim(before); + let u = model::lift_regex(after, r); + let xs = lift_set(before, children); + if r == before.constants.empty || r == before.constants.all || r == before.constants.epsilon { + assert(pre().nset_shape(inter, xs, u)); + } else { + lemma_regex_lift(after, r); + match after.regexes[r as int].kind { + model::RegexKindNode::Union(cs) => { + if !inter { lemma_set_node_link(before, after, children, inter, r, cs); } + else { lemma_single_link(before, after, children, inter, r); } + }, + model::RegexKindNode::Intersect(cs) => { + if inter { lemma_set_node_link(before, after, children, inter, r, cs); } + else { lemma_single_link(before, after, children, inter, r); } + }, + _ => { lemma_single_link(before, after, children, inter, r); }, + } + } +} + +/// The output is not a set of the connective's kind: it is itself a legal operand. +pub proof fn lemma_single_link(before: model::Graph, after: model::Graph, children: Seq, inter: bool, r: nat) + requires model::graph_wf(before), model::graph_wf(after), model::graph_extends(before, after), + norm::regex_ids_valid(before, children), ids_nf(before, children), r < after.regexes.len(), + norm::regex_set_shape(before, after, children, inter, r), + !(r == before.constants.empty || r == before.constants.all || r == before.constants.epsilon), + !norm::regex_is_set(after, r, inter), + ensures (core().nset)(inter, lift_set(before, children), model::lift_regex(after, r)), + regex_nf(model::lift_regex(after, r)), +{ + let u = model::lift_regex(after, r); + let xs = lift_set(before, children); + assert(norm::regex_piece_contains(after, r, inter, r)); + lemma_operand_link(before, after, children, inter, r); + assert(pre().sops(inter, u) == set![u]); + assert(pre().nset_shape(inter, xs, u)); +} + +/// The output is a set node of the connective's kind: its operands are legal operands. +pub proof fn lemma_set_node_link(before: model::Graph, after: model::Graph, children: Seq, inter: bool, r: nat, cs: Seq) + requires model::graph_wf(before), model::graph_wf(after), model::graph_extends(before, after), + norm::regex_ids_valid(before, children), ids_nf(before, children), r < after.regexes.len(), + norm::regex_set_shape(before, after, children, inter, r), + !(r == before.constants.empty || r == before.constants.all || r == before.constants.epsilon), + after.regexes[r as int].kind == set_kind_node(inter, cs), + ensures (core().nset)(inter, lift_set(before, children), model::lift_regex(after, r)), + regex_nf(model::lift_regex(after, r)), +{ + let u = model::lift_regex(after, r); + let xs = lift_set(before, children); + lemma_regex_lift(after, r); + let ls = model::lift_regexes(after, cs); + assert(model::bounded(cs, r) && model::strictly_increasing(cs)); + assert(model::bounded(cs, after.regexes.len())) by { + assert forall|j: int| 0 <= j < cs.len() implies #[trigger] cs[j] < after.regexes.len() by { assert(cs[j] < r); } + } + lemma_regex_lifts_nodup(after, cs); + assert(u == set_node(inter, ls)); + assert forall|j: int| 0 <= j < cs.len() implies ({ + let x = #[trigger] ls[j]; + &&& regex_nf(x) && !pre().is_set(inter, x) + &&& pre().in_sops_of(inter, xs, x) + || (pre().is_test(x) && exists|us: Set| #[trigger] pre().combo_from(inter, xs, us, x)) + }) by { + assert(cs[j] < r); + assert(norm::regex_piece_contains(after, r, inter, cs[j])) by { + assert(cs.contains(cs[j])); + } + lemma_operand_link(before, after, children, inter, cs[j]); + } + assert(regex_nf(u)) by { + if inter { + assert forall|j: int| 0 <= j < ls.len() implies regex_nf(#[trigger] ls[j]) && !(ls[j] is Intersect) by {} + } else { + assert forall|j: int| 0 <= j < ls.len() implies regex_nf(#[trigger] ls[j]) && !(ls[j] is Union) by {} + } + } + assert forall|o: R| #[trigger] pre().sops(inter, u).contains(o) implies + pre().in_sops_of(inter, xs, o) + || (pre().is_test(o) && exists|us: Set| #[trigger] pre().combo_from(inter, xs, us, o)) by { + broadcast use vstd::prelude::Seq::to_set_ensures; + assert(ls.contains(o)); + let j = choose|j: int| 0 <= j < ls.len() && ls[j] == o; + } + assert(pre().nset_shape(inter, xs, u)); +} + +pub open spec fn set_kind_node(inter: bool, cs: Seq) -> model::RegexKindNode { + if inter { model::RegexKindNode::Intersect(cs) } else { model::RegexKindNode::Union(cs) } +} + +} // verus! diff --git a/src/history-semantics/src/verify/finite_machine.rs b/src/history-semantics/src/verify/finite_machine.rs new file mode 100644 index 000000000..510654b34 --- /dev/null +++ b/src/history-semantics/src/verify/finite_machine.rs @@ -0,0 +1,615 @@ +//! Abstract interpretation of the transition normalizer's action machine (`normalize.rs` +//! `Action`): every stack value is abstracted by its class and sum class ([`av_of`]), every +//! action by the corresponding operation on classes ([`aapply`], mirroring +//! `normalize::verify::guarded_apply`), and a run by [`arun`]. The machine invariant is that the +//! abstract run of the remaining tasks on the abstract stack is below (`aref`) the abstract run +//! of the original action: then the result's class is bounded by the original action's +//! abstract effect. +use crate::normalize::verify::{self as norm, ActionShape}; +use crate::verify::finite_impl::*; +use crate::verify::finite_trans::*; +use junco_core::kernel::verify as model; +use junco_core::verify::history_specs::Regex; +use vstd::prelude::*; + +verus! { + +/// An abstract value: a class and a sum class. +pub struct AV { pub x: spec_fn(R) -> bool, pub y: spec_fn(R) -> bool } + +pub open spec fn av_le(a: AV, b: AV) -> bool { + &&& forall|v: R| #[trigger] (a.x)(v) ==> (b.x)(v) + &&& forall|v: R| #[trigger] (a.y)(v) ==> (b.y)(v) +} + +pub open spec fn stack_le(s: Seq, t: Seq) -> bool { + s.len() == t.len() && forall|i: int| 0 <= i < s.len() ==> #[trigger] av_le(s[i], t[i]) +} + +/// `after` is defined whenever `before` is, and below it pointwise. +pub open spec fn aref(before: Option>, after: Option>) -> bool { + match before { + None => true, + Some(l) => match after { Some(r) => stack_le(r, l), None => false }, + } +} + +pub open spec fn av_of(g: model::Graph, t: nat) -> AV { + AV { x: |v: R| tcls(g, t, v), y: |v: R| ycls(g, t, v) } +} + +pub open spec fn avs(g: model::Graph, ids: Seq) -> Seq { + ids.map(|i: int, t: nat| av_of(g, t)) +} + +pub open spec fn any_x(s: Seq, w: R) -> bool { + exists|i: int| #![trigger s[i]] 0 <= i < s.len() && (s[i].x)(w) +} + +pub open spec fn any_y(s: Seq, w: R) -> bool { + exists|i: int| #![trigger s[i]] 0 <= i < s.len() && (s[i].y)(w) +} + +pub open spec fn neg_of(a: AV, w: R) -> bool { + exists|x: R| (a.x)(x) && w == #[trigger] r_not(x) +} + +/// `N(w s)`. +pub open spec fn cat_r(w: R, s: R) -> R { + r_cat(seq![w, s]) +} + +pub open spec fn app_of(a: AV, s: R, v: R) -> bool { + exists|w: R| (a.x)(w) && v == #[trigger] cat_r(w, s) +} + +pub open spec fn top_cls() -> spec_fn(R) -> bool { + |v: R| true +} + +pub open spec fn av_if(a: AV, b: AV) -> AV { + AV { x: |v: R| (a.x)(v) || (b.x)(v), y: |v: R| (a.y)(v) || (b.y)(v) } +} + +pub open spec fn av_union(s: Seq) -> AV { + AV { x: |v: R| rconst(v) || any_x(s, v), y: |v: R| cl(false, |w: R| any_y(s, w), v) } +} + +pub open spec fn av_meet(s: Seq) -> AV { + AV { x: |v: R| cl(true, |w: R| any_x(s, w), v), y: top_cls() } +} + +pub open spec fn av_neg(a: AV) -> AV { + AV { x: |v: R| cl(true, |w: R| neg_of(a, w), v), y: top_cls() } +} + +pub open spec fn av_app(a: AV, s: R) -> AV { + AV { x: |v: R| rconst(v) || app_of(a, s, v), y: top_cls() } +} + +/// Abstract effect of an action (mirrors `guarded_apply`). +pub open spec fn aapply(g: model::Graph, action: ActionShape, s: Seq) -> Option> { + match action { + ActionShape::Clean(id, path) => Some(s.push(av_of(g, id))), + ActionShape::Not(id) => Some(s.push(av_neg(av_of(g, id)))), + ActionShape::Append(id, r) => Some(s.push(av_app(av_of(g, id), model::lift_regex(g, r)))), + ActionShape::Pair(a, b) => Some(s.push(av_meet(seq![av_of(g, a), av_of(g, b)]))), + ActionShape::Union(count) => if count <= s.len() { + let start = s.len() as int - count as int; + Some(s.take(start).push(av_union(s.subrange(start, s.len() as int)))) + } else { None }, + ActionShape::Intersect(count) => if count <= s.len() { + let start = s.len() as int - count as int; + Some(s.take(start).push(av_meet(s.subrange(start, s.len() as int)))) + } else { None }, + ActionShape::If(test) => if s.len() >= 2 { + Some(s.take(s.len() as int - 2).push(av_if(s[s.len() as int - 2], s.last()))) + } else { None }, + ActionShape::CleanIf(test, path) => if s.len() >= 2 { + Some(s.take(s.len() as int - 2).push(av_if(s[s.len() as int - 2], s.last()))) + } else { None }, + ActionShape::Fold(terms, index) => if index == 0 { + Some(s.push(av_meet(avs(g, terms)))) + } else if index < terms.len() { + if s.len() > 0 { + Some(s.drop_last().push(av_meet(seq![s.last()] + avs(g, terms.subrange(index as int, terms.len() as int))))) + } else { None } + } else { Some(s) }, + ActionShape::NotResult => if s.len() > 0 { Some(s.drop_last().push(av_neg(s.last()))) } else { None }, + ActionShape::AppendResult(r) => if s.len() > 0 { + Some(s.drop_last().push(av_app(s.last(), model::lift_regex(g, r)))) + } else { None }, + ActionShape::SwapThen => if s.len() >= 2 { + Some(s.take(s.len() as int - 2).push(s.last()).push(s[s.len() as int - 2])) + } else { None }, + } +} + +pub open spec fn arun(g: model::Graph, tasks: Seq, s: Seq) -> Option> + decreases tasks.len(), +{ + if tasks.len() == 0 { Some(s) } else { + match aapply(g, tasks.last(), s) { + Some(n) => arun(g, tasks.drop_last(), n), + None => None, + } + } +} + +// ===== order ===== + +pub proof fn lemma_av_le_refl(a: AV) + ensures av_le(a, a), +{} + +pub proof fn lemma_av_le_trans(a: AV, b: AV, c: AV) + requires av_le(a, b), av_le(b, c), + ensures av_le(a, c), +{ + assert forall|v: R| #[trigger] (a.x)(v) implies (c.x)(v) by { assert((b.x)(v)); } + assert forall|v: R| #[trigger] (a.y)(v) implies (c.y)(v) by { assert((b.y)(v)); } +} + +pub proof fn lemma_stack_le_refl(s: Seq) + ensures stack_le(s, s), +{ + assert forall|i: int| 0 <= i < s.len() implies #[trigger] av_le(s[i], s[i]) by { lemma_av_le_refl(s[i]); } +} + +pub proof fn lemma_stack_le_trans(a: Seq, b: Seq, c: Seq) + requires stack_le(a, b), stack_le(b, c), + ensures stack_le(a, c), +{ + assert forall|i: int| 0 <= i < a.len() implies #[trigger] av_le(a[i], c[i]) by { + assert(av_le(a[i], b[i])); + assert(av_le(b[i], c[i])); + lemma_av_le_trans(a[i], b[i], c[i]); + } +} + +pub proof fn lemma_aref_trans(a: Option>, b: Option>, c: Option>) + requires aref(a, b), aref(b, c), + ensures aref(a, c), +{ + match a { + None => {}, + Some(l) => match (b, c) { + (Some(m), Some(r)) => lemma_stack_le_trans(r, m, l), + _ => {}, + }, + } +} + +pub proof fn lemma_stack_le_push(s: Seq, t: Seq, a: AV, b: AV) + requires stack_le(s, t), av_le(a, b), + ensures stack_le(s.push(a), t.push(b)), +{ + assert forall|i: int| 0 <= i < s.push(a).len() implies #[trigger] av_le(s.push(a)[i], t.push(b)[i]) by { + if i < s.len() { assert(s.push(a)[i] == s[i]); assert(t.push(b)[i] == t[i]); } + } +} + +pub proof fn lemma_stack_le_sub(s: Seq, t: Seq, start: int, end: int) + requires stack_le(s, t), 0 <= start <= end <= s.len(), + ensures stack_le(s.subrange(start, end), t.subrange(start, end)), +{ + assert forall|i: int| 0 <= i < s.subrange(start, end).len() + implies #[trigger] av_le(s.subrange(start, end)[i], t.subrange(start, end)[i]) by { + assert(s.subrange(start, end)[i] == s[start + i]); + assert(t.subrange(start, end)[i] == t[start + i]); + } +} + +// ===== monotonicity of the operations ===== + +pub proof fn lemma_any_mono(s: Seq, t: Seq) + requires stack_le(s, t), + ensures + forall|w: R| #[trigger] any_x(s, w) ==> any_x(t, w), + forall|w: R| #[trigger] any_y(s, w) ==> any_y(t, w), +{ + assert forall|w: R| #[trigger] any_x(s, w) implies any_x(t, w) by { + let i = choose|i: int| #![trigger s[i]] 0 <= i < s.len() && (s[i].x)(w); + assert(av_le(s[i], t[i])); + assert((t[i].x)(w)); + } + assert forall|w: R| #[trigger] any_y(s, w) implies any_y(t, w) by { + let i = choose|i: int| #![trigger s[i]] 0 <= i < s.len() && (s[i].y)(w); + assert(av_le(s[i], t[i])); + assert((t[i].y)(w)); + } +} + +pub proof fn lemma_union_mono(s: Seq, t: Seq) + requires stack_le(s, t), + ensures av_le(av_union(s), av_union(t)), +{ + lemma_any_mono(s, t); + assert forall|v: R| #[trigger] (av_union(s).y)(v) implies (av_union(t).y)(v) by { + lemma_cl_mono(false, |w: R| any_y(s, w), |w: R| any_y(t, w), v); + } +} + +pub proof fn lemma_meet_mono(s: Seq, t: Seq) + requires stack_le(s, t), + ensures av_le(av_meet(s), av_meet(t)), +{ + lemma_any_mono(s, t); + assert forall|v: R| #[trigger] (av_meet(s).x)(v) implies (av_meet(t).x)(v) by { + lemma_cl_mono(true, |w: R| any_x(s, w), |w: R| any_x(t, w), v); + } +} + +pub proof fn lemma_neg_mono(a: AV, b: AV) + requires av_le(a, b), + ensures av_le(av_neg(a), av_neg(b)), +{ + assert forall|w: R| #[trigger] neg_of(a, w) implies neg_of(b, w) by { + let x = choose|x: R| (a.x)(x) && w == #[trigger] r_not(x); + assert((b.x)(x)); + } + assert forall|v: R| #[trigger] (av_neg(a).x)(v) implies (av_neg(b).x)(v) by { + lemma_cl_mono(true, |w: R| neg_of(a, w), |w: R| neg_of(b, w), v); + } +} + +pub proof fn lemma_app_mono(a: AV, b: AV, s: R) + requires av_le(a, b), + ensures av_le(av_app(a, s), av_app(b, s)), +{ + assert forall|v: R| #[trigger] (av_app(a, s).x)(v) implies (av_app(b, s).x)(v) by { + if app_of(a, s, v) { + let w = choose|w: R| (a.x)(w) && v == #[trigger] cat_r(w, s); + assert((b.x)(w)); + } + } +} + +pub proof fn lemma_if_mono(a: AV, b: AV, c: AV, d: AV) + requires av_le(a, c), av_le(b, d), + ensures av_le(av_if(a, b), av_if(c, d)), +{} + +pub proof fn lemma_aapply_mono(g: model::Graph, action: ActionShape, s1: Seq, s2: Seq) + requires stack_le(s1, s2), + ensures aref(aapply(g, action, s2), aapply(g, action, s1)), +{ + match action { + ActionShape::Clean(id, path) => { lemma_stack_le_push(s1, s2, av_of(g, id), av_of(g, id)); }, + ActionShape::Not(id) => { lemma_stack_le_push(s1, s2, av_neg(av_of(g, id)), av_neg(av_of(g, id))); }, + ActionShape::Append(id, r) => { + let a = av_app(av_of(g, id), model::lift_regex(g, r)); + lemma_stack_le_push(s1, s2, a, a); + }, + ActionShape::Pair(a, b) => { + let m = av_meet(seq![av_of(g, a), av_of(g, b)]); + lemma_stack_le_push(s1, s2, m, m); + }, + ActionShape::Union(count) => { + if count <= s2.len() { + let start = s2.len() as int - count as int; + lemma_stack_le_sub(s1, s2, 0, start); + lemma_stack_le_sub(s1, s2, start, s2.len() as int); + lemma_union_mono(s1.subrange(start, s1.len() as int), s2.subrange(start, s2.len() as int)); + assert(s1.take(start) == s1.subrange(0, start)); + assert(s2.take(start) == s2.subrange(0, start)); + lemma_stack_le_push(s1.take(start), s2.take(start), + av_union(s1.subrange(start, s1.len() as int)), av_union(s2.subrange(start, s2.len() as int))); + } + }, + ActionShape::Intersect(count) => { + if count <= s2.len() { + let start = s2.len() as int - count as int; + lemma_stack_le_sub(s1, s2, 0, start); + lemma_stack_le_sub(s1, s2, start, s2.len() as int); + lemma_meet_mono(s1.subrange(start, s1.len() as int), s2.subrange(start, s2.len() as int)); + assert(s1.take(start) == s1.subrange(0, start)); + assert(s2.take(start) == s2.subrange(0, start)); + lemma_stack_le_push(s1.take(start), s2.take(start), + av_meet(s1.subrange(start, s1.len() as int)), av_meet(s2.subrange(start, s2.len() as int))); + } + }, + ActionShape::If(test) => { lemma_aapply_if(s1, s2); }, + ActionShape::CleanIf(test, path) => { lemma_aapply_if(s1, s2); }, + ActionShape::Fold(terms, index) => { + if index == 0 { + lemma_stack_le_push(s1, s2, av_meet(avs(g, terms)), av_meet(avs(g, terms))); + } else if index < terms.len() { + if s2.len() > 0 { + let rest = avs(g, terms.subrange(index as int, terms.len() as int)); + lemma_stack_le_sub(s1, s2, 0, s1.len() - 1); + assert(av_le(s1[s1.len() - 1], s2[s2.len() - 1])); + let l1 = seq![s1.last()] + rest; + let l2 = seq![s2.last()] + rest; + assert(stack_le(l1, l2)) by { + assert forall|i: int| 0 <= i < l1.len() implies #[trigger] av_le(l1[i], l2[i]) by { + if i == 0 { } else { assert(l1[i] == rest[i - 1]); assert(l2[i] == rest[i - 1]); lemma_av_le_refl(rest[i - 1]); } + } + } + lemma_meet_mono(l1, l2); + assert(s1.drop_last() == s1.subrange(0, s1.len() - 1)); + assert(s2.drop_last() == s2.subrange(0, s2.len() - 1)); + lemma_stack_le_push(s1.drop_last(), s2.drop_last(), av_meet(l1), av_meet(l2)); + } + } + }, + ActionShape::NotResult => { + if s2.len() > 0 { + assert(av_le(s1[s1.len() - 1], s2[s2.len() - 1])); + lemma_neg_mono(s1.last(), s2.last()); + lemma_stack_le_sub(s1, s2, 0, s1.len() - 1); + assert(s1.drop_last() == s1.subrange(0, s1.len() - 1)); + assert(s2.drop_last() == s2.subrange(0, s2.len() - 1)); + lemma_stack_le_push(s1.drop_last(), s2.drop_last(), av_neg(s1.last()), av_neg(s2.last())); + } + }, + ActionShape::AppendResult(r) => { + if s2.len() > 0 { + assert(av_le(s1[s1.len() - 1], s2[s2.len() - 1])); + lemma_app_mono(s1.last(), s2.last(), model::lift_regex(g, r)); + lemma_stack_le_sub(s1, s2, 0, s1.len() - 1); + assert(s1.drop_last() == s1.subrange(0, s1.len() - 1)); + assert(s2.drop_last() == s2.subrange(0, s2.len() - 1)); + lemma_stack_le_push(s1.drop_last(), s2.drop_last(), + av_app(s1.last(), model::lift_regex(g, r)), av_app(s2.last(), model::lift_regex(g, r))); + } + }, + ActionShape::SwapThen => { + if s2.len() >= 2 { + let n = s1.len() as int; + lemma_stack_le_sub(s1, s2, 0, n - 2); + assert(s1.take(n - 2) == s1.subrange(0, n - 2)); + assert(s2.take(n - 2) == s2.subrange(0, n - 2)); + assert(av_le(s1[n - 1], s2[n - 1])); + assert(av_le(s1[n - 2], s2[n - 2])); + lemma_stack_le_push(s1.take(n - 2), s2.take(n - 2), s1.last(), s2.last()); + lemma_stack_le_push(s1.take(n - 2).push(s1.last()), s2.take(n - 2).push(s2.last()), s1[n - 2], s2[n - 2]); + } + }, + } +} + +pub proof fn lemma_aapply_if(s1: Seq, s2: Seq) + requires stack_le(s1, s2), + ensures s2.len() >= 2 ==> stack_le( + s1.take(s1.len() as int - 2).push(av_if(s1[s1.len() as int - 2], s1.last())), + s2.take(s2.len() as int - 2).push(av_if(s2[s2.len() as int - 2], s2.last()))), +{ + if s2.len() >= 2 { + let n = s1.len() as int; + lemma_stack_le_sub(s1, s2, 0, n - 2); + assert(s1.take(n - 2) == s1.subrange(0, n - 2)); + assert(s2.take(n - 2) == s2.subrange(0, n - 2)); + assert(av_le(s1[n - 1], s2[n - 1])); + assert(av_le(s1[n - 2], s2[n - 2])); + lemma_if_mono(s1[n - 2], s1.last(), s2[n - 2], s2.last()); + lemma_stack_le_push(s1.take(n - 2), s2.take(n - 2), av_if(s1[n - 2], s1.last()), av_if(s2[n - 2], s2.last())); + } +} + +pub proof fn lemma_arun_mono(g: model::Graph, tasks: Seq, s1: Seq, s2: Seq) + requires stack_le(s1, s2), + ensures aref(arun(g, tasks, s2), arun(g, tasks, s1)), + decreases tasks.len(), +{ + if tasks.len() > 0 { + lemma_aapply_mono(g, tasks.last(), s1, s2); + match aapply(g, tasks.last(), s2) { + Some(n2) => { + let n1 = aapply(g, tasks.last(), s1).unwrap(); + lemma_arun_mono(g, tasks.drop_last(), n1, n2); + }, + None => {}, + } + } +} + +pub proof fn lemma_arun_prefix(g: model::Graph, prefix: Seq, suffix: Seq, s: Seq) + ensures arun(g, prefix + suffix, s) == match arun(g, suffix, s) { + Some(next) => arun(g, prefix, next), + None => None, + }, + decreases suffix.len(), +{ + if suffix.len() > 0 { + assert((prefix + suffix).last() == suffix.last()); + assert((prefix + suffix).drop_last() =~= prefix + suffix.drop_last()); + match aapply(g, suffix.last(), s) { + Some(next) => lemma_arun_prefix(g, prefix, suffix.drop_last(), next), + None => {}, + } + } else { + assert(prefix + suffix =~= prefix); + } +} + +/// Frame rule: replacing an action by an expansion whose abstract run is below the action's +/// abstract effect keeps the whole run below. +pub proof fn lemma_frame(g: model::Graph, prefix: Seq, expansion: Seq, action: ActionShape, + before: Seq, after: Seq) + requires aref(aapply(g, action, before), arun(g, expansion, after)), + ensures aref(arun(g, prefix.push(action), before), arun(g, prefix + expansion, after)), +{ + lemma_arun_prefix(g, prefix, seq![action], before); + lemma_arun_prefix(g, prefix, expansion, after); + assert(prefix.push(action) =~= prefix + seq![action]); + assert(seq![action].last() == action); + assert(seq![action].drop_last() =~= Seq::::empty()); + match aapply(g, action, before) { + Some(n) => { + assert(arun(g, seq![action], before) == arun(g, Seq::::empty(), n)); + let m = arun(g, expansion, after).unwrap(); + lemma_arun_mono(g, prefix, m, n); + }, + None => { + assert(arun(g, seq![action], before) is None); + }, + } +} + +// ===== stability ===== + +pub proof fn lemma_av_stable(a: model::Graph, b: model::Graph, t: nat) + requires model::graph_wf(a), model::graph_extends(a, b), t < a.transitions.len(), + ensures av_of(a, t) == av_of(b, t), +{ + lemma_trans_stable(a, b, t); + assert(av_of(a, t).x =~= av_of(b, t).x); + assert(av_of(a, t).y =~= av_of(b, t).y); +} + +pub proof fn lemma_avs_stable(a: model::Graph, b: model::Graph, ids: Seq) + requires model::graph_wf(a), model::graph_extends(a, b), model::bounded(ids, a.transitions.len()), + ensures avs(a, ids) == avs(b, ids), +{ + assert forall|i: int| 0 <= i < ids.len() implies #[trigger] avs(a, ids)[i] == avs(b, ids)[i] by { + lemma_av_stable(a, b, ids[i]); + } + assert(avs(a, ids) =~= avs(b, ids)); +} + +pub proof fn lemma_aapply_stable(a: model::Graph, b: model::Graph, action: ActionShape, s: Seq) + requires model::graph_wf(a), model::graph_extends(a, b), norm::transition_action_valid(a, action), + ensures aapply(a, action, s) == aapply(b, action, s), +{ + model::lemma_graph_wf_elim(a); + match action { + ActionShape::Clean(id, path) => { lemma_av_stable(a, b, id); }, + ActionShape::Not(id) => { lemma_av_stable(a, b, id); }, + ActionShape::Append(id, r) => { lemma_av_stable(a, b, id); model::lemma_lift_regex_stable(a, b, r); }, + ActionShape::Pair(x, y) => { lemma_av_stable(a, b, x); lemma_av_stable(a, b, y); }, + ActionShape::Fold(terms, index) => { + lemma_avs_stable(a, b, terms); + if index < terms.len() { + let sub = terms.subrange(index as int, terms.len() as int); + assert(model::bounded(sub, a.transitions.len())) by { + assert forall|j: int| 0 <= j < sub.len() implies #[trigger] sub[j] < a.transitions.len() by { + assert(sub[j] == terms[index + j]); + } + } + lemma_avs_stable(a, b, sub); + } + }, + ActionShape::AppendResult(r) => { model::lemma_lift_regex_stable(a, b, r); }, + _ => {}, + } +} + +pub proof fn lemma_arun_stable(a: model::Graph, b: model::Graph, tasks: Seq, s: Seq) + requires model::graph_wf(a), model::graph_extends(a, b), norm::transition_tasks_valid(a, tasks), + ensures arun(a, tasks, s) == arun(b, tasks, s), + decreases tasks.len(), +{ + if tasks.len() > 0 { + assert(norm::transition_action_valid(a, tasks[tasks.len() - 1])); + lemma_aapply_stable(a, b, tasks.last(), s); + assert(norm::transition_tasks_valid(a, tasks.drop_last())) by { + assert forall|i: int| 0 <= i < tasks.drop_last().len() implies norm::transition_action_valid(a, tasks.drop_last()[i]) by { + assert(tasks.drop_last()[i] == tasks[i]); + } + } + match aapply(a, tasks.last(), s) { + Some(n) => lemma_arun_stable(a, b, tasks.drop_last(), n), + None => {}, + } + } +} + +// ===== members of nested sets ===== + +/// `x` is reached from `t` through nested unions (`!inter`) or intersections (`inter`). +pub open spec fn tpiece(g: model::Graph, t: nat, inter: bool, x: nat) -> bool + decreases t, +{ + x == t || (t < g.transitions.len() && match g.transitions[t as int] { + model::TransitionNode::Union(cs) => !inter + && exists|i: int| #![trigger cs[i]] 0 <= i < cs.len() && cs[i] < t && tpiece(g, cs[i], inter, x), + model::TransitionNode::Intersect(cs) => inter + && exists|i: int| #![trigger cs[i]] 0 <= i < cs.len() && cs[i] < t && tpiece(g, cs[i], inter, x), + _ => false, + }) +} + +/// `x` is a member of the nested sets of the inputs `orig`. +pub open spec fn piece_of(g: model::Graph, orig: Seq, inter: bool, x: nat) -> bool { + exists|i: int| #![trigger orig[i]] 0 <= i < orig.len() && tpiece(g, orig[i], inter, x) +} + +/// The node `id` (a child of a same-kind set node `x`) is reached as well. +pub proof fn lemma_tpiece_child(g: model::Graph, root: nat, inter: bool, x: nat, cs: Seq, i: int) + requires model::graph_wf(g), root < g.transitions.len(), x < g.transitions.len(), tpiece(g, root, inter, x), + g.transitions[x as int] == (if inter { model::TransitionNode::Intersect(cs) } else { model::TransitionNode::Union(cs) }), + 0 <= i < cs.len(), + ensures tpiece(g, root, inter, cs[i]), + decreases root, +{ + model::lemma_graph_transition_wf(g, x); + assert(cs[i] < x); + if x == root { + assert(tpiece(g, cs[i], inter, cs[i])); + } else { + match g.transitions[root as int] { + model::TransitionNode::Union(rs) => { + let j = choose|j: int| #![trigger rs[j]] 0 <= j < rs.len() && rs[j] < root && tpiece(g, rs[j], inter, x); + lemma_tpiece_child(g, rs[j], inter, x, cs, i); + assert(tpiece(g, rs[j], inter, cs[i])); + }, + model::TransitionNode::Intersect(rs) => { + let j = choose|j: int| #![trigger rs[j]] 0 <= j < rs.len() && rs[j] < root && tpiece(g, rs[j], inter, x); + lemma_tpiece_child(g, rs[j], inter, x, cs, i); + assert(tpiece(g, rs[j], inter, cs[i])); + }, + _ => {}, + } + } +} + +/// Members have smaller classes and sum classes (for unions), and inherit normal forms. +pub proof fn lemma_tpiece_class(g: model::Graph, root: nat, inter: bool, x: nat) + requires model::graph_wf(g), root < g.transitions.len(), tpiece(g, root, inter, x), + ensures + x < g.transitions.len(), + forall|v: R| #[trigger] tcls(g, x, v) ==> tcls(g, root, v), + !inter ==> forall|v: R| #[trigger] ycls(g, x, v) ==> ycls(g, root, v), + nf_sum(g, root) ==> nf_sum(g, x), + inter && nf_prod(g, root) && x != root ==> nf_lit(g, x), + decreases root, +{ + if x != root { + model::lemma_graph_transition_wf(g, root); + match g.transitions[root as int] { + model::TransitionNode::Union(cs) => { + let j = choose|j: int| #![trigger cs[j]] 0 <= j < cs.len() && cs[j] < root && tpiece(g, cs[j], inter, x); + lemma_tpiece_class(g, cs[j], inter, x); + assert forall|v: R| #[trigger] tcls(g, x, v) implies tcls(g, root, v) by { + lemma_tcls(g, root, v); + assert(tcls(g, cs[j], v)); + } + assert forall|v: R| #[trigger] ycls(g, x, v) implies ycls(g, root, v) by { + lemma_ycls(g, root, v); + assert(ycls(g, cs[j], v)); + assert(kids(yc(g), root, cs, v)); + lemma_cl_base(false, |w: R| kids(yc(g), root, cs, w), v); + } + }, + model::TransitionNode::Intersect(cs) => { + let j = choose|j: int| #![trigger cs[j]] 0 <= j < cs.len() && cs[j] < root && tpiece(g, cs[j], inter, x); + lemma_tpiece_class(g, cs[j], inter, x); + assert forall|v: R| #[trigger] tcls(g, x, v) implies tcls(g, root, v) by { + lemma_tcls(g, root, v); + assert(tcls(g, cs[j], v)); + assert(kids(tc(g), root, cs, v)); + lemma_cl_base(true, |w: R| kids(tc(g), root, cs, w), v); + } + if nf_prod(g, root) { + assert(nf_lit(g, cs[j])); + // a literal is not a set, so it reaches only itself + assert(x == cs[j]); + } + }, + _ => {}, + } + } +} + +} // verus! diff --git a/src/history-semantics/src/verify/finite_states.rs b/src/history-semantics/src/verify/finite_states.rs new file mode 100644 index 000000000..1542198e4 --- /dev/null +++ b/src/history-semantics/src/verify/finite_states.rs @@ -0,0 +1,2067 @@ +//! Finiteness of normalized derivative states (paper Lemma `lem:finite-states`, appendix `app:finiteness`). +//! +//! The development is abstract: a [`Model`] packages a set of states, their shapes, the +//! normalizing constructors `N(ΣX)`, `N(&X)`, `N(¬p)`, `N(p₁⋯pₖ)`, the test combination of +//! (N1)/(N2), and the implemented successor `p ↦ ∂p`, the evaluation of the *normalized* symbolic +//! derivative, over *all* valuations and events. Transition normalization distributes +//! concatenation and intersection over unions and conditionals, pushes complements inward, and +//! merges leaves, so evaluating a normalized transition selects a union of *products*, each an +//! intersection of *literals*. `lit(p, v)` and `prod(p, v)` hold when `v` is the value of a literal +//! or of a product of the transition of `p` under some valuation and event. +//! +//! [`Model::contract`] states (N0)–(N5) and the successor equations (S0)–(S6). These numbers, the +//! invariants (C1)–(C4) and the set `C(q)` are this development's; the paper's appendix +//! `app:finiteness` outlines the construction informally and calls `C(q)` `Bound(q)`. The table in +//! `refinement/finiteness.rs` names each condition and its predicate below. Under the +//! contract, [`lemma_finite_states`] builds `C(q)` and [`theorem_finite_reachable`] bounds every +//! state reachable from a state. [`lemma_uset_nset`] is the union-closure step, [`lemma_uset_closed`] +//! and [`lemma_dnf_closed`] are the successor-closure step, and [`lemma_cat_assoc`] is (N4′). +//! [`lemma_contract_satisfiable`] shows the contract is consistent. +//! +//! The implemented constructors establish (N1)–(N4) and the shape of (N5) in their postconditions +//! (`regex_set_shape`, `regex_not_result`, `regex_concat_result`, `test_connective_result` in +//! `normalize::verify`), and interning gives the (N0) fixpoints (`regex_kind_unique`, +//! `regex_not_fixpoint`, `regex_concat_fixpoint`). +use vstd::iset_lib::lemma_iset_subset_finite; +use vstd::prelude::*; +use vstd::set_lib::{lemma_int_range, lemma_set_empty_equivalency_len, set_int_range}; + +verus! { + +/// Head of a state. +pub enum Kind { Empty, Epsilon, Universal, Test, Union, Intersect, Not, Star, List } + +/// Abstract normalizer, states, and successors. +/// +/// `nset(false, X, u)` holds when `u` is an output of `N(ΣX)` and `nset(true, X, u)` when it is +/// an output of `N(&X)`; the output is a relation because the implementation orders operands by +/// interning order, so the lifted tree depends on the graph. `combo(false, T, t)` holds when +/// the test `t` is obtained by combining the tests `T` with `∨` (`∧` for `true`). For some +/// valuation `θ` and event `e`, `succ(p, v)` holds when `v = ∂(p)_θ(e)`, and `lit(p, v)` and +/// `prod(p, v)` when `v` is the value of a literal or of a product of the evaluated normalized +/// transition of `p`. +#[verifier::reject_recursive_types(S)] +pub struct Model { + pub state: spec_fn(S) -> bool, + pub kind: spec_fn(S) -> Kind, + pub ops: spec_fn(S) -> Set, + pub body: spec_fn(S) -> S, + pub elems: spec_fn(S) -> Seq, + pub size: spec_fn(S) -> nat, + pub empty: S, + pub epsilon: S, + pub universal: S, + pub nset: spec_fn(bool, Set, S) -> bool, + pub nnot: spec_fn(S) -> S, + pub ncat: spec_fn(Seq) -> S, + pub combo: spec_fn(bool, Set, S) -> bool, + pub succ: spec_fn(S, S) -> bool, + pub lit: spec_fn(S, S) -> bool, + pub prod: spec_fn(S, S) -> bool, +} + +pub open spec fn set_kind(inter: bool) -> Kind { + if inter { Kind::Intersect } else { Kind::Union } +} + +impl Model { + pub open spec fn st(self, x: S) -> bool { (self.state)(x) } + + pub open spec fn k(self, x: S) -> Kind { (self.kind)(x) } + + /// `N(x y)`. + pub open spec fn cat2(self, x: S, y: S) -> S { (self.ncat)(seq![x, y]) } + + pub open spec fn is_set(self, inter: bool, x: S) -> bool { self.k(x) == set_kind(inter) } + + pub open spec fn is_const(self, x: S) -> bool { + x == self.empty || x == self.epsilon || x == self.universal + } + + pub open spec fn is_test(self, x: S) -> bool { self.st(x) && self.k(x) == Kind::Test } + + /// Constants and tests. + pub open spec fn base_kind(self, x: S) -> bool { + self.k(x) == Kind::Empty || self.k(x) == Kind::Epsilon || self.k(x) == Kind::Universal + || self.k(x) == Kind::Test + } + + /// Union (`inter == false`) or intersection operands of a state; a state of another kind is + /// its own only operand. + pub open spec fn sops(self, inter: bool, x: S) -> Set { + if self.is_set(inter, x) { (self.ops)(x) } else { set![x] } + } + + /// `o ∈ ops₊(X)` (resp. `ops_&(X)`). + pub open spec fn in_sops_of(self, inter: bool, xs: Set, o: S) -> bool { + exists|x: S| xs.contains(x) && #[trigger] self.sops(inter, x).contains(o) + } + + /// A possible list element: neither a concatenation, nor `ε`, nor `∅`. + pub open spec fn atom(self, x: S) -> bool { + self.st(x) && self.k(x) != Kind::List && x != self.epsilon && x != self.empty + } + + pub open spec fn states(self, xs: Seq) -> bool { + forall|i: int| 0 <= i < xs.len() ==> self.st(#[trigger] xs[i]) + } + + pub open spec fn atoms(self, xs: Seq) -> bool { + forall|i: int| 0 <= i < xs.len() ==> self.atom(#[trigger] xs[i]) + } + + /// Contribution of one factor to a flattened concatenation. + pub open spec fn piece(self, x: S) -> Seq { + if self.k(x) == Kind::List { (self.elems)(x) } else if x == self.epsilon { seq![] } else { seq![x] } + } + + pub open spec fn flat(self, xs: Seq) -> Seq + decreases xs.len(), + { + if xs.len() == 0 { seq![] } else { self.flat(xs.drop_last()) + self.piece(xs.last()) } + } + + pub open spec fn has_empty(self, xs: Seq) -> bool { + exists|i: int| 0 <= i < xs.len() && xs[i] == self.empty + } + + // ----- (N0)–(N5) ----- + + /// (N0) constants. + pub open spec fn constants_ok(self) -> bool { + &&& self.st(self.empty) && self.k(self.empty) == Kind::Empty + &&& self.st(self.epsilon) && self.k(self.epsilon) == Kind::Epsilon + &&& self.st(self.universal) && self.k(self.universal) == Kind::Universal + &&& forall|x: S| self.st(x) && #[trigger] self.k(x) == Kind::Empty ==> x == self.empty + &&& forall|x: S| self.st(x) && #[trigger] self.k(x) == Kind::Epsilon ==> x == self.epsilon + &&& forall|x: S| self.st(x) && #[trigger] self.k(x) == Kind::Universal ==> x == self.universal + } + + /// (N0) sub-nodes of states are smaller states; list elements are atoms. + pub open spec fn substates_ok(self) -> bool { + &&& forall|x: S, o: S| self.st(x) && (self.k(x) == Kind::Union || self.k(x) == Kind::Intersect) + && #[trigger] (self.ops)(x).contains(o) ==> self.st(o) && (self.size)(o) < (self.size)(x) + &&& forall|x: S| self.st(x) && (self.k(x) == Kind::Not || self.k(x) == Kind::Star) + ==> self.st(#[trigger] (self.body)(x)) && (self.size)((self.body)(x)) < (self.size)(x) + &&& forall|x: S| self.st(x) && self.k(x) == Kind::List ==> { + let es = #[trigger] (self.elems)(x); + es.len() >= 2 && forall|i: int| 0 <= i < es.len() + ==> self.atom(#[trigger] es[i]) && (self.size)(es[i]) < (self.size)(x) + } + } + + /// (N0) constructors applied to the parts of a list or complement state return it unchanged. + pub open spec fn fixpoints_ok(self) -> bool { + &&& forall|x: S| self.st(x) && self.k(x) == Kind::List ==> (self.ncat)(#[trigger] (self.elems)(x)) == x + &&& forall|x: S| self.st(x) && self.k(x) == Kind::Not ==> (self.nnot)(#[trigger] (self.body)(x)) == x + } + + /// `o` combines tests `ts` drawn from `ops₊(X)` (resp. `ops_&(X)`). + pub open spec fn combo_from(self, inter: bool, xs: Set, ts: Set, o: S) -> bool { + &&& forall|t: S| ts.contains(t) ==> self.is_test(t) && self.in_sops_of(inter, xs, t) + &&& (self.combo)(inter, ts, o) + } + + /// (N1)/(N2) for one operand set and one output `u`. + pub open spec fn nset_shape(self, inter: bool, xs: Set, u: S) -> bool { + &&& self.st(u) + &&& self.is_const(u) || forall|o: S| #[trigger] self.sops(inter, u).contains(o) ==> + self.in_sops_of(inter, xs, o) + || (self.is_test(o) && exists|ts: Set| #[trigger] self.combo_from(inter, xs, ts, o)) + } + + /// The set `g` contains every union (`inter == false`) or intersection state whose operands lie in `f`. + pub open spec fn set_states_within(self, inter: bool, f: Set, g: Set) -> bool { + forall|x: S| self.st(x) && self.is_set(inter, x) && (self.ops)(x).subset_of(f) ==> #[trigger] g.contains(x) + } + + pub open spec fn has_set_bound(self, inter: bool, f: Set) -> bool { + exists|g: Set| #[trigger] self.set_states_within(inter, f, g) + } + + /// (N1)/(N2): every output has the shape above, and finitely many union (intersection) states + /// have their operands in a given finite set. + pub open spec fn nset_ok(self) -> bool { + &&& forall|inter: bool, xs: Set, u: S| (forall|x: S| xs.contains(x) ==> self.st(x)) + && #[trigger] (self.nset)(inter, xs, u) ==> self.nset_shape(inter, xs, u) + &&& forall|inter: bool, f: Set| #[trigger] self.has_set_bound(inter, f) + } + + /// (N3). + pub open spec fn not_shape(self, x: S) -> bool { + let r = (self.nnot)(x); + &&& self.st(r) + &&& self.is_const(r) || (self.k(x) == Kind::Not && r == (self.body)(x)) + || (self.k(r) == Kind::Not && (self.body)(r) == x) + } + + pub open spec fn not_ok(self) -> bool { + forall|x: S| self.st(x) ==> #[trigger] self.not_shape(x) + } + + /// (N4): `N(x₁⋯xₖ)` absorbs `∅`, flattens, drops `ε`, and returns `ε`, a single state, or a + /// list of the flattened factors. + pub open spec fn cat_shape(self, xs: Seq) -> bool { + let r = (self.ncat)(xs); + let f = self.flat(xs); + &&& self.st(r) + &&& if self.has_empty(xs) { r == self.empty } else if f.len() == 0 { r == self.epsilon } + else if f.len() == 1 { r == f[0] } else { self.k(r) == Kind::List && (self.elems)(r) == f } + } + + pub open spec fn cat_ok(self) -> bool { + forall|xs: Seq| self.states(xs) ==> #[trigger] self.cat_shape(xs) + } + + /// A finite set of tests containing `ts` and closed under the combinations of (N1)/(N2). + pub open spec fn closure_for(self, inter: bool, ts: ISet, c: ISet) -> bool { + &&& c.finite() + &&& ts.subset_of(c) + &&& forall|t: S| c.contains(t) ==> self.is_test(t) + &&& forall|us: Set, t: S| (forall|u: S| us.contains(u) ==> c.contains(u)) + && #[trigger] (self.combo)(inter, us, t) ==> c.contains(t) + } + + pub open spec fn has_closure(self, inter: bool, ts: ISet) -> bool { + exists|c: ISet| #[trigger] self.closure_for(inter, ts, c) + } + + /// (N5). + pub open spec fn tests_ok(self) -> bool { + forall|inter: bool, ts: ISet| ts.finite() && (forall|t: S| ts.contains(t) ==> self.is_test(t)) + ==> #[trigger] self.has_closure(inter, ts) + } + + /// `u` contains every output of `N(ΣX)` (`N(&X)`) for every finite `X ⊆ u`. + pub open spec fn nset_closed(self, inter: bool, u: ISet) -> bool { + forall|xs: Set, v: S| (forall|x: S| xs.contains(x) ==> u.contains(x)) && #[trigger] (self.nset)(inter, xs, v) + ==> u.contains(v) + } + + pub open spec fn has_consts(self, u: ISet) -> bool { + u.contains(self.empty) && u.contains(self.epsilon) && u.contains(self.universal) + } + + /// `v` is obtained from the constants and the states satisfying `base` by normalized unions + /// (`inter == false`) or intersections: it lies in every set that contains them and is closed + /// under `N(Σ·)` (`N(&·)`). This covers every bracketing and the merging of leaves. + pub open spec fn built(self, inter: bool, base: spec_fn(S) -> bool, v: S) -> bool { + forall|u: ISet| self.has_consts(u) && (forall|w: S| #[trigger] base(w) ==> u.contains(w)) + && self.nset_closed(inter, u) ==> #[trigger] u.contains(v) + } + + // ----- successor equations (S0)–(S6) ----- + + /// A literal of an operand. + pub open spec fn ops_lit(self, p: S, w: S) -> bool { + exists|o: S| (self.ops)(p).contains(o) && #[trigger] (self.lit)(o, w) + } + + /// The complement `N(¬ℓ)` of a literal `ℓ` of the body. + pub open spec fn not_lit(self, p: S, w: S) -> bool { + exists|l: S| #[trigger] (self.lit)((self.body)(p), l) && w == (self.nnot)(l) + } + + /// `N(v p)` for a product `v` of the body of the star `p`. + pub open spec fn star_lit(self, p: S, w: S) -> bool { + exists|a: S| #[trigger] (self.prod)((self.body)(p), a) && w == self.cat2(a, p) + } + + /// `N(v yᵢ₊₁⋯yₖ)` for a product `v` of a non-final element `yᵢ` of the list `p`, or a literal + /// of its final element (the nullability guards are left open). + pub open spec fn list_lit(self, p: S, w: S) -> bool { + let es = (self.elems)(p); + (exists|i: int, a: S| 0 <= i < es.len() - 1 && #[trigger] (self.prod)(es[i], a) + && w == (self.ncat)(seq![a] + es.skip(i + 1))) + || (self.lit)(es.last(), w) + } + + /// (S0), (S1). + pub open spec fn succ_shape(self, p: S, v: S) -> bool { + if self.base_kind(p) { self.is_const(v) } else { self.built(false, |w: S| (self.prod)(p, w), v) } + } + + /// (S1)–(S6) for literals. + pub open spec fn lit_shape(self, p: S, v: S) -> bool { + if self.base_kind(p) { + self.is_const(v) + } else if self.k(p) == Kind::Union { + self.built(false, |w: S| self.ops_lit(p, w), v) + } else if self.k(p) == Kind::Intersect { + self.built(true, |w: S| self.ops_lit(p, w), v) + } else if self.k(p) == Kind::Not { + self.built(true, |w: S| self.not_lit(p, w), v) + } else if self.k(p) == Kind::Star { + self.built(false, |w: S| self.star_lit(p, w), v) + } else { + self.built(false, |w: S| self.list_lit(p, w), v) + } + } + + /// (S1)–(S6) for products. + pub open spec fn prod_shape(self, p: S, v: S) -> bool { + if self.base_kind(p) { + self.is_const(v) + } else if self.k(p) == Kind::Union { + (exists|o: S| (self.ops)(p).contains(o) && #[trigger] (self.prod)(o, v)) || (self.lit)(p, v) + } else if self.k(p) == Kind::Intersect || self.k(p) == Kind::Not { + self.built(true, |w: S| (self.lit)(p, w), v) + } else if self.k(p) == Kind::Star { + (self.lit)(p, v) + } else { + (self.lit)(p, v) || (self.prod)((self.elems)(p).last(), v) + } + } + + pub open spec fn succ_ok(self) -> bool { + &&& forall|p: S, v: S| self.st(p) && #[trigger] (self.succ)(p, v) ==> self.st(v) && self.succ_shape(p, v) + &&& forall|p: S, v: S| self.st(p) && #[trigger] (self.lit)(p, v) ==> self.st(v) && self.lit_shape(p, v) + &&& forall|p: S, v: S| self.st(p) && #[trigger] (self.prod)(p, v) ==> self.st(v) && self.prod_shape(p, v) + } + + /// Language-independent structural contract: (N0)–(N5) and the successor equations (S0)–(S6), + /// named in the table of `refinement/finiteness.rs`. + pub open spec fn contract(self) -> bool { + &&& self.constants_ok() + &&& self.substates_ok() + &&& self.fixpoints_ok() + &&& self.nset_ok() + &&& self.not_ok() + &&& self.cat_ok() + &&& self.tests_ok() + &&& self.succ_ok() + } + + // ----- invariants (C1)–(C4) ----- + + pub open spec fn r_states(self, r: ISet) -> bool { + forall|p: S| r.contains(p) ==> self.st(p) + } + + /// Successors of members of `r` lie in `r`. + pub open spec fn r_closed(self, r: ISet) -> bool { + forall|p: S, v: S| r.contains(p) && #[trigger] (self.succ)(p, v) ==> r.contains(v) + } + + /// (C2) relative to a target set `u` (`good` uses `u == y`): successors, literals, and + /// products of members of `y` lie in `u`. + pub open spec fn vals_into(self, y: ISet, u: ISet) -> bool { + &&& forall|p: S, v: S| y.contains(p) && #[trigger] (self.succ)(p, v) ==> u.contains(v) + &&& forall|p: S, v: S| y.contains(p) && #[trigger] (self.lit)(p, v) ==> u.contains(v) + &&& forall|p: S, v: S| y.contains(p) && #[trigger] (self.prod)(p, v) ==> u.contains(v) + } + + /// (C3) + pub open spec fn r_ops(self, r: ISet) -> bool { + &&& forall|p: S, o: S| r.contains(p) && (self.k(p) == Kind::Union || self.k(p) == Kind::Intersect) + && #[trigger] (self.ops)(p).contains(o) ==> r.contains(o) + &&& forall|p: S| r.contains(p) && self.k(p) == Kind::Not ==> r.contains(#[trigger] (self.body)(p)) + } + + /// (C4) for one list `p` relative to a target set `u`: `N(v yᵢ₊₁⋯yₖ)` for the products `v` + /// of each element `yᵢ`. + pub open spec fn list_in(self, p: S, u: ISet) -> bool { + forall|i: int, a: S| 0 <= i < (self.elems)(p).len() && #[trigger] (self.prod)((self.elems)(p)[i], a) + ==> u.contains((self.ncat)(seq![a] + (self.elems)(p).skip(i + 1))) + } + + /// (C4) relative to a target set `u` (`good` uses `u == r`). + pub open spec fn r_lists_in(self, r: ISet, u: ISet) -> bool { + forall|p: S| r.contains(p) && self.k(p) == Kind::List ==> #[trigger] self.list_in(p, u) + } + + /// (C1)–(C4), named in the table of `refinement/finiteness.rs`. + pub open spec fn good(self, r: ISet, q: S) -> bool { + &&& r.finite() + &&& r.contains(q) && self.has_consts(r) + &&& self.r_states(r) + &&& self.vals_into(r, r) + &&& self.r_ops(r) + &&& self.r_lists_in(r, r) + } + + pub open spec fn rset(self, q: S) -> ISet { + choose|r: ISet| self.good(r, q) + } + + // ----- U(Y), U_&(Y), and U(U_&(Y)) ----- + + pub open spec fn tests_in(self, y: ISet) -> ISet { + y.filter(|x: S| self.is_test(x)) + } + + pub open spec fn tclosure(self, inter: bool, y: ISet) -> ISet { + choose|c: ISet| self.closure_for(inter, self.tests_in(y), c) + } + + /// `Y^∨` (resp. `Y^∧`). + pub open spec fn yv(self, inter: bool, y: ISet) -> ISet { + ISet::new(|x: S| y.contains(x) || self.is_const(x) || self.tclosure(inter, y).contains(x)) + } + + pub open spec fn ops_in(self, x: S, s: ISet) -> bool { + forall|o: S| #[trigger] (self.ops)(x).contains(o) ==> s.contains(o) + } + + /// `U(Y)` for `inter == false`, `U_&(Y)` for `inter == true`. + pub open spec fn uset(self, inter: bool, y: ISet) -> ISet { + ISet::new(|x: S| self.yv(inter, y).contains(x) + || (self.st(x) && self.is_set(inter, x) && self.ops_in(x, self.yv(inter, y)))) + } + + /// `U(U_&(Y))`. + pub open spec fn dnf(self, y: ISet) -> ISet { + self.uset(false, self.uset(true, y)) + } + + /// `Y` is finite, consists of states, and contains the operands of its members. + pub open spec fn y_ok(self, inter: bool, y: ISet) -> bool { + &&& y.finite() + &&& self.r_states(y) + &&& forall|p: S, o: S| y.contains(p) && self.is_set(inter, p) && #[trigger] (self.ops)(p).contains(o) + ==> y.contains(o) + } + + // ----- lists ----- + + /// `s_j = N(c_{j+1}⋯c_m)` in the list case. + pub open spec fn suffix(self, c: Seq, j: int) -> S { + (self.ncat)(c.skip(j + 1)) + } + + /// `T` in the list case. + pub open spec fn list_terms(self, c: Seq) -> ISet { + ISet::new(|y: S| exists|j: int, x: S| 0 <= j < c.len() && self.rset(c[j]).contains(x) + && y == #[trigger] self.cat2(x, self.suffix(c, j))) + } + + /// `T` in the star case. + pub open spec fn star_terms(self, q: S) -> ISet { + self.rset((self.body)(q)).map(|x: S| self.cat2(x, q)) + } + + /// `Y = ⋃ᵢ C(oᵢ)` in the union and intersection cases. + pub open spec fn ops_union(self, q: S) -> ISet { + ISet::new(|x: S| exists|o: S| (self.ops)(q).contains(o) && #[trigger] self.rset(o).contains(x)) + } +} + +/// States reachable from `q0` in `n` successor steps (over all valuations and events). +pub open spec fn reachable(m: Model, q0: S, n: nat, q: S) -> bool + decreases n, +{ + if n == 0 { q == q0 } else { exists|p: S| reachable(m, q0, (n - 1) as nat, p) && #[trigger] (m.succ)(p, q) } +} + +// ===== finiteness utilities ===== + +pub proof fn lemma_powerset_finite(f: Set) + ensures ISet::new(|s: Set| s.subset_of(f)).finite(), + decreases f.len(), +{ + let p = ISet::new(|s: Set| s.subset_of(f)); + if f.len() == 0 { + f.lemma_len0_is_empty(); + assert(p =~= ISet::empty().insert(Set::::empty())) by { + assert forall|s: Set| p.contains(s) implies s == Set::::empty() by { + assert(s =~= Set::::empty()); + } + } + } else { + let x = f.choose(); + assert(f.contains(x)) by { lemma_set_empty_equivalency_len(f); } + let g = f.remove(x); + lemma_powerset_finite(g); + let pg = ISet::new(|s: Set| s.subset_of(g)); + let ins = |s: Set| s.insert(x); + pg.lemma_map_finite(ins); + assert(p.subset_of(pg.union(pg.map(ins)))) by { + assert forall|s: Set| p.contains(s) implies pg.union(pg.map(ins)).contains(s) by { + if s.contains(x) { + let s0 = s.remove(x); + assert(pg.contains(s0)); + assert(s0.insert(x) =~= s); + assert(pg.map(ins).contains(s)); + } else { + assert(pg.contains(s)); + } + } + } + lemma_iset_subset_finite(pg.union(pg.map(ins)), p); + } +} + +pub proof fn lemma_big_union_finite(idx: Set, f: spec_fn(I) -> ISet) + requires forall|i: I| idx.contains(i) ==> #[trigger] f(i).finite(), + ensures ISet::new(|x: A| exists|i: I| idx.contains(i) && #[trigger] f(i).contains(x)).finite(), + decreases idx.len(), +{ + let u = ISet::new(|x: A| exists|i: I| idx.contains(i) && #[trigger] f(i).contains(x)); + if idx.len() == 0 { + idx.lemma_len0_is_empty(); + assert(u =~= ISet::::empty()); + } else { + let i0 = idx.choose(); + assert(idx.contains(i0)) by { lemma_set_empty_equivalency_len(idx); } + let rest = idx.remove(i0); + lemma_big_union_finite(rest, f); + let ur = ISet::new(|x: A| exists|i: I| rest.contains(i) && #[trigger] f(i).contains(x)); + assert(u =~= ur.union(f(i0))) by { + assert forall|x: A| u.contains(x) implies ur.union(f(i0)).contains(x) by { + let i = choose|i: I| idx.contains(i) && #[trigger] f(i).contains(x); + if i != i0 { assert(rest.contains(i)); } + } + } + } +} + +// ===== U(Y) ===== + +pub proof fn lemma_tclosure(m: Model, inter: bool, y: ISet) + requires m.contract(), y.finite(), + ensures m.closure_for(inter, m.tests_in(y), m.tclosure(inter, y)), +{ + let ts = m.tests_in(y); + lemma_iset_subset_finite(y, ts); + assert forall|t: S| ts.contains(t) implies m.is_test(t) by {} + assert(m.has_closure(inter, ts)); +} + +pub proof fn lemma_yv(m: Model, inter: bool, y: ISet) + requires m.contract(), m.y_ok(inter, y), + ensures + m.yv(inter, y).finite(), + m.r_states(m.yv(inter, y)), + forall|x: S| m.yv(inter, y).contains(x) && m.is_test(x) ==> #[trigger] m.tclosure(inter, y).contains(x), + forall|x: S| m.yv(inter, y).contains(x) && m.is_set(inter, x) ==> #[trigger] y.contains(x), + forall|x: S| #[trigger] m.yv(inter, y).contains(x) ==> y.contains(x) || m.is_const(x) || m.is_test(x), +{ + lemma_tclosure(m, inter, y); + let c = m.tclosure(inter, y); + let consts = ISet::empty().insert(m.empty).insert(m.epsilon).insert(m.universal); + assert(m.yv(inter, y) =~= y.union(consts).union(c)); + assert forall|x: S| m.yv(inter, y).contains(x) && m.is_test(x) implies #[trigger] c.contains(x) by { + if y.contains(x) { assert(m.tests_in(y).contains(x)); } + } +} + +pub proof fn lemma_uset_basic(m: Model, inter: bool, y: ISet) + requires m.contract(), m.y_ok(inter, y), + ensures + m.uset(inter, y).finite(), + m.r_states(m.uset(inter, y)), + y.subset_of(m.uset(inter, y)), + m.uset(inter, y).contains(m.empty), m.uset(inter, y).contains(m.epsilon), + m.uset(inter, y).contains(m.universal), + forall|x: S| m.uset(inter, y).contains(x) && !m.is_set(inter, x) ==> #[trigger] m.yv(inter, y).contains(x), +{ + lemma_yv(m, inter, y); + let yv = m.yv(inter, y); + let fy = Set::new_from_iset(yv).unwrap(); + assert(fy.to_iset() == yv); + assert(m.has_set_bound(inter, fy)); + let g = choose|g: Set| #[trigger] m.set_states_within(inter, fy, g); + let sets = ISet::new(|x: S| m.st(x) && m.is_set(inter, x) && m.ops_in(x, yv)); + assert(sets.subset_of(g.to_iset())) by { + assert forall|x: S| sets.contains(x) implies g.to_iset().contains(x) by { + let s = (m.ops)(x); + assert(s.subset_of(fy)) by { + assert forall|o: S| s.contains(o) implies fy.contains(o) by { assert(m.ops_in(x, yv)); } + } + assert(g.contains(x)); + } + } + vstd::set::lemma_to_iset_finite(g); + lemma_iset_subset_finite(g.to_iset(), sets); + assert(m.uset(inter, y) =~= yv.union(sets)); +} + +/// Operands of members of `X ⊆ U(Y)` lie in `Y^∨`. +pub proof fn lemma_uset_sops(m: Model, inter: bool, y: ISet, xs: Set) + requires + m.contract(), m.y_ok(inter, y), + forall|x: S| xs.contains(x) ==> m.uset(inter, y).contains(x), + ensures forall|o: S| m.in_sops_of(inter, xs, o) ==> #[trigger] m.yv(inter, y).contains(o), +{ + lemma_uset_basic(m, inter, y); + lemma_yv(m, inter, y); + assert forall|o: S| m.in_sops_of(inter, xs, o) implies #[trigger] m.yv(inter, y).contains(o) by { + let x = choose|x: S| xs.contains(x) && #[trigger] m.sops(inter, x).contains(o); + assert(m.uset(inter, y).contains(x)); + if m.is_set(inter, x) { + if m.yv(inter, y).contains(x) { + assert(y.contains(x)); + assert((m.ops)(x).contains(o)); + } else { + assert(m.ops_in(x, m.yv(inter, y))); + assert((m.ops)(x).contains(o)); + } + } else { + assert(o == x); + } + } +} + +/// `U(Y)` is closed under normalized unions (intersections) of its members. +pub proof fn lemma_uset_nset(m: Model, inter: bool, y: ISet, xs: Set, u: S) + requires + m.contract(), m.y_ok(inter, y), + forall|x: S| xs.contains(x) ==> m.uset(inter, y).contains(x), + (m.nset)(inter, xs, u), + ensures m.uset(inter, y).contains(u), +{ + lemma_uset_basic(m, inter, y); + lemma_yv(m, inter, y); + lemma_uset_sops(m, inter, y, xs); + lemma_tclosure(m, inter, y); + let yv = m.yv(inter, y); + let c = m.tclosure(inter, y); + assert forall|x: S| xs.contains(x) implies m.st(x) by {} + assert(m.nset_ok()); + assert(m.nset_shape(inter, xs, u)); + if !m.is_const(u) { + assert forall|o: S| #[trigger] m.sops(inter, u).contains(o) implies yv.contains(o) by { + if !m.in_sops_of(inter, xs, o) { + let ts = choose|ts: Set| #[trigger] m.combo_from(inter, xs, ts, o); + assert(m.combo_from(inter, xs, ts, o)); + assert forall|t: S| ts.contains(t) implies c.contains(t) by { + assert(m.is_test(t) && m.in_sops_of(inter, xs, t)); + assert(m.yv(inter, y).contains(t)); + } + assert(c.contains(o)); + } + } + if m.is_set(inter, u) { + assert(m.ops_in(u, yv)) by { + assert forall|o: S| #[trigger] (m.ops)(u).contains(o) implies yv.contains(o) by { + assert(m.sops(inter, u).contains(o)); + } + } + } else { + assert(m.sops(inter, u).contains(u)); + } + } +} + +pub proof fn lemma_uset_nset_closed(m: Model, inter: bool, y: ISet) + requires m.contract(), m.y_ok(inter, y), + ensures m.nset_closed(inter, m.uset(inter, y)), m.has_consts(m.uset(inter, y)), +{ + lemma_uset_basic(m, inter, y); + assert forall|xs: Set, u: S| (forall|x: S| xs.contains(x) ==> m.uset(inter, y).contains(x)) + && #[trigger] (m.nset)(inter, xs, u) implies m.uset(inter, y).contains(u) by { + lemma_uset_nset(m, inter, y, xs, u); + } +} + +/// (S1): constants and tests have constant successors, literals, and products. +pub proof fn lemma_base_vals(m: Model, p: S) + requires m.contract(), m.st(p), m.base_kind(p), + ensures + forall|v: S| #[trigger] (m.succ)(p, v) ==> m.is_const(v), + forall|v: S| #[trigger] (m.lit)(p, v) ==> m.is_const(v), + forall|v: S| #[trigger] (m.prod)(p, v) ==> m.is_const(v), +{ + assert forall|v: S| #[trigger] (m.succ)(p, v) implies m.is_const(v) by { assert(m.succ_shape(p, v)); } + assert forall|v: S| #[trigger] (m.lit)(p, v) implies m.is_const(v) by { assert(m.lit_shape(p, v)); } + assert forall|v: S| #[trigger] (m.prod)(p, v) implies m.is_const(v) by { assert(m.prod_shape(p, v)); } +} + +/// Members of `Y^∨` outside `Y` are constants or tests. +pub proof fn lemma_yv_base(m: Model, inter: bool, y: ISet, p: S) + requires m.contract(), m.y_ok(inter, y), m.yv(inter, y).contains(p), !y.contains(p), + ensures m.st(p), m.base_kind(p), +{ + lemma_yv(m, inter, y); + if m.is_const(p) { + assert(m.constants_ok()); + } else { + assert(m.is_test(p)); + } +} + +/// Successor closure: (C2) for `U(Y)` from (C2) for `Y`. +pub proof fn lemma_uset_closed(m: Model, y: ISet) + requires m.contract(), m.y_ok(false, y), m.vals_into(y, m.uset(false, y)), + ensures m.vals_into(m.uset(false, y), m.uset(false, y)), +{ + lemma_uset_basic(m, false, y); + lemma_yv(m, false, y); + lemma_uset_nset_closed(m, false, y); + let us = m.uset(false, y); + let yv = m.yv(false, y); + // Members of Y^∨. + assert(m.vals_into(yv, us)) by { + assert forall|p: S, v: S| yv.contains(p) && #[trigger] (m.succ)(p, v) implies us.contains(v) by { + if !y.contains(p) { lemma_yv_base(m, false, y, p); lemma_base_vals(m, p); } + } + assert forall|p: S, v: S| yv.contains(p) && #[trigger] (m.lit)(p, v) implies us.contains(v) by { + if !y.contains(p) { lemma_yv_base(m, false, y, p); lemma_base_vals(m, p); } + } + assert forall|p: S, v: S| yv.contains(p) && #[trigger] (m.prod)(p, v) implies us.contains(v) by { + if !y.contains(p) { lemma_yv_base(m, false, y, p); lemma_base_vals(m, p); } + } + } + // Union states with operands in Y^∨. + assert forall|p: S, v: S| us.contains(p) && #[trigger] (m.lit)(p, v) implies us.contains(v) by { + if !yv.contains(p) { + assert(m.st(p) && m.is_set(false, p) && m.ops_in(p, yv)); + assert(m.lit_shape(p, v)); + assert forall|w: S| m.ops_lit(p, w) implies us.contains(w) by { + let o = choose|o: S| (m.ops)(p).contains(o) && #[trigger] (m.lit)(o, w); + assert(yv.contains(o)); + } + assert(m.built(false, |w: S| m.ops_lit(p, w), v)); + assert(us.contains(v)); + } + } + assert forall|p: S, v: S| us.contains(p) && #[trigger] (m.prod)(p, v) implies us.contains(v) by { + if !yv.contains(p) { + assert(m.st(p) && m.is_set(false, p) && m.ops_in(p, yv)); + assert(m.prod_shape(p, v)); + if !(m.lit)(p, v) { + let o = choose|o: S| (m.ops)(p).contains(o) && #[trigger] (m.prod)(o, v); + assert(yv.contains(o)); + } + } + } + assert forall|p: S, v: S| us.contains(p) && #[trigger] (m.succ)(p, v) implies us.contains(v) by { + if !yv.contains(p) { + assert(m.st(p) && m.is_set(false, p)); + assert(m.succ_shape(p, v)); + assert forall|w: S| (m.prod)(p, w) implies us.contains(w) by {} + assert(m.built(false, |w: S| (m.prod)(p, w), v)); + assert(us.contains(v)); + } + } +} + +/// (C3) for `U(Y)` from (C3) for `Y`. +pub proof fn lemma_uset_ops(m: Model, inter: bool, y: ISet) + requires m.contract(), m.y_ok(inter, y), m.r_ops(y), + ensures m.r_ops(m.uset(inter, y)), +{ + lemma_uset_basic(m, inter, y); + lemma_yv(m, inter, y); + let us = m.uset(inter, y); + let yv = m.yv(inter, y); + assert forall|p: S, o: S| us.contains(p) && (m.k(p) == Kind::Union || m.k(p) == Kind::Intersect) + && #[trigger] (m.ops)(p).contains(o) implies us.contains(o) by { + if y.contains(p) { + } else if yv.contains(p) { + if !m.is_const(p) { assert(m.is_test(p)); } + } else { + assert(m.ops_in(p, yv)); + } + } + assert forall|p: S| us.contains(p) && m.k(p) == Kind::Not implies us.contains(#[trigger] (m.body)(p)) by { + if !y.contains(p) && yv.contains(p) && !m.is_const(p) { assert(m.is_test(p)); } + } +} + +/// The lists of `U(Y)` belong to `Y`, so (C4) carries over. +pub proof fn lemma_uset_lists(m: Model, inter: bool, y: ISet, u: ISet) + requires m.contract(), m.y_ok(inter, y), m.r_lists_in(y, u), + ensures m.r_lists_in(m.uset(inter, y), u), +{ + lemma_uset_basic(m, inter, y); + lemma_yv(m, inter, y); + let us = m.uset(inter, y); + let yv = m.yv(inter, y); + assert forall|p: S| us.contains(p) && m.k(p) == Kind::List implies #[trigger] m.list_in(p, u) by { + assert(yv.contains(p)); + if !y.contains(p) && !m.is_const(p) { assert(m.is_test(p)); } + } +} + +/// `U_&(Y)` contains the union operands of its members, and `U(U_&(Y))` is finite. +pub proof fn lemma_dnf_basic(m: Model, y: ISet) + requires m.contract(), m.y_ok(true, y), m.y_ok(false, y), + ensures + m.y_ok(false, m.uset(true, y)), + y.subset_of(m.uset(true, y)), + m.uset(true, y).subset_of(m.dnf(y)), + m.dnf(y).finite(), m.r_states(m.dnf(y)), m.has_consts(m.dnf(y)), + m.nset_closed(true, m.uset(true, y)), m.has_consts(m.uset(true, y)), + m.nset_closed(false, m.dnf(y)), +{ + lemma_uset_basic(m, true, y); + lemma_yv(m, true, y); + lemma_uset_nset_closed(m, true, y); + let ua = m.uset(true, y); + assert forall|p: S, o: S| ua.contains(p) && m.is_set(false, p) && #[trigger] (m.ops)(p).contains(o) + implies ua.contains(o) by { + assert(m.yv(true, y).contains(p)); + if !y.contains(p) && !m.is_const(p) { assert(m.is_test(p)); } + } + lemma_uset_basic(m, false, ua); + lemma_uset_nset_closed(m, false, ua); +} + +/// Successor closure for `U(U_&(Y))`: if the successors of members of `Y` lie in `U(U_&(Y))` and their +/// literals and products in `U_&(Y)`, then `U(U_&(Y))` satisfies (C2). +pub proof fn lemma_dnf_closed(m: Model, y: ISet) + requires + m.contract(), m.y_ok(true, y), m.y_ok(false, y), + forall|p: S, v: S| y.contains(p) && #[trigger] (m.succ)(p, v) ==> m.dnf(y).contains(v), + forall|p: S, v: S| y.contains(p) && #[trigger] (m.lit)(p, v) ==> m.uset(true, y).contains(v), + forall|p: S, v: S| y.contains(p) && #[trigger] (m.prod)(p, v) ==> m.uset(true, y).contains(v), + ensures m.vals_into(m.dnf(y), m.dnf(y)), +{ + lemma_dnf_basic(m, y); + lemma_yv(m, true, y); + let ua = m.uset(true, y); + let d = m.dnf(y); + let yv = m.yv(true, y); + // Literals and products of members of U_&(Y) lie in U_&(Y). + assert forall|p: S, v: S| ua.contains(p) && #[trigger] (m.lit)(p, v) implies ua.contains(v) by { + if y.contains(p) { + } else if yv.contains(p) { + lemma_yv_base(m, true, y, p); + lemma_base_vals(m, p); + } else { + assert(m.st(p) && m.is_set(true, p) && m.ops_in(p, yv)); + assert(m.lit_shape(p, v)); + assert forall|w: S| m.ops_lit(p, w) implies ua.contains(w) by { + let o = choose|o: S| (m.ops)(p).contains(o) && #[trigger] (m.lit)(o, w); + assert(yv.contains(o)); + if !y.contains(o) { lemma_yv_base(m, true, y, o); lemma_base_vals(m, o); } + } + assert(m.built(true, |w: S| m.ops_lit(p, w), v)); + assert(ua.contains(v)); + } + } + assert forall|p: S, v: S| ua.contains(p) && #[trigger] (m.prod)(p, v) implies ua.contains(v) by { + if y.contains(p) { + } else if yv.contains(p) { + lemma_yv_base(m, true, y, p); + lemma_base_vals(m, p); + } else { + assert(m.st(p) && m.is_set(true, p)); + assert(m.prod_shape(p, v)); + assert forall|w: S| (m.lit)(p, w) implies ua.contains(w) by {} + assert(m.built(true, |w: S| (m.lit)(p, w), v)); + assert(ua.contains(v)); + } + } + assert forall|p: S, v: S| ua.contains(p) && #[trigger] (m.succ)(p, v) implies d.contains(v) by { + if y.contains(p) { + } else if yv.contains(p) { + lemma_yv_base(m, true, y, p); + lemma_base_vals(m, p); + } else { + assert(m.st(p) && m.is_set(true, p)); + assert(m.succ_shape(p, v)); + assert forall|w: S| (m.prod)(p, w) implies d.contains(w) by { assert(ua.contains(w)); } + assert(m.built(false, |w: S| (m.prod)(p, w), v)); + assert(d.contains(v)); + } + } + lemma_uset_closed(m, ua); +} + +// ===== concatenation ===== + +pub proof fn lemma_flat_append(m: Model, xs: Seq, ys: Seq) + ensures m.flat(xs + ys) == m.flat(xs) + m.flat(ys), + decreases ys.len(), +{ + if ys.len() == 0 { + assert(xs + ys =~= xs); + assert(m.flat(xs) + m.flat(ys) =~= m.flat(xs)); + } else { + assert((xs + ys).drop_last() =~= xs + ys.drop_last()); + assert((xs + ys).last() == ys.last()); + lemma_flat_append(m, xs, ys.drop_last()); + assert(m.flat(xs + ys) =~= m.flat(xs) + m.flat(ys)); + } +} + +pub proof fn lemma_flat_single(m: Model, x: S) + ensures m.flat(seq![x]) == m.piece(x), +{ + assert(seq![x].drop_last() =~= Seq::::empty()); + assert(m.flat(Seq::::empty()) + m.piece(x) =~= m.piece(x)); +} + +pub proof fn lemma_flat_atoms(m: Model, xs: Seq) + requires m.atoms(xs), + ensures m.flat(xs) == xs, + decreases xs.len(), +{ + if xs.len() > 0 { + assert(m.atoms(xs.drop_last())); + lemma_flat_atoms(m, xs.drop_last()); + assert(m.atom(xs.last())); + assert(xs.drop_last() + seq![xs.last()] =~= xs); + } +} + +/// Without `∅`, the flattening of states consists of atoms. +pub proof fn lemma_flat_atoms_of(m: Model, xs: Seq) + requires m.contract(), m.states(xs), !m.has_empty(xs), + ensures m.atoms(m.flat(xs)), + decreases xs.len(), +{ + if xs.len() > 0 { + let init = xs.drop_last(); + let x = xs.last(); + assert(!m.has_empty(init)) by { + if m.has_empty(init) { + let i = choose|i: int| 0 <= i < init.len() && init[i] == m.empty; + assert(xs[i] == m.empty); + } + } + lemma_flat_atoms_of(m, init); + assert(m.st(x)); + assert(x != m.empty) by { assert(xs[xs.len() - 1] == x); } + assert(m.atoms(m.piece(x))) by { + if m.k(x) == Kind::List { + let es = (m.elems)(x); + assert forall|i: int| 0 <= i < es.len() implies m.atom(#[trigger] es[i]) by {} + } + } + let f = m.flat(xs); + assert(f == m.flat(init) + m.piece(x)); + assert forall|i: int| 0 <= i < f.len() implies m.atom(#[trigger] f[i]) by { + if i < m.flat(init).len() { + assert(f[i] == m.flat(init)[i]); + } else { + assert(f[i] == m.piece(x)[i - m.flat(init).len()]); + } + } + } +} + +pub proof fn lemma_list_unique(m: Model, a: S, b: S) + requires m.contract(), m.st(a), m.st(b), m.k(a) == Kind::List, m.k(b) == Kind::List, + (m.elems)(a) == (m.elems)(b), + ensures a == b, +{ + assert((m.ncat)((m.elems)(a)) == a); + assert((m.ncat)((m.elems)(b)) == b); +} + +/// Without `∅`, `N(xs)` is not `∅` and contributes exactly the flattening of `xs`. +pub proof fn lemma_cat_piece(m: Model, xs: Seq) + requires m.contract(), m.states(xs), !m.has_empty(xs), + ensures + (m.ncat)(xs) != m.empty, + m.st((m.ncat)(xs)), + m.piece((m.ncat)(xs)) == m.flat(xs), +{ + assert(m.cat_shape(xs)); + lemma_flat_atoms_of(m, xs); + let f = m.flat(xs); + let r = (m.ncat)(xs); + if f.len() == 0 { + assert(m.piece(r) =~= f); + } else if f.len() == 1 { + assert(m.atom(f[0])); + assert(m.piece(r) =~= f); + } else { + assert(m.k(r) == Kind::List); + } +} + +/// `N` depends only on the flattening, once `∅` is excluded. +pub proof fn lemma_cat_flat_eq(m: Model, xs: Seq, ys: Seq) + requires m.contract(), m.states(xs), m.states(ys), !m.has_empty(xs), !m.has_empty(ys), + m.flat(xs) == m.flat(ys), + ensures (m.ncat)(xs) == (m.ncat)(ys), +{ + assert(m.cat_shape(xs)); + assert(m.cat_shape(ys)); + if m.flat(xs).len() >= 2 { + lemma_list_unique(m, (m.ncat)(xs), (m.ncat)(ys)); + } +} + +pub proof fn lemma_no_empty_pair(m: Model, x: S, y: S) + requires x != m.empty, y != m.empty, + ensures !m.has_empty(seq![x, y]), +{ + if m.has_empty(seq![x, y]) { + let i = choose|i: int| 0 <= i < 2 && seq![x, y][i] == m.empty; + assert(i == 0 || i == 1); + } +} + +pub proof fn lemma_no_empty_atoms(m: Model, xs: Seq) + requires m.atoms(xs), + ensures !m.has_empty(xs), m.states(xs), +{ + if m.has_empty(xs) { + let i = choose|i: int| 0 <= i < xs.len() && xs[i] == m.empty; + assert(m.atom(xs[i])); + } + assert forall|i: int| 0 <= i < xs.len() implies m.st(#[trigger] xs[i]) by { assert(m.atom(xs[i])); } +} + +pub proof fn lemma_cat_single(m: Model, x: S) + requires m.contract(), m.st(x), + ensures (m.ncat)(seq![x]) == x, +{ + let xs = seq![x]; + assert(m.states(xs)); + assert(m.cat_shape(xs)); + lemma_flat_single(m, x); + if x == m.empty { + assert(xs[0] == m.empty); + } else { + assert(!m.has_empty(xs)) by { + if m.has_empty(xs) { let i = choose|i: int| 0 <= i < xs.len() && xs[i] == m.empty; } + } + if m.k(x) == Kind::List { + assert((m.elems)(x).len() >= 2); + lemma_list_unique(m, (m.ncat)(xs), x); + } + } +} + +/// A sequence of atoms normalizes to its single element or to the list of its elements. +pub proof fn lemma_cat_atoms(m: Model, zs: Seq) + requires m.contract(), m.atoms(zs), zs.len() >= 1, + ensures + zs.len() == 1 ==> (m.ncat)(zs) == zs[0], + zs.len() >= 2 ==> m.k((m.ncat)(zs)) == Kind::List && (m.elems)((m.ncat)(zs)) == zs, + m.st((m.ncat)(zs)), (m.ncat)(zs) != m.empty, +{ + lemma_no_empty_atoms(m, zs); + lemma_flat_atoms(m, zs); + assert(m.cat_shape(zs)); + assert(m.atom(zs[0])); +} + +/// `N(a z w) = N(N(a z) N(w))` for a state `a` and sequences of atoms `z`, `w`. +pub proof fn lemma_cat_assoc(m: Model, a: S, z: Seq, w: Seq) + requires m.contract(), m.st(a), m.atoms(z), m.atoms(w), + ensures (m.ncat)(seq![a] + z + w) == m.cat2((m.ncat)(seq![a] + z), (m.ncat)(w)), +{ + lemma_no_empty_atoms(m, z); + lemma_no_empty_atoms(m, w); + let az = seq![a] + z; + let azw = seq![a] + z + w; + assert(m.states(az)) by { + assert forall|i: int| 0 <= i < az.len() implies m.st(#[trigger] az[i]) by { + if i > 0 { assert(az[i] == z[i - 1]); } + } + } + assert(m.states(azw)) by { + assert forall|i: int| 0 <= i < azw.len() implies m.st(#[trigger] azw[i]) by { + if i > 0 && i <= z.len() { assert(azw[i] == z[i - 1]); } + if i > z.len() { assert(azw[i] == w[i - 1 - z.len()]); } + } + } + assert(m.cat_shape(az)); + assert(m.cat_shape(w)); + assert(m.cat_shape(azw)); + let l = (m.ncat)(az); + let r = (m.ncat)(w); + let outer = seq![l, r]; + assert(m.states(outer)) by { + assert forall|i: int| 0 <= i < outer.len() implies m.st(#[trigger] outer[i]) by {} + } + assert(m.cat_shape(outer)); + if a == m.empty { + assert(azw[0] == m.empty); + assert(az[0] == m.empty); + assert(outer[0] == m.empty); + } else { + assert(!m.has_empty(az)) by { + if m.has_empty(az) { + let i = choose|i: int| 0 <= i < az.len() && az[i] == m.empty; + if i > 0 { assert(az[i] == z[i - 1]); } + } + } + assert(!m.has_empty(azw)) by { + if m.has_empty(azw) { + let i = choose|i: int| 0 <= i < azw.len() && azw[i] == m.empty; + if i > 0 && i <= z.len() { assert(azw[i] == z[i - 1]); } + if i > z.len() { assert(azw[i] == w[i - 1 - z.len()]); } + } + } + lemma_cat_piece(m, az); + lemma_cat_piece(m, w); + lemma_no_empty_pair(m, l, r); + lemma_flat_append(m, seq![l], seq![r]); + assert(seq![l] + seq![r] =~= outer); + lemma_flat_single(m, l); + lemma_flat_single(m, r); + lemma_flat_append(m, az, w); + assert(az + w =~= azw); + lemma_cat_flat_eq(m, azw, outer); + } +} + +/// Shape of `N(x s)` for a state `x` and an atom sequence whose normal form is `s`. +pub proof fn lemma_cat_pair(m: Model, x: S, w: Seq) + requires m.contract(), m.st(x), m.atoms(w), + ensures + m.st(m.cat2(x, (m.ncat)(w))), + x == m.empty ==> m.cat2(x, (m.ncat)(w)) == m.empty, + x == m.epsilon ==> m.cat2(x, (m.ncat)(w)) == (m.ncat)(w), + x != m.empty ==> m.cat2(x, (m.ncat)(w)) == (m.ncat)(m.piece(x) + w), + x != m.empty && x != m.epsilon ==> m.atoms(m.piece(x)) && m.piece(x).len() >= 1, + m.k(x) != Kind::List && x != m.empty && x != m.epsilon ==> m.piece(x) == seq![x], +{ + lemma_no_empty_atoms(m, w); + let r = (m.ncat)(w); + assert(m.cat_shape(w)); + let xs = seq![x, r]; + lemma_cat_piece(m, w); + assert(m.states(xs)) by { + assert forall|i: int| 0 <= i < xs.len() implies m.st(#[trigger] xs[i]) by {} + } + assert(m.cat_shape(xs)); + if x == m.empty { + assert(xs[0] == m.empty); + } else { + lemma_no_empty_pair(m, x, r); + assert(m.states(seq![x])); + assert(!m.has_empty(seq![x])) by { + if m.has_empty(seq![x]) { let i = choose|i: int| 0 <= i < 1 && seq![x][i] == m.empty; } + } + lemma_flat_atoms_of(m, seq![x]); + lemma_flat_single(m, x); + lemma_flat_append(m, seq![x], seq![r]); + assert(seq![x] + seq![r] =~= xs); + lemma_flat_single(m, r); + lemma_flat_atoms(m, w); + let pw = m.piece(x) + w; + assert(m.atoms(m.piece(x))); + assert(m.atoms(pw)) by { + assert forall|i: int| 0 <= i < pw.len() implies m.atom(#[trigger] pw[i]) by { + if i < m.piece(x).len() { assert(pw[i] == m.piece(x)[i]); } else { assert(pw[i] == w[i - m.piece(x).len()]); } + } + } + lemma_no_empty_atoms(m, pw); + lemma_flat_atoms(m, pw); + lemma_cat_flat_eq(m, xs, pw); + if x == m.epsilon { + assert(pw =~= w); + } else { + if m.k(x) == Kind::List { + assert((m.elems)(x).len() >= 2); + } + } + } +} + +// ===== C(q) ===== + +pub proof fn lemma_vals_mono(m: Model, y: ISet, u1: ISet, u2: ISet) + requires m.vals_into(y, u1), u1.subset_of(u2), + ensures m.vals_into(y, u2), +{ + assert forall|p: S, v: S| y.contains(p) && #[trigger] (m.succ)(p, v) implies u2.contains(v) by { assert(u1.contains(v)); } + assert forall|p: S, v: S| y.contains(p) && #[trigger] (m.lit)(p, v) implies u2.contains(v) by { assert(u1.contains(v)); } + assert forall|p: S, v: S| y.contains(p) && #[trigger] (m.prod)(p, v) implies u2.contains(v) by { assert(u1.contains(v)); } +} + +pub proof fn lemma_list_in_mono(m: Model, p: S, u1: ISet, u2: ISet) + requires m.list_in(p, u1), u1.subset_of(u2), + ensures m.list_in(p, u2), +{ + assert forall|i: int, a: S| 0 <= i < (m.elems)(p).len() && #[trigger] (m.prod)((m.elems)(p)[i], a) + implies u2.contains((m.ncat)(seq![a] + (m.elems)(p).skip(i + 1))) by { + assert(u1.contains((m.ncat)(seq![a] + (m.elems)(p).skip(i + 1)))); + } +} + +pub proof fn lemma_lists_mono(m: Model, r: ISet, u1: ISet, u2: ISet) + requires m.r_lists_in(r, u1), u1.subset_of(u2), + ensures m.r_lists_in(r, u2), +{ + assert forall|p: S| r.contains(p) && m.k(p) == Kind::List implies #[trigger] m.list_in(p, u2) by { + assert(m.list_in(p, u1)); + lemma_list_in_mono(m, p, u1, u2); + } +} + +pub proof fn lemma_good_base(m: Model, q: S) + requires m.contract(), m.st(q), m.base_kind(q), + ensures m.good(m.rset(q), q), +{ + let r = ISet::empty().insert(q).insert(m.empty).insert(m.epsilon).insert(m.universal); + assert(m.constants_ok()); + assert forall|p: S| r.contains(p) implies m.st(p) && #[trigger] m.base_kind(p) by {} + assert(m.vals_into(r, r)) by { + assert forall|p: S, v: S| r.contains(p) && #[trigger] (m.succ)(p, v) implies r.contains(v) by { + assert(m.base_kind(p)); + lemma_base_vals(m, p); + } + assert forall|p: S, v: S| r.contains(p) && #[trigger] (m.lit)(p, v) implies r.contains(v) by { + assert(m.base_kind(p)); + lemma_base_vals(m, p); + } + assert forall|p: S, v: S| r.contains(p) && #[trigger] (m.prod)(p, v) implies r.contains(v) by { + assert(m.base_kind(p)); + lemma_base_vals(m, p); + } + } + assert forall|p: S| r.contains(p) && m.k(p) == Kind::List implies #[trigger] m.list_in(p, r) by { + assert(m.base_kind(p)); + } + assert(m.good(r, q)); +} + +/// `Y = ⋃ᵢ C(oᵢ)` inherits (C1)–(C4) from the `C(oᵢ)`. +pub proof fn lemma_ops_union(m: Model, q: S) + requires m.contract(), m.st(q), m.k(q) == Kind::Union || m.k(q) == Kind::Intersect, + forall|o: S| #[trigger] (m.ops)(q).contains(o) ==> m.good(m.rset(o), o), + ensures ({ + let y = m.ops_union(q); + &&& m.y_ok(false, y) && m.y_ok(true, y) && m.r_ops(y) + &&& m.vals_into(y, y) && m.r_lists_in(y, y) + &&& forall|o: S| #[trigger] (m.ops)(q).contains(o) ==> y.contains(o) + }), +{ + let os = (m.ops)(q); + let f = |o: S| m.rset(o); + lemma_big_union_finite(os, f); + let y = m.ops_union(q); + assert(y =~= ISet::new(|x: S| exists|o: S| os.contains(o) && #[trigger] f(o).contains(x))) by { + assert forall|x: S| y.contains(x) implies exists|o: S| os.contains(o) && #[trigger] f(o).contains(x) by { + let o = choose|o: S| os.contains(o) && #[trigger] m.rset(o).contains(x); + assert(f(o).contains(x)); + } + assert forall|x: S| (exists|o: S| os.contains(o) && #[trigger] f(o).contains(x)) implies y.contains(x) by { + let o = choose|o: S| os.contains(o) && #[trigger] f(o).contains(x); + assert(m.rset(o).contains(x)); + } + } + assert(m.r_states(y)) by { + assert forall|p: S| y.contains(p) implies m.st(p) by { + let o = choose|o: S| os.contains(o) && #[trigger] m.rset(o).contains(p); + assert(m.good(m.rset(o), o)); + } + } + assert(m.r_ops(y)) by { + assert forall|p: S, o2: S| y.contains(p) && (m.k(p) == Kind::Union || m.k(p) == Kind::Intersect) + && #[trigger] (m.ops)(p).contains(o2) implies y.contains(o2) by { + let o = choose|o: S| os.contains(o) && #[trigger] m.rset(o).contains(p); + assert(m.good(m.rset(o), o)); + assert(m.rset(o).contains(o2)); + } + assert forall|p: S| y.contains(p) && m.k(p) == Kind::Not implies y.contains(#[trigger] (m.body)(p)) by { + let o = choose|o: S| os.contains(o) && #[trigger] m.rset(o).contains(p); + assert(m.good(m.rset(o), o)); + assert(m.rset(o).contains((m.body)(p))); + } + } + assert(m.vals_into(y, y)) by { + assert forall|p: S, v: S| y.contains(p) && #[trigger] (m.succ)(p, v) implies y.contains(v) by { + let o = choose|o: S| os.contains(o) && #[trigger] m.rset(o).contains(p); + assert(m.good(m.rset(o), o)); + assert(m.rset(o).contains(v)); + } + assert forall|p: S, v: S| y.contains(p) && #[trigger] (m.lit)(p, v) implies y.contains(v) by { + let o = choose|o: S| os.contains(o) && #[trigger] m.rset(o).contains(p); + assert(m.good(m.rset(o), o)); + assert(m.rset(o).contains(v)); + } + assert forall|p: S, v: S| y.contains(p) && #[trigger] (m.prod)(p, v) implies y.contains(v) by { + let o = choose|o: S| os.contains(o) && #[trigger] m.rset(o).contains(p); + assert(m.good(m.rset(o), o)); + assert(m.rset(o).contains(v)); + } + } + assert(m.r_lists_in(y, y)) by { + assert forall|p: S| y.contains(p) && m.k(p) == Kind::List implies #[trigger] m.list_in(p, y) by { + let o = choose|o: S| os.contains(o) && #[trigger] m.rset(o).contains(p); + assert(m.good(m.rset(o), o)); + assert(m.list_in(p, m.rset(o))); + lemma_list_in_mono(m, p, m.rset(o), y); + } + } + assert forall|o: S| #[trigger] (m.ops)(q).contains(o) implies y.contains(o) by { + assert(m.good(m.rset(o), o)); + assert(m.rset(o).contains(o)); + } +} + +pub proof fn lemma_good_union(m: Model, q: S) + requires m.contract(), m.st(q), m.k(q) == Kind::Union, + forall|o: S| #[trigger] (m.ops)(q).contains(o) ==> m.good(m.rset(o), o), + ensures m.good(m.rset(q), q), +{ + lemma_ops_union(m, q); + let y = m.ops_union(q); + lemma_uset_basic(m, false, y); + lemma_yv(m, false, y); + let us = m.uset(false, y); + lemma_vals_mono(m, y, y, us); + lemma_uset_closed(m, y); + lemma_uset_ops(m, false, y); + lemma_lists_mono(m, y, y, us); + lemma_uset_lists(m, false, y, us); + assert(us.contains(q)) by { + assert(m.ops_in(q, m.yv(false, y))) by { + assert forall|o: S| #[trigger] (m.ops)(q).contains(o) implies m.yv(false, y).contains(o) by {} + } + } + assert(m.good(us, q)); +} + +pub proof fn lemma_good_inter(m: Model, q: S) + requires m.contract(), m.st(q), m.k(q) == Kind::Intersect, + forall|o: S| #[trigger] (m.ops)(q).contains(o) ==> m.good(m.rset(o), o), + ensures m.good(m.rset(q), q), +{ + lemma_ops_union(m, q); + let y = m.ops_union(q); + lemma_dnf_basic(m, y); + lemma_yv(m, true, y); + let ua = m.uset(true, y); + let d = m.dnf(y); + assert forall|p: S, v: S| y.contains(p) && #[trigger] (m.succ)(p, v) implies d.contains(v) by { assert(y.contains(v)); } + assert forall|p: S, v: S| y.contains(p) && #[trigger] (m.lit)(p, v) implies ua.contains(v) by { assert(y.contains(v)); } + assert forall|p: S, v: S| y.contains(p) && #[trigger] (m.prod)(p, v) implies ua.contains(v) by { assert(y.contains(v)); } + lemma_dnf_closed(m, y); + lemma_uset_ops(m, true, y); + lemma_uset_ops(m, false, ua); + lemma_lists_mono(m, y, y, d); + lemma_uset_lists(m, true, y, d); + lemma_uset_lists(m, false, ua, d); + assert(ua.contains(q)) by { + assert(m.ops_in(q, m.yv(true, y))) by { + assert forall|o: S| #[trigger] (m.ops)(q).contains(o) implies m.yv(true, y).contains(o) by {} + } + } + assert(m.good(d, q)); +} + +pub proof fn lemma_good_not(m: Model, q: S) + requires m.contract(), m.st(q), m.k(q) == Kind::Not, m.good(m.rset((m.body)(q)), (m.body)(q)), + ensures m.good(m.rset(q), q), +{ + let p = (m.body)(q); + let rp = m.rset(p); + let nn = |s: S| (m.nnot)(s); + rp.lemma_map_finite(nn); + let lam = rp.union(rp.map(nn)); + assert(m.constants_ok()); + // Members of Λ outside C(p) are constants or complements of members of C(p). + assert forall|x: S| lam.contains(x) && !rp.contains(x) implies m.st(x) + && (m.is_const(x) || (m.k(x) == Kind::Not && rp.contains((m.body)(x)))) by { + let s = choose|s: S| rp.contains(s) && nn(s) == x; + assert(m.not_shape(s)); + if !m.is_const(x) && !(m.k(x) == Kind::Not && (m.body)(x) == s) { + assert(m.k(s) == Kind::Not && x == (m.body)(s)); + } + } + assert(m.r_states(lam)); + assert forall|x: S, o: S| lam.contains(x) && (m.k(x) == Kind::Union || m.k(x) == Kind::Intersect) + && #[trigger] (m.ops)(x).contains(o) implies lam.contains(o) by { + assert(rp.contains(x)); + } + assert forall|x: S| lam.contains(x) && m.k(x) == Kind::Not implies lam.contains(#[trigger] (m.body)(x)) by {} + assert(m.y_ok(true, lam) && m.y_ok(false, lam) && m.r_ops(lam)); + lemma_dnf_basic(m, lam); + let ua = m.uset(true, lam); + let d = m.dnf(lam); + // Literals of a complement ¬s are normalized intersections of complements of literals of s. + assert forall|x: S, v: S| lam.contains(x) && #[trigger] (m.lit)(x, v) implies ua.contains(v) by { + if rp.contains(x) { + assert(rp.contains(v)); + } else if m.is_const(x) { + lemma_base_vals(m, x); + } else { + assert(m.lit_shape(x, v)); + assert forall|w: S| m.not_lit(x, w) implies ua.contains(w) by { + let l = choose|l: S| #[trigger] (m.lit)((m.body)(x), l) && w == (m.nnot)(l); + assert(rp.contains(l)); + assert(rp.map(nn).contains(nn(l))); + } + assert(m.built(true, |w: S| m.not_lit(x, w), v)); + assert(ua.contains(v)); + } + } + assert forall|x: S, v: S| lam.contains(x) && #[trigger] (m.prod)(x, v) implies ua.contains(v) by { + if rp.contains(x) { + assert(rp.contains(v)); + } else if m.is_const(x) { + lemma_base_vals(m, x); + } else { + assert(m.prod_shape(x, v)); + assert forall|w: S| (m.lit)(x, w) implies ua.contains(w) by {} + assert(m.built(true, |w: S| (m.lit)(x, w), v)); + assert(ua.contains(v)); + } + } + assert forall|x: S, v: S| lam.contains(x) && #[trigger] (m.succ)(x, v) implies d.contains(v) by { + if rp.contains(x) { + assert(rp.contains(v)); + } else if m.is_const(x) { + lemma_base_vals(m, x); + } else { + assert(m.succ_shape(x, v)); + assert forall|w: S| (m.prod)(x, w) implies d.contains(w) by { assert(ua.contains(w)); } + assert(m.built(false, |w: S| (m.prod)(x, w), v)); + assert(d.contains(v)); + } + } + lemma_dnf_closed(m, lam); + lemma_uset_ops(m, true, lam); + lemma_uset_ops(m, false, ua); + assert(m.r_lists_in(lam, d)) by { + assert forall|x: S| lam.contains(x) && m.k(x) == Kind::List implies #[trigger] m.list_in(x, d) by { + assert(rp.contains(x)); + assert(m.list_in(x, rp)); + lemma_list_in_mono(m, x, rp, d); + } + } + lemma_uset_lists(m, true, lam, d); + lemma_uset_lists(m, false, ua, d); + assert(lam.contains(q)) by { + assert((m.nnot)(p) == q); + assert(rp.map(nn).contains(nn(p))); + } + assert(m.good(d, q)); +} + +/// The element sequence of a member `x ∉ {∅, ε}` of `C(·)` satisfies (C4) relative to `C(·)`. +pub proof fn lemma_piece_tails(m: Model, r: ISet, q0: S, x: S) + requires m.contract(), m.good(r, q0), r.contains(x), x != m.empty, x != m.epsilon, + ensures + m.atoms(m.piece(x)), m.piece(x).len() >= 1, + forall|i: int, a: S| 0 <= i < m.piece(x).len() && #[trigger] (m.prod)(m.piece(x)[i], a) + ==> r.contains((m.ncat)(seq![a] + m.piece(x).skip(i + 1))), +{ + assert(m.st(x)); + let z = m.piece(x); + if m.k(x) == Kind::List { + assert(m.list_in(x, r)); + let es = (m.elems)(x); + assert(es.len() >= 2); + assert forall|i: int| 0 <= i < z.len() implies m.atom(#[trigger] z[i]) by { assert(z[i] == es[i]); } + } else { + assert(z == seq![x]); + assert(m.atom(x)); + assert(m.atoms(z)) by { + assert forall|i: int| 0 <= i < z.len() implies m.atom(#[trigger] z[i]) by { assert(i == 0); } + } + assert forall|i: int, a: S| 0 <= i < z.len() && #[trigger] (m.prod)(z[i], a) + implies r.contains((m.ncat)(seq![a] + z.skip(i + 1))) by { + assert(i == 0 && z[i] == x); + assert(r.contains(a)); + assert(m.st(a)); + assert(seq![a] + z.skip(1) =~= seq![a]); + lemma_cat_single(m, a); + } + } +} + +/// A list whose partial successors (C4) and final-element literals and products lie in a set `u` +/// closed under normalized unions has its successors, literals, and products in `u`, by (S6). +pub proof fn lemma_list_vals(m: Model, t: S, u: ISet) + requires + m.contract(), m.st(t), m.k(t) == Kind::List, + m.has_consts(u), m.nset_closed(false, u), m.list_in(t, u), + forall|w: S| #[trigger] (m.lit)((m.elems)(t).last(), w) ==> u.contains(w), + forall|w: S| #[trigger] (m.prod)((m.elems)(t).last(), w) ==> u.contains(w), + ensures + forall|v: S| #[trigger] (m.lit)(t, v) ==> u.contains(v), + forall|v: S| #[trigger] (m.prod)(t, v) ==> u.contains(v), + forall|v: S| #[trigger] (m.succ)(t, v) ==> u.contains(v), +{ + let es = (m.elems)(t); + assert forall|v: S| #[trigger] (m.lit)(t, v) implies u.contains(v) by { + assert(m.lit_shape(t, v)); + assert forall|w: S| m.list_lit(t, w) implies u.contains(w) by { + if !(m.lit)(es.last(), w) { + let (i, a) = choose|i: int, a: S| 0 <= i < es.len() - 1 && #[trigger] (m.prod)(es[i], a) + && w == (m.ncat)(seq![a] + es.skip(i + 1)); + } + } + assert(m.built(false, |w: S| m.list_lit(t, w), v)); + assert(u.contains(v)); + } + assert forall|v: S| #[trigger] (m.prod)(t, v) implies u.contains(v) by { + assert(m.prod_shape(t, v)); + } + assert forall|v: S| #[trigger] (m.succ)(t, v) implies u.contains(v) by { + assert(m.succ_shape(t, v)); + assert forall|w: S| (m.prod)(t, w) implies u.contains(w) by {} + assert(m.built(false, |w: S| (m.prod)(t, w), v)); + assert(u.contains(v)); + } +} + +pub proof fn lemma_good_star(m: Model, q: S) + requires m.contract(), m.st(q), m.k(q) == Kind::Star, m.good(m.rset((m.body)(q)), (m.body)(q)), + ensures m.good(m.rset(q), q), +{ + let p = (m.body)(q); + let rp = m.rset(p); + let cq = |x: S| m.cat2(x, q); + rp.lemma_map_finite(cq); + let t = m.star_terms(q); + let w = seq![q]; + assert(m.constants_ok()); + assert(m.atom(q)); + assert(m.atoms(w)); + lemma_cat_single(m, q); + assert((m.ncat)(w) == q); + // Members of T: ∅, q, or lists `z q`. + assert forall|x: S| rp.contains(x) implies m.st(#[trigger] m.cat2(x, q)) && ( + m.cat2(x, q) == m.empty && x == m.empty + || m.cat2(x, q) == q && x == m.epsilon + || (x != m.empty && x != m.epsilon && m.k(m.cat2(x, q)) == Kind::List + && (m.elems)(m.cat2(x, q)) == m.piece(x) + w)) by { + assert(m.st(x)); + lemma_cat_pair(m, x, w); + if x != m.empty && x != m.epsilon { + let z = m.piece(x); + let zw = z + w; + assert(m.atoms(zw)) by { + assert forall|h: int| 0 <= h < zw.len() implies m.atom(#[trigger] zw[h]) by { + if h < z.len() { assert(zw[h] == z[h]); } else { assert(zw[h] == w[h - z.len()]); } + } + } + lemma_cat_atoms(m, zw); + } + } + assert(t.contains(q)) by { + assert(cq(m.epsilon) == q); + } + assert forall|v: S| t.contains(v) implies exists|x: S| rp.contains(x) && v == #[trigger] m.cat2(x, q) by {} + assert(m.r_states(t)) by { + assert forall|v: S| t.contains(v) implies m.st(v) by { + let x = choose|x: S| rp.contains(x) && v == #[trigger] m.cat2(x, q); + } + } + // No unions, intersections, or complements in T. + assert forall|v: S| t.contains(v) implies m.k(v) != Kind::Union && m.k(v) != Kind::Intersect && m.k(v) != Kind::Not by { + let x = choose|x: S| rp.contains(x) && v == #[trigger] m.cat2(x, q); + } + assert(m.y_ok(false, t)); + assert(m.r_ops(t)); + lemma_uset_basic(m, false, t); + lemma_uset_nset_closed(m, false, t); + let us = m.uset(false, t); + // Literals, products, and successors of q: (S5). + assert forall|v: S| #[trigger] (m.lit)(q, v) implies us.contains(v) by { + assert(m.lit_shape(q, v)); + assert forall|wv: S| m.star_lit(q, wv) implies us.contains(wv) by { + let a = choose|a: S| #[trigger] (m.prod)((m.body)(q), a) && wv == m.cat2(a, q); + assert(rp.contains(a)); + assert(t.contains(cq(a))); + } + assert(m.built(false, |wv: S| m.star_lit(q, wv), v)); + assert(us.contains(v)); + } + assert forall|v: S| #[trigger] (m.prod)(q, v) implies us.contains(v) by { assert(m.prod_shape(q, v)); } + assert forall|v: S| #[trigger] (m.succ)(q, v) implies us.contains(v) by { + assert(m.succ_shape(q, v)); + assert forall|wv: S| (m.prod)(q, wv) implies us.contains(wv) by {} + assert(m.built(false, |wv: S| (m.prod)(q, wv), v)); + assert(us.contains(v)); + } + // (C4) for the lists of T, relative to U(T). + assert forall|y: S| t.contains(y) && m.k(y) == Kind::List implies #[trigger] m.list_in(y, us) by { + let x = choose|x: S| rp.contains(x) && y == #[trigger] m.cat2(x, q); + assert(x != m.empty && x != m.epsilon); + let z = m.piece(x); + lemma_piece_tails(m, rp, p, x); + let es = (m.elems)(y); + assert(es == z + w); + assert forall|i: int, a: S| 0 <= i < es.len() && #[trigger] (m.prod)(es[i], a) + implies us.contains((m.ncat)(seq![a] + es.skip(i + 1))) by { + if i < z.len() { + assert(es[i] == z[i]); + assert(m.st(z[i])); + assert(m.st(a)); + let zr = z.skip(i + 1); + assert(m.atoms(zr)) by { + assert forall|h: int| 0 <= h < zr.len() implies m.atom(#[trigger] zr[h]) by { assert(zr[h] == z[i + 1 + h]); } + } + lemma_cat_assoc(m, a, zr, w); + assert(seq![a] + es.skip(i + 1) =~= seq![a] + zr + w); + assert(rp.contains((m.ncat)(seq![a] + zr))); + assert(t.contains(cq((m.ncat)(seq![a] + zr)))); + } else { + assert(es[i] == q); + assert(m.st(a)); + assert(seq![a] + es.skip(i + 1) =~= seq![a]); + lemma_cat_single(m, a); + } + } + } + // (C2) for T. + assert forall|y: S| t.contains(y) implies { + &&& forall|v: S| #[trigger] (m.succ)(y, v) ==> us.contains(v) + &&& forall|v: S| #[trigger] (m.lit)(y, v) ==> us.contains(v) + &&& forall|v: S| #[trigger] (m.prod)(y, v) ==> us.contains(v) + } by { + let x = choose|x: S| rp.contains(x) && y == #[trigger] m.cat2(x, q); + if x == m.empty { + lemma_base_vals(m, y); + } else if x == m.epsilon { + } else { + assert(m.list_in(y, us)); + assert((m.elems)(y).last() == q); + lemma_list_vals(m, y, us); + } + } + assert(m.vals_into(t, us)); + lemma_uset_closed(m, t); + lemma_uset_ops(m, false, t); + lemma_uset_lists(m, false, t, us); + assert(m.good(us, q)); +} + +/// Facts shared by the list-case lemmas. +pub open spec fn list_ctx(m: Model, q: S) -> bool { + let c = (m.elems)(q); + &&& m.contract() && m.st(q) && m.k(q) == Kind::List && m.atoms(c) && c.len() >= 2 + &&& forall|j: int| 0 <= j < c.len() ==> m.good(m.rset(#[trigger] c[j]), c[j]) + &&& forall|j: int| 0 <= j < c.len() ==> #[trigger] m.atoms(c.skip(j + 1)) +} + +/// `T` contains `N(x s_j)` for `x ∈ C(c_j)`. +pub proof fn lemma_list_term(m: Model, c: Seq, j: int, x: S) + requires 0 <= j < c.len(), m.rset(c[j]).contains(x), + ensures m.list_terms(c).contains(m.cat2(x, m.suffix(c, j))), +{} + +/// Shape of a member `N(x s_j)` of `T` with `j < m`. +pub proof fn lemma_list_term_shape(m: Model, q: S, j: int, x: S) + requires list_ctx(m, q), 0 <= j < (m.elems)(q).len() - 1, m.rset((m.elems)(q)[j]).contains(x), + ensures ({ + let c = (m.elems)(q); + let y = m.cat2(x, m.suffix(c, j)); + &&& m.st(y) + &&& (x == m.empty && y == m.empty) + || (x == m.epsilon && j == c.len() - 2 && y == c[c.len() - 1]) + || (x != m.empty && m.k(y) == Kind::List && (m.elems)(y) == m.piece(x) + c.skip(j + 1) + && (m.elems)(y).last() == c[c.len() - 1]) + }), +{ + let c = (m.elems)(q); + let n = c.len() as int; + let w = c.skip(j + 1); + assert(m.good(m.rset(c[j]), c[j])); + assert(m.st(x)); + assert(m.atoms(w)); + lemma_cat_pair(m, x, w); + if x != m.empty { + let z = m.piece(x); + let es = z + w; + assert(m.atoms(z)) by { + if x == m.epsilon { assert(z =~= Seq::::empty()); } + } + assert(m.atoms(es)) by { + assert forall|h: int| 0 <= h < es.len() implies m.atom(#[trigger] es[h]) by { + if h < z.len() { assert(es[h] == z[h]); } else { assert(es[h] == w[h - z.len()]); } + } + } + lemma_cat_atoms(m, es); + assert(es.last() == c[n - 1]); + if es.len() == 1 { + assert(z.len() == 0); + assert(x == m.epsilon) by { + if x != m.epsilon { assert(m.piece(x).len() >= 1); } + } + assert(w.len() == 1); + assert(es[0] == c[n - 1]); + } + } +} + +/// (C4) for a list `N(x s_j)` of `T` with `j < m`, relative to `T`. +pub proof fn lemma_list_member(m: Model, q: S, j: int, x: S) + requires list_ctx(m, q), 0 <= j < (m.elems)(q).len() - 1, m.rset((m.elems)(q)[j]).contains(x), + x != m.empty, m.k(m.cat2(x, m.suffix((m.elems)(q), j))) == Kind::List, + ensures m.list_in(m.cat2(x, m.suffix((m.elems)(q), j)), m.list_terms((m.elems)(q))), +{ + let c = (m.elems)(q); + let n = c.len() as int; + let w = c.skip(j + 1); + let rx = m.rset(c[j]); + let tt = m.list_terms(c); + let y = m.cat2(x, m.suffix(c, j)); + lemma_list_term_shape(m, q, j, x); + assert(m.good(rx, c[j])); + let z = m.piece(x); + let es = (m.elems)(y); + assert(es == z + w); + if x != m.epsilon { + lemma_piece_tails(m, rx, c[j], x); + } else { + assert(z =~= Seq::::empty()); + } + assert(m.atoms(w)); + assert forall|i: int, a: S| 0 <= i < es.len() && #[trigger] (m.prod)(es[i], a) + implies tt.contains((m.ncat)(seq![a] + es.skip(i + 1))) by { + if i < z.len() { + assert(es[i] == z[i]); + assert(m.atoms(z)); + assert(m.st(z[i])); + assert(m.st(a)); + let zr = z.skip(i + 1); + assert(m.atoms(zr)) by { + assert forall|h: int| 0 <= h < zr.len() implies m.atom(#[trigger] zr[h]) by { assert(zr[h] == z[i + 1 + h]); } + } + lemma_cat_assoc(m, a, zr, w); + assert(seq![a] + es.skip(i + 1) =~= seq![a] + zr + w); + assert(rx.contains((m.ncat)(seq![a] + zr))); + lemma_list_term(m, c, j, (m.ncat)(seq![a] + zr)); + } else { + let k = j + 1 + (i - z.len()); + assert(es[i] == c[k]); + assert(m.good(m.rset(c[k]), c[k])); + assert(m.rset(c[k]).contains(c[k])); + assert(m.rset(c[k]).contains(a)); + assert(m.st(a)); + let w2 = c.skip(k + 1); + assert(m.atoms(w2)); + assert(es.skip(i + 1) =~= w2); + lemma_cat_assoc(m, a, Seq::::empty(), w2); + assert(seq![a] + Seq::::empty() + w2 =~= seq![a] + w2); + assert(seq![a] + Seq::::empty() =~= seq![a]); + lemma_cat_single(m, a); + lemma_list_term(m, c, k, a); + } + } +} + +pub proof fn lemma_good_list(m: Model, q: S) + requires m.contract(), m.st(q), m.k(q) == Kind::List, + forall|j: int| 0 <= j < (m.elems)(q).len() ==> m.good(m.rset(#[trigger] (m.elems)(q)[j]), (m.elems)(q)[j]), + ensures m.good(m.rset(q), q), +{ + let c = (m.elems)(q); + let n = c.len() as int; + assert(n >= 2); + assert(m.atoms(c)); + let t = m.list_terms(c); + // T is finite. + lemma_int_range(0, n); + let f = |j: int| m.rset(c[j]).map(|x: S| m.cat2(x, m.suffix(c, j))); + assert forall|j: int| set_int_range(0, n).contains(j) implies #[trigger] f(j).finite() by { + m.rset(c[j]).lemma_map_finite(|x: S| m.cat2(x, m.suffix(c, j))); + } + lemma_big_union_finite(set_int_range(0, n), f); + assert(t =~= ISet::new(|x: S| exists|j: int| set_int_range(0, n).contains(j) && #[trigger] f(j).contains(x))) by { + assert forall|y: S| t.contains(y) implies exists|j: int| set_int_range(0, n).contains(j) && #[trigger] f(j).contains(y) by { + let (j, x) = choose|j: int, x: S| 0 <= j < c.len() && m.rset(c[j]).contains(x) + && y == #[trigger] m.cat2(x, m.suffix(c, j)); + assert(f(j).contains(y)); + } + assert forall|y: S| (exists|j: int| set_int_range(0, n).contains(j) && #[trigger] f(j).contains(y)) implies t.contains(y) by { + let j = choose|j: int| set_int_range(0, n).contains(j) && #[trigger] f(j).contains(y); + let x = choose|x: S| m.rset(c[j]).contains(x) && y == m.cat2(x, m.suffix(c, j)); + assert(y == m.cat2(x, m.suffix(c, j))); + } + } + // Suffix facts. + assert forall|j: int| 0 <= j < n implies #[trigger] m.atoms(c.skip(j + 1)) by { + assert forall|h: int| 0 <= h < c.skip(j + 1).len() implies m.atom(#[trigger] c.skip(j + 1)[h]) by { + assert(c.skip(j + 1)[h] == c[j + 1 + h]); + } + } + assert(list_ctx(m, q)); + assert(m.suffix(c, n - 1) == m.epsilon) by { + assert(c.skip(n) =~= Seq::::empty()); + assert(m.states(c.skip(n))); + assert(m.cat_shape(c.skip(n))); + assert(!m.has_empty(c.skip(n))); + } + // q ∈ T. + assert(t.contains(q)) by { + assert(m.good(m.rset(c[0]), c[0])); + assert(m.rset(c[0]).contains(c[0])); + assert(m.atoms(c.skip(0int + 1))); + assert(m.atom(c[0])); + lemma_cat_pair(m, c[0], c.skip(1)); + assert(m.piece(c[0]) + c.skip(1) =~= c); + assert(m.fixpoints_ok()); + assert((m.ncat)(c) == q); + assert(m.cat2(c[0], m.suffix(c, 0)) == q); + lemma_list_term(m, c, 0, c[0]); + } + // Level-(m-1) members are C(c_m). + let rl = m.rset(c[n - 1]); + assert(m.good(rl, c[n - 1])); + assert forall|x: S| rl.contains(x) implies #[trigger] m.cat2(x, m.suffix(c, n - 1)) == x by { + assert(m.st(x)); + assert(c.skip(n) =~= Seq::::empty()); + lemma_cat_pair(m, x, c.skip(n)); + if x != m.empty && x != m.epsilon { + assert(m.piece(x) + c.skip(n) =~= m.piece(x)); + lemma_cat_pair(m, x, seq![]); + if m.k(x) == Kind::List { + lemma_cat_atoms(m, m.piece(x)); + lemma_list_unique(m, (m.ncat)(m.piece(x)), x); + } else { + lemma_cat_atoms(m, m.piece(x)); + } + } + } + assert forall|x: S| rl.contains(x) implies t.contains(x) by { + assert(m.cat2(x, m.suffix(c, n - 1)) == x); + lemma_list_term(m, c, n - 1, x); + } + // Classification of members of T. + assert forall|y: S| t.contains(y) implies m.st(y) && (rl.contains(y) || y == m.empty || (m.k(y) == Kind::List + && m.list_in(y, t) && (m.elems)(y).last() == c[n - 1])) by { + let (j, x) = choose|j: int, x: S| 0 <= j < c.len() && m.rset(c[j]).contains(x) + && y == #[trigger] m.cat2(x, m.suffix(c, j)); + if j == n - 1 { + assert(m.cat2(x, m.suffix(c, n - 1)) == x); + assert(m.good(m.rset(c[j]), c[j])); + } else { + lemma_list_term_shape(m, q, j, x); + if x != m.empty && !(x == m.epsilon && j == n - 2) { + lemma_list_member(m, q, j, x); + } + } + } + assert(m.r_states(t)); + assert(m.r_ops(t)) by { + assert forall|y: S, o: S| t.contains(y) && (m.k(y) == Kind::Union || m.k(y) == Kind::Intersect) + && #[trigger] (m.ops)(y).contains(o) implies t.contains(o) by { + assert(rl.contains(y)); + } + assert forall|y: S| t.contains(y) && m.k(y) == Kind::Not implies t.contains(#[trigger] (m.body)(y)) by { + assert(rl.contains(y)); + } + } + assert(m.y_ok(false, t)); + lemma_uset_basic(m, false, t); + lemma_uset_nset_closed(m, false, t); + let us = m.uset(false, t); + assert(m.r_lists_in(t, t)) by { + assert forall|y: S| t.contains(y) && m.k(y) == Kind::List implies #[trigger] m.list_in(y, t) by { + if rl.contains(y) { + assert(m.list_in(y, rl)); + lemma_list_in_mono(m, y, rl, t); + } + } + } + // (C2) for T. + assert forall|y: S| t.contains(y) implies { + &&& forall|v: S| #[trigger] (m.succ)(y, v) ==> us.contains(v) + &&& forall|v: S| #[trigger] (m.lit)(y, v) ==> us.contains(v) + &&& forall|v: S| #[trigger] (m.prod)(y, v) ==> us.contains(v) + } by { + if rl.contains(y) { + assert forall|v: S| #[trigger] (m.succ)(y, v) implies us.contains(v) by { assert(rl.contains(v)); } + assert forall|v: S| #[trigger] (m.lit)(y, v) implies us.contains(v) by { assert(rl.contains(v)); } + assert forall|v: S| #[trigger] (m.prod)(y, v) implies us.contains(v) by { assert(rl.contains(v)); } + } else if y == m.empty { + assert(m.constants_ok()); + lemma_base_vals(m, y); + } else { + lemma_list_in_mono(m, y, t, us); + assert forall|v: S| #[trigger] (m.lit)((m.elems)(y).last(), v) implies us.contains(v) by { assert(rl.contains(v)); } + assert forall|v: S| #[trigger] (m.prod)((m.elems)(y).last(), v) implies us.contains(v) by { assert(rl.contains(v)); } + lemma_list_vals(m, y, us); + } + } + assert(m.vals_into(t, us)); + lemma_uset_closed(m, t); + lemma_uset_ops(m, false, t); + lemma_lists_mono(m, t, t, us); + lemma_uset_lists(m, false, t, us); + assert(m.good(us, q)); +} + +pub proof fn lemma_finite_states(m: Model, q: S) + requires m.contract(), m.st(q), + ensures m.good(m.rset(q), q), + decreases (m.size)(q), +{ + let kq = m.k(q); + if m.base_kind(q) { + lemma_good_base(m, q); + } else if kq == Kind::Union || kq == Kind::Intersect { + assert forall|o: S| #[trigger] (m.ops)(q).contains(o) implies m.good(m.rset(o), o) by { + lemma_finite_states(m, o); + } + if kq == Kind::Union { lemma_good_union(m, q); } else { lemma_good_inter(m, q); } + } else if kq == Kind::Not { + lemma_finite_states(m, (m.body)(q)); + lemma_good_not(m, q); + } else if kq == Kind::Star { + lemma_finite_states(m, (m.body)(q)); + lemma_good_star(m, q); + } else { + let c = (m.elems)(q); + assert forall|j: int| 0 <= j < c.len() implies m.good(m.rset(#[trigger] c[j]), c[j]) by { + assert(m.atom(c[j])); + lemma_finite_states(m, c[j]); + } + lemma_good_list(m, q); + } +} + +/// Paper Lemma `lem:finite-states`: for every state `q` there is a finite set, independent of +/// valuations and events, containing `q`, closed under all successors, and containing every state +/// reachable from `q`. +pub proof fn theorem_finite_reachable(m: Model, q: S) -> (r: Set) + requires m.contract(), m.st(q), + ensures + r.contains(q), + forall|p: S| r.contains(p) ==> m.st(p), + forall|p: S, v: S| r.contains(p) && #[trigger] (m.succ)(p, v) ==> r.contains(v), + forall|n: nat, p: S| #[trigger] reachable(m, q, n, p) ==> r.contains(p), +{ + lemma_finite_states(m, q); + let ri = m.rset(q); + let r = Set::new_from_iset(ri).unwrap(); + assert(r.to_iset() == ri); + assert(m.r_closed(ri)); + assert forall|n: nat, p: S| #[trigger] reachable(m, q, n, p) implies r.contains(p) by { + lemma_reachable_in(m, q, ri, n, p); + } + r +} + +pub proof fn lemma_reachable_in(m: Model, q: S, r: ISet, n: nat, p: S) + requires r.contains(q), m.r_closed(r), reachable(m, q, n, p), + ensures r.contains(p), + decreases n, +{ + if n > 0 { + let p0 = choose|p0: S| reachable(m, q, (n - 1) as nat, p0) && #[trigger] (m.succ)(p0, p); + lemma_reachable_in(m, q, r, (n - 1) as nat, p0); + } +} + +// ===== non-vacuity: a model satisfying the contract ===== + +/// States of a small model: the constants and lists of `Univ`. +pub enum Toy { Emp, Eps, Univ, Lst(Seq) } + +pub open spec fn toy_univs(s: Seq) -> bool { + forall|i: int| 0 <= i < s.len() ==> #[trigger] s[i] == Toy::Univ +} + +pub open spec fn toy_state(x: Toy) -> bool { + match x { Toy::Lst(s) => s.len() >= 2 && toy_univs(s), _ => true } +} + +pub open spec fn toy_kind(x: Toy) -> Kind { + match x { Toy::Emp => Kind::Empty, Toy::Eps => Kind::Epsilon, Toy::Univ => Kind::Universal, Toy::Lst(_) => Kind::List } +} + +pub open spec fn toy_elems(x: Toy) -> Seq { + match x { Toy::Lst(s) => s, _ => seq![] } +} + +/// Successors, literals, and products of the small model coincide: `Univ` for `Univ`, else `∅`. +pub open spec fn toy_succ(p: Toy, v: Toy) -> bool { + (p == Toy::Emp || p == Toy::Eps || p is Lst) && v == Toy::Emp || p == Toy::Univ && v == Toy::Univ +} + +pub open spec fn toy_base() -> Model { + Model { + state: |x: Toy| toy_state(x), + kind: |x: Toy| toy_kind(x), + ops: |x: Toy| Set::::empty(), + body: |x: Toy| Toy::Emp, + elems: |x: Toy| toy_elems(x), + size: |x: Toy| if x is Lst { 1nat } else { 0nat }, + empty: Toy::Emp, + epsilon: Toy::Eps, + universal: Toy::Univ, + nset: |inter: bool, xs: Set, u: Toy| u == Toy::Emp, + nnot: |x: Toy| Toy::Emp, + ncat: |xs: Seq| Toy::Emp, + combo: |inter: bool, ts: Set, t: Toy| false, + succ: |p: Toy, v: Toy| toy_succ(p, v), + lit: |p: Toy, v: Toy| toy_succ(p, v), + prod: |p: Toy, v: Toy| toy_succ(p, v), + } +} + +/// `N(x₁⋯xₖ)` of the small model, defined by (N4). +pub open spec fn toy_cat(xs: Seq) -> Toy { + let f = toy_base().flat(xs); + if toy_base().has_empty(xs) { Toy::Emp } else if f.len() == 0 { Toy::Eps } else if f.len() == 1 { f[0] } else { Toy::Lst(f) } +} + +pub open spec fn toy() -> Model { + Model { ncat: |xs: Seq| toy_cat(xs), ..toy_base() } +} + +pub proof fn lemma_toy_flat(xs: Seq) + requires forall|i: int| 0 <= i < xs.len() ==> toy_state(#[trigger] xs[i]), + ensures + !toy_base().has_empty(xs) ==> toy_univs(toy_base().flat(xs)), + toy().flat(xs) == toy_base().flat(xs), + decreases xs.len(), +{ + if xs.len() > 0 { + let init = xs.drop_last(); + assert forall|i: int| 0 <= i < init.len() implies toy_state(#[trigger] init[i]) by { assert(init[i] == xs[i]); } + lemma_toy_flat(init); + if !toy_base().has_empty(xs) { + assert(!toy_base().has_empty(init)) by { + if toy_base().has_empty(init) { + let i = choose|i: int| 0 <= i < init.len() && init[i] == Toy::Emp; + assert(xs[i] == Toy::Emp); + } + } + let f0 = toy_base().flat(init); + let p = toy_base().piece(xs.last()); + assert(toy_state(xs[xs.len() - 1])); + assert(xs[xs.len() - 1] != Toy::Emp); + assert(toy_univs(p)); + assert forall|i: int| 0 <= i < (f0 + p).len() implies #[trigger] (f0 + p)[i] == Toy::Univ by { + if i < f0.len() { assert((f0 + p)[i] == f0[i]); } else { assert((f0 + p)[i] == p[i - f0.len()]); } + } + } + } +} + +/// The contract is satisfiable, so `theorem_finite_reachable` is not vacuous. +pub proof fn lemma_contract_satisfiable() + ensures toy().contract(), +{ + let m = toy(); + assert(m.constants_ok()); + assert(m.substates_ok()); + assert forall|xs: Seq| m.states(xs) implies #[trigger] m.cat_shape(xs) by { + lemma_toy_flat(xs); + } + assert(m.fixpoints_ok()) by { + assert forall|x: Toy| m.st(x) && m.k(x) == Kind::List implies (m.ncat)(#[trigger] (m.elems)(x)) == x by { + let s = toy_elems(x); + assert forall|i: int| 0 <= i < s.len() implies toy_state(#[trigger] s[i]) by {} + lemma_toy_flat(s); + assert(m.flat(s) == s) by { + assert forall|i: int| 0 <= i < s.len() implies m.atom(#[trigger] s[i]) by {} + lemma_flat_atoms(m, s); + } + assert(!m.has_empty(s)); + } + } + assert(m.nset_ok()) by { + assert forall|inter: bool, f: Set| #[trigger] m.has_set_bound(inter, f) by { + assert(m.set_states_within(inter, f, Set::empty())); + } + } + assert(m.not_ok()); + assert(m.cat_ok()); + assert(m.tests_ok()) by { + assert forall|inter: bool, ts: ISet| ts.finite() && (forall|t: Toy| ts.contains(t) ==> m.is_test(t)) + implies #[trigger] m.has_closure(inter, ts) by { + assert(m.closure_for(inter, ts, ts)); + } + } + assert(m.succ_ok()) by { + assert forall|p: Toy, v: Toy| m.st(p) && #[trigger] (m.succ)(p, v) implies m.st(v) && m.succ_shape(p, v) by { + if p is Lst { assert(m.built(false, |w: Toy| (m.prod)(p, w), v)); } + } + assert forall|p: Toy, v: Toy| m.st(p) && #[trigger] (m.lit)(p, v) implies m.st(v) && m.lit_shape(p, v) by { + if p is Lst { assert(m.built(false, |w: Toy| m.list_lit(p, w), v)); } + } + assert forall|p: Toy, v: Toy| m.st(p) && #[trigger] (m.prod)(p, v) implies m.st(v) && m.prod_shape(p, v) by {} + } +} + +} // verus! diff --git a/src/history-semantics/src/verify/finite_steps.rs b/src/history-semantics/src/verify/finite_steps.rs new file mode 100644 index 000000000..d29ca486a --- /dev/null +++ b/src/history-semantics/src/verify/finite_steps.rs @@ -0,0 +1,817 @@ +//! The machine typing invariant of the transition normalizer (`normalize.rs` `Action`): every +//! task and stack value is a normal form ([`xnf_task`], [`xnf_values`]), and each step replaces +//! its action by an expansion whose abstract run (`verify::finite_machine::arun`) is below the +//! action's abstract effect ([`xeffect`]). With the frame rule this bounds the class of the +//! result of `Action::run` by the abstract effect of the original action ([`run_bound`]), which +//! gives the class bounds of the transition constructors `intersect`, `not`, `append`, and +//! `if_then_else`. (N4′) for `r_cat` on normal forms is [`lemma_cat_inline`]. +use crate::normalize::verify::{self as norm, ActionShape, ChildShape}; +use crate::verify::finite_collect::*; +use crate::verify::finite_impl::*; +use crate::verify::finite_link::*; +use crate::verify::finite_machine::*; +use crate::verify::finite_states::*; +use crate::verify::finite_trans::*; +use junco_core::kernel::verify as model; +use junco_core::kernel::{RegexId, TestId, TransitionId}; +use junco_core::verify::history_specs::Regex; +use vstd::prelude::*; + +verus! { + +broadcast use junco_core::kernel::verify::group_kernel_views; + +// ===== the invariant ===== + +/// A task over normal-form transitions and suffixes. +pub open spec fn xnf_task(g: model::Graph, a: ActionShape) -> bool { + match a { + ActionShape::Clean(id, _) => nf_sum(g, id), + ActionShape::Not(id) => nf_sum(g, id), + ActionShape::Append(id, r) => nf_sum(g, id) && r < g.regexes.len() && regex_nf(model::lift_regex(g, r)), + ActionShape::Pair(a, b) => nf_sum(g, a) && nf_sum(g, b), + ActionShape::Fold(terms, _) => all_nf(g, terms), + ActionShape::AppendResult(r) => r < g.regexes.len() && regex_nf(model::lift_regex(g, r)), + _ => true, + } +} + +pub open spec fn xnf_tasks(g: model::Graph, ts: Seq) -> bool { + forall|i: int| 0 <= i < ts.len() ==> #[trigger] xnf_task(g, ts[i]) +} + +pub open spec fn xnf_values(g: model::Graph, vs: Seq) -> bool { + forall|i: int| #![trigger vs[i]] 0 <= i < vs.len() ==> nf_sum(g, vs[i]@) +} + +/// Abstract stack of a value stack. +pub open spec fn vavs(g: model::Graph, vs: Seq) -> Seq { + avs(g, model::transition_ids(vs)) +} + +/// The configuration before a step of `task` is typed. +#[verifier::opaque] +pub open spec fn xpre(g: model::Graph, task: ActionShape, pending: Seq, prior: Seq) -> bool { + xnf_tasks(g, pending) && xnf_task(g, task) && xnf_values(g, prior) +} + +/// The configuration after a step of `task` is typed, and the step's expansion is below the +/// abstract effect of `task`. +#[verifier::opaque] +pub open spec fn xeffect(g: model::Graph, task: ActionShape, pending: Seq, prior: Seq, + tasks: Seq, values: Seq) -> bool { + &&& pending.is_prefix_of(tasks) + &&& xnf_tasks(g, tasks) && xnf_values(g, values) + &&& aref(aapply(g, task, vavs(g, prior)), arun(g, tasks.subrange(pending.len() as int, tasks.len() as int), vavs(g, values))) +} + +/// The run invariant: the remaining run is below the original action's. +#[verifier::opaque] +pub open spec fn xrun(g: model::Graph, shape: ActionShape, tasks: Seq, values: Seq) -> bool { + &&& xnf_tasks(g, tasks) && xnf_values(g, values) + &&& aref(arun(g, seq![shape], Seq::empty()), arun(g, tasks, vavs(g, values))) +} + +/// The abstract value pushed by an action that pushes one value. +pub open spec fn push_av(g: model::Graph, task: ActionShape) -> AV { + match task { + ActionShape::Clean(id, _) => av_of(g, id), + ActionShape::Not(id) => av_neg(av_of(g, id)), + ActionShape::Append(id, r) => av_app(av_of(g, id), model::lift_regex(g, r)), + ActionShape::Pair(a, b) => av_meet(seq![av_of(g, a), av_of(g, b)]), + ActionShape::Fold(terms, _) => av_meet(avs(g, terms)), + _ => av_of(g, 0), + } +} + +/// The result `id` of `Action::run` for `shape` is a normal form whose abstract value is below +/// the abstract effect of `shape`. +pub open spec fn run_bound(g: model::Graph, shape: ActionShape, id: nat) -> bool { + nf_sum(g, id) && av_le(av_of(g, id), push_av(g, shape)) +} + +/// The class bound of `if_then_else(test, a, b)`. +pub open spec fn ite_bound(g: model::Graph, out: nat, a: nat, b: nat) -> bool { + nf_sum(g, out) && av_le(av_of(g, out), av_if(av_of(g, a), av_of(g, b))) +} + +/// `N(w ys)`. +pub open spec fn cat_front(w: R, ys: Seq) -> R { + r_cat(seq![w] + ys) +} + +/// The class bound of `append(t, s)` with lifted suffix `ys`: constants and `N(w ys)` for members +/// `w` of `t`'s class. +pub open spec fn app_bound(g: model::Graph, out: nat, t: nat, ys: Seq) -> bool { + &&& nf_sum(g, out) + &&& forall|v: R| #[trigger] tcls(g, out, v) ==> rconst(v) || exists|w: R| tcls(g, t, w) && v == #[trigger] cat_front(w, ys) +} + +/// A typed configuration. +#[verifier::opaque] +pub open spec fn xcfg(g: model::Graph, tasks: Seq, values: Seq) -> bool { + xnf_tasks(g, tasks) && xnf_values(g, values) +} + +/// A machine step from `(t0, v0)` to `(t1, v1)` keeps the typing and lowers the abstract run. +#[verifier::opaque] +pub open spec fn xstep(g: model::Graph, t0: Seq, v0: Seq, t1: Seq, v1: Seq) -> bool { + xcfg(g, t1, v1) && aref(arun(g, t0, vavs(g, v0)), arun(g, t1, vavs(g, v1))) +} + +// ===== sequences ===== + +pub proof fn lemma_vavs_index(g: model::Graph, vs: Seq, i: int) + requires 0 <= i < vs.len(), + ensures vavs(g, vs).len() == vs.len(), vavs(g, vs)[i] == av_of(g, vs[i]@), +{ + assert(model::transition_ids(vs)[i] == vs[i]@); +} + +pub proof fn lemma_vavs_push(g: model::Graph, vs: Seq, x: TransitionId) + ensures vavs(g, vs.push(x)) == vavs(g, vs).push(av_of(g, x@)), +{ + assert(model::transition_ids(vs.push(x)) =~= model::transition_ids(vs).push(x@)); + assert(vavs(g, vs.push(x)) =~= vavs(g, vs).push(av_of(g, x@))); +} + +pub proof fn lemma_vavs_sub(g: model::Graph, vs: Seq, i: int, j: int) + requires 0 <= i <= j <= vs.len(), + ensures vavs(g, vs.subrange(i, j)) == vavs(g, vs).subrange(i, j), + model::transition_ids(vs.subrange(i, j)) == model::transition_ids(vs).subrange(i, j), +{ + assert(model::transition_ids(vs.subrange(i, j)) =~= model::transition_ids(vs).subrange(i, j)); + assert(vavs(g, vs.subrange(i, j)) =~= vavs(g, vs).subrange(i, j)); +} + +pub proof fn lemma_vavs_take(g: model::Graph, vs: Seq, i: int) + requires 0 <= i <= vs.len(), + ensures vavs(g, vs.take(i)) == vavs(g, vs).take(i), +{ + lemma_vavs_sub(g, vs, 0, i); + assert(vs.take(i) == vs.subrange(0, i)); + assert(vavs(g, vs).take(i) == vavs(g, vs).subrange(0, i)); +} + +pub proof fn lemma_xnf_values_push(g: model::Graph, vs: Seq, x: TransitionId) + requires xnf_values(g, vs), nf_sum(g, x@), + ensures xnf_values(g, vs.push(x)), +{ + assert forall|i: int| #![trigger vs.push(x)[i]] 0 <= i < vs.push(x).len() implies nf_sum(g, vs.push(x)[i]@) by { + if i < vs.len() { assert(vs.push(x)[i] == vs[i]); } + } +} + +pub proof fn lemma_xnf_values_sub(g: model::Graph, vs: Seq, i: int, j: int) + requires xnf_values(g, vs), 0 <= i <= j <= vs.len(), + ensures xnf_values(g, vs.subrange(i, j)), xnf_values(g, vs.take(j)), all_nf(g, model::transition_ids(vs.subrange(i, j))), +{ + assert forall|k: int| #![trigger vs.subrange(i, j)[k]] 0 <= k < vs.subrange(i, j).len() implies nf_sum(g, vs.subrange(i, j)[k]@) by { + assert(vs.subrange(i, j)[k] == vs[i + k]); + } + assert forall|k: int| #![trigger vs.take(j)[k]] 0 <= k < vs.take(j).len() implies nf_sum(g, vs.take(j)[k]@) by { + assert(vs.take(j)[k] == vs[k]); + } + assert forall|k: int| 0 <= k < model::transition_ids(vs.subrange(i, j)).len() + implies nf_sum(g, #[trigger] model::transition_ids(vs.subrange(i, j))[k]) by { + assert(vs.subrange(i, j)[k] == vs[i + k]); + } +} + +pub proof fn lemma_xnf_tasks_append(g: model::Graph, a: Seq, b: Seq) + requires xnf_tasks(g, a), xnf_tasks(g, b), + ensures xnf_tasks(g, a + b), +{ + assert forall|i: int| 0 <= i < (a + b).len() implies #[trigger] xnf_task(g, (a + b)[i]) by { + if i < a.len() { assert((a + b)[i] == a[i]); } else { assert((a + b)[i] == b[i - a.len()]); } + } +} + +pub proof fn lemma_xnf_tasks_push(g: model::Graph, a: Seq, t: ActionShape) + requires xnf_tasks(g, a), xnf_task(g, t), + ensures xnf_tasks(g, a.push(t)), +{ + assert forall|i: int| 0 <= i < a.push(t).len() implies #[trigger] xnf_task(g, a.push(t)[i]) by { + if i < a.len() { assert(a.push(t)[i] == a[i]); } + } +} + +pub proof fn lemma_xnf_tasks_pop(g: model::Graph, a: Seq, t: ActionShape) + requires xnf_tasks(g, a.push(t)), + ensures xnf_tasks(g, a), xnf_task(g, t), +{ + assert(a.push(t)[a.len() as int] == t); + assert forall|i: int| 0 <= i < a.len() implies #[trigger] xnf_task(g, a[i]) by { + assert(a.push(t)[i] == a[i]); + } +} + +pub proof fn lemma_xnf1(g: model::Graph, a: ActionShape) + requires xnf_task(g, a), + ensures xnf_tasks(g, seq![a]), +{ + assert(xnf_tasks(g, Seq::::empty())); + lemma_xnf_tasks_push(g, Seq::empty(), a); +} + +pub proof fn lemma_xnf2(g: model::Graph, a: ActionShape, b: ActionShape) + requires xnf_task(g, a), xnf_task(g, b), + ensures xnf_tasks(g, seq![a, b]), +{ + lemma_xnf1(g, a); + lemma_xnf_tasks_push(g, seq![a], b); +} + +pub proof fn lemma_xnf3(g: model::Graph, a: ActionShape, b: ActionShape, c: ActionShape) + requires xnf_task(g, a), xnf_task(g, b), xnf_task(g, c), + ensures xnf_tasks(g, seq![a, b, c]), +{ + lemma_xnf2(g, a, b); + lemma_xnf_tasks_push(g, seq![a, b], c); +} + +/// A pair whose elements are the first two of `t` contributes classes of `t`. +pub proof fn lemma_any_x_pair(s: Seq, t: Seq) + requires s.len() == 2, t.len() >= 2, s[0] == t[0], s[1] == t[1], + ensures forall|w: R| #[trigger] any_x(s, w) ==> any_x(t, w), +{ + assert forall|w: R| #[trigger] any_x(s, w) implies any_x(t, w) by { + let i = choose|i: int| #![trigger s[i]] 0 <= i < s.len() && (s[i].x)(w); + assert(t[i] == s[i]); + } +} + +pub proof fn lemma_tasks_valid1(g: model::Graph, s: Seq, t: ActionShape) + requires s.len() == 1, s[0] == t, norm::transition_action_valid(g, t), + ensures norm::transition_tasks_valid(g, s), +{ + assert forall|i: int| 0 <= i < s.len() implies norm::transition_action_valid(g, s[i]) by { assert(i == 0); } +} + +pub proof fn lemma_rnf_seq2(s: Seq) + requires s.len() == 2, regex_nf(s[0]), regex_nf(s[1]), + ensures all_rnf(s), +{ + assert forall|i: int| 0 <= i < s.len() implies regex_nf(#[trigger] s[i]) by { if i == 0 {} else { assert(i == 1); } } +} + +// ===== stability ===== + +pub proof fn lemma_nf_sum_stable(a: model::Graph, b: model::Graph, t: nat) + requires model::graph_wf(a), model::graph_extends(a, b), t < a.transitions.len(), + ensures nf_sum(a, t) == nf_sum(b, t), nf_prod(a, t) == nf_prod(b, t), nf_lit(a, t) == nf_lit(b, t), + av_of(a, t) == av_of(b, t), b.transitions[t as int] == a.transitions[t as int], t < b.transitions.len(), +{ + lemma_trans_stable(a, b, t); + lemma_av_stable(a, b, t); + assert(a.transitions == b.transitions.subrange(0, a.transitions.len() as int)); +} + +pub proof fn lemma_regex_nf_stable(a: model::Graph, b: model::Graph, r: nat) + requires model::graph_wf(a), model::graph_extends(a, b), r < a.regexes.len(), + ensures model::lift_regex(a, r) == model::lift_regex(b, r), r < b.regexes.len(), +{ + model::lemma_graph_wf_elim(a); + model::lemma_lift_regex_stable(a, b, r); +} + +pub proof fn lemma_all_nf_stable(a: model::Graph, b: model::Graph, ts: Seq) + requires model::graph_wf(a), model::graph_extends(a, b), model::bounded(ts, a.transitions.len()), all_nf(a, ts), + ensures all_nf(b, ts), avs(a, ts) == avs(b, ts), +{ + assert forall|k: int| 0 <= k < ts.len() implies nf_sum(b, #[trigger] ts[k]) by { + lemma_nf_sum_stable(a, b, ts[k]); + } + lemma_avs_stable(a, b, ts); +} + +pub proof fn lemma_xnf_task_stable(a: model::Graph, b: model::Graph, t: ActionShape) + requires model::graph_wf(a), model::graph_extends(a, b), norm::transition_action_valid(a, t), xnf_task(a, t), + ensures xnf_task(b, t), norm::transition_action_valid(b, t), +{ + model::lemma_graph_wf_elim(a); + match t { + ActionShape::Clean(id, _) => { lemma_nf_sum_stable(a, b, id); }, + ActionShape::Not(id) => { lemma_nf_sum_stable(a, b, id); }, + ActionShape::Append(id, r) => { lemma_nf_sum_stable(a, b, id); lemma_regex_nf_stable(a, b, r); }, + ActionShape::Pair(x, y) => { lemma_nf_sum_stable(a, b, x); lemma_nf_sum_stable(a, b, y); }, + ActionShape::Fold(terms, _) => { + lemma_all_nf_stable(a, b, terms); + assert(model::bounded(terms, b.transitions.len())) by { + assert forall|k: int| 0 <= k < terms.len() implies #[trigger] terms[k] < b.transitions.len() by {} + } + }, + ActionShape::AppendResult(r) => { lemma_regex_nf_stable(a, b, r); }, + _ => {}, + } +} + +pub proof fn lemma_xnf_tasks_stable(a: model::Graph, b: model::Graph, ts: Seq) + requires model::graph_wf(a), model::graph_extends(a, b), norm::transition_tasks_valid(a, ts), xnf_tasks(a, ts), + ensures xnf_tasks(b, ts), +{ + assert forall|i: int| 0 <= i < ts.len() implies #[trigger] xnf_task(b, ts[i]) by { + assert(norm::transition_action_valid(a, ts[i])); + assert(xnf_task(a, ts[i])); + lemma_xnf_task_stable(a, b, ts[i]); + } +} + +pub proof fn lemma_values_stable(a: model::Graph, b: model::Graph, vs: Seq) + requires model::graph_wf(a), model::graph_extends(a, b), norm::transition_ids_valid(a, vs), + ensures vavs(a, vs) == vavs(b, vs), xnf_values(a, vs) ==> xnf_values(b, vs), + norm::transition_ids_valid(b, vs), model::bounded(model::transition_ids(vs), a.transitions.len()), +{ + assert(model::bounded(model::transition_ids(vs), a.transitions.len())) by { + assert forall|k: int| 0 <= k < model::transition_ids(vs).len() implies #[trigger] model::transition_ids(vs)[k] < a.transitions.len() by { + assert(model::transition_ids(vs)[k] == vs[k]@); + } + } + lemma_avs_stable(a, b, model::transition_ids(vs)); + if xnf_values(a, vs) { + assert forall|i: int| #![trigger vs[i]] 0 <= i < vs.len() implies nf_sum(b, vs[i]@) by { + lemma_nf_sum_stable(a, b, vs[i]@); + } + } + assert forall|i: int| 0 <= i < vs.len() implies vs[i]@ < b.transitions.len() by { + lemma_nf_sum_stable(a, b, vs[i]@); + } +} + +pub proof fn lemma_tasks_valid_stable(a: model::Graph, b: model::Graph, ts: Seq) + requires model::graph_wf(a), model::graph_extends(a, b), norm::transition_tasks_valid(a, ts), + ensures norm::transition_tasks_valid(b, ts), +{ + assert forall|i: int| 0 <= i < ts.len() implies norm::transition_action_valid(b, ts[i]) by { + assert(norm::transition_action_valid(a, ts[i])); + match ts[i] { + ActionShape::Fold(terms, _) => { + assert forall|k: int| 0 <= k < terms.len() implies #[trigger] terms[k] < b.transitions.len() by {} + }, + _ => {}, + } + } +} + +/// The typed configuration before a step survives graph extension, with the same abstract effect. +pub proof fn lemma_xpre_stable(a: model::Graph, b: model::Graph, task: ActionShape, pending: Seq, prior: Seq) + requires model::graph_wf(a), model::graph_extends(a, b), norm::transition_tasks_valid(a, pending), + norm::transition_action_valid(a, task), norm::transition_ids_valid(a, prior), xpre(a, task, pending, prior), + ensures xpre(b, task, pending, prior), vavs(a, prior) == vavs(b, prior), + aapply(a, task, vavs(a, prior)) == aapply(b, task, vavs(b, prior)), + norm::transition_action_valid(b, task), norm::transition_tasks_valid(b, pending), norm::transition_ids_valid(b, prior), +{ + reveal(xpre); + lemma_xnf_tasks_stable(a, b, pending); + lemma_xnf_task_stable(a, b, task); + lemma_values_stable(a, b, prior); + lemma_aapply_stable(a, b, task, vavs(a, prior)); + lemma_tasks_valid_stable(a, b, pending); +} + +// ===== the generic step ===== + +pub proof fn lemma_aapply_push(g: model::Graph, task: ActionShape, s: Seq) + requires norm::transition_action_pushes(task), + ensures aapply(g, task, s) == Some(s.push(push_av(g, task))), +{} + +pub proof fn lemma_aref_refl(s: Seq) + ensures aref(Some(s), Some(s)), +{ + lemma_stack_le_refl(s); +} + +pub proof fn lemma_aref_push(s: Seq, x: AV, y: AV) + requires av_le(y, x), + ensures aref(Some(s.push(x)), Some(s.push(y))), +{ + lemma_stack_le_refl(s); + lemma_stack_le_push(s, s, y, x); +} + +pub open spec fn xctx(e: model::Graph, g: model::Graph, task: ActionShape, p0: Seq, v0: Seq) -> bool { + &&& model::graph_wf(e) && model::graph_wf(g) && model::graph_extends(e, g) + &&& norm::transition_configuration_valid(e, p0, v0) && norm::transition_action_valid(e, task) + &&& xpre(e, task, p0, v0) +} + +/// A pushing step whose expansion `exp` run on the new values `v1` pushes `y` below the action's +/// effect. +pub proof fn lemma_effect(e: model::Graph, g: model::Graph, task: ActionShape, p0: Seq, v0: Seq, + exp: Seq, v1: Seq, y: AV) + requires xctx(e, g, task, p0, v0), norm::transition_action_pushes(task), + xnf_tasks(g, exp), xnf_values(g, v1), + arun(g, exp, vavs(g, v1)) == Some(vavs(g, v0).push(y)), + av_le(y, push_av(g, task)), + ensures xeffect(g, task, p0, v0, p0 + exp, v1), +{ + reveal(xpre); reveal(xeffect); + lemma_xpre_stable(e, g, task, p0, v0); + lemma_xnf_tasks_append(g, p0, exp); + assert((p0 + exp).subrange(p0.len() as int, (p0 + exp).len() as int) =~= exp); + assert(p0.is_prefix_of(p0 + exp)) by { assert((p0 + exp).subrange(0, p0.len() as int) =~= p0); } + lemma_aapply_push(g, task, vavs(g, v0)); + lemma_aref_push(vavs(g, v0), push_av(g, task), y); +} + +/// A pushing step that pushes the value `out`. +pub proof fn lemma_effect_value(e: model::Graph, g: model::Graph, task: ActionShape, p0: Seq, v0: Seq, + out: TransitionId) + requires xctx(e, g, task, p0, v0), norm::transition_action_pushes(task), nf_sum(g, out@), + av_le(av_of(g, out@), push_av(g, task)), + ensures xeffect(g, task, p0, v0, p0, v0.push(out)), +{ + reveal(xpre); reveal(xeffect); + lemma_xpre_stable(e, g, task, p0, v0); + lemma_xnf_values_push(g, v0, out); + lemma_vavs_push(g, v0, out); + assert(xnf_tasks(g, Seq::::empty())); + lemma_effect(e, g, task, p0, v0, Seq::empty(), v0.push(out), av_of(g, out@)); + assert(p0 + Seq::::empty() =~= p0); +} + +// ===== runs of short expansions ===== + +pub proof fn lemma_arun_one(g: model::Graph, t: ActionShape, s: Seq) + ensures arun(g, seq![t], s) == aapply(g, t, s), +{ + assert(seq![t].drop_last() =~= Seq::::empty()); + assert(seq![t].last() == t); + match aapply(g, t, s) { + Some(n) => { assert(arun(g, Seq::::empty(), n) == Some(n)); }, + None => {}, + } +} + +/// `arun(p.push(t), s)` runs `t` first. +pub proof fn lemma_arun_push(g: model::Graph, p: Seq, t: ActionShape, s: Seq) + ensures arun(g, p.push(t), s) == match aapply(g, t, s) { Some(n) => arun(g, p, n), None => None }, +{ + assert(p.push(t).drop_last() =~= p); + assert(p.push(t).last() == t); +} + +// ===== classes of nodes ===== + +pub proof fn lemma_tc(g: model::Graph, t: nat, v: R) + ensures (tc(g))(t, v) == tcls(g, t, v), (yc(g))(t, v) == ycls(g, t, v), +{} + +/// A conditional's abstract value is the join of its branches'. +pub proof fn lemma_if_cls(g: model::Graph, t: nat, test: nat, a: nat, b: nat) + requires model::graph_wf(g), t < g.transitions.len(), g.transitions[t as int] == model::TransitionNode::If(test, a, b), + ensures av_le(av_if(av_of(g, a), av_of(g, b)), av_of(g, t)), av_le(av_of(g, a), av_of(g, t)), av_le(av_of(g, b), av_of(g, t)), + av_le(av_of(g, t), av_if(av_of(g, a), av_of(g, b))), a < t, b < t, +{ + model::lemma_graph_transition_wf(g, t); + assert forall|v: R| #[trigger] tcls(g, a, v) implies tcls(g, t, v) by { lemma_tcls(g, t, v); } + assert forall|v: R| #[trigger] tcls(g, b, v) implies tcls(g, t, v) by { lemma_tcls(g, t, v); } + assert forall|v: R| #[trigger] ycls(g, a, v) implies ycls(g, t, v) by { lemma_ycls(g, t, v); } + assert forall|v: R| #[trigger] ycls(g, b, v) implies ycls(g, t, v) by { lemma_ycls(g, t, v); } + assert forall|v: R| #[trigger] tcls(g, t, v) implies tcls(g, a, v) || tcls(g, b, v) by { lemma_tcls(g, t, v); } + assert forall|v: R| #[trigger] ycls(g, t, v) implies ycls(g, a, v) || ycls(g, b, v) by { lemma_ycls(g, t, v); } +} + +/// A union's abstract value is the union of its children's; children are below it. +pub proof fn lemma_union_cls(g: model::Graph, t: nat, cs: Seq) + requires model::graph_wf(g), t < g.transitions.len(), g.transitions[t as int] == model::TransitionNode::Union(cs), + ensures av_le(av_union(avs(g, cs)), av_of(g, t)), + forall|i: int| 0 <= i < cs.len() ==> #[trigger] av_le(av_of(g, cs[i]), av_of(g, t)), + model::bounded(cs, t), +{ + model::lemma_graph_transition_wf(g, t); + let s = avs(g, cs); + assert forall|v: R| #[trigger] (av_union(s).x)(v) implies tcls(g, t, v) by { + lemma_tcls(g, t, v); + if any_x(s, v) { + let i = choose|i: int| #![trigger s[i]] 0 <= i < s.len() && (s[i].x)(v); + assert(s[i] == av_of(g, cs[i])); + assert(cs[i] < t); + assert(kids(tc(g), t, cs, v)); + } + } + let yb = |w: R| kids(yc(g), t, cs, w); + assert forall|v: R| #[trigger] (av_union(s).y)(v) implies ycls(g, t, v) by { + lemma_ycls(g, t, v); + assert forall|w: R| #[trigger] any_y(s, w) implies yb(w) by { + let i = choose|i: int| #![trigger s[i]] 0 <= i < s.len() && (s[i].y)(w); + assert(s[i] == av_of(g, cs[i])); + assert(cs[i] < t); + } + lemma_cl_mono(false, |w: R| any_y(s, w), yb, v); + } + assert forall|i: int| 0 <= i < cs.len() implies #[trigger] av_le(av_of(g, cs[i]), av_of(g, t)) by { + assert(cs[i] < t); + assert forall|v: R| #[trigger] tcls(g, cs[i], v) implies tcls(g, t, v) by { + lemma_tcls(g, t, v); + assert(kids(tc(g), t, cs, v)); + } + assert forall|v: R| #[trigger] ycls(g, cs[i], v) implies ycls(g, t, v) by { + lemma_ycls(g, t, v); + assert(yb(v)); + lemma_cl_base(false, yb, v); + } + } +} + +/// An intersection's abstract value is the closure of its children's. +pub proof fn lemma_inter_cls(g: model::Graph, t: nat, cs: Seq) + requires model::graph_wf(g), t < g.transitions.len(), g.transitions[t as int] == model::TransitionNode::Intersect(cs), + ensures av_le(av_meet(avs(g, cs)), av_of(g, t)), + forall|v: R| #[trigger] ycls(g, t, v), + forall|i: int, v: R| 0 <= i < cs.len() && #[trigger] tcls(g, cs[i], v) ==> tcls(g, t, v), + model::bounded(cs, t), +{ + model::lemma_graph_transition_wf(g, t); + let s = avs(g, cs); + let kb = |w: R| kids(tc(g), t, cs, w); + assert forall|w: R| #[trigger] any_x(s, w) implies kb(w) by { + let i = choose|i: int| #![trigger s[i]] 0 <= i < s.len() && (s[i].x)(w); + assert(s[i] == av_of(g, cs[i])); + assert(cs[i] < t); + } + assert forall|v: R| #[trigger] (av_meet(s).x)(v) implies tcls(g, t, v) by { + lemma_tcls(g, t, v); + lemma_cl_mono(true, |w: R| any_x(s, w), kb, v); + } + assert forall|v: R| #[trigger] ycls(g, t, v) by { lemma_ycls(g, t, v); } + assert forall|i: int, v: R| 0 <= i < cs.len() && #[trigger] tcls(g, cs[i], v) implies tcls(g, t, v) by { + assert(cs[i] < t); + lemma_tcls(g, t, v); + assert(kb(v)); + lemma_cl_base(true, kb, v); + } +} + +/// A complement node's abstract value is the complement of its operand's (both ways). +pub proof fn lemma_not_cls(g: model::Graph, t: nat, k: nat) + requires model::graph_wf(g), t < g.transitions.len(), g.transitions[t as int] == model::TransitionNode::Not(k), + ensures av_le(av_neg(av_of(g, k)), av_of(g, t)), av_le(av_of(g, t), av_neg(av_of(g, k))), k < t, +{ + model::lemma_graph_transition_wf(g, t); + let nb = |w: R| negs(tc(g), t, k, w); + let ob = |w: R| neg_of(av_of(g, k), w); + assert forall|w: R| #[trigger] nb(w) <==> ob(w) by { + if nb(w) { let x = choose|x: R| k < t && (tc(g))(k, x) && w == #[trigger] r_not(x); assert((av_of(g, k).x)(x)); } + if ob(w) { let x = choose|x: R| (av_of(g, k).x)(x) && w == #[trigger] r_not(x); assert((tc(g))(k, x)); } + } + assert forall|v: R| #[trigger] tcls(g, t, v) <==> (av_neg(av_of(g, k)).x)(v) by { + lemma_tcls(g, t, v); + if cl(true, nb, v) { lemma_cl_mono(true, nb, ob, v); } + if cl(true, ob, v) { lemma_cl_mono(true, ob, nb, v); } + } + assert forall|v: R| #[trigger] ycls(g, t, v) by { lemma_ycls(g, t, v); } +} + +/// An append node's class: constants and `N(w s)` for members `w` of its body's class. +pub proof fn lemma_append_cls(g: model::Graph, t: nat, k: nat, rs: Seq) + requires model::graph_wf(g), t < g.transitions.len(), g.transitions[t as int] == model::TransitionNode::Append(k, rs), + ensures forall|v: R| #[trigger] tcls(g, t, v) <==> (rconst(v) || exists|w: R| tcls(g, k, w) && v == #[trigger] ccat(g, w, rs)), + forall|v: R| #[trigger] ycls(g, t, v), k < t, +{ + model::lemma_graph_transition_wf(g, t); + assert forall|v: R| #[trigger] tcls(g, t, v) <==> (rconst(v) || exists|w: R| tcls(g, k, w) && v == #[trigger] ccat(g, w, rs)) by { + lemma_tcls(g, t, v); + if exists|w: R| tcls(g, k, w) && v == #[trigger] ccat(g, w, rs) { + let w = choose|w: R| tcls(g, k, w) && v == #[trigger] ccat(g, w, rs); + assert((tc(g))(k, w)); + } + } + assert forall|v: R| #[trigger] ycls(g, t, v) by { lemma_ycls(g, t, v); } +} + +/// A constant node's class: constants and its regex. +pub proof fn lemma_const_cls(g: model::Graph, t: nat, r: nat) + requires t < g.transitions.len(), g.transitions[t as int] == model::TransitionNode::Const(r), + ensures forall|v: R| #[trigger] tcls(g, t, v) <==> (rconst(v) || v == model::lift_regex(g, r)), + forall|v: R| #[trigger] ycls(g, t, v) <==> v == model::lift_regex(g, r), +{ + assert forall|v: R| #[trigger] tcls(g, t, v) <==> (rconst(v) || v == model::lift_regex(g, r)) by { lemma_tcls(g, t, v); } + assert forall|v: R| #[trigger] ycls(g, t, v) <==> v == model::lift_regex(g, r) by { lemma_ycls(g, t, v); } +} + +/// The constant transitions have constant classes. +pub proof fn lemma_const_transitions(g: model::Graph) + requires model::graph_wf(g), + ensures + forall|v: R| #[trigger] tcls(g, g.constants.transition_empty, v) ==> rconst(v), + forall|v: R| #[trigger] tcls(g, g.constants.transition_all, v) ==> rconst(v), + forall|v: R| #[trigger] tcls(g, g.constants.transition_epsilon, v) ==> rconst(v), + forall|v: R| #[trigger] ycls(g, g.constants.transition_empty, v) ==> v == Regex::::Empty, + forall|v: R| #[trigger] ycls(g, g.constants.transition_epsilon, v) ==> v == Regex::::Epsilon, + nf_sum(g, g.constants.transition_empty), nf_sum(g, g.constants.transition_all), nf_sum(g, g.constants.transition_epsilon), + g.constants.transition_empty < g.transitions.len(), g.constants.transition_all < g.transitions.len(), + g.constants.transition_epsilon < g.transitions.len(), +{ + model::lemma_graph_wf_elim(g); + norm::regex_constants(g); + let c = g.constants; + lemma_const_cls(g, c.transition_empty, c.empty); + lemma_const_cls(g, c.transition_all, c.all); + lemma_const_cls(g, c.transition_epsilon, c.epsilon); +} + +// ===== normal forms ===== + +pub proof fn lemma_nf_weaken(g: model::Graph, t: nat) + ensures nf_lit(g, t) ==> nf_prod(g, t), nf_prod(g, t) ==> nf_sum(g, t), +{ + if t < g.transitions.len() { + match g.transitions[t as int] { + model::TransitionNode::Intersect(cs) => {}, + model::TransitionNode::If(_, _, _) => {}, + model::TransitionNode::Union(_) => {}, + _ => {}, + } + } +} + +/// Children of normal forms are normal forms. +pub proof fn lemma_nf_children(g: model::Graph, t: nat) + requires nf_sum(g, t), + ensures match g.transitions[t as int] { + model::TransitionNode::If(_, a, b) => nf_sum(g, a) && nf_sum(g, b), + model::TransitionNode::Union(cs) => all_nf(g, cs), + model::TransitionNode::Intersect(cs) => all_nf(g, cs) && forall|i: int| 0 <= i < cs.len() ==> nf_lit(g, #[trigger] cs[i]), + model::TransitionNode::Not(k) => nf_lit(g, k) && nf_sum(g, k), + model::TransitionNode::Append(k, rs) => nf_prod(g, k) && nf_sum(g, k) && nats_nf(g, rs) && model::bounded(rs, g.regexes.len()), + model::TransitionNode::Const(r) => r < g.regexes.len() && regex_nf(model::lift_regex(g, r)), + }, +{ + match g.transitions[t as int] { + model::TransitionNode::Intersect(cs) => { + assert forall|k: int| 0 <= k < cs.len() implies nf_sum(g, #[trigger] cs[k]) by { + lemma_nf_weaken(g, cs[k]); + } + }, + model::TransitionNode::Not(k) => { lemma_nf_weaken(g, k); }, + model::TransitionNode::Append(k, rs) => { lemma_nf_weaken(g, k); }, + _ => {}, + } +} + +/// Members of the class of a normal form are normal forms. +pub proof fn lemma_cls_nf(g: model::Graph, t: nat, v: R) + requires nf_sum(g, t), tcls(g, t, v), + ensures regex_nf(v), +{ + lemma_tcls_nf(g, t, v); +} + +pub proof fn lemma_not_not(v: R) + requires regex_nf(v), + ensures r_not(r_not(v)) == v, +{ + match v { + Regex::Not(b) => {}, + _ => {}, + } +} + +// ===== (N4′) ===== + +pub proof fn lemma_has_empty_concat(m: Model, a: Seq, b: Seq) + ensures m.has_empty(a + b) == (m.has_empty(a) || m.has_empty(b)), +{ + if m.has_empty(a + b) { + let i = choose|i: int| 0 <= i < (a + b).len() && (a + b)[i] == m.empty; + if i < a.len() { assert(a[i] == (a + b)[i]); } else { assert(b[i - a.len()] == (a + b)[i]); } + } + if m.has_empty(a) { + let i = choose|i: int| 0 <= i < a.len() && a[i] == m.empty; + assert((a + b)[i] == a[i]); + } + if m.has_empty(b) { + let i = choose|i: int| 0 <= i < b.len() && b[i] == m.empty; + assert((a + b)[a.len() + i] == b[i]); + } +} + +pub open spec fn all_rnf(xs: Seq) -> bool { + forall|i: int| 0 <= i < xs.len() ==> regex_nf(#[trigger] xs[i]) +} + +pub proof fn lemma_all_rnf_concat(a: Seq, b: Seq) + requires all_rnf(a), all_rnf(b), + ensures all_rnf(a + b), +{ + assert forall|i: int| 0 <= i < (a + b).len() implies regex_nf(#[trigger] (a + b)[i]) by { + if i < a.len() { assert((a + b)[i] == a[i]); } else { assert((a + b)[i] == b[i - a.len()]); } + } +} + +/// (N4′): inlining a normalized concatenation of normal forms does not change `N`. +pub proof fn lemma_cat_inline(xs: Seq, ys: Seq, zs: Seq) + requires all_rnf(xs), all_rnf(ys), all_rnf(zs), + ensures r_cat(xs + seq![r_cat(ys)] + zs) == r_cat(xs + ys + zs), +{ + let m = m_impl(); + theorem_impl_contract(); + lemma_models_agree(); + let z = r_cat(ys); + lemma_cat_nf(ys); + let l = xs + seq![z] + zs; + let r = xs + ys + zs; + assert(all_rnf(seq![z])) by { assert forall|i: int| 0 <= i < 1 implies regex_nf(#[trigger] seq![z][i]) by {} } + lemma_all_rnf_concat(xs, seq![z]); + lemma_all_rnf_concat(xs + seq![z], zs); + lemma_all_rnf_concat(xs, ys); + lemma_all_rnf_concat(xs + ys, zs); + assert(m.states(l)) by { assert forall|i: int| 0 <= i < l.len() implies m.st(#[trigger] l[i]) by {} } + assert(m.states(r)) by { assert forall|i: int| 0 <= i < r.len() implies m.st(#[trigger] r[i]) by {} } + assert(m.states(ys)) by { assert forall|i: int| 0 <= i < ys.len() implies m.st(#[trigger] ys[i]) by {} } + assert(m.cat_shape(l)); + assert(m.cat_shape(r)); + assert(m.cat_shape(ys)); + lemma_flat_agree(m, pre(), l); + lemma_flat_agree(m, pre(), r); + lemma_flat_agree(m, pre(), ys); + lemma_has_empty_concat(m, xs, seq![z]); + lemma_has_empty_concat(m, xs + seq![z], zs); + lemma_has_empty_concat(m, xs, ys); + lemma_has_empty_concat(m, xs + ys, zs); + let hz = m.has_empty(seq![z]); + if m.has_empty(ys) { + assert(z == m.empty); + assert(seq![z][0] == m.empty); + } else if m.has_empty(xs) || m.has_empty(zs) { + } else { + lemma_cat_piece(m, ys); + assert(!hz) by { + if hz { let i = choose|i: int| 0 <= i < 1 && seq![z][i] == m.empty; } + } + lemma_flat_append(m, xs, seq![z]); + lemma_flat_append(m, xs + seq![z], zs); + lemma_flat_append(m, xs, ys); + lemma_flat_append(m, xs + ys, zs); + lemma_flat_single(m, z); + lemma_cat_flat_eq(m, l, r); + } +} + +/// `N(w N(ys)) = N(w ys)`. +pub proof fn lemma_cat_nest(w: R, ys: Seq) + requires regex_nf(w), all_rnf(ys), + ensures r_cat(seq![w, r_cat(ys)]) == r_cat(seq![w] + ys), +{ + assert(all_rnf(seq![w])) by { assert forall|i: int| 0 <= i < 1 implies regex_nf(#[trigger] seq![w][i]) by {} } + assert(all_rnf(Seq::::empty())); + lemma_cat_inline(seq![w], ys, Seq::empty()); + assert(seq![w] + seq![r_cat(ys)] + Seq::::empty() =~= seq![w, r_cat(ys)]); + assert(seq![w] + ys + Seq::::empty() =~= seq![w] + ys); +} + +/// `N(w ε) = w`. +pub proof fn lemma_cat_eps(w: R) + requires regex_nf(w), + ensures r_cat(seq![w, Regex::Epsilon]) == w, +{ + theorem_impl_contract(); + lemma_models_agree(); + assert(all_rnf(Seq::::empty())); + assert(pre().flat(Seq::::empty()) =~= Seq::::empty()); + assert(!pre().has_empty(Seq::::empty())); + assert(r_cat(Seq::::empty()) == Regex::::Epsilon); + lemma_cat_nest(w, Seq::empty()); + assert(seq![w] + Seq::::empty() =~= seq![w]); + lemma_cat_single(m_impl(), w); +} + +/// `N(N(w ys) z) = N(w N(ys z))`. +pub proof fn lemma_cat_shift(w: R, ys: Seq, z: R) + requires regex_nf(w), all_rnf(ys), regex_nf(z), + ensures r_cat(seq![r_cat(seq![w] + ys), z]) == r_cat(seq![w, r_cat(ys.push(z))]), +{ + let ws = seq![w]; + let zs = seq![z]; + assert(all_rnf(ws)) by { assert forall|i: int| 0 <= i < 1 implies regex_nf(#[trigger] ws[i]) by {} } + assert(all_rnf(zs)) by { assert forall|i: int| 0 <= i < 1 implies regex_nf(#[trigger] zs[i]) by {} } + assert(all_rnf(Seq::::empty())); + lemma_all_rnf_concat(ws, ys); + lemma_all_rnf_concat(ys, zs); + assert(ys.push(z) =~= ys + zs); + lemma_cat_inline(Seq::empty(), ws + ys, zs); + assert(Seq::::empty() + seq![r_cat(ws + ys)] + zs =~= seq![r_cat(seq![w] + ys), z]); + assert(Seq::::empty() + (ws + ys) + zs =~= ws + ys + zs); + lemma_cat_inline(ws, ys + zs, Seq::empty()); + assert(ws + seq![r_cat(ys + zs)] + Seq::::empty() =~= seq![w, r_cat(ys.push(z))]); + assert(ws + (ys + zs) + Seq::::empty() =~= ws + ys + zs); +} + +/// A list state is the normal form of its elements. +pub proof fn lemma_cat_list(ls: Seq) + requires regex_nf(Regex::Concat(ls)), + ensures r_cat(ls) == Regex::Concat(ls), all_rnf(ls), +{ + theorem_impl_contract(); + lemma_models_agree(); + let m = m_impl(); + assert(m.atoms(ls)) by { + assert forall|i: int| 0 <= i < ls.len() implies m.atom(#[trigger] ls[i]) by {} + } + lemma_cat_atoms(m, ls); + assert(all_rnf(ls)) by { assert forall|i: int| 0 <= i < ls.len() implies regex_nf(#[trigger] ls[i]) by {} } +} + +} // verus! diff --git a/src/history-semantics/src/verify/finite_trans.rs b/src/history-semantics/src/verify/finite_trans.rs new file mode 100644 index 000000000..6696dd357 --- /dev/null +++ b/src/history-semantics/src/verify/finite_trans.rs @@ -0,0 +1,953 @@ +//! Transition-level successor equations for the implementation (the +//! successor equations (S0)–(S6) of `finite_states::Model::contract`, for normalized transitions). +//! +//! A transition id `t` of a graph gets +//! - a *class* [`tcls`]: the literal and product values it may contribute (a single class +//! suffices: for every non-sum node, the literal class and the product class coincide; an +//! intersection's class is the `N(&·)` closure of its operands' classes, which covers merged +//! leaves; a complement's class is the closure of the complemented operand class; a +//! concatenation's class is `N(v s)` for the values `v` of its body's class); +//! - a *sum class* [`ycls`] bounding its value through conditionals and unions only (exact for +//! conditional trees of leaves, used for the constant/test case (S1)); +//! - its values [`tval`]: what `TransitionId::interpret` may return, with every normalized union, +//! intersection, complement, and concatenation taken in the relations of `m_impl`; +//! - the normal form [`nf_sum`]: conditionals and unions over products, each an intersection of +//! literals or a literal, a literal being a normal-form leaf, a complemented literal, or a +//! concatenation of a product with normal-form suffixes. +//! The three relations are least fixpoints of one-step equations ([`lfp`]), unfolded by +//! [`lemma_tcls`], [`lemma_ycls`], [`lemma_tval`]. [`lemma_sum_sound`] shows that the values of +//! a normal-form transition are normalized unions of its class; [`lemma_succ_from_class`] turns +//! a class bound for the derivative of `p` into successors of `p` in `m_impl`. +use crate::verify::finite_impl::*; +use crate::verify::finite_link::*; +use crate::verify::finite_states::*; +use junco_core::kernel::verify as model; +use junco_core::verify::history_specs::Regex; +use vstd::prelude::*; + +verus! { + +pub open spec fn rconst(v: R) -> bool { + v == Regex::::Empty || v == Regex::::Epsilon || v == Regex::::All +} + +/// `⟨base⟩&` (`inter`) or `⟨base⟩+` in `m_impl`. +pub open spec fn cl(inter: bool, base: spec_fn(R) -> bool, v: R) -> bool { + m_impl().built(inter, base, v) +} + +/// `N(w s₁⋯sₙ)` for the lifted suffix ids `rs`. +pub open spec fn ccat(g: model::Graph, w: R, rs: Seq) -> R { + r_cat(seq![w] + model::lift_regexes(g, rs)) +} + +// ===== least fixpoints ===== + +/// A relation between transition ids and trees. +pub type Rel = spec_fn(nat, R) -> bool; + +pub open spec fn rel_le(a: Rel, b: Rel) -> bool { + forall|t: nat, v: R| #[trigger] a(t, v) ==> b(t, v) +} + +pub open spec fn step_mono(step: spec_fn(Rel, nat, R) -> bool) -> bool { + forall|a: Rel, b: Rel, t: nat, v: R| #![trigger step(a, t, v), step(b, t, v)] + rel_le(a, b) && step(a, t, v) ==> step(b, t, v) +} + +pub open spec fn pre_closed(step: spec_fn(Rel, nat, R) -> bool, c: Rel) -> bool { + forall|t: nat, v: R| #[trigger] step(c, t, v) ==> c(t, v) +} + +pub open spec fn lfp(step: spec_fn(Rel, nat, R) -> bool, t: nat, v: R) -> bool { + forall|c: Rel| #[trigger] pre_closed(step, c) ==> c(t, v) +} + +pub open spec fn lfp_rel(step: spec_fn(Rel, nat, R) -> bool) -> Rel { + |t: nat, v: R| lfp(step, t, v) +} + +pub proof fn lemma_lfp_fold(step: spec_fn(Rel, nat, R) -> bool, t: nat, v: R) + requires step_mono(step), step(lfp_rel(step), t, v), + ensures lfp(step, t, v), +{ + assert forall|c: Rel| #[trigger] pre_closed(step, c) implies c(t, v) by { + assert(rel_le(lfp_rel(step), c)) by { + assert forall|x: nat, w: R| #[trigger] (lfp_rel(step))(x, w) implies c(x, w) by { + assert(lfp(step, x, w)); + } + } + assert(step(c, t, v)); + } +} + +pub proof fn lemma_lfp_unfold(step: spec_fn(Rel, nat, R) -> bool, t: nat, v: R) + requires step_mono(step), lfp(step, t, v), + ensures step(lfp_rel(step), t, v), +{ + let d: Rel = |x: nat, w: R| step(lfp_rel(step), x, w); + assert(pre_closed(step, d)) by { + assert forall|x: nat, w: R| #[trigger] step(d, x, w) implies d(x, w) by { + assert(rel_le(d, lfp_rel(step))) by { + assert forall|y: nat, u: R| #[trigger] d(y, u) implies (lfp_rel(step))(y, u) by { + lemma_lfp_fold(step, y, u); + } + } + } + } +} + +// ===== the class ===== + +pub open spec fn kids(c: Rel, t: nat, cs: Seq, w: R) -> bool { + exists|i: int| #![trigger cs[i]] 0 <= i < cs.len() && cs[i] < t && c(cs[i], w) +} + +pub open spec fn negs(c: Rel, t: nat, k: nat, w: R) -> bool { + exists|x: R| k < t && c(k, x) && w == #[trigger] r_not(x) +} + +pub open spec fn apps(g: model::Graph, c: Rel, t: nat, k: nat, rs: Seq, v: R) -> bool { + exists|w: R| k < t && c(k, w) && v == #[trigger] ccat(g, w, rs) +} + +/// One step of the class equations. +pub open spec fn cls_step(g: model::Graph, c: Rel, t: nat, v: R) -> bool { + if t >= g.transitions.len() { rconst(v) } else { + match g.transitions[t as int] { + model::TransitionNode::Const(r) => rconst(v) || v == model::lift_regex(g, r), + model::TransitionNode::If(_, a, b) => (a < t && c(a, v)) || (b < t && c(b, v)), + model::TransitionNode::Union(cs) => rconst(v) || kids(c, t, cs, v), + model::TransitionNode::Intersect(cs) => cl(true, |w: R| kids(c, t, cs, w), v), + model::TransitionNode::Not(k) => cl(true, |w: R| negs(c, t, k, w), v), + model::TransitionNode::Append(k, rs) => rconst(v) || apps(g, c, t, k, rs, v), + } + } +} + +pub open spec fn cls_steps(g: model::Graph) -> spec_fn(Rel, nat, R) -> bool { + |c: Rel, t: nat, v: R| cls_step(g, c, t, v) +} + +/// Class of a transition (see the module documentation). +pub open spec fn tcls(g: model::Graph, t: nat, v: R) -> bool { + lfp(cls_steps(g), t, v) +} + +pub open spec fn tc(g: model::Graph) -> Rel { + lfp_rel(cls_steps(g)) +} + +/// One step of the sum-class equations. +pub open spec fn ycls_step(g: model::Graph, c: Rel, t: nat, v: R) -> bool { + if t >= g.transitions.len() { true } else { + match g.transitions[t as int] { + model::TransitionNode::Const(r) => v == model::lift_regex(g, r), + model::TransitionNode::If(_, a, b) => (a < t && c(a, v)) || (b < t && c(b, v)), + model::TransitionNode::Union(cs) => cl(false, |w: R| kids(c, t, cs, w), v), + _ => true, + } + } +} + +pub open spec fn ycls_steps(g: model::Graph) -> spec_fn(Rel, nat, R) -> bool { + |c: Rel, t: nat, v: R| ycls_step(g, c, t, v) +} + +/// Sum class of a transition. +pub open spec fn ycls(g: model::Graph, t: nat, v: R) -> bool { + lfp(ycls_steps(g), t, v) +} + +pub open spec fn yc(g: model::Graph) -> Rel { + lfp_rel(ycls_steps(g)) +} + +/// `vs` are values of the children `cs` (below `t`). +pub open spec fn kid_vals(c: Rel, t: nat, cs: Seq, vs: Seq) -> bool { + vs.len() == cs.len() && forall|i: int| #![trigger vs[i]] #![trigger cs[i]] 0 <= i < cs.len() ==> cs[i] < t && c(cs[i], vs[i]) +} + +/// One step of the value equations. +pub open spec fn val_step(g: model::Graph, c: Rel, t: nat, v: R) -> bool { + if t >= g.transitions.len() { false } else { + match g.transitions[t as int] { + model::TransitionNode::Const(r) => v == model::lift_regex(g, r), + model::TransitionNode::If(_, a, b) => (a < t && c(a, v)) || (b < t && c(b, v)), + model::TransitionNode::Union(cs) => + exists|vs: Seq| #[trigger] kid_vals(c, t, cs, vs) && (core().nset)(false, vs.to_set(), v), + model::TransitionNode::Intersect(cs) => + exists|vs: Seq| #[trigger] kid_vals(c, t, cs, vs) && (core().nset)(true, vs.to_set(), v), + model::TransitionNode::Not(k) => negs(c, t, k, v), + model::TransitionNode::Append(k, rs) => apps(g, c, t, k, rs, v), + } + } +} + +pub open spec fn val_steps(g: model::Graph) -> spec_fn(Rel, nat, R) -> bool { + |c: Rel, t: nat, v: R| val_step(g, c, t, v) +} + +/// Values of a transition under some selection of the branches of its conditionals. +pub open spec fn tval(g: model::Graph, t: nat, v: R) -> bool { + lfp(val_steps(g), t, v) +} + +pub open spec fn tv(g: model::Graph) -> Rel { + lfp_rel(val_steps(g)) +} + +// ----- monotonicity and unfolding ----- + +pub proof fn lemma_cl_mono(inter: bool, b1: spec_fn(R) -> bool, b2: spec_fn(R) -> bool, v: R) + requires forall|w: R| #[trigger] b1(w) ==> b2(w), cl(inter, b1, v), + ensures cl(inter, b2, v), +{ + lemma_built_mono(m_impl(), m_impl(), inter, b1, b2, v); +} + +pub proof fn lemma_steps_mono(g: model::Graph) + ensures step_mono(cls_steps(g)), step_mono(ycls_steps(g)), step_mono(val_steps(g)), +{ + assert forall|a: Rel, b: Rel, t: nat, v: R| #![trigger (cls_steps(g))(a, t, v), (cls_steps(g))(b, t, v)] + rel_le(a, b) && (cls_steps(g))(a, t, v) implies (cls_steps(g))(b, t, v) by { + if t < g.transitions.len() { + match g.transitions[t as int] { + model::TransitionNode::Union(cs) => { + if !rconst(v) { + let i = choose|i: int| #![trigger cs[i]] 0 <= i < cs.len() && cs[i] < t && a(cs[i], v); + assert(b(cs[i], v)); + } + }, + model::TransitionNode::Intersect(cs) => { + assert forall|w: R| #[trigger] kids(a, t, cs, w) implies kids(b, t, cs, w) by { + let i = choose|i: int| #![trigger cs[i]] 0 <= i < cs.len() && cs[i] < t && a(cs[i], w); + assert(b(cs[i], w)); + } + lemma_cl_mono(true, |w: R| kids(a, t, cs, w), |w: R| kids(b, t, cs, w), v); + }, + model::TransitionNode::Not(k) => { + assert forall|w: R| #[trigger] negs(a, t, k, w) implies negs(b, t, k, w) by { + let x = choose|x: R| k < t && a(k, x) && w == #[trigger] r_not(x); + assert(b(k, x)); + } + lemma_cl_mono(true, |w: R| negs(a, t, k, w), |w: R| negs(b, t, k, w), v); + }, + model::TransitionNode::Append(k, rs) => { + if !rconst(v) { + let w = choose|w: R| k < t && a(k, w) && v == #[trigger] ccat(g, w, rs); + assert(b(k, w)); + } + }, + _ => {}, + } + } + } + assert forall|a: Rel, b: Rel, t: nat, v: R| #![trigger (ycls_steps(g))(a, t, v), (ycls_steps(g))(b, t, v)] + rel_le(a, b) && (ycls_steps(g))(a, t, v) implies (ycls_steps(g))(b, t, v) by { + if t < g.transitions.len() { + match g.transitions[t as int] { + model::TransitionNode::Union(cs) => { + assert forall|w: R| #[trigger] kids(a, t, cs, w) implies kids(b, t, cs, w) by { + let i = choose|i: int| #![trigger cs[i]] 0 <= i < cs.len() && cs[i] < t && a(cs[i], w); + assert(b(cs[i], w)); + } + lemma_cl_mono(false, |w: R| kids(a, t, cs, w), |w: R| kids(b, t, cs, w), v); + }, + _ => {}, + } + } + } + assert forall|a: Rel, b: Rel, t: nat, v: R| #![trigger (val_steps(g))(a, t, v), (val_steps(g))(b, t, v)] + rel_le(a, b) && (val_steps(g))(a, t, v) implies (val_steps(g))(b, t, v) by { + if t < g.transitions.len() { + match g.transitions[t as int] { + model::TransitionNode::Union(cs) => { + let vs = choose|vs: Seq| #[trigger] kid_vals(a, t, cs, vs) && (core().nset)(false, vs.to_set(), v); + assert(kid_vals(a, t, cs, vs)); + assert forall|i: int| 0 <= i < cs.len() implies cs[i] < t && b(cs[i], #[trigger] vs[i]) by { + assert(cs[i] < t && a(cs[i], vs[i])); + assert(rel_le(a, b)); + } + assert(kid_vals(b, t, cs, vs)); + }, + model::TransitionNode::Intersect(cs) => { + let vs = choose|vs: Seq| #[trigger] kid_vals(a, t, cs, vs) && (core().nset)(true, vs.to_set(), v); + assert(kid_vals(a, t, cs, vs)); + assert forall|i: int| 0 <= i < cs.len() implies cs[i] < t && b(cs[i], #[trigger] vs[i]) by { + assert(cs[i] < t && a(cs[i], vs[i])); + assert(rel_le(a, b)); + } + assert(kid_vals(b, t, cs, vs)); + }, + model::TransitionNode::Not(k) => { + let x = choose|x: R| k < t && a(k, x) && v == #[trigger] r_not(x); + assert(b(k, x)); + }, + model::TransitionNode::Append(k, rs) => { + let w = choose|w: R| k < t && a(k, w) && v == #[trigger] ccat(g, w, rs); + assert(b(k, w)); + }, + _ => {}, + } + } + } +} + +pub proof fn lemma_tcls(g: model::Graph, t: nat, v: R) + ensures tcls(g, t, v) == cls_step(g, tc(g), t, v), +{ + lemma_steps_mono(g); + if tcls(g, t, v) { lemma_lfp_unfold(cls_steps(g), t, v); } + if cls_step(g, tc(g), t, v) { lemma_lfp_fold(cls_steps(g), t, v); } +} + +pub proof fn lemma_ycls(g: model::Graph, t: nat, v: R) + ensures ycls(g, t, v) == ycls_step(g, yc(g), t, v), +{ + lemma_steps_mono(g); + if ycls(g, t, v) { lemma_lfp_unfold(ycls_steps(g), t, v); } + if ycls_step(g, yc(g), t, v) { lemma_lfp_fold(ycls_steps(g), t, v); } +} + +pub proof fn lemma_tval(g: model::Graph, t: nat, v: R) + ensures tval(g, t, v) == val_step(g, tv(g), t, v), +{ + lemma_steps_mono(g); + if tval(g, t, v) { lemma_lfp_unfold(val_steps(g), t, v); } + if val_step(g, tv(g), t, v) { lemma_lfp_fold(val_steps(g), t, v); } +} + +// ----- normal form ----- + +pub open spec fn nf_lit(g: model::Graph, t: nat) -> bool + decreases t, 0nat, +{ + t < g.transitions.len() && match g.transitions[t as int] { + model::TransitionNode::Const(r) => r < g.regexes.len() && regex_nf(model::lift_regex(g, r)), + model::TransitionNode::Not(c) => c < t && nf_lit(g, c), + model::TransitionNode::Append(c, rs) => c < t && nf_prod(g, c) + && model::bounded(rs, g.regexes.len()) && nats_nf(g, rs), + _ => false, + } +} + +pub open spec fn nf_prod(g: model::Graph, t: nat) -> bool + decreases t, 1nat, +{ + t < g.transitions.len() && match g.transitions[t as int] { + model::TransitionNode::Intersect(cs) => forall|i: int| 0 <= i < cs.len() ==> cs[i] < t && nf_lit(g, #[trigger] cs[i]), + _ => nf_lit(g, t), + } +} + +pub open spec fn nf_sum(g: model::Graph, t: nat) -> bool + decreases t, 2nat, +{ + t < g.transitions.len() && match g.transitions[t as int] { + model::TransitionNode::If(_, a, b) => a < t && b < t && nf_sum(g, a) && nf_sum(g, b), + model::TransitionNode::Union(cs) => forall|i: int| 0 <= i < cs.len() ==> cs[i] < t && nf_sum(g, #[trigger] cs[i]), + _ => nf_prod(g, t), + } +} + +// ===== closures ===== + +pub proof fn lemma_cl_base(inter: bool, base: spec_fn(R) -> bool, v: R) + requires base(v), + ensures cl(inter, base, v), +{} + +pub proof fn lemma_cl_const(inter: bool, base: spec_fn(R) -> bool, v: R) + requires rconst(v), + ensures cl(inter, base, v), +{} + +/// `⟨⟨X⟩⟩ = ⟨X⟩`. +pub proof fn lemma_cl_idem(inter: bool, base: spec_fn(R) -> bool, v: R) + requires cl(inter, |w: R| cl(inter, base, w), v), + ensures cl(inter, base, v), +{ + let m = m_impl(); + assert forall|u: ISet| m.has_consts(u) && (forall|w: R| #[trigger] base(w) ==> u.contains(w)) + && m.nset_closed(inter, u) implies #[trigger] u.contains(v) by { + assert forall|w: R| #[trigger] cl(inter, base, w) implies u.contains(w) by {} + assert(m.built(inter, |w: R| cl(inter, base, w), v)); + } +} + +/// Normalized outputs of members of a closure are members. +pub proof fn lemma_cl_nset(inter: bool, base: spec_fn(R) -> bool, xs: Set, v: R) + requires forall|x: R| xs.contains(x) ==> cl(inter, base, x), (core().nset)(inter, xs, v), + ensures cl(inter, base, v), +{ + let m = m_impl(); + lemma_models_agree(); + assert forall|u: ISet| m.has_consts(u) && (forall|w: R| #[trigger] base(w) ==> u.contains(w)) + && m.nset_closed(inter, u) implies #[trigger] u.contains(v) by { + assert forall|x: R| xs.contains(x) implies u.contains(x) by { assert(cl(inter, base, x)); } + assert((m.nset)(inter, xs, v)); + } +} + +/// Closures of normal forms consist of normal forms. +pub proof fn lemma_cl_nf(inter: bool, base: spec_fn(R) -> bool, v: R) + requires forall|w: R| #[trigger] base(w) ==> regex_nf(w), cl(inter, base, v), + ensures regex_nf(v), +{ + let m = m_impl(); + lemma_models_agree(); + let u = ISet::new(|w: R| regex_nf(w)); + assert(m.has_consts(u)); + assert forall|w: R| #[trigger] base(w) implies u.contains(w) by {} + assert(m.nset_closed(inter, u)) by { + assert forall|xs: Set, w: R| (forall|x: R| xs.contains(x) ==> u.contains(x)) && #[trigger] (m.nset)(inter, xs, w) + implies u.contains(w) by { + assert(pre().nset_shape(inter, xs, w)); + } + } + assert(m.built(inter, base, v)); + assert(u.contains(v)); +} + +// ===== normal forms of values ===== + +pub proof fn lemma_not_nf(x: R) + requires regex_nf(x), + ensures regex_nf(r_not(x)), +{ + theorem_impl_contract(); + lemma_models_agree(); + assert(m_impl().not_shape(x)); +} + +pub proof fn lemma_cat_nf(xs: Seq) + requires forall|i: int| 0 <= i < xs.len() ==> regex_nf(#[trigger] xs[i]), + ensures regex_nf(r_cat(xs)), +{ + theorem_impl_contract(); + lemma_models_agree(); + assert(m_impl().states(xs)) by { + assert forall|i: int| 0 <= i < xs.len() implies m_impl().st(#[trigger] xs[i]) by {} + } + assert(m_impl().cat_shape(xs)); +} + +pub proof fn lemma_ccat_nf(g: model::Graph, w: R, rs: Seq) + requires regex_nf(w), nats_nf(g, rs), + ensures regex_nf(ccat(g, w, rs)), +{ + let s = seq![w] + model::lift_regexes(g, rs); + assert forall|i: int| 0 <= i < s.len() implies regex_nf(#[trigger] s[i]) by { + if i > 0 { assert(s[i] == model::lift_regex(g, rs[i - 1])); } + } + lemma_cat_nf(s); +} + +/// Class members of a normal-form transition are normal forms. +pub proof fn lemma_tcls_nf(g: model::Graph, t: nat, v: R) + requires nf_sum(g, t) || nf_prod(g, t) || nf_lit(g, t), tcls(g, t, v), + ensures regex_nf(v), + decreases t, +{ + lemma_tcls(g, t, v); + match g.transitions[t as int] { + model::TransitionNode::Const(r) => {}, + model::TransitionNode::If(_, a, b) => { + if a < t && tcls(g, a, v) { lemma_tcls_nf(g, a, v); } else { lemma_tcls_nf(g, b, v); } + }, + model::TransitionNode::Union(cs) => { + if !rconst(v) { + let i = choose|i: int| #![trigger cs[i]] 0 <= i < cs.len() && cs[i] < t && (tc(g))(cs[i], v); + assert(nf_sum(g, cs[i])); + lemma_tcls_nf(g, cs[i], v); + } + }, + model::TransitionNode::Intersect(cs) => { + let base = |w: R| kids(tc(g), t, cs, w); + assert forall|w: R| #[trigger] base(w) implies regex_nf(w) by { + let i = choose|i: int| #![trigger cs[i]] 0 <= i < cs.len() && cs[i] < t && (tc(g))(cs[i], w); + assert(nf_lit(g, cs[i])); + lemma_tcls_nf(g, cs[i], w); + } + lemma_cl_nf(true, base, v); + }, + model::TransitionNode::Not(c) => { + let base = |w: R| negs(tc(g), t, c, w); + assert forall|w: R| #[trigger] base(w) implies regex_nf(w) by { + let x = choose|x: R| c < t && (tc(g))(c, x) && w == #[trigger] r_not(x); + lemma_tcls_nf(g, c, x); + lemma_not_nf(x); + } + lemma_cl_nf(true, base, v); + }, + model::TransitionNode::Append(c, rs) => { + if !rconst(v) { + let w = choose|w: R| c < t && (tc(g))(c, w) && v == #[trigger] ccat(g, w, rs); + lemma_tcls_nf(g, c, w); + lemma_ccat_nf(g, w, rs); + } + }, + } +} + +// ===== soundness of the classes ===== + +/// Values of literals and products are normal forms in their class. +pub proof fn lemma_prod_sound(g: model::Graph, t: nat, v: R) + requires nf_prod(g, t), tval(g, t, v), + ensures regex_nf(v), tcls(g, t, v), + decreases t, 1nat, +{ + lemma_tval(g, t, v); + lemma_tcls(g, t, v); + match g.transitions[t as int] { + model::TransitionNode::Intersect(cs) => { + let vs = choose|vs: Seq| #[trigger] kid_vals(tv(g), t, cs, vs) && (core().nset)(true, vs.to_set(), v); + let base = |w: R| kids(tc(g), t, cs, w); + assert forall|x: R| vs.to_set().contains(x) implies cl(true, base, x) by { + broadcast use vstd::prelude::Seq::to_set_ensures; + let i = choose|i: int| 0 <= i < vs.len() && vs[i] == x; + assert(nf_lit(g, cs[i])); + assert(tval(g, cs[i], vs[i])); + lemma_lit_sound(g, cs[i], vs[i]); + assert(base(x)); + lemma_cl_base(true, base, x); + } + lemma_cl_nset(true, base, vs.to_set(), v); + lemma_models_agree(); + assert(pre().nset_shape(true, vs.to_set(), v)); + }, + _ => { lemma_lit_sound(g, t, v); }, + } +} + +pub proof fn lemma_lit_sound(g: model::Graph, t: nat, v: R) + requires nf_lit(g, t), tval(g, t, v), + ensures regex_nf(v), tcls(g, t, v), + decreases t, 0nat, +{ + lemma_tval(g, t, v); + lemma_tcls(g, t, v); + match g.transitions[t as int] { + model::TransitionNode::Const(r) => {}, + model::TransitionNode::Not(c) => { + let w = choose|w: R| c < t && (tv(g))(c, w) && v == #[trigger] r_not(w); + lemma_lit_sound(g, c, w); + lemma_not_nf(w); + let base = |x: R| negs(tc(g), t, c, x); + assert(base(v)); + lemma_cl_base(true, base, v); + }, + model::TransitionNode::Append(c, rs) => { + let w = choose|w: R| c < t && (tv(g))(c, w) && v == #[trigger] ccat(g, w, rs); + lemma_prod_sound(g, c, w); + lemma_ccat_nf(g, w, rs); + assert(apps(g, tc(g), t, c, rs, v)); + }, + _ => {}, + } +} + +/// Values of a normal-form transition are normalized unions of its class, and lie in its sum +/// class. +pub proof fn lemma_sum_sound(g: model::Graph, t: nat, v: R) + requires nf_sum(g, t), tval(g, t, v), + ensures regex_nf(v), cl(false, |w: R| tcls(g, t, w), v), ycls(g, t, v), + decreases t, 2nat, +{ + lemma_tval(g, t, v); + lemma_ycls(g, t, v); + match g.transitions[t as int] { + model::TransitionNode::If(_, a, b) => { + let c = if a < t && tval(g, a, v) { a } else { b }; + lemma_sum_sound(g, c, v); + assert forall|w: R| #[trigger] tcls(g, c, w) implies tcls(g, t, w) by { lemma_tcls(g, t, w); } + lemma_cl_mono(false, |w: R| tcls(g, c, w), |w: R| tcls(g, t, w), v); + }, + model::TransitionNode::Union(cs) => { + let vs = choose|vs: Seq| #[trigger] kid_vals(tv(g), t, cs, vs) && (core().nset)(false, vs.to_set(), v); + let tb = |w: R| tcls(g, t, w); + let yb = |w: R| kids(yc(g), t, cs, w); + assert forall|x: R| vs.to_set().contains(x) implies cl(false, tb, x) && cl(false, yb, x) by { + broadcast use vstd::prelude::Seq::to_set_ensures; + let i = choose|i: int| 0 <= i < vs.len() && vs[i] == x; + assert(nf_sum(g, cs[i])); + assert(tval(g, cs[i], vs[i])); + lemma_sum_sound(g, cs[i], vs[i]); + assert forall|w: R| #[trigger] tcls(g, cs[i], w) implies tb(w) by { + lemma_tcls(g, t, w); + assert(kids(tc(g), t, cs, w)); + } + lemma_cl_mono(false, |w: R| tcls(g, cs[i], w), tb, x); + assert(ycls(g, cs[i], x)); + assert(yb(x)); + lemma_cl_base(false, yb, x); + } + lemma_cl_nset(false, tb, vs.to_set(), v); + lemma_cl_nset(false, yb, vs.to_set(), v); + lemma_models_agree(); + assert(pre().nset_shape(false, vs.to_set(), v)); + }, + _ => { + lemma_prod_sound(g, t, v); + lemma_cl_base(false, |w: R| tcls(g, t, w), v); + }, + } +} + +// ===== successors ===== + +/// The class bound of a derivative: the transition is a normal form whose class consists of +/// literals and products of `p`; for a constant or test `p`, its sum class consists of +/// constants. +pub open spec fn dclass(g: model::Graph, t: nat, p: R) -> bool { + &&& nf_sum(g, t) + &&& forall|w: R| #[trigger] tcls(g, t, w) ==> (m_impl().lit)(p, w) && (m_impl().prod)(p, w) + &&& m_impl().base_kind(p) ==> forall|w: R| #[trigger] ycls(g, t, w) ==> rconst(w) +} + +/// Every value of a transition with the class bound of `p` is a successor of `p` in `m_impl`. +pub proof fn lemma_succ_from_class(g: model::Graph, t: nat, p: R, v: R) + requires regex_nf(p), dclass(g, t, p), tval(g, t, v), + ensures (m_impl().succ)(p, v), +{ + lemma_sum_sound(g, t, v); + lemma_models_agree(); + lemma_impl_gfp_shapes(p, v); + if m_impl().base_kind(p) { + assert(rconst(v)); + assert(m_impl().succ_shape(p, v)); + } else { + lemma_cl_mono(false, |w: R| tcls(g, t, w), |w: R| (m_impl().prod)(p, w), v); + assert(m_impl().succ_shape(p, v)); + } + assert(g_succ(p, v)); +} + +// ===== stability under graph extension ===== + +pub open spec fn stable_at(a: model::Graph, b: model::Graph, t: nat) -> bool { + &&& forall|v: R| #[trigger] tcls(a, t, v) == tcls(b, t, v) + &&& forall|v: R| #[trigger] ycls(a, t, v) == ycls(b, t, v) + &&& forall|v: R| #[trigger] tval(a, t, v) == tval(b, t, v) + &&& nf_lit(a, t) == nf_lit(b, t) && nf_prod(a, t) == nf_prod(b, t) && nf_sum(a, t) == nf_sum(b, t) +} + +/// Classes, values, and normal forms of existing transitions survive graph extension. +pub proof fn lemma_trans_stable(a: model::Graph, b: model::Graph, t: nat) + requires model::graph_wf(a), model::graph_extends(a, b), t < a.transitions.len(), + ensures stable_at(a, b, t), + decreases t, +{ + model::lemma_graph_wf_elim(a); + model::lemma_graph_transition_wf(a, t); + assert(a.transitions[t as int] == b.transitions[t as int]) by { + assert(a.transitions == b.transitions.subrange(0, a.transitions.len() as int)); + } + let node = a.transitions[t as int]; + match node { + model::TransitionNode::Const(r) => { model::lemma_lift_regex_stable(a, b, r); }, + model::TransitionNode::If(_, x, y) => { lemma_trans_stable(a, b, x); lemma_trans_stable(a, b, y); }, + model::TransitionNode::Union(cs) => { + assert forall|i: int| 0 <= i < cs.len() implies #[trigger] stable_at(a, b, cs[i]) by { + assert(cs[i] < t); + lemma_trans_stable(a, b, cs[i]); + } + }, + model::TransitionNode::Intersect(cs) => { + assert forall|i: int| 0 <= i < cs.len() implies #[trigger] stable_at(a, b, cs[i]) by { + assert(cs[i] < t); + lemma_trans_stable(a, b, cs[i]); + } + }, + model::TransitionNode::Not(k) => { lemma_trans_stable(a, b, k); }, + model::TransitionNode::Append(k, rs) => { + lemma_trans_stable(a, b, k); + assert forall|j: int| 0 <= j < rs.len() implies #[trigger] model::lift_regex(a, rs[j]) == model::lift_regex(b, rs[j]) by { + model::lemma_lift_regex_stable(a, b, rs[j]); + } + assert(model::lift_regexes(a, rs) =~= model::lift_regexes(b, rs)); + }, + } + assert(kids_stable(a, b, t)) by { + match node { + model::TransitionNode::Const(r) => {}, + model::TransitionNode::Union(cs) => {}, + model::TransitionNode::Intersect(cs) => {}, + model::TransitionNode::Append(k, rs) => { + assert(model::bounded(rs, b.regexes.len())) by { + assert forall|j: int| 0 <= j < rs.len() implies #[trigger] rs[j] < b.regexes.len() by {} + } + }, + _ => {}, + } + } + lemma_tcls_stable_node(a, b, t); + lemma_ycls_stable_node(a, b, t); + lemma_tval_stable_node(a, b, t); + lemma_nf_stable_node(a, b, t); +} + +/// The children of `t` (in both graphs) are stable, and so are its leaf and suffixes. +pub open spec fn kids_stable(a: model::Graph, b: model::Graph, t: nat) -> bool { + &&& t < a.transitions.len() && t < b.transitions.len() && a.transitions[t as int] == b.transitions[t as int] + &&& match a.transitions[t as int] { + model::TransitionNode::Const(r) => r < a.regexes.len() && r < b.regexes.len() + && model::lift_regex(a, r) == model::lift_regex(b, r), + model::TransitionNode::If(_, x, y) => x < t && y < t && stable_at(a, b, x) && stable_at(a, b, y), + model::TransitionNode::Union(cs) => forall|i: int| 0 <= i < cs.len() ==> cs[i] < t && #[trigger] stable_at(a, b, cs[i]), + model::TransitionNode::Intersect(cs) => forall|i: int| 0 <= i < cs.len() ==> cs[i] < t && #[trigger] stable_at(a, b, cs[i]), + model::TransitionNode::Not(k) => k < t && stable_at(a, b, k), + model::TransitionNode::Append(k, rs) => k < t && stable_at(a, b, k) + && model::lift_regexes(a, rs) == model::lift_regexes(b, rs) + && model::bounded(rs, a.regexes.len()) && model::bounded(rs, b.regexes.len()), + } +} + +pub proof fn lemma_tcls_stable_node(a: model::Graph, b: model::Graph, t: nat) + requires kids_stable(a, b, t), + ensures forall|v: R| #[trigger] tcls(a, t, v) == tcls(b, t, v), +{ + let node = a.transitions[t as int]; + assert forall|v: R| #[trigger] tcls(a, t, v) == tcls(b, t, v) by { + lemma_tcls(a, t, v); + lemma_tcls(b, t, v); + match node { + model::TransitionNode::Union(cs) => { + if kids(tc(a), t, cs, v) { + let i = choose|i: int| #![trigger cs[i]] 0 <= i < cs.len() && cs[i] < t && (tc(a))(cs[i], v); + assert(stable_at(a, b, cs[i])); + assert(tcls(a, cs[i], v) == tcls(b, cs[i], v)); + } + if kids(tc(b), t, cs, v) { + let i = choose|i: int| #![trigger cs[i]] 0 <= i < cs.len() && cs[i] < t && (tc(b))(cs[i], v); + assert(stable_at(a, b, cs[i])); + assert(tcls(a, cs[i], v) == tcls(b, cs[i], v)); + } + }, + model::TransitionNode::Intersect(cs) => { + assert forall|w: R| #[trigger] kids(tc(a), t, cs, w) == kids(tc(b), t, cs, w) by { + if kids(tc(a), t, cs, w) { + let i = choose|i: int| #![trigger cs[i]] 0 <= i < cs.len() && cs[i] < t && (tc(a))(cs[i], w); + assert(stable_at(a, b, cs[i])); + assert(tcls(a, cs[i], w) == tcls(b, cs[i], w)); + } + if kids(tc(b), t, cs, w) { + let i = choose|i: int| #![trigger cs[i]] 0 <= i < cs.len() && cs[i] < t && (tc(b))(cs[i], w); + assert(stable_at(a, b, cs[i])); + assert(tcls(a, cs[i], w) == tcls(b, cs[i], w)); + } + } + if cl(true, |w: R| kids(tc(a), t, cs, w), v) { + lemma_cl_mono(true, |w: R| kids(tc(a), t, cs, w), |w: R| kids(tc(b), t, cs, w), v); + } + if cl(true, |w: R| kids(tc(b), t, cs, w), v) { + lemma_cl_mono(true, |w: R| kids(tc(b), t, cs, w), |w: R| kids(tc(a), t, cs, w), v); + } + }, + model::TransitionNode::Not(k) => { + assert forall|w: R| #[trigger] negs(tc(a), t, k, w) == negs(tc(b), t, k, w) by { + if negs(tc(a), t, k, w) { + let x = choose|x: R| k < t && (tc(a))(k, x) && w == #[trigger] r_not(x); + assert(tcls(a, k, x) == tcls(b, k, x)); + } + if negs(tc(b), t, k, w) { + let x = choose|x: R| k < t && (tc(b))(k, x) && w == #[trigger] r_not(x); + assert(tcls(a, k, x) == tcls(b, k, x)); + } + } + if cl(true, |w: R| negs(tc(a), t, k, w), v) { + lemma_cl_mono(true, |w: R| negs(tc(a), t, k, w), |w: R| negs(tc(b), t, k, w), v); + } + if cl(true, |w: R| negs(tc(b), t, k, w), v) { + lemma_cl_mono(true, |w: R| negs(tc(b), t, k, w), |w: R| negs(tc(a), t, k, w), v); + } + }, + model::TransitionNode::Append(k, rs) => { + if apps(a, tc(a), t, k, rs, v) { + let w = choose|w: R| k < t && (tc(a))(k, w) && v == #[trigger] ccat(a, w, rs); + assert(tcls(a, k, w) == tcls(b, k, w)); + assert(ccat(a, w, rs) == ccat(b, w, rs)); + } + if apps(b, tc(b), t, k, rs, v) { + let w = choose|w: R| k < t && (tc(b))(k, w) && v == #[trigger] ccat(b, w, rs); + assert(tcls(a, k, w) == tcls(b, k, w)); + assert(ccat(a, w, rs) == ccat(b, w, rs)); + } + }, + model::TransitionNode::If(_, x, y) => { + assert(tcls(a, x, v) == tcls(b, x, v)); + assert(tcls(a, y, v) == tcls(b, y, v)); + }, + _ => {}, + } + } +} + +pub proof fn lemma_ycls_stable_node(a: model::Graph, b: model::Graph, t: nat) + requires kids_stable(a, b, t), + ensures forall|v: R| #[trigger] ycls(a, t, v) == ycls(b, t, v), +{ + let node = a.transitions[t as int]; + assert forall|v: R| #[trigger] ycls(a, t, v) == ycls(b, t, v) by { + lemma_ycls(a, t, v); + lemma_ycls(b, t, v); + match node { + model::TransitionNode::Union(cs) => { + assert forall|w: R| #[trigger] kids(yc(a), t, cs, w) == kids(yc(b), t, cs, w) by { + if kids(yc(a), t, cs, w) { + let i = choose|i: int| #![trigger cs[i]] 0 <= i < cs.len() && cs[i] < t && (yc(a))(cs[i], w); + assert(stable_at(a, b, cs[i])); + assert(ycls(a, cs[i], w) == ycls(b, cs[i], w)); + } + if kids(yc(b), t, cs, w) { + let i = choose|i: int| #![trigger cs[i]] 0 <= i < cs.len() && cs[i] < t && (yc(b))(cs[i], w); + assert(stable_at(a, b, cs[i])); + assert(ycls(a, cs[i], w) == ycls(b, cs[i], w)); + } + } + if cl(false, |w: R| kids(yc(a), t, cs, w), v) { + lemma_cl_mono(false, |w: R| kids(yc(a), t, cs, w), |w: R| kids(yc(b), t, cs, w), v); + } + if cl(false, |w: R| kids(yc(b), t, cs, w), v) { + lemma_cl_mono(false, |w: R| kids(yc(b), t, cs, w), |w: R| kids(yc(a), t, cs, w), v); + } + }, + model::TransitionNode::If(_, x, y) => { + assert(ycls(a, x, v) == ycls(b, x, v)); + assert(ycls(a, y, v) == ycls(b, y, v)); + }, + _ => {}, + } + } +} + +pub proof fn lemma_tval_stable_node(a: model::Graph, b: model::Graph, t: nat) + requires kids_stable(a, b, t), + ensures forall|v: R| #[trigger] tval(a, t, v) == tval(b, t, v), +{ + let node = a.transitions[t as int]; + assert forall|v: R| #[trigger] tval(a, t, v) == tval(b, t, v) by { + lemma_tval(a, t, v); + lemma_tval(b, t, v); + match node { + model::TransitionNode::Union(cs) => { lemma_kid_vals_stable(a, b, t, cs, v, false); }, + model::TransitionNode::Intersect(cs) => { lemma_kid_vals_stable(a, b, t, cs, v, true); }, + model::TransitionNode::Not(k) => { + if negs(tv(a), t, k, v) { + let x = choose|x: R| k < t && (tv(a))(k, x) && v == #[trigger] r_not(x); + assert(tval(a, k, x) == tval(b, k, x)); + } + if negs(tv(b), t, k, v) { + let x = choose|x: R| k < t && (tv(b))(k, x) && v == #[trigger] r_not(x); + assert(tval(a, k, x) == tval(b, k, x)); + } + }, + model::TransitionNode::Append(k, rs) => { + if apps(a, tv(a), t, k, rs, v) { + let w = choose|w: R| k < t && (tv(a))(k, w) && v == #[trigger] ccat(a, w, rs); + assert(tval(a, k, w) == tval(b, k, w)); + assert(ccat(a, w, rs) == ccat(b, w, rs)); + } + if apps(b, tv(b), t, k, rs, v) { + let w = choose|w: R| k < t && (tv(b))(k, w) && v == #[trigger] ccat(b, w, rs); + assert(tval(a, k, w) == tval(b, k, w)); + assert(ccat(a, w, rs) == ccat(b, w, rs)); + } + }, + model::TransitionNode::If(_, x, y) => { + assert(tval(a, x, v) == tval(b, x, v)); + assert(tval(a, y, v) == tval(b, y, v)); + }, + _ => {}, + } + } +} + +pub proof fn lemma_nf_stable_node(a: model::Graph, b: model::Graph, t: nat) + requires kids_stable(a, b, t), + ensures nf_lit(a, t) == nf_lit(b, t), nf_prod(a, t) == nf_prod(b, t), nf_sum(a, t) == nf_sum(b, t), +{ + let node = a.transitions[t as int]; + match node { + model::TransitionNode::Const(r) => {}, + model::TransitionNode::Append(k, rs) => { + assert(nats_nf(a, rs) == nats_nf(b, rs)) by { + if nats_nf(a, rs) { + assert forall|j: int| 0 <= j < rs.len() implies regex_nf(#[trigger] model::lift_regex(b, rs[j])) by { + assert(model::lift_regexes(a, rs)[j] == model::lift_regex(a, rs[j])); + assert(model::lift_regexes(b, rs)[j] == model::lift_regex(b, rs[j])); + } + } + if nats_nf(b, rs) { + assert forall|j: int| 0 <= j < rs.len() implies regex_nf(#[trigger] model::lift_regex(a, rs[j])) by { + assert(model::lift_regexes(a, rs)[j] == model::lift_regex(a, rs[j])); + assert(model::lift_regexes(b, rs)[j] == model::lift_regex(b, rs[j])); + } + } + } + assert(model::bounded(rs, a.regexes.len())); + }, + model::TransitionNode::Union(cs) => { + assert(nf_sum(a, t) == nf_sum(b, t)) by { + if nf_sum(a, t) { + assert forall|i: int| 0 <= i < cs.len() implies cs[i] < t && nf_sum(b, #[trigger] cs[i]) by { + assert(stable_at(a, b, cs[i])); + } + } + if nf_sum(b, t) { + assert forall|i: int| 0 <= i < cs.len() implies cs[i] < t && nf_sum(a, #[trigger] cs[i]) by { + assert(stable_at(a, b, cs[i])); + } + } + } + }, + model::TransitionNode::Intersect(cs) => { + assert(nf_prod(a, t) == nf_prod(b, t)) by { + if nf_prod(a, t) { + assert forall|i: int| 0 <= i < cs.len() implies cs[i] < t && nf_lit(b, #[trigger] cs[i]) by { + assert(stable_at(a, b, cs[i])); + } + } + if nf_prod(b, t) { + assert forall|i: int| 0 <= i < cs.len() implies cs[i] < t && nf_lit(a, #[trigger] cs[i]) by { + assert(stable_at(a, b, cs[i])); + } + } + } + }, + _ => {}, + } +} + +pub proof fn lemma_kid_vals_stable(a: model::Graph, b: model::Graph, t: nat, cs: Seq, v: R, inter: bool) + requires forall|i: int| 0 <= i < cs.len() ==> #[trigger] stable_at(a, b, cs[i]), + ensures (exists|vs: Seq| #[trigger] kid_vals(tv(a), t, cs, vs) && (core().nset)(inter, vs.to_set(), v)) + == (exists|vs: Seq| #[trigger] kid_vals(tv(b), t, cs, vs) && (core().nset)(inter, vs.to_set(), v)), +{ + assert forall|vs: Seq| #[trigger] kid_vals(tv(a), t, cs, vs) == kid_vals(tv(b), t, cs, vs) by { + if kid_vals(tv(a), t, cs, vs) { + assert forall|i: int| #![trigger vs[i]] 0 <= i < cs.len() implies cs[i] < t && (tv(b))(cs[i], vs[i]) by { + assert(stable_at(a, b, cs[i])); + assert(tval(a, cs[i], vs[i]) == tval(b, cs[i], vs[i])); + } + } + if kid_vals(tv(b), t, cs, vs) { + assert forall|i: int| #![trigger vs[i]] 0 <= i < cs.len() implies cs[i] < t && (tv(a))(cs[i], vs[i]) by { + assert(stable_at(a, b, cs[i])); + assert(tval(a, cs[i], vs[i]) == tval(b, cs[i], vs[i])); + } + } + } + if exists|vs: Seq| #[trigger] kid_vals(tv(a), t, cs, vs) && (core().nset)(inter, vs.to_set(), v) { + let vs = choose|vs: Seq| #[trigger] kid_vals(tv(a), t, cs, vs) && (core().nset)(inter, vs.to_set(), v); + assert(kid_vals(tv(b), t, cs, vs)); + } + if exists|vs: Seq| #[trigger] kid_vals(tv(b), t, cs, vs) && (core().nset)(inter, vs.to_set(), v) { + let vs = choose|vs: Seq| #[trigger] kid_vals(tv(b), t, cs, vs) && (core().nset)(inter, vs.to_set(), v); + assert(kid_vals(tv(a), t, cs, vs)); + } +} + +} // verus! diff --git a/src/history-semantics/src/verify/history_algebra.rs b/src/history-semantics/src/verify/history_algebra.rs new file mode 100644 index 000000000..fe7955d3a --- /dev/null +++ b/src/history-semantics/src/verify/history_algebra.rs @@ -0,0 +1,1730 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Paper-shaped regex-language theorems for the source policy language: +//! similarity preserves language, symbolic derivative correctness, matcher correctness. + +use alloc::boxed::Box; +use history_syntax::syntax::Component; +use junco_core::kernel::verify as model; +use junco_core::verify::history_specs as language; +use junco_core::verify::history_specs::{EventView, Head, Regex, SrcTest, Subst, Term, Transition}; +use vstd::prelude::*; + +verus! { + +broadcast use {vstd::string::group_string_axioms, vstd::seq::group_seq_lemmas, + junco_core::kernel::verify::group_kernel_views}; + +pub open spec fn src_sem(theta: Subst) -> spec_fn(SrcTest, EventView) -> bool { + |test: SrcTest, event: EventView| language::src_test_holds(theta, test, event) +} + +/// The paper's δ, without runtime normalization or graph representation. +pub open spec fn symbolic_derivative(r: Regex) -> Transition + decreases r, 1nat, 0nat, +{ + match r { + Regex::Empty | Regex::Epsilon => Transition::Const(Regex::Empty), + Regex::All => Transition::Const(Regex::All), + Regex::Test(l) => Transition::If(l, Box::new(Transition::Const(Regex::Epsilon)), Box::new(Transition::Const(Regex::Empty))), + Regex::Union(cs) => Transition::Union(Seq::new(cs.len(), |i: int| if 0 <= i < cs.len() { symbolic_derivative(cs[i]) } else { Transition::Const(Regex::Empty) })), + Regex::Intersect(cs) => Transition::Intersect(Seq::new(cs.len(), |i: int| if 0 <= i < cs.len() { symbolic_derivative(cs[i]) } else { Transition::Const(Regex::Empty) })), + Regex::Not(c) => Transition::Not(Box::new(symbolic_derivative(*c))), + Regex::Star(c) => Transition::Append(Box::new(symbolic_derivative(*c)), seq![Regex::Star(c)]), + Regex::Concat(cs) => symbolic_derivative_concat(r, cs), + } +} + +pub open spec fn symbolic_derivative_concat(bound: Regex, cs: Seq>) -> Transition + decreases bound, 0nat, cs.len(), + when forall|i: int| 0 <= i < cs.len() ==> is_smaller_than(cs[i], bound) +{ + if cs.len() == 0 { Transition::Const(Regex::Empty) } + else { + Transition::Union(seq![Transition::Append(Box::new(symbolic_derivative(cs[0])), cs.drop_first())] + + if language::nullable(cs[0]) { seq![symbolic_derivative_concat(bound, cs.drop_first())] } else { Seq::empty() }) + } +} + +pub proof fn lemma_symbolic_derivative_concat_interp(sem: spec_fn(L, EventView) -> bool, e: EventView, bound: Regex, cs: Seq>) + requires + forall|i: int| 0 <= i < cs.len() ==> is_smaller_than(cs[i], bound), + forall|i: int| 0 <= i < cs.len() ==> #[trigger] language::interp_transition(sem, e, symbolic_derivative(cs[i])) == language::derivative(sem, e, cs[i]), + ensures language::interp_transition(sem, e, symbolic_derivative_concat(bound, cs)) == language::derivative_concat(sem, e, bound, cs), + decreases cs.len(), +{ + reveal_with_fuel(language::interp_transition, 3); + if cs.len() > 0 { + let rest = cs.drop_first(); + assert(rest.len() == cs.len() - 1); + assert forall|i: int| 0 <= i < rest.len() implies is_smaller_than(rest[i], bound) by { + assert(rest[i] == cs[i + 1]); + } + assert forall|i: int| 0 <= i < rest.len() implies language::interp_transition(sem, e, symbolic_derivative(rest[i])) == language::derivative(sem, e, rest[i]) by { + assert(rest[i] == cs[i + 1]); + } + lemma_symbolic_derivative_concat_interp(sem, e, bound, rest); + let ts = seq![Transition::Append(Box::new(symbolic_derivative(cs[0])), rest)] + + if language::nullable(cs[0]) { seq![symbolic_derivative_concat(bound, rest)] } else { Seq::empty() }; + let ds = seq![Regex::Concat(seq![language::derivative(sem, e, cs[0])] + rest)] + + if language::nullable(cs[0]) { seq![language::derivative_concat(sem, e, bound, rest)] } else { Seq::empty() }; + let out = language::interp_transition(sem, e, Transition::Union(ts)); + assert(out is Union); + assert(ts.len() == ds.len()); + assert forall|i: int| 0 <= i < ts.len() implies language::interp_transition(sem, e, ts[i]) == ds[i] by { + assert(i == 0 || (language::nullable(cs[0]) && i == 1)); + if i == 0 { + assert(ts[i] == Transition::Append(Box::new(symbolic_derivative(cs[0])), rest)); + assert(ds[i] == Regex::Concat(seq![language::derivative(sem, e, cs[0])] + rest)); + assert(language::interp_transition(sem, e, symbolic_derivative(cs[0])) == language::derivative(sem, e, cs[0])); + assert(language::interp_transition(sem, e, ts[i])->Concat_0 =~= seq![language::derivative(sem, e, cs[0])] + rest); + } else { + assert(ts[i] == symbolic_derivative_concat(bound, rest)); + assert(ds[i] == language::derivative_concat(sem, e, bound, rest)); + } + } + assert(out->Union_0 =~= ds); + } +} + +pub proof fn lemma_symbolic_derivative_interp(sem: spec_fn(L, EventView) -> bool, e: EventView, r: Regex) + ensures language::interp_transition(sem, e, symbolic_derivative(r)) == language::derivative(sem, e, r), + decreases r, +{ + reveal_with_fuel(language::interp_transition, 2); + reveal_with_fuel(symbolic_derivative, 2); + reveal_with_fuel(language::derivative, 2); + match r { + Regex::Union(cs) | Regex::Intersect(cs) => { + let ts = Seq::new(cs.len(), |i: int| if 0 <= i < cs.len() { symbolic_derivative(cs[i]) } else { Transition::Const(Regex::Empty) }); + let ds = Seq::new(cs.len(), |i: int| if 0 <= i < cs.len() { language::derivative(sem, e, cs[i]) } else { Regex::Empty }); + assert forall|i: int| 0 <= i < cs.len() implies language::interp_transition(sem, e, ts[i]) == ds[i] by { + lemma_symbolic_derivative_interp(sem, e, cs[i]); + } + let interpreted = Seq::new(ts.len(), |i: int| if 0 <= i < ts.len() { language::interp_transition(sem, e, ts[i]) } else { Regex::Empty }); + assert(interpreted =~= ds); + if r is Union { + assert(symbolic_derivative(r)->Union_0 =~= ts); + assert(language::interp_transition(sem, e, Transition::Union(ts))->Union_0 =~= interpreted); + assert(language::derivative(sem, e, r)->Union_0 =~= ds); + } else { + assert(symbolic_derivative(r)->Intersect_0 =~= ts); + assert(language::interp_transition(sem, e, Transition::Intersect(ts))->Intersect_0 =~= interpreted); + assert(language::derivative(sem, e, r)->Intersect_0 =~= ds); + } + }, + Regex::Not(c) => lemma_symbolic_derivative_interp(sem, e, *c), + Regex::Star(c) => { + lemma_symbolic_derivative_interp(sem, e, *c); + assert(seq![language::derivative(sem, e, *c)] + seq![Regex::Star(c)] =~= seq![language::derivative(sem, e, *c), Regex::Star(c)]); + }, + Regex::Concat(cs) => { + assert forall|i: int| 0 <= i < cs.len() implies is_smaller_than(cs[i], r) by { } + assert forall|i: int| 0 <= i < cs.len() implies language::interp_transition(sem, e, symbolic_derivative(cs[i])) == language::derivative(sem, e, cs[i]) by { + lemma_symbolic_derivative_interp(sem, e, cs[i]); + } + lemma_symbolic_derivative_concat_interp(sem, e, r, cs); + assert(language::interp_transition(sem, e, symbolic_derivative(r)) == language::derivative(sem, e, r)); + }, + Regex::Test(l) => language::lemma_interp_if(sem, e, l, Transition::Const(Regex::Epsilon), Transition::Const(Regex::Empty)), + _ => {}, + } +} + +/// Lemma One-step correctness (`lem:sderiv`), modulo language rather than normalization: the +/// interpreted symbolic derivative has the one-event derivative language. +pub open spec fn stmt_symbolic_derivative_correct() -> bool { + forall|sem: spec_fn(L, EventView) -> bool, e: EventView, r: Regex, w: Seq| + #[trigger] language::numeric_lang(sem, language::interp_transition(sem, e, symbolic_derivative(r)), w) + == language::numeric_lang(sem, r, seq![e] + w) +} + +pub proof fn lemma_symbolic_derivative_correct(sem: spec_fn(L, EventView) -> bool, e: EventView, r: Regex, w: Seq) + ensures language::numeric_lang(sem, language::interp_transition(sem, e, symbolic_derivative(r)), w) == language::numeric_lang(sem, r, seq![e] + w), +{ + lemma_symbolic_derivative_interp(sem, e, r); + language::lemma_derivative_correct(sem, e, r, w); +} + +pub proof fn theorem_symbolic_derivative_correct() + ensures stmt_symbolic_derivative_correct::(), +{ + assert forall|sem: spec_fn(L, EventView) -> bool, e: EventView, r: Regex, w: Seq| + #[trigger] language::numeric_lang(sem, language::interp_transition(sem, e, symbolic_derivative(r)), w) + == language::numeric_lang(sem, r, seq![e] + w) by { + lemma_symbolic_derivative_correct(sem, e, r, w); + } +} + +/// The paper's state sequence q, consuming events oldest first. +pub open spec fn symbolic_run(sem: spec_fn(L, EventView) -> bool, u: Seq, r: Regex) -> Regex + decreases u.len(), +{ + if u.len() == 0 { r } + else { symbolic_run(sem, u.drop_first(), language::interp_transition(sem, u[0], symbolic_derivative(r))) } +} + +pub proof fn lemma_symbolic_run_is_derive_word(sem: spec_fn(L, EventView) -> bool, u: Seq, r: Regex) + ensures symbolic_run(sem, u, r) == language::derive_word(sem, u, r), + decreases u.len(), +{ + if u.len() > 0 { + lemma_symbolic_derivative_interp(sem, u[0], r); + lemma_symbolic_run_is_derive_word(sem, u.drop_first(), language::derivative(sem, u[0], r)); + } +} + +/// Theorem Symbolic derivative correctness (`thm:sderiv`), modulo language rather than +/// normalization: the symbolic run over a history is nullable iff the history is in the language. +pub open spec fn stmt_symbolic_run_correct() -> bool { + forall|sem: spec_fn(L, EventView) -> bool, u: Seq, r: Regex| + language::nullable(#[trigger] symbolic_run(sem, u, r)) == language::numeric_lang(sem, r, u) +} + +pub proof fn lemma_symbolic_run_correct(sem: spec_fn(L, EventView) -> bool, u: Seq, r: Regex) + ensures language::nullable(symbolic_run(sem, u, r)) == language::numeric_lang(sem, r, u), +{ + lemma_symbolic_run_is_derive_word(sem, u, r); + language::lemma_derive_word_nullable(sem, u, r); +} + +pub proof fn theorem_symbolic_run_correct() + ensures stmt_symbolic_run_correct::(), +{ + assert forall|sem: spec_fn(L, EventView) -> bool, u: Seq, r: Regex| + language::nullable(#[trigger] symbolic_run(sem, u, r)) == language::numeric_lang(sem, r, u) by { + lemma_symbolic_run_correct(sem, u, r); + } +} + +/// Theorem Matcher correctness (`thm:matcher`), steps 2–3: a fired rule decides by the symbolic +/// run of its tail under its unique complete head substitution. +pub open spec fn stmt_rule_decision() -> bool { + forall|head: Head, tail: Regex, request: EventView, history: Seq, theta: Subst| + #![trigger language::head_match(head, request, theta), symbolic_run(src_sem(theta), history, tail)] + language::head_match(head, request, theta) + ==> language::pair_lang(head, tail, request, history) == language::nullable(symbolic_run(src_sem(theta), history, tail)) +} + +pub proof fn lemma_rule_decision(head: Head, tail: Regex, request: EventView, history: Seq, theta: Subst) + requires language::head_match(head, request, theta), + ensures language::pair_lang(head, tail, request, history) == language::nullable(symbolic_run(src_sem(theta), history, tail)), +{ + language::lemma_pair_lang_substitutions(head, tail, request, history, theta); + lemma_symbolic_run_correct(src_sem(theta), history, tail); +} + +pub proof fn theorem_rule_decision() + ensures stmt_rule_decision(), +{ + assert forall|head: Head, tail: Regex, request: EventView, history: Seq, theta: Subst| + #![trigger language::head_match(head, request, theta), symbolic_run(src_sem(theta), history, tail)] + language::head_match(head, request, theta) + implies language::pair_lang(head, tail, request, history) == language::nullable(symbolic_run(src_sem(theta), history, tail)) by { + lemma_rule_decision(head, tail, request, history, theta); + } +} + +pub enum TestRule { + AndSet(Seq, Seq), + OrSet(Seq, Seq), + AndFlatten(Seq, int), + OrFlatten(Seq, int), + AndTrue(Seq, int), + OrFalse(Seq, int), + AndFalse(Seq, int), + OrTrue(Seq, int), + AndSingleton(SrcTest), + OrSingleton(SrcTest), + AndNil, + OrNil, + AndAbsorb(SrcTest, Seq), + OrAbsorb(SrcTest, Seq), + AndDistrib(SrcTest, Seq), + OrDistrib(SrcTest, Seq), + AndExclusive(Seq, int, int), + AndDistinctConstants(Seq, int, int), +} + +pub open spec fn test_rule_lhs(rule: TestRule) -> SrcTest { + match rule { + TestRule::AndSet(cs, _) + | TestRule::AndFlatten(cs, _) + | TestRule::AndTrue(cs, _) + | TestRule::AndFalse(cs, _) + | TestRule::AndExclusive(cs, _, _) + | TestRule::AndDistinctConstants(cs, _, _) => SrcTest::And(cs), + TestRule::OrSet(cs, _) + | TestRule::OrFlatten(cs, _) + | TestRule::OrFalse(cs, _) + | TestRule::OrTrue(cs, _) => SrcTest::Or(cs), + TestRule::AndSingleton(t) => SrcTest::And(seq![t]), + TestRule::OrSingleton(t) => SrcTest::Or(seq![t]), + TestRule::AndNil => SrcTest::And(Seq::empty()), + TestRule::OrNil => SrcTest::Or(Seq::empty()), + TestRule::AndAbsorb(t, cs) + | TestRule::AndDistrib(t, cs) => SrcTest::And(seq![t, SrcTest::Or(cs)]), + TestRule::OrAbsorb(t, cs) + | TestRule::OrDistrib(t, cs) => SrcTest::Or(seq![t, SrcTest::And(cs)]), + } +} + +pub open spec fn test_rule_rhs(rule: TestRule) -> SrcTest { + match rule { + TestRule::AndSet(_, ds) => SrcTest::And(ds), + TestRule::OrSet(_, ds) => SrcTest::Or(ds), + TestRule::AndFlatten(cs, i) => { + if 0 <= i < cs.len() { + match cs[i] { + SrcTest::And(ds) => SrcTest::And(cs.take(i) + ds + cs.skip(i + 1)), + _ => SrcTest::And(cs), + } + } else { SrcTest::And(cs) } + }, + TestRule::OrFlatten(cs, i) => { + if 0 <= i < cs.len() { + match cs[i] { + SrcTest::Or(ds) => SrcTest::Or(cs.take(i) + ds + cs.skip(i + 1)), + _ => SrcTest::Or(cs), + } + } else { SrcTest::Or(cs) } + }, + TestRule::AndTrue(cs, i) => { + SrcTest::And(if 0 <= i < cs.len() { cs.remove(i) } else { cs }) + }, + TestRule::OrFalse(cs, i) => { + SrcTest::Or(if 0 <= i < cs.len() { cs.remove(i) } else { cs }) + }, + TestRule::AndFalse(_, _) + | TestRule::OrNil + | TestRule::AndExclusive(_, _, _) + | TestRule::AndDistinctConstants(_, _, _) => SrcTest::Bool(false), + TestRule::OrTrue(_, _) + | TestRule::AndNil => SrcTest::Bool(true), + TestRule::AndSingleton(t) + | TestRule::OrSingleton(t) + | TestRule::AndAbsorb(t, _) + | TestRule::OrAbsorb(t, _) => t, + TestRule::AndDistrib(t, cs) => SrcTest::Or( + Seq::new(cs.len(), |k: int| SrcTest::And(seq![t, cs[k]]))), + TestRule::OrDistrib(t, cs) => SrcTest::And( + Seq::new(cs.len(), |k: int| SrcTest::Or(seq![t, cs[k]]))), + } +} + +pub open spec fn test_rule_valid(rule: TestRule) -> bool { + match rule { + TestRule::AndSet(cs, ds) + | TestRule::OrSet(cs, ds) => cs.to_set() == ds.to_set(), + TestRule::AndFlatten(cs, i) => 0 <= i < cs.len() && cs[i] is And, + TestRule::OrFlatten(cs, i) => 0 <= i < cs.len() && cs[i] is Or, + TestRule::AndTrue(cs, i) => 0 <= i < cs.len() && cs[i] == SrcTest::Bool(true), + TestRule::OrFalse(cs, i) => 0 <= i < cs.len() && cs[i] == SrcTest::Bool(false), + TestRule::AndFalse(cs, i) => 0 <= i < cs.len() && cs[i] == SrcTest::Bool(false), + TestRule::OrTrue(cs, i) => 0 <= i < cs.len() && cs[i] == SrcTest::Bool(true), + TestRule::AndAbsorb(t, cs) + | TestRule::OrAbsorb(t, cs) => cs.contains(t), + TestRule::AndExclusive(cs, i, j) => { + 0 <= i < cs.len() && 0 <= j < cs.len() + && match (cs[i], cs[j]) { + (SrcTest::Eq(p, t), SrcTest::Neq(q, u)) => p == q && t == u, + _ => false, + } + }, + TestRule::AndDistinctConstants(cs, i, j) => { + 0 <= i < cs.len() && 0 <= j < cs.len() + && match (cs[i], cs[j]) { + (SrcTest::Eq(p, Term::Constant(c)), SrcTest::Eq(q, Term::Constant(d))) => + p == q && c != d, + _ => false, + } + }, + TestRule::AndSingleton(_) + | TestRule::OrSingleton(_) + | TestRule::AndNil + | TestRule::OrNil + | TestRule::AndDistrib(_, _) + | TestRule::OrDistrib(_, _) => true, + } +} + +pub proof fn lemma_test_quantifiers_set(p: spec_fn(A) -> bool, cs: Seq, ds: Seq) + requires cs.to_set() == ds.to_set(), + ensures + (forall|k: int| 0 <= k < cs.len() ==> p(cs[k])) + == (forall|k: int| 0 <= k < ds.len() ==> p(ds[k])), + (exists|k: int| 0 <= k < cs.len() && p(cs[k])) + == (exists|k: int| 0 <= k < ds.len() && p(ds[k])), +{ + broadcast use vstd::set::group_set_lemmas; + cs.to_set_ensures(); + ds.to_set_ensures(); + if forall|k: int| 0 <= k < cs.len() ==> p(cs[k]) { + assert forall|k: int| 0 <= k < ds.len() implies p(ds[k]) by { + assert(ds.contains(ds[k])); + assert(cs.to_set().contains(ds[k])); + assert(cs.contains(ds[k])); + let j = choose|j: int| 0 <= j < cs.len() && cs[j] == ds[k]; + assert(p(cs[j])); + } + } + if forall|k: int| 0 <= k < ds.len() ==> p(ds[k]) { + assert forall|k: int| 0 <= k < cs.len() implies p(cs[k]) by { + assert(cs.contains(cs[k])); + assert(ds.to_set().contains(cs[k])); + assert(ds.contains(cs[k])); + let j = choose|j: int| 0 <= j < ds.len() && ds[j] == cs[k]; + assert(p(ds[j])); + } + } + if exists|k: int| 0 <= k < cs.len() && p(cs[k]) { + let k = choose|k: int| 0 <= k < cs.len() && p(cs[k]); + assert(ds.to_set().contains(cs[k])); + assert(cs.contains(cs[k])); + assert(ds.contains(cs[k])); + let j = choose|j: int| 0 <= j < ds.len() && ds[j] == cs[k]; + assert(p(ds[j])); + assert(exists|j: int| 0 <= j < ds.len() && p(ds[j])); + } + if exists|k: int| 0 <= k < ds.len() && p(ds[k]) { + let k = choose|k: int| 0 <= k < ds.len() && p(ds[k]); + assert(cs.to_set().contains(ds[k])); + assert(ds.contains(ds[k])); + assert(cs.contains(ds[k])); + let j = choose|j: int| 0 <= j < cs.len() && cs[j] == ds[k]; + assert(p(cs[j])); + assert(exists|j: int| 0 <= j < cs.len() && p(cs[j])); + } +} + +pub proof fn lemma_test_quantifiers_concat(p: spec_fn(A) -> bool, cs: Seq, ds: Seq) + ensures + (forall|k: int| 0 <= k < (cs + ds).len() ==> p((cs + ds)[k])) + == ((forall|k: int| 0 <= k < cs.len() ==> p(cs[k])) + && (forall|k: int| 0 <= k < ds.len() ==> p(ds[k]))), + (exists|k: int| 0 <= k < (cs + ds).len() && p((cs + ds)[k])) + == ((exists|k: int| 0 <= k < cs.len() && p(cs[k])) + || (exists|k: int| 0 <= k < ds.len() && p(ds[k]))), +{ + if forall|k: int| 0 <= k < (cs + ds).len() ==> p((cs + ds)[k]) { + assert forall|k: int| 0 <= k < cs.len() implies p(cs[k]) by { + assert((cs + ds)[k] == cs[k]); + } + assert forall|k: int| 0 <= k < ds.len() implies p(ds[k]) by { + assert((cs + ds)[cs.len() + k] == ds[k]); + assert(p((cs + ds)[cs.len() + k])); + } + } + if (forall|k: int| 0 <= k < cs.len() ==> p(cs[k])) + && (forall|k: int| 0 <= k < ds.len() ==> p(ds[k])) { + assert forall|k: int| 0 <= k < (cs + ds).len() implies p((cs + ds)[k]) by { + if k < cs.len() { assert((cs + ds)[k] == cs[k]); } + else { assert((cs + ds)[k] == ds[k - cs.len()]); } + } + } + if exists|k: int| 0 <= k < (cs + ds).len() && p((cs + ds)[k]) { + let k = choose|k: int| 0 <= k < (cs + ds).len() && p((cs + ds)[k]); + if k < cs.len() { + assert((cs + ds)[k] == cs[k]); + assert(exists|j: int| 0 <= j < cs.len() && p(cs[j])); + } else { + assert((cs + ds)[k] == ds[k - cs.len()]); + assert(exists|j: int| 0 <= j < ds.len() && p(ds[j])); + } + } + if exists|k: int| 0 <= k < cs.len() && p(cs[k]) { + let k = choose|k: int| 0 <= k < cs.len() && p(cs[k]); + assert((cs + ds)[k] == cs[k]); + assert(exists|j: int| 0 <= j < (cs + ds).len() && p((cs + ds)[j])); + } + if exists|k: int| 0 <= k < ds.len() && p(ds[k]) { + let k = choose|k: int| 0 <= k < ds.len() && p(ds[k]); + assert((cs + ds)[cs.len() + k] == ds[k]); + assert(p((cs + ds)[cs.len() + k])); + assert(exists|j: int| 0 <= j < (cs + ds).len() && p((cs + ds)[j])); + } +} + +pub proof fn lemma_test_quantifiers_remove(p: spec_fn(A) -> bool, cs: Seq, i: int) + requires 0 <= i < cs.len(), + ensures + (forall|k: int| 0 <= k < cs.len() ==> p(cs[k])) + == (p(cs[i]) && (forall|k: int| 0 <= k < cs.remove(i).len() ==> p(cs.remove(i)[k]))), + (exists|k: int| 0 <= k < cs.len() && p(cs[k])) + == (p(cs[i]) || (exists|k: int| 0 <= k < cs.remove(i).len() && p(cs.remove(i)[k]))), +{ + let ds = cs.remove(i); + assert(ds.len() == cs.len() - 1); + assert forall|k: int| 0 <= k < ds.len() + implies ds[k] == if k < i { cs[k] } else { cs[k + 1] } by {} + if forall|k: int| 0 <= k < cs.len() ==> p(cs[k]) { + assert(p(cs[i])); + assert forall|k: int| 0 <= k < ds.len() implies p(ds[k]) by { + let j = if k < i { k } else { k + 1 }; + assert(ds[k] == cs[j]); + assert(p(cs[j])); + } + } + if p(cs[i]) && (forall|k: int| 0 <= k < ds.len() ==> p(ds[k])) { + assert forall|k: int| 0 <= k < cs.len() implies p(cs[k]) by { + if k < i { assert(ds[k] == cs[k]); } + else if k > i { assert(ds[k - 1] == cs[k]); } + } + } + if exists|k: int| 0 <= k < cs.len() && p(cs[k]) { + let k = choose|k: int| 0 <= k < cs.len() && p(cs[k]); + if k != i { + let j = if k < i { k } else { k - 1 }; + assert(ds[j] == cs[k]); + assert(exists|j: int| 0 <= j < ds.len() && p(ds[j])); + } + } + if p(cs[i]) { + assert(exists|k: int| 0 <= k < cs.len() && p(cs[k])); + } + if exists|k: int| 0 <= k < ds.len() && p(ds[k]) { + let k = choose|k: int| 0 <= k < ds.len() && p(ds[k]); + let j = if k < i { k } else { k + 1 }; + assert(ds[k] == cs[j]); + assert(exists|j: int| 0 <= j < cs.len() && p(cs[j])); + } +} + +pub proof fn lemma_test_quantifiers_splice(p: spec_fn(A) -> bool, cs: Seq, i: int, ds: Seq) + requires 0 <= i < cs.len(), + ensures + (forall|k: int| 0 <= k < (cs.take(i) + ds + cs.skip(i + 1)).len() + ==> p(#[trigger] (cs.take(i) + ds + cs.skip(i + 1))[k])) + == ((forall|k: int| 0 <= k < cs.remove(i).len() ==> p(cs.remove(i)[k])) + && (forall|k: int| 0 <= k < ds.len() ==> p(ds[k]))), + (exists|k: int| 0 <= k < (cs.take(i) + ds + cs.skip(i + 1)).len() + && p(#[trigger] (cs.take(i) + ds + cs.skip(i + 1))[k])) + == ((exists|k: int| 0 <= k < cs.remove(i).len() && p(cs.remove(i)[k])) + || (exists|k: int| 0 <= k < ds.len() && p(ds[k]))), +{ + assert(cs.remove(i) =~= cs.take(i) + cs.skip(i + 1)) by { + assert forall|k: int| 0 <= k < cs.remove(i).len() + implies cs.remove(i)[k] == (cs.take(i) + cs.skip(i + 1))[k] by { + if k < i { assert(cs.remove(i)[k] == cs[k]); } + else { assert(cs.remove(i)[k] == cs[k + 1]); } + } + } + lemma_test_quantifiers_concat(p, cs.take(i), cs.skip(i + 1)); + lemma_test_quantifiers_concat(p, cs.take(i), ds); + lemma_test_quantifiers_concat(p, cs.take(i) + ds, cs.skip(i + 1)); +} + +pub proof fn lemma_test_connectives(theta: Subst, cs: Seq, e: EventView) + ensures + language::src_test_holds(theta, SrcTest::And(cs), e) + == (forall|k: int| 0 <= k < cs.len() ==> language::src_test_holds(theta, cs[k], e)), + language::src_test_holds(theta, SrcTest::Or(cs), e) + == (exists|k: int| 0 <= k < cs.len() && language::src_test_holds(theta, cs[k], e)), +{ + reveal_with_fuel(language::src_test_holds, 2); + assert((SrcTest::And(cs))->And_0 == cs); + assert((SrcTest::Or(cs))->Or_0 == cs); + if language::src_test_holds(theta, SrcTest::And(cs), e) { + assert forall|k: int| 0 <= k < cs.len() + implies language::src_test_holds(theta, cs[k], e) by { + assert(language::src_test_holds(theta, SrcTest::And(cs), e)); + } + } + if language::src_test_holds(theta, SrcTest::Or(cs), e) { + let k = choose|k: int| 0 <= k < cs.len() && language::src_test_holds(theta, cs[k], e); + assert(exists|j: int| 0 <= j < cs.len() && language::src_test_holds(theta, cs[j], e)); + } + if exists|k: int| 0 <= k < cs.len() && language::src_test_holds(theta, cs[k], e) { + let k = choose|k: int| 0 <= k < cs.len() && language::src_test_holds(theta, cs[k], e); + assert(language::src_test_holds(theta, SrcTest::Or(cs), e)); + } +} + +pub proof fn lemma_test_binary(theta: Subst, a: SrcTest, b: SrcTest, e: EventView) + ensures + language::src_test_holds(theta, SrcTest::And(seq![a, b]), e) + == (language::src_test_holds(theta, a, e) && language::src_test_holds(theta, b, e)), + language::src_test_holds(theta, SrcTest::Or(seq![a, b]), e) + == (language::src_test_holds(theta, a, e) || language::src_test_holds(theta, b, e)), +{ + let cs = seq![a, b]; + lemma_test_connectives(theta, cs, e); + if language::src_test_holds(theta, a, e) && language::src_test_holds(theta, b, e) { + assert forall|k: int| 0 <= k < cs.len() + implies language::src_test_holds(theta, cs[k], e) by { + assert(k == 0 || k == 1); + } + } + if language::src_test_holds(theta, SrcTest::And(cs), e) { + assert(language::src_test_holds(theta, cs[0], e)); + assert(language::src_test_holds(theta, cs[1], e)); + } + if language::src_test_holds(theta, SrcTest::Or(cs), e) { + let k = choose|k: int| 0 <= k < cs.len() && language::src_test_holds(theta, cs[k], e); + assert(k == 0 || k == 1); + } + if language::src_test_holds(theta, a, e) { + assert(language::src_test_holds(theta, cs[0], e)); + assert(exists|k: int| 0 <= k < cs.len() && language::src_test_holds(theta, cs[k], e)); + } + if language::src_test_holds(theta, b, e) { + assert(language::src_test_holds(theta, cs[1], e)); + assert(exists|k: int| 0 <= k < cs.len() && language::src_test_holds(theta, cs[k], e)); + } +} + +pub proof fn lemma_test_rule_sound(theta: Subst, rule: TestRule, e: EventView) + requires test_rule_valid(rule), + ensures language::src_test_holds(theta, test_rule_lhs(rule), e) + == language::src_test_holds(theta, test_rule_rhs(rule), e), +{ + let p = |t: SrcTest| language::src_test_holds(theta, t, e); + match rule { + TestRule::AndSet(cs, ds) | TestRule::OrSet(cs, ds) => { + lemma_test_quantifiers_set(p, cs, ds); + lemma_test_connectives(theta, cs, e); + lemma_test_connectives(theta, ds, e); + }, + TestRule::AndFlatten(cs, i) => { + let ds = cs[i]->And_0; + lemma_test_quantifiers_remove(p, cs, i); + lemma_test_quantifiers_splice(p, cs, i, ds); + lemma_test_connectives(theta, cs, e); + lemma_test_connectives(theta, ds, e); + lemma_test_connectives(theta, cs.take(i) + ds + cs.skip(i + 1), e); + }, + TestRule::OrFlatten(cs, i) => { + let ds = cs[i]->Or_0; + lemma_test_quantifiers_remove(p, cs, i); + lemma_test_quantifiers_splice(p, cs, i, ds); + lemma_test_connectives(theta, cs, e); + lemma_test_connectives(theta, ds, e); + lemma_test_connectives(theta, cs.take(i) + ds + cs.skip(i + 1), e); + }, + TestRule::AndTrue(cs, i) | TestRule::OrFalse(cs, i) => { + lemma_test_quantifiers_remove(p, cs, i); + lemma_test_connectives(theta, cs, e); + lemma_test_connectives(theta, cs.remove(i), e); + }, + TestRule::AndFalse(cs, i) => { + lemma_test_connectives(theta, cs, e); + assert(!language::src_test_holds(theta, cs[i], e)); + }, + TestRule::OrTrue(cs, i) => { + lemma_test_connectives(theta, cs, e); + assert(language::src_test_holds(theta, cs[i], e)); + assert(exists|k: int| 0 <= k < cs.len() && language::src_test_holds(theta, cs[k], e)); + }, + TestRule::AndSingleton(t) | TestRule::OrSingleton(t) => { + let cs = seq![t]; + lemma_test_connectives(theta, cs, e); + if language::src_test_holds(theta, SrcTest::And(cs), e) { + assert(language::src_test_holds(theta, cs[0], e)); + } + if language::src_test_holds(theta, t, e) { + assert forall|k: int| 0 <= k < cs.len() + implies language::src_test_holds(theta, cs[k], e) by { assert(k == 0); } + assert(exists|k: int| 0 <= k < cs.len() && language::src_test_holds(theta, cs[k], e)); + } + if language::src_test_holds(theta, SrcTest::Or(cs), e) { + let k = choose|k: int| 0 <= k < cs.len() && language::src_test_holds(theta, cs[k], e); + assert(k == 0); + } + }, + TestRule::AndNil | TestRule::OrNil => { + lemma_test_connectives(theta, Seq::empty(), e); + }, + TestRule::AndAbsorb(t, cs) => { + lemma_test_binary(theta, t, SrcTest::Or(cs), e); + lemma_test_connectives(theta, cs, e); + let k = choose|k: int| 0 <= k < cs.len() && cs[k] == t; + if language::src_test_holds(theta, t, e) { + assert(language::src_test_holds(theta, cs[k], e)); + assert(exists|j: int| 0 <= j < cs.len() && language::src_test_holds(theta, cs[j], e)); + } + }, + TestRule::OrAbsorb(t, cs) => { + lemma_test_binary(theta, t, SrcTest::And(cs), e); + lemma_test_connectives(theta, cs, e); + let k = choose|k: int| 0 <= k < cs.len() && cs[k] == t; + if language::src_test_holds(theta, SrcTest::And(cs), e) { + assert(language::src_test_holds(theta, cs[k], e)); + } + }, + TestRule::AndDistrib(t, cs) => { + let ds = Seq::new(cs.len(), |k: int| SrcTest::And(seq![t, cs[k]])); + lemma_test_binary(theta, t, SrcTest::Or(cs), e); + lemma_test_connectives(theta, cs, e); + lemma_test_connectives(theta, ds, e); + assert forall|k: int| 0 <= k < cs.len() + implies language::src_test_holds(theta, ds[k], e) + == (language::src_test_holds(theta, t, e) && language::src_test_holds(theta, cs[k], e)) by { + lemma_test_binary(theta, t, cs[k], e); + } + if language::src_test_holds(theta, SrcTest::And(seq![t, SrcTest::Or(cs)]), e) { + let k = choose|k: int| 0 <= k < cs.len() && language::src_test_holds(theta, cs[k], e); + assert(language::src_test_holds(theta, ds[k], e)); + assert(exists|j: int| 0 <= j < ds.len() && language::src_test_holds(theta, ds[j], e)); + } + if language::src_test_holds(theta, SrcTest::Or(ds), e) { + let k = choose|k: int| 0 <= k < ds.len() && language::src_test_holds(theta, ds[k], e); + assert(language::src_test_holds(theta, t, e)); + assert(language::src_test_holds(theta, cs[k], e)); + assert(exists|j: int| 0 <= j < cs.len() && language::src_test_holds(theta, cs[j], e)); + } + }, + TestRule::OrDistrib(t, cs) => { + let ds = Seq::new(cs.len(), |k: int| SrcTest::Or(seq![t, cs[k]])); + lemma_test_binary(theta, t, SrcTest::And(cs), e); + lemma_test_connectives(theta, cs, e); + lemma_test_connectives(theta, ds, e); + assert forall|k: int| 0 <= k < cs.len() + implies language::src_test_holds(theta, ds[k], e) + == (language::src_test_holds(theta, t, e) || language::src_test_holds(theta, cs[k], e)) by { + lemma_test_binary(theta, t, cs[k], e); + } + if language::src_test_holds(theta, SrcTest::Or(seq![t, SrcTest::And(cs)]), e) { + assert forall|k: int| 0 <= k < ds.len() + implies language::src_test_holds(theta, ds[k], e) by { + if !language::src_test_holds(theta, t, e) { + assert(language::src_test_holds(theta, cs[k], e)); + } + } + } + if language::src_test_holds(theta, SrcTest::And(ds), e) + && !language::src_test_holds(theta, t, e) { + assert forall|k: int| 0 <= k < cs.len() + implies language::src_test_holds(theta, cs[k], e) by { + assert(language::src_test_holds(theta, ds[k], e)); + } + } + }, + TestRule::AndExclusive(cs, i, j) => { + lemma_test_connectives(theta, cs, e); + if language::src_test_holds(theta, SrcTest::And(cs), e) { + assert(language::src_test_holds(theta, cs[i], e)); + assert(language::src_test_holds(theta, cs[j], e)); + let path = cs[i]->Eq_0; + let term = cs[i]->Eq_1; + assert(cs[j] == SrcTest::Neq(path, term)); + assert(language::field_value(e, path) == language::term_value(theta, term)); + assert(language::field_value(e, path) != language::term_value(theta, term)); + } + }, + TestRule::AndDistinctConstants(cs, i, j) => { + lemma_test_connectives(theta, cs, e); + if language::src_test_holds(theta, SrcTest::And(cs), e) { + assert(language::src_test_holds(theta, cs[i], e)); + assert(language::src_test_holds(theta, cs[j], e)); + let path = cs[i]->Eq_0; + let c = (cs[i]->Eq_1)->Constant_0; + let d = (cs[j]->Eq_1)->Constant_0; + assert(c != d); + assert(cs[i] == SrcTest::Eq(path, Term::Constant(c))); + assert(cs[j] == SrcTest::Eq(path, Term::Constant(d))); + assert(language::field_value(e, path) == c); + assert(language::field_value(e, path) == d); + } + }, + } +} + +/// Equation groups 1 and 3; n-ary sequences expose indices and side conditions. +pub enum RegexRule { + UnionSet(Seq>, Seq>), + IntersectSet(Seq>, Seq>), + UnionFlatten(Seq>, int), + IntersectFlatten(Seq>, int), + ConcatFlatten(Seq>, int), + UnionEmpty(Seq>, int), UnionAll(Seq>, int), + IntersectAll(Seq>, int), IntersectEmpty(Seq>, int), + ConcatEpsilon(Seq>, int), ConcatEmpty(Seq>, int), + UnionSingleton(Regex), IntersectSingleton(Regex), ConcatSingleton(Regex), + UnionNil, IntersectNil, ConcatNil, + StarStar(Regex), StarEpsilon, StarEmpty, StarAll, + NotNot(Regex), NotEmpty, NotAll, + TestUnion(Seq), TestIntersect(Seq), TestFalse, + IntersectEpsilonTest(Seq>, int, int), StarTrue, +} + +pub open spec fn regex_rule_lhs(rule: RegexRule) -> Regex { + match rule { + RegexRule::UnionSet(cs, _) | RegexRule::UnionFlatten(cs, _) + | RegexRule::UnionEmpty(cs, _) | RegexRule::UnionAll(cs, _) => Regex::Union(cs), + RegexRule::IntersectSet(cs, _) | RegexRule::IntersectFlatten(cs, _) + | RegexRule::IntersectAll(cs, _) | RegexRule::IntersectEmpty(cs, _) + | RegexRule::IntersectEpsilonTest(cs, _, _) => Regex::Intersect(cs), + RegexRule::ConcatFlatten(cs, _) | RegexRule::ConcatEpsilon(cs, _) + | RegexRule::ConcatEmpty(cs, _) => Regex::Concat(cs), + RegexRule::UnionSingleton(c) => Regex::Union(seq![c]), + RegexRule::IntersectSingleton(c) => Regex::Intersect(seq![c]), + RegexRule::ConcatSingleton(c) => Regex::Concat(seq![c]), + RegexRule::UnionNil => Regex::Union(Seq::empty()), + RegexRule::IntersectNil => Regex::Intersect(Seq::empty()), + RegexRule::ConcatNil => Regex::Concat(Seq::empty()), + RegexRule::StarStar(c) => Regex::Star(Box::new(Regex::Star(Box::new(c)))), + RegexRule::StarEpsilon => Regex::Star(Box::new(Regex::Epsilon)), + RegexRule::StarEmpty => Regex::Star(Box::new(Regex::Empty)), + RegexRule::StarAll => Regex::Star(Box::new(Regex::All)), + RegexRule::NotNot(c) => Regex::Not(Box::new(Regex::Not(Box::new(c)))), + RegexRule::NotEmpty => Regex::Not(Box::new(Regex::Empty)), + RegexRule::NotAll => Regex::Not(Box::new(Regex::All)), + RegexRule::TestUnion(phis) => Regex::Union(Seq::new(phis.len(), |k: int| Regex::Test(phis[k]))), + RegexRule::TestIntersect(phis) => Regex::Intersect(Seq::new(phis.len(), |k: int| Regex::Test(phis[k]))), + RegexRule::TestFalse => Regex::Test(SrcTest::Bool(false)), + RegexRule::StarTrue => Regex::Star(Box::new(Regex::Test(SrcTest::Bool(true)))), + } +} + +pub open spec fn regex_rule_rhs(rule: RegexRule) -> Regex { + match rule { + RegexRule::UnionSet(_, ds) => Regex::Union(ds), + RegexRule::IntersectSet(_, ds) => Regex::Intersect(ds), + RegexRule::UnionFlatten(cs, i) => Regex::Union(cs.take(i) + cs[i]->Union_0 + cs.skip(i + 1)), + RegexRule::IntersectFlatten(cs, i) => Regex::Intersect(cs.take(i) + cs[i]->Intersect_0 + cs.skip(i + 1)), + RegexRule::ConcatFlatten(cs, i) => Regex::Concat(cs.take(i) + cs[i]->Concat_0 + cs.skip(i + 1)), + RegexRule::UnionEmpty(cs, i) => Regex::Union(cs.remove(i)), + RegexRule::IntersectAll(cs, i) => Regex::Intersect(cs.remove(i)), + RegexRule::ConcatEpsilon(cs, i) => Regex::Concat(cs.remove(i)), + RegexRule::UnionAll(_, _) | RegexRule::IntersectNil | RegexRule::StarAll | RegexRule::NotEmpty | RegexRule::StarTrue => Regex::All, + RegexRule::IntersectEmpty(_, _) | RegexRule::ConcatEmpty(_, _) | RegexRule::UnionNil + | RegexRule::NotAll | RegexRule::TestFalse | RegexRule::IntersectEpsilonTest(_, _, _) => Regex::Empty, + RegexRule::UnionSingleton(c) | RegexRule::IntersectSingleton(c) | RegexRule::ConcatSingleton(c) | RegexRule::NotNot(c) => c, + RegexRule::ConcatNil | RegexRule::StarEpsilon | RegexRule::StarEmpty => Regex::Epsilon, + RegexRule::StarStar(c) => Regex::Star(Box::new(c)), + RegexRule::TestUnion(phis) => Regex::Test(SrcTest::Or(phis)), + RegexRule::TestIntersect(phis) => Regex::Test(SrcTest::And(phis)), + } +} + +pub open spec fn regex_rule_valid(rule: RegexRule) -> bool { + match rule { + RegexRule::UnionSet(cs, ds) | RegexRule::IntersectSet(cs, ds) => cs.to_set() == ds.to_set(), + RegexRule::UnionFlatten(cs, i) => 0 <= i < cs.len() && cs[i] is Union, + RegexRule::IntersectFlatten(cs, i) => 0 <= i < cs.len() && cs[i] is Intersect, + RegexRule::ConcatFlatten(cs, i) => 0 <= i < cs.len() && cs[i] is Concat, + RegexRule::UnionEmpty(cs, i) | RegexRule::IntersectEmpty(cs, i) | RegexRule::ConcatEmpty(cs, i) => 0 <= i < cs.len() && cs[i] == Regex::Empty, + RegexRule::UnionAll(cs, i) | RegexRule::IntersectAll(cs, i) => 0 <= i < cs.len() && cs[i] == Regex::All, + RegexRule::ConcatEpsilon(cs, i) => 0 <= i < cs.len() && cs[i] == Regex::Epsilon, + RegexRule::TestIntersect(phis) => phis.len() > 0, + RegexRule::IntersectEpsilonTest(cs, i, j) => 0 <= i < cs.len() && 0 <= j < cs.len() && cs[i] == Regex::Epsilon && cs[j] is Test, + _ => true, + } +} + +pub proof fn lemma_lang_union_set(sem: spec_fn(L, EventView) -> bool, cs: Seq>, ds: Seq>, w: Seq) + requires cs.to_set() == ds.to_set(), + ensures language::numeric_lang(sem, Regex::Union(cs), w) == language::numeric_lang(sem, Regex::Union(ds), w), +{ + lemma_test_quantifiers_set(|r: Regex| language::numeric_lang(sem, r, w), cs, ds); + language::lemma_lang_union(sem, cs, w); language::lemma_lang_union(sem, ds, w); +} + +pub proof fn lemma_lang_intersect_set(sem: spec_fn(L, EventView) -> bool, cs: Seq>, ds: Seq>, w: Seq) + requires cs.to_set() == ds.to_set(), + ensures language::numeric_lang(sem, Regex::Intersect(cs), w) == language::numeric_lang(sem, Regex::Intersect(ds), w), +{ + lemma_test_quantifiers_set(|r: Regex| language::numeric_lang(sem, r, w), cs, ds); + language::lemma_lang_intersect(sem, cs, w); language::lemma_lang_intersect(sem, ds, w); +} + + +pub proof fn lemma_lang_union_splice(sem: spec_fn(L, EventView) -> bool, cs: Seq>, i: int, w: Seq) + requires 0 <= i < cs.len(), cs[i] is Union, + ensures language::numeric_lang(sem, Regex::Union(cs), w) == language::numeric_lang(sem, Regex::Union(cs.take(i) + cs[i]->Union_0 + cs.skip(i + 1)), w), +{ + lemma_test_quantifiers_remove(|r: Regex| language::numeric_lang(sem, r, w), cs, i); + lemma_test_quantifiers_splice(|r: Regex| language::numeric_lang(sem, r, w), cs, i, cs[i]->Union_0); + language::lemma_lang_union(sem, cs, w); + language::lemma_lang_union(sem, cs[i]->Union_0, w); + language::lemma_lang_union(sem, cs.take(i) + cs[i]->Union_0 + cs.skip(i + 1), w); +} + +pub proof fn lemma_lang_intersect_splice(sem: spec_fn(L, EventView) -> bool, cs: Seq>, i: int, w: Seq) + requires 0 <= i < cs.len(), cs[i] is Intersect, + ensures language::numeric_lang(sem, Regex::Intersect(cs), w) == language::numeric_lang(sem, Regex::Intersect(cs.take(i) + cs[i]->Intersect_0 + cs.skip(i + 1)), w), +{ + lemma_test_quantifiers_remove(|r: Regex| language::numeric_lang(sem, r, w), cs, i); + lemma_test_quantifiers_splice(|r: Regex| language::numeric_lang(sem, r, w), cs, i, cs[i]->Intersect_0); + language::lemma_lang_intersect(sem, cs, w); + language::lemma_lang_intersect(sem, cs[i]->Intersect_0, w); + language::lemma_lang_intersect(sem, cs.take(i) + cs[i]->Intersect_0 + cs.skip(i + 1), w); +} + +pub proof fn lemma_concat_split( + sem: spec_fn(L, EventView) -> bool, + cs: Seq>, + ds: Seq>, + w: Seq, +) + ensures language::numeric_lang(sem, Regex::Concat(cs + ds), w) <==> + exists|a: Seq, b: Seq| w == a + b + && language::numeric_lang(sem, Regex::Concat(cs), a) + && language::numeric_lang(sem, Regex::Concat(ds), b), + decreases cs.len(), +{ + if language::numeric_lang(sem, Regex::Concat(cs + ds), w) { + let parts = choose|p: Seq>| p.len() == (cs + ds).len() + && w == p.flatten() + && forall|k: int| 0 <= k < (cs + ds).len() ==> + language::numeric_lang(sem, (cs + ds)[k], p[k]); + let ap = parts.subrange(0, cs.len() as int); + let bp = parts.subrange(cs.len() as int, parts.len() as int); + assert(parts =~= ap + bp); + vstd::seq_lib::lemma_flatten_concat(ap, bp); + assert(parts.flatten() == ap.flatten() + bp.flatten()); + assert forall|k: int| 0 <= k < cs.len() implies + language::numeric_lang(sem, cs[k], ap[k]) by { + assert(cs[k] == (cs + ds)[k]); + assert(ap[k] == parts[k]); + } + assert forall|k: int| 0 <= k < ds.len() implies + language::numeric_lang(sem, ds[k], bp[k]) by { + assert(ds[k] == (cs + ds)[cs.len() + k]); + assert(bp[k] == parts[cs.len() + k]); + } + assert(language::numeric_lang(sem, Regex::Concat(cs), ap.flatten())); + assert(language::numeric_lang(sem, Regex::Concat(ds), bp.flatten())); + } + if exists|a: Seq, b: Seq| w == a + b + && language::numeric_lang(sem, Regex::Concat(cs), a) + && language::numeric_lang(sem, Regex::Concat(ds), b) { + let (a, b) = choose|a: Seq, b: Seq| w == a + b + && language::numeric_lang(sem, Regex::Concat(cs), a) + && language::numeric_lang(sem, Regex::Concat(ds), b); + let ap = choose|p: Seq>| p.len() == cs.len() + && a == p.flatten() + && forall|k: int| 0 <= k < cs.len() ==> language::numeric_lang(sem, cs[k], p[k]); + let bp = choose|p: Seq>| p.len() == ds.len() + && b == p.flatten() + && forall|k: int| 0 <= k < ds.len() ==> language::numeric_lang(sem, ds[k], p[k]); + let parts = ap + bp; + vstd::seq_lib::lemma_flatten_concat(ap, bp); + assert(parts.flatten() == w); + assert forall|k: int| 0 <= k < (cs + ds).len() implies + language::numeric_lang(sem, (cs + ds)[k], parts[k]) by { + if k < cs.len() { + assert((cs + ds)[k] == cs[k]); + assert(parts[k] == ap[k]); + } else { + assert((cs + ds)[k] == ds[k - cs.len()]); + assert(parts[k] == bp[k - cs.len()]); + } + } + assert(language::numeric_lang(sem, Regex::Concat(cs + ds), w)); + } +} + +pub proof fn lemma_parts_star_nil(sem: spec_fn(L, EventView) -> bool, c: Regex) + ensures language::numeric_lang(sem, Regex::Star(Box::new(c)), Seq::empty()), +{ + let parts = Seq::>::empty(); + assert(parts.flatten() == Seq::::empty()); + assert(forall|k: int| 0 <= k < parts.len() ==> language::numeric_lang(sem, c, parts[k])); +} + +pub proof fn lemma_parts_star_single( + sem: spec_fn(L, EventView) -> bool, c: Regex, w: Seq, +) + requires language::numeric_lang(sem, c, w), + ensures language::numeric_lang(sem, Regex::Star(Box::new(c)), w), +{ + let parts = seq![w]; + parts.lemma_flatten_one_element(); + assert forall|k: int| 0 <= k < parts.len() implies language::numeric_lang(sem, c, parts[k]) by { + assert(k == 0); + } +} + +pub proof fn lemma_parts_star_join( + sem: spec_fn(L, EventView) -> bool, c: Regex, a: Seq, b: Seq, +) + requires language::numeric_lang(sem, Regex::Star(Box::new(c)), a), + language::numeric_lang(sem, Regex::Star(Box::new(c)), b), + ensures language::numeric_lang(sem, Regex::Star(Box::new(c)), a + b), +{ + let ap = choose|p: Seq>| a == p.flatten() + && forall|k: int| 0 <= k < p.len() ==> language::numeric_lang(sem, c, p[k]); + let bp = choose|p: Seq>| b == p.flatten() + && forall|k: int| 0 <= k < p.len() ==> language::numeric_lang(sem, c, p[k]); + let parts = ap + bp; + vstd::seq_lib::lemma_flatten_concat(ap, bp); + assert(parts.flatten() == a + b); + assert forall|k: int| 0 <= k < parts.len() implies language::numeric_lang(sem, c, parts[k]) by { + if k < ap.len() { + assert(parts[k] == ap[k]); + } else { + assert(parts[k] == bp[k - ap.len()]); + } + } +} + +/// Concatenating finitely many words in c* remains in c*, including empty parts. +pub proof fn lemma_parts_star_flatten( + sem: spec_fn(L, EventView) -> bool, c: Regex, parts: Seq>, +) + requires forall|k: int| 0 <= k < parts.len() ==> + language::numeric_lang(sem, Regex::Star(Box::new(c)), parts[k]), + ensures language::numeric_lang(sem, Regex::Star(Box::new(c)), parts.flatten()), + decreases parts.len(), +{ + if parts.len() == 0 { + lemma_parts_star_nil(sem, c); + } else { + assert forall|k: int| 0 <= k < parts.drop_first().len() implies + language::numeric_lang(sem, Regex::Star(Box::new(c)), parts.drop_first()[k]) by { + assert(parts.drop_first()[k] == parts[k + 1]); + } + lemma_parts_star_flatten(sem, c, parts.drop_first()); + lemma_parts_star_join(sem, c, parts[0], parts.drop_first().flatten()); + } +} + +pub proof fn lemma_star_star(sem: spec_fn(L, EventView) -> bool, c: Regex, w: Seq) + ensures language::numeric_lang(sem, Regex::Star(Box::new(Regex::Star(Box::new(c)))), w) + == language::numeric_lang(sem, Regex::Star(Box::new(c)), w), +{ + if language::numeric_lang(sem, Regex::Star(Box::new(Regex::Star(Box::new(c)))), w) { + let parts = choose|p: Seq>| w == p.flatten() + && forall|k: int| 0 <= k < p.len() ==> + language::numeric_lang(sem, Regex::Star(Box::new(c)), p[k]); + lemma_parts_star_flatten(sem, c, parts); + } + if language::numeric_lang(sem, Regex::Star(Box::new(c)), w) { + lemma_parts_star_single(sem, Regex::Star(Box::new(c)), w); + } +} + +pub proof fn lemma_star_of_nullary( + sem: spec_fn(L, EventView) -> bool, c: Regex, w: Seq, +) + requires forall|v: Seq| language::numeric_lang(sem, c, v) ==> v.len() == 0, + ensures language::numeric_lang(sem, Regex::Star(Box::new(c)), w) == (w.len() == 0), +{ + if language::numeric_lang(sem, Regex::Star(Box::new(c)), w) { + let parts = choose|p: Seq>| w == p.flatten() + && forall|k: int| 0 <= k < p.len() ==> language::numeric_lang(sem, c, p[k]); + assert forall|k: int| 0 <= k < parts.len() implies parts[k].len() == 0 by { + assert(language::numeric_lang(sem, c, parts[k])); + } + language::lemma_flatten_empty(parts); + } + if w.len() == 0 { + assert(w =~= Seq::::empty()); + lemma_parts_star_nil(sem, c); + } +} + +pub proof fn lemma_singletons_flatten(w: Seq) + ensures Seq::new(w.len(), |k: int| seq![w[k]]).flatten() == w, + decreases w.len(), +{ + if w.len() == 0 { + assert(Seq::new(w.len(), |k: int| seq![w[k]]) =~= Seq::>::empty()); + } else { + let prefix = w.drop_last(); + let parts = Seq::new(prefix.len(), |k: int| seq![prefix[k]]); + lemma_singletons_flatten(prefix); + assert(Seq::new(w.len(), |k: int| seq![w[k]]) =~= parts.push(seq![w.last()])); + parts.lemma_flatten_push(seq![w.last()]); + assert(prefix + seq![w.last()] =~= w); + } +} + +/// Equal tail languages can be substituted after the same first expression. +pub proof fn lemma_parts_concat_tail_congruent( + sem: spec_fn(L, EventView) -> bool, + c: Regex, + left: Seq>, + right: Seq>, + w: Seq, +) + requires forall|v: Seq| language::numeric_lang(sem, Regex::Concat(left), v) + == language::numeric_lang(sem, Regex::Concat(right), v), + ensures language::numeric_lang(sem, Regex::Concat(seq![c] + left), w) + == language::numeric_lang(sem, Regex::Concat(seq![c] + right), w), +{ + language::lemma_concat_prepend(sem, c, left, w); + language::lemma_concat_prepend(sem, c, right, w); + if language::numeric_lang(sem, Regex::Concat(seq![c] + left), w) { + let (a, b) = choose|a: Seq, b: Seq| w == a + b + && language::numeric_lang(sem, c, a) + && language::numeric_lang(sem, Regex::Concat(left), b); + assert(language::numeric_lang(sem, Regex::Concat(right), b)); + assert(exists|a: Seq, b: Seq| w == a + b + && language::numeric_lang(sem, c, a) + && language::numeric_lang(sem, Regex::Concat(right), b)); + } + if language::numeric_lang(sem, Regex::Concat(seq![c] + right), w) { + let (a, b) = choose|a: Seq, b: Seq| w == a + b + && language::numeric_lang(sem, c, a) + && language::numeric_lang(sem, Regex::Concat(right), b); + assert(language::numeric_lang(sem, Regex::Concat(left), b)); + assert(exists|a: Seq, b: Seq| w == a + b + && language::numeric_lang(sem, c, a) + && language::numeric_lang(sem, Regex::Concat(left), b)); + } +} + +pub proof fn lemma_lang_concat_splice( + sem: spec_fn(L, EventView) -> bool, cs: Seq>, i: int, w: Seq, +) + requires 0 <= i < cs.len(), cs[i] is Concat, + ensures language::numeric_lang(sem, Regex::Concat(cs), w) + == language::numeric_lang(sem, Regex::Concat(cs.take(i) + cs[i]->Concat_0 + cs.skip(i + 1)), w), + decreases i, +{ + let inner = cs[i]->Concat_0; + let ds = cs.take(i) + inner + cs.skip(i + 1); + if i == 0 { + assert(ds =~= inner + cs.drop_first()); + language::lemma_concat_uncons(sem, cs, w); + lemma_concat_split(sem, inner, cs.drop_first(), w); + assert(cs[0] == Regex::Concat(inner)); + } else { + let tail = cs.drop_first(); + assert(tail[i - 1] == cs[i]); + let flat_tail = tail.take(i - 1) + inner + tail.skip(i); + assert(cs =~= seq![cs[0]] + tail); + assert(ds =~= seq![cs[0]] + flat_tail); + assert forall|v: Seq| language::numeric_lang(sem, Regex::Concat(tail), v) + == language::numeric_lang(sem, Regex::Concat(flat_tail), v) by { + lemma_lang_concat_splice(sem, tail, i - 1, v); + } + lemma_parts_concat_tail_congruent(sem, cs[0], tail, flat_tail, w); + } +} + +pub proof fn lemma_parts_concat_nil(sem: spec_fn(L, EventView) -> bool, w: Seq) + ensures language::numeric_lang(sem, Regex::Concat(Seq::>::empty()), w) == (w.len() == 0), +{ + if language::numeric_lang(sem, Regex::Concat(Seq::>::empty()), w) { + let parts = choose|p: Seq>| p.len() == 0 && w == p.flatten() + && forall|k: int| 0 <= k < 0 ==> + language::numeric_lang(sem, Seq::>::empty()[k], p[k]); + assert(parts =~= Seq::>::empty()); + } + if w.len() == 0 { + let parts = Seq::>::empty(); + assert(w =~= parts.flatten()); + assert(forall|k: int| 0 <= k < 0 ==> + language::numeric_lang(sem, Seq::>::empty()[k], parts[k])); + } +} + +pub proof fn lemma_lang_concat_epsilon( + sem: spec_fn(L, EventView) -> bool, cs: Seq>, i: int, w: Seq, +) + requires 0 <= i < cs.len(), cs[i] == Regex::Epsilon, + ensures language::numeric_lang(sem, Regex::Concat(cs), w) + == language::numeric_lang(sem, Regex::Concat(cs.remove(i)), w), + decreases i, +{ + let tail = cs.drop_first(); + if i == 0 { + assert(cs.remove(i) =~= tail); + language::lemma_concat_uncons(sem, cs, w); + if language::numeric_lang(sem, Regex::Concat(cs), w) { + let (a, b) = choose|a: Seq, b: Seq| w == a + b + && language::numeric_lang(sem, cs[0], a) + && language::numeric_lang(sem, Regex::Concat(tail), b); + assert(a =~= Seq::::empty()); + assert(b =~= w); + } + if language::numeric_lang(sem, Regex::Concat(tail), w) { + let a = Seq::::empty(); + assert(w == a + w); + assert(language::numeric_lang(sem, cs[0], a)); + assert(exists|a: Seq, b: Seq| w == a + b + && language::numeric_lang(sem, cs[0], a) + && language::numeric_lang(sem, Regex::Concat(tail), b)); + } + } else { + assert(tail[i - 1] == cs[i]); + let shorter = tail.remove(i - 1); + assert(cs =~= seq![cs[0]] + tail); + assert(cs.remove(i) =~= seq![cs[0]] + shorter); + assert forall|v: Seq| language::numeric_lang(sem, Regex::Concat(tail), v) + == language::numeric_lang(sem, Regex::Concat(shorter), v) by { + lemma_lang_concat_epsilon(sem, tail, i - 1, v); + } + lemma_parts_concat_tail_congruent(sem, cs[0], tail, shorter, w); + } +} + +pub proof fn lemma_lang_concat_empty( + sem: spec_fn(L, EventView) -> bool, cs: Seq>, i: int, w: Seq, +) + requires 0 <= i < cs.len(), cs[i] == Regex::Empty, + ensures !language::numeric_lang(sem, Regex::Concat(cs), w), +{ + if language::numeric_lang(sem, Regex::Concat(cs), w) { + let parts = choose|p: Seq>| p.len() == cs.len() && w == p.flatten() + && forall|k: int| 0 <= k < cs.len() ==> language::numeric_lang(sem, cs[k], p[k]); + assert(language::numeric_lang(sem, cs[i], parts[i])); + } +} + +pub proof fn lemma_regex_rule_sound(theta: Subst, rule: RegexRule, w: Seq) + requires regex_rule_valid(rule), + ensures language::numeric_lang(src_sem(theta), regex_rule_lhs(rule), w) == language::numeric_lang(src_sem(theta), regex_rule_rhs(rule), w), +{ + let sem = src_sem(theta); + reveal_with_fuel(language::numeric_lang, 3); + match rule { + RegexRule::UnionSet(cs, ds) => lemma_lang_union_set(sem, cs, ds, w), + RegexRule::IntersectSet(cs, ds) => lemma_lang_intersect_set(sem, cs, ds, w), + RegexRule::UnionFlatten(cs, i) => lemma_lang_union_splice(sem, cs, i, w), + RegexRule::IntersectFlatten(cs, i) => lemma_lang_intersect_splice(sem, cs, i, w), + RegexRule::ConcatFlatten(cs, i) => lemma_lang_concat_splice(sem, cs, i, w), + RegexRule::UnionEmpty(cs, i) | RegexRule::IntersectAll(cs, i) => { + lemma_test_quantifiers_remove(|r: Regex| language::numeric_lang(sem, r, w), cs, i); + if rule is UnionEmpty { + language::lemma_lang_union(sem, cs, w); + language::lemma_lang_union(sem, cs.remove(i), w); + } else { + language::lemma_lang_intersect(sem, cs, w); + language::lemma_lang_intersect(sem, cs.remove(i), w); + } + }, + RegexRule::UnionAll(cs, i) => { + language::lemma_lang_union(sem, cs, w); + assert(language::numeric_lang(sem, cs[i], w)); + }, + RegexRule::IntersectEmpty(cs, i) => { + language::lemma_lang_intersect(sem, cs, w); + assert(!language::numeric_lang(sem, cs[i], w)); + }, + RegexRule::ConcatEpsilon(cs, i) => lemma_lang_concat_epsilon(sem, cs, i, w), + RegexRule::ConcatEmpty(cs, i) => lemma_lang_concat_empty(sem, cs, i, w), + RegexRule::UnionSingleton(c) => { + language::lemma_union_optional(sem, c, c, false, w); + assert(seq![c] + Seq::empty() =~= seq![c]); + }, + RegexRule::IntersectSingleton(c) => { + language::lemma_lang_intersect(sem, seq![c], w); + assert forall|i: int| 0 <= i < 1 implies seq![c][i] == c by { assert(i == 0); } + if language::numeric_lang(sem, Regex::Intersect(seq![c]), w) { + assert(language::numeric_lang(sem, seq![c][0], w)); + } + }, + RegexRule::ConcatSingleton(c) => language::lemma_concat_singleton(sem, c, w), + RegexRule::ConcatNil => lemma_parts_concat_nil(sem, w), + RegexRule::StarStar(c) => lemma_star_star(sem, c, w), + RegexRule::StarEpsilon => { + assert forall|v: Seq| language::numeric_lang(sem, Regex::Epsilon, v) implies v.len() == 0 by { } + lemma_star_of_nullary(sem, Regex::Epsilon, w); + }, + RegexRule::StarEmpty => { + assert forall|v: Seq| language::numeric_lang(sem, Regex::Empty, v) implies v.len() == 0 by { } + lemma_star_of_nullary(sem, Regex::Empty, w); + }, + RegexRule::StarAll | RegexRule::StarTrue => { + let c = if rule is StarAll { Regex::All } else { Regex::Test(SrcTest::Bool(true)) }; + let parts = Seq::new(w.len(), |k: int| seq![w[k]]); + lemma_singletons_flatten(w); + assert forall|k: int| 0 <= k < parts.len() implies language::numeric_lang(sem, c, parts[k]) by { + assert(parts[k].len() == 1); assert(parts[k][0] == w[k]); + } + assert(language::numeric_lang(sem, Regex::Star(Box::new(c)), w)); + }, + RegexRule::TestUnion(phis) => { + let cs = Seq::new(phis.len(), |k: int| Regex::Test(phis[k])); + assert(regex_rule_lhs(rule)->Union_0 =~= cs); + if w.len() == 1 { lemma_test_connectives(theta, phis, w[0]); } + language::lemma_lang_union(sem, cs, w); + if language::numeric_lang(sem, Regex::Union(cs), w) { + let k = choose|k: int| 0 <= k < cs.len() && language::numeric_lang(sem, cs[k], w); + assert(w.len() == 1 && language::src_test_holds(theta, phis[k], w[0])); + assert(language::src_test_holds(theta, SrcTest::Or(phis), w[0])); + } + if language::numeric_lang(sem, Regex::Test(SrcTest::Or(phis)), w) { + let k = choose|k: int| 0 <= k < phis.len() && language::src_test_holds(theta, phis[k], w[0]); + assert(language::numeric_lang(sem, cs[k], w)); + } + }, + RegexRule::TestIntersect(phis) => { + let cs = Seq::new(phis.len(), |k: int| Regex::Test(phis[k])); + assert(regex_rule_lhs(rule)->Intersect_0 =~= cs); + if w.len() == 1 { lemma_test_connectives(theta, phis, w[0]); } + language::lemma_lang_intersect(sem, cs, w); + if language::numeric_lang(sem, Regex::Intersect(cs), w) { + assert(language::numeric_lang(sem, cs[0], w)); + assert(w.len() == 1); + assert forall|k: int| 0 <= k < phis.len() implies language::src_test_holds(theta, phis[k], w[0]) by { + assert(language::numeric_lang(sem, cs[k], w)); + } + } + if language::numeric_lang(sem, Regex::Test(SrcTest::And(phis)), w) { + assert forall|k: int| 0 <= k < cs.len() implies language::numeric_lang(sem, cs[k], w) by { } + } + }, + RegexRule::IntersectEpsilonTest(cs, i, j) => { + language::lemma_lang_intersect(sem, cs, w); + if language::numeric_lang(sem, Regex::Intersect(cs), w) { + assert(language::numeric_lang(sem, cs[i], w)); + assert(language::numeric_lang(sem, cs[j], w)); + } + }, + RegexRule::NotNot(c) => { + assert(language::numeric_lang(sem, regex_rule_lhs(rule), w) == language::numeric_lang(sem, c, w)); + }, + RegexRule::UnionNil | RegexRule::IntersectNil | RegexRule::NotEmpty | RegexRule::NotAll | RegexRule::TestFalse => { + assert(language::numeric_lang(sem, regex_rule_lhs(rule), w) == language::numeric_lang(sem, regex_rule_rhs(rule), w)); + }, + } +} + +/// Finite derivations generate exactly the equivalence/congruence closure of the rules. +pub enum TestSim { + Rule(TestRule), Refl(SrcTest), Sym(Box), Trans(Box, Box), + And(Seq), Or(Seq), +} + +pub enum Sim { + Rule(RegexRule), Refl(Regex), Sym(Box), Trans(Box, Box), + Test(TestSim), Union(Seq), Concat(Seq), Intersect(Seq), Star(Box), Not(Box), +} + +pub open spec fn test_sim_lhs(d: TestSim) -> SrcTest decreases d { + match d { + TestSim::Rule(rule) => test_rule_lhs(rule), + TestSim::Refl(t) => t, + TestSim::Sym(c) => test_sim_rhs(*c), + TestSim::Trans(a, _) => test_sim_lhs(*a), + TestSim::And(ds) => SrcTest::And(Seq::new(ds.len(), |k: int| if 0 <= k < ds.len() { test_sim_lhs(ds[k]) } else { SrcTest::Bool(true) })), + TestSim::Or(ds) => SrcTest::Or(Seq::new(ds.len(), |k: int| if 0 <= k < ds.len() { test_sim_lhs(ds[k]) } else { SrcTest::Bool(true) })), + } +} + +pub open spec fn test_sim_rhs(d: TestSim) -> SrcTest decreases d { + match d { + TestSim::Rule(rule) => test_rule_rhs(rule), + TestSim::Refl(t) => t, + TestSim::Sym(c) => test_sim_lhs(*c), + TestSim::Trans(_, b) => test_sim_rhs(*b), + TestSim::And(ds) => SrcTest::And(Seq::new(ds.len(), |k: int| if 0 <= k < ds.len() { test_sim_rhs(ds[k]) } else { SrcTest::Bool(true) })), + TestSim::Or(ds) => SrcTest::Or(Seq::new(ds.len(), |k: int| if 0 <= k < ds.len() { test_sim_rhs(ds[k]) } else { SrcTest::Bool(true) })), + } +} + +pub open spec fn test_sim_valid(d: TestSim) -> bool decreases d { + match d { + TestSim::Rule(rule) => test_rule_valid(rule), + TestSim::Refl(_) => true, + TestSim::Sym(c) => test_sim_valid(*c), + TestSim::Trans(a, b) => test_sim_valid(*a) && test_sim_valid(*b) && test_sim_rhs(*a) == test_sim_lhs(*b), + TestSim::And(ds) => forall|k: int| 0 <= k < ds.len() ==> test_sim_valid(#[trigger] ds[k]), + TestSim::Or(ds) => forall|k: int| 0 <= k < ds.len() ==> test_sim_valid(#[trigger] ds[k]), + } +} + +pub open spec fn sim_lhs(d: Sim) -> Regex decreases d { + match d { + Sim::Rule(rule) => regex_rule_lhs(rule), + Sim::Refl(r) => r, + Sim::Sym(c) => sim_rhs(*c), + Sim::Trans(a, _) => sim_lhs(*a), + Sim::Test(t) => Regex::Test(test_sim_lhs(t)), + Sim::Union(ds) => Regex::Union(Seq::new(ds.len(), |k: int| if 0 <= k < ds.len() { sim_lhs(ds[k]) } else { Regex::Empty })), + Sim::Concat(ds) => Regex::Concat(Seq::new(ds.len(), |k: int| if 0 <= k < ds.len() { sim_lhs(ds[k]) } else { Regex::Empty })), + Sim::Intersect(ds) => Regex::Intersect(Seq::new(ds.len(), |k: int| if 0 <= k < ds.len() { sim_lhs(ds[k]) } else { Regex::Empty })), + Sim::Star(c) => Regex::Star(Box::new(sim_lhs(*c))), + Sim::Not(c) => Regex::Not(Box::new(sim_lhs(*c))), + } +} + +pub open spec fn sim_rhs(d: Sim) -> Regex decreases d { + match d { + Sim::Rule(rule) => regex_rule_rhs(rule), + Sim::Refl(r) => r, + Sim::Sym(c) => sim_lhs(*c), + Sim::Trans(_, b) => sim_rhs(*b), + Sim::Test(t) => Regex::Test(test_sim_rhs(t)), + Sim::Union(ds) => Regex::Union(Seq::new(ds.len(), |k: int| if 0 <= k < ds.len() { sim_rhs(ds[k]) } else { Regex::Empty })), + Sim::Concat(ds) => Regex::Concat(Seq::new(ds.len(), |k: int| if 0 <= k < ds.len() { sim_rhs(ds[k]) } else { Regex::Empty })), + Sim::Intersect(ds) => Regex::Intersect(Seq::new(ds.len(), |k: int| if 0 <= k < ds.len() { sim_rhs(ds[k]) } else { Regex::Empty })), + Sim::Star(c) => Regex::Star(Box::new(sim_rhs(*c))), + Sim::Not(c) => Regex::Not(Box::new(sim_rhs(*c))), + } +} + +pub open spec fn sim_valid(d: Sim) -> bool decreases d { + match d { + Sim::Rule(rule) => regex_rule_valid(rule), + Sim::Refl(_) => true, + Sim::Sym(c) => sim_valid(*c), + Sim::Trans(a, b) => sim_valid(*a) && sim_valid(*b) && sim_rhs(*a) == sim_lhs(*b), + Sim::Test(t) => test_sim_valid(t), + Sim::Union(ds) => forall|k: int| 0 <= k < ds.len() ==> sim_valid(#[trigger] ds[k]), + Sim::Concat(ds) => forall|k: int| 0 <= k < ds.len() ==> sim_valid(#[trigger] ds[k]), + Sim::Intersect(ds) => forall|k: int| 0 <= k < ds.len() ==> sim_valid(#[trigger] ds[k]), + Sim::Star(c) | Sim::Not(c) => sim_valid(*c), + } +} + +pub open spec fn test_similar(a: SrcTest, b: SrcTest) -> bool { + exists|d: TestSim| #[trigger] test_sim_valid(d) && test_sim_lhs(d) == a && test_sim_rhs(d) == b +} + +pub open spec fn similar(r: Regex, s: Regex) -> bool { + exists|d: Sim| #[trigger] sim_valid(d) && sim_lhs(d) == r && sim_rhs(d) == s +} + +pub proof fn lemma_test_sim_valid_children(ds: Seq) + ensures + test_sim_valid(TestSim::And(ds)) == (forall|k: int| 0 <= k < ds.len() ==> test_sim_valid(#[trigger] ds[k])), + test_sim_valid(TestSim::Or(ds)) == (forall|k: int| 0 <= k < ds.len() ==> test_sim_valid(#[trigger] ds[k])), +{ + assert((TestSim::And(ds))->And_0 =~= ds); + assert((TestSim::Or(ds))->Or_0 =~= ds); +} + +pub proof fn lemma_sim_valid_children(ds: Seq) + ensures + sim_valid(Sim::Union(ds)) == (forall|k: int| 0 <= k < ds.len() ==> sim_valid(#[trigger] ds[k])), + sim_valid(Sim::Intersect(ds)) == (forall|k: int| 0 <= k < ds.len() ==> sim_valid(#[trigger] ds[k])), + sim_valid(Sim::Concat(ds)) == (forall|k: int| 0 <= k < ds.len() ==> sim_valid(#[trigger] ds[k])), +{ + assert((Sim::Union(ds))->Union_0 =~= ds); + assert((Sim::Intersect(ds))->Intersect_0 =~= ds); + assert((Sim::Concat(ds))->Concat_0 =~= ds); +} + +pub proof fn lemma_test_similar_preserves(theta: Subst, d: TestSim, e: EventView) + requires test_sim_valid(d), + ensures language::src_test_holds(theta, test_sim_lhs(d), e) == language::src_test_holds(theta, test_sim_rhs(d), e), + decreases d, +{ + reveal_with_fuel(test_sim_valid, 2); + match d { + TestSim::Rule(rule) => lemma_test_rule_sound(theta, rule, e), + TestSim::Refl(_) => {}, + TestSim::Sym(c) => lemma_test_similar_preserves(theta, *c, e), + TestSim::Trans(a, b) => { + lemma_test_similar_preserves(theta, *a, e); + lemma_test_similar_preserves(theta, *b, e); + }, + TestSim::And(ds) => { + lemma_test_sim_valid_children(ds); + let cs = test_sim_lhs(d)->And_0; + let es = test_sim_rhs(d)->And_0; + assert(cs.len() == ds.len() && es.len() == ds.len()); + assert forall|k: int| 0 <= k < ds.len() implies language::src_test_holds(theta, cs[k], e) == language::src_test_holds(theta, es[k], e) by { + assert(test_sim_valid(d)); + lemma_test_similar_preserves(theta, ds[k], e); + } + lemma_test_connectives(theta, cs, e); lemma_test_connectives(theta, es, e); + }, + TestSim::Or(ds) => { + lemma_test_sim_valid_children(ds); + let cs = test_sim_lhs(d)->Or_0; + let es = test_sim_rhs(d)->Or_0; + assert(cs.len() == ds.len() && es.len() == ds.len()); + assert forall|k: int| 0 <= k < ds.len() implies language::src_test_holds(theta, cs[k], e) == language::src_test_holds(theta, es[k], e) by { + assert(test_sim_valid(d)); + lemma_test_similar_preserves(theta, ds[k], e); + } + lemma_test_connectives(theta, cs, e); lemma_test_connectives(theta, es, e); + if language::src_test_holds(theta, SrcTest::Or(cs), e) { + let k = choose|k: int| 0 <= k < cs.len() && language::src_test_holds(theta, cs[k], e); + assert(language::src_test_holds(theta, es[k], e)); + } + if language::src_test_holds(theta, SrcTest::Or(es), e) { + let k = choose|k: int| 0 <= k < es.len() && language::src_test_holds(theta, es[k], e); + assert(language::src_test_holds(theta, cs[k], e)); + } + }, + } +} + +pub proof fn lemma_similar_preserves_lang(theta: Subst, d: Sim, w: Seq) + requires sim_valid(d), + ensures language::numeric_lang(src_sem(theta), sim_lhs(d), w) == language::numeric_lang(src_sem(theta), sim_rhs(d), w), + decreases d, +{ + reveal_with_fuel(sim_valid, 2); + let sem = src_sem(theta); + match d { + Sim::Rule(rule) => lemma_regex_rule_sound(theta, rule, w), + Sim::Refl(_) => {}, + Sim::Sym(c) => lemma_similar_preserves_lang(theta, *c, w), + Sim::Trans(a, b) => { + lemma_similar_preserves_lang(theta, *a, w); + lemma_similar_preserves_lang(theta, *b, w); + }, + Sim::Test(t) => { + if w.len() == 1 { lemma_test_similar_preserves(theta, t, w[0]); } + }, + Sim::Not(c) => lemma_similar_preserves_lang(theta, *c, w), + Sim::Star(c) => { + assert forall|v: Seq| language::numeric_lang(sem, sim_lhs(*c), v) == language::numeric_lang(sem, sim_rhs(*c), v) by { + lemma_similar_preserves_lang(theta, *c, v); + } + if language::numeric_lang(sem, sim_lhs(d), w) { + let parts = choose|parts: Seq>| w == parts.flatten() + && forall|k: int| 0 <= k < parts.len() ==> language::numeric_lang(sem, sim_lhs(*c), parts[k]); + assert forall|k: int| 0 <= k < parts.len() implies language::numeric_lang(sem, sim_rhs(*c), parts[k]) by { } + assert(language::numeric_lang(sem, sim_rhs(d), w)); + } + if language::numeric_lang(sem, sim_rhs(d), w) { + let parts = choose|parts: Seq>| w == parts.flatten() + && forall|k: int| 0 <= k < parts.len() ==> language::numeric_lang(sem, sim_rhs(*c), parts[k]); + assert forall|k: int| 0 <= k < parts.len() implies language::numeric_lang(sem, sim_lhs(*c), parts[k]) by { } + assert(language::numeric_lang(sem, sim_lhs(d), w)); + } + }, + Sim::Union(ds) => { + lemma_sim_valid_children(ds); + let cs = sim_lhs(d)->Union_0; + let es = sim_rhs(d)->Union_0; + assert(cs.len() == ds.len() && es.len() == ds.len()); + assert forall|k: int| 0 <= k < ds.len() implies language::numeric_lang(sem, cs[k], w) == language::numeric_lang(sem, es[k], w) by { + assert(sim_valid(d)); + lemma_similar_preserves_lang(theta, ds[k], w); + } + language::lemma_lang_union(sem, cs, w); language::lemma_lang_union(sem, es, w); + if language::numeric_lang(sem, Regex::Union(cs), w) { + let k = choose|k: int| 0 <= k < cs.len() && language::numeric_lang(sem, cs[k], w); + assert(language::numeric_lang(sem, es[k], w)); + } + if language::numeric_lang(sem, Regex::Union(es), w) { + let k = choose|k: int| 0 <= k < es.len() && language::numeric_lang(sem, es[k], w); + assert(language::numeric_lang(sem, cs[k], w)); + } + }, + Sim::Intersect(ds) => { + lemma_sim_valid_children(ds); + let cs = sim_lhs(d)->Intersect_0; + let es = sim_rhs(d)->Intersect_0; + assert(cs.len() == ds.len() && es.len() == ds.len()); + assert forall|k: int| 0 <= k < ds.len() implies language::numeric_lang(sem, cs[k], w) == language::numeric_lang(sem, es[k], w) by { + assert(sim_valid(d)); + lemma_similar_preserves_lang(theta, ds[k], w); + } + language::lemma_lang_intersect(sem, cs, w); language::lemma_lang_intersect(sem, es, w); + }, + Sim::Concat(ds) => { + lemma_sim_valid_children(ds); + let cs = sim_lhs(d)->Concat_0; + let es = sim_rhs(d)->Concat_0; + assert(cs.len() == ds.len() && es.len() == ds.len()); + assert forall|k: int, v: Seq| 0 <= k < ds.len() implies language::numeric_lang(sem, cs[k], v) == language::numeric_lang(sem, es[k], v) by { + assert(sim_valid(d)); + lemma_similar_preserves_lang(theta, ds[k], v); + } + if language::numeric_lang(sem, Regex::Concat(cs), w) { + let parts = choose|parts: Seq>| parts.len() == cs.len() && w == parts.flatten() + && forall|k: int| 0 <= k < cs.len() ==> language::numeric_lang(sem, cs[k], parts[k]); + assert forall|k: int| 0 <= k < es.len() implies language::numeric_lang(sem, es[k], parts[k]) by { } + assert(language::numeric_lang(sem, Regex::Concat(es), w)); + } + if language::numeric_lang(sem, Regex::Concat(es), w) { + let parts = choose|parts: Seq>| parts.len() == es.len() && w == parts.flatten() + && forall|k: int| 0 <= k < es.len() ==> language::numeric_lang(sem, es[k], parts[k]); + assert forall|k: int| 0 <= k < cs.len() implies language::numeric_lang(sem, cs[k], parts[k]) by { } + assert(language::numeric_lang(sem, Regex::Concat(cs), w)); + } + }, + } +} + +/// Proposition Similarity preserves language (`lem:similarity-language`): similar tails have the +/// same language under every substitution. +pub open spec fn stmt_similarity_preserves_language() -> bool { + forall|r: Regex, s: Regex, theta: Subst, w: Seq| + #![trigger similar(r, s), language::numeric_lang(src_sem(theta), r, w)] + similar(r, s) ==> language::numeric_lang(src_sem(theta), r, w) == language::numeric_lang(src_sem(theta), s, w) +} + +pub proof fn lemma_similarity_preserves_language(r: Regex, s: Regex, theta: Subst, w: Seq) + requires similar(r, s), + ensures language::numeric_lang(src_sem(theta), r, w) == language::numeric_lang(src_sem(theta), s, w), +{ + let d = choose|d: Sim| sim_valid(d) && sim_lhs(d) == r && sim_rhs(d) == s; + lemma_similar_preserves_lang(theta, d, w); +} + +pub proof fn theorem_similarity_preserves_language() + ensures stmt_similarity_preserves_language(), +{ + assert forall|r: Regex, s: Regex, theta: Subst, w: Seq| + #![trigger similar(r, s), language::numeric_lang(src_sem(theta), r, w)] + similar(r, s) implies language::numeric_lang(src_sem(theta), r, w) == language::numeric_lang(src_sem(theta), s, w) by { + lemma_similarity_preserves_language(r, s, theta, w); + } +} + +/// Theorem Matcher correctness (`thm:matcher`), normalization step: similar tails give identical +/// rule decisions under every head. +pub open spec fn stmt_similar_tails_same_decision() -> bool { + forall|head: Head, r: Regex, s: Regex, request: EventView, history: Seq| + #![trigger similar(r, s), language::pair_lang(head, r, request, history)] + similar(r, s) ==> language::pair_lang(head, r, request, history) == language::pair_lang(head, s, request, history) +} + +pub proof fn lemma_similar_tails_same_decision(head: Head, r: Regex, s: Regex, request: EventView, history: Seq) + requires similar(r, s), + ensures language::pair_lang(head, r, request, history) == language::pair_lang(head, s, request, history), +{ + if language::pair_lang(head, r, request, history) { + let theta = choose|theta: Subst| language::head_match(head, request, theta) + && language::numeric_lang(src_sem(theta), r, history); + lemma_similarity_preserves_language(r, s, theta, history); + assert(language::pair_lang(head, s, request, history)); + } + if language::pair_lang(head, s, request, history) { + let theta = choose|theta: Subst| language::head_match(head, request, theta) + && language::numeric_lang(src_sem(theta), s, history); + lemma_similarity_preserves_language(r, s, theta, history); + assert(language::pair_lang(head, r, request, history)); + } +} + +pub proof fn theorem_similar_tails_same_decision() + ensures stmt_similar_tails_same_decision(), +{ + assert forall|head: Head, r: Regex, s: Regex, request: EventView, history: Seq| + #![trigger similar(r, s), language::pair_lang(head, r, request, history)] + similar(r, s) implies language::pair_lang(head, r, request, history) == language::pair_lang(head, s, request, history) by { + lemma_similar_tails_same_decision(head, r, s, request, history); + } +} + +/// Mandatory coordinates make Eq and Neq exact complements. +pub proof fn lemma_eq_or_neq_is_true(theta: Subst, field: Component, term: Term, event: EventView) + ensures language::src_test_holds(theta, + SrcTest::Or(seq![SrcTest::Eq(field, term), SrcTest::Neq(field, term)]), event), +{ + lemma_test_binary(theta, SrcTest::Eq(field, term), SrcTest::Neq(field, term), event); +} + +/// Test polarity complements the same fixed typed primitive. +pub open spec fn test_complement(t: model::Test) -> model::Test + decreases t, +{ + match t { + model::Test::True => model::Test::False, + model::Test::False => model::Test::True, + model::Test::Atom(p, positive) => model::Test::Atom(p, !positive), + model::Test::And(cs) => model::Test::Or(Seq::new(cs.len(), |k: int| if 0 <= k < cs.len() { test_complement(cs[k]) } else { model::Test::True })), + model::Test::Or(cs) => model::Test::And(Seq::new(cs.len(), |k: int| if 0 <= k < cs.len() { test_complement(cs[k]) } else { model::Test::False })), + } +} + +pub proof fn lemma_test_complement_holds(theta: Subst, t: model::Test, e: EventView) + ensures model::test_holds(theta, test_complement(t), e) == !model::test_holds(theta, t, e), + decreases t, +{ + match t { + model::Test::And(cs) => { + let ds = test_complement(t)->Or_0; + assert(ds.len() == cs.len()); + assert((model::Test::And(cs))->And_0 =~= cs); + assert((model::Test::Or(ds))->Or_0 =~= ds); + assert forall|k: int| 0 <= k < cs.len() implies model::test_holds(theta, ds[k], e) == !model::test_holds(theta, cs[k], e) by { + lemma_test_complement_holds(theta, cs[k], e); + } + if !model::test_holds(theta, t, e) { + let k = choose|k: int| 0 <= k < cs.len() && !model::test_holds(theta, cs[k], e); + assert(model::test_holds(theta, ds[k], e)); + } + if model::test_holds(theta, test_complement(t), e) { + let k = choose|k: int| 0 <= k < ds.len() && model::test_holds(theta, ds[k], e); + assert(!model::test_holds(theta, cs[k], e)); + } + }, + model::Test::Or(cs) => { + let ds = test_complement(t)->And_0; + assert(ds.len() == cs.len()); + assert((model::Test::Or(cs))->Or_0 =~= cs); + assert((model::Test::And(ds))->And_0 =~= ds); + assert forall|k: int| 0 <= k < cs.len() implies model::test_holds(theta, ds[k], e) == !model::test_holds(theta, cs[k], e) by { + lemma_test_complement_holds(theta, cs[k], e); + } + }, + _ => {}, + } +} + +pub proof fn lemma_test_complement_involutive(t: model::Test) + ensures test_complement(test_complement(t)) == t, + decreases t, +{ + reveal_with_fuel(test_complement, 2); + match t { + model::Test::And(cs) => { + assert forall|k: int| 0 <= k < cs.len() implies test_complement(test_complement(cs[k])) == cs[k] by { + lemma_test_complement_involutive(cs[k]); + } + assert(test_complement(test_complement(t))->And_0 =~= cs); + }, + model::Test::Or(cs) => { + assert forall|k: int| 0 <= k < cs.len() implies test_complement(test_complement(cs[k])) == cs[k] by { + lemma_test_complement_involutive(cs[k]); + } + assert(test_complement(test_complement(t))->Or_0 =~= cs); + }, + _ => {}, + } +} + +/// Extend the pinned graph; graph replacement requires a fresh root association. +#[verifier::spinoff_prover] +pub proof fn lemma_batch_extends_pinned_prefix( + before: model::Graph, after: model::Graph, theta: Subst, + root: nat, start: nat, out: nat, history: Seq, consumed: nat, end: nat, +) + requires + model::graph_wf(before), model::graph_wf(after), model::graph_extends(before, after), + root < before.regexes.len(), start < before.regexes.len(), out < after.regexes.len(), + consumed <= end <= history.len(), + forall|word: Seq| model::regex_lang(before, theta, start, word) + == model::regex_lang(before, theta, root, history.take(consumed as int) + word), + forall|word: Seq| model::regex_lang(after, theta, out, word) + == model::regex_lang(after, theta, start, + history.subrange(consumed as int, end as int) + word), + ensures + forall|word: Seq| model::regex_lang(after, theta, out, word) + == model::regex_lang(before, theta, root, history.take(end as int) + word), + language::nullable(model::lift_regex(after, out)) + == model::regex_lang(before, theta, root, history.take(end as int)), +{ + hide(language::numeric_lang); + hide(model::lift_regex); + hide(model::test_holds); + hide(model::regex_lang); + hide(language::nullable); + // Only the table facts: `unique_nodes` adds a quadratic `no_duplicates` matching loop. + assert(model::tables_wf(before)) by { model::lemma_graph_wf_elim(before); } + model::lemma_lift_regex_stable(before, after, start); + assert forall|word: Seq| model::regex_lang(after, theta, start, word) + == model::regex_lang(before, theta, start, word) by { + reveal(model::regex_lang); + } + assert(history.take(consumed as int) + history.subrange(consumed as int, end as int) + =~= history.take(end as int)); + assert forall|word: Seq| model::regex_lang(after, theta, out, word) + == model::regex_lang(before, theta, root, history.take(end as int) + word) by { + let suffix = history.subrange(consumed as int, end as int) + word; + assert(model::regex_lang(after, theta, out, word) + == model::regex_lang(after, theta, start, suffix)); + assert(model::regex_lang(after, theta, start, suffix) + == model::regex_lang(before, theta, start, suffix)); + assert(model::regex_lang(before, theta, start, suffix) + == model::regex_lang(before, theta, root, history.take(consumed as int) + suffix)); + assert(history.take(consumed as int) + suffix =~= history.take(end as int) + word); + } + assert(model::regex_lang(after, theta, out, Seq::::empty()) + == model::regex_lang(before, theta, root, + history.take(end as int) + Seq::::empty())); + language::lemma_nullable_iff_nil(model::gsem(theta), model::lift_regex(after, out)); + assert(model::regex_lang(after, theta, out, Seq::::empty()) + == language::numeric_lang(model::gsem(theta), model::lift_regex(after, out), Seq::::empty())) by { + reveal(model::regex_lang); + } + assert(history.take(end as int) + Seq::::empty() =~= history.take(end as int)); +} + +} diff --git a/src/history-semantics/src/verify/history_examples.rs b/src/history-semantics/src/verify/history_examples.rs new file mode 100644 index 000000000..17aa7c09e --- /dev/null +++ b/src/history-semantics/src/verify/history_examples.rs @@ -0,0 +1,407 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Typed policy examples connected to the production fold, answer, and cache transaction bodies. + +use super::history_algebra::{self as algebra, src_sem}; +use crate::compile::verify as source; +use crate::progress::{CompiledPair, verify as progress}; +use crate::runtime::RuleRuntime; +use crate::runtime::verify::{self as cache, HistorySnapshots}; +use alloc::boxed::Box; +use alloc::sync::Arc; +use alloc::vec::Vec; +use history_store::cache::HistoryCursor; +use history_store::history::StoredHistory; +use history_store::store::{Event, HistoryStore}; +use history_syntax::syntax::Component; +use junco_core::flat::FlatPair; +use junco_core::kernel::verify as model; +use junco_core::kernel::{Bindings, KernelResult, RegexId}; +use junco_core::limits::Limits; +use junco_core::observation::ObservationWorld; +use junco_core::verify::history_specs::{ + self as language, EventView, Head, HeadField, Regex, SrcTest, Subst, Term, +}; +use vstd::prelude::*; + +verus! { +broadcast use junco_core::kernel::verify::group_kernel_views; + +pub open spec fn event(principal: nat, action: nat, resource: nat) -> EventView { + seq![principal, action, resource] +} + +pub open spec fn any_head() -> Head { + seq![HeadField::Any, HeadField::Any, HeadField::Any] +} + +pub open spec fn release_head() -> Head { + seq![HeadField::Bind, HeadField::Constant(3), HeadField::Bind] +} + +pub open spec fn prior_edit_test() -> SrcTest { + SrcTest::And(seq![ + SrcTest::Eq(Component(0), Term::Variable(Component(0))), + SrcTest::Eq(Component(1), Term::Constant(2)), + SrcTest::Eq(Component(2), Term::Variable(Component(2))), + ]) +} + +pub open spec fn prior_edit_tail() -> Regex { + Regex::Concat(seq![Regex::All, Regex::Test(prior_edit_test()), Regex::All]) +} + +pub proof fn epsilon_versus_test_true_on_empty_history(request: EventView) + requires request.len() == 3, + ensures language::pair_lang(any_head(), Regex::Epsilon, request, Seq::empty()), + !language::pair_lang(any_head(), Regex::Test(SrcTest::Bool(true)), request, Seq::empty()), +{ + let theta = event(0, 0, 0); + language::lemma_pair_lang_substitutions(any_head(), Regex::Epsilon, request, Seq::empty(), theta); + language::lemma_pair_lang_substitutions(any_head(), Regex::Test(SrcTest::Bool(true)), request, Seq::empty(), theta); +} + +pub proof fn candidate_bindings_are_fixed_and_domain_scoped(principal: nat, resource: nat) + ensures language::head_match(release_head(), event(principal, 3, resource), event(principal, 0, resource)), + language::src_test_holds(event(principal, 0, resource), prior_edit_test(), event(principal, 2, resource)), + forall|other: nat| other != principal ==> !language::src_test_holds( + event(principal, 0, resource), prior_edit_test(), event(other, 2, resource)), + forall|other: nat| other != resource ==> !language::src_test_holds( + event(principal, 0, resource), prior_edit_test(), event(principal, 2, other)), +{ + reveal_with_fuel(language::src_test_holds, 3); + let children = prior_edit_test()->And_0; + assert forall|i: int| 0 <= i < children.len() implies language::src_test_holds( + event(principal, 0, resource), children[i], event(principal, 2, resource)) by { + assert(i == 0 || i == 1 || i == 2); + } +} + +pub proof fn prior_edit_grants_matching_release(principal: nat, resource: nat) + ensures language::pair_lang(release_head(), prior_edit_tail(), + event(principal, 3, resource), seq![event(principal, 2, resource)]), +{ + candidate_bindings_are_fixed_and_domain_scoped(principal, resource); + let theta = event(principal, 0, resource); + let history = seq![event(principal, 2, resource)]; + let empty = Seq::::empty(); + let singleton = seq![empty]; + singleton.lemma_flatten_one_element(); + singleton.lemma_flatten_push(history); + singleton.push(history).lemma_flatten_push(empty); + let parts = singleton.push(history).push(empty); + assert(parts.flatten() =~= history); + let children = prior_edit_tail()->Concat_0; + assert forall|i: int| 0 <= i < children.len() + implies language::numeric_lang(src_sem(theta), children[i], parts[i]) by { + assert(i == 0 || i == 1 || i == 2); + } + assert(language::numeric_lang(src_sem(theta), prior_edit_tail(), history)); + language::lemma_pair_lang_substitutions(release_head(), prior_edit_tail(), + event(principal, 3, resource), history, theta); +} + +pub proof fn same_event_differs_under_candidate_bindings(principal: nat, other: nat, resource: nat) + requires principal != other, + ensures language::src_test_holds(event(principal, 0, resource), prior_edit_test(), event(principal, 2, resource)), + !language::src_test_holds(event(other, 0, resource), prior_edit_test(), event(principal, 2, resource)), +{ + candidate_bindings_are_fixed_and_domain_scoped(principal, resource); + candidate_bindings_are_fixed_and_domain_scoped(other, resource); +} + +pub proof fn mandatory_field_neq_is_eq_complement(theta: Subst, field: Component, value: nat, request: EventView) + ensures language::src_test_holds(theta, SrcTest::Neq(field, Term::Constant(value)), request) + == !language::src_test_holds(theta, SrcTest::Eq(field, Term::Constant(value)), request), +{ } + +pub proof fn empty_regex_lists_keep_their_identities(theta: Subst, history: Seq) + ensures language::numeric_lang(src_sem(theta), Regex::Concat(Seq::empty()), history) == (history.len() == 0), + !language::numeric_lang(src_sem(theta), Regex::Union(Seq::empty()), history), + language::numeric_lang(src_sem(theta), Regex::Intersect(Seq::empty()), history), +{ + algebra::lemma_parts_concat_nil(src_sem(theta), history); +} + +pub proof fn regex_not_is_not_one_event_neq(theta: Subst, first: EventView, second: EventView) + ensures language::numeric_lang(src_sem(theta), Regex::Not(Box::new(Regex::Test(SrcTest::Bool(true)))), seq![first, second]), + !language::numeric_lang(src_sem(theta), Regex::Test(SrcTest::Bool(false)), seq![first, second]), +{ + reveal_with_fuel(language::numeric_lang, 2); + assert(seq![first, second].len() == 2); +} + +pub proof fn star_accepts_two_typed_events(theta: Subst, first: EventView, second: EventView) + ensures language::numeric_lang(src_sem(theta), Regex::Star(Box::new(Regex::Test(SrcTest::Bool(true)))), seq![first, second]), +{ + let item = Regex::Test(SrcTest::Bool(true)); + algebra::lemma_parts_star_single(src_sem(theta), item, seq![first]); + algebra::lemma_parts_star_single(src_sem(theta), item, seq![second]); + algebra::lemma_parts_star_join(src_sem(theta), item, seq![first], seq![second]); + assert(seq![first] + seq![second] =~= seq![first, second]); +} + +/// The same production bodies used by HISTORY_STEP implement the typed decision. +pub(crate) fn fold_decision( + pair: &mut CompiledPair, residual: RegexId, events: &[Event], bindings: &Bindings, + limits: &mut L, world: &mut ObservationWorld, +) -> (result: KernelResult) + requires progress::pair_wf(*old(pair)), + residual@ < (*old(pair)).store.graph().regexes.len(), + ensures progress::pair_wf(*final(pair)), + progress::pair_frame(*old(pair), *final(pair)), + result matches Ok(answer) ==> answer == model::regex_lang( + (*old(pair)).store.graph(), bindings@, residual@, history_store::store::verify::events_view(events@)), +{ + hide(language::numeric_lang); + hide(model::lift_regex); + hide(model::test_holds); + proof { + assert(model::graph_wf((*pair).store.graph())); + } + let ghost entry = *pair; + let out = pair.fold(residual, events, bindings, limits, world)?; + proof { + let graph = (*pair).store.graph(); + let word = history_store::store::verify::events_view(events@); + assert(progress::residual_folds(*pair, bindings@, residual, word, out)); + assert(model::regex_lang(graph, bindings@, out@, Seq::::empty()) + == model::regex_lang(graph, bindings@, residual@, word + Seq::::empty())); + assert(word + Seq::::empty() =~= word); + language::lemma_nullable_iff_nil(model::gsem(bindings@), model::lift_regex(graph, out@)); + model::lemma_graph_wf_elim(entry.store.graph()); + model::lemma_lift_regex_stable(entry.store.graph(), graph, residual@); + assert(language::nullable(model::lift_regex(graph, out@)) + == model::regex_lang(entry.store.graph(), bindings@, residual@, word)); + } + let ghost folded = *pair; + let answer = pair.answer(out, limits, world)?; + proof { + assert((*pair).store.graph() == folded.store.graph()); + assert(progress::pair_frame(entry, *pair)); + } + Ok(answer) +} + +pub(crate) proof fn cache_rejects_wrong_residual( + pair: CompiledPair, cursor: HistoryCursor, snapshots: HistorySnapshots, +) + requires progress::pair_wf(pair), + pair.root@ == pair.store.graph().constants.empty, + cursor.residual@ == pair.store.graph().constants.all, + snapshots.contains_key((cursor.history, cursor.revision)), + cursor.consumed <= snapshots[(cursor.history, cursor.revision)].len(), + language::event_wf(cursor.bindings@, cursor.bindings@.len()), + ensures !cache::cursor_matches_snapshot(pair, cursor, snapshots), + !cache::cursor_cache_wf(pair, seq![cursor], snapshots), +{ + let graph = pair.store.graph(); + let empty = Seq::::empty(); + let prefix = snapshots[(cursor.history, cursor.revision)].take(cursor.consumed as int); + model::lemma_graph_wf_elim(graph); + assert(model::lift_regex(graph, pair.root@) == Regex::Empty); + assert(model::lift_regex(graph, cursor.residual@) == Regex::All); + assert(model::regex_lang(graph, cursor.bindings@, cursor.residual@, empty)); + assert(!model::regex_lang(graph, cursor.bindings@, pair.root@, prefix + empty)); + if cache::cursor_matches_snapshot(pair, cursor, snapshots) { + assert(model::regex_lang(graph, cursor.bindings@, cursor.residual@, empty) + == model::regex_lang(graph, cursor.bindings@, pair.root@, prefix + empty)); + } + if cache::cursor_cache_wf(pair, seq![cursor], snapshots) { + assert(seq![cursor][0] == cursor); + assert(cache::cursor_matches_snapshot(pair, seq![cursor][0], snapshots)); + } +} + +/// Cache selection and every batch use the production transaction bodies. +pub(crate) fn cached_decision( + runtime: &mut RuleRuntime, bindings: &Bindings, stored: &StoredHistory, + target_len: usize, batch_size: usize, limits: &mut L, world: &mut ObservationWorld, +) -> (result: KernelResult) + requires cache::cursor_cache_wf(old(runtime).pair, old(runtime).cursors@, old(runtime).snapshots@), + cache::snapshot_compatible(old(runtime).snapshots@, stored.id(), stored.revision(), + stored@.events), + language::event_wf(bindings@, bindings@.len()), batch_size > 0, target_len <= stored@.events.len(), + ensures cache::cursor_cache_wf(final(runtime).pair, final(runtime).cursors@, final(runtime).snapshots@), + progress::pair_frame(old(runtime).pair, final(runtime).pair), + final(runtime).spec_store() == old(runtime).spec_store(), + result matches Ok(answer) ==> answer == model::regex_lang( + old(runtime).pair.store.graph(), bindings@, old(runtime).pair.root@, + stored@.events.take(target_len as int)), +{ + hide(language::numeric_lang); + hide(model::lift_regex); + hide(model::test_holds); + reveal(cache::runtime_wf); + reveal(cache::resume_requires); + reveal(cache::resume_ensures); + reveal(cache::advance_requires); + reveal(cache::advance_ensures); + proof { history_store::history::lemma_stored_history_view(*stored); } + let ghost entry = runtime.pair; + let mut cursor = runtime.resume_cursor(bindings, stored, target_len); + loop + invariant entry == old(runtime).pair, + runtime.store == old(runtime).store, + progress::pair_wf(entry), + cache::cursor_cache_wf(runtime.pair, runtime.cursors@, runtime.snapshots@), + progress::pair_frame(entry, runtime.pair), + runtime.snapshots@.contains_key((stored.id(), stored.revision())), + runtime.snapshots@[(stored.id(), stored.revision())] == stored@.events, + cache::batch_matches_snapshot(runtime.pair, cursor, stored.id(), stored.revision(), + *bindings, runtime.snapshots@), + cursor.consumed <= target_len, target_len <= stored@.events.len(), + language::event_wf(bindings@, bindings@.len()), batch_size > 0, + decreases target_len - cursor.consumed, + { + proof { + history_store::history::lemma_stored_history_view(*stored); + cache::lemma_snapshot_compatible_intro(runtime.snapshots@, stored.id(), stored.revision(), stored@.events); + } + let ghost batch_entry = runtime.pair; + let ghost consumed = cursor.consumed; + let result = runtime.advance_cursor(&mut cursor, bindings, stored, + target_len, batch_size, limits, world); + proof { + let first = entry.store.graph(); + let last = runtime.pair.store.graph(); + assert(first.tests.is_prefix_of(last.tests)); + assert(first.regexes.is_prefix_of(last.regexes)); + assert(first.transitions.is_prefix_of(last.transitions)); + assert(progress::pair_frame(entry, runtime.pair)); + // Only the table facts: `unique_nodes` adds a quadratic `no_duplicates` matching loop. + assert(model::tables_wf(first)) by { model::lemma_graph_wf_elim(first); } + model::lemma_lift_regex_stable(first, batch_entry.store.graph(), entry.root@); + } + match result { + Err(error) => return Err(error), + Ok(Some(answer)) => return Ok(answer), + Ok(None) => { + proof { + language::lemma_selected_end(consumed as nat, target_len as nat, batch_size as nat); + assert(consumed < target_len); + assert(consumed < cursor.consumed); + } + }, + } + } +} + +/// Construction and cache-backed decisions preserve the supplied numeric template's language. +pub(crate) fn template_cached_decision( + store: &Arc, template: &FlatPair, precompile: bool, bindings: &Bindings, + stored: &StoredHistory, target_len: usize, batch_size: usize, + limits: &mut L, world: &mut ObservationWorld, +) -> (result: KernelResult) + requires language::event_wf(bindings@, bindings@.len()), batch_size > 0, target_len <= stored@.events.len(), + ensures result matches Ok(answer) ==> answer == source::source_regex( + *template, template.root as nat, bindings@, + stored@.events.take(target_len as int)), +{ + hide(language::numeric_lang); + hide(model::lift_regex); + hide(model::test_holds); + reveal(cache::constructor_result); + reveal(cache::runtime_wf); + let mut runtime = RuleRuntime::new(store, template, precompile, limits, world)?; + proof { + history_store::history::lemma_stored_history_view(*stored); + cache::lemma_constructor_snapshot_compatible(runtime, *store, *template, *stored); + } + cached_decision(&mut runtime, bindings, stored, target_len, batch_size, limits, world) +} + +/// The portable encoding endpoint reaches the same construction and cache transaction bodies. +pub(crate) fn flat_template_cached_decision( + store: &Arc, template: &FlatPair, precompile: bool, request: &Event, + stored: &StoredHistory, target_len: usize, batch_size: usize, + Ghost(candidate): Ghost>, Ghost(word): Ghost>>, + limits: &mut L, world: &mut ObservationWorld, +) -> (result: KernelResult>) + requires junco_core::flat::verify::structural_wf(*template), batch_size > 0, + target_len <= stored@.events.len(), junco_core::verify::encoding::event_representation(candidate, request@), + junco_core::verify::encoding::word_representation(word, stored@.events.take(target_len as int)), + forall|i: int| 0 <= i < word.len() ==> #[trigger] word[i].len() == candidate.len(), + ensures result matches Ok(answer) ==> match answer { + None => !junco_core::flat::verify::head_matches(template.head@, candidate, + junco_core::verify::encoding::numeric_equality()), + Some(accepted) => junco_core::flat::verify::head_matches(template.head@, candidate, + junco_core::verify::encoding::numeric_equality()) + && accepted == junco_core::flat::verify::flat_lang(template.tests@, template.regexes@, + template.root as nat, candidate, word, junco_core::verify::encoding::numeric_equality()), + }, +{ + proof { source::lemma_flat_head(*template, candidate, request@); } + let bindings = match crate::runtime::RuleRuntime::bindings(template, request) { + Some(bindings) => { + proof { source::lemma_bindings_match(*template, *request, bindings); } + bindings + }, + None => { + proof { source::lemma_head_rejects(*template, *request); } + return Ok(None); + }, + }; + proof { assert(language::event_wf(bindings@, bindings@.len())); } + let accepted = template_cached_decision(store, template, precompile, &bindings, + stored, target_len, batch_size, limits, world)?; + proof { + source::lemma_flat_regex(*template, template.root as nat, candidate, request@, + word, stored@.events.take(target_len as int), bindings@); + } + Ok(Some(accepted)) +} + +/// The crate-internal cursor API, driven once from a fresh store: resume, advance to the stored +/// length, and read the answer against `runtime_accepts`. +fn numeric_runtime_readiness(bindings: &Bindings, + limits: &mut L, world: &mut ObservationWorld) -> Result<(), junco_core::HistoryError> + requires language::event_wf(bindings@, bindings@.len()), + 1 <= bindings@.len() <= history_syntax::MAX_ARITY, +{ + let arity = bindings.arity(); + let owner = HistoryStore::new(arity); + let store = history_store::store::borrow_numeric_owner(&owner); + let handle = owner.new_history(limits, world)?; + let record = store.history_record(&handle)?; + let guard = record.read(); + let stored: &StoredHistory = &guard; + let target = stored.len(); + let mut regexes = Vec::new(); + regexes.push(junco_core::flat::FlatRegex::All); + let mut head = Vec::new(); + while head.len() < arity + invariant head@.len() <= arity, + forall|i: int| 0 <= i < head@.len() ==> head@[i] == junco_core::flat::FlatHead::::Bind, + decreases arity - head@.len(), + { + head.push(junco_core::flat::FlatHead::::Bind); + } + let template = FlatPair { + head, + tests: Vec::new(), regexes, root: 0, + }; + let mut state = RuleRuntime::new(&owner, &template, false, limits, world)?; + let ghost constructed = state; + proof { + cache::lemma_constructor_runtime_wf(state, owner, template); + cache::lemma_constructor_snapshot_compatible(state, owner, template, *stored); + cache::lemma_resume_requires(state, *bindings, *stored, target); + } + let mut cursor = state.resume_cursor(bindings, stored, target); + proof { cache::lemma_resume_can_advance(constructed, state, cursor, *bindings, *stored, target); } + let ghost before = state; + let ghost start = cursor; + let answer = state.advance_cursor(&mut cursor, bindings, stored, target, target, limits, world); + proof { + cache::lemma_advance_result_facts(before, state, start, cursor, *bindings, *stored, target, target, answer); + cache::lemma_runtime_frame_accepts(constructed, before, bindings@, stored@.events.take(target as int)); + assert(answer matches Ok(Some(accepted)) ==> + accepted == cache::runtime_accepts(constructed, bindings@, stored@.events.take(target as int))); + assert(answer != Err(junco_core::HistoryError::WrongHistoryOwner)); + } + Ok(()) +} + +} diff --git a/src/history-semantics/src/verify/mod.rs b/src/history-semantics/src/verify/mod.rs new file mode 100644 index 000000000..f1e065741 --- /dev/null +++ b/src/history-semantics/src/verify/mod.rs @@ -0,0 +1,17 @@ +//! Checked semantic and typed-history proof clients. +pub mod finite_branch; +pub mod finite_collect; +pub mod finite_compile; +pub mod finite_deriv; +pub mod finite_impl; +pub mod finite_interp; +pub mod finite_link; +pub mod finite_machine; +pub mod finite_states; +pub mod finite_steps; +pub mod finite_trans; +pub mod history_algebra; +pub mod history_examples; +pub mod paper; +pub mod refinement; +pub mod typed_decision; diff --git a/src/history-semantics/src/verify/paper.rs b/src/history-semantics/src/verify/paper.rs new file mode 100644 index 000000000..b5f6ad03e --- /dev/null +++ b/src/history-semantics/src/verify/paper.rs @@ -0,0 +1,350 @@ +//! Paper index: one `stmt_(f: spec_fn(A) -> bool, bound: ISet) + requires + bound.finite(), + forall|a: A| f(a) ==> bound.contains(a), + ensures + Set::new(f) is Some, + forall|a: A| #[trigger] Set::new(f).unwrap().contains(a) == f(a), +{ + assert(ISet::new(f).subset_of(bound)); + lemma_iset_subset_finite(bound, ISet::new(f)); + assert(Set::new(f) is Some); +} + +pub open spec fn head_value(h: NHead, c: Component) -> nat { + match n_head_field(h, c) { Some(v) => v, None => 0 } +} + +/// A finite coordinate-indexed bound on a head's constant pairs. +pub open spec fn head_coordinate_pairs(h: NHead) -> Set<(Component, nat)> { + Seq::new(h.len(), |i: int| { + let c = Component(i as u8); + (c, head_value(h, c)) + }).to_set() +} + +pub proof fn lemma_head_coordinate_pairs(h: NHead, c: Component, v: nat) + requires n_head_field(h, c) == Some(v), + ensures head_coordinate_pairs(h).contains((c, v)), +{ + let pairs = Seq::new(h.len(), |i: int| { + let field = Component(i as u8); + (field, head_value(h, field)) + }); + assert(c.0 < h.len()); + assert(pairs[c.0 as int] == (c, v)); + assert(pairs.contains((c, v))); +} + +/// `Γ_R` has exactly the equalities of the head's constant coordinates. +pub proof fn lemma_head_constraint(h: NHead) + ensures + forall|l: Literal| #[trigger] head_constraint(h).contains(l) + <==> (l.equal && n_head_field(h, l.component) == Some(l.value)), +{ + let make = |p: (Component, nat)| eq_literal(p.0, p.1); + let bound = head_coordinate_pairs(h).to_iset().map(make); + head_coordinate_pairs(h).to_iset().lemma_map_finite(make); + let f = |l: Literal| l.equal && n_head_field(h, l.component) == Some(l.value); + assert forall|l: Literal| f(l) implies bound.contains(l) by { + lemma_head_coordinate_pairs(h, l.component, l.value); + assert(l == make((l.component, l.value))); + } + lemma_set_new_bounded(f, bound); + assert(head_constraint(h) == Set::new(f).unwrap()); +} + +/// A finite superset of `head_pairs(p)`. +pub open spec fn head_pairs_bound(p: Seq) -> ISet<(Component, nat)> + decreases p.len(), +{ + if p.len() == 0 { + ISet::empty() + } else { + let h = p.last().head; + head_pairs_bound(p.drop_last()).union(head_coordinate_pairs(h).to_iset()) + } +} + +pub proof fn lemma_head_pairs_bound(p: Seq) + ensures + head_pairs_bound(p).finite(), + forall|pair: (Component, nat)| (exists|i: int| 0 <= i < p.len() && #[trigger] n_head_field(p[i].head, pair.0) == Some(pair.1)) + ==> #[trigger] head_pairs_bound(p).contains(pair), + decreases p.len(), +{ + broadcast use vstd::iset::lemma_iset_union_finite, vstd::set::lemma_to_iset_finite; + if p.len() > 0 { + let q = p.drop_last(); + lemma_head_pairs_bound(q); + let h = p.last().head; + assert forall|pair: (Component, nat)| (exists|i: int| 0 <= i < p.len() && #[trigger] n_head_field(p[i].head, pair.0) == Some(pair.1)) + implies #[trigger] head_pairs_bound(p).contains(pair) by { + let i = choose|i: int| 0 <= i < p.len() && #[trigger] n_head_field(p[i].head, pair.0) == Some(pair.1); + if i < p.len() - 1 { + assert(q[i] == p[i]); + assert(n_head_field(q[i].head, pair.0) == Some(pair.1)); + assert(head_pairs_bound(q).contains(pair)); + } else { + assert(n_head_field(h, pair.0) == Some(pair.1)); + lemma_head_coordinate_pairs(h, pair.0, pair.1); + } + } + } +} + +/// `Π` has exactly the head constants of `P` (finitely many). +pub proof fn lemma_head_pairs(p: Seq) + ensures + forall|pair: (Component, nat)| #[trigger] head_pairs(p).contains(pair) + <==> exists|i: int| 0 <= i < p.len() && #[trigger] n_head_field(p[i].head, pair.0) == Some(pair.1), +{ + lemma_head_pairs_bound(p); + let f = |pair: (Component, nat)| exists|i: int| 0 <= i < p.len() && #[trigger] n_head_field(p[i].head, pair.0) == Some(pair.1); + lemma_set_new_bounded(f, head_pairs_bound(p)); + assert(head_pairs(p) == Set::new(f).unwrap()); +} + +/// Both literals of every pair of `Π`. +pub open spec fn pair_literals(pi: Pairs) -> Set { + pi.map(|p: (Component, nat)| eq_literal(p.0, p.1)).union(pi.map(|p: (Component, nat)| ne_literal(p.0, p.1))) +} + +/// Membership in the paper's `Split` (the defining set is finite). +pub proof fn lemma_paper_split_members(d: NDomains, g: Constraint, pi: Pairs) + ensures + forall|g1: Constraint| #[trigger] paper_split(d, g, pi).contains(g1) + <==> exists|delta: Constraint| #[trigger] split_delta(d, g, pi, delta) && g1 == g.union(delta) + && satisfiable(d, g1), +{ + let lits = pair_literals(pi); + lemma_powerset_finite(lits); + let pw = ISet::new(|s: Set| s.subset_of(lits)); + let un = |delta: Set| g.union(delta); + pw.lemma_map_finite(un); + let f = |g1: Constraint| exists|delta: Constraint| #[trigger] split_delta(d, g, pi, delta) && g1 == g.union(delta) + && satisfiable(d, g1); + assert forall|g1: Constraint| f(g1) implies pw.map(un).contains(g1) by { + let delta = choose|delta: Constraint| #[trigger] split_delta(d, g, pi, delta) && g1 == g.union(delta) + && satisfiable(d, g1); + assert forall|l: Literal| delta.contains(l) implies lits.contains(l) by { + let pr = (l.component, l.value); + assert(pi.contains(pr)); + if l.equal { + assert(l == eq_literal(pr.0, pr.1)); + assert(pi.map(|p: (Component, nat)| eq_literal(p.0, p.1)).contains(l)); + } else { + assert(l == ne_literal(pr.0, pr.1)); + assert(pi.map(|p: (Component, nat)| ne_literal(p.0, p.1)).contains(l)); + } + } + assert(pw.contains(delta)); + assert(un(delta) == g1); + } + lemma_set_new_bounded(f, pw.map(un)); + assert(paper_split(d, g, pi) == Set::new(f).unwrap()); +} + +// ----- proofs: constraints ----- + +pub proof fn lemma_entails_subset(d: NDomains, g1: Constraint, g2: Constraint) + requires g2.subset_of(g1), + ensures entails(d, g1, g2), +{ + assert forall|theta: Subst| n_theta_ok(d, theta) && #[trigger] sat_by(theta, g1) implies sat_by(theta, g2) by { + assert forall|l: Literal| #[trigger] g2.contains(l) implies literal_holds(theta, l) by { + assert(g1.contains(l)); + } + } +} + +pub proof fn lemma_entails_trans(d: NDomains, a: Constraint, b: Constraint, c: Constraint) + requires entails(d, a, b), entails(d, b, c), + ensures entails(d, a, c), +{ + assert forall|theta: Subst| n_theta_ok(d, theta) && #[trigger] sat_by(theta, a) implies sat_by(theta, c) by { + assert(sat_by(theta, b)); + } +} + +/// A constraint satisfied by `θ0` that decides every literal of `gh` (all equalities, also +/// satisfied by `θ0`) entails `gh`. +pub proof fn lemma_decided_entails(d: NDomains, g1: Constraint, gh: Constraint, theta0: Subst) + requires + n_theta_ok(d, theta0), + sat_by(theta0, g1), + sat_by(theta0, gh), + forall|l: Literal| #[trigger] gh.contains(l) ==> l.equal && decides(d, g1, l.component, l.value), + ensures entails(d, g1, gh), +{ + assert forall|theta: Subst| n_theta_ok(d, theta) && #[trigger] sat_by(theta, g1) implies sat_by(theta, gh) by { + assert forall|l: Literal| #[trigger] gh.contains(l) implies literal_holds(theta, l) by { + let eq = eq_literal(l.component, l.value); + let ne = ne_literal(l.component, l.value); + assert(literal_holds(theta0, l)); + if entails(d, g1, set![ne]) { + assert(sat_by(theta0, set![ne])); + assert(set![ne].contains(ne)); + assert(false); + } + assert(entails(d, g1, set![eq])); + assert(sat_by(theta, set![eq])); + assert(set![eq].contains(eq)); + assert(l == eq); + } + } +} + +/// Under a valuation, `Δ` is determined by `Π` and the undecided pairs. +pub proof fn lemma_delta_unique(d: NDomains, g: Constraint, pi: Pairs, d1: Constraint, d2: Constraint, theta: Subst) + requires + split_delta(d, g, pi, d1), + split_delta(d, g, pi, d2), + sat_by(theta, d1), + sat_by(theta, d2), + ensures d1 == d2, +{ + assert forall|l: Literal| d1.contains(l) implies d2.contains(l) by { + lemma_delta_unique_one(d, g, pi, d1, d2, theta, l); + } + assert forall|l: Literal| d2.contains(l) implies d1.contains(l) by { + lemma_delta_unique_one(d, g, pi, d2, d1, theta, l); + } + assert(d1 =~= d2); +} + +proof fn lemma_delta_unique_one(d: NDomains, g: Constraint, pi: Pairs, d1: Constraint, d2: Constraint, theta: Subst, l: Literal) + requires + split_delta(d, g, pi, d1), + split_delta(d, g, pi, d2), + sat_by(theta, d1), + sat_by(theta, d2), + d1.contains(l), + ensures d2.contains(l), +{ + let pr = (l.component, l.value); + assert(pi.contains(pr) && !decides(d, g, pr.0, pr.1)); + let eq = eq_literal(pr.0, pr.1); + let ne = ne_literal(pr.0, pr.1); + assert(d2.contains(eq) != d2.contains(ne)); + assert(literal_holds(theta, l)); + if d2.contains(eq) { + assert(literal_holds(theta, eq)); + assert(l == eq); + } else { + assert(literal_holds(theta, ne)); + assert(l == ne); + } +} + +pub proof fn lemma_paper_split_ok(d: NDomains, g: Constraint, pi: Pairs) + ensures split_ok(d, g, pi, paper_split(d, g, pi)), +{ + let cases = paper_split(d, g, pi); + lemma_paper_split_members(d, g, pi); + assert forall|g1: Constraint| #[trigger] cases.contains(g1) implies satisfiable(d, g1) && entails(d, g1, g) + && forall|p: (Component, nat)| pi.contains(p) ==> #[trigger] decides(d, g1, p.0, p.1) by { + let delta = choose|delta: Constraint| #[trigger] split_delta(d, g, pi, delta) && g1 == g.union(delta) + && satisfiable(d, g1); + lemma_entails_subset(d, g1, g); + assert forall|p: (Component, nat)| pi.contains(p) implies #[trigger] decides(d, g1, p.0, p.1) by { + let eq = eq_literal(p.0, p.1); + let ne = ne_literal(p.0, p.1); + if decides(d, g, p.0, p.1) { + if entails(d, g, set![eq]) { + lemma_entails_trans(d, g1, g, set![eq]); + } else { + lemma_entails_trans(d, g1, g, set![ne]); + } + } else if delta.contains(eq) { + lemma_entails_subset(d, g1, set![eq]); + } else { + assert(delta.contains(ne)); + lemma_entails_subset(d, g1, set![ne]); + } + } + } + assert forall|theta: Subst| n_theta_ok(d, theta) && #[trigger] sat_by(theta, g) + implies exists|g1: Constraint| #[trigger] cases.contains(g1) && sat_by(theta, g1) by { + let undecided = pi.filter(|p: (Component, nat)| !decides(d, g, p.0, p.1)); + let mk = |p: (Component, nat)| Literal { component: p.0, value: p.1, equal: language::field_value(theta, p.0) == p.1 }; + let delta = undecided.map(mk); + assert forall|l: Literal| #[trigger] delta.contains(l) implies pi.contains((l.component, l.value)) + && !decides(d, g, l.component, l.value) && literal_holds(theta, l) by { + let p = choose|p: (Component, nat)| undecided.contains(p) && l == mk(p); + assert((l.component, l.value) == p); + } + assert forall|p: (Component, nat)| #[trigger] pi.contains(p) && !decides(d, g, p.0, p.1) + implies delta.contains(eq_literal(p.0, p.1)) != delta.contains(ne_literal(p.0, p.1)) by { + assert(undecided.contains(p)); + assert(delta.contains(mk(p))); + if language::field_value(theta, p.0) == p.1 { + assert(mk(p) == eq_literal(p.0, p.1)); + assert(!literal_holds(theta, ne_literal(p.0, p.1))); + } else { + assert(mk(p) == ne_literal(p.0, p.1)); + assert(!literal_holds(theta, eq_literal(p.0, p.1))); + } + } + assert(split_delta(d, g, pi, delta)); + let g1 = g.union(delta); + assert(sat_by(theta, g1)); + assert(satisfiable(d, g1)); + assert(cases.contains(g1)); + } + assert forall|theta: Subst, g1: Constraint, g2: Constraint| n_theta_ok(d, theta) && cases.contains(g1) && cases.contains(g2) + && #[trigger] sat_by(theta, g1) && #[trigger] sat_by(theta, g2) implies g1 == g2 by { + let d1 = choose|delta: Constraint| #[trigger] split_delta(d, g, pi, delta) && g1 == g.union(delta) + && satisfiable(d, g1); + let d2 = choose|delta: Constraint| #[trigger] split_delta(d, g, pi, delta) && g2 == g.union(delta) + && satisfiable(d, g2); + lemma_entails_subset(d, g1, d1); + lemma_entails_subset(d, g2, d2); + assert forall|l: Literal| #[trigger] d1.contains(l) implies literal_holds(theta, l) by { assert(g1.contains(l)); } + assert forall|l: Literal| #[trigger] d2.contains(l) implies literal_holds(theta, l) by { assert(g2.contains(l)); } + lemma_delta_unique(d, g, pi, d1, d2, theta); + } +} + +pub proof fn theorem_paper_split_ok() + ensures stmt_paper_split_ok(), +{ + assert forall|d: NDomains, g: Constraint, pi: Pairs| #[trigger] split_ok(d, g, pi, paper_split(d, g, pi)) by { + lemma_paper_split_ok(d, g, pi); + } +} + +// ----- proofs: policy reduction ----- + +/// `θ ⊨ Γ_R` iff the head matches `θ`. +pub proof fn lemma_head_sat(h: NHead, theta: Subst) + requires h.len() == theta.len(), h.len() <= MAX_ARITY, + ensures sat_by(theta, head_constraint(h)) == n_head_matches(h, theta), +{ + lemma_head_constraint(h); + if n_head_matches(h, theta) { + assert forall|l: Literal| #[trigger] head_constraint(h).contains(l) implies literal_holds(theta, l) by { + assert(n_head_field(h, l.component) == Some(l.value)); + } + } + if sat_by(theta, head_constraint(h)) { + assert forall|i: int| #![trigger h[i]] 0 <= i < h.len() implies + (h[i] matches Some(v) ==> theta[i] == v) by { + let c = Component(i as u8); + assert(c.0 as int == i); + if let Some(v) = h[i] { + assert(n_head_field(h, c) == Some(v)); + assert(head_constraint(h).contains(eq_literal(c, v))); + assert(literal_holds(theta, eq_literal(c, v))); + } + } + } +} + +/// `L(ρ_R)` is the set of histories violating the rule's mode. +pub proof fn lemma_denial_lang(rule: NRule, theta: Subst, w: Seq) + ensures n_lang(theta, denial(rule), w) == violated_by(rule.mode, n_lang(theta, rule.tail, w)), +{ +} + +/// `R` denies iff `θ ⊨ Γ_R` and `w ∈ L_θ(ρ_R)`. +pub proof fn lemma_rule_denies_iff(rule: NRule, theta: Subst, w: Seq) + requires rule.head.len() == theta.len(), rule.head.len() <= MAX_ARITY, + ensures n_rule_denies(rule, theta, w) == (sat_by(theta, head_constraint(rule.head)) && n_lang(theta, denial(rule), w)), +{ + lemma_head_sat(rule.head, theta); + lemma_denial_lang(rule, theta, w); +} + +/// The language of the firing denials under a case. +pub proof fn lemma_firing_lang(d: NDomains, p: Seq, g1: Constraint, theta: Subst, w: Seq) + ensures + n_lang(theta, firing_denials(d, p, g1), w) <==> exists|j: int| 0 <= j < p.len() + && entails(d, g1, head_constraint(p[j].head)) && #[trigger] n_lang(theta, denial(p[j]), w), +{ + let firing = p.filter(|r: NRule| entails(d, g1, head_constraint(r.head))); + let ms = firing.map(|i: int, r: NRule| denial(r)); + assert(firing_denials(d, p, g1) == Regex::Union(ms)); + if n_lang(theta, firing_denials(d, p, g1), w) { + let i = choose|i: int| 0 <= i < ms.len() && language::numeric_lang(model::gsem(theta), ms[i], w); + let r = firing[i]; + assert(entails(d, g1, head_constraint(r.head))); + assert(firing.contains(r)); + p.lemma_filter_contains_rev(|r: NRule| entails(d, g1, head_constraint(r.head)), r); + let j = choose|j: int| 0 <= j < p.len() && p[j] == r; + assert(n_lang(theta, denial(p[j]), w)); + } + if exists|j: int| 0 <= j < p.len() && entails(d, g1, head_constraint(p[j].head)) && #[trigger] n_lang(theta, denial(p[j]), w) { + let j = choose|j: int| 0 <= j < p.len() && entails(d, g1, head_constraint(p[j].head)) && #[trigger] n_lang(theta, denial(p[j]), w); + assert(firing.contains(p[j])); + let i = choose|i: int| 0 <= i < firing.len() && firing[i] == p[j]; + assert(ms[i] == denial(p[j])); + assert(language::numeric_lang(model::gsem(theta), ms[i], w)); + language::lemma_lang_union(model::gsem(theta), ms, w); + } +} + +/// In a case deciding every policy head constant, the firing language is exactly policy denial. +/// This single-case interface does not require constructing or retaining the entire split. +pub proof fn lemma_firing_policy_iff(d: NDomains, p: Seq, g: Constraint, + theta: Subst, w: Seq) + requires + forall|i: int| 0 <= i < p.len() ==> #[trigger] p[i].head.len() == d.len(), + n_theta_ok(d, theta), + sat_by(theta, g), + forall|pair: (Component, nat)| head_pairs(p).contains(pair) + ==> #[trigger] decides(d, g, pair.0, pair.1), + ensures n_lang(theta, firing_denials(d, p, g), w) == n_policy_denies(p, theta, w), +{ + lemma_head_pairs(p); + lemma_firing_lang(d, p, g, theta, w); + if n_policy_denies(p, theta, w) { + let j = choose|j: int| 0 <= j < p.len() && #[trigger] n_rule_denies(p[j], theta, w); + let gj = head_constraint(p[j].head); + lemma_rule_denies_iff(p[j], theta, w); + lemma_head_constraint(p[j].head); + assert forall|l: Literal| #[trigger] gj.contains(l) + implies l.equal && decides(d, g, l.component, l.value) by { + assert(n_head_field(p[j].head, l.component) == Some(l.value)); + assert(head_pairs(p).contains((l.component, l.value))); + } + lemma_decided_entails(d, g, gj, theta); + } + if n_lang(theta, firing_denials(d, p, g), w) { + let j = choose|j: int| 0 <= j < p.len() + && entails(d, g, head_constraint(p[j].head)) && #[trigger] n_lang(theta, denial(p[j]), w); + assert(sat_by(theta, head_constraint(p[j].head))); + lemma_rule_denies_iff(p[j], theta, w); + assert(n_rule_denies(p[j], theta, w)); + } +} + +/// Transfer one numeric inclusion witness to an uncovered rule witness, including explicit +/// failure of coverage. This is shared by the reduction, search composition, and typed bridge. +pub proof fn lemma_policy_counterexample_transfer(d: NDomains, p: Seq, rule: NRule, + g: Constraint, theta: Subst, w: Seq) + requires + rule.head.len() == d.len(), + forall|i: int| 0 <= i < p.len() ==> #[trigger] p[i].head.len() == d.len(), + entails(d, g, head_constraint(rule.head)), + forall|pair: (Component, nat)| head_pairs(p).contains(pair) + ==> #[trigger] decides(d, g, pair.0, pair.1), + inclusion_cex(d, g, denial(rule), firing_denials(d, p, g), theta, w), + ensures + n_rule_denies(rule, theta, w), + !n_policy_denies(p, theta, w), + !n_covers(d, p, rule), +{ + assert(sat_by(theta, head_constraint(rule.head))); + lemma_rule_denies_iff(rule, theta, w); + lemma_firing_policy_iff(d, p, g, theta, w); +} + +/// Per-case minimum length transfers in the reverse direction: any shorter uncovered pair +/// would be a shorter counterexample to the selected constrained inclusion. +pub proof fn lemma_policy_no_shorter(d: NDomains, p: Seq, rule: NRule, g: Constraint, n: nat) + requires + rule.head.len() == d.len(), + forall|i: int| 0 <= i < p.len() ==> #[trigger] p[i].head.len() == d.len(), + forall|pair: (Component, nat)| head_pairs(p).contains(pair) + ==> #[trigger] decides(d, g, pair.0, pair.1), + no_cex_shorter(d, g, denial(rule), firing_denials(d, p, g), n), + ensures n_no_uncovered_shorter(d, p, rule, g, n), +{ + assert forall|theta: Subst, w: Seq| n_theta_ok(d, theta) && n_history_in(d, w) + && sat_by(theta, g) && w.len() < n + implies !(#[trigger] n_rule_denies(rule, theta, w) && !n_policy_denies(p, theta, w)) by { + lemma_rule_denies_iff(rule, theta, w); + lemma_firing_policy_iff(d, p, g, theta, w); + if n_rule_denies(rule, theta, w) && !n_policy_denies(p, theta, w) { + assert(inclusion_cex(d, g, denial(rule), firing_denials(d, p, g), theta, w)); + } + } +} + +/// Compose a single decided search case, independently of the other cases in the family. +pub proof fn lemma_policy_case_outcome(d: NDomains, p: Seq, rule: NRule, + g0: Constraint, outcome: Outcome) + requires + rule.head.len() == d.len(), + forall|i: int| 0 <= i < p.len() ==> #[trigger] p[i].head.len() == d.len(), + entails(d, g0, head_constraint(rule.head)), + forall|pair: (Component, nat)| head_pairs(p).contains(pair) + ==> #[trigger] decides(d, g0, pair.0, pair.1), + outcome_ok(d, g0, denial(rule), firing_denials(d, p, g0), outcome), + ensures policy_case_outcome_ok(d, p, rule, g0, outcome), +{ + match outcome { + Outcome::Refuted(g, letters) => { + let theta = choose|theta: Subst| n_theta_ok(d, theta) && #[trigger] sat_by(theta, g); + let w = choose|w: Seq| #[trigger] follows(d, letters, theta, w); + lemma_policy_counterexample_transfer(d, p, rule, g0, theta, w); + assert(exists|t: Subst, u: Seq| n_theta_ok(d, t) + && sat_by(t, g) && #[trigger] follows(d, letters, t, u)); + assert forall|t: Subst, u: Seq| n_theta_ok(d, t) && sat_by(t, g) + && #[trigger] follows(d, letters, t, u) + implies n_rule_denies(rule, t, u) && !n_policy_denies(p, t, u) by { + lemma_policy_counterexample_transfer(d, p, rule, g0, t, u); + } + lemma_policy_no_shorter(d, p, rule, g0, letters.len()); + }, + Outcome::Holds => {}, + Outcome::Exhausted => {}, + } +} + +pub proof fn lemma_policy_reduction(d: NDomains, p: Seq, rule: NRule, cases: Set) + requires split_ok(d, head_constraint(rule.head), head_pairs(p), cases), + rule.head.len() == d.len(), + forall|i: int| 0 <= i < p.len() ==> #[trigger] p[i].head.len() == d.len(), + ensures + n_covers(d, p, rule) <==> forall|g1: Constraint| #[trigger] cases.contains(g1) + ==> included_under(d, g1, denial(rule), firing_denials(d, p, g1)), +{ + let gr = head_constraint(rule.head); + if n_covers(d, p, rule) { + assert forall|g1: Constraint| #[trigger] cases.contains(g1) + implies included_under(d, g1, denial(rule), firing_denials(d, p, g1)) by { + assert forall|theta: Subst, w: Seq| n_theta_ok(d, theta) && n_history_in(d, w) && sat_by(theta, g1) + && #[trigger] n_lang(theta, denial(rule), w) implies n_lang(theta, firing_denials(d, p, g1), w) by { + assert(entails(d, g1, gr)); + assert(sat_by(theta, gr)); + lemma_rule_denies_iff(rule, theta, w); + assert(n_rule_denies(rule, theta, w)); + lemma_firing_policy_iff(d, p, g1, theta, w); + } + } + } + if forall|g1: Constraint| #[trigger] cases.contains(g1) ==> included_under(d, g1, denial(rule), firing_denials(d, p, g1)) { + assert forall|theta: Subst, w: Seq| n_theta_ok(d, theta) && n_history_in(d, w) + && #[trigger] n_rule_denies(rule, theta, w) implies n_policy_denies(p, theta, w) by { + lemma_rule_denies_iff(rule, theta, w); + assert(sat_by(theta, gr)); + let g1 = choose|g1: Constraint| #[trigger] cases.contains(g1) && sat_by(theta, g1); + assert(included_under(d, g1, denial(rule), firing_denials(d, p, g1))); + assert(n_lang(theta, firing_denials(d, p, g1), w)); + lemma_firing_policy_iff(d, p, g1, theta, w); + } + } +} + +pub proof fn theorem_policy_reduction() + ensures stmt_policy_reduction(), +{ + assert forall|d: NDomains, p: Seq, rule: NRule, cases: Set| + rule.head.len() == d.len() + && (forall|i: int| 0 <= i < p.len() ==> #[trigger] p[i].head.len() == d.len()) + && #[trigger] split_ok(d, head_constraint(rule.head), head_pairs(p), cases) + implies (n_covers(d, p, rule) <==> forall|g1: Constraint| #[trigger] cases.contains(g1) + ==> included_under(d, g1, denial(rule), firing_denials(d, p, g1))) by { + lemma_policy_reduction(d, p, rule, cases); + } +} + +pub proof fn lemma_policy_search_composition(d: NDomains, p: Seq, rule: NRule, + cases: Set, outcomes: spec_fn(Constraint) -> Outcome) + requires + rule.head.len() == d.len(), + forall|i: int| 0 <= i < p.len() ==> #[trigger] p[i].head.len() == d.len(), + split_ok(d, head_constraint(rule.head), head_pairs(p), cases), + forall|g: Constraint| #[trigger] cases.contains(g) + ==> outcome_ok(d, g, denial(rule), firing_denials(d, p, g), outcomes(g)), + ensures + (forall|g: Constraint| #[trigger] cases.contains(g) ==> outcomes(g) is Holds) + ==> n_covers(d, p, rule), + forall|g: Constraint| #[trigger] cases.contains(g) + ==> policy_case_outcome_ok(d, p, rule, g, outcomes(g)), +{ + lemma_policy_reduction(d, p, rule, cases); + if forall|g: Constraint| #[trigger] cases.contains(g) ==> outcomes(g) is Holds { + assert forall|g: Constraint| #[trigger] cases.contains(g) + implies included_under(d, g, denial(rule), firing_denials(d, p, g)) by { + assert(outcomes(g) == Outcome::Holds); + } + } + assert forall|g: Constraint| #[trigger] cases.contains(g) + implies policy_case_outcome_ok(d, p, rule, g, outcomes(g)) by { + lemma_policy_case_outcome(d, p, rule, g, outcomes(g)); + } +} + +pub proof fn theorem_policy_search_composition() + ensures stmt_policy_search_composition(), +{ + assert forall|d: NDomains, p: Seq, rule: NRule, cases: Set, + outcomes: spec_fn(Constraint) -> Outcome| + #[trigger] policy_search_outcomes_ok(d, p, rule, cases, outcomes) + implies { + &&& ((forall|g: Constraint| #[trigger] cases.contains(g) ==> outcomes(g) is Holds) + ==> n_covers(d, p, rule)) + &&& forall|g: Constraint| #[trigger] cases.contains(g) + ==> policy_case_outcome_ok(d, p, rule, g, outcomes(g)) + } by { + lemma_policy_search_composition(d, p, rule, cases, outcomes); + } +} + +pub proof fn lemma_vacuity(d: NDomains, rule: NRule) + requires rule.head.len() == d.len(), + ensures + (forall|theta: Subst, w: Seq| n_theta_ok(d, theta) && n_history_in(d, w) ==> !#[trigger] n_rule_denies(rule, theta, w)) + <==> included_under(d, head_constraint(rule.head), denial(rule), Regex::Empty), + (forall|theta: Subst, w: Seq| n_theta_ok(d, theta) && n_history_in(d, w) && n_head_matches(rule.head, theta) + ==> #[trigger] n_rule_denies(rule, theta, w)) + <==> included_under(d, head_constraint(rule.head), Regex::All, denial(rule)), +{ + let gr = head_constraint(rule.head); + if forall|theta: Subst, w: Seq| n_theta_ok(d, theta) && n_history_in(d, w) ==> !#[trigger] n_rule_denies(rule, theta, w) { + assert forall|theta: Subst, w: Seq| n_theta_ok(d, theta) && n_history_in(d, w) && sat_by(theta, gr) + && #[trigger] n_lang(theta, denial(rule), w) implies n_lang(theta, Regex::Empty, w) by { + lemma_rule_denies_iff(rule, theta, w); + } + } + if included_under(d, gr, denial(rule), Regex::Empty) { + assert forall|theta: Subst, w: Seq| n_theta_ok(d, theta) && n_history_in(d, w) + implies !#[trigger] n_rule_denies(rule, theta, w) by { + lemma_rule_denies_iff(rule, theta, w); + if n_rule_denies(rule, theta, w) { + assert(n_lang(theta, denial(rule), w)); + } + } + } + if forall|theta: Subst, w: Seq| n_theta_ok(d, theta) && n_history_in(d, w) && n_head_matches(rule.head, theta) + ==> #[trigger] n_rule_denies(rule, theta, w) { + assert forall|theta: Subst, w: Seq| n_theta_ok(d, theta) && n_history_in(d, w) && sat_by(theta, gr) + && #[trigger] n_lang(theta, Regex::All, w) implies n_lang(theta, denial(rule), w) by { + lemma_rule_denies_iff(rule, theta, w); + lemma_head_sat(rule.head, theta); + assert(n_rule_denies(rule, theta, w)); + } + } + if included_under(d, gr, Regex::All, denial(rule)) { + assert forall|theta: Subst, w: Seq| n_theta_ok(d, theta) && n_history_in(d, w) && n_head_matches(rule.head, theta) + implies #[trigger] n_rule_denies(rule, theta, w) by { + lemma_rule_denies_iff(rule, theta, w); + lemma_head_sat(rule.head, theta); + assert(n_lang(theta, Regex::All, w)); + } + } +} + +pub proof fn theorem_vacuity_reductions() + ensures stmt_vacuity_reductions(), +{ + assert forall|d: NDomains, rule: NRule| + #![trigger included_under(d, head_constraint(rule.head), denial(rule), Regex::Empty)] + rule.head.len() == d.len() implies ( + (forall|theta: Subst, w: Seq| n_theta_ok(d, theta) && n_history_in(d, w) ==> !#[trigger] n_rule_denies(rule, theta, w)) + <==> included_under(d, head_constraint(rule.head), denial(rule), Regex::Empty)) by { + lemma_vacuity(d, rule); + } + assert forall|d: NDomains, rule: NRule| + #![trigger included_under(d, head_constraint(rule.head), Regex::All, denial(rule))] + rule.head.len() == d.len() implies ( + (forall|theta: Subst, w: Seq| n_theta_ok(d, theta) && n_history_in(d, w) && n_head_matches(rule.head, theta) + ==> #[trigger] n_rule_denies(rule, theta, w)) + <==> included_under(d, head_constraint(rule.head), Regex::All, denial(rule))) by { + lemma_vacuity(d, rule); + } +} + +pub proof fn theorem_vacuity_via_refinement() + ensures stmt_vacuity_via_refinement::(), +{ + assert forall|d: DomainsView, r: RuleView| + #[trigger] never_denies::(d, r) <==> refines::(d, Seq::empty(), seq![r]) by { + let single = seq![r]; + assert forall|c: E, h: Seq| policy_denies(single, c, h) <==> rule_violated(r, c, h) by { + assert(single[0] == r); + } + assert(forall|c: E, h: Seq| !policy_denies(Seq::>::empty(), c, h)); + if never_denies::(d, r) { + assert forall|c: E, h: Seq| in_domains::(d, c, h) && policy_permits(Seq::empty(), c, h) + implies #[trigger] policy_permits(single, c, h) by { + assert(!rule_violated(r, c, h)); + } + } + if refines::(d, Seq::empty(), single) { + assert forall|c: E, h: Seq| in_domains::(d, c, h) implies !#[trigger] rule_violated(r, c, h) by { + assert(policy_permits(single, c, h)); + } + } + } + assert forall|d: DomainsView, r: RuleView| + #[trigger] always_denies::(d, r) <==> refines::(d, seq![r], seq![forbid_all(r.head)]) by { + let single = seq![r]; + let all = seq![forbid_all(r.head)]; + assert forall|c: E, h: Seq| policy_denies(single, c, h) <==> rule_violated(r, c, h) by { + assert(single[0] == r); + } + assert forall|c: E, h: Seq| policy_denies(all, c, h) <==> head_matches(r.head, event_view(c)) by { + assert(all[0] == forbid_all(r.head)); + assert(lang(RegexView::::All, r.head, event_view(c), history_view(h))); + assert(rule_violated(forbid_all(r.head), c, h) == head_matches(r.head, event_view(c))); + } + if always_denies::(d, r) { + assert forall|c: E, h: Seq| in_domains::(d, c, h) && policy_permits(single, c, h) + implies #[trigger] policy_permits(all, c, h) by { + assert(!rule_violated(r, c, h)); + } + } + if refines::(d, single, all) { + assert forall|c: E, h: Seq| in_domains::(d, c, h) && head_matches(r.head, event_view(c)) + implies #[trigger] rule_violated(r, c, h) by { + assert(policy_denies(all, c, h)); + assert(!policy_permits(all, c, h)); + } + } + } +} + +} // verus! diff --git a/src/history-semantics/src/verify/refinement/mod.rs b/src/history-semantics/src/verify/refinement/mod.rs new file mode 100644 index 000000000..9e30d5a8f --- /dev/null +++ b/src/history-semantics/src/verify/refinement/mod.rs @@ -0,0 +1,25 @@ +//! Specification hierarchy for the correctness of policy-refinement analysis. +//! +//! Each layer holds definitions, the theorem statements (`stmt_*` spec functions returning the +//! proposition), and their proofs (`theorem_*`, each with `ensures stmt_*(...)`). Every `stmt_*` +//! is proved. The mapping to the paper's results is the index `crate::verify::paper`. +//! +//! Layers, top-down: +//! - [`semantics`]: proofs of the policy questions (refinement iff coverage, redundancy iff +//! coverage, genericity) and the constants of a rule. What each analyzer verdict means is stated by +//! the analyzer specification (`history_analysis::spec::analyzer`), over the semantics and the +//! analysis questions (`junco_core::spec::{semantics, questions}`). +//! - [`encoding`]: typed rules as numeric rules, through the existing verified front end +//! (`flatten_rule`, `lower_flat`, `compile`), plus renaming invariance for fresh values. +//! - [`inclusion`]: constraints, `Split`, constrained inclusion, and the policy reduction. +//! - [`search`]: items, witnesses, successor cases, and the breadth-first search. +//! - [`pruning`]: state decomposition, dead items, domination, syntactic simulation. +//! - [`finiteness`]: finitely many reachable states, via the abstract model of `finite_states`. +//! - [`implementation`]: graph ids, interned constraints and letters as abstract objects. +pub mod encoding; +pub mod finiteness; +pub mod implementation; +pub mod inclusion; +pub mod pruning; +pub mod search; +pub mod semantics; diff --git a/src/history-semantics/src/verify/refinement/pruning.rs b/src/history-semantics/src/verify/refinement/pruning.rs new file mode 100644 index 000000000..58c5236b5 --- /dev/null +++ b/src/history-semantics/src/verify/refinement/pruning.rs @@ -0,0 +1,545 @@ +//! Layer 4: pruning (appendix `app:pruning`, Definition Pruning checks `def:pruning`, Lemma +//! `lem:prune`; simulation, appendix `app:simulation`). +//! +//! The search may discard an item at insertion when `search::may_discard` holds. This layer +//! states that the implemented checks (dead items, domination up to a sound simulation) imply it. +//! The simulation rules are those of `history-analysis/src/simulation.rs`. They differ from Figure +//! `fig:simulation`: the code reads `SumL`, `SumR`, `AndL` and `AndR` on lifted tests only when both +//! sides are lifted tests (`test_step`), so its relation is smaller than the Figure's. The side +//! conditions `k ≥ 2` and `a + b ≥ 1` are dropped. Soundness is proved; that the recursion decides +//! the Figure's relation is not. +use super::encoding::*; +use super::inclusion::*; +use super::search::*; +use alloc::boxed::Box; +use junco_core::kernel::verify as model; +use junco_core::verify::history_specs as language; +use junco_core::verify::history_specs::{EventView, Regex, Subst}; +use vstd::prelude::*; + +verus! { + +/// `L_θ(x) ⊆ L_θ(y)` for every admissible `θ`. +pub open spec fn lang_le(x: Regex, y: Regex) -> bool { + forall|theta: Subst, w: Seq| language::event_wf(theta, theta.len()) && #[trigger] n_lang(theta, x, w) ==> n_lang(theta, y, w) +} + +pub open spec fn test_le_sem(x: model::Test, y: model::Test) -> bool { + forall|theta: Subst, e: EventView| language::event_wf(theta, theta.len()) && #[trigger] model::test_holds(theta, x, e) ==> model::test_holds(theta, y, e) +} + +/// `≤` is sound (Lemma Simulation soundness and decidability, `lem:simulation`). +pub open spec fn sim_sound(le: spec_fn(Regex, Regex) -> bool) -> bool { + forall|x: Regex, y: Regex| #[trigger] le(x, y) ==> lang_le(x, y) +} + +pub open spec fn test_sim_sound(tle: spec_fn(model::Test, model::Test) -> bool) -> bool { + forall|x: model::Test, y: model::Test| #[trigger] tle(x, y) ==> test_le_sem(x, y) +} + +/// Operands of `q` for `&` (`+`): its operands if it is an intersection (union), else `{q}`. +pub open spec fn inter_ops(q: Regex) -> Seq> { + match q { Regex::Intersect(cs) => cs, _ => seq![q] } +} + +pub open spec fn union_ops(q: Regex) -> Seq> { + match q { Regex::Union(cs) => cs, _ => seq![q] } +} + +/// `dec(q) = (P, N)` (Definition Decomposition, `def:decomposition`). +pub open spec fn required(q: Regex, p: Regex) -> bool { + inter_ops(q).contains(p) && !(p is Not) +} + +pub open spec fn excluded(q: Regex, n: Regex) -> bool { + exists|v: Regex| #[trigger] inter_ops(q).contains(Regex::Not(Box::new(v))) && union_ops(v).contains(n) +} + +/// Equation `eq:decomposition`: `L_θ(q) = ⋂_{p∈P} L_θ(p) \ ⋃_{n∈N} L_θ(n)`. +pub open spec fn stmt_decomposition() -> bool { + forall|q: Regex, theta: Subst, w: Seq| #[trigger] n_lang(theta, q, w) == ( + (forall|p: Regex| #[trigger] required(q, p) ==> n_lang(theta, p, w)) + && (forall|n: Regex| #[trigger] excluded(q, n) ==> !n_lang(theta, n, w))) +} + +/// Dead test (Definition Pruning checks, `def:pruning`). +pub open spec fn dead(le: spec_fn(Regex, Regex) -> bool, q: Regex) -> bool { + exists|p: Regex| #[trigger] required(q, p) && forall|v: Regex| #[trigger] union_ops(p).contains(v) + ==> exists|n: Regex| #[trigger] excluded(q, n) && le(v, n) +} + +/// Domination `J ⊑ I` (Definition Pruning checks, `def:pruning`). +pub open spec fn dominated(d: NDomains, le: spec_fn(Regex, Regex) -> bool, j: Item, i: Item) -> bool { + &&& entails(d, j.constraint, i.constraint) + &&& forall|p: Regex| #[trigger] required(i.state, p) ==> required(j.state, p) + &&& forall|n: Regex| #[trigger] excluded(i.state, n) ==> exists|n2: Regex| #[trigger] excluded(j.state, n2) && le(n, n2) +} + +/// Lemma Pruning soundness (`lem:prune`): a dead item has no witnesses, and `J ⊑ I` gives `W(J) ⊆ W(I)`. +pub open spec fn stmt_prune_sound() -> bool { + forall|d: NDomains, le: spec_fn(Regex, Regex) -> bool, j: Item, i: Item| + #[trigger] sim_sound(le) ==> { + &&& (dead(le, j.state) ==> no_witness(d, j)) + &&& (#[trigger] dominated(d, le, j, i) ==> witnesses_within(d, j, i)) + } +} + +/// One rule of the code's term simulation, with premises read from `le` and `tle`. +pub open spec fn sim_step(le: spec_fn(Regex, Regex) -> bool, + tle: spec_fn(model::Test, model::Test) -> bool, x: Regex, y: Regex) -> bool { + ||| x == y // Refl + ||| x is Empty // Zero + ||| y is All // One + ||| x is Epsilon && language::nullable(y) // Eps + ||| (x matches Regex::Union(cs) && forall|i: int| 0 <= i < cs.len() ==> #[trigger] le(cs[i], y)) // SumL + ||| (y matches Regex::Union(cs) && exists|i: int| 0 <= i < cs.len() && #[trigger] le(x, cs[i])) // SumR + ||| (x matches Regex::Intersect(cs) && exists|i: int| 0 <= i < cs.len() && #[trigger] le(cs[i], y)) // AndL + ||| (y matches Regex::Intersect(cs) && forall|i: int| 0 <= i < cs.len() ==> #[trigger] le(x, cs[i])) // AndR + ||| (x matches Regex::Not(a) && y matches Regex::Not(b) && le(*b, *a)) // Not + ||| (x matches Regex::Test(f) && y matches Regex::Test(g) && tle(f, g)) // tests + ||| (x matches Regex::Star(a) && y matches Regex::Star(b) && le(*a, *b)) // Star + ||| (y matches Regex::Star(b) && le(x, *b)) // StarI + ||| (y matches Regex::Concat(ys) && cat_padded(le, x, ys)) // Cat, PadL, PadR +} + +/// `x`'s factors (its list, or `x` itself) match `ys` pointwise after dropping `a` leading and +/// `b` trailing `Univ` factors of `ys`. +pub open spec fn cat_padded(le: spec_fn(Regex, Regex) -> bool, + x: Regex, ys: Seq>) -> bool { + let xs = match x { Regex::Concat(cs) => cs, _ => seq![x] }; + exists|a: nat, b: nat| #![trigger padding_trigger(ys, a, b)] padding_ok(ys, a, b, xs.len()) + && forall|i: int| #![trigger ys[a + i]] 0 <= i < xs.len() ==> le(xs[i], ys[a + i]) +} + +pub open spec fn padding_ok(ys: Seq>, a: nat, b: nat, len: nat) -> bool { + a + b + len == ys.len() + && forall|i: int| (0 <= i < a || ys.len() - b <= i < ys.len()) ==> #[trigger] ys[i] is All +} + +/// One rule of the code's test simulation (`Simulation::test_le` in `history-analysis/src/simulation.rs`). +pub open spec fn test_step(tle: spec_fn(model::Test, model::Test) -> bool, x: model::Test, y: model::Test) -> bool { + ||| x == y + ||| y is True + ||| x is False + ||| (x matches model::Test::Or(cs) && forall|i: int| 0 <= i < cs.len() ==> #[trigger] tle(cs[i], y)) + ||| (y matches model::Test::And(cs) && forall|i: int| 0 <= i < cs.len() ==> #[trigger] tle(x, cs[i])) + ||| (x matches model::Test::And(cs) && exists|i: int| 0 <= i < cs.len() && #[trigger] tle(cs[i], y)) + ||| (y matches model::Test::Or(cs) && exists|i: int| 0 <= i < cs.len() && #[trigger] tle(x, cs[i])) +} + +/// Lemma Simulation soundness (`lem:simulation`), rule by rule: each rule applied to sound premises gives a +/// sound conclusion; by induction on derivations the least relation closed under the rules, +/// and any relation the memoized recursion computes inside it, is sound. +pub open spec fn stmt_sim_rules_sound() -> bool { + forall|le: spec_fn(Regex, Regex) -> bool, tle: spec_fn(model::Test, model::Test) -> bool, + x: Regex, y: Regex| + sim_sound(le) && test_sim_sound(tle) && #[trigger] sim_step(le, tle, x, y) ==> lang_le(x, y) +} + +pub open spec fn stmt_test_rules_sound() -> bool { + forall|tle: spec_fn(model::Test, model::Test) -> bool, x: model::Test, y: model::Test| + test_sim_sound(tle) && #[trigger] test_step(tle, x, y) ==> test_le_sem(x, y) +} + +/// The implemented insertion checks discharge `search::may_discard`: the dead check gives no +/// witnesses, and domination by an earlier node gives `W(J) ⊆ W(K)`. +pub open spec fn stmt_checks_discard() -> bool { + forall|d: NDomains, le: spec_fn(Regex, Regex) -> bool, nodes: Seq, j: Item, depth: nat| + #[trigger] sim_sound(le) && (dead(le, j.state) || exists|k: int| 0 <= k < nodes.len() && nodes[k].depth <= depth + && #[trigger] dominated(d, le, j, nodes[k].item)) + ==> #[trigger] may_discard(d, nodes, j, depth) +} + +// ----- proofs ----- + +/// `L_θ(v)` is the union of the languages of `v`'s union operands. +pub proof fn lemma_union_ops_lang(theta: Subst, v: Regex, w: Seq) + ensures n_lang(theta, v, w) == exists|n: Regex| #[trigger] union_ops(v).contains(n) && n_lang(theta, n, w), +{ + let sem = model::gsem(theta); + match v { + Regex::Union(cs) => { + language::lemma_lang_union(sem, cs, w); + if n_lang(theta, v, w) { + let i = choose|i: int| 0 <= i < cs.len() && language::numeric_lang(sem, cs[i], w); + assert(union_ops(v).contains(cs[i])); + assert(n_lang(theta, cs[i], w)); + } + if exists|n: Regex| #[trigger] union_ops(v).contains(n) && n_lang(theta, n, w) { + let n = choose|n: Regex| #[trigger] union_ops(v).contains(n) && n_lang(theta, n, w); + let i = choose|i: int| 0 <= i < cs.len() && cs[i] == n; + assert(language::numeric_lang(sem, cs[i], w)); + } + }, + _ => { + assert(union_ops(v)[0] == v); + assert(union_ops(v).contains(v)); + if exists|n: Regex| #[trigger] union_ops(v).contains(n) && n_lang(theta, n, w) { + let n = choose|n: Regex| #[trigger] union_ops(v).contains(n) && n_lang(theta, n, w); + let i = choose|i: int| 0 <= i < union_ops(v).len() && union_ops(v)[i] == n; + assert(i == 0); + } + }, + } +} + +/// `L_θ(q)` is the intersection of the languages of `q`'s intersection operands. +pub proof fn lemma_inter_ops_lang(theta: Subst, q: Regex, w: Seq) + ensures n_lang(theta, q, w) == (forall|i: int| + 0 <= i < inter_ops(q).len() ==> #[trigger] n_lang(theta, inter_ops(q)[i], w)), +{ + match q { + Regex::Intersect(cs) => { + language::lemma_lang_intersect(model::gsem(theta), cs, w); + assert forall|i: int| 0 <= i < cs.len() implies + n_lang(theta, q, w) ==> #[trigger] n_lang(theta, cs[i], w) by {} + if forall|i: int| 0 <= i < cs.len() ==> #[trigger] n_lang(theta, cs[i], w) { + assert forall|i: int| 0 <= i < cs.len() implies + language::numeric_lang(model::gsem(theta), cs[i], w) by { + assert(n_lang(theta, cs[i], w)); + } + } + }, + _ => { + assert(inter_ops(q).len() == 1 && inter_ops(q)[0] == q); + if forall|i: int| 0 <= i < inter_ops(q).len() ==> #[trigger] n_lang(theta, inter_ops(q)[i], w) { + assert(n_lang(theta, inter_ops(q)[0], w)); + } + }, + } +} + +pub proof fn lemma_decomposition(q: Regex, theta: Subst, w: Seq) + ensures n_lang(theta, q, w) == ( + (forall|p: Regex| #[trigger] required(q, p) ==> n_lang(theta, p, w)) + && (forall|n: Regex| #[trigger] excluded(q, n) ==> !n_lang(theta, n, w))), +{ + let ops = inter_ops(q); + lemma_inter_ops_lang(theta, q, w); + if n_lang(theta, q, w) { + assert forall|p: Regex| #[trigger] required(q, p) implies n_lang(theta, p, w) by { + let i = choose|i: int| 0 <= i < ops.len() && ops[i] == p; + assert(n_lang(theta, ops[i], w)); + } + assert forall|n: Regex| #[trigger] excluded(q, n) implies !n_lang(theta, n, w) by { + let v = choose|v: Regex| #[trigger] inter_ops(q).contains(Regex::Not(Box::new(v))) && union_ops(v).contains(n); + let i = choose|i: int| 0 <= i < ops.len() && ops[i] == Regex::Not(Box::new(v)); + assert(n_lang(theta, ops[i], w)); + assert(!n_lang(theta, v, w)); + lemma_union_ops_lang(theta, v, w); + } + } + if (forall|p: Regex| #[trigger] required(q, p) ==> n_lang(theta, p, w)) + && (forall|n: Regex| #[trigger] excluded(q, n) ==> !n_lang(theta, n, w)) { + assert forall|i: int| 0 <= i < ops.len() implies #[trigger] n_lang(theta, ops[i], w) by { + assert(ops.contains(ops[i])); + match ops[i] { + Regex::Not(b) => { + let v = *b; + assert(ops[i] == Regex::Not(Box::new(v))); + lemma_union_ops_lang(theta, v, w); + assert forall|n: Regex| #[trigger] union_ops(v).contains(n) implies !n_lang(theta, n, w) by { + assert(inter_ops(q).contains(Regex::Not(Box::new(v))) && union_ops(v).contains(n)); + assert(excluded(q, n)); + } + }, + _ => { assert(required(q, ops[i])); }, + } + } + } +} + +pub proof fn theorem_decomposition() + ensures stmt_decomposition(), +{ + assert forall|q: Regex, theta: Subst, w: Seq| #[trigger] n_lang(theta, q, w) == ( + (forall|p: Regex| #[trigger] required(q, p) ==> n_lang(theta, p, w)) + && (forall|n: Regex| #[trigger] excluded(q, n) ==> !n_lang(theta, n, w))) by { + lemma_decomposition(q, theta, w); + } +} + +/// Lemma `lem:prune` for one pair of items. +pub proof fn lemma_prune_sound(d: NDomains, le: spec_fn(Regex, Regex) -> bool, j: Item, i: Item) + requires sim_sound(le), + ensures + dead(le, j.state) ==> no_witness(d, j), + dominated(d, le, j, i) ==> witnesses_within(d, j, i), +{ + if dead(le, j.state) { + assert forall|theta: Subst, w: Seq| !#[trigger] witness(d, j, theta, w) by { + if witness(d, j, theta, w) { + let p = choose|p: Regex| #[trigger] required(j.state, p) && forall|v: Regex| #[trigger] union_ops(p).contains(v) + ==> exists|n: Regex| #[trigger] excluded(j.state, n) && le(v, n); + lemma_decomposition(j.state, theta, w); + assert(n_lang(theta, p, w)); + lemma_union_ops_lang(theta, p, w); + let v = choose|v: Regex| #[trigger] union_ops(p).contains(v) && n_lang(theta, v, w); + let n = choose|n: Regex| #[trigger] excluded(j.state, n) && le(v, n); + assert(lang_le(v, n)); + assert(n_lang(theta, n, w)); + } + } + } + if dominated(d, le, j, i) { + assert forall|theta: Subst, w: Seq| #[trigger] witness(d, j, theta, w) implies witness(d, i, theta, w) by { + lemma_decomposition(j.state, theta, w); + lemma_decomposition(i.state, theta, w); + assert(sat_by(theta, i.constraint)); + assert forall|p: Regex| #[trigger] required(i.state, p) implies n_lang(theta, p, w) by { + assert(required(j.state, p)); + } + assert forall|n: Regex| #[trigger] excluded(i.state, n) implies !n_lang(theta, n, w) by { + let n2 = choose|n2: Regex| #[trigger] excluded(j.state, n2) && le(n, n2); + assert(lang_le(n, n2)); + assert(!n_lang(theta, n2, w)); + } + } + } +} + +pub proof fn theorem_prune_sound() + ensures stmt_prune_sound(), +{ + assert forall|d: NDomains, le: spec_fn(Regex, Regex) -> bool, + j: Item, theta: Subst, w: Seq| + #[trigger] sim_sound(le) && #[trigger] dead(le, j.state) + implies !#[trigger] witness(d, j, theta, w) by { + lemma_prune_sound(d, le, j, j); + } + assert forall|d: NDomains, le: spec_fn(Regex, Regex) -> bool, + j: Item, i: Item| + #[trigger] sim_sound(le) && #[trigger] dominated(d, le, j, i) + implies witnesses_within(d, j, i) by { + lemma_prune_sound(d, le, j, i); + } +} + +/// Cat/PadL/PadR, with the factors' parts given. +proof fn lemma_cat_parts(le: spec_fn(Regex, Regex) -> bool, xs: Seq>, + ys: Seq>, a: nat, b: nat, parts: Seq>, theta: Subst, w: Seq) + requires + sim_sound(le), language::event_wf(theta, theta.len()), + padding_ok(ys, a, b, xs.len()), + forall|i: int| 0 <= i < xs.len() ==> #[trigger] le(xs[i], ys[a + i]), + parts.len() == xs.len(), parts.flatten() == w, + forall|i: int| 0 <= i < xs.len() ==> #[trigger] n_lang(theta, xs[i], parts[i]), + ensures n_lang(theta, Regex::Concat(ys), w), +{ + let pre = Seq::new(a, |k: int| Seq::::empty()); + let post = Seq::new(b, |k: int| Seq::::empty()); + let all = pre + parts + post; + vstd::seq_lib::lemma_flatten_concat(pre + parts, post); + vstd::seq_lib::lemma_flatten_concat(pre, parts); + language::lemma_flatten_empty(pre); + language::lemma_flatten_empty(post); + assert(pre.flatten() =~= Seq::::empty()); + assert(post.flatten() =~= Seq::::empty()); + assert(all.flatten() =~= w); + assert(all.len() == ys.len()); + assert forall|i: int| 0 <= i < ys.len() implies language::numeric_lang(model::gsem(theta), ys[i], all[i]) by { + if i < a { + assert(ys[i] is All); + } else if i < a + xs.len() { + let k = i - a; + assert(all[i] == parts[k]); + assert(ys[a + k] == ys[i]); + assert(le(xs[k], ys[a + k])); + assert(lang_le(xs[k], ys[a + k])); + assert(n_lang(theta, xs[k], parts[k])); + assert(n_lang(theta, ys[i], all[i])); + } else { + assert(ys.len() - b <= i); + assert(ys[i] is All); + } + } +} + +proof fn lemma_cat_padded_sound(le: spec_fn(Regex, Regex) -> bool, x: Regex, + ys: Seq>, theta: Subst, w: Seq) + requires sim_sound(le), language::event_wf(theta, theta.len()), cat_padded(le, x, ys), n_lang(theta, x, w), + ensures n_lang(theta, Regex::Concat(ys), w), +{ + let sem = model::gsem(theta); + reveal(cat_padded); + let xs = match x { Regex::Concat(cs) => cs, _ => seq![x] }; + let (a, b) = choose|a: nat, b: nat| #[trigger] padding_ok(ys, a, b, xs.len()) + && forall|i: int| 0 <= i < xs.len() ==> #[trigger] le(xs[i], ys[a + i]); + match x { + Regex::Concat(cs) => { + let parts = choose|parts: Seq>| parts.len() == cs.len() && w == parts.flatten() + && forall|i: int| 0 <= i < cs.len() ==> language::numeric_lang(sem, cs[i], parts[i]); + assert forall|i: int| 0 <= i < xs.len() implies #[trigger] n_lang(theta, xs[i], parts[i]) by {} + lemma_cat_parts(le, xs, ys, a, b, parts, theta, w); + }, + _ => { + let parts = seq![w]; + parts.lemma_flatten_one_element(); + assert forall|i: int| 0 <= i < xs.len() implies #[trigger] n_lang(theta, xs[i], parts[i]) by { + assert(i == 0); + } + lemma_cat_parts(le, xs, ys, a, b, parts, theta, w); + }, + } +} + +/// One rule of the term simulation is sound. +pub proof fn lemma_sim_step_sound(le: spec_fn(Regex, Regex) -> bool, + tle: spec_fn(model::Test, model::Test) -> bool, x: Regex, y: Regex) + requires sim_sound(le), test_sim_sound(tle), sim_step(le, tle, x, y), + ensures lang_le(x, y), +{ + assert forall|theta: Subst, w: Seq| language::event_wf(theta, theta.len()) && #[trigger] n_lang(theta, x, w) + implies n_lang(theta, y, w) by { + let sem = model::gsem(theta); + if x is Epsilon && language::nullable(y) { + language::lemma_nullable_iff_nil(sem, y); + assert(w =~= Seq::::empty()); + } + if x matches Regex::Union(cs) && forall|i: int| 0 <= i < cs.len() ==> #[trigger] le(cs[i], y) { + let cs = x->Union_0; + let i = choose|i: int| 0 <= i < cs.len() && language::numeric_lang(sem, cs[i], w); + assert(le(cs[i], y)); + assert(lang_le(cs[i], y)); + assert(n_lang(theta, cs[i], w)); + } + if y matches Regex::Union(cs) && exists|i: int| 0 <= i < cs.len() && #[trigger] le(x, cs[i]) { + let cs = y->Union_0; + let i = choose|i: int| 0 <= i < cs.len() && #[trigger] le(x, cs[i]); + assert(lang_le(x, cs[i])); + assert(n_lang(theta, cs[i], w)); + language::lemma_lang_union(sem, cs, w); + } + if x matches Regex::Intersect(cs) && exists|i: int| 0 <= i < cs.len() && #[trigger] le(cs[i], y) { + let cs = x->Intersect_0; + let i = choose|i: int| 0 <= i < cs.len() && #[trigger] le(cs[i], y); + assert(lang_le(cs[i], y)); + assert(language::numeric_lang(sem, cs[i], w)); + assert(n_lang(theta, cs[i], w)); + } + if y matches Regex::Intersect(cs) && forall|i: int| 0 <= i < cs.len() ==> #[trigger] le(x, cs[i]) { + let cs = y->Intersect_0; + assert forall|i: int| 0 <= i < cs.len() implies language::numeric_lang(sem, cs[i], w) by { + assert(le(x, cs[i])); + assert(lang_le(x, cs[i])); + assert(n_lang(theta, cs[i], w)); + } + language::lemma_lang_intersect(sem, cs, w); + } + if x matches Regex::Not(a) && y matches Regex::Not(b) && le(*b, *a) { + let a = *(x->Not_0); + let b = *(y->Not_0); + assert(lang_le(b, a)); + if n_lang(theta, b, w) { assert(n_lang(theta, a, w)); } + } + if x matches Regex::Test(f) && y matches Regex::Test(g) && tle(f, g) { + let f = x->Test_0; + let g = y->Test_0; + assert(test_le_sem(f, g)); + assert(model::test_holds(theta, f, w[0])); + assert(model::test_holds(theta, g, w[0])); + } + if x matches Regex::Star(a) && y matches Regex::Star(b) && le(*a, *b) { + let a = *(x->Star_0); + let b = *(y->Star_0); + assert(lang_le(a, b)); + let parts = choose|parts: Seq>| w == parts.flatten() + && forall|i: int| 0 <= i < parts.len() ==> language::numeric_lang(sem, a, parts[i]); + assert forall|i: int| 0 <= i < parts.len() implies language::numeric_lang(sem, b, parts[i]) by { + assert(n_lang(theta, a, parts[i])); + } + } + if y matches Regex::Star(b) && le(x, *b) { + let b = *(y->Star_0); + assert(lang_le(x, b)); + assert(n_lang(theta, b, w)); + crate::verify::history_algebra::lemma_parts_star_single(sem, b, w); + } + if y matches Regex::Concat(ys) && cat_padded(le, x, ys) { + lemma_cat_padded_sound(le, x, y->Concat_0, theta, w); + } + } +} + +pub proof fn theorem_sim_rules_sound() + ensures stmt_sim_rules_sound(), +{ + assert forall|le: spec_fn(Regex, Regex) -> bool, tle: spec_fn(model::Test, model::Test) -> bool, + x: Regex, y: Regex| + sim_sound(le) && test_sim_sound(tle) && #[trigger] sim_step(le, tle, x, y) implies lang_le(x, y) by { + lemma_sim_step_sound(le, tle, x, y); + } +} + +/// One rule of the test simulation is sound. +pub proof fn lemma_test_step_sound(tle: spec_fn(model::Test, model::Test) -> bool, x: model::Test, y: model::Test) + requires test_sim_sound(tle), test_step(tle, x, y), + ensures test_le_sem(x, y), +{ + assert forall|theta: Subst, e: EventView| language::event_wf(theta, theta.len()) && #[trigger] model::test_holds(theta, x, e) + implies model::test_holds(theta, y, e) by { + if x matches model::Test::Or(cs) && forall|i: int| 0 <= i < cs.len() ==> #[trigger] tle(cs[i], y) { + let cs = x->Or_0; + let i = choose|i: int| 0 <= i < cs.len() && model::test_holds(theta, cs[i], e); + assert(tle(cs[i], y)); + assert(test_le_sem(cs[i], y)); + } + if y matches model::Test::And(cs) && forall|i: int| 0 <= i < cs.len() ==> #[trigger] tle(x, cs[i]) { + let cs = y->And_0; + assert forall|i: int| 0 <= i < cs.len() implies model::test_holds(theta, cs[i], e) by { + assert(tle(x, cs[i])); + assert(test_le_sem(x, cs[i])); + } + } + if x matches model::Test::And(cs) && exists|i: int| 0 <= i < cs.len() && #[trigger] tle(cs[i], y) { + let cs = x->And_0; + let i = choose|i: int| 0 <= i < cs.len() && #[trigger] tle(cs[i], y); + assert(test_le_sem(cs[i], y)); + assert(model::test_holds(theta, cs[i], e)); + } + if y matches model::Test::Or(cs) && exists|i: int| 0 <= i < cs.len() && #[trigger] tle(x, cs[i]) { + let cs = y->Or_0; + let i = choose|i: int| 0 <= i < cs.len() && #[trigger] tle(x, cs[i]); + assert(test_le_sem(x, cs[i])); + assert(model::test_holds(theta, cs[i], e)); + } + } +} + +pub proof fn theorem_test_rules_sound() + ensures stmt_test_rules_sound(), +{ + assert forall|tle: spec_fn(model::Test, model::Test) -> bool, x: model::Test, y: model::Test| + test_sim_sound(tle) && #[trigger] test_step(tle, x, y) implies test_le_sem(x, y) by { + lemma_test_step_sound(tle, x, y); + } +} + +pub proof fn theorem_checks_discard() + ensures stmt_checks_discard(), +{ + assert forall|d: NDomains, le: spec_fn(Regex, Regex) -> bool, nodes: Seq, j: Item, depth: nat| + #[trigger] sim_sound(le) && (dead(le, j.state) || exists|k: int| 0 <= k < nodes.len() && nodes[k].depth <= depth + && #[trigger] dominated(d, le, j, nodes[k].item)) + implies #[trigger] may_discard(d, nodes, j, depth) by { + if dead(le, j.state) { + lemma_prune_sound(d, le, j, j); + } else { + let k = choose|k: int| 0 <= k < nodes.len() && nodes[k].depth <= depth && #[trigger] dominated(d, le, j, nodes[k].item); + lemma_prune_sound(d, le, j, nodes[k].item); + assert(witnesses_within(d, j, nodes[k].item)); + } + } +} + +// The trigger must not capture the conditional operand list inside `cat_padded`. +pub closed spec fn padding_trigger(ys: Seq>, a: nat, b: nat) -> (nat, nat) { + (a, b) +} + +pub proof fn lemma_padding_trigger(ys: Seq>, a: nat, b: nat) + ensures padding_trigger(ys, a, b) == (a, b), +{ + reveal(padding_trigger); +} +} // verus! diff --git a/src/history-semantics/src/verify/refinement/search.rs b/src/history-semantics/src/verify/refinement/search.rs new file mode 100644 index 000000000..61189b3b9 --- /dev/null +++ b/src/history-semantics/src/verify/refinement/search.rs @@ -0,0 +1,1101 @@ +//! Layer 3: the symbolic search (`sec:search-state`, `sec:search`; appendix `app:cases`, +//! `app:search-proof`; differences from the paper's presentation in `app:mech-diff`). +//! +//! States are abstract expressions `Regex`; the implementation's states are graph +//! ids, abstracted by `model::lift_regex` (see `implementation`). The search is specified by its +//! *traces*: the sequence of inserted items in insertion order, with parents and depths, as kept +//! by `history-analysis/src/search.rs` (`items`, `next`). Insertion-time discarding is specified +//! semantically (no witnesses, or witnesses contained in those of an earlier item); the `pruning` +//! layer shows the implemented checks imply it. +use super::encoding::*; +use super::inclusion::*; +use history_syntax::syntax::Component; +use junco_core::kernel::verify as model; +use junco_core::verify::history_specs as language; +use junco_core::verify::history_specs::{EventView, Regex, Subst}; +use vstd::prelude::*; + +verus! { + +/// A search item `(Γ, q)`. +pub struct Item { pub constraint: Constraint, pub state: Regex } + +/// `(θ, w) ∈ W(I)` (`sec:search-state`). +pub open spec fn witness(d: NDomains, item: Item, theta: Subst, w: Seq) -> bool { + n_theta_ok(d, theta) && n_history_in(d, w) && sat_by(theta, item.constraint) && n_lang(theta, item.state, w) +} + +pub open spec fn no_witness(d: NDomains, item: Item) -> bool { + forall|theta: Subst, w: Seq| !#[trigger] witness(d, item, theta, w) +} + +/// `W(J) ⊆ W(I)`. +pub open spec fn witnesses_within(d: NDomains, j: Item, i: Item) -> bool { + forall|theta: Subst, w: Seq| #[trigger] witness(d, j, theta, w) ==> witness(d, i, theta, w) +} + +/// `W(I)` has a member of length `n` (used for the minimality argument). +pub open spec fn has_witness_of_length(d: NDomains, item: Item, n: nat) -> bool { + exists|theta: Subst, w: Seq| w.len() == n && #[trigger] witness(d, item, theta, w) +} + +// ----- atoms, assignments, successor cases (`def:atoms`, `def:realize`, `def:successors`, `alg:succ`) ----- + +/// An atom assignment; its domain is the atom set. +pub type Assignment = Map; + +/// `(θ, e)` realizes `α`. +pub open spec fn realizes(theta: Subst, e: EventView, alpha: Assignment) -> bool { + forall|p: model::Primitive| #[trigger] alpha.dom().contains(p) ==> alpha[p] == model::primitive_holds(theta, p, e) +} + +/// The finite set of `a` with `f(a)`; empty if there are infinitely many (every use is bounded by +/// a finite set, see `inclusion::lemma_set_new_bounded`). +pub open spec fn finite_set(f: spec_fn(A) -> bool) -> Set { + Set::new(f).unwrap_or(Set::empty()) +} + +/// `s` as a finite set; empty if `s` is infinite (every use is proved finite first). +pub open spec fn finite_of(s: ISet) -> Set { + Set::new_from_iset(s).unwrap_or(Set::empty()) +} + +/// `Π_q`: `(x_c, v)` such that `π_c = x_c` and `π_c = v` are both atoms. +pub open spec fn atom_pairs(atoms: Set) -> Pairs { + finite_set(|p: (Component, nat)| atoms.contains(model::Primitive::Eq(p.0, model::GTerm::Variable(p.0))) + && atoms.contains(model::Primitive::Eq(p.0, model::GTerm::Constant(p.1)))) +} + +/// `next` is the successor of `q` for `α`: `L_θ(next) = e⁻¹ L_θ(q)` whenever `(θ, e)` realizes `α` +/// (the implementation's `successor_entries_wf` in `history-semantics/src/progress.rs`). +pub open spec fn successor_ok(q: Regex, alpha: Assignment, next: Regex) -> bool { + forall|theta: Subst, e: EventView, w: Seq| language::event_wf(theta, theta.len()) && #[trigger] realizes(theta, e, alpha) + ==> (#[trigger] n_lang(theta, next, w) == n_lang(theta, q, seq![e] + w)) +} + +/// One successor case `(Γ', α, q')`. +pub struct Case { pub constraint: Constraint, pub alpha: Assignment, pub next: Regex } + +pub open spec fn case_item(c: Case) -> Item { Item { constraint: c.constraint, state: c.next } } + +/// The conclusion of Lemmas `lem:succ` and `lem:uniform`, stated over successor cases +/// (`app:mech-diff`), for a set of cases of `item`. +pub open spec fn steps_ok(d: NDomains, item: Item, cases: Set) -> bool { + &&& forall|c: Case| #[trigger] cases.contains(c) ==> { + &&& satisfiable(d, c.constraint) && entails(d, c.constraint, item.constraint) + &&& successor_ok(item.state, c.alpha, c.next) + // uniform realizability + &&& forall|theta: Subst| n_theta_ok(d, theta) && #[trigger] sat_by(theta, c.constraint) + ==> exists|e: EventView| n_event_in(d, e) && #[trigger] realizes(theta, e, c.alpha) + } + // every (θ, e) belongs to exactly one case + &&& forall|theta: Subst, e: EventView| n_theta_ok(d, theta) && #[trigger] n_event_in(d, e) && #[trigger] sat_by(theta, item.constraint) + ==> exists|c: Case| #[trigger] cases.contains(c) && sat_by(theta, c.constraint) && realizes(theta, e, c.alpha) + &&& forall|theta: Subst, e: EventView, c1: Case, c2: Case| n_theta_ok(d, theta) + && cases.contains(c1) && cases.contains(c2) && #[trigger] sat_by(theta, c1.constraint) && #[trigger] sat_by(theta, c2.constraint) + && #[trigger] realizes(theta, e, c1.alpha) && realizes(theta, e, c2.alpha) ==> c1 == c2 +} + +/// The paper's successors `succ(Γ, q)` as cases `(Γ', α, next(α))`, for an atom set and the +/// successors `next(α)`. +pub open spec fn paper_steps(d: NDomains, item: Item, atoms: Set, + cases_split: Set, next: spec_fn(Assignment) -> Regex) -> ISet { + ISet::new(|c: Case| cases_split.contains(c.constraint) && c.alpha.dom() == atoms && c.next == next(c.alpha) + && exists|theta: Subst, e: EventView| n_theta_ok(d, theta) && n_event_in(d, e) + && #[trigger] sat_by(theta, c.constraint) && #[trigger] realizes(theta, e, c.alpha)) +} + +/// The atoms determine `q`'s derivative: realizing the same assignment gives the same residual +/// language for bounded-arity valuations, including empty bindings (true for the atoms of +/// `δ(q)`'s conditions by Theorem Symbolic derivative correctness, `thm:sderiv`). +pub open spec fn atoms_complete(q: Regex, atoms: Set) -> bool { + forall|theta: Subst, e1: EventView, e2: EventView, w: Seq| + theta.len() <= history_syntax::MAX_ARITY + && (forall|p: model::Primitive| atoms.contains(p) ==> #[trigger] model::primitive_holds(theta, p, e1) == model::primitive_holds(theta, p, e2)) + ==> (#[trigger] n_lang(theta, q, seq![e1] + w) == #[trigger] n_lang(theta, q, seq![e2] + w)) +} + +/// Component-locality of atoms (`sec:events`): a variable atom compares a component only with the +/// candidate's value of the same component. The analyzer enforces it (`search.rs` `atom`). +pub open spec fn atoms_local(atoms: Set) -> bool { + forall|c: Component, c2: Component| #[trigger] atoms.contains(model::Primitive::Eq(c, model::GTerm::Variable(c2))) ==> c2 == c +} + +/// Every field and register read by an atom belongs to the event's arity. +pub open spec fn atoms_bounded(atoms: Set, arity: nat) -> bool { + forall|p: model::Primitive| #[trigger] atoms.contains(p) ==> match p { + model::Primitive::Eq(c, model::GTerm::Constant(_)) => c.0 < arity, + model::Primitive::Eq(c, model::GTerm::Variable(v)) => c.0 < arity && v.0 < arity, + } +} + +/// `Π` of the search: the paper's `Π_q` (`atom_pairs`), plus, for a register compared at a +/// component with a declared finite domain, every declared value (as `split_register` in +/// `history-analysis/src/constraint.rs` does). Without declared domains it is `Π_q`. +pub open spec fn domain_pairs(d: NDomains, atoms: Set) -> Pairs { + finite_set(|p: (Component, nat)| atom_pairs(atoms).contains(p) + || (atoms.contains(model::Primitive::Eq(p.0, model::GTerm::Variable(p.0))) + && match n_domain(d, p.0) { Some(values) => values.contains(p.1), None => false })) +} + +/// Lemmas `lem:succ` and `lem:uniform` (one statement over successor cases, `app:mech-diff`): +/// with `Γ` satisfiable, complete atoms, correct successors for every realizable assignment, and +/// any `Split(Γ; Π)` family, the successor cases are finite and satisfy `steps_ok`. Declared +/// finite domains are covered (`domain_pairs`), beyond the paper. +pub open spec fn stmt_successor_cases() -> bool { + forall|d: NDomains, item: Item, atoms: Set, cases_split: Set, + next: spec_fn(Assignment) -> Regex| + satisfiable(d, item.constraint) && atoms_local(atoms) && atoms_complete(item.state, atoms) + && atoms_bounded(atoms, d.len()) + && split_ok(d, item.constraint, domain_pairs(d, atoms), cases_split) + && (forall|alpha: Assignment| alpha.dom() == atoms ==> #[trigger] successor_ok(item.state, alpha, next(alpha))) + ==> #[trigger] paper_steps(d, item, atoms, cases_split, next).finite() + && steps_ok(d, item, finite_of(paper_steps(d, item, atoms, cases_split, next))) +} + +// ----- the breadth-first search (Algorithm Inclusion search, `alg:search`) ----- + +pub struct Node { pub item: Item, pub parent: Option<(nat, Assignment)>, pub depth: nat } + +/// The search state the implementation keeps: inserted nodes in insertion order (never removed) +/// and the number of expanded nodes. +pub struct Trace { pub nodes: Seq, pub expanded: nat } + +pub enum Outcome { Holds, Refuted(Constraint, Seq), Exhausted } + +pub open spec fn nullable_state(q: Regex) -> bool { language::nullable(q) } + +/// A successor item may be dropped at insertion: its state is `∅`, or it has no witnesses +/// (dead), or an already inserted node of depth at most `depth` has all its witnesses +/// (an identical item or a dominating one). +pub open spec fn may_discard(d: NDomains, nodes: Seq, j: Item, depth: nat) -> bool { + ||| j.state == Regex::::Empty + ||| no_witness(d, j) + ||| exists|k: int| 0 <= k < nodes.len() && nodes[k].depth <= depth && #[trigger] witnesses_within(d, j, nodes[k].item) +} + +/// Assignments along the parent chain of node `n`, oldest first (`alg:search`). +pub open spec fn chain(nodes: Seq, n: int, fuel: nat) -> Seq + decreases fuel, +{ + if fuel == 0 || n < 0 || n >= nodes.len() { Seq::empty() } else { + match nodes[n].parent { + None => Seq::empty(), + Some((p, alpha)) => chain(nodes, p as int, (fuel - 1) as nat).push(alpha), + } + } +} + +/// Node `j` is a successor case of an expanded earlier node, one level deeper. +pub open spec fn parent_ok(cases_of: spec_fn(Item) -> Set, t: Trace, j: int) -> bool { + match t.nodes[j].parent { + None => false, + Some((p, alpha)) => p < t.expanded && p < j && t.nodes[j].depth == t.nodes[p as int].depth + 1 + && exists|c: Case| #[trigger] cases_of(t.nodes[p as int].item).contains(c) && c.alpha == alpha + && t.nodes[j].item == case_item(c), + } +} + +/// `t` is a trace of the search from `(Γ₀, q₀)` that enumerates successor cases with `cases_of`. +pub open spec fn trace_wf(d: NDomains, g0: Constraint, q0: Regex, + cases_of: spec_fn(Item) -> Set, t: Trace) -> bool { + let nodes = t.nodes; + &&& t.expanded <= nodes.len() + // the root is inserted unless it may be discarded + &&& if nodes.len() == 0 { may_discard(d, nodes, Item { constraint: g0, state: q0 }, 0) } + else { nodes[0] == (Node { item: Item { constraint: g0, state: q0 }, parent: None, depth: 0 }) } + // every other node is a successor case of an expanded node, one level deeper + &&& forall|j: int| 0 < j < nodes.len() ==> #[trigger] parent_ok(cases_of, t, j) + &&& forall|i: int, j: int| 0 <= i < j < nodes.len() ==> #[trigger] nodes[i].depth <= #[trigger] nodes[j].depth + && nodes[i].item != nodes[j].item + // expanded nodes are not nullable, and every one of their cases was inserted or discarded + &&& forall|p: int| 0 <= p < t.expanded ==> !nullable_state(#[trigger] nodes[p].item.state) + && forall|c: Case| #[trigger] cases_of(nodes[p].item).contains(c) ==> + (exists|j: int| 0 < j < nodes.len() && nodes[j].parent == Some((p as nat, c.alpha)) && nodes[j].item == case_item(c)) + || may_discard(d, nodes, case_item(c), nodes[p].depth + 1) +} + +/// The outcome a trace returns: a counterexample from the first unexpanded node if nullable, +/// `Holds` if every node was expanded, and `Exhausted` from a limit at any point. +pub open spec fn trace_outcome(t: Trace, outcome: Outcome) -> bool { + match outcome { + Outcome::Holds => t.expanded == t.nodes.len(), + Outcome::Refuted(g, letters) => t.expanded < t.nodes.len() && nullable_state(t.nodes[t.expanded as int].item.state) + && g == t.nodes[t.expanded as int].item.constraint + && letters == chain(t.nodes, t.expanded as int, t.nodes[t.expanded as int].depth), + Outcome::Exhausted => true, + } +} + +/// `(θ, u)` follows the recorded assignments. +pub open spec fn follows(d: NDomains, letters: Seq, theta: Subst, u: Seq) -> bool { + u.len() == letters.len() && n_history_in(d, u) + && forall|j: int| 0 <= j < u.len() ==> #[trigger] realizes(theta, u[j], letters[j]) +} + +/// What a returned outcome means for the query `r ⊑_{Γ₀} s` (Theorem Inclusion search correctness, `thm:search`). +pub open spec fn outcome_ok(d: NDomains, g0: Constraint, r: Regex, s: Regex, outcome: Outcome) -> bool { + match outcome { + Outcome::Holds => included_under(d, g0, r, s), + Outcome::Refuted(g, letters) => + // realizable, and every realization is a counterexample + (exists|theta: Subst| n_theta_ok(d, theta) && #[trigger] sat_by(theta, g)) + && (forall|theta: Subst| n_theta_ok(d, theta) && #[trigger] sat_by(theta, g) + ==> exists|u: Seq| #[trigger] follows(d, letters, theta, u)) + && (forall|theta: Subst, u: Seq| n_theta_ok(d, theta) && sat_by(theta, g) && #[trigger] follows(d, letters, theta, u) + ==> inclusion_cex(d, g0, r, s, theta, u)) + // minimum length for this query + && no_cex_shorter(d, g0, r, s, letters.len()), + Outcome::Exhausted => true, + } +} + +/// `q₀ = N(r & ¬s)` has the language of `r & ¬s`. +pub open spec fn initial_ok(q0: Regex, r: Regex, s: Regex) -> bool { + forall|theta: Subst, w: Seq| language::event_wf(theta, theta.len()) + ==> (#[trigger] n_lang(theta, q0, w) == (n_lang(theta, r, w) && !n_lang(theta, s, w))) +} + +/// Inclusion search correctness: every returned trace satisfies `outcome_ok`, with or without +/// pruning, for undeclared and declared finite domains alike. Complete successor cases are +/// required only for expanded trace nodes, exactly the premise established by the executable. +pub open spec fn stmt_search_correct() -> bool { + forall|d: NDomains, g0: Constraint, r: Regex, s: Regex, q0: Regex, + cases_of: spec_fn(Item) -> Set, t: Trace, outcome: Outcome| + satisfiable(d, g0) && #[trigger] initial_ok(q0, r, s) + && trace_steps_ok(d, cases_of, t) + && #[trigger] trace_wf(d, g0, q0, cases_of, t) && #[trigger] trace_outcome(t, outcome) + ==> outcome_ok(d, g0, r, s, outcome) +} + +/// Items reachable from `start` through successor cases, in `n` steps. +pub open spec fn reachable_item(cases_of: spec_fn(Item) -> Set, start: Item, n: nat, j: Item) -> bool + decreases n, +{ + if n == 0 { j == start } else { + exists|i: Item, c: Case| reachable_item(cases_of, start, (n - 1) as nat, i) + && #[trigger] cases_of(i).contains(c) && case_item(c) == j + } +} + +/// Hypothesis of termination: finitely many items are reachable. It follows from finitely many +/// reachable states (`finiteness::stmt_items_from_states`): constraints are `Γ₀` plus literals +/// over the atoms of reachable states. For the paper's model normalizer the states are bounded by +/// Lemma Finitely many residuals (`lem:finite-states`); for the implementation by the same +/// lemma instantiated with `verify::finite_impl::m_impl` (`finiteness::theorem_impl_finitely_many_items`, +/// with the implemented step abstracted by `finiteness::lemma_impl_successor_abstracts`). +pub open spec fn items_within(cases_of: spec_fn(Item) -> Set, start: Item, f: Set) -> bool { + forall|n: nat, j: Item| #[trigger] reachable_item(cases_of, start, n, j) ==> f.contains(j) +} + +pub open spec fn finitely_many_items(cases_of: spec_fn(Item) -> Set, start: Item) -> bool { + exists|f: Set| #[trigger] items_within(cases_of, start, f) +} + +/// Every trace from `(Γ₀, q₀)` has at most `bound` nodes. +pub open spec fn traces_bounded(g0: Constraint, q0: Regex, cases_of: spec_fn(Item) -> Set, bound: nat) -> bool { + forall|d: NDomains, t: Trace| #[trigger] trace_wf(d, g0, q0, cases_of, t) ==> t.nodes.len() <= bound +} + +/// Theorem Inclusion search correctness (`thm:search`), termination, *conditional* on finitely many reachable items: no trace has more +/// than `bound` nodes (nodes are distinct reachable items), so the search returns after at most +/// `bound` expansions. +pub open spec fn stmt_search_terminates() -> bool { + forall|g0: Constraint, q0: Regex, cases_of: spec_fn(Item) -> Set| + #[trigger] finitely_many_items(cases_of, Item { constraint: g0, state: q0 }) + ==> exists|bound: nat| #[trigger] traces_bounded(g0, q0, cases_of, bound) +} + +// ----- proofs ----- + +pub open spec fn induced_assignment(theta: Subst, e: EventView, + atoms: Set) -> Assignment { + Map::new(atoms, |p: model::Primitive| model::primitive_holds(theta, p, e)) +} + +pub proof fn lemma_induced_realizes(theta: Subst, e: EventView, atoms: Set) + ensures induced_assignment(theta, e, atoms).dom() == atoms, + realizes(theta, e, induced_assignment(theta, e, atoms)), +{} + +pub proof fn lemma_realizes_unique(theta: Subst, e: EventView, + atoms: Set, a: Assignment, b: Assignment) + requires a.dom() == atoms, b.dom() == atoms, realizes(theta, e, a), realizes(theta, e, b), + ensures a == b, +{ + assert(a =~= b); +} + +pub proof fn lemma_paper_steps_finite(d: NDomains, item: Item, atoms: Set, + cases_split: Set, next: spec_fn(Assignment) -> Regex) + ensures paper_steps(d, item, atoms, cases_split, next).finite(), +{ + crate::verify::finite_states::lemma_powerset_finite(atoms); + let pw = ISet::new(|s: Set| s.subset_of(atoms)); + let assignment = |s: Set| Map::new(atoms, + |p: model::Primitive| s.contains(p)); + pw.lemma_map_finite(assignment); + let assignments = pw.map(assignment); + let maker = |g: Constraint| assignments.map(|a: Assignment| + Case { constraint: g, alpha: a, next: next(a) }); + assert forall|g: Constraint| cases_split.contains(g) implies #[trigger] maker(g).finite() by { + assignments.lemma_map_finite(|a: Assignment| + Case { constraint: g, alpha: a, next: next(a) }); + } + crate::verify::finite_states::lemma_big_union_finite(cases_split, maker); + let bound = ISet::new(|c: Case| exists|g: Constraint| + cases_split.contains(g) && #[trigger] maker(g).contains(c)); + assert forall|c: Case| paper_steps(d, item, atoms, cases_split, next).contains(c) + implies bound.contains(c) by { + let yes = atoms.filter(|p: model::Primitive| c.alpha[p]); + assert(yes.subset_of(atoms)); + assert(assignment(yes) =~= c.alpha); + assert(pw.contains(yes)); + assert(assignments.contains(c.alpha)); + assert(maker(c.constraint).contains(c)); + } + vstd::iset_lib::lemma_iset_subset_finite(bound, + paper_steps(d, item, atoms, cases_split, next)); +} + +pub proof fn lemma_node_reachable(d: NDomains, g0: Constraint, q0: Regex, + cases_of: spec_fn(Item) -> Set, t: Trace, j: int) + requires trace_wf(d, g0, q0, cases_of, t), 0 <= j < t.nodes.len(), + ensures reachable_item(cases_of, Item { constraint: g0, state: q0 }, + t.nodes[j].depth, t.nodes[j].item), + decreases j, +{ + if j > 0 { + assert(parent_ok(cases_of, t, j)); + let (p, alpha) = t.nodes[j].parent.unwrap(); + let c = choose|c: Case| #[trigger] cases_of(t.nodes[p as int].item).contains(c) + && c.alpha == alpha && t.nodes[j].item == case_item(c); + lemma_node_reachable(d, g0, q0, cases_of, t, p as int); + assert(reachable_item(cases_of, Item { constraint: g0, state: q0 }, + (t.nodes[j].depth - 1) as nat, t.nodes[p as int].item)); + } +} + +pub proof fn lemma_chain_len(d: NDomains, g0: Constraint, q0: Regex, + cases_of: spec_fn(Item) -> Set, t: Trace, j: int, fuel: nat) + requires trace_wf(d, g0, q0, cases_of, t), 0 <= j < t.nodes.len(), + fuel >= t.nodes[j].depth, + ensures chain(t.nodes, j, fuel).len() == t.nodes[j].depth, + chain(t.nodes, j, fuel) == chain(t.nodes, j, t.nodes[j].depth), + decreases j, +{ + if j > 0 { + assert(parent_ok(cases_of, t, j)); + let (p, alpha) = t.nodes[j].parent.unwrap(); + lemma_chain_len(d, g0, q0, cases_of, t, p as int, (fuel - 1) as nat); + lemma_chain_len(d, g0, q0, cases_of, t, p as int, + (t.nodes[j].depth - 1) as nat); + } +} + +pub proof fn lemma_trace_nodes_bounded(g0: Constraint, q0: Regex, + cases_of: spec_fn(Item) -> Set, f: Set, d: NDomains, t: Trace) + requires items_within(cases_of, Item { constraint: g0, state: q0 }, f), + trace_wf(d, g0, q0, cases_of, t), + ensures t.nodes.len() <= f.len(), +{ + let items = t.nodes.map(|i: int, n: Node| n.item); + assert(items.no_duplicates()) by { + assert forall|i: int, j: int| 0 <= i < items.len() && 0 <= j < items.len() + && i != j implies items[i] != items[j] by { + if i < j { + assert(t.nodes[i].depth <= t.nodes[j].depth); + assert(t.nodes[i].item != t.nodes[j].item); + } else { + assert(t.nodes[j].depth <= t.nodes[i].depth); + assert(t.nodes[j].item != t.nodes[i].item); + } + } + } + assert forall|j: int| 0 <= j < items.len() implies f.contains(#[trigger] items[j]) by { + lemma_node_reachable(d, g0, q0, cases_of, t, j); + } + crate::verify::finite_impl::lemma_nodup_len(items, f); +} + +pub proof fn theorem_search_terminates() + ensures stmt_search_terminates(), +{ + assert forall|g0: Constraint, q0: Regex, + cases_of: spec_fn(Item) -> Set| + #[trigger] finitely_many_items(cases_of, Item { constraint: g0, state: q0 }) + implies exists|bound: nat| #[trigger] traces_bounded(g0, q0, cases_of, bound) by { + let f = choose|f: Set| #[trigger] items_within(cases_of, + Item { constraint: g0, state: q0 }, f); + assert(traces_bounded(g0, q0, cases_of, f.len())) by { + assert forall|d: NDomains, t: Trace| #[trigger] trace_wf(d, g0, q0, cases_of, t) + implies t.nodes.len() <= f.len() by { + lemma_trace_nodes_bounded(g0, q0, cases_of, f, d, t); + } + } + } +} + +pub open spec fn atom_pair_image(p: model::Primitive) -> (Component, nat) { + match p { + model::Primitive::Eq(c, model::GTerm::Constant(v)) => (c, v), + model::Primitive::Eq(c, model::GTerm::Variable(_)) => (c, 0), + } +} + +pub proof fn lemma_atom_pairs_members(atoms: Set) + ensures forall|p: (Component, nat)| #[trigger] atom_pairs(atoms).contains(p) + <==> (atoms.contains(model::Primitive::Eq(p.0, model::GTerm::Variable(p.0))) + && atoms.contains(model::Primitive::Eq(p.0, model::GTerm::Constant(p.1)))), +{ + let image = |p: model::Primitive| atom_pair_image(p); + let bound = atoms.to_iset().map(image); + atoms.to_iset().lemma_map_finite(image); + let f = |p: (Component, nat)| + atoms.contains(model::Primitive::Eq(p.0, model::GTerm::Variable(p.0))) + && atoms.contains(model::Primitive::Eq(p.0, model::GTerm::Constant(p.1))); + assert forall|p: (Component, nat)| f(p) implies bound.contains(p) by { + let a = model::Primitive::Eq(p.0, model::GTerm::Constant(p.1)); + assert(atom_pair_image(a) == p); + } + lemma_set_new_bounded(f, bound); +} + +/// Finite union of the per-coordinate declared-domain pairs. +pub open spec fn domain_pair_bound(d: NDomains) -> ISet<(Component, nat)> + decreases d.len(), +{ + if d.len() == 0 { ISet::empty() } else { + let c = Component((d.len() - 1) as u8); + domain_pair_bound(d.drop_last()).union( + d.last().unwrap_or(Set::empty()).to_iset().map(|v: nat| (c, v))) + } +} + +pub proof fn lemma_domain_pair_bound(d: NDomains) + ensures domain_pair_bound(d).finite(), + forall|p: (Component, nat)| (n_domain(d, p.0) matches Some(values) && values.contains(p.1)) + ==> #[trigger] domain_pair_bound(d).contains(p), + decreases d.len(), +{ + broadcast use vstd::set::lemma_to_iset_finite, vstd::iset::lemma_iset_union_finite; + if d.len() > 0 { + let prefix = d.drop_last(); + lemma_domain_pair_bound(prefix); + let c = Component((d.len() - 1) as u8); + let values = d.last().unwrap_or(Set::empty()); + values.to_iset().lemma_map_finite(|v: nat| (c, v)); + assert forall|p: (Component, nat)| (n_domain(d, p.0) matches Some(vs) && vs.contains(p.1)) + implies #[trigger] domain_pair_bound(d).contains(p) by { + assert(p.0.0 < d.len()); + if p.0.0 < prefix.len() { + assert(n_domain(prefix, p.0) == n_domain(d, p.0)); + } else { + assert(p.0 == c); + assert(n_domain(d, p.0) == d.last()); + assert(values.to_iset().map(|v: nat| (c, v)).contains(p)); + } + } + } +} + +pub proof fn lemma_domain_pairs_members(d: NDomains, atoms: Set) + ensures forall|p: (Component, nat)| #[trigger] domain_pairs(d, atoms).contains(p) + <==> (atom_pairs(atoms).contains(p) + || (atoms.contains(model::Primitive::Eq(p.0, model::GTerm::Variable(p.0))) + && match n_domain(d, p.0) { + Some(values) => values.contains(p.1), None => false, + })), +{ + broadcast use vstd::set::lemma_to_iset_finite, vstd::iset::lemma_iset_union_finite; + lemma_domain_pair_bound(d); + let bound = atom_pairs(atoms).to_iset().union(domain_pair_bound(d)); + let f = |p: (Component, nat)| atom_pairs(atoms).contains(p) + || (atoms.contains(model::Primitive::Eq(p.0, model::GTerm::Variable(p.0))) + && match n_domain(d, p.0) { Some(values) => values.contains(p.1), None => false }); + assert forall|p: (Component, nat)| f(p) implies bound.contains(p) by { + if !atom_pairs(atoms).contains(p) { + assert(domain_pair_bound(d).contains(p)); + } + } + lemma_set_new_bounded(f, bound); +} + +pub proof fn lemma_decided_agreement(d: NDomains, g: Constraint, k: Component, v: nat, + theta0: Subst, theta: Subst) + requires decides(d, g, k, v), n_theta_ok(d, theta0), n_theta_ok(d, theta), + sat_by(theta0, g), sat_by(theta, g), + ensures (language::field_value(theta0, k) == v) == (language::field_value(theta, k) == v), +{ + let eq = eq_literal(k, v); + let ne = ne_literal(k, v); + if entails(d, g, set![eq]) { + assert(sat_by(theta0, set![eq])); + assert(sat_by(theta, set![eq])); + assert(set![eq].contains(eq)); + } else { + assert(sat_by(theta0, set![ne])); + assert(sat_by(theta, set![ne])); + assert(set![ne].contains(ne)); + } +} + +pub proof fn lemma_finite_nat_bound(s: Set) -> (bound: nat) + ensures forall|v: nat| #[trigger] s.contains(v) ==> v < bound, + decreases s.len(), +{ + if s.len() == 0 { + s.lemma_len0_is_empty(); + assert forall|v: nat| #[trigger] s.contains(v) implies v < 0nat by {} + 0 + } else { + let x = s.choose(); + let b = lemma_finite_nat_bound(s.remove(x)); + assert forall|v: nat| #[trigger] s.contains(v) implies v < b + x + 1 by { + if v != x { assert(s.remove(x).contains(v)); } + } + b + x + 1 + } +} + +/// One coordinate of a realization transported to a different candidate valuation. +pub open spec fn field_realizes(d: NDomains, atoms: Set, alpha: Assignment, + theta: Subst, e0: EventView, k: Component, v: nat) -> bool { + &&& (n_domain(d, k) matches Some(values) ==> values.contains(v)) + &&& forall|p: model::Primitive| #[trigger] atoms.contains(p) + && (p matches model::Primitive::Eq(c, _) && c == k) + ==> alpha[p] == model::primitive_holds(theta, p, e0.update(k.0 as int, v)) +} + +pub proof fn lemma_transport_field(d: NDomains, atoms: Set, pi: Pairs, + g: Constraint, alpha: Assignment, theta0: Subst, e0: EventView, theta: Subst, + k: Component) -> (v: nat) + requires atoms_local(atoms), alpha.dom() == atoms, k.0 < d.len(), + pi == domain_pairs(d, atoms), + forall|p: (Component, nat)| pi.contains(p) ==> #[trigger] decides(d, g, p.0, p.1), + n_theta_ok(d, theta0), n_event_in(d, e0), sat_by(theta0, g), realizes(theta0, e0, alpha), + n_theta_ok(d, theta), sat_by(theta, g), + ensures field_realizes(d, atoms, alpha, theta, e0, k, v), +{ + lemma_atom_pairs_members(atoms); + lemma_domain_pairs_members(d, atoms); + let reg = model::Primitive::Eq(k, model::GTerm::Variable(k)); + let x0 = language::field_value(theta0, k); + let x = language::field_value(theta, k); + let old = language::field_value(e0, k); + let v; + if n_domain(d, k) is Some { + if atoms.contains(reg) { + let values = n_domain(d, k).unwrap(); + assert(values.contains(x0)); + assert(pi.contains((k, x0))); + lemma_decided_agreement(d, g, k, x0, theta0, theta); + assert(x == x0); + } + v = old; + } else if atoms.contains(reg) && alpha[reg] { + v = x; + } else if exists|c: nat| atoms.contains(model::Primitive::Eq(k, model::GTerm::Constant(c))) + && alpha[model::Primitive::Eq(k, model::GTerm::Constant(c))] { + let c = choose|c: nat| atoms.contains(model::Primitive::Eq(k, model::GTerm::Constant(c))) + && alpha[model::Primitive::Eq(k, model::GTerm::Constant(c))]; + assert(old == c); + if atoms.contains(reg) { + assert(pi.contains((k, c))); + lemma_decided_agreement(d, g, k, c, theta0, theta); + assert(x != c); + } + v = c; + } else { + let codes = atoms.map(|p: model::Primitive| atom_pair_image(p).1).insert(x); + let bound = lemma_finite_nat_bound(codes); + assert(codes.contains(x)); + assert(x < bound); + v = bound; + assert(v != x); + assert forall|c: nat| atoms.contains(model::Primitive::Eq(k, model::GTerm::Constant(c))) + implies v != c by { + assert(codes.contains(c)); + } + } + let event = e0.update(k.0 as int, v); + assert(language::field_value(event, k) == v); + assert forall|p: model::Primitive| #[trigger] atoms.contains(p) + && (p matches model::Primitive::Eq(c, _) && c == k) + implies alpha[p] == model::primitive_holds(theta, p, event) by { + match p { + model::Primitive::Eq(c, model::GTerm::Variable(c2)) => { + assert(c == k && c2 == k); + assert(p == reg); + }, + model::Primitive::Eq(c, model::GTerm::Constant(code)) => { + assert(alpha[p] == (old == code)); + if n_domain(d, k) is None && atoms.contains(reg) && alpha[reg] { + assert(old == x0); + assert(pi.contains((k, code))); + lemma_decided_agreement(d, g, k, code, theta0, theta); + } + }, + } + } + v +} + +pub proof fn lemma_transport_realizer(d: NDomains, item: Item, atoms: Set, + pi: Pairs, cases_split: Set, c: Case, theta: Subst) + requires atoms_local(atoms), atoms_bounded(atoms, d.len()), + split_ok(d, item.constraint, pi, cases_split), + pi == domain_pairs(d, atoms), + cases_split.contains(c.constraint), c.alpha.dom() == atoms, + exists|t0: Subst, e0: EventView| n_theta_ok(d, t0) && n_event_in(d, e0) + && sat_by(t0, c.constraint) && realizes(t0, e0, c.alpha), + n_theta_ok(d, theta), sat_by(theta, c.constraint), + ensures exists|e: EventView| n_event_in(d, e) && #[trigger] realizes(theta, e, c.alpha), +{ + let (t0, e0) = choose|t0: Subst, e0: EventView| n_theta_ok(d, t0) && n_event_in(d, e0) + && sat_by(t0, c.constraint) && realizes(t0, e0, c.alpha); + let pick = |i: int| choose|v: nat| + #[trigger] field_realizes(d, atoms, c.alpha, theta, e0, Component(i as u8), v); + let e = Seq::new(d.len(), pick); + assert forall|i: int| #![trigger e[i]] 0 <= i < d.len() implies + field_realizes(d, atoms, c.alpha, theta, e0, Component(i as u8), e[i]) by { + let k = Component(i as u8); + assert(k.0 as int == i); + let v = lemma_transport_field(d, atoms, pi, c.constraint, c.alpha, t0, e0, theta, k); + assert(field_realizes(d, atoms, c.alpha, theta, e0, k, v)); + assert(exists|v: nat| #[trigger] field_realizes(d, atoms, c.alpha, theta, e0, k, v)); + } + assert(n_event_in(d, e)) by { + assert forall|i: int| #![trigger d[i], e[i]] 0 <= i < d.len() implies + (d[i] matches Some(values) ==> values.contains(e[i])) by { + let k = Component(i as u8); + assert(k.0 as int == i); + assert(field_realizes(d, atoms, c.alpha, theta, e0, k, e[i])); + } + } + assert(realizes(theta, e, c.alpha)) by { + assert forall|p: model::Primitive| #[trigger] c.alpha.dom().contains(p) + implies c.alpha[p] == model::primitive_holds(theta, p, e) by { + match p { + model::Primitive::Eq(k, term) => { + assert(k.0 < d.len()); + assert(field_realizes(d, atoms, c.alpha, theta, e0, k, e[k.0 as int])); + assert(c.alpha[p] == model::primitive_holds(theta, p, + e0.update(k.0 as int, e[k.0 as int]))); + }, + } + } + } +} + +pub proof fn lemma_successor_cases_common(d: NDomains, item: Item, + atoms: Set, pi: Pairs, cases_split: Set, + next: spec_fn(Assignment) -> Regex) + requires atoms_local(atoms), atoms_bounded(atoms, d.len()), + split_ok(d, item.constraint, pi, cases_split), + pi == domain_pairs(d, atoms), + forall|alpha: Assignment| alpha.dom() == atoms + ==> #[trigger] successor_ok(item.state, alpha, next(alpha)), + ensures paper_steps(d, item, atoms, cases_split, next).finite(), + steps_ok(d, item, finite_of(paper_steps(d, item, atoms, cases_split, next))), +{ + hide(language::numeric_lang); + hide(successor_ok); + hide(realizes); + hide(n_theta_ok); + hide(n_event_in); + hide(atoms_local); + hide(atom_pairs); + hide(domain_pairs); + hide(satisfiable); + hide(entails); + broadcast use vstd::set::lemma_set_new_from_iset; + lemma_paper_steps_finite(d, item, atoms, cases_split, next); + let cases = finite_of(paper_steps(d, item, atoms, cases_split, next)); + assert(cases.to_iset() == paper_steps(d, item, atoms, cases_split, next)); + assert forall|c: Case| #[trigger] cases.contains(c) implies { + &&& satisfiable(d, c.constraint) && entails(d, c.constraint, item.constraint) + &&& successor_ok(item.state, c.alpha, c.next) + &&& forall|theta: Subst| n_theta_ok(d, theta) && #[trigger] sat_by(theta, c.constraint) + ==> exists|e: EventView| n_event_in(d, e) && #[trigger] realizes(theta, e, c.alpha) + } by { + assert(paper_steps(d, item, atoms, cases_split, next).contains(c)); + assert forall|theta: Subst| n_theta_ok(d, theta) && #[trigger] sat_by(theta, c.constraint) + implies exists|e: EventView| n_event_in(d, e) && #[trigger] realizes(theta, e, c.alpha) by { + lemma_transport_realizer(d, item, atoms, pi, cases_split, c, theta); + } + } + assert forall|theta: Subst, e: EventView| n_theta_ok(d, theta) + && #[trigger] n_event_in(d, e) && #[trigger] sat_by(theta, item.constraint) + implies exists|c: Case| #[trigger] cases.contains(c) + && sat_by(theta, c.constraint) && realizes(theta, e, c.alpha) by { + let g = choose|g: Constraint| #[trigger] cases_split.contains(g) && sat_by(theta, g); + let alpha = induced_assignment(theta, e, atoms); + lemma_induced_realizes(theta, e, atoms); + let c = Case { constraint: g, alpha, next: next(alpha) }; + assert(paper_steps(d, item, atoms, cases_split, next).contains(c)); + assert(cases.contains(c)); + } + assert forall|theta: Subst, e: EventView, c1: Case, c2: Case| n_theta_ok(d, theta) + && cases.contains(c1) && cases.contains(c2) && #[trigger] sat_by(theta, c1.constraint) + && #[trigger] sat_by(theta, c2.constraint) && #[trigger] realizes(theta, e, c1.alpha) + && realizes(theta, e, c2.alpha) implies c1 == c2 by { + assert(paper_steps(d, item, atoms, cases_split, next).contains(c1)); + assert(paper_steps(d, item, atoms, cases_split, next).contains(c2)); + assert(c1.constraint == c2.constraint); + lemma_realizes_unique(theta, e, atoms, c1.alpha, c2.alpha); + } +} + +pub proof fn theorem_successor_cases() + ensures stmt_successor_cases(), +{ + hide(language::numeric_lang); + hide(successor_ok); + hide(atoms_complete); + hide(steps_ok); + hide(paper_steps); + assert forall|d: NDomains, item: Item, atoms: Set, + cases_split: Set, next: spec_fn(Assignment) -> Regex| + satisfiable(d, item.constraint) && atoms_local(atoms) && atoms_complete(item.state, atoms) + && atoms_bounded(atoms, d.len()) + && split_ok(d, item.constraint, domain_pairs(d, atoms), cases_split) + && (forall|alpha: Assignment| alpha.dom() == atoms + ==> #[trigger] successor_ok(item.state, alpha, next(alpha))) + implies #[trigger] paper_steps(d, item, atoms, cases_split, next).finite() + && steps_ok(d, item, finite_of(paper_steps(d, item, atoms, cases_split, next))) by { + lemma_successor_cases_common(d, item, atoms, domain_pairs(d, atoms), cases_split, next); + } +} + +/// Only expanded nodes need complete cases; an implementation may retain their ghost evidence. +pub open spec fn trace_steps_ok(d: NDomains, cases_of: spec_fn(Item) -> Set, + t: Trace) -> bool { + forall|p: int| 0 <= p < t.expanded ==> #[trigger] steps_ok(d, t.nodes[p].item, + cases_of(t.nodes[p].item)) +} + +pub proof fn lemma_follows_push(d: NDomains, letters: Seq, theta: Subst, + u: Seq, alpha: Assignment, e: EventView) + requires follows(d, letters, theta, u), n_event_in(d, e), realizes(theta, e, alpha), + ensures follows(d, letters.push(alpha), theta, u.push(e)), +{ + assert(n_history_in(d, u.push(e))) by { + assert forall|i: int| 0 <= i < u.push(e).len() + implies #[trigger] n_event_in(d, u.push(e)[i]) by { + if i < u.len() { assert(u.push(e)[i] == u[i]); } + } + } + assert forall|i: int| 0 <= i < u.push(e).len() + implies #[trigger] realizes(theta, u.push(e)[i], letters.push(alpha)[i]) by { + if i < u.len() { assert(u.push(e)[i] == u[i]); } + } +} + +pub proof fn lemma_follows_unpush(d: NDomains, letters: Seq, theta: Subst, + u: Seq, alpha: Assignment) + requires follows(d, letters.push(alpha), theta, u), + ensures follows(d, letters, theta, u.drop_last()), n_event_in(d, u.last()), + realizes(theta, u.last(), alpha), u.drop_last().push(u.last()) == u, +{ + assert(u.len() > 0); + assert(u.drop_last().push(u.last()) =~= u); + assert(n_history_in(d, u.drop_last())) by { + assert forall|i: int| 0 <= i < u.drop_last().len() + implies #[trigger] n_event_in(d, u.drop_last()[i]) by { + assert(u.drop_last()[i] == u[i]); + } + } + assert forall|i: int| 0 <= i < u.drop_last().len() + implies #[trigger] realizes(theta, u.drop_last()[i], letters[i]) by { + assert(u.drop_last()[i] == u[i]); + assert(letters.push(alpha)[i] == letters[i]); + } + assert(realizes(theta, u[u.len() - 1], letters.push(alpha)[letters.len() as int])); +} + +pub proof fn lemma_node_realizable(d: NDomains, g0: Constraint, q0: Regex, + cases_of: spec_fn(Item) -> Set, t: Trace, j: int) + requires satisfiable(d, g0), trace_steps_ok(d, cases_of, t), + trace_wf(d, g0, q0, cases_of, t), 0 <= j < t.nodes.len(), + ensures entails(d, t.nodes[j].item.constraint, g0), + satisfiable(d, t.nodes[j].item.constraint), + forall|theta: Subst| n_theta_ok(d, theta) && sat_by(theta, t.nodes[j].item.constraint) + ==> exists|u: Seq| #[trigger] follows(d, + chain(t.nodes, j, t.nodes[j].depth), theta, u), + decreases j, +{ + hide(language::numeric_lang); + hide(realizes); + hide(successor_ok); + hide(follows); + hide(n_history_in); + hide(n_event_in); + hide(n_theta_ok); + hide(satisfiable); + hide(entails); + hide(sat_by); + lemma_chain_len(d, g0, q0, cases_of, t, j, t.nodes[j].depth); + if j == 0 { + assert(chain(t.nodes, j, t.nodes[j].depth) == Seq::::empty()); + assert(entails(d, g0, g0)) by { reveal(entails); } + assert forall|theta: Subst| n_theta_ok(d, theta) && sat_by(theta, g0) + implies exists|u: Seq| #[trigger] follows(d, + chain(t.nodes, j, t.nodes[j].depth), theta, u) by { + assert(follows(d, Seq::empty(), theta, Seq::empty())) by { + reveal(follows); + reveal(n_history_in); + } + } + } else { + assert(parent_ok(cases_of, t, j)); + let (p, alpha) = t.nodes[j].parent.unwrap(); + let c = choose|c: Case| #[trigger] cases_of(t.nodes[p as int].item).contains(c) + && c.alpha == alpha && t.nodes[j].item == case_item(c); + assert(steps_ok(d, t.nodes[p as int].item, cases_of(t.nodes[p as int].item))); + lemma_node_realizable(d, g0, q0, cases_of, t, p as int); + lemma_entails_trans(d, c.constraint, t.nodes[p as int].item.constraint, g0); + lemma_chain_len(d, g0, q0, cases_of, t, p as int, + (t.nodes[j].depth - 1) as nat); + let prefix = chain(t.nodes, p as int, t.nodes[p as int].depth); + assert(chain(t.nodes, j, t.nodes[j].depth) == prefix.push(alpha)); + assert forall|theta: Subst| n_theta_ok(d, theta) && sat_by(theta, c.constraint) + implies exists|u: Seq| #[trigger] follows(d, + chain(t.nodes, j, t.nodes[j].depth), theta, u) by { + assert(sat_by(theta, t.nodes[p as int].item.constraint)) by { reveal(entails); } + let u = choose|u: Seq| #[trigger] follows(d, prefix, theta, u); + let e = choose|e: EventView| n_event_in(d, e) && #[trigger] realizes(theta, e, c.alpha); + lemma_follows_push(d, prefix, theta, u, alpha, e); + } + } +} + +// Keep the suffix explicit to avoid recursively generating larger SMT language terms. +pub proof fn lemma_node_language(d: NDomains, g0: Constraint, q0: Regex, + cases_of: spec_fn(Item) -> Set, t: Trace, j: int, theta: Subst, + u: Seq, w: Seq) + requires trace_steps_ok(d, cases_of, t), trace_wf(d, g0, q0, cases_of, t), + 0 <= j < t.nodes.len(), n_theta_ok(d, theta), sat_by(theta, t.nodes[j].item.constraint), + follows(d, chain(t.nodes, j, t.nodes[j].depth), theta, u), + ensures n_lang(theta, t.nodes[j].item.state, w) == n_lang(theta, q0, u + w), + decreases j, +{ + hide(language::numeric_lang); + hide(realizes); + hide(successor_ok); + hide(follows); + hide(n_history_in); + hide(n_event_in); + hide(n_theta_ok); + hide(satisfiable); + hide(entails); + hide(sat_by); + lemma_chain_len(d, g0, q0, cases_of, t, j, t.nodes[j].depth); + if j == 0 { + assert(u =~= Seq::::empty()) by { reveal(follows); } + assert(u + w =~= w); + } else { + assert(parent_ok(cases_of, t, j)); + let (p, alpha) = t.nodes[j].parent.unwrap(); + let c = choose|c: Case| #[trigger] cases_of(t.nodes[p as int].item).contains(c) + && c.alpha == alpha && t.nodes[j].item == case_item(c); + assert(steps_ok(d, t.nodes[p as int].item, cases_of(t.nodes[p as int].item))); + lemma_chain_len(d, g0, q0, cases_of, t, p as int, + (t.nodes[j].depth - 1) as nat); + let prefix = chain(t.nodes, p as int, t.nodes[p as int].depth); + assert(chain(t.nodes, j, t.nodes[j].depth) == prefix.push(alpha)); + lemma_follows_unpush(d, prefix, theta, u, alpha); + assert(sat_by(theta, t.nodes[p as int].item.constraint)) by { reveal(entails); } + let e = u.last(); + let before = u.drop_last(); + assert(successor_ok(t.nodes[p as int].item.state, c.alpha, c.next)); + assert(n_lang(theta, c.next, w) + == n_lang(theta, t.nodes[p as int].item.state, seq![e] + w)) by { + reveal(successor_ok); + reveal(n_theta_ok); + } + lemma_node_language(d, g0, q0, cases_of, t, p as int, theta, before, seq![e] + w); + assert(before + (seq![e] + w) =~= u + w); + } +} + +pub proof fn lemma_node_semantics(d: NDomains, g0: Constraint, q0: Regex, + cases_of: spec_fn(Item) -> Set, t: Trace, j: int) + requires satisfiable(d, g0), trace_steps_ok(d, cases_of, t), + trace_wf(d, g0, q0, cases_of, t), 0 <= j < t.nodes.len(), + ensures entails(d, t.nodes[j].item.constraint, g0), + satisfiable(d, t.nodes[j].item.constraint), + forall|theta: Subst| n_theta_ok(d, theta) && sat_by(theta, t.nodes[j].item.constraint) + ==> exists|u: Seq| #[trigger] follows(d, + chain(t.nodes, j, t.nodes[j].depth), theta, u), + forall|theta: Subst, u: Seq, w: Seq| + n_theta_ok(d, theta) && sat_by(theta, t.nodes[j].item.constraint) + && #[trigger] follows(d, chain(t.nodes, j, t.nodes[j].depth), theta, u) + ==> #[trigger] n_lang(theta, t.nodes[j].item.state, w) == n_lang(theta, q0, u + w), +{ + hide(language::numeric_lang); + hide(follows); + hide(n_theta_ok); + hide(sat_by); + hide(entails); + hide(satisfiable); + hide(successor_ok); + lemma_node_realizable(d, g0, q0, cases_of, t, j); + assert forall|theta: Subst, u: Seq, w: Seq| + n_theta_ok(d, theta) && sat_by(theta, t.nodes[j].item.constraint) + && #[trigger] follows(d, chain(t.nodes, j, t.nodes[j].depth), theta, u) + implies #[trigger] n_lang(theta, t.nodes[j].item.state, w) == n_lang(theta, q0, u + w) by { + lemma_node_language(d, g0, q0, cases_of, t, j, theta, u, w); + } +} + +pub proof fn lemma_no_witness_below(d: NDomains, g0: Constraint, q0: Regex, + cases_of: spec_fn(Item) -> Set, t: Trace, j: int, theta: Subst, w: Seq) + requires trace_steps_ok(d, cases_of, t), trace_wf(d, g0, q0, cases_of, t), + 0 <= j < t.nodes.len(), witness(d, t.nodes[j].item, theta, w), + forall|k: int| #![trigger t.nodes[k]] 0 <= k < t.nodes.len() + && t.nodes[k].depth <= t.nodes[j].depth + w.len() ==> k < t.expanded, + ensures false, + decreases w.len(), +{ + hide(language::numeric_lang); + hide(successor_ok); + hide(realizes); + hide(n_theta_ok); + hide(n_event_in); + hide(n_history_in); + hide(sat_by); + hide(entails); + hide(satisfiable); + assert(t.nodes[j].depth <= t.nodes[j].depth + w.len()); + assert(j < t.expanded); + assert(!nullable_state(t.nodes[j].item.state)); + if w.len() == 0 { + assert(w =~= Seq::::empty()); + language::lemma_nullable_iff_nil(model::gsem(theta), t.nodes[j].item.state); + } else { + assert(steps_ok(d, t.nodes[j].item, cases_of(t.nodes[j].item))); + let e = w[0]; + let tail = w.drop_first(); + assert(w =~= seq![e] + tail); + assert(n_event_in(d, e)) by { reveal(n_history_in); } + let c = choose|c: Case| #[trigger] cases_of(t.nodes[j].item).contains(c) + && sat_by(theta, c.constraint) && realizes(theta, e, c.alpha); + assert(n_lang(theta, c.next, tail)) by { + reveal(successor_ok); + reveal(n_theta_ok); + assert(successor_ok(t.nodes[j].item.state, c.alpha, c.next)); + } + assert(n_history_in(d, tail)) by { + reveal(n_history_in); + assert forall|i: int| 0 <= i < tail.len() + implies #[trigger] n_event_in(d, tail[i]) by { assert(tail[i] == w[i + 1]); } + } + assert(witness(d, case_item(c), theta, tail)); + if exists|k: int| 0 < k < t.nodes.len() + && t.nodes[k].parent == Some((j as nat, c.alpha)) && t.nodes[k].item == case_item(c) { + let k = choose|k: int| 0 < k < t.nodes.len() + && t.nodes[k].parent == Some((j as nat, c.alpha)) + && t.nodes[k].item == case_item(c); + assert(parent_ok(cases_of, t, k)); + assert(t.nodes[k].depth == t.nodes[j].depth + 1); + lemma_no_witness_below(d, g0, q0, cases_of, t, k, theta, tail); + } else { + assert(may_discard(d, t.nodes, case_item(c), t.nodes[j].depth + 1)); + if c.next == Regex::::Empty { + reveal(language::numeric_lang); + } else if no_witness(d, case_item(c)) { + assert(!witness(d, case_item(c), theta, tail)); + } else { + let k = choose|k: int| 0 <= k < t.nodes.len() + && t.nodes[k].depth <= t.nodes[j].depth + 1 + && #[trigger] witnesses_within(d, case_item(c), t.nodes[k].item); + assert(witness(d, t.nodes[k].item, theta, tail)); + assert forall|h: int| #![trigger t.nodes[h]] 0 <= h < t.nodes.len() + && t.nodes[h].depth <= t.nodes[k].depth + tail.len() + implies h < t.expanded by { + assert(t.nodes[h].depth <= t.nodes[j].depth + w.len()); + } + lemma_no_witness_below(d, g0, q0, cases_of, t, k, theta, tail); + } + } + } +} + +pub proof fn lemma_search_correct(d: NDomains, g0: Constraint, r: Regex, + s: Regex, q0: Regex, cases_of: spec_fn(Item) -> Set, + t: Trace, outcome: Outcome) + requires satisfiable(d, g0), initial_ok(q0, r, s), trace_steps_ok(d, cases_of, t), + trace_wf(d, g0, q0, cases_of, t), trace_outcome(t, outcome), + ensures outcome_ok(d, g0, r, s, outcome), +{ + hide(language::numeric_lang); + match outcome { + Outcome::Exhausted => {}, + Outcome::Holds => { + assert forall|theta: Subst, w: Seq| n_theta_ok(d, theta) + && n_history_in(d, w) && sat_by(theta, g0) && #[trigger] n_lang(theta, r, w) + implies n_lang(theta, s, w) by { + if !n_lang(theta, s, w) { + let root = Item { constraint: g0, state: q0 }; + assert(witness(d, root, theta, w)); + if t.nodes.len() > 0 { + lemma_no_witness_below(d, g0, q0, cases_of, t, 0, theta, w); + } else { + assert(may_discard(d, t.nodes, root, 0)); + if q0 == Regex::::Empty { reveal(language::numeric_lang); } + else { assert(no_witness(d, root)); } + } + } + } + }, + Outcome::Refuted(g, letters) => { + let j = t.expanded as int; + lemma_node_realizable(d, g0, q0, cases_of, t, j); + lemma_chain_len(d, g0, q0, cases_of, t, j, t.nodes[j].depth); + assert(letters.len() == t.nodes[j].depth); + assert forall|theta: Subst, u: Seq| n_theta_ok(d, theta) + && sat_by(theta, g) && #[trigger] follows(d, letters, theta, u) + implies inclusion_cex(d, g0, r, s, theta, u) by { + language::lemma_nullable_iff_nil(model::gsem(theta), t.nodes[j].item.state); + assert(n_lang(theta, t.nodes[j].item.state, Seq::empty())); + lemma_node_language(d, g0, q0, cases_of, t, j, theta, u, Seq::empty()); + assert(u + Seq::::empty() =~= u); + assert(n_lang(theta, q0, u)); + assert(sat_by(theta, g0)); + } + assert(no_cex_shorter(d, g0, r, s, letters.len())) by { + assert forall|theta: Subst, w: Seq| w.len() < letters.len() + implies !#[trigger] inclusion_cex(d, g0, r, s, theta, w) by { + if inclusion_cex(d, g0, r, s, theta, w) { + assert(witness(d, t.nodes[0].item, theta, w)); + assert forall|k: int| #![trigger t.nodes[k]] 0 <= k < t.nodes.len() + && t.nodes[k].depth <= t.nodes[0].depth + w.len() + implies k < t.expanded by { + if k >= j { + if k > j { assert(t.nodes[j].depth <= t.nodes[k].depth); } + assert(false); + } + } + lemma_no_witness_below(d, g0, q0, cases_of, t, 0, theta, w); + } + } + } + }, + } +} + +pub proof fn theorem_search_correct() + ensures stmt_search_correct(), +{ + assert forall|d: NDomains, g0: Constraint, r: Regex, s: Regex, + q0: Regex, cases_of: spec_fn(Item) -> Set, t: Trace, outcome: Outcome| + satisfiable(d, g0) && #[trigger] initial_ok(q0, r, s) + && trace_steps_ok(d, cases_of, t) + && #[trigger] trace_wf(d, g0, q0, cases_of, t) && #[trigger] trace_outcome(t, outcome) + implies outcome_ok(d, g0, r, s, outcome) by { + lemma_search_correct(d, g0, r, s, q0, cases_of, t, outcome); + } +} + +} // verus! diff --git a/src/history-semantics/src/verify/refinement/semantics.rs b/src/history-semantics/src/verify/refinement/semantics.rs new file mode 100644 index 000000000..1b198c5fd --- /dev/null +++ b/src/history-semantics/src/verify/refinement/semantics.rs @@ -0,0 +1,668 @@ +//! Layer 0: proofs about the typed semantics and the policy questions +//! (`junco_core::spec::{semantics, questions}`; paper `sec:rules`, `sec:policy`, appendix +//! `app:policy-reduction`), plus the constants of a rule, which the analyzer specification reads. +//! +//! The valuation `θ` of the paper is the candidate itself; histories are oldest first and never +//! contain the candidate. Component equality is `PartialEqSpec::eq_spec`. A policy is a finite +//! sequence of rules; its order is irrelevant to every predicate below. +use alloc::boxed::Box; +use history_syntax::Comparison; +use history_syntax::Event; +use history_syntax::event::specs::EventSpec; +use history_syntax::spec::events::{HeadView, PatternView, RegexView, RuleView, TestView}; +use junco_core::spec::questions::{ + DomainsView, constants_union, covers, in_domains, pattern_constant, refines, regex_constant_at, + regex_constant_forest, regex_constants, rule_constants, test_constant_at, test_constant_forest, + test_constants, +}; +use junco_core::spec::semantics as tdsl; +use junco_core::spec::semantics::{policy_denies, rule_violated, rule_wf}; +use vstd::prelude::*; +use vstd::std_specs::cmp::PartialEqSpec; + +verus! { + +broadcast use {vstd::std_specs::vec::group_vec_axioms, vstd::seq::group_seq_lemmas}; + +// ----- theorem statements ----- + +/// `P ⊑ Q` iff `P` covers every rule of `Q` (appendix `app:policy-reduction`). +pub open spec fn stmt_refines_iff_covers() -> bool { + forall|domains: DomainsView, p: Seq>, q: Seq>| + #[trigger] refines::(domains, p, q) <==> forall|i: int| 0 <= i < q.len() ==> covers::(domains, p, #[trigger] q[i]) +} + +/// Removing a covered rule changes no decision (appendix `app:policy-reduction`): with `others` the policy +/// without the rule, the two policies deny the same pairs iff `others` covers the rule. +pub open spec fn stmt_redundant_iff_covered() -> bool { + forall|domains: DomainsView, others: Seq>, rule: RuleView| + #[trigger] covers::(domains, others, rule) <==> forall|c: E, h: Seq| + in_domains::(domains, c, h) + ==> (#[trigger] policy_denies(others.push(rule), c, h) == policy_denies(others, c, h)) +} + +/// Genericity: semantics depends only on which values are equal and on equality with the +/// rules' constants. Hence a property proved for every pair over one set of values holds for +/// every pair over any other: map the finitely many values of a pair injectively, fixing the +/// constants. Stated for one rule; policies follow pointwise. +pub open spec fn renaming_preserves_eq(f: spec_fn(C) -> C, fixed: Set, values: ISet) -> bool { + &&& forall|x: C, y: C| values.contains(x) && values.contains(y) ==> (#[trigger] f(x).eq_spec(&#[trigger] f(y)) == x.eq_spec(&y)) + &&& forall|x: C, k: C| values.contains(x) && fixed.contains(k) ==> (#[trigger] f(x).eq_spec(&k) == #[trigger] x.eq_spec(&k)) +} + +/// A renaming that also keeps every value's coordinate tag. +pub open spec fn renaming_preserves(f: spec_fn(E::Component) -> E::Component, fixed: Set, values: ISet) -> bool { + renaming_preserves_eq(f, fixed, values) + && forall|x: E::Component| values.contains(x) ==> E::coordinate_spec(#[trigger] f(x)) == E::coordinate_spec(x) +} + +pub open spec fn rename_event(f: Seq C>, e: Seq) -> Seq { + Seq::new(e.len(), |i: int| f[i](e[i])) +} + +pub open spec fn rename_history(f: Seq C>, h: Seq>) -> Seq> { + h.map(|i: int, e: Seq| rename_event(f, e)) +} + +/// The values used at one coordinate of a candidate and its history. +pub open spec fn pair_values(candidate: Seq, history: Seq>, coordinate: int) -> ISet { + ISet::new(|x: C| (0 <= coordinate < candidate.len() && x == candidate[coordinate]) + || exists|i: int| 0 <= i < history.len() && 0 <= coordinate < history[i].len() + && #[trigger] history[i][coordinate] == x) +} + +/// Rule violation (`rule_violated_view`) is invariant under tag-preserving renamings of the +/// pair's values that fix the rule's constants. +pub open spec fn stmt_genericity() -> bool { + forall|rule: RuleView, candidate: Seq, history: Seq>, f: Seq E::Component>| + rule_wf(rule) && candidate.len() == rule.head.len() + && (forall|i: int| 0 <= i < history.len() ==> history[i].len() == candidate.len()) + && renamings_preserve::(f, rule_constants(rule), + Seq::new(candidate.len(), |i: int| pair_values(candidate, history, i))) + ==> (tdsl::rule_violated_view(rule, candidate, history) + == #[trigger] tdsl::rule_violated_view(rule, rename_event(f, candidate), rename_history(f, history))) +} + +pub proof fn lemma_constants_union(sets: Seq>, i: int) + requires 0 <= i < sets.len(), + ensures sets[i].subset_of(constants_union(sets)), + decreases sets.len(), +{ + if i < sets.len() - 1 { + lemma_constants_union(sets.drop_last(), i); + assert(sets[i] == sets.drop_last()[i]); + } else { + assert(sets[i] == sets.last()); + } +} + +proof fn lemma_test_constant_forest_index(tests: Seq>, arity: nat, j: int) + requires 0 <= j < arity, + ensures test_constant_forest(tests, j) == constants_union(Seq::new(tests.len(), |i: int| + if 0 <= i < tests.len() { test_constants(tests[i], arity)[j] } else { Set::empty() })), + decreases tests.len(), +{ + if tests.len() > 0 { + let prior = tests.drop_last(); + lemma_test_constant_forest_index(prior, arity, j); + let values = Seq::new(tests.len(), |i: int| + if 0 <= i < tests.len() { test_constants(tests[i], arity)[j] } else { Set::empty() }); + let prefix = Seq::new(prior.len(), |i: int| + if 0 <= i < prior.len() { test_constants(prior[i], arity)[j] } else { Set::empty() }); + assert(values.drop_last() =~= prefix); + assert(values.last() == test_constant_at(tests.last(), j)); + } +} + +proof fn lemma_regex_constant_forest_index(regexes: Seq>, arity: nat, j: int) + requires 0 <= j < arity, + ensures regex_constant_forest(regexes, j) == constants_union(Seq::new(regexes.len(), |i: int| + if 0 <= i < regexes.len() { regex_constants(regexes[i], arity)[j] } else { Set::empty() })), + decreases regexes.len(), +{ + if regexes.len() > 0 { + let prior = regexes.drop_last(); + lemma_regex_constant_forest_index(prior, arity, j); + let values = Seq::new(regexes.len(), |i: int| + if 0 <= i < regexes.len() { regex_constants(regexes[i], arity)[j] } else { Set::empty() }); + let prefix = Seq::new(prior.len(), |i: int| + if 0 <= i < prior.len() { regex_constants(prior[i], arity)[j] } else { Set::empty() }); + assert(values.drop_last() =~= prefix); + assert(values.last() == regex_constant_at(regexes.last(), j)); + } +} + +/// One coordinate of a test's constants, with recursive calls left at their own fuel level. +pub proof fn lemma_test_constants_index(test: TestView, arity: nat, j: int) + requires 0 <= j < arity, + ensures test_constants(test, arity)[j] == match test { + TestView::True | TestView::False => Set::empty(), + TestView::Atom { pattern, .. } => + if j == pattern.component { pattern_constant(pattern.pattern) } else { Set::empty() }, + TestView::And(cs) | TestView::Or(cs) => constants_union(Seq::new(cs.len(), |i: int| + if 0 <= i < cs.len() { test_constants(cs[i], arity)[j] } else { Set::empty() })), + }, +{ + reveal_with_fuel(test_constant_at, 2); + match test { + TestView::And(cs) | TestView::Or(cs) => lemma_test_constant_forest_index(cs, arity, j), + _ => {}, + } +} + +/// The analogous indexed unfolding for regex constants. +pub proof fn lemma_regex_constants_index(regex: RegexView, arity: nat, j: int) + requires 0 <= j < arity, + ensures regex_constants(regex, arity)[j] == match regex { + RegexView::Empty | RegexView::All | RegexView::Epsilon => Set::empty(), + RegexView::Test(test) => test_constants(test, arity)[j], + RegexView::Union(cs) | RegexView::Concat(cs) | RegexView::Intersect(cs) => + constants_union(Seq::new(cs.len(), |i: int| + if 0 <= i < cs.len() { regex_constants(cs[i], arity)[j] } else { Set::empty() })), + RegexView::Star(child) | RegexView::Not(child) => regex_constants(*child, arity)[j], + }, +{ + reveal_with_fuel(regex_constant_at, 2); + match regex { + RegexView::Union(cs) | RegexView::Concat(cs) | RegexView::Intersect(cs) => + lemma_regex_constant_forest_index(cs, arity, j), + _ => {}, + } +} +// ----- proofs ----- + +/// Appending a rule to a policy adds exactly that rule's violations. +pub proof fn lemma_policy_denies_push( + policy: Seq>, rule: RuleView, c: E, h: Seq, +) + ensures + policy_denies(policy.push(rule), c, h) + == (policy_denies(policy, c, h) || rule_violated(rule, c, h)), +{ + let q = policy.push(rule); + if policy_denies(policy, c, h) { + let i = choose|i: int| 0 <= i < policy.len() && #[trigger] rule_violated(policy[i], c, h); + assert(q[i] == policy[i]); + assert(rule_violated(q[i], c, h)); + } + if rule_violated(rule, c, h) { + let n = policy.len() as int; + assert(q[n] == rule); + assert(rule_violated(q[n], c, h)); + } + if policy_denies(q, c, h) { + let i = choose|i: int| 0 <= i < q.len() && #[trigger] rule_violated(q[i], c, h); + if i < policy.len() { + assert(q[i] == policy[i]); + assert(rule_violated(policy[i], c, h)); + } + } +} + +pub proof fn theorem_refines_iff_covers() + ensures stmt_refines_iff_covers::(), +{ + assert forall|domains: DomainsView, p: Seq>, q: Seq>| + #[trigger] refines::(domains, p, q) <==> forall|i: int| 0 <= i < q.len() ==> covers::(domains, p, #[trigger] q[i]) + by { + if refines::(domains, p, q) { + assert forall|i: int| 0 <= i < q.len() implies covers::(domains, p, #[trigger] q[i]) by { + assert forall|c: E, h: Seq| + in_domains::(domains, c, h) && #[trigger] rule_violated(q[i], c, h) + implies policy_denies(p, c, h) by { + assert(policy_denies(q, c, h)); + assert(!tdsl::policy_permits(q, c, h)); + } + } + } + if forall|i: int| 0 <= i < q.len() ==> covers::(domains, p, #[trigger] q[i]) { + assert forall|c: E, h: Seq| + in_domains::(domains, c, h) && tdsl::policy_permits(p, c, h) + implies #[trigger] tdsl::policy_permits(q, c, h) by { + if policy_denies(q, c, h) { + let i = choose|i: int| 0 <= i < q.len() && #[trigger] rule_violated(q[i], c, h); + assert(covers::(domains, p, q[i])); + } + } + } + } +} + +pub proof fn theorem_redundant_iff_covered() + ensures stmt_redundant_iff_covered::(), +{ + assert forall|domains: DomainsView, others: Seq>, rule: RuleView| + #[trigger] covers::(domains, others, rule) <==> forall|c: E, h: Seq| + in_domains::(domains, c, h) + ==> (#[trigger] policy_denies(others.push(rule), c, h) == policy_denies(others, c, h)) + by { + if covers::(domains, others, rule) { + assert forall|c: E, h: Seq| + in_domains::(domains, c, h) + implies (#[trigger] policy_denies(others.push(rule), c, h) + == policy_denies(others, c, h)) by { + lemma_policy_denies_push(others, rule, c, h); + } + } + if forall|c: E, h: Seq| + in_domains::(domains, c, h) + ==> (#[trigger] policy_denies(others.push(rule), c, h) == policy_denies(others, c, h)) + { + assert forall|c: E, h: Seq| + in_domains::(domains, c, h) && #[trigger] rule_violated(rule, c, h) + implies policy_denies(others, c, h) by { + lemma_policy_denies_push(others, rule, c, h); + assert(policy_denies(others.push(rule), c, h) == policy_denies(others, c, h)); + } + } + } +} + +// ----- genericity ----- + +/// Every component lies in its corresponding value set, at exactly that arity. +pub open spec fn values_in(e: Seq, values: Seq>) -> bool { + e.len() == values.len() && forall|i: int| 0 <= i < e.len() ==> #[trigger] values[i].contains(e[i]) +} + +pub open spec fn word_values_in(w: Seq>, values: Seq>) -> bool { + forall|i: int| 0 <= i < w.len() ==> #[trigger] values_in(w[i], values) +} + +pub open spec fn renamings_preserve_eq( + f: Seq C>, fixed: Seq>, values: Seq>, +) -> bool { + f.len() == fixed.len() && values.len() == fixed.len() + && forall|i: int| 0 <= i < f.len() ==> renaming_preserves_eq(#[trigger] f[i], fixed[i], values[i]) +} + +pub open spec fn renamings_preserve( + f: Seq E::Component>, fixed: Seq>, values: Seq>, +) -> bool { + f.len() == fixed.len() && values.len() == fixed.len() + && forall|i: int| 0 <= i < f.len() ==> renaming_preserves::(#[trigger] f[i], fixed[i], values[i]) +} + +pub open spec fn rename_parts(f: Seq C>, parts: Seq>>) -> Seq>> { + parts.map(|i: int, part: Seq>| rename_history(f, part)) +} + +pub proof fn lemma_renaming_mono(f: spec_fn(T) -> T, small: Set, big: Set, values: ISet) + requires + renaming_preserves_eq(f, big, values), + forall|x: T| #[trigger] small.contains(x) ==> big.contains(x), + ensures renaming_preserves_eq(f, small, values), +{ + assert forall|x: T, k: T| values.contains(x) && small.contains(k) + implies (#[trigger] f(x).eq_spec(&k) == #[trigger] x.eq_spec(&k)) by { + assert(big.contains(k)); + } +} + +pub proof fn lemma_renamings_mono( + f: Seq C>, small: Seq>, big: Seq>, values: Seq>, +) + requires renamings_preserve_eq(f, big, values), small.len() == big.len(), + forall|i: int| 0 <= i < small.len() ==> #[trigger] small[i].subset_of(big[i]), + ensures renamings_preserve_eq(f, small, values), +{ + assert forall|i: int| 0 <= i < f.len() implies renaming_preserves_eq(#[trigger] f[i], small[i], values[i]) by { + assert(small[i].subset_of(big[i])); + assert forall|x: C| #[trigger] small[i].contains(x) implies big[i].contains(x) by {} + lemma_renaming_mono(f[i], small[i], big[i], values[i]); + } +} + +pub proof fn lemma_head_pattern_rename(pattern: PatternView, f: spec_fn(T) -> T, fixed: Set, values: ISet, x: T) + requires + renaming_preserves_eq(f, fixed, values), + values.contains(x), + forall|k: T| #[trigger] pattern_constant(pattern).contains(k) ==> fixed.contains(k), + ensures tdsl::head_pattern_matches(pattern, f(x)) == tdsl::head_pattern_matches(pattern, x), +{ + if let PatternView::Constant(k) = pattern { + assert(pattern_constant(pattern).contains(k)); + assert(f(x).eq_spec(&k) == x.eq_spec(&k)); + } +} + +pub proof fn lemma_comparison_rename( + comparison: Comparison, pattern: PatternView, head: PatternView, f: spec_fn(T) -> T, + fixed: Set, values: ISet, c: T, e: T, +) + requires + renaming_preserves_eq(f, fixed, values), + values.contains(c), + values.contains(e), + forall|k: T| #[trigger] pattern_constant(pattern).contains(k) ==> fixed.contains(k), + ensures + tdsl::comparison_sem(comparison, f(e), tdsl::resolve_pattern(pattern, head, f(c))) + == tdsl::comparison_sem(comparison, e, tdsl::resolve_pattern(pattern, head, c)), +{ + match pattern { + PatternView::Constant(k) => { + assert(pattern_constant(pattern).contains(k)); + assert(f(e).eq_spec(&k) == e.eq_spec(&k)); + }, + PatternView::Variable(_) => { + assert(f(e).eq_spec(&f(c)) == e.eq_spec(&c)); + }, + } +} + +pub proof fn lemma_test_rename( + test: TestView, head: HeadView, candidate: Seq, event: Seq, + f: Seq C>, values: Seq>, +) + requires renamings_preserve_eq(f, test_constants(test, head.len()), values), + values_in(candidate, values), values_in(event, values), + ensures tdsl::test_sem(test, head, rename_event(f, candidate), rename_event(f, event)) + == tdsl::test_sem(test, head, candidate, event), + decreases test, +{ + let rc = rename_event(f, candidate); + let re = rename_event(f, event); + match test { + TestView::True | TestView::False => {}, + TestView::Atom { comparison, pattern } => { + let j = pattern.component as int; + if j < head.len() { + lemma_test_constants_index(test, head.len(), j); + assert(test_constants(test, head.len())[j] == pattern_constant(pattern.pattern)); + lemma_comparison_rename(comparison, pattern.pattern, head[j], f[j], + test_constants(test, head.len())[j], values[j], candidate[j], event[j]); + } + }, + TestView::And(cs) | TestView::Or(cs) => { + assert forall|i: int| 0 <= i < cs.len() implies + tdsl::test_sem(cs[i], head, rc, re) == tdsl::test_sem(cs[i], head, candidate, event) by { + assert forall|j: int| 0 <= j < head.len() implies + #[trigger] test_constants(cs[i], head.len())[j].subset_of(test_constants(test, head.len())[j]) by { + lemma_test_constants_index(test, head.len(), j); + let sets = Seq::new(cs.len(), |k: int| if 0 <= k < cs.len() { test_constants(cs[k], head.len())[j] } else { Set::empty() }); + lemma_constants_union(sets, i); + assert(sets[i] == test_constants(cs[i], head.len())[j]); + } + lemma_renamings_mono(f, test_constants(cs[i], head.len()), test_constants(test, head.len()), values); + lemma_test_rename(cs[i], head, candidate, event, f, values); + } + }, + } +} + +/// Renaming commutes with flattening. +pub proof fn lemma_flatten_rename( + f: Seq C>, parts: Seq>>, +) + ensures rename_history(f, parts.flatten()) == rename_parts(f, parts).flatten(), + decreases parts.len(), +{ + let rp = rename_parts(f, parts); + if parts.len() == 0 { + assert(rename_history(f, parts.flatten()) =~= rp.flatten()); + } else { + lemma_flatten_rename(f, parts.drop_first()); + assert(rp.drop_first() =~= rename_parts(f, parts.drop_first())); + let a = parts.first(); + let b = parts.drop_first().flatten(); + assert(rename_history(f, a + b) =~= rename_history(f, a) + rename_history(f, b)); + assert(rp.first() == rename_history(f, a)); + } +} + +/// A word whose renaming is split into parts splits into parts with those renamings. +pub proof fn lemma_unflatten_rename( + f: Seq C>, rparts: Seq>>, + w: Seq>, +) -> (parts: Seq>>) + requires rparts.flatten() == rename_history(f, w), + ensures + parts.len() == rparts.len(), + parts.flatten() == w, + forall|i: int| 0 <= i < parts.len() ==> rename_history(f, #[trigger] parts[i]) == rparts[i], + decreases rparts.len(), +{ + if rparts.len() == 0 { + assert(w =~= Seq::>::empty()); + Seq::empty() + } else { + let first = rparts.first(); + let rest = rparts.drop_first(); + let k = first.len() as int; + let rw = rename_history(f, w); + assert(rw == first + rest.flatten()); + let w0 = w.subrange(0, k); + let w1 = w.subrange(k, w.len() as int); + assert(rename_history(f, w0) =~= first) by { + assert forall|j: int| 0 <= j < k implies rename_history(f, w0)[j] == first[j] by { + assert(rw[j] == (first + rest.flatten())[j]); + } + } + assert(rename_history(f, w1) =~= rest.flatten()) by { + assert forall|j: int| 0 <= j < w.len() - k implies rename_history(f, w1)[j] == rest.flatten()[j] by { + assert(rw[k + j] == (first + rest.flatten())[k + j]); + } + } + let tail = lemma_unflatten_rename(f, rest, w1); + let parts = seq![w0] + tail; + assert(parts.drop_first() =~= tail); + assert(parts.first() == w0); + assert(parts.flatten() == w0 + tail.flatten()); + assert(w0 + w1 =~= w); + assert forall|i: int| 0 <= i < parts.len() implies rename_history(f, #[trigger] parts[i]) == rparts[i] by { + if i > 0 { + assert(parts[i] == tail[i - 1]); + assert(rparts[i] == rest[i - 1]); + } + } + parts + } +} + +/// The parts of a word only contain the word's values. +pub proof fn lemma_flatten_values_in(parts: Seq>>, values: Seq>) + requires word_values_in(parts.flatten(), values), + ensures forall|i: int| 0 <= i < parts.len() ==> word_values_in(#[trigger] parts[i], values), + decreases parts.len(), +{ + if parts.len() > 0 { + let a = parts.first(); + let b = parts.drop_first().flatten(); + assert(parts.flatten() == a + b); + assert forall|j: int| 0 <= j < a.len() implies #[trigger] values_in(a[j], values) by { + assert((a + b)[j] == a[j]); + } + assert forall|j: int| 0 <= j < b.len() implies #[trigger] values_in(b[j], values) by { + assert((a + b)[a.len() + j] == b[j]); + } + lemma_flatten_values_in(parts.drop_first(), values); + assert forall|i: int| 0 <= i < parts.len() implies word_values_in(#[trigger] parts[i], values) by { + if i > 0 { + assert(parts[i] == parts.drop_first()[i - 1]); + } + } + } +} + +pub proof fn lemma_lang_rename( + regex: RegexView, head: HeadView, candidate: Seq, w: Seq>, + f: Seq C>, values: Seq>, +) + requires + renamings_preserve_eq(f, regex_constants(regex, head.len()), values), + values_in(candidate, values), + word_values_in(w, values), + ensures + tdsl::lang(regex, head, rename_event(f, candidate), rename_history(f, w)) + == tdsl::lang(regex, head, candidate, w), + decreases regex, 1nat, +{ + let rc = rename_event(f, candidate); + let rw = rename_history(f, w); + match regex { + RegexView::Empty | RegexView::All | RegexView::Epsilon => {}, + RegexView::Test(t) => { + assert(regex_constants(regex, head.len()) =~= test_constants(t, head.len())); + if w.len() == 1 { + assert(values_in(w[0], values)); + lemma_test_rename(t, head, candidate, w[0], f, values); + } + }, + RegexView::Star(b) | RegexView::Not(b) => { + lemma_lang_rename_star_not(regex, *b, head, candidate, w, f, values); + }, + RegexView::Union(cs) | RegexView::Concat(cs) | RegexView::Intersect(cs) => { + assert forall|i: int| 0 <= i < cs.len() implies + #[trigger] renamings_preserve_eq(f, regex_constants(cs[i], head.len()), values) by { + assert forall|j: int| 0 <= j < head.len() implies + #[trigger] regex_constants(cs[i], head.len())[j].subset_of(regex_constants(regex, head.len())[j]) by { + lemma_regex_constants_index(regex, head.len(), j); + let sets = Seq::new(cs.len(), |k: int| if 0 <= k < cs.len() { regex_constants(cs[k], head.len())[j] } else { Set::empty() }); + lemma_constants_union(sets, i); + assert(sets[i] == regex_constants(cs[i], head.len())[j]); + } + lemma_renamings_mono(f, regex_constants(cs[i], head.len()), regex_constants(regex, head.len()), values); + } + if regex is Concat { + if tdsl::lang(regex, head, candidate, w) { + let parts = choose|parts: Seq>>| parts.len() == cs.len() && w == parts.flatten() + && forall|i: int| 0 <= i < cs.len() ==> tdsl::lang(cs[i], head, candidate, parts[i]); + lemma_flatten_values_in(parts, values); + lemma_flatten_rename(f, parts); + let rp = rename_parts(f, parts); + assert forall|i: int| 0 <= i < cs.len() implies tdsl::lang(cs[i], head, rc, rp[i]) by { + assert(renamings_preserve_eq(f, regex_constants(cs[i], head.len()), values)); + assert(word_values_in(parts[i], values)); + lemma_lang_rename(cs[i], head, candidate, parts[i], f, values); + } + assert(rp.len() == cs.len() && rw == rp.flatten()); + } + if tdsl::lang(regex, head, rc, rw) { + let rparts = choose|parts: Seq>>| parts.len() == cs.len() && rw == parts.flatten() + && forall|i: int| 0 <= i < cs.len() ==> tdsl::lang(cs[i], head, rc, parts[i]); + let parts = lemma_unflatten_rename(f, rparts, w); + lemma_flatten_values_in(parts, values); + assert forall|i: int| 0 <= i < cs.len() implies tdsl::lang(cs[i], head, candidate, parts[i]) by { + assert(renamings_preserve_eq(f, regex_constants(cs[i], head.len()), values)); + assert(word_values_in(parts[i], values)); + assert(rename_history(f, parts[i]) == rparts[i]); + lemma_lang_rename(cs[i], head, candidate, parts[i], f, values); + } + } + } else { + assert forall|i: int| 0 <= i < cs.len() implies + tdsl::lang(cs[i], head, rc, rw) == tdsl::lang(cs[i], head, candidate, w) by { + assert(renamings_preserve_eq(f, regex_constants(cs[i], head.len()), values)); + lemma_lang_rename(cs[i], head, candidate, w, f, values); + } + } + }, + } +} + +proof fn lemma_lang_rename_star_not( + regex: RegexView, b: RegexView, head: HeadView, candidate: Seq, + w: Seq>, f: Seq C>, + values: Seq>, +) + requires + regex == RegexView::Star(Box::new(b)) || regex == RegexView::Not(Box::new(b)), + renamings_preserve_eq(f, regex_constants(regex, head.len()), values), + values_in(candidate, values), + word_values_in(w, values), + ensures + tdsl::lang(regex, head, rename_event(f, candidate), rename_history(f, w)) + == tdsl::lang(regex, head, candidate, w), + decreases regex, 0nat, +{ + let rc = rename_event(f, candidate); + let rw = rename_history(f, w); + assert(regex_constants(b, head.len()) =~= regex_constants(regex, head.len())); + if regex is Not { + lemma_lang_rename(b, head, candidate, w, f, values); + } else { + if tdsl::lang(regex, head, candidate, w) { + let parts = choose|parts: Seq>>| w == parts.flatten() + && forall|i: int| 0 <= i < parts.len() ==> tdsl::lang(b, head, candidate, parts[i]); + lemma_flatten_values_in(parts, values); + lemma_flatten_rename(f, parts); + let rp = rename_parts(f, parts); + assert forall|i: int| 0 <= i < rp.len() implies tdsl::lang(b, head, rc, rp[i]) by { + assert(word_values_in(parts[i], values)); + lemma_lang_rename(b, head, candidate, parts[i], f, values); + } + assert(rw == rp.flatten()); + } + if tdsl::lang(regex, head, rc, rw) { + let rparts = choose|parts: Seq>>| rw == parts.flatten() + && forall|i: int| 0 <= i < parts.len() ==> tdsl::lang(b, head, rc, parts[i]); + let parts = lemma_unflatten_rename(f, rparts, w); + lemma_flatten_values_in(parts, values); + assert forall|i: int| 0 <= i < parts.len() implies tdsl::lang(b, head, candidate, parts[i]) by { + assert(word_values_in(parts[i], values)); + assert(rename_history(f, parts[i]) == rparts[i]); + lemma_lang_rename(b, head, candidate, parts[i], f, values); + } + } + } +} + +/// Violation is invariant under renamings that preserve equality on the given values and with +/// the rule's constants. +pub proof fn lemma_violation_rename( + rule: RuleView, candidate: Seq, history: Seq>, + f: Seq C>, values: Seq>, +) + requires + renamings_preserve_eq(f, rule_constants(rule), values), + values_in(candidate, values), + word_values_in(history, values), + ensures + tdsl::rule_violated_view(rule, candidate, history) + == tdsl::rule_violated_view(rule, rename_event(f, candidate), rename_history(f, history)), +{ + let k = rule_constants(rule); + assert forall|i: int| 0 <= i < rule.head.len() implies + tdsl::head_pattern_matches(rule.head[i], rename_event(f, candidate)[i]) + == tdsl::head_pattern_matches(rule.head[i], candidate[i]) by { + lemma_head_pattern_rename(rule.head[i], f[i], k[i], values[i], candidate[i]); + } + assert(tdsl::head_matches(rule.head, candidate) == tdsl::head_matches(rule.head, rename_event(f, candidate))); + assert forall|i: int| 0 <= i < rule.head.len() implies + #[trigger] regex_constants(rule.tail, rule.head.len())[i].subset_of(k[i]) by {} + lemma_renamings_mono(f, regex_constants(rule.tail, rule.head.len()), k, values); + lemma_lang_rename(rule.tail, rule.head, candidate, history, f, values); +} + +pub proof fn lemma_pair_values_contains(candidate: Seq, history: Seq>, coordinate: int, i: int) + requires 0 <= i < history.len(), 0 <= coordinate < history[i].len(), + ensures pair_values(candidate, history, coordinate).contains(history[i][coordinate]), +{ + let x = history[i][coordinate]; + assert(exists|j: int| 0 <= j < history.len() && 0 <= coordinate < history[j].len() + && #[trigger] history[j][coordinate] == x); +} + +pub proof fn theorem_genericity() + ensures stmt_genericity::(), +{ + assert forall|rule: RuleView, candidate: Seq, history: Seq>, f: Seq E::Component>| + rule_wf(rule) && candidate.len() == rule.head.len() + && (forall|i: int| 0 <= i < history.len() ==> history[i].len() == candidate.len()) + && renamings_preserve::(f, rule_constants(rule), + Seq::new(candidate.len(), |i: int| pair_values(candidate, history, i))) + implies (tdsl::rule_violated_view(rule, candidate, history) + == #[trigger] tdsl::rule_violated_view(rule, rename_event(f, candidate), rename_history(f, history))) by { + let values = Seq::new(candidate.len(), |i: int| pair_values(candidate, history, i)); + assert(values_in(candidate, values)); + assert forall|i: int| 0 <= i < history.len() implies #[trigger] values_in(history[i], values) by { + assert forall|j: int| 0 <= j < candidate.len() implies #[trigger] values[j].contains(history[i][j]) by { + lemma_pair_values_contains(candidate, history, j, i); + } + } + assert(renamings_preserve_eq(f, rule_constants(rule), values)); + lemma_violation_rename(rule, candidate, history, f, values); + } +} + +} // verus! diff --git a/src/history-semantics/src/verify/typed_decision.rs b/src/history-semantics/src/verify/typed_decision.rs new file mode 100644 index 000000000..837ea0743 --- /dev/null +++ b/src/history-semantics/src/verify/typed_decision.rs @@ -0,0 +1,532 @@ +//! Owned DSL → finite component books → retained numeric runtime composition. +//! +//! The public constructor and decision bodies supply the structural flattening, +//! finite published snapshots, history correspondence, and cached numeric answer. +//! Native Eq/Hash/projection remain conditional; retained provenance follows lifecycle resources. +//! Ordered Vec construction, first-source denial, callback pairing, and validator +//! append/no-append transactions are exercised by actual checked API clients below. + +use crate::compile::verify as numeric; +use crate::compiled_rule::CompiledRule; +use crate::compiled_rule::verify as typed; +use crate::policy::evaluate::{policy_decision_result, verify as policy}; +use crate::policy::rule::verify::{policy_rule_diagnostic, policy_rule_source}; +use crate::policy::{CompiledPolicy, PolicyDecision, PolicyRule}; +use crate::runtime::{RuleRuntime, verify as cache}; +use crate::spec::monitor::{check_frame, check_step}; +use crate::validator::{Decision, Validator}; +use alloc::sync::Arc; +use alloc::vec::Vec; +use history_store::history::{History, verify as raw}; +use history_store::typed::{Store, borrow_store, share_store, verify as books}; +use history_syntax::Event; +use history_syntax::syntax::Rule; +use history_syntax::{Head, RegexExpr, RuleMode}; +use junco_core::errors::{CompileError, HistoryError}; +use junco_core::event::Request; +use junco_core::flat::FlatPair; +use junco_core::kernel::verify as graph; +use junco_core::limits::Limits; +use junco_core::observation::ObservationWorld; +use junco_core::spec::semantics as dsl; +use vstd::prelude::*; +use vstd::std_specs::iter::IteratorSpec; + +verus! { +broadcast use {junco_core::kernel::verify::group_kernel_views, + vstd::std_specs::vec::group_vec_axioms, vstd::seq::group_seq_lemmas}; + +/// The numeric constructor's property is preserved by successful and failed batches. +pub(crate) open spec fn runtime_represents(template: FlatPair, runtime: RuleRuntime) -> bool { + cache::runtime_wf(runtime) + && numeric::regex_correct(runtime.pair.store.graph(), template, template.root as nat, runtime.pair.root) +} + +pub(crate) proof fn lemma_runtime_frame(template: FlatPair, before: RuleRuntime, after: RuleRuntime) + requires runtime_represents(template, before), cache::runtime_wf(after), + crate::progress::verify::pair_frame(before.pair, after.pair), + ensures runtime_represents(template, after), +{ + let first = before.pair.store.graph(); + let last = after.pair.store.graph(); + graph::lemma_graph_wf_elim(first); + graph::lemma_lift_regex_stable(first, last, before.pair.root@); + assert forall|theta: junco_core::verify::history_specs::Subst, + word: Seq| + junco_core::verify::history_specs::event_wf(theta, theta.len()) implies + graph::regex_lang(last, theta, after.pair.root@, word) + == numeric::source_regex(template, template.root as nat, theta, word) by { + assert(graph::regex_lang(first, theta, before.pair.root@, word) + == numeric::source_regex(template, template.root as nat, theta, word)); + } +} + +/// Shared Arc adapters establish matching ownership before the public decision. +pub(crate) fn shared_store_owner_decision_client( + store: Arc>, rule: Rule, candidate: &E, +) -> (result: Result<(CompiledRule, History, Result, HistoryError>), CompileError>) + requires books::store_wf(*store), + ensures result matches Ok((compiled, history, answer)) ==> + typed::decision_requires(compiled, history) + && books::same_store_owner(compiled.store, raw::store_of(history)) + && answer != Err(HistoryError::WrongHistoryOwner), +{ + let history_owner = share_store(&store); + let ghost source = rule; + let mut compiled = CompiledRule::new(store, rule)?; + let history = History::new(history_owner)?; + proof { + raw::lemma_empty_history(history, history_owner); + typed::lemma_constructed_decision(compiled, source, store, history); + books::lemma_same_store_owner_identity(compiled.store, raw::store_of(history)); + } + let answer = compiled.accepts_history(&history, candidate); + Ok((compiled, history, answer)) +} + +/// Distinct constructor receipts contradict successful native pointer comparison. +pub(crate) fn independent_store_owner_decision_client( + rule: Rule, candidate: &E, +) -> (result: Result<(CompiledRule, History, Result, HistoryError>), CompileError>) + ensures result matches Ok((compiled, history, answer)) ==> + typed::decision_requires(compiled, history) + && !books::same_store_owner(compiled.store, raw::store_of(history)) + && answer == Err(HistoryError::WrongHistoryOwner), +{ + let (left, right) = match books::independently_constructed_stores_client::() { + Ok(owners) => owners, + Err(error) => { rule.dispose(); return Err(CompileError::Runtime(error)); }, + }; + let left = Arc::new(left); + let right = Arc::new(right); + let left_referent = borrow_store(&left); + let right_referent = borrow_store(&right); + let same = CompiledRule::same_owner(&left, &right); + proof { + assert(books::store_id(*left_referent) != books::store_id(*right_referent)); + assert(!same); + } + let ghost source = rule; + let mut compiled = CompiledRule::new(left, rule)?; + let history = History::new(right)?; + proof { + raw::lemma_empty_history(history, right); + typed::lemma_constructed_decision(compiled, source, left, history); + } + let answer = compiled.accepts_history(&history, candidate); + Ok((compiled, history, answer)) +} + +/// This is the actual public consuming constructor followed by the public decision. +/// No numeric-only event restriction or semantic-equivalence premise is supplied. +pub(crate) fn public_compiled_decision( + store: Arc>, rule: Rule, history: &History, candidate: &E, +) -> (result: Result, CompileError>) + requires books::store_wf(*store), raw::history_wf(*history), + ensures junco_core::spec::hypotheses::event_obligations::() ==> (result matches Ok(answer) + ==> answer == dsl::rule_evaluation(rule@, *candidate, raw::raw_events(*history))), +{ + let ghost source = rule; + let mut compiled = CompiledRule::new(store, rule)?; + proof { typed::lemma_constructed_decision(compiled, source, store, *history); } + let accepted = compiled.accepts_history(history, candidate)?; + Ok(accepted) +} + +/// Real retained decisions span append, rollback, same-length replacement, truncate, +/// and a fresh-owner fork, without any caller-supplied cache-provenance premise. +pub(crate) fn retained_history_lifecycle( + store: Arc>, rule: Rule, history: &mut History, appended: E, + replacement: E, truncate_to: usize, candidate: &E, +) -> (result: Result, CompileError>) + requires books::store_wf(*store), raw::history_wf(*old(history)), + ensures raw::history_wf(*final(history)), + junco_core::spec::hypotheses::event_obligations::() ==> (result matches Ok(answer) + ==> answer == dsl::rule_evaluation(rule@, *candidate, raw::raw_events(*final(history)))), +{ + let ghost source = rule; + let mut compiled = CompiledRule::new(store, rule)?; + proof { typed::lemma_constructed_decision(compiled, source, store, *history); } + let checkpoint = history.checkpoint(); + let _ = compiled.accepts_history(history, candidate)?; + history.push(appended)?; + let _ = compiled.accepts_history(history, candidate)?; + history.rollback(checkpoint)?; + let _ = compiled.accepts_history(history, candidate)?; + history.push(replacement)?; + history.truncate(truncate_to)?; + let _ = compiled.accepts_history(history, candidate)?; + let fork = history.try_clone()?; + proof { raw::lemma_clone_raw_word(*history, fork); } + let accepted = compiled.accepts_history(&fork, candidate)?; + proof { + assert(raw::raw_word(*history) =~= raw::raw_events(*history).map( + |i: int, event: E| history_syntax::spec::events::event_view(event))); + assert(raw::raw_word(fork) =~= raw::raw_events(fork).map( + |i: int, event: E| history_syntax::spec::events::event_view(event))); + } + Ok(accepted) +} + +/// Retained-prefix clients exercise the very same body with explicit host fault leaves. +/// Later book extensions are acquired inside that body from both the constants' +/// and the history's finite published snapshots before deriving DSL semantics. +pub(crate) fn compiled_cached_decision( + compiled: &mut CompiledRule, history: &History, candidate: &E, + limits: &mut L, world: &mut ObservationWorld, +) -> (result: Result, HistoryError>) + requires typed::decision_requires(*old(compiled), *history), + ensures typed::decision_result(*old(compiled), *final(compiled), *history, *candidate, result), + junco_core::spec::hypotheses::event_obligations::() ==> + typed::dsl_result(typed::source_rule(*old(compiled)), *history, *candidate, result), +{ + compiled.accepts_history_with_limits(history, candidate, limits, world) +} + +// These clients exercise construction and transactions, rather than assuming a verdict. +pub(crate) fn validator_check_client( + state: &mut Validator, request: Request, +) -> (result: Result, HistoryError>) + requires old(state).wf(), + ensures final(state).wf(), check_frame(old(state)@, final(state)@, request, result), + junco_core::spec::hypotheses::event_obligations::() ==> check_step(old(state)@, request, result), +{ + state.check(request) +} + +pub(crate) fn compiled_policy_decide_client C>( + state: &mut CompiledPolicy, history: &History, candidate: &E, context: F, +) -> (result: Result) + requires policy::policy_wf(*old(state)), raw::history_wf(*history), call_requires(context, ()), + ensures policy_decision_result(*old(state), *final(state), *history, *candidate, result), +{ + state.decide(history, candidate, context) +} + +pub(crate) fn validator_from_rules_client( + store: Arc>, rules: Vec>, +) -> (result: Result, CompileError>) + requires books::store_wf(*store), + ensures result matches Ok(state) ==> state.wf() + && state@.rules == dsl::rule_views(rules@) && state@.history == Seq::::empty(), +{ + let ghost original = rules@; + let count = rules.len(); + let mut builder = Validator::builder(store); + let mut remaining = rules.into_iter(); + let mut index: usize = 0; + proof { assert(builder.rules() =~= dsl::rule_views(original.take(0))); } + while index < count + invariant count == original.len(), index <= original.len(), builder.wf(), + builder.rules() == dsl::rule_views(original.take(index as int)), + remaining.remaining() == original.skip(index as int), + remaining.obeys_prophetic_iter_laws(), + decreases original.len() - index, + { + let item = remaining.next(); + match item { + Some(source) => { builder.add_rule(source)?; }, + None => { proof { assert(false); } }, + } + index += 1; + proof { + assert(builder.rules() =~= dsl::rule_views(original.take(index as int))); + } + } + let state = builder.finish()?; + proof { assert(original.take(original.len() as int) =~= original); } + Ok(state) +} + +pub(crate) fn compiled_policy_from_vec_client( + store: Arc>, rules: Vec>, +) -> (result: Result, CompileError>) + requires books::store_wf(*store), + ensures result matches Ok(state) ==> policy::policy_wf(state) + && policy::policy_store(state) == store + && policy::policy_sources(state) == rules@.map(|i: int, item: PolicyRule| policy_rule_source(item)) + && policy::policy_diagnostic_ids(state) == rules@.map(|i: int, item: PolicyRule| policy_rule_diagnostic(item)) + && policy::policy_trace_empty(state), +{ + CompiledPolicy::new(store, rules) +} + +pub(crate) fn validator_require_empty_then_forbid_all_client( + store: Arc>, request: Request, head: Head, second_head: Head, +) -> (result: Result<(Validator, Decision), CompileError>) + requires books::store_wf(*store), junco_core::spec::hypotheses::event_obligations::(), dsl::head_matches(head@, history_syntax::spec::events::event_view(request.event)), second_head == head, + ensures result matches Ok((state, decision)) ==> state.wf() + && state@.rules == dsl::rule_views(seq![Rule { mode: RuleMode::Require, head: head, tail: RegexExpr::Empty }, Rule { mode: RuleMode::Forbid, head: second_head, tail: RegexExpr::All }]) + && state@.history == Seq::::empty() + && dsl::least_violation(state@.rules, request.event, state@.history, 0) + && decision is Denied && (decision matches Decision::Denied(denial) ==> denial.mode == RuleMode::Require && denial.event == request.event), +{ + let mut rules = Vec::new(); + rules.push(Rule { mode: RuleMode::Require, head: head, tail: RegexExpr::Empty }); + rules.push(Rule { mode: RuleMode::Forbid, head: second_head, tail: RegexExpr::All }); + let ghost sources = rules@; + let mut state = validator_from_rules_client(store, rules)?; + let ghost before = state; + proof { + assert(state@.rules[0] == sources[0]@); + assert(dsl::least_violation(state@.rules, request.event, state@.history, 0)); + } + let decision = validator_check_client(&mut state, request)?; + proof { lemma_denied_at_zero(before@, request, decision); } + Ok((state, decision)) +} + +pub(crate) fn validator_forbid_all_then_require_empty_client( + store: Arc>, request: Request, head: Head, second_head: Head, +) -> (result: Result<(Validator, Decision), CompileError>) + requires books::store_wf(*store), junco_core::spec::hypotheses::event_obligations::(), dsl::head_matches(head@, history_syntax::spec::events::event_view(request.event)), second_head == head, + ensures result matches Ok((state, decision)) ==> state.wf() + && state@.rules == dsl::rule_views(seq![Rule { mode: RuleMode::Forbid, head: head, tail: RegexExpr::All }, Rule { mode: RuleMode::Require, head: second_head, tail: RegexExpr::Empty }]) + && state@.history == Seq::::empty() + && dsl::least_violation(state@.rules, request.event, state@.history, 0) + && decision is Denied && (decision matches Decision::Denied(denial) ==> denial.mode == RuleMode::Forbid && denial.event == request.event), +{ + let mut rules = Vec::new(); + rules.push(Rule { mode: RuleMode::Forbid, head: head, tail: RegexExpr::All }); + rules.push(Rule { mode: RuleMode::Require, head: second_head, tail: RegexExpr::Empty }); + let ghost sources = rules@; + let mut state = validator_from_rules_client(store, rules)?; + let ghost before = state; + proof { + assert(state@.rules[0] == sources[0]@); + assert(dsl::least_violation(state@.rules, request.event, state@.history, 0)); + } + let decision = validator_check_client(&mut state, request)?; + proof { lemma_denied_at_zero(before@, request, decision); } + Ok((state, decision)) +} + +/// A `check_step` whose first rule is violated denies with that rule's mode. +proof fn lemma_denied_at_zero(before: crate::spec::monitor::ValidatorView, request: Request, decision: Decision) + requires check_step(before, request, Ok(decision)), + dsl::least_violation(before.rules, request.event, before.history, 0), + ensures decision is Denied, + decision matches Decision::Denied(denial) ==> denial.mode == before.rules[0].mode, +{ + match decision { + Decision::Grant(_) => { + assert(dsl::policy_denies(before.rules, request.event, before.history)); + }, + Decision::Denied(denial) => { + let index = choose|i: int| #[trigger] dsl::least_violation(before.rules, request.event, before.history, i) + && denial.mode == before.rules[i].mode; + if index > 0 { + assert(!dsl::rule_violated(before.rules[0], request.event, before.history)); + } + }, + } +} + +pub(crate) fn validator_require_all_and_forbid_empty_client( + store: Arc>, request: Request, head: Head, second_head: Head, +) -> (result: Result<(Validator, Decision), CompileError>) + requires books::store_wf(*store), junco_core::spec::hypotheses::event_obligations::(), dsl::head_matches(head@, history_syntax::spec::events::event_view(request.event)), second_head == head, + ensures result matches Ok((state, decision)) ==> state.wf() + && state@.rules == dsl::rule_views(seq![Rule { mode: RuleMode::Require, head: head, tail: RegexExpr::All }, Rule { mode: RuleMode::Forbid, head: second_head, tail: RegexExpr::Empty }]) + && state@.history == seq![request.event] + && decision is Grant && (decision matches Decision::Grant(grant) ==> grant.event == request.event && grant.metadata == request.metadata), +{ + let mut rules = Vec::new(); + rules.push(Rule { mode: RuleMode::Require, head: head, tail: RegexExpr::All }); + rules.push(Rule { mode: RuleMode::Forbid, head: second_head, tail: RegexExpr::Empty }); + let ghost sources = rules@; + let mut state = validator_from_rules_client(store, rules)?; + let ghost before = state; + proof { + assert forall|i: int| 0 <= i < state@.rules.len() implies + !dsl::rule_violated(state@.rules[i], request.event, state@.history) by { + assert(state@.rules[i] == sources[i]@); + } + } + let decision = validator_check_client(&mut state, request)?; + proof { lemma_granted(before@, state@, request, decision); } + Ok((state, decision)) +} + +pub(crate) fn validator_head_mismatch_client( + store: Arc>, request: Request, head: Head, +) -> (result: Result<(Validator, Decision), CompileError>) + requires books::store_wf(*store), junco_core::spec::hypotheses::event_obligations::(), !dsl::head_matches(head@, history_syntax::spec::events::event_view(request.event)), + ensures result matches Ok((state, decision)) ==> state.wf() + && state@.rules == dsl::rule_views(seq![Rule { mode: RuleMode::Require, head: head, tail: RegexExpr::Empty }]) + && state@.history == seq![request.event] + && decision is Grant && (decision matches Decision::Grant(grant) ==> grant.event == request.event && grant.metadata == request.metadata), +{ + let mut rules = Vec::new(); + rules.push(Rule { mode: RuleMode::Require, head: head, tail: RegexExpr::Empty }); + let ghost sources = rules@; + let mut state = validator_from_rules_client(store, rules)?; + let ghost before = state; + proof { + assert forall|i: int| 0 <= i < state@.rules.len() implies + !dsl::rule_violated(state@.rules[i], request.event, state@.history) by { + assert(state@.rules[i] == sources[i]@); + } + } + let decision = validator_check_client(&mut state, request)?; + proof { lemma_granted(before@, state@, request, decision); } + Ok((state, decision)) +} + +pub(crate) fn validator_empty_table_client( + store: Arc>, request: Request, +) -> (result: Result<(Validator, Decision), CompileError>) + requires books::store_wf(*store), junco_core::spec::hypotheses::event_obligations::(), + ensures result matches Ok((state, decision)) ==> state.wf() + && state@.rules == Seq::>::empty() + && state@.history == seq![request.event] + && decision is Grant && (decision matches Decision::Grant(grant) ==> grant.event == request.event && grant.metadata == request.metadata), +{ + let rules = Vec::new(); + let mut state = validator_from_rules_client(store, rules)?; + let ghost before = state; + proof { assert(state@.rules =~= Seq::>::empty()); } + let decision = validator_check_client(&mut state, request)?; + proof { lemma_granted(before@, state@, request, decision); } + Ok((state, decision)) +} + +/// A `check` on an empty history that violates no rule grants and commits exactly the event. +proof fn lemma_granted(before: crate::spec::monitor::ValidatorView, after: crate::spec::monitor::ValidatorView, request: Request, decision: Decision) + requires check_frame(before, after, request, Ok(decision)), check_step(before, request, Ok(decision)), + before.history == Seq::::empty(), + forall|i: int| 0 <= i < before.rules.len() ==> !dsl::rule_violated(before.rules[i], request.event, before.history), + ensures decision is Grant, after.history == seq![request.event], + decision matches Decision::Grant(grant) ==> grant.event == request.event && grant.metadata == request.metadata, +{ + if let Decision::Denied(denial) = decision { + let index = choose|i: int| #[trigger] dsl::least_violation(before.rules, request.event, before.history, i) + && denial.mode == before.rules[i].mode; + assert(false); + } + assert(after.history =~= seq![request.event]); +} + +pub(crate) fn compiled_policy_require_empty_then_forbid_all_client C>( + store: Arc>, rules: Vec>, history: &History, candidate: &E, context: F, head: Ghost>, second_head: Ghost>, +) -> (result: Result<(CompiledPolicy, PolicyDecision), CompileError>) + requires books::store_wf(*store), raw::history_wf(*history), junco_core::spec::hypotheses::event_obligations::(), rules@.map(|i: int, item: PolicyRule| policy_rule_source(item)) == seq![Rule { mode: RuleMode::Require, head: head@, tail: RegexExpr::Empty }, Rule { mode: RuleMode::Forbid, head: second_head@, tail: RegexExpr::All }], dsl::head_matches(head@@, history_syntax::spec::events::event_view(*candidate)), second_head@ == head@, + call_requires(context, ()), + ensures result matches Ok((state, decision)) ==> policy::policy_wf(state) + && policy::policy_sources(state) == rules@.map(|i: int, item: PolicyRule| policy_rule_source(item)) + && policy::policy_diagnostic_ids(state) == rules@.map(|i: int, item: PolicyRule| policy_rule_diagnostic(item)) + && decision is Deny && policy::policy_trace(state).calls.len() == 1 + && policy::policy_trace(state).context_calls == 1 && policy::policy_trace(state).diagnostic_calls == 1 + && policy::policy_trace(state).calls[0].index == 0 + && policy::policy_trace(state).calls[0].source == policy_rule_source(rules@[0]) + && policy::policy_trace(state).calls[0].diagnostic_id == policy_rule_diagnostic(rules@[0]), +{ + let mut state = compiled_policy_from_vec_client(store, rules)?; + let ghost before = state; + proof { + assert(dsl::least_violation(dsl::rule_views(policy::policy_sources(state)), *candidate, raw::raw_events(*history), 0)); + } + let decision = compiled_policy_decide_client(&mut state, history, candidate, context)?; + proof { + if decision is Deny { + let index = policy::policy_trace(state).calls.last().index; + assert(index == 0) by { + if index > 0 { assert(!dsl::rule_violated(policy::policy_sources(before)[0]@, *candidate, raw::raw_events(*history))); } + } + } + } + Ok((state, decision)) +} + +pub(crate) fn compiled_policy_forbid_all_then_require_empty_client C>( + store: Arc>, rules: Vec>, history: &History, candidate: &E, context: F, head: Ghost>, second_head: Ghost>, +) -> (result: Result<(CompiledPolicy, PolicyDecision), CompileError>) + requires books::store_wf(*store), raw::history_wf(*history), junco_core::spec::hypotheses::event_obligations::(), rules@.map(|i: int, item: PolicyRule| policy_rule_source(item)) == seq![Rule { mode: RuleMode::Forbid, head: head@, tail: RegexExpr::All }, Rule { mode: RuleMode::Require, head: second_head@, tail: RegexExpr::Empty }], dsl::head_matches(head@@, history_syntax::spec::events::event_view(*candidate)), second_head@ == head@, + call_requires(context, ()), + ensures result matches Ok((state, decision)) ==> policy::policy_wf(state) + && policy::policy_sources(state) == rules@.map(|i: int, item: PolicyRule| policy_rule_source(item)) + && policy::policy_diagnostic_ids(state) == rules@.map(|i: int, item: PolicyRule| policy_rule_diagnostic(item)) + && decision is Deny && policy::policy_trace(state).calls.len() == 1 + && policy::policy_trace(state).context_calls == 1 && policy::policy_trace(state).diagnostic_calls == 1 + && policy::policy_trace(state).calls[0].index == 0 + && policy::policy_trace(state).calls[0].source == policy_rule_source(rules@[0]) + && policy::policy_trace(state).calls[0].diagnostic_id == policy_rule_diagnostic(rules@[0]), +{ + let mut state = compiled_policy_from_vec_client(store, rules)?; + let ghost before = state; + proof { + assert(dsl::least_violation(dsl::rule_views(policy::policy_sources(state)), *candidate, raw::raw_events(*history), 0)); + } + let decision = compiled_policy_decide_client(&mut state, history, candidate, context)?; + proof { + if decision is Deny { + let index = policy::policy_trace(state).calls.last().index; + assert(index == 0) by { + if index > 0 { assert(!dsl::rule_violated(policy::policy_sources(before)[0]@, *candidate, raw::raw_events(*history))); } + } + } + } + Ok((state, decision)) +} + +pub(crate) fn compiled_policy_require_all_and_forbid_empty_client C>( + store: Arc>, rules: Vec>, history: &History, candidate: &E, context: F, head: Ghost>, second_head: Ghost>, +) -> (result: Result<(CompiledPolicy, PolicyDecision), CompileError>) + requires books::store_wf(*store), raw::history_wf(*history), junco_core::spec::hypotheses::event_obligations::(), rules@.map(|i: int, item: PolicyRule| policy_rule_source(item)) == seq![Rule { mode: RuleMode::Require, head: head@, tail: RegexExpr::All }, Rule { mode: RuleMode::Forbid, head: second_head@, tail: RegexExpr::Empty }], dsl::head_matches(head@@, history_syntax::spec::events::event_view(*candidate)), second_head@ == head@, + call_requires(context, ()), + ensures result matches Ok((state, decision)) ==> policy::policy_wf(state) + && policy::policy_sources(state) == rules@.map(|i: int, item: PolicyRule| policy_rule_source(item)) + && policy::policy_diagnostic_ids(state) == rules@.map(|i: int, item: PolicyRule| policy_rule_diagnostic(item)) + && decision is Grant && policy::policy_trace_empty(state) + && policy::policy_trace(state).context_calls == 0 && policy::policy_trace(state).diagnostic_calls == 0, +{ + let mut state = compiled_policy_from_vec_client(store, rules)?; + proof { + assert forall|i: int| 0 <= i < policy::policy_sources(state).len() implies + !dsl::rule_violated(policy::policy_sources(state)[i]@, *candidate, raw::raw_events(*history)) by {} + } + let decision = compiled_policy_decide_client(&mut state, history, candidate, context)?; + Ok((state, decision)) +} + +pub(crate) fn compiled_policy_head_mismatch_client C>( + store: Arc>, rules: Vec>, history: &History, candidate: &E, context: F, head: Ghost>, +) -> (result: Result<(CompiledPolicy, PolicyDecision), CompileError>) + requires books::store_wf(*store), raw::history_wf(*history), junco_core::spec::hypotheses::event_obligations::(), rules@.map(|i: int, item: PolicyRule| policy_rule_source(item)) == seq![Rule { mode: RuleMode::Require, head: head@, tail: RegexExpr::Empty }], !dsl::head_matches(head@@, history_syntax::spec::events::event_view(*candidate)), + call_requires(context, ()), + ensures result matches Ok((state, decision)) ==> policy::policy_wf(state) + && policy::policy_sources(state) == rules@.map(|i: int, item: PolicyRule| policy_rule_source(item)) + && policy::policy_diagnostic_ids(state) == rules@.map(|i: int, item: PolicyRule| policy_rule_diagnostic(item)) + && decision is Grant && policy::policy_trace_empty(state) + && policy::policy_trace(state).context_calls == 0 && policy::policy_trace(state).diagnostic_calls == 0, +{ + let mut state = compiled_policy_from_vec_client(store, rules)?; + proof { + assert forall|i: int| 0 <= i < policy::policy_sources(state).len() implies + !dsl::rule_violated(policy::policy_sources(state)[i]@, *candidate, raw::raw_events(*history)) by {} + } + let decision = compiled_policy_decide_client(&mut state, history, candidate, context)?; + Ok((state, decision)) +} + +pub(crate) fn compiled_policy_empty_table_client C>( + store: Arc>, rules: Vec>, history: &History, candidate: &E, context: F, +) -> (result: Result<(CompiledPolicy, PolicyDecision), CompileError>) + requires books::store_wf(*store), raw::history_wf(*history), junco_core::spec::hypotheses::event_obligations::(), rules@.map(|i: int, item: PolicyRule| policy_rule_source(item)) == seq![], + call_requires(context, ()), + ensures result matches Ok((state, decision)) ==> policy::policy_wf(state) + && policy::policy_sources(state) == rules@.map(|i: int, item: PolicyRule| policy_rule_source(item)) + && policy::policy_diagnostic_ids(state) == rules@.map(|i: int, item: PolicyRule| policy_rule_diagnostic(item)) + && decision is Grant && policy::policy_trace_empty(state) + && policy::policy_trace(state).context_calls == 0 && policy::policy_trace(state).diagnostic_calls == 0, +{ + let mut state = compiled_policy_from_vec_client(store, rules)?; + proof { + assert forall|i: int| 0 <= i < policy::policy_sources(state).len() implies + !dsl::rule_violated(policy::policy_sources(state)[i]@, *candidate, raw::raw_events(*history)) by {} + } + let decision = compiled_policy_decide_client(&mut state, history, candidate, context)?; + Ok((state, decision)) +} + +} diff --git a/src/history-semantics/tests/public_specs.rs b/src/history-semantics/tests/public_specs.rs new file mode 100644 index 000000000..dc1774a28 --- /dev/null +++ b/src/history-semantics/tests/public_specs.rs @@ -0,0 +1,749 @@ +#![cfg(all(verus_keep_ghost, feature = "runtime"))] + +extern crate alloc; + +use alloc::{boxed::Box, string::String, sync::Arc, vec::Vec}; +use history_semantics::compiled_rule::{CompiledRule, verify as compiled}; +use history_semantics::policy::evaluate::verify as policy; +use history_semantics::policy::rule::verify::diagnostic_output; +use history_semantics::policy::trace::verify as trace; +use history_semantics::policy::{CompiledPolicy, PolicyDecision, TracePolicy, TraceRule}; +use history_semantics::validator::{Decision, Validator}; +use history_store::history::{History, verify as history}; +use history_store::store::{HistoryStore, verify as records}; +use history_store::typed::{Store, share_store, verify as books}; +use history_syntax::event::specs::EventSpec; +use history_syntax::spec::events::{ + HeadView, RegexView, TestView, arity, event_view, projection_laws, +}; +use history_syntax::{Component, Event, Head, MAX_ARITY, RegexExpr, Rule, RuleMode}; +use junco_core::event::Request; +use junco_core::limits::Limits; +use junco_core::observation::ObservationWorld; +use junco_core::spec::semantics as dsl; +use junco_core::verify::history_specs; +use junco_core::{CompileError, HistoryError}; +use vstd::prelude::*; +use vstd::view::DeepView; + +verus! { +broadcast use {vstd::std_specs::vec::group_vec_axioms, vstd::seq::group_seq_lemmas, + junco_core::verify::dsl::lemma_rule_views_index}; + +fn indexed_projection(event: E, index: usize) -> (result: (E::Component, usize)) + requires E::obeys_projection_spec(), projection_laws::(), index < arity::(), + ensures result.0 == event_view(event)[index as int], result.1 == index, +{ + let component = event.component(index); + let coordinate = E::coordinate(component); + proof { + assert(E::coordinate_spec(event.component_spec(index as int)) == index); + } + (component, coordinate) +} + +// Native event laws are needed for semantic answers, not for construction or exact sequences. +fn vec_history(events: Vec) -> (result: Result, HistoryError>) + ensures result matches Ok(value) ==> history::history_wf(value) + && history::raw_events(value) == events@ + && value.spec_numeric().spec_revision() == 0, +{ + let store = Arc::new(Store::::new()?); + proof { history_specs::lemma_vec_into_iter_yields(events); } + let value = History::from_events(store, events)?; + proof { history::lemma_initialized_history_facts(value, store); } + Ok(value) +} + +// Scoped native sources cannot manufacture structural or scope errors. +fn scoped_production_compile(source: Rule) + -> (result: Result, CompileError>) + requires junco_core::spec::hypotheses::event_obligations::(), dsl::head_scoped(source.head@), + dsl::regex_scoped(source.tail@, source.head@), + ensures history_specs::no_invariant_compile_failure(result), + !(result matches Err(CompileError::VariableComponentConflict { .. })), + !(result matches Err(CompileError::UnboundVariable { .. })), + !(result matches Err(CompileError::Runtime(HistoryError::InvalidPolicy { .. }))), +{ + let store = Arc::new(Store::::new()?); + CompiledRule::new(store, source) +} + +// One executable client is universally instantiated over all five truth-table cases. +fn compiled_truth_table( + head: Head, mode: RuleMode, universal: bool, events: Vec, candidate: &E, +) -> (result: Result<(History, CompiledRule, Result, HistoryError>), CompileError>) + requires junco_core::spec::hypotheses::event_obligations::(), + ensures result matches Ok((value, rule, answer)) ==> + history::raw_events(value) == events@ + && compiled::source_rule(rule) == (Rule { mode, head, + tail: if universal { RegexExpr::All } else { RegexExpr::Empty } }) + && answer != Err(HistoryError::WrongHistoryOwner) + && history_specs::no_invariant_failure(answer) + && (answer matches Ok(option) ==> + option == (if dsl::head_matches(head@, event_view(*candidate)) { + Some(universal) + } else { None })) + && (answer is Ok ==> dsl::rule_violated(compiled::source_rule(rule)@, *candidate, events@) + == (dsl::head_matches(head@, event_view(*candidate)) + && match mode { RuleMode::Require => !universal, RuleMode::Forbid => universal })), +{ + let store = Arc::new(Store::::new()?); + let owner = share_store(&store); + proof { books::lemma_same_store_owner_identity(store, owner); } + proof { history_specs::lemma_vec_into_iter_yields(events); } + let value = History::from_events(owner, events)?; + let tail = if universal { RegexExpr::All } else { RegexExpr::Empty }; + let source = Rule::new(mode, head, tail); + let ghost original = source; + let mut rule = CompiledRule::new(store, source)?; + proof { + history::lemma_initialized_history_facts(value, owner); + compiled::lemma_constructed_decision(rule, original, store, value); + } + let ghost before = rule; + let answer = rule.accepts_history(&value, candidate); + proof { + compiled::lemma_decision_result_facts(before, rule, value, *candidate, answer); + if answer is Ok { + assert(answer == Ok(dsl::rule_evaluation(original@, *candidate, events@))); + } + } + Ok((value, rule, answer)) +} + +fn five_decision_cases(mismatch: Head, require_all: Head, forbid_all: Head, + require_empty: Head, forbid_empty: Head, candidate: &E) -> Result<(), CompileError> + requires junco_core::spec::hypotheses::event_obligations::(), + !dsl::head_matches(mismatch@, event_view(*candidate)), + dsl::head_matches(require_all@, event_view(*candidate)), + dsl::head_matches(forbid_all@, event_view(*candidate)), + dsl::head_matches(require_empty@, event_view(*candidate)), + dsl::head_matches(forbid_empty@, event_view(*candidate)), +{ + let (value, rule, answer) = compiled_truth_table(mismatch, RuleMode::Require, false, Vec::new(), candidate)?; + assert(answer is Ok ==> answer == Ok(None)); + assert(answer is Ok ==> !dsl::rule_violated(compiled::source_rule(rule)@, *candidate, history::raw_events(value))); + let (value, rule, answer) = compiled_truth_table(require_all, RuleMode::Require, true, Vec::new(), candidate)?; + assert(answer is Ok ==> answer == Ok(Some(true))); + assert(answer is Ok ==> !dsl::rule_violated(compiled::source_rule(rule)@, *candidate, history::raw_events(value))); + let (value, rule, answer) = compiled_truth_table(forbid_all, RuleMode::Forbid, true, Vec::new(), candidate)?; + assert(answer is Ok ==> answer == Ok(Some(true))); + assert(answer is Ok ==> dsl::rule_violated(compiled::source_rule(rule)@, *candidate, history::raw_events(value))); + let (value, rule, answer) = compiled_truth_table(require_empty, RuleMode::Require, false, Vec::new(), candidate)?; + assert(answer is Ok ==> answer == Ok(Some(false))); + assert(answer is Ok ==> dsl::rule_violated(compiled::source_rule(rule)@, *candidate, history::raw_events(value))); + let (value, rule, answer) = compiled_truth_table(forbid_empty, RuleMode::Forbid, false, Vec::new(), candidate)?; + assert(answer is Ok ==> answer == Ok(Some(false))); + assert(answer is Ok ==> !dsl::rule_violated(compiled::source_rule(rule)@, *candidate, history::raw_events(value))); + Ok(()) +} + +// No Event/projection premise is needed to rule out selection from an empty table. +fn empty_policy(events: Vec, candidate: &E) + -> (result: Result<(CompiledPolicy, Result), CompileError>) + ensures result matches Ok((state, answer)) ==> + policy::policy_sources(state) == Seq::>::empty() + && policy::policy_context_calls(state) == 0 + && policy::policy_diagnostic_calls(state) == 0 + && (answer is Ok ==> answer == Ok(PolicyDecision::Grant)), +{ + let store = Arc::new(Store::::new()?); + let owner = share_store(&store); + proof { history_specs::lemma_vec_into_iter_yields(events); } + let value = History::from_events(owner, events)?; + let rules = Vec::>::new(); + let mut state = CompiledPolicy::new(store, rules)?; + proof { policy::lemma_policy_wf(state); } + let ghost before = state; + let context = || (); + let answer = state.decide(&value, candidate, context); + proof { policy::lemma_policy_decision_result_facts(before, state, value, *candidate, answer); } + Ok((state, answer)) +} + +// Both rules violate. Selection is by index, without assuming distinct callback identities. +fn trace_first_diagnostic (String, Vec) + Send + Sync + 'static, + D1: Fn(&E) -> (String, Vec) + Send + Sync + 'static>( + first_head: Head, second_head: Head, events: Vec, candidate: &E, + first_diagnostic: D0, second_diagnostic: D1, +) -> (result: Result<(History, TracePolicy, Result), CompileError>) + requires junco_core::spec::hypotheses::event_obligations::(), + dsl::head_matches(first_head@, event_view(*candidate)), + dsl::head_matches(second_head@, event_view(*candidate)), + forall|argument: &E| call_requires(first_diagnostic, (argument,)), + forall|argument: &E| call_requires(second_diagnostic, (argument,)), + ensures result matches Ok((value, state, answer)) ==> + history::raw_events(value) == events@ + && trace::trace_sources(state) == seq![ + Rule { mode: RuleMode::Forbid, head: first_head, tail: RegexExpr::All }, + Rule { mode: RuleMode::Require, head: second_head, tail: RegexExpr::Empty }] + && trace::trace_diagnostic_ids(state) == seq![ + trace::trace_callback_identity(first_diagnostic), trace::trace_callback_identity(second_diagnostic)] + && answer != Err(HistoryError::WrongHistoryOwner) + && match answer { + Err(_) => trace::trace_context_calls(state) == 0 && trace::trace_diagnostic_calls(state) == 0, + Ok(PolicyDecision::Grant) => false, + Ok(PolicyDecision::Deny { failed_precondition, allowed_fixes }) => + trace::trace_context_calls(state) == 1 && trace::trace_diagnostic_calls(state) == 1 + && trace::trace_selected_index(state) == 0 + && trace::trace_selected_diagnostic_id(state) == trace::trace_callback_identity(first_diagnostic) + && diagnostic_output(trace::trace_callback_identity(first_diagnostic), *candidate, + failed_precondition@, allowed_fixes.deep_view()) + && exists|argument: &E| *argument == *candidate + && call_ensures(first_diagnostic, (argument,), (failed_precondition, allowed_fixes)), + }, +{ + let store = Arc::new(Store::::new()?); + let owner = share_store(&store); + proof { books::lemma_same_store_owner_identity(store, owner); } + proof { history_specs::lemma_vec_into_iter_yields(events); } + let value = History::from_events(owner, events)?; + proof { history::lemma_initialized_history_facts(value, owner); } + let first = Rule::new(RuleMode::Forbid, first_head, RegexExpr::All); + let second = Rule::new(RuleMode::Require, second_head, RegexExpr::Empty); + let ghost first_source = first; + let ghost second_source = second; + proof { + assert(first_source.tail@ == RegexView::All); + assert(second_source.tail@ == RegexView::Empty); + assert(dsl::lang(first_source.tail@, first_head@, event_view(*candidate), + events@.map(|i: int, event: E| event_view(event)))); + assert(!dsl::lang(second_source.tail@, second_head@, event_view(*candidate), + events@.map(|i: int, event: E| event_view(event)))); + assert(dsl::rule_evaluation(first_source@, *candidate, events@) == Some(true)); + assert(dsl::rule_evaluation(second_source@, *candidate, events@) == Some(false)); + assert(dsl::rule_violated(first_source@, *candidate, events@)); + assert(dsl::rule_violated(second_source@, *candidate, events@)); + } + let first = TraceRule::new(first, first_diagnostic); + let second = TraceRule::new(second, second_diagnostic); + let ghost first_rule = first; + proof { + assert forall|value: E, output: (String, Vec)| + #[trigger] diagnostic_output(trace::trace_rule_diagnostic_id(first_rule), value, output.0@, output.1.deep_view()) + implies exists|argument: &E| *argument == value && call_ensures(first_diagnostic, (argument,), output) by {} + } + let mut rules = Vec::new(); + rules.push(first); + rules.push(second); + proof { history_specs::lemma_vec_into_iter_yields(rules); } + let ghost items = rules@; + let mut state = TracePolicy::new(store, rules)?; + proof { + assert(trace::trace_sources(state) + == items.map(|i: int, item: TraceRule| trace::trace_rule_source(item))); + assert(trace::trace_diagnostic_ids(state) + == items.map(|i: int, item: TraceRule| trace::trace_rule_diagnostic_id(item))); + assert(trace::trace_sources(state) =~= seq![first_source, second_source]); + assert(trace::trace_diagnostic_ids(state) =~= seq![ + trace::trace_callback_identity(first_diagnostic), trace::trace_callback_identity(second_diagnostic)]); + assert(trace::trace_context_calls(state) == 0); + assert(trace::trace_diagnostic_calls(state) == 0); + assert(trace::trace_store(state) == store); + assert(books::same_store_owner(trace::trace_store(state), history::store_of(value))); + } + let ghost before = state; + let ghost raw_before = history::raw_events(value); + let answer = state.decide(&value, candidate); + proof { + trace::lemma_trace_decision_result_facts(before, state, value, *candidate, answer); + assert(history::raw_events(value) == raw_before); + if let Ok(PolicyDecision::Grant) = answer { + assert(dsl::rule_views(trace::trace_sources(before))[0] == first_source@); + assert(dsl::policy_denies(dsl::rule_views(trace::trace_sources(before)), *candidate, events@)); + assert(false); + } + if let Ok(PolicyDecision::Deny { ref failed_precondition, ref allowed_fixes }) = answer { + let index = trace::trace_selected_index(state) as int; + assert(dsl::least_violation(dsl::rule_views(trace::trace_sources(before)), *candidate, history::raw_events(value), index)); + assert(0 <= index < 2); + if index != 0 { + assert(0 <= 0 < index); + assert(!dsl::rule_violated(trace::trace_sources(before)[0]@, *candidate, events@)); + assert(false); + } + assert(trace::trace_selected_index(state) == 0); + assert(diagnostic_output(trace::trace_rule_diagnostic_id(first_rule), *candidate, + failed_precondition@, allowed_fixes.deep_view())); + let output = (*failed_precondition, *allowed_fixes); + assert(diagnostic_output(trace::trace_rule_diagnostic_id(first_rule), *candidate, output.0@, output.1.deep_view())); + assert(exists|argument: &E| *argument == *candidate + && call_ensures(first_diagnostic, (argument,), (*failed_precondition, *allowed_fixes))); + } + } + Ok((value, state, answer)) +} + +fn validator_transaction(head: Head, universal: bool, request: Request) + -> (result: Result<(Validator, Result, HistoryError>), CompileError>) + requires junco_core::spec::hypotheses::event_obligations::(), dsl::head_matches(head@, event_view(request.event)), + ensures result matches Ok((state, answer)) ==> state.wf() + && match answer { + Ok(Decision::Grant(grant)) => universal && grant.event == request.event + && grant.metadata == request.metadata + && state@.history == seq![request.event], + Ok(Decision::Denied(denial)) => !universal && denial.event == request.event + && denial.mode == RuleMode::Require + && denial.index == 0 + && state@.history == Seq::::empty(), + Err(_) => state@.history == Seq::::empty(), + }, +{ + let store = Arc::new(Store::::new()?); + let mut builder = Validator::builder(store); + let tail = if universal { RegexExpr::All } else { RegexExpr::Empty }; + let rule = Rule::new(RuleMode::Require, head, tail); + let ghost source = rule; + builder.add_rule(rule)?; + proof { assert(builder.rules() =~= seq![source@]); } + let mut state = builder.finish()?; + let ghost before = state; + proof { + assert(before@.rules == seq![source@]); + assert(before@.history == Seq::::empty()); + assert(source.tail@ == if universal { RegexView::All } else { RegexView::Empty }); + assert(dsl::lang(source.tail@, head@, event_view(request.event), + Seq::::empty().map(|i: int, event: E| event_view(event))) == universal); + assert(dsl::rule_evaluation(source@, request.event, Seq::::empty()) == Some(universal)); + assert(dsl::rule_violated(source@, request.event, Seq::::empty()) == !universal); + } + let answer = state.check(request); + proof { + match answer { + Ok(Decision::Grant(_)) => { + if !universal { + assert(before@.rules[0] == source@); + assert(dsl::rule_violated(before@.rules[0], request.event, before@.history)); + assert(dsl::policy_denies(before@.rules, request.event, before@.history)); + } + assert(state@.history =~= seq![request.event]); + }, + Ok(Decision::Denied(ref denial)) => { + let index = denial.index as int; + assert(index == 0); + assert(dsl::rule_violated(before@.rules[0], request.event, before@.history)); + }, + Err(_) => {}, + } + } + Ok((state, answer)) +} + +fn trace_observations(rules: Vec>, events: Vec, candidate: &E) + -> (result: Result<(History, TracePolicy, Result), CompileError>) + ensures result matches Ok((value, state, answer)) ==> + history::raw_events(value) == events@ + && trace::trace_sources(state) == rules@.map(|i: int, item: TraceRule| trace::trace_rule_source(item)) + && trace::trace_diagnostic_ids(state) == rules@.map(|i: int, item: TraceRule| trace::trace_rule_diagnostic_id(item)) + && match answer { + Err(_) => trace::trace_context_calls(state) == 0 && trace::trace_diagnostic_calls(state) == 0, + Ok(PolicyDecision::Grant) => trace::trace_context_calls(state) == 0 + && trace::trace_diagnostic_calls(state) == 0 + && (junco_core::spec::hypotheses::event_obligations::() ==> + dsl::policy_permits(dsl::rule_views(trace::trace_sources(state)), *candidate, events@)), + Ok(PolicyDecision::Deny { failed_precondition, allowed_fixes }) => + trace::trace_context_calls(state) == 1 && trace::trace_diagnostic_calls(state) == 1 + && trace::trace_selected_index(state) < rules@.len() + && trace::trace_selected_diagnostic_id(state) + == trace::trace_rule_diagnostic_id(rules@[trace::trace_selected_index(state) as int]) + && diagnostic_output(trace::trace_selected_diagnostic_id(state), *candidate, + failed_precondition@, allowed_fixes.deep_view()) + && (junco_core::spec::hypotheses::event_obligations::() ==> + dsl::least_violation(dsl::rule_views(trace::trace_sources(state)), *candidate, events@, + trace::trace_selected_index(state) as int)), + }, +{ + let store = Arc::new(Store::::new()?); + let owner = share_store(&store); + proof { + history_specs::lemma_vec_into_iter_yields(events); + history_specs::lemma_vec_into_iter_yields(rules); + } + let value = History::from_events(owner, events)?; + let ghost items = rules@; + let mut state = TracePolicy::new(store, rules)?; + proof { + assert(history::raw_events(value) == events@); + assert(trace::trace_sources(state) + == items.map(|i: int, item: TraceRule| trace::trace_rule_source(item))); + assert(trace::trace_diagnostic_ids(state) + == items.map(|i: int, item: TraceRule| trace::trace_rule_diagnostic_id(item))); + assert(trace::trace_sources(state).len() == items.len()); + assert(trace::trace_context_calls(state) == 0); + assert(trace::trace_diagnostic_calls(state) == 0); + } + let ghost before = state; + let ghost raw_before = history::raw_events(value); + let answer = state.decide(&value, candidate); + proof { + trace::lemma_trace_decision_result_facts(before, state, value, *candidate, answer); + assert(history::raw_events(value) == raw_before); + match answer { + Ok(PolicyDecision::Deny { .. }) => { + let index = trace::trace_selected_index(state) as int; + assert(0 <= index < items.len()); + assert(trace::trace_diagnostic_ids(before)[index] == trace::trace_rule_diagnostic_id(items[index])); + }, + _ => {}, + } + } + Ok((value, state, answer)) +} + +fn last_state_change_helper( + setter: history_syntax::TestExpr, stable: history_syntax::TestExpr, + head: Ghost>, + candidate: Ghost>, + word: Ghost>>, +) -> (tail: RegexExpr) + ensures tail@ == RegexView::Concat(seq![RegexView::All, RegexView::Test(setter@), + RegexView::Star(Box::new(RegexView::Test(stable@)))]), + dsl::lang(tail@, head@, candidate@, word@) <==> exists|i: int| 0 <= i < word@.len() + && dsl::test_sem(setter@, head@, candidate@, word@[i]) + && forall|j: int| i < j < word@.len() ==> dsl::test_sem(stable@, head@, candidate@, word@[j]), +{ + let ghost setter_view = setter@; + let ghost stable_view = stable@; + let tail = history_semantics::policy::last_state_change(setter, stable); + proof { junco_core::verify::dsl::lemma_last_state_change_lang(setter_view, stable_view, head@, candidate@, word@); } + tail +} + +// These are component-language facts: arbitrary native Event, Hash, and callback laws are irrelevant. +proof fn last_state_change_cases( + setter: TestView, stable: TestView, head: HeadView, + candidate: Seq, set: Seq, kept: Seq, broken: Seq, +) + requires dsl::test_sem(setter, head, candidate, set), + dsl::test_sem(stable, head, candidate, kept), + !dsl::test_sem(setter, head, candidate, broken), + !dsl::test_sem(stable, head, candidate, broken), + ensures + !dsl::lang(RegexView::Concat(seq![RegexView::All, RegexView::Test(setter), + RegexView::Star(Box::new(RegexView::Test(stable)))]), head, candidate, seq![]), + dsl::lang(RegexView::Concat(seq![RegexView::All, RegexView::Test(setter), + RegexView::Star(Box::new(RegexView::Test(stable)))]), head, candidate, seq![set, kept]), + !dsl::lang(RegexView::Concat(seq![RegexView::All, RegexView::Test(setter), + RegexView::Star(Box::new(RegexView::Test(stable)))]), head, candidate, seq![set, broken]), + dsl::lang(RegexView::Concat(seq![RegexView::All, RegexView::Test(TestView::True), + RegexView::Star(Box::new(RegexView::Test(TestView::True)))]), head, candidate, seq![set, kept]), +{ + junco_core::verify::dsl::lemma_last_state_change_lang(setter, stable, head, candidate, seq![]); + junco_core::verify::dsl::lemma_last_state_change_lang(setter, stable, head, candidate, seq![set, kept]); + assert(exists|i: int| 0 <= i < 2 && dsl::test_sem(setter, head, candidate, seq![set, kept][i]) + && forall|j: int| i < j < 2 ==> dsl::test_sem(stable, head, candidate, seq![set, kept][j])) by { + assert(dsl::test_sem(setter, head, candidate, seq![set, kept][0])); + } + junco_core::verify::dsl::lemma_last_state_change_lang(setter, stable, head, candidate, seq![set, broken]); + assert forall|i: int| 0 <= i < 2 implies + !(dsl::test_sem(setter, head, candidate, seq![set, broken][i]) + && forall|j: int| i < j < 2 ==> dsl::test_sem(stable, head, candidate, seq![set, broken][j])) by { + if i == 0 { assert(!dsl::test_sem(stable, head, candidate, seq![set, broken][1])); } + } + junco_core::verify::dsl::lemma_last_state_change_lang(TestView::True, TestView::True, head, candidate, seq![set, kept]); + assert(exists|i: int| 0 <= i < 2 && dsl::test_sem(TestView::True, head, candidate, seq![set, kept][i]) + && forall|j: int| i < j < 2 ==> dsl::test_sem(TestView::True, head, candidate, seq![set, kept][j])) by { + assert(dsl::test_sem(TestView::True, head, candidate, seq![set, kept][0])); + } +} + +fn shared_owner(source: Rule, candidate: &E) + -> (result: Result, HistoryError>, CompileError>) + ensures result matches Ok(answer) ==> answer != Err(HistoryError::WrongHistoryOwner), +{ + let store = Arc::new(Store::::new()?); + let owner = share_store(&store); + proof { books::lemma_same_store_owner_identity(store, owner); } + let value = History::new(owner)?; + let ghost original = source; + let mut rule = CompiledRule::new(store, source)?; + proof { + history::lemma_empty_history(value, owner); + compiled::lemma_constructed_decision(rule, original, store, value); + } + let ghost before = rule; + let answer = rule.accepts_history(&value, candidate); + proof { compiled::lemma_decision_result_facts(before, rule, value, *candidate, answer); } + Ok(answer) +} + +fn independent_owners(head: Head, candidate: &E) + -> (result: Result, HistoryError>, CompileError>) + ensures result matches Ok(answer) ==> answer == Err(HistoryError::WrongHistoryOwner), +{ + let (left, right) = books::independently_constructed_stores_client::()?; + let left = Arc::new(left); + let right = Arc::new(right); + let same = CompiledRule::same_owner(&left, &right); + proof { assert(!same); } + let left_owner = share_store(&left); + let left_history = History::new(left_owner)?; + let checkpoint = left_history.checkpoint(); + let mut value = History::new(right)?; + proof { + history::lemma_empty_history(left_history, left_owner); + history::lemma_empty_history(value, right); + history::lemma_distinct_checkpoint_owner(left_history, value, checkpoint); + } + let ghost before_rollback = value; + let rollback = value.rollback(checkpoint); + proof { + history::lemma_rollback_result(before_rollback, value, checkpoint, rollback); + history::lemma_state_frame_facts(before_rollback, value); + assert(rollback == Err(HistoryError::WrongCheckpointOwner)); + } + let source = Rule::new(RuleMode::Require, head, RegexExpr::All); + let ghost original = source; + let mut rule = CompiledRule::new(left, source)?; + proof { + compiled::lemma_constructed_decision(rule, original, left, value); + } + let ghost before = rule; + let answer = rule.accepts_history(&value, candidate); + proof { compiled::lemma_decision_result_facts(before, rule, value, *candidate, answer); } + Ok(answer) +} + +// Exhaustive typed tables are consumed after actual mutations, not supplied as premises. +fn typed_truncate_table(value: &mut History, len: usize) + -> (result: Result<(), HistoryError>) + requires history::history_wf(*old(value)), + ensures history::history_wf(*final(value)), + if len >= history::raw_events(*old(value)).len() { + result == Ok(()) && history::raw_events(*final(value)) == history::raw_events(*old(value)) + && final(value).spec_numeric().spec_revision() == old(value).spec_numeric().spec_revision() + && history::stored_events(final(value).spec_numeric()) == history::stored_events(old(value).spec_numeric()) + } else if old(value).spec_numeric().spec_revision() == u64::MAX { + result == Err(HistoryError::RevisionExhausted) + && history::raw_events(*final(value)) == history::raw_events(*old(value)) + && final(value).spec_numeric().spec_revision() == old(value).spec_numeric().spec_revision() + && history::stored_events(final(value).spec_numeric()) == history::stored_events(old(value).spec_numeric()) + } else { + result == Ok(()) + && history::raw_events(*final(value)) == history::raw_events(*old(value)).take(len as int) + && history::stored_events(final(value).spec_numeric()) == history::stored_events(old(value).spec_numeric()).take(len as int) + && final(value).spec_numeric().spec_revision() == old(value).spec_numeric().spec_revision() + 1 + }, +{ + let ghost before = *value; + let result = value.truncate(len); + proof { + history::lemma_truncate_result(before, *value, len, result); + if len >= history::raw_events(before).len() || before.spec_numeric().spec_revision() == u64::MAX { + history::lemma_state_frame_facts(before, *value); + } + } + result +} + +fn typed_rollback_table(value: &mut History, checkpoint: history_store::history::Checkpoint) + -> (result: Result<(), HistoryError>) + requires history::history_wf(*old(value)), + ensures history::history_wf(*final(value)), + !history::checkpoint_owned(*old(value), checkpoint) ==> + result == Err(HistoryError::WrongCheckpointOwner), + history::checkpoint_owned(*old(value), checkpoint) + && history::checkpoint_len(checkpoint) > history::raw_events(*old(value)).len() ==> + result == Err(HistoryError::CheckpointBeyondHistory), + history::checkpoint_owned(*old(value), checkpoint) + && history::checkpoint_len(checkpoint) == history::raw_events(*old(value)).len() ==> + result == Ok(()) + && history::raw_events(*final(value)) == history::raw_events(*old(value)) + && history::stored_events(final(value).spec_numeric()) == history::stored_events(old(value).spec_numeric()) + && final(value).spec_numeric().spec_revision() == old(value).spec_numeric().spec_revision(), + history::checkpoint_owned(*old(value), checkpoint) + && history::checkpoint_len(checkpoint) < history::raw_events(*old(value)).len() ==> + if old(value).spec_numeric().spec_revision() == u64::MAX { + result == Err(HistoryError::RevisionExhausted) + } else { + result == Ok(()) + && history::raw_events(*final(value)) == history::raw_events(*old(value)).take(history::checkpoint_len(checkpoint) as int) + && history::stored_events(final(value).spec_numeric()) == history::stored_events(old(value).spec_numeric()).take(history::checkpoint_len(checkpoint) as int) + && final(value).spec_numeric().spec_revision() == old(value).spec_numeric().spec_revision() + 1 + }, + result is Err ==> history::raw_events(*final(value)) == history::raw_events(*old(value)) + && history::stored_events(final(value).spec_numeric()) == history::stored_events(old(value).spec_numeric()) + && final(value).spec_numeric().spec_revision() == old(value).spec_numeric().spec_revision(), +{ + let ghost before = *value; + let result = value.rollback(checkpoint); + proof { + history::lemma_rollback_result(before, *value, checkpoint, result); + if result is Err || (history::checkpoint_owned(before, checkpoint) + && history::checkpoint_len(checkpoint) == history::raw_events(before).len()) { + history::lemma_state_frame_facts(before, *value); + } + } + result +} + +// These concrete reachable states cover no-op, shrink, owner precedence, and a future marker. +fn typed_history_transactions(event: E) + -> (result: Result, HistoryError>) + ensures result matches Ok(value) ==> history::raw_events(value) == seq![event] + && value.spec_numeric().spec_revision() == 2, +{ + let mut events = Vec::new(); + events.push(event); + events.push(event); + let mut value = vec_history(events)?; + let full = value.checkpoint(); + let ghost original = value; + proof { history::lemma_checkpoint_matches(value, full); } + let no_op = value.truncate(2); + proof { + history::lemma_truncate_result(original, value, 2, no_op); + history::lemma_state_frame_facts(original, value); + assert(no_op == Ok(())); + history::lemma_checkpoint_owner_preserved(original, value, full); + } + let ghost before_shrink = value; + let shrink = value.truncate(1); + proof { + history::lemma_truncate_result(before_shrink, value, 1, shrink); + assert(shrink == Ok(())); + history::lemma_checkpoint_owner_preserved(before_shrink, value, full); + } + let ghost before_beyond = value; + let beyond = value.rollback(full); + proof { + history::lemma_rollback_result(before_beyond, value, full, beyond); + history::lemma_state_frame_facts(before_beyond, value); + assert(beyond == Err(HistoryError::CheckpointBeyondHistory)); + } + let marker = value.checkpoint(); + let ghost before_fork = value; + let mut fork = value.try_clone()?; + proof { history::lemma_clone_facts(before_fork, fork, marker); } + let ghost before_foreign = fork; + let foreign = fork.rollback(marker); + proof { + history::lemma_rollback_result(before_foreign, fork, marker, foreign); + history::lemma_state_frame_facts(before_foreign, fork); + assert(foreign == Err(HistoryError::WrongCheckpointOwner)); + } + let ghost before_noop = value; + proof { history::lemma_checkpoint_matches(value, marker); } + let no_op = value.rollback(marker); + proof { + history::lemma_rollback_result(before_noop, value, marker, no_op); + history::lemma_state_frame_facts(before_noop, value); + history::lemma_checkpoint_owner_preserved(before_noop, value, marker); + assert(no_op == Ok(())); + } + let ghost before_push = value; + let push = value.push(event); + proof { + history::lemma_push_result(before_push, value, event, push); + history::lemma_checkpoint_owner_preserved(before_push, value, marker); + } + push?; + let ghost before_rollback = value; + let rollback = value.rollback(marker); + proof { + history::lemma_rollback_result(before_rollback, value, marker, rollback); + assert(rollback == Ok(())); + } + Ok(value) +} + +// The explicit numeric boundary is separate from the typed lifecycle reachability invariant. +fn revision_exhaustion(events: Vec) + requires events@.len() > 0, +{ + let mut stored = history::revision_boundary_record(17, events); + let ghost before = stored; + let exhausted = history::truncate_boundary_record(&mut stored, 0); + proof { history::lemma_stored_truncate_result_facts(before, stored, 0, exhausted); } + assert(exhausted == Err(HistoryError::RevisionExhausted)); + assert(history::stored_events(&stored) == events@); + assert(stored.spec_revision() == u64::MAX); + assert(stored@ == before@ && stored.spec_id() == 17); + let count = stored.len(); + let ghost before_noop = stored; + let unchanged = history::truncate_boundary_record(&mut stored, count); + proof { history::lemma_stored_truncate_result_facts(before_noop, stored, count, unchanged); } + assert(unchanged == Ok(())); + assert(history::stored_events(&stored) == history::stored_events(&before)); + assert(stored.spec_revision() == u64::MAX); + assert(stored@ == before@ && stored.spec_id() == 17); + let ghost before_max_noop = stored; + let max_noop = history::truncate_boundary_record(&mut stored, usize::MAX); + proof { history::lemma_stored_truncate_result_facts(before_max_noop, stored, usize::MAX, max_noop); } + assert(max_noop == Ok(())); + assert(history::stored_events(&stored) == events@); + assert(stored.spec_revision() == u64::MAX); + assert(stored@ == before@ && stored.spec_id() == 17); +} + +fn byte_identity(path: &[u8], different: &[u8], limits: &mut L, world: &mut ObservationWorld) + -> (result: Result<(u64, u64, u64), HistoryError>) + requires path@ != different@, + ensures result matches Ok((first, again, other)) ==> first == again && first != other, +{ + let owner = HistoryStore::new(1); + let store = history_store::store::borrow_numeric_owner(&owner); + let (first, first_receipt) = store.intern_observed(Component(0), path, limits, world)?; + let (again, again_receipt) = store.intern_observed(Component(0), path, limits, world)?; + let (other, other_receipt) = store.intern_observed(Component(0), different, limits, world)?; + proof { + records::lemma_byte_binding_pair_facts(store, 0, path@, first, first_receipt@, + path@, again, again_receipt@); + records::lemma_byte_binding_pair_facts(store, 0, path@, first, first_receipt@, + different@, other, other_receipt@); + history_store::store::lemma_byte_binding_reuse(first_receipt.borrow(), again_receipt.borrow()); + history_store::store::lemma_byte_binding_separation(first_receipt.borrow(), other_receipt.borrow()); + } + Ok((first, again, other)) +} + +// Releasing the first guard permits arbitrary intervening writers; only lifecycle facts survive. +fn retained_raw_observations(arity: usize, events: &[history_store::store::Event], + limits: &mut L, world: &mut ObservationWorld) -> (result: Result<(), HistoryError>) + requires 1 <= arity <= MAX_ARITY, +{ + let owner = HistoryStore::new(arity); + let store = history_store::store::borrow_numeric_owner(&owner); + let handle = owner.new_history(limits, world)?; + let record = store.history_record(&handle)?; + let tracked previous; + { + let guard = record.read(); + let observed = guard.as_slice(); + let len = guard.len(); + let revision = guard.revision(); + proof { + guard.lemma_observation(); + assert(records::events_view(observed@) == guard.snapshot_view().value().events); + assert(len == guard.snapshot_view().value().events.len()); + assert(revision == guard.snapshot_view().value().revision); + previous = guard.snapshot(); + } + } + let append = store.append(&handle, events, limits, world); + proof { + records::lemma_append_result_facts(store, handle, events@, append); + if events@.len() > 0 && append is Ok { + records::lemma_record_append_observed(handle, events@, append); + assert(exists|before: history_store::history::StoredHistory, after: history_store::history::StoredHistory| + records::record_transaction(handle, before, after) + && history::stored_events(&after) == history::stored_events(&before) + events@ + && after.spec_revision() == before.spec_revision()); + } + } + let _ = append; + let truncate = store.truncate(&handle, 1); + proof { + records::lemma_truncate_result_facts(store, handle, 1, truncate); + records::lemma_record_truncate_observed(handle, 1, truncate); + } + let later = record.read(); + later.validate_snapshot(Tracked(&previous)); + assert(previous.value().revision <= later.snapshot_view().value().revision); + assert(previous.value().revision == later.snapshot_view().value().revision ==> + previous.value().events.is_prefix_of(later.snapshot_view().value().events)); + Ok(()) +} +} diff --git a/src/history-semantics/tests/reviewer.rs b/src/history-semantics/tests/reviewer.rs new file mode 100644 index 000000000..eabbe5c2c --- /dev/null +++ b/src/history-semantics/tests/reviewer.rs @@ -0,0 +1,266 @@ +//! Reviewer theorems for the monitor (Theorem `thm:matcher` at the level of `Validator`). +//! +//! Every statement here uses only public items: the event interface, the semantics, the analysis questions, the hypotheses, the monitor specification, `Validator` and `Store`. The generic +//! theorems take the hypotheses' `event_obligations::()`; the concrete `(u32, u64)` instances +//! are premise-free (`junco_core::verify::hypotheses` proves every conjunct). +#![cfg(all(verus_keep_ghost, feature = "runtime"))] + +extern crate alloc; + +use alloc::sync::Arc; +use history_semantics::spec::monitor::{ + ValidatorView, check_frame, check_step, permits_result, rollback_step, trace_safe, +}; +use history_semantics::validator::verify::{ + lemma_check_preserves_trace_safe, lemma_rollback_preserves_trace_safe, +}; +use history_semantics::validator::{Decision, Validator}; +use history_store::typed::Store; +use history_syntax::event::Component2; +use history_syntax::spec::events::event_view; +use history_syntax::{Event, Head, RegexExpr, Rule, RuleMode}; +use junco_core::event::Request; +use junco_core::spec::hypotheses::event_obligations; +use junco_core::spec::questions::{DomainsView, in_domains, refines}; +use junco_core::spec::semantics::{ + head_matches, least_violation, policy_denies, policy_permits, rule_violated, +}; +use junco_core::verify::hypotheses::lemma_u32_u64_event_hypotheses; +use junco_core::{CompileError, HistoryError}; +use vstd::prelude::*; + +verus! { + +broadcast use vstd::seq::group_seq_lemmas; + +// ----- thm:matcher at the monitor level ----- + +/// The three readable cases of `check_step`: a grant means no rule is violated; a denial +/// names the first violated rule, in source order, by index and mode; errors are operational +/// resource failures. Spelled out with `rule_violated` without further unfolding. +pub open spec fn stmt_monitor_check( + before: ValidatorView, request: Request, result: Result, HistoryError>, +) -> bool { + match result { + Ok(Decision::Grant(grant)) => grant.event == request.event + && forall|i: int| 0 <= i < before.rules.len() + ==> !rule_violated(#[trigger] before.rules[i], request.event, before.history), + Ok(Decision::Denied(denial)) => denial.event == request.event && exists|i: int| + 0 <= i < before.rules.len() + && rule_violated(#[trigger] before.rules[i], request.event, before.history) + && denial.mode == before.rules[i].mode + && i == denial.index as int + && forall|j: int| 0 <= j < i ==> !rule_violated(#[trigger] before.rules[j], request.event, before.history), + Err(error) => junco_core::spec::semantics::resource_error(error), + } +} + +/// `thm:matcher` for `Validator::check`: the contract's `check_step` and `check_frame` give the +/// readable statement. +pub proof fn theorem_monitor_check( + before: ValidatorView, after: ValidatorView, request: Request, + result: Result, HistoryError>, +) + requires check_frame(before, after, request, result), check_step(before, request, result), + ensures stmt_monitor_check(before, request, result), +{ + match result { + Ok(Decision::Grant(_)) => { + assert forall|i: int| 0 <= i < before.rules.len() + implies !rule_violated(#[trigger] before.rules[i], request.event, before.history) by { + if rule_violated(before.rules[i], request.event, before.history) { + assert(policy_denies(before.rules, request.event, before.history)); + } + } + }, + Ok(Decision::Denied(denial)) => { + let i = denial.index as int; + assert(rule_violated(before.rules[i], request.event, before.history)); + }, + Err(_) => {}, + } +} + +/// Both monitor entry points reserve errors for operational resource failures. +pub proof fn theorem_monitor_resource_errors( + before: ValidatorView, request: Request, + checked: Result, HistoryError>, permitted: Result, +) + requires check_step(before, request, checked), + history_semantics::spec::monitor::permits_result(before, request.event, permitted), + ensures checked matches Err(error) ==> junco_core::spec::semantics::resource_error(error), + permitted matches Err(error) ==> junco_core::spec::semantics::resource_error(error), + !(checked matches Err(HistoryError::UnknownId { .. })), + !(permitted matches Err(HistoryError::UnknownId { .. })), +{ +} + +/// A well-formed, correctly tagged rule of the event arity has no input-error exit. +fn valid_rule_registration( + builder: &mut history_semantics::validator::ValidatorBuilder, rule: Rule, +) -> (result: Result<(), CompileError>) + requires old(builder).wf(), event_obligations::(), + junco_core::spec::semantics::rule_wf(rule@), + rule@.head.len() == history_syntax::spec::events::arity::(), + junco_core::spec::semantics::rule_constants_tagged::(rule@), + ensures result is Ok || (result matches Err(CompileError::Runtime(error)) + && junco_core::spec::semantics::resource_error(error)), +{ + builder.add_rule(rule)?; + Ok(()) +} + +/// `permits` answers exactly whether every rule accepts the candidate after the committed history. +pub proof fn theorem_monitor_permits( + v: ValidatorView, candidate: E, result: Result, +) + requires permits_result(v, candidate, result), + ensures result matches Ok(permitted) ==> permitted == forall|i: int| 0 <= i < v.rules.len() + ==> !rule_violated(#[trigger] v.rules[i], candidate, v.history), +{ + if let Ok(permitted) = result { + if permitted { + assert forall|i: int| 0 <= i < v.rules.len() + implies !rule_violated(#[trigger] v.rules[i], candidate, v.history) by { + if rule_violated(v.rules[i], candidate, v.history) { + assert(policy_denies(v.rules, candidate, v.history)); + } + } + } + } +} + +// ----- trace safety of every reachable state ----- + +/// One observable step of a `Validator`: a `check` with its result, or a `rollback` with its result. +pub enum Step { + Check(Request, Result, HistoryError>), + Rollback(Result<(), HistoryError>), +} + +/// What `Validator::check`/`rollback` guarantee about one step (their contracts, under +/// `event_obligations::()` for `check_step`). +pub open spec fn step_ok(before: ValidatorView, after: ValidatorView, step: Step) -> bool { + match step { + Step::Check(request, result) => check_frame(before, after, request, result) + && check_step(before, request, result), + Step::Rollback(result) => rollback_step(before, after, result), + } +} + +/// A run: `states[0]` is a freshly finished validator (empty history) and every step is one +/// `check` or `rollback`. +pub open spec fn run_ok(states: Seq>, steps: Seq>) -> bool { + &&& states.len() == steps.len() + 1 + &&& states[0].history == Seq::::empty() + &&& forall|k: int| 0 <= k < steps.len() ==> step_ok(states[k], states[k + 1], #[trigger] steps[k]) +} + +/// Every state of a run is trace safe: each committed event was permitted by every rule against +/// the history before it. Induction over the run, using the two preservation lemmas. +pub proof fn theorem_trace_safe(states: Seq>, steps: Seq>, k: int) + requires run_ok(states, steps), 0 <= k < states.len(), + ensures trace_safe(states[k]), + decreases k, +{ + if k == 0 { + assert(states[0].history.len() == 0); + } else { + theorem_trace_safe(states, steps, k - 1); + match steps[k - 1] { + Step::Check(request, result) => lemma_check_preserves_trace_safe(states[k - 1], states[k], request, result), + Step::Rollback(result) => lemma_rollback_preserves_trace_safe(states[k - 1], states[k], result), + } + } +} + +// ----- analyzer-to-monitor bridge on declared domains, stated with `refines` ----- + +/// If `p` refines `q` on the declared domains (`at_least_as_strict(p, q)` returned `Holds`), +/// then whenever a validator over `p` grants a request inside the domains, the validator over `q` +/// with the same history permits it, so it cannot deny it. +pub proof fn theorem_analyzer_to_monitor( + domains: DomainsView, p: ValidatorView, q: ValidatorView, + request: Request, result_p: Result, HistoryError>, + result_q: Result, HistoryError>, +) + requires + refines::(domains, p.rules, q.rules), + q.history == p.history, + in_domains::(domains, request.event, p.history), + check_step(p, request, result_p), check_step(q, request, result_q), + result_p is Ok && result_p->Ok_0 is Grant, + ensures + policy_permits(q.rules, request.event, q.history), + !(result_q matches Ok(Decision::Denied(_))), +{ + assert(policy_permits(p.rules, request.event, p.history)); + if let Ok(Decision::Denied(denial)) = result_q { + let i = choose|i: int| #[trigger] least_violation(q.rules, request.event, q.history, i) + && denial.mode == q.rules[i].mode; + assert(policy_denies(q.rules, request.event, q.history)); + } +} + +// ----- the concrete event type (u32, u64) ----- + +/// `(u32, u64)` events satisfy every hypothesis; no premise. +pub proof fn theorem_event_obligations_u32_u64() + ensures event_obligations::<(u32, u64)>(), +{ + lemma_u32_u64_event_hypotheses(); +} + +/// Exec client: builds a validator with one rule over `head` and checks one request; the result +/// satisfies `thm:matcher` and the state is trace safe, discharged from the public contracts only. +fn monitor_client(head: Head, request: Request) + -> (result: Result<(Validator, Result, HistoryError>), CompileError>) + requires event_obligations::(), + ensures result matches Ok((state, answer)) ==> { + let before = ValidatorView { rules: state@.rules, history: Seq::::empty() }; + &&& state.wf() + &&& state@.rules == seq![Rule { mode: RuleMode::Forbid, head, tail: RegexExpr::All }@] + &&& junco_core::spec::semantics::rule_wf(state@.rules[0]) + &&& head@.len() == history_syntax::spec::events::arity::() + &&& junco_core::verify::flatten::head_coordinates_wf::(head@) + &&& check_frame(before, state@, request, answer) + &&& stmt_monitor_check(before, request, answer) + &&& trace_safe(state@) + &&& head_matches(head@, event_view(request.event)) ==> !(answer matches Ok(Decision::Grant(_))) + }, +{ + let store = Arc::new(Store::::new()?); + let mut builder = Validator::builder(store); + let rule = Rule::new(RuleMode::Forbid, head, RegexExpr::All); + let ghost source = rule; + builder.add_rule(rule)?; + proof { assert(builder.rules() =~= seq![source@]); } + let mut state = builder.finish()?; + let ghost before = state@; + let answer = state.check(request); + proof { + theorem_monitor_check(before, state@, request, answer); + assert(trace_safe(before)); + lemma_check_preserves_trace_safe(before, state@, request, answer); + if head_matches(head@, event_view(request.event)) { + assert(rule_violated(before.rules[0], request.event, before.history)); + } + } + Ok((state, answer)) +} + +/// The same client for `(u32, u64)` events, premise-free. +fn monitor_client_u32_u64(head: Head<(u32, u64)>, request: Request<(u32, u64), M>) + -> (result: Result<(Validator<(u32, u64)>, Result, HistoryError>), CompileError>) + ensures result matches Ok((state, answer)) ==> state.wf() + && stmt_monitor_check(ValidatorView { rules: state@.rules, history: Seq::<(u32, u64)>::empty() }, request, answer) + && trace_safe(state@), +{ + proof { theorem_event_obligations_u32_u64(); } + monitor_client(head, request) +} + +} // verus! + +#[test] +fn compiles() {} diff --git a/src/history-semantics/tests/syntax_semantics.rs b/src/history-semantics/tests/syntax_semantics.rs new file mode 100644 index 000000000..91f1bf2a1 --- /dev/null +++ b/src/history-semantics/tests/syntax_semantics.rs @@ -0,0 +1,497 @@ +#![cfg(feature = "runtime")] + +use std::sync::Arc; + +use history_semantics::CompiledRule; +use history_store::{History, Store}; +use history_syntax::{ + AtomPattern, Comparison, Component, Component3, ComponentPattern, Event, Head, N3, RegexExpr, + Rule, RuleMode, TestExpr, +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +enum Action { + Read, + Edit, + Release, + Remove, +} + +// Unverified glue: `hash_respects_eq` is a hypothesis for this type (as `event_laws` already is). +impl history_syntax::KeyHash for Action { + fn key_hash(&self) -> u64 { + history_syntax::key_hash::hash_via_std(self) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +struct Record { + principal: u32, + action: Action, + resource: u32, +} + +impl Event for Record { + type Component = Component3; + type Arity = N3; + + fn component(self, index: usize) -> Self::Component { + match index { + 0 => Component3::C0(self.principal), + 1 => Component3::C1(self.action), + _ => Component3::C2(self.resource), + } + } + + fn coordinate(component: Self::Component) -> usize { + match component { + Component3::C0(_) => 0, + Component3::C1(_) => 1, + Component3::C2(_) => 2, + } + } +} + +fn event(principal: u32, action: Action, resource: u32) -> Record { + Record { + principal, + action, + resource, + } +} + +fn rule(tail: RegexExpr) -> Rule { + Rule::new( + RuleMode::Require, + Head::new([ + ComponentPattern::variable("actor"), + ComponentPattern::variable("action"), + ComponentPattern::variable("resource"), + ]), + tail, + ) +} + +fn action_test(comparison: Comparison, value: Action) -> TestExpr { + TestExpr::atom( + comparison, + AtomPattern::new( + Component(1), + ComponentPattern::constant(Component3::C1(value)), + ), + ) +} + +fn action(value: Action) -> RegexExpr { + RegexExpr::test(action_test(Comparison::Eq, value)) +} + +fn principal(comparison: Comparison, value: u32) -> TestExpr { + TestExpr::atom( + comparison, + AtomPattern::new( + Component(0), + ComponentPattern::constant(Component3::C0(value)), + ), + ) +} + +fn resource(value: u32) -> TestExpr { + TestExpr::atom( + Comparison::Eq, + AtomPattern::new( + Component(2), + ComponentPattern::constant(Component3::C2(value)), + ), + ) +} + +// Compare languages, not the removed arena's canonical handles or minterm layout. +fn equivalent(left: RegexExpr, right: RegexExpr) { + let store = Arc::new(Store::new().unwrap()); + let mut left = CompiledRule::new(store.clone(), rule(left)).unwrap(); + let mut right = CompiledRule::new(store.clone(), rule(right)).unwrap(); + let alphabet = [ + event(100, Action::Read, 0), + event(101, Action::Edit, 1), + event(100, Action::Release, 1), + event(101, Action::Remove, 0), + ]; + let candidate = event(102, Action::Release, 3); + for length in 0..=3 { + for mut word in 0..alphabet.len().pow(length) { + let events = (0..length).map(|_| { + let event = alphabet[word % alphabet.len()]; + word /= alphabet.len(); + event + }); + let history = History::from_events(store.clone(), events).unwrap(); + let expected = right.accepts_history(&history, &candidate).unwrap(); + assert_eq!( + left.accepts_history(&history, &candidate).unwrap(), + expected, + "{history:?}" + ); + assert_eq!( + left.accepts_history(&history, &candidate).unwrap(), + expected, + "warm {history:?}" + ); + } + } +} + +#[test] +fn associative_commutative_idempotent_and_identity_languages_are_preserved() { + equivalent( + RegexExpr::union([ + action(Action::Read), + RegexExpr::empty(), + action(Action::Edit), + action(Action::Read), + ]), + RegexExpr::union([action(Action::Edit), action(Action::Read)]), + ); + equivalent( + RegexExpr::concat([ + RegexExpr::epsilon(), + action(Action::Read), + RegexExpr::epsilon(), + ]), + action(Action::Read), + ); + let edit = action(Action::Edit); + equivalent( + RegexExpr::intersect([edit.clone(), RegexExpr::complement(edit)]), + RegexExpr::empty(), + ); +} + +#[test] +fn boolean_absorption_and_distinct_component_equalities_keep_their_languages() { + let read = action_test(Comparison::Eq, Action::Read); + let edit = action_test(Comparison::Eq, Action::Edit); + let not_read = action_test(Comparison::Neq, Action::Read); + let not_edit = action_test(Comparison::Neq, Action::Edit); + equivalent( + RegexExpr::test(TestExpr::and([ + read.clone(), + TestExpr::or([read.clone(), edit.clone()]), + ])), + action(Action::Read), + ); + equivalent( + RegexExpr::test(TestExpr::and([read.clone(), edit])), + RegexExpr::empty(), + ); + equivalent( + RegexExpr::test(TestExpr::and([read.clone(), not_edit.clone()])), + action(Action::Read), + ); + equivalent( + RegexExpr::test(TestExpr::or([read, not_edit.clone()])), + RegexExpr::test(not_edit.clone()), + ); + for tests in [ + vec![not_read.clone(), not_edit.clone()], + vec![not_edit, not_read], + vec![ + principal(Comparison::Neq, 100), + principal(Comparison::Neq, 101), + ], + vec![ + TestExpr::atom( + Comparison::Neq, + AtomPattern::new( + Component(2), + ComponentPattern::constant(Component3::C2(0u32)), + ), + ), + TestExpr::atom( + Comparison::Neq, + AtomPattern::new( + Component(2), + ComponentPattern::constant(Component3::C2(1u32)), + ), + ), + ], + ] { + equivalent( + RegexExpr::test(TestExpr::or(tests)), + RegexExpr::test(TestExpr::true_test()), + ); + } + equivalent( + RegexExpr::star(RegexExpr::test(TestExpr::true_test())), + RegexExpr::all(), + ); +} + +#[test] +fn compound_boolean_rewrites_are_construction_order_independent() { + let p = principal(Comparison::Eq, 100); + let a = action_test(Comparison::Eq, Action::Read); + let r = resource(0); + let compound = TestExpr::and([p.clone(), a.clone()]); + let complement = TestExpr::or([ + principal(Comparison::Neq, 100), + action_test(Comparison::Neq, Action::Read), + ]); + equivalent( + RegexExpr::test(TestExpr::and([compound.clone(), complement.clone()])), + RegexExpr::empty(), + ); + equivalent( + RegexExpr::test(TestExpr::or([compound.clone(), complement])), + RegexExpr::test(TestExpr::true_test()), + ); + let larger = TestExpr::and([p.clone(), a.clone(), r.clone()]); + for tests in [ + vec![compound.clone(), larger.clone()], + vec![larger, compound.clone()], + ] { + equivalent( + RegexExpr::test(TestExpr::or(tests)), + RegexExpr::test(compound.clone()), + ); + } + let smaller = TestExpr::or([p.clone(), a.clone()]); + let larger = TestExpr::or([p, a, r]); + for tests in [ + vec![smaller.clone(), larger.clone()], + vec![larger, smaller.clone()], + ] { + equivalent( + RegexExpr::test(TestExpr::and(tests)), + RegexExpr::test(smaller.clone()), + ); + } +} + +#[test] +fn epsilon_set_languages_preserve_nullability() { + let nullable = RegexExpr::star(action(Action::Read)); + equivalent( + RegexExpr::union([RegexExpr::epsilon(), nullable.clone()]), + nullable.clone(), + ); + equivalent( + RegexExpr::intersect([RegexExpr::epsilon(), nullable]), + RegexExpr::epsilon(), + ); + let nonnullable = action(Action::Edit); + equivalent( + RegexExpr::intersect([RegexExpr::epsilon(), nonnullable.clone()]), + RegexExpr::empty(), + ); + equivalent( + RegexExpr::intersect([ + nonnullable.clone(), + RegexExpr::complement(RegexExpr::epsilon()), + ]), + nonnullable, + ); +} + +#[test] +fn mixed_regex_operands_and_absorption_keep_their_languages() { + let other = RegexExpr::star(action(Action::Release)); + let grouped = RegexExpr::union([ + RegexExpr::test(TestExpr::or([ + action_test(Comparison::Eq, Action::Read), + action_test(Comparison::Eq, Action::Edit), + ])), + other.clone(), + ]); + for source in [ + RegexExpr::union([action(Action::Read), other.clone(), action(Action::Edit)]), + RegexExpr::union([other.clone(), action(Action::Edit), action(Action::Read)]), + RegexExpr::union([ + action(Action::Read), + RegexExpr::union([action(Action::Edit), other.clone()]), + ]), + ] { + equivalent(source, grouped.clone()); + } + equivalent( + RegexExpr::intersect([action(Action::Read), other.clone(), action(Action::Edit)]), + RegexExpr::empty(), + ); + let read = action(Action::Read); + equivalent( + RegexExpr::union([ + read.clone(), + RegexExpr::intersect([read.clone(), other.clone()]), + ]), + read.clone(), + ); + equivalent( + RegexExpr::intersect([read.clone(), RegexExpr::union([read.clone(), other])]), + read, + ); +} + +#[test] +fn every_regex_form_has_the_expected_complete_word_language() { + let store = Arc::new(Store::new().unwrap()); + let read = action(Action::Read); + let edit = action(Action::Edit); + let sources = [ + RegexExpr::empty(), + RegexExpr::all(), + RegexExpr::epsilon(), + read.clone(), + RegexExpr::union([read.clone(), RegexExpr::star(edit.clone())]), + RegexExpr::intersect([ + RegexExpr::star(read.clone()), + RegexExpr::complement(RegexExpr::epsilon()), + ]), + RegexExpr::concat([ + RegexExpr::star(read.clone()), + edit.clone(), + RegexExpr::all(), + ]), + RegexExpr::star(RegexExpr::union([read.clone(), edit.clone()])), + RegexExpr::complement(RegexExpr::concat([read, edit])), + ]; + let mut compiled: Vec<_> = sources + .into_iter() + .map(|source| CompiledRule::new(store.clone(), rule(source)).unwrap()) + .collect(); + for word in [ + vec![], + vec![Action::Read], + vec![Action::Edit], + vec![Action::Release], + vec![Action::Read, Action::Edit], + vec![Action::Read, Action::Read], + vec![Action::Edit, Action::Release], + vec![Action::Read, Action::Edit, Action::Release], + ] { + let history = + History::from_events(store.clone(), word.iter().map(|&a| event(100, a, 0))).unwrap(); + let read_edit_prefix = word + .iter() + .position(|&a| a != Action::Read) + .is_some_and(|index| word[index] == Action::Edit); + let expected = [ + false, + true, + word.is_empty(), + word == [Action::Read], + word == [Action::Read] || word.iter().all(|&a| a == Action::Edit), + !word.is_empty() && word.iter().all(|&a| a == Action::Read), + read_edit_prefix, + word.iter() + .all(|&a| matches!(a, Action::Read | Action::Edit)), + word != [Action::Read, Action::Edit], + ]; + for (compiled, expected) in compiled.iter_mut().zip(expected) { + for _ in 0..2 { + assert_eq!( + compiled + .accepts_history(&history, &event(100, Action::Read, 0)) + .unwrap(), + Some(expected), + "{word:?}" + ); + } + } + } +} + +#[test] +fn candidate_bindings_and_wide_constant_alphabets_remain_exact() { + let store = Arc::new(Store::new().unwrap()); + let mut bound_action = CompiledRule::new( + store.clone(), + rule(RegexExpr::test(TestExpr::atom( + Comparison::Eq, + AtomPattern::new(Component(1), ComponentPattern::variable("action")), + ))), + ) + .unwrap(); + for probe in [event(100, Action::Read, 0), event(101, Action::Edit, 1)] { + let history = History::from_events(store.clone(), [probe]).unwrap(); + assert_eq!( + bound_action.accepts_history(&history, &probe).unwrap(), + Some(true) + ); + let different = event(probe.principal, Action::Remove, probe.resource); + assert_eq!( + bound_action.accepts_history(&history, &different).unwrap(), + Some(false) + ); + } + let alternatives = (0..=64).map(|value| RegexExpr::test(principal(Comparison::Eq, value))); + let mut wide = CompiledRule::new(store.clone(), rule(RegexExpr::union(alternatives))).unwrap(); + for (actor, expected) in [(7, true), (104, false)] { + let history = History::from_events(store.clone(), [event(actor, Action::Read, 2)]).unwrap(); + assert_eq!( + wide.accepts_history(&history, &event(102, Action::Edit, 3)) + .unwrap(), + Some(expected) + ); + } +} + +#[test] +fn appended_suffixes_replacements_and_forks_keep_exact_residual_answers() { + let store = Arc::new(Store::new().unwrap()); + let tail = RegexExpr::concat([action(Action::Read), RegexExpr::all(), action(Action::Edit)]); + let mut compiled = CompiledRule::new(store.clone(), rule(tail)).unwrap(); + let candidate = event(100, Action::Release, 0); + let mut history = History::new(store).unwrap(); + for (appended, expected) in [ + (None, false), + (Some(Action::Read), false), + (Some(Action::Edit), true), + (Some(Action::Edit), true), + (Some(Action::Remove), false), + (Some(Action::Edit), true), + ] { + if let Some(action) = appended { + history.push(event(101, action, 1)).unwrap(); + } + for _ in 0..2 { + assert_eq!( + compiled.accepts_history(&history, &candidate).unwrap(), + Some(expected) + ); + } + } + history.truncate(1).unwrap(); + history.push(event(100, Action::Remove, 0)).unwrap(); + assert_eq!( + compiled.accepts_history(&history, &candidate).unwrap(), + Some(false) + ); + let checkpoint = history.checkpoint(); + history.push(event(100, Action::Edit, 0)).unwrap(); + assert_eq!( + compiled.accepts_history(&history, &candidate).unwrap(), + Some(true) + ); + history.rollback(checkpoint).unwrap(); + assert_eq!( + compiled.accepts_history(&history, &candidate).unwrap(), + Some(false) + ); + history.truncate(1).unwrap(); + let mut first = history.try_clone().unwrap(); + let mut second = history.try_clone().unwrap(); + first.push(event(100, Action::Edit, 0)).unwrap(); + second.push(event(100, Action::Remove, 0)).unwrap(); + assert_eq!( + compiled.accepts_history(&first, &candidate).unwrap(), + Some(true) + ); + assert_eq!( + compiled.accepts_history(&second, &candidate).unwrap(), + Some(false) + ); + assert_eq!( + compiled.accepts_history(&first, &candidate).unwrap(), + Some(true) + ); +} diff --git a/src/history-semantics/tests/typed_history.rs b/src/history-semantics/tests/typed_history.rs new file mode 100644 index 000000000..3ac4c33fc --- /dev/null +++ b/src/history-semantics/tests/typed_history.rs @@ -0,0 +1,329 @@ +#![cfg(feature = "runtime")] + +use core::cell::Cell; +use core::hash::{Hash, Hasher}; +use history_semantics::CompiledRule; +use history_store::{History, Store}; +use history_syntax::{ + AtomPattern, Comparison, Component, ComponentPattern as P, Coprod, Coproduct, Event, Head, N3, + RegexExpr as R, Rule, RuleMode, TestExpr as T, +}; +use junco_core::HistoryError; +use std::sync::Arc; + +std::thread_local! { + static HISTORY_PROJECTIONS: Cell = const { Cell::new(0) }; +} + +#[derive(Clone, Copy, Debug)] +struct Part { + identity: u8, + payload: u8, +} + +impl PartialEq for Part { + fn eq(&self, other: &Self) -> bool { + self.identity == other.identity + } +} +impl Eq for Part {} +impl Hash for Part { + fn hash(&self, state: &mut H) { + 0u8.hash(state); + } +} + +#[derive(Clone, Copy, Debug)] +struct Record { + principal: Part, + action: Part, + resource: Part, + payload: u16, +} + +impl Record { + fn raw_key(self) -> (u8, u8, u8, u8, u8, u8, u16) { + ( + self.principal.identity, + self.principal.payload, + self.action.identity, + self.action.payload, + self.resource.identity, + self.resource.payload, + self.payload, + ) + } + + fn observe_history_projection(self) { + if self.payload < 1000 { + HISTORY_PROJECTIONS.with(|count| count.set(count.get() + 1)); + } + } +} +impl PartialEq for Record { + fn eq(&self, other: &Self) -> bool { + self.raw_key() == other.raw_key() + } +} +impl Eq for Record {} +impl Hash for Record { + fn hash(&self, state: &mut H) { + self.raw_key().hash(state); + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +enum RecordComponent { + Principal(Part), + Action(Part), + Resource(Part), +} + +// Unverified glue: `hash_respects_eq` is a hypothesis for this type (as `event_laws` already is). +impl history_syntax::KeyHash for RecordComponent { + fn key_hash(&self) -> u64 { + history_syntax::key_hash::hash_via_std(self) + } +} + +impl Event for Record { + type Component = RecordComponent; + type Arity = N3; + + fn component(self, index: usize) -> RecordComponent { + self.observe_history_projection(); + match index { + 0 => RecordComponent::Principal(self.principal), + 1 => RecordComponent::Action(self.action), + _ => RecordComponent::Resource(self.resource), + } + } + + fn coordinate(component: RecordComponent) -> usize { + match component { + RecordComponent::Principal(_) => 0, + RecordComponent::Action(_) => 1, + RecordComponent::Resource(_) => 2, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +struct Approval(Record); +impl Event for Approval { + type Component = RecordComponent; + type Arity = N3; + + fn component(self, index: usize) -> RecordComponent { + self.0.component(index) + } + + fn coordinate(component: RecordComponent) -> usize { + Record::coordinate(component) + } +} + +type Mixed = Coprod![Record, Approval]; + +fn record(actor: u8, action: u8, resource: u8, representation: u8, payload: u16) -> Record { + Record { + principal: Part { + identity: actor, + payload: representation, + }, + action: Part { + identity: action, + payload: representation, + }, + resource: Part { + identity: resource, + payload: representation, + }, + payload, + } +} + +fn head>() -> Head { + Head::new([ + P::variable("actor"), + P::constant(RecordComponent::Action(Part { + identity: 2, + payload: 99, + })), + P::variable("resource"), + ]) +} + +fn prior_edit>() -> Rule { + Rule::new( + RuleMode::Require, + head(), + R::concat([ + R::all(), + R::test(T::and([ + T::atom( + Comparison::Eq, + AtomPattern::new(Component(0), P::variable("actor")), + ), + T::atom( + Comparison::Eq, + AtomPattern::new( + Component(1), + P::constant(RecordComponent::Action(Part { + identity: 1, + payload: 99, + })), + ), + ), + T::atom( + Comparison::Eq, + AtomPattern::new(Component(2), P::variable("resource")), + ), + ])), + R::all(), + ]), + ) +} + +fn reads_only() -> Rule { + Rule::new( + RuleMode::Require, + head(), + R::star(R::test(T::atom( + Comparison::Eq, + AtomPattern::new( + Component(1), + P::constant(RecordComponent::Action(Part { + identity: 0, + payload: 99, + })), + ), + ))), + ) +} + +#[test] +fn non_structural_equality_and_hash_collisions_preserve_payloads_and_variants() { + let store = Arc::new(Store::::new().unwrap()); + let mut rule = CompiledRule::new(store.clone(), prior_edit()).unwrap(); + let first = record(7, 1, 9, 1, 11); + let second = record(7, 1, 9, 2, 22); + let events: [Mixed; 2] = [ + Coproduct::Inl(first), + Coproduct::Inr(Coproduct::Inl(Approval(second))), + ]; + let history = History::from_events(store, events).unwrap(); + assert_eq!(history.as_slice(), &events); + assert_ne!(history.as_slice()[0], history.as_slice()[1]); + assert!(matches!(history.as_slice()[0], Coproduct::Inl(value) if value.principal.payload == 1)); + assert!( + matches!(history.as_slice()[1], Coproduct::Inr(Coproduct::Inl(value)) if value.0.principal.payload == 2) + ); + for representation in [1, 2] { + let candidate = Coproduct::Inl(record(7, 2, 9, representation, 2000)); + assert_eq!( + rule.accepts_history(&history, &candidate).unwrap(), + Some(true) + ); + } + let unequal_same_hash = Coproduct::Inl(record(8, 2, 9, 2, 2000)); + assert_eq!( + rule.accepts_history(&history, &unequal_same_hash).unwrap(), + Some(false) + ); + let different_resource = Coproduct::Inl(record(7, 2, 10, 2, 2000)); + assert_eq!( + rule.accepts_history(&history, &different_resource).unwrap(), + Some(false) + ); + assert_eq!(history.as_slice(), &events); +} + +#[test] +fn a_fork_cannot_inherit_another_owners_terminal_residual() { + let store = Arc::new(Store::::new().unwrap()); + let mut rule = CompiledRule::new(store.clone(), reads_only()).unwrap(); + let mut original = History::from_events(store, [record(7, 0, 9, 1, 1); 2]).unwrap(); + let probe = record(7, 2, 9, 2, 2000); + assert_eq!(rule.accepts_history(&original, &probe).unwrap(), Some(true)); + let mut fork = original.try_clone().unwrap(); + original.push(record(7, 1, 9, 1, 2)).unwrap(); + assert_eq!( + rule.accepts_history(&original, &probe).unwrap(), + Some(false) + ); + fork.push(record(7, 0, 9, 2, 3)).unwrap(); + assert_eq!(original.len(), fork.len()); + assert_eq!(rule.accepts_history(&fork, &probe).unwrap(), Some(true)); + assert_eq!( + rule.accepts_history(&original, &probe).unwrap(), + Some(false) + ); + fork.truncate(1).unwrap(); + assert_eq!(rule.accepts_history(&fork, &probe).unwrap(), Some(true)); +} + +#[test] +fn checkpoint_errors_are_owner_specific_and_fail_before_mutation() { + let store = Arc::new(Store::::new().unwrap()); + let event = record(7, 0, 9, 1, 1); + let mut history = History::from_events(store.clone(), [event, event]).unwrap(); + let checkpoint = history.checkpoint(); + let mut sibling = History::from_events(store, [event, event]).unwrap(); + assert!(matches!( + sibling.rollback(checkpoint), + Err(HistoryError::WrongCheckpointOwner) + )); + assert_eq!(sibling.as_slice(), &[event, event]); + history.truncate(1).unwrap(); + assert!(matches!( + history.rollback(checkpoint), + Err(HistoryError::CheckpointBeyondHistory) + )); + assert_eq!(history.as_slice(), &[event]); + history.push(event).unwrap(); + history.rollback(checkpoint).unwrap(); + assert_eq!(history.as_slice(), &[event, event]); + let another_store = Arc::new(Store::::new().unwrap()); + let same_raw = History::from_events(another_store, [event, event]).unwrap(); + assert_eq!(history, same_raw); + assert_eq!(format!("{history:?}"), format!("{same_raw:?}")); + assert!(matches!( + sibling.rollback(same_raw.checkpoint()), + Err(HistoryError::WrongCheckpointOwner) + )); +} + +#[test] +fn foreign_store_fails_before_candidate_projection_or_cache_lookup() { + let store = Arc::new(Store::::new().unwrap()); + let mut rule = CompiledRule::new(store, prior_edit()).unwrap(); + let foreign = History::new(Arc::new(Store::::new().unwrap())).unwrap(); + HISTORY_PROJECTIONS.with(|count| count.set(0)); + let candidate = record(7, 2, 9, 1, 1); + assert!(matches!( + rule.accepts_history(&foreign, &candidate), + Err(HistoryError::WrongHistoryOwner) + )); + HISTORY_PROJECTIONS.with(|count| assert_eq!(count.get(), 0)); + assert!(foreign.is_empty()); +} + +#[test] +fn decisions_and_forks_do_not_reencode_committed_events() { + let store = Arc::new(Store::::new().unwrap()); + let mut rule = CompiledRule::new(store.clone(), prior_edit()).unwrap(); + let history = History::from_events(store, [record(7, 1, 9, 1, 1); 4]).unwrap(); + HISTORY_PROJECTIONS.with(|count| count.set(0)); + let candidate = record(7, 2, 9, 2, 2000); + for _ in 0..3 { + assert_eq!( + rule.accepts_history(&history, &candidate).unwrap(), + Some(true) + ); + } + let fork = history.try_clone().unwrap(); + assert_eq!(fork.as_slice(), history.as_slice()); + assert_eq!(rule.accepts_history(&fork, &candidate).unwrap(), Some(true)); + HISTORY_PROJECTIONS.with(|count| assert_eq!(count.get(), 0)); + assert_eq!(history.len(), 4); +} diff --git a/src/history-store/Cargo.toml b/src/history-store/Cargo.toml new file mode 100644 index 000000000..5411b58af --- /dev/null +++ b/src/history-store/Cargo.toml @@ -0,0 +1,36 @@ +[package] +name = "history-store" +description = "Interned event store, committed histories and symbolic graphs for Regorus history rules" +version = "0.1.0" +edition = "2024" +license = "MIT" +repository = "https://github.com/microsoft/regorus" + +[package.metadata.verus] +verify = true + +[features] +default = [] +runtime = ["junco-core/runtime", "dep:bumpus", "dep:hashconsius", "dep:smallvec", "dep:lru", "dep:spin"] +std = ["dep:parking_lot", "junco-core/std", "history-syntax/std", "vstd/std"] +test-util = ["runtime", "junco-core/test-util"] + +[dependencies] +# Keep aligned with the root crate's vstd pin (.github/workflows/verus.yml). +vstd = { version = "=0.0.0-2026-10-04-0306", default-features = false, features = ["alloc"] } +junco-core = { path = "../junco-core", version = "0.1.0", default-features = false } +history-syntax = { path = "../history-syntax", version = "0.1.0", default-features = false } +parking_lot = { version = "0.13", optional = true } +smallvec = { version = "=1.16.2", default-features = false, optional = true } +# Verified arena and hash-consing crates; both pin the same vstd as this crate, +# and bumpus must equal hashconsius's own `=0.1.2` pin. +bumpus = { version = "=0.1.2", optional = true } +hashconsius = { version = "=0.1.4", default-features = false, optional = true } +lru = { version = "0.19.0", default-features = false, features = ["hashbrown"], optional = true } +spin = { version = "0.12.0", default-features = false, features = ["mutex", "spin_mutex", "rwlock"], optional = true } + +[dev-dependencies] +junco-core = { path = "../junco-core", default-features = false, features = ["test-util"] } + +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(verus_keep_ghost)'] } diff --git a/src/history-store/src/cache.rs b/src/history-store/src/cache.rs new file mode 100644 index 000000000..55ce32e24 --- /dev/null +++ b/src/history-store/src/cache.rs @@ -0,0 +1,391 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. +//! Storage for graph-local memoization and bounded history cursors. +use crate::graph::allocation; +use alloc::vec::Vec; +use core::num::NonZeroUsize; +use junco_core::errors::HistoryError; +use junco_core::kernel::{AtomSet, RegexId, TransitionId}; +use junco_core::limits::Limits; +use junco_core::observation::ObservationWorld; +#[cfg(verus_keep_ghost)] +use junco_core::observation::SmallVecSpecFns; +#[cfg(verus_keep_ghost)] +use junco_core::verify::history_assumptions::*; +use lru::LruCache; +use smallvec::SmallVec; +#[cfg(verus_keep_ghost)] +use verify::*; +use vstd::prelude::*; +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct EventClass { + pub transition: TransitionId, + pub words: SmallVec<[u64; 2]>, +} + +/// Self-loop certificate for one residual: when any atom of `transition` whose bit is set in +/// `mask` is false on an event, the event's successor is the residual itself. `mask == 0` +/// means "computed, nothing usable" (constant, wide, or budget-limited transition). +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Guard { + pub transition: TransitionId, + pub mask: u64, +} + +#[verus_verify] +pub const SUCCESSOR_CAPACITY: u64 = 256; + +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Debug)] +pub struct GraphCaches { + pub derivatives: Vec>, + pub atoms: Vec>, + pub guards: Vec>, + pub successors: Option>, +} +#[verus_verify] +impl GraphCaches { + #[expect( + clippy::new_without_default, + reason = "Construction stays on this verified constructor; Default would add an unverified path." + )] + #[verus_spec(result => ensures result.derivatives@ == Seq::>::empty(), + result.atoms@ == Seq::>::empty(), result.guards@ == Seq::>::empty(), + result.successors is None)] + pub const fn new() -> Self { + Self { + derivatives: Vec::new(), + atoms: Vec::new(), + guards: Vec::new(), + successors: None, + } + } + // Concrete LRU leaves expose semantic keys and membership, not policy semantics. The lookup + // contracts below assume that the derived `Hash`/`Eq` of `EventClass` (a `TransitionId` and a + // `SmallVec<[u64; 2]>`) agree with equality of its `class_key`; this is trusted (TRUST.md). + #[verus_verify(external_body)] + #[verus_spec(result => ensures result is Some, + result matches Some(cache) ==> successor_cache_view(cache) == Map::::empty())] + pub fn successor_cache() -> Option> { + usize::try_from(SUCCESSOR_CAPACITY) + .ok() + .and_then(NonZeroUsize::new) + .map(LruCache::new) + } + + #[verus_verify(external_body)] + #[verus_spec(result => + ensures successor_entries(*final(cache)) == successor_entries(*old(cache)), + result == if successor_entries(*old(cache)).contains_key(class_key(*key)) { + Some(successor_entries(*old(cache))[class_key(*key)]) + } else { None }, + )] + pub fn successor_get( + cache: &mut Option>, + key: &EventClass, + ) -> Option { + cache.as_mut().and_then(|cache| cache.get(key)).copied() + } + + #[verus_verify(external_body)] + #[verus_spec( + ensures *old(cache) is Some ==> *final(cache) is Some + && successor_entries(*final(cache)).contains_key(class_key(key)) + && successor_entries(*final(cache))[class_key(key)] == value, + *old(cache) is None ==> *final(cache) is None, + forall|other: ClassKey| #[trigger] successor_entries(*final(cache)).contains_key(other) ==> other == class_key(key) + || (successor_entries(*old(cache)).contains_key(other) + && successor_entries(*final(cache))[other] == successor_entries(*old(cache))[other]), + )] + pub fn successor_put( + cache: &mut Option>, + key: EventClass, + value: RegexId, + ) { + if let Some(cache) = cache.as_mut() { + cache.put(key, value); + } + } +} +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy, Debug)] +pub struct HistoryCursor { + pub history: usize, + pub bindings: junco_core::kernel::Bindings, + pub revision: u64, + pub consumed: usize, + pub residual: junco_core::kernel::RegexId, +} + +#[verus_verify] +pub const HISTORY_CACHE_CAPACITY: usize = 16; + +impl HistoryCursor { + // The pinned vstd lacks Iterator::position; this leaf selects an existing exact key only. + #[verus_verify(external_body)] + #[verus_spec(result => ensures match result { + Some(index) => index < cursors@.len() && cursor_key_eq(cursors@[index as int], *self) + && (forall|i: int| 0 <= i < index ==> !cursor_key_eq(cursors@[i], *self)), + None => forall|i: int| 0 <= i < cursors@.len() ==> !cursor_key_eq(cursors@[i], *self), + })] + #[inline] + pub fn position(&self, cursors: &[Self]) -> Option { + cursors + .iter() + .position(|old| old.history == self.history && old.bindings == self.bindings) + } +} + +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Debug)] +pub struct CursorCache { + entries: Vec, +} +#[verus_verify] +impl CursorCache { + /// Construction can fail only during reservation or host memory enforcement; + /// publishing cursors uses the reserved storage and has no fallible result. + #[verus_spec(result => ensures + result != Err(HistoryError::WrongHistoryOwner), + junco_core::verify::history_specs::no_invariant_failure(result), + result matches Err(error) ==> error is AllocationFailed || error is Limit, + result matches Err(error) ==> junco_core::spec::semantics::resource_error(error), + result matches Ok(cache) ==> cache@ == Seq::::empty() && cursor_cache_wf(cache@))] + pub fn new( + limits: &mut L, + world: &mut ObservationWorld, + ) -> Result { + let mut entries = Vec::new(); + allocation(world.try_reserve_vec_exact(&mut entries, HISTORY_CACHE_CAPACITY))?; + limits.enforce_memory()?; + proof! { reveal(::view); } + Ok(Self { entries }) + } + + #[verus_spec(result => ensures result@ == self@)] + pub fn entries(&self) -> &[HistoryCursor] { + proof! { reveal(::view); } + &self.entries + } + + #[expect( + clippy::collapsible_if, + reason = "Pinned Verus does not support let-chain expressions" + )] + #[verus_spec( + requires cursor_cache_wf(old(self)@), + ensures final(self)@ == published_cursors(old(self)@, cursor), + cursor_cache_wf(final(self)@), + longer_cached_prefix(old(self)@, cursor) ==> final(self)@ == old(self)@, + !longer_cached_prefix(old(self)@, cursor) ==> final(self)@.len() > 0 && final(self)@[0] == cursor, + forall|i: int| 0 <= i < final(self)@.len() ==> final(self)@[i] == cursor || old(self)@.contains(final(self)@[i]), + )] + pub fn publish(&mut self, cursor: HistoryCursor) { + proof! { reveal(::view); } + proof_decl! { let ghost entry = self.entries@; } + if let Some(position) = cursor.position(&self.entries) { + proof! { + assert forall|i: int| 0 <= i < entry.len() && cursor_key_eq(entry[i], cursor) implies i == position by { + if i < position { assert(!cursor_key_eq(entry[i], entry[position as int])); } + if i > position { assert(!cursor_key_eq(entry[position as int], entry[i])); } + } + } + if let Some(old) = self.entries.get(position) { + if old.revision == cursor.revision && old.consumed > cursor.consumed { + proof! { assert(longer_cached_prefix(entry, cursor)); } + return; + } + } + proof! { assert(!longer_cached_prefix(entry, cursor)); } + self.entries.remove(position); + proof! { + entry.remove_ensures(position as int); + assert(self.entries@ == kept_cursors(entry, cursor)); + lemma_kept_cursors(entry, cursor); + } + } else { + proof! { assert(!longer_cached_prefix(entry, cursor)); } + if self.entries.len() >= HISTORY_CACHE_CAPACITY { + self.entries.pop(); + } + proof! { + assert(self.entries@ == kept_cursors(entry, cursor)); + lemma_kept_cursors(entry, cursor); + } + } + proof_decl! { let ghost kept = self.entries@; } + // Capacity was reserved at construction; publication cannot allocate or fail. + self.entries.insert(0, cursor); + proof! { + assert(self.entries@ =~= seq![cursor] + kept); + assert forall|i: int, j: int| 0 <= i < j < self.entries@.len() + implies !cursor_key_eq(self.entries@[i], self.entries@[j]) by { + if i == 0 { assert(self.entries@[j] == kept[j - 1]); } + else { assert(self.entries@[i] == kept[i - 1]); assert(self.entries@[j] == kept[j - 1]); } + } + assert forall|i: int| 0 <= i < self.entries@.len() + implies self.entries@[i] == cursor || entry.contains(self.entries@[i]) by { + if i > 0 { assert(self.entries@[i] == kept[i - 1]); } + } + } + } +} +#[cfg(verus_keep_ghost)] +pub mod verify { + use super::*; + verus! { + #[verifier::external_type_specification] + #[verifier::external_body] + pub struct ExSuccessorHasher(lru::DefaultHasher); + #[verifier::external_type_specification] + #[verifier::external_body] + #[verifier::accept_recursive_types(K)] + #[verifier::accept_recursive_types(V)] + #[verifier::reject_recursive_types(S)] + pub struct ExLruCache(LruCache); + + + + pub struct ClassKey { pub transition: TransitionId, pub words: Seq } + pub open spec fn class_key(key: EventClass) -> ClassKey { + ClassKey { transition: key.transition, words: key.words.view() } + } + pub uninterp spec fn successor_cache_view(cache: LruCache) -> Map; + pub open spec fn successor_entries(cache: Option>) -> Map { + match cache { Some(cache) => successor_cache_view(cache), None => Map::empty() } + } + + impl View for CursorCache { + type V = Seq; + open(super) spec fn view(&self) -> Seq { self.entries@ } + } + pub open spec fn cursor_key_eq(left: HistoryCursor, right: HistoryCursor) -> bool { + left.history == right.history && left.bindings@ == right.bindings@ + } + pub open spec fn cursor_cache_wf(cursors: Seq) -> bool { + cursors.len() <= HISTORY_CACHE_CAPACITY + && (forall|i: int, j: int| 0 <= i < j < cursors.len() ==> !cursor_key_eq(cursors[i], cursors[j])) + } + pub open spec fn longer_cached_prefix(cursors: Seq, cursor: HistoryCursor) -> bool { + exists|i: int| 0 <= i < cursors.len() && cursor_key_eq(cursors[i], cursor) + && cursors[i].revision == cursor.revision && cursors[i].consumed > cursor.consumed + } + pub open spec fn kept_cursors(cursors: Seq, cursor: HistoryCursor) -> Seq { + if exists|i: int| 0 <= i < cursors.len() && cursor_key_eq(cursors[i], cursor) { + let index = choose|i: int| 0 <= i < cursors.len() && cursor_key_eq(cursors[i], cursor); + cursors.remove(index) + } else if cursors.len() >= HISTORY_CACHE_CAPACITY { cursors.drop_last() } + else { cursors } + } + pub open spec fn published_cursors(cursors: Seq, cursor: HistoryCursor) -> Seq { + if longer_cached_prefix(cursors, cursor) { cursors } + else { seq![cursor] + kept_cursors(cursors, cursor) } + } + pub proof fn lemma_kept_cursors(cursors: Seq, cursor: HistoryCursor) + requires cursor_cache_wf(cursors), + ensures kept_cursors(cursors, cursor).len() < HISTORY_CACHE_CAPACITY, + cursor_cache_wf(kept_cursors(cursors, cursor)), + forall|i: int| 0 <= i < kept_cursors(cursors, cursor).len() + ==> !cursor_key_eq(kept_cursors(cursors, cursor)[i], cursor) + && cursors.contains(kept_cursors(cursors, cursor)[i]), + { + let kept = kept_cursors(cursors, cursor); + if exists|i: int| 0 <= i < cursors.len() && cursor_key_eq(cursors[i], cursor) { + let index = choose|i: int| 0 <= i < cursors.len() && cursor_key_eq(cursors[i], cursor); + cursors.remove_ensures(index); + assert forall|i: int| 0 <= i < kept.len() implies !cursor_key_eq(kept[i], cursor) && cursors.contains(kept[i]) by { + let original = if i < index { i } else { i + 1 }; + assert(kept[i] == cursors[original]); + if original < index { assert(!cursor_key_eq(cursors[original], cursors[index])); } + else { assert(!cursor_key_eq(cursors[index], cursors[original])); } + } + assert forall|i: int, j: int| 0 <= i < j < kept.len() implies !cursor_key_eq(kept[i], kept[j]) by { + let left = if i < index { i } else { i + 1 }; + let right = if j < index { j } else { j + 1 }; + assert(kept[i] == cursors[left]); assert(kept[j] == cursors[right]); + } + } else { + assert forall|i: int| 0 <= i < kept.len() implies !cursor_key_eq(kept[i], cursor) && cursors.contains(kept[i]) by { + assert(kept[i] == cursors[i]); + } + assert forall|i: int, j: int| 0 <= i < j < kept.len() implies !cursor_key_eq(kept[i], kept[j]) by { + assert(kept[i] == cursors[i]); assert(kept[j] == cursors[j]); + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::graph::CanonicalStore; + use crate::store::HistoryStore; + use junco_core::kernel::Bindings; + use junco_core::limits::Unmetered; + + #[test] + fn publication_evicts_replaces_and_retains_longer_prefix() -> Result<(), HistoryError> { + let store = HistoryStore::new(3); + let graph = CanonicalStore::new()?; + let mut cache = CursorCache::new(&mut Unmetered, &mut ObservationWorld)?; + let mut handles = Vec::new(); + for _ in 0..=HISTORY_CACHE_CAPACITY { + let history = store.new_history(&mut Unmetered, &mut ObservationWorld)?; + cache.publish(HistoryCursor { + history: history.index(), + bindings: Bindings::new(&[0; 3]), + revision: 0, + consumed: 3, + residual: graph.constants().all, + }); + handles.push(history); + } + assert_eq!(cache.entries().len(), HISTORY_CACHE_CAPACITY); + assert!( + !cache + .entries() + .iter() + .any(|entry| entry.history == handles[0].index()) + ); + let replacement = HistoryCursor { + history: handles[8].index(), + bindings: Bindings::new(&[0; 3]), + revision: 0, + consumed: 5, + residual: graph.constants().epsilon, + }; + cache.publish(replacement); + assert_eq!(cache.entries()[0].history, replacement.history); + assert_eq!( + cache + .entries() + .iter() + .filter(|entry| entry.history == replacement.history) + .count(), + 1 + ); + let before = cache.entries().to_vec(); + cache.publish(HistoryCursor { + consumed: 4, + residual: graph.constants().empty, + ..replacement + }); + assert_eq!(cache.entries().len(), before.len()); + for (old, new) in before.iter().zip(cache.entries()) { + assert_eq!(old.history, new.history); + assert_eq!(old.bindings, new.bindings); + assert_eq!(old.revision, new.revision); + assert_eq!(old.consumed, new.consumed); + assert_eq!(old.residual, new.residual); + } + Ok(()) + } +} diff --git a/src/history-store/src/graph.rs b/src/history-store/src/graph.rs new file mode 100644 index 000000000..278ff29a0 --- /dev/null +++ b/src/history-store/src/graph.rs @@ -0,0 +1,2788 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +// Hash-consing mixes `u32` ids, counts, and flags into `u64` digests; every cast widens. +#![allow(clippy::as_conversions)] + +use alloc::vec::Vec; +use bumpus::{AllocErr, CHUNK_ALIGN, SliceArena}; +use core::mem::{align_of, size_of}; +use hashconsius::BHConsign; +#[cfg(verus_keep_ghost)] +use history_syntax::syntax::Component; +#[cfg(verus_keep_ghost)] +use junco_core::kernel::verify as model; +use junco_core::limits::Limits; +use junco_core::observation::ObservationWorld; +#[cfg(verus_keep_ghost)] +use junco_core::observation::SmallVecSpecFns; +#[cfg(verus_keep_ghost)] +use junco_core::verify::history_assumptions::KernelStoreSpec; +#[cfg(verus_keep_ghost)] +use junco_core::verify::history_specs::no_invariant_failure; +use junco_core::{errors::HistoryError, kernel::*}; +use vstd::prelude::*; +#[cfg(verus_keep_ghost)] +use vstd::std_specs::cmp::PartialEqSpec; + +#[allow( + clippy::option_if_let_else, + reason = "Explicit matches preserve the Verus proof structure" +)] +#[verus_verify] +#[verus_spec(result => ensures result == match value { + Some(value) => Ok(value), + None => Err((HistoryError::Invariant { message })), +})] +fn present(value: Option, message: &'static str) -> KernelResult { + match value { + Some(value) => Ok(value), + None => Err(HistoryError::Invariant { message }), + } +} +#[allow( + clippy::option_if_let_else, + reason = "Explicit matches preserve the Verus proof structure" +)] +#[verus_verify] +#[verus_spec(outcome => ensures outcome == match result { + Ok(value) => Ok(value), + Err(_) => Err(HistoryError::AllocationFailed), +}, outcome matches Err(error) ==> junco_core::spec::semantics::resource_error(error))] +pub fn allocation(result: Result) -> KernelResult { + match result { + Ok(value) => Ok(value), + Err(_) => Err(HistoryError::AllocationFailed), + } +} +/// Arena pushes: `Exhausted` is the only error the capacity theorem reasons about. +#[verus_verify] +#[verus_spec(outcome => ensures outcome == match result { + Ok(value) => Ok(value), + Err(AllocErr::Exhausted) => Err(HistoryError::ArenaExhausted), + Err(_) => Err(HistoryError::AllocationFailed), +}, outcome matches Err(error) ==> junco_core::spec::semantics::resource_error(error))] +fn arena(result: Result) -> KernelResult { + match result { + Ok(value) => Ok(value), + Err(AllocErr::Exhausted) => Err(HistoryError::ArenaExhausted), + Err(AllocErr::Global | AllocErr::Capacity) => Err(HistoryError::AllocationFailed), + } +} + +/// Chunk size per arena. Sufficiency: every pushed byte is charged via `projected` first; +/// `size_of::() > 0`, `align_of::() <= CHUNK_ALIGN` and +/// `ARENA_CAPACITY % align == 0` are asserted below for every compile target and re-checked at +/// runtime in `ArenaTables::with_capacity` so Verus can use them; same-type allocations from an +/// aligned cursor never pad. Theorem (`CanonicalStore::intern_*`): `ArenaExhausted` is returned +/// only if `storage.slack() < budget - storage.capacity()`, which a store whose arenas hold its +/// budget (`capacity == budget`, `slack == 0`) never satisfies. +// ponytail: six budget-sized chunks per retained pair (100 KiB for the runtime); share a chunk if +// allocation cost matters. +#[verus_verify] +pub(crate) const ARENA_CAPACITY: usize = MAX_GRAPH_BYTES; +// Premises of the capacity argument, checked on every compile target. `%` rather than +// `is_multiple_of` so Verus can reason about the same expression at runtime below. +#[allow(clippy::manual_is_multiple_of)] +const _: () = assert!( + size_of::() > 0 + && size_of::() > 0 + && size_of::() > 0 + && align_of::() <= CHUNK_ALIGN + && align_of::() <= CHUNK_ALIGN + && align_of::() <= CHUNK_ALIGN + && align_of::() <= CHUNK_ALIGN + && align_of::() <= CHUNK_ALIGN + && align_of::() <= CHUNK_ALIGN + && ARENA_CAPACITY % align_of::() == 0 + && ARENA_CAPACITY % align_of::() == 0 + && ARENA_CAPACITY % align_of::() == 0 + && ARENA_CAPACITY % align_of::() == 0 + && ARENA_CAPACITY % align_of::() == 0 + && ARENA_CAPACITY % align_of::() == 0 +); +#[verus_verify] +#[verus_spec(result => ensures match result { + Ok(bytes) => bytes as int == len * vstd::layout::size_of::(), + Err(error) => error is GraphIndex, +}, result matches Err(error) ==> junco_core::spec::semantics::resource_error(error))] +pub fn sequence_bytes(len: usize) -> KernelResult { + vstd::layout::layout_for_type_is_valid::(); + len.checked_mul(size_of::()) + .ok_or(HistoryError::GraphIndex) +} + +// Crate visibility lets Verus retain these payload types in the open weight specs. +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy)] +pub(crate) enum TestNode { + True, + False, + Atom { + primitive: Primitive, + positive: bool, + }, + And(usize), + Or(usize), +} +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy)] +enum RegexKind { + Empty, + All, + Epsilon, + Test(TestId), + Union(usize), + Concat(usize), + Star(RegexId), + Intersect(usize), + Not(RegexId), +} +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy)] +pub(crate) struct RegexNode { + kind: RegexKind, + nullable: bool, +} +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy)] +pub(crate) enum TransitionNode { + Const(RegexId), + If { + test: TestId, + then_transition: TransitionId, + else_transition: TransitionId, + }, + Union(usize), + Intersect(usize), + Not(TransitionId), + Append { + transition: TransitionId, + suffix: usize, + }, +} + +// Identity keys keep hash-consing over arena records, not lifted graph nodes. +vstd::prelude::verus! { + // Pinned 64-bit native layouts, observed from the compiled Rust types. + // Verus erasure emits exact Rust const assertions, so compiler layout drift fails to build. + #[cfg(target_pointer_width = "64")] + global layout TestNode is size == 32, align == 8; + #[cfg(target_pointer_width = "64")] + global layout RegexNode is size == 24, align == 8; + #[cfg(target_pointer_width = "64")] + global layout TransitionNode is size == 16, align == 8; + #[cfg(target_pointer_width = "64")] + global layout TestId is size == 4, align == 4; + #[cfg(target_pointer_width = "64")] + global layout RegexId is size == 4, align == 4; + #[cfg(target_pointer_width = "64")] + global layout TransitionId is size == 4, align == 4; + + impl View for TestNode { + type V = Self; + open(in crate::graph) spec fn view(&self) -> Self { *self } + } + impl View for RegexNode { + type V = Self; + open(in crate::graph) spec fn view(&self) -> Self { *self } + } + impl View for TransitionNode { + type V = Self; + open(in crate::graph) spec fn view(&self) -> Self { *self } + } + + pub(crate) open spec fn field_key(field: Component) -> u64 { + field.0 as u64 + } + pub(crate) open spec fn primitive_key_hash(p: Primitive) -> u64 { + match p { + Primitive::Eq { field, term: Term::Constant(c) } => hashconsius::spec_mix(hashconsius::spec_mix(field_key(field), 0), c), + Primitive::Eq { field, term: Term::Variable(v) } => hashconsius::spec_mix(hashconsius::spec_mix(field_key(field), 1), field_key(v)), + } + } + impl hashconsius::HashKey for TestNode { + open(in crate::graph) spec fn spec_hash(v: Self::V) -> u64 { match v { + TestNode::True => 0, + TestNode::False => 1, + TestNode::Atom { primitive, positive } => hashconsius::spec_mix(hashconsius::spec_mix(2, primitive_key_hash(primitive)), positive as u64), + TestNode::And(s) => hashconsius::spec_mix(3, s as u64), + TestNode::Or(s) => hashconsius::spec_mix(4, s as u64), + } } + fn hash(&self) -> (h: u64) + ensures h == Self::spec_hash(self@), + { + let v = *self; + match v { + TestNode::True => 0, + TestNode::False => 1, + TestNode::Atom { primitive, positive } => hashconsius::mix(hashconsius::mix(2, match primitive { + Primitive::Eq { field, term: Term::Constant(c) } => hashconsius::mix(hashconsius::mix(field.index() as u64, 0), c), + Primitive::Eq { field, term: Term::Variable(variable) } => hashconsius::mix(hashconsius::mix(field.index() as u64, 1), variable.index() as u64), + }), positive as u64), + TestNode::And(s) => hashconsius::mix(3, s as u64), + TestNode::Or(s) => hashconsius::mix(4, s as u64), + } + } + fn key_eq(&self, other: &Self) -> (b: bool) + ensures b == (self@ == other@), + { match (*self, *other) { + (TestNode::True, TestNode::True) | (TestNode::False, TestNode::False) => true, + // Full-field keys avoid the pinned verifier's early inherited-equality dependency; see verification/verus/inherited_ensures_order.rs. + ( + TestNode::Atom { + primitive: Primitive::Eq { field: a, term: x }, + positive: p, + }, + TestNode::Atom { + primitive: Primitive::Eq { field: b, term: y }, + positive: q, + }, + ) => { + a == b + && p == q + && match (x, y) { + (Term::Constant(c), Term::Constant(d)) => c == d, + (Term::Variable(c), Term::Variable(d)) => c == d, + _ => false, + } + }, + (TestNode::And(a), TestNode::And(b)) | (TestNode::Or(a), TestNode::Or(b)) => a == b, + _ => false, + } } + } + impl hashconsius::HashKey for RegexNode { + open(in crate::graph) spec fn spec_hash(v: Self::V) -> u64 { hashconsius::spec_mix(match v.kind { + RegexKind::Empty => 0, + RegexKind::All => 1, + RegexKind::Epsilon => 2, + RegexKind::Test(id) => hashconsius::spec_mix(3, id@ as u64), + RegexKind::Union(s) => hashconsius::spec_mix(4, s as u64), + RegexKind::Concat(s) => hashconsius::spec_mix(5, s as u64), + RegexKind::Star(id) => hashconsius::spec_mix(6, id@ as u64), + RegexKind::Intersect(s) => hashconsius::spec_mix(7, s as u64), + RegexKind::Not(id) => hashconsius::spec_mix(8, id@ as u64), + }, v.nullable as u64) } + fn hash(&self) -> (h: u64) + ensures h == Self::spec_hash(self@), + { + let v = *self; + hashconsius::mix(match v.kind { + RegexKind::Empty => 0, + RegexKind::All => 1, + RegexKind::Epsilon => 2, + RegexKind::Test(id) => hashconsius::mix(3, id.get() as u64), + RegexKind::Union(s) => hashconsius::mix(4, s as u64), + RegexKind::Concat(s) => hashconsius::mix(5, s as u64), + RegexKind::Star(id) => hashconsius::mix(6, id.get() as u64), + RegexKind::Intersect(s) => hashconsius::mix(7, s as u64), + RegexKind::Not(id) => hashconsius::mix(8, id.get() as u64), + }, v.nullable as u64) + } + fn key_eq(&self, other: &Self) -> (b: bool) + ensures b == (self@ == other@), + { self.nullable == other.nullable && match (self.kind, other.kind) { + (RegexKind::Empty, RegexKind::Empty) | (RegexKind::All, RegexKind::All) | (RegexKind::Epsilon, RegexKind::Epsilon) => true, + (RegexKind::Test(a), RegexKind::Test(b)) => a == b, + (RegexKind::Union(a), RegexKind::Union(b)) | (RegexKind::Concat(a), RegexKind::Concat(b)) | (RegexKind::Intersect(a), RegexKind::Intersect(b)) => a == b, + (RegexKind::Star(a), RegexKind::Star(b)) | (RegexKind::Not(a), RegexKind::Not(b)) => a == b, + _ => false, + } } + } + impl hashconsius::HashKey for TransitionNode { + open(in crate::graph) spec fn spec_hash(v: Self::V) -> u64 { match v { + TransitionNode::Const(id) => hashconsius::spec_mix(0, id@ as u64), + TransitionNode::If { test, then_transition, else_transition } => hashconsius::spec_mix(hashconsius::spec_mix(hashconsius::spec_mix(1, test@ as u64), then_transition@ as u64), else_transition@ as u64), + TransitionNode::Union(s) => hashconsius::spec_mix(2, s as u64), + TransitionNode::Intersect(s) => hashconsius::spec_mix(3, s as u64), + TransitionNode::Not(id) => hashconsius::spec_mix(4, id@ as u64), + TransitionNode::Append { transition, suffix } => hashconsius::spec_mix(hashconsius::spec_mix(5, transition@ as u64), suffix as u64), + } } + fn hash(&self) -> (h: u64) + ensures h == Self::spec_hash(self@), + { + let v = *self; + match v { + TransitionNode::Const(id) => hashconsius::mix(0, id.get() as u64), + TransitionNode::If { test, then_transition, else_transition } => hashconsius::mix(hashconsius::mix(hashconsius::mix(1, test.get() as u64), then_transition.get() as u64), else_transition.get() as u64), + TransitionNode::Union(s) => hashconsius::mix(2, s as u64), + TransitionNode::Intersect(s) => hashconsius::mix(3, s as u64), + TransitionNode::Not(id) => hashconsius::mix(4, id.get() as u64), + TransitionNode::Append { transition, suffix } => hashconsius::mix(hashconsius::mix(5, transition.get() as u64), suffix as u64), + } + } + fn key_eq(&self, other: &Self) -> (b: bool) + ensures b == (self@ == other@), + { match (*self, *other) { + (TransitionNode::Const(a), TransitionNode::Const(b)) => a == b, + (TransitionNode::If { test: a, then_transition: b, else_transition: c }, TransitionNode::If { test: d, then_transition: e, else_transition: f }) => a == d && b == e && c == f, + (TransitionNode::Union(a), TransitionNode::Union(b)) | (TransitionNode::Intersect(a), TransitionNode::Intersect(b)) => a == b, + (TransitionNode::Not(a), TransitionNode::Not(b)) => a == b, + (TransitionNode::Append { transition: a, suffix: b }, TransitionNode::Append { transition: c, suffix: d }) => a == c && b == d, + _ => false, + } } + } +} + +macro_rules! id_lists { + ($name:ident, $id:ident, $eq_lemma:ident) => { + #[verus_verify] + struct $name { + slices: SliceArena<$id>, + index: hashconsius::index::Buckets, + } + vstd::prelude::verus! { + impl View for $name { + type V = Seq>; + open(in crate::graph) spec fn view(&self) -> Self::V { self.slices@ } + } + impl $name { + pub(super) open(in crate::graph) spec fn ids_hash_prefix(ids: Seq<$id>, n: nat) -> u64 + recommends n <= ids.len(), + decreases n, + { + if n == 0 { ids.len() as u64 } + else { hashconsius::spec_mix(Self::ids_hash_prefix(ids, (n - 1) as nat), ids[n - 1]@ as u64) } + } + pub(super) open(in crate::graph) spec fn ids_spec_hash(ids: Seq<$id>) -> u64 { + Self::ids_hash_prefix(ids, ids.len()) + } + pub(super) open(in crate::graph) spec fn hashes(self) -> Seq { + self@.map_values(|ids: Seq<$id>| Self::ids_spec_hash(ids)) + } + pub(super) open(in crate::graph) spec fn inv(self) -> bool { + self.index.inv(self.hashes()) && self@.no_duplicates() + && self@.len() <= usize::MAX + } + pub(super) open(in crate::graph) spec fn capacity(self) -> int { self.slices.capacity() } + pub(super) open(in crate::graph) spec fn remaining(self) -> int { self.slices.remaining() } + pub(super) open(in crate::graph) spec fn aligned(self) -> bool { self.slices.aligned() } + + fn ids_hash(ids: &[$id]) -> (h: u64) + ensures h == Self::ids_spec_hash(ids@), + { + let mut h = ids.len() as u64; + let mut i = 0; + while i < ids.len() + invariant i <= ids.len(), h == Self::ids_hash_prefix(ids@, i as nat), + decreases ids.len() - i, + { + let id = match ids.get(i) { Some(id) => id, None => return h }; + h = hashconsius::mix(h, id.get() as u64); + i = i.saturating_add(1); + } + h + } + + fn with_capacity(bytes: usize) -> (r: Result) + ensures r matches Ok(a) ==> a.inv() && a@ == Seq::>::empty() + && a.capacity() == bytes && a.remaining() == bytes + && (vstd::layout::align_of::<$id>() <= CHUNK_ALIGN + && bytes as int % vstd::layout::align_of::<$id>() as int == 0 ==> a.aligned()), + { + vstd::layout::layout_for_type_is_valid::<$id>(); + let slices = SliceArena::with_capacity(bytes)?; + let index = hashconsius::index::Buckets::new(64); + let result = Self { slices, index }; + proof { assert(result.hashes() =~= Seq::::empty()); } + Ok(result) + } + + + fn find(&self, ids: &[$id]) -> (r: Option) + requires self.inv(), + ensures + r matches Some(slot) ==> slot < self@.len() && self@[slot as int] == ids@, + r is None ==> !self@.contains(ids@), + { + let h = Self::ids_hash(ids); + proof { self.index.lemma_nonempty(self.hashes()); } + let bucket = self.index.bucket(h); + let mut j = 0; + while j < bucket.len() + invariant + self.inv(), h == Self::ids_spec_hash(ids@), + self.index.nb() > 0, + bucket@ == self.index.bucket_of(h), j <= bucket@.len(), + forall|k: int| 0 <= k < j ==> bucket@[k].1 < self@.len() + && !(bucket@[k].0 == h && self@[bucket@[k].1 as int] == ids@), + decreases bucket@.len() - j, + { + let (bh, slot) = match bucket.get(j) { + Some(entry) => *entry, + None => return None, + }; + proof { self.index.lemma_sound(self.hashes(), h, j as int); } + if bh == h { + let candidate = match self.slices.get(slot) { + Some(candidate) => candidate, + None => return None, + }; + proof { + assert forall|a: $id, b: $id| #[trigger] a.eq_spec(&b) == (a == b) by { + verify::$eq_lemma(a, b); + } + } + if junco_core::kernel::id_slice_eq(candidate, ids) { return Some(slot); } + } + j = j.saturating_add(1); + } + proof { + assert forall|slot: int| 0 <= slot < self@.len() + implies self@[slot] != ids@ by { + if self@[slot] == ids@ { + self.index.lemma_complete(self.hashes(), slot); + assert(self.hashes()[slot] == h); + let k = bucket@.lemma_contains_to_index((h, slot as usize)); + assert(bucket@[k] == (h, slot as usize)); + } + } + } + None + } + + fn intern(&mut self, ids: &[$id]) -> (r: Result) + requires old(self).inv(), + ensures + final(self).inv(), + old(self)@.is_prefix_of(final(self)@), + final(self).capacity() == old(self).capacity(), + old(self).aligned() ==> final(self).aligned(), + r is Err ==> final(self)@ == old(self)@ + && final(self).remaining() == old(self).remaining() + && final(self).aligned() == old(self).aligned(), + r matches Ok(slot) ==> slot < final(self)@.len() + && final(self)@[slot as int] == ids@ + && (old(self)@.contains(ids@) ==> + final(self)@ == old(self)@ + && final(self).remaining() == old(self).remaining()) + && (!old(self)@.contains(ids@) ==> + slot == old(self)@.len() && final(self)@ == old(self)@.push(ids@) + && (old(self).aligned() ==> final(self).remaining() + == old(self).remaining() - ids@.len() * vstd::layout::size_of::<$id>())), + old(self).aligned() && r == Err(AllocErr::Exhausted) ==> + ids@.len() * vstd::layout::size_of::<$id>() > old(self).remaining(), + { + vstd::layout::layout_for_type_is_valid::<$id>(); + let ghost before = *self; + match self.find(ids) { + Some(slot) => return Ok(slot), + None => {}, + } + let h = Self::ids_hash(ids); + let ghost hashes = self.hashes(); + let slot = self.slices.len(); + self.slices.try_push(ids)?; + let _count = self.slices.len(); + proof { + assert(self@ == before@.push(ids@)); + assert(self@.no_duplicates()); + assert(self.hashes() =~= hashes.push(h)); + assert(hashes.len() < usize::MAX) by { + assert(_count == hashes.len() + 1); + } + } + self.index.insert(h, slot, Ghost(hashes)); + Ok(slot) + } + + fn free(self) + requires self.inv(), + { self.slices.free(); } + } + } + }; +} + +id_lists!(TestIdLists, TestId, lemma_test_id_eq); +id_lists!(RegexIdLists, RegexId, lemma_regex_id_eq); +id_lists!(TransitionIdLists, TransitionId, lemma_transition_id_eq); + +#[verus_verify] +struct ArenaTables { + tests: BHConsign, + test_ids: TestIdLists, + regexes: BHConsign, + regex_ids: RegexIdLists, + transitions: BHConsign, + transition_ids: TransitionIdLists, + #[cfg(test)] + lifetime_counts: Option>, +} +#[verus_verify] +pub(crate) struct ArenaStorage { + tables: Option, +} + +// Verus does not model implicit destruction; ArenaTables::release checks the six frees. +#[verus_verify(external)] +impl Drop for ArenaStorage { + fn drop(&mut self) { + if let Some(tables) = self.tables.take() { + tables.release(); + } + } +} + +#[cfg(test)] +#[derive(Default)] +pub struct ArenaLifetimeCounts { + allocations: core::sync::atomic::AtomicUsize, + frees: core::sync::atomic::AtomicUsize, +} + +#[cfg(test)] +impl ArenaLifetimeCounts { + pub fn snapshot(&self) -> (usize, usize) { + use core::sync::atomic::Ordering; + ( + self.allocations.load(Ordering::Relaxed), + self.frees.load(Ordering::Relaxed), + ) + } + + fn freed(counts: &Option>) { + if let Some(counts) = counts { + counts + .frees + .fetch_add(1, core::sync::atomic::Ordering::Relaxed); + } + } +} + +#[cfg(test)] +impl ArenaStorage { + /// Observe this storage's six existing chunks and their individual frees. + pub fn track_lifetime( + &mut self, + counts: alloc::sync::Arc, + ) -> KernelResult<()> { + let tables = present(self.tables.as_mut(), "arena released")?; + if tables.lifetime_counts.is_some() { + return Err(HistoryError::invariant("arena lifetime already observed")); + } + counts + .allocations + .fetch_add(6, core::sync::atomic::Ordering::Relaxed); + tables.lifetime_counts = Some(counts); + Ok(()) + } +} + +#[cfg(verus_keep_ghost)] +verus! { + impl ArenaStorage { + pub(crate) closed spec fn has_tables(&self) -> bool { + self.tables is Some + } + + #[verifier::type_invariant] + closed spec fn inv(&self) -> bool { + self.tables is Some ==> verify::tables_wf(&self.tables->0) + } + } +} + +#[verus_verify] +impl ArenaTables { + #[allow( + clippy::arithmetic_side_effects, + reason = "Type alignments are nonzero, so these remainder checks cannot panic" + )] + #[verus_spec(result => ensures result matches Ok(t) ==> verify::tables_wf(&t) + && verify::empty_tables(verify::tables_graph(&t)) + && verify::tables_capacity(&t) == capacity && verify::tables_slack(&t) == 0, + result matches Err(error) ==> error is Invariant || error is AllocationFailed, + verify::construction_layout(capacity) ==> no_invariant_failure(result))] + #[allow(clippy::manual_is_multiple_of)] + fn with_capacity(capacity: usize) -> KernelResult { + vstd::layout::layout_for_type_is_valid::(); + vstd::layout::layout_for_type_is_valid::(); + vstd::layout::layout_for_type_is_valid::(); + vstd::layout::layout_for_type_is_valid::(); + vstd::layout::layout_for_type_is_valid::(); + vstd::layout::layout_for_type_is_valid::(); + // Statically true (see the `const _` assert above); repeated here so Verus can use it. + if size_of::() == 0 + || size_of::() == 0 + || size_of::() == 0 + || align_of::() > CHUNK_ALIGN + || align_of::() > CHUNK_ALIGN + || align_of::() > CHUNK_ALIGN + || align_of::() > CHUNK_ALIGN + || align_of::() > CHUNK_ALIGN + || align_of::() > CHUNK_ALIGN + || capacity % align_of::() != 0 + || capacity % align_of::() != 0 + || capacity % align_of::() != 0 + || capacity % align_of::() != 0 + || capacity % align_of::() != 0 + || capacity % align_of::() != 0 + { + return Err(HistoryError::invariant("arena layout premises violated")); + } + let tests = allocation(BHConsign::new(capacity))?; + let test_ids = match TestIdLists::with_capacity(capacity) { + Ok(arena) => arena, + Err(_) => { + tests.free(); + return Err(HistoryError::AllocationFailed); + } + }; + let regexes = match BHConsign::new(capacity) { + Ok(arena) => arena, + Err(_) => { + tests.free(); + test_ids.free(); + return Err(HistoryError::AllocationFailed); + } + }; + let regex_ids = match RegexIdLists::with_capacity(capacity) { + Ok(arena) => arena, + Err(_) => { + tests.free(); + test_ids.free(); + regexes.free(); + return Err(HistoryError::AllocationFailed); + } + }; + let transitions = match BHConsign::new(capacity) { + Ok(arena) => arena, + Err(_) => { + tests.free(); + test_ids.free(); + regexes.free(); + regex_ids.free(); + return Err(HistoryError::AllocationFailed); + } + }; + let transition_ids = match TransitionIdLists::with_capacity(capacity) { + Ok(arena) => arena, + Err(_) => { + tests.free(); + test_ids.free(); + regexes.free(); + regex_ids.free(); + transitions.free(); + return Err(HistoryError::AllocationFailed); + } + }; + let tables = Self { + tests, + test_ids, + regexes, + regex_ids, + transitions, + transition_ids, + #[cfg(test)] + lifetime_counts: None, + }; + proof! { verify::lemma_fresh_tables(&tables, capacity); } + Ok(tables) + } + #[verus_spec(result => requires verify::tables_wf(self), ensures + result matches Ok(v) ==> index < verify::tables_graph(self).tests.len() + && v@ == verify::tables_graph(self).tests[index as int], + result matches Err(error) ==> error is Invariant, + index < verify::tables_graph(self).tests.len() ==> result is Ok)] + fn test(&self, index: usize) -> KernelResult> { + if index >= self.tests.len() { + return Err(HistoryError::invariant("invalid test ID")); + } + let node = self.tests.elem(index); + proof! { assert(verify::arena_test_wf(self, *node)); } + Ok(match *node { + TestNode::True => TestView::True, + TestNode::False => TestView::False, + TestNode::Atom { + primitive, + positive, + } => TestView::Atom { + primitive, + positive, + }, + TestNode::And(slot) => TestView::And(present( + self.test_ids.slices.get(slot), + "invalid test children", + )?), + TestNode::Or(slot) => TestView::Or(present( + self.test_ids.slices.get(slot), + "invalid test children", + )?), + }) + } + #[verus_spec(result => requires verify::tables_wf(self), ensures + result matches Ok(v) ==> index < verify::tables_graph(self).regexes.len() + && v@ == verify::tables_graph(self).regexes[index as int], + result matches Err(error) ==> error is Invariant, + index < verify::tables_graph(self).regexes.len() ==> result is Ok)] + fn regex(&self, index: usize) -> KernelResult> { + if index >= self.regexes.len() { + return Err(HistoryError::invariant("invalid regex ID")); + } + let node = self.regexes.elem(index); + proof! { assert(verify::arena_regex_wf(self, *node)); } + let kind = match node.kind { + RegexKind::Empty => RegexKindView::Empty, + RegexKind::All => RegexKindView::All, + RegexKind::Epsilon => RegexKindView::Epsilon, + RegexKind::Test(id) => RegexKindView::Test(id), + RegexKind::Union(slot) => RegexKindView::Union(present( + self.regex_ids.slices.get(slot), + "invalid regex children", + )?), + RegexKind::Concat(slot) => RegexKindView::Concat(present( + self.regex_ids.slices.get(slot), + "invalid regex children", + )?), + RegexKind::Star(id) => RegexKindView::Star(id), + RegexKind::Intersect(slot) => RegexKindView::Intersect(present( + self.regex_ids.slices.get(slot), + "invalid regex children", + )?), + RegexKind::Not(id) => RegexKindView::Not(id), + }; + Ok(RegexView { + kind, + nullable: node.nullable, + }) + } + #[verus_spec(result => requires verify::tables_wf(self), ensures + result matches Ok(v) ==> index < verify::tables_graph(self).transitions.len() + && v@ == verify::tables_graph(self).transitions[index as int], + result matches Err(error) ==> error is Invariant, + index < verify::tables_graph(self).transitions.len() ==> result is Ok)] + fn transition(&self, index: usize) -> KernelResult> { + if index >= self.transitions.len() { + return Err(HistoryError::invariant("invalid transition ID")); + } + let node = self.transitions.elem(index); + proof! { assert(verify::arena_transition_wf(self, *node)); } + Ok(match *node { + TransitionNode::Const(id) => TransitionView::Const(id), + TransitionNode::If { + test, + then_transition, + else_transition, + } => TransitionView::If { + test, + then_transition, + else_transition, + }, + TransitionNode::Union(slot) => TransitionView::Union(present( + self.transition_ids.slices.get(slot), + "invalid transition children", + )?), + TransitionNode::Intersect(slot) => TransitionView::Intersect(present( + self.transition_ids.slices.get(slot), + "invalid transition children", + )?), + TransitionNode::Not(id) => TransitionView::Not(id), + TransitionNode::Append { transition, suffix } => TransitionView::Append { + transition, + suffix: present(self.regex_ids.slices.get(suffix), "invalid append suffix")?, + }, + }) + } + #[verus_spec(result => requires verify::tables_wf(self), ensures + result matches Ok(Some(id)) ==> id@ < verify::tables_graph(self).tests.len() + && verify::tables_graph(self).tests[id@ as int] == view@, + result matches Ok(None) ==> !verify::tables_graph(self).tests.contains(view@), + result matches Err(error) ==> error is GraphIndex)] + fn find_test(&self, view: TestView<'_>) -> KernelResult> { + let node = match view { + TestView::True => TestNode::True, + TestView::False => TestNode::False, + TestView::Atom { + primitive, + positive, + } => TestNode::Atom { + primitive, + positive, + }, + TestView::And(ids) | TestView::Or(ids) => { + let Some(slot) = self.test_ids.find(ids) else { + proof! { verify::lemma_missing_test_children(self, view@, ids@); } + return Ok(None); + }; + match view { + TestView::And(_) => TestNode::And(slot), + _ => TestNode::Or(slot), + } + } + }; + proof! { verify::lemma_test_contains(self, node); } + match self.tests.find(&node) { + Some(slot) => Ok(Some(TestId::from_index(slot)?)), + None => Ok(None), + } + } + #[verus_spec(result => requires verify::tables_wf(self), ensures + result matches Ok(Some(id)) ==> id@ < verify::tables_graph(self).regexes.len() + && verify::tables_graph(self).regexes[id@ as int] == view@, + result matches Ok(None) ==> !verify::tables_graph(self).regexes.contains(view@), + result matches Err(error) ==> error is GraphIndex)] + fn find_regex(&self, view: RegexView<'_>) -> KernelResult> { + let kind = match view.kind { + RegexKindView::Empty => RegexKind::Empty, + RegexKindView::All => RegexKind::All, + RegexKindView::Epsilon => RegexKind::Epsilon, + RegexKindView::Test(id) => RegexKind::Test(id), + RegexKindView::Star(id) => RegexKind::Star(id), + RegexKindView::Not(id) => RegexKind::Not(id), + RegexKindView::Union(ids) + | RegexKindView::Concat(ids) + | RegexKindView::Intersect(ids) => { + let Some(slot) = self.regex_ids.find(ids) else { + proof! { verify::lemma_missing_regex_children(self, view@, ids@); } + return Ok(None); + }; + match view.kind { + RegexKindView::Union(_) => RegexKind::Union(slot), + RegexKindView::Concat(_) => RegexKind::Concat(slot), + _ => RegexKind::Intersect(slot), + } + } + }; + let node = RegexNode { + kind, + nullable: view.nullable, + }; + proof! { verify::lemma_regex_contains(self, node); } + match self.regexes.find(&node) { + Some(slot) => Ok(Some(RegexId::from_index(slot)?)), + None => Ok(None), + } + } + #[verus_spec(result => requires verify::tables_wf(self), ensures + result matches Ok(Some(id)) ==> id@ < verify::tables_graph(self).transitions.len() + && verify::tables_graph(self).transitions[id@ as int] == view@, + result matches Ok(None) ==> !verify::tables_graph(self).transitions.contains(view@), + result matches Err(error) ==> error is GraphIndex)] + fn find_transition(&self, view: TransitionView<'_>) -> KernelResult> { + let node = match view { + TransitionView::Const(id) => TransitionNode::Const(id), + TransitionView::If { + test, + then_transition, + else_transition, + } => TransitionNode::If { + test, + then_transition, + else_transition, + }, + TransitionView::Not(id) => TransitionNode::Not(id), + TransitionView::Union(ids) | TransitionView::Intersect(ids) => { + let Some(slot) = self.transition_ids.find(ids) else { + proof! { verify::lemma_missing_transition_children(self, view@, ids@); } + return Ok(None); + }; + match view { + TransitionView::Union(_) => TransitionNode::Union(slot), + _ => TransitionNode::Intersect(slot), + } + } + TransitionView::Append { transition, suffix } => { + let Some(slot) = self.regex_ids.find(suffix) else { + proof! { verify::lemma_missing_append_suffix(self, transition@, suffix@); } + return Ok(None); + }; + TransitionNode::Append { + transition, + suffix: slot, + } + } + }; + proof! { verify::lemma_transition_contains(self, node); } + match self.transitions.find(&node) { + Some(slot) => Ok(Some(TransitionId::from_index(slot)?)), + None => Ok(None), + } + } + #[verus_spec(result => requires verify::tables_wf(old(self)), + !verify::tables_graph(old(self)).tests.contains(view@), ensures + verify::tables_wf(final(self)), + verify::tables_graph(final(self)).constants == verify::tables_graph(old(self)).constants, + verify::tables_graph(final(self)).regexes == verify::tables_graph(old(self)).regexes, + verify::tables_graph(final(self)).transitions == verify::tables_graph(old(self)).transitions, + result is Err ==> verify::tables_graph(final(self)) == verify::tables_graph(old(self)), + result matches Ok(id) ==> id@ == verify::tables_graph(old(self)).tests.len() + && verify::tables_graph(final(self)).tests == verify::tables_graph(old(self)).tests.push(view@), + result matches Err(error) ==> error is GraphBudget || error is GraphIndex || error is ArenaExhausted || error is AllocationFailed, + verify::tables_capacity(final(self)) == verify::tables_capacity(old(self)), + result is Ok ==> verify::tables_slack(final(self)) >= verify::tables_slack(old(self)), + result matches Err(error) ==> error is ArenaExhausted ==> + verify::graph_weight(verify::tables_graph(old(self))) + verify::test_weight(view@) + - verify::tables_slack(old(self)) > verify::tables_capacity(old(self)))] + fn push_test(&mut self, view: TestView<'_>) -> KernelResult { + vstd::layout::layout_for_type_is_valid::(); + proof_decl! { let ghost before = *self; } + let id = TestId::from_index(self.tests.len())?; + let node = match view { + TestView::True => TestNode::True, + TestView::False => TestNode::False, + TestView::Atom { + primitive, + positive, + } => TestNode::Atom { + primitive, + positive, + }, + TestView::And(ids) => { + let slot = arena(self.test_ids.intern(ids))?; + proof! { verify::lemma_pool_bytes_push(before.test_ids@, ids@); } + proof! { + assert(verify::pool_bytes(self.test_ids@) <= verify::pool_bytes(before.test_ids@) + + verify::mul_bytes(ids@.len(), vstd::layout::size_of::())); + } + TestNode::And(slot) + } + TestView::Or(ids) => { + let slot = arena(self.test_ids.intern(ids))?; + proof! { verify::lemma_pool_bytes_push(before.test_ids@, ids@); } + proof! { + assert(verify::pool_bytes(self.test_ids@) <= verify::pool_bytes(before.test_ids@) + + verify::mul_bytes(ids@.len(), vstd::layout::size_of::())); + } + TestNode::Or(slot) + } + }; + proof! { + assert(self.test_ids@.take(before.test_ids@.len() as int) =~= before.test_ids@); + assert(self.regex_ids@.take(before.regex_ids@.len() as int) =~= before.regex_ids@); + assert(self.transition_ids@.take(before.transition_ids@.len() as int) =~= before.transition_ids@); + verify::pool_extension(&before, &*self); + assert(verify::tables_space_wf(self)); + assert(verify::arena_test_node(node, self.test_ids@) == view@); + verify::lemma_test_contains(self, node); + assert(!self.tests@.contains(node)); + } + let _handle = match self.tests.try_mk(node) { + Ok(handle) => handle, + Err(_) => return Err(HistoryError::ArenaExhausted), + }; + proof! { + assert(verify::tables_graph(self).tests =~= verify::tables_graph(&before).tests.push(view@)); + assert(_handle.spec_uid() == id@ as nat); + assert forall|i: int| 0 <= i < self.tests@.len() implies + verify::arena_test_wf(self, self.tests@[i]) by { + if i < before.tests@.len() { assert(self.tests@[i] == before.tests@[i]); } + } + verify::lemma_tests_weight_push(verify::tables_graph(&before).tests, view@); + verify::lemma_mul_bytes_succ(before.tests@.len(), vstd::layout::size_of::()); + assert(verify::tables_wf(self)); + assert(verify::arena_live(self) <= verify::arena_live(&before) + verify::test_weight(view@)); + } + Ok(id) + } + #[allow( + clippy::shadow_unrelated, + reason = "Local node identifiers mirror the matched Verus model variants" + )] + #[verus_spec(result => requires verify::tables_wf(old(self)), + !verify::tables_graph(old(self)).regexes.contains(view@), ensures + verify::tables_wf(final(self)), + verify::tables_graph(final(self)).constants == verify::tables_graph(old(self)).constants, + verify::tables_graph(final(self)).tests == verify::tables_graph(old(self)).tests, + verify::tables_graph(final(self)).transitions == verify::tables_graph(old(self)).transitions, + result is Err ==> verify::tables_graph(final(self)) == verify::tables_graph(old(self)), + result matches Ok(id) ==> id@ == verify::tables_graph(old(self)).regexes.len() + && verify::tables_graph(final(self)).regexes == verify::tables_graph(old(self)).regexes.push(view@), + result matches Err(error) ==> error is GraphBudget || error is GraphIndex || error is ArenaExhausted || error is AllocationFailed, + verify::tables_capacity(final(self)) == verify::tables_capacity(old(self)), + result is Ok ==> verify::tables_slack(final(self)) >= verify::tables_slack(old(self)), + result matches Err(error) ==> error is ArenaExhausted ==> + verify::graph_weight(verify::tables_graph(old(self))) + verify::regex_weight(view@) + - verify::tables_slack(old(self)) > verify::tables_capacity(old(self)))] + fn push_regex(&mut self, view: RegexView<'_>) -> KernelResult { + vstd::layout::layout_for_type_is_valid::(); + proof_decl! { let ghost before = *self; } + let id = RegexId::from_index(self.regexes.len())?; + let kind = match view.kind { + RegexKindView::Empty => RegexKind::Empty, + RegexKindView::All => RegexKind::All, + RegexKindView::Epsilon => RegexKind::Epsilon, + RegexKindView::Test(id) => RegexKind::Test(id), + RegexKindView::Union(ids) => { + let slot = arena(self.regex_ids.intern(ids))?; + proof! { verify::lemma_pool_bytes_push(before.regex_ids@, ids@); } + proof! { + assert(verify::pool_bytes(self.regex_ids@) <= verify::pool_bytes(before.regex_ids@) + + verify::mul_bytes(ids@.len(), vstd::layout::size_of::())); + } + RegexKind::Union(slot) + } + RegexKindView::Concat(ids) => { + let slot = arena(self.regex_ids.intern(ids))?; + proof! { verify::lemma_pool_bytes_push(before.regex_ids@, ids@); } + proof! { + assert(verify::pool_bytes(self.regex_ids@) <= verify::pool_bytes(before.regex_ids@) + + verify::mul_bytes(ids@.len(), vstd::layout::size_of::())); + } + RegexKind::Concat(slot) + } + RegexKindView::Star(id) => RegexKind::Star(id), + RegexKindView::Intersect(ids) => { + let slot = arena(self.regex_ids.intern(ids))?; + proof! { verify::lemma_pool_bytes_push(before.regex_ids@, ids@); } + proof! { + assert(verify::pool_bytes(self.regex_ids@) <= verify::pool_bytes(before.regex_ids@) + + verify::mul_bytes(ids@.len(), vstd::layout::size_of::())); + } + RegexKind::Intersect(slot) + } + RegexKindView::Not(id) => RegexKind::Not(id), + }; + let node = RegexNode { + kind, + nullable: view.nullable, + }; + proof! { + assert(self.test_ids@.take(before.test_ids@.len() as int) =~= before.test_ids@); + assert(self.regex_ids@.take(before.regex_ids@.len() as int) =~= before.regex_ids@); + assert(self.transition_ids@.take(before.transition_ids@.len() as int) =~= before.transition_ids@); + verify::pool_extension(&before, &*self); + assert(verify::tables_space_wf(self)); + assert(verify::arena_regex_node(node, self.regex_ids@) == view@); + verify::lemma_regex_contains(self, node); + assert(!self.regexes@.contains(node)); + } + let _handle = match self.regexes.try_mk(node) { + Ok(handle) => handle, + Err(_) => return Err(HistoryError::ArenaExhausted), + }; + proof! { + assert(verify::tables_graph(self).regexes =~= verify::tables_graph(&before).regexes.push(view@)); + assert(_handle.spec_uid() == id@ as nat); + assert forall|i: int| 0 <= i < self.regexes@.len() implies + verify::arena_regex_wf(self, self.regexes@[i]) by { + if i < before.regexes@.len() { assert(self.regexes@[i] == before.regexes@[i]); } + } + verify::lemma_regexes_weight_push(verify::tables_graph(&before).regexes, view@); + verify::lemma_mul_bytes_succ(before.regexes@.len(), vstd::layout::size_of::()); + assert(verify::tables_wf(self)); + assert(verify::arena_live(self) <= verify::arena_live(&before) + verify::regex_weight(view@)); + } + Ok(id) + } + #[allow( + clippy::shadow_unrelated, + reason = "Local node identifiers mirror the matched Verus model variants" + )] + #[verus_spec(result => requires verify::tables_wf(old(self)), + !verify::tables_graph(old(self)).transitions.contains(view@), ensures + verify::tables_wf(final(self)), + verify::tables_graph(final(self)).constants == verify::tables_graph(old(self)).constants, + verify::tables_graph(final(self)).tests == verify::tables_graph(old(self)).tests, + verify::tables_graph(final(self)).regexes == verify::tables_graph(old(self)).regexes, + result is Err ==> verify::tables_graph(final(self)) == verify::tables_graph(old(self)), + result matches Ok(id) ==> id@ == verify::tables_graph(old(self)).transitions.len() + && verify::tables_graph(final(self)).transitions == verify::tables_graph(old(self)).transitions.push(view@), + result matches Err(error) ==> error is GraphBudget || error is GraphIndex || error is ArenaExhausted || error is AllocationFailed, + verify::tables_capacity(final(self)) == verify::tables_capacity(old(self)), + result is Ok ==> verify::tables_slack(final(self)) >= verify::tables_slack(old(self)), + result matches Err(error) ==> error is ArenaExhausted ==> + verify::graph_weight(verify::tables_graph(old(self))) + verify::transition_weight(view@) + - verify::tables_slack(old(self)) > verify::tables_capacity(old(self)))] + fn push_transition(&mut self, view: TransitionView<'_>) -> KernelResult { + vstd::layout::layout_for_type_is_valid::(); + proof_decl! { let ghost before = *self; } + let id = TransitionId::from_index(self.transitions.len())?; + let node = match view { + TransitionView::Const(id) => TransitionNode::Const(id), + TransitionView::If { + test, + then_transition, + else_transition, + } => TransitionNode::If { + test, + then_transition, + else_transition, + }, + TransitionView::Union(ids) => { + let slot = arena(self.transition_ids.intern(ids))?; + proof! { verify::lemma_pool_bytes_push(before.transition_ids@, ids@); } + proof! { + assert(verify::pool_bytes(self.transition_ids@) <= verify::pool_bytes(before.transition_ids@) + + verify::mul_bytes(ids@.len(), vstd::layout::size_of::())); + } + TransitionNode::Union(slot) + } + TransitionView::Intersect(ids) => { + let slot = arena(self.transition_ids.intern(ids))?; + proof! { verify::lemma_pool_bytes_push(before.transition_ids@, ids@); } + proof! { + assert(verify::pool_bytes(self.transition_ids@) <= verify::pool_bytes(before.transition_ids@) + + verify::mul_bytes(ids@.len(), vstd::layout::size_of::())); + } + TransitionNode::Intersect(slot) + } + TransitionView::Not(id) => TransitionNode::Not(id), + TransitionView::Append { transition, suffix } => { + let slot = arena(self.regex_ids.intern(suffix))?; + proof! { verify::lemma_pool_bytes_push(before.regex_ids@, suffix@); } + proof! { + assert(verify::pool_bytes(self.regex_ids@) <= verify::pool_bytes(before.regex_ids@) + + verify::mul_bytes(suffix@.len(), vstd::layout::size_of::())); + } + TransitionNode::Append { + transition, + suffix: slot, + } + } + }; + proof! { + assert(self.test_ids@.take(before.test_ids@.len() as int) =~= before.test_ids@); + assert(self.regex_ids@.take(before.regex_ids@.len() as int) =~= before.regex_ids@); + assert(self.transition_ids@.take(before.transition_ids@.len() as int) =~= before.transition_ids@); + verify::pool_extension(&before, &*self); + assert(verify::tables_space_wf(self)); + assert(verify::arena_transition_node(node, self.transition_ids@, self.regex_ids@) == view@); + verify::lemma_transition_contains(self, node); + assert(!self.transitions@.contains(node)); + } + let _handle = match self.transitions.try_mk(node) { + Ok(handle) => handle, + Err(_) => return Err(HistoryError::ArenaExhausted), + }; + proof! { + assert(verify::tables_graph(self).transitions =~= verify::tables_graph(&before).transitions.push(view@)); + assert(_handle.spec_uid() == id@ as nat); + assert forall|i: int| 0 <= i < self.transitions@.len() implies + verify::arena_transition_wf(self, self.transitions@[i]) by { + if i < before.transitions@.len() { assert(self.transitions@[i] == before.transitions@[i]); } + } + verify::lemma_transitions_weight_push(verify::tables_graph(&before).transitions, view@); + verify::lemma_mul_bytes_succ(before.transitions@.len(), vstd::layout::size_of::()); + assert(verify::tables_wf(self)); + assert(verify::arena_live(self) <= verify::arena_live(&before) + verify::transition_weight(view@)); + } + Ok(id) + } + #[verus_spec(requires verify::tables_wf(&self))] + fn release(self) { + self.tests.free(); + #[cfg(test)] + ArenaLifetimeCounts::freed(&self.lifetime_counts); + self.test_ids.free(); + #[cfg(test)] + ArenaLifetimeCounts::freed(&self.lifetime_counts); + self.regexes.free(); + #[cfg(test)] + ArenaLifetimeCounts::freed(&self.lifetime_counts); + self.regex_ids.free(); + #[cfg(test)] + ArenaLifetimeCounts::freed(&self.lifetime_counts); + self.transitions.free(); + #[cfg(test)] + ArenaLifetimeCounts::freed(&self.lifetime_counts); + self.transition_ids.free(); + #[cfg(test)] + ArenaLifetimeCounts::freed(&self.lifetime_counts); + } +} +#[verus_verify] +impl ArenaStorage { + #[verus_spec(result => ensures result matches Ok(s) ==> verify::empty_tables(s.graph()) + && s.has_tables() && s.capacity() == capacity && s.slack() == 0, + result matches Err(error) ==> error is Invariant || error is AllocationFailed, + verify::construction_layout(capacity) ==> no_invariant_failure(result))] + pub(crate) fn with_capacity(capacity: usize) -> KernelResult { + Ok(Self { + tables: Some(ArenaTables::with_capacity(capacity)?), + }) + } + #[allow( + clippy::option_if_let_else, + reason = "Explicit matches preserve the Verus proof structure" + )] + #[verus_spec(result => ensures + result.0 == self.graph().tests.len(), + result.1 == self.graph().regexes.len(), + result.2 == self.graph().transitions.len())] + pub(crate) fn lengths(&self) -> (usize, usize, usize) { + proof! { use_type_invariant(&*self); } + match self.tables.as_ref() { + Some(tables) => ( + tables.tests.len(), + tables.regexes.len(), + tables.transitions.len(), + ), + None => (0, 0, 0), + } + } +} +#[verus_verify] +impl ArenaStorage { + #[verus_spec(r => + ensures r matches Ok(v) ==> id@ < self.graph().tests.len() + && v@ == self.graph().tests[id@ as int], + r matches Err(error) ==> error is Invariant, + self.tables is Some && id@ < self.graph().tests.len() ==> r is Ok + )] + fn test(&self, id: TestId) -> KernelResult> { + proof! { use_type_invariant(&*self); } + let tables = present(self.tables.as_ref(), "arena released")?; + proof! { TestId::lemma_view(id); } + tables.test(id.index()?) + } + #[verus_spec(r => + ensures r matches Ok(Some(id)) ==> id@ < self.graph().tests.len() + && self.graph().tests[id@ as int] == view@, + r matches Ok(None) ==> !self.graph().tests.contains(view@), + r matches Err(error) ==> error is Invariant || error is GraphIndex, + self.tables is Some ==> no_invariant_failure(r) + )] + fn find_test(&self, view: TestView<'_>) -> KernelResult> { + proof! { use_type_invariant(&*self); } + present(self.tables.as_ref(), "arena released")?.find_test(view) + } + #[verus_spec(r => + ensures r matches Ok(Some(id)) ==> id@ < self.graph().regexes.len() + && self.graph().regexes[id@ as int] == view@, + r matches Ok(None) ==> !self.graph().regexes.contains(view@), + r matches Err(error) ==> error is Invariant || error is GraphIndex, + self.tables is Some ==> no_invariant_failure(r) + )] + fn find_regex(&self, view: RegexView<'_>) -> KernelResult> { + proof! { use_type_invariant(&*self); } + present(self.tables.as_ref(), "arena released")?.find_regex(view) + } + #[verus_spec(r => + ensures r matches Ok(Some(id)) ==> id@ < self.graph().transitions.len() + && self.graph().transitions[id@ as int] == view@, + r matches Ok(None) ==> !self.graph().transitions.contains(view@), + r matches Err(error) ==> error is Invariant || error is GraphIndex, + self.tables is Some ==> no_invariant_failure(r) + )] + fn find_transition(&self, view: TransitionView<'_>) -> KernelResult> { + proof! { use_type_invariant(&*self); } + present(self.tables.as_ref(), "arena released")?.find_transition(view) + } + #[verus_spec(r => + requires !old(self).graph().tests.contains(view@), + ensures + (final(self).tables is Some) == (old(self).tables is Some), + old(self).tables is Some ==> no_invariant_failure(r), + final(self).graph().constants == old(self).graph().constants, + final(self).graph().regexes == old(self).graph().regexes, + final(self).graph().transitions == old(self).graph().transitions, + r is Err ==> final(self).graph() == old(self).graph(), + r matches Ok(id) ==> id@ == old(self).graph().tests.len() + && final(self).graph().tests == old(self).graph().tests.push(view@), + r matches Err(error) ==> error is Invariant || error is GraphBudget || error is GraphIndex + || error is ArenaExhausted || error is AllocationFailed, + final(self).capacity() == old(self).capacity(), + r is Ok ==> final(self).slack() >= old(self).slack(), + r matches Err(error) ==> error is ArenaExhausted ==> + verify::graph_weight(old(self).graph()) + verify::test_weight(view@) - old(self).slack() + > old(self).capacity() + )] + fn push_test(&mut self, view: TestView<'_>) -> KernelResult { + proof! { use_type_invariant(&*self); } + // Restore table ownership before propagating either success or failure. + let Some(mut tables) = self.tables.take() else { + return Err(HistoryError::invariant("arena released")); + }; + let result = tables.push_test(view); + self.tables = Some(tables); + result + } + #[verus_spec(r => + ensures r matches Ok(v) ==> id@ < self.graph().regexes.len() + && v@ == self.graph().regexes[id@ as int], + r matches Err(error) ==> error is Invariant, + self.tables is Some && id@ < self.graph().regexes.len() ==> r is Ok + )] + fn regex(&self, id: RegexId) -> KernelResult> { + proof! { use_type_invariant(&*self); } + let tables = present(self.tables.as_ref(), "arena released")?; + proof! { RegexId::lemma_view(id); } + tables.regex(id.index()?) + } + #[verus_spec(r => + requires !old(self).graph().regexes.contains(view@), + ensures + (final(self).tables is Some) == (old(self).tables is Some), + old(self).tables is Some ==> no_invariant_failure(r), + final(self).graph().constants == old(self).graph().constants, + final(self).graph().tests == old(self).graph().tests, + final(self).graph().transitions == old(self).graph().transitions, + r is Err ==> final(self).graph() == old(self).graph(), + r matches Ok(id) ==> id@ == old(self).graph().regexes.len() + && final(self).graph().regexes == old(self).graph().regexes.push(view@), + r matches Err(error) ==> error is Invariant || error is GraphBudget || error is GraphIndex + || error is ArenaExhausted || error is AllocationFailed, + final(self).capacity() == old(self).capacity(), + r is Ok ==> final(self).slack() >= old(self).slack(), + r matches Err(error) ==> error is ArenaExhausted ==> + verify::graph_weight(old(self).graph()) + verify::regex_weight(view@) - old(self).slack() + > old(self).capacity() + )] + fn push_regex(&mut self, view: RegexView<'_>) -> KernelResult { + proof! { use_type_invariant(&*self); } + let Some(mut tables) = self.tables.take() else { + return Err(HistoryError::invariant("arena released")); + }; + let result = tables.push_regex(view); + self.tables = Some(tables); + result + } + #[verus_spec(r => + ensures r matches Ok(v) ==> id@ < self.graph().transitions.len() + && v@ == self.graph().transitions[id@ as int], + r matches Err(error) ==> error is Invariant, + self.tables is Some && id@ < self.graph().transitions.len() ==> r is Ok + )] + fn transition(&self, id: TransitionId) -> KernelResult> { + proof! { use_type_invariant(&*self); } + let tables = present(self.tables.as_ref(), "arena released")?; + proof! { TransitionId::lemma_view(id); } + tables.transition(id.index()?) + } + #[verus_spec(r => + requires !old(self).graph().transitions.contains(view@), + ensures + (final(self).tables is Some) == (old(self).tables is Some), + old(self).tables is Some ==> no_invariant_failure(r), + final(self).graph().constants == old(self).graph().constants, + final(self).graph().tests == old(self).graph().tests, + final(self).graph().regexes == old(self).graph().regexes, + r is Err ==> final(self).graph() == old(self).graph(), + r matches Ok(id) ==> id@ == old(self).graph().transitions.len() + && final(self).graph().transitions == old(self).graph().transitions.push(view@), + r matches Err(error) ==> error is Invariant || error is GraphBudget || error is GraphIndex + || error is ArenaExhausted || error is AllocationFailed, + final(self).capacity() == old(self).capacity(), + r is Ok ==> final(self).slack() >= old(self).slack(), + r matches Err(error) ==> error is ArenaExhausted ==> + verify::graph_weight(old(self).graph()) + verify::transition_weight(view@) - old(self).slack() + > old(self).capacity() + )] + fn push_transition(&mut self, view: TransitionView<'_>) -> KernelResult { + proof! { use_type_invariant(&*self); } + let Some(mut tables) = self.tables.take() else { + return Err(HistoryError::invariant("arena released")); + }; + let result = tables.push_transition(view); + self.tables = Some(tables); + result + } +} + +#[verus_verify(external)] +impl core::fmt::Debug for ArenaStorage { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let (tests, regexes, transitions) = self.lengths(); + f.debug_struct("ArenaStorage") + .field("tests", &tests) + .field("regexes", ®exes) + .field("transitions", &transitions) + .finish() + } +} + +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Debug)] +pub struct CanonicalStore { + pub(crate) storage: ArenaStorage, + // Verus needs every field crate-visible for direct accounting contracts. + pub(crate) constants: Constants, + pub(crate) bytes: usize, + /// Bytes the graph may be charged; each arena holds this many. + pub(crate) budget: usize, +} +#[verus_verify] +impl CanonicalStore { + #[cfg(verus_keep_ghost)] + verus! { + pub closed spec fn charged(&self) -> nat { self.bytes as nat } + pub closed spec fn budget(&self) -> nat { self.budget as nat } + + /// Charged native node payloads leave representable room for cache and truth indices. + #[cfg(target_pointer_width = "64")] + pub proof fn lemma_node_count_bounds(&self) + requires self.valid_store(), + ensures self.graph().tests.len() + 64 <= usize::MAX, + self.graph().regexes.len() < usize::MAX, + self.graph().transitions.len() < usize::MAX, + { + verify::lemma_tests_weight_count(self.graph().tests); + verify::lemma_regexes_weight_count(self.graph().regexes); + verify::lemma_transitions_weight_count(self.graph().transitions); + } + + /// Every native constant payload is a `u64`, including after graph extension. + pub proof fn lemma_constant_bounds(&self) + ensures forall|i: int| #![trigger self.graph().tests[i]] + 0 <= i < self.graph().tests.len() ==> match self.graph().tests[i] { + model::TestNode::Atom(model::Primitive::Eq(_, model::GTerm::Constant(v)), _) => v <= u64::MAX, + _ => true, + }, + { + match self.storage.tables { + Some(t) => { + assert forall|i: int| #![trigger self.graph().tests[i]] + 0 <= i < self.graph().tests.len() implies + match self.graph().tests[i] { + model::TestNode::Atom(model::Primitive::Eq(_, model::GTerm::Constant(v)), _) => v <= u64::MAX, + _ => true, + } by { + match t.tests@[i] { + TestNode::Atom { primitive, .. } => { + match primitive { + Primitive::Eq { term: Term::Constant(value), .. } => {}, + _ => {}, + } + }, + _ => {}, + } + } + }, + None => {}, + } + } + } + + /// Creates the canonical graph with the runtime's budget, [`MAX_GRAPH_BYTES`], and its + /// algebraic constants. Live production operations report graph/resource failures, never + /// internal/owner errors. + #[verus_spec(result => ensures match result { + Ok(store) => model::graph_wf(store.graph()) && store.valid_store(), + Err(error) => error is GraphBudget || error is GraphIndex || error is ArenaExhausted || error is AllocationFailed, + }, no_invariant_failure(result), + result matches Err(error) ==> junco_core::spec::semantics::resource_error(error))] + pub fn new() -> KernelResult { + proof! { + #[cfg(target_pointer_width = "64")] + verify::lemma_production_layout(); + } + Self::with_budget(ARENA_CAPACITY) + } + + /// Creates a canonical graph that may be charged `budget` bytes, and its algebraic + /// constants. Each of its six arenas holds `budget` bytes, so the charge rather than arena + /// space bounds the graph. `budget` must be a multiple of every node alignment, as any + /// multiple of 16 is; otherwise the arena layout check fails with an internal error. + #[verus_spec(result => ensures match result { + Ok(store) => model::graph_wf(store.graph()) && store.valid_store(), + Err(error) => error is GraphBudget || error is GraphIndex || error is ArenaExhausted || error is AllocationFailed + || error is Invariant, + }, verify::construction_layout(budget) ==> no_invariant_failure(result), + verify::construction_layout(budget) ==> + (result matches Err(error) ==> junco_core::spec::semantics::resource_error(error)))] + pub fn with_budget(budget: usize) -> KernelResult { + Self::from_storage(ArenaStorage::with_capacity(budget)?, budget) + } + + #[verus_spec(result => + requires storage.tables is Some, verify::empty_tables(storage.graph()), + ensures match result { + Ok(store) => model::graph_wf(store.graph()) && store.valid_store(), + Err(error) => error is GraphBudget || error is GraphIndex || error is ArenaExhausted || error is AllocationFailed, + }, + result matches Err(error) ==> junco_core::spec::semantics::resource_error(error), + )] + fn from_storage(storage: ArenaStorage, budget: usize) -> KernelResult { + proof_decl! { let ghost initial_graph = storage.graph(); } + let mut store = Self { + storage, + bytes: 0, + budget, + constants: Constants { + test_true: TestId::ZERO, + test_false: TestId::ZERO, + empty: RegexId::ZERO, + all: RegexId::ZERO, + epsilon: RegexId::ZERO, + transition_empty: TransitionId::ZERO, + transition_all: TransitionId::ZERO, + transition_epsilon: TransitionId::ZERO, + }, + }; + proof! { assert(store.valid_store()); } + proof! { verify::lemma_tables_wf_same_tables(initial_graph, store.graph()); } + store.intern_constants()?; + Ok(store) + } + + verus! { + #[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] + #[cfg_attr(verus_keep_ghost, verifier::rlimit(30))] + #[verus_spec(result => + requires old(self).valid_store(), verify::empty_tables(old(self).graph()), + model::tables_wf(old(self).graph()), + ensures final(self).valid_store(), match result { + Ok(()) => model::graph_wf(final(self).graph()), + Err(error) => error is GraphBudget || error is GraphIndex || error is ArenaExhausted || error is AllocationFailed, + }, + result matches Err(error) ==> junco_core::spec::semantics::resource_error(error), + )] + fn intern_constants(&mut self) -> KernelResult<()> { + // Each interner preserves these predicates through its checked contract. + // Unfold their quantified/recursive bodies only at the final constant update. + hide(CanonicalStore::valid_store); + hide(model::unique_nodes); + hide(model::tables_wf); + hide(verify::graph_weight); + let test_true = self.intern_test(TestView::True)?; + let test_false = self.intern_test(TestView::False)?; + let empty = self.intern_regex(RegexKindView::Empty, false)?; + let all = self.intern_regex(RegexKindView::All, true)?; + let epsilon = self.intern_regex(RegexKindView::Epsilon, true)?; + let transition_empty = self.intern_transition(TransitionView::Const(empty))?; + let transition_all = self.intern_transition(TransitionView::Const(all))?; + let transition_epsilon = self.intern_transition(TransitionView::Const(epsilon))?; + proof_decl! { let ghost built_graph = self.graph(); } + self.constants = Constants { + test_true, + test_false, + empty, + all, + epsilon, + transition_empty, + transition_all, + transition_epsilon, + }; + proof! { + verify::lemma_tables_wf_same_tables(built_graph, self.graph()); + assert(self.graph().tests == built_graph.tests); + assert(self.graph().regexes == built_graph.regexes); + assert(self.graph().transitions == built_graph.transitions); + assert(verify::graph_weight(self.graph()) == verify::graph_weight(built_graph)) by { + reveal(verify::graph_weight); + } + assert(self.valid_store()) by { + reveal(CanonicalStore::valid_store); + reveal(model::unique_nodes); + } + assert(model::tables_wf(self.graph())); + assert(model::constants_wf(self.graph())); + assert(model::unique_nodes(self.graph())) by { + reveal(CanonicalStore::valid_store); + } + model::lemma_graph_wf_intro(self.graph()); + } + Ok(()) + } + } + + #[verus_spec(result => ensures match result { + Ok(total) => total as int == self.charged() as int + bytes as int + && total as int <= self.budget() as int, + Err(error) => error matches HistoryError::GraphBudget { limit } && limit as nat == self.budget() + && self.charged() + bytes > self.budget(), + }, result matches Err(error) ==> junco_core::spec::semantics::resource_error(error))] + pub fn projected(&self, bytes: usize) -> KernelResult { + let total = self + .bytes + .checked_add(bytes) + .ok_or(HistoryError::GraphBudget { limit: self.budget })?; + if total > self.budget { + return Err(HistoryError::GraphBudget { limit: self.budget }); + } + Ok(total) + } + #[verus_spec(result => ensures final(self).graph() == old(self).graph(), + (final(self).bytes as nat) >= (old(self).bytes as nat), + old(self).valid_store() ==> final(self).valid_store(), + result matches Err(error) ==> error matches HistoryError::GraphBudget { limit } && limit as nat == old(self).budget() + && old(self).charged() + bytes > old(self).budget())] + pub(crate) fn charge(&mut self, bytes: usize) -> KernelResult<()> { + self.bytes = self.projected(bytes)?; + Ok(()) + } + /// Raises the byte charge to a value previously obtained from `projected` on this store. + /// The charge never decreases, so `graph_weight(graph) <= bytes` is preserved + /// even if an intervening checkpoint or intern already charged more. + #[allow( + clippy::missing_const_for_fn, + reason = "Keep the existing mutable operation and its Verus contract unchanged" + )] + #[verus_spec( + ensures final(self).graph() == old(self).graph(), + old(self).valid_store() ==> final(self).valid_store(), + final(self).charged() >= old(self).charged(), + final(self).charged() >= bytes as nat, + )] + pub fn set_charged_bytes(&mut self, bytes: usize) { + if bytes > self.bytes { + self.bytes = bytes; + } + } + + #[verus_spec(result => ensures result@ == self.graph().constants)] + pub const fn constants(&self) -> Constants { + self.constants + } + #[verus_spec(result => + requires old(self).valid_store(), model::test_node_wf(old(self).graph(), node@), + ensures + final(self).valid_store(), + model::graph_extends(old(self).graph(), final(self).graph()), + model::tables_wf(old(self).graph()) ==> model::tables_wf(final(self).graph()), + model::graph_wf(old(self).graph()) ==> model::graph_wf(final(self).graph()), + match result { + Ok(id) => id@ < final(self).graph().tests.len() + && final(self).graph().tests[id@ as int] == node@, + Err(_) => final(self).graph() == old(self).graph() + && (final(self).bytes as nat) == (old(self).bytes as nat), + }, + result matches Err(error) ==> error is GraphBudget || error is GraphIndex + || error is ArenaExhausted || error is AllocationFailed, + result matches Err(error) ==> junco_core::spec::semantics::resource_error(error), + final(self).storage.capacity() == old(self).storage.capacity(), + result is Ok ==> final(self).storage.slack() >= old(self).storage.slack(), + result matches Err(error) ==> error is ArenaExhausted ==> + old(self).storage.slack() < old(self).budget as int - old(self).storage.capacity(), + )] + pub(crate) fn intern_test(&mut self, node: TestView<'_>) -> KernelResult { + proof_decl! { let ghost original = self.graph(); } + if let Some(id) = self.storage.find_test(node)? { + return Ok(id); + } + let len = match node { + TestView::And(ids) | TestView::Or(ids) => ids.len(), + _ => 0, + }; + let bytes = size_of::() + .checked_add(sequence_bytes::(len)?) + .ok_or(HistoryError::GraphIndex)?; + let projected = self.projected(bytes)?; + proof! { + assert(model::unique_nodes(original)); + assert(verify::graph_weight(self.storage.graph()) == verify::graph_weight(original)); + assert(bytes as int == verify::test_weight(node@)); + assert(verify::graph_weight(original) + verify::test_weight(node@) <= self.budget as int); + } + // Publish the charge only after storage succeeds; failed pushes leave accounting unchanged. + let id = self.storage.push_test(node)?; + self.bytes = projected; + proof! { + assert(self.graph() == model::append_test(original, node@)); + assert(model::unique_nodes(self.graph())); + verify::lemma_tests_weight_push(original.tests, node@); + assert(verify::graph_weight(self.graph()) == verify::graph_weight(original) + verify::test_weight(node@)); + assert(self.valid_store()); + if model::graph_wf(original) { model::lemma_graph_wf_elim(original); } + if model::tables_wf(original) { model::lemma_tables_wf_append_test(original, node@); } + } + Ok(id) + } + #[verus_spec(result => + requires old(self).valid_store(), model::regex_node_wf(old(self).graph(), model::RegexNode { kind: kind@, nullable }), + ensures + final(self).valid_store(), + model::graph_extends(old(self).graph(), final(self).graph()), + model::tables_wf(old(self).graph()) ==> model::tables_wf(final(self).graph()), + model::graph_wf(old(self).graph()) ==> model::graph_wf(final(self).graph()), + match result { + Ok(id) => id@ < final(self).graph().regexes.len() + && final(self).graph().regexes[id@ as int] == (model::RegexNode { kind: kind@, nullable }), + Err(_) => final(self).graph() == old(self).graph() + && (final(self).bytes as nat) == (old(self).bytes as nat), + }, + result matches Err(error) ==> error is GraphBudget || error is GraphIndex + || error is ArenaExhausted || error is AllocationFailed, + result matches Err(error) ==> junco_core::spec::semantics::resource_error(error), + final(self).storage.capacity() == old(self).storage.capacity(), + result is Ok ==> final(self).storage.slack() >= old(self).storage.slack(), + result matches Err(error) ==> error is ArenaExhausted ==> + old(self).storage.slack() < old(self).budget as int - old(self).storage.capacity(), + )] + pub(crate) fn intern_regex( + &mut self, + kind: RegexKindView<'_>, + nullable: bool, + ) -> KernelResult { + proof_decl! { let ghost original = self.graph(); } + let node = RegexView { kind, nullable }; + if let Some(id) = self.storage.find_regex(node)? { + return Ok(id); + } + let len = match kind { + RegexKindView::Union(ids) + | RegexKindView::Concat(ids) + | RegexKindView::Intersect(ids) => ids.len(), + _ => 0, + }; + let bytes = size_of::() + .checked_add(sequence_bytes::(len)?) + .ok_or(HistoryError::GraphIndex)?; + let projected = self.projected(bytes)?; + proof! { + assert(model::unique_nodes(original)); + assert(verify::graph_weight(self.storage.graph()) == verify::graph_weight(original)); + assert(bytes as int == verify::regex_weight(node@)); + assert(verify::graph_weight(original) + verify::regex_weight(node@) <= self.budget as int); + } + let id = self.storage.push_regex(node)?; + self.bytes = projected; + proof! { + assert(self.graph() == model::append_regex(original, node@)); + assert(model::unique_nodes(self.graph())); + verify::lemma_regexes_weight_push(original.regexes, node@); + assert(verify::graph_weight(self.graph()) == verify::graph_weight(original) + verify::regex_weight(node@)); + assert(self.valid_store()); + if model::graph_wf(original) { model::lemma_graph_wf_elim(original); } + if model::tables_wf(original) { model::lemma_tables_wf_append_regex(original, node@); } + } + Ok(id) + } + #[verus_spec(result => + requires old(self).valid_store(), model::transition_node_wf(old(self).graph(), node@), + ensures + final(self).valid_store(), + model::graph_extends(old(self).graph(), final(self).graph()), + model::tables_wf(old(self).graph()) ==> model::tables_wf(final(self).graph()), + model::graph_wf(old(self).graph()) ==> model::graph_wf(final(self).graph()), + match result { + Ok(id) => id@ < final(self).graph().transitions.len() + && final(self).graph().transitions[id@ as int] == node@, + Err(_) => final(self).graph() == old(self).graph() + && (final(self).bytes as nat) == (old(self).bytes as nat), + }, + result matches Err(error) ==> error is GraphBudget || error is GraphIndex + || error is ArenaExhausted || error is AllocationFailed, + result matches Err(error) ==> junco_core::spec::semantics::resource_error(error), + final(self).storage.capacity() == old(self).storage.capacity(), + result is Ok ==> final(self).storage.slack() >= old(self).storage.slack(), + result matches Err(error) ==> error is ArenaExhausted ==> + old(self).storage.slack() < old(self).budget as int - old(self).storage.capacity(), + )] + pub(crate) fn intern_transition( + &mut self, + node: TransitionView<'_>, + ) -> KernelResult { + proof_decl! { let ghost original = self.graph(); } + if let Some(id) = self.storage.find_transition(node)? { + return Ok(id); + } + let children = match node { + TransitionView::Union(ids) | TransitionView::Intersect(ids) => { + sequence_bytes::(ids.len())? + } + TransitionView::Append { suffix, .. } => sequence_bytes::(suffix.len())?, + _ => 0, + }; + let bytes = size_of::() + .checked_add(children) + .ok_or(HistoryError::GraphIndex)?; + let projected = self.projected(bytes)?; + proof! { + assert(model::unique_nodes(original)); + assert(verify::graph_weight(self.storage.graph()) == verify::graph_weight(original)); + assert(bytes as int == verify::transition_weight(node@)); + assert(verify::graph_weight(original) + verify::transition_weight(node@) <= self.budget as int); + } + let id = self.storage.push_transition(node)?; + self.bytes = projected; + proof! { + assert(self.graph() == model::append_transition(original, node@)); + assert(model::unique_nodes(self.graph())); + verify::lemma_transitions_weight_push(original.transitions, node@); + assert(verify::graph_weight(self.graph()) == verify::graph_weight(original) + verify::transition_weight(node@)); + assert(self.valid_store()); + if model::graph_wf(original) { model::lemma_graph_wf_elim(original); } + if model::tables_wf(original) { model::lemma_tables_wf_append_transition(original, node@); } + } + Ok(id) + } +} + +#[cfg(any(test, feature = "test-util"))] +impl CanonicalStore { + pub fn replace_graph_byte_pressure(&mut self, bytes: usize) -> usize { + core::mem::replace(&mut self.bytes, bytes) + } + + pub fn charged_bytes(&self) -> usize { + self.bytes + } +} + +#[cfg(any(test, feature = "test-util"))] +impl CanonicalStore { + pub fn table_counts(&self) -> Option<(usize, usize)> { + self.storage + .tables + .as_ref() + .map(|tables| (tables.test_ids.slices.len(), tables.tests.len())) + } +} +#[verus_verify] +pub struct RuntimeKernel<'a, L: Limits> { + pub store: &'a mut CanonicalStore, + pub limits: &'a mut L, + pub world: &'a mut ObservationWorld, +} +#[verus_verify] +impl KernelStore for RuntimeKernel<'_, L> { + #[verus_spec(result => ensures result matches Err(error) ==> error is Limit)] + fn checkpoint(&mut self) -> KernelResult<()> { + self.limits.checkpoint()?; + Ok(()) + } + #[verus_spec(result => ensures result matches Err(error) ==> error is Limit || error is GraphBudget || error is GraphIndex)] + fn charge_aux(&mut self, bytes: usize) -> KernelResult<()> { + self.checkpoint()?; + self.store.charge(bytes) + } + #[verus_spec(result => ensures result matches Err(error) ==> error is AllocationFailed)] + fn reserve_derivatives( + &mut self, + values: &mut Vec>, + additional: usize, + ) -> KernelResult<()> { + allocation(self.world.try_reserve_vec(values, additional)) + } + #[verus_spec(result => ensures result matches Err(error) ==> error is AllocationFailed)] + fn reserve_atoms(&mut self, values: &mut Vec, additional: usize) -> KernelResult<()> { + allocation(self.world.try_reserve_vec(values, additional)) + } + fn constants(&self) -> Constants { + self.store.constants() + } + #[verus_spec(result => ensures result matches Err(error) ==> error is Invariant)] + fn test(&self, id: TestId) -> KernelResult> { + self.store.storage.test(id) + } + #[verus_spec(result => ensures result matches Err(error) ==> error is Invariant)] + fn regex(&self, id: RegexId) -> KernelResult> { + self.store.storage.regex(id) + } + #[verus_spec(result => ensures result matches Err(error) ==> error is Invariant)] + fn transition(&self, id: TransitionId) -> KernelResult> { + self.store.storage.transition(id) + } + #[verus_spec(result => ensures result matches Err(error) ==> error is Limit + || error is GraphBudget || error is GraphIndex || error is ArenaExhausted || error is AllocationFailed)] + fn intern_test(&mut self, node: TestView<'_>) -> KernelResult { + self.checkpoint()?; + let id = self.store.intern_test(node)?; + self.checkpoint()?; + Ok(id) + } + #[verus_spec(result => ensures result matches Err(error) ==> error is Limit + || error is GraphBudget || error is GraphIndex || error is ArenaExhausted || error is AllocationFailed)] + fn intern_regex(&mut self, kind: RegexKindView<'_>, nullable: bool) -> KernelResult { + self.checkpoint()?; + let id = self.store.intern_regex(kind, nullable)?; + self.checkpoint()?; + Ok(id) + } + #[verus_spec(result => ensures result matches Err(error) ==> error is Limit + || error is GraphBudget || error is GraphIndex || error is ArenaExhausted || error is AllocationFailed)] + fn intern_transition(&mut self, node: TransitionView<'_>) -> KernelResult { + self.checkpoint()?; + let id = self.store.intern_transition(node)?; + self.checkpoint()?; + Ok(id) + } +} + +#[cfg(test)] +mod storage_tests { + #![allow(clippy::panic_in_result_fn)] + use super::*; + + #[test] + fn atom_key_equality_preserves_full_width_and_domains() { + use history_syntax::syntax::Component; + + let fixtures = [ + (Component(0), Term::Constant(0), true), + (Component(0), Term::Constant(1_u64 << 32), true), + (Component(0), Term::Constant(u64::MAX), true), + (Component(1), Term::Constant(0), true), + (Component(2), Term::Constant(0), true), + (Component(0), Term::Variable(Component(0)), true), + (Component(0), Term::Variable(Component(1)), true), + (Component(0), Term::Variable(Component(2)), true), + (Component(0), Term::Constant(0), false), + ] + .map(|(field, term, positive)| TestNode::Atom { + primitive: Primitive::Eq { field, term }, + positive, + }); + for (i, left) in fixtures.iter().enumerate() { + for (j, right) in fixtures.iter().enumerate() { + assert_eq!(hashconsius::HashKey::key_eq(left, right), i == j); + } + } + } + + fn tracked_store( + counts: &alloc::sync::Arc, + ) -> KernelResult { + let mut storage = ArenaStorage::with_capacity(512)?; + storage.track_lifetime(alloc::sync::Arc::clone(counts))?; + CanonicalStore::from_storage(storage, MAX_GRAPH_BYTES) + } + + #[test] + fn pinned_graph_survives_replacement_and_frees_only_at_last_arc() -> KernelResult<()> { + use alloc::sync::Arc; + + let counts = Arc::new(ArenaLifetimeCounts::default()); + let mut current = Arc::new(tracked_store(&counts)?); + let pinned = Arc::clone(¤t); + assert_eq!(counts.snapshot(), (6, 0)); + + for generation in 2_usize..=33 { + current = Arc::new(tracked_store(&counts)?); + assert_eq!( + counts.snapshot(), + ( + generation.saturating_mul(6), + generation.saturating_sub(2).saturating_mul(6) + ) + ); + } + drop(current); + assert_eq!(counts.snapshot(), (198, 192)); + assert!(pinned.storage.regex(pinned.constants().all)?.nullable); + drop(pinned); + assert_eq!(counts.snapshot(), (198, 198)); + Ok(()) + } + + #[test] + fn failed_store_construction_frees_owned_arenas() -> KernelResult<()> { + use alloc::sync::Arc; + + let counts = Arc::new(ArenaLifetimeCounts::default()); + let mut storage = ArenaStorage::with_capacity(CHUNK_ALIGN)?; + storage.track_lifetime(Arc::clone(&counts))?; + assert!(matches!( + CanonicalStore::from_storage(storage, MAX_GRAPH_BYTES), + Err(HistoryError::ArenaExhausted) + )); + assert_eq!(counts.snapshot(), (6, 6)); + Ok(()) + } + + #[test] + fn budget_equality_is_allowed_and_failed_growth_is_transactional() -> KernelResult<()> { + let mut store = CanonicalStore::new()?; + let payload = size_of::(); + store.bytes = MAX_GRAPH_BYTES + .checked_sub(payload) + .ok_or_else(|| HistoryError::invariant("invalid test budget"))?; + let node = TestView::Atom { + primitive: Primitive::Eq { + field: history_syntax::syntax::Component(0), + term: Term::Constant(0), + }, + positive: true, + }; + let id = store.intern_test(node)?; + assert_eq!(store.bytes, MAX_GRAPH_BYTES); + assert_eq!(store.intern_test(node)?, id); + let rows = store.storage.lengths(); + let failed = store.intern_test(TestView::Atom { + primitive: Primitive::Eq { + field: history_syntax::syntax::Component(0), + term: Term::Constant(1), + }, + positive: true, + }); + assert!(matches!( + failed, + Err(HistoryError::GraphBudget { + limit: MAX_GRAPH_BYTES + }) + )); + assert_eq!(store.bytes, MAX_GRAPH_BYTES); + assert_eq!(store.storage.lengths(), rows); + Ok(()) + } + + #[test] + fn a_store_enforces_its_own_budget() -> KernelResult<()> { + let atom = |constant| TestView::Atom { + primitive: Primitive::Eq { + field: history_syntax::syntax::Component(0), + term: Term::Constant(constant), + }, + positive: true, + }; + let budget = 2 * MAX_GRAPH_BYTES; + let mut store = CanonicalStore::with_budget(budget)?; + // Past the runtime's budget, within this store's. + store.bytes = MAX_GRAPH_BYTES; + store.intern_test(atom(0))?; + store.bytes = budget; + assert!(matches!( + store.intern_test(atom(1)), + Err(HistoryError::GraphBudget { limit }) if limit == budget + )); + assert!(CanonicalStore::with_budget(MAX_GRAPH_BYTES + 1).is_err()); + Ok(()) + } + + #[test] + fn arena_allocation_failure_does_not_publish_or_charge() -> KernelResult<()> { + let mut store = + CanonicalStore::from_storage(ArenaStorage::with_capacity(512)?, MAX_GRAPH_BYTES)?; + for path in 0_u32..u32::MAX { + let before = (store.bytes, store.storage.lengths()); + match store.intern_test(TestView::Atom { + primitive: Primitive::Eq { + field: history_syntax::syntax::Component(0), + term: Term::Constant(u64::from(path)), + }, + positive: true, + }) { + Ok(_) => {} + Err(HistoryError::ArenaExhausted) => { + assert_eq!((store.bytes, store.storage.lengths()), before); + let constant = store.intern_test(TestView::True); + let expected = store.constants().test_true; + assert_eq!(constant?, expected); + return Ok(()); + } + Err(error) => return Err(error), + } + } + Err(HistoryError::invariant("512-byte arena did not exhaust")) + } + + #[test] + fn arena_round_trips_child_slices() -> KernelResult<()> { + let mut store = CanonicalStore::new()?; + let outcome = (|| -> KernelResult<_> { + let a = store.intern_test(TestView::Atom { + primitive: Primitive::Eq { + field: history_syntax::syntax::Component(0), + term: Term::Constant(1), + }, + positive: true, + })?; + let b = store.intern_test(TestView::Atom { + primitive: Primitive::Eq { + field: history_syntax::syntax::Component(0), + term: Term::Constant(2), + }, + positive: true, + })?; + let and = store.intern_test(TestView::And(&[a, b]))?; + let r = store.intern_regex(RegexKindView::Test(a), false)?; + let epsilon = store.constants().epsilon; + let union = store.intern_regex(RegexKindView::Union(&[r, epsilon]), true)?; + let transition_epsilon = store.constants().transition_epsilon; + let append = TransitionView::Append { + transition: transition_epsilon, + suffix: &[r], + }; + let t = store.intern_transition(append)?; + assert_eq!(store.storage.test(and)?, TestView::And(&[a, b])); + assert_eq!( + store.storage.regex(union)?.kind, + RegexKindView::Union(&[r, epsilon]) + ); + assert_eq!(store.storage.transition(t)?, append); + assert_eq!(store.intern_test(TestView::And(&[a, b]))?, and); + assert_eq!( + store.intern_regex(RegexKindView::Union(&[r, epsilon]), true)?, + union + ); + assert_eq!(store.intern_transition(append)?, t); + Ok(()) + })(); + outcome?; + Ok(()) + } +} + +#[cfg(verus_keep_ghost)] +pub mod verify { + use super::*; + use junco_core::kernel::verify as model; + + verus! { + + pub open spec fn storage_constants() -> model::ConstantsModel { + model::ConstantsModel { + test_true: 0, test_false: 0, empty: 0, all: 0, epsilon: 0, + transition_empty: 0, transition_all: 0, transition_epsilon: 0, + } + } + + + pub(super) open spec fn arena_test_node(node: TestNode, pools: Seq>) -> model::TestNode { + match node { + TestNode::True => model::TestNode::True, + TestNode::False => model::TestNode::False, + TestNode::Atom { primitive, positive } => model::TestNode::Atom(primitive@, positive), + TestNode::And(slot) => model::TestNode::And(model::test_ids(pools[slot as int])), + TestNode::Or(slot) => model::TestNode::Or(model::test_ids(pools[slot as int])), + } + } + pub(super) open spec fn arena_regex_node(node: RegexNode, pools: Seq>) -> model::RegexNode { + model::RegexNode { + nullable: node.nullable, + kind: match node.kind { + RegexKind::Empty => model::RegexKindNode::Empty, + RegexKind::All => model::RegexKindNode::All, + RegexKind::Epsilon => model::RegexKindNode::Epsilon, + RegexKind::Test(id) => model::RegexKindNode::Test(id@), + RegexKind::Union(slot) => model::RegexKindNode::Union(model::regex_ids(pools[slot as int])), + RegexKind::Concat(slot) => model::RegexKindNode::Concat(model::regex_ids(pools[slot as int])), + RegexKind::Star(id) => model::RegexKindNode::Star(id@), + RegexKind::Intersect(slot) => model::RegexKindNode::Intersect(model::regex_ids(pools[slot as int])), + RegexKind::Not(id) => model::RegexKindNode::Not(id@), + }, + } + } + pub(super) open spec fn arena_transition_node(node: TransitionNode, ids: Seq>, regex_pools: Seq>) -> model::TransitionNode { + match node { + TransitionNode::Const(id) => model::TransitionNode::Const(id@), + TransitionNode::If { test, then_transition, else_transition } => model::TransitionNode::If(test@, then_transition@, else_transition@), + TransitionNode::Union(slot) => model::TransitionNode::Union(model::transition_ids(ids[slot as int])), + TransitionNode::Intersect(slot) => model::TransitionNode::Intersect(model::transition_ids(ids[slot as int])), + TransitionNode::Not(id) => model::TransitionNode::Not(id@), + TransitionNode::Append { transition, suffix } => model::TransitionNode::Append(transition@, model::regex_ids(regex_pools[suffix as int])), + } + } + pub(super) open spec fn arena_test_wf(t: &ArenaTables, node: TestNode) -> bool { + match node { + TestNode::And(slot) | TestNode::Or(slot) => slot < t.test_ids@.len(), + _ => true, + } + } + pub(super) open spec fn arena_regex_wf(t: &ArenaTables, node: RegexNode) -> bool { + match node.kind { + RegexKind::Union(slot) | RegexKind::Concat(slot) | RegexKind::Intersect(slot) => + slot < t.regex_ids@.len(), + _ => true, + } + } + pub(super) open spec fn arena_transition_wf(t: &ArenaTables, node: TransitionNode) -> bool { + match node { + TransitionNode::Union(slot) | TransitionNode::Intersect(slot) => slot < t.transition_ids@.len(), + TransitionNode::Append { suffix, .. } => suffix < t.regex_ids@.len(), + _ => true, + } + } + proof fn lemma_pool_slot_eq(pool: Seq>, a: usize, b: usize) + requires pool.no_duplicates(), a < pool.len(), b < pool.len(), + ensures (a == b) == (pool[a as int] == pool[b as int]), + {} + pub(super) proof fn lemma_test_id_eq(a: TestId, b: TestId) + ensures (a == b) == (a@ == b@), + { + model::lemma_test_ids_eq(seq![a], seq![b]); + assert(model::test_ids(seq![a]) =~= seq![a@]); + assert(model::test_ids(seq![b]) =~= seq![b@]); + if a@ == b@ { + assert(model::test_ids(seq![a]) == model::test_ids(seq![b])); + assert(seq![a] == seq![b]); + assert(seq![a][0] == seq![b][0]); + assert(a == b); + } + } + pub(super) proof fn lemma_regex_id_eq(a: RegexId, b: RegexId) + ensures (a == b) == (a@ == b@), + { + model::lemma_regex_ids_eq(seq![a], seq![b]); + assert(model::regex_ids(seq![a]) =~= seq![a@]); + assert(model::regex_ids(seq![b]) =~= seq![b@]); + if a@ == b@ { + assert(model::regex_ids(seq![a]) == model::regex_ids(seq![b])); + assert(seq![a] == seq![b]); + assert(seq![a][0] == seq![b][0]); + assert(a == b); + } + } + pub(super) proof fn lemma_transition_id_eq(a: TransitionId, b: TransitionId) + ensures (a == b) == (a@ == b@), + { + model::lemma_transition_ids_eq(seq![a], seq![b]); + assert(model::transition_ids(seq![a]) =~= seq![a@]); + assert(model::transition_ids(seq![b]) =~= seq![b@]); + if a@ == b@ { + assert(model::transition_ids(seq![a]) == model::transition_ids(seq![b])); + assert(seq![a] == seq![b]); + assert(seq![a][0] == seq![b][0]); + assert(a == b); + } + } + proof fn lemma_primitive_eq(a: Primitive, b: Primitive) + ensures (a == b) == (a@ == b@), + { + match (a, b) { + (Primitive::Eq { term: x, .. }, Primitive::Eq { term: y, .. }) => { + match (x, y) { + (junco_core::kernel::Term::Constant(_), junco_core::kernel::Term::Constant(_)) => {}, + (junco_core::kernel::Term::Variable(_), junco_core::kernel::Term::Variable(_)) => {}, + _ => {}, + } + }, + } + } + pub(super) proof fn lemma_arena_test_eq_iff_node_eq(t: &ArenaTables, a: TestNode, b: TestNode) + requires tables_index_wf(t), arena_test_wf(t, a), arena_test_wf(t, b), + ensures (a == b) == (arena_test_node(a, t.test_ids@) == arena_test_node(b, t.test_ids@)), + { + match (a, b) { + (TestNode::And(x), TestNode::And(y)) | (TestNode::Or(x), TestNode::Or(y)) => { + model::lemma_test_ids_eq(t.test_ids@[x as int], t.test_ids@[y as int]); + lemma_pool_slot_eq(t.test_ids@, x, y); + }, + (TestNode::Atom { primitive: x, .. }, TestNode::Atom { primitive: y, .. }) => { + lemma_primitive_eq(x, y); + }, + _ => {}, + } + } + pub(super) proof fn lemma_arena_regex_eq_iff_node_eq(t: &ArenaTables, a: RegexNode, b: RegexNode) + requires tables_index_wf(t), arena_regex_wf(t, a), arena_regex_wf(t, b), + ensures (a == b) == (arena_regex_node(a, t.regex_ids@) == arena_regex_node(b, t.regex_ids@)), + { + match (a.kind, b.kind) { + (RegexKind::Union(x), RegexKind::Union(y)) + | (RegexKind::Concat(x), RegexKind::Concat(y)) + | (RegexKind::Intersect(x), RegexKind::Intersect(y)) => { + model::lemma_regex_ids_eq(t.regex_ids@[x as int], t.regex_ids@[y as int]); + lemma_pool_slot_eq(t.regex_ids@, x, y); + }, + (RegexKind::Test(x), RegexKind::Test(y)) => { + lemma_test_id_eq(x, y); + }, + (RegexKind::Star(x), RegexKind::Star(y)) + | (RegexKind::Not(x), RegexKind::Not(y)) => { + lemma_regex_id_eq(x, y); + }, + _ => {}, + } + } + pub(super) proof fn lemma_arena_transition_eq_iff_node_eq(t: &ArenaTables, a: TransitionNode, b: TransitionNode) + requires tables_index_wf(t), arena_transition_wf(t, a), arena_transition_wf(t, b), + ensures (a == b) == (arena_transition_node(a, t.transition_ids@, t.regex_ids@) + == arena_transition_node(b, t.transition_ids@, t.regex_ids@)), + { + match (a, b) { + (TransitionNode::Union(x), TransitionNode::Union(y)) + | (TransitionNode::Intersect(x), TransitionNode::Intersect(y)) => { + model::lemma_transition_ids_eq(t.transition_ids@[x as int], t.transition_ids@[y as int]); + lemma_pool_slot_eq(t.transition_ids@, x, y); + }, + (TransitionNode::Append { transition: a, suffix: x }, TransitionNode::Append { transition: b, suffix: y }) => { + lemma_transition_id_eq(a, b); + model::lemma_regex_ids_eq(t.regex_ids@[x as int], t.regex_ids@[y as int]); + lemma_pool_slot_eq(t.regex_ids@, x, y); + }, + (TransitionNode::Const(x), TransitionNode::Const(y)) => { + lemma_regex_id_eq(x, y); + }, + (TransitionNode::If { test: t, then_transition: a, else_transition: b }, + TransitionNode::If { test: u, then_transition: c, else_transition: d }) => { + lemma_test_id_eq(t, u); + lemma_transition_id_eq(a, c); + lemma_transition_id_eq(b, d); + }, + (TransitionNode::Not(x), TransitionNode::Not(y)) => { + lemma_transition_id_eq(x, y); + }, + _ => {}, + } + } + pub(super) proof fn lemma_test_contains(t: &ArenaTables, node: TestNode) + requires tables_index_wf(t), arena_test_wf(t, node), + ensures t.tests@.contains(node) == tables_graph(t).tests.contains(arena_test_node(node, t.test_ids@)), + { + let lifted = arena_test_node(node, t.test_ids@); + if t.tests@.contains(node) { + let i = t.tests@.lemma_contains_to_index(node); + assert(tables_graph(t).tests[i] == lifted); + } + if tables_graph(t).tests.contains(lifted) { + let i = tables_graph(t).tests.lemma_contains_to_index(lifted); + lemma_arena_test_eq_iff_node_eq(t, t.tests@[i], node); + assert(t.tests@.contains(node)); + } + } + pub(super) proof fn lemma_regex_contains(t: &ArenaTables, node: RegexNode) + requires tables_index_wf(t), arena_regex_wf(t, node), + ensures t.regexes@.contains(node) == tables_graph(t).regexes.contains(arena_regex_node(node, t.regex_ids@)), + { + let lifted = arena_regex_node(node, t.regex_ids@); + if t.regexes@.contains(node) { + let i = t.regexes@.lemma_contains_to_index(node); + assert(tables_graph(t).regexes[i] == lifted); + } + if tables_graph(t).regexes.contains(lifted) { + let i = tables_graph(t).regexes.lemma_contains_to_index(lifted); + lemma_arena_regex_eq_iff_node_eq(t, t.regexes@[i], node); + assert(t.regexes@.contains(node)); + } + } + pub(super) proof fn lemma_transition_contains(t: &ArenaTables, node: TransitionNode) + requires tables_index_wf(t), arena_transition_wf(t, node), + ensures t.transitions@.contains(node) == tables_graph(t).transitions.contains( + arena_transition_node(node, t.transition_ids@, t.regex_ids@)), + { + let lifted = arena_transition_node(node, t.transition_ids@, t.regex_ids@); + if t.transitions@.contains(node) { + let i = t.transitions@.lemma_contains_to_index(node); + assert(tables_graph(t).transitions[i] == lifted); + } + if tables_graph(t).transitions.contains(lifted) { + let i = tables_graph(t).transitions.lemma_contains_to_index(lifted); + lemma_arena_transition_eq_iff_node_eq(t, t.transitions@[i], node); + assert(t.transitions@.contains(node)); + } + } + pub(super) proof fn lemma_missing_test_children(t: &ArenaTables, view: model::TestNode, ids: Seq) + requires tables_index_wf(t), !t.test_ids@.contains(ids), + view == model::TestNode::And(model::test_ids(ids)) || view == model::TestNode::Or(model::test_ids(ids)), + ensures !tables_graph(t).tests.contains(view), + { + assert forall|i: int| 0 <= i < t.tests@.len() implies tables_graph(t).tests[i] != view by { + match t.tests@[i] { + TestNode::And(slot) | TestNode::Or(slot) => { + assert(t.test_ids@.contains(t.test_ids@[slot as int])); + model::lemma_test_ids_eq(t.test_ids@[slot as int], ids); + }, + _ => {}, + } + } + } + pub(super) proof fn lemma_missing_regex_children(t: &ArenaTables, view: model::RegexNode, ids: Seq) + requires tables_index_wf(t), !t.regex_ids@.contains(ids), + view.kind == model::RegexKindNode::Union(model::regex_ids(ids)) + || view.kind == model::RegexKindNode::Concat(model::regex_ids(ids)) + || view.kind == model::RegexKindNode::Intersect(model::regex_ids(ids)), + ensures !tables_graph(t).regexes.contains(view), + { + assert forall|i: int| 0 <= i < t.regexes@.len() implies tables_graph(t).regexes[i] != view by { + match t.regexes@[i].kind { + RegexKind::Union(slot) | RegexKind::Concat(slot) | RegexKind::Intersect(slot) => { + assert(t.regex_ids@.contains(t.regex_ids@[slot as int])); + model::lemma_regex_ids_eq(t.regex_ids@[slot as int], ids); + }, + _ => {}, + } + } + } + pub(super) proof fn lemma_missing_transition_children(t: &ArenaTables, view: model::TransitionNode, ids: Seq) + requires tables_index_wf(t), !t.transition_ids@.contains(ids), + view == model::TransitionNode::Union(model::transition_ids(ids)) + || view == model::TransitionNode::Intersect(model::transition_ids(ids)), + ensures !tables_graph(t).transitions.contains(view), + { + assert forall|i: int| 0 <= i < t.transitions@.len() implies tables_graph(t).transitions[i] != view by { + match t.transitions@[i] { + TransitionNode::Union(slot) | TransitionNode::Intersect(slot) => { + assert(t.transition_ids@.contains(t.transition_ids@[slot as int])); + model::lemma_transition_ids_eq(t.transition_ids@[slot as int], ids); + }, + _ => {}, + } + } + } + pub(super) proof fn lemma_missing_append_suffix(t: &ArenaTables, transition: nat, ids: Seq) + requires tables_index_wf(t), !t.regex_ids@.contains(ids), + ensures !tables_graph(t).transitions.contains(model::TransitionNode::Append(transition, model::regex_ids(ids))), + { + assert forall|i: int| 0 <= i < t.transitions@.len() implies tables_graph(t).transitions[i] + != model::TransitionNode::Append(transition, model::regex_ids(ids)) by { + match t.transitions@[i] { + TransitionNode::Append { suffix, .. } => { + assert(t.regex_ids@.contains(t.regex_ids@[suffix as int])); + model::lemma_regex_ids_eq(t.regex_ids@[suffix as int], ids); + }, + _ => {}, + } + } + } + pub(super) open spec fn tables_wf(t: &ArenaTables) -> bool { + tables_index_wf(t) && tables_space_wf(t) + } + // Every pool slot referenced by a node exists. + pub(super) open spec fn tables_index_wf(t: &ArenaTables) -> bool { + &&& t.tests.inv() && t.regexes.inv() && t.transitions.inv() + &&& t.test_ids.inv() && t.regex_ids.inv() && t.transition_ids.inv() + &&& forall|i: int| 0 <= i < t.tests@.len() ==> match #[trigger] t.tests@[i] { + TestNode::And(slot) | TestNode::Or(slot) => slot < t.test_ids@.len(), + _ => true, + } + &&& forall|i: int| 0 <= i < t.regexes@.len() ==> match (#[trigger] t.regexes@[i]).kind { + RegexKind::Union(slot) | RegexKind::Concat(slot) | RegexKind::Intersect(slot) => slot < t.regex_ids@.len(), + _ => true, + } + &&& forall|i: int| 0 <= i < t.transitions@.len() ==> match #[trigger] t.transitions@[i] { + TransitionNode::Union(slot) | TransitionNode::Intersect(slot) => slot < t.transition_ids@.len(), + TransitionNode::Append { transition, suffix } => suffix < t.regex_ids@.len(), + _ => true, + } + } + pub(super) open spec fn tables_graph(t: &ArenaTables) -> model::Graph { + model::Graph { + tests: Seq::new(t.tests@.len(), |i: int| arena_test_node(t.tests@[i], t.test_ids@)), + regexes: Seq::new(t.regexes@.len(), |i: int| arena_regex_node(t.regexes@[i], t.regex_ids@)), + transitions: Seq::new(t.transitions@.len(), |i: int| arena_transition_node(t.transitions@[i], t.transition_ids@, t.regex_ids@)), + constants: storage_constants(), + } + } + + // ---- Capacity accounting ------------------------------------------------------------- + // + // `graph_weight` is the byte charge `CanonicalStore::intern_*` levies for a graph + // (`size_of::()` per node plus `size_of::()` per child). `arena_live` is what the + // six arenas actually hold. Their difference, `tables_slack`, never decreases on a successful + // push and is 0 for a fresh store, so exhaustion before `GraphBudget` is impossible. + + pub open spec fn mul_bytes(count: nat, size: nat) -> nat { count * size } + pub proof fn lemma_mul_bytes_succ(count: nat, size: nat) + ensures mul_bytes(count + 1, size) == mul_bytes(count, size) + size, + { + assert((count + 1) * size == count * size + size) by (nonlinear_arith); + } + + pub open(super) spec fn test_weight(n: model::TestNode) -> nat { + vstd::layout::size_of::() + match n { + model::TestNode::And(ids) | model::TestNode::Or(ids) => mul_bytes(ids.len(), vstd::layout::size_of::()), + _ => 0, + } + } + pub open(super) spec fn regex_weight(n: model::RegexNode) -> nat { + vstd::layout::size_of::() + match n.kind { + model::RegexKindNode::Union(ids) | model::RegexKindNode::Concat(ids) | model::RegexKindNode::Intersect(ids) => + mul_bytes(ids.len(), vstd::layout::size_of::()), + _ => 0, + } + } + pub open(super) spec fn transition_weight(n: model::TransitionNode) -> nat { + vstd::layout::size_of::() + match n { + model::TransitionNode::Union(ids) | model::TransitionNode::Intersect(ids) => + mul_bytes(ids.len(), vstd::layout::size_of::()), + model::TransitionNode::Append(_, suffix) => mul_bytes(suffix.len(), vstd::layout::size_of::()), + _ => 0, + } + } + pub open spec fn tests_weight(s: Seq) -> nat + decreases s.len(), + { + if s.len() == 0 { 0 } else { tests_weight(s.drop_last()) + test_weight(s.last()) } + } + pub open spec fn regexes_weight(s: Seq) -> nat + decreases s.len(), + { + if s.len() == 0 { 0 } else { regexes_weight(s.drop_last()) + regex_weight(s.last()) } + } + pub open spec fn transitions_weight(s: Seq) -> nat + decreases s.len(), + { + if s.len() == 0 { 0 } else { transitions_weight(s.drop_last()) + transition_weight(s.last()) } + } + pub open spec fn graph_weight(g: model::Graph) -> nat { + tests_weight(g.tests) + regexes_weight(g.regexes) + transitions_weight(g.transitions) + } + + #[cfg(target_pointer_width = "64")] + pub(super) proof fn lemma_tests_weight_count(s: Seq) + ensures 32 * s.len() <= tests_weight(s), + decreases s.len(), + { + broadcast use super::VERUS_layout_of_TestNode; + if s.len() > 0 { + lemma_tests_weight_count(s.drop_last()); + assert(s.drop_last().len() + 1 == s.len()); + assert(test_weight(s.last()) >= 32); + } + } + + #[cfg(target_pointer_width = "64")] + pub(super) proof fn lemma_regexes_weight_count(s: Seq) + ensures 24 * s.len() <= regexes_weight(s), + decreases s.len(), + { + broadcast use super::VERUS_layout_of_RegexNode; + if s.len() > 0 { + lemma_regexes_weight_count(s.drop_last()); + assert(s.drop_last().len() + 1 == s.len()); + assert(regex_weight(s.last()) >= 24); + } + } + + #[cfg(target_pointer_width = "64")] + pub(super) proof fn lemma_transitions_weight_count(s: Seq) + ensures 16 * s.len() <= transitions_weight(s), + decreases s.len(), + { + broadcast use super::VERUS_layout_of_TransitionNode; + if s.len() > 0 { + lemma_transitions_weight_count(s.drop_last()); + assert(s.drop_last().len() + 1 == s.len()); + assert(transition_weight(s.last()) >= 16); + } + } + pub proof fn lemma_tests_weight_push(s: Seq, n: model::TestNode) + ensures tests_weight(s.push(n)) == tests_weight(s) + test_weight(n), + { + assert(s.push(n).drop_last() =~= s); + } + pub proof fn lemma_regexes_weight_push(s: Seq, n: model::RegexNode) + ensures regexes_weight(s.push(n)) == regexes_weight(s) + regex_weight(n), + { + assert(s.push(n).drop_last() =~= s); + } + pub proof fn lemma_transitions_weight_push(s: Seq, n: model::TransitionNode) + ensures transitions_weight(s.push(n)) == transitions_weight(s) + transition_weight(n), + { + assert(s.push(n).drop_last() =~= s); + } + + pub open spec fn pool_bytes(p: Seq>) -> nat + decreases p.len(), + { + if p.len() == 0 { 0 } else { pool_bytes(p.drop_last()) + mul_bytes(p.last().len(), vstd::layout::size_of::()) } + } + pub proof fn lemma_pool_bytes_push(p: Seq>, s: Seq) + ensures pool_bytes(p.push(s)) == pool_bytes(p) + mul_bytes(s.len(), vstd::layout::size_of::()), + { + assert(p.push(s).drop_last() =~= p); + } + + /// Exact native layout premises checked before allocating any of the six arenas. + pub open(crate) spec fn construction_layout(capacity: usize) -> bool { + &&& vstd::layout::size_of::() > 0 + &&& vstd::layout::size_of::() > 0 + &&& vstd::layout::size_of::() > 0 + &&& vstd::layout::align_of::() <= CHUNK_ALIGN + &&& vstd::layout::align_of::() <= CHUNK_ALIGN + &&& vstd::layout::align_of::() <= CHUNK_ALIGN + &&& vstd::layout::align_of::() <= CHUNK_ALIGN + &&& vstd::layout::align_of::() <= CHUNK_ALIGN + &&& vstd::layout::align_of::() <= CHUNK_ALIGN + &&& capacity as int % vstd::layout::align_of::() as int == 0 + &&& capacity as int % vstd::layout::align_of::() as int == 0 + &&& capacity as int % vstd::layout::align_of::() as int == 0 + &&& capacity as int % vstd::layout::align_of::() as int == 0 + &&& capacity as int % vstd::layout::align_of::() as int == 0 + &&& capacity as int % vstd::layout::align_of::() as int == 0 + } + + /// Every 16-byte-aligned budget satisfies the native arena layout checks on the pinned + /// 64-bit verification target. Small budgets may still report graph/resource exhaustion. + #[cfg(target_pointer_width = "64")] + pub proof fn lemma_aligned_budget_layout(capacity: usize) + requires capacity as int % 16 == 0, + ensures construction_layout(capacity), + { + // Activate the existing global-layout directives' generated theorems locally. + broadcast use { + super::VERUS_layout_of_TestNode, + super::VERUS_layout_of_RegexNode, + super::VERUS_layout_of_TransitionNode, + super::VERUS_layout_of_TestId, + super::VERUS_layout_of_RegexId, + super::VERUS_layout_of_TransitionId, + }; + assert(vstd::layout::size_of::() == 32); + assert(vstd::layout::size_of::() == 24); + assert(vstd::layout::size_of::() == 16); + assert(vstd::layout::align_of::() == 8); + assert(vstd::layout::align_of::() == 8); + assert(vstd::layout::align_of::() == 8); + assert(vstd::layout::align_of::() == 4); + assert(vstd::layout::align_of::() == 4); + assert(vstd::layout::align_of::() == 4); + assert(CHUNK_ALIGN == 16) by (compute); + assert(capacity as int % 8 == 0 && capacity as int % 4 == 0); + } + + #[cfg(target_pointer_width = "64")] + pub(super) proof fn lemma_production_layout() + ensures construction_layout(ARENA_CAPACITY), + { + assert(ARENA_CAPACITY == 102400) by (compute); + assert(102400int % 16 == 0) by (compute); + lemma_aligned_budget_layout(ARENA_CAPACITY); + } + + pub(super) open spec fn layout_premises() -> bool { + &&& vstd::layout::size_of::() > 0 + &&& vstd::layout::size_of::() > 0 + &&& vstd::layout::size_of::() > 0 + } + pub(super) open spec fn arena_live(t: &ArenaTables) -> nat { + mul_bytes(t.tests@.len(), vstd::layout::size_of::()) + + mul_bytes(t.regexes@.len(), vstd::layout::size_of::()) + + mul_bytes(t.transitions@.len(), vstd::layout::size_of::()) + + pool_bytes(t.test_ids@) + pool_bytes(t.regex_ids@) + pool_bytes(t.transition_ids@) + } + // All six arenas share one capacity, stay aligned, and hold exactly `arena_live` bytes. + pub(super) open spec fn tables_space_wf(t: &ArenaTables) -> bool { + let cap = t.tests.capacity(); + &&& layout_premises() + &&& t.tests.aligned() && t.test_ids.aligned() && t.regexes.aligned() + && t.regex_ids.aligned() && t.transitions.aligned() && t.transition_ids.aligned() + &&& t.test_ids.capacity() == cap && t.regexes.capacity() == cap && t.regex_ids.capacity() == cap + && t.transitions.capacity() == cap && t.transition_ids.capacity() == cap + &&& t.tests.remaining() == cap - mul_bytes(t.tests@.len(), vstd::layout::size_of::()) + &&& t.regexes.remaining() == cap - mul_bytes(t.regexes@.len(), vstd::layout::size_of::()) + &&& t.transitions.remaining() == cap - mul_bytes(t.transitions@.len(), vstd::layout::size_of::()) + &&& t.test_ids.remaining() == cap - pool_bytes(t.test_ids@) + &&& t.regex_ids.remaining() == cap - pool_bytes(t.regex_ids@) + &&& t.transition_ids.remaining() == cap - pool_bytes(t.transition_ids@) + } + pub(super) open spec fn tables_capacity(t: &ArenaTables) -> int { t.tests.capacity() } + pub(super) open spec fn tables_slack(t: &ArenaTables) -> int { + graph_weight(tables_graph(t)) - arena_live(t) + } + // A freshly constructed table set: empty, aligned, full capacity, zero slack. + pub(super) proof fn lemma_fresh_tables(t: &ArenaTables, capacity: usize) + requires + layout_premises(), + t.tests.inv() && t.regexes.inv() && t.transitions.inv(), + t.test_ids.inv() && t.regex_ids.inv() && t.transition_ids.inv(), + t.tests@ == Seq::::empty(), t.regexes@ == Seq::::empty(), + t.transitions@ == Seq::::empty(), + t.test_ids@ == Seq::>::empty(), t.regex_ids@ == Seq::>::empty(), + t.transition_ids@ == Seq::>::empty(), + t.tests.aligned() && t.test_ids.aligned() && t.regexes.aligned() + && t.regex_ids.aligned() && t.transitions.aligned() && t.transition_ids.aligned(), + t.tests.capacity() == capacity && t.test_ids.capacity() == capacity + && t.regexes.capacity() == capacity && t.regex_ids.capacity() == capacity + && t.transitions.capacity() == capacity && t.transition_ids.capacity() == capacity, + t.tests.remaining() == capacity && t.test_ids.remaining() == capacity + && t.regexes.remaining() == capacity && t.regex_ids.remaining() == capacity + && t.transitions.remaining() == capacity && t.transition_ids.remaining() == capacity, + ensures + tables_wf(t), empty_tables(tables_graph(t)), + tables_capacity(t) == capacity, tables_slack(t) == 0, + { + assert(tables_graph(t).tests.len() == 0); + assert(tables_graph(t).regexes.len() == 0); + assert(tables_graph(t).transitions.len() == 0); + assert(graph_weight(tables_graph(t)) == 0); + assert(arena_live(t) == 0); + } + + // Appending an unused pool slot cannot change any already-published node. + pub(super) proof fn pool_extension(before: &ArenaTables, after: &ArenaTables) + requires + tables_index_wf(before), + after.tests.inv() && after.regexes.inv() && after.transitions.inv(), + after.test_ids.inv() && after.regex_ids.inv() && after.transition_ids.inv(), + before.tests@ == after.tests@, + before.regexes@ == after.regexes@, + before.transitions@ == after.transitions@, + before.test_ids@.len() <= after.test_ids@.len(), + before.regex_ids@.len() <= after.regex_ids@.len(), + before.transition_ids@.len() <= after.transition_ids@.len(), + after.test_ids@.take(before.test_ids@.len() as int) == before.test_ids@, + after.regex_ids@.take(before.regex_ids@.len() as int) == before.regex_ids@, + after.transition_ids@.take(before.transition_ids@.len() as int) == before.transition_ids@, + ensures tables_index_wf(after), tables_graph(after) == tables_graph(before), + { + assert forall|i: int| 0 <= i < before.tests@.len() implies + arena_test_node(before.tests@[i], before.test_ids@) == + arena_test_node(after.tests@[i], after.test_ids@) by { + match before.tests@[i] { + TestNode::And(slot) | TestNode::Or(slot) => { + assert(before.test_ids@[slot as int] == after.test_ids@[slot as int]); + }, + _ => {}, + } + } + assert forall|i: int| 0 <= i < before.regexes@.len() implies + arena_regex_node(before.regexes@[i], before.regex_ids@) == + arena_regex_node(after.regexes@[i], after.regex_ids@) by { + match before.regexes@[i].kind { + RegexKind::Union(slot) | RegexKind::Concat(slot) | RegexKind::Intersect(slot) => { + assert(before.regex_ids@[slot as int] == after.regex_ids@[slot as int]); + }, + _ => {}, + } + } + assert forall|i: int| 0 <= i < before.transitions@.len() implies + arena_transition_node(before.transitions@[i], before.transition_ids@, before.regex_ids@) == + arena_transition_node(after.transitions@[i], after.transition_ids@, after.regex_ids@) by { + match before.transitions@[i] { + TransitionNode::Union(slot) | TransitionNode::Intersect(slot) => { + assert(before.transition_ids@[slot as int] == after.transition_ids@[slot as int]); + }, + TransitionNode::Append { transition, suffix } => { + assert(before.regex_ids@[suffix as int] == after.regex_ids@[suffix as int]); + }, + _ => {}, + } + } + assert(tables_index_wf(after)); + assert(tables_graph(after).tests =~= tables_graph(before).tests); + assert(tables_graph(after).regexes =~= tables_graph(before).regexes); + assert(tables_graph(after).transitions =~= tables_graph(before).transitions); + } + impl ArenaStorage { + pub(crate) open(super) spec fn graph(&self) -> model::Graph { + match self.tables { + Some(t) => tables_graph(&t), + None => model::Graph { + tests: Seq::empty(), regexes: Seq::empty(), transitions: Seq::empty(), + constants: storage_constants(), + }, + } + } + pub(crate) open(super) spec fn capacity(&self) -> int { + match self.tables { Some(t) => tables_capacity(&t), None => 0 } + } + pub(crate) open(super) spec fn slack(&self) -> int { + match self.tables { Some(t) => tables_slack(&t), None => 0 } + } + } + + impl CanonicalStore { + pub open(super) spec fn graph(&self) -> model::Graph { + model::Graph { constants: self.constants@, ..self.storage.graph() } + } + pub open(super) spec fn valid_store(&self) -> bool { + let g = self.graph(); + self.storage.tables is Some + && model::unique_nodes(g) && graph_weight(g) <= (self.bytes as nat) + } + } + + impl junco_core::verify::history_assumptions::KernelStoreSpec for RuntimeKernel<'_, L> { + open spec fn graph(&self) -> model::Graph { self.store.graph() } + open spec fn valid_store(&self) -> bool { self.store.valid_store() } + open spec fn errors_are_non_owner(&self) -> bool { true } + open spec fn errors_are_non_invariant(&self) -> bool { true } + open spec fn errors_are_non_invalid_policy(&self) -> bool { true } + open spec fn errors_are_resource(&self) -> bool { true } + #[verifier::prophetic] + open spec fn restoration(&self) -> (model::Graph, bool) { + let restored = mut_ref_future(self.store); + (restored.graph(), restored.valid_store()) + } + } + + + + pub(super) proof fn lemma_tables_wf_same_tables(before: model::Graph, after: model::Graph) + requires + model::tables_wf(before), + before.tests == after.tests, + before.regexes == after.regexes, + before.transitions == after.transitions, + ensures model::tables_wf(after), + { + model::lemma_old_nodes_wf_under_extends(before, after); + } + + + pub open spec fn empty_tables(g: model::Graph) -> bool { + g.tests.len() == 0 && g.regexes.len() == 0 && g.transitions.len() == 0 + } + + + } +} diff --git a/src/history-store/src/history.rs b/src/history-store/src/history.rs new file mode 100644 index 000000000..f00b3a7ae --- /dev/null +++ b/src/history-store/src/history.rs @@ -0,0 +1,1699 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +//! Numeric and typed committed histories with failure-atomic mutation. +//! Typed owners retain erased process-key receipts alongside their local lifecycle registration; +//! mutation preserves identity evidence, while a fork retains its newly issued key receipt. +//! Arc sharing retains native referent identity separately from registry and encoding receipts. +//! Actual source checkpoints and retained owner receipts prove foreign rollback rejection. +//! Exact iterator conversion facts retain the original event sequence when the input supplies +//! the shared conversion law. Truncation is a no-op at or beyond length, otherwise consumes +//! one revision or fails unchanged at exhaustion; rollback checks owner, then length first. + +#[cfg(verus_keep_ghost)] +use self::verify::*; +use crate::graph::allocation; +use crate::store::Event; +#[cfg(verus_keep_ghost)] +use crate::typed::verify as books; +use crate::typed::{Store, share_store}; +use alloc::sync::Arc; +use alloc::vec::Vec; +use core::fmt; +use history_syntax::Event as TypedEvent; +use junco_core::errors::HistoryError; +use junco_core::limits::{Limits, Unmetered}; +use junco_core::observation::ObservationWorld; +use vstd::prelude::*; +#[cfg(verus_keep_ghost)] +use vstd::std_specs::iter::IteratorSpec; + +#[cfg(verus_keep_ghost)] +verus! { +impl View for StoredHistory { + type V = junco_core::verify::history_specs::HistoryStateView; + closed spec fn view(&self) -> junco_core::verify::history_specs::HistoryStateView { + junco_core::verify::history_specs::HistoryStateView { + events: crate::store::verify::events_view(self.events@), + revision: self.revision as nat, + } + } +} + +pub proof fn lemma_stored_history_view(stored: StoredHistory) + ensures stored@ == (junco_core::verify::history_specs::HistoryStateView { + events: crate::store::verify::events_view(verify::stored_events(&stored)), + revision: stored.spec_revision() as nat, + }), +{ + reveal(::view); +} +} + +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Debug)] +pub struct StoredHistory { + pub(crate) events: Vec, + pub(crate) revision: u64, + pub(crate) id: usize, +} + +#[verus_verify] +impl StoredHistory { + #[cfg(verus_keep_ghost)] + verus! { + pub closed spec fn spec_revision(&self) -> u64 { self.revision } + pub closed spec fn spec_id(&self) -> usize { self.id } + } + + #[verus_spec(result => ensures result@ == verify::stored_events(self), + crate::store::verify::events_view(result@) == self@.events)] + pub fn as_slice(&self) -> &[Event] { + proof! { reveal(::view); } + &self.events + } + + /// Return the number of encoded events without exposing mutable storage. + #[verus_spec(result => ensures result == self@.events.len())] + pub fn len(&self) -> usize { + proof! { reveal(::view); } + self.events.len() + } + + /// Return whether the encoded history is empty without exposing storage. + #[verus_spec(result => ensures result == (self@.events.len() == 0))] + pub fn is_empty(&self) -> bool { + proof! { reveal(::view); } + self.events.is_empty() + } + + /// Return the revision invalidating decisions after a shortening transaction. + #[cfg_attr(verus_keep_ghost, verifier::when_used_as_spec(spec_revision))] + #[verus_spec(result => ensures result == self@.revision, result == self.spec_revision())] + pub const fn revision(&self) -> u64 { + proof! { reveal(::view); } + self.revision + } + + /// Return the immutable process-wide key that names this record in cursor caches. + #[cfg_attr(verus_keep_ghost, verifier::when_used_as_spec(spec_id))] + #[verus_spec(result => ensures result == self.spec_id())] + pub const fn id(&self) -> usize { + self.id + } + + #[verus_spec(result => ensures result.events@ == Seq::::empty(), result.revision == 0, + verify::stored_events(&result) == Seq::::empty(), result.spec_revision() == 0, + result.id == id, result.spec_id() == id)] + pub(crate) const fn new(id: usize) -> Self { + Self { + events: Vec::new(), + revision: 0, + id, + } + } + + #[verus_spec(result => + ensures verify::stored_append_result(*old(self), *final(self), events@, result), + result != Err(HistoryError::WrongHistoryOwner), + junco_core::verify::history_specs::no_invariant_failure(result), + result matches Err(error) ==> junco_core::spec::semantics::resource_error(error), + )] + pub(crate) fn append_events( + &mut self, + events: &[Event], + limits: &mut L, + world: &mut ObservationWorld, + ) -> Result<(), HistoryError> { + proof! { + reveal(::view); + reveal(StoredHistory::spec_id); + reveal(StoredHistory::spec_revision); + } + proof_decl! { let ghost entry_events = self.events@; } + proof_decl! { let ghost entry = *self; } + let previous = self.events.len(); + allocation(world.try_reserve_vec(&mut self.events, events.len()))?; + limits.enforce_memory()?; + self.events.extend_from_slice(events); + if let Err(error) = limits.enforce_memory() { + self.events.truncate(previous); + proof! { + assert(self.events@ =~= entry_events); + assert(self.id == entry.id && self.revision == entry.revision); + assert(junco_core::verify::history_specs::history_mutation(entry@, self@)); + assert(verify::stored_events(&*self) == entry_events); + } + return Err(error.into()); + } + proof! { + assert(crate::store::verify::events_view(self.events@) + =~= crate::store::verify::events_view(entry_events) + + crate::store::verify::events_view(events@)); + assert(self.id == entry.id && self.revision == entry.revision); + assert(self.events@ == entry_events + events@); + assert(junco_core::verify::history_specs::history_mutation(entry@, self@)); + assert(verify::stored_events(&*self) == entry_events + events@); + } + Ok(()) + } + + #[verus_spec(result => + ensures verify::stored_truncate_result(*old(self), *final(self), len, result), + )] + pub(crate) fn truncate_events(&mut self, len: usize) -> Result<(), HistoryError> { + proof! { reveal(::view); } + proof_decl! { let ghost entry_events = self.events@; } + if len < self.events.len() { + let revision = self + .revision + .checked_add(1) + .ok_or(HistoryError::RevisionExhausted)?; + self.events.truncate(len); + self.revision = revision; + proof! { + assert(self.events@ == entry_events.take(len as int)); + assert(crate::store::verify::events_view(self.events@) + =~= crate::store::verify::events_view(entry_events).take(len as int)); + } + } + Ok(()) + } +} + +/// Opaque length marker accepted only by the history that produced it. +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct Checkpoint { + pub(crate) store_id: u64, + pub(crate) history: usize, + pub(crate) len: usize, +} + +/// Raw committed events and their store-bound numeric encoding. +/// +/// Equality and diagnostics observe the original events, not their projections or owner. +/// No mutable slice or numeric record escapes this owner. +#[verus_verify] +pub struct History { + pub(crate) events: Vec, + pub(crate) numeric: StoredHistory, + pub(crate) store: Arc>, + #[cfg(verus_keep_ghost)] + pub(crate) maps: Ghost>, + #[cfg(verus_keep_ghost)] + pub(crate) lifecycle: Tracked, + #[cfg(verus_keep_ghost)] + pub(crate) registration: Tracked, + #[cfg(verus_keep_ghost)] + pub(crate) global_registration: Tracked, +} + +#[verus_verify] +impl History { + #[cfg(verus_keep_ghost)] + verus! { + pub closed spec fn spec_id(&self) -> usize { self.numeric.id } + pub closed spec fn spec_numeric(&self) -> &StoredHistory { &self.numeric } + } + + /// Returns the numeric record's process-wide key. + #[cfg_attr(verus_keep_ghost, verifier::when_used_as_spec(spec_id))] + #[verus_spec(result => ensures result == self.spec_id())] + pub const fn id(&self) -> usize { + self.numeric.id + } + + #[cfg_attr(verus_keep_ghost, verifier::when_used_as_spec(spec_numeric))] + #[verus_spec(result => ensures *result == *self.spec_numeric())] + pub fn numeric(&self) -> &StoredHistory { + &self.numeric + } + + /// Creates an empty history in `store`, with a fresh process-wide key. + #[verus_spec(result => + requires books::store_wf(*store), + ensures result matches Ok(history) ==> history_wf(history) && empty_history(history, store), + junco_core::verify::history_specs::no_invariant_failure(result), + )] + pub fn new(store: Arc>) -> Result { + proof! { books::lemma_empty_snapshot(&*store); } + proof_decl! { + let ghost empty = junco_core::verify::history_specs::HistoryStateView { + events: Seq::empty(), revision: 0, + }; + let tracked lifecycle = Lifecycle::new(empty); + } + #[cfg(verus_keep_ghost)] + let (id, registration, global_registration) = store.allocate_history_id_for_resource( + verus_exec_expr! { Ghost(lifecycle.id()) }, + verus_exec_expr! { Tracked(None) }, + )?; + #[cfg(not(verus_keep_ghost))] + let (id, _, _) = + store.allocate_history_id_for_resource(Ghost::assume_new(), Tracked::assume_new())?; + let numeric = StoredHistory::new(id); + proof! { + reveal(::view); + assert(crate::store::verify::events_view(numeric.events@) =~= Seq::empty()); + assert(numeric@ == empty); + if junco_core::spec::hypotheses::event_obligations::() { books::lemma_empty_maps_wf::(); } + } + Ok(Self { + events: Vec::new(), + numeric, + store, + #[cfg(verus_keep_ghost)] + maps: verus_exec_expr! { Ghost(books::empty_maps::()) }, + #[cfg(verus_keep_ghost)] + lifecycle: verus_exec_expr! { Tracked(lifecycle) }, + #[cfg(verus_keep_ghost)] + registration, + #[cfg(verus_keep_ghost)] + global_registration, + }) + } + + /// Creates a history by committing the supplied events in iteration order. + #[verus_spec(result => + requires books::store_wf(*store), + ensures result matches Ok(history) ==> history_wf(history) && initialized_history(history, store) + && forall|items: Seq| junco_core::verify::history_specs::into_iter_yields(events, items) + ==> raw_events(history) == items, + )] + pub fn from_events>( + store: Arc>, + events: I, + ) -> Result { + proof_decl! { let ghost input = events; } + let convert = I::into_iter; + let iterator = convert(events); + proof_decl! { let ghost converted = iterator; } + proof! { assert(call_ensures(convert, (input,), converted)); } + let result = Self::from_iterator(store, iterator); + proof! { + if let Ok(ref history) = result { + assert forall|items: Seq| + junco_core::verify::history_specs::into_iter_yields(input, items) + implies raw_events(*history) == items by { + assert(converted.obeys_prophetic_iter_laws()); + assert(converted.remaining() == items); + } + } + } + result + } + + // Caller-supplied iterators may be infinite; each yielded event still commits atomically. + #[cfg_attr(verus_keep_ghost, verifier::exec_allows_no_decreases_clause)] + #[verus_spec(result => + requires books::store_wf(*store), + ensures result matches Ok(history) ==> history_wf(history) + && history.numeric.revision == 0 && history.store == store + && (iterator.obeys_prophetic_iter_laws() ==> history.events@ == iterator.remaining()), + )] + fn from_iterator>( + store: Arc>, + iterator: I, + ) -> Result { + proof_decl! { let ghost original_iterator = iterator; } + let mut remaining = iterator; + let mut history = Self::new(store)?; + #[cfg_attr(verus_keep_ghost, verus_spec(invariant history_wf(history), + history.numeric.revision == 0, history.store == store, + original_iterator == iterator, + remaining.obeys_prophetic_iter_laws() == original_iterator.obeys_prophetic_iter_laws(), + remaining.obeys_prophetic_iter_laws() ==> + history.events@ + remaining.remaining() == original_iterator.remaining()))] + loop { + match remaining.next() { + Some(event) => history.push(event)?, + None => { + proof! { + assert(history_wf(history)); + assert(history.numeric.revision == 0); + assert(history.store == store); + if original_iterator.obeys_prophetic_iter_laws() { + assert(remaining.remaining().len() == 0); + assert(history.events@ =~= original_iterator.remaining()); + assert(history.events@ == iterator.remaining()); + } + } + return Ok(history); + } + } + } + } + + /// Appends one original event and its numeric encoding atomically. + #[verus_spec(result => + requires history_wf(*old(self)), + ensures history_wf(*final(self)), push_result(*old(self), *final(self), event, result), + result matches Err(error) ==> junco_core::spec::semantics::resource_error(error), + )] + pub fn push(&mut self, event: E) -> Result<(), HistoryError> { + self.push_with(event, &mut Unmetered, &mut ObservationWorld) + } + + #[verus_spec(result => + requires history_wf(*old(self)), + ensures history_wf(*final(self)), push_result(*old(self), *final(self), event, result), + result matches Err(error) ==> junco_core::spec::semantics::resource_error(error), + )] + pub fn push_with( + &mut self, + event: E, + limits: &mut L, + world: &mut ObservationWorld, + ) -> Result<(), HistoryError> { + proof_decl! { let ghost before = *self; } + proof! { + reveal(::view); + reveal(StoredHistory::spec_id); + reveal(StoredHistory::spec_revision); + } + allocation(world.try_reserve_vec(&mut self.events, 1))?; + limits.checkpoint()?; + #[cfg(verus_keep_ghost)] + let (encoded, maps) = self.store.encode_event_with_snapshot( + &event, + verus_exec_expr! { Ghost(self.maps@) }, + verus_exec_expr! { Ghost(self.maps@) }, + ); + #[cfg(not(verus_keep_ghost))] + let encoded = self.store.encode_event(&event); + proof! { + *self.maps = maps@; + if junco_core::spec::hypotheses::event_obligations::() { + lemma_correspondence_extends(before.events@, before.numeric.events@, + before.maps@, self.maps@); + } + } + let encoded = encoded?; + self.numeric.append_events(&[encoded], limits, world)?; + self.events.push(event); + proof! { + assert(self.events@ == before.events@.push(event)); + assert(self.numeric.events@ == before.numeric.events@.push(encoded)); + assert(self.numeric.events@.last() == encoded); + assert(stored_events(&self.numeric) == stored_events(&before.numeric) + seq![encoded]); + assert(stored_append_result(before.numeric, self.numeric, seq![encoded], Ok(()))); + if junco_core::spec::hypotheses::event_obligations::() { + assert forall|i: int| 0 <= i < self.events@.len() implies + books::event_encoded::(self.maps@, self.events@[i], self.numeric.events@[i]) by { + if i < before.events@.len() { + assert(self.events@[i] == before.events@[i]); + assert(self.numeric.events@[i] == before.numeric.events@[i]); + } else { + assert(i == before.events@.len()); + assert(self.events@[i] == event && self.numeric.events@[i] == encoded); + } + } + } + self.lifecycle.borrow_mut().advance(self.numeric@); + assert(owner_frame(before, *self)); + assert(self.numeric.events@.drop_last() == before.numeric.events@); + if junco_core::spec::hypotheses::event_obligations::() { + assert(books::maps_extend::(before.maps@, self.maps@)); + } + assert(push_result(before, *self, event, Ok(()))); + } + Ok(()) + } + + /// Shortens the history; equal or larger lengths are no-ops. + #[verus_spec(result => + requires history_wf(*old(self)), + ensures history_wf(*final(self)), truncate_result(*old(self), *final(self), len, result), + )] + pub fn truncate(&mut self, len: usize) -> Result<(), HistoryError> { + proof_decl! { let ghost before = *self; } + proof! { reveal(::view); } + self.numeric.truncate_events(len)?; + self.events.truncate(len); + proof! { + if len < before.events@.len() { + assert(self.events@ == before.events@.take(len as int)); + } + if junco_core::spec::hypotheses::event_obligations::() { + assert forall|i: int| 0 <= i < self.events@.len() implies + books::event_encoded::(self.maps@, self.events@[i], self.numeric.events@[i]) by { + assert(self.events@[i] == before.events@[i]); + assert(self.numeric.events@[i] == before.numeric.events@[i]); + } + } + self.lifecycle.borrow_mut().advance(self.numeric@); + assert(owner_frame(before, *self)); + assert(self.maps@ == before.maps@); + assert(junco_core::verify::history_specs::history_mutation(before.numeric@, self.numeric@)); + if len < before.events@.len() { + assert(self.numeric.events@ == before.numeric.events@.take(len as int)); + assert(self.numeric.revision == before.numeric.revision + 1); + } else { + assert(self.events@ =~= before.events@); + assert(self.numeric.events@ == before.numeric.events@); + assert(self.numeric.revision == before.numeric.revision); + assert(state_frame(before, *self)); + } + assert(truncate_result(before, *self, len, Ok(()))); + } + Ok(()) + } + + /// Restores a marker's length after checking store, owner, then length. + #[verus_spec(result => + requires history_wf(*old(self)), + ensures history_wf(*final(self)), rollback_result(*old(self), *final(self), checkpoint, result), + )] + pub fn rollback(&mut self, checkpoint: Checkpoint) -> Result<(), HistoryError> { + if checkpoint.store_id != self.store.id() || checkpoint.history != self.numeric.id { + return Err(HistoryError::WrongCheckpointOwner); + } + if checkpoint.len > self.events.len() { + return Err(HistoryError::CheckpointBeyondHistory); + } + self.truncate(checkpoint.len) + } + + /// Copies raw and numeric events without invoking user projections or `Clone`. + /// The fork shares codebooks, but has a fresh key and revision zero. + #[verus_spec(result => + requires history_wf(*self), + ensures result matches Ok(history) ==> history_wf(history) && clone_result(*self, history), + )] + pub fn try_clone(&self) -> Result { + self.try_clone_with(&mut Unmetered, &mut ObservationWorld) + } + + #[verus_spec(result => + requires history_wf(*self), + ensures result matches Ok(history) ==> history_wf(history) && clone_result(*self, history), + )] + pub(crate) fn try_clone_with( + &self, + limits: &mut L, + world: &mut ObservationWorld, + ) -> Result { + let mut events = Vec::new(); + allocation(world.try_reserve_vec_exact(&mut events, self.events.len()))?; + let mut numeric_events = Vec::new(); + allocation(world.try_reserve_vec_exact(&mut numeric_events, self.numeric.events.len()))?; + limits.enforce_memory()?; + let mut index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec(invariant index <= self.events@.len(), + events@ == self.events@.take(index as int), + numeric_events@ == self.numeric.events@.take(index as int), + history_wf(*self), + decreases self.events@.len() - index))] + while index < self.events.len() { + limits.checkpoint()?; + events.push(self.events[index]); + numeric_events.push(self.numeric.events[index]); + index += 1; + } + limits.enforce_memory()?; + proof_decl! { + let ghost copied = junco_core::verify::history_specs::HistoryStateView { + events: crate::store::verify::events_view(numeric_events@), revision: 0, + }; + let tracked lifecycle = Lifecycle::new(copied); + } + #[cfg(verus_keep_ghost)] + let (id, registration, global_registration) = self.store.allocate_history_id_for_resource( + verus_exec_expr! { Ghost(lifecycle.id()) }, + verus_exec_expr! { Tracked(Some(self.registration.borrow())) }, + )?; + #[cfg(not(verus_keep_ghost))] + let (id, _, _) = self + .store + .allocate_history_id_for_resource(Ghost::assume_new(), Tracked::assume_new())?; + // Move the copied buffer into the fresh record; no event is copied twice. + let numeric = StoredHistory { + events: numeric_events, + revision: 0, + id, + }; + proof! { reveal(::view); } + let clone = Self { + events, + numeric, + store: share_store(&self.store), + #[cfg(verus_keep_ghost)] + maps: self.maps, + #[cfg(verus_keep_ghost)] + lifecycle: verus_exec_expr! { Tracked(lifecycle) }, + #[cfg(verus_keep_ghost)] + registration, + #[cfg(verus_keep_ghost)] + global_registration, + }; + proof! { + assert(clone.events@ == self.events@); + assert(clone.numeric.events@ == self.numeric.events@); + assert(clone.numeric.revision == 0); + assert(clone.store == self.store); + assert(clone.numeric.id > self.numeric.id); + assert(history_wf(clone)); + assert(clone_result(*self, clone)); + } + Ok(clone) + } + + /// Returns the original committed events, including all payload fields and variants. + #[verus_spec(result => ensures result@ == raw_events(*self))] + pub fn as_slice(&self) -> &[E] { + &self.events + } + + /// Iterates the original committed events in order. + pub fn iter(&self) -> core::slice::Iter<'_, E> { + self.events.iter() + } + + /// Returns the number of committed events. + #[verus_spec(result => ensures result == raw_events(*self).len())] + pub fn len(&self) -> usize { + self.events.len() + } + + /// Returns whether the history is empty. + #[verus_spec(result => ensures result == (raw_events(*self).len() == 0))] + pub fn is_empty(&self) -> bool { + self.events.is_empty() + } + + /// Captures a reusable owner-specific length marker. + #[verus_spec(result => ensures checkpoint_matches(*self, result))] + pub fn checkpoint(&self) -> Checkpoint { + Checkpoint { + store_id: self.store.id(), + history: self.numeric.id, + len: self.events.len(), + } + } + + /// Returns the shared store binding this history's numeric events. + #[verus_spec(result => ensures *result == store_of(*self), + junco_core::verify::history_assumptions::arc_identity(*result) + == junco_core::verify::history_assumptions::arc_identity(store_of(*self)))] + pub fn store(&self) -> &Arc> { + &self.store + } +} + +impl fmt::Debug for History { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_tuple("History") + .field(&self.events) + .finish() + } +} + +impl PartialEq for History { + fn eq(&self, other: &Self) -> bool { + self.events == other.events + } +} + +impl Eq for History {} + +/// Finite observed codebook snapshots supporting the typed/numeric correspondence. +#[cfg(verus_keep_ghost)] +pub mod verify { + use super::*; + use history_syntax::{Arity, spec::events::event_view}; + use junco_core::verify::history_specs::{ + HistoryStateView, history_mutation, lemma_revision_chain_preserves_prefix, + }; + use vstd::prelude::*; + use vstd::resource::Loc; + use vstd::resource::map::{GhostMapAuth, GhostPersistentPointsTo}; + + verus! { + broadcast use {vstd::std_specs::vec::group_vec_axioms, vstd::seq::group_seq_lemmas}; + + pub open(super) spec fn stored_events(stored: &StoredHistory) -> Seq { stored.events@ } + + /// Failure-atomic numeric append, retaining record identity and lifecycle compatibility. + pub open spec fn stored_append_result(before: StoredHistory, after: StoredHistory, + events: Seq, result: Result<(), HistoryError>) -> bool { + after.spec_id() == before.spec_id() && after.spec_revision() == before.spec_revision() + && history_mutation(before@, after@) + && match result { + Ok(()) => stored_events(&after) == stored_events(&before) + events, + Err(_) => stored_events(&after) == stored_events(&before), + } + } + + /// Exact numeric truncation table; only a proper shrink consumes a revision. + pub open spec fn stored_truncate_result(before: StoredHistory, after: StoredHistory, + len: usize, result: Result<(), HistoryError>) -> bool { + after.spec_id() == before.spec_id() && history_mutation(before@, after@) + && if len >= stored_events(&before).len() { + result == Ok(()) && after@ == before@ + && stored_events(&after) == stored_events(&before) && after.spec_revision() == before.spec_revision() + } else if before.spec_revision() == u64::MAX { + result == Err(HistoryError::RevisionExhausted) && after@ == before@ + && stored_events(&after) == stored_events(&before) && after.spec_revision() == before.spec_revision() + } else { + result == Ok(()) && stored_events(&after) == stored_events(&before).take(len as int) + && after.spec_revision() == before.spec_revision() + 1 + } + } + + /// Expose every numeric truncate case and its public record observations. + pub proof fn lemma_stored_truncate_result_facts( + before: StoredHistory, after: StoredHistory, len: usize, result: Result<(), HistoryError>, + ) + requires stored_truncate_result(before, after, len, result), + ensures + after.spec_id() == before.spec_id(), history_mutation(before@, after@), + before@.events.len() == stored_events(&before).len(), + after@.events.len() == stored_events(&after).len(), + before@.revision == before.spec_revision() as nat, + after@.revision == after.spec_revision() as nat, + if len >= before@.events.len() { + result == Ok(()) && after@ == before@ + && stored_events(&after) == stored_events(&before) + && after.spec_revision() == before.spec_revision() + } else if before.spec_revision() == u64::MAX { + result == Err(HistoryError::RevisionExhausted) && after@ == before@ + && stored_events(&after) == stored_events(&before) + && after.spec_revision() == before.spec_revision() + } else { + result == Ok(()) + && stored_events(&after) == stored_events(&before).take(len as int) + && after@.events == before@.events.take(len as int) + && after.spec_revision() == before.spec_revision() + 1 + && after@.revision == before@.revision + 1 + }, + { + super::lemma_stored_history_view(before); + super::lemma_stored_history_view(after); + if len < stored_events(&before).len() && before.spec_revision() < u64::MAX { + assert(after@.events =~= before@.events.take(len as int)); + } + } + + + impl History { + pub open(super) spec fn lifecycle_model(&self) -> Lifecycle { self.lifecycle@ } + pub open(super) spec fn registration_model(&self) -> books::HistoryRegistration { self.registration@ } + pub open(super) spec fn global_registration_model(&self) -> crate::store::HistoryKeyReceipt { + self.global_registration@ + } + + pub proof fn lifecycle_ref(tracked &self) -> (tracked reference: &Lifecycle) + requires history_wf(*self), + ensures *reference == self.lifecycle_model(), + reference.wf(), reference.state() == (*self.spec_numeric())@, + reference.id() == self.registration_model().value(), + { self.lifecycle.borrow() } + + pub proof fn registration_ref(tracked &self) -> (tracked reference: &books::HistoryRegistration) + requires history_wf(*self), + ensures *reference == self.registration_model(), + reference.id() == books::registry_id::(&*store_of(*self)), + reference.key() == self.spec_id(), reference.value() == self.lifecycle_model().id(), + { self.registration.borrow() } + + pub(crate) proof fn history_key_receipt_ref(tracked &self) + -> (tracked reference: &crate::store::HistoryKeyReceipt) + requires history_wf(*self), + ensures *reference == self.global_registration_model(), + reference.id() == crate::store::verify::history_authority(), + reference.key() == self.spec_id(), + reference.value() == (crate::store::HistoryIssuer::Typed { + store: books::registry_id::(&*store_of(*self)), + lifecycle: self.lifecycle_model().id(), + }), + { self.global_registration.borrow() } + } + + pub proof fn lemma_history_wf(history: History) + requires history_wf(history), + ensures books::store_wf(*store_of(history)), + history.registration_model().id() == books::registry_id::(&*store_of(history)), + history.registration_model().key() == history.spec_id(), + history.spec_id() == history.spec_numeric().spec_id(), + raw_events(history).len() == stored_events(history.spec_numeric()).len(), + history.lifecycle_model().wf(), history.lifecycle_model().state() == (*history.spec_numeric())@, + history.lifecycle_model().id() == history.registration_model().value(), + junco_core::spec::hypotheses::event_obligations::() ==> books::maps_wf::(history_maps(history)) + && books::snapshot_published::(books::registry_id::(&*store_of(history)), history_maps(history)) + && correspondence(raw_events(history), stored_events(history.spec_numeric()), history_maps(history)), + { reveal(history_wf); } + + pub type Snapshot = GhostPersistentPointsTo; + + /// Only actual numeric transactions append to this ghost-only lifecycle ledger. + pub tracked struct Lifecycle { + pub(crate) authority: GhostMapAuth, + pub(crate) current: Snapshot, + pub(crate) ghost states: Seq, + } + + impl Lifecycle { + pub closed spec fn id(self) -> Loc { self.authority.id() } + + pub closed spec fn state(self) -> HistoryStateView { self.states.last() } + + pub closed spec fn wf(self) -> bool { + self.states.len() > 0 && self.states[0].revision <= u64::MAX + && (forall|i: nat| #[trigger] self.authority@.contains_key(i) == (i < self.states.len()) + && (i < self.states.len() ==> self.authority@[i] == self.states[i as int])) + && (forall|i: int| 0 < i < self.states.len() + ==> #[trigger] history_mutation(self.states[i - 1], self.states[i])) + && self.current.id() == self.id() && self.current.key() == self.states.len() - 1 + && self.current.value() == self.state() + } + + pub proof fn new(state: HistoryStateView) -> (tracked result: Self) + requires state.revision <= u64::MAX, + ensures result.wf(), result.state() == state, + { + let tracked (mut authority, empty) = GhostMapAuth::new(Map::::empty()); + let tracked current = authority.insert(0, state).persist(); + Self { authority, current, states: seq![state] } + } + + pub proof fn advance(tracked &mut self, next: HistoryStateView) + requires old(self).wf(), history_mutation(old(self).state(), next), + ensures final(self).wf(), final(self).id() == old(self).id(), final(self).state() == next, + { + let ghost previous = self.states; + let tracked current = self.authority.insert(previous.len(), next).persist(); + self.current = current; + self.states = previous.push(next); + assert forall|i: nat| self.authority@.contains_key(i) == (i < self.states.len()) + && (i < self.states.len() ==> self.authority@[i] == self.states[i as int]) by { + if i < previous.len() { assert(self.states[i as int] == previous[i as int]); } + } + assert forall|i: int| 0 < i < self.states.len() implies + #[trigger] history_mutation(self.states[i - 1], self.states[i]) by { + if i < previous.len() { + assert(history_mutation(previous[i - 1], previous[i])); + } else { + assert(self.states[i - 1] == previous.last()); + assert(self.states[i] == next); + } + } + } + + pub proof fn observe(tracked &self) -> (tracked result: Snapshot) + requires self.wf(), + ensures result.id() == self.id(), result.value() == self.state(), + { + self.current.duplicate() + } + + pub proof fn validate(tracked &self, tracked snapshot: &Snapshot) + requires self.wf(), snapshot.id() == self.id(), + ensures snapshot.value().revision <= self.state().revision, + snapshot.value().revision == self.state().revision + ==> snapshot.value().events.is_prefix_of(self.state().events), + { + snapshot.agree(&self.authority); + let index = snapshot.key(); + assert(index < self.states.len()); + assert(self.states[index as int] == snapshot.value()); + let suffix = self.states.subrange(index as int, self.states.len() as int); + assert(suffix.len() > 0); + assert(suffix.first() == snapshot.value()); + assert(suffix.last() == self.state()); + assert forall|i: int| 0 < i < suffix.len() implies + #[trigger] history_mutation(suffix[i - 1], suffix[i]) by { + assert(suffix[i - 1] == self.states[index + i - 1]); + assert(suffix[i] == self.states[index + i]); + assert(history_mutation(self.states[index + i - 1], self.states[index + i])); + } + lemma_revision_chain_preserves_prefix(suffix); + } + } + + pub open(super) spec fn raw_events(history: History) -> Seq { + history.events@ + } + + pub open(super) spec fn store_of(history: History) -> Arc> { + history.store + } + + pub open(super) spec fn initialized_history(history: History, store: Arc>) -> bool { + history.numeric.revision == 0 && history.store == store + } + + pub open(super) spec fn empty_history(history: History, store: Arc>) -> bool { + initialized_history(history, store) && history.events@ == Seq::::empty() + && history.numeric.events@ == Seq::::empty() + } + + pub open(super) spec fn checkpoint_matches(history: History, checkpoint: Checkpoint) -> bool { + checkpoint.store_id == books::store_id(*history.store) + && checkpoint.history == history.numeric.id && checkpoint.len == history.events@.len() + } + + pub open(super) spec fn rollback_result(before: History, after: History, + checkpoint: Checkpoint, result: Result<(), HistoryError>) -> bool { + history_wf(after) && owner_frame(before, after) && after.maps@ == before.maps@ + && (result is Err ==> state_frame(before, after)) + && if checkpoint.store_id != books::store_id(*before.store) || checkpoint.history != before.numeric.id { + result == Err(HistoryError::WrongCheckpointOwner) && state_frame(before, after) + } else if checkpoint.len > before.events@.len() { + result == Err(HistoryError::CheckpointBeyondHistory) && state_frame(before, after) + } else { + truncate_result(before, after, checkpoint.len, result) + } + } + + pub open spec fn correspondence( + raw: Seq, numeric: Seq, maps: books::ComponentMaps, + ) -> bool { + raw.len() == numeric.len() && forall|i: int| 0 <= i < raw.len() + ==> books::event_encoded::(maps, raw[i], numeric[i]) + } + + pub open(super) spec fn history_maps(history: History) -> books::ComponentMaps { + history.maps@ + } + + pub open(super) spec fn history_wf(history: History) -> bool { + books::store_wf(*history.store) + && history.registration@.id() == books::registry_id::(&*history.store) + && history.registration@.key() == history.numeric.id + && history.events@.len() == history.numeric.events@.len() + && history.lifecycle@.wf() && history.lifecycle@.state() == history.numeric@ + && history.lifecycle@.id() == history.registration@.value() + && history.global_registration@.id() == crate::store::verify::history_authority() + && history.global_registration@.key() == history.numeric.id + && history.global_registration@.value() == (crate::store::HistoryIssuer::Typed { + store: books::registry_id::(&*history.store), + lifecycle: history.lifecycle@.id(), + }) + && (junco_core::spec::hypotheses::event_obligations::() ==> books::maps_wf::(history.maps@) + && books::snapshot_published::(books::registry_id::(&history.store), history.maps@) + && correspondence(history.events@, history.numeric.events@, history.maps@)) + } + + pub open spec fn raw_event(event: E) + -> Seq + { + event_view(event) + } + + pub open spec fn raw_word(history: History) + -> Seq> + { + raw_events(history).map(|i: int, event: E| raw_event(event)) + } + + pub open(super) spec fn owner_frame(before: History, after: History) -> bool { + after.store == before.store && after.numeric.id == before.numeric.id + && after.lifecycle@.id() == before.lifecycle@.id() + && after.global_registration@.id() == before.global_registration@.id() + && after.global_registration@.key() == before.global_registration@.key() + && after.global_registration@.value() == before.global_registration@.value() + } + + pub open(super) spec fn state_frame(before: History, after: History) -> bool { + owner_frame(before, after) && after.events@ == before.events@ + && after.numeric.events@ == before.numeric.events@ + && after.numeric.revision == before.numeric.revision + } + + pub open(super) spec fn push_result( + before: History, after: History, event: E, result: Result<(), HistoryError>, + ) -> bool { + history_wf(after) && owner_frame(before, after) + && (junco_core::spec::hypotheses::event_obligations::() ==> junco_core::verify::history_specs::no_invariant_failure(result)) + && after.numeric.revision == before.numeric.revision + && junco_core::verify::history_specs::history_mutation(before.numeric@, after.numeric@) + && (junco_core::spec::hypotheses::event_obligations::() ==> books::maps_extend::(before.maps@, after.maps@)) + && match result { + Err(_) => state_frame(before, after), + Ok(()) => after.events@ == before.events@.push(event) + && after.numeric.events@.len() > 0 + && stored_append_result(before.numeric, after.numeric, + seq![after.numeric.events@.last()], result), + } + } + + pub proof fn lemma_state_frame_facts(before: History, after: History) + requires state_frame(before, after), + ensures raw_events(after) == raw_events(before), store_of(after) == store_of(before), + stored_events(after.spec_numeric()) == stored_events(before.spec_numeric()), + after.spec_numeric().spec_revision() == before.spec_numeric().spec_revision(), + {} + + pub proof fn lemma_checkpoint_matches(history: History, checkpoint: Checkpoint) + requires checkpoint_matches(history, checkpoint), + ensures checkpoint_owned(history, checkpoint), checkpoint_len(checkpoint) == raw_events(history).len(), + {} + + pub proof fn lemma_checkpoint_owner_preserved(before: History, after: History, checkpoint: Checkpoint) + requires owner_frame(before, after), + ensures checkpoint_owned(before, checkpoint) == checkpoint_owned(after, checkpoint), + {} + + pub proof fn lemma_distinct_checkpoint_owner(left: History, right: History, checkpoint: Checkpoint) + requires checkpoint_matches(left, checkpoint), books::store_id(*store_of(left)) != books::store_id(*store_of(right)), + ensures !checkpoint_owned(right, checkpoint), + {} + + /// Boundary harness for the exact numeric table, not a forged reachable typed lifecycle. + #[doc(hidden)] + pub fn revision_boundary_record(id: usize, events: Vec) -> (stored: StoredHistory) + ensures stored.spec_id() == id, stored.spec_revision() == u64::MAX, + stored_events(&stored) == events@, + { StoredHistory { id, revision: u64::MAX, events } } + + #[doc(hidden)] + pub fn truncate_boundary_record(stored: &mut StoredHistory, len: usize) -> (result: Result<(), HistoryError>) + ensures stored_truncate_result(*old(stored), *final(stored), len, result), + { stored.truncate_events(len) } + + pub proof fn lemma_initialized_history_facts(history: History, store: Arc>) + requires initialized_history(history, store), + ensures store_of(history) == store, history.spec_numeric().spec_revision() == 0, + {} + + pub proof fn lemma_clone_facts(before: History, after: History, checkpoint: Checkpoint) + requires clone_result(before, after), checkpoint_matches(before, checkpoint), + ensures raw_events(after) == raw_events(before), store_of(after) == store_of(before), + after.spec_numeric().spec_revision() == 0, after.spec_id() != before.spec_id(), + !checkpoint_owned(after, checkpoint), + {} + + pub proof fn lemma_empty_history(history: History, store: Arc>) + requires history_wf(history), empty_history(history, store), + ensures raw_events(history) == Seq::::empty(), store_of(history) == store, + books::store_wf(*store), history.spec_numeric().spec_revision() == 0, + {} + + pub proof fn lemma_push_result(before: History, after: History, event: E, + result: Result<(), HistoryError>) + requires push_result(before, after, event, result), + ensures history_wf(after), owner_frame(before, after), store_of(after) == store_of(before), + after.spec_numeric().spec_revision() == before.spec_numeric().spec_revision(), + junco_core::spec::hypotheses::event_obligations::() ==> junco_core::verify::history_specs::no_invariant_failure(result), + result is Err ==> state_frame(before, after), + result is Ok ==> raw_events(after) == raw_events(before).push(event), + {} + + pub proof fn lemma_state_frame_transitive(before: History, middle: History, after: History) + requires state_frame(before, middle), state_frame(middle, after), + ensures state_frame(before, after), + {} + + pub proof fn lemma_history_frame_facts(before: History, after: History) + ensures state_frame(before, before), owner_frame(before, before), + owner_frame(before, after) ==> store_of(before) == store_of(after), + state_frame(before, after) ==> raw_events(before) == raw_events(after), + history_wf(before) ==> books::store_wf(*store_of(before)), + {} + + pub closed spec fn checkpoint_owned(history: History, checkpoint: Checkpoint) -> bool { + checkpoint.store_id == books::store_id(*history.store) && checkpoint.history == history.numeric.id + } + pub closed spec fn checkpoint_len(checkpoint: Checkpoint) -> usize { checkpoint.len } + + pub proof fn lemma_rollback_result(before: History, after: History, checkpoint: Checkpoint, + result: Result<(), HistoryError>) + requires history_wf(after), rollback_result(before, after, checkpoint, result), + ensures owner_frame(before, after), store_of(before) == store_of(after), + history_maps(after) == history_maps(before), + result is Err ==> state_frame(before, after), + !checkpoint_owned(before, checkpoint) ==> result == Err(HistoryError::WrongCheckpointOwner), + checkpoint_owned(before, checkpoint) && checkpoint_len(checkpoint) > raw_events(before).len() + ==> result == Err(HistoryError::CheckpointBeyondHistory), + checkpoint_owned(before, checkpoint) && checkpoint_len(checkpoint) <= raw_events(before).len() + ==> truncate_result(before, after, checkpoint_len(checkpoint), result), + checkpoint_owned(before, checkpoint) && checkpoint_len(checkpoint) == raw_events(before).len() + ==> result == Ok(()) && state_frame(before, after), + checkpoint_owned(before, checkpoint) && checkpoint_len(checkpoint) < raw_events(before).len() + && before.spec_numeric().spec_revision() == u64::MAX + ==> result == Err(HistoryError::RevisionExhausted) && state_frame(before, after), + checkpoint_owned(before, checkpoint) && checkpoint_len(checkpoint) < raw_events(before).len() + && before.spec_numeric().spec_revision() < u64::MAX + ==> result == Ok(()) && raw_events(after) == raw_events(before).take(checkpoint_len(checkpoint) as int) + && stored_events(after.spec_numeric()) == stored_events(before.spec_numeric()).take(checkpoint_len(checkpoint) as int) + && after.spec_numeric().spec_revision() == before.spec_numeric().spec_revision() + 1, + { + if checkpoint_owned(before, checkpoint) && checkpoint_len(checkpoint) <= raw_events(before).len() { + lemma_truncate_result(before, after, checkpoint_len(checkpoint), result); + } + } + + pub open(super) spec fn truncate_result( + before: History, after: History, len: usize, result: Result<(), HistoryError>, + ) -> bool { + history_wf(before) && history_wf(after) && owner_frame(before, after) && after.maps@ == before.maps@ + && stored_truncate_result(before.numeric, after.numeric, len, result) + && if result is Err || len >= before.events@.len() { + state_frame(before, after) + } else { + after.events@ == before.events@.take(len as int) + } + } + + pub proof fn lemma_truncate_result(before: History, after: History, len: usize, + result: Result<(), HistoryError>) + requires truncate_result(before, after, len, result), + ensures history_wf(after), owner_frame(before, after), store_of(before) == store_of(after), + history_maps(after) == history_maps(before), + stored_truncate_result(*before.spec_numeric(), *after.spec_numeric(), len, result), + result is Err ==> state_frame(before, after), + len >= raw_events(before).len() ==> result == Ok(()) && state_frame(before, after), + len < raw_events(before).len() && before.spec_numeric().spec_revision() == u64::MAX + ==> result == Err(HistoryError::RevisionExhausted) && state_frame(before, after), + len < raw_events(before).len() && before.spec_numeric().spec_revision() < u64::MAX + ==> result == Ok(()) && raw_events(after) == raw_events(before).take(len as int) + && stored_events(after.spec_numeric()) == stored_events(before.spec_numeric()).take(len as int) + && after.spec_numeric().spec_revision() == before.spec_numeric().spec_revision() + 1, + { + reveal(History::spec_numeric); + reveal(StoredHistory::spec_revision); + reveal(history_wf); + lemma_stored_truncate_result_facts(before.numeric, after.numeric, len, result); + } + + pub open(super) spec fn clone_result(before: History, after: History) -> bool { + history_wf(after) && after.store == before.store && after.numeric.id > before.numeric.id + && after.events@ == before.events@ && after.numeric.events@ == before.numeric.events@ + && after.numeric.revision == 0 && after.maps@ == before.maps@ + } + + pub proof fn lemma_clone_raw_word(before: History, after: History) + requires clone_result(before, after), + ensures raw_word(after) == raw_word(before), after.spec_id() != before.spec_id(), + {} + + pub(crate) proof fn lemma_foreign_store_checkpoint( + source: History, target: History, checkpoint: Checkpoint, + tracked source_receipt: &crate::typed::StoreIdReceipt, + tracked target_receipt: &crate::typed::StoreIdReceipt, + ) + requires history_wf(source), history_wf(target), checkpoint_matches(source, checkpoint), + source_receipt.id() == target_receipt.id(), + source_receipt.id() == source.store.store_id_receipt@.id(), + source_receipt.key() == books::store_id(*source.store), + target_receipt.key() == books::store_id(*target.store), + source_receipt.value() == books::registry_id::(&*source.store), + target_receipt.value() == books::registry_id::(&*target.store), + books::registry_id::(&*source.store) != books::registry_id::(&*target.store), + ensures checkpoint.store_id != books::store_id(*target.store), + { + books::lemma_store_receipts_distinct( + books::registry_id::(&*source.store), books::registry_id::(&*target.store), + source_receipt, target_receipt, + ); + } + + pub(crate) fn independently_constructed_foreign_rollback_client() + -> (result: Result<(History, Ghost>, Result<(), HistoryError>), HistoryError>) + ensures result matches Ok((target, before, rollback)) ==> history_wf(target) + && state_frame(before@, target) + && rollback == Err(HistoryError::WrongCheckpointOwner), + { + let mut source_store = Store::::new()?; + let target_store = Store::::new()?; + proof { + books::lemma_registry_births_distinct( + source_store.registry_birth.borrow_mut(), target_store.registry_birth.borrow(), + ); + books::lemma_store_receipts_distinct( + source_store.history_registry@, target_store.history_registry@, + source_store.store_id_receipt.borrow(), target_store.store_id_receipt.borrow(), + ); + assert(books::store_wf(source_store)); + assert(books::store_wf(target_store)); + assert(source_store.history_registry@ != target_store.history_registry@); + assert(books::store_id(source_store) != books::store_id(target_store)); + } + let source_store = Arc::new(source_store); + let target_store = Arc::new(target_store); + let source = History::new(source_store)?; + let mut target = History::new(target_store)?; + let checkpoint = source.checkpoint(); + proof { + lemma_foreign_store_checkpoint( + source, target, checkpoint, + source.store.store_id_receipt_ref(), target.store.store_id_receipt_ref(), + ); + } + let ghost before = target; + let rollback = target.rollback(checkpoint); + proof { + assert(rollback == Err(HistoryError::WrongCheckpointOwner)); + assert(state_frame(before, target)); + } + Ok((target, Ghost(before), rollback)) + } + + pub(crate) fn byte_typed_history_key_client( + store: Arc>, limits: &mut L, world: &mut ObservationWorld, + ) -> (result: Result<(crate::store::HistoryHandle, History), HistoryError>) + requires books::store_wf(*store), + ensures result matches Ok((byte, typed)) ==> crate::store::verify::handle_wf(byte) + && history_wf(typed) + && crate::store::verify::handle_index(byte) != typed.spec_id(), + { + let owner = crate::store::HistoryStore::new(E::Arity::value()); + let byte = owner.new_history(limits, world)?; + let typed = History::new(store)?; + proof { + let tracked byte_receipt = byte.history_key_receipt_ref(); + let tracked typed_receipt = typed.history_key_receipt_ref(); + let tracked mut duplicate = byte_receipt.duplicate(); + duplicate.intersection_agrees(typed_receipt); + assert(byte_receipt.value() != typed_receipt.value()); + assert(crate::store::verify::handle_index(byte) != typed.spec_id()); + } + Ok((byte, typed)) + } + + pub(crate) fn same_store_fork_receipt_client(source: &History) + -> (result: Result, HistoryError>) + requires history_wf(*source), + ensures result matches Ok(fork) ==> clone_result(*source, fork) + && fork.global_registration@.id() == source.global_registration@.id() + && fork.global_registration@.key() != source.global_registration@.key(), + { + let fork = source.try_clone()?; + proof { + let tracked source_receipt = source.history_key_receipt_ref(); + let tracked fork_receipt = fork.history_key_receipt_ref(); + assert(source_receipt.id() == fork_receipt.id()); + assert(source_receipt.key() < fork_receipt.key()); + } + Ok(fork) + } + + pub proof fn lemma_correspondence_extends( + raw: Seq, numeric: Seq, before: books::ComponentMaps, after: books::ComponentMaps, + ) + requires correspondence(raw, numeric, before), books::maps_extend::(before, after), + ensures correspondence(raw, numeric, after), + { + assert forall|i: int| 0 <= i < raw.len() implies + books::event_encoded::(after, raw[i], numeric[i]) by { + books::lemma_event_extension::(before, after, raw[i], numeric[i]); + } + } + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + use crate::store::HistoryStore; + use junco_core::limits::{LimitError, Unmetered}; + + struct FailMemory { + observations: usize, + fail_at: usize, + } + + impl Limits for FailMemory { + fn checkpoint(&mut self) -> Result<(), LimitError> { + Ok(()) + } + fn publication_checkpoint(&mut self) -> Result<(), LimitError> { + Ok(()) + } + fn enforce_memory(&mut self) -> Result<(), LimitError> { + self.observations = self.observations.saturating_add(1); + if self.observations == self.fail_at { + Err(LimitError::MemoryLimitExceeded { usage: 1, limit: 0 }) + } else { + Ok(()) + } + } + } + + fn fresh_key() -> usize { + HistoryStore::new(3) + .allocate_history_after(0, Ghost::assume_new(), Tracked::assume_new()) + .unwrap() + .0 + } + + fn event() -> Event { + let store = HistoryStore::new(3); + let mut slots = [0; 3]; + for (index, bytes) in [b"alice".as_slice(), b"edit".as_slice(), b"doc".as_slice()] + .into_iter() + .enumerate() + { + slots[index] = store + .intern( + history_syntax::Component::new(index), + bytes, + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + } + Event::from_encoded(&slots) + } + + #[test] + fn append_memory_failures_preserve_sequence_and_revision() { + let event = event(); + let mut stored = StoredHistory::new(fresh_key()); + stored + .append_events(&[event], &mut Unmetered, &mut ObservationWorld) + .unwrap(); + for fail_at in [1, 2] { + let mut limits = FailMemory { + observations: 0, + fail_at, + }; + assert!(matches!( + stored.append_events(&[event, event], &mut limits, &mut ObservationWorld), + Err(HistoryError::Limit(_)) + )); + assert_eq!(stored.events, [event]); + assert_eq!(stored.len(), 1); + assert_eq!(stored.revision(), 0); + } + stored + .append_events(&[event], &mut Unmetered, &mut ObservationWorld) + .unwrap(); + assert_eq!(stored.events, [event, event]); + assert_eq!(stored.revision(), 0); + } + + #[test] + fn truncate_revision_exhaustion_fails_before_mutation() { + let event = event(); + let mut stored = StoredHistory::new(fresh_key()); + stored + .append_events(&[event, event], &mut Unmetered, &mut ObservationWorld) + .unwrap(); + stored.revision = u64::MAX; + assert!(matches!( + stored.truncate_events(1), + Err(HistoryError::RevisionExhausted) + )); + assert_eq!(stored.events, [event, event]); + assert_eq!(stored.revision(), u64::MAX); + stored.truncate_events(2).unwrap(); + stored.truncate_events(3).unwrap(); + assert_eq!(stored.events, [event, event]); + assert_eq!(stored.revision(), u64::MAX); + } +} + +#[cfg(test)] +mod typed_tests { + use super::*; + use core::time::Duration; + use junco_core::limits::LimitError; + use junco_core::observation::fail_reservations_after; + + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] + struct Actor(u32); + + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] + struct Path(u32); + + impl history_syntax::KeyHash for Actor { + fn key_hash(&self) -> u64 { + history_syntax::key_hash::hash_via_std(self) + } + } + + impl history_syntax::KeyHash for Path { + fn key_hash(&self) -> u64 { + history_syntax::key_hash::hash_via_std(self) + } + } + + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] + struct TestEvent { + actor: Actor, + path: Path, + } + + impl TypedEvent for TestEvent { + type Component = history_syntax::Component3; + type Arity = history_syntax::N3; + + fn component(self, index: usize) -> Self::Component { + (self.actor, (), self.path).component(index) + } + + fn coordinate(component: Self::Component) -> usize { + <(Actor, (), Path) as TypedEvent>::coordinate(component) + } + } + + fn read(actor: Actor) -> TestEvent { + TestEvent { + actor, + path: Path(0), + } + } + + fn store() -> Arc> { + Arc::new(Store::new().unwrap()) + } + + fn assert_unchanged( + history: &History, + raw: &[TestEvent], + numeric: &[Event], + revision: u64, + ) { + assert_eq!(history.as_slice(), raw); + assert_eq!(history.numeric.events, numeric); + assert_eq!(history.numeric.revision, revision); + } + + #[test] + fn clone_is_an_equal_new_owner_at_revision_zero() { + let store = store(); + let mut original = History::from_events( + store.clone(), + [read(Actor(1)), read(Actor(2)), read(Actor(3))], + ) + .unwrap(); + original.truncate(2).unwrap(); + assert_eq!(original.numeric.revision, 1); + + let clone = original.try_clone().unwrap(); + assert_eq!(clone, original); + assert_ne!(clone.id(), original.id()); + assert_eq!(clone.numeric.revision, 0); + assert_eq!(clone.numeric.events, original.numeric.events); + assert!(Arc::ptr_eq(clone.store(), original.store())); + + let other_owner = History::from_events(self::store(), original.iter().copied()).unwrap(); + assert_eq!(other_owner, original); + assert_eq!( + alloc::format!("{:?}", clone), + alloc::format!("{:?}", original) + ); + } + + #[test] + fn only_real_shortening_advances_the_revision() { + let mut history = History::new(store()).unwrap(); + let empty = history.checkpoint(); + history.push(read(Actor(1))).unwrap(); + history.push(read(Actor(2))).unwrap(); + assert_eq!(history.numeric.revision, 0); + + history.truncate(2).unwrap(); + history.truncate(5).unwrap(); + history.rollback(history.checkpoint()).unwrap(); + assert_eq!(history.numeric.revision, 0); + + history.truncate(1).unwrap(); + assert_eq!(history.numeric.revision, 1); + assert_eq!(history.as_slice(), [read(Actor(1))]); + + history.push(read(Actor(3))).unwrap(); + assert_eq!(history.numeric.revision, 1); + history.rollback(empty).unwrap(); + assert_eq!(history.numeric.revision, 2); + assert!(history.is_empty()); + assert!(history.numeric.events.is_empty()); + } + + #[test] + fn byte_and_typed_records_share_one_key_space() { + use crate::store::HistoryStore; + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] + struct Other(u8); + impl TypedEvent for Other { + type Component = history_syntax::Component3; + type Arity = history_syntax::N3; + + fn component(self, index: usize) -> Self::Component { + (self.0, self.0, self.0).component(index) + } + + fn coordinate(component: Self::Component) -> usize { + <(u8, u8, u8) as TypedEvent>::coordinate(component) + } + } + let bytes = HistoryStore::new(3); + let byte_first = bytes + .new_history(&mut Unmetered, &mut ObservationWorld) + .unwrap(); + let byte_second = bytes + .new_history(&mut Unmetered, &mut ObservationWorld) + .unwrap(); + let view = store(); + let first = History::new(view.clone()).unwrap(); + let second = History::new(view.clone()).unwrap(); + let from_events = History::from_events(view.clone(), [read(Actor(1))]).unwrap(); + let fork = from_events.try_clone().unwrap(); + let other_view = History::new(store()).unwrap(); + let other_event = + History::from_events(Arc::new(Store::new().unwrap()), [Other(1)]).unwrap(); + assert!(Arc::ptr_eq(view.numeric_store(), &bytes)); + assert!(Arc::ptr_eq(other_event.store().numeric_store(), &bytes)); + assert_eq!( + bytes.history_record(&byte_first).unwrap().read().id(), + byte_first.index() + ); + assert_eq!(fork.numeric().id(), fork.id()); + let keys = [ + byte_first.index(), + byte_second.index(), + first.id(), + second.id(), + from_events.id(), + fork.id(), + other_view.id(), + other_event.id(), + ]; + let distinct: alloc::collections::BTreeSet<_> = keys.iter().copied().collect(); + assert_eq!(distinct.len(), keys.len()); + assert!(keys.iter().all(|key| *key > 0)); + } + + struct FailLimits { + checkpoint: bool, + memory_calls: usize, + fail_memory_at: usize, + } + + impl Limits for FailLimits { + fn checkpoint(&mut self) -> Result<(), LimitError> { + if self.checkpoint { + Err(LimitError::TimeLimitExceeded { + elapsed: Duration::from_secs(1), + limit: Duration::ZERO, + }) + } else { + Ok(()) + } + } + fn publication_checkpoint(&mut self) -> Result<(), LimitError> { + Ok(()) + } + fn enforce_memory(&mut self) -> Result<(), LimitError> { + self.memory_calls = self.memory_calls.saturating_add(1); + if self.memory_calls == self.fail_memory_at { + Err(LimitError::MemoryLimitExceeded { usage: 1, limit: 0 }) + } else { + Ok(()) + } + } + } + + #[test] + fn append_reservation_failures_preserve_both_sequences_and_revision() { + // Raw reservation, a new principal, then numeric reservation are separate failure leaves. + for successful_reservations in 0..3 { + let mut history = History::from_events(store(), [read(Actor(1))]).unwrap(); + let numeric = history.numeric.events.clone(); + { + let _failure = fail_reservations_after(successful_reservations); + assert!(matches!( + history.push(read(Actor(2))), + Err(HistoryError::AllocationFailed) + )); + } + assert_unchanged(&history, &[read(Actor(1))], &numeric, 0); + history.push(read(Actor(2))).unwrap(); + assert_eq!(history.as_slice(), [read(Actor(1)), read(Actor(2))]); + assert_eq!(history.numeric.events.len(), 2); + assert_eq!(history.numeric.revision, 0); + } + } + + #[test] + fn append_checkpoint_and_memory_failures_preserve_both_sequences() { + let mut history = History::from_events(store(), [read(Actor(1))]).unwrap(); + let numeric = history.numeric.events.clone(); + for (checkpoint, fail_memory_at) in [(true, 0), (false, 1), (false, 2)] { + let mut limits = FailLimits { + checkpoint, + memory_calls: 0, + fail_memory_at, + }; + assert!(matches!( + history.push_with(read(Actor(2)), &mut limits, &mut ObservationWorld), + Err(HistoryError::Limit(_)) + )); + assert_unchanged(&history, &[read(Actor(1))], &numeric, 0); + } + history.push(read(Actor(2))).unwrap(); + assert_eq!(history.len(), 2); + } + + #[test] + fn clone_failures_never_modify_the_original() { + let history = History::from_events(store(), [read(Actor(1)), read(Actor(2))]).unwrap(); + let numeric = history.numeric.events.clone(); + for successful_reservations in [0, 1] { + let _failure = fail_reservations_after(successful_reservations); + assert!(matches!( + history.try_clone(), + Err(HistoryError::AllocationFailed) + )); + assert_unchanged(&history, &[read(Actor(1)), read(Actor(2))], &numeric, 0); + } + for (checkpoint, fail_memory_at) in [(true, 0), (false, 1), (false, 2)] { + let mut limits = FailLimits { + checkpoint, + memory_calls: 0, + fail_memory_at, + }; + assert!(matches!( + history.try_clone_with(&mut limits, &mut ObservationWorld), + Err(HistoryError::Limit(_)) + )); + assert_unchanged(&history, &[read(Actor(1)), read(Actor(2))], &numeric, 0); + } + } + + #[test] + fn invalid_checkpoints_and_revision_exhaustion_fail_before_mutation() { + let store = store(); + let mut history = + History::from_events(store.clone(), [read(Actor(1)), read(Actor(2))]).unwrap(); + let future = history.checkpoint(); + history.truncate(1).unwrap(); + let numeric = history.numeric.events.clone(); + let foreign = History::from_events(store, [read(Actor(1)), read(Actor(2))]) + .unwrap() + .checkpoint(); + let foreign_store = History::from_events(self::store(), [read(Actor(1)), read(Actor(2))]) + .unwrap() + .checkpoint(); + for checkpoint in [foreign, foreign_store] { + assert_eq!( + history.rollback(checkpoint), + Err(HistoryError::WrongCheckpointOwner) + ); + assert_unchanged(&history, &[read(Actor(1))], &numeric, 1); + } + assert_eq!( + history.rollback(future), + Err(HistoryError::CheckpointBeyondHistory) + ); + assert_unchanged(&history, &[read(Actor(1))], &numeric, 1); + + history.numeric.revision = u64::MAX; + assert_eq!(history.truncate(0), Err(HistoryError::RevisionExhausted)); + assert_unchanged(&history, &[read(Actor(1))], &numeric, u64::MAX); + history.truncate(1).unwrap(); + history.truncate(usize::MAX).unwrap(); + history.rollback(history.checkpoint()).unwrap(); + assert_unchanged(&history, &[read(Actor(1))], &numeric, u64::MAX); + let clone = history.try_clone().unwrap(); + assert_eq!(clone.numeric.revision, 0); + assert_eq!(clone.numeric.events, numeric); + assert_ne!(clone.id(), history.id()); + } +} + +#[cfg(test)] +mod typed_copy_tests { + use super::*; + use core::sync::atomic::{AtomicUsize, Ordering}; + + static PROJECTIONS: AtomicUsize = AtomicUsize::new(0); + + #[derive(Copy, Debug, PartialEq, Eq, Hash)] + struct CopyOnly(u8); + + #[allow( + clippy::non_canonical_clone_impl, + reason = "Regression fixture rejects user Clone calls; production forks copy Copy events" + )] + impl Clone for CopyOnly { + fn clone(&self) -> Self { + panic!("a history fork must copy events, not invoke user Clone") + } + } + + impl TypedEvent for CopyOnly { + type Component = history_syntax::Component3; + type Arity = history_syntax::N3; + + fn component(self, index: usize) -> Self::Component { + PROJECTIONS.fetch_add(1, Ordering::Relaxed); + (self.0, self.0, self.0).component(index) + } + + fn coordinate(component: Self::Component) -> usize { + <(u8, u8, u8) as TypedEvent>::coordinate(component) + } + } + + #[test] + fn fork_copies_both_sequences_without_projection_or_user_clone() { + let store = Arc::new(Store::new().unwrap()); + let mut history = History::from_events(store, [CopyOnly(1), CopyOnly(2)]).unwrap(); + PROJECTIONS.store(0, Ordering::Relaxed); + let clone = history.try_clone().unwrap(); + assert_eq!(PROJECTIONS.load(Ordering::Relaxed), 0); + assert_eq!(clone.as_slice(), history.as_slice()); + assert_eq!(clone.numeric.events, history.numeric.events); + assert_eq!( + history.rollback(clone.checkpoint()), + Err(HistoryError::WrongCheckpointOwner) + ); + assert_eq!(history.len(), 2); + assert_eq!(history.numeric.revision, 0); + } +} + +#[cfg(test)] +mod arity_tests { + use super::*; + use crate::store::HistoryStore; + use alloc::collections::BTreeSet; + + #[test] + fn history_keys_do_not_alias_across_event_arities() { + let mut keys = BTreeSet::new(); + for arity in 1..=history_syntax::MAX_ARITY { + let store = HistoryStore::new(arity); + let history = store + .new_history(&mut Unmetered, &mut ObservationWorld) + .unwrap(); + assert!(keys.insert(history.index())); + } + let pair = History::from_events(Arc::new(Store::new().unwrap()), [(1_u8, 2_u8)]).unwrap(); + let quartet = + History::from_events(Arc::new(Store::new().unwrap()), [(1_u8, 2_u8, 3_u8, 4_u8)]) + .unwrap(); + assert!(keys.insert(pair.id())); + assert!(keys.insert(quartet.id())); + assert_eq!(pair.numeric.events[0].arity(), 2); + assert_eq!(quartet.numeric.events[0].arity(), 4); + } +} diff --git a/src/history-store/src/keyed.rs b/src/history-store/src/keyed.rs new file mode 100644 index 000000000..87a09371f --- /dev/null +++ b/src/history-store/src/keyed.rs @@ -0,0 +1,213 @@ +//! Verified `eq_spec`-keyed map: entries in insertion order behind a chained hash index on +//! `KeyHash::key_hash`. Under `key_laws` `find` is a lookup on `eq_spec` classes, by proof; +//! nothing here assumes anything about `std::hash::Hash`. +//! +//! Keys are user component types, so user `Eq`/`KeyHash` code runs under the store lock. A panic +//! there unwinds through the lock and is outside the trusted base: Verus assumes the lock +//! invariant on re-entry, and the contracts below hold only for code that returns. + +use alloc::vec::Vec; +use hashconsius::index::Buckets; +use history_syntax::KeyHash; +#[cfg(verus_keep_ghost)] +use history_syntax::key_hash::specs::KeyHashSpec; +use junco_core::errors::HistoryError; +#[cfg(verus_keep_ghost)] +use junco_core::spec::hypotheses::key_laws; +use vstd::prelude::*; +#[cfg(verus_keep_ghost)] +use vstd::std_specs::cmp::PartialEqSpec; + +verus! { + +broadcast use vstd::std_specs::vec::group_vec_axioms; + +/// `index` is `None` only while the map is empty, so `new` allocates nothing and mutation can +/// swap the whole table out (Verus checks the type invariant after every `&mut` field call). +pub struct KeyedMap { + entries: Vec<(K, V)>, + hashes: Vec, + index: Option, +} + +impl View for KeyedMap { + type V = Seq<(K, V)>; + closed spec fn view(&self) -> Seq<(K, V)> { self.entries@ } +} + +impl KeyedMap { + #[verifier::type_invariant] + closed spec fn inv(&self) -> bool { + &&& self.hashes@.len() == self.entries@.len() + &&& match self.index { + Some(index) => index.inv(self.hashes@), + None => self.entries@.len() == 0, + } + &&& K::obeys_hash_spec() ==> forall|j: int| 0 <= j < self.entries@.len() + ==> #[trigger] self.hashes@[j] == self.entries@[j].0.hash_spec() + } + + #[allow(clippy::new_without_default)] + pub fn new() -> (m: Self) + ensures m@ == Seq::<(K, V)>::empty(), + { + Self { entries: Vec::new(), hashes: Vec::new(), index: None } + } + + /// Index of an entry whose key is `eq_spec`-equal to `key`, if any. + pub fn find(&self, key: &K) -> (r: Option) + ensures + r matches Some(i) ==> i < self@.len(), + key_laws::() ==> match r { + Some(i) => key.eq_spec(&self@[i as int].0), + None => forall|i: int| 0 <= i < self@.len() ==> !key.eq_spec(&self@[i].0), + }, + { + proof { use_type_invariant(&*self); } + let index = match &self.index { + Some(index) => index, + None => { return None; }, + }; + let h = key.key_hash(); + proof { + index.lemma_nonempty(self.hashes@); + vstd::std_specs::vec::axiom_spec_len(&self.entries); + } + let bucket = index.bucket(h); + let mut j = 0; + while j < bucket.len() + invariant + self.inv(), self.index == Some(*index), index.nb() > 0, self@.len() <= usize::MAX, + K::obeys_hash_spec() ==> h == key.hash_spec(), + bucket@ == index.bucket_of(h), + 0 <= j <= bucket@.len(), + forall|k: int| 0 <= k < j ==> (#[trigger] bucket@[k].1 < self@.len() + && (K::obeys_eq_spec() + ==> !(bucket@[k].0 == h && key.eq_spec(&self@[bucket@[k].1 as int].0)))), + decreases bucket@.len() - j, + { + let (bh, u) = bucket[j]; + proof { index.lemma_sound(self.hashes@, h, j as int); } + if bh == h && *key == self.entries[u].0 { + return Some(u); + } + j += 1; + } + proof { + if key_laws::() { + assert forall|i: int| 0 <= i < self@.len() implies !key.eq_spec(&self@[i].0) by { + if key.eq_spec(&self@[i].0) { + assert(self.hashes@[i] == self@[i].0.hash_spec()); + assert(self.hashes@[i] == h); + index.lemma_complete(self.hashes@, i); + let k = bucket@.lemma_contains_to_index((h, i as usize)); + assert(bucket@[k].0 == h && key.eq_spec(&self@[bucket@[k].1 as int].0)); + } + } + } + } + None + } + + pub fn get(&self, key: &K) -> (r: Option<&V>) + ensures key_laws::() ==> match r { + Some(v) => exists|i: int| 0 <= i < self@.len() && *v == self@[i].1 + && key.eq_spec(&self@[i].0), + None => forall|i: int| 0 <= i < self@.len() ==> !key.eq_spec(&self@[i].0), + }, + { + match self.find(key) { + Some(i) => Some(&self.entries[i].1), + None => None, + } + } + + pub fn at(&self, i: usize) -> (r: &(K, V)) + requires i < self@.len(), + ensures *r == self@[i as int], + { + &self.entries[i] + } + + /// Appends an entry. No freshness precondition: holders prove their own no-duplicate facts + /// from `find`'s `None` case. `Buckets` growth aborts on OOM (hashconsius's failure model); + /// call `reserve_one` first for the entry storage. + // `verus!` expands the destructuring pattern to `entries: entries`. + #[allow(non_shorthand_field_patterns)] + pub fn insert_fresh(&mut self, key: K, value: V) + ensures final(self)@ == old(self)@.push((key, value)), + { + proof { use_type_invariant(&*self); } + let h = key.key_hash(); + let mut table = Self { entries: Vec::new(), hashes: Vec::new(), index: None }; + core::mem::swap(self, &mut table); + let Self { entries, hashes, index } = table; + let mut entries = entries; + let mut hashes = hashes; + let ghost hs = hashes@; + let mut index = match index { + Some(index) => index, + None => { + proof { assert(hs =~= Seq::::empty()); } + Buckets::new(16) + }, + }; + let uid = entries.len(); + entries.push((key, value)); + hashes.push(h); + proof { vstd::std_specs::vec::axiom_spec_len(&hashes); } + index.insert(h, uid, Ghost(hs)); + *self = Self { entries, hashes, index: Some(index) }; + } + + /// Reserves room for one more entry; the test-util checkpoint injects allocation failures. + #[verifier::external_body] + pub fn reserve_one(&mut self) -> (result: Result<(), HistoryError>) + ensures final(self)@ == old(self)@, + result is Err ==> result == Err(HistoryError::AllocationFailed), + { + #[cfg(any(test, feature = "test-util"))] + junco_core::observation::reservation_checkpoint() + .map_err(|_| HistoryError::AllocationFailed)?; + self.entries.try_reserve(1).map_err(|_| HistoryError::AllocationFailed)?; + self.hashes.try_reserve(1).map_err(|_| HistoryError::AllocationFailed) + } +} + +impl KeyedMap { + #[allow(clippy::manual_map)] + pub fn lookup(&self, key: &K) -> (r: Option) + ensures key_laws::() ==> match r { + Some(v) => exists|i: int| 0 <= i < self@.len() && self@[i].1 == v + && key.eq_spec(&self@[i].0), + None => forall|i: int| 0 <= i < self@.len() ==> !key.eq_spec(&self@[i].0), + }, + { + match self.find(key) { + Some(i) => Some(self.entries[i].1), + None => None, + } + } +} + +impl KeyedMap> { + #[allow(non_shorthand_field_patterns)] + pub fn push_at(&mut self, i: usize, value: T) + requires i < old(self)@.len(), + ensures + final(self)@.len() == old(self)@.len(), + final(self)@[i as int].0 == old(self)@[i as int].0, + final(self)@[i as int].1@ == old(self)@[i as int].1@.push(value), + forall|j: int| 0 <= j < final(self)@.len() && j != i ==> final(self)@[j] == old(self)@[j], + { + proof { use_type_invariant(&*self); } + let mut table = Self { entries: Vec::new(), hashes: Vec::new(), index: None }; + core::mem::swap(self, &mut table); + let Self { entries, hashes, index } = table; + let mut entries = entries; + entries[i].1.push(value); + *self = Self { entries, hashes, index }; + } +} + +} // verus! diff --git a/src/history-store/src/lib.rs b/src/history-store/src/lib.rs new file mode 100644 index 000000000..e5cff8520 --- /dev/null +++ b/src/history-store/src/lib.rs @@ -0,0 +1,31 @@ +#![no_std] +#![cfg_attr(not(verus_keep_ghost), forbid(unsafe_code))] +#![cfg_attr(verus_keep_ghost, feature(proc_macro_hygiene, allocator_api))] +#![cfg_attr(docsrs, feature(doc_cfg))] +extern crate alloc; +#[cfg(any(feature = "std", test))] +extern crate std; +#[cfg(feature = "runtime")] +#[cfg_attr(docsrs, doc(cfg(feature = "runtime")))] +#[doc(hidden)] +pub mod cache; +#[cfg(feature = "runtime")] +#[cfg_attr(docsrs, doc(cfg(feature = "runtime")))] +#[doc(hidden)] +pub mod graph; +#[cfg(feature = "runtime")] +#[cfg_attr(docsrs, doc(cfg(feature = "runtime")))] +pub mod history; +#[cfg(feature = "runtime")] +#[cfg_attr(docsrs, doc(cfg(feature = "runtime")))] +pub mod keyed; +#[cfg(feature = "runtime")] +#[cfg_attr(docsrs, doc(cfg(feature = "runtime")))] +pub mod store; +#[cfg(feature = "runtime")] +#[cfg_attr(docsrs, doc(cfg(feature = "runtime")))] +pub mod typed; +#[cfg(feature = "runtime")] +pub use history::{Checkpoint, History}; +#[cfg(feature = "runtime")] +pub use typed::Store; diff --git a/src/history-store/src/store.rs b/src/history-store/src/store.rs new file mode 100644 index 000000000..70eb16b77 --- /dev/null +++ b/src/history-store/src/store.rs @@ -0,0 +1,2972 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +//! Process-wide exact-byte identities and synchronized numeric histories. +//! Issuance, bidirectional persistent byte bindings, and lock-local record transactions are checked. +//! Const/static installation, reference identity, and lock/guard mechanics remain +//! narrow native leaves; concurrent observations use retained lifecycle snapshots. + +use crate::graph::allocation; +use crate::history::StoredHistory; +use alloc::collections::{BTreeMap, BTreeSet}; +use alloc::sync::Arc; +use alloc::vec::Vec; +use history_syntax::{Component, MAX_ARITY}; +use junco_core::errors::HistoryError; +use junco_core::limits::Limits; +use junco_core::observation::ObservationWorld; +#[cfg(verus_keep_ghost)] +use junco_core::verify::history_assumptions::{arc_identity, reference_identity}; +#[cfg(feature = "std")] +use parking_lot::{Mutex, RwLock, RwLockReadGuard}; +#[cfg(not(feature = "std"))] +use spin::{Mutex, RwLock, RwLockReadGuard}; +#[cfg(verus_keep_ghost)] +use verify::*; +use vstd::prelude::*; +#[cfg(verus_keep_ghost)] +use vstd::std_specs::option::OptionAdditionalFns; + +// Per-arity byte domains share one process-wide numeric issuance authority. +static STORES: spin::Mutex> = spin::Mutex::new(None); + +struct StoreRegistry { + authorities: Arc, + stores: [Option>; MAX_ARITY], +} + +#[cfg(verus_keep_ghost)] +verus! { + +impl View for Domain { + type V = DomainView; + closed spec fn view(&self) -> DomainView { + DomainView { paths: path_map(self.paths), ids: self.ids@ } + } +} + +} + +/// An inline numeric event; identity and hashing use only its active coordinates. +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Copy, Debug)] +pub struct Event { + pub(crate) arity: u8, + pub(crate) slots: [u64; MAX_ARITY], +} + +#[cfg(verus_keep_ghost)] +verus! { +impl Event { + #[verifier::type_invariant] + closed spec fn inv(&self) -> bool { self.arity <= MAX_ARITY } +} +} + +#[verus_verify] +impl Event { + #[verus_spec(result => requires values@.len() <= MAX_ARITY, + ensures result@ == values@.map(|i: int, value: u64| value as nat))] + pub(crate) fn from_encoded(values: &[u64]) -> Self { + assert!(values.len() <= MAX_ARITY); + let mut slots = [0; MAX_ARITY]; + let mut index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant index <= values@.len() <= MAX_ARITY, + forall|i: int| 0 <= i < MAX_ARITY ==> slots@[i] == + if i < index { values@[i] } else { 0 }, + decreases values@.len() - index, + ))] + while index < values.len() { + slots[index] = values[index]; + index += 1; + } + Self { + arity: values.len() as u8, + slots, + } + } + + /// Return a coordinate, or zero when the index is outside the active tuple. + #[verus_spec(result => ensures index < self@.len() ==> result as nat == self@[index as int], + index >= self@.len() ==> result == 0)] + pub fn component(&self, index: usize) -> u64 { + proof! { use_type_invariant(self); } + if index < self.arity as usize { + self.slots[index] + } else { + 0 + } + } + + #[verus_spec(result => ensures result == self@.len(), result <= MAX_ARITY)] + pub const fn arity(&self) -> usize { + proof! { use_type_invariant(self); } + self.arity as usize + } +} + +#[verus_verify] +impl Clone for Event { + #[verus_spec(result => ensures result == *self)] + fn clone(&self) -> Self { + *self + } +} + +#[verus_verify] +impl PartialEq for Event { + #[verus_spec(result => ensures result == (self@ == other@))] + fn eq(&self, other: &Self) -> bool { + proof! { use_type_invariant(self); use_type_invariant(other); } + if self.arity != other.arity { + return false; + } + let mut index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant index <= self.arity <= MAX_ARITY, self.arity == other.arity, + forall|i: int| 0 <= i < index ==> self.slots@[i] == other.slots@[i], + decreases self.arity - index, + ))] + while index < self.arity as usize { + if self.slots[index] != other.slots[index] { + proof! { assert(self@[index as int] != other@[index as int]); } + return false; + } + index += 1; + } + proof! { assert(self@ =~= other@); } + true + } +} +impl Eq for Event {} + +impl core::hash::Hash for Event { + fn hash(&self, state: &mut H) { + core::hash::Hash::hash(&self.slots[..self.arity as usize], state); + } +} + +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Debug)] +struct Domain { + paths: BTreeMap, u64>, + ids: BTreeSet, + #[cfg(verus_keep_ghost)] + issued: Tracked>, + #[cfg(verus_keep_ghost)] + bindings: Tracked, +} + +#[verus_verify] +impl Default for Domain { + #[verus_spec(result => ensures domain_wf(result@), domain_unissued(result), domain_bindings_wf(result))] + fn default() -> Self { + proof! { reveal(path_map); reveal(::view); } + proof_decl! { let tracked bindings = ByteBindings::empty(); } + let result = Self { + paths: BTreeMap::new(), + ids: BTreeSet::new(), + #[cfg(verus_keep_ghost)] + issued: verus_exec_expr! { Tracked(None) }, + #[cfg(verus_keep_ghost)] + bindings: verus_exec_expr! { Tracked(bindings) }, + }; + proof! { + reveal(domain_bindings_wf); + assert(path_map(result.paths) =~= Map::, nat>::empty()); + assert(result@.paths == Map::, nat>::empty()); + assert(result@.ids == Set::::empty()); + assert(domain_bindings_wf(result)); + } + result + } +} + +#[verus_verify] +impl Domain { + // Allocation fails without changing the counter; zero is never issued. + #[verus_verify] + #[verus_spec(result => ensures + match result { + Ok(id) => id == *old(next) && id > 0 && *final(next) == id + 1, + Err(error) => *final(next) == *old(next) + && (*old(next) == 0 || *old(next) == u64::MAX) + && error == HistoryError::IdExhausted { domain }, + } + )] + const fn allocate_id(next: &mut u64, domain: &'static str) -> Result { + let id = *next; + if id == 0 { + return Err(HistoryError::IdExhausted { domain }); + } + let following = match id.checked_add(1) { + Some(following) => following, + None => return Err(HistoryError::IdExhausted { domain }), + }; + *next = following; + Ok(id) + } + + // Borrowed byte-slice keys and native BTree ordering are outside the pinned vstd model. + #[verus_verify(external_body)] + #[verus_spec(result => ensures match result { + Some(id) => path_map(*paths).contains_key(path@) + && path_map(*paths)[path@] == id as nat, + None => !path_map(*paths).contains_key(path@), + })] + #[inline] + fn path_lookup(paths: &BTreeMap, u64>, path: &[u8]) -> Option { + paths.get(path).copied() + } + + #[verus_verify(external_body)] + #[verus_spec(ensures path_map(*final(paths)) == path_map(*old(paths)).insert( + path@, id as nat))] + #[inline] + fn path_insert(paths: &mut BTreeMap, u64>, path: Vec, id: u64) { + paths.insert(path, id); + } + + #[verus_verify(external_body)] + #[verus_spec(ensures path_map(*final(paths)) == path_map(*old(paths)).remove( + path@))] + #[inline] + fn path_remove(paths: &mut BTreeMap, u64>, path: &[u8]) { + paths.remove(path); + } + + #[verus_spec(result => + requires domain_wf(old(self)@), domain_provenance(*old(self), index as int), index < MAX_ARITY, + domain_bindings_wf(*old(self)), + numeric_store_wf(*numeric_store), + ensures domain_wf(final(self)@), domain_provenance(*final(self), index as int), + domain_bindings_wf(*final(self)), + domain_forward_authority(*final(self)) == domain_forward_authority(*old(self)), + domain_reverse_authority(*final(self)) == domain_reverse_authority(*old(self)), + result is Err ==> final(self)@ == old(self)@, + result is Err ==> final(self).issued@ == old(self).issued@, + result is Err ==> final(self).bindings@ == old(self).bindings@, + result matches Ok((id, receipt)) ==> receipt@.valid() + && receipt@.path() == path@ && receipt@.id() == id + && receipt@.coordinate_authority() == coordinate_authority(index as int) + && receipt@.forward_authority() == domain_forward_authority(*old(self)) + && receipt@.reverse_authority() == domain_reverse_authority(*old(self)) + && 0 < id < u64::MAX + && final(self)@.paths == old(self)@.paths.insert(path@, id as nat), + result matches Ok((id, receipt)) ==> final(self)@.ids == old(self)@.ids.insert(id), + old(self)@.paths.contains_key(path@) ==> result is Ok + && final(self)@ == old(self)@ + && result->Ok_0.0 as nat == old(self)@.paths[path@], + forall|old_path: Seq| old(self)@.paths.contains_key(old_path) + ==> final(self)@.paths.contains_key(old_path) + && final(self)@.paths[old_path] == old(self)@.paths[old_path], + )] + fn intern( + &mut self, + path: &[u8], + index: usize, + domain: &'static str, + limits: &mut L, + numeric_store: &HistoryStore, + ) -> Result<(u64, Tracked), HistoryError> { + proof! { reveal(::view); reveal(domain_wf); } + proof_decl! { let ghost entry = self@; } + proof_decl! { let ghost entry_bindings = self.bindings@; } + if let Some(id) = Self::path_lookup(&self.paths, path) { + proof_decl! { let tracked binding; } + proof! { + reveal(domain_bindings_wf); + reveal(domain_provenance); + let key = path@; + assert(self@.paths.contains_key(key)); + assert(self.bindings@.forward@[key] == id); + assert(self@.ids.contains(id)); + assert(self.bindings@.reverse@[id] == key); + let tracked bindings = self.bindings.borrow(); + bindings.paths.agree(&bindings.forward); + bindings.ids.agree(&bindings.reverse); + let tracked mut paths = bindings.paths.duplicate(); + let tracked forward = paths.split_points_to(key); + forward.agree(&bindings.forward); + assert(forward@ == (key, id)); + let tracked mut ids = bindings.ids.duplicate(); + let tracked reverse = ids.split_points_to(id); + reverse.agree(&bindings.reverse); + assert(reverse@ == (id, key)); + assert(self.issued@ is Some); + let tracked held = self.issued.borrow().tracked_borrow(); + assert(held.id() == coordinate_authority(index as int)); + assert(held@.contains_key(id)); + assert(held@[id] == ComponentIssuer::Byte); + let tracked mut issued = held.duplicate(); + let tracked issuer = issued.split_points_to(id); + assert(issuer@ == (id, ComponentIssuer::Byte)); + binding = ByteBindingReceipt { forward, reverse, issuer }; + } + return Ok((id, verus_exec_expr! { Tracked(binding) })); + } + let mut owned = Vec::new(); + allocation(owned.try_reserve(path.len()))?; + owned.extend_from_slice(path); + limits.enforce_memory()?; + proof_decl! { let tracked prior = match self.issued.borrow() { Some(previous) => Some(previous), None => None }; } + proof_decl! { let ghost prior_view = prior; } + let (id, _receipt) = numeric_store.allocate_after( + index, + domain, + 0, + verus_exec_expr! { Ghost(ComponentIssuer::Byte) }, + verus_exec_expr! { Tracked(prior) }, + )?; + proof! { + assert(owned@ == path@); + assert(entry.ids == self.ids@); + assert forall|old_path: Seq| entry.paths.contains_key(old_path) + implies 0 < entry.paths[old_path] < id as nat by { + let old_id = entry.paths[old_path] as u64; + assert(old_id as nat == entry.paths[old_path]); + assert(entry.paths.values().contains(old_id as nat)); + assert(entry.ids.contains(old_id) <==> entry.paths.values().contains(old_id as nat)); + assert(self.ids@.contains(old_id)); + match prior_view { + Some(previous) => { assert(previous@.contains_key(old_id)); } + None => { assert(self.ids@ == Set::::empty()); } + } + assert(old_id < id); + } + assert(!entry.ids.contains(id)); + assert(junco_core::verify::history_specs::interner_wf(entry.paths, id as nat)); + junco_core::verify::history_specs::lemma_interner_fresh_nonreuse(entry.paths, id as nat, + path@, id as nat); + } + Self::path_insert(&mut self.paths, owned, id); + self.ids.insert(id); + if let Err(error) = limits.enforce_memory() { + // Roll back the mapping, never the allocator: an issued ID must never be reused. + Self::path_remove(&mut self.paths, path); + self.ids.remove(&id); + proof! { + assert(self@.paths =~= entry.paths); + assert(self@.ids =~= entry.ids); + } + return Err(error.into()); + } + proof_decl! { let tracked binding; } + proof! { + junco_core::verify::history_specs::lemma_interner_raise_frontier(self@.paths, + id as nat + 1, u64::MAX as nat); + assert forall|known_id: u64| self.ids@.contains(known_id) + <==> self@.paths.values().contains(known_id as nat) by { + let key = path@; + let updated = entry.paths.insert(key, id as nat); + if updated.values().contains(known_id as nat) { + let witness = choose|p: Seq| updated.contains_key(p) + && updated[p] == known_id as nat; + if witness != key { + assert(entry.paths.contains_key(witness)); + assert(entry.paths[witness] == known_id as nat); + assert(entry.paths.values().contains(known_id as nat)); + } + } + if entry.paths.values().contains(known_id as nat) { + let witness = choose|p: Seq| entry.paths.contains_key(p) + && entry.paths[p] == known_id as nat; + assert(witness != key); + assert(updated.contains_key(witness)); + assert(updated[witness] == known_id as nat); + assert(updated.values().contains(known_id as nat)); + } + if known_id == id { + assert(updated.contains_key(key)); + assert(updated[key] == known_id as nat); + assert(updated.values().contains(known_id as nat)); + } + } + let key = path@; + let tracked forward = self.bindings.borrow_mut().forward.insert(key, id).persist(); + let tracked reverse = self.bindings.borrow_mut().reverse.insert(id, key).persist(); + self.bindings.borrow_mut().paths.combine_points_to(forward.duplicate()); + self.bindings.borrow_mut().ids.combine_points_to(reverse.duplicate()); + let tracked receipt = _receipt.get(); + let tracked mut held = None; + vstd::modes::tracked_swap(self.issued.borrow_mut(), &mut held); + let tracked updated = match held { + None => receipt.duplicate().submap(), + Some(mut previous) => { previous.combine_points_to(receipt.duplicate()); previous }, + }; + *self.issued.borrow_mut() = Some(updated); + binding = ByteBindingReceipt { forward, reverse, issuer: receipt }; + assert forall|p: Seq| self@.paths.contains_key(p) + implies self.bindings@.forward@[p] as nat == self@.paths[p] by { + if p != key { assert(entry.paths.contains_key(p)); } + } + assert forall|known: u64| self@.ids.contains(known) + implies self@.paths.contains_key(self.bindings@.reverse@[known]) + && self@.paths[self.bindings@.reverse@[known]] == known as nat by { + if known != id { + assert(entry.ids.contains(known)); + let p = entry_bindings.reverse@[known]; + assert(entry.paths.contains_key(p)); + assert(p != key); + } + } + assert forall|p: Seq| self@.paths.contains_key(p) + implies self.bindings@.reverse@.contains_key(self.bindings@.forward@[p]) + && self.bindings@.reverse@[self.bindings@.forward@[p]] == p by { + if p != key { + assert(entry.paths.contains_key(p)); + assert(entry_bindings.forward@[p] != id); + } + } + } + Ok((id, verus_exec_expr! { Tracked(binding) })) + } + + #[verus_spec(result => requires domain_wf(self@), + ensures (result is Ok) == self.ids@.contains(id), + result is Ok ==> result == Ok(()), + result is Ok ==> self@.paths.values().contains(id as nat), + result is Err ==> result == Err(HistoryError::UnknownId { domain, id }))] + fn validate(&self, id: u64, domain: &'static str) -> Result<(), HistoryError> { + proof! { + reveal(::view); + reveal(domain_wf); + assert(self@.ids.contains(id) <==> self@.paths.values().contains(id as nat)); + } + if self.ids.contains(&id) { + Ok(()) + } else { + Err(HistoryError::UnknownId { domain, id }) + } + } +} + +/// Advance the process history-key counter, failing at `usize::MAX` without changing it. +#[verus_verify] +#[verus_spec(result => + requires 0 < *old(next), + ensures match result { + Ok(id) => id == *old(next) && 0 < id < usize::MAX && *final(next) == id + 1, + Err(error) => *old(next) == usize::MAX && *final(next) == *old(next) + && error == HistoryError::IdExhausted { domain: "history" }, + } +)] +fn next_history_id(next: &mut usize) -> Result { + let id = *next; + let following = match id.checked_add(1) { + Some(following) => following, + None => return Err(HistoryError::IdExhausted { domain: "history" }), + }; + *next = following; + Ok(id) +} + +// Process authorities are embedded in the live allocator mutex payloads. +// Erased Ghost/Tracked signatures retain issuer and receipt types, but not their proof-only contents. +pub(crate) type ComponentIdReceipt = + vstd::resource::map::GhostPersistentPointsTo; +pub(crate) type ComponentReceipts = + vstd::resource::map::GhostPersistentSubmap; +pub(crate) type HistoryKeyReceipt = + vstd::resource::map::GhostPersistentPointsTo; + +verus! { +pub(crate) enum ComponentIssuer { + #[cfg(verus_keep_ghost)] + Byte, + #[cfg(verus_keep_ghost)] + Typed(vstd::resource::Loc), +} +pub(crate) enum HistoryIssuer { + #[cfg(verus_keep_ghost)] + Byte, + #[cfg(verus_keep_ghost)] + Typed { store: vstd::resource::Loc, lifecycle: vstd::resource::Loc }, +} + +#[cfg(verus_keep_ghost)] +tracked struct ByteBindings { + forward: vstd::resource::map::GhostMapAuth, u64>, + reverse: vstd::resource::map::GhostMapAuth>, + paths: vstd::resource::map::GhostPersistentSubmap, u64>, + ids: vstd::resource::map::GhostPersistentSubmap>, +} +#[cfg(verus_keep_ghost)] +impl ByteBindings { + proof fn empty() -> (tracked result: Self) + ensures result.forward@ == Map::empty(), result.reverse@ == Map::empty(), + result.paths@ == Map::empty(), result.ids@ == Map::empty(), + result.paths.id() == result.forward.id(), result.ids.id() == result.reverse.id(), + { + let tracked (forward, paths) = vstd::resource::map::GhostMapAuth::new(Map::empty()); + let tracked (reverse, ids) = vstd::resource::map::GhostMapAuth::new(Map::empty()); + Self { forward, reverse, paths: paths.persist(), ids: ids.persist() } + } +} + +/// Persistent evidence of one byte-path binding; no native map or allocation is added. +pub tracked struct ByteBindingReceipt { + #[cfg(verus_keep_ghost)] + forward: vstd::resource::map::GhostPersistentPointsTo, u64>, + #[cfg(verus_keep_ghost)] + reverse: vstd::resource::map::GhostPersistentPointsTo>, + #[cfg(verus_keep_ghost)] + issuer: ComponentIdReceipt, +} + +impl ByteBindingReceipt { + #[verifier::type_invariant] + spec fn inv(self) -> bool { + self.forward.key() == self.reverse.value() && self.forward.value() == self.reverse.key() + && self.issuer.key() == self.forward.value() && self.issuer.value() == ComponentIssuer::Byte + } + pub closed spec fn valid(self) -> bool { self.inv() } + pub closed spec fn path(self) -> Seq { self.forward.key() } + pub closed spec fn id(self) -> u64 { self.forward.value() } + pub closed spec fn coordinate_authority(self) -> vstd::resource::Loc { self.issuer.id() } + pub closed spec fn forward_authority(self) -> vstd::resource::Loc { self.forward.id() } + pub closed spec fn reverse_authority(self) -> vstd::resource::Loc { self.reverse.id() } + + pub(crate) proof fn issuer_receipt(tracked &self) -> (tracked result: ComponentIdReceipt) + ensures result.id() == self.coordinate_authority(), result@ == (self.id(), ComponentIssuer::Byte), + result.key() == self.id(), result.value() == ComponentIssuer::Byte, + { + use_type_invariant(self); + self.issuer.duplicate() + } +} + +pub proof fn lemma_byte_binding_reuse(tracked left: &ByteBindingReceipt, tracked right: &ByteBindingReceipt) + requires left.forward_authority() == right.forward_authority(), + left.reverse_authority() == right.reverse_authority(), left.path() == right.path(), + ensures left.id() == right.id(), +{ + let tracked mut forward = left.forward.duplicate(); + forward.intersection_agrees(&right.forward); +} + +pub proof fn lemma_byte_binding_separation(tracked left: &ByteBindingReceipt, tracked right: &ByteBindingReceipt) + requires left.forward_authority() == right.forward_authority(), + left.reverse_authority() == right.reverse_authority(), left.path() != right.path(), + ensures left.id() != right.id(), +{ + use_type_invariant(left); use_type_invariant(right); + let tracked mut reverse = left.reverse.duplicate(); + reverse.intersection_agrees(&right.reverse); +} + +#[cfg(verus_keep_ghost)] +pub(crate) tracked struct CoordinateAuthorities { + pub(crate) entries: Seq>, +} +#[verifier::external_derive] +#[derive(Debug)] +pub(crate) struct CoordinateState { + pub(crate) next: [u64; MAX_ARITY], + #[cfg(verus_keep_ghost)] + pub(crate) authorities: Tracked, +} +#[verifier::external_derive] +#[derive(Debug)] +pub(crate) struct HistoryKeyState { + pub(crate) next: usize, + #[cfg(verus_keep_ghost)] + pub(crate) issued: Tracked>, +} +#[cfg(any(test, verus_keep_ghost))] +impl CoordinateState { + pub(crate) fn new() -> (result: Self) + ensures coordinate_wf(result), result.next@ == Seq::new(MAX_ARITY as nat, |i: int| 1u64), + { + let tracked authorities = empty_coordinate_authorities(MAX_ARITY as nat); + Self { next: [1; MAX_ARITY], #[cfg(verus_keep_ghost)] authorities: Tracked(authorities) } + } +} +#[cfg(any(test, verus_keep_ghost))] +impl HistoryKeyState { + pub(crate) fn new() -> (result: Self) + ensures history_key_wf(result), result.next == 1, + { + let tracked issued = empty_history_authority(); + Self { next: 1, #[cfg(verus_keep_ghost)] issued: Tracked(issued) } + } +} + +pub(crate) fn allocate_coordinate_state(state: &mut CoordinateState, index: usize, + domain: &'static str, last: u64, Ghost(issuer): Ghost, + Tracked(prior): Tracked>) + -> (result: Result<(u64, Tracked), HistoryError>) + requires coordinate_wf(*old(state)), coordinate_prior(*old(state), index, prior), + ensures coordinate_result(*old(state), *final(state), index, domain, last, issuer, prior, result), + result != Err(HistoryError::WrongHistoryOwner), +{ + if index >= MAX_ARITY { return Err(HistoryError::invariant("invalid identity domain")); } + let ghost entry = *state; + let ghost before = coordinate_map(*state, index as int); + proof { + if let Some(previous) = prior { + previous.agree(state.authorities.borrow().entries.tracked_borrow(index as int)); + if previous@.contains_key(last) { + assert(before.contains_key(last)); + assert(last < entry.next@[index as int]); + } + } + } + let mut next = state.next[index]; + let allocated = Domain::allocate_id(&mut next, domain); + state.next[index] = next; + proof { + if allocated is Err { + assert(state.next@ =~= entry.next@); + assert(state.next == entry.next); + } + } + let id = allocated?; + let tracked receipt; + proof { + assert(!before.contains_key(id)); + receipt = state.authorities.borrow_mut().entries.tracked_borrow_mut(index as int) + .insert(id, issuer).persist(); + assert forall|d: int, key: u64| 0 <= d < MAX_ARITY implies + (coordinate_map(*state, d).contains_key(key) <==> 0 < key < state.next@[d]) by { + if d == index { assert(coordinate_map(*state, d) == before.insert(id, issuer)); } + else { + assert(coordinate_map(*state, d) == coordinate_map(entry, d)); + assert(state.next@[d] == entry.next@[d]); + assert(coordinate_map(entry, d).contains_key(key) <==> 0 < key < entry.next@[d]); + } + } + if let Some(previous) = prior { + assert forall|key: u64| previous@.contains_key(key) implies key < id by { + assert(before.contains_key(key)); + } + } + } + proof { + if last == 0 || (match prior { Some(previous) => previous@.contains_key(last), None => false }) { + assert(last < id); + } + } + if id <= last { return Err(HistoryError::invariant("identity allocator moved backwards")); } + Ok((id, Tracked(receipt))) +} + +pub(crate) fn allocate_history_state(state: &mut HistoryKeyState, last: usize, + Ghost(issuer): Ghost) + -> (result: Result<(usize, Tracked), HistoryError>) + requires history_key_wf(*old(state)), + ensures history_key_result(*old(state), *final(state), last, issuer, result), + last < old(state).next ==> (result matches Err(error) ==> + error == HistoryError::IdExhausted { domain: "history" }), +{ + if last == usize::MAX { return Err(HistoryError::IdExhausted { domain: "history" }); } + let ghost before = (state.issued@)@; + let id = next_history_id(&mut state.next)?; + let tracked receipt; + proof { + assert(!before.contains_key(id)); + receipt = state.issued.borrow_mut().insert(id, issuer).persist(); + assert forall|key: usize| (state.issued@)@.contains_key(key) + <==> 0 < key < state.next by { + if key != id { assert((state.issued@)@.contains_key(key) == before.contains_key(key)); } + } + } + if id <= last { return Err(HistoryError::invariant("history identity allocator moved backwards")); } + Ok((id, Tracked(receipt))) +} +#[verifier::external_body] +#[verifier::external_derive] +#[repr(transparent)] +#[derive(Debug)] +pub(crate) struct NativeCoordinates { pub(crate) inner: spin::Mutex } +impl NativeCoordinates { + #[verifier::external_body] + pub(crate) const fn new() -> (result: Self) + ensures coordinates_mutex_valid(result), + { + let tracked authorities = empty_coordinate_authorities(MAX_ARITY as nat); + let state = CoordinateState { next: [1; MAX_ARITY], #[cfg(verus_keep_ghost)] authorities: Tracked(authorities) }; + Self { inner: spin::Mutex::new(state) } + } + // Only installation and mutex/callback fidelity are native leaves. + #[verifier::external_body] + pub(crate) fn with_state R>( + &self, context: Context, operation: F) -> (result: R) + requires coordinates_mutex_valid(*self), + forall|borrow: &mut CoordinateState| coordinates_acquired(mut_ref_current(borrow), *self) + ==> call_requires(operation, (borrow, context)), + forall|borrow: &mut CoordinateState, output: R| + coordinates_acquired(mut_ref_current(borrow), *self) && call_ensures(operation, (borrow, context), output) + ==> coordinate_frame(mut_ref_current(borrow), mut_ref_future(borrow)), + ensures exists|borrow: &mut CoordinateState| + coordinates_acquired(mut_ref_current(borrow), *self) + && coordinate_frame(mut_ref_current(borrow), mut_ref_future(borrow)) + && call_ensures(operation, (borrow, context), result), + { + let mut state = self.inner.lock(); + operation(&mut state, context) + } +} +#[verifier::external_body] +#[verifier::external_derive] +#[repr(transparent)] +#[derive(Debug)] +pub(crate) struct NativeHistoryKeys { pub(crate) inner: spin::Mutex } +impl NativeHistoryKeys { + #[verifier::external_body] + pub(crate) const fn new() -> (result: Self) + ensures history_keys_mutex_valid(result), + { + let tracked issued = empty_history_authority(); + let state = HistoryKeyState { next: 1, #[cfg(verus_keep_ghost)] issued: Tracked(issued) }; + Self { inner: spin::Mutex::new(state) } + } + // Only installation and mutex/callback fidelity are native leaves. + #[verifier::external_body] + pub(crate) fn with_state R>( + &self, context: Context, operation: F) -> (result: R) + requires history_keys_mutex_valid(*self), + forall|borrow: &mut HistoryKeyState| history_keys_acquired(mut_ref_current(borrow), *self) + ==> call_requires(operation, (borrow, context)), + forall|borrow: &mut HistoryKeyState, output: R| + history_keys_acquired(mut_ref_current(borrow), *self) && call_ensures(operation, (borrow, context), output) + ==> history_key_frame(mut_ref_current(borrow), mut_ref_future(borrow)), + ensures exists|borrow: &mut HistoryKeyState| + history_keys_acquired(mut_ref_current(borrow), *self) + && history_key_frame(mut_ref_current(borrow), mut_ref_future(borrow)) + && call_ensures(operation, (borrow, context), result), + { + let mut state = self.inner.lock(); + operation(&mut state, context) + } +} +} + +#[verus_verify] +#[verus_verify(external_body)] +#[verus_verify(external_derive)] +#[cfg_attr(not(verus_keep_ghost), repr(transparent))] +#[cfg_attr(not(verus_keep_ghost), derive(Debug))] +pub(crate) struct NativeDomain { + inner: Mutex, + #[cfg(verus_keep_ghost)] + index: Ghost, +} +#[verus_verify] +impl NativeDomain { + #[verus_spec(result => requires index@ < MAX_ARITY, + ensures native_domain_valid(result), native_domain_index(result) == index@ as int)] + fn new(index: Ghost) -> Self { + let domain = Domain::default(); + Self::place(domain, index) + } + // Only placement of the checked payload in the native mutex is trusted. + #[verus_verify(external_body)] + #[verus_spec(result => requires _index@ < MAX_ARITY, domain_wf(domain@), domain_unissued(domain), + domain_bindings_wf(domain), + ensures native_domain_valid(result), native_domain_index(result) == _index@ as int, + native_domain_forward_authority(result) == domain_forward_authority(domain), + native_domain_reverse_authority(result) == domain_reverse_authority(domain))] + fn place(domain: Domain, _index: Ghost) -> Self { + Self { + inner: Mutex::new(domain), + #[cfg(verus_keep_ghost)] + index: _index, + } + } + #[verus_verify(external_body)] + #[verus_spec(result => requires native_domain_valid(*self), + forall|borrow: &mut Domain| domain_acquired(mut_ref_current(borrow), *self) + ==> call_requires(operation, (borrow, context)), + forall|borrow: &mut Domain, output: R| domain_acquired(mut_ref_current(borrow), *self) + && call_ensures(operation, (borrow, context), output) + ==> domain_acquired(mut_ref_future(borrow), *self), + ensures exists|borrow: &mut Domain| domain_acquired(mut_ref_current(borrow), *self) + && domain_acquired(mut_ref_future(borrow), *self) + && call_ensures(operation, (borrow, context), result))] + fn with_domain R>( + &self, + context: Context, + operation: F, + ) -> R { + let mut domain = self.inner.lock(); + operation(&mut domain, context) + } +} + +#[verus_verify] +#[verus_verify(external_derive)] +#[cfg_attr(not(verus_keep_ghost), derive(Debug))] +pub(crate) struct RecordCell { + pub(crate) stored: StoredHistory, + #[cfg(verus_keep_ghost)] + pub(crate) lifecycle: Tracked, +} + +#[verus_verify] +impl RecordCell { + #[verus_spec(result => requires old(self).lifecycle@.wf(), + old(self).lifecycle@.state() == old(self).stored@, events@.len() > 0, + ensures crate::history::verify::stored_append_result(old(self).stored, final(self).stored, events@, result), + result != Err(HistoryError::WrongHistoryOwner), + result matches Err(error) ==> junco_core::spec::semantics::resource_error(error), + final(self).lifecycle@.wf(), final(self).lifecycle@.state() == final(self).stored@, + final(self).lifecycle@.id() == old(self).lifecycle@.id(), + result is Err ==> final(self).lifecycle@ == old(self).lifecycle@)] + fn append_events( + &mut self, + events: &[Event], + limits: &mut L, + world: &mut ObservationWorld, + ) -> Result<(), HistoryError> { + proof_decl! { let ghost before = self.stored; } + let result = self.stored.append_events(events, limits, world); + proof! { + crate::history::lemma_stored_history_view(before); + crate::history::lemma_stored_history_view(self.stored); + if let Ok(()) = result { + self.lifecycle.borrow_mut().advance(self.stored@); + } else { + assert(self.stored@ == before@); + } + } + result + } + + #[verus_spec(result => requires old(self).lifecycle@.wf(), + old(self).lifecycle@.state() == old(self).stored@, + ensures crate::history::verify::stored_truncate_result(old(self).stored, final(self).stored, len, result), + final(self).lifecycle@.wf(), final(self).lifecycle@.state() == final(self).stored@, + final(self).lifecycle@.id() == old(self).lifecycle@.id(), + (result is Err || len >= old(self).stored@.events.len()) + ==> final(self).lifecycle@ == old(self).lifecycle@)] + fn truncate_events(&mut self, len: usize) -> Result<(), HistoryError> { + proof_decl! { let ghost before = self.stored; } + proof_decl! { let ghost previous = self.stored@.events.len(); } + let result = self.stored.truncate_events(len); + proof! { + crate::history::lemma_stored_history_view(before); + crate::history::lemma_stored_history_view(self.stored); + if let Ok(()) = result { + if len < previous { self.lifecycle.borrow_mut().advance(self.stored@); } + } + } + result + } +} + +#[verus_verify(external_body)] +#[verus_verify(external_derive)] +#[repr(transparent)] +#[cfg_attr(not(verus_keep_ghost), derive(Debug))] +pub(crate) struct NativeRecord { + pub(crate) inner: Arc>, +} +#[verus_verify] +impl NativeRecord { + #[cfg(verus_keep_ghost)] + verus! { + pub(crate) uninterp spec fn record_id(self) -> usize; + pub(crate) uninterp spec fn lifecycle_id(self) -> vstd::resource::Loc; + } + + #[verus_spec(result => ensures record_valid(result), + result.record_id() == stored.spec_id(), record_installed(result, stored))] + fn new(stored: StoredHistory) -> Self { + proof! { crate::history::lemma_stored_history_view(stored); } + proof_decl! { let tracked lifecycle = crate::history::verify::Lifecycle::new(stored@); } + Self::place_cell(RecordCell { + stored, + #[cfg(verus_keep_ghost)] + lifecycle: verus_exec_expr! { Tracked(lifecycle) }, + }) + } + + // Native placement publishes only the supplied checked cell and its lock invariant. + #[verus_verify(external_body)] + #[verus_spec(result => requires cell.lifecycle@.wf(), cell.lifecycle@.state() == cell.stored@, + ensures record_valid(result), result.record_id() == cell.stored.spec_id(), + result.lifecycle_id() == cell.lifecycle@.id(), record_installed(result, cell.stored))] + fn place_cell(cell: RecordCell) -> Self { + Self { + inner: Arc::new(RwLock::new(cell)), + } + } + + // Acquisition/release and faithful execution of a checked callback are native. + #[verus_verify(external_body)] + #[verus_spec(result => requires record_valid(*self), + forall|borrow: &mut RecordCell| record_acquired(mut_ref_current(borrow), *self) + ==> call_requires(operation, (borrow, context)), + forall|borrow: &mut RecordCell, output: R| record_acquired(mut_ref_current(borrow), *self) + && call_ensures(operation, (borrow, context), output) + ==> record_acquired(mut_ref_future(borrow), *self), + ensures exists|borrow: &mut RecordCell| record_acquired(mut_ref_current(borrow), *self) + && record_acquired(mut_ref_future(borrow), *self) + && call_ensures(operation, (borrow, context), result))] + fn with_record R>( + &self, + context: Context, + operation: F, + ) -> R { + let mut cell = self.inner.write(); + operation(&mut cell, context) + } +} +#[verus_verify] +impl Clone for NativeRecord { + #[verus_verify(external_body)] + #[verus_spec(result => ensures result == *self)] + fn clone(&self) -> Self { + Self { + inner: Arc::clone(&self.inner), + } + } +} +#[cfg(verus_keep_ghost)] +verus! { +pub mod verify { + use super::*; + use vstd::std_specs::option::OptionAdditionalFns; + pub(crate) uninterp spec fn native_domain_valid(wrapper: NativeDomain) -> bool; + pub(crate) uninterp spec fn native_domain_index(wrapper: NativeDomain) -> int; + pub(crate) uninterp spec fn native_domain_forward_authority(wrapper: NativeDomain) -> vstd::resource::Loc; + pub(crate) uninterp spec fn native_domain_reverse_authority(wrapper: NativeDomain) -> vstd::resource::Loc; + pub(super) open spec fn domain_acquired(domain: Domain, wrapper: NativeDomain) -> bool { + domain_wf(domain@) && domain_provenance(domain, native_domain_index(wrapper)) + && domain_bindings_wf(domain) + && domain_forward_authority(domain) == native_domain_forward_authority(wrapper) + && domain_reverse_authority(domain) == native_domain_reverse_authority(wrapper) + } + pub(crate) uninterp spec fn record_valid(record: NativeRecord) -> bool; + pub open(crate) spec fn record_acquired(cell: RecordCell, record: NativeRecord) -> bool { + cell.lifecycle@.wf() && cell.lifecycle@.state() == cell.stored@ + && cell.stored.spec_id() == record.record_id() + && cell.lifecycle@.id() == record.lifecycle_id() + } + pub(crate) closed spec fn record_installed(record: NativeRecord, stored: StoredHistory) -> bool { + exists|borrow: &mut RecordCell| record_acquired(mut_ref_current(borrow), record) + && mut_ref_current(borrow).stored == stored + } + pub open(crate) spec fn handle_index(handle: HistoryHandle) -> usize { handle.index } + /// Fixed lifecycle resource identity, never a mutable observation of shared contents. + pub open(crate) spec fn handle_lifecycle_id(handle: HistoryHandle) -> vstd::resource::Loc { + handle.record.lifecycle_id() + } + /// The native referent owned by the handle, independent of its numeric key. + pub open(crate) spec fn handle_owner_identity(handle: HistoryHandle) -> vstd::resource::Loc { + arc_identity(handle.owner) + } + pub open(crate) spec fn handle_owner(handle: HistoryHandle) -> Arc { handle.owner } + pub open(crate) spec fn handle_wf(handle: HistoryHandle) -> bool { + numeric_store_wf(*handle.owner) && record_valid(handle.record) + && handle.record.record_id() == handle.index + && handle.global_registration@.id() == history_authority() + && handle.global_registration@@ == (handle.index, HistoryIssuer::Byte) + } + + /// Initial placement observation, not an assertion about a later unlocked record. + pub open(crate) spec fn history_created(history: HistoryHandle) -> bool { + exists|stored: StoredHistory| record_installed(history.record, stored) + && stored.spec_id() == handle_index(history) + && crate::history::verify::stored_events(&stored) == Seq::::empty() + && stored.spec_revision() == 0 + } + pub open(crate) spec fn record_matches_handle(record: HistoryRecord, history: HistoryHandle) -> bool { + record_view(record) == history.record + } + + + /// The actual current/future borrow of one lock acquisition. Other writers may + /// intervene before or after this transaction, never between these witnesses. + #[verifier::prophetic] + pub open(crate) spec fn record_transaction(history: HistoryHandle, + before: StoredHistory, after: StoredHistory) -> bool { + exists|borrow: &mut RecordCell| record_acquired(mut_ref_current(borrow), history.record) + && record_acquired(mut_ref_future(borrow), history.record) + && mut_ref_current(borrow).stored == before && mut_ref_future(borrow).stored == after + } + + #[verifier::prophetic] + pub open(crate) spec fn record_append_observed(history: HistoryHandle, events: Seq, + result: Result<(), HistoryError>) -> bool { + exists|before: StoredHistory, after: StoredHistory| record_transaction(history, before, after) + && crate::history::verify::stored_append_result(before, after, events, result) + } + + #[verifier::prophetic] + pub open(crate) spec fn record_truncate_observed(history: HistoryHandle, len: usize, + result: Result<(), HistoryError>) -> bool { + exists|before: StoredHistory, after: StoredHistory| record_transaction(history, before, after) + && crate::history::verify::stored_truncate_result(before, after, len, result) + } + + pub(super) open spec fn byte_domain(store: &HistoryStore, index: int) -> NativeDomain { + store.domains@[index] + } + + /// Fixed identities, transparent to the owning facade but closed to its callers. + pub open(super) spec fn byte_coordinate_authority(store: &HistoryStore, index: int) -> vstd::resource::Loc { + coordinate_ids(store.authorities.coordinates)[index] + } + pub open(super) spec fn byte_forward_authority(store: &HistoryStore, index: int) -> vstd::resource::Loc { + native_domain_forward_authority(byte_domain(store, index)) + } + pub open(super) spec fn byte_reverse_authority(store: &HistoryStore, index: int) -> vstd::resource::Loc { + native_domain_reverse_authority(byte_domain(store, index)) + } + + /// The actual current/future borrow from one acquisition of one coordinate lock. + #[verifier::prophetic] + pub open(super) spec fn byte_domain_transaction(store: &HistoryStore, index: int, + before: DomainView, after: DomainView) -> bool { + 0 <= index < store.arity_spec() && exists|borrow: &mut Domain| + domain_acquired(mut_ref_current(borrow), byte_domain(store, index)) + && domain_acquired(mut_ref_future(borrow), byte_domain(store, index)) + && mut_ref_current(borrow)@ == before && mut_ref_future(borrow)@ == after + } + + pub open spec fn byte_intern_maps(before: DomainView, after: DomainView, + path: Seq, result: Result) -> bool { + domain_wf(before) && domain_wf(after) && before.paths.submap_of(after.paths) + && match result { + Ok(id) => 0 < id < u64::MAX + && after.paths == before.paths.insert(path, id as nat) + && after.ids == before.ids.insert(id), + Err(_) => after == before, + } + && (before.paths.contains_key(path) + ==> result == Ok(before.paths[path] as u64) && after == before) + } + + #[verifier::prophetic] + pub open spec fn byte_intern_result(store: &HistoryStore, index: int, + path: Seq, result: Result) -> bool { + if 0 <= index < store.arity_spec() { + exists|before: DomainView, after: DomainView| byte_domain_transaction(store, index, before, after) + && byte_intern_maps(before, after, path, result) + } else { + match result { Err(error) => component_index_error(error), Ok(_) => false } + } + } + + pub open spec fn byte_binding_result(store: &HistoryStore, index: int, + path: Seq, id: u64, receipt: ByteBindingReceipt) -> bool { + receipt.valid() && receipt.path() == path && receipt.id() == id + && receipt.coordinate_authority() == byte_coordinate_authority(store, index) + && receipt.forward_authority() == byte_forward_authority(store, index) + && receipt.reverse_authority() == byte_reverse_authority(store, index) + } + + pub proof fn lemma_byte_binding_pair_facts(store: &HistoryStore, index: int, + left_path: Seq, left_id: u64, left: ByteBindingReceipt, + right_path: Seq, right_id: u64, right: ByteBindingReceipt) + requires byte_binding_result(store, index, left_path, left_id, left), + byte_binding_result(store, index, right_path, right_id, right), + ensures left.path() == left_path, left.id() == left_id, + right.path() == right_path, right.id() == right_id, + left.forward_authority() == right.forward_authority(), + left.reverse_authority() == right.reverse_authority(), + left.coordinate_authority() == right.coordinate_authority(), + {} + + /// A read observation of one domain. Coordinates are read independently, never as one snapshot. + #[verifier::prophetic] + pub open(super) spec fn byte_validation_observed(store: &HistoryStore, index: int, + id: u64, known: bool) -> bool { + exists|view: DomainView| byte_domain_transaction(store, index, view, view) + && domain_wf(view) && known == view.ids.contains(id) + } + + pub open spec fn event_arity_error(error: HistoryError) -> bool { + match error { + HistoryError::InvalidPolicy { path, message } => path@ == "event"@ + && message == "event arity does not match store", + _ => false, + } + } + + pub open spec fn component_index_error(error: HistoryError) -> bool { + match error { + HistoryError::InvalidPolicy { path, message } => path@ == "component"@ + && message == "component index is outside event arity", + _ => false, + } + } + + /// Validation reads coordinates in increasing index order, stopping at the first absent ID. + #[verifier::prophetic] + pub open spec fn event_validation_result(store: &HistoryStore, event: Event, + result: Result<(), HistoryError>) -> bool { + if event@.len() != store.arity_spec() { + match result { Err(error) => event_arity_error(error), Ok(_) => false } + } else { + (result == Ok(()) && forall|i: int| 0 <= i < event@.len() + ==> byte_validation_observed(store, i, event@[i] as u64, true)) + || (exists|i: int| 0 <= i < event@.len() + && (forall|j: int| 0 <= j < i ==> byte_validation_observed(store, j, event@[j] as u64, true)) + && byte_validation_observed(store, i, event@[i] as u64, false) + && result == Err(HistoryError::UnknownId { domain: "component", id: event@[i] as u64 })) + } + } + + pub proof fn lemma_byte_validation_observed(store: &HistoryStore, index: int, id: u64, known: bool) + requires byte_validation_observed(store, index, id, known), + ensures exists|view: DomainView| byte_domain_transaction(store, index, view, view) + && domain_wf(view) && known == view.ids.contains(id), + { reveal(byte_validation_observed); } + + pub proof fn lemma_event_validation_result_facts(store: &HistoryStore, event: Event, + result: Result<(), HistoryError>) + requires event_validation_result(store, event, result), + ensures result matches Err(error) ==> event_validation_error(event, error), + result is Ok ==> event@.len() == store.arity_spec() + && (forall|i: int| 0 <= i < event@.len() + ==> byte_validation_observed(store, i, event@[i] as u64, true)), + result matches Err(HistoryError::UnknownId { domain, id }) ==> + domain == "component" && event@.len() == store.arity_spec() + && (exists|i: int| 0 <= i < event@.len() && id == event@[i] + && byte_validation_observed(store, i, id, false) + && (forall|j: int| 0 <= j < i + ==> byte_validation_observed(store, j, event@[j] as u64, true))), + result matches Err(HistoryError::InvalidPolicy { .. }) ==> event@.len() != store.arity_spec(), + { + if let Err(HistoryError::UnknownId { domain, id }) = result { + let i = choose|i: int| 0 <= i < event@.len() + && (forall|j: int| 0 <= j < i ==> byte_validation_observed(store, j, event@[j] as u64, true)) + && byte_validation_observed(store, i, event@[i] as u64, false) + && result == Err(HistoryError::UnknownId { domain: "component", id: event@[i] as u64 }); + assert(event@[i] <= u64::MAX); + assert(id == event@[i]); + } + } + + /// Errors retain the absent numeric coordinate or report an event/store arity mismatch. + pub open spec fn event_validation_error(event: Event, error: HistoryError) -> bool { + event_arity_error(error) || exists|i: int| 0 <= i < event@.len() + && error == (HistoryError::UnknownId { domain: "component", id: event@[i] as u64 }) + } + + #[verifier::prophetic] + pub open(crate) spec fn append_result(store: &HistoryStore, history: HistoryHandle, + events: Seq, result: Result<(), HistoryError>) -> bool { + if reference_identity(store) != handle_owner_identity(history) { + result == Err(HistoryError::WrongHistoryOwner) + } else if events.len() == 0 { + result == Ok(()) + } else { + result != Err(HistoryError::WrongHistoryOwner) + && ((exists|i: int, error: HistoryError| 0 <= i < events.len() + && result == Err(error) && event_validation_error(events[i], error)) + || record_append_observed(history, events, result)) + } + } + + #[verifier::prophetic] + pub open(crate) spec fn truncate_result(store: &HistoryStore, history: HistoryHandle, + len: usize, result: Result<(), HistoryError>) -> bool { + if reference_identity(store) != handle_owner_identity(history) { + result == Err(HistoryError::WrongHistoryOwner) + } else { record_truncate_observed(history, len, result) } + } + + pub open(crate) spec fn len_result(store: &HistoryStore, history: HistoryHandle, + result: Result) -> bool { + if reference_identity(store) != handle_owner_identity(history) { + result == Err(HistoryError::WrongHistoryOwner) + } else { + exists|record: HistoryRecord, guard: HistoryRecordReadGuard| + record_view(record) == history.record && record_read_observed(record, guard) + && result == Ok(guard.stored_view()@.events.len() as usize) + } + } + + pub proof fn lemma_history_created(history: HistoryHandle) + requires handle_wf(history), history_created(history), + ensures exists|stored: StoredHistory| stored.spec_id() == handle_index(history) + && stored@.events == Seq::::empty() && stored@.revision == 0, + { + reveal(history_created); + let stored = choose|stored: StoredHistory| record_installed(history.record, stored) + && stored.spec_id() == handle_index(history) + && crate::history::verify::stored_events(&stored) == Seq::::empty() + && stored.spec_revision() == 0; + crate::history::lemma_stored_history_view(stored); + } + + pub proof fn lemma_record_transaction_ids(history: HistoryHandle, + before: StoredHistory, after: StoredHistory) + requires handle_wf(history), record_transaction(history, before, after), + ensures before.spec_id() == handle_index(history), after.spec_id() == handle_index(history), + {} + + pub proof fn lemma_record_append_observed(history: HistoryHandle, events: Seq, + result: Result<(), HistoryError>) + requires handle_wf(history), record_append_observed(history, events, result), + ensures exists|before: StoredHistory, after: StoredHistory| + record_transaction(history, before, after) + && before.spec_id() == handle_index(history) && after.spec_id() == handle_index(history) + && crate::history::verify::stored_append_result(before, after, events, result), + {} + + pub proof fn lemma_record_truncate_observed(history: HistoryHandle, len: usize, + result: Result<(), HistoryError>) + requires handle_wf(history), record_truncate_observed(history, len, result), + ensures exists|before: StoredHistory, after: StoredHistory| + record_transaction(history, before, after) + && before.spec_id() == handle_index(history) && after.spec_id() == handle_index(history) + && crate::history::verify::stored_truncate_result(before, after, len, result), + {} + + pub proof fn lemma_append_result_facts(store: &HistoryStore, history: HistoryHandle, + events: Seq, result: Result<(), HistoryError>) + requires append_result(store, history, events, result), + ensures (result == Err(HistoryError::WrongHistoryOwner)) + == (reference_identity(store) != handle_owner_identity(history)), + reference_identity(store) == handle_owner_identity(history) && events.len() == 0 + ==> result == Ok(()), + events.len() > 0 && result is Ok ==> record_append_observed(history, events, result), + reference_identity(store) == handle_owner_identity(history) && events.len() > 0 + ==> (exists|i: int, error: HistoryError| 0 <= i < events.len() + && result == Err(error) && event_validation_error(events[i], error)) + || record_append_observed(history, events, result), + {} + + pub proof fn lemma_truncate_result_facts(store: &HistoryStore, history: HistoryHandle, + len: usize, result: Result<(), HistoryError>) + requires truncate_result(store, history, len, result), + ensures (result == Err(HistoryError::WrongHistoryOwner)) + == (reference_identity(store) != handle_owner_identity(history)), + reference_identity(store) == handle_owner_identity(history) + ==> record_truncate_observed(history, len, result), + {} + + pub proof fn lemma_len_result_facts(store: &HistoryStore, history: HistoryHandle, + result: Result) + requires handle_wf(history), len_result(store, history, result), + ensures (result is Ok) == (reference_identity(store) == handle_owner_identity(history)), + result is Err ==> result == Err(HistoryError::WrongHistoryOwner), + result is Ok ==> exists|guard: HistoryRecordReadGuard| guard.valid() + && guard.record_id() == handle_index(history) + && guard.lifecycle_id() == handle_lifecycle_id(history) + && guard.snapshot_view().id() == handle_lifecycle_id(history) + && guard.snapshot_view().value() == guard.stored_view()@ + && result == Ok(guard.stored_view()@.events.len() as usize), + { + reveal(handle_lifecycle_id); + reveal(HistoryRecord::record_id); + reveal(HistoryRecord::lifecycle_id); + if result is Ok { + let (record, guard) = choose|record: HistoryRecord, guard: HistoryRecordReadGuard| + record_view(record) == history.record && record_read_observed(record, guard) + && result == Ok(guard.stored_view()@.events.len() as usize); + guard.lemma_observation(); + } + } + pub open(super) spec fn handle_clone_frame(before: HistoryHandle, after: HistoryHandle) -> bool { + before.owner == after.owner && handle_owner_identity(before) == handle_owner_identity(after) + && before.index == after.index && before.record == after.record + && before.global_registration@.id() == after.global_registration@.id() + && before.global_registration@@ == after.global_registration@@ + } + pub open(crate) spec fn singleton_valid(arity: nat) -> bool { + let store = singleton_store(arity); + 1 <= arity <= MAX_ARITY && store.arity_spec() == arity + && store.domains@.len() == arity + && store.authorities == numeric_authorities() + && coordinates_mutex_valid(store.authorities.coordinates) + && history_keys_mutex_valid(store.authorities.history_keys) + && (forall|i: int| 0 <= i < arity ==> native_domain_valid(store.domains@[i]) + && native_domain_index(store.domains@[i]) == i) + } + /// The store is the process-wide singleton of its arity, with its static authorities installed. + pub open(crate) spec fn numeric_store_wf(store: HistoryStore) -> bool { + 1 <= store.arity_spec() <= MAX_ARITY && store == *singleton_store(store.arity_spec()) + && singleton_valid(store.arity_spec()) + } + + pub uninterp spec fn coordinate_ids(wrapper: NativeCoordinates) -> Seq; + pub uninterp spec fn coordinates_mutex_valid(wrapper: NativeCoordinates) -> bool; + pub open(crate) spec fn coordinates_acquired(state: CoordinateState, wrapper: NativeCoordinates) -> bool { + coordinate_wf(state) && forall|d: int| 0 <= d < MAX_ARITY ==> coordinate_id(state,d) == coordinate_ids(wrapper)[d] + } + pub uninterp spec fn history_keys_id(wrapper: NativeHistoryKeys) -> vstd::resource::Loc; + pub uninterp spec fn history_keys_mutex_valid(wrapper: NativeHistoryKeys) -> bool; + pub open(crate) spec fn history_keys_acquired(state: HistoryKeyState, wrapper: NativeHistoryKeys) -> bool { + history_key_wf(state) && state.issued@.id() == history_keys_id(wrapper) + } + + pub(crate) fn allocator_stale_and_drop_client() { + let mut coordinates = CoordinateState::new(); + let ghost original = coordinates; + let stale = allocate_coordinate_state(&mut coordinates, 0, "component", 1, + Ghost(ComponentIssuer::Byte), Tracked(None)); + assert(stale is Err); + assert(coordinates.next@[0] == 2); + assert(coordinate_map(coordinates,0).contains_key(1)); + let second = allocate_coordinate_state(&mut coordinates, 0, "component", 0, + Ghost(ComponentIssuer::Byte), Tracked(None)); + assert(second is Ok); + assert(second.unwrap().0 == 2); + assert(coordinate_map(coordinates,0).contains_key(1)); + assert(coordinate_map(coordinates,0).contains_key(2)); + // A consumer may fail after issuance and discard its persistent receipt. + let third = allocate_coordinate_state(&mut coordinates, 0, "component", 0, + Ghost(ComponentIssuer::Byte), Tracked(None)); + assert(third is Ok); + assert(third.unwrap().0 == 3); + assert(coordinate_frame(original,coordinates)); + let ghost before_invalid = coordinates; + let invalid = allocate_coordinate_state(&mut coordinates, MAX_ARITY, "component", 0, + Ghost(ComponentIssuer::Byte), Tracked(None)); + assert(invalid is Err); + assert(coordinates.next == before_invalid.next); + assert forall|d: int| 0 <= d < MAX_ARITY implies coordinate_map(coordinates,d) == coordinate_map(before_invalid,d) by {} + let mut histories = HistoryKeyState::new(); + let stale = allocate_history_state(&mut histories, 1, Ghost(HistoryIssuer::Byte)); + assert(stale is Err); + assert(histories.next == 2); + assert((histories.issued@)@.contains_key(1)); + let second = allocate_history_state(&mut histories, 0, Ghost(HistoryIssuer::Byte)); + assert(second is Ok); + assert(second.unwrap().0 == 2); + assert((histories.issued@)@.contains_key(1)); + assert((histories.issued@)@.contains_key(2)); + let ghost before_max = histories; + let exhausted = allocate_history_state(&mut histories, usize::MAX, Ghost(HistoryIssuer::Byte)); + assert(exhausted == Err(HistoryError::IdExhausted { domain: "history" })); + assert(histories.next == before_max.next); + assert((histories.issued@)@ == (before_max.issued@)@); + } + pub(crate) fn allocator_arithmetic_exhaustion_client(coordinates: &mut CoordinateState, + histories: &mut HistoryKeyState) + requires coordinate_wf(*old(coordinates)), old(coordinates).next@[0] == u64::MAX, + history_key_wf(*old(histories)), old(histories).next == usize::MAX, + ensures final(coordinates).next == old(coordinates).next, + coordinate_map(*final(coordinates),0) == coordinate_map(*old(coordinates),0), + final(histories).next == old(histories).next, + (final(histories).issued@)@ == (old(histories).issued@)@, + { + let component = allocate_coordinate_state(coordinates,0,"component",0, + Ghost(ComponentIssuer::Byte),Tracked(None)); + assert(component is Err); + let history = allocate_history_state(histories,0,Ghost(HistoryIssuer::Byte)); + assert(history is Err); + } + + pub(crate) fn allocator_later_failure_client() { + let mut coordinates = CoordinateState::new(); + let failure: Result<(), HistoryError> = match allocate_coordinate_state(&mut coordinates, + 0, "component", 0, Ghost(ComponentIssuer::Byte), Tracked(None)) { + Ok((_id, _receipt)) => Err(HistoryError::AllocationFailed), + Err(error) => Err(error), + }; + assert(failure == Err(HistoryError::AllocationFailed)); + let second = allocate_coordinate_state(&mut coordinates, 0, "component", 0, + Ghost(ComponentIssuer::Byte), Tracked(None)); + assert(second matches Ok((id, _)) && id == 2); + assert(coordinate_map(coordinates, 0).contains_key(1)); + assert(coordinate_map(coordinates, 0).contains_key(2)); + + let mut histories = HistoryKeyState::new(); + let failure: Result<(), HistoryError> = match allocate_history_state(&mut histories, + 0, Ghost(HistoryIssuer::Byte)) { + Ok((_id, _receipt)) => Err(HistoryError::AllocationFailed), + Err(error) => Err(error), + }; + assert(failure == Err(HistoryError::AllocationFailed)); + let second = allocate_history_state(&mut histories, 0, Ghost(HistoryIssuer::Byte)); + assert(second matches Ok((id, _)) && id == 2); + assert((histories.issued@)@.contains_key(1)); + assert((histories.issued@)@.contains_key(2)); + } + + pub(crate) fn allocator_last_legal_key_client(coordinates: &mut CoordinateState, + histories: &mut HistoryKeyState) + requires coordinate_wf(*old(coordinates)), old(coordinates).next@[0] == u64::MAX - 1, + history_key_wf(*old(histories)), old(histories).next == usize::MAX - 1, + ensures coordinate_frame(*old(coordinates), *final(coordinates)), + final(coordinates).next@[0] == u64::MAX, + coordinate_map(*final(coordinates), 0) == coordinate_map(*old(coordinates), 0).insert((u64::MAX - 1) as u64, ComponentIssuer::Byte), + history_key_frame(*old(histories), *final(histories)), final(histories).next == usize::MAX, + (final(histories).issued@)@ == (old(histories).issued@)@.insert((usize::MAX - 1) as usize, HistoryIssuer::Byte), + { + let component = allocate_coordinate_state(coordinates, 0, "component", 0, + Ghost(ComponentIssuer::Byte), Tracked(None)); + assert(component matches Ok((id, _)) && id == u64::MAX - 1); + let exhausted = allocate_coordinate_state(coordinates, 0, "component", 0, + Ghost(ComponentIssuer::Byte), Tracked(None)); + assert(exhausted == Err(HistoryError::IdExhausted { domain: "component" })); + let history = allocate_history_state(histories, 0, Ghost(HistoryIssuer::Byte)); + assert(history matches Ok((id, _)) && id == usize::MAX - 1); + let exhausted = allocate_history_state(histories, 0, Ghost(HistoryIssuer::Byte)); + assert(exhausted == Err(HistoryError::IdExhausted { domain: "history" })); + } + + pub open(crate) spec fn coordinate_map(state: CoordinateState, index: int) -> Map { + state.authorities@.entries[index]@ + } + pub open(crate) spec fn coordinate_id(state: CoordinateState, index: int) -> vstd::resource::Loc { + state.authorities@.entries[index].id() + } + pub open(crate) spec fn coordinate_wf(state: CoordinateState) -> bool { + state.authorities@.entries.len() == MAX_ARITY + && forall|d: int| 0 <= d < MAX_ARITY ==> state.next@[d] > 0 + && (forall|id: u64| coordinate_map(state, d).contains_key(id) <==> 0 < id < state.next@[d]) + } + pub open(crate) spec fn coordinate_frame(before: CoordinateState, after: CoordinateState) -> bool { + coordinate_wf(after) && forall|d: int| 0 <= d < MAX_ARITY ==> + coordinate_id(before, d) == coordinate_id(after, d) + && coordinate_map(before, d).submap_of(coordinate_map(after, d)) + } + pub open(crate) spec fn coordinate_prior(state: CoordinateState, index: usize, + prior: Option<&ComponentReceipts>) -> bool { + match prior { None => true, Some(previous) => index < MAX_ARITY && previous.id() == coordinate_id(state, index as int) } + } + pub open(crate) spec fn coordinate_result(before: CoordinateState, after: CoordinateState, + index: usize, domain: &'static str, last: u64, issuer: ComponentIssuer, prior: Option<&ComponentReceipts>, + result: Result<(u64, Tracked), HistoryError>) -> bool { + coordinate_frame(before, after) + && (index < MAX_ARITY && (last == 0 || match prior { + Some(previous) => previous@.contains_key(last), None => false, + }) ==> (result matches Err(error) ==> error == HistoryError::IdExhausted { domain })) + && if index >= MAX_ARITY { + after.next == before.next && (forall|d: int| 0 <= d < MAX_ARITY ==> coordinate_map(after,d) == coordinate_map(before,d)) + && result == Err(HistoryError::Invariant { message: "invalid identity domain" }) + } else if before.next@[index as int] == u64::MAX { + after.next == before.next && (forall|d: int| 0 <= d < MAX_ARITY ==> coordinate_map(after,d) == coordinate_map(before,d)) + && result == Err(HistoryError::IdExhausted { domain }) + } else { + let id = before.next@[index as int]; + after.next@ == before.next@.update(index as int, (id + 1) as u64) + && (forall|d: int| 0 <= d < MAX_ARITY ==> coordinate_map(after,d) == + if d == index { coordinate_map(before,d).insert(id,issuer) } else { coordinate_map(before,d) }) + && if id <= last { result == Err(HistoryError::Invariant { message: "identity allocator moved backwards" }) } + else { match result { Ok((key, receipt)) => key == id && 0 < key < u64::MAX + && receipt@.id() == coordinate_id(after,index as int) && receipt@@ == (key,issuer) + && (match prior { None => true, Some(previous) => forall|k: u64| previous@.contains_key(k) ==> k < key }), + Err(_) => false } } + } + } + pub open(crate) spec fn history_key_wf(state: HistoryKeyState) -> bool { + state.next > 0 && forall|id: usize| (state.issued@)@.contains_key(id) <==> 0 < id < state.next + } + pub open(crate) spec fn history_key_frame(before: HistoryKeyState, after: HistoryKeyState) -> bool { + history_key_wf(after) && before.issued@.id() == after.issued@.id() + && (before.issued@)@.submap_of((after.issued@)@) + } + pub open(crate) spec fn history_key_result(before: HistoryKeyState, after: HistoryKeyState, + last: usize, issuer: HistoryIssuer, result: Result<(usize, Tracked), HistoryError>) -> bool { + history_key_frame(before,after) && if last == usize::MAX || before.next == usize::MAX { + after.next == before.next && (after.issued@)@ == (before.issued@)@ + && result == Err(HistoryError::IdExhausted { domain: "history" }) + } else { + after.next == before.next + 1 && (after.issued@)@ == (before.issued@)@.insert(before.next,issuer) + && if before.next <= last { result == Err(HistoryError::Invariant { message: "history identity allocator moved backwards" }) } + else { match result { Ok((key,receipt)) => key == before.next && 0 < key < usize::MAX + && receipt@.id() == after.issued@.id() && receipt@@ == (key,issuer), Err(_) => false } } + } + } + pub(crate) proof fn empty_coordinate_authorities(count: nat) -> (tracked result: CoordinateAuthorities) + ensures result.entries.len() == count, + forall|i: int| 0 <= i < count ==> result.entries[i]@ == Map::empty(), + decreases count, + { + if count == 0 { + CoordinateAuthorities { entries: Seq::tracked_empty() } + } else { + let tracked mut result = empty_coordinate_authorities((count - 1) as nat); + let tracked (authority, _) = vstd::resource::map::GhostMapAuth::new(Map::empty()); + result.entries.tracked_push(authority); + assert forall|i: int| 0 <= i < count implies result.entries[i]@ == Map::empty() by { + if i < count - 1 { assert(result.entries[i]@ == Map::empty()); } + } + result + } + } + pub(crate) proof fn empty_history_authority() -> (tracked result: vstd::resource::map::GhostMapAuth) + ensures result@ == Map::empty(), + { + let tracked (authority, _) = vstd::resource::map::GhostMapAuth::new(Map::empty()); + authority + } + + /// One process-wide store per arity, installed by `HistoryStore::new`. + pub uninterp spec fn singleton_store(arity: nat) -> Arc; + pub(crate) uninterp spec fn numeric_authorities() -> Arc; + pub open(crate) spec fn coordinate_authority(index: int) -> vstd::resource::Loc { + coordinate_ids(numeric_authorities().coordinates)[index] + } + pub open(crate) spec fn history_authority() -> vstd::resource::Loc { + history_keys_id(numeric_authorities().history_keys) + } + + use junco_core::verify::history_specs as language; + impl View for Event { + type V = language::EventView; + open(crate) spec fn view(&self) -> language::EventView { + Seq::new(self.arity as nat, |i: int| self.slots@[i] as nat) + } + } + impl vstd::std_specs::cmp::PartialEqSpecImpl for Event { + open spec fn obeys_eq_spec() -> bool { true } + open spec fn eq_spec(&self, other: &Self) -> bool { self@ == other@ } + } + pub open spec fn events_view(events: Seq) -> Seq { + Seq::new(events.len(), |i: int| events[i]@) + } + + // Default's trait contract is public; its model is visible but predicate bodies stay local. + pub struct DomainView { + pub paths: Map, nat>, + pub ids: Set, + } + + #[verifier::opaque] + pub(super) open spec fn path_map(paths: BTreeMap, u64>) -> Map, nat> { + Map::new( + paths@.dom().map(|path: Vec| path@), + |bytes: Seq| { + let path = choose|path: Vec| paths@.contains_key(path) + && path@ == bytes; + paths@[path] as nat + }, + ) + } + + + pub open spec fn domain_wf(domain: DomainView) -> bool { + language::interner_wf(domain.paths, u64::MAX as nat) + && (forall|id: u64| domain.ids.contains(id) + <==> domain.paths.values().contains(id as nat)) + } + pub open(super) spec fn domain_unissued(domain: Domain) -> bool { domain.issued@ is None } + + pub open(super) spec fn domain_provenance(domain: Domain, index: int) -> bool { + match domain.issued@ { + None => domain.ids@ == Set::empty(), + Some(receipts) => receipts.id() == coordinate_authority(index) + && receipts@.dom() == domain.ids@ + && forall|id: u64| receipts@.contains_key(id) ==> receipts@[id] == ComponentIssuer::Byte, + } + } + + pub(super) open spec fn domain_forward_authority(domain: Domain) -> vstd::resource::Loc { + domain.bindings@.forward.id() + } + pub(super) open spec fn domain_reverse_authority(domain: Domain) -> vstd::resource::Loc { + domain.bindings@.reverse.id() + } + pub open(super) spec fn domain_bindings_wf(domain: Domain) -> bool { + let bindings = domain.bindings@; + bindings.paths.id() == bindings.forward.id() && bindings.ids.id() == bindings.reverse.id() + && bindings.paths@ == bindings.forward@ && bindings.ids@ == bindings.reverse@ + && bindings.forward@.dom() == domain@.paths.dom() + && (forall|path: Seq| domain@.paths.contains_key(path) + ==> bindings.forward@[path] as nat == domain@.paths[path]) + && bindings.reverse@.dom() == domain@.ids + && (forall|id: u64| domain@.ids.contains(id) + ==> domain@.paths.contains_key(bindings.reverse@[id]) + && domain@.paths[bindings.reverse@[id]] == id as nat) + && (forall|path: Seq| domain@.paths.contains_key(path) + ==> bindings.reverse@.contains_key(bindings.forward@[path]) + && bindings.reverse@[bindings.forward@[path]] == path) + } + + pub open(crate) spec fn record_view(record: HistoryRecord) -> NativeRecord { record.native } + + /// A lock-local read observation, not a mutable state attached to a shared record. + pub open(crate) spec fn record_read_observed(record: HistoryRecord, guard: HistoryRecordReadGuard) -> bool { + guard.valid() && guard.native_record() == record.native + && guard.record_id() == record.record_id() + && guard.lifecycle_id() == record.lifecycle_id() + && guard.stored_view().spec_id() == record.record_id() + && guard.snapshot_view().id() == record.lifecycle_id() + && guard.snapshot_view().value() == guard.stored_view()@ + } +} +} + +/// The process-wide synchronized byte identities and numeric ID allocators. +/// +/// Every handle owns its record; this owner never retains histories, runtimes or caches. +#[verus_verify] +#[verus_verify(external_derive)] +#[cfg_attr(not(verus_keep_ghost), derive(Debug))] +pub struct HistoryStore { + pub(crate) domains: Vec, + pub(crate) authorities: Arc, +} + +#[verus_verify] +#[verus_verify(external_derive)] +#[cfg_attr(not(verus_keep_ghost), derive(Debug))] +pub(crate) struct NumericAuthorities { + pub(crate) coordinates: NativeCoordinates, + pub(crate) history_keys: NativeHistoryKeys, +} + +/// A shared history reference. Cloning it never copies events. +#[verus_verify] +#[verus_verify(external_derive)] +#[cfg_attr(not(verus_keep_ghost), derive(Debug))] +pub struct HistoryHandle { + pub(crate) owner: Arc, + pub(crate) index: usize, + pub(crate) record: NativeRecord, + #[cfg(verus_keep_ghost)] + pub(crate) global_registration: Tracked, +} + +impl HistoryHandle { + #[verus_verify] + /// Return the opaque, never-reused process-wide history ID. + #[verus_spec(result => requires handle_wf(*self), ensures result == handle_index(*self))] + pub const fn index(&self) -> usize { + self.index + } + + /// Check exact native owner identity without exposing the store or a mutable record. + #[verus_verify] + #[verus_spec(result => ensures + result == (reference_identity(store) == handle_owner_identity(*self)), + result ==> *store == *handle_owner(*self))] + pub fn belongs_to(&self, store: &HistoryStore) -> bool { + let owner = borrow_numeric_owner(&self.owner); + same_numeric_reference(store, owner) + } +} + +// Native Arc dereference and reference pointer comparison are the only owner leaves. +#[doc(hidden)] +#[verus_verify(external_body)] +#[verus_spec(result => ensures *result == **owner, + reference_identity(result) == arc_identity(*owner))] +pub fn borrow_numeric_owner(owner: &Arc) -> &HistoryStore { + owner.as_ref() +} + +#[verus_verify(external_body)] +#[verus_spec(result => ensures + result == (reference_identity(left) == reference_identity(right)), + result ==> *left == *right)] +fn same_numeric_reference(left: &HistoryStore, right: &HistoryStore) -> bool { + core::ptr::eq(left, right) +} + +#[verus_verify(external_body)] +#[verus_spec(result => ensures result == *owner, *result == **owner, + arc_identity(result) == arc_identity(*owner))] +fn share_numeric_owner(owner: &Arc) -> Arc { + Arc::clone(owner) +} + +#[verus_verify] +impl Clone for HistoryHandle { + #[verus_spec(result => ensures handle_wf(*self) ==> handle_wf(result), handle_clone_frame(*self, result))] + fn clone(&self) -> Self { + proof_decl! { let tracked receipt = self.global_registration.borrow().duplicate(); } + Self { + owner: share_numeric_owner(&self.owner), + index: self.index, + record: self.record.clone(), + #[cfg(verus_keep_ghost)] + global_registration: verus_exec_expr! { Tracked(receipt) }, + } + } +} +#[cfg(verus_keep_ghost)] +verus! { +impl HistoryHandle { + pub(crate) proof fn history_key_receipt_ref(tracked &self) -> (tracked result: &HistoryKeyReceipt) + requires handle_wf(*self), + ensures result.id() == history_authority(), result@ == (handle_index(*self), HistoryIssuer::Byte), + { self.global_registration.borrow() } +} +} + +/// A shared read-only history record. Mutations remain transactions on `HistoryStore`. +/// +/// A record never grants the write capability needed to replace another history's word: +/// +/// ```compile_fail +/// use history_store::store::HistoryRecord; +/// fn swap_histories(left: &HistoryRecord, right: &HistoryRecord) { +/// let mut left = left.read(); +/// let mut right = right.read(); +/// core::mem::swap(&mut *left, &mut *right); +/// } +/// ``` +/// +/// ```compile_fail +/// use history_store::store::HistoryRecord; +/// fn write_history(record: &HistoryRecord) { +/// let _guard = record.write(); +/// } +/// ``` +#[verus_verify] +#[verus_verify(external_derive)] +#[cfg_attr(not(verus_keep_ghost), derive(Debug))] +pub struct HistoryRecord { + pub(crate) native: NativeRecord, +} + +#[verus_verify] +impl HistoryRecord { + #[verus_spec(result => requires record_valid(native), + ensures record_view(result) == native, result.valid(), + result.record_id() == native.record_id(), result.lifecycle_id() == native.lifecycle_id())] + pub(crate) fn from_native(native: NativeRecord) -> Self { + Self { native } + } + + /// Hold a read lock without exposing the underlying lock or its write capability. + /// The retained snapshot describes this acquisition, not an unlocked future state. + #[verus_spec(result => requires self.valid(), + ensures record_read_observed(*self, result), result.valid(), + result.record_id() == self.record_id(), result.lifecycle_id() == self.lifecycle_id(), + result.stored_view().spec_id() == self.record_id(), + result.snapshot_view().id() == self.lifecycle_id(), + result.snapshot_view().value() == result.stored_view()@, + result.snapshot_view().value().events == events_view(crate::history::verify::stored_events(&result.stored_view())), + result.snapshot_view().value().revision == result.stored_view().spec_revision(), + result.snapshot_view().value().events.len() == crate::history::verify::stored_events(&result.stored_view()).len())] + pub fn read(&self) -> HistoryRecordReadGuard<'_> { + let guard = NativeRecordReadGuard::acquire(&self.native); + #[cfg(verus_keep_ghost)] + let cell = guard.cell(); + proof_decl! { let tracked snapshot = cell.lifecycle.borrow().observe(); } + proof! { crate::history::lemma_stored_history_view(cell.stored); } + HistoryRecordReadGuard { + guard, + #[cfg(verus_keep_ghost)] + snapshot: verus_exec_expr! { Tracked(snapshot) }, + } + } +} + +#[verus_verify] +impl Clone for HistoryRecord { + #[verus_spec(result => ensures result == *self, self.valid() ==> result.valid())] + fn clone(&self) -> Self { + Self { + native: self.native.clone(), + } + } +} + +/// A borrowed record view. The native guard stays private because it can reveal its lock. +/// +/// ```compile_fail +/// use history_store::store::HistoryRecord; +/// fn recover_native_guard(record: &HistoryRecord) { +/// let _native_guard = record.read().guard; +/// } +/// ``` +#[verus_verify] +pub struct HistoryRecordReadGuard<'a> { + guard: NativeRecordReadGuard<'a>, + #[cfg(verus_keep_ghost)] + snapshot: Tracked, +} + +#[verus_verify] +impl core::ops::Deref for HistoryRecordReadGuard<'_> { + type Target = StoredHistory; + + #[verus_spec(result => ensures *result == self.stored_view())] + fn deref(&self) -> &Self::Target { + let cell = self.guard.cell(); + &cell.stored + } +} + +#[verus_verify] +impl HistoryRecordReadGuard<'_> { + /// Validate an actual retained snapshot against the lifecycle held by this read lock. + #[doc(hidden)] + #[cfg(verus_keep_ghost)] + #[verus_spec(requires self.valid(), previous@.id() == self.lifecycle_id(), + ensures previous@.value().revision <= self.snapshot_view().value().revision, + previous@.value().revision == self.snapshot_view().value().revision + ==> previous@.value().events.is_prefix_of(self.snapshot_view().value().events))] + pub fn validate_snapshot(&self, previous: Tracked<&crate::history::verify::Snapshot>) { + let cell = self.guard.cell(); + proof! { + let tracked snapshot = previous.get(); + cell.lifecycle.borrow().validate(snapshot); + } + } +} + +// Only native read-lock acquisition and fidelity of a borrow under that guard are trusted. +#[verus_verify] +#[verus_verify(external_body)] +struct NativeRecordReadGuard<'a> { + guard: RwLockReadGuard<'a, RecordCell>, +} + +#[verus_verify] +impl<'a> NativeRecordReadGuard<'a> { + #[verus_verify(external_body)] + #[verus_spec(result => requires record_valid(*record), + ensures result.record_view() == *record, record_acquired(result.cell_view(), *record))] + fn acquire(record: &'a NativeRecord) -> Self { + Self { + guard: record.inner.read(), + } + } + + #[verus_verify(external_body)] + #[verus_spec(result => ensures *result == self.cell_view())] + fn cell(&self) -> &RecordCell { + &self.guard + } +} + +#[cfg(verus_keep_ghost)] +verus! { +impl NativeRecordReadGuard<'_> { + uninterp spec fn cell_view(self) -> RecordCell; + uninterp spec fn record_view(self) -> NativeRecord; +} + +impl HistoryRecord { + pub open(crate) spec fn valid(&self) -> bool { record_valid(self.native) } + pub open(crate) spec fn record_id(&self) -> usize { self.native.record_id() } + pub open(crate) spec fn lifecycle_id(&self) -> vstd::resource::Loc { self.native.lifecycle_id() } +} + +impl HistoryRecordReadGuard<'_> { + /// The exact stored payload borrowed while this read lock is held. + pub closed spec fn stored_view(&self) -> StoredHistory { self.guard.cell_view().stored } + /// The persistent observation retained from this read acquisition. + pub closed spec fn snapshot_view(&self) -> crate::history::verify::Snapshot { self.snapshot@ } + pub closed spec fn record_id(&self) -> usize { self.guard.record_view().record_id() } + pub closed spec fn lifecycle_id(&self) -> vstd::resource::Loc { self.guard.record_view().lifecycle_id() } + pub(crate) closed spec fn native_record(&self) -> NativeRecord { self.guard.record_view() } + pub closed spec fn valid(&self) -> bool { + record_acquired(self.guard.cell_view(), self.guard.record_view()) + && self.snapshot@.id() == self.lifecycle_id() + && self.snapshot@.value() == self.stored_view()@ + } + + pub proof fn snapshot_ref(tracked &self) -> (tracked result: &crate::history::verify::Snapshot) + requires self.valid(), + ensures *result == self.snapshot_view(), result.id() == self.lifecycle_id(), + result.value() == self.stored_view()@, + { self.snapshot.borrow() } + + /// Retain evidence after releasing the guard, without copying any native events. + pub proof fn snapshot(tracked &self) -> (tracked result: crate::history::verify::Snapshot) + requires self.valid(), + ensures result.id() == self.lifecycle_id(), result.value() == self.stored_view()@, + result@ == self.snapshot_view()@, + { self.snapshot.borrow().duplicate() } + + pub proof fn lemma_observation(&self) + requires self.valid(), + ensures self.stored_view().spec_id() == self.record_id(), + self.snapshot_view().id() == self.lifecycle_id(), + self.snapshot_view().value() == self.stored_view()@, + self.snapshot_view().value().events == events_view(crate::history::verify::stored_events(&self.stored_view())), + self.snapshot_view().value().revision == self.stored_view().spec_revision(), + self.snapshot_view().value().events.len() == crate::history::verify::stored_events(&self.stored_view()).len(), + { crate::history::lemma_stored_history_view(self.stored_view()); } +} +} + +#[verus_verify] +impl HistoryStore { + /// Return the process-wide store for `arity`, sharing numeric issuance across all arities. + /// Panics unless `1 <= arity <= MAX_ARITY`. + // Native static initialization and Arc allocation; no user code runs under this lock. + #[verus_verify(external_body)] + #[verus_spec(result => requires 1 <= arity <= MAX_ARITY, + ensures result == singleton_store(arity as nat), singleton_valid(arity as nat), + numeric_store_wf(*result), result.arity_spec() == arity, + arc_identity(result) == arc_identity(singleton_store(arity as nat)))] + pub fn new(arity: usize) -> Arc { + assert!( + (1..=MAX_ARITY).contains(&arity), + "event arity must be between 1 and MAX_ARITY" + ); + let mut registry = STORES.lock(); + let registry = registry.get_or_insert_with(|| StoreRegistry { + authorities: Arc::new(NumericAuthorities { + coordinates: NativeCoordinates::new(), + history_keys: NativeHistoryKeys::new(), + }), + stores: core::array::from_fn(|_| None), + }); + if let Some(store) = ®istry.stores[arity - 1] { + return Arc::clone(store); + } + let mut domains = Vec::with_capacity(arity); + for _index in 0..arity { + domains.push(NativeDomain::new(verus_exec_expr! { Ghost(_index) })); + } + let store = Arc::new(Self { + domains, + authorities: Arc::clone(®istry.authorities), + }); + registry.stores[arity - 1] = Some(Arc::clone(&store)); + store + } + + #[cfg(verus_keep_ghost)] + verus! { + pub closed spec fn arity_spec(&self) -> nat { self.domains@.len() } + } + + #[verus_spec(result => ensures result == self.arity_spec())] + pub fn arity(&self) -> usize { + self.domains.len() + } + + /// Issue a component ID above `last` from the counters shared by byte and typed views, + /// so a numeric event from one view can never name another view's identity. + #[verus_spec(result => + requires numeric_store_wf(*self), + match prior@ { None => true, Some(previous) => index < MAX_ARITY && previous.id() == coordinate_authority(index as int) }, + ensures result matches Ok((id, receipt)) ==> last < id < u64::MAX + && receipt@.id() == coordinate_authority(index as int) && receipt@@ == (id, issuer@) + && (match prior@ { None => true, Some(previous) => forall|key: u64| previous@.contains_key(key) ==> key < id }), + result != Err(HistoryError::WrongHistoryOwner), + index < MAX_ARITY && (last == 0 || match prior@ { + Some(previous) => previous@.contains_key(last), None => false, + }) ==> (result matches Err(error) ==> error == HistoryError::IdExhausted { domain }), + )] + pub(crate) fn allocate_after( + &self, + index: usize, + domain: &'static str, + last: u64, + issuer: Ghost, + prior: Tracked>, + ) -> Result<(u64, Tracked), HistoryError> { + proof! { reveal(coordinate_authority); } + self.authorities.coordinates.with_state((index, domain, last, issuer, prior), + verus_exec_expr! { + |state: &mut CoordinateState, context: (usize, &'static str, u64, Ghost, Tracked>)| + -> (result: Result<(u64, Tracked), HistoryError>) + requires coordinates_acquired(*old(state), self.authorities.coordinates), + coordinate_prior(*old(state), context.0, context.4@), + ensures coordinate_result(*old(state), *final(state), context.0, context.1, context.2, context.3@, context.4@, result), + result != Err(HistoryError::WrongHistoryOwner), + context.0 < MAX_ARITY && (context.2 == 0 || match context.4@ { + Some(previous) => previous@.contains_key(context.2), None => false, + }) ==> (result matches Err(error) ==> error == HistoryError::IdExhausted { domain: context.1 }), + { allocate_coordinate_state(state, context.0, context.1, context.2, context.3, context.4) } }) + } + + /// Issue a never-recycled history ID above `last`; retained receipts certify a live frontier. + #[verus_spec(result => requires numeric_store_wf(*self), + match prior@ { Some(previous) => previous.id() == history_authority(), None => true }, + ensures result matches Ok((id, receipt)) ==> last < id < usize::MAX + && receipt@.id() == history_authority() && receipt@@ == (id, issuer@), + last == 0 || (match prior@ { Some(previous) => previous.key() == last, None => false }) ==> + (result matches Err(error) ==> error == HistoryError::IdExhausted { domain: "history" }))] + pub(crate) fn allocate_history_after( + &self, + last: usize, + issuer: Ghost, + prior: Tracked>, + ) -> Result<(usize, Tracked), HistoryError> { + proof! { reveal(history_authority); } + if last == usize::MAX { + return Err(HistoryError::IdExhausted { domain: "history" }); + } + self.authorities.history_keys.with_state((last, issuer, prior), + verus_exec_expr! { + |state: &mut HistoryKeyState, context: (usize, Ghost, Tracked>)| + -> (result: Result<(usize, Tracked), HistoryError>) + requires history_keys_acquired(*old(state), self.authorities.history_keys), + match context.2@ { Some(previous) => previous.id() == old(state).issued@.id(), None => true }, + ensures history_key_result(*old(state), *final(state), context.0, context.1@, result), + context.0 == 0 || (match context.2@ { Some(previous) => previous.key() == context.0, None => false }) ==> + (result matches Err(error) ==> error == HistoryError::IdExhausted { domain: "history" }), + { + let (last, issuer, Tracked(prior)) = context; + proof { + if let Some(previous) = prior { + previous.agree(state.issued.borrow()); + assert((state.issued@)@.contains_key(previous.key())); + assert(previous.key() < state.next); + } + } + allocate_history_state(state, last, issuer) + } }) + } +} + +#[verus_verify] +impl HistoryStore { + /// Intern arbitrary exact bytes in one coordinate; prior bindings survive every outcome. + /// A coordinate outside this store's arity returns `InvalidPolicy` without touching a domain. + #[verus_verify] + #[verus_spec(result => requires numeric_store_wf(*self), + ensures result matches Ok(id) ==> 0 < id < u64::MAX, + byte_intern_result(self, component.0 as int, bytes@, result))] + pub fn intern( + &self, + component: Component, + bytes: &[u8], + limits: &mut L, + world: &mut ObservationWorld, + ) -> Result { + match self.intern_observed(component, bytes, limits, world) { + Ok((id, _receipt)) => Ok(id), + Err(error) => Err(error), + } + } + + /// Retain persistent byte identity evidence without another native lookup or allocation. + #[doc(hidden)] + #[verus_verify] + #[verus_spec(result => requires numeric_store_wf(*self), + ensures byte_intern_result(self, component.0 as int, bytes@, + match result { Ok((id, _)) => Ok(id), Err(error) => Err(error) }), + result matches Ok((id, receipt)) ==> 0 < id < u64::MAX + && component.0 < self.arity_spec() + && byte_binding_result(self, component.0 as int, bytes@, id, receipt@) + && receipt@.coordinate_authority() == coordinate_authority(component.0 as int))] + pub fn intern_observed( + &self, + component: Component, + bytes: &[u8], + limits: &mut L, + _world: &mut ObservationWorld, + ) -> Result<(u64, Tracked), HistoryError> { + let index = component.index(); + if index >= self.arity() { + return Err(HistoryError::invalid_policy( + "component", + "component index is outside event arity", + )); + } + let native = &self.domains[index]; + let context = (bytes, limits); + proof_decl! { let ghost input = context; } + let operation = verus_exec_expr! { + |domain: &mut Domain, context: (&[u8], &mut L)| + -> (result: Result<(u64, Tracked), HistoryError>) + requires domain_acquired(*old(domain), *native), + native_domain_index(*native) == index, numeric_store_wf(*self), + index < self.arity_spec() <= MAX_ARITY, + *native == byte_domain(self, index as int), + ensures domain_acquired(*final(domain), *native), + byte_intern_maps(old(domain)@, final(domain)@, context.0@, + match result { Ok((id, _)) => Ok(id), Err(error) => Err(error) }), + result matches Ok((id, receipt)) ==> byte_binding_result(self, index as int, context.0@, id, receipt@) + && 0 < id < u64::MAX + && receipt@.coordinate_authority() == coordinate_authority(index as int), + { domain.intern(context.0, index, "component", context.1, self) } + }; + let result = native.with_domain(context, operation); + proof! { + let borrow = choose|borrow: &mut Domain| domain_acquired(mut_ref_current(borrow), *native) + && domain_acquired(mut_ref_future(borrow), *native) + && call_ensures(operation, (borrow, input), result); + let before = mut_ref_current(borrow)@; + let after = mut_ref_future(borrow)@; + assert(byte_domain_transaction(self, index as int, before, after)); + assert(byte_intern_maps(before, after, bytes@, + match result { Ok((id, _)) => Ok(id), Err(error) => Err(error) })); + assert(byte_intern_result(self, index as int, bytes@, + match result { Ok((id, _)) => Ok(id), Err(error) => Err(error) })); + } + result + } + + /// Create an empty history owned by its handles and read-only records. + #[verus_verify] + #[verus_spec(result => requires numeric_store_wf(**self), + ensures result matches Ok(handle) ==> handle_wf(handle) + && handle_owner_identity(handle) == arc_identity(*self) && history_created(handle))] + pub fn new_history( + self: &Arc, + limits: &mut L, + _world: &mut ObservationWorld, + ) -> Result { + let (index, _global_registration) = self.allocate_history_after( + 0, + verus_exec_expr! { Ghost(HistoryIssuer::Byte) }, + verus_exec_expr! { Tracked(None) }, + )?; + limits.enforce_memory()?; + let stored = StoredHistory::new(index); + proof! { crate::history::lemma_stored_history_view(stored); } + let record = NativeRecord::new(stored); + limits.enforce_memory()?; + let handle = HistoryHandle { + owner: share_numeric_owner(self), + index, + record, + #[cfg(verus_keep_ghost)] + global_registration: _global_registration, + }; + proof! { + assert(handle_wf(handle)); + assert(handle_owner_identity(handle) == arc_identity(*self)); + assert(crate::history::verify::stored_events(&stored).len() == 0); + assert(crate::history::verify::stored_events(&stored) =~= Seq::::empty()); + assert(stored.spec_revision() == 0); + assert(record_installed(record, stored)); + assert(history_created(handle)); + } + Ok(handle) + } + + /// Build an inline event from IDs belonging to this store's byte domains. + /// Wrong arity and unknown IDs are rejected before the event is returned. + #[verus_verify] + #[verus_spec(result => requires numeric_store_wf(*self), + ensures result matches Ok(event) ==> event@ == slots@.map(|i: int, id: u64| id as nat) + && event@.len() == self.arity_spec() && event_validation_result(self, event, Ok(())), + slots@.len() != self.arity_spec() ==> match result { + Err(error) => event_arity_error(error), Ok(_) => false, + }, + slots@.len() == self.arity_spec() ==> exists|event: Event| + event@ == slots@.map(|i: int, id: u64| id as nat) + && event_validation_result(self, event, + match result { Ok(_) => Ok(()), Err(error) => Err(error) }))] + pub fn event(&self, slots: &[u64]) -> Result { + if slots.len() != self.arity() { + return Err(HistoryError::invalid_policy( + "event", + "event arity does not match store", + )); + } + let event = Event::from_encoded(slots); + let validation = self.validate_event(&event); + proof! { + assert(exists|candidate: Event| candidate@ == slots@.map(|i: int, id: u64| id as nat) + && event_validation_result(self, candidate, validation)); + } + validation?; + Ok(event) + } + + /// Validate arity, then coordinates in index order at separate read linearizations. + #[verus_verify] + #[verus_spec(result => requires numeric_store_wf(*self), + ensures event_validation_result(self, *event, result), + result matches Err(error) ==> event_validation_error(*event, error))] + pub fn validate_event(&self, event: &Event) -> Result<(), HistoryError> { + let arity = self.arity(); + if event.arity() != arity { + return Err(HistoryError::invalid_policy( + "event", + "event arity does not match store", + )); + } + let mut index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant numeric_store_wf(*self), + index <= arity == self.arity_spec(), event@.len() == arity, + forall|i: int| 0 <= i < index ==> byte_validation_observed(self, i, event@[i] as u64, true), + decreases arity - index, + ))] + while index < arity { + let native = &self.domains[index]; + let id = event.component(index); + let operation = verus_exec_expr! { + |domain: &mut Domain, id: u64| -> (result: Result<(), HistoryError>) + requires domain_acquired(*old(domain), *native), + ensures domain_acquired(*final(domain), *native), final(domain)@ == old(domain)@, + (result is Ok) == old(domain)@.ids.contains(id), + result is Ok ==> result == Ok(()), + result is Err ==> result == Err(HistoryError::UnknownId { domain: "component", id }), + { + proof { reveal(::view); } + domain.validate(id, "component") + } + }; + let result = native.with_domain(id, operation); + proof! { + let borrow = choose|borrow: &mut Domain| domain_acquired(mut_ref_current(borrow), *native) + && domain_acquired(mut_ref_future(borrow), *native) + && call_ensures(operation, (borrow, id), result); + let view = mut_ref_current(borrow)@; + assert(mut_ref_future(borrow)@ == view); + assert(byte_domain_transaction(self, index as int, view, view)); + assert((result is Ok) == view.ids.contains(id)); + assert(byte_validation_observed(self, index as int, id, result is Ok)); + if result is Err { + assert(event_validation_result(self, *event, result)); + lemma_event_validation_result_facts(self, *event, result); + } + } + result?; + index += 1; + } + proof! { assert(event_validation_result(self, *event, Ok(()))); } + Ok(()) + } +} + +impl HistoryStore { + /// Borrow a read-only record after checking that the history belongs to this store. + #[verus_verify] + #[verus_spec(result => requires handle_wf(*history), + ensures result is Ok <==> reference_identity(self) == handle_owner_identity(*history), + result is Err ==> result == Err(HistoryError::WrongHistoryOwner), + result matches Ok(record) ==> record_matches_handle(record, *history) && record.valid() + && record.record_id() == handle_index(*history) + && record.lifecycle_id() == handle_lifecycle_id(*history))] + pub fn history_record(&self, history: &HistoryHandle) -> Result { + let record = self.history_record_inner(history)?; + Ok(HistoryRecord::from_native(record)) + } + + #[verus_verify] + #[verus_spec(result => requires handle_wf(*history), + ensures result is Ok <==> reference_identity(self) == handle_owner_identity(*history), + result is Err ==> result == Err(HistoryError::WrongHistoryOwner), + result matches Ok(record) ==> record == history.record && record_valid(record) + && numeric_store_wf(*self))] + fn history_record_inner(&self, history: &HistoryHandle) -> Result { + if !history.belongs_to(self) { + return Err(HistoryError::WrongHistoryOwner); + } + Ok(history.record.clone()) + } + + /// Atomically append validated events, preserving the history revision. + /// The postcondition describes only this operation's lock-local transaction; + /// ownership and validation errors, and empty input, need no record lock. + #[verus_verify] + #[verus_spec(result => requires handle_wf(*history), + ensures append_result(self, *history, events@, result))] + pub fn append( + &self, + history: &HistoryHandle, + events: &[Event], + limits: &mut L, + world: &mut ObservationWorld, + ) -> Result<(), HistoryError> { + let record = self.history_record_inner(history)?; + if events.is_empty() { + return Ok(()); + } + let mut index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant index <= events@.len(), events@.len() > 0, handle_wf(*history), + record == history.record, record_valid(record), numeric_store_wf(*self), + reference_identity(self) == handle_owner_identity(*history), + decreases events@.len() - index))] + while index < events.len() { + let validation = self.validate_event(&events[index]); + proof! { + if let Err(error) = &validation { + assert(event_validation_error(events@[index as int], *error)); + assert(exists|i: int, failed: HistoryError| 0 <= i < events@.len() + && Err::<(), HistoryError>(*error) == Err(failed) + && event_validation_error(events@[i], failed)); + } + } + validation?; + index += 1; + } + let context = (events, limits, world); + proof_decl! { let ghost input = context; } + let operation = verus_exec_expr! { + |cell: &mut RecordCell, context: (&[Event], &mut L, &mut ObservationWorld)| + -> (result: Result<(), HistoryError>) + requires record_acquired(*old(cell), record), context.0@.len() > 0, + ensures record_acquired(*final(cell), record), + crate::history::verify::stored_append_result(old(cell).stored, final(cell).stored, + context.0@, result), result != Err(HistoryError::WrongHistoryOwner), + result matches Err(error) ==> junco_core::spec::semantics::resource_error(error), + { cell.append_events(context.0, context.1, context.2) } + }; + let result = record.with_record(context, operation); + proof! { + let borrow = choose|borrow: &mut RecordCell| record_acquired(mut_ref_current(borrow), record) + && record_acquired(mut_ref_future(borrow), record) + && call_ensures(operation, (borrow, input), result); + let before = mut_ref_current(borrow).stored; + let after = mut_ref_future(borrow).stored; + assert(crate::history::verify::stored_append_result(before, after, events@, result)); + assert(record_transaction(*history, before, after)); + assert(record_append_observed(*history, events@, result)); + } + result + } + + /// Remove a suffix, invalidating prior snapshots only when events are removed. + /// No-op, proper shrink, and revision exhaustion use the exact lock-local table. + #[verus_verify] + #[verus_spec(result => requires handle_wf(*history), + ensures truncate_result(self, *history, len, result))] + pub fn truncate(&self, history: &HistoryHandle, len: usize) -> Result<(), HistoryError> { + let record = self.history_record_inner(history)?; + let operation = verus_exec_expr! { + |cell: &mut RecordCell, len: usize| -> (result: Result<(), HistoryError>) + requires record_acquired(*old(cell), record), + ensures record_acquired(*final(cell), record), + crate::history::verify::stored_truncate_result(old(cell).stored, final(cell).stored, len, result), + { cell.truncate_events(len) } + }; + let result = record.with_record(len, operation); + proof! { + let borrow = choose|borrow: &mut RecordCell| record_acquired(mut_ref_current(borrow), record) + && record_acquired(mut_ref_future(borrow), record) + && call_ensures(operation, (borrow, len), result); + let before = mut_ref_current(borrow).stored; + let after = mut_ref_future(borrow).stored; + assert(crate::history::verify::stored_truncate_result(before, after, len, result)); + assert(record_transaction(*history, before, after)); + assert(record_truncate_observed(*history, len, result)); + } + result + } + + /// Return the event count observed by a read guard after verifying ownership. + /// Concurrent callers may change the record after this observation is released. + #[verus_verify] + #[verus_spec(result => requires handle_wf(*history), + ensures len_result(self, *history, result))] + pub fn len(&self, history: &HistoryHandle) -> Result { + let record = self.history_record(history)?; + let guard = record.read(); + let len = guard.len(); + proof! { + assert(exists|observed: HistoryRecord, held: HistoryRecordReadGuard| + record_view(observed) == history.record && record_read_observed(observed, held) + && Ok::(len) == Ok(held.stored_view()@.events.len() as usize)); + } + Ok(len) + } +} + +#[cfg(test)] +mod tests { + #![allow( + clippy::unwrap_used, + clippy::indexing_slicing, + clippy::arithmetic_side_effects + )] + + use super::*; + use junco_core::limits::Unmetered; + + fn event(store: &HistoryStore) -> Event { + Event::from_encoded(&[ + store + .intern( + Component(0), + b"alice", + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(), + store + .intern(Component(1), b"edit", &mut Unmetered, &mut ObservationWorld) + .unwrap(), + store + .intern(Component(2), b"doc", &mut Unmetered, &mut ObservationWorld) + .unwrap(), + ]) + } + + fn typed_event() -> Event { + // A fresh typed view issues IDs that are never members of a byte domain. + crate::typed::Store::<((), (), ())>::new() + .unwrap() + .encode_event(&((), (), ())) + .unwrap() + } + + #[test] + fn global_owners_share_identities_and_handles() { + let first = HistoryStore::new(3); + let second = HistoryStore::new(3); + assert!(Arc::ptr_eq(&first, &second)); + let principal = first + .intern( + Component(0), + b"global-test/alice", + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + assert_eq!( + principal, + second + .intern( + Component(0), + b"global-test/alice", + &mut Unmetered, + &mut ObservationWorld + ) + .unwrap() + ); + let history = first + .new_history(&mut Unmetered, &mut ObservationWorld) + .unwrap(); + assert!(history.belongs_to(&second)); + second + .append( + &history, + &[event(&first)], + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + assert_eq!(first.len(&history).unwrap(), 1); + assert!(matches!( + first.allocate_history_after(usize::MAX, Ghost::assume_new(), Tracked::assume_new()), + Err(HistoryError::IdExhausted { domain: "history" }) + )); + } + + #[test] + fn all_arities_share_numeric_authorities_not_byte_domains() { + let first = HistoryStore::new(1); + let mut history_ids = BTreeSet::new(); + let mut coordinate_ids: Vec> = + (0..MAX_ARITY).map(|_| BTreeSet::new()).collect(); + for arity in 1..=MAX_ARITY { + let store = HistoryStore::new(arity); + assert_eq!(store.arity(), arity); + assert_eq!(store.domains.len(), arity); + assert!(Arc::ptr_eq(&store, &HistoryStore::new(arity))); + assert!(Arc::ptr_eq(&first.authorities, &store.authorities)); + let mut slots = [0; MAX_ARITY]; + for index in 0..arity { + let bytes = b"all-arities/\xff\x80\0"; + let component = Component(index as u8); + let id = store + .intern(component, bytes, &mut Unmetered, &mut ObservationWorld) + .unwrap(); + assert_eq!( + id, + store + .intern(component, bytes, &mut Unmetered, &mut ObservationWorld) + .unwrap() + ); + assert!(coordinate_ids[index].insert(id)); + slots[index] = id; + } + let event = store.event(&slots[..arity]).unwrap(); + assert_eq!(event.arity(), arity); + store.validate_event(&event).unwrap(); + let history = store + .new_history(&mut Unmetered, &mut ObservationWorld) + .unwrap(); + assert!(history_ids.insert(history.index())); + store + .append(&history, &[event], &mut Unmetered, &mut ObservationWorld) + .unwrap(); + if arity != 1 { + assert!(!history.belongs_to(&first)); + assert!(matches!( + first.len(&history), + Err(HistoryError::WrongHistoryOwner) + )); + assert!(matches!( + first.validate_event(&event), + Err(HistoryError::InvalidPolicy { .. }) + )); + } + for index in [arity as u8, u8::MAX] { + assert!(matches!( + store.intern( + Component(index), + b"invalid", + &mut Unmetered, + &mut ObservationWorld + ), + Err(HistoryError::InvalidPolicy { .. }) + )); + } + let malformed = Event::from_encoded(&slots[..arity - 1]); + assert!(matches!( + store.event(&slots[..arity - 1]), + Err(HistoryError::InvalidPolicy { .. }) + )); + assert!(matches!( + store.event(&[1; MAX_ARITY + 1]), + Err(HistoryError::InvalidPolicy { .. }) + )); + assert!(matches!( + store.event(&[0; MAX_ARITY][..arity]), + Err(HistoryError::UnknownId { + domain: "component", + id: 0 + }) + )); + assert!(matches!( + store.validate_event(&malformed), + Err(HistoryError::InvalidPolicy { .. }) + )); + assert!(matches!( + store.append( + &history, + &[event, malformed], + &mut Unmetered, + &mut ObservationWorld + ), + Err(HistoryError::InvalidPolicy { .. }) + )); + assert_eq!(store.len(&history).unwrap(), 1); + assert_eq!(event.component(arity), 0); + assert_eq!(event.component(usize::MAX), 0); + } + } + + #[test] + fn numeric_event_equality_and_hash_ignore_inactive_slots() { + use core::hash::{Hash, Hasher}; + #[derive(Default)] + struct TestHasher(u64); + impl Hasher for TestHasher { + fn finish(&self) -> u64 { + self.0 + } + fn write(&mut self, bytes: &[u8]) { + for byte in bytes { + self.0 = self.0.wrapping_mul(31).wrapping_add(u64::from(*byte)); + } + } + } + for arity in 1..=MAX_ARITY { + let left = Event::from_encoded(&[17; MAX_ARITY][..arity]); + let mut right = left; + right.slots[arity..].fill(u64::MAX); + assert_eq!(left, right); + let mut left_hash = TestHasher::default(); + let mut right_hash = TestHasher::default(); + left.hash(&mut left_hash); + right.hash(&mut right_hash); + assert_eq!(left_hash.finish(), right_hash.finish()); + if arity < MAX_ARITY { + assert_ne!(left, Event::from_encoded(&[17; MAX_ARITY][..arity + 1])); + } + } + } + + #[test] + #[should_panic(expected = "event arity must be between 1 and MAX_ARITY")] + fn zero_store_arity_is_rejected() { + HistoryStore::new(0); + } + + #[test] + #[should_panic(expected = "event arity must be between 1 and MAX_ARITY")] + fn oversized_store_arity_is_rejected() { + HistoryStore::new(MAX_ARITY + 1); + } + + #[test] + fn read_only_record_clones_observe_store_transactions() { + let store = HistoryStore::new(3); + let history = store + .new_history(&mut Unmetered, &mut ObservationWorld) + .unwrap(); + let record = store.history_record(&history).unwrap(); + let retained = record.clone(); + { + let first = record.read(); + let second = retained.read(); + assert!(core::ptr::eq(&*first, &*second)); + assert_eq!(first.len(), 0); + assert_eq!(second.revision(), 0); + assert_eq!(first.id(), history.index()); + } + let event = event(&store); + store + .append(&history, &[event], &mut Unmetered, &mut ObservationWorld) + .unwrap(); + assert_eq!(retained.read().len(), 1); + assert_eq!(record.read().revision(), 0); + store.truncate(&history, 0).unwrap(); + assert_eq!(retained.read().len(), 0); + assert_eq!(record.read().revision(), 1); + store + .append( + &history, + &[event, event], + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + // Records keep the buffer alive after the handle; the singleton never retains it. + let weak = Arc::downgrade(&history.record.inner); + drop(history); + assert_eq!(retained.read().as_slice(), [event, event]); + assert_eq!(retained.read().revision(), 1); + drop(record); + drop(retained); + assert!(weak.upgrade().is_none()); + } + + #[test] + fn exact_identities_and_large_domain() { + let store = HistoryStore::new(3); + let paths = ["a", "A", "/a", "a/", "a\0", "é", "e\u{301}"]; + let mut ids = BTreeSet::new(); + for path in paths { + let id = store + .intern( + Component(0), + path.as_bytes(), + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + assert_eq!( + id, + store + .intern( + Component(0), + path.as_bytes(), + &mut Unmetered, + &mut ObservationWorld + ) + .unwrap() + ); + assert!(ids.insert(id)); + } + let first = store + .intern( + Component(2), + b"common/prefix/0", + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + let mut resources = BTreeSet::from([first]); + for index in 1..5000 { + assert!( + resources.insert( + store + .intern( + Component(2), + alloc::format!("common/prefix/{index}").as_bytes(), + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap() + ) + ); + } + assert_eq!( + first, + store + .intern( + Component(2), + b"common/prefix/0", + &mut Unmetered, + &mut ObservationWorld + ) + .unwrap() + ); + assert_eq!(resources.len(), 5000); + let action = store + .intern(Component(1), b"a", &mut Unmetered, &mut ObservationWorld) + .unwrap(); + store + .intern(Component(0), b"new", &mut Unmetered, &mut ObservationWorld) + .unwrap(); + assert_eq!( + action, + store + .intern(Component(1), b"a", &mut Unmetered, &mut ObservationWorld) + .unwrap() + ); + let long = "x".repeat(4096); + assert_ne!( + store + .intern( + Component(2), + long.as_bytes(), + &mut Unmetered, + &mut ObservationWorld + ) + .unwrap(), + store + .intern( + Component(2), + (long + "/").as_bytes(), + &mut Unmetered, + &mut ObservationWorld + ) + .unwrap() + ); + } + + #[test] + fn checked_full_width_allocator() { + let mut next = u64::from(u32::MAX) + 1; + assert_eq!( + Domain::allocate_id(&mut next, "component").unwrap(), + u64::from(u32::MAX) + 1 + ); + next = u64::MAX - 1; + assert_eq!( + Domain::allocate_id(&mut next, "component").unwrap(), + u64::MAX - 1 + ); + assert!(matches!( + Domain::allocate_id(&mut next, "component"), + Err(HistoryError::IdExhausted { + domain: "component" + }) + )); + assert_eq!(next, u64::MAX); + } + + #[test] + fn checked_history_key_counter() { + let mut next = 1; + assert_eq!(next_history_id(&mut next).unwrap(), 1); + assert_eq!(next, 2); + next = usize::MAX - 1; + assert_eq!(next_history_id(&mut next).unwrap(), usize::MAX - 1); + assert_eq!(next, usize::MAX); + assert!(matches!( + next_history_id(&mut next), + Err(HistoryError::IdExhausted { domain: "history" }) + )); + assert_eq!(next, usize::MAX); + } + + #[test] + fn allocator_failures_preserve_consumed_ids() { + let mut coordinates = CoordinateState::new(); + assert!(matches!( + allocate_coordinate_state( + &mut coordinates, + 0, + "component", + 1, + Ghost::assume_new(), + Tracked::assume_new() + ), + Err(HistoryError::Invariant { .. }) + )); + assert_eq!(coordinates.next[0], 2); + assert_eq!(&coordinates.next[1..], &[1; MAX_ARITY - 1]); + let (second, _) = allocate_coordinate_state( + &mut coordinates, + 0, + "component", + 0, + Ghost::assume_new(), + Tracked::assume_new(), + ) + .unwrap(); + assert_eq!(second, 2); + assert_eq!(coordinates.next[0], 3); + assert_eq!(&coordinates.next[1..], &[1; MAX_ARITY - 1]); + assert!(matches!( + allocate_coordinate_state( + &mut coordinates, + MAX_ARITY, + "invalid", + 0, + Ghost::assume_new(), + Tracked::assume_new() + ), + Err(HistoryError::Invariant { .. }) + )); + assert_eq!(coordinates.next[0], 3); + assert_eq!(&coordinates.next[1..], &[1; MAX_ARITY - 1]); + + let mut histories = HistoryKeyState::new(); + assert!(matches!( + allocate_history_state(&mut histories, 1, Ghost::assume_new()), + Err(HistoryError::Invariant { .. }) + )); + assert_eq!(histories.next, 2); + let (second, _) = allocate_history_state(&mut histories, 0, Ghost::assume_new()).unwrap(); + assert_eq!(second, 2); + assert_eq!(histories.next, 3); + assert!(matches!( + allocate_history_state(&mut histories, usize::MAX, Ghost::assume_new()), + Err(HistoryError::IdExhausted { domain: "history" }) + )); + assert_eq!(histories.next, 3); + } + + #[test] + fn atomic_append_and_revisions() { + let store = HistoryStore::new(3); + let history = store + .new_history(&mut Unmetered, &mut ObservationWorld) + .unwrap(); + let valid = event(&store); + let typed = typed_event(); + store + .append(&history, &[valid], &mut Unmetered, &mut ObservationWorld) + .unwrap(); + assert!(matches!( + store.append( + &history, + &[valid, typed], + &mut Unmetered, + &mut ObservationWorld + ), + Err(HistoryError::UnknownId { + domain: "component", + .. + }) + )); + let record = store.history_record(&history).unwrap(); + assert_eq!(record.read().as_slice(), [valid]); + assert_eq!(record.read().revision, 0); + assert!(matches!( + store.validate_event(&Event::from_encoded(&[ + valid.component(0), + typed.component(1), + valid.component(2), + ])), + Err(HistoryError::UnknownId { + domain: "component", + .. + }) + )); + assert!(matches!( + store.validate_event(&Event::from_encoded(&[ + valid.component(0), + valid.component(1), + typed.component(2), + ])), + Err(HistoryError::UnknownId { + domain: "component", + .. + }) + )); + store + .append( + &history, + &[valid, valid], + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + assert_eq!(store.len(&history.clone()).unwrap(), 3); + assert_eq!(record.read().revision, 0); + store.truncate(&history, 4).unwrap(); + store.truncate(&history, 3).unwrap(); + assert_eq!(record.read().revision, 0); + store.truncate(&history, 2).unwrap(); + assert_eq!(record.read().revision, 1); + store + .history_record_inner(&history) + .unwrap() + .inner + .write() + .stored + .revision = u64::MAX; + assert!(matches!( + store.truncate(&history, 0), + Err(HistoryError::RevisionExhausted) + )); + assert_eq!(store.len(&history).unwrap(), 2); + } + + #[cfg(feature = "std")] + #[test] + fn synchronized_interning_shares_one_identity() { + fn assert_send_sync() {} + use alloc::vec::Vec; + assert_send_sync::(); + let barrier = Arc::new(std::sync::Barrier::new(8)); + let threads: Vec<_> = (0..8) + .map(|_| { + let barrier = Arc::clone(&barrier); + std::thread::spawn(move || { + barrier.wait(); + let store = HistoryStore::new(3); + let history = store + .new_history(&mut Unmetered, &mut ObservationWorld) + .unwrap(); + (event(&store), history) + }) + }) + .collect(); + let results: Vec<_> = threads + .into_iter() + .map(|thread| thread.join().unwrap()) + .collect(); + let store = HistoryStore::new(3); + let mut keys = BTreeSet::new(); + for (event, history) in &results { + assert_eq!(*event, results[0].0); + assert!(Arc::ptr_eq(&history.owner, &store)); + assert!(history.index() > 0); + assert!(keys.insert(history.index())); + } + } + + #[test] + fn interning_and_history_creation_roll_back_memory_failures() { + struct FailMemory { + calls: usize, + fail_at: usize, + } + impl Limits for FailMemory { + fn checkpoint(&mut self) -> Result<(), junco_core::limits::LimitError> { + Ok(()) + } + fn publication_checkpoint(&mut self) -> Result<(), junco_core::limits::LimitError> { + Ok(()) + } + fn enforce_memory(&mut self) -> Result<(), junco_core::limits::LimitError> { + self.calls = self.calls.saturating_add(1); + if self.calls == self.fail_at { + Err(junco_core::limits::LimitError::MemoryLimitExceeded { usage: 1, limit: 0 }) + } else { + Ok(()) + } + } + } + let store = HistoryStore::new(3); + let known = store + .intern( + Component(0), + b"rollback-test/known", + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + for fail_at in [1, 2] { + let mut limits = FailMemory { calls: 0, fail_at }; + assert!(matches!( + store.intern( + Component(0), + b"rollback-test/new", + &mut limits, + &mut ObservationWorld + ), + Err(HistoryError::Limit(_)) + )); + let domain = store.domains[0].inner.lock(); + assert_eq!( + domain.paths.get(b"rollback-test/known".as_slice()), + Some(&known) + ); + assert!(!domain.paths.contains_key(b"rollback-test/new".as_slice())); + drop(domain); + + let mut limits = FailMemory { calls: 0, fail_at }; + assert!(matches!( + store.new_history(&mut limits, &mut ObservationWorld), + Err(HistoryError::Limit(_)) + )); + } + let history = store + .new_history(&mut Unmetered, &mut ObservationWorld) + .unwrap(); + assert!(history.index() > 0); + assert!(history.belongs_to(&store)); + assert_eq!(store.len(&history).unwrap(), 0); + } +} diff --git a/src/history-store/src/typed.rs b/src/history-store/src/typed.rs new file mode 100644 index 000000000..00df5ab1a --- /dev/null +++ b/src/history-store/src/typed.rs @@ -0,0 +1,1963 @@ +//! Scoped typed views retain persistent receipts from process-wide identity authorities. +//! Receipts certify each committed frontier, including after a later allocation fails. +//! Exclusive registry births distinguish owners; native key laws govern Eq classes. + +use crate::store::Event as NumericEvent; +use crate::store::HistoryStore; +use alloc::sync::Arc; +use alloc::vec::Vec; +use history_syntax::KeyHash; +#[cfg(verus_keep_ghost)] +use history_syntax::event::specs::{AritySpec, EventSpec}; +#[cfg(verus_keep_ghost)] +use history_syntax::spec::events::{arity, event_view, projection_laws}; +use history_syntax::syntax::Component; +use history_syntax::{Arity, Event, MAX_ARITY}; +use junco_core::compile::{FlatEncoder, lower_flat, validate_component}; +use junco_core::errors::HistoryError; +use junco_core::flat::FlatPair; +use junco_core::limits::Limits; +use junco_core::observation::ObservationWorld; +#[cfg(verus_keep_ghost)] +use junco_core::verify::history_assumptions::{arc_identity, reference_identity}; +#[cfg(feature = "std")] +use parking_lot::Mutex; +#[cfg(not(feature = "std"))] +use spin::Mutex; +#[cfg(verus_keep_ghost)] +use verify::*; +use vstd::prelude::*; +#[cfg(verus_keep_ghost)] +use vstd::std_specs::cmp::PartialEqSpec; + +use crate::keyed::KeyedMap; + +// Ghost signatures still name T after native erasure; this is the exact finite model. +pub type ComponentMaps = vstd::seq::Seq::Component, u64)>>; +pub type HistoryRegistration = + vstd::resource::map::GhostPersistentPointsTo; +pub(crate) type RegistryBirth = vstd::resource::map::GhostPointsTo; +pub(crate) type StoreIdReceipt = + vstd::resource::map::GhostPersistentPointsTo; +#[cfg(verus_keep_ghost)] +pub(crate) type StoreIdAuth = vstd::resource::map::GhostMapAuth; + +// One process allocator across every E, including on targets without AtomicU64. +#[verus_verify] +static STORE_IDS: NativeStoreIds = NativeStoreIds::new(); + +verus! { + +broadcast use {vstd::seq::group_seq_lemmas, vstd::std_specs::vec::group_vec_axioms}; + +pub(crate) struct Codebook { + pub(crate) values: KeyedMap, + pub(crate) last: u64, + #[cfg(verus_keep_ghost)] + pub(crate) issued: Tracked>, +} + +/// Checked arithmetic for the process store-ID allocator. +fn checked_successor(last: u64, domain: &'static str) -> (result: Result) + ensures match result { + Ok(id) => last < u64::MAX && id == last + 1 && id > 0, + Err(error) => last == u64::MAX && error == HistoryError::IdExhausted { domain }, + }, +{ + match last.checked_add(1) { + Some(id) => Ok(id), + None => Err(HistoryError::IdExhausted { domain }), + } +} + +// Checked payload of the live process store-ID authority. +pub(crate) struct StoreIdState { + pub(crate) last: u64, + #[cfg(verus_keep_ghost)] + pub(crate) issued: Tracked, +} + +impl StoreIdState { + pub(crate) const fn new() -> (result: Self) + ensures store_id_state_wf(result), result.last == 0, + (result.issued@)@ == Map::::empty(), + { + let tracked issued = empty_store_id_authority(); + Self { last: 0, #[cfg(verus_keep_ghost)] issued: Tracked(issued) } + } +} + +pub(crate) fn issue_store_id(state: &mut StoreIdState, + Ghost(registry): Ghost) + -> (result: Result<(u64, Tracked), HistoryError>) + requires store_id_state_wf(*old(state)), + ensures store_id_issue_result(*old(state), *final(state), registry, result), +{ + let ghost before = (state.issued@)@; + let id = match checked_successor(state.last, "store") { + Ok(id) => id, + Err(_) => return Err(HistoryError::IdExhausted { domain: "store" }), + }; + proof { assert(!before.contains_key(id)); } + let tracked receipt = state.issued.borrow_mut().insert(id, registry).persist(); + state.last = id; + proof { + assert forall|key: u64| #[trigger] (state.issued@)@.contains_key(key) + <==> 0 < key <= state.last by { + if key != id { assert((state.issued@)@.contains_key(key) == before.contains_key(key)); } + } + assert(before <= (state.issued@)@); + } + Ok((id, Tracked(receipt))) +} + +// Only const mutex installation and lock/callback fidelity remain native leaves. +#[verifier::external_body] +pub(crate) struct NativeStoreIds { + pub(crate) inner: spin::Mutex, +} + +impl NativeStoreIds { + #[verifier::external_body] + pub(crate) const fn new() -> (result: Self) + ensures store_ids_mutex_valid(result), + { + Self { inner: spin::Mutex::new(StoreIdState::new()) } + } + + #[verifier::external_body] + pub(crate) fn with_state R>( + &self, context: Context, operation: F) -> (result: R) + requires store_ids_mutex_valid(*self), + forall|borrow: &mut StoreIdState| + store_id_state_acquired(mut_ref_current(borrow), *self) + ==> call_requires(operation, (borrow, context)), + forall|borrow: &mut StoreIdState, output: R| + store_id_state_acquired(mut_ref_current(borrow), *self) + && call_ensures(operation, (borrow, context), output) + ==> store_id_state_frame(mut_ref_current(borrow), mut_ref_future(borrow)), + ensures exists|borrow: &mut StoreIdState| + store_id_state_acquired(mut_ref_current(borrow), *self) + && store_id_state_frame(mut_ref_current(borrow), mut_ref_future(borrow)) + && call_ensures(operation, (borrow, context), result), + { + let mut state = self.inner.lock(); + operation(&mut state, context) + } +} + +impl Codebook { + fn new() -> (result: Self) + ensures book_wf(result), book_entries(result) == Seq::<(K, u64)>::empty(), + result.issued@ is None, result.last == 0, + forall|index: int, issuer: crate::store::ComponentIssuer| + book_receipts_wf(result, index, issuer), + { + Self { values: KeyedMap::new(), last: 0, + #[cfg(verus_keep_ghost)] issued: Tracked(None) } + } + + fn intern(&mut self, value: &K, index: usize, domain: &'static str, + numeric_store: &HistoryStore, Ghost(issuer): Ghost) + -> (result: Result) + requires crate::store::verify::numeric_store_wf(*numeric_store), + index < numeric_store.arity_spec(), + book_receipts_wf(*old(self), index as int, issuer), + ensures book_receipts_wf(*final(self), index as int, issuer), + result != Err(HistoryError::WrongHistoryOwner), + junco_core::verify::history_specs::no_invariant_failure(result), + result matches Err(error) ==> error == HistoryError::AllocationFailed + || error == (HistoryError::IdExhausted { domain }), + result matches Err(_) ==> final(self).issued@ == old(self).issued@, + junco_core::spec::hypotheses::key_laws::() && book_wf(*old(self)) ==> { + &&& book_wf(*final(self)) + &&& book_entries(*old(self)).is_prefix_of(book_entries(*final(self))) + &&& match result { + Ok(id) => book_encoded(*final(self), *value, id) + && (book_entries(*final(self)) == book_entries(*old(self)) + || book_entries(*final(self)) == book_entries(*old(self)).push((*value, id))), + Err(_) => book_entries(*final(self)) == book_entries(*old(self)) + && final(self).last == old(self).last, + } + }, + { + let ghost before = book_entries(*self); + let ghost initial_wf = book_wf(*self); + let ghost prior_entries = match self.issued@ { + Some(receipts) => receipts@, None => Map::::empty(), + }; + if let Some(id) = self.values.lookup(value) { + return Ok(id); + } + // Reuse is checked first, so an exhausted domain still accepts established keys. + let tracked prior = match self.issued.borrow() { + Some(receipts) => Some(receipts), None => None, + }; + let (id, Tracked(receipt)) = numeric_store.allocate_after(index, domain, self.last, + Ghost(issuer), Tracked(prior))?; + self.values.reserve_one()?; + self.values.insert_fresh(*value, id); + self.last = id; + proof { + let tracked mut previous = None; + vstd::modes::tracked_swap(self.issued.borrow_mut(), &mut previous); + let tracked aggregate = match previous { + Some(mut aggregate) => { aggregate.combine_points_to(receipt); aggregate }, + None => receipt.submap(), + }; + *self.issued.borrow_mut() = Some(aggregate); + assert(self.issued@ is Some); + assert((self.issued@->0)@ == prior_entries.insert(id, issuer)); + assert((self.issued@->0)@.contains_key(self.last)); + } + proof { + if junco_core::spec::hypotheses::key_laws::() { + assert(book_entries(*self) == before.push((*value, id))); + let ghost old_ids = before.map(|i: int, pair: (K,u64)| pair.1); + let ghost new_ids = book_entries(*self).map(|i: int, pair: (K,u64)| pair.1); + assert(prior_entries.dom() == old_ids.to_set()); + assert(new_ids =~= old_ids.push(id)); + old_ids.lemma_push_to_set_commute(id); + assert((self.issued@->0)@.dom() =~= prior_entries.dom().insert(id)); + assert((self.issued@->0)@.dom() == new_ids.to_set()); + } + assert forall|key: u64| (self.issued@->0)@.contains_key(key) implies + 0 < key <= self.last && (self.issued@->0)@[key] == issuer by { + if key != id { assert(prior_entries.contains_key(key)); } + } + if junco_core::spec::hypotheses::key_laws::() && initial_wf { + assert forall|i: int| #![trigger book_entries(*self)[i]] + 0 <= i < book_entries(*self).len() implies + 0 < book_entries(*self)[i].1 <= self.last by { + if i < before.len() { assert(before[i].1 < id); } + } + assert forall|i: int, j: int| + 0 <= i < book_entries(*self).len() && 0 <= j < book_entries(*self).len() + implies (book_entries(*self)[i].0.eq_spec(&book_entries(*self)[j].0) + == (book_entries(*self)[i].1 == book_entries(*self)[j].1)) by { + if i == before.len() && j < before.len() { + assert(!value.eq_spec(&before[j].0)); + assert(!before[j].0.eq_spec(value)); + } else if j == before.len() && i < before.len() { + assert(!value.eq_spec(&before[i].0)); + assert(!before[i].0.eq_spec(value)); + } + } + assert(book_encoded(*self, *value, id)) by { + assert(book_entries(*self)[before.len() as int] == (*value, id)); + } + } + } + Ok(id) + } +} + +pub(crate) struct ComponentBooks { + pub(crate) books: Vec>, + #[cfg(verus_keep_ghost)] + pub(crate) registry: Ghost, +} + +pub(crate) struct Codebooks { + pub(crate) components: ComponentBooks, + pub(crate) next_history: usize, + #[cfg(verus_keep_ghost)] + pub(crate) owner: Ghost, + #[cfg(verus_keep_ghost)] + pub(crate) history_resources: Tracked>, + #[cfg(verus_keep_ghost)] + pub(crate) latest_history: Tracked>, +} + +impl Codebooks { + fn new(Ghost(owner): Ghost, + Tracked(authority): Tracked>) + -> (result: Self) + requires authority@ == map![0usize => authority.id()], + ensures books_wf(result), result.owner@ == owner, result.next_history == 1, + books_maps(result) == empty_maps::(), registry_wf(result), + result.history_resources@ == authority, + { + let width = E::Arity::value(); + let mut components = Vec::with_capacity(width); + let mut index = 0; + while index < width + invariant index == components@.len(), index <= width, + width == arity::(), 1 <= width <= MAX_ARITY, + forall|i: int| 0 <= i < index ==> book_wf(components@[i]) + && book_entries(components@[i]) == Seq::<(E::Component, u64)>::empty() + && book_receipts_wf(components@[i], i, + crate::store::ComponentIssuer::Typed(authority.id())), + decreases width - index, + { + components.push(Codebook::new()); + index += 1; + } + let result = Self { + components: ComponentBooks { + books: components, + #[cfg(verus_keep_ghost)] + registry: Ghost(authority.id()), + }, + next_history: 1, + #[cfg(verus_keep_ghost)] + owner: Ghost(owner), + #[cfg(verus_keep_ghost)] + history_resources: Tracked(authority), + #[cfg(verus_keep_ghost)] + latest_history: Tracked(None), + }; + proof { + lemma_component_maps_wf(result.components); + assert forall|field: int| 0 <= field < arity::() implies + books_maps(result)[field] =~= empty_maps::()[field] by {} + assert(books_maps(result) =~= empty_maps::()); + } + result + } + + // The local frontier is registration bookkeeping; the process store is the allocation authority. + fn allocate_history_id(&mut self, numeric_store: &HistoryStore, + Ghost(location): Ghost) + -> (result: Result<(usize, Tracked), HistoryError>) + requires registry_wf(*old(self)), crate::store::verify::numeric_store_wf(*numeric_store), + ensures self_same_books(*old(self), *final(self)), registry_wf(*final(self)), + junco_core::verify::history_specs::no_invariant_failure(result), + result matches Err(error) ==> error == (HistoryError::IdExhausted { domain: "history" }), + final(self).history_resources@ == old(self).history_resources@, + match result { + Ok((id, receipt)) => old(self).next_history <= id && 0 < id < usize::MAX + && final(self).next_history == id + 1 + && receipt@.id() == crate::store::verify::history_authority() + && receipt@.key() == id + && receipt@.value() == (crate::store::HistoryIssuer::Typed { + store: old(self).history_resources@.id(), lifecycle: location }), + Err(_) => final(self).next_history == old(self).next_history, + }, + { + let frontier = self.next_history; + if frontier == usize::MAX { + return Err(HistoryError::IdExhausted { domain: "history" }); + } + let last = match frontier.checked_sub(1) { + Some(last) => last, + None => return Err(HistoryError::invariant("history frontier is zero")), + }; + let tracked prior = match self.latest_history.borrow() { + Some(receipt) => Some(receipt), None => None, + }; + let (id, receipt) = numeric_store.allocate_history_after(last, + Ghost(crate::store::HistoryIssuer::Typed { + store: self.history_resources@.id(), lifecycle: location }), Tracked(prior))?; + let next = match id.checked_add(1) { + Some(next) => next, + None => return Err(HistoryError::IdExhausted { domain: "history" }), + }; + self.next_history = next; + proof { + *self.latest_history.borrow_mut() = Some(receipt.borrow().duplicate()); + assert forall|key: usize| (self.history_resources@)@.contains_key(key) + implies key < self.next_history by { + assert(key < frontier); + } + } + Ok((id, receipt)) + } + + fn allocate_history_id_for_resource(&mut self, numeric_store: &HistoryStore, + Ghost(location): Ghost, + Tracked(prior): Tracked>) + -> (result: Result<(usize, Tracked, Tracked), HistoryError>) + requires registry_wf(*old(self)), crate::store::verify::numeric_store_wf(*numeric_store), + match prior { Some(registration) => registration.id() == old(self).history_resources@.id(), None => true }, + ensures registry_wf(*final(self)), self_same_books(*old(self), *final(self)), + junco_core::verify::history_specs::no_invariant_failure(result), + result matches Err(error) ==> error == (HistoryError::IdExhausted { domain: "history" }), + final(self).history_resources@.id() == old(self).history_resources@.id(), + (old(self).history_resources@)@.submap_of((final(self).history_resources@)@), + match result { + Ok((id, registration, receipt)) => 0 < id < usize::MAX && old(self).next_history <= id + && final(self).next_history == id + 1 + && (final(self).history_resources@)@ == (old(self).history_resources@)@.insert(id, location) + && registration@.id() == old(self).history_resources@.id() + && registration@.key() == id && registration@.value() == location + && receipt@.id() == crate::store::verify::history_authority() + && receipt@.key() == id + && receipt@.value() == (crate::store::HistoryIssuer::Typed { + store: old(self).history_resources@.id(), lifecycle: location }) + && match prior { Some(previous) => previous.key() < id, None => true }, + Err(_) => final(self).next_history == old(self).next_history + && final(self).history_resources@ == old(self).history_resources@, + }, + { + let ghost resources = (self.history_resources@)@; + let ghost frontier = self.next_history; + proof { + if let Some(previous) = prior { + previous.agree(self.history_resources.borrow()); + } + } + let (id, receipt) = self.allocate_history_id(numeric_store, Ghost(location))?; + proof { assert(!resources.contains_key(id)); } + let tracked registration = self.history_resources.borrow_mut().insert(id, location).persist(); + proof { + assert forall|previous: usize| (self.history_resources@)@.contains_key(previous) + implies previous < self.next_history by { + if previous != id { assert(resources.contains_key(previous)); } + } + } + Ok((id, Tracked(registration), receipt)) + } +} + +// Native locks carry only the Codebooks invariant and finite snapshot provenance. +// They do not supply equality preservation or ID injection: intern proves those. +#[verifier::external_body] +#[verifier::accept_recursive_types(E)] +pub(crate) struct NativeBooks { + inner: Mutex>, +} + +impl NativeBooks { + #[verifier::external_body] + fn new(books: Codebooks, Tracked(birth): Tracked<&RegistryBirth>) -> (result: Self) + requires books_wf(books), registry_wf(books), + birth.id() == books.history_resources@.id() && birth.key() == 0 + && birth.value() == books.history_resources@.id(), + ensures mutex_valid(result, books.owner@, books.history_resources@.id()), + snapshot_published::(books.history_resources@.id(), books_maps(books)), + { + Self { inner: Mutex::new(books) } + } + + // Locking invokes only a callback whose checked contract restores the actual entry frame. + #[verifier::external_body] + fn with_books, Context) -> R>(&self, + Ghost(owner): Ghost, Ghost(first): Ghost>, + Ghost(second): Ghost>, Ghost(registry): Ghost, + context: Context, operation: F) -> (result: R) + requires mutex_valid(*self, owner, registry), + junco_core::spec::hypotheses::event_obligations::() ==> snapshot_published::(registry, first) + && maps_wf::(first) && snapshot_published::(registry, second) && maps_wf::(second), + forall|borrow: &mut Codebooks| books_acquired(mut_ref_current(borrow), owner, registry, first, second) + ==> call_requires(operation, (borrow, context)), + forall|borrow: &mut Codebooks, output: R| + books_acquired(mut_ref_current(borrow), owner, registry, first, second) + && call_ensures(operation, (borrow, context), output) + ==> publication_frame(mut_ref_current(borrow), mut_ref_future(borrow)), + ensures exists|borrow: &mut Codebooks| + books_acquired(mut_ref_current(borrow), owner, registry, first, second) + && publication_frame(mut_ref_current(borrow), mut_ref_future(borrow)) + && call_ensures(operation, (borrow, context), result) + && snapshot_published::(registry, books_maps(mut_ref_future(borrow))), + { + let mut books = self.inner.lock(); + operation(&mut books, context) + } +} + +/// Policy-arity typed coordinate codebooks scoped to this view. Component and history IDs +/// come from shared process-wide authorities, so views never issue colliding identities. +/// Share a store with `Arc`; components and events retain their original Rust values. +pub struct Store { + pub(crate) id: u64, + pub(crate) books: NativeBooks, + pub(crate) numeric_store: Arc, + #[cfg(verus_keep_ghost)] + pub(crate) history_registry: Ghost, + #[cfg(verus_keep_ghost)] + pub(crate) store_id_receipt: Tracked, + #[cfg(verus_keep_ghost)] + pub(crate) registry_birth: Tracked, +} + +/// Share the native store allocation without changing its logical contents. +#[doc(hidden)] +#[verifier::external_body] +pub fn share_store(store: &Arc>) -> (result: Arc>) + ensures result == *store, *result == **store, + arc_identity(result) == arc_identity(*store), same_store_owner(result, *store), +{ + Arc::clone(store) +} + +/// Borrow the referent whose native identity is retained by the Arc. +#[doc(hidden)] +#[verifier::external_body] +pub fn borrow_store(store: &Arc>) -> (result: &Store) + ensures *result == **store, reference_identity(result) == arc_identity(*store), +{ + store.as_ref() +} + +// Verus statics are exec-only; this leaf exposes the one installed mutex reference. +#[verifier::external_body] +fn process_store_ids_ref() -> (result: &'static NativeStoreIds) + ensures *result == process_store_ids(), store_ids_mutex_valid(*result), +{ &STORE_IDS } + +fn allocate_store_id(Ghost(registry): Ghost) + -> (result: Result<(u64, Tracked), HistoryError>) + ensures result matches Ok((id, receipt)) ==> id > 0 + && receipt@.id() == store_id_authority() && receipt@.key() == id + && receipt@.value() == registry, + junco_core::verify::history_specs::no_invariant_failure(result), + result matches Err(error) ==> error == (HistoryError::IdExhausted { domain: "store" }), +{ + proof { reveal(store_id_authority); } + let ids = process_store_ids_ref(); + ids.with_state(Ghost(registry), + |state: &mut StoreIdState, registry: Ghost| + -> (result: Result<(u64, Tracked), HistoryError>) + requires store_id_state_acquired(*old(state), *ids), + ensures store_id_issue_result(*old(state), *final(state), registry@, result), + { issue_store_id(state, registry) }) +} + +/// A fresh process-wide owner id from the store-id allocator, for clients that tag handles with +/// their issuer (the analyzer's `RuleId`). Ids are issued in increasing order, so no two calls in +/// one process return the same id; the allocator's ghost receipt is not needed by these clients. +pub fn issue_owner_id() -> (result: Result) + ensures result matches Ok(id) ==> id > 0, + junco_core::verify::history_specs::no_invariant_failure(result), + result matches Err(error) ==> error == (HistoryError::IdExhausted { domain: "store" }), +{ + let (id, _receipt) = allocate_store_id(Ghost(arbitrary()))?; + Ok(id) +} + +impl Store { + /// Create an empty typed view. Store-ID exhaustion is reported before wrapping. + pub fn new() -> (result: Result) + ensures result matches Ok(store) ==> store_wf(store), + junco_core::verify::history_specs::no_invariant_failure(result), + result matches Err(error) ==> error == (HistoryError::IdExhausted { domain: "store" }), + { + let tracked (mut authority, empty) = vstd::resource::map::GhostMapAuth::new( + Map::::empty()); + let ghost registry = authority.id(); + let tracked birth = authority.insert(0, registry); + let (id, _receipt) = allocate_store_id(Ghost(registry))?; + let state = Codebooks::new(Ghost(id), Tracked(authority)); + let books = NativeBooks::new(state, Tracked(&birth)); + Ok(Self { id, books, numeric_store: HistoryStore::new(E::Arity::value()), + #[cfg(verus_keep_ghost)] + history_registry: Ghost(registry), + #[cfg(verus_keep_ghost)] + store_id_receipt: _receipt, + #[cfg(verus_keep_ghost)] + registry_birth: Tracked(birth), + }) + } + + /// Return the numeric store shared by every typed view and byte history of this arity. + pub fn numeric_store(&self) -> (result: &Arc) + ensures *result == numeric_owner(*self), + store_wf(*self) ==> *result == crate::store::verify::singleton_store(arity::()) + && crate::store::verify::numeric_store_wf(**result) + && result.arity_spec() == arity::(), + { + &self.numeric_store + } + + pub(crate) fn id(&self) -> (result: u64) + ensures result == store_id(*self), + { + self.id + } + pub(crate) proof fn store_id_receipt_ref(tracked &self) -> (tracked result: &StoreIdReceipt) + requires store_wf(*self), + ensures result.id() == store_id_authority(), result.key() == self.id, + result.value() == self.history_registry@, + { self.store_id_receipt.borrow() } + + #[cfg(verus_keep_ghost)] + pub(crate) fn allocate_history_id(&self) -> (result: Result) + requires store_wf(*self), + ensures result matches Ok(id) ==> 0 < id < usize::MAX, + junco_core::verify::history_specs::no_invariant_failure(result), + result matches Err(error) ==> error == (HistoryError::IdExhausted { domain: "history" }), + { + let (id, _registration, _receipt) = self.allocate_history_id_for_resource(Ghost(arbitrary()), Tracked(None))?; + Ok(id) + } + + /// The checked allocation body publishes an immutable resource-backed receipt. + pub(crate) fn allocate_history_id_for_resource(&self, + Ghost(location): Ghost, Tracked(prior): Tracked>) + -> (result: Result<(usize, Tracked, Tracked), HistoryError>) + requires store_wf(*self), + match prior { Some(registration) => registration.id() == registry_id(self), None => true }, + ensures result matches Ok((id, registration, receipt)) ==> 0 < id < usize::MAX + && registration@.id() == registry_id(self) && registration@.key() == id + && registration@.value() == location + && receipt@.id() == crate::store::verify::history_authority() && receipt@.key() == id + && receipt@.value() == (crate::store::HistoryIssuer::Typed { + store: registry_id(self), lifecycle: location }) + && match prior { Some(previous) => previous.key() < id, None => true }, + junco_core::verify::history_specs::no_invariant_failure(result), + result matches Err(error) ==> error == (HistoryError::IdExhausted { domain: "history" }), + { + proof { if junco_core::spec::hypotheses::event_obligations::() { lemma_empty_maps_wf::(); } } + let ghost owner = self.id; + let ghost registry = self.history_registry@; + self.books.with_books(Ghost(owner), Ghost(empty_maps::()), Ghost(empty_maps::()), Ghost(registry), + &*self.numeric_store, + |books: &mut Codebooks, numeric_store: &HistoryStore| -> (result: Result<(usize, Tracked, Tracked), HistoryError>) + requires books_acquired(*old(books), owner, registry, empty_maps::(), empty_maps::()), + crate::store::verify::numeric_store_wf(*numeric_store), + match prior { Some(previous) => previous.id() == registry, None => true }, + ensures publication_frame(*old(books), *final(books)), + junco_core::verify::history_specs::no_invariant_failure(result), + result matches Err(error) ==> error == (HistoryError::IdExhausted { domain: "history" }), + result matches Ok((id, registration, receipt)) ==> 0 < id < usize::MAX + && registration@.id() == registry && registration@.key() == id + && registration@.value() == location + && receipt@.id() == crate::store::verify::history_authority() && receipt@.key() == id + && receipt@.value() == (crate::store::HistoryIssuer::Typed { + store: registry, lifecycle: location }) + && match prior { Some(previous) => previous.key() < id, None => true }, + { + books.allocate_history_id_for_resource(numeric_store, Ghost(location), Tracked(prior)) + }) + } + + pub(crate) fn encode_event(&self, event: &E) -> (result: Result) + requires store_wf(*self), + ensures result matches Ok(numeric) ==> numeric@.len() == arity::(), + junco_core::spec::hypotheses::event_obligations::() ==> (result matches Ok(numeric) ==> + exists|maps: ComponentMaps| snapshot_published::(registry_id(self), maps) + && maps_wf::(maps) && event_encoded::(maps, *event, numeric)), + junco_core::verify::history_specs::no_invariant_failure(result), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + result matches Err(error) ==> junco_core::spec::semantics::resource_error(error), + { + proof { if junco_core::spec::hypotheses::event_obligations::() { lemma_empty_maps_wf::(); } } + let (result, _) = self.encode_event_with_snapshot(event, + Ghost(empty_maps::()), Ghost(empty_maps::())); + result + } + + /// Extend two previously published finite snapshots under one lock acquisition. + pub fn encode_event_with_snapshot(&self, event: &E, + Ghost(first): Ghost>, Ghost(second): Ghost>) + -> (result: (Result, Ghost>)) + requires store_wf(*self), + junco_core::spec::hypotheses::event_obligations::() ==> maps_wf::(first) + && snapshot_published::(registry_id(self), first) && maps_wf::(second) + && snapshot_published::(registry_id(self), second), + ensures snapshot_published::(registry_id(self), result.1@), + result.0 != Err(HistoryError::WrongHistoryOwner), + result.0 matches Ok(numeric) ==> numeric@.len() == arity::(), + junco_core::verify::history_specs::no_invariant_failure(result.0), + !(result.0 matches Err(HistoryError::InvalidPolicy { .. })), + result.0 matches Err(error) ==> junco_core::spec::semantics::resource_error(error), + junco_core::spec::hypotheses::event_obligations::() ==> maps_wf::(result.1@) + && maps_extend::(first, result.1@) && maps_extend::(second, result.1@) + && (result.0 matches Ok(numeric) ==> event_encoded::(result.1@, *event, numeric)), + { + let ghost owner = self.id; + let ghost registry = self.history_registry@; + self.books.with_books(Ghost(owner), Ghost(first), Ghost(second), Ghost(registry), &*self.numeric_store, + |books: &mut Codebooks, numeric_store: &HistoryStore| -> (output: (Result, Ghost>)) + requires books_acquired(*old(books), owner, registry, first, second), + crate::store::verify::numeric_store_wf(*numeric_store), + numeric_store.arity_spec() == arity::(), + ensures publication_frame(*old(books), *final(books)), + output.0 != Err(HistoryError::WrongHistoryOwner), + output.0 matches Ok(numeric) ==> numeric@.len() == arity::(), + junco_core::verify::history_specs::no_invariant_failure(output.0), + !(output.0 matches Err(HistoryError::InvalidPolicy { .. })), + output.0 matches Err(error) ==> junco_core::spec::semantics::resource_error(error), + output.1@ == books_maps(*final(books)), + junco_core::spec::hypotheses::event_obligations::() ==> maps_wf::(output.1@) + && maps_extend::(first, output.1@) && maps_extend::(second, output.1@) + && (output.0 matches Ok(numeric) ==> event_encoded::(output.1@, *event, numeric)), + { + let ghost initial = books_maps(*books); + let ghost initial_registry = books.components.registry@; + let result = { + let mut encoder = BorrowedEncoder { books: &mut books.components, numeric_store, + #[cfg(verus_keep_ghost)] calls: Ghost(0nat) }; + encoder.encode_event(event) + }; + let ghost maps = books_maps(*books); + proof { + assert(component_receipts_wf(books.components)); + assert(books.components.registry@ == initial_registry); + assert(components_wf(books.components)); + if junco_core::spec::hypotheses::event_obligations::() { + lemma_component_maps_wf(books.components); + junco_core::verify::encoding::lemma_extends_transitive(first, initial, maps, + junco_core::verify::flatten::component_equality::()); + junco_core::verify::encoding::lemma_extends_transitive(second, initial, maps, + junco_core::verify::flatten::component_equality::()); + } + } + (result, Ghost(maps)) + }) + } + + /// Validate/encode constants while holding the same single lock used by requests. + pub fn lower_with_snapshot(&self, source: &FlatPair, + limits: &mut L, world: &mut ObservationWorld, Ghost(prior): Ghost>) + -> (result: (Result, HistoryError>, Ghost>)) + requires store_wf(*self), + junco_core::spec::hypotheses::event_obligations::() ==> maps_wf::(prior) + && snapshot_published::(registry_id(self), prior), + ensures result.0 matches Ok(numeric) ==> junco_core::flat::verify::structural_wf(numeric), + snapshot_published::(registry_id(self), result.1@), + junco_core::spec::hypotheses::event_obligations::() ==> junco_core::verify::history_specs::no_invariant_failure(result.0), + junco_core::spec::hypotheses::event_obligations::() && junco_core::flat::verify::structural_wf(*source) + && junco_core::verify::encoding::constants_in_domain(*source, domain::()) + ==> !(result.0 matches Err(HistoryError::InvalidPolicy { .. })), + junco_core::spec::hypotheses::event_obligations::() && junco_core::flat::verify::structural_wf(*source) + && junco_core::verify::encoding::constants_in_domain(*source, domain::()) + ==> (result.0 matches Err(error) ==> junco_core::spec::semantics::resource_error(error)), + junco_core::spec::hypotheses::event_obligations::() ==> maps_wf::(result.1@) + && maps_extend::(prior, result.1@) + && (result.0 matches Ok(numeric) ==> + junco_core::verify::encoding::lowering(*source, numeric, result.1@, + junco_core::verify::flatten::component_equality::()) + && junco_core::verify::encoding::constants_in_domain(*source, domain::())), + { + let ghost owner = self.id; + let ghost registry = self.history_registry@; + self.books.with_books(Ghost(owner), Ghost(prior), Ghost(prior), Ghost(registry), + (limits, world, &*self.numeric_store), + |books: &mut Codebooks, context: (&mut L, &mut ObservationWorld, &HistoryStore)| + -> (output: (Result, HistoryError>, Ghost>)) + requires books_acquired(*old(books), owner, registry, prior, prior), + crate::store::verify::numeric_store_wf(*context.2), + context.2.arity_spec() == arity::(), + ensures publication_frame(*old(books), *final(books)), + output.1@ == books_maps(*final(books)), + output.0 matches Ok(numeric) ==> junco_core::flat::verify::structural_wf(numeric), + junco_core::spec::hypotheses::event_obligations::() ==> junco_core::verify::history_specs::no_invariant_failure(output.0), + junco_core::spec::hypotheses::event_obligations::() && junco_core::flat::verify::structural_wf(*source) + && junco_core::verify::encoding::constants_in_domain(*source, domain::()) + ==> !(output.0 matches Err(HistoryError::InvalidPolicy { .. })), + junco_core::spec::hypotheses::event_obligations::() && junco_core::flat::verify::structural_wf(*source) + && junco_core::verify::encoding::constants_in_domain(*source, domain::()) + ==> (output.0 matches Err(error) ==> junco_core::spec::semantics::resource_error(error)), + junco_core::spec::hypotheses::event_obligations::() ==> maps_wf::(output.1@) && maps_extend::(prior, output.1@) + && (output.0 matches Ok(numeric) ==> + junco_core::verify::encoding::lowering(*source, numeric, output.1@, + junco_core::verify::flatten::component_equality::()) + && junco_core::verify::encoding::constants_in_domain(*source, domain::())), + { + let (limits, world, numeric_store) = context; + let ghost initial = books_maps(*books); + let ghost initial_registry = books.components.registry@; + proof { if junco_core::spec::hypotheses::event_obligations::() { lemma_component_maps_wf(books.components); } } + let result = { + let mut encoder = BorrowedEncoder { books: &mut books.components, numeric_store, + #[cfg(verus_keep_ghost)] calls: Ghost(0nat) }; + lower_flat(source, &mut encoder, limits, world) + }; + let ghost maps = books_maps(*books); + proof { + assert(component_receipts_wf(books.components)); + assert(books.components.registry@ == initial_registry); + assert(components_wf(books.components)); + if junco_core::spec::hypotheses::event_obligations::() { + junco_core::verify::encoding::lemma_extends_transitive(prior, initial, maps, + junco_core::verify::flatten::component_equality::()); + } + } + (result, Ghost(maps)) + }) + } +} + +/// A scoped encoder borrows codebooks and the process allocator, restoring receipt validity and registry identity. +pub(crate) struct BorrowedEncoder<'a, E: Event> { + pub(crate) books: &'a mut ComponentBooks, + pub(crate) numeric_store: &'a HistoryStore, + #[cfg(verus_keep_ghost)] + pub(crate) calls: Ghost, +} + +impl<'a, E: Event> FlatEncoder for BorrowedEncoder<'a, E> { + open spec fn equality() -> junco_core::verify::encoding::Equality { + junco_core::verify::flatten::component_equality::() + } + open spec fn domain() -> junco_core::verify::encoding::Domain { domain::() } + open(crate) spec fn maps(&self) -> ComponentMaps { component_maps(*self.books) } + open(crate) spec fn encoding_calls(&self) -> nat { self.calls@ } + open(crate) spec fn state_wf(&self) -> bool { + component_receipts_wf(*self.books) + && crate::store::verify::numeric_store_wf(*self.numeric_store) + && self.numeric_store.arity_spec() == arity::() + } + open(crate) spec fn obeys_encoding_spec(&self) -> bool { + junco_core::spec::hypotheses::event_obligations::() && components_wf(*self.books) + } + open spec fn errors_are_non_invariant(&self) -> bool { true } + open spec fn errors_are_resource(&self) -> bool { true } + + #[verifier::prophetic] + open(crate) spec fn restoration(&self) -> (ComponentMaps, bool) { + let restored = mut_ref_future(self.books); + (component_maps(restored), components_wf(restored) + && restored.registry@ == self.books.registry@) + } + + fn encode(&mut self, field: Component, value: &E::Component) + -> (result: Result) + ensures encoder_frame(*old(self), *final(self)), + result != Err(HistoryError::WrongHistoryOwner), + junco_core::verify::history_specs::no_invariant_failure(result), + junco_core::spec::hypotheses::event_obligations::() && domain::()(field, *value) + ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + junco_core::spec::hypotheses::event_obligations::() && domain::()(field, *value) + ==> (result matches Err(error) ==> junco_core::spec::semantics::resource_error(error)), + { + proof { + self.calls = Ghost(self.calls@ + 1); + junco_core::verify::encoding::lemma_grows_by_refl(component_maps(*self.books), junco_core::verify::encoding::only_value(field, *value)); + } + validate_component::(field, value)?; + let index = field.index(); + if index >= self.books.books.len() { + return Err(HistoryError::invalid_policy("$", "constant belongs to another component")); + } + self.intern_component(index, value) + } +} + +impl<'a, E: Event> BorrowedEncoder<'a, E> { + // Requests obtain the coordinate from their position, not from untrusted native key code. + // Constant encoding checks that position before reaching this common receipt-preserving path. + fn intern_component(&mut self, index: usize, value: &E::Component) + -> (result: Result) + requires old(self).state_wf(), index < arity::(), + junco_core::spec::hypotheses::event_obligations::() && components_wf(*old(self).books) + ==> domain::()(Component(index as u8), *value), + ensures final(self).state_wf(), encoder_frame(*old(self), *final(self)), + final(self).restoration() == old(self).restoration(), + final(self).calls == old(self).calls, + result != Err(HistoryError::WrongHistoryOwner), + junco_core::verify::history_specs::no_invariant_failure(result), + result matches Err(error) ==> error == HistoryError::AllocationFailed + || error == (HistoryError::IdExhausted { domain: "component" }), + junco_core::spec::hypotheses::event_obligations::() && components_wf(*old(self).books) ==> + maps_wf::(component_maps(*final(self).books)) + && maps_extend::(component_maps(*old(self).books), component_maps(*final(self).books)) + && junco_core::verify::encoding::grows_by(component_maps(*old(self).books), component_maps(*final(self).books), + junco_core::verify::encoding::only_value(Component(index as u8), *value)) + && (result matches Ok(id) ==> junco_core::verify::encoding::encoded( + component_maps(*final(self).books), Self::equality(), Component(index as u8), *value, id)), + { + let ghost initial = *self.books; + let ghost initial_wf = components_wf(initial); + let result = self.books.books[index].intern(value, index, "component", self.numeric_store, + Ghost(crate::store::ComponentIssuer::Typed(self.books.registry@))); + proof { + assert forall|i: int| 0 <= i < arity::() implies + book_receipts_wf(self.books.books@[i], i, + crate::store::ComponentIssuer::Typed(self.books.registry@)) by { + if i != index { assert(self.books.books@[i] == initial.books@[i]); } + } + assert(component_receipts_wf(*self.books)); + if junco_core::spec::hypotheses::event_obligations::() && initial_wf { + assert forall|i: int| 0 <= i < arity::() implies + book_wf(self.books.books@[i]) + && (forall|j: int| 0 <= j < book_entries(self.books.books@[i]).len() ==> + E::coordinate_spec(book_entries(self.books.books@[i])[j].0) == i) by { + if i == index { + let before = book_entries(initial.books@[i]); + let after = book_entries(self.books.books@[i]); + assert forall|j: int| 0 <= j < after.len() implies + E::coordinate_spec(after[j].0) == i by { + if j < before.len() { assert(after[j] == before[j]); } + else { assert(after[j].0 == *value); } + } + } else { assert(self.books.books@[i] == initial.books@[i]); } + } + assert(components_wf(*self.books)); + assert forall|i: int| 0 <= i < arity::() implies + book_entries(initial.books@[i]).is_prefix_of(book_entries(self.books.books@[i])) by { + if i != index { assert(self.books.books@[i] == initial.books@[i]); } + } + lemma_component_maps_wf(*self.books); + lemma_component_maps_extend(initial, *self.books); + assert forall|i: int| 0 <= i < arity::() && i != index + implies self.books.books@[i] == initial.books@[i] by {} + if let Ok(id) = result { + assert(book_entries(self.books.books@[index as int]) == book_entries(initial.books@[index as int]) + || book_entries(self.books.books@[index as int]) == book_entries(initial.books@[index as int]).push((*value, id))); + } + lemma_component_maps_grow(initial, *self.books, index as int, *value); + if let Ok(id) = result { + lemma_component_book_encoded(*self.books, Component(index as u8), *value, id); + } + } + } + result + } + + fn encode_event(&mut self, event: &E) -> (result: Result) + requires old(self).state_wf(), components_wf(*old(self).books), + ensures final(self).state_wf(), components_wf(*final(self).books), + result matches Ok(numeric) ==> numeric@.len() == arity::(), + result != Err(HistoryError::WrongHistoryOwner), + junco_core::verify::history_specs::no_invariant_failure(result), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + result matches Err(error) ==> junco_core::spec::semantics::resource_error(error), + final(self).books.registry@ == old(self).books.registry@, + junco_core::spec::hypotheses::event_obligations::() ==> + maps_extend::(component_maps(*old(self).books), component_maps(*final(self).books)) + && (result matches Ok(numeric) ==> event_encoded::(component_maps(*final(self).books), *event, numeric)), + final(self).restoration() == old(self).restoration(), + { + let width = E::Arity::value(); + let mut slots = [0u64; MAX_ARITY]; + let ghost before = component_maps(*self.books); + let ghost registry = self.books.registry@; + let ghost restored = self.restoration(); + let mut index = 0; + while index < width + invariant index <= width, width == arity::(), 1 <= width <= MAX_ARITY, + self.state_wf(), components_wf(*self.books), self.books.registry@ == registry, + registry == old(self).books.registry@, + self.restoration() == restored, restored == old(self).restoration(), + before == component_maps(*old(self).books), + junco_core::spec::hypotheses::event_obligations::() ==> maps_extend::(before, component_maps(*self.books)), + junco_core::spec::hypotheses::event_obligations::() ==> forall|i: int| 0 <= i < index ==> + junco_core::verify::encoding::encoded(component_maps(*self.books), Self::equality(), + Component(i as u8), event_view(*event)[i], slots@[i]), + decreases width - index, + { + let value = event.component(index); + let ghost previous = component_maps(*self.books); + let result = self.intern_component(index, &value); + proof { + if junco_core::spec::hypotheses::event_obligations::() { + junco_core::verify::encoding::lemma_extends_transitive(before, previous, + component_maps(*self.books), Self::equality()); + assert(before.len() == previous.len()); + assert(previous.len() == component_maps(*self.books).len()); + assert(maps_extend::(before, component_maps(*self.books))); + assert forall|i: int| 0 <= i < index implies + junco_core::verify::encoding::encoded(component_maps(*self.books), Self::equality(), + Component(i as u8), event_view(*event)[i], slots@[i]) by { + assert(junco_core::verify::encoding::encoded(previous, Self::equality(), + Component(i as u8), event_view(*event)[i], slots@[i])); + } + } + } + slots[index] = result?; + index += 1; + } + let numeric = NumericEvent::from_encoded(&slots[..width]); + proof { + assert forall|i: int| 0 <= i < width implies numeric_values(numeric)[i] == slots@[i] by {} + if junco_core::spec::hypotheses::event_obligations::() { + assert forall|i: int| 0 <= i < width implies + domain::()(Component(i as u8), event_view(*event)[i]) by {} + } + } + Ok(numeric) + } +} +} + +impl core::fmt::Debug for Store { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("Store") + .field("id", &self.id) + .finish_non_exhaustive() + } +} + +#[cfg(verus_keep_ghost)] +pub mod verify { + use super::*; + use junco_core::verify::encoding; + use junco_core::verify::flatten::component_equality; + use vstd::std_specs::option::OptionAdditionalFns; + verus! { + + pub type ComponentMaps = super::ComponentMaps; + pub type HistoryRegistration = super::HistoryRegistration; + + /// Native allocation identity, independent of codebook and registry identities. + pub closed spec fn same_store_owner(left: Arc>, right: Arc>) -> bool { + arc_identity(left) == arc_identity(right) + } + + pub proof fn lemma_same_store_owner_identity(left: Arc>, right: Arc>) + ensures same_store_owner(left, right) == (arc_identity(left) == arc_identity(right)), + {} + + pub(crate) proof fn empty_store_id_authority() -> (tracked result: StoreIdAuth) + ensures result@ == Map::::empty(), + { + let tracked (authority, empty) = StoreIdAuth::new(Map::empty()); + authority + } + + pub open(crate) spec fn store_id_state_wf(state: StoreIdState) -> bool { + forall|id: u64| #[trigger] (state.issued@)@.contains_key(id) + <==> 0 < id <= state.last + } + + pub open(crate) spec fn store_id_state_frame(before: StoreIdState, after: StoreIdState) -> bool { + store_id_state_wf(after) && before.issued@.id() == after.issued@.id() + && before.last <= after.last && (before.issued@)@ <= (after.issued@)@ + } + + pub(crate) uninterp spec fn store_ids_authority_id(ids: NativeStoreIds) -> vstd::resource::Loc; + pub(crate) uninterp spec fn process_store_ids() -> NativeStoreIds; + pub open(super) spec fn store_id_authority() -> vstd::resource::Loc { + store_ids_authority_id(process_store_ids()) + } + pub(crate) uninterp spec fn store_ids_mutex_valid(ids: NativeStoreIds) -> bool; + + pub open(crate) spec fn store_id_state_acquired(state: StoreIdState, ids: NativeStoreIds) -> bool { + store_id_state_wf(state) && state.issued@.id() == store_ids_authority_id(ids) + } + + pub open(crate) spec fn store_id_issue_result(before: StoreIdState, after: StoreIdState, + registry: vstd::resource::Loc, + result: Result<(u64, Tracked), HistoryError>) -> bool { + &&& store_id_state_frame(before, after) + &&& match result { + Ok((id, receipt)) => { + &&& before.last < u64::MAX + &&& id == before.last + 1 + &&& after.last == id + &&& (after.issued@)@ == (before.issued@)@.insert(id, registry) + &&& receipt@.id() == after.issued@.id() + &&& receipt@.key() == id + &&& receipt@.value() == registry + &&& 0 < id <= after.last + }, + Err(error) => { + &&& before.last == u64::MAX + &&& after.last == before.last + &&& (after.issued@)@ == (before.issued@)@ + &&& error == HistoryError::IdExhausted { domain: "store" } + }, + } + } + + // Dropping the first consumer's receipt cannot recycle its authoritative entry. + pub(crate) fn store_id_state_nonrecycling_client(Ghost(registry): Ghost) + -> (result: StoreIdState) + ensures store_id_state_wf(result), result.last == 2, + (result.issued@)@ == map![1u64 => registry, 2u64 => registry], + { + let mut state = StoreIdState::new(); + { + let first = issue_store_id(&mut state, Ghost(registry)); + assert(first matches Ok((id, _)) && id == 1); + } + let second = issue_store_id(&mut state, Ghost(registry)); + assert(second matches Ok((id, _)) && id == 2); + state + } + + pub(crate) fn store_id_state_max_client(state: &mut StoreIdState, + Ghost(registry): Ghost) + requires store_id_state_wf(*old(state)), old(state).last == u64::MAX - 1, + ensures store_id_state_wf(*final(state)), final(state).last == u64::MAX, + final(state).issued@.id() == old(state).issued@.id(), + (final(state).issued@)@ == (old(state).issued@)@.insert(u64::MAX, registry), + { + let first = issue_store_id(state, Ghost(registry)); + assert(first matches Ok((id, _)) && id == u64::MAX); + let ghost issued = (state.issued@)@; + let second = issue_store_id(state, Ghost(registry)); + assert(second == Err(HistoryError::IdExhausted { domain: "store" })); + assert((state.issued@)@ == issued); + } + + pub(crate) proof fn lemma_registry_births_distinct( + tracked left: &mut RegistryBirth, tracked right: &RegistryBirth) + requires old(left).key() == 0, right.key() == 0, + ensures final(left).id() == old(left).id(), final(left)@ == old(left)@, + final(left).id() != right.id(), + { + if left.id() == right.id() { + left.disjoint(right); + assert(false); + } + } + + pub(crate) proof fn lemma_store_receipts_distinct( + left_registry: vstd::resource::Loc, right_registry: vstd::resource::Loc, + tracked left: &StoreIdReceipt, tracked right: &StoreIdReceipt) + requires left.id() == right.id(), left.value() == left_registry, + right.value() == right_registry, left_registry != right_registry, + ensures left.key() != right.key(), + { + let tracked mut witness = left.duplicate(); + witness.intersection_agrees(right); + } + + #[doc(hidden)] + pub fn independently_constructed_stores_client() + -> (result: Result<(Store, Store), HistoryError>) + ensures result matches Ok((left, right)) ==> store_wf(left) && store_wf(right) + && registry_id(&left) != registry_id(&right) && store_id(left) != store_id(right), + { + let mut left = Store::::new()?; + let right = Store::::new()?; + proof { + lemma_registry_births_distinct(left.registry_birth.borrow_mut(), right.registry_birth.borrow()); + lemma_store_receipts_distinct(left.history_registry@, right.history_registry@, + left.store_id_receipt.borrow(), right.store_id_receipt.borrow()); + } + Ok((left, right)) + } + + fn typed_component_receipt_client(store: &Store, value: &E::Component, index: usize) + -> (result: Result<(u64, Tracked), HistoryError>) + requires store_wf(*store), index < arity::(), junco_core::spec::hypotheses::key_laws::(), + ensures result matches Ok((id, receipt)) ==> receipt@.key() == id + && receipt@.id() == crate::store::verify::coordinate_authority(index as int) + && receipt@.value() == crate::store::ComponentIssuer::Typed(store.history_registry@), + { + let mut book = Codebook::::new(); + let id = book.intern(value, index, "component", store.numeric_store(), + Ghost(crate::store::ComponentIssuer::Typed(store.history_registry@)))?; + let tracked receipt; + proof { + let ghost entries = book_entries(book); + let ghost i = choose|i: int| 0 <= i < entries.len() + && entries[i].1 == id && value.eq_spec(&entries[i].0); + let ghost ids = entries.map(|i: int, pair: (E::Component, u64)| pair.1); + assert(ids[i] == id); + assert(ids.to_set().contains(id)); + assert(book.issued@ is Some); + let tracked held = book.issued.borrow().tracked_borrow(); + let tracked mut aggregate = held.duplicate(); + assert(aggregate@.contains_key(id)); + receipt = aggregate.split_points_to(id); + } + Ok((id, Tracked(receipt))) + } + + pub(crate) fn component_receipts_client( + left: &Store, right: &Store, first: &E::Component, second: &F::Component, + component: Component, bytes: &[u8], limits: &mut L, world: &mut ObservationWorld) + -> (result: Result<(u64, u64, u64), HistoryError>) + requires store_wf(*left), store_wf(*right), component.0 < arity::(), + component.0 < arity::(), left.history_registry@ != right.history_registry@, + junco_core::spec::hypotheses::key_laws::(), junco_core::spec::hypotheses::key_laws::(), + ensures result matches Ok((byte, first, second)) ==> + byte != first && byte != second && first != second, + { + let index = component.index(); + let (byte, Tracked(binding)) = left.numeric_store().intern_observed(component, bytes, limits, world)?; + let tracked byte_receipt = binding.issuer_receipt(); + let (first, Tracked(first_receipt)) = typed_component_receipt_client(left, first, index)?; + let (second, Tracked(second_receipt)) = typed_component_receipt_client(right, second, index)?; + proof { + let tracked mut byte_witness = byte_receipt.duplicate(); + byte_witness.intersection_agrees(&first_receipt); + byte_witness.intersection_agrees(&second_receipt); + let tracked mut typed_witness = first_receipt.duplicate(); + typed_witness.intersection_agrees(&second_receipt); + } + Ok((byte, first, second)) + } + + + pub open spec fn domain() -> encoding::Domain { + junco_core::verify::flatten::component_domain::() + } + + /// The event obligations make component equality an equivalence. + pub proof fn lemma_native_obligations_eq_equivalence() + requires junco_core::spec::hypotheses::event_obligations::(), + ensures junco_core::spec::hypotheses::eq_equivalence::(), + { + } + + /// Projection and arity facts available to typed-policy clients outside this crate. + pub proof fn lemma_native_obligations_projection() + requires junco_core::spec::hypotheses::event_obligations::(), + ensures E::obeys_projection_spec(), projection_laws::(), + 1 <= arity::() <= MAX_ARITY, + {} + + pub open spec fn empty_maps() -> ComponentMaps { + Seq::new(arity::(), |i: int| Seq::<(E::Component, u64)>::empty()) + } + + pub open spec fn maps_wf(maps: ComponentMaps) -> bool { + maps.len() == arity::() + && encoding::maps_wf(maps, component_equality::(), domain::()) + } + pub open spec fn maps_extend(before: ComponentMaps, after: ComponentMaps) -> bool { + before.len() == after.len() && encoding::extends(before, after, component_equality::()) + } + + /// Persistent provenance scoped to the unique, linearly owned mutex registry resource. + pub uninterp spec fn snapshot_published(registry: vstd::resource::Loc, maps: ComponentMaps) -> bool; + + pub open(crate) spec fn store_id(store: Store) -> u64 { store.id } + pub open(super) spec fn numeric_owner(store: Store) -> Arc { store.numeric_store } + pub open(crate) spec fn store_wf(store: Store) -> bool { + store.id > 0 && mutex_valid(store.books, store.id, store.history_registry@) + && snapshot_published::(store.history_registry@, empty_maps::()) + && store.numeric_store == crate::store::verify::singleton_store(arity::()) + && crate::store::verify::numeric_store_wf(*store.numeric_store) + && store.numeric_store.arity_spec() == arity::() + && store.store_id_receipt@.id() == store_id_authority() + && store.store_id_receipt@.key() == store.id + && store.store_id_receipt@.value() == store.history_registry@ + && store.registry_birth@.id() == store.history_registry@ + && store.registry_birth@.key() == 0 + && store.registry_birth@.value() == store.history_registry@ + } + + pub open(crate) spec fn registry_id(store: &Store) -> vstd::resource::Loc { + store.history_registry@ + } + + pub proof fn lemma_empty_snapshot(store: &Store) + requires store_wf(*store), + ensures snapshot_published::(registry_id(store), empty_maps::()), + {} + + + pub proof fn registrations_agree(tracked left: &HistoryRegistration, tracked right: &HistoryRegistration) + requires left.id() == right.id(), left.key() == right.key(), + ensures left.value() == right.value(), + { + let tracked mut left_map = left.duplicate().submap(); + left_map.combine_points_to(right.duplicate()); + } + + + pub open spec fn numeric_values(numeric: NumericEvent) -> Seq { + numeric@.map(|i: int, value: nat| value as u64) + } + + pub open spec fn event_encoded(maps: ComponentMaps, raw: E, numeric: NumericEvent) -> bool { + encoding::event_encoded(maps, component_equality::(), domain::(), + event_view(raw), numeric_values(numeric)) + && junco_core::verify::encoding::event_representation(numeric_values(numeric), numeric@) + } + + pub(crate) open(crate) spec fn book_entries(book: Codebook) -> Seq<(K, u64)> { + book.values@ + } + pub(crate) open(crate) spec fn book_wf(book: Codebook) -> bool { + (forall|i: int| #![trigger book_entries(book)[i]] + 0 <= i < book_entries(book).len() ==> 0 < book_entries(book)[i].1 <= book.last) + && (junco_core::spec::hypotheses::key_laws::() ==> forall|i: int, j: int| + 0 <= i < book_entries(book).len() && 0 <= j < book_entries(book).len() + ==> (book_entries(book)[i].0.eq_spec(&book_entries(book)[j].0) + == (book_entries(book)[i].1 == book_entries(book)[j].1))) + } + pub(crate) open(crate) spec fn book_encoded(book: Codebook, value: K, id: u64) -> bool { + id > 0 && exists|i: int| 0 <= i < book_entries(book).len() + && book_entries(book)[i].1 == id && value.eq_spec(&book_entries(book)[i].0) + } + pub(crate) open(crate) spec fn book_receipts_wf(book: Codebook, + index: int, issuer: crate::store::ComponentIssuer) -> bool { + match book.issued@ { + None => book.last == 0 + && (junco_core::spec::hypotheses::key_laws::() ==> book_entries(book).len() == 0), + Some(receipts) => receipts.id() == crate::store::verify::coordinate_authority(index) + && receipts@.contains_key(book.last) + && (forall|id: u64| #[trigger] receipts@.contains_key(id) ==> + 0 < id <= book.last && receipts@[id] == issuer) + && (junco_core::spec::hypotheses::key_laws::() ==> receipts@.dom() == + book_entries(book).map(|i: int, pair: (K,u64)| pair.1).to_set()), + } + } + pub(crate) open(crate) spec fn component_receipts_wf(books: ComponentBooks) -> bool { + books.books@.len() == arity::() && 1 <= arity::() <= MAX_ARITY + && forall|index: int| 0 <= index < arity::() ==> + book_receipts_wf(books.books@[index], index, + crate::store::ComponentIssuer::Typed(books.registry@)) + } + pub(crate) open(crate) spec fn components_wf(books: ComponentBooks) -> bool { + component_receipts_wf(books) + && (junco_core::spec::hypotheses::event_obligations::() ==> forall|index: int| 0 <= index < arity::() ==> + book_wf(books.books@[index]) + && forall|i: int| 0 <= i < book_entries(books.books@[index]).len() ==> + E::coordinate_spec(book_entries(books.books@[index])[i].0) == index) + } + pub open(crate) spec fn encoder_frame<'a, E: Event>(before: BorrowedEncoder<'a, E>, after: BorrowedEncoder<'a, E>) -> bool { + before.books.registry@ == after.books.registry@ + && (components_wf(*before.books) ==> components_wf(*after.books)) + } + pub(crate) open(crate) spec fn component_maps(books: ComponentBooks) -> ComponentMaps { + books.books@.map(|i: int, book: Codebook| book_entries(book)) + } + + pub(crate) proof fn lemma_component_book_encoded( + books: ComponentBooks, field: Component, value: E::Component, id: u64) + requires junco_core::spec::hypotheses::event_obligations::(), components_wf(books), + field.0 < arity::(), domain::()(field, value), + book_encoded(books.books@[field.0 as int], value, id), + ensures encoding::encoded(component_maps(books), component_equality::(), field, value, id), + domain::()(field, value), + { + let f = field.0 as int; + let entries = book_entries(books.books@[f]); + let i = choose|i: int| 0 <= i < entries.len() && entries[i].1 == id + && value.eq_spec(&entries[i].0); + assert(component_maps(books)[f][i] == entries[i]); + } + pub(crate) open(crate) spec fn books_wf(books: Codebooks) -> bool { + components_wf(books.components) && books.components.registry@ == books.history_resources@.id() + } + pub(crate) open(crate) spec fn books_maps(books: Codebooks) -> ComponentMaps { + component_maps(books.components) + } + pub(crate) open(crate) spec fn self_same_books(before: Codebooks, after: Codebooks) -> bool { + before.components == after.components && before.owner@ == after.owner@ + } + // Keys may be sparse: other views and byte records share the process allocator. + pub(crate) open(crate) spec fn registry_wf(books: Codebooks) -> bool { + books.next_history > 0 && (books.history_resources@)@.contains_key(0) + && (books.history_resources@)@[0] == books.history_resources@.id() + && (forall|id: usize| (books.history_resources@)@.contains_key(id) ==> id < books.next_history) + && match books.latest_history@ { + None => books.next_history == 1, + Some(receipt) => receipt.id() == crate::store::verify::history_authority() + && receipt.key() + 1 == books.next_history, + } + } + pub(crate) uninterp spec fn mutex_valid(mutex: NativeBooks, owner: u64, registry: vstd::resource::Loc) -> bool; + + pub(crate) open(crate) spec fn books_acquired(books: Codebooks, owner: u64, + registry: vstd::resource::Loc, first: ComponentMaps, second: ComponentMaps) -> bool { + books.owner@ == owner && registry_wf(books) && books.history_resources@.id() == registry + && books_wf(books) + && (junco_core::spec::hypotheses::event_obligations::() ==> + maps_extend::(first, books_maps(books)) && maps_extend::(second, books_maps(books))) + } + + pub(crate) open(crate) spec fn publication_frame(before: Codebooks, after: Codebooks) -> bool { + before.owner@ == after.owner@ && registry_wf(after) + && before.components.registry@ == after.components.registry@ && books_wf(after) + && before.history_resources@.id() == after.history_resources@.id() + && (before.history_resources@)@.submap_of((after.history_resources@)@) + && (junco_core::spec::hypotheses::event_obligations::() ==> books_wf(after) && maps_extend::(books_maps(before), books_maps(after))) + } + + pub proof fn lemma_empty_maps_wf() + requires junco_core::spec::hypotheses::event_obligations::(), + ensures maps_wf::(empty_maps::()), + {} + + pub(super) proof fn lemma_component_maps_wf(books: ComponentBooks) + requires components_wf(books), + ensures junco_core::spec::hypotheses::event_obligations::() ==> maps_wf::(component_maps(books)), + { + if junco_core::spec::hypotheses::event_obligations::() { + assert(encoding::equality_laws(component_equality::(), domain::())); + assert forall|f: int, i: int| 0 <= f < arity::() && 0 <= i < component_maps(books)[f].len() + implies domain::()(encoding::field_at(f), component_maps(books)[f][i].0) + && component_maps(books)[f][i].1 > 0 by { + assert(component_maps(books)[f] == book_entries(books.books@[f])); + } + assert forall|f: int, i: int, j: int| 0 <= f < arity::() + && 0 <= i < component_maps(books)[f].len() && 0 <= j < component_maps(books)[f].len() + implies (component_equality::()(encoding::field_at(f), component_maps(books)[f][i].0, + component_maps(books)[f][j].0) == (component_maps(books)[f][i].1 == component_maps(books)[f][j].1)) by { + assert(book_wf(books.books@[f])); + } + } + } + + pub(super) proof fn lemma_component_maps_extend(before: ComponentBooks, after: ComponentBooks) + requires before.books@.len() == after.books@.len(), + forall|f: int| 0 <= f < before.books@.len() ==> + book_entries(before.books@[f]).is_prefix_of(book_entries(after.books@[f])), + ensures maps_extend::(component_maps(before), component_maps(after)), + { + assert forall|field: Component, value: E::Component, id: u64| + encoding::encoded(component_maps(before), component_equality::(), field, value, id) + implies encoding::encoded(component_maps(after), component_equality::(), field, value, id) by { + let f = junco_core::flat::verify::field_index(field); + let i = choose|i: int| 0 <= i < component_maps(before)[f].len() && component_maps(before)[f][i].1 == id + && component_equality::()(field, value, component_maps(before)[f][i].0); + assert(book_entries(before.books@[f]).is_prefix_of(book_entries(after.books@[f]))); + assert(component_maps(after)[f][i] == component_maps(before)[f][i]); + } + } + + /// One `intern` at `index` adds at most the interned value to the books. + pub(super) proof fn lemma_component_maps_grow(before: ComponentBooks, after: ComponentBooks, + index: int, value: E::Component) + requires before.books@.len() == after.books@.len(), 0 <= index < before.books@.len(), + forall|f: int| 0 <= f < before.books@.len() && f != index ==> after.books@[f] == before.books@[f], + book_entries(after.books@[index]) == book_entries(before.books@[index]) + || exists|id: u64| book_entries(after.books@[index]) == book_entries(before.books@[index]).push((value, id)), + ensures encoding::grows_by(component_maps(before), component_maps(after), encoding::only_value(Component(index as u8), value)), + { + let b = component_maps(before); + let a = component_maps(after); + assert forall|f: int, i: int| #![trigger a[f][i]] 0 <= f < a.len() && 0 <= i < a[f].len() + implies (exists|j: int| 0 <= j < b[f].len() && (#[trigger] b[f][j]).0 == a[f][i].0) + || encoding::only_value(Component(index as u8), value)(encoding::field_at(f), a[f][i].0) by { + assert(a[f] == book_entries(after.books@[f])); + assert(b[f] == book_entries(before.books@[f])); + if f == index && i >= b[f].len() { + assert(a[f][i].0 == value); + } else { + assert(a[f][i] == b[f][i]); + } + } + } + + pub proof fn lemma_event_extension(before: ComponentMaps, after: ComponentMaps, + raw: E, numeric: NumericEvent) + requires maps_extend::(before, after), event_encoded::(before, raw, numeric), + ensures event_encoded::(after, raw, numeric), + {} + } +} + +#[cfg(test)] +mod tests { + use super::*; + use core::hash::{Hash, Hasher}; + use history_syntax::{Component3, Component4, N3, N4}; + + #[derive(Copy, Clone, Debug)] + struct Key { + identity: u8, + payload: u8, + } + impl PartialEq for Key { + fn eq(&self, other: &Self) -> bool { + self.identity == other.identity + } + } + impl Eq for Key {} + impl Hash for Key { + fn hash(&self, state: &mut H) { + 0u8.hash(state); + } + } + impl history_syntax::KeyHash for Key { + fn key_hash(&self) -> u64 { + history_syntax::key_hash::hash_via_std(self) + } + } + #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] + struct TestEvent(Key); + impl Event for TestEvent { + type Component = Component3; + type Arity = N3; + fn component(self, index: usize) -> Self::Component { + match index { + 0 => Component3::C0(self.0), + 1 => Component3::C1(self.0), + _ => Component3::C2(self.0), + } + } + fn coordinate(component: Self::Component) -> usize { + match component { + Component3::C0(_) => 0, + Component3::C1(_) => 1, + Component3::C2(_) => 2, + } + } + } + + #[test] + fn checked_allocator_rejects_wrap_without_global_mutation() { + assert_eq!(checked_successor(0, "store").unwrap(), 1); + assert_eq!(checked_successor(u64::MAX - 1, "store").unwrap(), u64::MAX); + assert!(matches!( + checked_successor(u64::MAX, "store"), + Err(HistoryError::IdExhausted { domain: "store" }) + )); + } + + #[test] + fn failed_allocation_preserves_reuse_and_collisions_are_not_identity() { + let numeric = HistoryStore::new(3); + let mut book = Codebook::new(); + let first = Key { + identity: 7, + payload: 1, + }; + let equivalent = Key { + identity: 7, + payload: 2, + }; + let other = Key { + identity: 8, + payload: 1, + }; + assert_eq!(equivalent.payload, 2); + let id = book + .intern(&first, 0, "component", &numeric, Ghost::assume_new()) + .unwrap(); + assert_eq!( + book.intern(&equivalent, 0, "component", &numeric, Ghost::assume_new()) + .unwrap(), + id + ); + // No shared-counter ID exceeds this book's newest one, so only reuse can succeed. + book.last = u64::MAX; + assert!(matches!( + book.intern(&other, 0, "component", &numeric, Ghost::assume_new()), + Err(HistoryError::Invariant { .. }) + )); + assert_eq!(book.last, u64::MAX); + assert_eq!( + book.intern(&equivalent, 0, "component", &numeric, Ghost::assume_new()) + .unwrap(), + id + ); + assert_eq!(book.values.lookup(&other), None); + let mut book = Codebook::new(); + let first_action = book + .intern(&first, 1, "component", &numeric, Ghost::assume_new()) + .unwrap(); + assert!( + book.intern(&other, 1, "component", &numeric, Ghost::assume_new()) + .unwrap() + > first_action + ); + assert_eq!( + book.intern(&equivalent, 1, "component", &numeric, Ghost::assume_new()) + .unwrap(), + first_action + ); + } + + #[test] + fn history_exhaustion_is_checked_and_does_not_change_codebooks() { + // The shared counter's MAX boundary is covered by `store::next_history_id` on locals. + let numeric = HistoryStore::new(3); + let mut books = Codebooks::::new(Ghost::assume_new(), Tracked::assume_new()); + books.next_history = usize::MAX; + assert!(matches!( + books.allocate_history_id(&numeric, Ghost::assume_new()), + Err(HistoryError::IdExhausted { domain: "history" }) + )); + assert_eq!(books.next_history, usize::MAX); + assert!(books.components.books.iter().all(|book| book.last == 0)); + + let store = alloc::sync::Arc::new(Store::::new().unwrap()); + let history = crate::history::History::from_events( + alloc::sync::Arc::clone(&store), + [TestEvent(Key { + identity: 7, + payload: 1, + })], + ) + .unwrap(); + let raw = history.as_slice().to_vec(); + let numeric = history.numeric.events.clone(); + let revision = history.numeric.revision; + store.books.inner.lock().next_history = usize::MAX; + assert!(matches!( + crate::history::History::new(alloc::sync::Arc::clone(&store)), + Err(HistoryError::IdExhausted { domain: "history" }) + )); + assert!(matches!( + history.try_clone(), + Err(HistoryError::IdExhausted { domain: "history" }) + )); + assert_eq!(history.as_slice(), raw.as_slice()); + assert_eq!(history.numeric.events, numeric); + assert_eq!(history.numeric.revision, revision); + } + + #[test] + fn typed_domains_and_all_event_types_use_one_store_allocator() { + let store = Store::::new().unwrap(); + #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] + struct OtherEvent(u8); + impl Event for OtherEvent { + type Component = Component4; + type Arity = N4; + fn component(self, index: usize) -> Self::Component { + match index { + 0 => Component4::C0(self.0), + 1 => Component4::C1(self.0), + 2 => Component4::C2(self.0), + _ => Component4::C3(self.0), + } + } + fn coordinate(component: Self::Component) -> usize { + match component { + Component4::C0(_) => 0, + Component4::C1(_) => 1, + Component4::C2(_) => 2, + Component4::C3(_) => 3, + } + } + } + let other = Store::::new().unwrap(); + assert_ne!(store.id(), other.id()); + let first = TestEvent(Key { + identity: 7, + payload: 1, + }); + let equivalent = TestEvent(Key { + identity: 7, + payload: 2, + }); + let encoded = store.encode_event(&first).unwrap(); + assert_eq!(encoded, store.encode_event(&equivalent).unwrap()); + let other_encoded = other.encode_event(&OtherEvent(7)).unwrap(); + assert_eq!(encoded.arity(), 3); + assert_eq!(other_encoded.arity(), 4); + assert!(!Arc::ptr_eq(store.numeric_store(), other.numeric_store())); + for index in 0..encoded.arity() { + assert!(encoded.component(index) < other_encoded.component(index)); + } + { + let mut books = store.books.inner.lock(); + let mut encoder = BorrowedEncoder { + books: &mut books.components, + numeric_store: &store.numeric_store, + #[cfg(verus_keep_ghost)] + calls: Ghost(0nat), + }; + let value = Key { + identity: 8, + payload: 0, + }; + assert!( + encoder + .encode(Component(0), &Component3::C0(value)) + .unwrap() + > encoded.component(0) + ); + assert!( + encoder + .encode(Component(1), &Component3::C1(value)) + .unwrap() + > encoded.component(1) + ); + assert!( + encoder + .encode(Component(2), &Component3::C2(value)) + .unwrap() + > encoded.component(2) + ); + assert!(matches!( + encoder.encode(Component(2), &Component3::C0(value)), + Err(HistoryError::InvalidPolicy { + message: "constant belongs to another component", + .. + }) + )); + } + } + + #[test] + fn typed_numeric_events_never_name_byte_store_identities() { + use junco_core::limits::Unmetered; + use junco_core::observation::ObservationWorld; + let byte = HistoryStore::new(3); + let fresh = |bytes: &[u8]| { + byte.intern(Component(0), bytes, &mut Unmetered, &mut ObservationWorld) + .unwrap() + }; + let before = fresh(b"typed-vs-byte/before\xff"); + let action = byte + .intern( + Component(1), + b"typed-vs-byte/edit\xfe", + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + let resource = byte + .intern( + Component(2), + b"typed-vs-byte/doc\x80", + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + let typed = alloc::sync::Arc::new(Store::::new().unwrap()); + assert!(alloc::sync::Arc::ptr_eq(typed.numeric_store(), &byte)); + let history = crate::history::History::from_events( + typed, + [TestEvent(Key { + identity: 7, + payload: 1, + })], + ) + .unwrap(); + let exported = history.numeric().as_slice()[0]; + let after = fresh(b"typed-vs-byte/after\xff"); + // Fresh per-test names: the shared counter orders these three issuances. + assert!(before < exported.component(0)); + assert!(exported.component(0) < after); + assert_ne!(exported.component(1), action); + assert_ne!(exported.component(2), resource); + let target = byte + .new_history(&mut Unmetered, &mut ObservationWorld) + .unwrap(); + let valid = NumericEvent::from_encoded(&[before, action, resource]); + byte.append(&target, &[valid], &mut Unmetered, &mut ObservationWorld) + .unwrap(); + for index in 0..3 { + let mut slots = [before, action, resource]; + slots[index] = exported.component(index); + let invalid = NumericEvent::from_encoded(&slots); + assert!(matches!( + byte.append( + &target, + &[valid, invalid], + &mut Unmetered, + &mut ObservationWorld + ), + Err(HistoryError::UnknownId { .. }) + )); + let record = byte.history_record(&target).unwrap(); + let record = record.read(); + assert_eq!(record.as_slice(), &[valid]); + assert_eq!(record.revision(), 0); + } + } + + #[test] + // The test proves non-Send components work; `History` still takes its store by `Arc`. + #[allow(clippy::arc_with_non_send_sync)] + fn borrowed_non_send_components_stay_scoped() { + use core::cell::Cell; + #[derive(Copy, Clone, Debug)] + struct Borrowed<'a> { + id: u8, + cell: &'a Cell, + } + impl PartialEq for Borrowed<'_> { + fn eq(&self, other: &Self) -> bool { + self.id == other.id + } + } + impl Eq for Borrowed<'_> {} + impl Hash for Borrowed<'_> { + fn hash(&self, state: &mut H) { + self.id.hash(state); + } + } + impl history_syntax::KeyHash for Borrowed<'_> { + fn key_hash(&self) -> u64 { + history_syntax::key_hash::hash_via_std(self) + } + } + #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] + struct BorrowedEvent<'a>(Borrowed<'a>); + impl<'a> Event for BorrowedEvent<'a> { + type Component = Component3, u8, u8>; + type Arity = N3; + fn component(self, index: usize) -> Self::Component { + match index { + 0 => Component3::C0(self.0), + 1 => Component3::C1(1), + _ => Component3::C2(2), + } + } + fn coordinate(component: Self::Component) -> usize { + match component { + Component3::C0(_) => 0, + Component3::C1(_) => 1, + Component3::C2(_) => 2, + } + } + } + let cell = Cell::new(3); + let event = BorrowedEvent(Borrowed { id: 9, cell: &cell }); + let store = alloc::sync::Arc::new(Store::new().unwrap()); + let mut history = crate::history::History::from_events(store, [event]).unwrap(); + history.push(event).unwrap(); + cell.set(4); + assert_eq!(history.len(), 2); + assert!(history.iter().all(|event| event.0.cell.get() == 4)); + let numeric = history.numeric().as_slice(); + assert_eq!(numeric[0], numeric[1]); + } + + #[test] + fn failed_map_reservation_keeps_existing_associations() { + let mut book = Codebook::new(); + let first = Key { + identity: 7, + payload: 1, + }; + let other = Key { + identity: 8, + payload: 2, + }; + let numeric = HistoryStore::new(3); + let id = book + .intern(&first, 2, "component", &numeric, Ghost::assume_new()) + .unwrap(); + let _failure = junco_core::observation::fail_reservations_after(0); + assert!(matches!( + book.intern(&other, 2, "component", &numeric, Ghost::assume_new()), + Err(HistoryError::AllocationFailed) + )); + assert_eq!(book.last, id); + assert_eq!( + book.intern(&first, 2, "component", &numeric, Ghost::assume_new()) + .unwrap(), + id + ); + assert_eq!(book.values.lookup(&other), None); + } + + #[cfg(feature = "std")] + #[test] + fn component_hash_unwind_releases_the_store_lock() { + #[derive(Copy, Clone, Debug, Eq, PartialEq)] + struct PanickingKey(u8); + impl Hash for PanickingKey { + fn hash(&self, state: &mut H) { + assert_ne!(self.0, 8, "deliberate component hash failure"); + self.0.hash(state); + } + } + impl history_syntax::KeyHash for PanickingKey { + fn key_hash(&self) -> u64 { + history_syntax::key_hash::hash_via_std(self) + } + } + #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] + struct PanicEvent(PanickingKey); + impl Event for PanicEvent { + type Component = Component3; + type Arity = N3; + fn component(self, index: usize) -> Self::Component { + match index { + 0 => Component3::C0(self.0), + 1 => Component3::C1(()), + _ => Component3::C2(()), + } + } + fn coordinate(component: Self::Component) -> usize { + match component { + Component3::C0(_) => 0, + Component3::C1(_) => 1, + Component3::C2(_) => 2, + } + } + } + let store = Store::::new().unwrap(); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + store.encode_event(&PanicEvent(PanickingKey(8))) + })); + assert!(result.is_err()); + assert!(store.books.inner.try_lock().is_some()); + assert!(store.encode_event(&PanicEvent(PanickingKey(7))).is_ok()); + } + + #[test] + fn every_supported_arity_retains_scoped_shared_authorities() { + let mut previous = [0; MAX_ARITY]; + macro_rules! check { + ($arity:ty) => {{ + #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] + struct SizedEvent([u8; MAX_ARITY]); + impl Event for SizedEvent { + type Component = (u8, u8); + type Arity = $arity; + fn component(self, index: usize) -> Self::Component { + let index = index.min(Self::Arity::value() - 1); + (index as u8, self.0[index]) + } + fn coordinate(component: Self::Component) -> usize { + component.0 as usize + } + } + let width = <$arity>::value(); + let store = Store::::new().unwrap(); + let other = Store::::new().unwrap(); + assert!(Arc::ptr_eq(store.numeric_store(), other.numeric_store())); + assert_eq!(store.numeric_store().arity(), width); + let event = SizedEvent([17; MAX_ARITY]); + let encoded = store.encode_event(&event).unwrap(); + let distinct = other.encode_event(&event).unwrap(); + assert_eq!(encoded.arity(), width); + assert_eq!(encoded, store.encode_event(&event).unwrap()); + for (index, previous) in previous.iter_mut().enumerate().take(width) { + assert!(*previous < encoded.component(index)); + assert!(encoded.component(index) < distinct.component(index)); + *previous = distinct.component(index); + } + let mut books = store.books.inner.lock(); + assert_eq!(books.components.books.len(), width); + let mut encoder = BorrowedEncoder { + books: &mut books.components, + numeric_store: store.numeric_store(), + #[cfg(verus_keep_ghost)] + calls: Ghost(0nat), + }; + assert_eq!( + encoder + .encode(Component((width - 1) as u8), &((width - 1) as u8, 17)) + .unwrap(), + encoded.component(width - 1) + ); + // Even a malformed native coordinate implementation cannot index past the books. + assert!(matches!( + encoder.encode(Component(width as u8), &(width as u8, 17)), + Err(HistoryError::InvalidPolicy { .. }) + )); + }}; + } + check!(history_syntax::N1); + check!(history_syntax::N2); + check!(history_syntax::N3); + check!(history_syntax::N4); + check!(history_syntax::N5); + check!(history_syntax::N6); + check!(history_syntax::N7); + check!(history_syntax::N8); + } + + #[test] + fn partial_event_allocation_retains_committed_coordinates() { + let store = Store::<(u8, u8, u8, u8)>::new().unwrap(); + let event = (11, 12, 13, 14); + { + let _failure = junco_core::observation::fail_reservations_after(2); + assert!(matches!( + store.encode_event(&event), + Err(HistoryError::AllocationFailed) + )); + } + let first = { + let books = store.books.inner.lock(); + let first = books.components.books[0] + .values + .lookup(&Component4::C0(11)) + .unwrap(); + assert!( + books.components.books[1] + .values + .lookup(&Component4::C1(12)) + .is_some() + ); + assert!( + books.components.books[2] + .values + .lookup(&Component4::C2(13)) + .is_none() + ); + assert!( + books.components.books[3] + .values + .lookup(&Component4::C3(14)) + .is_none() + ); + first + }; + let encoded = store.encode_event(&event).unwrap(); + assert_eq!(encoded.component(0), first); + assert_eq!(encoded, store.encode_event(&event).unwrap()); + } +} diff --git a/src/history-syntax/Cargo.toml b/src/history-syntax/Cargo.toml new file mode 100644 index 000000000..d4d51669d --- /dev/null +++ b/src/history-syntax/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "history-syntax" +description = "Rule syntax and event model for Regorus history rules" +version = "0.1.0" +edition = "2024" +license = "MIT" +repository = "https://github.com/microsoft/regorus" + +[package.metadata.verus] +verify = true + +[features] +default = [] +serde = ["dep:serde"] +std = ["vstd/std"] + +[dependencies] +# Keep aligned with the root crate's vstd pin (.github/workflows/verus.yml). +vstd = { version = "=0.0.0-2026-10-04-0306", default-features = false, features = ["alloc"] } +frunk_core = { version = "=0.5.0", default-features = false } +serde = { version = "1", default-features = false, features = ["derive", "alloc"], optional = true } + +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(verus_keep_ghost)'] } diff --git a/src/history-syntax/src/event.rs b/src/history-syntax/src/event.rs new file mode 100644 index 000000000..683e50574 --- /dev/null +++ b/src/history-syntax/src/event.rs @@ -0,0 +1,495 @@ +//! Compact, statically dispatched events with policy-selected coordinates. + +use core::fmt::Debug; +use core::hash::Hash; +use frunk_core::coproduct::{CNil, Coproduct}; + +use crate::key_hash::{KeyHash, mix}; +use vstd::prelude::*; + +#[cfg(verus_keep_ghost)] +use self::specs::{AritySpec, EventSpec}; + +verus! { +/// Largest arity any event type may declare; sizes inline numeric tuples. +pub const MAX_ARITY: usize = 8; +} + +mod sealed { + #[vstd::prelude::verus_verify] + pub trait Sealed {} +} + +/// Type-level event arity. Only [`N1`] through [`N8`] implement this trait. +pub trait Arity: sealed::Sealed { + /// Number of coordinates, between one and [`MAX_ARITY`] inclusive. + fn value() -> usize; +} + +macro_rules! arities { + ($($name:ident = $value:literal),+ $(,)?) => {$ ( + #[doc = concat!("An event with ", stringify!($value), " coordinates.")] + #[verus_verify] + pub struct $name; + + #[verus_verify] + impl sealed::Sealed for $name {} + + #[verus_verify] + impl Arity for $name { + fn value() -> usize { $value } + } + + #[cfg(verus_keep_ghost)] + verus! { + impl specs::AritySpecImpl for $name { + open spec fn value_spec() -> nat { $value } + } + } + )+}; +} + +arities!( + N1 = 1, + N2 = 2, + N3 = 3, + N4 = 4, + N5 = 5, + N6 = 6, + N7 = 7, + N8 = 8 +); + +/// Event matched by heads and tail atoms. +/// +/// Equality and hashing describe the full event, including its variant and payload. +/// Projections, equality and hashing must remain stable while values are used by a policy. +pub trait Event: Copy + Debug + Eq + Hash { + /// Tagged value of one coordinate, with one variant per coordinate. + type Component: Copy + Debug + Eq + Hash + KeyHash; + /// Number of coordinates in this event. + type Arity: Arity; + + /// Projects coordinate `index`; out-of-range indices map to the last coordinate. + fn component(self, index: usize) -> Self::Component; + /// Returns the coordinate of a tagged value. + /// + /// For every valid `i`, `Self::coordinate(event.component(i)) == i`. + fn coordinate(component: Self::Component) -> usize; +} + +/// Tagged coordinates of a two-component tuple event. +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Component2 { + /// Coordinate zero. + C0(A), + /// Coordinate one. + C1(B), +} + +/// Tagged coordinates of a three-component tuple event. +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Component3 { + /// Coordinate zero. + C0(A), + /// Coordinate one. + C1(B), + /// Coordinate two. + C2(C), +} + +/// Tagged coordinates of a four-component tuple event. +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Component4 { + /// Coordinate zero. + C0(A), + /// Coordinate one. + C1(B), + /// Coordinate two. + C2(C), + /// Coordinate three. + C3(D), +} + +#[verus_verify] +impl Event for (A, B) +where + (A, B): Copy, +{ + type Component = Component2; + type Arity = N2; + + fn component(self, index: usize) -> Self::Component { + match index { + 0 => Component2::C0(self.0), + _ => Component2::C1(self.1), + } + } + + fn coordinate(component: Self::Component) -> usize { + match component { + Component2::C0(_) => 0, + Component2::C1(_) => 1, + } + } +} + +#[verus_verify] +impl< + A: Copy + Debug + Eq + Hash + KeyHash, + B: Copy + Debug + Eq + Hash + KeyHash, + C: Copy + Debug + Eq + Hash + KeyHash, +> Event for (A, B, C) +where + (A, B, C): Copy, +{ + type Component = Component3; + type Arity = N3; + + fn component(self, index: usize) -> Self::Component { + match index { + 0 => Component3::C0(self.0), + 1 => Component3::C1(self.1), + _ => Component3::C2(self.2), + } + } + + fn coordinate(component: Self::Component) -> usize { + match component { + Component3::C0(_) => 0, + Component3::C1(_) => 1, + Component3::C2(_) => 2, + } + } +} + +#[verus_verify] +impl< + A: Copy + Debug + Eq + Hash + KeyHash, + B: Copy + Debug + Eq + Hash + KeyHash, + C: Copy + Debug + Eq + Hash + KeyHash, + D: Copy + Debug + Eq + Hash + KeyHash, +> Event for (A, B, C, D) +where + (A, B, C, D): Copy, +{ + type Component = Component4; + type Arity = N4; + + fn component(self, index: usize) -> Self::Component { + match index { + 0 => Component4::C0(self.0), + 1 => Component4::C1(self.1), + 2 => Component4::C2(self.2), + _ => Component4::C3(self.3), + } + } + + fn coordinate(component: Self::Component) -> usize { + match component { + Component4::C0(_) => 0, + Component4::C1(_) => 1, + Component4::C2(_) => 2, + Component4::C3(_) => 3, + } + } +} + +#[verus_verify] +impl KeyHash for Component2 { + fn key_hash(&self) -> u64 { + match self { + Component2::C0(a) => mix(0, a.key_hash()), + Component2::C1(b) => mix(1, b.key_hash()), + } + } +} + +#[verus_verify] +impl KeyHash for Component3 { + fn key_hash(&self) -> u64 { + match self { + Component3::C0(a) => mix(0, a.key_hash()), + Component3::C1(b) => mix(1, b.key_hash()), + Component3::C2(c) => mix(2, c.key_hash()), + } + } +} + +#[verus_verify] +impl KeyHash for Component4 { + fn key_hash(&self) -> u64 { + match self { + Component4::C0(a) => mix(0, a.key_hash()), + Component4::C1(b) => mix(1, b.key_hash()), + Component4::C2(c) => mix(2, c.key_hash()), + Component4::C3(d) => mix(3, d.key_hash()), + } + } +} + +// The pinned verifier rejects zero-arm matches; this leaf eliminates only Frunk's empty CNil. +#[verus_verify] +#[verus_verify(external_body)] +#[verus_spec(result => ensures false)] +fn absurd_nil(nil: CNil) -> T { + match nil {} +} + +/// Final variant of a Frunk event union. +#[verus_verify] +impl Event for Coproduct { + type Component = H::Component; + type Arity = H::Arity; + + fn component(self, index: usize) -> Self::Component { + match self { + Coproduct::Inl(head) => head.component(index), + Coproduct::Inr(nil) => absurd_nil(nil), + } + } + + fn coordinate(component: Self::Component) -> usize { + H::coordinate(component) + } +} + +/// Head variant of a Frunk event union sharing tagged coordinates and arity. +#[verus_verify] +impl Event for Coproduct> +where + H: Event, + Coproduct: Event, +{ + type Component = H::Component; + type Arity = H::Arity; + + fn component(self, index: usize) -> Self::Component { + match self { + Coproduct::Inl(head) => head.component(index), + Coproduct::Inr(tail) => tail.component(index), + } + } + + fn coordinate(component: Self::Component) -> usize { + H::coordinate(component) + } +} + +/// Conditional native projection boundary; implementations need not opt in. +#[cfg(verus_keep_ghost)] +pub mod specs { + use super::*; + use crate::key_hash::specs::{KeyHashSpec, KeyHashSpecImpl, spec_mix}; + use vstd::std_specs::cmp::{PartialEqSpec, PartialEqSpecImpl}; + verus! { + + #[verifier::external_trait_specification] + #[verifier::external_trait_extension(AritySpec via AritySpecImpl)] + pub trait ExArity: sealed::Sealed { + type ExternalTraitSpecificationFor: Arity; + spec fn value_spec() -> nat; + fn value() -> (result: usize) + ensures 1 <= result <= MAX_ARITY, result == Self::value_spec(); + } + + // Transparent specifications expose exactly the Frunk enum variants to body proofs. + #[verifier::external_type_specification] + #[verifier::accept_recursive_types(H)] + #[verifier::reject_recursive_types_in_ground_variants(T)] + pub struct ExCoproduct(Coproduct); + + #[verifier::external_type_specification] + // Like vstd's Infallible: the pinned verifier cannot represent a zero-variant datatype. + #[verifier::external_body] + pub struct ExCNil(CNil); + + #[verifier::external_trait_specification] + #[verifier::external_trait_extension(EventSpec via EventSpecImpl)] + pub trait ExEvent: Copy + Debug + Eq + Hash { + type ExternalTraitSpecificationFor: Event; + type Component: Copy + Debug + Eq + Hash + KeyHash; + type Arity: Arity; + + spec fn obeys_projection_spec() -> bool; + spec fn component_spec(self, index: int) -> Self::Component; + spec fn coordinate_spec(component: Self::Component) -> nat; + + fn component(self, index: usize) -> (result: Self::Component) + ensures Self::obeys_projection_spec() ==> result == self.component_spec(index as int); + fn coordinate(component: Self::Component) -> (result: usize) + ensures Self::obeys_projection_spec() ==> + result as nat == Self::coordinate_spec(component) + && result < Self::Arity::value_spec(); + } + + impl EventSpecImpl for (A, B) + where (A, B): Copy, + { + open spec fn obeys_projection_spec() -> bool { true } + open spec fn component_spec(self, index: int) -> Self::Component { + if index == 0 { Component2::C0(self.0) } else { Component2::C1(self.1) } + } + open spec fn coordinate_spec(component: Self::Component) -> nat { + match component { Component2::C0(_) => 0, Component2::C1(_) => 1 } + } + } + + impl EventSpecImpl for (A, B, C) + where (A, B, C): Copy, + { + open spec fn obeys_projection_spec() -> bool { true } + open spec fn component_spec(self, index: int) -> Self::Component { + if index == 0 { Component3::C0(self.0) } + else if index == 1 { Component3::C1(self.1) } + else { Component3::C2(self.2) } + } + open spec fn coordinate_spec(component: Self::Component) -> nat { + match component { Component3::C0(_) => 0, Component3::C1(_) => 1, Component3::C2(_) => 2 } + } + } + + impl EventSpecImpl for (A, B, C, D) + where (A, B, C, D): Copy, + { + open spec fn obeys_projection_spec() -> bool { true } + open spec fn component_spec(self, index: int) -> Self::Component { + if index == 0 { Component4::C0(self.0) } + else if index == 1 { Component4::C1(self.1) } + else if index == 2 { Component4::C2(self.2) } + else { Component4::C3(self.3) } + } + open spec fn coordinate_spec(component: Self::Component) -> nat { + match component { + Component4::C0(_) => 0, Component4::C1(_) => 1, + Component4::C2(_) => 2, Component4::C3(_) => 3, + } + } + } + + /// `eq_spec` of a tagged component: same coordinate and payloads `eq_spec`-equal; the derived + /// `PartialEq` compares the variant and then the payload, so it is faithful when the payloads' are. + impl PartialEqSpecImpl for Component2 { + open spec fn obeys_eq_spec() -> bool { A::obeys_eq_spec() && B::obeys_eq_spec() } + open spec fn eq_spec(&self, other: &Self) -> bool { + match (self, other) { + (Component2::C0(a), Component2::C0(b)) => a.eq_spec(b), + (Component2::C1(a), Component2::C1(b)) => a.eq_spec(b), + _ => false, + } + } + } + + impl + PartialEqSpecImpl for Component3 + { + open spec fn obeys_eq_spec() -> bool { + A::obeys_eq_spec() && B::obeys_eq_spec() && C::obeys_eq_spec() + } + open spec fn eq_spec(&self, other: &Self) -> bool { + match (self, other) { + (Component3::C0(a), Component3::C0(b)) => a.eq_spec(b), + (Component3::C1(a), Component3::C1(b)) => a.eq_spec(b), + (Component3::C2(a), Component3::C2(b)) => a.eq_spec(b), + _ => false, + } + } + } + + impl PartialEqSpecImpl for Component4 + { + open spec fn obeys_eq_spec() -> bool { + A::obeys_eq_spec() && B::obeys_eq_spec() && C::obeys_eq_spec() && D::obeys_eq_spec() + } + open spec fn eq_spec(&self, other: &Self) -> bool { + match (self, other) { + (Component4::C0(a), Component4::C0(b)) => a.eq_spec(b), + (Component4::C1(a), Component4::C1(b)) => a.eq_spec(b), + (Component4::C2(a), Component4::C2(b)) => a.eq_spec(b), + (Component4::C3(a), Component4::C3(b)) => a.eq_spec(b), + _ => false, + } + } + } + + /// `hash_spec` of a tagged component mixes the coordinate tag with the payload's `hash_spec`. + impl KeyHashSpecImpl for Component2 { + open spec fn obeys_hash_spec() -> bool { A::obeys_hash_spec() && B::obeys_hash_spec() } + open spec fn hash_spec(&self) -> u64 { + match self { + Component2::C0(a) => spec_mix(0, a.hash_spec()), + Component2::C1(b) => spec_mix(1, b.hash_spec()), + } + } + } + + impl KeyHashSpecImpl for Component3 { + open spec fn obeys_hash_spec() -> bool { + A::obeys_hash_spec() && B::obeys_hash_spec() && C::obeys_hash_spec() + } + open spec fn hash_spec(&self) -> u64 { + match self { + Component3::C0(a) => spec_mix(0, a.hash_spec()), + Component3::C1(b) => spec_mix(1, b.hash_spec()), + Component3::C2(c) => spec_mix(2, c.hash_spec()), + } + } + } + + impl KeyHashSpecImpl for Component4 { + open spec fn obeys_hash_spec() -> bool { + A::obeys_hash_spec() && B::obeys_hash_spec() && C::obeys_hash_spec() && D::obeys_hash_spec() + } + open spec fn hash_spec(&self) -> u64 { + match self { + Component4::C0(a) => spec_mix(0, a.hash_spec()), + Component4::C1(b) => spec_mix(1, b.hash_spec()), + Component4::C2(c) => spec_mix(2, c.hash_spec()), + Component4::C3(d) => spec_mix(3, d.hash_spec()), + } + } + } + + impl EventSpecImpl for Coproduct { + open spec fn obeys_projection_spec() -> bool { H::obeys_projection_spec() } + // CNil has no values; projecting through an arbitrary `H` keeps `H`'s projection laws. + open spec fn component_spec(self, index: int) -> Self::Component { + match self { + Coproduct::Inl(head) => head.component_spec(index), + Coproduct::Inr(_) => arbitrary::().component_spec(index), + } + } + open spec fn coordinate_spec(component: Self::Component) -> nat { + H::coordinate_spec(component) + } + } + + impl EventSpecImpl for Coproduct> + where + H: Event, + Coproduct: Event, + { + open spec fn obeys_projection_spec() -> bool { + H::obeys_projection_spec() && as EventSpec>::obeys_projection_spec() + } + open spec fn component_spec(self, index: int) -> Self::Component { + match self { + Coproduct::Inl(head) => head.component_spec(index), + Coproduct::Inr(tail) => tail.component_spec(index), + } + } + open spec fn coordinate_spec(component: Self::Component) -> nat { + H::coordinate_spec(component) + } + } + } +} diff --git a/src/history-syntax/src/key_hash.rs b/src/history-syntax/src/key_hash.rs new file mode 100644 index 000000000..818e613b5 --- /dev/null +++ b/src/history-syntax/src/key_hash.rs @@ -0,0 +1,122 @@ +//! Verified key hashing: `key_hash` is fixed by the spec function `hash_spec`, so a hash table +//! keyed by it is a map on `eq_spec` classes by proof (`junco_core::spec::hypotheses::hash_respects_eq`), +//! never by assumption about `std::hash::Hash`. + +use vstd::prelude::*; + +/// Hash of a table key. +/// +/// Verified impls return `hash_spec(self)`; unverified types use [`hash_via_std`]. +pub trait KeyHash { + /// The key's 64-bit hash. + fn key_hash(&self) -> u64; +} + +/// FNV-1a 64 over `Hash::hash`; for unverified glue types only. +pub fn hash_via_std(value: &T) -> u64 { + struct Fnv1a(u64); + impl core::hash::Hasher for Fnv1a { + fn finish(&self) -> u64 { + self.0 + } + fn write(&mut self, bytes: &[u8]) { + for byte in bytes { + self.0 = (self.0 ^ u64::from(*byte)).wrapping_mul(0x100000001b3); + } + } + } + let mut hasher = Fnv1a(0xcbf29ce484222325); + value.hash(&mut hasher); + hasher.0 +} + +/// One FNV-1a combining step. +#[verus_verify] +#[verus_spec(r => ensures r == specs::spec_mix(h, x))] +pub fn mix(h: u64, x: u64) -> u64 { + (h ^ x).wrapping_mul(0x100000001b3) +} + +#[verus_verify] +impl KeyHash for () { + fn key_hash(&self) -> u64 { + 0 + } +} + +#[verus_verify] +impl KeyHash for bool { + fn key_hash(&self) -> u64 { + if *self { 1 } else { 0 } + } +} + +macro_rules! unsigned_key_hash { + ($($t:ty),+) => {$( + #[verus_verify] + impl KeyHash for $t { + fn key_hash(&self) -> u64 { + *self as u64 + } + } + #[cfg(verus_keep_ghost)] + verus! { + impl specs::KeyHashSpecImpl for $t { + open spec fn obeys_hash_spec() -> bool { true } + open spec fn hash_spec(&self) -> u64 { *self as u64 } + } + } + )+}; +} + +unsigned_key_hash!(u8, u16, u32, u64, usize); + +#[verus_verify] +impl KeyHash for (A, B) { + fn key_hash(&self) -> u64 { + mix(self.0.key_hash(), self.1.key_hash()) + } +} + +/// Spec bridge: `hash_spec` names the hash a verified impl returns. +#[cfg(verus_keep_ghost)] +pub mod specs { + use super::*; + use vstd::wrapping::u64_specs; + + verus! { + + /// The step `mix` computes. + pub open spec fn spec_mix(h: u64, x: u64) -> u64 { + u64_specs::wrapping_mul(h ^ x, 0x100000001b3) + } + + #[verifier::external_trait_specification] + #[verifier::external_trait_extension(KeyHashSpec via KeyHashSpecImpl)] + pub trait ExKeyHash { + type ExternalTraitSpecificationFor: KeyHash; + + spec fn obeys_hash_spec() -> bool; + spec fn hash_spec(&self) -> u64; + + fn key_hash(&self) -> (h: u64) + ensures Self::obeys_hash_spec() ==> h == self.hash_spec(); + } + + impl KeyHashSpecImpl for () { + open spec fn obeys_hash_spec() -> bool { true } + open spec fn hash_spec(&self) -> u64 { 0 } + } + + impl KeyHashSpecImpl for bool { + open spec fn obeys_hash_spec() -> bool { true } + open spec fn hash_spec(&self) -> u64 { if *self { 1u64 } else { 0u64 } } + } + + impl KeyHashSpecImpl for (A, B) { + open spec fn obeys_hash_spec() -> bool { A::obeys_hash_spec() && B::obeys_hash_spec() } + open spec fn hash_spec(&self) -> u64 { spec_mix(self.0.hash_spec(), self.1.hash_spec()) } + } + + } // verus! +} diff --git a/src/history-syntax/src/lib.rs b/src/history-syntax/src/lib.rs new file mode 100644 index 000000000..c824866fe --- /dev/null +++ b/src/history-syntax/src/lib.rs @@ -0,0 +1,27 @@ +#![no_std] +// Verus generates erased unsafe scaffolding for native specifications. +#![cfg_attr(not(verus_keep_ghost), forbid(unsafe_code))] +#![cfg_attr(verus_keep_ghost, feature(proc_macro_hygiene, allocator_api))] +#![cfg_attr(docsrs, feature(doc_cfg))] + +extern crate alloc; +#[cfg(any(feature = "std", test))] +extern crate std; + +pub mod event; +pub mod key_hash; +#[cfg(verus_keep_ghost)] +pub mod spec; +pub mod syntax; +#[cfg(verus_keep_ghost)] +pub mod verify; + +pub use event::{ + Arity, Component2, Component3, Component4, Event, MAX_ARITY, N1, N2, N3, N4, N5, N6, N7, N8, +}; +pub use frunk_core::Coprod; +pub use frunk_core::coproduct::{CNil, Coproduct}; +pub use key_hash::KeyHash; +pub use syntax::{ + AtomPattern, Comparison, Component, ComponentPattern, Head, RegexExpr, Rule, RuleMode, TestExpr, +}; diff --git a/src/history-syntax/src/spec/events.rs b/src/history-syntax/src/spec/events.rs new file mode 100644 index 000000000..2634ceaf8 --- /dev/null +++ b/src/history-syntax/src/spec/events.rs @@ -0,0 +1,162 @@ +//! Events as tagged component tuples, and the views of the owned DSL (paper: `sec:events`, +//! `sec:rules`). + +use crate::event::specs::{AritySpec, EventSpec}; +use crate::syntax::{ + AtomPattern, Comparison, ComponentPattern, Head, RegexExpr, Rule, RuleMode, TestExpr, +}; +use crate::{Event, MAX_ARITY}; +use alloc::boxed::Box; +use vstd::prelude::*; + +verus! { + +broadcast use {vstd::std_specs::vec::group_vec_axioms, vstd::seq::group_seq_lemmas}; + +/// The number of coordinates of an event type (paper: product events, `sec:events`). +pub open spec fn arity() -> nat { E::Arity::value_spec() } + +/// Every projection of an event carries its own coordinate as tag (`sec:events`). +pub open spec fn projection_laws() -> bool { + forall|e: E, i: int| 0 <= i < arity::() ==> + E::coordinate_spec(e.component_spec(i)) == i +} + +/// An event as the tuple of its tagged components, coordinate by coordinate (`sec:events`). +pub open spec fn event_view(e: E) -> Seq { + Seq::new(arity::(), |i: int| e.component_spec(i)) +} + +/// `xs` has the shape of an event: arity-many components, the i-th tagged with coordinate i +/// (paper: product events, `sec:events`). +pub open spec fn well_tagged(xs: Seq) -> bool { + xs.len() == arity::() + && forall|i: int| 0 <= i < xs.len() ==> E::coordinate_spec(#[trigger] xs[i]) == i +} + +/// Every well-tagged tuple is the view of some event; makes the tagged component type +/// equivalent to the paper's product domain (`sec:events`). +pub open spec fn views_surjective() -> bool { + forall|xs: Seq| #[trigger] well_tagged::(xs) ==> exists|e: E| event_view(e) == xs +} + +/// Everything the semantics assumes about an event type's projections (`sec:events`). +pub open spec fn event_laws() -> bool { + &&& 1 <= arity::() <= MAX_ARITY + &&& E::obeys_projection_spec() + &&& projection_laws::() + &&& views_surjective::() +} + +pub enum PatternView { + Constant(T), + Variable(Seq), +} + +pub type HeadView = Seq>; + +pub struct AtomView { + pub component: nat, + pub pattern: PatternView, +} + +pub enum TestView { + True, + False, + Atom { comparison: Comparison, pattern: AtomView }, + And(Seq>), + Or(Seq>), +} + +/// The same algebra as the numeric history model, over concrete component values. +pub enum RegexView { + Empty, All, Epsilon, + Test(TestView), + Union(Seq>), + Concat(Seq>), + Star(Box>), + Intersect(Seq>), + Not(Box>), +} + +pub struct RuleView { + pub mode: RuleMode, + pub head: HeadView, + pub tail: RegexView, +} + +impl View for ComponentPattern { + type V = PatternView; + open spec fn view(&self) -> Self::V { + match self { + ComponentPattern::Constant(value) => PatternView::Constant(*value), + ComponentPattern::Variable(name) => PatternView::Variable(name@), + } + } +} + +impl View for Head { + type V = HeadView; + open spec fn view(&self) -> Self::V { + self.0@.map(|i: int, pattern: ComponentPattern| pattern@) + } +} + +impl View for AtomPattern { + type V = AtomView; + open spec fn view(&self) -> Self::V { + AtomView { component: self.component.0 as nat, pattern: self.pattern@ } + } +} + +pub open spec fn test_view(test: TestExpr) -> TestView + decreases test, +{ + match test { + TestExpr::True => TestView::True, + TestExpr::False => TestView::False, + TestExpr::Atom { comparison, pattern } => TestView::Atom { comparison, pattern: pattern@ }, + TestExpr::And(children) => TestView::And(Seq::new(children@.len(), |i: int| + if 0 <= i < children@.len() { test_view(children@[i]) } else { TestView::False })), + TestExpr::Or(children) => TestView::Or(Seq::new(children@.len(), |i: int| + if 0 <= i < children@.len() { test_view(children@[i]) } else { TestView::False })), + } +} + +impl View for TestExpr { + type V = TestView; + open spec fn view(&self) -> Self::V { test_view(*self) } +} + +pub open spec fn regex_view(regex: RegexExpr) -> RegexView + decreases regex, +{ + match regex { + RegexExpr::Empty => RegexView::Empty, + RegexExpr::All => RegexView::All, + RegexExpr::Epsilon => RegexView::Epsilon, + RegexExpr::Test(test) => RegexView::Test(test_view(test)), + RegexExpr::Union(children) => RegexView::Union(Seq::new(children@.len(), |i: int| + if 0 <= i < children@.len() { regex_view(children@[i]) } else { RegexView::Empty })), + RegexExpr::Concat(children) => RegexView::Concat(Seq::new(children@.len(), |i: int| + if 0 <= i < children@.len() { regex_view(children@[i]) } else { RegexView::Empty })), + RegexExpr::Star(child) => RegexView::Star(Box::new(regex_view(*child))), + RegexExpr::Intersect(children) => RegexView::Intersect(Seq::new(children@.len(), |i: int| + if 0 <= i < children@.len() { regex_view(children@[i]) } else { RegexView::Empty })), + RegexExpr::Not(child) => RegexView::Not(Box::new(regex_view(*child))), + } +} + +impl View for RegexExpr { + type V = RegexView; + open spec fn view(&self) -> Self::V { regex_view(*self) } +} + +impl View for Rule { + type V = RuleView; + open spec fn view(&self) -> Self::V { + RuleView { mode: self.mode, head: self.head@, tail: self.tail@ } + } +} + +} // verus! diff --git a/src/history-syntax/src/spec/mod.rs b/src/history-syntax/src/spec/mod.rs new file mode 100644 index 000000000..0c44fff8e --- /dev/null +++ b/src/history-syntax/src/spec/mod.rs @@ -0,0 +1,3 @@ +//! Reviewer-facing specifications of this crate: what an event is and how the owned DSL is viewed. + +pub mod events; diff --git a/src/history-syntax/src/syntax.rs b/src/history-syntax/src/syntax.rs new file mode 100644 index 000000000..0fd2d7d38 --- /dev/null +++ b/src/history-syntax/src/syntax.rs @@ -0,0 +1,418 @@ +//! Owned source language for declarative policy rules over one [`Event`] type. +//! +//! Constants retain the event's tagged component type. Variables are local names; +//! source expressions contain no arena references, compiler identities or store backreferences. + +use crate::event::{Event, MAX_ARITY}; +use alloc::boxed::Box; +use alloc::string::String; +use alloc::vec::Vec; +use core::iter::FromIterator; +use vstd::prelude::*; + +#[cfg(verus_keep_ghost)] +use crate::verify::dsl::{ + lemma_regex_forest_append, lemma_test_forest_append, regex_forest_nodes, regex_nodes, + test_forest_nodes, test_nodes, +}; +#[cfg(verus_keep_ghost)] +use vstd::std_specs::convert::IntoSpec; +#[cfg(verus_keep_ghost)] +use vstd::std_specs::iter::into_iter_remaining; + +/// Constant-or-variable pattern for one statically selected product component. +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum ComponentPattern { + /// Match one equal component value, using the component's equality relation. + Constant(T), + /// Bind or resolve a named component value. + Variable(Variable), +} + +#[verus_verify] +impl ComponentPattern { + /// Creates a constant pattern from a value convertible to `T`. + #[verus_spec(result => ensures + result is Constant, + I::obeys_into_spec() ==> result == Self::Constant(value.into_spec()), + )] + pub fn constant>(value: I) -> Self { + Self::Constant(value.into()) + } + + /// Creates a named variable pattern. + #[verus_spec(result => ensures + result is Variable, + I::obeys_into_spec() ==> result == Self::Variable(name.into_spec()), + )] + pub fn variable>(name: I) -> Self { + Self::Variable(name.into()) + } +} + +/// Candidate-only pattern over the event coordinates. +/// Variables declared here may be resolved only in the same tail coordinate. +/// The compiler checks that the number of slots equals the event type's arity. +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Head(pub Vec>); + +#[verus_verify] +impl Head { + /// Creates a head in coordinate order. + #[verus_spec(result => ensures result.0@ == into_iter_remaining(slots))] + pub fn new>>(slots: I) -> Self { + Self(Vec::from_iter(slots)) + } + + /// Patterns in coordinate order. + #[verus_spec(result => ensures result@ == self.0@)] + pub fn slots(&self) -> &[ComponentPattern] { + self.0.as_slice() + } +} + +/// Coordinate of the event tuple; order is part of the portable format. +#[verus_verify] +#[verus_verify(external_derive)] +#[cfg_attr(verus_keep_ghost, derive(Structural))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Component(pub u8); + +#[verus_verify] +impl Component { + /// Returns the coordinate's position in a portable head. + #[verus_spec(result => ensures result == self.0 as usize)] + pub const fn index(self) -> usize { + self.0 as usize + } + + /// Creates a coordinate index, panicking if it exceeds the supported arity. + #[verus_spec(result => requires index < MAX_ARITY, ensures result.0 == index)] + pub const fn new(index: usize) -> Self { + assert!(index < MAX_ARITY); + Self(index as u8) + } +} + +/// Comparison applied by a one-event atom. +#[verus_verify] +#[verus_verify(external_derive)] +#[cfg_attr(verus_keep_ghost, derive(Structural))] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Comparison { + /// Accept equal component values. + Eq, + /// Accept unequal component values. + Neq, +} + +#[verus_verify] +impl core::ops::Not for Comparison { + type Output = Self; + + #[verus_spec(result => ensures result == match self { + Self::Eq => Self::Neq, Self::Neq => Self::Eq, + })] + fn not(self) -> Self::Output { + match self { + Self::Eq => Self::Neq, + Self::Neq => Self::Eq, + } + } +} + +/// Owned one-event component pattern. +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct AtomPattern { + /// Coordinate selected by this atom. + pub component: Component, + /// Constant or head-bound variable to compare. + pub pattern: ComponentPattern, +} + +#[verus_verify] +impl AtomPattern { + /// Creates a pattern over a selected coordinate. + #[verus_spec(result => ensures result.component == component, result.pattern == pattern)] + pub fn new(component: Component, pattern: ComponentPattern) -> Self { + Self { component, pattern } + } + + /// Returns the coordinate selected by this atom. + #[verus_spec(result => ensures result == self.component)] + pub fn component(&self) -> Component { + self.component + } +} + +/// Owned boolean expression over one history event. +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum TestExpr { + /// Predicate accepting every event. + True, + /// Predicate accepting no event. + False, + /// Component equality or disequality predicate. + Atom { + /// Comparison applied after resolving the component pattern. + comparison: Comparison, + /// Typed component pattern. + pattern: AtomPattern, + }, + /// Conjunction. Empty input is true. + And(Vec>), + /// Disjunction. Empty input is false. + Or(Vec>), +} + +#[verus_verify] +impl TestExpr { + /// Returns the predicate accepting every event. + #[verus_spec(result => ensures result is True)] + pub const fn true_test() -> Self { + Self::True + } + + /// Returns the predicate accepting no event. + #[verus_spec(result => ensures result is False)] + pub const fn false_test() -> Self { + Self::False + } + + /// Creates a component equality or disequality predicate. + #[verus_spec(result => ensures result == (Self::Atom { comparison, pattern }))] + pub fn atom(comparison: Comparison, pattern: AtomPattern) -> Self { + Self::Atom { + comparison, + pattern, + } + } + + /// Conjoins source predicates in iterator order. + #[verus_spec(result => ensures match result { + Self::And(children) => children@ == into_iter_remaining(tests), _ => false, + })] + pub fn and>>(tests: I) -> Self { + Self::And(Vec::from_iter(tests)) + } + + /// Disjoins source predicates in iterator order. + #[verus_spec(result => ensures match result { + Self::Or(children) => children@ == into_iter_remaining(tests), _ => false, + })] + pub fn or>>(tests: I) -> Self { + Self::Or(Vec::from_iter(tests)) + } +} + +/// Owned regular expression over complete event histories. +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum RegexExpr { + /// Empty language. + Empty, + /// Universal language over complete histories. + All, + /// Language containing only the empty history. + Epsilon, + /// One-event language selected by a boolean source expression. + Test(TestExpr), + /// Set union. Empty input is the empty language. + Union(Vec>), + /// Ordered language concatenation. Empty input is epsilon. + Concat(Vec>), + /// Kleene star. + Star(Box>), + /// Set intersection. Empty input is the universal language. + Intersect(Vec>), + /// Whole-language complement, not a one-event negation. + Not(Box>), +} + +#[verus_verify] +impl RegexExpr { + /// Returns the empty language. + #[verus_spec(result => ensures result is Empty)] + pub const fn empty() -> Self { + Self::Empty + } + + /// Returns the universal language. + #[verus_spec(result => ensures result is All)] + pub const fn all() -> Self { + Self::All + } + + /// Returns the language containing only the empty history. + #[verus_spec(result => ensures result is Epsilon)] + pub const fn epsilon() -> Self { + Self::Epsilon + } + + /// Lifts a one-event predicate into a one-event language. + #[verus_spec(result => ensures result == Self::Test(test))] + pub fn test(test: TestExpr) -> Self { + Self::Test(test) + } + + /// Constructs set union in iterator order. + #[verus_spec(result => ensures match result { + Self::Union(children) => children@ == into_iter_remaining(regexes), _ => false, + })] + pub fn union>>(regexes: I) -> Self { + Self::Union(Vec::from_iter(regexes)) + } + + /// Constructs ordered language concatenation. + #[verus_spec(result => ensures match result { + Self::Concat(children) => children@ == into_iter_remaining(regexes), _ => false, + })] + pub fn concat>>(regexes: I) -> Self { + Self::Concat(Vec::from_iter(regexes)) + } + + /// Constructs Kleene star. + #[verus_spec(result => ensures result == Self::Star(Box::new(regex)))] + pub fn star(regex: RegexExpr) -> Self { + Self::Star(Box::new(regex)) + } + + /// Constructs set intersection in iterator order. + #[verus_spec(result => ensures match result { + Self::Intersect(children) => children@ == into_iter_remaining(regexes), _ => false, + })] + pub fn intersect>>(regexes: I) -> Self { + Self::Intersect(Vec::from_iter(regexes)) + } + + /// Constructs whole-language complement. + #[verus_spec(result => ensures result == Self::Not(Box::new(regex)))] + pub fn complement(regex: RegexExpr) -> Self { + Self::Not(Box::new(regex)) + } +} + +/// Relationship required between committed history and a matching rule tail. +#[verus_verify] +#[verus_verify(external_derive)] +#[cfg_attr(verus_keep_ghost, derive(Structural))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum RuleMode { + /// Deny when committed history is outside the tail language. + Require, + /// Deny when committed history is inside the tail language. + Forbid, +} + +/// Complete owned source rule. +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub struct Rule { + /// Required or forbidden relationship to the tail language. + pub mode: RuleMode, + /// Candidate-only pattern declaring the rule's variables. + pub head: Head, + /// Complete-history language evaluated under candidate bindings. + pub tail: RegexExpr, +} + +#[verus_verify] +impl Rule { + /// Creates a declarative rule with no compiler or validator backreferences. + #[verus_spec(result => ensures result.mode == mode, result.head == head, result.tail == tail)] + pub fn new(mode: RuleMode, head: Head, tail: RegexExpr) -> Self { + Self { mode, head, tail } + } + + /// Releases an owned rule without recursively dropping its expression tree. + pub fn dispose(self) { + let Self { + mode: _, + head: _, + tail, + } = self; + let mut regexes = Vec::new(); + let mut tests = Vec::new(); + regexes.push(tail); + #[cfg_attr(verus_keep_ghost, verus_spec(decreases regex_forest_nodes(regexes@)))] + while !regexes.is_empty() { + proof_decl! { let ghost pending_before = regexes@; } + proof! { reveal_with_fuel(regex_forest_nodes, 2); reveal(regex_nodes); } + if let Some(regex) = regexes.pop() { + proof! { + assert(pending_before =~= regexes@.push(regex)); + assert(regex_forest_nodes(pending_before) + == regex_forest_nodes(regexes@) + regex_nodes(regex)); + } + match regex { + RegexExpr::Union(mut children) + | RegexExpr::Concat(mut children) + | RegexExpr::Intersect(mut children) => { + proof! { lemma_regex_forest_append(regexes@, children@); } + regexes.append(&mut children); + proof! { assert(regex_forest_nodes(regexes@) < regex_forest_nodes(pending_before)); } + } + RegexExpr::Star(child) | RegexExpr::Not(child) => { + proof_decl! { let ghost prefix = regexes@; let ghost next = *child; } + proof! { lemma_regex_forest_append(regexes@, seq![*child]); } + regexes.push(*child); + proof! { + assert(regexes@ =~= prefix + seq![next]); + assert(regex_forest_nodes(regexes@) == regex_forest_nodes(prefix) + regex_nodes(next)); + assert(regex_forest_nodes(regexes@) < regex_forest_nodes(pending_before)); + } + } + RegexExpr::Test(test) => { + tests.push(test); + proof! { assert(regex_forest_nodes(regexes@) < regex_forest_nodes(pending_before)); } + } + RegexExpr::Empty | RegexExpr::All | RegexExpr::Epsilon => { + proof! { assert(regex_forest_nodes(regexes@) < regex_forest_nodes(pending_before)); } + } + } + } + } + #[cfg_attr(verus_keep_ghost, verus_spec(decreases test_forest_nodes(tests@)))] + while !tests.is_empty() { + proof_decl! { let ghost pending_before = tests@; } + proof! { reveal_with_fuel(test_forest_nodes, 2); reveal(test_nodes); } + if let Some(test) = tests.pop() { + proof! { + assert(pending_before =~= tests@.push(test)); + assert(test_forest_nodes(pending_before) + == test_forest_nodes(tests@) + test_nodes(test)); + } + match test { + TestExpr::And(mut children) | TestExpr::Or(mut children) => { + proof! { lemma_test_forest_append(tests@, children@); } + tests.append(&mut children); + } + TestExpr::True | TestExpr::False | TestExpr::Atom { .. } => {} + } + } + } + } +} + +#[cfg(verus_keep_ghost)] +verus! { +impl vstd::std_specs::ops::NotSpecImpl for Comparison { + open spec fn obeys_not_spec() -> bool { true } + open spec fn not_req(self) -> bool { true } + open spec fn not_spec(self) -> Self { + match self { Self::Eq => Self::Neq, Self::Neq => Self::Eq } + } +} +} diff --git a/src/history-syntax/src/verify/dsl.rs b/src/history-syntax/src/verify/dsl.rs new file mode 100644 index 000000000..30db9579d --- /dev/null +++ b/src/history-syntax/src/verify/dsl.rs @@ -0,0 +1,91 @@ +//! Node counters and constructor/disposal proofs for the owned DSL; the views live in +//! `crate::spec::events`. + +use crate::Event; +use crate::spec::events::{RegexView, regex_view}; +use crate::syntax::{ComponentPattern, Head, RegexExpr, Rule, RuleMode, TestExpr}; +use alloc::boxed::Box; +use vstd::prelude::*; + +verus! { + +broadcast use {vstd::std_specs::vec::group_vec_axioms, vstd::seq::group_seq_lemmas}; + + +/// Remaining source nodes, used to prove that iterative disposal terminates. +pub open spec fn test_nodes(test: TestExpr) -> nat + decreases test, +{ + 1 + match test { + TestExpr::And(children) | TestExpr::Or(children) => test_forest_nodes(children@), + _ => 0, + } +} + +pub open spec fn test_forest_nodes(tests: Seq>) -> nat + decreases tests, +{ + if tests.len() == 0 { 0 } + else { test_forest_nodes(tests.drop_last()) + test_nodes(tests.last()) } +} + +pub open spec fn regex_nodes(regex: RegexExpr) -> nat + decreases regex, +{ + 1 + match regex { + RegexExpr::Union(children) | RegexExpr::Concat(children) | RegexExpr::Intersect(children) => + regex_forest_nodes(children@), + RegexExpr::Star(child) | RegexExpr::Not(child) => regex_nodes(*child), + _ => 0, + } +} + +pub open spec fn regex_forest_nodes(regexes: Seq>) -> nat + decreases regexes, +{ + if regexes.len() == 0 { 0 } + else { regex_forest_nodes(regexes.drop_last()) + regex_nodes(regexes.last()) } +} + +pub proof fn lemma_test_forest_append(left: Seq>, right: Seq>) + ensures test_forest_nodes(left + right) == test_forest_nodes(left) + test_forest_nodes(right), + decreases right.len(), +{ + if right.len() > 0 { + lemma_test_forest_append(left, right.drop_last()); + assert((left + right).drop_last() =~= left + right.drop_last()); + assert((left + right).last() == right.last()); + } else { + assert(left + right =~= left); + } +} + +pub proof fn lemma_regex_forest_append(left: Seq>, right: Seq>) + ensures regex_forest_nodes(left + right) == regex_forest_nodes(left) + regex_forest_nodes(right), + decreases right.len(), +{ + if right.len() > 0 { + lemma_regex_forest_append(left, right.drop_last()); + assert((left + right).drop_last() =~= left + right.drop_last()); + assert((left + right).last() == right.last()); + } else { + assert(left + right =~= left); + } +} + +/// A real constructor/projection proof client, without a projection-obedience assumption. +pub fn constructor_client(slots: alloc::vec::Vec>) + -> (rule: Rule) + ensures + rule@.mode == RuleMode::Require, + rule@.head == slots@.map(|i: int, pattern: ComponentPattern| pattern@), + rule@.tail == RegexView::Not(Box::new(RegexView::Epsilon)), +{ + proof! { reveal_with_fuel(regex_view, 2); } + let iter = slots.into_iter(); + proof! { vstd::std_specs::iter::axiom_from_iterator_ensures(iter); } + let head = Head::new(iter); + let tail = RegexExpr::complement(RegexExpr::epsilon()); + Rule::new(RuleMode::Require, head, tail) +} +} diff --git a/src/history-syntax/src/verify/events.rs b/src/history-syntax/src/verify/events.rs new file mode 100644 index 000000000..73515229b --- /dev/null +++ b/src/history-syntax/src/verify/events.rs @@ -0,0 +1,97 @@ +//! `event_laws` (`history_syntax::spec::events`) for the built-in event types: tuples and Frunk coproducts (`sec:events`). + +use crate::event::specs::EventSpec; +use crate::event::{Component2, Component3, Component4, Event}; +use crate::key_hash::KeyHash; +use crate::spec::events::{arity, event_laws, event_view, well_tagged}; +use core::fmt::Debug; +use core::hash::Hash; +use frunk_core::coproduct::{CNil, Coproduct}; +use vstd::prelude::*; + +verus! { + +/// A pair projects each coordinate with its own tag and every well-tagged pair is a view. +pub proof fn lemma_event_laws_pair() + ensures event_laws::<(A, B)>(), +{ + assert forall|xs: Seq>| #[trigger] well_tagged::<(A, B)>(xs) + implies exists|e: (A, B)| event_view(e) == xs by { + let a = match xs[0] { Component2::C0(a) => a, _ => arbitrary() }; + let b = match xs[1] { Component2::C1(b) => b, _ => arbitrary() }; + let e = (a, b); + assert(event_view(e) =~= xs); + } +} + +/// A triple projects each coordinate with its own tag and every well-tagged triple is a view. +pub proof fn lemma_event_laws_triple() + ensures event_laws::<(A, B, C)>(), +{ + assert forall|xs: Seq>| #[trigger] well_tagged::<(A, B, C)>(xs) + implies exists|e: (A, B, C)| event_view(e) == xs by { + let a = match xs[0] { Component3::C0(a) => a, _ => arbitrary() }; + let b = match xs[1] { Component3::C1(b) => b, _ => arbitrary() }; + let c = match xs[2] { Component3::C2(c) => c, _ => arbitrary() }; + let e = (a, b, c); + assert(event_view(e) =~= xs); + } +} + +/// A quadruple projects each coordinate with its own tag and every well-tagged quadruple is a view. +pub proof fn lemma_event_laws_quad() + ensures event_laws::<(A, B, C, D)>(), +{ + assert forall|xs: Seq>| #[trigger] well_tagged::<(A, B, C, D)>(xs) + implies exists|e: (A, B, C, D)| event_view(e) == xs by { + let a = match xs[0] { Component4::C0(a) => a, _ => arbitrary() }; + let b = match xs[1] { Component4::C1(b) => b, _ => arbitrary() }; + let c = match xs[2] { Component4::C2(c) => c, _ => arbitrary() }; + let d = match xs[3] { Component4::C3(d) => d, _ => arbitrary() }; + let e = (a, b, c, d); + assert(event_view(e) =~= xs); + } +} + +/// The final coproduct variant inherits `H`'s laws (its `CNil` arm has no values). +pub proof fn lemma_event_laws_coproduct_nil() + requires event_laws::(), + ensures event_laws::>(), +{ + assert forall|xs: Seq| #[trigger] well_tagged::>(xs) + implies exists|e: Coproduct| event_view(e) == xs by { + assert(well_tagged::(xs)); + let h = choose|h: H| event_view(h) == xs; + assert(event_view(Coproduct::::Inl(h)) =~= xs); + } +} + +/// A head variant inherits the laws of its head and of the rest of the union, provided the rest +/// tags components the way the head does (the union projects with the head's `coordinate`). +pub proof fn lemma_event_laws_coproduct_cons() + where + H: Event, + Coproduct: Event, + requires event_laws::(), event_laws::>(), + forall|c: H::Component| #[trigger] as EventSpec>::coordinate_spec(c) + == H::coordinate_spec(c), + ensures event_laws::>>(), +{ + assert forall|e: Coproduct>, i: int| 0 <= i < arity::() + implies H::coordinate_spec(#[trigger] e.component_spec(i)) == i by { + match e { + Coproduct::Inl(head) => assert(e.component_spec(i) == head.component_spec(i)), + Coproduct::Inr(tail) => assert(e.component_spec(i) == tail.component_spec(i)), + } + } + assert forall|xs: Seq| #[trigger] well_tagged::>>(xs) + implies exists|e: Coproduct>| event_view(e) == xs by { + assert(well_tagged::(xs)); + let h = choose|h: H| event_view(h) == xs; + assert(event_view(Coproduct::>::Inl(h)) =~= xs); + } +} + +} // verus! diff --git a/src/history-syntax/src/verify/mod.rs b/src/history-syntax/src/verify/mod.rs new file mode 100644 index 000000000..343c0a1c2 --- /dev/null +++ b/src/history-syntax/src/verify/mod.rs @@ -0,0 +1,2 @@ +pub mod dsl; +pub mod events; diff --git a/src/history-syntax/tests/dsl.rs b/src/history-syntax/tests/dsl.rs new file mode 100644 index 000000000..93601d570 --- /dev/null +++ b/src/history-syntax/tests/dsl.rs @@ -0,0 +1,194 @@ +use history_syntax::{ + AtomPattern, CNil, Comparison, Component, Component3, ComponentPattern, Coproduct, Event, Head, + N3, RegexExpr, Rule, RuleMode, TestExpr, +}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +struct DocumentEvent { + principal: u8, + action: u8, + resource: u8, + payload: u16, +} + +impl Event for DocumentEvent { + type Component = Component3; + type Arity = N3; + + fn component(self, index: usize) -> Self::Component { + match index { + 0 => Component3::C0(self.principal), + 1 => Component3::C1(self.action), + _ => Component3::C2(self.resource), + } + } + + fn coordinate(component: Self::Component) -> usize { + match component { + Component3::C0(_) => 0, + Component3::C1(_) => 1, + Component3::C2(_) => 2, + } + } +} + +fn head() -> Head { + Head::new([ + ComponentPattern::variable("actor"), + ComponentPattern::constant(Component3::C1(2)), + ComponentPattern::variable("document"), + ]) +} + +fn action(value: u8) -> RegexExpr { + RegexExpr::test(TestExpr::atom( + Comparison::Eq, + AtomPattern::new( + Component(1), + ComponentPattern::constant(Component3::C1(value)), + ), + )) +} + +#[test] +fn typed_constructors_keep_values_names_and_field_order() { + assert_eq!( + ComponentPattern::::constant(7_u8), + ComponentPattern::Constant(7_u32) + ); + assert_eq!( + ComponentPattern::::variable("actor"), + ComponentPattern::Variable("actor".into()) + ); + let rule = Rule::new(RuleMode::Require, head(), action(1)); + assert_eq!(rule.mode, RuleMode::Require); + assert_eq!( + rule.head.slots()[0], + ComponentPattern::Variable("actor".into()) + ); + assert_eq!( + rule.head.slots()[1], + ComponentPattern::Constant(Component3::C1(2)) + ); + assert_eq!( + rule.head.slots()[2], + ComponentPattern::Variable("document".into()) + ); + assert_eq!(rule.tail, action(1)); +} + +#[test] +fn comparisons_and_atoms_preserve_the_selected_domain() { + assert_eq!(!Comparison::Eq, Comparison::Neq); + assert_eq!(!Comparison::Neq, Comparison::Eq); + let principal: AtomPattern = + AtomPattern::new(Component(0), ComponentPattern::constant(Component3::C0(1))); + let action: AtomPattern = + AtomPattern::new(Component(1), ComponentPattern::constant(Component3::C1(1))); + let resource: AtomPattern = + AtomPattern::new(Component(2), ComponentPattern::constant(Component3::C2(1))); + assert_eq!(principal.component(), Component(0)); + assert_eq!(action.component(), Component(1)); + assert_eq!(resource.component(), Component(2)); + assert_ne!(principal, action); + assert_ne!(action, resource); +} + +#[test] +fn boolean_constructors_retain_empty_operators_and_iterator_order() { + type Test = TestExpr; + assert_eq!(Test::true_test(), Test::True); + assert_eq!(Test::false_test(), Test::False); + assert_eq!(Test::and([]), Test::And(vec![])); + assert_eq!(Test::or([]), Test::Or(vec![])); + assert_eq!( + Test::and([Test::True, Test::False]), + Test::And(vec![Test::True, Test::False]) + ); + assert_eq!( + Test::or([Test::False, Test::True]), + Test::Or(vec![Test::False, Test::True]) + ); +} + +#[test] +fn regex_constructors_keep_whole_word_complement_and_concat_order() { + type Regex = RegexExpr; + assert_eq!(Regex::empty(), Regex::Empty); + assert_eq!(Regex::all(), Regex::All); + assert_eq!(Regex::epsilon(), Regex::Epsilon); + assert_eq!(Regex::concat([]), Regex::Concat(vec![])); + assert_eq!(Regex::union([]), Regex::Union(vec![])); + assert_eq!(Regex::intersect([]), Regex::Intersect(vec![])); + assert_eq!( + Regex::concat([action(1), action(2)]), + Regex::Concat(vec![action(1), action(2)]) + ); + assert_ne!( + Regex::concat([action(1), action(2)]), + Regex::concat([action(2), action(1)]) + ); + assert_eq!(Regex::star(action(1)), Regex::Star(Box::new(action(1)))); + assert_eq!( + Regex::complement(action(1)), + Regex::Not(Box::new(action(1))) + ); + assert_eq!( + Regex::union([action(1), action(2)]), + Regex::Union(vec![action(1), action(2)]) + ); + assert_eq!( + Regex::intersect([action(1), action(2)]), + Regex::Intersect(vec![action(1), action(2)]) + ); +} + +#[test] +fn conversions_use_the_callers_actual_conversion() { + struct Offset(u8); + impl From for u16 { + fn from(value: Offset) -> u16 { + u16::from(value.0) + 10 + } + } + assert_eq!( + ComponentPattern::::constant(Offset(3)), + ComponentPattern::Constant(13) + ); +} + +#[test] +fn coproducts_forward_projections_without_changing_event_identity() { + type Events = Coproduct>; + let event = DocumentEvent { + principal: 1, + action: 2, + resource: 3, + payload: 99, + }; + let left: Events = Coproduct::Inl(event); + let right: Events = Coproduct::Inr(Coproduct::Inl(event)); + for (index, expected) in [Component3::C0(1), Component3::C1(2), Component3::C2(3)] + .into_iter() + .enumerate() + { + assert_eq!(left.component(index), expected); + assert_eq!(right.component(index), expected); + assert_eq!(Events::coordinate(expected), index); + } + assert_ne!(left, right); +} + +#[test] +fn iterative_disposal_handles_deep_owned_trees() { + let mut tail: RegexExpr = RegexExpr::epsilon(); + for _ in 0..4096 { + tail = RegexExpr::complement(tail); + } + Rule::new(RuleMode::Require, head(), tail).dispose(); + let mut test: TestExpr = TestExpr::true_test(); + for _ in 0..4096 { + test = TestExpr::and([test]); + } + Rule::new(RuleMode::Require, head(), RegexExpr::test(test)).dispose(); +} diff --git a/src/junco-core/Cargo.toml b/src/junco-core/Cargo.toml new file mode 100644 index 000000000..fdd18fb3c --- /dev/null +++ b/src/junco-core/Cargo.toml @@ -0,0 +1,32 @@ +[package] +name = "junco-core" +description = "Portable rule tables, lowering and numeric kernel for Regorus history rules" +version = "0.1.0" +edition = "2024" +license = "MIT" +repository = "https://github.com/microsoft/regorus" + +[package.metadata.verus] +verify = true + +[features] +default = [] +serde = ["dep:serde", "history-syntax/serde"] +runtime = ["dep:smallvec"] +std = ["vstd/std", "history-syntax/std"] +test-util = ["runtime"] + +[dependencies] +# Keep aligned with the root crate's vstd pin (.github/workflows/verus.yml). +vstd = { version = "=0.0.0-2026-10-04-0306", default-features = false, features = ["alloc"] } +thiserror = { version = "2", default-features = false } +history-syntax = { path = "../history-syntax", version = "0.1.0", default-features = false } +serde = { version = "1", default-features = false, features = ["derive", "alloc"], optional = true } +smallvec = { version = "=1.16.2", default-features = false, optional = true } + +[dev-dependencies] +serde_json = { version = "1", default-features = false, features = ["alloc"] } +postcard = { version = "1.1.3", default-features = false, features = ["alloc"] } + +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(verus_keep_ghost)'] } diff --git a/src/junco-core/src/bits.rs b/src/junco-core/src/bits.rs new file mode 100644 index 000000000..a5938bbd7 --- /dev/null +++ b/src/junco-core/src/bits.rs @@ -0,0 +1,26 @@ +//! Checked `u64` shifts with verified bodies, used where `u64::checked_shl`/`checked_shr` +//! would otherwise need an assumed specification (the pinned vstd specifies neither). + +use vstd::prelude::*; + +/// `value << shift`, or `None` when `shift` is at least 64, like `u64::checked_shl`. +#[verus_verify] +#[verus_spec(result => ensures result == if shift < 64 { Some(value << shift) } else { None })] +pub fn checked_shl(value: u64, shift: u32) -> Option { + if shift < 64 { + Some(value << shift) + } else { + None + } +} + +/// `value >> shift`, or `None` when `shift` is at least 64, like `u64::checked_shr`. +#[verus_verify] +#[verus_spec(result => ensures result == if shift < 64 { Some(value >> shift) } else { None })] +pub fn checked_shr(value: u64, shift: u32) -> Option { + if shift < 64 { + Some(value >> shift) + } else { + None + } +} diff --git a/src/junco-core/src/compile.rs b/src/junco-core/src/compile.rs new file mode 100644 index 000000000..8f87a6802 --- /dev/null +++ b/src/junco-core/src/compile.rs @@ -0,0 +1,430 @@ +//! Constant encoding preserves portable DAG topology; graph compilation is separate. + +use crate::errors::HistoryError; +use crate::flat::{FlatBuilder, FlatHead, FlatPair, FlatRegex, FlatTerm, FlatTest}; +use crate::limits::Limits; +use crate::observation::ObservationWorld; +#[cfg(verus_keep_ghost)] +use crate::verify::encoding::*; +#[cfg(verus_keep_ghost)] +use crate::verify::history_specs::no_invariant_failure; +use alloc::vec::Vec; +use history_syntax::Event; +#[cfg(verus_keep_ghost)] +use history_syntax::event::specs::EventSpec; +use history_syntax::syntax::Component; +use vstd::prelude::*; + +// Expand inside the trait contract: calling a FlatEncoder-bounded predicate there is cyclic. +#[cfg(verus_keep_ghost)] +macro_rules! encoder_wf_clause { + ($model:ty, $($encoder:tt)+) => { + vstd::prelude::verus_proof_expr! { + ($($encoder)+).obeys_encoding_spec() + && maps_wf(($($encoder)+).maps(), <$model>::equality(), <$model>::domain()) + } + }; +} + +verus! { + +broadcast use {vstd::std_specs::vec::group_vec_axioms, vstd::seq::group_seq_lemmas}; + +/// Component-specific constant encoding. Hashes are lookup aids, never identities. +/// +/// Native implementations opt in to the ghost contract only after establishing +/// their equality/hash correspondence and finite-map implementation obligations. +pub trait FlatEncoder: Sized { + spec fn equality() -> Equality; + spec fn domain() -> Domain; + spec fn maps(&self) -> Codebook; + spec fn obeys_encoding_spec(&self) -> bool; + spec fn encoding_calls(&self) -> nat; + + open spec fn state_wf(&self) -> bool { true } + + /// Opt in only when valid component requests cannot report structural failures. + open spec fn errors_are_non_invariant(&self) -> bool { false } + open spec fn errors_are_resource(&self) -> bool { false } + + // Keep the original books valid when a nested mutable encoder borrow ends. + #[verifier::prophetic] + spec fn restoration(&self) -> (Codebook, bool); + + fn encode(&mut self, field: Component, value: &C) -> (result: Result) + requires old(self).state_wf(), + ensures final(self).state_wf(), + final(self).restoration() == old(self).restoration(), + final(self).errors_are_non_invariant() == old(self).errors_are_non_invariant(), + final(self).errors_are_resource() == old(self).errors_are_resource(), + old(self).errors_are_resource() && encoder_wf_clause!(Self, old(self)) + && Self::domain()(field, *value) + ==> (result matches Err(error) ==> crate::spec::semantics::resource_error(error)), + old(self).errors_are_non_invariant() && encoder_wf_clause!(Self, old(self)) + ==> no_invariant_failure(result) + && (Self::domain()(field, *value) + ==> !(result matches Err(HistoryError::InvalidPolicy { .. }))), + encoder_wf_clause!(Self, old(self)) ==> { + encoder_wf_clause!(Self, final(self)) + && extends(old(self).maps(), final(self).maps(), Self::equality()) + && grows_by(old(self).maps(), final(self).maps(), only_value(field, *value)) + && final(self).encoding_calls() == old(self).encoding_calls() + 1 + && match result { + Ok(id) => Self::domain()(field, *value) + && encoded(final(self).maps(), Self::equality(), field, *value, id), + Err(_) => true, + } + }; +} + +pub open spec fn encoder_wf>(encoder: M) -> bool { + encoder_wf_clause!(M, encoder) +} + +/// Validate a typed constant's coordinate before touching a component codebook. +pub fn validate_component(field: Component, value: &E::Component) + -> (result: Result<(), HistoryError>) + ensures E::obeys_projection_spec() ==> + result.is_ok() == (E::coordinate_spec(*value) == field.0 as nat), + E::obeys_projection_spec() && result.is_ok() ==> + field.0 < history_syntax::spec::events::arity::(), + result matches Err(error) ==> match error { + HistoryError::InvalidPolicy { path, message } => path@ == "$"@ + && message == "constant belongs to another component", + _ => false, + }, +{ + if E::coordinate(*value) == field.index() { + Ok(()) + } else { + Err(HistoryError::invalid_policy("$", "constant belongs to another component")) + } +} + +fn invalid_source() -> (error: HistoryError) + ensures match error { + HistoryError::InvalidPolicy { path, message } => path@ == "$"@ + && message == "invalid portable history source", + _ => false, + }, +{ + HistoryError::invalid_policy("$", "invalid portable history source") +} + +fn copy_ids(source: &[u32], limits: &mut L, world: &mut ObservationWorld) + -> (result: Result, HistoryError>) + ensures result matches Ok(ids) ==> ids@ == source@, + no_invariant_failure(result), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + result matches Err(error) ==> crate::spec::semantics::resource_error(error), +{ + let mut ids = Vec::new(); + match world.try_reserve_vec_exact(&mut ids, source.len()) { + Ok(()) => {}, Err(_) => return Err(HistoryError::AllocationFailed), + } + let mut index = 0; + while index < source.len() + invariant index <= source@.len(), ids@ == source@.take(index as int), + decreases source@.len() - index, + { + limits.checkpoint()?; + ids.push(source[index]); + index += 1; + } + Ok(ids) +} + +fn encode_head>(source: &FlatHead, field: Component, encoder: &mut M) + -> (result: Result, HistoryError>) + requires old(encoder).state_wf(), + ensures final(encoder).state_wf(), + result matches Ok(head) ==> head_shape(*source, head), + final(encoder).restoration() == old(encoder).restoration(), + final(encoder).errors_are_non_invariant() == old(encoder).errors_are_non_invariant(), + final(encoder).errors_are_resource() == old(encoder).errors_are_resource(), + old(encoder).errors_are_resource() && encoder_wf::(*old(encoder)) + && head_in_domain(*source, field, M::domain()) + ==> (result matches Err(error) ==> crate::spec::semantics::resource_error(error)), + encoder_wf::(*old(encoder)) ==> + final(encoder).encoding_calls() <= old(encoder).encoding_calls() + 1, + old(encoder).errors_are_non_invariant() && encoder_wf::(*old(encoder)) + ==> no_invariant_failure(result) + && (head_in_domain(*source, field, M::domain()) + ==> !(result matches Err(HistoryError::InvalidPolicy { .. }))), + encoder_wf::(*old(encoder)) ==> encoder_wf::(*final(encoder)) + && extends(old(encoder).maps(), final(encoder).maps(), M::equality()) + && grows_by(old(encoder).maps(), final(encoder).maps(), head_constant_of(*source, field)) + && (result matches Ok(head) ==> head_encoded(*source, head, field, final(encoder).maps(), M::equality()) + && head_in_domain(*source, field, M::domain())), +{ + let ghost added = head_constant_of(*source, field); + match source { + FlatHead::Any => { proof { lemma_grows_by_refl(encoder.maps(), added); } Ok(FlatHead::Any) }, + FlatHead::Bind => { proof { lemma_grows_by_refl(encoder.maps(), added); } Ok(FlatHead::Bind) }, + FlatHead::Constant(value) => { + let result = encoder.encode(field, value); + proof { if encoder_wf::(*old(encoder)) { + lemma_grows_by_weaken(old(encoder).maps(), encoder.maps(), only_value(field, *value), added); + } } + Ok(FlatHead::Constant(result?)) + }, + } +} + +fn encode_test, L: Limits>(source: &FlatTest, encoder: &mut M, + limits: &mut L, world: &mut ObservationWorld) -> (result: Result, HistoryError>) + requires old(encoder).state_wf(), + ensures final(encoder).state_wf(), + result matches Ok(test) ==> test_shape(*source, test), + final(encoder).restoration() == old(encoder).restoration(), + final(encoder).errors_are_non_invariant() == old(encoder).errors_are_non_invariant(), + final(encoder).errors_are_resource() == old(encoder).errors_are_resource(), + old(encoder).errors_are_resource() && encoder_wf::(*old(encoder)) + && test_in_domain(*source, M::domain()) + ==> (result matches Err(error) ==> crate::spec::semantics::resource_error(error)), + encoder_wf::(*old(encoder)) ==> + final(encoder).encoding_calls() <= old(encoder).encoding_calls() + 1, + old(encoder).errors_are_non_invariant() && encoder_wf::(*old(encoder)) + ==> no_invariant_failure(result) + && (test_in_domain(*source, M::domain()) + ==> !(result matches Err(HistoryError::InvalidPolicy { .. }))), + encoder_wf::(*old(encoder)) ==> encoder_wf::(*final(encoder)) + && extends(old(encoder).maps(), final(encoder).maps(), M::equality()) + && grows_by(old(encoder).maps(), final(encoder).maps(), test_constant_of(*source)) + && (result matches Ok(test) ==> test_encoded(*source, test, final(encoder).maps(), M::equality()) + && test_in_domain(*source, M::domain())), +{ + let ghost added = test_constant_of(*source); + proof { lemma_grows_by_refl(encoder.maps(), added); } + match source { + FlatTest::Bool(value) => Ok(FlatTest::Bool(*value)), + FlatTest::Atom { field, term, positive } => { + let term = match term { + FlatTerm::Constant(value) => { + let result = encoder.encode(*field, value); + proof { if encoder_wf::(*old(encoder)) { + lemma_grows_by_weaken(old(encoder).maps(), encoder.maps(), only_value(*field, *value), added); + } } + FlatTerm::Constant(result?) + }, + FlatTerm::Variable(variable) => FlatTerm::Variable(*variable), + }; + Ok(FlatTest::Atom { field: *field, term, positive: *positive }) + }, + FlatTest::And(children) => Ok(FlatTest::And(copy_ids(children, limits, world)?)), + FlatTest::Or(children) => Ok(FlatTest::Or(copy_ids(children, limits, world)?)), + } +} + +fn copy_regex(source: &FlatRegex, limits: &mut L, world: &mut ObservationWorld) + -> (result: Result) + ensures result matches Ok(regex) ==> regex_same(*source, regex), + no_invariant_failure(result), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + result matches Err(error) ==> crate::spec::semantics::resource_error(error), +{ + Ok(match source { + FlatRegex::Empty => FlatRegex::Empty, + FlatRegex::All => FlatRegex::All, + FlatRegex::Epsilon => FlatRegex::Epsilon, + FlatRegex::Test(id) => FlatRegex::Test(*id), + FlatRegex::Concat(ids) => FlatRegex::Concat(copy_ids(ids, limits, world)?), + FlatRegex::Union(ids) => FlatRegex::Union(copy_ids(ids, limits, world)?), + FlatRegex::Intersect(ids) => FlatRegex::Intersect(copy_ids(ids, limits, world)?), + FlatRegex::Star(id) => FlatRegex::Star(*id), + FlatRegex::Complement(id) => FlatRegex::Complement(*id), + }) +} + +/// Validate before interning, then encode each stored constant exactly once. +/// Repeated edges, unreachable nodes, and non-last roots remain untouched. +/// Encoders retain their error capability; opted-in well-formed encoders cannot +/// report internal failures, or invalid-policy errors for valid in-domain sources. +pub fn lower_flat, L: Limits>(source: &FlatPair, encoder: &mut M, + limits: &mut L, world: &mut ObservationWorld) -> (result: Result, HistoryError>) + requires old(encoder).state_wf(), + ensures final(encoder).state_wf(), + result matches Ok(target) ==> topology(*source, target) + && crate::flat::verify::structural_wf(target), + final(encoder).restoration() == old(encoder).restoration(), + final(encoder).errors_are_non_invariant() == old(encoder).errors_are_non_invariant(), + final(encoder).errors_are_resource() == old(encoder).errors_are_resource(), + old(encoder).errors_are_resource() && encoder_wf::(*old(encoder)) + && crate::flat::verify::structural_wf(*source) && constants_in_domain(*source, M::domain()) + ==> (result matches Err(error) ==> crate::spec::semantics::resource_error(error)), + encoder_wf::(*old(encoder)) ==> + final(encoder).encoding_calls() <= old(encoder).encoding_calls() + + source.head@.len() + source.tests@.len(), + old(encoder).errors_are_non_invariant() && encoder_wf::(*old(encoder)) + ==> no_invariant_failure(result) + && (crate::flat::verify::structural_wf(*source) + && constants_in_domain(*source, M::domain()) + ==> !(result matches Err(HistoryError::InvalidPolicy { .. }))), + encoder_wf::(*old(encoder)) ==> encoder_wf::(*final(encoder)) + && extends(old(encoder).maps(), final(encoder).maps(), M::equality()) + && grows_by(old(encoder).maps(), final(encoder).maps(), source_constants(*source)) + && (result matches Ok(target) ==> lowering(*source, target, final(encoder).maps(), M::equality()) + && constants_in_domain(*source, M::domain())), +{ + if source.validate().is_err() { + proof { lemma_grows_by_refl(encoder.maps(), source_constants(*source)); } + return Err(invalid_source()); + } + let ghost initial_maps = encoder.maps(); + let ghost verified = encoder_wf::(*encoder); + let ghost initial_calls = encoder.encoding_calls(); + proof { lemma_grows_by_refl(initial_maps, source_constants(*source)); } + let mut head = Vec::new(); + if world.try_reserve_vec_exact(&mut head, source.head.len()).is_err() { + return Err(HistoryError::AllocationFailed); + } + limits.enforce_memory()?; + let mut index = 0; + while index < source.head.len() + invariant index <= source.head@.len(), head@.len() == index, + encoder.state_wf(), + crate::flat::verify::structural_wf(*source), + encoder.restoration() == old(encoder).restoration(), + encoder.errors_are_non_invariant() == old(encoder).errors_are_non_invariant(), + encoder.errors_are_resource() == old(encoder).errors_are_resource(), + initial_maps == old(encoder).maps(), verified == encoder_wf::(*old(encoder)), + initial_calls == old(encoder).encoding_calls(), + verified ==> encoder.encoding_calls() <= initial_calls + index, + (forall|i: int| 0 <= i < index ==> head_shape(source.head@[i], head@[i])), + verified ==> encoder_wf::(*encoder) + && extends(initial_maps, encoder.maps(), M::equality()) + && grows_by(initial_maps, encoder.maps(), source_constants(*source)) + && (forall|i: int| 0 <= i < index ==> head_in_domain(source.head@[i], field_at(i), M::domain())) + && (forall|i: int| 0 <= i < index ==> head_encoded(source.head@[i], head@[i], field_at(i), encoder.maps(), M::equality())), + decreases source.head@.len() - index, + { + limits.checkpoint()?; + let field = Component::new(index); + let ghost before = encoder.maps(); + proof { + assert(field == field_at(index as int)); + assert(constants_in_domain(*source, M::domain()) + ==> head_in_domain(source.head@[index as int], field, M::domain())); + } + let slot = encode_head(&source.head[index], field, encoder); + proof { + if verified { + lemma_extends_transitive(initial_maps, before, encoder.maps(), M::equality()); + lemma_head_source_constant(*source, index as int); + lemma_grows_by_transitive(initial_maps, before, encoder.maps(), source_constants(*source), + head_constant_of(source.head@[index as int], field), source_constants(*source)); + if slot is Ok { + assert forall|i: int| 0 <= i < index implies + head_encoded(source.head@[i], head@[i], field_at(i), encoder.maps(), M::equality()) by { + lemma_head_extends(source.head@[i], head@[i], field_at(i), before, encoder.maps(), M::equality()); + } + } + } + } + let slot = slot?; + head.push(slot); + index += 1; + } + let mut builder = FlatBuilder::new(head); + index = 0; + while index < source.tests.len() + invariant index <= source.tests@.len(), builder.wf(), + encoder.state_wf(), + crate::flat::verify::structural_wf(*source), + encoder.restoration() == old(encoder).restoration(), + encoder.errors_are_non_invariant() == old(encoder).errors_are_non_invariant(), + encoder.errors_are_resource() == old(encoder).errors_are_resource(), + initial_maps == old(encoder).maps(), verified == encoder_wf::(*old(encoder)), + initial_calls == old(encoder).encoding_calls(), + verified ==> encoder.encoding_calls() <= initial_calls + source.head@.len() + index, + builder.tests_view().len() == index, builder.regexes_view().len() == 0, + builder.head_view().len() == source.head@.len(), + (forall|i: int| 0 <= i < source.head@.len() ==> head_shape(source.head@[i], builder.head_view()[i])), + (forall|i: int| 0 <= i < index ==> test_shape(source.tests@[i], builder.tests_view()[i])), + verified ==> encoder_wf::(*encoder) + && extends(initial_maps, encoder.maps(), M::equality()) + && grows_by(initial_maps, encoder.maps(), source_constants(*source)) + && (forall|i: int| 0 <= i < source.head@.len() ==> head_in_domain(source.head@[i], field_at(i), M::domain())) + && (forall|i: int| 0 <= i < index ==> test_in_domain(source.tests@[i], M::domain())) + && (forall|i: int| 0 <= i < source.head@.len() ==> head_encoded(source.head@[i], builder.head_view()[i], field_at(i), encoder.maps(), M::equality())) + && (forall|i: int| 0 <= i < index ==> test_encoded(source.tests@[i], builder.tests_view()[i], encoder.maps(), M::equality())), + decreases source.tests@.len() - index, + { + limits.checkpoint()?; + let ghost before = encoder.maps(); + proof { + assert(encoder.state_wf()); + assert(encoder.errors_are_non_invariant() == old(encoder).errors_are_non_invariant()); + assert(verified ==> encoder_wf::(*encoder)); + assert(constants_in_domain(*source, M::domain()) + ==> test_in_domain(source.tests@[index as int], M::domain())); + } + let node = encode_test(&source.tests[index], encoder, limits, world); + proof { + if verified { + lemma_extends_transitive(initial_maps, before, encoder.maps(), M::equality()); + lemma_test_source_constant(*source, index as int); + lemma_grows_by_transitive(initial_maps, before, encoder.maps(), source_constants(*source), + test_constant_of(source.tests@[index as int]), source_constants(*source)); + } + } + let node = node?; + proof { + assert(crate::flat::verify::test_wf(source.head@, source.tests@[index as int], index as nat)); + if let FlatTest::Atom { field, term: FlatTerm::Variable(_), .. } = node { + let f = crate::flat::verify::field_index(field); + assert(source.head@[f] is Bind); + assert(builder.head_view()[f] is Bind); + } + assert(crate::flat::verify::test_wf(builder.head_view(), node, builder.tests_view().len())); + if verified { + assert forall|i: int| 0 <= i < source.head@.len() implies head_encoded(source.head@[i], builder.head_view()[i], field_at(i), encoder.maps(), M::equality()) by { + lemma_head_extends(source.head@[i], builder.head_view()[i], field_at(i), before, encoder.maps(), M::equality()); + } + assert forall|i: int| 0 <= i < index implies test_encoded(source.tests@[i], builder.tests_view()[i], encoder.maps(), M::equality()) by { + lemma_test_extends(source.tests@[i], builder.tests_view()[i], before, encoder.maps(), M::equality()); + } + } + } + builder.test(node, limits, world)?; + index += 1; + } + index = 0; + while index < source.regexes.len() + invariant index <= source.regexes@.len(), builder.wf(), + encoder.state_wf(), + crate::flat::verify::structural_wf(*source), + encoder.restoration() == old(encoder).restoration(), + encoder.errors_are_non_invariant() == old(encoder).errors_are_non_invariant(), + encoder.errors_are_resource() == old(encoder).errors_are_resource(), + initial_maps == old(encoder).maps(), verified == encoder_wf::(*old(encoder)), + initial_calls == old(encoder).encoding_calls(), + verified ==> encoder.encoding_calls() <= initial_calls + source.head@.len() + source.tests@.len(), + regex_tables_same(source.regexes@.take(index as int), builder.regexes_view()), + builder.tests_view().len() == source.tests@.len(), + builder.regexes_view().len() == index, + builder.head_view().len() == source.head@.len(), + (forall|i: int| 0 <= i < source.head@.len() ==> head_shape(source.head@[i], builder.head_view()[i])), + (forall|i: int| 0 <= i < source.tests@.len() ==> test_shape(source.tests@[i], builder.tests_view()[i])), + verified ==> encoder_wf::(*encoder) + && extends(initial_maps, encoder.maps(), M::equality()) + && grows_by(initial_maps, encoder.maps(), source_constants(*source)) + && constants_in_domain(*source, M::domain()) + && (forall|i: int| 0 <= i < source.head@.len() ==> head_encoded(source.head@[i], builder.head_view()[i], field_at(i), encoder.maps(), M::equality())) + && (forall|i: int| 0 <= i < source.tests@.len() ==> test_encoded(source.tests@[i], builder.tests_view()[i], encoder.maps(), M::equality())), + decreases source.regexes@.len() - index, + { + limits.checkpoint()?; + let node = copy_regex(&source.regexes[index], limits, world)?; + proof { + assert(crate::flat::verify::regex_wf(source.regexes@[index as int], index as nat, source.tests@.len())); + assert(crate::flat::verify::regex_wf(node, builder.regexes_view().len(), builder.tests_view().len())); + } + builder.regex(node, limits, world)?; + index += 1; + } + proof { assert(source.root < builder.regexes_view().len()); } + builder.finish(source.root) +} + +} diff --git a/src/junco-core/src/errors.rs b/src/junco-core/src/errors.rs new file mode 100644 index 000000000..167f9497a --- /dev/null +++ b/src/junco-core/src/errors.rs @@ -0,0 +1,175 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +use crate::limits::LimitError; +use alloc::borrow::ToOwned; +use alloc::string::String; +use vstd::prelude::*; + +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum HistoryError { + #[error("invalid history policy at {path}: {message}")] + InvalidPolicy { path: String, message: &'static str }, + #[error("history variable {name:?} is not bound by request pattern")] + UnboundVariable { name: String }, + #[error("history symbolic graph payload exceeds {limit} bytes")] + GraphBudget { limit: usize }, + #[error("history graph index or size computation overflowed")] + GraphIndex, + #[error("history allocation failed")] + AllocationFailed, + #[error("history arena exhausted")] + ArenaExhausted, + #[error("history invariant violated: {message}")] + Invariant { message: &'static str }, + #[error("history {domain} identity exhausted")] + IdExhausted { domain: &'static str }, + #[error("unknown history {domain} identity {id}")] + UnknownId { domain: &'static str, id: u64 }, + #[error("history belongs to another store")] + WrongHistoryOwner, + #[error("checkpoint does not belong to this history")] + WrongCheckpointOwner, + #[error("checkpoint is beyond the current history")] + CheckpointBeyondHistory, + #[error("history revision exhausted")] + RevisionExhausted, + #[error("history changed from revision {expected} to {actual}")] + HistoryChanged { expected: u64, actual: u64 }, + #[error(transparent)] + Limit(LimitError), +} + +#[verus_verify] +impl From for HistoryError { + #[verus_spec(result => ensures result == Self::Limit(error))] + fn from(error: LimitError) -> Self { + Self::Limit(error) + } +} + +#[verus_verify] +impl HistoryError { + #[verus_verify] + #[verus_spec(result => ensures match result { + Self::InvalidPolicy { path: owned, message: actual } => owned@ == path@ && actual == message, + _ => false, + })] + pub fn invalid_policy(path: &str, message: &'static str) -> Self { + Self::InvalidPolicy { + path: path.to_owned(), + message, + } + } + #[verus_verify] + #[verus_spec(result => ensures result == (HistoryError::Invariant { message }))] + pub const fn invariant(message: &'static str) -> HistoryError { + HistoryError::Invariant { message } + } + + #[cfg(feature = "runtime")] + #[verus_verify] + #[verus_spec(result => ensures result is Invariant)] + #[inline] + pub const fn normalization_invariant() -> HistoryError { + HistoryError::Invariant { + message: "invalid normalization work stack", + } + } + #[cfg(feature = "runtime")] + #[verus_verify] + #[verus_spec(result => ensures result is Invariant)] + #[inline] + pub const fn symbolic_invariant() -> HistoryError { + HistoryError::Invariant { + message: "invalid symbolic work stack", + } + } + #[cfg(feature = "runtime")] + #[verus_verify] + #[verus_spec(result => ensures result is Invariant)] + #[inline] + pub const fn invalid_truth_assignment() -> HistoryError { + HistoryError::Invariant { + message: "invalid truth assignment", + } + } + #[cfg(feature = "runtime")] + #[verus_verify] + #[verus_spec(result => ensures result is Invariant)] + #[inline] + pub const fn graph_id_overflow() -> HistoryError { + HistoryError::Invariant { + message: "graph ID does not fit usize", + } + } + #[verus_verify] + #[verus_spec(result => ensures result is GraphIndex)] + #[inline] + pub const fn graph_index_overflow() -> HistoryError { + HistoryError::GraphIndex + } + #[cfg(feature = "runtime")] + #[verus_verify] + #[verus_spec(result => ensures result is Invariant)] + #[inline] + pub const fn invalid_atom_set() -> HistoryError { + HistoryError::Invariant { + message: "invalid primitive atom set", + } + } + #[cfg(feature = "runtime")] + #[verus_verify] + #[verus_spec(result => ensures result is Invariant)] + #[inline] + pub const fn missing_transition_atom() -> HistoryError { + HistoryError::Invariant { + message: "transition primitive missing from atom set", + } + } +} + +/// Rule-compilation failure detected before a validator can execute. +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum CompileError { + /// The head must have exactly the event type's number of coordinates. + #[error("head has {found} slots but the event type has {expected}")] + HeadArity { expected: usize, found: usize }, + /// Tagged constants may only be used in their own coordinate. + #[error("constant of coordinate {coordinate} used in coordinate {component}")] + ComponentCoordinate { component: usize, coordinate: usize }, + /// One variable name occurs in different product components in the same rule. + #[error("variable {name:?} occurs in different product components")] + VariableComponentConflict { name: String }, + /// A tail references a variable that its head does not bind. + #[error("tail variable {name:?} is not bound by the head")] + UnboundVariable { name: String }, + #[error(transparent)] + Runtime(HistoryError), +} + +#[verus_verify] +impl From for CompileError { + #[verus_spec(result => ensures result == Self::Runtime(error))] + fn from(error: HistoryError) -> Self { + Self::Runtime(error) + } +} + +#[cfg(verus_keep_ghost)] +verus! { +impl vstd::std_specs::convert::FromSpecImpl for HistoryError { + open spec fn obeys_from_spec() -> bool { true } + open spec fn from_spec(error: LimitError) -> Self { Self::Limit(error) } +} + +impl vstd::std_specs::convert::FromSpecImpl for CompileError { + open spec fn obeys_from_spec() -> bool { true } + open spec fn from_spec(error: HistoryError) -> Self { Self::Runtime(error) } +} + +} diff --git a/src/junco-core/src/event.rs b/src/junco-core/src/event.rs new file mode 100644 index 000000000..bf803153f --- /dev/null +++ b/src/junco-core/src/event.rs @@ -0,0 +1,35 @@ +//! Request and grant records at the authorization boundary. + +use history_syntax::Event; +use vstd::prelude::*; + +/// Capability request with opaque caller metadata. +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Request { + /// Product event evaluated by the policy. + pub event: E, + /// Opaque value passed through unchanged on grant. + pub metadata: M, +} + +#[verus_verify] +impl Request { + /// Creates a request from an event and opaque metadata. + #[verus_spec(result => ensures result.event == event, result.metadata == metadata)] + pub fn new(event: E, metadata: M) -> Self { + Self { event, metadata } + } +} + +/// Accepted request echoed at the authorization boundary. +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Grant { + /// Accepted event, also appended to committed history. + pub event: E, + /// Original request metadata, preserved unchanged. + pub metadata: M, +} diff --git a/src/junco-core/src/flat.rs b/src/junco-core/src/flat.rs new file mode 100644 index 000000000..46d3c39a2 --- /dev/null +++ b/src/junco-core/src/flat.rs @@ -0,0 +1,656 @@ +//! Portable, store-independent source tables and their checked construction boundary. + +use crate::errors::HistoryError; +use crate::limits::Limits; +use crate::observation::ObservationWorld; +#[cfg(verus_keep_ghost)] +use crate::verify::history_specs::no_invariant_failure; +use alloc::string::String; +use alloc::vec::Vec; +use history_syntax::{ + MAX_ARITY, + syntax::{Component, RuleMode}, +}; +use vstd::prelude::*; + +#[verus_verify] +#[verus_verify(external_derive)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum FlatHead { + Any, + Constant(C), + Bind, +} + +#[verus_verify] +#[verus_verify(external_derive)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum FlatTerm { + Constant(C), + Variable(Component), +} + +#[verus_verify] +#[verus_verify(external_derive)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum FlatTest { + Bool(bool), + Atom { + field: Component, + term: FlatTerm, + positive: bool, + }, + And(Vec), + Or(Vec), +} + +// Variant order and names are the version-9 portable wire format. +#[verus_verify] +#[verus_verify(external_derive)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum FlatRegex { + Empty, + All, + Epsilon, + Test(u32), + Concat(Vec), + Union(Vec), + Intersect(Vec), + Star(u32), + Complement(u32), +} + +/// References are backward within their own table; the root need not be last. +#[verus_verify] +#[verus_verify(external_derive)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FlatPair { + pub head: Vec>, + pub tests: Vec>, + pub regexes: Vec, + pub root: u32, +} + +#[verus_verify] +#[verus_verify(external_derive)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct FlatRule { + pub mode: RuleMode, + pub source: FlatPair, +} + +#[cfg(verus_keep_ghost)] +pub mod verify { + use super::*; + + verus! { + impl View for FlatHead { + type V = crate::verify::history_specs::HeadField; + open spec fn view(&self) -> crate::verify::history_specs::HeadField { + match self { + FlatHead::Any => crate::verify::history_specs::HeadField::Any, + FlatHead::Constant(value) => crate::verify::history_specs::HeadField::Constant(*value as nat), + FlatHead::Bind => crate::verify::history_specs::HeadField::Bind, + } + } + } + + broadcast use {vstd::std_specs::vec::group_vec_axioms, vstd::seq::group_seq_lemmas}; + + pub open spec fn field_index(field: Component) -> int { + field.0 as int + } + + pub open spec fn references_before(children: Seq, bound: nat) -> bool { + forall|i: int| 0 <= i < children.len() ==> #[trigger] children[i] < bound + } + + pub open spec fn test_wf(head: Seq>, test: FlatTest, index: nat) -> bool { + match test { + FlatTest::Bool(_) => true, + FlatTest::Atom { field, term: FlatTerm::Variable(variable), .. } => + field_index(field) < head.len() && field == variable && head[field_index(field)] is Bind, + FlatTest::Atom { field, .. } => field_index(field) < head.len(), + FlatTest::And(children) | FlatTest::Or(children) => references_before(children@, index), + } + } + + pub open spec fn regex_wf(regex: FlatRegex, index: nat, tests: nat) -> bool { + match regex { + FlatRegex::Empty | FlatRegex::All | FlatRegex::Epsilon => true, + FlatRegex::Test(test) => test < tests, + FlatRegex::Concat(children) | FlatRegex::Union(children) | FlatRegex::Intersect(children) => + references_before(children@, index), + FlatRegex::Star(child) | FlatRegex::Complement(child) => child < index, + } + } + + pub open spec fn prefix_wf( + head: Seq>, tests: Seq>, regexes: Seq, + ) -> bool { + 1 <= head.len() <= MAX_ARITY + && (forall|i: int| 0 <= i < tests.len() ==> test_wf(head, #[trigger] tests[i], i as nat)) + && (forall|i: int| 0 <= i < regexes.len() ==> + regex_wf(#[trigger] regexes[i], i as nat, tests.len())) + } + + pub open spec fn structural_wf(pair: FlatPair) -> bool { + prefix_wf(pair.head@, pair.tests@, pair.regexes@) && pair.root < pair.regexes@.len() + } + + pub open spec fn event_wf(event: Seq, arity: nat) -> bool { event.len() == arity } + + /// Equality has the same actual/expected orientation as the owned DSL. + pub open spec fn head_matches( + head: Seq>, candidate: Seq, eq: spec_fn(Component, C, C) -> bool, + ) -> bool { + 1 <= head.len() <= MAX_ARITY && event_wf(candidate, head.len()) + && (forall|i: int| 0 <= i < head.len() ==> match #[trigger] head[i] { + FlatHead::Constant(expected) => eq(Component(i as u8), candidate[i], expected), + _ => true, + }) + } + + pub open spec fn test_sem( + tests: Seq>, id: nat, candidate: Seq, event: Seq, + eq: spec_fn(Component, C, C) -> bool, + ) -> bool + decreases id, + { + id < tests.len() && event_wf(event, candidate.len()) && match tests[id as int] { + FlatTest::Bool(value) => value, + FlatTest::Atom { field, term, positive } => { + let expected = match term { + FlatTerm::Constant(value) => value, + FlatTerm::Variable(variable) => candidate[field_index(variable)], + }; + field_index(field) < event.len() + && (match term { FlatTerm::Variable(v) => field_index(v) < candidate.len(), _ => true }) + && positive == eq(field, event[field_index(field)], expected) + }, + FlatTest::And(children) => references_before(children@, id) + && (forall|i: int| 0 <= i < children@.len() ==> + test_sem(tests, children@[i] as nat, candidate, event, eq)), + FlatTest::Or(children) => references_before(children@, id) + && (exists|i: int| 0 <= i < children@.len() + && test_sem(tests, children@[i] as nat, candidate, event, eq)), + } + } + + /// Whole-word languages over concrete event tuples, not numeric graph states. + pub open spec fn flat_lang( + tests: Seq>, regexes: Seq, id: nat, + candidate: Seq, word: Seq>, eq: spec_fn(Component, C, C) -> bool, + ) -> bool + decreases id, + { + id < regexes.len() + && (forall|i: int| 0 <= i < word.len() ==> event_wf(#[trigger] word[i], candidate.len())) + && match regexes[id as int] { + FlatRegex::Empty => false, + FlatRegex::All => true, + FlatRegex::Epsilon => word.len() == 0, + FlatRegex::Test(test) => word.len() == 1 + && test_sem(tests, test as nat, candidate, word[0], eq), + FlatRegex::Union(children) => references_before(children@, id) + && (exists|i: int| 0 <= i < children@.len() + && flat_lang(tests, regexes, children@[i] as nat, candidate, word, eq)), + FlatRegex::Intersect(children) => references_before(children@, id) + && (forall|i: int| 0 <= i < children@.len() ==> + flat_lang(tests, regexes, children@[i] as nat, candidate, word, eq)), + FlatRegex::Concat(children) => references_before(children@, id) + && (exists|parts: Seq>>| parts.len() == children@.len() + && word == parts.flatten() + && (forall|i: int| 0 <= i < children@.len() ==> + flat_lang(tests, regexes, children@[i] as nat, candidate, parts[i], eq))), + FlatRegex::Star(child) => child < id + && (exists|parts: Seq>>| word == parts.flatten() + && (forall|i: int| 0 <= i < parts.len() ==> + flat_lang(tests, regexes, child as nat, candidate, parts[i], eq))), + FlatRegex::Complement(child) => child < id + && !flat_lang(tests, regexes, child as nat, candidate, word, eq), + } + } + + /// Sharing, repeated edges and unreachable suffixes do not change a stored test. + pub proof fn lemma_test_prefix( + tests: Seq>, extended: Seq>, id: nat, + candidate: Seq, event: Seq, eq: spec_fn(Component, C, C) -> bool, + ) + requires id < tests.len(), extended.len() >= tests.len(), + extended.take(tests.len() as int) == tests, + ensures test_sem(tests, id, candidate, event, eq) + == test_sem(extended, id, candidate, event, eq), + decreases id, + { + assert(extended[id as int] == tests[id as int]); + match tests[id as int] { + FlatTest::And(children) | FlatTest::Or(children) => { + if references_before(children@, id) { + assert forall|i: int| 0 <= i < children@.len() implies + test_sem(tests, children@[i] as nat, candidate, event, eq) + == test_sem(extended, children@[i] as nat, candidate, event, eq) by { + lemma_test_prefix(tests, extended, children@[i] as nat, candidate, event, eq); + } + } + }, + _ => {}, + } + } + + /// Appending table nodes preserves every already stored language, without unfolding its DAG. + pub proof fn lemma_lang_prefix( + tests: Seq>, more_tests: Seq>, + regexes: Seq, more_regexes: Seq, id: nat, + candidate: Seq, word: Seq>, eq: spec_fn(Component, C, C) -> bool, + ) + requires id < regexes.len(), more_tests.len() >= tests.len(), + more_tests.take(tests.len() as int) == tests, + more_regexes.len() >= regexes.len(), more_regexes.take(regexes.len() as int) == regexes, + forall|i: int| 0 <= i < regexes.len() ==> + regex_wf(#[trigger] regexes[i], i as nat, tests.len()), + ensures flat_lang(tests, regexes, id, candidate, word, eq) + == flat_lang(more_tests, more_regexes, id, candidate, word, eq), + decreases id, + { + assert(more_regexes[id as int] == regexes[id as int]); + match regexes[id as int] { + FlatRegex::Test(test) => { + if word.len() == 1 { + lemma_test_prefix(tests, more_tests, test as nat, candidate, word[0], eq); + } + }, + FlatRegex::Concat(children) => { + assert forall|parts: Seq>>| parts.len() == children@.len() implies + ((forall|i: int| 0 <= i < children@.len() ==> + flat_lang(tests, regexes, children@[i] as nat, candidate, parts[i], eq)) + == (forall|i: int| 0 <= i < children@.len() ==> + flat_lang(more_tests, more_regexes, children@[i] as nat, candidate, parts[i], eq))) by { + assert forall|i: int| 0 <= i < children@.len() implies + flat_lang(tests, regexes, children@[i] as nat, candidate, parts[i], eq) + == flat_lang(more_tests, more_regexes, children@[i] as nat, candidate, parts[i], eq) by { + lemma_lang_prefix(tests, more_tests, regexes, more_regexes, + children@[i] as nat, candidate, parts[i], eq); + } + } + assert(flat_lang(tests, regexes, id, candidate, word, eq) + == flat_lang(more_tests, more_regexes, id, candidate, word, eq)); + }, + FlatRegex::Union(children) | FlatRegex::Intersect(children) => { + assert forall|i: int| 0 <= i < children@.len() implies + flat_lang(tests, regexes, children@[i] as nat, candidate, word, eq) + == flat_lang(more_tests, more_regexes, children@[i] as nat, candidate, word, eq) by { + lemma_lang_prefix(tests, more_tests, regexes, more_regexes, + children@[i] as nat, candidate, word, eq); + } + assert(flat_lang(tests, regexes, id, candidate, word, eq) + == flat_lang(more_tests, more_regexes, id, candidate, word, eq)); + }, + FlatRegex::Star(child) => { + assert forall|parts: Seq>>| #![trigger parts.len()] + ((forall|i: int| 0 <= i < parts.len() ==> + flat_lang(tests, regexes, child as nat, candidate, parts[i], eq)) + == (forall|i: int| 0 <= i < parts.len() ==> + flat_lang(more_tests, more_regexes, child as nat, candidate, parts[i], eq))) by { + assert forall|i: int| 0 <= i < parts.len() implies + flat_lang(tests, regexes, child as nat, candidate, parts[i], eq) + == flat_lang(more_tests, more_regexes, child as nat, candidate, parts[i], eq) by { + lemma_lang_prefix(tests, more_tests, regexes, more_regexes, + child as nat, candidate, parts[i], eq); + } + } + assert(flat_lang(tests, regexes, id, candidate, word, eq) + == flat_lang(more_tests, more_regexes, id, candidate, word, eq)); + }, + FlatRegex::Complement(child) => { + lemma_lang_prefix(tests, more_tests, regexes, more_regexes, + child as nat, candidate, word, eq); + }, + _ => {}, + } + } + + pub proof fn lemma_empty_operators(empty: Vec, candidate: Seq, word: Seq>, + eq: spec_fn(Component, C, C) -> bool) + requires empty@.len() == 0, + forall|i: int| 0 <= i < word.len() ==> event_wf(#[trigger] word[i], candidate.len()), + ensures + test_sem(seq![FlatTest::And(empty)], 0, candidate, candidate, eq), + !test_sem(seq![FlatTest::Or(empty)], 0, candidate, candidate, eq), + !flat_lang(Seq::>::empty(), seq![FlatRegex::Union(empty)], 0, candidate, word, eq), + flat_lang(Seq::>::empty(), seq![FlatRegex::Intersect(empty)], 0, candidate, word, eq), + flat_lang(Seq::>::empty(), seq![FlatRegex::Concat(empty)], 0, candidate, word, eq) + <==> word.len() == 0, + { + if flat_lang(Seq::>::empty(), seq![FlatRegex::Concat(empty)], 0, candidate, word, eq) { + let parts = choose|parts: Seq>>| parts.len() == 0 && word == parts.flatten(); + assert(parts =~= Seq::empty()); + } + if word.len() == 0 { + let parts: Seq>> = Seq::empty(); + assert(parts.flatten() =~= word); + assert(flat_lang(Seq::>::empty(), seq![FlatRegex::Concat(empty)], 0, candidate, word, eq)); + } + } + + pub proof fn lemma_complement_is_whole_word( + tests: Seq>, regexes: Seq, id: nat, child: u32, + candidate: Seq, word: Seq>, eq: spec_fn(Component, C, C) -> bool, + ) + requires id < regexes.len(), regexes[id as int] == FlatRegex::Complement(child), + child < id, + forall|i: int| 0 <= i < word.len() ==> event_wf(#[trigger] word[i], candidate.len()), + ensures flat_lang(tests, regexes, id, candidate, word, eq) + <==> !flat_lang(tests, regexes, child as nat, candidate, word, eq), + {} + } +} + +#[verus_verify] +#[verus_spec(result => ensures result == verify::references_before(children@, bound as nat))] +fn references_before(children: &[u32], bound: usize) -> bool { + let mut index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant index <= children@.len(), + forall|i: int| 0 <= i < index ==> #[trigger] children@[i] < bound, + decreases children@.len() - index, + ))] + while index < children.len() { + let child = children[index]; + let child = match usize::try_from(child) { + Ok(child) => child, + Err(_) => return false, + }; + if child >= bound { + return false; + } + index += 1; + } + true +} + +#[verus_verify] +#[verus_spec(result => ensures result == verify::test_wf(head@, *test, index as nat))] +fn test_valid(head: &[FlatHead], test: &FlatTest, index: usize) -> bool { + match test { + FlatTest::Bool(_) => true, + FlatTest::Atom { + field, + term: FlatTerm::Variable(variable), + .. + } => { + if field != variable { + return false; + } + matches!(head.get(field.index()), Some(&FlatHead::Bind)) + } + FlatTest::Atom { field, .. } => field.index() < head.len(), + FlatTest::And(children) | FlatTest::Or(children) => references_before(children, index), + } +} + +#[verus_verify] +#[verus_spec(result => ensures result == verify::regex_wf(*regex, index as nat, tests as nat))] +fn regex_valid(regex: &FlatRegex, index: usize, tests: usize) -> bool { + match regex { + FlatRegex::Empty | FlatRegex::All | FlatRegex::Epsilon => true, + FlatRegex::Test(test) => match usize::try_from(*test) { + Ok(test) => test < tests, + Err(_) => false, + }, + FlatRegex::Concat(children) + | FlatRegex::Union(children) + | FlatRegex::Intersect(children) => references_before(children, index), + FlatRegex::Star(child) | FlatRegex::Complement(child) => match usize::try_from(*child) { + Ok(child) => child < index, + Err(_) => false, + }, + } +} + +#[verus_verify] +impl FlatPair { + /// Validate even when no evaluator or runtime feature is enabled. + #[verus_spec(result => ensures result is Ok <==> verify::structural_wf(*self))] + pub fn validate(&self) -> Result<(), String> { + if self.head.is_empty() || self.head.len() > MAX_ARITY { + return Err(String::from( + "history head arity is outside the supported range", + )); + } + let mut index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant index <= self.tests@.len(), + forall|i: int| 0 <= i < index ==> + verify::test_wf(self.head@, #[trigger] self.tests@[i], i as nat), + decreases self.tests@.len() - index, + ))] + while index < self.tests.len() { + let test = &self.tests[index]; + if !test_valid(&self.head, test, index) { + return Err(String::from(match test { + FlatTest::Atom { .. } => "history variable must bind its own head domain", + _ => "history test reference must point to an earlier node", + })); + } + index += 1; + } + index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant index <= self.regexes@.len(), + forall|i: int| 0 <= i < self.tests@.len() ==> + verify::test_wf(self.head@, #[trigger] self.tests@[i], i as nat), + forall|i: int| 0 <= i < index ==> + verify::regex_wf(#[trigger] self.regexes@[i], i as nat, self.tests@.len()), + decreases self.regexes@.len() - index, + ))] + while index < self.regexes.len() { + let regex = &self.regexes[index]; + if !regex_valid(regex, index, self.tests.len()) { + return Err(String::from(match regex { + FlatRegex::Test(_) => "history regex test reference is out of bounds", + _ => "history regex reference must point to an earlier node", + })); + } + index += 1; + } + let root = match usize::try_from(self.root) { + Ok(root) => root, + Err(_) => return Err(String::from("history regex root is out of bounds")), + }; + if root >= self.regexes.len() { + return Err(String::from("history regex root is out of bounds")); + } + Ok(()) + } +} + +/// Checked, topology-preserving construction shared by both source frontends. +#[verus_verify] +pub struct FlatBuilder { + head: Vec>, + tests: Vec>, + regexes: Vec, +} + +#[cfg(verus_keep_ghost)] +verus! { +impl FlatBuilder { + pub closed spec fn head_view(&self) -> Seq> { self.head@ } + pub closed spec fn tests_view(&self) -> Seq> { self.tests@ } + pub closed spec fn regexes_view(&self) -> Seq { self.regexes@ } + pub open spec fn wf(&self) -> bool { + verify::prefix_wf(self.head_view(), self.tests_view(), self.regexes_view()) + } +} +} + +#[verus_verify] +#[verus_spec(result => ensures result is InvalidPolicy)] +fn invalid_source() -> HistoryError { + HistoryError::InvalidPolicy { + path: String::from("$"), + message: "invalid portable history source", + } +} + +#[verus_verify] +impl FlatBuilder { + #[verus_spec(result => requires 1 <= head@.len() <= MAX_ARITY, + ensures result.wf(), result.head_view() == head@, + result.tests_view() == Seq::>::empty(), result.regexes_view() == Seq::::empty())] + pub fn new(head: Vec>) -> Self { + proof! { reveal(FlatBuilder::head_view); reveal(FlatBuilder::tests_view); reveal(FlatBuilder::regexes_view); } + Self { + head, + tests: Vec::new(), + regexes: Vec::new(), + } + } + + #[verus_spec(result => ensures result@ == self.head_view())] + pub fn head(&self) -> &[FlatHead] { + proof! { reveal(FlatBuilder::head_view); } + &self.head + } + + #[verus_spec(result => ensures result@ == self.tests_view())] + pub fn tests(&self) -> &Vec> { + proof! { reveal(FlatBuilder::tests_view); } + &self.tests + } + + #[verus_spec(result => ensures result@ == self.regexes_view())] + pub fn regexes(&self) -> &Vec { + proof! { reveal(FlatBuilder::regexes_view); } + &self.regexes + } + + #[verus_spec(result => requires old(self).wf(), ensures + final(self).wf(), final(self).head_view() == old(self).head_view(), + final(self).regexes_view() == old(self).regexes_view(), + no_invariant_failure(result), + verify::test_wf(old(self).head_view(), node, old(self).tests_view().len()) + ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + verify::test_wf(old(self).head_view(), node, old(self).tests_view().len()) + ==> (result matches Err(error) ==> crate::spec::semantics::resource_error(error)), + match result { + Ok(id) => id == old(self).tests_view().len() + && final(self).tests_view() == old(self).tests_view().push(node), + Err(_) => final(self).tests_view() == old(self).tests_view(), + }, + )] + pub fn test( + &mut self, + node: FlatTest, + limits: &mut L, + world: &mut ObservationWorld, + ) -> Result { + proof! { reveal(FlatBuilder::head_view); reveal(FlatBuilder::tests_view); reveal(FlatBuilder::regexes_view); } + limits.checkpoint()?; + if !test_valid(&self.head, &node, self.tests.len()) { + return Err(invalid_source()); + } + let id = match u32::try_from(self.tests.len()) { + Ok(id) => id, + Err(_) => return Err(HistoryError::graph_index_overflow()), + }; + if world.try_reserve_vec(&mut self.tests, 1).is_err() { + return Err(HistoryError::AllocationFailed); + } + limits.enforce_memory()?; + proof_decl! { let ghost previous = self.tests@; } + self.tests.push(node); + proof! { + assert forall|i: int| 0 <= i < self.tests@.len() implies + verify::test_wf(self.head@, #[trigger] self.tests@[i], i as nat) by { + if i < previous.len() { assert(self.tests@[i] == previous[i]); } + else { assert(i == previous.len()); } + } + assert forall|i: int| 0 <= i < self.regexes@.len() implies + verify::regex_wf(#[trigger] self.regexes@[i], i as nat, self.tests@.len()) by { + assert(verify::regex_wf(self.regexes@[i], i as nat, previous.len())); + } + } + Ok(id) + } + + #[verus_spec(result => requires old(self).wf(), ensures + final(self).wf(), final(self).head_view() == old(self).head_view(), + final(self).tests_view() == old(self).tests_view(), + no_invariant_failure(result), + verify::regex_wf(node, old(self).regexes_view().len(), old(self).tests_view().len()) + ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + verify::regex_wf(node, old(self).regexes_view().len(), old(self).tests_view().len()) + ==> (result matches Err(error) ==> crate::spec::semantics::resource_error(error)), + match result { + Ok(id) => id == old(self).regexes_view().len() + && final(self).regexes_view() == old(self).regexes_view().push(node), + Err(_) => final(self).regexes_view() == old(self).regexes_view(), + }, + )] + pub fn regex( + &mut self, + node: FlatRegex, + limits: &mut L, + world: &mut ObservationWorld, + ) -> Result { + proof! { reveal(FlatBuilder::head_view); reveal(FlatBuilder::tests_view); reveal(FlatBuilder::regexes_view); } + limits.checkpoint()?; + if !regex_valid(&node, self.regexes.len(), self.tests.len()) { + return Err(invalid_source()); + } + let id = match u32::try_from(self.regexes.len()) { + Ok(id) => id, + Err(_) => return Err(HistoryError::graph_index_overflow()), + }; + if world.try_reserve_vec(&mut self.regexes, 1).is_err() { + return Err(HistoryError::AllocationFailed); + } + limits.enforce_memory()?; + proof_decl! { let ghost previous = self.regexes@; } + self.regexes.push(node); + proof! { + assert forall|i: int| 0 <= i < self.regexes@.len() implies + verify::regex_wf(#[trigger] self.regexes@[i], i as nat, self.tests@.len()) by { + if i < previous.len() { assert(self.regexes@[i] == previous[i]); } + else { assert(i == previous.len()); } + } + } + Ok(id) + } + + #[verus_spec(result => requires self.wf(), ensures + (result is Ok) <==> root < self.regexes_view().len(), + no_invariant_failure(result), + root < self.regexes_view().len() + ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + root < self.regexes_view().len() + ==> (result matches Err(error) ==> crate::spec::semantics::resource_error(error)), + match result { + Ok(pair) => verify::structural_wf(pair) && pair.head@ == self.head_view() + && pair.tests@ == self.tests_view() && pair.regexes@ == self.regexes_view() + && pair.root == root, + Err(_) => true, + }, + )] + pub fn finish(self, root: u32) -> Result, HistoryError> { + proof! { reveal(FlatBuilder::head_view); reveal(FlatBuilder::tests_view); reveal(FlatBuilder::regexes_view); } + let pair = FlatPair { + head: self.head, + tests: self.tests, + regexes: self.regexes, + root, + }; + if pair.validate().is_err() { + return Err(invalid_source()); + } + Ok(pair) + } +} diff --git a/src/junco-core/src/flatten.rs b/src/junco-core/src/flatten.rs new file mode 100644 index 000000000..c7b3a6ca7 --- /dev/null +++ b/src/junco-core/src/flatten.rs @@ -0,0 +1,996 @@ +//! Fallible, iterative lowering of the owned DSL into the canonical portable tables. + +use crate::errors::{CompileError, HistoryError}; +use crate::flat::{FlatBuilder, FlatHead, FlatPair, FlatRegex, FlatRule, FlatTerm, FlatTest}; +use crate::limits::Limits; +use crate::observation::ObservationWorld; +use crate::scope::VariableScope; +use alloc::vec::Vec; +use history_syntax::syntax::{ + AtomPattern, Comparison, Component, ComponentPattern, Head, RegexExpr, Rule, RuleMode, TestExpr, +}; +use history_syntax::{Arity, Event}; +use vstd::prelude::*; + +#[cfg(verus_keep_ghost)] +use crate::verify::flatten::*; +#[cfg(verus_keep_ghost)] +use crate::verify::history_specs::{no_invariant_compile_failure, no_invariant_failure}; +#[cfg(verus_keep_ghost)] +use history_syntax::event::specs::EventSpec; +#[cfg(verus_keep_ghost)] +use history_syntax::spec::events::arity; + +#[cfg(verus_keep_ghost)] +verus! { + broadcast use {vstd::std_specs::vec::group_vec_axioms, vstd::seq::group_seq_lemmas}; +} + +// Only borrowed source nodes enter the work stack: every failure leaves caller-owned trees intact. +#[verus_verify] +pub(crate) enum Work<'a, E: Event> { + Regex(&'a RegexExpr), + Test(&'a TestExpr), + FinishRegex(&'a RegexExpr, usize), + FinishTest(&'a TestExpr, usize), +} + +#[verus_verify] +#[verus_spec(result => ensures + result is Ok ==> final(values)@ == old(values)@.push(value), + result is Err ==> final(values)@ == old(values)@, + no_invariant_failure(result), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + result matches Err(error) ==> crate::spec::semantics::resource_error(error), +)] +fn push( + values: &mut Vec, + value: T, + limits: &mut L, + world: &mut ObservationWorld, +) -> Result<(), HistoryError> { + match world.try_reserve_vec(values, 1) { + Ok(()) => {} + Err(_) => return Err(HistoryError::AllocationFailed), + } + limits.enforce_memory()?; + values.push(value); + Ok(()) +} + +#[verus_verify] +#[verus_spec(result => ensures + start <= old(values)@.len() ==> no_invariant_failure(result), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + start <= old(values)@.len() ==> (result matches Err(error) ==> crate::spec::semantics::resource_error(error)), + match result { + Ok(children) => start <= old(values)@.len() + && children@ == old(values)@.subrange(start as int, old(values)@.len() as int) + && final(values)@ == old(values)@.subrange(0, start as int), + Err(_) => final(values)@ == old(values)@, + }, +)] +fn take_children( + values: &mut Vec, + start: usize, + limits: &mut L, + world: &mut ObservationWorld, +) -> Result, HistoryError> { + if start > values.len() { + return Err(HistoryError::invariant("invalid source operand range")); + } + let count = values.len() - start; + let mut children = Vec::new(); + match world.try_reserve_vec_exact(&mut children, count) { + Ok(()) => {} + Err(_) => return Err(HistoryError::AllocationFailed), + } + limits.enforce_memory()?; + let mut index = start; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant start <= index <= values@.len(), + children@ == values@.subrange(start as int, index as int), + decreases values@.len() - index, + ))] + while index < values.len() { + limits.checkpoint()?; + children.push(values[index]); + index += 1; + } + values.truncate(start); + Ok(children) +} + +#[verus_verify] +#[verus_spec(result => requires + old(scope).wf(), old(scope).arity_spec() == arity::(), + forall|i: int| 0 <= i < arity::() ==> #[trigger] old(scope).name_spec(Component(i as u8)) is None, + ensures result matches Ok(flat) ==> + head_represents::(flat@, head@) && crate::spec::semantics::head_scoped(head@) + && scope_matches::(*final(scope), head@) + && (E::obeys_projection_spec() ==> head_coordinates_wf::(head@)), + crate::spec::semantics::head_scoped(head@) ==> + !(result matches Err(CompileError::VariableComponentConflict { .. })), + !(result matches Err(CompileError::UnboundVariable { .. })), + E::obeys_projection_spec() && head_coordinates_wf::(head@) + && crate::spec::semantics::head_scoped(head@) ==> result is Ok || result matches Err(CompileError::Runtime(_)), + no_invariant_compile_failure(result), + !(result matches Err(CompileError::Runtime(HistoryError::InvalidPolicy { .. }))), + result matches Err(CompileError::Runtime(error)) ==> crate::spec::semantics::resource_error(error), +)] +fn flatten_head<'a, E: Event, L: Limits>( + head: &'a Head, + scope: &mut VariableScope<'a>, + limits: &mut L, + world: &mut ObservationWorld, +) -> Result>, CompileError> { + let arity = E::Arity::value(); + let slots = head.slots(); + if slots.len() != arity { + return Err(CompileError::HeadArity { + expected: arity, + found: slots.len(), + }); + } + let mut flat = Vec::new(); + match world.try_reserve_vec_exact(&mut flat, arity) { + Ok(()) => {} + Err(_) => return Err(HistoryError::AllocationFailed.into()), + } + limits.enforce_memory().map_err(HistoryError::from)?; + let mut index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant index <= arity, arity == history_syntax::spec::events::arity::(), + 1 <= arity <= history_syntax::MAX_ARITY, + head@.len() == arity, slots@.len() == arity, + forall|i: int| 0 <= i < arity ==> slots@[i]@ == head@[i], + flat@.len() == index, scope.wf(), scope.arity_spec() == arity, + forall|i: int| 0 <= i < index ==> head_slot_represents(flat@[i], head@[i]), + crate::spec::semantics::head_scoped(head@.take(index as int)), + forall|i: int| 0 <= i < arity ==> match #[trigger] scope.name_spec(Component(i as u8)) { + Some(name) => i < index && crate::spec::semantics::pattern_name(head@[i]) == Some(name@), + None => i >= index || crate::spec::semantics::pattern_name(head@[i]) is None, + }, + E::obeys_projection_spec() ==> forall|i: int| 0 <= i < index ==> match #[trigger] head@[i] { + history_syntax::spec::events::PatternView::Constant(value) => E::coordinate_spec(value) == i, + _ => true, + }, + decreases arity - index, + ))] + while index < arity { + limits.checkpoint().map_err(HistoryError::from)?; + let component = Component::new(index); + proof_decl! { let ghost previous_scope = *scope; } + let slot = match &slots[index] { + ComponentPattern::Constant(value) => { + let coordinate = E::coordinate(*value); + if coordinate != index { + return Err(CompileError::ComponentCoordinate { + component: index, + coordinate, + }); + } + FlatHead::Constant(*value) + } + ComponentPattern::Variable(name) => { + proof! { + if crate::spec::semantics::head_scoped(head@) { + assert forall|i: int| 0 <= i < scope.arity_spec() && i != component.0 implies + !(#[trigger] scope.has_name(Component(i as u8), name@)) by { + if i < index { + assert(crate::spec::semantics::distinct_names(head@[i], head@[index as int])); + } + } + } + } + scope.bind(component, name.as_str())?; + proof! { + assert forall|i: int| 0 <= i < index implies + crate::spec::semantics::distinct_names(head@[i], head@[index as int]) by { + assert(!previous_scope.has_name(Component(i as u8), name@)); + } + } + FlatHead::Bind + } + }; + proof! { + assert forall|i: int, j: int| 0 <= i < j < index + 1 implies + crate::spec::semantics::distinct_names(head@[i], head@[j]) by { + if j < index { + assert(head@.take(index as int)[i] == head@[i]); + assert(head@.take(index as int)[j] == head@[j]); + } else { + assert(j == index); + } + } + } + flat.push(slot); + index += 1; + } + proof! { assert(head@.take(index as int) =~= head@); } + Ok(flat) +} + +#[verus_verify] +#[verus_spec(result => requires scope.wf(), scope.arity_spec() == arity::(), + ensures result matches Ok((field, term)) ==> + (forall|head| scope_matches::(*scope, head) ==> atom_term_represents::(field, term, atom@, head)) + && (E::obeys_projection_spec() ==> atom_coordinates_wf::(atom@)), + no_invariant_compile_failure(result), + atom@.component < scope.arity_spec() ==> + !(result matches Err(CompileError::Runtime(HistoryError::InvalidPolicy { .. }))), + forall|head| scope_matches::(*scope, head) && crate::spec::semantics::atom_scoped(atom@, head) ==> + !(result matches Err(CompileError::VariableComponentConflict { .. })) + && !(result matches Err(CompileError::UnboundVariable { .. })), + E::obeys_projection_spec() && atom_coordinates_wf::(atom@) ==> + (forall|head| scope_matches::(*scope, head) && crate::spec::semantics::atom_scoped(atom@, head) + ==> result is Ok), +)] +fn flatten_atom( + atom: &AtomPattern, + scope: &VariableScope<'_>, +) -> Result<(Component, FlatTerm), CompileError> { + let component = atom.component; + let index = component.index(); + if index >= scope.arity() { + return Err(HistoryError::invalid_policy( + "atom.component", + "component index is outside the event arity", + ) + .into()); + } + let term = match &atom.pattern { + ComponentPattern::Constant(value) => { + let coordinate = E::coordinate(*value); + if coordinate != index { + return Err(CompileError::ComponentCoordinate { + component: index, + coordinate, + }); + } + FlatTerm::Constant(*value) + } + ComponentPattern::Variable(name) => { + FlatTerm::Variable(scope.resolve(component, name.as_str())?) + } + }; + Ok((component, term)) +} + +#[verus_verify] +#[verus_spec(result => ensures result is Ok ==> forall|ts, rs| + run_work::(final(work)@, ts, rs) == run_work::(old(work)@, ts, + rs + regex_views::(children@)), + result is Ok ==> work_cost::(final(work)@) == work_cost::(old(work)@) + + regex_forest_cost::(regex_views::(children@)), + no_invariant_failure(result), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + result matches Err(error) ==> crate::spec::semantics::resource_error(error), + result is Ok ==> forall|head| work_scoped::(old(work)@, head) + && (forall|i: int| 0 <= i < children@.len() + ==> crate::spec::semantics::regex_scoped(children@[i]@, head)) + ==> work_scoped::(final(work)@, head), + result is Ok ==> forall|tail| work_within::(old(work)@, tail) + && (forall|i: int| 0 <= i < children@.len() ==> regex_constants_within(children@[i]@, tail)) + ==> work_within::(final(work)@, tail), +)] +fn schedule_regexes<'a, E: Event, L: Limits>( + work: &mut Vec>, + children: &'a [RegexExpr], + limits: &mut L, + world: &mut ObservationWorld, +) -> Result<(), HistoryError> { + proof_decl! { let ghost before = work@; } + let mut index = children.len(); + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant index <= children@.len(), + forall|ts, rs| run_work::(work@, ts, rs) + == run_work::(before, ts, rs + regex_views::(children@.subrange(index as int, children@.len() as int))), + work_cost::(work@) == work_cost::(before) + + regex_forest_cost::(regex_views::(children@.subrange(index as int, children@.len() as int))), + forall|head| work_scoped::(before, head) + && (forall|i: int| 0 <= i < children@.len() + ==> crate::spec::semantics::regex_scoped(children@[i]@, head)) + ==> work_scoped::(work@, head), + forall|tail| work_within::(before, tail) + && (forall|i: int| 0 <= i < children@.len() ==> regex_constants_within(children@[i]@, tail)) + ==> work_within::(work@, tail), + decreases index, + ))] + while index > 0 { + limits.checkpoint()?; + proof_decl! { let ghost previous = work@; } + index -= 1; + push(work, Work::Regex(&children[index]), limits, world)?; + proof! { + assert(work@.drop_last() =~= previous); + assert forall|head| work_scoped::(before, head) + && (forall|i: int| 0 <= i < children@.len() + ==> crate::spec::semantics::regex_scoped(children@[i]@, head)) + implies work_scoped::(work@, head) by { + lemma_work_scoped_push::(previous, Work::Regex(&children[index as int]), head); + } + assert forall|tail| work_within::(before, tail) + && (forall|i: int| 0 <= i < children@.len() ==> regex_constants_within(children@[i]@, tail)) + implies work_within::(work@, tail) by { + lemma_work_within_push::(previous, Work::Regex(&children[index as int]), tail); + } + assert(match work@.last() { Work::Regex(source) => source@ == children@[index as int]@, _ => false }); + reveal_with_fuel(regex_forest_cost, 2); + let suffix = regex_views::(children@.subrange(index as int + 1, children@.len() as int)); + assert(regex_views::(children@.subrange(index as int, children@.len() as int)) + =~= seq![children@[index as int]@] + suffix); + lemma_regex_forest_cost_append::(seq![children@[index as int]@], suffix); + reveal_with_fuel(run_work, 2); + reveal_with_fuel(work_cost, 2); + assert forall|ts, rs| run_work::(work@, ts, rs) + == run_work::(before, ts, rs + regex_views::(children@.subrange(index as int, children@.len() as int))) by { + assert(run_work::(work@, ts, rs) + == run_work::(previous, ts, rs.push(children@[index as int]@))); + assert(rs.push(children@[index as int]@) + suffix + =~= rs + regex_views::(children@.subrange(index as int, children@.len() as int))); + } + assert(work_cost::(work@) == work_cost::(previous) + regex_cost::(children@[index as int]@)); + } + } + proof! { assert(children@.subrange(0, children@.len() as int) =~= children@); } + Ok(()) +} + +#[verus_verify] +#[verus_spec(result => ensures result is Ok ==> forall|ts, rs| + run_work::(final(work)@, ts, rs) == run_work::(old(work)@, + ts + test_views::(children@), rs), + result is Ok ==> work_cost::(final(work)@) == work_cost::(old(work)@) + + test_forest_cost::(test_views::(children@)), + no_invariant_failure(result), + !(result matches Err(HistoryError::InvalidPolicy { .. })), + result matches Err(error) ==> crate::spec::semantics::resource_error(error), + result is Ok ==> forall|head| work_scoped::(old(work)@, head) + && (forall|i: int| 0 <= i < children@.len() + ==> crate::spec::semantics::test_scoped(children@[i]@, head)) + ==> work_scoped::(final(work)@, head), + result is Ok ==> forall|tail| work_within::(old(work)@, tail) + && (forall|i: int| 0 <= i < children@.len() ==> test_constants_within(children@[i]@, tail)) + ==> work_within::(final(work)@, tail), +)] +fn schedule_tests<'a, E: Event, L: Limits>( + work: &mut Vec>, + children: &'a [TestExpr], + limits: &mut L, + world: &mut ObservationWorld, +) -> Result<(), HistoryError> { + proof_decl! { let ghost before = work@; } + let mut index = children.len(); + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant index <= children@.len(), + forall|ts, rs| run_work::(work@, ts, rs) + == run_work::(before, ts + test_views::(children@.subrange(index as int, children@.len() as int)), rs), + work_cost::(work@) == work_cost::(before) + + test_forest_cost::(test_views::(children@.subrange(index as int, children@.len() as int))), + forall|head| work_scoped::(before, head) + && (forall|i: int| 0 <= i < children@.len() + ==> crate::spec::semantics::test_scoped(children@[i]@, head)) + ==> work_scoped::(work@, head), + forall|tail| work_within::(before, tail) + && (forall|i: int| 0 <= i < children@.len() ==> test_constants_within(children@[i]@, tail)) + ==> work_within::(work@, tail), + decreases index, + ))] + while index > 0 { + limits.checkpoint()?; + proof_decl! { let ghost previous = work@; } + index -= 1; + push(work, Work::Test(&children[index]), limits, world)?; + proof! { + assert(work@.drop_last() =~= previous); + assert forall|head| work_scoped::(before, head) + && (forall|i: int| 0 <= i < children@.len() + ==> crate::spec::semantics::test_scoped(children@[i]@, head)) + implies work_scoped::(work@, head) by { + lemma_work_scoped_push::(previous, Work::Test(&children[index as int]), head); + } + assert forall|tail| work_within::(before, tail) + && (forall|i: int| 0 <= i < children@.len() ==> test_constants_within(children@[i]@, tail)) + implies work_within::(work@, tail) by { + lemma_work_within_push::(previous, Work::Test(&children[index as int]), tail); + } + assert(match work@.last() { Work::Test(source) => source@ == children@[index as int]@, _ => false }); + reveal_with_fuel(test_forest_cost, 2); + let suffix = test_views::(children@.subrange(index as int + 1, children@.len() as int)); + assert(test_views::(children@.subrange(index as int, children@.len() as int)) + =~= seq![children@[index as int]@] + suffix); + lemma_test_forest_cost_append::(seq![children@[index as int]@], suffix); + reveal_with_fuel(run_work, 2); + reveal_with_fuel(work_cost, 2); + assert forall|ts, rs| run_work::(work@, ts, rs) + == run_work::(before, ts + test_views::(children@.subrange(index as int, children@.len() as int)), rs) by { + assert(run_work::(work@, ts, rs) + == run_work::(previous, ts.push(children@[index as int]@), rs)); + assert(ts.push(children@[index as int]@) + suffix + =~= ts + test_views::(children@.subrange(index as int, children@.len() as int))); + } + assert(work_cost::(work@) == work_cost::(previous) + test_cost::(children@[index as int]@)); + } + } + proof! { assert(children@.subrange(0, children@.len() as int) =~= children@); } + Ok(()) +} + +/// Lowers a rule through the borrowed-source flattener. +#[verus_verify] +#[verus_spec(result => ensures + no_invariant_compile_failure(result), + crate::spec::semantics::regex_scoped(rule.tail@, rule.head@) ==> + !(result matches Err(CompileError::Runtime(HistoryError::InvalidPolicy { .. }))), + crate::spec::semantics::head_scoped(rule.head@) + && crate::spec::semantics::regex_scoped(rule.tail@, rule.head@) + ==> !(result matches Err(CompileError::VariableComponentConflict { .. })) + && !(result matches Err(CompileError::UnboundVariable { .. })), + result matches Ok(flat) ==> flattened::(*rule, flat) + && (E::obeys_projection_spec() ==> crate::verify::encoding::constants_in_domain(flat.source, component_domain::())), + result matches Ok(flat) ==> flat.source.tests@.len() + flat.source.regexes@.len() + <= regex_cost::(rule.tail@), + crate::spec::hypotheses::event_obligations::() && crate::spec::semantics::rule_wf(rule@) + && rule@.head.len() == arity::() && crate::spec::semantics::rule_constants_tagged::(rule@) + ==> (result is Ok || (result matches Err(CompileError::Runtime(error)) && crate::spec::semantics::resource_error(error))), +)] +pub fn flatten_rule( + rule: &Rule, + limits: &mut L, + world: &mut ObservationWorld, +) -> Result, CompileError> { + flatten_rule_parts(rule.mode, &rule.head, &rule.tail, limits, world) +} + +/// Lowers borrowed syntax in source order without constructing an executable graph. +/// Resource failures propagate; well-scoped inputs cannot produce scope diagnostics. +/// The continuation invariant excludes internal stack and operand-guard failures. +#[verus_verify] +#[cfg_attr(verus_keep_ghost, verifier::spinoff_prover)] +#[cfg_attr(verus_keep_ghost, verifier::rlimit(90))] +#[verus_spec(result => ensures + no_invariant_compile_failure(result), + crate::spec::semantics::regex_scoped(source_tail@, source_head@) ==> + !(result matches Err(CompileError::Runtime(HistoryError::InvalidPolicy { .. }))), + crate::spec::semantics::head_scoped(source_head@) + && crate::spec::semantics::regex_scoped(source_tail@, source_head@) + ==> !(result matches Err(CompileError::VariableComponentConflict { .. })) + && !(result matches Err(CompileError::UnboundVariable { .. })), + result matches Ok(flat) ==> flattened::(Rule { mode, head: *source_head, tail: *source_tail }, flat) + && (E::obeys_projection_spec() ==> crate::verify::encoding::constants_in_domain(flat.source, component_domain::())), + result matches Ok(flat) ==> flat.source.tests@.len() + flat.source.regexes@.len() + <= regex_cost::(source_tail@), + crate::spec::hypotheses::event_obligations::() + && crate::spec::semantics::rule_wf(Rule { mode, head: *source_head, tail: *source_tail }@) + && source_head@.len() == arity::() + && crate::spec::semantics::rule_constants_tagged::(Rule { mode, head: *source_head, tail: *source_tail }@) + ==> (result is Ok || (result matches Err(CompileError::Runtime(error)) && crate::spec::semantics::resource_error(error))), +)] +pub fn flatten_rule_parts( + mode: RuleMode, + source_head: &Head, + source_tail: &RegexExpr, + limits: &mut L, + world: &mut ObservationWorld, +) -> Result, CompileError> { + proof_decl! { let ghost rule = Rule { mode, head: *source_head, tail: *source_tail }; } + limits.checkpoint().map_err(HistoryError::from)?; + let mut scope = VariableScope::new(E::Arity::value()); + proof! { + if crate::spec::hypotheses::event_obligations::() && crate::spec::semantics::rule_wf(rule@) + && rule@.head.len() == arity::() && crate::spec::semantics::rule_constants_tagged::(rule@) { + lemma_rule_head_coordinates::(rule@); + } + } + let head = flatten_head(source_head, &mut scope, limits, world)?; + let mut builder = FlatBuilder::new(head); + let mut work = Vec::new(); + let mut tests: Vec = Vec::new(); + let mut regexes: Vec = Vec::new(); + proof_decl! { + let ghost mut test_sources = Seq::empty(); + let ghost mut regex_sources = Seq::empty(); + } + push(&mut work, Work::Regex(source_tail), limits, world)?; + proof! { + reveal_with_fuel(work_cost, 2); + assert(work_cost::(work@) == regex_cost::(rule.tail@)); + assert(run_work::(work@, test_sources, regex_sources) == Some((Seq::empty(), seq![rule.tail@]))) by { + reveal_with_fuel(run_work, 2); + } + if crate::spec::semantics::regex_scoped(rule.tail@, rule.head@) { + assert(work_scoped::(work@, rule.head@)) by { reveal(work_scoped); } + } + assert(work_within::(work@, rule.tail@)) by { reveal(work_within); } + } + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant builder.wf(), + rule.head@ == source_head@, rule.tail@ == source_tail@, + rule == (Rule { mode, head: *source_head, tail: *source_tail }), + head_represents::(builder.head_view(), rule.head@), + crate::spec::semantics::head_scoped(rule.head@), + scope_matches::(scope, rule.head@), + crate::spec::semantics::regex_scoped(rule.tail@, rule.head@) + ==> work_scoped::(work@, rule.head@), + E::obeys_projection_spec() ==> forall|i: int| 0 <= i < builder.head_view().len() + ==> crate::verify::encoding::head_in_domain( + builder.head_view()[i], crate::verify::encoding::field_at(i), component_domain::()), + E::obeys_projection_spec() ==> forall|i: int| 0 <= i < builder.tests_view().len() + ==> crate::verify::encoding::test_in_domain(builder.tests_view()[i], component_domain::()), + work_within::(work@, rule.tail@), + forall|i: int| 0 <= i < builder.tests_view().len() + ==> flat_test_within(#[trigger] builder.tests_view()[i], rule.tail@), + result_stacks::(builder.tests_view(), builder.regexes_view(), tests@, regexes@, + test_sources, regex_sources, rule.head@), + run_work::(work@, test_sources, regex_sources) == Some((Seq::empty(), seq![rule.tail@])), + builder.tests_view().len() + builder.regexes_view().len() + work_cost::(work@) + <= regex_cost::(rule.tail@), + decreases work_cost::(work@), + ))] + while !work.is_empty() { + limits.checkpoint().map_err(HistoryError::from)?; + proof_decl! { + let ghost old_tests = builder.tests_view(); + let ghost old_regexes = builder.regexes_view(); + let ghost old_work = work@; + let ghost old_test_ids = tests@; + let ghost old_regex_ids = regexes@; + let ghost old_test_sources = test_sources; + let ghost old_regex_sources = regex_sources; + } + let task = match work.pop() { + Some(task) => task, + None => return Err(HistoryError::invariant("missing source work").into()), + }; + proof! { + assert(old_work =~= work@.push(task)); + assert(old_work.drop_last() =~= work@); + lemma_run_work_step::(old_work, test_sources, regex_sources); + if crate::spec::semantics::regex_scoped(rule.tail@, rule.head@) { + lemma_work_scoped_pop::(old_work, rule.head@); + assert(work_scoped::(work@, rule.head@)); + } + lemma_work_within_pop::(old_work, rule.tail@); + reveal_with_fuel(work_cost, 2); + reveal_with_fuel(history_syntax::spec::events::regex_view, 2); + reveal_with_fuel(history_syntax::spec::events::test_view, 2); + reveal(regex_cost); + reveal(test_cost); + } + match task { + Work::Regex(regex) => match regex { + RegexExpr::Empty | RegexExpr::All | RegexExpr::Epsilon => { + let node = match regex { + RegexExpr::Empty => FlatRegex::Empty, + RegexExpr::All => FlatRegex::All, + _ => FlatRegex::Epsilon, + }; + let id = builder.regex(node, limits, world)?; + proof! { + assert(builder.tests_view().take(old_tests.len() as int) =~= old_tests); + assert(builder.regexes_view().take(old_regexes.len() as int) =~= old_regexes); + lemma_stack_extension::(old_tests, builder.tests_view(), old_regexes, builder.regexes_view(), + old_test_ids, old_regex_ids, old_test_sources, old_regex_sources, rule.head@); + assert(regex_represents::(builder.tests_view(), builder.regexes_view(), id as nat, regex@, rule.head@)); + } + push(&mut regexes, id, limits, world)?; + proof! { regex_sources = regex_sources.push(regex@); } + } + RegexExpr::Test(test) => { + proof! { + lemma_visit_test_regex::(work@, regex, test, tests.len(), test_sources, regex_sources, rule.head@, rule.tail@); + lemma_work_cost_push::(work@, Work::FinishRegex(regex, tests.len())); + lemma_work_cost_push::(work@.push(Work::FinishRegex(regex, tests.len())), Work::Test(test)); + } + push( + &mut work, + Work::FinishRegex(regex, tests.len()), + limits, + world, + )?; + push(&mut work, Work::Test(test), limits, world)?; + proof! { + assert(run_work::(work@, test_sources, regex_sources) == Some((Seq::empty(), seq![rule.tail@]))); + assert(work_cost::(work@) < work_cost::(old_work)); + } + } + RegexExpr::Star(child) | RegexExpr::Not(child) => { + proof! { + lemma_visit_unary_regex::(work@, regex, child, regexes.len(), test_sources, regex_sources, rule.head@, rule.tail@); + lemma_work_cost_push::(work@, Work::FinishRegex(regex, regexes.len())); + lemma_work_cost_push::(work@.push(Work::FinishRegex(regex, regexes.len())), Work::Regex(child)); + } + push( + &mut work, + Work::FinishRegex(regex, regexes.len()), + limits, + world, + )?; + push(&mut work, Work::Regex(child), limits, world)?; + proof! { + assert(run_work::(work@, test_sources, regex_sources) == Some((Seq::empty(), seq![rule.tail@]))); + assert(work_cost::(work@) < work_cost::(old_work)); + } + } + RegexExpr::Concat(children) + | RegexExpr::Union(children) + | RegexExpr::Intersect(children) => { + proof! { match regex@ { + history_syntax::spec::events::RegexView::Concat(items) | history_syntax::spec::events::RegexView::Union(items) + | history_syntax::spec::events::RegexView::Intersect(items) => assert(items =~= regex_views::(children@)), + _ => {}, + } } + proof! { + lemma_finish_many_regex::(work@, regex, regexes.len(), test_sources, regex_sources, regex_views::(children@), rule.head@, rule.tail@); + if crate::spec::semantics::regex_scoped(rule.tail@, rule.head@) { + assert forall|i: int| 0 <= i < children@.len() implies + crate::spec::semantics::regex_scoped(children@[i]@, rule.head@) by { + assert(regex_views::(children@)[i] == children@[i]@); + } + } + assert forall|i: int| 0 <= i < children@.len() implies + regex_constants_within(children@[i]@, rule.tail@) by { + assert(regex_views::(children@)[i] == children@[i]@); + } + lemma_work_cost_push::(work@, Work::FinishRegex(regex, regexes.len())); + assert(regex_cost::(regex@) == 2 + regex_forest_cost::(regex_views::(children@))); + } + push( + &mut work, + Work::FinishRegex(regex, regexes.len()), + limits, + world, + )?; + schedule_regexes(&mut work, children, limits, world)?; + proof! { + assert(run_work::(work@, test_sources, regex_sources) == Some((Seq::empty(), seq![rule.tail@]))); + assert(work_cost::(work@) < work_cost::(old_work)); + } + } + }, + Work::Test(test) => match test { + TestExpr::True | TestExpr::False | TestExpr::Atom { .. } => { + let node = match test { + TestExpr::True => FlatTest::Bool(true), + TestExpr::False => FlatTest::Bool(false), + TestExpr::Atom { + comparison, + pattern, + } => { + proof! { + if crate::spec::semantics::regex_scoped(rule.tail@, rule.head@) { + assert(crate::spec::semantics::atom_scoped(pattern@, rule.head@)) by { + reveal_with_fuel(crate::spec::semantics::test_scoped, 1); + } + } + } + proof! { + if crate::spec::hypotheses::event_obligations::() && crate::spec::semantics::rule_wf(rule@) + && rule@.head.len() == arity::() && crate::spec::semantics::rule_constants_tagged::(rule@) { + assert(test_constants_within(test@, rule.tail@)); + assert(atom_coordinates_wf::(pattern@)) by { + if let history_syntax::spec::events::PatternView::Constant(value) = pattern@.pattern { + let i = pattern@.component as int; + assert(crate::spec::questions::test_constant_at(test@, i).contains(value)); + assert(crate::spec::questions::regex_constant_at(rule.tail@, i).contains(value)); + assert(crate::spec::questions::rule_constants(rule@)[i].contains(value)); + } + } + } + } + let atom_result = flatten_atom(pattern, &scope); + proof! { + if crate::spec::hypotheses::event_obligations::() + && crate::spec::semantics::rule_wf(Rule { mode, head: *source_head, tail: *source_tail }@) + && source_head@.len() == arity::() + && crate::spec::semantics::rule_constants_tagged::(Rule { mode, head: *source_head, tail: *source_tail }@) { + assert(scope_matches::(scope, rule.head@)); + assert(crate::spec::semantics::atom_scoped(pattern@, rule.head@)); + assert(atom_result is Ok); + } + } + let (field, term) = atom_result?; + FlatTest::Atom { + field, + term, + positive: matches!(comparison, Comparison::Eq), + } + } + _ => return Err(HistoryError::invariant("invalid source test leaf").into()), + }; + proof! { + assert(crate::flat::verify::test_wf(builder.head_view(), node, builder.tests_view().len())); + assert(E::obeys_projection_spec() ==> crate::verify::encoding::test_in_domain(node, component_domain::())); + if let TestExpr::Atom { pattern, .. } = test { + if let FlatTest::Atom { field, term: FlatTerm::Constant(value), .. } = &node { + assert(atom_term_represents::(*field, FlatTerm::Constant(*value), pattern@, rule.head@)); + assert(crate::spec::questions::test_constant_at(test@, field.0 as int).contains(*value)); + } + } + assert(flat_test_within(node, rule.tail@)); + } + let id = builder.test(node, limits, world)?; + proof! { + assert(builder.tests_view().take(old_tests.len() as int) =~= old_tests); + assert(builder.regexes_view().take(old_regexes.len() as int) =~= old_regexes); + lemma_stack_extension::(old_tests, builder.tests_view(), old_regexes, builder.regexes_view(), + old_test_ids, old_regex_ids, old_test_sources, old_regex_sources, rule.head@); + assert(test_represents::(builder.tests_view(), id as nat, test@, rule.head@)); + } + push(&mut tests, id, limits, world)?; + proof! { test_sources = test_sources.push(test@); } + } + TestExpr::And(children) | TestExpr::Or(children) => { + proof! { match test@ { + history_syntax::spec::events::TestView::And(items) | history_syntax::spec::events::TestView::Or(items) => + assert(items =~= test_views::(children@)), + _ => {}, + } } + proof! { + assert(test@ == history_syntax::spec::events::TestView::And(test_views::(children@)) + || test@ == history_syntax::spec::events::TestView::Or(test_views::(children@))); + lemma_finish_test::(work@, test, tests.len(), test_sources, regex_sources, test_views::(children@), rule.head@, rule.tail@); + if crate::spec::semantics::regex_scoped(rule.tail@, rule.head@) { + assert forall|i: int| 0 <= i < children@.len() implies + crate::spec::semantics::test_scoped(children@[i]@, rule.head@) by { + assert(test_views::(children@)[i] == children@[i]@); + } + } + assert forall|i: int| 0 <= i < children@.len() implies + test_constants_within(children@[i]@, rule.tail@) by { + assert(test_views::(children@)[i] == children@[i]@); + } + assert(test_cost::(test@) == 2 + test_forest_cost::(test_views::(children@))); + } + proof_decl! { let ghost prefix = work@; } + proof! { lemma_work_cost_push::(prefix, Work::FinishTest(test, tests.len())); } + proof! { assert(work_cost::(old_work) == work_cost::(prefix) + test_cost::(test@)); } + push( + &mut work, + Work::FinishTest(test, tests.len()), + limits, + world, + )?; + proof_decl! { let ghost finish = work@; } + proof! { + assert(finish.drop_last() =~= prefix); + assert(finish.last() is FinishTest); + assert(work_cost::(finish) == work_cost::(prefix) + 1); + } + schedule_tests(&mut work, children, limits, world)?; + proof! { + assert(run_work::(work@, test_sources, regex_sources) == Some((Seq::empty(), seq![rule.tail@]))); + assert(work_cost::(work@) == work_cost::(finish) + + test_forest_cost::(test_views::(children@))); + assert(work_cost::(work@) < work_cost::(old_work)); + } + } + }, + Work::FinishTest(test, start) => { + proof! { + assert(test@ is And || test@ is Or); + assert(start <= test_sources.len()); + assert(start <= tests@.len()); + } + let children = take_children(&mut tests, start, limits, world)?; + proof_decl! { let ghost child_ids = children@; } + let node = match test { + TestExpr::And(_) => FlatTest::And(children), + TestExpr::Or(_) => FlatTest::Or(children), + _ => return Err(HistoryError::invariant("invalid source test finish").into()), + }; + proof! { + assert forall|i: int| 0 <= i < child_ids.len() implies + child_ids[i] < builder.tests_view().len() by { + assert(child_ids[i] == old_test_ids[start as int + i]); + assert(test_represents::(builder.tests_view(), child_ids[i] as nat, + old_test_sources[start as int + i], rule.head@)); + } + assert(crate::flat::verify::references_before(child_ids, builder.tests_view().len())); + assert(crate::flat::verify::test_wf(builder.head_view(), node, builder.tests_view().len())); + } + let id = builder.test(node, limits, world)?; + proof! { + lemma_test_operands(builder.tests_view()[id as int]); + assert(builder.tests_view().take(old_tests.len() as int) =~= old_tests); + assert(builder.regexes_view().take(old_regexes.len() as int) =~= old_regexes); + lemma_stack_extension::(old_tests, builder.tests_view(), old_regexes, builder.regexes_view(), + old_test_ids, old_regex_ids, old_test_sources, old_regex_sources, rule.head@); + let sources = match test@ { + history_syntax::spec::events::TestView::And(items) | history_syntax::spec::events::TestView::Or(items) => items, + _ => arbitrary(), + }; + assert(old_test_sources.subrange(start as int, old_test_sources.len() as int) == sources); + assert forall|i: int| 0 <= i < sources.len() implies + test_represents::(builder.tests_view(), child_ids[i] as nat, sources[i], rule.head@) by { + assert(child_ids[i] == old_test_ids[start as int + i]); + assert(sources[i] == old_test_sources[start as int + i]); + } + assert forall|i: int| 0 <= i < sources.len() implies + crate::spec::semantics::test_scoped(sources[i], rule.head@) by { + assert(test_represents::(builder.tests_view(), child_ids[i] as nat, sources[i], rule.head@)); + } + reveal_with_fuel(crate::spec::semantics::test_scoped, 2); + assert(crate::spec::semantics::test_scoped(test@, rule.head@)); + assert(child_ids.len() == sources.len()); + assert(crate::flat::verify::references_before(child_ids, id as nat)); + assert(test_represents::(builder.tests_view(), id as nat, test@, rule.head@)); + } + push(&mut tests, id, limits, world)?; + proof! { test_sources = test_sources.subrange(0, start as int).push(test@); } + } + Work::FinishRegex(regex, start) => { + proof! { + assert(match regex@ { + history_syntax::spec::events::RegexView::Test(_) => test_sources.len() == start + 1, + history_syntax::spec::events::RegexView::Star(_) | history_syntax::spec::events::RegexView::Not(_) + => regex_sources.len() == start + 1, + history_syntax::spec::events::RegexView::Concat(_) | history_syntax::spec::events::RegexView::Union(_) + | history_syntax::spec::events::RegexView::Intersect(_) => start <= regex_sources.len(), + _ => false, + }); + } + let node = match regex { + RegexExpr::Test(_) => { + proof! { assert(tests@.len() == start + 1); } + let child = match tests.pop() { + Some(child) => child, + None => { + return Err( + HistoryError::invariant("missing source test operand").into() + ); + } + }; + proof! { test_sources = test_sources.drop_last(); } + FlatRegex::Test(child) + } + RegexExpr::Star(_) | RegexExpr::Not(_) => { + proof! { assert(regexes@.len() == start + 1); } + let child = match regexes.pop() { + Some(child) => child, + None => { + return Err(HistoryError::invariant( + "missing source regex operand", + ) + .into()); + } + }; + proof! { regex_sources = regex_sources.drop_last(); } + match regex { + RegexExpr::Star(_) => FlatRegex::Star(child), + _ => FlatRegex::Complement(child), + } + } + RegexExpr::Concat(_) | RegexExpr::Union(_) | RegexExpr::Intersect(_) => { + proof! { assert(start <= regexes@.len()); } + let children = take_children(&mut regexes, start, limits, world)?; + proof! { regex_sources = regex_sources.subrange(0, start as int); } + match regex { + RegexExpr::Concat(_) => FlatRegex::Concat(children), + RegexExpr::Union(_) => FlatRegex::Union(children), + _ => FlatRegex::Intersect(children), + } + } + _ => return Err(HistoryError::invariant("invalid source regex finish").into()), + }; + proof_decl! { let ghost finished = node; } + proof! { + lemma_regex_operands(node); + match node { + FlatRegex::Test(child) => { + assert(child == old_test_ids.last()); + assert(test_represents::(builder.tests_view(), child as nat, + old_test_sources.last(), rule.head@)); + }, + FlatRegex::Star(child) | FlatRegex::Complement(child) => { + assert(child == old_regex_ids.last()); + assert(regex_represents::(builder.tests_view(), builder.regexes_view(), child as nat, + old_regex_sources.last(), rule.head@)); + }, + FlatRegex::Concat(ref ids) | FlatRegex::Union(ref ids) | FlatRegex::Intersect(ref ids) => { + assert forall|i: int| 0 <= i < ids@.len() implies + ids@[i] < builder.regexes_view().len() by { + assert(ids@[i] == old_regex_ids[start as int + i]); + assert(regex_represents::(builder.tests_view(), builder.regexes_view(), ids@[i] as nat, + old_regex_sources[start as int + i], rule.head@)); + } + }, + _ => {}, + } + assert(crate::flat::verify::regex_wf(node, builder.regexes_view().len(), builder.tests_view().len())); + } + let id = builder.regex(node, limits, world)?; + proof! { + lemma_regex_operands(builder.regexes_view()[id as int]); + assert(builder.tests_view().take(old_tests.len() as int) =~= old_tests); + assert(builder.regexes_view().take(old_regexes.len() as int) =~= old_regexes); + lemma_stack_extension::(old_tests, builder.tests_view(), old_regexes, builder.regexes_view(), + old_test_ids, old_regex_ids, old_test_sources, old_regex_sources, rule.head@); + match regex@ { + history_syntax::spec::events::RegexView::Test(source) => { + let child = match finished { FlatRegex::Test(id) => id, _ => arbitrary() }; + assert(test_represents::(builder.tests_view(), child as nat, source, rule.head@)); + }, + history_syntax::spec::events::RegexView::Star(source) | history_syntax::spec::events::RegexView::Not(source) => { + let child = match finished { FlatRegex::Star(id) | FlatRegex::Complement(id) => id, _ => arbitrary() }; + assert(regex_represents::(builder.tests_view(), builder.regexes_view(), child as nat, *source, rule.head@)); + }, + history_syntax::spec::events::RegexView::Concat(sources) | history_syntax::spec::events::RegexView::Union(sources) + | history_syntax::spec::events::RegexView::Intersect(sources) => { + let ids = match finished { + FlatRegex::Concat(ids) | FlatRegex::Union(ids) | FlatRegex::Intersect(ids) => ids@, + _ => arbitrary(), + }; + assert(old_regex_sources.subrange(start as int, old_regex_sources.len() as int) == sources); + assert forall|i: int| 0 <= i < sources.len() implies + regex_represents::(builder.tests_view(), builder.regexes_view(), ids[i] as nat, sources[i], rule.head@) by { + assert(ids[i] == old_regex_ids[start as int + i]); + assert(sources[i] == old_regex_sources[start as int + i]); + } + assert forall|i: int| 0 <= i < sources.len() implies + crate::spec::semantics::regex_scoped(sources[i], rule.head@) by { + assert(regex_represents::(builder.tests_view(), builder.regexes_view(), ids[i] as nat, sources[i], rule.head@)); + } + }, + _ => {}, + } + reveal_with_fuel(crate::spec::semantics::regex_scoped, 2); + assert(crate::spec::semantics::regex_scoped(regex@, rule.head@)); + assert(regex_represents::(builder.tests_view(), builder.regexes_view(), id as nat, regex@, rule.head@)); + } + push(&mut regexes, id, limits, world)?; + proof! { regex_sources = regex_sources.push(regex@); } + } + } + proof! { + reveal(result_stacks); + reveal_with_fuel(work_cost, 2); + assert(work_cost::(work@) < work_cost::(old_work)); + assert(builder.tests_view().len() + builder.regexes_view().len() + <= old_tests.len() + old_regexes.len() + 1); + assert(builder.tests_view().len() + builder.regexes_view().len() + + work_cost::(work@) <= regex_cost::(rule.tail@)); + if E::obeys_projection_spec() { + assert forall|i: int| 0 <= i < builder.tests_view().len() implies + crate::verify::encoding::test_in_domain(builder.tests_view()[i], component_domain::()) by { + if i < old_tests.len() { assert(builder.tests_view()[i] == old_tests[i]); } + } + } + assert forall|i: int| 0 <= i < builder.tests_view().len() implies + flat_test_within(#[trigger] builder.tests_view()[i], rule.tail@) by { + if i < old_tests.len() { assert(builder.tests_view()[i] == old_tests[i]); } + } + } + } + proof! { + reveal(result_stacks); + reveal_with_fuel(run_work, 1); + assert(test_sources =~= Seq::empty()); + assert(regex_sources =~= seq![rule.tail@]); + assert(tests@.len() == 0); + assert(regexes@.len() == 1); + } + if regexes.len() != 1 || !tests.is_empty() { + return Err(HistoryError::invariant("invalid source result stack").into()); + } + proof_decl! { let ghost result_ids = regexes@; } + let root = match regexes.pop() { + Some(root) => root, + None => return Err(HistoryError::invariant("missing source root").into()), + }; + proof! { + assert(result_ids =~= seq![root]); + assert(regex_represents::(builder.tests_view(), builder.regexes_view(), result_ids[0] as nat, regex_sources[0], rule.head@)); + assert(regex_represents::(builder.tests_view(), builder.regexes_view(), root as nat, rule.tail@, rule.head@)); + } + limits.checkpoint().map_err(HistoryError::from)?; + let source: FlatPair = builder.finish(root)?; + proof! { + assert(head_represents::(source.head@, rule.head@)); + assert(regex_represents::(source.tests@, source.regexes@, source.root as nat, rule.tail@, rule.head@)); + assert(E::obeys_projection_spec() ==> crate::verify::encoding::constants_in_domain(source, component_domain::())); + assert(forall|i: int| 0 <= i < source.tests@.len() ==> flat_test_within(#[trigger] source.tests@[i], rule.tail@)); + } + Ok(FlatRule { mode, source }) +} diff --git a/src/junco-core/src/kernel.rs b/src/junco-core/src/kernel.rs new file mode 100644 index 000000000..646a31125 --- /dev/null +++ b/src/junco-core/src/kernel.rs @@ -0,0 +1,1687 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +use super::errors::HistoryError; +use alloc::vec::Vec; +use history_syntax::{KeyHash, MAX_ARITY, syntax::Component}; +use vstd::prelude::*; + +#[cfg(verus_keep_ghost)] +use crate::verify::history_assumptions::*; +#[cfg(verus_keep_ghost)] +use crate::verify::history_specs::no_invariant_failure; +#[cfg(verus_keep_ghost)] +use verify::*; +#[cfg(verus_keep_ghost)] +use vstd::std_specs::cmp::PartialEqSpec; + +pub type KernelResult = core::result::Result; +pub use crate::limits::MAX_GRAPH_BYTES; + +// Keep a loop-body error in a local, stop the loop, and propagate it after the loop. +#[macro_export] +macro_rules! loop_try { + ($expression:expr, $failure:ident) => {{ + let outcome = $expression; + match outcome { + Ok(value) => value, + Err(error) => { + $failure = Some(error); + break; + } + } + }}; +} + +// A checked iteration is one function call. No partially reborrowed store is +// carried by an early loop exit; success and failure meet at the loop condition. +#[macro_export] +macro_rules! scan { + ($state:ident,$index:ident,$count:expr,$condition:expr,$value:ident=>$step:expr) => {{ + let mut $index = 0; + while $index < $count && $condition { + $state = match $state { + Ok($value) => $step, + Err(error) => Err(error), + }; + $index = $index.saturating_add(1); + } + }}; + ($state:ident,$index:ident,$count:expr,$condition:expr,$value:ident=>$step:expr; $($spec:tt)*) => {{ + let mut $index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec($($spec)*))] + while $index < $count && $condition { + $state = match $state { + Ok($value) => $step, + Err(error) => Err(error), + }; + $index = $index.saturating_add(1); + } + }}; +} + +macro_rules! id { + ($name:ident) => { + #[verus_verify] + #[verus_verify(external_derive)] + #[cfg_attr(verus_keep_ghost, derive(Structural))] + #[derive(Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] + pub struct $name(pub(crate) u32); + #[verus_verify] + impl Clone for $name { + #[verus_spec(result => ensures result == *self)] + fn clone(&self) -> Self { + *self + } + } + #[verus_verify] + impl KeyHash for $name { + fn key_hash(&self) -> u64 { + self.0 as u64 + } + } + #[verus_verify] + impl $name { + verus! { + pub closed const ZERO: Self = Self(0); + } + + #[verus_spec(result => ensures result as nat == self@)] + pub const fn get(self) -> u32 { + self.0 + } + + #[verus_spec(result => ensures + self@ > usize::MAX || no_invariant_failure(result), + self@ > usize::MAX || match result { + Ok(_) => true, + Err(error) => crate::spec::semantics::resource_error(error), + }, + match result { + Ok(index) => index as nat == self@, + Err(error) => self@ > usize::MAX as nat && error is Invariant, + }, + )] + pub fn index(self) -> KernelResult { + match usize::try_from(self.0) { + Ok(index) => Ok(index), + Err(_) => Err(HistoryError::graph_id_overflow()), + } + } + #[verus_spec(result => ensures + no_invariant_failure(result), + match result { + Ok(_) => true, + Err(error) => crate::spec::semantics::resource_error(error), + }, + match result { + Ok(id) => id@ == index as nat, + Err(error) => index as nat > u32::MAX as nat && error is GraphIndex, + }, + )] + pub fn from_index(index: usize) -> KernelResult { + match u32::try_from(index) { + Ok(value) => Ok(Self(value)), + Err(_) => Err(HistoryError::graph_index_overflow()), + } + } + } + }; +} +id!(TestId); +id!(RegexId); +id!(TransitionId); + +// `eq` is proved equal to structural equality on the view, so derived `Hash` agrees with it. +#[allow(clippy::derived_hash_with_manual_eq)] +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy, Debug, PartialOrd, Ord, Hash)] +pub enum Term { + Constant(u64), + Variable(Component), +} +#[allow(clippy::derived_hash_with_manual_eq)] +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy, Debug, PartialOrd, Ord, Hash)] +pub enum Primitive { + Eq { field: Component, term: Term }, +} + +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy, Debug)] +pub struct Bindings { + pub(crate) arity: u8, + pub(crate) slots: [u64; MAX_ARITY], +} + +#[cfg(verus_keep_ghost)] +verus! { +impl Bindings { + #[verifier::type_invariant] + closed spec fn inv(&self) -> bool { + self.arity <= MAX_ARITY + } +} +} + +#[verus_verify] +impl Bindings { + #[verus_spec(result => requires values@.len() <= MAX_ARITY, + ensures result@ == values@.map(|i: int, value: u64| value as nat))] + pub fn new(values: &[u64]) -> Self { + assert!(values.len() <= MAX_ARITY); + let mut slots = [0; MAX_ARITY]; + let mut index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant index <= values@.len() <= MAX_ARITY, + forall|i: int| 0 <= i < MAX_ARITY ==> slots@[i] == + if i < index { values@[i] } else { 0 }, + decreases values@.len() - index, + ))] + while index < values.len() { + slots[index] = values[index]; + index += 1; + } + Self { + arity: values.len() as u8, + slots, + } + } + + #[verus_spec(result => requires index < self@.len(), ensures result as nat == self@[index as int])] + pub fn get(&self, index: usize) -> u64 { + proof! { use_type_invariant(self); } + self.slots[index] + } + + #[verus_spec(result => ensures result == self@.len(), result <= MAX_ARITY)] + pub const fn arity(&self) -> usize { + proof! { use_type_invariant(self); } + self.arity as usize + } +} + +#[verus_verify] +impl PartialEq for Bindings { + fn eq(&self, other: &Self) -> bool { + proof! { use_type_invariant(self); use_type_invariant(other); } + if self.arity != other.arity { + return false; + } + let mut index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant index <= self.arity <= MAX_ARITY, self.arity == other.arity, + forall|i: int| 0 <= i < index ==> self.slots@[i] == other.slots@[i], + decreases self.arity - index, + ))] + while index < self.arity as usize { + if self.slots[index] != other.slots[index] { + proof! { assert(self@[index as int] != other@[index as int]); } + return false; + } + index += 1; + } + proof! { assert(self@ =~= other@); } + true + } +} + +impl Eq for Bindings {} + +impl core::hash::Hash for Bindings { + fn hash(&self, state: &mut H) { + core::hash::Hash::hash(&self.slots[..self.arity as usize], state); + } +} + +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy, Debug, Hash)] +pub enum TestView<'a> { + True, + False, + Atom { + primitive: Primitive, + positive: bool, + }, + And(&'a [TestId]), + Or(&'a [TestId]), +} +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy, Debug, Hash)] +pub enum RegexKindView<'a> { + Empty, + All, + Epsilon, + Test(TestId), + Union(&'a [RegexId]), + Concat(&'a [RegexId]), + Star(RegexId), + Intersect(&'a [RegexId]), + Not(RegexId), +} +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy, Debug, Eq, Hash)] +pub struct RegexView<'a> { + pub kind: RegexKindView<'a>, + pub nullable: bool, +} +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy, Debug, Hash)] +pub enum TransitionView<'a> { + Const(RegexId), + If { + test: TestId, + then_transition: TransitionId, + else_transition: TransitionId, + }, + Union(&'a [TransitionId]), + Intersect(&'a [TransitionId]), + Not(TransitionId), + Append { + transition: TransitionId, + suffix: &'a [RegexId], + }, +} + +// Copy the drop-free operands before comparing. Deriving these enum comparisons +// delegates borrowed child fields to a reference-of-reference Eq implementation +// which the pinned extractor cannot interpret. +#[verus_verify] +#[verus_spec(result => + requires T::obeys_eq_spec(), + forall|a: T, b: T| a.eq_spec(&b) == (a == b), + ensures result == (left@ == right@), +)] +pub fn id_slice_eq(left: &[T], right: &[T]) -> bool { + let mut equal = left.len() == right.len(); + let mut index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant + T::obeys_eq_spec(), + forall|a: T, b: T| a.eq_spec(&b) == (a == b), + index <= left.len(), + equal ==> left.len() == right.len(), + equal ==> forall|i: int| 0 <= i < index ==> left@[i] == right@[i], + !equal ==> left@ != right@, + decreases left.len() - index, + ))] + while equal && index < left.len() { + equal = match (left.get(index).copied(), right.get(index).copied()) { + (Some(a), Some(b)) => a == b, + _ => false, + }; + proof! { + if equal { + assert forall|i: int| 0 <= i <= index implies left@[i] == right@[i] by {} + } else { + assert(left@[index as int] != right@[index as int]); + assert(left@ != right@); + } + } + index = index.saturating_add(1); + } + proof! { if equal { assert(left@ =~= right@); } } + equal +} +#[verus_verify] +impl PartialEq for Term { + #[verus_spec(result => ensures result == (self@ == other@))] + fn eq(&self, other: &Self) -> bool { + match (*self, *other) { + (Self::Constant(a), Self::Constant(b)) => a == b, + (Self::Variable(a), Self::Variable(b)) => a == b, + _ => false, + } + } +} +impl Eq for Term {} +#[verus_verify] +impl PartialEq for Primitive { + #[verus_spec(result => ensures result == (self@ == other@))] + fn eq(&self, other: &Self) -> bool { + match (*self, *other) { + (Self::Eq { field: p, term: t }, Self::Eq { field: q, term: u }) => p == q && t == u, + } + } +} +impl Eq for Primitive {} +#[verus_verify] +impl PartialEq for TestView<'_> { + #[verus_spec(result => ensures result == (self@ == other@))] + fn eq(&self, other: &Self) -> bool { + match (*self, *other) { + (Self::True, Self::True) | (Self::False, Self::False) => true, + ( + Self::Atom { + primitive: p, + positive: x, + }, + Self::Atom { + primitive: q, + positive: y, + }, + ) => p == q && x == y, + (Self::And(a), Self::And(b)) | (Self::Or(a), Self::Or(b)) => { + proof! { lemma_test_ids_eq(a@, b@); } + id_slice_eq(a, b) + } + _ => false, + } + } +} +impl Eq for TestView<'_> {} +#[verus_verify] +impl PartialEq for RegexKindView<'_> { + #[verus_spec(result => ensures result == (self@ == other@))] + fn eq(&self, other: &Self) -> bool { + match (*self, *other) { + (Self::Empty, Self::Empty) + | (Self::All, Self::All) + | (Self::Epsilon, Self::Epsilon) => true, + (Self::Test(a), Self::Test(b)) => a == b, + (Self::Star(a), Self::Star(b)) | (Self::Not(a), Self::Not(b)) => a == b, + (Self::Union(a), Self::Union(b)) + | (Self::Concat(a), Self::Concat(b)) + | (Self::Intersect(a), Self::Intersect(b)) => { + proof! { lemma_regex_ids_eq(a@, b@); } + id_slice_eq(a, b) + } + _ => false, + } + } +} +impl Eq for RegexKindView<'_> {} +#[verus_verify] +impl PartialEq for RegexView<'_> { + #[verus_spec(result => ensures result == (self@ == other@))] + fn eq(&self, other: &Self) -> bool { + self.kind == other.kind && self.nullable == other.nullable + } +} +#[verus_verify] +impl PartialEq for TransitionView<'_> { + #[verus_spec(result => ensures result == (self@ == other@))] + fn eq(&self, other: &Self) -> bool { + match (*self, *other) { + (Self::Const(a), Self::Const(b)) => a == b, + ( + Self::If { + test: a, + then_transition: b, + else_transition: c, + }, + Self::If { + test: x, + then_transition: y, + else_transition: z, + }, + ) => a == x && b == y && c == z, + (Self::Union(a), Self::Union(b)) | (Self::Intersect(a), Self::Intersect(b)) => { + proof! { lemma_transition_ids_eq(a@, b@); } + id_slice_eq(a, b) + } + (Self::Not(a), Self::Not(b)) => a == b, + ( + Self::Append { + transition: a, + suffix: x, + }, + Self::Append { + transition: b, + suffix: y, + }, + ) => { + proof! { lemma_regex_ids_eq(x@, y@); } + a == b && id_slice_eq(x, y) + } + _ => false, + } + } +} +impl Eq for TransitionView<'_> {} + +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy, Debug)] +pub struct Constants { + pub test_true: TestId, + pub test_false: TestId, + pub empty: RegexId, + pub all: RegexId, + pub epsilon: RegexId, + pub transition_empty: TransitionId, + pub transition_all: TransitionId, + pub transition_epsilon: TransitionId, +} +/// Store-backed graph operations. In verified code, error exclusions are opt-in +/// through `KernelStoreSpec`; custom stores retain arbitrary errors by default. +#[cfg(not(verus_keep_ghost))] +pub trait KernelStore { + fn checkpoint(&mut self) -> KernelResult<()>; + fn charge_aux(&mut self, bytes: usize) -> KernelResult<()>; + fn reserve_derivatives( + &mut self, + values: &mut Vec>, + additional: usize, + ) -> KernelResult<()>; + fn reserve_atoms(&mut self, values: &mut Vec, additional: usize) -> KernelResult<()>; + fn constants(&self) -> Constants; + fn test(&self, id: TestId) -> KernelResult>; + fn regex(&self, id: RegexId) -> KernelResult>; + fn transition(&self, id: TransitionId) -> KernelResult>; + fn intern_test(&mut self, node: TestView<'_>) -> KernelResult; + fn intern_regex(&mut self, kind: RegexKindView<'_>, nullable: bool) -> KernelResult; + fn intern_transition(&mut self, node: TransitionView<'_>) -> KernelResult; +} + +#[cfg(verus_keep_ghost)] +verus! { +pub trait KernelStore: KernelStoreSpec { + fn checkpoint(&mut self) -> (r: KernelResult<()>) + ensures final(self).graph() == old(self).graph(), + final(self).errors_are_non_owner() == old(self).errors_are_non_owner(), + final(self).errors_are_non_invariant() == old(self).errors_are_non_invariant(), + final(self).errors_are_non_invalid_policy() == old(self).errors_are_non_invalid_policy(), + final(self).errors_are_resource() == old(self).errors_are_resource(), + old(self).errors_are_resource() && old(self).valid_store() ==> + (r matches Err(error) ==> crate::spec::semantics::resource_error(error)), + old(self).errors_are_non_owner() ==> r != Err(HistoryError::WrongHistoryOwner), + old(self).errors_are_non_invariant() && old(self).valid_store() ==> no_invariant_failure(r), + old(self).errors_are_non_invalid_policy() && old(self).valid_store() ==> !(r matches Err(HistoryError::InvalidPolicy { .. })), + final(self).valid_store() == old(self).valid_store(), final(self).restoration() == old(self).restoration(); + fn charge_aux(&mut self, bytes: usize) -> (r: KernelResult<()>) + ensures final(self).graph() == old(self).graph(), + final(self).errors_are_non_owner() == old(self).errors_are_non_owner(), + final(self).errors_are_non_invariant() == old(self).errors_are_non_invariant(), + final(self).errors_are_non_invalid_policy() == old(self).errors_are_non_invalid_policy(), + final(self).errors_are_resource() == old(self).errors_are_resource(), + old(self).errors_are_resource() && old(self).valid_store() ==> + (r matches Err(error) ==> crate::spec::semantics::resource_error(error)), + old(self).errors_are_non_owner() ==> r != Err(HistoryError::WrongHistoryOwner), + old(self).errors_are_non_invariant() && old(self).valid_store() ==> no_invariant_failure(r), + old(self).errors_are_non_invalid_policy() && old(self).valid_store() ==> !(r matches Err(HistoryError::InvalidPolicy { .. })), + old(self).valid_store() ==> final(self).valid_store(), final(self).restoration() == old(self).restoration(); + fn reserve_derivatives(&mut self, values: &mut Vec>, additional: usize) + -> (r: KernelResult<()>) + ensures final(self).graph() == old(self).graph(), final(values)@ == old(values)@, + final(self).errors_are_non_owner() == old(self).errors_are_non_owner(), + final(self).errors_are_non_invariant() == old(self).errors_are_non_invariant(), + final(self).errors_are_non_invalid_policy() == old(self).errors_are_non_invalid_policy(), + final(self).errors_are_resource() == old(self).errors_are_resource(), + old(self).errors_are_resource() && old(self).valid_store() ==> + (r matches Err(error) ==> crate::spec::semantics::resource_error(error)), + old(self).errors_are_non_owner() ==> r != Err(HistoryError::WrongHistoryOwner), + old(self).errors_are_non_invariant() && old(self).valid_store() ==> no_invariant_failure(r), + old(self).errors_are_non_invalid_policy() && old(self).valid_store() ==> !(r matches Err(HistoryError::InvalidPolicy { .. })), + final(self).valid_store() == old(self).valid_store(), final(self).restoration() == old(self).restoration(); + fn reserve_atoms(&mut self, values: &mut Vec, additional: usize) + -> (r: KernelResult<()>) + ensures final(self).graph() == old(self).graph(), final(values)@ == old(values)@, + final(self).errors_are_non_owner() == old(self).errors_are_non_owner(), + final(self).errors_are_non_invariant() == old(self).errors_are_non_invariant(), + final(self).errors_are_non_invalid_policy() == old(self).errors_are_non_invalid_policy(), + final(self).errors_are_resource() == old(self).errors_are_resource(), + old(self).errors_are_resource() && old(self).valid_store() ==> + (r matches Err(error) ==> crate::spec::semantics::resource_error(error)), + old(self).errors_are_non_owner() ==> r != Err(HistoryError::WrongHistoryOwner), + old(self).errors_are_non_invariant() && old(self).valid_store() ==> no_invariant_failure(r), + old(self).errors_are_non_invalid_policy() && old(self).valid_store() ==> !(r matches Err(HistoryError::InvalidPolicy { .. })), + final(self).valid_store() == old(self).valid_store(), final(self).restoration() == old(self).restoration(); + fn constants(&self) -> (r: Constants) + ensures r@ == self.graph().constants; + // Valid production lookups allocate nothing and always find their live node. + // Totality is needed by AtomSet validation, which deliberately masks lookup errors. + fn test(&self, id: TestId) -> (r: KernelResult>) + ensures r matches Ok(v) ==> id@ < self.graph().tests.len() + && v@ == self.graph().tests[id@ as int], + self.errors_are_resource() && self.valid_store() && id@ < self.graph().tests.len() ==> + r is Ok && (r matches Err(error) ==> crate::spec::semantics::resource_error(error)), + self.errors_are_non_owner() ==> r != Err(HistoryError::WrongHistoryOwner), + self.errors_are_non_invariant() && self.valid_store() && id@ < self.graph().tests.len() + ==> r is Ok && no_invariant_failure(r), + self.errors_are_non_invalid_policy() && self.valid_store() && id@ < self.graph().tests.len() + ==> !(r matches Err(HistoryError::InvalidPolicy { .. })); + fn regex(&self, id: RegexId) -> (r: KernelResult>) + ensures r matches Ok(v) ==> id@ < self.graph().regexes.len() + && v@ == self.graph().regexes[id@ as int], + self.errors_are_resource() && self.valid_store() && id@ < self.graph().regexes.len() ==> + r is Ok && (r matches Err(error) ==> crate::spec::semantics::resource_error(error)), + self.errors_are_non_owner() ==> r != Err(HistoryError::WrongHistoryOwner), + self.errors_are_non_invariant() && self.valid_store() && id@ < self.graph().regexes.len() + ==> r is Ok && no_invariant_failure(r), + self.errors_are_non_invalid_policy() && self.valid_store() && id@ < self.graph().regexes.len() + ==> !(r matches Err(HistoryError::InvalidPolicy { .. })); + fn transition(&self, id: TransitionId) -> (r: KernelResult>) + ensures r matches Ok(v) ==> id@ < self.graph().transitions.len() + && v@ == self.graph().transitions[id@ as int], + self.errors_are_resource() && self.valid_store() && id@ < self.graph().transitions.len() ==> + r is Ok && (r matches Err(error) ==> crate::spec::semantics::resource_error(error)), + self.errors_are_non_owner() ==> r != Err(HistoryError::WrongHistoryOwner), + self.errors_are_non_invariant() && self.valid_store() && id@ < self.graph().transitions.len() + ==> r is Ok && no_invariant_failure(r), + self.errors_are_non_invalid_policy() && self.valid_store() && id@ < self.graph().transitions.len() + ==> !(r matches Err(HistoryError::InvalidPolicy { .. })); + fn intern_test(&mut self, node: TestView<'_>) -> (r: KernelResult) + requires old(self).valid_store(), test_node_wf(old(self).graph(), node@), + ensures + final(self).errors_are_non_owner() == old(self).errors_are_non_owner(), + final(self).errors_are_non_invariant() == old(self).errors_are_non_invariant(), + final(self).errors_are_non_invalid_policy() == old(self).errors_are_non_invalid_policy(), + final(self).errors_are_resource() == old(self).errors_are_resource(), + old(self).errors_are_resource() ==> + (r matches Err(error) ==> crate::spec::semantics::resource_error(error)), + old(self).errors_are_non_owner() ==> r != Err(HistoryError::WrongHistoryOwner), + old(self).errors_are_non_invariant() ==> no_invariant_failure(r), + old(self).errors_are_non_invalid_policy() ==> !(r matches Err(HistoryError::InvalidPolicy { .. })), + final(self).restoration() == old(self).restoration(), + final(self).valid_store(), + graph_extends(old(self).graph(), final(self).graph()), + tables_wf(old(self).graph()) ==> tables_wf(final(self).graph()), + graph_wf(old(self).graph()) ==> graph_wf(final(self).graph()), + r matches Ok(id) ==> id@ < final(self).graph().tests.len() + && final(self).graph().tests[id@ as int] == node@; + fn intern_regex(&mut self, kind: RegexKindView<'_>, nullable: bool) + -> (r: KernelResult) + requires old(self).valid_store(), regex_node_wf(old(self).graph(), RegexNode { kind: kind@, nullable }), + ensures + final(self).errors_are_non_owner() == old(self).errors_are_non_owner(), + final(self).errors_are_non_invariant() == old(self).errors_are_non_invariant(), + final(self).errors_are_non_invalid_policy() == old(self).errors_are_non_invalid_policy(), + final(self).errors_are_resource() == old(self).errors_are_resource(), + old(self).errors_are_resource() ==> + (r matches Err(error) ==> crate::spec::semantics::resource_error(error)), + old(self).errors_are_non_owner() ==> r != Err(HistoryError::WrongHistoryOwner), + old(self).errors_are_non_invariant() ==> no_invariant_failure(r), + old(self).errors_are_non_invalid_policy() ==> !(r matches Err(HistoryError::InvalidPolicy { .. })), + final(self).restoration() == old(self).restoration(), + final(self).valid_store(), + graph_extends(old(self).graph(), final(self).graph()), + tables_wf(old(self).graph()) ==> tables_wf(final(self).graph()), + graph_wf(old(self).graph()) ==> graph_wf(final(self).graph()), + r matches Ok(id) ==> id@ < final(self).graph().regexes.len() + && final(self).graph().regexes[id@ as int] == (RegexNode { kind: kind@, nullable }); + fn intern_transition(&mut self, node: TransitionView<'_>) -> (r: KernelResult) + requires old(self).valid_store(), transition_node_wf(old(self).graph(), node@), + ensures + final(self).errors_are_non_owner() == old(self).errors_are_non_owner(), + final(self).errors_are_non_invariant() == old(self).errors_are_non_invariant(), + final(self).errors_are_non_invalid_policy() == old(self).errors_are_non_invalid_policy(), + final(self).errors_are_resource() == old(self).errors_are_resource(), + old(self).errors_are_resource() ==> + (r matches Err(error) ==> crate::spec::semantics::resource_error(error)), + old(self).errors_are_non_owner() ==> r != Err(HistoryError::WrongHistoryOwner), + old(self).errors_are_non_invariant() ==> no_invariant_failure(r), + old(self).errors_are_non_invalid_policy() ==> !(r matches Err(HistoryError::InvalidPolicy { .. })), + final(self).restoration() == old(self).restoration(), + final(self).valid_store(), + graph_extends(old(self).graph(), final(self).graph()), + tables_wf(old(self).graph()) ==> tables_wf(final(self).graph()), + graph_wf(old(self).graph()) ==> graph_wf(final(self).graph()), + r matches Ok(id) ==> id@ < final(self).graph().transitions.len() + && final(self).graph().transitions[id@ as int] == node@; +} +} + +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Debug)] +pub struct AtomSet { + ids: Vec, +} +#[verus_verify] +impl AtomSet { + #[verus_spec(result => ensures result@ == self@)] + pub const fn ids(&self) -> &[TestId] { + self.ids.as_slice() + } + #[allow( + clippy::option_if_let_else, + reason = "Explicit matches preserve the Verus proof structure" + )] + #[verus_verify] + #[verus_spec(result => ensures + final(store).graph() == old(store).graph(), + final(store).valid_store() == old(store).valid_store(), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_resource() && old(store).valid_store() + && atom_ids_wf(old(store).graph(), ids@) && index < ids@.len() + && previous == (if index == 0 { None } else { Some(ids@[index as int - 1]) }) + ==> (result matches Err(error) ==> crate::spec::semantics::resource_error(error)), + old(store).errors_are_non_invariant() && old(store).valid_store() + && atom_ids_wf(old(store).graph(), ids@) && index < ids@.len() + && previous == (if index == 0 { None } else { Some(ids@[index as int - 1]) }) + ==> no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() + && atom_ids_wf(old(store).graph(), ids@) && index < ids@.len() + && previous == (if index == 0 { None } else { Some(ids@[index as int - 1]) }) + ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + match result { + Ok(Some(id)) => index < ids@.len() && id == ids@[index as int] + && id@ < final(store).graph().tests.len() + && (final(store).graph().tests[id@ as int] matches TestNode::Atom(_, true)) + && match previous { Some(prev) => prev@ < id@, None => true }, + _ => result is Err, + }, + )] + fn validate_id( + store: &mut G, + ids: &[TestId], + index: usize, + previous: Option, + ) -> KernelResult> { + store.checkpoint()?; + let id = match ids.get(index) { + Some(v) => *v, + None => return Err(HistoryError::invalid_atom_set()), + }; + proof! { + if (store.errors_are_non_invariant() || store.errors_are_resource()) && store.valid_store() + && atom_ids_wf(store.graph(), ids@) && index < ids@.len() + && previous == (if index == 0 { None } else { Some(ids@[index as int - 1]) }) { + assert(id@ < store.graph().tests.len()); + assert(store.graph().tests[id@ as int] matches TestNode::Atom(_, true)); + if index > 0 { + assert(test_ids(ids@)[index as int - 1] < test_ids(ids@)[index as int]); + } + } + } + let valid = matches!(id.head(store), Ok(TestHead::Atom(_, true))); + let unordered = match previous { + Some(prev) => prev >= id, + None => false, + }; + if !valid || unordered { + Err(HistoryError::invalid_atom_set()) + } else { + Ok(Some(id)) + } + } + #[verus_verify] + #[verus_spec(result => ensures + final(store).graph() == old(store).graph(), + final(store).valid_store() == old(store).valid_store(), + final(store).restoration() == old(store).restoration(), + final(store).errors_are_non_owner() == old(store).errors_are_non_owner(), + final(store).errors_are_non_invariant() == old(store).errors_are_non_invariant(), + final(store).errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + final(store).errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_resource() && old(store).valid_store() + && atom_ids_wf(old(store).graph(), ids@) + ==> (result matches Err(error) ==> crate::spec::semantics::resource_error(error)), + old(store).errors_are_non_invariant() && old(store).valid_store() + && atom_ids_wf(old(store).graph(), ids@) ==> no_invariant_failure(result), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() + && atom_ids_wf(old(store).graph(), ids@) ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + match result { Ok(atoms) => atoms@ == ids@ && atom_ids_wf(final(store).graph(), atoms@), Err(_) => true }, + )] + pub fn new(store: &mut G, ids: Vec) -> KernelResult { + let mut state = Ok(None); + scan!(state,index,ids.len(),state.is_ok(),previous=>Self::validate_id(store,&ids,index,previous); + invariant + store.graph() == old(store).graph(), + store.valid_store() == old(store).valid_store(), + store.restoration() == old(store).restoration(), + store.errors_are_non_owner() == old(store).errors_are_non_owner(), + store.errors_are_non_invariant() == old(store).errors_are_non_invariant(), + store.errors_are_non_invalid_policy() == old(store).errors_are_non_invalid_policy(), + store.errors_are_resource() == old(store).errors_are_resource(), + old(store).errors_are_resource() && old(store).valid_store() + && atom_ids_wf(old(store).graph(), ids@) + ==> (state matches Err(error) ==> crate::spec::semantics::resource_error(error)), + old(store).errors_are_non_invariant() && old(store).valid_store() + && atom_ids_wf(old(store).graph(), ids@) ==> no_invariant_failure(state), + old(store).errors_are_non_invalid_policy() && old(store).valid_store() + && atom_ids_wf(old(store).graph(), ids@) ==> !(state matches Err(HistoryError::InvalidPolicy { .. })), + old(store).errors_are_non_owner() ==> state != Err(HistoryError::WrongHistoryOwner), + index <= ids.len(), + match state { + Ok(previous) => atom_prefix_wf(store.graph(), ids@, index as nat) + && previous == if index == 0 { None } else { Some(ids@[index as int - 1]) }, + Err(_) => true, + }, + decreases ids.len() - index, + ); + state?; + Ok(AtomSet { ids }) + } +} + +// Drop-free heads end store-backed slice borrows before any mutable operation. +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy)] +pub enum TestHead { + True, + False, + Atom(Primitive, bool), + And(usize), + Or(usize), +} +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy)] +pub enum RegexHead { + Empty, + All, + Epsilon, + Test(TestId), + Union(usize), + Concat(usize), + Star(RegexId), + Intersect(usize), + Not(RegexId), +} +#[verus_verify] +#[verus_verify(external_derive)] +#[derive(Clone, Copy)] +pub enum TransitionHead { + Const(RegexId), + If(TestId, TransitionId, TransitionId), + Union(usize), + Intersect(usize), + Not(TransitionId), + Append(TransitionId, usize), +} +impl TestId { + #[verus_verify] + #[verus_spec(result => ensures + store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() && self@ < store.graph().tests.len() + ==> result is Ok && no_invariant_failure(result), + store.errors_are_non_invalid_policy() && store.valid_store() && self@ < store.graph().tests.len() + ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + store.errors_are_resource() && store.valid_store() && self@ < store.graph().tests.len() + ==> result is Ok && (result matches Err(error) ==> crate::spec::semantics::resource_error(error)), + match result { + Ok(head) => self@ < store.graph().tests.len() && head@ == test_node_head(store.graph().tests[self@ as int]), + Err(_) => true, + })] + pub fn head(self, store: &G) -> KernelResult { + Ok(match store.test(self)? { + TestView::True => TestHead::True, + TestView::False => TestHead::False, + TestView::Atom { + primitive, + positive, + } => TestHead::Atom(primitive, positive), + TestView::And(xs) => TestHead::And(xs.len()), + TestView::Or(xs) => TestHead::Or(xs.len()), + }) + } +} + +impl RegexId { + #[verus_verify] + #[verus_spec(result => ensures + store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() && self@ < store.graph().regexes.len() + ==> result is Ok && no_invariant_failure(result), + store.errors_are_non_invalid_policy() && store.valid_store() && self@ < store.graph().regexes.len() + ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + store.errors_are_resource() && store.valid_store() && self@ < store.graph().regexes.len() + ==> result is Ok && (result matches Err(error) ==> crate::spec::semantics::resource_error(error)), + match result { + Ok(head) => self@ < store.graph().regexes.len() && head@ == regex_node_head(store.graph().regexes[self@ as int].kind), + Err(_) => true, + })] + pub fn head(self, store: &G) -> KernelResult { + Ok(match store.regex(self)?.kind { + RegexKindView::Empty => RegexHead::Empty, + RegexKindView::All => RegexHead::All, + RegexKindView::Epsilon => RegexHead::Epsilon, + RegexKindView::Test(t) => RegexHead::Test(t), + RegexKindView::Union(xs) => RegexHead::Union(xs.len()), + RegexKindView::Concat(xs) => RegexHead::Concat(xs.len()), + RegexKindView::Star(inner) => RegexHead::Star(inner), + RegexKindView::Intersect(xs) => RegexHead::Intersect(xs.len()), + RegexKindView::Not(inner) => RegexHead::Not(inner), + }) + } +} + +impl TransitionId { + #[verus_verify] + #[verus_spec(result => ensures + store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() && self@ < store.graph().transitions.len() + ==> result is Ok && no_invariant_failure(result), + store.errors_are_non_invalid_policy() && store.valid_store() && self@ < store.graph().transitions.len() + ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + store.errors_are_resource() && store.valid_store() && self@ < store.graph().transitions.len() + ==> result is Ok && (result matches Err(error) ==> crate::spec::semantics::resource_error(error)), + match result { + Ok(head) => self@ < store.graph().transitions.len() && head@ == transition_node_head(store.graph().transitions[self@ as int]), + Err(_) => true, + })] + pub fn head(self, store: &G) -> KernelResult { + Ok(match store.transition(self)? { + TransitionView::Const(r) => TransitionHead::Const(r), + TransitionView::If { + test, + then_transition, + else_transition, + } => TransitionHead::If(test, then_transition, else_transition), + TransitionView::Union(xs) => TransitionHead::Union(xs.len()), + TransitionView::Intersect(xs) => TransitionHead::Intersect(xs.len()), + TransitionView::Not(inner) => TransitionHead::Not(inner), + TransitionView::Append { transition, suffix } => { + TransitionHead::Append(transition, suffix.len()) + } + }) + } +} + +impl TestId { + #[allow( + clippy::option_if_let_else, + reason = "Explicit matches preserve the Verus proof structure" + )] + #[verus_verify] + #[verus_spec(result => ensures + store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() && self@ < store.graph().tests.len() + && test_node_child(store.graph().tests[self@ as int], index as nat) is Some + ==> result is Ok && no_invariant_failure(result), + store.errors_are_non_invalid_policy() && store.valid_store() && self@ < store.graph().tests.len() + && test_node_child(store.graph().tests[self@ as int], index as nat) is Some + ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + store.errors_are_resource() && store.valid_store() && self@ < store.graph().tests.len() + && test_node_child(store.graph().tests[self@ as int], index as nat) is Some + ==> result is Ok && (result matches Err(error) ==> crate::spec::semantics::resource_error(error)), + match result { + Ok(child) => self@ < store.graph().tests.len() && test_node_child(store.graph().tests[self@ as int], index as nat) == Some(child@), + Err(_) => true, + })] + pub fn child(self, store: &G, index: usize) -> KernelResult { + match store.test(self)? { + TestView::And(xs) | TestView::Or(xs) => match xs.get(index) { + Some(value) => Ok(*value), + None => Err(HistoryError::normalization_invariant()), + }, + _ => Err(HistoryError::normalization_invariant()), + } + } +} + +impl RegexId { + #[allow( + clippy::option_if_let_else, + reason = "Explicit matches preserve the Verus proof structure" + )] + #[verus_verify] + #[verus_spec(result => ensures + store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() && self@ < store.graph().regexes.len() + && regex_node_child(store.graph().regexes[self@ as int].kind, index as nat) is Some + ==> result is Ok && no_invariant_failure(result), + store.errors_are_non_invalid_policy() && store.valid_store() && self@ < store.graph().regexes.len() + && regex_node_child(store.graph().regexes[self@ as int].kind, index as nat) is Some + ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + store.errors_are_resource() && store.valid_store() && self@ < store.graph().regexes.len() + && regex_node_child(store.graph().regexes[self@ as int].kind, index as nat) is Some + ==> result is Ok && (result matches Err(error) ==> crate::spec::semantics::resource_error(error)), + match result { + Ok(child) => self@ < store.graph().regexes.len() && regex_node_child(store.graph().regexes[self@ as int].kind, index as nat) == Some(child@), + Err(_) => true, + })] + pub fn child(self, store: &G, index: usize) -> KernelResult { + match store.regex(self)?.kind { + RegexKindView::Union(xs) | RegexKindView::Concat(xs) | RegexKindView::Intersect(xs) => { + match xs.get(index) { + Some(value) => Ok(*value), + None => Err(HistoryError::normalization_invariant()), + } + } + _ => Err(HistoryError::normalization_invariant()), + } + } +} + +impl TransitionId { + #[allow( + clippy::option_if_let_else, + reason = "Explicit matches preserve the Verus proof structure" + )] + #[verus_verify] + #[verus_spec(result => ensures + store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() && self@ < store.graph().transitions.len() + && transition_node_child(store.graph().transitions[self@ as int], index as nat) is Some + ==> result is Ok && no_invariant_failure(result), + store.errors_are_non_invalid_policy() && store.valid_store() && self@ < store.graph().transitions.len() + && transition_node_child(store.graph().transitions[self@ as int], index as nat) is Some + ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + store.errors_are_resource() && store.valid_store() && self@ < store.graph().transitions.len() + && transition_node_child(store.graph().transitions[self@ as int], index as nat) is Some + ==> result is Ok && (result matches Err(error) ==> crate::spec::semantics::resource_error(error)), + match result { + Ok(child) => self@ < store.graph().transitions.len() && transition_node_child(store.graph().transitions[self@ as int], index as nat) == Some(child@), + Err(_) => true, + })] + pub fn child(self, store: &G, index: usize) -> KernelResult { + match store.transition(self)? { + TransitionView::Union(xs) | TransitionView::Intersect(xs) => match xs.get(index) { + Some(value) => Ok(*value), + None => Err(HistoryError::normalization_invariant()), + }, + _ => Err(HistoryError::normalization_invariant()), + } + } +} + +impl TransitionId { + #[allow( + clippy::option_if_let_else, + reason = "Explicit matches preserve the Verus proof structure" + )] + #[verus_verify] + #[verus_spec(result => ensures + store.errors_are_non_owner() ==> result != Err(HistoryError::WrongHistoryOwner), + store.errors_are_non_invariant() && store.valid_store() && self@ < store.graph().transitions.len() + && transition_node_suffix(store.graph().transitions[self@ as int], index as nat) is Some + ==> result is Ok && no_invariant_failure(result), + store.errors_are_non_invalid_policy() && store.valid_store() && self@ < store.graph().transitions.len() + && transition_node_suffix(store.graph().transitions[self@ as int], index as nat) is Some + ==> !(result matches Err(HistoryError::InvalidPolicy { .. })), + store.errors_are_resource() && store.valid_store() && self@ < store.graph().transitions.len() + && transition_node_suffix(store.graph().transitions[self@ as int], index as nat) is Some + ==> result is Ok && (result matches Err(error) ==> crate::spec::semantics::resource_error(error)), + match result { + Ok(child) => self@ < store.graph().transitions.len() && transition_node_suffix(store.graph().transitions[self@ as int], index as nat) == Some(child@), + Err(_) => true, + })] + pub fn suffix_child(self, store: &G, index: usize) -> KernelResult { + match store.transition(self)? { + TransitionView::Append { suffix, .. } => match suffix.get(index) { + Some(value) => Ok(*value), + None => Err(HistoryError::normalization_invariant()), + }, + _ => Err(HistoryError::normalization_invariant()), + } + } +} + +#[cfg(verus_keep_ghost)] +pub mod verify { + use super::*; + use crate::verify::history_specs::{self as language, Regex, Transition}; + use crate::verify::history_specs::{EventView, Subst}; + use alloc::boxed::Box; + use vstd::std_specs::cmp::{OrdSpecImpl, PartialEqSpecImpl, PartialOrdSpecImpl}; + + macro_rules! id_model { + ($id:ident, $ids:ident, $lemma:ident) => { verus! { + impl View for $id { + type V = nat; + open(crate) spec fn view(&self) -> nat { self.0 as nat } + } + impl PartialEqSpecImpl for $id { + open spec fn obeys_eq_spec() -> bool { true } + open spec fn eq_spec(&self, other: &Self) -> bool { self@ == other@ } + } + impl history_syntax::key_hash::specs::KeyHashSpecImpl for $id { + open spec fn obeys_hash_spec() -> bool { true } + open spec fn hash_spec(&self) -> u64 { self@ as u64 } + } + impl OrdSpecImpl for $id { + open spec fn obeys_cmp_spec() -> bool { true } + open spec fn cmp_spec(&self, other: &Self) -> core::cmp::Ordering { + if self@ < other@ { core::cmp::Ordering::Less } + else if self@ == other@ { core::cmp::Ordering::Equal } + else { core::cmp::Ordering::Greater } + } + } + impl PartialOrdSpecImpl for $id { + open spec fn obeys_partial_cmp_spec() -> bool { true } + open spec fn partial_cmp_spec(&self, other: &Self) -> Option { + Some(if self@ < other@ { core::cmp::Ordering::Less } + else if self@ == other@ { core::cmp::Ordering::Equal } + else { core::cmp::Ordering::Greater }) + } + } + impl $id { + /// Proof-only ID with an exact view; the payload itself stays crate-private. + pub closed spec fn from_view(value: u32) -> Self { Self(value) } + pub broadcast proof fn lemma_from_view(value: u32) + ensures #[trigger] Self::from_view(value)@ == value as nat, + {} + /// The payload bound and injectivity that crate-local proofs read off `self.0`. + pub broadcast proof fn lemma_view(id: Self) + ensures (#[trigger] id@) <= u32::MAX, id == Self::from_view(id@ as u32), + {} + /// Equality and order are those of the view on `nat`: vstd's total-order laws, + /// which `sort_unstable`, `binary_search` and `dedup` require of their elements. + pub proof fn lemma_obeys_cmp() + ensures vstd::laws_cmp::obeys_cmp::(), + { + reveal(vstd::laws_eq::obeys_eq_spec_properties); + reveal(vstd::laws_cmp::obeys_partial_cmp_spec_properties); + reveal(vstd::laws_cmp::obeys_cmp_partial_ord); + reveal(vstd::laws_cmp::obeys_cmp_ord); + } + /// `eq_spec` compares the view and `hash_spec` is a function of the payload, so an + /// ID is a hash key (`key_laws`). + pub proof fn lemma_key_laws() + ensures crate::spec::hypotheses::key_laws::(), + { + } + } + pub open spec fn $ids(ids: Seq<$id>) -> Seq { + Seq::new(ids.len(), |i: int| ids[i]@) + } + pub proof fn $lemma(a: Seq<$id>, b: Seq<$id>) + ensures ($ids(a) == $ids(b)) == (a == b), + { + if $ids(a) == $ids(b) { + assert($ids(a).len() == a.len()); + assert($ids(b).len() == b.len()); + assert(a.len() == b.len()); + assert forall|i: int| 0 <= i < a.len() implies a[i] == b[i] by { + assert($ids(a)[i] == a[i]@); + assert($ids(b)[i] == b[i]@); + } + assert(a =~= b); + } + } + }}; + } + id_model!(TestId, test_ids, lemma_test_ids_eq); + id_model!(RegexId, regex_ids, lemma_regex_ids_eq); + id_model!(TransitionId, transition_ids, lemma_transition_ids_eq); + + verus! { + + pub enum GTerm { Constant(nat), Variable(Component) } + pub enum Primitive { Eq(Component, GTerm) } + pub enum TestNode { True, False, Atom(Primitive, bool), And(Seq), Or(Seq) } + pub enum Test { True, False, Atom(Primitive, bool), And(Seq), Or(Seq) } + pub enum RegexKindNode { + Empty, All, Epsilon, Test(nat), Union(Seq), Concat(Seq), + Star(nat), Intersect(Seq), Not(nat), + } + pub struct RegexNode { pub kind: RegexKindNode, pub nullable: bool } + pub enum TransitionNode { + Const(nat), If(nat, nat, nat), Union(Seq), Intersect(Seq), + Not(nat), Append(nat, Seq), + } + pub struct ConstantsModel { + pub test_true: nat, pub test_false: nat, + pub empty: nat, pub all: nat, pub epsilon: nat, + pub transition_empty: nat, pub transition_all: nat, pub transition_epsilon: nat, + } + pub struct Graph { + pub tests: Seq, pub regexes: Seq, + pub transitions: Seq, pub constants: ConstantsModel, + } + pub enum TestHeadNode { True, False, Atom(Primitive, bool), And(nat), Or(nat) } + pub enum RegexHeadNode { + Empty, All, Epsilon, Test(nat), Union(nat), Concat(nat), Star(nat), Intersect(nat), Not(nat), + } + pub enum TransitionHeadNode { Const(nat), If(nat, nat, nat), Union(nat), Intersect(nat), Not(nat), Append(nat, nat) } + + impl PartialEqSpecImpl for super::Term { + open spec fn obeys_eq_spec() -> bool { true } + open spec fn eq_spec(&self, other: &Self) -> bool { self@ == other@ } + } + impl PartialEqSpecImpl for super::Primitive { + open spec fn obeys_eq_spec() -> bool { true } + open spec fn eq_spec(&self, other: &Self) -> bool { self@ == other@ } + } + impl PartialEqSpecImpl for TestView<'_> { + open spec fn obeys_eq_spec() -> bool { true } + open spec fn eq_spec(&self, other: &Self) -> bool { self@ == other@ } + } + impl PartialEqSpecImpl for RegexKindView<'_> { + open spec fn obeys_eq_spec() -> bool { true } + open spec fn eq_spec(&self, other: &Self) -> bool { self@ == other@ } + } + impl PartialEqSpecImpl for RegexView<'_> { + open spec fn obeys_eq_spec() -> bool { true } + open spec fn eq_spec(&self, other: &Self) -> bool { self@ == other@ } + } + impl PartialEqSpecImpl for TransitionView<'_> { + open spec fn obeys_eq_spec() -> bool { true } + open spec fn eq_spec(&self, other: &Self) -> bool { self@ == other@ } + } + + impl View for super::Term { + type V = GTerm; + open spec fn view(&self) -> GTerm { + match self { super::Term::Constant(c) => GTerm::Constant(*c as nat), super::Term::Variable(v) => GTerm::Variable(*v) } + } + } + impl View for super::Primitive { + type V = Primitive; + open spec fn view(&self) -> Primitive { + match self { super::Primitive::Eq { field, term } => Primitive::Eq(*field, term@) } + } + } + impl View for Bindings { + type V = Subst; + open(crate) spec fn view(&self) -> Subst { + Seq::new(self.arity as nat, |i: int| self.slots@[i] as nat) + } + } + impl PartialEqSpecImpl for Bindings { + open spec fn obeys_eq_spec() -> bool { true } + open spec fn eq_spec(&self, other: &Self) -> bool { self@ == other@ } + } + /// Binding coordinates fit u64, including zero-valued unbound slots. + pub broadcast proof fn lemma_bindings_view_wf(bindings: Bindings) + ensures language::event_wf(#[trigger] bindings@, bindings@.len()), + {} + + /// Representation facts restored for proofs outside this crate, where the payload views are opaque. + pub broadcast group group_kernel_views { + TestId::lemma_from_view, TestId::lemma_view, + RegexId::lemma_from_view, RegexId::lemma_view, + TransitionId::lemma_from_view, TransitionId::lemma_view, + lemma_bindings_view_wf, + } + + impl View for TestView<'_> { + type V = TestNode; + open spec fn view(&self) -> TestNode { + match self { + TestView::True => TestNode::True, TestView::False => TestNode::False, + TestView::Atom { primitive, positive } => TestNode::Atom(primitive@, *positive), + TestView::And(ids) => TestNode::And(test_ids(ids@)), TestView::Or(ids) => TestNode::Or(test_ids(ids@)), + } + } + } + impl View for RegexKindView<'_> { + type V = RegexKindNode; + open spec fn view(&self) -> RegexKindNode { + match self { + RegexKindView::Empty => RegexKindNode::Empty, RegexKindView::All => RegexKindNode::All, + RegexKindView::Epsilon => RegexKindNode::Epsilon, RegexKindView::Test(t) => RegexKindNode::Test(t@), + RegexKindView::Union(ids) => RegexKindNode::Union(regex_ids(ids@)), + RegexKindView::Concat(ids) => RegexKindNode::Concat(regex_ids(ids@)), + RegexKindView::Star(r) => RegexKindNode::Star(r@), + RegexKindView::Intersect(ids) => RegexKindNode::Intersect(regex_ids(ids@)), + RegexKindView::Not(r) => RegexKindNode::Not(r@), + } + } + } + impl View for RegexView<'_> { + type V = RegexNode; + open spec fn view(&self) -> RegexNode { RegexNode { kind: self.kind@, nullable: self.nullable } } + } + impl View for TransitionView<'_> { + type V = TransitionNode; + open spec fn view(&self) -> TransitionNode { + match self { + TransitionView::Const(r) => TransitionNode::Const(r@), + TransitionView::If { test, then_transition, else_transition } => TransitionNode::If(test@, then_transition@, else_transition@), + TransitionView::Union(ids) => TransitionNode::Union(transition_ids(ids@)), + TransitionView::Intersect(ids) => TransitionNode::Intersect(transition_ids(ids@)), + TransitionView::Not(t) => TransitionNode::Not(t@), + TransitionView::Append { transition, suffix } => TransitionNode::Append(transition@, regex_ids(suffix@)), + } + } + } + impl View for Constants { + type V = ConstantsModel; + open spec fn view(&self) -> ConstantsModel { + ConstantsModel { test_true: self.test_true@, test_false: self.test_false@, + empty: self.empty@, all: self.all@, epsilon: self.epsilon@, + transition_empty: self.transition_empty@, transition_all: self.transition_all@, + transition_epsilon: self.transition_epsilon@ } + } + } + impl View for AtomSet { + type V = Seq; + open(super) spec fn view(&self) -> Seq { self.ids@ } + } + impl View for TestHead { + type V = TestHeadNode; + open spec fn view(&self) -> TestHeadNode { + match self { + TestHead::True => TestHeadNode::True, TestHead::False => TestHeadNode::False, + TestHead::Atom(p, b) => TestHeadNode::Atom(p@, *b), + TestHead::And(n) => TestHeadNode::And(*n as nat), TestHead::Or(n) => TestHeadNode::Or(*n as nat), + } + } + } + impl View for RegexHead { + type V = RegexHeadNode; + open spec fn view(&self) -> RegexHeadNode { + match self { + RegexHead::Empty => RegexHeadNode::Empty, RegexHead::All => RegexHeadNode::All, + RegexHead::Epsilon => RegexHeadNode::Epsilon, RegexHead::Test(t) => RegexHeadNode::Test(t@), + RegexHead::Union(n) => RegexHeadNode::Union(*n as nat), RegexHead::Concat(n) => RegexHeadNode::Concat(*n as nat), + RegexHead::Star(r) => RegexHeadNode::Star(r@), RegexHead::Intersect(n) => RegexHeadNode::Intersect(*n as nat), + RegexHead::Not(r) => RegexHeadNode::Not(r@), + } + } + } + impl View for TransitionHead { + type V = TransitionHeadNode; + open spec fn view(&self) -> TransitionHeadNode { + match self { + TransitionHead::Const(r) => TransitionHeadNode::Const(r@), + TransitionHead::If(t, a, b) => TransitionHeadNode::If(t@, a@, b@), + TransitionHead::Union(n) => TransitionHeadNode::Union(*n as nat), + TransitionHead::Intersect(n) => TransitionHeadNode::Intersect(*n as nat), + TransitionHead::Not(t) => TransitionHeadNode::Not(t@), + TransitionHead::Append(t, n) => TransitionHeadNode::Append(t@, *n as nat), + } + } + } + + pub open spec fn test_node_head(node: TestNode) -> TestHeadNode { + match node { + TestNode::True => TestHeadNode::True, TestNode::False => TestHeadNode::False, + TestNode::Atom(p, b) => TestHeadNode::Atom(p, b), TestNode::And(cs) => TestHeadNode::And(cs.len()), TestNode::Or(cs) => TestHeadNode::Or(cs.len()), + } + } + pub open spec fn regex_node_head(node: RegexKindNode) -> RegexHeadNode { + match node { + RegexKindNode::Empty => RegexHeadNode::Empty, RegexKindNode::All => RegexHeadNode::All, + RegexKindNode::Epsilon => RegexHeadNode::Epsilon, RegexKindNode::Test(t) => RegexHeadNode::Test(t), + RegexKindNode::Union(cs) => RegexHeadNode::Union(cs.len()), RegexKindNode::Concat(cs) => RegexHeadNode::Concat(cs.len()), + RegexKindNode::Star(r) => RegexHeadNode::Star(r), RegexKindNode::Intersect(cs) => RegexHeadNode::Intersect(cs.len()), + RegexKindNode::Not(r) => RegexHeadNode::Not(r), + } + } + pub open spec fn transition_node_head(node: TransitionNode) -> TransitionHeadNode { + match node { + TransitionNode::Const(r) => TransitionHeadNode::Const(r), TransitionNode::If(t, a, b) => TransitionHeadNode::If(t, a, b), + TransitionNode::Union(cs) => TransitionHeadNode::Union(cs.len()), TransitionNode::Intersect(cs) => TransitionHeadNode::Intersect(cs.len()), + TransitionNode::Not(t) => TransitionHeadNode::Not(t), TransitionNode::Append(t, rs) => TransitionHeadNode::Append(t, rs.len()), + } + } + pub open spec fn test_node_child(node: TestNode, i: nat) -> Option { + match node { TestNode::And(cs) | TestNode::Or(cs) => if i < cs.len() { Some(cs[i as int]) } else { None }, _ => None } + } + pub open spec fn regex_node_child(node: RegexKindNode, i: nat) -> Option { + match node { RegexKindNode::Union(cs) | RegexKindNode::Concat(cs) | RegexKindNode::Intersect(cs) => if i < cs.len() { Some(cs[i as int]) } else { None }, _ => None } + } + pub open spec fn transition_node_child(node: TransitionNode, i: nat) -> Option { + match node { TransitionNode::Union(cs) | TransitionNode::Intersect(cs) => if i < cs.len() { Some(cs[i as int]) } else { None }, _ => None } + } + pub open spec fn transition_node_suffix(node: TransitionNode, i: nat) -> Option { + match node { TransitionNode::Append(_, cs) => if i < cs.len() { Some(cs[i as int]) } else { None }, _ => None } + } + + pub open spec fn bounded(cs: Seq, bound: nat) -> bool { + forall|i: int| 0 <= i < cs.len() ==> #[trigger] cs[i] < bound + } + pub open spec fn strictly_increasing(cs: Seq) -> bool { + forall|i: int, j: int| 0 <= i < j < cs.len() ==> #[trigger] cs[i] < #[trigger] cs[j] + } + pub open spec fn nondecreasing(cs: Seq) -> bool { + forall|i: int, j: int| 0 <= i < j < cs.len() ==> #[trigger] cs[i] <= #[trigger] cs[j] + } + pub open spec fn test_node_wf_at(g: Graph, node: TestNode, bound: nat) -> bool { + match node { + TestNode::And(cs) | TestNode::Or(cs) => bounded(cs, bound) && strictly_increasing(cs), + _ => true, + } + } + pub open spec fn test_node_wf(g: Graph, node: TestNode) -> bool { test_node_wf_at(g, node, g.tests.len()) } + pub open spec fn regex_kind_wf_at(g: Graph, node: RegexKindNode, bound: nat) -> bool { + match node { + RegexKindNode::Test(t) => t < g.tests.len(), + RegexKindNode::Union(cs) | RegexKindNode::Intersect(cs) => bounded(cs, bound) && strictly_increasing(cs), + RegexKindNode::Concat(cs) => bounded(cs, bound), + RegexKindNode::Star(r) | RegexKindNode::Not(r) => r < bound, + _ => true, + } + } + pub open spec fn transition_node_wf_at(g: Graph, node: TransitionNode, bound: nat) -> bool { + match node { + TransitionNode::Const(r) => r < g.regexes.len(), + TransitionNode::If(t, a, b) => t < g.tests.len() && a < bound && b < bound, + TransitionNode::Union(cs) | TransitionNode::Intersect(cs) => bounded(cs, bound) && strictly_increasing(cs), + TransitionNode::Not(t) => t < bound, + TransitionNode::Append(t, rs) => t < bound && bounded(rs, g.regexes.len()), + } + } + pub open spec fn transition_node_wf(g: Graph, node: TransitionNode) -> bool { transition_node_wf_at(g, node, g.transitions.len()) } + + pub open spec fn lift_test(g: Graph, i: nat) -> Test + decreases i, 1nat, + { + if i >= g.tests.len() { Test::False } else { + match g.tests[i as int] { + TestNode::True => Test::True, TestNode::False => Test::False, TestNode::Atom(p, b) => Test::Atom(p, b), + TestNode::And(cs) => Test::And(lift_tests(g, cs, i)), TestNode::Or(cs) => Test::Or(lift_tests(g, cs, i)), + } + } + } + pub open spec fn lift_tests(g: Graph, cs: Seq, bound: nat) -> Seq + decreases bound, 0nat, + { + Seq::new(cs.len(), |j: int| if 0 <= j < cs.len() && cs[j] < bound { lift_test(g, cs[j]) } else { Test::False }) + } + pub open spec fn lift_regex(g: Graph, i: nat) -> Regex + decreases i, 2nat, + { + if i >= g.regexes.len() { Regex::Empty } else { lift_regex_kind_bounded(g, g.regexes[i as int].kind, i) } + } + pub open spec fn lift_regex_kind_bounded(g: Graph, node: RegexKindNode, bound: nat) -> Regex + decreases bound, 1nat, + { + match node { + RegexKindNode::Empty => Regex::Empty, RegexKindNode::All => Regex::All, RegexKindNode::Epsilon => Regex::Epsilon, + RegexKindNode::Test(t) => Regex::Test(lift_test(g, t)), + RegexKindNode::Union(cs) => Regex::Union(lift_regexes_bounded(g, cs, bound)), + RegexKindNode::Concat(cs) => Regex::Concat(lift_regexes_bounded(g, cs, bound)), + RegexKindNode::Intersect(cs) => Regex::Intersect(lift_regexes_bounded(g, cs, bound)), + RegexKindNode::Star(r) => Regex::Star(Box::new(if r < bound { lift_regex(g, r) } else { Regex::Empty })), + RegexKindNode::Not(r) => Regex::Not(Box::new(if r < bound { lift_regex(g, r) } else { Regex::Empty })), + } + } + pub open spec fn lift_regexes_bounded(g: Graph, cs: Seq, bound: nat) -> Seq> + decreases bound, 0nat, + { + Seq::new(cs.len(), |j: int| if 0 <= j < cs.len() && cs[j] < bound { lift_regex(g, cs[j]) } else { Regex::Empty }) + } + pub open spec fn lift_regex_kind(g: Graph, node: RegexKindNode) -> Regex { lift_regex_kind_bounded(g, node, g.regexes.len()) } + pub open spec fn lift_regexes(g: Graph, cs: Seq) -> Seq> { + Seq::new(cs.len(), |j: int| lift_regex(g, cs[j])) + } + pub open spec fn lift_transition(g: Graph, i: nat) -> Transition + decreases i, 1nat, + { + if i >= g.transitions.len() { Transition::Const(Regex::Empty) } else { + match g.transitions[i as int] { + TransitionNode::Const(r) => Transition::Const(lift_regex(g, r)), + TransitionNode::If(t, a, b) => Transition::If(lift_test(g, t), + Box::new(if a < i { lift_transition(g, a) } else { Transition::Const(Regex::Empty) }), + Box::new(if b < i { lift_transition(g, b) } else { Transition::Const(Regex::Empty) })), + TransitionNode::Union(cs) => Transition::Union(lift_transitions(g, cs, i)), + TransitionNode::Intersect(cs) => Transition::Intersect(lift_transitions(g, cs, i)), + TransitionNode::Not(t) => Transition::Not(Box::new(if t < i { lift_transition(g, t) } else { Transition::Const(Regex::Empty) })), + TransitionNode::Append(t, rs) => Transition::Append( + Box::new(if t < i { lift_transition(g, t) } else { Transition::Const(Regex::Empty) }), lift_regexes(g, rs)), + } + } + } + pub open spec fn lift_transitions(g: Graph, cs: Seq, bound: nat) -> Seq> + decreases bound, 0nat, + { + Seq::new(cs.len(), |j: int| if 0 <= j < cs.len() && cs[j] < bound { lift_transition(g, cs[j]) } else { Transition::Const(Regex::Empty) }) + } + + pub open spec fn regex_node_wf_at(g: Graph, node: RegexNode, bound: nat) -> bool { + regex_kind_wf_at(g, node.kind, bound) + && node.nullable == language::nullable(lift_regex_kind_bounded(g, node.kind, bound)) + } + pub open spec fn regex_node_wf(g: Graph, node: RegexNode) -> bool { regex_node_wf_at(g, node, g.regexes.len()) } + pub open spec fn tables_wf(g: Graph) -> bool { + (forall|i: int| 0 <= i < g.tests.len() ==> test_node_wf_at(g, #[trigger] g.tests[i], i as nat)) + && (forall|i: int| 0 <= i < g.regexes.len() ==> regex_node_wf_at(g, #[trigger] g.regexes[i], i as nat)) + && (forall|i: int| 0 <= i < g.transitions.len() ==> transition_node_wf_at(g, #[trigger] g.transitions[i], i as nat)) + } + pub open spec fn constants_wf(g: Graph) -> bool { + let c = g.constants; + c.test_true < g.tests.len() && g.tests[c.test_true as int] == TestNode::True + && c.test_false < g.tests.len() && g.tests[c.test_false as int] == TestNode::False + && c.empty < g.regexes.len() && g.regexes[c.empty as int] == (RegexNode { kind: RegexKindNode::Empty, nullable: false }) + && c.all < g.regexes.len() && g.regexes[c.all as int] == (RegexNode { kind: RegexKindNode::All, nullable: true }) + && c.epsilon < g.regexes.len() && g.regexes[c.epsilon as int] == (RegexNode { kind: RegexKindNode::Epsilon, nullable: true }) + && c.transition_empty < g.transitions.len() && g.transitions[c.transition_empty as int] == TransitionNode::Const(c.empty) + && c.transition_all < g.transitions.len() && g.transitions[c.transition_all as int] == TransitionNode::Const(c.all) + && c.transition_epsilon < g.transitions.len() && g.transitions[c.transition_epsilon as int] == TransitionNode::Const(c.epsilon) + } + pub open spec fn unique_nodes(g: Graph) -> bool { + g.tests.no_duplicates() && g.regexes.no_duplicates() && g.transitions.no_duplicates() + } + #[verifier::opaque] + pub open spec fn graph_wf(g: Graph) -> bool { tables_wf(g) && constants_wf(g) && unique_nodes(g) } + + pub proof fn lemma_graph_wf_elim(g: Graph) + requires graph_wf(g), + ensures tables_wf(g), constants_wf(g), unique_nodes(g), + { reveal(graph_wf); } + + pub proof fn lemma_graph_wf_intro(g: Graph) + requires tables_wf(g), constants_wf(g), unique_nodes(g), + ensures graph_wf(g), + { reveal(graph_wf); } + + pub proof fn lemma_graph_test_wf(g: Graph, id: nat) + requires graph_wf(g), id < g.tests.len(), + ensures test_node_wf_at(g, g.tests[id as int], id), + { reveal(graph_wf); } + + pub proof fn lemma_graph_regex_wf(g: Graph, id: nat) + requires graph_wf(g), id < g.regexes.len(), + ensures regex_node_wf_at(g, g.regexes[id as int], id), + g.regexes[id as int].nullable == language::nullable(lift_regex(g, id)), + { reveal(graph_wf); } + + pub proof fn lemma_graph_transition_wf(g: Graph, id: nat) + requires graph_wf(g), id < g.transitions.len(), + ensures transition_node_wf_at(g, g.transitions[id as int], id), + { reveal(graph_wf); } + + pub open spec fn tables_extend(old: Graph, new: Graph) -> bool { + old.tests.is_prefix_of(new.tests) && old.regexes.is_prefix_of(new.regexes) && old.transitions.is_prefix_of(new.transitions) + } + pub open spec fn graph_extends(old: Graph, new: Graph) -> bool { tables_extend(old, new) && old.constants == new.constants } + pub open spec fn primitive_holds(theta: Subst, p: Primitive, e: EventView) -> bool { + match p { + Primitive::Eq(field, term) => field.0 < e.len() && match term { + GTerm::Constant(c) => language::field_value(e, field) == c, + GTerm::Variable(v) => v.0 < theta.len() + && language::field_value(e, field) == language::field_value(theta, v), + }, + } + } + pub open spec fn test_holds(theta: Subst, t: Test, e: EventView) -> bool + decreases t, + { + match t { + Test::True => true, Test::False => false, Test::Atom(p, positive) => primitive_holds(theta, p, e) == positive, + Test::And(cs) => forall|i: int| 0 <= i < cs.len() ==> test_holds(theta, cs[i], e), + Test::Or(cs) => exists|i: int| 0 <= i < cs.len() && test_holds(theta, cs[i], e), + } + } + pub open spec fn gsem(theta: Subst) -> spec_fn(Test, EventView) -> bool { |t: Test, e: EventView| test_holds(theta, t, e) } + pub open spec fn regex_lang(g: Graph, theta: Subst, i: nat, word: Seq) -> bool { + language::numeric_lang(gsem(theta), lift_regex(g, i), word) + } + pub open spec fn atom_ids_wf(g: Graph, ids: Seq) -> bool { + strictly_increasing(test_ids(ids)) + && forall|i: int| 0 <= i < ids.len() ==> ids[i]@ < g.tests.len() + && #[trigger] g.tests[ids[i]@ as int] matches TestNode::Atom(_, true) + } + + pub open spec fn atom_prefix_wf(g: Graph, ids: Seq, n: nat) -> bool { + n <= ids.len() + && (forall|i: int| 0 <= i < n ==> ids[i]@ < g.tests.len() + && #[trigger] g.tests[ids[i]@ as int] matches TestNode::Atom(_, true)) + && (forall|i: int, j: int| 0 <= i < j < n ==> #[trigger] ids[i]@ < #[trigger] ids[j]@) + } + + pub proof fn lemma_constant_atoms_disjoint(theta: Subst, field: Component, a: nat, b: nat, event: EventView) + requires a != b, + ensures !(primitive_holds(theta, Primitive::Eq(field, GTerm::Constant(a)), event) + && primitive_holds(theta, Primitive::Eq(field, GTerm::Constant(b)), event)), + {} + + pub proof fn lemma_lift_test_stable(a: Graph, b: Graph, i: nat) + requires tables_extend(a, b), i < a.tests.len(), + ensures lift_test(a, i) == lift_test(b, i), + decreases i, + { + assert(a.tests[i as int] == b.tests[i as int]); + match a.tests[i as int] { + TestNode::And(cs) | TestNode::Or(cs) => { + assert forall|j: int| 0 <= j < cs.len() + implies lift_tests(a, cs, i)[j] == lift_tests(b, cs, i)[j] by { + if cs[j] < i { lemma_lift_test_stable(a, b, cs[j]); } + } + assert(lift_tests(a, cs, i) =~= lift_tests(b, cs, i)); + }, + _ => {}, + } + } + + pub proof fn lemma_lift_regex_stable(a: Graph, b: Graph, i: nat) + requires tables_wf(a), tables_extend(a, b), i < a.regexes.len(), + ensures lift_regex(a, i) == lift_regex(b, i), + decreases i, 2nat, + { + assert(a.regexes[i as int] == b.regexes[i as int]); + lemma_lift_regex_kind_stable(a, b, a.regexes[i as int].kind, i); + } + + pub proof fn lemma_lift_regex_kind_stable(a: Graph, b: Graph, node: RegexKindNode, bound: nat) + requires tables_wf(a), tables_extend(a, b), bound <= a.regexes.len(), regex_kind_wf_at(a, node, bound), + ensures lift_regex_kind_bounded(a, node, bound) == lift_regex_kind_bounded(b, node, bound), + decreases bound, 1nat, + { + match node { + RegexKindNode::Test(t) => { lemma_lift_test_stable(a, b, t); }, + RegexKindNode::Star(r) | RegexKindNode::Not(r) => { lemma_lift_regex_stable(a, b, r); }, + RegexKindNode::Union(cs) | RegexKindNode::Concat(cs) | RegexKindNode::Intersect(cs) => { + assert forall|j: int| 0 <= j < cs.len() + implies lift_regexes_bounded(a, cs, bound)[j] == lift_regexes_bounded(b, cs, bound)[j] by { + lemma_lift_regex_stable(a, b, cs[j]); + } + assert(lift_regexes_bounded(a, cs, bound) =~= lift_regexes_bounded(b, cs, bound)); + }, + _ => {}, + } + } + + pub proof fn lemma_lift_transition_stable(a: Graph, b: Graph, i: nat) + requires tables_wf(a), tables_extend(a, b), i < a.transitions.len(), + ensures lift_transition(a, i) == lift_transition(b, i), + decreases i, + { + assert(a.transitions[i as int] == b.transitions[i as int]); + match a.transitions[i as int] { + TransitionNode::Const(r) => { lemma_lift_regex_stable(a, b, r); }, + TransitionNode::If(t, x, y) => { + lemma_lift_test_stable(a, b, t); + lemma_lift_transition_stable(a, b, x); + lemma_lift_transition_stable(a, b, y); + }, + TransitionNode::Not(t) => { lemma_lift_transition_stable(a, b, t); }, + TransitionNode::Union(cs) | TransitionNode::Intersect(cs) => { + assert forall|j: int| 0 <= j < cs.len() + implies lift_transitions(a, cs, i)[j] == lift_transitions(b, cs, i)[j] by { + lemma_lift_transition_stable(a, b, cs[j]); + } + assert(lift_transitions(a, cs, i) =~= lift_transitions(b, cs, i)); + }, + TransitionNode::Append(t, rs) => { + lemma_lift_transition_stable(a, b, t); + assert forall|j: int| 0 <= j < rs.len() + implies lift_regexes(a, rs)[j] == lift_regexes(b, rs)[j] by { + lemma_lift_regex_stable(a, b, rs[j]); + } + assert(lift_regexes(a, rs) =~= lift_regexes(b, rs)); + }, + } + } + + pub proof fn lemma_lift_stable_under_extends(a: Graph, b: Graph) + requires tables_wf(a), tables_extend(a, b), + ensures + forall|i: nat| i < a.tests.len() ==> lift_test(a, i) == lift_test(b, i), + forall|i: nat| i < a.regexes.len() ==> lift_regex(a, i) == lift_regex(b, i), + forall|i: nat| i < a.transitions.len() ==> lift_transition(a, i) == lift_transition(b, i), + { + assert forall|i: nat| i < a.tests.len() implies lift_test(a, i) == lift_test(b, i) by { lemma_lift_test_stable(a, b, i); } + assert forall|i: nat| i < a.regexes.len() implies lift_regex(a, i) == lift_regex(b, i) by { lemma_lift_regex_stable(a, b, i); } + assert forall|i: nat| i < a.transitions.len() implies lift_transition(a, i) == lift_transition(b, i) by { lemma_lift_transition_stable(a, b, i); } + } + + pub proof fn lemma_old_nodes_wf_under_extends(a: Graph, b: Graph) + requires tables_wf(a), tables_extend(a, b), + ensures + forall|i: int| 0 <= i < a.tests.len() ==> test_node_wf_at(b, #[trigger] a.tests[i], i as nat), + forall|i: int| 0 <= i < a.regexes.len() ==> regex_node_wf_at(b, #[trigger] a.regexes[i], i as nat), + forall|i: int| 0 <= i < a.transitions.len() ==> transition_node_wf_at(b, #[trigger] a.transitions[i], i as nat), + { + assert forall|i: int| 0 <= i < a.regexes.len() + implies regex_node_wf_at(b, #[trigger] a.regexes[i], i as nat) by { + lemma_lift_regex_kind_stable(a, b, a.regexes[i].kind, i as nat); + } + assert forall|i: int| 0 <= i < a.transitions.len() + implies transition_node_wf_at(b, #[trigger] a.transitions[i], i as nat) by { + match a.transitions[i] { + TransitionNode::Append(_, rs) => { + assert forall|j: int| 0 <= j < rs.len() implies #[trigger] rs[j] < b.regexes.len() by {} + }, + _ => {}, + } + } + } + + pub open spec fn append_test(g: Graph, node: TestNode) -> Graph { Graph { tests: g.tests.push(node), ..g } } + pub open spec fn append_regex(g: Graph, node: RegexNode) -> Graph { Graph { regexes: g.regexes.push(node), ..g } } + pub open spec fn append_transition(g: Graph, node: TransitionNode) -> Graph { Graph { transitions: g.transitions.push(node), ..g } } + + pub proof fn lemma_constants_stable(a: Graph, b: Graph) + requires constants_wf(a), graph_extends(a, b), + ensures constants_wf(b), + {} + + pub proof fn lemma_tables_wf_append_test(g: Graph, node: TestNode) + requires tables_wf(g), test_node_wf(g, node), + ensures tables_wf(append_test(g, node)), graph_extends(g, append_test(g, node)), + graph_wf(g) && !g.tests.contains(node) ==> graph_wf(append_test(g, node)), + { + reveal(graph_wf); + let next = append_test(g, node); + lemma_old_nodes_wf_under_extends(g, next); + assert forall|i: int| 0 <= i < next.tests.len() + implies test_node_wf_at(next, #[trigger] next.tests[i], i as nat) by { + if i == g.tests.len() {} else { assert(next.tests[i] == g.tests[i]); } + } + if constants_wf(g) { lemma_constants_stable(g, next); } + } + + pub proof fn lemma_tables_wf_append_regex(g: Graph, node: RegexNode) + requires tables_wf(g), regex_node_wf(g, node), + ensures tables_wf(append_regex(g, node)), graph_extends(g, append_regex(g, node)), + graph_wf(g) && !g.regexes.contains(node) ==> graph_wf(append_regex(g, node)), + { + reveal(graph_wf); + let next = append_regex(g, node); + lemma_old_nodes_wf_under_extends(g, next); + lemma_lift_regex_kind_stable(g, next, node.kind, g.regexes.len()); + assert forall|i: int| 0 <= i < next.regexes.len() + implies regex_node_wf_at(next, #[trigger] next.regexes[i], i as nat) by { + if i == g.regexes.len() {} else { assert(next.regexes[i] == g.regexes[i]); } + } + if constants_wf(g) { lemma_constants_stable(g, next); } + } + + pub proof fn lemma_tables_wf_append_transition(g: Graph, node: TransitionNode) + requires tables_wf(g), transition_node_wf(g, node), + ensures tables_wf(append_transition(g, node)), graph_extends(g, append_transition(g, node)), + graph_wf(g) && !g.transitions.contains(node) ==> graph_wf(append_transition(g, node)), + { + reveal(graph_wf); + let next = append_transition(g, node); + lemma_old_nodes_wf_under_extends(g, next); + assert forall|i: int| 0 <= i < next.transitions.len() + implies transition_node_wf_at(next, #[trigger] next.transitions[i], i as nat) by { + if i == g.transitions.len() {} else { assert(next.transitions[i] == g.transitions[i]); } + } + if constants_wf(g) { lemma_constants_stable(g, next); } + } + + } +} diff --git a/src/junco-core/src/lib.rs b/src/junco-core/src/lib.rs new file mode 100644 index 000000000..fa201d46a --- /dev/null +++ b/src/junco-core/src/lib.rs @@ -0,0 +1,37 @@ +#![no_std] +// Verus generates erased unsafe scaffolding for native specifications. +#![cfg_attr(not(verus_keep_ghost), forbid(unsafe_code))] +#![cfg_attr(verus_keep_ghost, feature(proc_macro_hygiene, allocator_api))] +#![cfg_attr(docsrs, feature(doc_cfg))] + +extern crate alloc; +#[cfg(any(feature = "std", test, feature = "test-util"))] +extern crate std; + +pub mod bits; +pub mod compile; +pub mod errors; +pub mod event; +pub mod flat; +pub mod flatten; +pub mod limits; +pub mod observation; +pub mod scope; + +#[cfg(feature = "runtime")] +#[cfg_attr(docsrs, doc(cfg(feature = "runtime")))] +pub mod kernel; + +#[cfg(feature = "test-util")] +#[cfg_attr(docsrs, doc(cfg(feature = "test-util")))] +pub mod reference; + +#[cfg(verus_keep_ghost)] +pub mod spec; +#[cfg(verus_keep_ghost)] +pub mod verify; + +pub use compile::{FlatEncoder, lower_flat}; +pub use errors::{CompileError, HistoryError}; +pub use event::{Grant, Request}; +pub use flatten::flatten_rule; diff --git a/src/utils/limits/error.rs b/src/junco-core/src/limits.rs similarity index 73% rename from src/utils/limits/error.rs rename to src/junco-core/src/limits.rs index 97de7f303..b329cc6f4 100644 --- a/src/utils/limits/error.rs +++ b/src/junco-core/src/limits.rs @@ -5,6 +5,7 @@ use core::fmt; use core::time::Duration; +use vstd::prelude::{verus_spec, verus_verify}; /// Errors reported when execution resource ceilings are enforced. #[derive(Clone, Copy, PartialEq, Eq)] @@ -90,3 +91,44 @@ impl fmt::Display for LimitError { } impl core::error::Error for LimitError {} + +#[cfg(verus_keep_ghost)] +vstd::prelude::verus! { + #[verifier::external_type_specification] + #[verifier::external_body] + pub struct ExLimitError(LimitError); +} + +/// Maximum retained symbolic graph payload in bytes. +#[verus_verify] +pub const MAX_GRAPH_BYTES: usize = 100 * 1024; + +/// Host resource observations used by the shared history engine. +#[verus_verify] +pub trait Limits { + fn checkpoint(&mut self) -> Result<(), LimitError>; + fn publication_checkpoint(&mut self) -> Result<(), LimitError>; + fn enforce_memory(&mut self) -> Result<(), LimitError>; +} + +/// No configured host budget; allocation and structural bounds still apply. +#[verus_verify] +pub struct Unmetered; + +#[verus_verify] +impl Limits for Unmetered { + #[verus_spec(result => ensures result == Ok(()))] + fn checkpoint(&mut self) -> Result<(), LimitError> { + Ok(()) + } + + #[verus_spec(result => ensures result == Ok(()))] + fn publication_checkpoint(&mut self) -> Result<(), LimitError> { + Ok(()) + } + + #[verus_spec(result => ensures result == Ok(()))] + fn enforce_memory(&mut self) -> Result<(), LimitError> { + Ok(()) + } +} diff --git a/src/junco-core/src/observation.rs b/src/junco-core/src/observation.rs new file mode 100644 index 000000000..9050cf234 --- /dev/null +++ b/src/junco-core/src/observation.rs @@ -0,0 +1,125 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use alloc::vec::Vec; +#[cfg(feature = "runtime")] +use smallvec::SmallVec; +use vstd::prelude::*; + +#[cfg(any(test, feature = "test-util"))] +std::thread_local! { + static RESERVATION_FAILURE_AFTER: core::cell::Cell> = const { + core::cell::Cell::new(None) + }; +} + +#[cfg(any(test, feature = "test-util"))] +pub struct ReservationFailureGuard(Option); + +#[cfg(any(test, feature = "test-util"))] +impl Drop for ReservationFailureGuard { + fn drop(&mut self) { + RESERVATION_FAILURE_AFTER.with(|remaining| remaining.set(self.0)); + } +} + +#[cfg(any(test, feature = "test-util"))] +pub fn fail_reservations_after(successful: usize) -> ReservationFailureGuard { + ReservationFailureGuard( + RESERVATION_FAILURE_AFTER.with(|remaining| remaining.replace(Some(successful))), + ) +} + +#[cfg(any(test, feature = "test-util"))] +pub fn reservation_checkpoint() -> Result<(), alloc::collections::TryReserveError> { + let fail = RESERVATION_FAILURE_AFTER.with(|remaining| match remaining.get() { + None => false, + Some(0) => true, + Some(count) => { + remaining.set(Some(count - 1)); + false + } + }); + if fail { + Vec::::new().try_reserve(usize::MAX) + } else { + Ok(()) + } +} + +// Native SmallVec contents are an explicit container boundary, shared by its leaves. +#[cfg(all(feature = "runtime", verus_keep_ghost))] +verus! { + #[verifier::external_trait_specification] + pub trait ExSmallVecArray { + type ExternalTraitSpecificationFor: smallvec::Array; + type Item; + } + + #[verifier::external_type_specification] + #[verifier::external_body] + #[verifier::accept_recursive_types(A)] + pub struct ExSmallVec(SmallVec); + + #[verifier::external_type_specification] + #[verifier::external_body] + pub struct ExCollectionAllocErr(smallvec::CollectionAllocErr); + + pub trait SmallVecSpecFns { + spec fn view(&self) -> Seq; + } + + impl SmallVecSpecFns for SmallVec { + uninterp spec fn view(&self) -> Seq; + } +} + +/// Capability for native reservation observations during one history operation. +#[verus_verify] +pub struct ObservationWorld; + +impl ObservationWorld { + // Native reservation may fail but must preserve every existing element. + #[verus_verify(external_body)] + #[verus_spec(result => ensures final(values)@ == old(values)@)] + #[inline] + pub fn try_reserve_vec( + &mut self, + values: &mut Vec, + additional: usize, + ) -> Result<(), alloc::collections::TryReserveError> { + #[cfg(any(test, feature = "test-util"))] + reservation_checkpoint()?; + values.try_reserve(additional) + } + + // Vec::try_reserve_exact is unsupported by Verus; reservation preserves elements. + #[verus_verify(external_body)] + #[verus_spec(result => ensures final(values)@ == old(values)@)] + #[inline] + pub fn try_reserve_vec_exact( + &mut self, + values: &mut Vec, + additional: usize, + ) -> Result<(), alloc::collections::TryReserveError> { + #[cfg(any(test, feature = "test-util"))] + reservation_checkpoint()?; + values.try_reserve_exact(additional) + } + + #[cfg(feature = "runtime")] + #[verus_verify(external_body)] + #[verus_spec(result => ensures final(values).view() == old(values).view())] + #[inline] + pub fn try_reserve_words( + &mut self, + values: &mut SmallVec<[u64; 2]>, + additional: usize, + ) -> Result<(), smallvec::CollectionAllocErr> { + #[cfg(any(test, feature = "test-util"))] + if reservation_checkpoint().is_err() { + return values.try_reserve_exact(usize::MAX); + } + values.try_reserve_exact(additional) + } +} diff --git a/src/junco-core/src/reference.rs b/src/junco-core/src/reference.rs new file mode 100644 index 000000000..88caa5cdc --- /dev/null +++ b/src/junco-core/src/reference.rs @@ -0,0 +1,548 @@ +//! Unverified reference evaluator for numeric history sources by Brzozowski derivatives, +//! kept (`test-util`) as a differential oracle for the symbolic `history-semantics` runtime. +//! +//! A history is in a rule's language iff folding [`Lang::step`] over its events ends in a +//! [`Lang::nullable`] language. Smart constructors apply similarity rules so residuals of the +//! usual `[any, ..., any]` and `star(...)` shapes stay small. + +use crate::errors::HistoryError; +use crate::flat::{FlatHead, FlatPair, FlatRegex, FlatTerm, FlatTest}; +use crate::limits::Limits; +use alloc::boxed::Box; +use alloc::vec::Vec; + +/// Deepest residual the evaluator builds or recurses over. +pub const MAX_REFERENCE_DEPTH: usize = 256; +/// Most nodes built while inflating a source or taking one derivative. +pub const MAX_REFERENCE_NODES: usize = 1 << 16; + +/// Whether `request` matches the head. Head variables bind their own coordinate, so a +/// matching request is also the bindings vector. +pub fn head_matches(head: &[FlatHead], request: &[u64]) -> bool { + head.len() == request.len() + && head.iter().zip(request).all(|(slot, value)| match slot { + FlatHead::Constant(constant) => constant == value, + FlatHead::Any | FlatHead::Bind => true, + }) +} + +/// Truth value of every test for one event. Validated sources only reference earlier tests, +/// so one pass in index order evaluates the DAG without recursion. +fn test_values(tests: &[FlatTest], event: &[u64], bindings: &[u64]) -> Vec { + let mut values: Vec = Vec::with_capacity(tests.len()); + for test in tests { + let child = |index: &u32| { + usize::try_from(*index) + .ok() + .and_then(|index| values.get(index)) + .copied() + .unwrap_or(false) + }; + let value = match test { + FlatTest::Bool(value) => *value, + FlatTest::Atom { + field, + term, + positive, + } => { + let expected = match term { + FlatTerm::Constant(constant) => Some(constant), + FlatTerm::Variable(variable) => bindings.get(variable.index()), + }; + match (event.get(field.index()), expected) { + (Some(actual), Some(expected)) => (actual == expected) == *positive, + _ => false, + } + } + FlatTest::And(children) => children.iter().all(child), + FlatTest::Or(children) => children.iter().any(child), + }; + values.push(value); + } + values +} + +/// Node counter shared by one inflation or one derivative. +struct Budget<'a, L> { + limits: &'a mut L, + nodes: usize, +} + +impl Budget<'_, L> { + fn charge(&mut self, nodes: usize) -> Result<(), HistoryError> { + self.limits.checkpoint()?; + self.nodes = self.nodes.saturating_add(nodes); + if self.nodes > MAX_REFERENCE_NODES { + return Err(HistoryError::GraphBudget { + limit: MAX_REFERENCE_NODES, + }); + } + Ok(()) + } + + fn clone(&mut self, lang: &Lang) -> Result { + self.charge(lang.size())?; + Ok(lang.clone()) + } +} + +/// A regular language over events; `Test(i)` is the single events satisfying test `i`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Lang { + Empty, + All, + Epsilon, + Test(u32), + Union(Vec), + Concat(Vec), + Intersect(Vec), + Star(Box), + Not(Box), +} + +// shortcut: structural dedup is quadratic in the number of alternatives; the symbolic +// checker hash-conses residuals when wide unions matter. +fn push_unique(children: &mut Vec, child: Lang) { + if !children.contains(&child) { + children.push(child); + } +} + +impl Lang { + fn union(children: Vec) -> Lang { + let mut out = Vec::new(); + for child in children { + match child { + Lang::Empty => {} + Lang::All => return Lang::All, + Lang::Union(inner) => inner.into_iter().for_each(|c| push_unique(&mut out, c)), + other => push_unique(&mut out, other), + } + } + match out.len() { + 0 => Lang::Empty, + 1 => out.pop().unwrap_or(Lang::Empty), + _ => Lang::Union(out), + } + } + + fn intersect(children: Vec) -> Lang { + let mut out = Vec::new(); + for child in children { + match child { + Lang::All => {} + Lang::Empty => return Lang::Empty, + Lang::Intersect(inner) => { + inner.into_iter().for_each(|c| push_unique(&mut out, c)); + } + other => push_unique(&mut out, other), + } + } + match out.len() { + 0 => Lang::All, + 1 => out.pop().unwrap_or(Lang::All), + _ => Lang::Intersect(out), + } + } + + fn concat(children: Vec) -> Lang { + let mut out = Vec::new(); + for child in children { + match child { + Lang::Epsilon => {} + Lang::Empty => return Lang::Empty, + Lang::Concat(inner) => out.extend(inner), + other => out.push(other), + } + } + match out.len() { + 0 => Lang::Epsilon, + 1 => out.pop().unwrap_or(Lang::Epsilon), + _ => Lang::Concat(out), + } + } + + fn star(inner: Lang) -> Lang { + match inner { + Lang::Empty | Lang::Epsilon => Lang::Epsilon, + Lang::All => Lang::All, + star @ Lang::Star(_) => star, + other => Lang::Star(Box::new(other)), + } + } + + fn not(inner: Lang) -> Lang { + match inner { + Lang::Empty => Lang::All, + Lang::All => Lang::Empty, + Lang::Not(inner) => *inner, + other => Lang::Not(Box::new(other)), + } + } + + /// Builds the language of `pair`'s root regex. + // shortcut: expands the source DAG into a tree under depth/node caps; fine for small + // differential corpora, never used to decide production requests. + pub fn inflate(pair: &FlatPair, limits: &mut L) -> Result { + let mut budget = Budget { limits, nodes: 0 }; + Self::inflate_node(&pair.regexes, pair.root, 0, &mut budget) + } + + fn inflate_node( + regexes: &[FlatRegex], + index: u32, + depth: usize, + budget: &mut Budget<'_, L>, + ) -> Result { + budget.charge(1)?; + check_depth(depth)?; + let regex = usize::try_from(index) + .ok() + .and_then(|index| regexes.get(index)) + .ok_or(HistoryError::GraphIndex)?; + let depth = depth.saturating_add(1); + let mut all = |children: &[u32]| -> Result, HistoryError> { + children + .iter() + .map(|child| Self::inflate_node(regexes, *child, depth, budget)) + .collect() + }; + Ok(match regex { + FlatRegex::Empty => Lang::Empty, + FlatRegex::All => Lang::All, + FlatRegex::Epsilon => Lang::Epsilon, + FlatRegex::Test(test) => Lang::Test(*test), + FlatRegex::Concat(children) => Self::concat(all(children)?), + FlatRegex::Union(children) => Self::union(all(children)?), + FlatRegex::Intersect(children) => Self::intersect(all(children)?), + FlatRegex::Star(child) => { + Self::star(Self::inflate_node(regexes, *child, depth, budget)?) + } + FlatRegex::Complement(child) => { + Self::not(Self::inflate_node(regexes, *child, depth, budget)?) + } + }) + } + + /// Whether the empty history is in the language. + pub fn nullable(&self) -> bool { + match self { + Lang::Empty | Lang::Test(_) => false, + Lang::All | Lang::Epsilon | Lang::Star(_) => true, + Lang::Union(children) => children.iter().any(Lang::nullable), + Lang::Concat(children) | Lang::Intersect(children) => { + children.iter().all(Lang::nullable) + } + Lang::Not(inner) => !inner.nullable(), + } + } + + fn size(&self) -> usize { + match self { + Lang::Empty | Lang::All | Lang::Epsilon | Lang::Test(_) => 1, + Lang::Union(children) | Lang::Concat(children) | Lang::Intersect(children) => children + .iter() + .fold(1, |total, child| total.saturating_add(child.size())), + Lang::Star(inner) | Lang::Not(inner) => inner.size().saturating_add(1), + } + } + + /// Residual after one event whose bindings come from the matched request. + pub fn step( + &self, + pair: &FlatPair, + event: &[u64], + bindings: &[u64], + limits: &mut L, + ) -> Result { + let holds = test_values(&pair.tests, event, bindings); + let next = self.derivative(&holds, &mut Budget { limits, nodes: 0 })?; + next.check_depths(0)?; + Ok(next) + } + + /// Derivative given the truth value of every test for one event. + fn derivative( + &self, + holds: &[bool], + budget: &mut Budget<'_, L>, + ) -> Result { + budget.charge(1)?; + Ok(match self { + Lang::Empty | Lang::Epsilon => Lang::Empty, + Lang::All => Lang::All, + Lang::Test(test) => { + let held = usize::try_from(*test) + .ok() + .and_then(|index| holds.get(index)) + .copied() + .unwrap_or(false); + if held { Lang::Epsilon } else { Lang::Empty } + } + Lang::Union(children) => Self::union( + children + .iter() + .map(|c| c.derivative(holds, budget)) + .collect::>()?, + ), + Lang::Intersect(children) => Self::intersect( + children + .iter() + .map(|c| c.derivative(holds, budget)) + .collect::>()?, + ), + Lang::Not(inner) => Self::not(inner.derivative(holds, budget)?), + Lang::Star(inner) => Self::concat(alloc::vec![ + inner.derivative(holds, budget)?, + budget.clone(self)? + ]), + Lang::Concat(children) => { + let mut alternatives = Vec::new(); + for (index, child) in children.iter().enumerate() { + let mut factors = alloc::vec![child.derivative(holds, budget)?]; + for rest in children.iter().skip(index.saturating_add(1)) { + factors.push(budget.clone(rest)?); + } + alternatives.push(Self::concat(factors)); + if !child.nullable() { + break; + } + } + Self::union(alternatives) + } + }) + } + + fn check_depths(&self, depth: usize) -> Result<(), HistoryError> { + check_depth(depth)?; + let depth = depth.saturating_add(1); + match self { + Lang::Empty | Lang::All | Lang::Epsilon | Lang::Test(_) => Ok(()), + Lang::Union(children) | Lang::Concat(children) | Lang::Intersect(children) => children + .iter() + .try_for_each(|child| child.check_depths(depth)), + Lang::Star(inner) | Lang::Not(inner) => inner.check_depths(depth), + } + } +} + +fn check_depth(depth: usize) -> Result<(), HistoryError> { + if depth > MAX_REFERENCE_DEPTH { + return Err(HistoryError::GraphBudget { + limit: MAX_REFERENCE_DEPTH, + }); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::flat::FlatBuilder; + use crate::limits::Unmetered; + use crate::observation::ObservationWorld; + use alloc::vec; + use history_syntax::syntax::Component; + + const ACTOR: u64 = 7; + const EDIT: u64 = 11; + const DOC: u64 = 13; + const REMOVE: u64 = 17; + + struct Source(FlatBuilder); + + impl Source { + // Head: principal and resource bind, action is any. + fn new() -> Self { + Self(FlatBuilder::new(vec![ + FlatHead::Bind, + FlatHead::Any, + FlatHead::Bind, + ])) + } + + fn test(&mut self, node: FlatTest) -> u32 { + self.0 + .test(node, &mut Unmetered, &mut ObservationWorld) + .unwrap() + } + + fn regex(&mut self, node: FlatRegex) -> u32 { + self.0 + .regex(node, &mut Unmetered, &mut ObservationWorld) + .unwrap() + } + + // `principal == actor, action == action, resource == doc`. + fn event_test(&mut self, action: u64) -> u32 { + let principal = self.test(FlatTest::Atom { + field: Component(0), + term: FlatTerm::Variable(Component(0)), + positive: true, + }); + let action = self.test(FlatTest::Atom { + field: Component(1), + term: FlatTerm::Constant(action), + positive: true, + }); + let resource = self.test(FlatTest::Atom { + field: Component(2), + term: FlatTerm::Variable(Component(2)), + positive: true, + }); + self.test(FlatTest::And(vec![principal, action, resource])) + } + + // `[any, , any]`. + fn contains(&mut self, test: u32) -> u32 { + let any = self.regex(FlatRegex::All); + let event = self.regex(FlatRegex::Test(test)); + self.regex(FlatRegex::Concat(vec![any, event, any])) + } + + fn finish(self, root: u32) -> FlatPair { + self.0.finish(root).unwrap() + } + } + + fn accepts(pair: &FlatPair, request: &[u64], history: &[[u64; 3]]) -> bool { + assert!(head_matches(&pair.head, request)); + let mut lang = Lang::inflate(pair, &mut Unmetered).unwrap(); + for event in history { + lang = lang.step(pair, event, request, &mut Unmetered).unwrap(); + } + lang.nullable() + } + + #[test] + fn prior_edit_by_the_same_principal_on_the_same_resource() { + let mut source = Source::new(); + let edit = source.event_test(EDIT); + let root = source.contains(edit); + let pair = source.finish(root); + let request = [ACTOR, 99, DOC]; + + assert!(!Lang::inflate(&pair, &mut Unmetered).unwrap().nullable()); + assert!(accepts(&pair, &request, &[[ACTOR, EDIT, DOC]])); + assert!(accepts( + &pair, + &request, + &[[1, 2, 3], [ACTOR, EDIT, DOC], [4, 5, 6]] + )); + assert!(!accepts(&pair, &request, &[])); + assert!(!accepts(&pair, &request, &[[ACTOR + 1, EDIT, DOC]])); + assert!(!accepts(&pair, &request, &[[ACTOR, REMOVE, DOC]])); + assert!(!accepts( + &pair, + &[ACTOR, 99, DOC + 1], + &[[ACTOR, EDIT, DOC]] + )); + } + + #[test] + fn residual_of_a_contains_pattern_stays_small() { + let mut source = Source::new(); + let edit = source.event_test(EDIT); + let root = source.contains(edit); + let pair = source.finish(root); + let request = [ACTOR, 99, DOC]; + let mut lang = Lang::inflate(&pair, &mut Unmetered).unwrap(); + for _ in 0..64 { + lang = lang + .step(&pair, &[1, 2, 3], &request, &mut Unmetered) + .unwrap(); + } + assert!(lang.size() <= 8, "{lang:?}"); + lang = lang + .step(&pair, &[ACTOR, EDIT, DOC], &request, &mut Unmetered) + .unwrap(); + assert_eq!(lang, Lang::All); + } + + #[test] + fn complement_and_intersection() { + // Edited somewhere, and never removed: `[any, edit, any] & ![any, remove, any]`. + let mut source = Source::new(); + let edit = source.event_test(EDIT); + let remove = source.event_test(REMOVE); + let edited = source.contains(edit); + let removed = source.contains(remove); + let not_removed = source.regex(FlatRegex::Complement(removed)); + let root = source.regex(FlatRegex::Intersect(vec![edited, not_removed])); + let pair = source.finish(root); + let request = [ACTOR, 99, DOC]; + + assert!(accepts(&pair, &request, &[[ACTOR, EDIT, DOC]])); + assert!(!accepts( + &pair, + &request, + &[[ACTOR, EDIT, DOC], [ACTOR, REMOVE, DOC]] + )); + assert!(!accepts(&pair, &request, &[])); + // A removal by someone else does not count. + assert!(accepts( + &pair, + &request, + &[[ACTOR, EDIT, DOC], [ACTOR + 1, REMOVE, DOC]] + )); + } + + #[test] + fn star_accepts_only_repetitions() { + let mut source = Source::new(); + let edit = source.event_test(EDIT); + let event = source.regex(FlatRegex::Test(edit)); + let root = source.regex(FlatRegex::Star(event)); + let pair = source.finish(root); + let request = [ACTOR, 99, DOC]; + + assert!(accepts(&pair, &request, &[])); + assert!(accepts(&pair, &request, &[[ACTOR, EDIT, DOC]; 3])); + assert!(!accepts( + &pair, + &request, + &[[ACTOR, EDIT, DOC], [ACTOR, REMOVE, DOC]] + )); + } + + #[test] + fn head_constants_must_match_the_request() { + let head = [FlatHead::Constant(EDIT), FlatHead::Any, FlatHead::Bind]; + assert!(head_matches(&head, &[EDIT, 1, 2])); + assert!(!head_matches(&head, &[EDIT + 1, 1, 2])); + assert!(!head_matches(&head, &[EDIT, 1])); + } + + #[test] + fn deep_sources_exceed_the_depth_budget() { + let mut source = Source::new(); + let mut node = source.regex(FlatRegex::Epsilon); + for _ in 0..=MAX_REFERENCE_DEPTH { + node = source.regex(FlatRegex::Complement(node)); + } + let pair = source.finish(node); + assert_eq!( + Lang::inflate(&pair, &mut Unmetered), + Err(HistoryError::GraphBudget { + limit: MAX_REFERENCE_DEPTH + }) + ); + } + + #[test] + fn shared_subterms_exceed_the_node_budget() { + // Each level doubles the inflated tree: 2^17 leaves exceed the node cap. + let mut source = Source::new(); + let mut node = source.regex(FlatRegex::Epsilon); + for _ in 0..17 { + node = source.regex(FlatRegex::Union(vec![node, node])); + } + let pair = source.finish(node); + assert_eq!( + Lang::inflate(&pair, &mut Unmetered), + Err(HistoryError::GraphBudget { + limit: MAX_REFERENCE_NODES + }) + ); + } +} diff --git a/src/junco-core/src/scope.rs b/src/junco-core/src/scope.rs new file mode 100644 index 000000000..2de38825c --- /dev/null +++ b/src/junco-core/src/scope.rs @@ -0,0 +1,151 @@ +//! Rule-local variable validation over indexed event coordinates. + +use crate::errors::CompileError; +#[cfg(verus_keep_ghost)] +use crate::verify::history_specs::no_invariant_compile_failure; +use alloc::borrow::ToOwned; +use history_syntax::{Component, MAX_ARITY}; +use vstd::prelude::*; + +/// Borrowed head-name slots; names are local to one rule. +#[verus_verify] +pub struct VariableScope<'a> { + names: [Option<&'a str>; MAX_ARITY], + arity: usize, +} + +#[verus_verify] +impl<'a> VariableScope<'a> { + /// Creates an empty rule scope of the event type's arity. + #[verus_spec(result => requires 1 <= arity <= MAX_ARITY, + ensures result.wf(), result.arity_spec() == arity, + forall|field: Component| result.name_spec(field) is None)] + pub fn new(arity: usize) -> Self { + proof! { reveal(VariableScope::name_spec); reveal(VariableScope::arity_spec); reveal(VariableScope::wf); } + Self { + names: [None; MAX_ARITY], + arity, + } + } + + /// Number of coordinates in this scope. + #[verus_spec(result => ensures result == self.arity_spec())] + pub fn arity(&self) -> usize { + proof! { reveal(VariableScope::arity_spec); } + self.arity + } + + /// Returns the name bound in one coordinate, or `None` outside the scope. + #[verus_spec(result => requires self.wf(), ensures result == self.name_spec(component))] + pub fn name(&self, component: Component) -> Option<&'a str> { + proof! { reveal(VariableScope::name_spec); reveal(VariableScope::wf); } + let index = component.index(); + if index < self.arity { + self.names[index] + } else { + None + } + } + + /// Binds a head name, rejecting its use in any other coordinate. + #[verus_spec(result => requires old(self).wf(), component.0 < old(self).arity_spec(), + ensures final(self).wf(), final(self).arity_spec() == old(self).arity_spec(), + result is Ok <==> !old(self).conflicts(component, name@), + result is Err ==> *final(self) == *old(self), + result is Ok ==> final(self).name_spec(component) == Some(name), + forall|field: Component| field != component ==> + final(self).name_spec(field) == old(self).name_spec(field), + result matches Err(CompileError::VariableComponentConflict { name: bad }) ==> bad@ == name@, + result is Err ==> result matches Err(CompileError::VariableComponentConflict { .. }), + no_invariant_compile_failure(result), + )] + pub fn bind(&mut self, component: Component, name: &'a str) -> Result<(), CompileError> { + proof! { reveal(VariableScope::name_spec); reveal(VariableScope::arity_spec); reveal(VariableScope::wf); } + if self.has_conflict(component, name) { + return Err(CompileError::VariableComponentConflict { + name: name.to_owned(), + }); + } + self.names[component.index()] = Some(name); + Ok(()) + } + + /// Resolves a tail name only in its own coordinate. + #[verus_spec(result => requires self.wf(), component.0 < self.arity_spec(), + ensures result == Ok(component) <==> self.has_name(component, name@), + result is Ok ==> result == Ok(component), + result matches Err(CompileError::VariableComponentConflict { name: bad }) ==> bad@ == name@, + result matches Err(CompileError::UnboundVariable { name: bad }) ==> bad@ == name@, + result matches Err(CompileError::VariableComponentConflict { .. }) <==> + !self.has_name(component, name@) && self.conflicts(component, name@), + result matches Err(CompileError::UnboundVariable { .. }) <==> + !self.has_name(component, name@) && !self.conflicts(component, name@), + no_invariant_compile_failure(result), + result is Err ==> result matches Err(CompileError::VariableComponentConflict { .. }) + || result matches Err(CompileError::UnboundVariable { .. }), + )] + pub fn resolve(&self, component: Component, name: &str) -> Result { + if Self::same_name(self.name(component), name) { + Ok(component) + } else if self.has_conflict(component, name) { + Err(CompileError::VariableComponentConflict { + name: name.to_owned(), + }) + } else { + Err(CompileError::UnboundVariable { + name: name.to_owned(), + }) + } + } + + #[verus_spec(result => requires self.wf(), ensures result == self.conflicts(component, name@))] + fn has_conflict(&self, component: Component, name: &str) -> bool { + proof! { reveal(VariableScope::name_spec); reveal(VariableScope::arity_spec); reveal(VariableScope::wf); } + let mut index = 0; + #[cfg_attr(verus_keep_ghost, verus_spec( + invariant self.wf(), index <= self.arity <= MAX_ARITY, + forall|i: int| 0 <= i < index && i != component.0 ==> + !#[trigger] self.has_name(Component(i as u8), name@), + decreases self.arity - index, + ))] + while index < self.arity { + if index != component.index() && Self::same_name(self.names[index], name) { + proof! { assert(self.has_name(Component(index as u8), name@)); } + return true; + } + index += 1; + } + false + } + + #[verus_spec(result => ensures result == match bound { + Some(existing) => existing@ == name@, None => false, + })] + fn same_name(bound: Option<&str>, name: &str) -> bool { + match bound { + Some(existing) => existing == name, + None => false, + } + } +} + +#[cfg(verus_keep_ghost)] +verus! { +impl VariableScope<'_> { + pub closed spec fn arity_spec(&self) -> nat { self.arity as nat } + pub closed spec fn wf(&self) -> bool { 1 <= self.arity <= MAX_ARITY } + + pub closed spec fn name_spec(&self, component: Component) -> Option<&str> { + if component.0 < self.arity { self.names@[component.0 as int] } else { None } + } + + pub open spec fn has_name(&self, component: Component, name: Seq) -> bool { + match self.name_spec(component) { Some(bound) => bound@ == name, None => false } + } + + pub open spec fn conflicts(&self, component: Component, name: Seq) -> bool { + exists|i: int| 0 <= i < self.arity_spec() && i != component.0 + && #[trigger] self.has_name(Component(i as u8), name) + } +} +} diff --git a/src/junco-core/src/spec/hypotheses.rs b/src/junco-core/src/spec/hypotheses.rs new file mode 100644 index 000000000..3848746d5 --- /dev/null +++ b/src/junco-core/src/spec/hypotheses.rs @@ -0,0 +1,40 @@ +//! The hypothesis bundles every monitor and analyzer guarantee assumes about its event type. +//! They have no uninterpreted conjunct: `key_laws` is proved for every built-in key type +//! (`junco_core::verify::hypotheses`), so `event_obligations::()` is a theorem for the +//! built-in events. + +use crate::spec::semantics::*; +use history_syntax::key_hash::specs::KeyHashSpec; +use history_syntax::spec::events::event_laws; +use history_syntax::{Event, KeyHash}; +use vstd::prelude::*; +use vstd::std_specs::cmp::PartialEqSpec; + +verus! { + +/// `eq_spec` is an equivalence relation on `T`. +pub open spec fn eq_equivalence() -> bool { + &&& forall|a: T| #[trigger] a.eq_spec(&a) + &&& forall|a: T, b: T| #[trigger] a.eq_spec(&b) == b.eq_spec(&a) + &&& forall|a: T, b: T, c: T| #[trigger] a.eq_spec(&b) && #[trigger] b.eq_spec(&c) ==> a.eq_spec(&c) +} + +/// `hash_spec` is constant on `eq_spec` classes, so a table keyed by it is a map on those classes. +/// Proved per key type in `junco_core::verify::hypotheses`; never assumed. +pub open spec fn hash_respects_eq() -> bool { + forall|a: K, b: K| #[trigger] a.eq_spec(&b) ==> a.hash_spec() == b.hash_spec() +} + +/// What a hash-container key must satisfy: `Eq` agrees with `eq_spec`, which is an equivalence, +/// and `key_hash` agrees with `hash_spec`, which respects `eq_spec`. +pub open spec fn key_laws() -> bool { + K::obeys_eq_spec() && eq_equivalence::() && K::obeys_hash_spec() && hash_respects_eq::() +} + +/// The one bundle every monitor and analyzer guarantee assumes about the event type `E` +/// (`event_laws` from `history_syntax::spec::events` plus `key_laws` of its component type). +pub open spec fn event_obligations() -> bool { + event_laws::() && key_laws::() +} + +} // verus! diff --git a/src/junco-core/src/spec/mod.rs b/src/junco-core/src/spec/mod.rs new file mode 100644 index 000000000..77116a73f --- /dev/null +++ b/src/junco-core/src/spec/mod.rs @@ -0,0 +1,7 @@ +//! Reviewer-facing specifications of this crate: the typed semantics of rules over events (`semantics`), +//! the policy questions and counterexample instances (`questions`), and the hypothesis bundles +//! (`hypotheses`). + +pub mod hypotheses; +pub mod questions; +pub mod semantics; diff --git a/src/junco-core/src/spec/questions.rs b/src/junco-core/src/spec/questions.rs new file mode 100644 index 000000000..a378af280 --- /dev/null +++ b/src/junco-core/src/spec/questions.rs @@ -0,0 +1,345 @@ +//! The policy questions the analyzer decides (paper Section 5, Definition +//! `def:policy-refinement`, appendix `app:policy-reduction`), declared domains, symbolic +//! counterexamples with their real instances, fresh-value capacity, and per-case minimality. +//! Everything is stated over real events `E` through the semantics (`junco_core::spec::semantics`). + +use crate::spec::semantics::*; +use history_syntax::event::specs::EventSpec; +use history_syntax::spec::events::{ + AtomView, HeadView, PatternView, RegexView, RuleView, TestView, arity, event_view, +}; +use history_syntax::{Event, MAX_ARITY, RuleMode}; +use vstd::prelude::*; +use vstd::std_specs::cmp::PartialEqSpec; + +verus! { + +broadcast use vstd::seq::group_seq_lemmas; + +// ----- declared domains ----- + +/// The values a coordinate ranges over: all values of its type (`None`), or a declared finite +/// set. The paper assumes infinite domains (`sec:events`); declared finite domains are an +/// implementation feature (`Domains::with_domain`). +pub type DomainsView = Seq>>; + +/// `value` lies in the domain: always for an undeclared coordinate, up to `eq_spec` for a declared +/// set. +pub open spec fn in_domain(domain: Option>, value: T) -> bool { + match domain { + None => true, + Some(values) => exists|w: T| values.contains(w) && value.eq_spec(&w), + } +} + +/// A component tuple lies coordinate-wise in the domains. +pub open spec fn event_in(domains: DomainsView, event: Seq) -> bool { + 1 <= domains.len() <= MAX_ARITY && event.len() == domains.len() + && forall|i: int| 0 <= i < domains.len() ==> in_domain(#[trigger] domains[i], event[i]) +} + +/// Every event of a history lies in the domains. +pub open spec fn history_in(domains: DomainsView, history: Seq>) -> bool { + forall|i: int| 0 <= i < history.len() ==> #[trigger] event_in(domains, history[i]) +} + +/// `v` equals no member of `values`. +pub open spec fn misses(values: Set, v: T) -> bool { + forall|w: T| values.contains(w) ==> !v.eq_spec(&w) +} + +/// A real candidate and history inside the declared domains (undeclared coordinate = every +/// value of its type). +pub open spec fn in_domains( + domains: DomainsView, candidate: E, history: Seq, +) -> bool { + event_in(domains, event_view(candidate)) && history_in(domains, history_view(history)) +} + +/// Declared domains: one slot per coordinate; a declared set is nonempty and tagged with its +/// coordinate; `Set` is finite by construction in this vstd. +pub open spec fn domains_wf(domains: DomainsView) -> bool { + domains.len() == arity::() && forall|i: int| 0 <= i < domains.len() ==> match #[trigger] domains[i] { + None => true, + Some(values) => values.len() > 0 + && forall|v: E::Component| values.contains(v) ==> E::coordinate_spec(v) == i, + } +} + +// ----- the questions (`def:policy-refinement`, `app:policy-reduction`) ----- + +/// `P ⊑ Q` (`def:policy-refinement`): every pair in the domains permitted by `P` is permitted by +/// `Q`. +pub open spec fn refines( + domains: DomainsView, p: Seq>, q: Seq>, +) -> bool { + forall|c: E, h: Seq| in_domains::(domains, c, h) && policy_permits(p, c, h) + ==> #[trigger] policy_permits(q, c, h) +} + +/// `P` covers `rule`: every pair the rule violates is denied by `P` (`app:policy-reduction`). +pub open spec fn covers( + domains: DomainsView, p: Seq>, rule: RuleView, +) -> bool { + forall|c: E, h: Seq| in_domains::(domains, c, h) && #[trigger] rule_violated(rule, c, h) + ==> policy_denies(p, c, h) +} + +/// The rule violates no pair in the domains. +pub open spec fn never_denies( + domains: DomainsView, rule: RuleView, +) -> bool { + forall|c: E, h: Seq| in_domains::(domains, c, h) ==> !#[trigger] rule_violated(rule, c, h) +} + +/// The rule violates every pair in the domains whose candidate matches its head. +pub open spec fn always_denies( + domains: DomainsView, rule: RuleView, +) -> bool { + forall|c: E, h: Seq| in_domains::(domains, c, h) && head_matches(rule.head, event_view(c)) + ==> #[trigger] rule_violated(rule, c, h) +} + +/// `forbid head Univ`: denies every candidate matching `head` (vacuity through refinement). +pub open spec fn forbid_all(head: HeadView) -> RuleView { + RuleView { mode: RuleMode::Forbid, head, tail: RegexView::All } +} + +/// Tail inclusion for every matching candidate in the domains: `L(left) ⊆ L(right)` read with +/// the head's bindings. +pub open spec fn tails_included( + domains: DomainsView, head: HeadView, + left: RegexView, right: RegexView, +) -> bool { + forall|c: E, h: Seq| in_domains::(domains, c, h) && head_matches(head, event_view(c)) + && #[trigger] lang(left, head, event_view(c), history_view(h)) + ==> lang(right, head, event_view(c), history_view(h)) +} + +// ----- symbolic counterexamples and their real instances ----- + +/// `Value`: a constant, or a numbered value of an undeclared coordinate that equals no +/// constant the analyzer knows. +pub enum ValueView { Constant(T), Fresh(nat) } + +pub type ComponentsView = Seq>; + +/// `Counterexample`: a candidate and a history (oldest first). +pub struct CexView { pub candidate: ComponentsView, pub history: Seq> } + +/// `Inclusion`: the answer to a query. +pub enum InclusionView { Holds, Counterexample(CexView), Exhausted } + +/// Per-coordinate choice of a value for each fresh number. +pub type FreshChoice = Seq C>; + +/// The real value a symbolic value denotes under the choice `f` of its coordinate. +pub open spec fn value_of(v: ValueView, f: spec_fn(nat) -> T) -> T { + match v { ValueView::Constant(c) => c, ValueView::Fresh(n) => f(n) } +} + +/// The real tuple a symbolic tuple denotes. +pub open spec fn event_of(c: ComponentsView, f: FreshChoice) -> Seq { + Seq::new(c.len(), |i: int| value_of(c[i], f[i])) +} + +/// The real history a symbolic history denotes. +pub open spec fn history_of(cex: CexView, f: FreshChoice) -> Seq> { + cex.history.map(|i: int, c: ComponentsView| event_of(c, f)) +} + +/// Fresh numbers used at one coordinate. +pub open spec fn fresh_used(cex: CexView, coordinate: int) -> ISet { + ISet::new(|n: nat| (0 <= coordinate < cex.candidate.len() + && cex.candidate[coordinate] == ValueView::::Fresh(n)) + || exists|i: int| 0 <= i < cex.history.len() && 0 <= coordinate < cex.history[i].len() + && #[trigger] cex.history[i][coordinate] == ValueView::::Fresh(n)) +} + +/// Every symbolic tuple of the counterexample has `arity` coordinates. +pub open spec fn cex_arity(cex: CexView, arity: nat) -> bool { + cex.candidate.len() == arity + && forall|i: int| 0 <= i < cex.history.len() ==> #[trigger] cex.history[i].len() == arity +} + +/// Fresh numbers at coordinate `i` map to pairwise distinct values tagged `i`, inside the +/// domain, equal to no known constant. +pub open spec fn choice_ok( + f: spec_fn(nat) -> E::Component, used: ISet, known: Set, + domain: Option>, i: int, +) -> bool { + &&& forall|m: nat, n: nat| #![trigger used.contains(m), used.contains(n)] + used.contains(m) && used.contains(n) && m != n ==> !f(m).eq_spec(&f(n)) + &&& forall|n: nat, k: E::Component| #![trigger used.contains(n), known.contains(k)] + used.contains(n) && known.contains(k) ==> !f(n).eq_spec(&k) + &&& forall|n: nat| #[trigger] used.contains(n) ==> in_domain(domain, f(n)) && E::coordinate_spec(f(n)) == i +} + +/// A choice of fresh values admissible at every coordinate of the counterexample. +pub open spec fn admissible( + domains: DomainsView, known: Seq>, + cex: CexView, f: FreshChoice, +) -> bool { + &&& domains.len() == arity::() && known.len() == arity::() && f.len() == arity::() + &&& cex_arity(cex, arity::()) + &&& forall|i: int| 0 <= i < arity::() + ==> choice_ok::(#[trigger] f[i], fresh_used(cex, i), known[i], domains[i], i) +} + +/// `(c, h)` is the real pair the symbolic counterexample denotes under `f`. +pub open spec fn instantiates( + cex: CexView, f: FreshChoice, c: E, h: Seq, +) -> bool { + event_view(c) == event_of(cex.candidate, f) && history_view(h) == history_of(cex, f) +} + +/// Some admissible choice denotes a real pair. +pub open spec fn cex_has_instance( + domains: DomainsView, known: Seq>, cex: CexView, +) -> bool { + exists|f: FreshChoice, c: E, h: Seq| + admissible::(domains, known, cex, f) && #[trigger] instantiates::(cex, f, c, h) +} + +/// Every real instance lies in the domains and satisfies `fails`. +pub open spec fn every_instance( + domains: DomainsView, known: Seq>, cex: CexView, + fails: spec_fn(E, Seq) -> bool, +) -> bool { + forall|f: FreshChoice, c: E, h: Seq| + admissible::(domains, known, cex, f) && #[trigger] instantiates::(cex, f, c, h) + ==> in_domains::(domains, c, h) && fails(c, h) +} + +/// Coordinate `i` offers at least `k` pairwise distinct values tagged `i`, inside its domain, +/// equal to no known constant. +pub open spec fn fresh_capacity( + domains: DomainsView, known: Seq>, i: int, k: nat, +) -> bool { + exists|vs: Seq| #[trigger] vs.len() == k + && (forall|a: int, b: int| 0 <= a < b < vs.len() ==> !vs[a].eq_spec(&vs[b])) + && forall|a: int| 0 <= a < vs.len() ==> E::coordinate_spec(#[trigger] vs[a]) == i + && in_domain(domains[i], vs[a]) && misses(known[i], vs[a]) +} + +/// Capacity for exactly the fresh values the counterexample uses (zero at declared coordinates). +pub open spec fn capacity_for( + domains: DomainsView, known: Seq>, cex: CexView, +) -> bool { + forall|i: int| 0 <= i < arity::() + ==> #[trigger] fresh_capacity::(domains, known, i, fresh_used(cex, i).len()) +} + +// ----- minimality (over events) ----- + +/// `c2` agrees with `c` on equality with every known constant (so it lies in the same candidate +/// case of every split the analyzer makes). +pub open spec fn same_profile(known: Seq>, c: Seq, c2: Seq) -> bool { + &&& c.len() == known.len() && c2.len() == known.len() + &&& forall|i: int, k: C| 0 <= i < known.len() && #[trigger] known[i].contains(k) + ==> (c[i].eq_spec(&k) == c2[i].eq_spec(&k)) +} + +/// No failing pair in the domains has a history shorter than `n`. +pub open spec fn shortest( + domains: DomainsView, n: nat, fails: spec_fn(E, Seq) -> bool, +) -> bool { + forall|c: E, h: Seq| in_domains::(domains, c, h) && h.len() < n ==> !#[trigger] fails(c, h) +} + +/// No failing pair with the constant profile of `c` has a history shorter than `n` (minimum +/// length per inclusion query, Theorem `thm:search`). +pub open spec fn shortest_in_case( + domains: DomainsView, known: Seq>, c: E, n: nat, + fails: spec_fn(E, Seq) -> bool, +) -> bool { + forall|c2: E, h: Seq| in_domains::(domains, c2, h) && h.len() < n + && same_profile(known, event_view(c), event_view(c2)) ==> !#[trigger] fails(c2, h) +} + +/// Per-case minimality: every real instance is shortest among candidates with its constant +/// profile. +pub open spec fn minimal_in_case( + domains: DomainsView, known: Seq>, cex: CexView, + fails: spec_fn(E, Seq) -> bool, +) -> bool { + forall|f: FreshChoice, c: E, h: Seq| + admissible::(domains, known, cex, f) && #[trigger] instantiates::(cex, f, c, h) + ==> shortest_in_case::(domains, known, c, cex.history.len(), fails) +} + +// ----- the constants a rule mentions (what `known` and freshness are relative to) ----- + +/// The constant of a head or atom pattern, if any. +pub open spec fn pattern_constant(pattern: PatternView) -> Set { + match pattern { PatternView::Constant(c) => Set::empty().insert(c), PatternView::Variable(_) => Set::empty() } +} + +/// A finite union, built from finite sets rather than an unrestricted comprehension. +pub open spec fn constants_union(sets: Seq>) -> Set + decreases sets.len(), +{ + if sets.len() == 0 { Set::empty() } + else { constants_union(sets.drop_last()).union(sets.last()) } +} + +/// The constants a test compares coordinate `coordinate` against. +pub open spec fn test_constant_at(test: TestView, coordinate: int) -> Set + decreases test, +{ + match test { + TestView::True | TestView::False => Set::empty(), + TestView::Atom { pattern, .. } => + if coordinate == pattern.component { pattern_constant(pattern.pattern) } else { Set::empty() }, + TestView::And(cs) | TestView::Or(cs) => test_constant_forest(cs, coordinate), + } +} + +pub open spec fn test_constant_forest(tests: Seq>, coordinate: int) -> Set + decreases tests, +{ + if tests.len() == 0 { Set::empty() } + else { test_constant_forest(tests.drop_last(), coordinate).union(test_constant_at(tests.last(), coordinate)) } +} + +/// The constants a test mentions, per coordinate. +pub open spec fn test_constants(test: TestView, arity: nat) -> Seq> { + Seq::new(arity, |j: int| test_constant_at(test, j)) +} + +/// The constants a tail compares coordinate `coordinate` against. +pub open spec fn regex_constant_at(regex: RegexView, coordinate: int) -> Set + decreases regex, +{ + match regex { + RegexView::Empty | RegexView::All | RegexView::Epsilon => Set::empty(), + RegexView::Test(test) => test_constant_at(test, coordinate), + RegexView::Union(cs) | RegexView::Concat(cs) | RegexView::Intersect(cs) => regex_constant_forest(cs, coordinate), + RegexView::Star(child) | RegexView::Not(child) => regex_constant_at(*child, coordinate), + } +} + +pub open spec fn regex_constant_forest(regexes: Seq>, coordinate: int) -> Set + decreases regexes, +{ + if regexes.len() == 0 { Set::empty() } + else { regex_constant_forest(regexes.drop_last(), coordinate).union(regex_constant_at(regexes.last(), coordinate)) } +} + +/// The constants a tail mentions, per coordinate. +pub open spec fn regex_constants(regex: RegexView, arity: nat) -> Seq> { + Seq::new(arity, |j: int| regex_constant_at(regex, j)) +} + +/// The constants of a head, per coordinate. +pub open spec fn head_constants(head: HeadView) -> Seq> { + head.map(|i: int, pattern: PatternView| pattern_constant(pattern)) +} + +/// Exact finite constants of the head and tail, separately at every coordinate. +pub open spec fn rule_constants(rule: RuleView) -> Seq> { + Seq::new(rule.head.len(), |i: int| + regex_constants(rule.tail, rule.head.len())[i].union(head_constants(rule.head)[i])) +} + +} // verus! diff --git a/src/junco-core/src/spec/semantics.rs b/src/junco-core/src/spec/semantics.rs new file mode 100644 index 000000000..f63377f87 --- /dev/null +++ b/src/junco-core/src/spec/semantics.rs @@ -0,0 +1,281 @@ +//! The typed semantics of rules (paper `sec:rules`, Definitions `def:violates` and +//! `def:policy-violates`), first over component tuples, then over events through `event_view`. +//! +//! Component equality is `PartialEqSpec::eq_spec`, not representation equality. Connecting +//! native projections/equality to this model remains conditional on their respective contracts. + +use history_syntax::event::specs::EventSpec; +use history_syntax::spec::events::{ + AtomView, HeadView, PatternView, RegexView, RuleView, TestView, event_view, +}; +use history_syntax::{Comparison, Event, Rule, RuleMode}; +use vstd::prelude::*; +use vstd::std_specs::cmp::PartialEqSpec; + +verus! { + +broadcast use {vstd::std_specs::vec::group_vec_axioms, vstd::seq::group_seq_lemmas}; + +/// Operational resource failures, never malformed input, ownership errors or invariant failures. +pub open spec fn resource_error(error: crate::errors::HistoryError) -> bool { + matches!(error, crate::errors::HistoryError::GraphBudget { .. } + | crate::errors::HistoryError::GraphIndex + | crate::errors::HistoryError::AllocationFailed + | crate::errors::HistoryError::ArenaExhausted + | crate::errors::HistoryError::IdExhausted { .. } + | crate::errors::HistoryError::RevisionExhausted + | crate::errors::HistoryError::Limit(_)) +} + +/// Every source constant has the tag of the coordinate where it is compared. +pub open spec fn rule_constants_tagged(rule: RuleView) -> bool { + forall|i: int, value: E::Component| 0 <= i < rule.head.len() + && #[trigger] crate::spec::questions::rule_constants(rule)[i].contains(value) + ==> E::coordinate_spec(value) == i +} + +// ----- heads, scoping, and tails over component tuples ----- + +/// The variable name of a head or atom pattern, if it is a variable. +pub open spec fn pattern_name(pattern: PatternView) -> Option> { + match pattern { PatternView::Constant(_) => None, PatternView::Variable(name) => Some(name) } +} + +/// Two patterns do not share a variable name. +pub open spec fn distinct_names(left: PatternView, right: PatternView) -> bool { + match (pattern_name(left), pattern_name(right)) { + (Some(a), Some(b)) => a != b, + _ => true, + } +} + +/// Head variables have pairwise distinct names (`sec:rules`). +pub open spec fn head_scoped(head: HeadView) -> bool { + forall|i: int, j: int| 0 <= i < j < head.len() ==> + distinct_names(#[trigger] head[i], #[trigger] head[j]) +} + +/// A head pattern matches a component: a constant up to `eq_spec`, a variable always. +pub open spec fn head_pattern_matches(pattern: PatternView, actual: T) -> bool { + match pattern { + PatternView::Constant(expected) => actual.eq_spec(&expected), + PatternView::Variable(_) => true, + } +} + +/// The head unifies with the candidate tuple (`sec:rules`). +pub open spec fn head_matches(head: HeadView, candidate: Seq) -> bool { + head.len() == candidate.len() + && forall|i: int| 0 <= i < head.len() ==> + head_pattern_matches(#[trigger] head[i], candidate[i]) +} + +/// Substitution is coordinate-local: an identically spelled name in another coordinate is absent. +pub open spec fn resolve_pattern( + pattern: PatternView, head: PatternView, candidate: T, +) -> Option { + match pattern { + PatternView::Constant(value) => Some(value), + PatternView::Variable(name) => match head { + PatternView::Variable(bound) => if name == bound { Some(candidate) } else { None }, + PatternView::Constant(_) => None, + }, + } +} + +/// A tail pattern is a constant or the head variable of its own coordinate. +pub open spec fn pattern_scoped(pattern: PatternView, head: PatternView) -> bool { + match pattern { + PatternView::Constant(_) => true, + PatternView::Variable(name) => pattern_name(head) == Some(name), + } +} + +pub open spec fn atom_scoped(atom: AtomView, head: HeadView) -> bool { + atom.component < head.len() && pattern_scoped(atom.pattern, head[atom.component as int]) +} + +pub open spec fn test_scoped(test: TestView, head: HeadView) -> bool + decreases test, +{ + match test { + TestView::True | TestView::False => true, + TestView::Atom { pattern, .. } => atom_scoped(pattern, head), + // Separate bindings keep conditional expressions out of the quantified index triggers. + TestView::And(children) => + forall|i: int| 0 <= i < children.len() ==> test_scoped(#[trigger] children[i], head), + TestView::Or(children) => + forall|i: int| 0 <= i < children.len() ==> test_scoped(#[trigger] children[i], head), + } +} + +/// Every variable of the tail is the head variable of its own coordinate (component-locality, +/// `sec:events`). +pub open spec fn regex_scoped(regex: RegexView, head: HeadView) -> bool + decreases regex, +{ + match regex { + RegexView::Empty | RegexView::All | RegexView::Epsilon => true, + RegexView::Test(test) => test_scoped(test, head), + RegexView::Union(children) => + forall|i: int| 0 <= i < children.len() ==> regex_scoped(#[trigger] children[i], head), + RegexView::Concat(children) => + forall|i: int| 0 <= i < children.len() ==> regex_scoped(#[trigger] children[i], head), + RegexView::Intersect(children) => + forall|i: int| 0 <= i < children.len() ==> regex_scoped(#[trigger] children[i], head), + RegexView::Star(child) | RegexView::Not(child) => regex_scoped(*child, head), + } +} + +/// An atom comparison against a resolved operand; an unresolved operand is false. +pub open spec fn comparison_sem(comparison: Comparison, actual: T, expected: Option) -> bool { + match expected { + None => false, + Some(value) => match comparison { + Comparison::Eq => actual.eq_spec(&value), + Comparison::Neq => !actual.eq_spec(&value), + }, + } +} + +/// Component tests read one event coordinate and the candidate's binding of that coordinate. +pub open spec fn atom_sem( + comparison: Comparison, atom: AtomView, head: HeadView, + candidate: Seq, event: Seq, +) -> bool { + atom.component < head.len() && atom.component < candidate.len() && atom.component < event.len() + && comparison_sem(comparison, event[atom.component as int], + resolve_pattern(atom.pattern, head[atom.component as int], candidate[atom.component as int])) +} + +/// Boolean combinations of component tests over one history event. +pub open spec fn test_sem( + test: TestView, head: HeadView, + candidate: Seq, event: Seq, +) -> bool + decreases test, +{ + match test { + TestView::True => true, + TestView::False => false, + TestView::Atom { comparison, pattern } => atom_sem(comparison, pattern, head, candidate, event), + TestView::And(children) => forall|i: int| 0 <= i < children.len() ==> + test_sem(children[i], head, candidate, event), + TestView::Or(children) => exists|i: int| 0 <= i < children.len() + && test_sem(children[i], head, candidate, event), + } +} + +/// Whole-word language semantics of a tail, in oldest-to-newest event order (`sec:rules`). +pub open spec fn lang( + regex: RegexView, head: HeadView, candidate: Seq, + word: Seq>, +) -> bool + decreases regex, +{ + match regex { + RegexView::Empty => false, + RegexView::All => true, + RegexView::Epsilon => word.len() == 0, + RegexView::Test(test) => word.len() == 1 && test_sem(test, head, candidate, word[0]), + RegexView::Union(children) => exists|i: int| 0 <= i < children.len() + && lang(children[i], head, candidate, word), + RegexView::Intersect(children) => forall|i: int| 0 <= i < children.len() ==> + lang(children[i], head, candidate, word), + RegexView::Not(child) => !lang(*child, head, candidate, word), + RegexView::Concat(children) => exists|parts: Seq>>| + parts.len() == children.len() && word == parts.flatten() + && forall|i: int| 0 <= i < children.len() ==> lang(children[i], head, candidate, parts[i]), + RegexView::Star(child) => exists|parts: Seq>>| + word == parts.flatten() + && forall|i: int| 0 <= i < parts.len() ==> lang(*child, head, candidate, parts[i]), + } +} + +// ----- rules ----- + +/// `mode = require` and the history is outside the tail, or `mode = forbid` and it is inside. +pub open spec fn violated_by(mode: RuleMode, inside: bool) -> bool { + match mode { RuleMode::Require => !inside, RuleMode::Forbid => inside } +} + +/// Head variables have distinct names and every tail variable is the head variable of its own +/// component (`sec:rules`, "a tail whose variables occur in h"; component-locality, `sec:events`). +pub open spec fn rule_wf(rule: RuleView) -> bool { + 1 <= rule.head.len() <= history_syntax::MAX_ARITY && head_scoped(rule.head) && regex_scoped(rule.tail, rule.head) +} + +/// A head with two tails, both reading only the head's variables (the `tail_included` inputs). +pub open spec fn head_tails_wf(head: HeadView, left: RegexView, right: RegexView) -> bool { + 1 <= head.len() <= history_syntax::MAX_ARITY && head_scoped(head) && regex_scoped(left, head) && regex_scoped(right, head) +} + +/// The matcher's answer on component tuples: `None` if the head does not match, else tail +/// membership of the history. +pub open spec fn rule_evaluation_view( + rule: RuleView, candidate: Seq, history: Seq>, +) -> Option { + if !head_matches(rule.head, candidate) { None } + else { Some(lang(rule.tail, rule.head, candidate, history)) } +} + +/// Rule violation on tuples: fired, and the mode disagrees with tail membership (`def:violates`). +pub open spec fn rule_violated_view( + rule: RuleView, candidate: Seq, history: Seq>, +) -> bool { + match rule_evaluation_view(rule, candidate, history) { + None => false, + Some(inside) => violated_by(rule.mode, inside), + } +} + +// ----- events ----- + +/// A history of events as the tuples the semantics reads (`event_view`, oldest first). +pub open spec fn history_view(history: Seq) -> Seq> { + history.map(|i: int, e: E| event_view(e)) +} + +/// The views of a sequence of source rules, in order. +pub open spec fn rule_views(rules: Seq>) -> Seq> { + rules.map(|i: int, r: Rule| r@) +} + +/// Evaluates the tail over the committed history, excluding the candidate; a head mismatch is +/// `None`. +pub open spec fn rule_evaluation( + rule: RuleView, candidate: E, history: Seq, +) -> Option { + rule_evaluation_view(rule, event_view(candidate), history_view(history)) +} + +/// Definition Rule violation (`def:violates`), over events. +pub open spec fn rule_violated( + rule: RuleView, candidate: E, history: Seq, +) -> bool { + rule_violated_view(rule, event_view(candidate), history_view(history)) +} + +/// Definition Policy violation (`def:policy-violates`): some rule is violated. +pub open spec fn policy_denies( + rules: Seq>, candidate: E, history: Seq, +) -> bool { + exists|i: int| 0 <= i < rules.len() && #[trigger] rule_violated(rules[i], candidate, history) +} + +/// The policy permits the candidate after the history: no rule is violated. +pub open spec fn policy_permits( + rules: Seq>, candidate: E, history: Seq, +) -> bool { + !policy_denies(rules, candidate, history) +} + +/// `index` is the first violated rule in source order (the monitor's reported rule). +pub open spec fn least_violation( + rules: Seq>, candidate: E, history: Seq, index: int, +) -> bool { + 0 <= index < rules.len() && rule_violated(rules[index], candidate, history) + && forall|j: int| 0 <= j < index ==> !rule_violated(rules[j], candidate, history) +} + +} // verus! diff --git a/src/junco-core/src/verify/capacity.rs b/src/junco-core/src/verify/capacity.rs new file mode 100644 index 000000000..685a2d6fd --- /dev/null +++ b/src/junco-core/src/verify/capacity.rs @@ -0,0 +1,348 @@ +//! Real instances of symbolic counterexamples (`junco_core::spec::questions`): fresh-value capacity gives an +//! admissible choice of fresh values, `views_surjective` turns the chosen tuples into events, +//! and integer coordinates have capacity whenever the type is large enough. + +use crate::spec::hypotheses::{eq_equivalence, event_obligations}; +use crate::spec::questions::*; +use crate::spec::semantics::history_view; +use history_syntax::Event; +use history_syntax::event::specs::EventSpec; +use history_syntax::spec::events::{arity, event_view, well_tagged}; +use vstd::prelude::*; +use vstd::std_specs::cmp::PartialEqSpec; + +verus! { + +broadcast use {vstd::seq::group_seq_lemmas, vstd::iset::group_iset_lemmas}; + +/// Every constant of the counterexample at coordinate `i` is tagged `i` (the reconstruction +/// bridge establishes it from the analyzer's constant book). +pub open spec fn cex_constants_tagged(cex: CexView) -> bool { + &&& forall|i: int| 0 <= i < cex.candidate.len() ==> match #[trigger] cex.candidate[i] { + ValueView::Constant(c) => E::coordinate_spec(c) == i, + ValueView::Fresh(_) => true, + } + &&& forall|j: int, i: int| 0 <= j < cex.history.len() && 0 <= i < cex.history[j].len() + ==> match #[trigger] cex.history[j][i] { + ValueView::Constant(c) => E::coordinate_spec(c) == i, + ValueView::Fresh(_) => true, + } +} + +/// A finite candidate and history contain finitely many fresh numbers per coordinate. +pub proof fn lemma_fresh_used_finite(cex: CexView, coordinate: int) + ensures fresh_used(cex, coordinate).finite(), +{ + broadcast use vstd::set::lemma_to_iset_finite, vstd::prelude::Seq::to_set_ensures; + let events = cex.history.to_set().insert(cex.candidate).to_iset(); + let number = |c: ComponentsView| if 0 <= coordinate < c.len() { + match c[coordinate] { ValueView::Fresh(n) => n, ValueView::Constant(_) => 0nat } + } else { 0nat }; + events.lemma_map_finite(number); + assert forall|n: nat| fresh_used(cex, coordinate).contains(n) + implies events.map(number).contains(n) by { + let c = if 0 <= coordinate < cex.candidate.len() + && cex.candidate[coordinate] == ValueView::Fresh(n) { + cex.candidate + } else { + let i = choose|i: int| 0 <= i < cex.history.len() && 0 <= coordinate < cex.history[i].len() + && #[trigger] cex.history[i][coordinate] == ValueView::Fresh(n); + assert(cex.history.to_set().contains(cex.history[i])); + cex.history[i] + }; + assert(events.contains(c)); + assert(number(c) == n); + assert(events.map(number).contains(n)); + } + vstd::iset_lib::lemma_iset_subset_finite(events.map(number), fresh_used(cex, coordinate)); +} + +/// An injection of a finite set of numbers into `0..len`. +proof fn lemma_enumerate(used: ISet) -> (g: spec_fn(nat) -> nat) + requires used.finite(), + ensures + forall|n: nat| used.contains(n) ==> #[trigger] g(n) < used.len(), + forall|m: nat, n: nat| used.contains(m) && used.contains(n) && m != n ==> #[trigger] g(m) != #[trigger] g(n), + decreases used.len(), +{ + if used.len() == 0 { + used.lemma_len0_is_empty(); + |n: nat| 0nat + } else { + let a = used.choose(); + assert(used.contains(a)); + let rest = used.remove(a); + let g0 = lemma_enumerate(rest); + let g = |n: nat| if n == a { rest.len() } else { g0(n) }; + assert forall|m: nat, n: nat| used.contains(m) && used.contains(n) && m != n + implies #[trigger] g(m) != #[trigger] g(n) by { + if m == a { assert(rest.contains(n)); } + else if n == a { assert(rest.contains(m)); } + else { assert(rest.contains(m) && rest.contains(n)); } + } + g + } +} + +/// Capacity at one coordinate yields an admissible choice for the fresh numbers used there. +proof fn lemma_choice_from_capacity( + domains: DomainsView, known: Seq>, cex: CexView, i: int, +) -> (f: spec_fn(nat) -> E::Component) + requires + eq_equivalence::(), + fresh_capacity::(domains, known, i, fresh_used(cex, i).len()), + ensures choice_ok::(f, fresh_used(cex, i), known[i], domains[i], i), +{ + let used = fresh_used(cex, i); + lemma_fresh_used_finite(cex, i); + let vs = choose|vs: Seq| #[trigger] vs.len() == used.len() + && (forall|a: int, b: int| 0 <= a < b < vs.len() ==> !vs[a].eq_spec(&vs[b])) + && forall|a: int| 0 <= a < vs.len() ==> E::coordinate_spec(#[trigger] vs[a]) == i + && in_domain(domains[i], vs[a]) && misses(known[i], vs[a]); + let g = lemma_enumerate(used); + let f = |n: nat| vs[g(n) as int]; + assert forall|m: nat, n: nat| #![trigger used.contains(m), used.contains(n)] + used.contains(m) && used.contains(n) && m != n implies !f(m).eq_spec(&f(n)) by { + let a = g(m) as int; + let b = g(n) as int; + if a < b { assert(!vs[a].eq_spec(&vs[b])); } + else { assert(!vs[b].eq_spec(&vs[a])); assert(vs[a].eq_spec(&vs[b]) == vs[b].eq_spec(&vs[a])); } + } + assert forall|n: nat, k: E::Component| #![trigger used.contains(n), known[i].contains(k)] + used.contains(n) && known[i].contains(k) implies !f(n).eq_spec(&k) by { + assert(misses(known[i], vs[g(n) as int])); + } + f +} + +/// Capacity for the counterexample's own fresh values yields an admissible choice. +pub proof fn lemma_admissible_from_capacity( + domains: DomainsView, known: Seq>, cex: CexView, +) -> (f: FreshChoice) + requires + eq_equivalence::(), + domains.len() == arity::(), known.len() == arity::(), cex_arity(cex, arity::()), + capacity_for::(domains, known, cex), + ensures admissible::(domains, known, cex, f), +{ + assert forall|i: int| 0 <= i < arity::() implies + exists|f: spec_fn(nat) -> E::Component| choice_ok::(f, #[trigger] fresh_used(cex, i), known[i], domains[i], i) by { + let f = lemma_choice_from_capacity::(domains, known, cex, i); + } + let f = Seq::new(arity::(), |i: int| choose|f: spec_fn(nat) -> E::Component| + choice_ok::(f, fresh_used(cex, i), known[i], domains[i], i)); + assert forall|i: int| 0 <= i < arity::() implies + choice_ok::(#[trigger] f[i], fresh_used(cex, i), known[i], domains[i], i) by {} + f +} + +/// Under an admissible choice every tuple the counterexample denotes is well tagged. +proof fn lemma_event_of_well_tagged( + domains: DomainsView, known: Seq>, cex: CexView, + f: FreshChoice, c: ComponentsView, +) + requires + admissible::(domains, known, cex, f), + c.len() == arity::(), + forall|i: int| 0 <= i < c.len() ==> match #[trigger] c[i] { + ValueView::Constant(k) => E::coordinate_spec(k) == i, + ValueView::Fresh(n) => fresh_used(cex, i).contains(n), + }, + ensures well_tagged::(event_of(c, f)), +{ + assert forall|i: int| 0 <= i < c.len() implies E::coordinate_spec(#[trigger] event_of(c, f)[i]) == i by { + match c[i] { + ValueView::Constant(k) => {}, + ValueView::Fresh(n) => { + assert(choice_ok::(f[i], fresh_used(cex, i), known[i], domains[i], i)); + assert(fresh_used(cex, i).contains(n)); + }, + } + } +} + +/// An admissible choice denotes a real pair of events (`views_surjective` in `history_syntax::spec::events`). +pub proof fn lemma_instance_from_choice( + domains: DomainsView, known: Seq>, cex: CexView, + f: FreshChoice, +) + requires + event_obligations::(), + cex_constants_tagged::(cex), + admissible::(domains, known, cex, f), + ensures exists|c: E, h: Seq| #[trigger] instantiates::(cex, f, c, h), +{ + assert forall|i: int| 0 <= i < cex.candidate.len() implies match #[trigger] cex.candidate[i] { + ValueView::Constant(k) => E::coordinate_spec(k) == i, + ValueView::Fresh(n) => fresh_used(cex, i).contains(n), + } by { + if let ValueView::Fresh(n) = cex.candidate[i] { assert(fresh_used(cex, i).contains(n)); } + } + lemma_event_of_well_tagged::(domains, known, cex, f, cex.candidate); + let c = choose|c: E| event_view(c) == event_of(cex.candidate, f); + assert forall|j: int| 0 <= j < cex.history.len() implies + exists|e: E| event_view(e) == event_of(#[trigger] cex.history[j], f) by { + assert forall|i: int| 0 <= i < cex.history[j].len() implies match #[trigger] cex.history[j][i] { + ValueView::Constant(k) => E::coordinate_spec(k) == i, + ValueView::Fresh(n) => fresh_used(cex, i).contains(n), + } by { + if let ValueView::Fresh(n) = cex.history[j][i] { assert(fresh_used(cex, i).contains(n)); } + } + lemma_event_of_well_tagged::(domains, known, cex, f, cex.history[j]); + } + let h = Seq::new(cex.history.len(), |j: int| choose|e: E| event_view(e) == event_of(cex.history[j], f)); + assert(history_view(h) =~= history_of(cex, f)); + assert(instantiates::(cex, f, c, h)); +} + +/// Decision 2: capacity for the counterexample's own fresh values gives a real instance. +pub proof fn lemma_capacity_gives_instance( + domains: DomainsView, known: Seq>, cex: CexView, +) + requires + event_obligations::(), + domains.len() == arity::(), known.len() == arity::(), cex_arity(cex, arity::()), + cex_constants_tagged::(cex), + capacity_for::(domains, known, cex), + ensures cex_has_instance::(domains, known, cex), +{ + let f = lemma_admissible_from_capacity::(domains, known, cex); + lemma_instance_from_choice::(domains, known, cex, f); + let (c, h) = choose|c: E, h: Seq| #[trigger] instantiates::(cex, f, c, h); + assert(admissible::(domains, known, cex, f) && instantiates::(cex, f, c, h)); +} + +// ----- capacity of integer coordinates ----- + +/// `size` values `embed(0), …, embed(size-1)`, pairwise distinct up to `eq_spec` and tagged `i`, +/// give capacity `k` at an undeclared coordinate whenever `known[i].len() + k <= size`: each +/// known constant blocks at most one of them. +pub proof fn lemma_fresh_capacity_range( + domains: DomainsView, known: Seq>, i: int, k: nat, + embed: spec_fn(int) -> E::Component, size: nat, +) + requires + eq_equivalence::(), + 0 <= i < domains.len(), 0 <= i < known.len(), domains[i] is None, + known[i].len() + k <= size, + forall|a: int, b: int| 0 <= a < size && 0 <= b < size ==> (#[trigger] embed(a).eq_spec(&embed(b)) <==> a == b), + forall|a: int| 0 <= a < size ==> E::coordinate_spec(#[trigger] embed(a)) == i, + ensures fresh_capacity::(domains, known, i, k), +{ + broadcast use {vstd::set::lemma_to_iset_len, vstd::set::lemma_to_iset_finite, + vstd::iset_lib::group_iset_properties, vstd::prelude::Seq::to_set_ensures}; + let fixed = known[i]; + let codes = vstd::iset_lib::set_int_range(0, size as int); + vstd::iset_lib::lemma_int_range(0, size as int); + let blocked = codes.filter(|n: int| !misses(fixed, embed(n))); + codes.lemma_len_filter(|n: int| !misses(fixed, embed(n))); + let pick = |n: int| choose|w: E::Component| fixed.contains(w) && embed(n).eq_spec(&w); + assert forall|m: int, n: int| blocked.contains(m) && blocked.contains(n) && #[trigger] pick(m) == #[trigger] pick(n) + implies m == n by { + let w = pick(m); + assert(fixed.contains(w) && embed(m).eq_spec(&w)); + assert(embed(n).eq_spec(&w)); + assert(w.eq_spec(&embed(n))); + assert(embed(m).eq_spec(&embed(n))); + } + assert(blocked.injective_on(pick)); + vstd::iset_lib::lemma_map_size(blocked, blocked.map(pick), pick); + assert forall|w: E::Component| blocked.map(pick).contains(w) implies fixed.to_iset().contains(w) by { + let n = choose|n: int| blocked.contains(n) && pick(n) == w; + assert(fixed.contains(pick(n))); + } + vstd::iset_lib::lemma_len_subset(blocked.map(pick), fixed.to_iset()); + assert(blocked.len() <= fixed.len()); + let free = codes.difference(blocked); + assert(codes.intersect(blocked) =~= blocked); + assert(free.len() == size - blocked.len()); + assert(free.len() >= k); + let all = free.to_seq(); + free.lemma_to_seq_len(); + free.lemma_to_seq_no_duplicates(); + free.lemma_to_seq_to_set_id(); + let picked = all.take(k as int); + let vs = picked.map(|j: int, n: int| embed(n)); + assert(vs.len() == k); + assert forall|a: int| 0 <= a < k implies free.contains(#[trigger] picked[a]) by { + assert(all.to_set().contains(all[a])); + assert(all.to_set().to_iset().contains(all[a])); + } + assert forall|a: int, b: int| 0 <= a < b < vs.len() implies !vs[a].eq_spec(&vs[b]) by { + assert(picked[a] != picked[b]); + assert(codes.contains(picked[a]) && codes.contains(picked[b])); + } + assert forall|a: int| 0 <= a < vs.len() implies E::coordinate_spec(#[trigger] vs[a]) == i + && in_domain(domains[i], vs[a]) && misses(fixed, vs[a]) by { + assert(codes.contains(picked[a])); + assert(!blocked.contains(picked[a])); + } + assert(exists|vs: Seq| #[trigger] vs.len() == k + && (forall|a: int, b: int| 0 <= a < b < vs.len() ==> !vs[a].eq_spec(&vs[b])) + && forall|a: int| 0 <= a < vs.len() ==> E::coordinate_spec(#[trigger] vs[a]) == i + && in_domain(domains[i], vs[a]) && misses(known[i], vs[a])); +} + +/// Capacity `k` at an undeclared `u8` coordinate `i`, embedded by `embed` (injective up to +/// `eq_spec`, tagged `i`), whenever `known[i].len() + k <= 256`. +pub proof fn lemma_fresh_capacity_u8( + domains: DomainsView, known: Seq>, i: int, k: nat, + embed: spec_fn(u8) -> E::Component, +) + requires + eq_equivalence::(), + 0 <= i < domains.len(), 0 <= i < known.len(), domains[i] is None, + known[i].len() + k <= 0x100, + forall|a: u8, b: u8| #[trigger] embed(a).eq_spec(&embed(b)) <==> a == b, + forall|a: u8| E::coordinate_spec(#[trigger] embed(a)) == i, + ensures fresh_capacity::(domains, known, i, k), +{ + lemma_fresh_capacity_range::(domains, known, i, k, |n: int| embed(n as u8), 0x100); +} + +pub proof fn lemma_fresh_capacity_u16( + domains: DomainsView, known: Seq>, i: int, k: nat, + embed: spec_fn(u16) -> E::Component, +) + requires + eq_equivalence::(), + 0 <= i < domains.len(), 0 <= i < known.len(), domains[i] is None, + known[i].len() + k <= 0x1_0000, + forall|a: u16, b: u16| #[trigger] embed(a).eq_spec(&embed(b)) <==> a == b, + forall|a: u16| E::coordinate_spec(#[trigger] embed(a)) == i, + ensures fresh_capacity::(domains, known, i, k), +{ + lemma_fresh_capacity_range::(domains, known, i, k, |n: int| embed(n as u16), 0x1_0000); +} + +pub proof fn lemma_fresh_capacity_u32( + domains: DomainsView, known: Seq>, i: int, k: nat, + embed: spec_fn(u32) -> E::Component, +) + requires + eq_equivalence::(), + 0 <= i < domains.len(), 0 <= i < known.len(), domains[i] is None, + known[i].len() + k <= 0x1_0000_0000, + forall|a: u32, b: u32| #[trigger] embed(a).eq_spec(&embed(b)) <==> a == b, + forall|a: u32| E::coordinate_spec(#[trigger] embed(a)) == i, + ensures fresh_capacity::(domains, known, i, k), +{ + lemma_fresh_capacity_range::(domains, known, i, k, |n: int| embed(n as u32), 0x1_0000_0000); +} + +pub proof fn lemma_fresh_capacity_u64( + domains: DomainsView, known: Seq>, i: int, k: nat, + embed: spec_fn(u64) -> E::Component, +) + requires + eq_equivalence::(), + 0 <= i < domains.len(), 0 <= i < known.len(), domains[i] is None, + known[i].len() + k <= 0x1_0000_0000_0000_0000, + forall|a: u64, b: u64| #[trigger] embed(a).eq_spec(&embed(b)) <==> a == b, + forall|a: u64| E::coordinate_spec(#[trigger] embed(a)) == i, + ensures fresh_capacity::(domains, known, i, k), +{ + lemma_fresh_capacity_range::(domains, known, i, k, |n: int| embed(n as u64), 0x1_0000_0000_0000_0000); +} + +} // verus! diff --git a/src/junco-core/src/verify/dsl.rs b/src/junco-core/src/verify/dsl.rs new file mode 100644 index 000000000..915a9de6b --- /dev/null +++ b/src/junco-core/src/verify/dsl.rs @@ -0,0 +1,229 @@ +//! Lemmas about the typed semantics of `crate::spec::semantics`, and a real scope client. + +use crate::spec::semantics::{lang, rule_views, test_sem}; +use alloc::boxed::Box; +use history_syntax::spec::events::{HeadView, RegexView, TestView}; +use history_syntax::{Component, Event, Rule}; +use vstd::prelude::*; + +verus! { + +broadcast use {vstd::std_specs::vec::group_vec_axioms, vstd::seq::group_seq_lemmas}; + +/// Indexing the views of a rule sequence is the view of the indexed rule. +pub broadcast proof fn lemma_rule_views_index(rules: Seq>, i: int) + requires 0 <= i < rules.len(), + ensures #![trigger rule_views(rules)[i]] #![trigger rules[i]@] rule_views(rules)[i] == rules[i]@, +{} + +/// Empty operators retain their different Boolean and language identities. +pub proof fn lemma_empty_operators( + head: HeadView, candidate: Seq, word: Seq>, +) + ensures + test_sem(TestView::And(Seq::empty()), head, candidate, candidate), + !test_sem(TestView::Or(Seq::empty()), head, candidate, candidate), + !lang(RegexView::Union(Seq::empty()), head, candidate, word), + lang(RegexView::Intersect(Seq::empty()), head, candidate, word), + lang(RegexView::Concat(Seq::empty()), head, candidate, word) <==> word.len() == 0, +{ + if lang(RegexView::Concat(Seq::empty()), head, candidate, word) { + let parts = choose|parts: Seq>>| + parts.len() == 0 && word == parts.flatten() + && forall|i: int| 0 <= i < 0 ==> lang(RegexView::Empty, head, candidate, parts[i]); + assert(parts =~= Seq::empty()); + } + if word.len() == 0 { + let parts: Seq>> = Seq::empty(); + assert(word =~= parts.flatten()); + assert(lang(RegexView::Concat(Seq::empty()), head, candidate, word)); + } +} + +proof fn lemma_star_test_lang( + test: TestView, head: HeadView, candidate: Seq, + word: Seq>, +) + ensures + lang(RegexView::Star(Box::new(RegexView::Test(test))), head, candidate, word) + <==> forall|i: int| 0 <= i < word.len() ==> test_sem(test, head, candidate, word[i]), + decreases word.len(), +{ + reveal_with_fuel(lang, 2); + let star = RegexView::Star(Box::new(RegexView::Test(test))); + if word.len() == 0 { + let parts: Seq>> = Seq::empty(); + assert(word =~= parts.flatten()); + assert(forall|i: int| 0 <= i < parts.len() ==> + lang(RegexView::Test(test), head, candidate, parts[i])); + assert(lang(star, head, candidate, word)); + } else { + let rest = word.drop_first(); + lemma_star_test_lang(test, head, candidate, rest); + if lang(star, head, candidate, word) { + let parts = choose|parts: Seq>>| + word == parts.flatten() + && forall|i: int| 0 <= i < parts.len() ==> + lang(RegexView::Test(test), head, candidate, parts[i]); + assert(parts.len() > 0); + assert(lang(RegexView::Test(test), head, candidate, parts[0])); + assert(parts[0].len() == 1); + let tail = parts.drop_first(); + assert(word == parts[0] + tail.flatten()); + assert(word[0] == parts[0][0]); + assert(parts[0] =~= seq![word[0]]); + assert(rest =~= tail.flatten()); + assert forall|i: int| 0 <= i < tail.len() implies + lang(RegexView::Test(test), head, candidate, tail[i]) by { + assert(tail[i] == parts[i + 1]); + } + assert(lang(star, head, candidate, rest)); + assert forall|i: int| 0 <= i < word.len() implies + test_sem(test, head, candidate, word[i]) by { + if i > 0 { + assert(rest[i - 1] == word[i]); + assert(test_sem(test, head, candidate, rest[i - 1])); + } + } + } + if forall|i: int| 0 <= i < word.len() ==> test_sem(test, head, candidate, word[i]) { + assert forall|i: int| 0 <= i < rest.len() implies + test_sem(test, head, candidate, rest[i]) by { + assert(rest[i] == word[i + 1]); + } + assert(lang(star, head, candidate, rest)); + let tail = choose|tail: Seq>>| + rest == tail.flatten() + && forall|i: int| 0 <= i < tail.len() ==> + lang(RegexView::Test(test), head, candidate, tail[i]); + let parts = seq![seq![word[0]]] + tail; + assert(parts.drop_first() =~= tail); + assert(word =~= seq![word[0]] + rest); + assert(parts.flatten() == word); + assert forall|i: int| 0 <= i < parts.len() implies + lang(RegexView::Test(test), head, candidate, parts[i]) by { + if i > 0 { + assert(parts[i] == tail[i - 1]); + } else { + assert(parts[i] == seq![word[0]]); + } + } + assert(lang(star, head, candidate, word)); + } + } +} + +/// A setter followed by a stable suffix; the setter need not be unique or disjoint from stable. +/// The empty word cannot match because the setter consumes exactly one event. +#[verifier::spinoff_prover] +pub proof fn lemma_last_state_change_lang( + setter: TestView, stable: TestView, head: HeadView, + candidate: Seq, word: Seq>, +) + ensures + lang(RegexView::Concat(seq![RegexView::All, RegexView::Test(setter), + RegexView::Star(Box::new(RegexView::Test(stable)))]), head, candidate, word) + <==> exists|i: int| 0 <= i < word.len() + && test_sem(setter, head, candidate, word[i]) + && forall|j: int| i < j < word.len() ==> test_sem(stable, head, candidate, word[j]), +{ + reveal_with_fuel(lang, 2); + reveal_with_fuel(Seq::flatten, 4); + let children = seq![RegexView::All, RegexView::Test(setter), + RegexView::Star(Box::new(RegexView::Test(stable)))]; + let regex = RegexView::Concat(children); + if lang(regex, head, candidate, word) { + let parts = choose|parts: Seq>>| + parts.len() == children.len() && word == parts.flatten() + && forall|k: int| 0 <= k < children.len() ==> + lang(children[k], head, candidate, parts[k]); + assert(lang(children[1], head, candidate, parts[1])); + assert(parts[1].len() == 1); + assert(parts =~= seq![parts[0], parts[1], parts[2]]); + assert(parts.flatten() == parts[0] + parts[1] + parts[2]); + let i = parts[0].len() as int; + assert(0 <= i < word.len()); + assert(word[i] == parts[1][0]); + assert(test_sem(setter, head, candidate, word[i])); + assert(lang(children[2], head, candidate, parts[2])); + lemma_star_test_lang(stable, head, candidate, parts[2]); + assert forall|j: int| i < j < word.len() implies + test_sem(stable, head, candidate, word[j]) by { + assert(0 <= j - i - 1 < parts[2].len()); + assert(word[j] == parts[2][j - i - 1]); + assert(test_sem(stable, head, candidate, parts[2][j - i - 1])); + } + assert(exists|i: int| 0 <= i < word.len() + && test_sem(setter, head, candidate, word[i]) + && forall|j: int| i < j < word.len() ==> test_sem(stable, head, candidate, word[j])); + } + if exists|i: int| 0 <= i < word.len() + && test_sem(setter, head, candidate, word[i]) + && forall|j: int| i < j < word.len() ==> test_sem(stable, head, candidate, word[j]) { + let i = choose|i: int| 0 <= i < word.len() + && test_sem(setter, head, candidate, word[i]) + && forall|j: int| i < j < word.len() ==> test_sem(stable, head, candidate, word[j]); + let prefix = word.take(i); + let suffix = word.skip(i + 1); + word.lemma_split_at(i); + word.skip(i).lemma_split_at(1); + assert(word.skip(i).take(1) =~= seq![word[i]]); + assert(word.skip(i).skip(1) =~= suffix); + assert(word == prefix + seq![word[i]] + suffix); + assert forall|j: int| 0 <= j < suffix.len() implies + test_sem(stable, head, candidate, suffix[j]) by { + assert(suffix[j] == word[i + 1 + j]); + assert(test_sem(stable, head, candidate, word[i + 1 + j])); + } + lemma_star_test_lang(stable, head, candidate, suffix); + let parts = seq![prefix, seq![word[i]], suffix]; + assert(parts.flatten() == word); + assert forall|k: int| 0 <= k < children.len() implies + lang(children[k], head, candidate, parts[k]) by { + if k == 0 { + assert(children[k] == RegexView::All); + } else if k == 1 { + assert(children[k] == RegexView::Test(setter)); + assert(parts[k] == seq![word[i]]); + } else { + assert(k == 2); + assert(children[k] == RegexView::Star(Box::new(RegexView::Test(stable)))); + assert(parts[k] == suffix); + } + } + assert(lang(regex, head, candidate, word)); + } +} + +pub proof fn lemma_complement_is_whole_word( + regex: RegexView, head: HeadView, candidate: Seq, + word: Seq>, +) + ensures lang(RegexView::Not(Box::new(regex)), head, candidate, word) + <==> !lang(regex, head, candidate, word), +{} + + +/// The real scope bodies preserve declarations and reject a cross-coordinate use. +pub fn scope_client<'a>(name: &'a str, arity: usize, first: Component, second: Component) + -> (result: Result) + requires 1 <= arity <= history_syntax::MAX_ARITY, + first.0 < arity, second.0 < arity, first != second, + ensures result == Ok(first), +{ + let mut scope = crate::scope::VariableScope::new(arity); + let bound = scope.bind(first, name); + proof! { + assert(bound is Ok); + let witness = first.0 as int; + assert(Component(witness as u8) == first); + assert(scope.has_name(Component(witness as u8), name@)); + assert(0 <= witness < scope.arity_spec() && witness != second.0); + assert(scope.conflicts(second, name@)); + } + let conflict = scope.bind(second, name); + proof! { assert(conflict is Err); } + scope.resolve(first, name) +} + +} diff --git a/src/junco-core/src/verify/encoding.rs b/src/junco-core/src/verify/encoding.rs new file mode 100644 index 000000000..8bb55a554 --- /dev/null +++ b/src/junco-core/src/verify/encoding.rs @@ -0,0 +1,641 @@ +//! Finite component codebooks and the constant-encoding bridge. +//! +//! Representatives are concrete values. Equality, domain membership, and native +//! lookup correspondence are obligations of an opted-in encoder, not Rust identity. + +use crate::flat::verify::field_index; +use crate::flat::{FlatHead, FlatPair, FlatRegex, FlatTerm, FlatTest}; +use crate::verify::history_specs::EventView; +use history_syntax::MAX_ARITY; +use history_syntax::syntax::Component; +use vstd::prelude::*; + +verus! { + +broadcast use {vstd::std_specs::vec::group_vec_axioms, vstd::seq::group_seq_lemmas}; + +/// Pointwise numeric representation preserves the policy's coordinate count. +pub open spec fn event_representation(event: Seq, numeric: EventView) -> bool { + event.len() == numeric.len() + && forall|i: int| 0 <= i < event.len() ==> numeric[i] == event[i] as nat +} + +pub open spec fn event_relation() -> spec_fn(Seq, EventView) -> bool { + |event: Seq, numeric: EventView| event_representation(event, numeric) +} + +pub open spec fn word_representation(word: Seq>, numeric: Seq) -> bool { + pointwise(word, numeric, event_relation()) +} + +pub type Equality = spec_fn(Component, C, C) -> bool; +pub type Domain = spec_fn(Component, C) -> bool; +/// One finite sequence of representatives per policy coordinate. +pub type Codebook = Seq>; + +pub open spec fn field_at(index: int) -> Component { + Component(index as u8) +} + +pub open spec fn equality_laws(eq: Equality, domain: Domain) -> bool { + (forall|f: Component, a: C| #[trigger] domain(f, a) ==> eq(f, a, a)) + && (forall|f: Component, a: C, b: C| domain(f, a) && domain(f, b) + ==> #[trigger] eq(f, a, b) == eq(f, b, a)) + && (forall|f: Component, a: C, b: C, c: C| + domain(f, a) && domain(f, b) && domain(f, c) + && #[trigger] eq(f, a, b) && #[trigger] eq(f, b, c) + ==> eq(f, a, c)) +} + +pub open spec fn encoded(maps: Codebook, eq: Equality, field: Component, value: C, id: u64) -> bool { + 1 <= maps.len() <= MAX_ARITY && 0 <= field_index(field) < maps.len() + && id > 0 && exists|i: int| + 0 <= i < maps[field_index(field)].len() + && maps[field_index(field)][i].1 == id + && eq(field, value, maps[field_index(field)][i].0) +} + +pub open spec fn maps_wf(maps: Codebook, eq: Equality, domain: Domain) -> bool { + 1 <= maps.len() <= MAX_ARITY && equality_laws(eq, domain) + && (forall|f: int, i: int| 0 <= f < maps.len() && 0 <= i < maps[f].len() + ==> domain(field_at(f), maps[f][i].0) && maps[f][i].1 > 0) + && (forall|f: int, i: int, j: int| + 0 <= f < maps.len() && 0 <= i < maps[f].len() && 0 <= j < maps[f].len() + ==> (eq(field_at(f), maps[f][i].0, maps[f][j].0) + == (maps[f][i].1 == maps[f][j].1))) +} + +/// Even an unsuccessful insertion preserves every previously published association. +pub open spec fn extends(before: Codebook, after: Codebook, eq: Equality) -> bool { + forall|f: Component, value: C, id: u64| encoded(before, eq, f, value, id) + ==> encoded(after, eq, f, value, id) +} + +pub proof fn lemma_extends_transitive(a: Codebook, b: Codebook, c: Codebook, eq: Equality) + requires extends(a, b, eq), extends(b, c, eq), + ensures extends(a, c, eq), +{} + +/// Every value in `after`'s books is a value `before` held at the same coordinate or one that +/// `added` admits there: an encoding interns nothing but what it was asked to encode. +pub open spec fn grows_by(before: Codebook, after: Codebook, added: spec_fn(Component, C) -> bool) -> bool { + after.len() == before.len() && forall|f: int, i: int| #![trigger after[f][i]] 0 <= f < after.len() && 0 <= i < after[f].len() + ==> (exists|j: int| 0 <= j < before[f].len() && (#[trigger] before[f][j]).0 == after[f][i].0) + || added(field_at(f), after[f][i].0) +} + +/// The one value an `encode` call may intern. +pub open spec fn only_value(field: Component, value: C) -> spec_fn(Component, C) -> bool { + |f: Component, v: C| f == field && v == value +} + +/// The constant a head slot at `field` may intern. +pub open spec fn head_constant_of(head: FlatHead, field: Component) -> spec_fn(Component, C) -> bool { + |f: Component, v: C| f == field && head == FlatHead::Constant(v) +} + +/// The constant a test atom may intern. +pub open spec fn test_constant_of(test: FlatTest) -> spec_fn(Component, C) -> bool { + |f: Component, v: C| match test { + FlatTest::Atom { field, term: FlatTerm::Constant(value), .. } => f == field && v == value, + _ => false, + } +} + +/// `value` is a constant of `source` at coordinate `field` (a head slot or a test atom). +pub open spec fn source_constant(source: FlatPair, field: Component, value: C) -> bool { + (exists|i: int| 0 <= i < source.head@.len() && field_at(i) == field + && (#[trigger] source.head@[i]) == FlatHead::Constant(value)) + || (exists|i: int| 0 <= i < source.tests@.len() && match #[trigger] source.tests@[i] { + FlatTest::Atom { field: f, term: FlatTerm::Constant(v), .. } => f == field && v == value, + _ => false, + }) +} + +pub open spec fn source_constants(source: FlatPair) -> spec_fn(Component, C) -> bool { + |f: Component, v: C| source_constant(source, f, v) +} + +pub proof fn lemma_head_source_constant(source: FlatPair, i: int) + requires 0 <= i < source.head@.len(), + ensures forall|f: Component, v: C| #[trigger] head_constant_of(source.head@[i], field_at(i))(f, v) + ==> source_constants(source)(f, v), +{ + assert forall|f: Component, v: C| #[trigger] head_constant_of(source.head@[i], field_at(i))(f, v) + implies source_constants(source)(f, v) by { + assert(source.head@[i] == FlatHead::Constant(v)); + } +} + +pub proof fn lemma_test_source_constant(source: FlatPair, i: int) + requires 0 <= i < source.tests@.len(), + ensures forall|f: Component, v: C| #[trigger] test_constant_of(source.tests@[i])(f, v) + ==> source_constants(source)(f, v), +{ + assert forall|f: Component, v: C| #[trigger] test_constant_of(source.tests@[i])(f, v) + implies source_constants(source)(f, v) by { + assert(match source.tests@[i] { + FlatTest::Atom { field: f2, term: FlatTerm::Constant(v2), .. } => f2 == f && v2 == v, + _ => false, + }); + } +} + +pub proof fn lemma_grows_by_refl(book: Codebook, added: spec_fn(Component, C) -> bool) + ensures grows_by(book, book, added), +{ + assert forall|f: int, i: int| #![trigger book[f][i]] 0 <= f < book.len() && 0 <= i < book[f].len() + implies exists|j: int| 0 <= j < book[f].len() && (#[trigger] book[f][j]).0 == book[f][i].0 by { + let j = i; + assert(0 <= j < book[f].len() && book[f][j].0 == book[f][i].0); + } +} + +/// Two growths compose, and either bound may be weakened to a common one. +pub proof fn lemma_grows_by_transitive(a: Codebook, b: Codebook, c: Codebook, + p: spec_fn(Component, C) -> bool, q: spec_fn(Component, C) -> bool, r: spec_fn(Component, C) -> bool) + requires grows_by(a, b, p), grows_by(b, c, q), + forall|f: Component, v: C| #[trigger] p(f, v) ==> r(f, v), + forall|f: Component, v: C| #[trigger] q(f, v) ==> r(f, v), + ensures grows_by(a, c, r), +{ + assert forall|f: int, i: int| #![trigger c[f][i]] 0 <= f < c.len() && 0 <= i < c[f].len() + implies (exists|j: int| 0 <= j < a[f].len() && (#[trigger] a[f][j]).0 == c[f][i].0) + || r(field_at(f), c[f][i].0) by { + if exists|j: int| 0 <= j < b[f].len() && (#[trigger] b[f][j]).0 == c[f][i].0 { + let j = choose|j: int| 0 <= j < b[f].len() && (#[trigger] b[f][j]).0 == c[f][i].0; + assert(0 <= f < b.len() && 0 <= j < b[f].len()); + } + } +} + +pub proof fn lemma_grows_by_weaken(a: Codebook, b: Codebook, + p: spec_fn(Component, C) -> bool, q: spec_fn(Component, C) -> bool) + requires grows_by(a, b, p), forall|f: Component, v: C| #[trigger] p(f, v) ==> q(f, v), + ensures grows_by(a, b, q), +{ + lemma_grows_by_refl(a, p); + lemma_grows_by_transitive(a, a, b, p, p, q); +} + +pub proof fn lemma_encoded_equality( + maps: Codebook, eq: Equality, domain: Domain, field: Component, + left: C, right: C, left_id: u64, right_id: u64, +) + requires maps_wf(maps, eq, domain), domain(field, left), domain(field, right), + encoded(maps, eq, field, left, left_id), encoded(maps, eq, field, right, right_id), + ensures eq(field, left, right) == (left_id == right_id), +{ + let f = field_index(field); + assert(field_at(f) == field); + let i = choose|i: int| 0 <= i < maps[f].len() && maps[f][i].1 == left_id + && eq(field, left, maps[f][i].0); + let j = choose|j: int| 0 <= j < maps[f].len() && maps[f][j].1 == right_id + && eq(field, right, maps[f][j].0); + let a = maps[f][i].0; + let b = maps[f][j].0; + assert(domain(field, a) && domain(field, b)); + assert(eq(field, a, left)); + assert(eq(field, b, right)); + if eq(field, left, right) { + assert(eq(field, a, right)); + assert(eq(field, a, b)); + } + if left_id == right_id { + assert(eq(field, a, b)); + assert(eq(field, left, b)); + assert(eq(field, left, right)); + } +} + +pub open spec fn head_shape(source: FlatHead, target: FlatHead) -> bool { + match (source, target) { + (FlatHead::Any, FlatHead::Any) | (FlatHead::Bind, FlatHead::Bind) + | (FlatHead::Constant(_), FlatHead::Constant(_)) => true, + _ => false, + } +} + +pub open spec fn head_encoded(source: FlatHead, target: FlatHead, field: Component, + maps: Codebook, eq: Equality) -> bool { + match (source, target) { + (FlatHead::Any, FlatHead::Any) | (FlatHead::Bind, FlatHead::Bind) => true, + (FlatHead::Constant(value), FlatHead::Constant(id)) => encoded(maps, eq, field, value, id), + _ => false, + } +} + +pub open spec fn test_shape(source: FlatTest, target: FlatTest) -> bool { + match (source, target) { + (FlatTest::Bool(a), FlatTest::Bool(b)) => a == b, + (FlatTest::Atom { field: a, term: x, positive: p }, + FlatTest::Atom { field: b, term: y, positive: q }) => a == b && p == q && match (x, y) { + (FlatTerm::Constant(_), FlatTerm::Constant(_)) => true, + (FlatTerm::Variable(i), FlatTerm::Variable(j)) => i == j, + _ => false, + }, + (FlatTest::And(a), FlatTest::And(b)) | (FlatTest::Or(a), FlatTest::Or(b)) => a@ == b@, + _ => false, + } +} + +pub open spec fn test_encoded(source: FlatTest, target: FlatTest, maps: Codebook, eq: Equality) -> bool { + test_shape(source, target) && match (source, target) { + (FlatTest::Atom { field, term: FlatTerm::Constant(value), .. }, + FlatTest::Atom { term: FlatTerm::Constant(id), .. }) => encoded(maps, eq, field, value, id), + _ => true, + } +} + +pub open spec fn regex_same(source: FlatRegex, target: FlatRegex) -> bool { + match (source, target) { + (FlatRegex::Empty, FlatRegex::Empty) | (FlatRegex::All, FlatRegex::All) + | (FlatRegex::Epsilon, FlatRegex::Epsilon) => true, + (FlatRegex::Test(a), FlatRegex::Test(b)) | (FlatRegex::Star(a), FlatRegex::Star(b)) + | (FlatRegex::Complement(a), FlatRegex::Complement(b)) => a == b, + (FlatRegex::Concat(a), FlatRegex::Concat(b)) | (FlatRegex::Union(a), FlatRegex::Union(b)) + | (FlatRegex::Intersect(a), FlatRegex::Intersect(b)) => a@ == b@, + _ => false, + } +} + +pub open spec fn regex_tables_same(source: Seq, target: Seq) -> bool { + source.len() == target.len() && forall|i: int| 0 <= i < source.len() + ==> regex_same(source[i], target[i]) +} + +pub open spec fn topology(source: FlatPair, target: FlatPair) -> bool { + source.root == target.root && regex_tables_same(source.regexes@, target.regexes@) + && source.tests@.len() == target.tests@.len() + && source.head@.len() == target.head@.len() + && (forall|i: int| 0 <= i < source.head@.len() ==> head_shape(source.head@[i], target.head@[i])) + && (forall|i: int| 0 <= i < source.tests@.len() ==> test_shape(source.tests@[i], target.tests@[i])) +} + +pub proof fn lemma_topology_wf(source: FlatPair, target: FlatPair) + requires crate::flat::verify::structural_wf(source), topology(source, target), + ensures crate::flat::verify::structural_wf(target), +{ + assert forall|i: int| 0 <= i < target.tests@.len() implies + crate::flat::verify::test_wf(target.head@, target.tests@[i], i as nat) by { + if let FlatTest::Atom { field, term: FlatTerm::Variable(_), .. } = target.tests@[i] { + let f = field_index(field); + assert(source.head@[f] is Bind); + assert(target.head@[f] is Bind); + } + } + assert forall|i: int| 0 <= i < target.regexes@.len() implies + crate::flat::verify::regex_wf(target.regexes@[i], i as nat, target.tests@.len()) by { + } +} + +pub open spec fn lowering(source: FlatPair, target: FlatPair, maps: Codebook, eq: Equality) -> bool { + topology(source, target) + && (forall|i: int| 0 <= i < source.head@.len() ==> head_encoded(source.head@[i], target.head@[i], field_at(i), maps, eq)) + && (forall|i: int| 0 <= i < source.tests@.len() ==> test_encoded(source.tests@[i], target.tests@[i], maps, eq)) +} + +pub proof fn lemma_head_extends(source: FlatHead, target: FlatHead, field: Component, + before: Codebook, after: Codebook, eq: Equality) + requires head_encoded(source, target, field, before, eq), extends(before, after, eq), + ensures head_encoded(source, target, field, after, eq), +{} + +pub proof fn lemma_test_extends(source: FlatTest, target: FlatTest, + before: Codebook, after: Codebook, eq: Equality) + requires test_encoded(source, target, before, eq), extends(before, after, eq), + ensures test_encoded(source, target, after, eq), +{} + +pub proof fn lemma_lowering_extends(source: FlatPair, target: FlatPair, + before: Codebook, after: Codebook, eq: Equality) + requires lowering(source, target, before, eq), extends(before, after, eq), + ensures lowering(source, target, after, eq), +{ + assert forall|i: int| 0 <= i < source.head@.len() implies head_encoded(source.head@[i], target.head@[i], field_at(i), after, eq) by { + lemma_head_extends(source.head@[i], target.head@[i], field_at(i), before, after, eq); + } + assert forall|i: int| 0 <= i < source.tests@.len() implies test_encoded(source.tests@[i], target.tests@[i], after, eq) by { + lemma_test_extends(source.tests@[i], target.tests@[i], before, after, eq); + } +} + +pub open spec fn event_encoded(maps: Codebook, eq: Equality, domain: Domain, + source: Seq, target: Seq) -> bool { + source.len() == maps.len() && target.len() == maps.len() + && forall|i: int| 0 <= i < maps.len() ==> domain(field_at(i), source[i]) + && encoded(maps, eq, field_at(i), source[i], target[i]) +} + +pub open spec fn word_encoded(maps: Codebook, eq: Equality, domain: Domain, + source: Seq>, target: Seq>) -> bool { + source.len() == target.len() && forall|i: int| 0 <= i < source.len() + ==> event_encoded(maps, eq, domain, source[i], target[i]) +} + +pub open spec fn head_in_domain(head: FlatHead, field: Component, domain: Domain) -> bool { + match head { FlatHead::Constant(value) => domain(field, value), _ => true } +} + +pub open spec fn test_in_domain(test: FlatTest, domain: Domain) -> bool { + match test { + FlatTest::Atom { field, term: FlatTerm::Constant(value), .. } => domain(field, value), _ => true, + } +} + +pub open spec fn constants_in_domain(source: FlatPair, domain: Domain) -> bool { + (forall|i: int| 0 <= i < source.head@.len() ==> head_in_domain(source.head@[i], field_at(i), domain)) + && (forall|i: int| 0 <= i < source.tests@.len() ==> test_in_domain(source.tests@[i], domain)) +} + +pub open spec fn numeric_equality() -> Equality { |_: Component, a: u64, b: u64| a == b } + +pub proof fn lemma_head_preservation(source: FlatPair, target: FlatPair, + maps: Codebook, eq: Equality, domain: Domain, request: Seq, numeric: Seq) + requires lowering(source, target, maps, eq), maps_wf(maps, eq, domain), + constants_in_domain(source, domain), event_encoded(maps, eq, domain, request, numeric), + ensures crate::flat::verify::head_matches(source.head@, request, eq) + == crate::flat::verify::head_matches(target.head@, numeric, numeric_equality()), +{ + if source.head@.len() == request.len() { + assert forall|i: int| 0 <= i < source.head@.len() implies (match (#[trigger] source.head@[i], target.head@[i]) { + (FlatHead::Constant(value), FlatHead::Constant(id)) => eq(field_at(i), request[i], value) == (numeric[i] == id), + _ => true, + }) by { + if let FlatHead::Constant(value) = source.head@[i] { + if let FlatHead::Constant(id) = target.head@[i] { + lemma_encoded_equality(maps, eq, domain, field_at(i), request[i], value, numeric[i], id); + } + } + } + } +} + +pub open spec fn pointwise(source: Seq, target: Seq, relation: spec_fn(A, B) -> bool) -> bool { + source.len() == target.len() && forall|i: int| 0 <= i < source.len() ==> relation(source[i], target[i]) +} + +/// Lift a partition by its lengths; no injectivity of the event representation is needed. +pub proof fn lemma_partition_lift(source: Seq, target: Seq, parts: Seq>, + relation: spec_fn(A, B) -> bool) + requires pointwise(source, target, relation), target == parts.flatten(), + ensures exists|lifted: Seq>| lifted.len() == parts.len() && source == lifted.flatten() + && forall|i: int| 0 <= i < parts.len() ==> pointwise(lifted[i], parts[i], relation), + decreases parts.len(), +{ + if parts.len() == 0 { + assert(source == Seq::::empty()); + assert(source == Seq::>::empty().flatten()); + } else { + let count = parts[0].len() as int; + let prefix = source.take(count); + let suffix = source.skip(count); + assert(target.take(count) =~= parts[0]); + assert(target.skip(count) =~= parts.drop_first().flatten()); + assert forall|i: int| 0 <= i < prefix.len() implies relation(prefix[i], parts[0][i]) by { + assert(prefix[i] == source[i]); + assert(parts[0][i] == target[i]); + } + assert forall|i: int| 0 <= i < suffix.len() implies relation(suffix[i], target.skip(count)[i]) by { + assert(suffix[i] == source[i + count]); + assert(target.skip(count)[i] == target[i + count]); + } + lemma_partition_lift(suffix, target.skip(count), parts.drop_first(), relation); + let tail = choose|tail: Seq>| tail.len() == parts.drop_first().len() + && suffix == tail.flatten() + && forall|i: int| 0 <= i < parts.drop_first().len() ==> pointwise(tail[i], parts.drop_first()[i], relation); + let lifted = seq![prefix] + tail; + assert(lifted.drop_first() =~= tail); + assert(lifted.flatten() == source); + assert forall|i: int| 0 <= i < parts.len() implies pointwise(lifted[i], parts[i], relation) by { + if i > 0 { assert(lifted[i] == tail[i - 1]); assert(parts[i] == parts.drop_first()[i - 1]); } + } + } +} + +pub proof fn lemma_test_preservation(source: FlatPair, target: FlatPair, id: nat, + maps: Codebook, eq: Equality, domain: Domain, request: Seq, numeric_request: Seq, + event: Seq, numeric_event: Seq) + requires crate::flat::verify::structural_wf(source), lowering(source, target, maps, eq), + id < source.tests@.len(), maps_wf(maps, eq, domain), constants_in_domain(source, domain), + event_encoded(maps, eq, domain, request, numeric_request), + event_encoded(maps, eq, domain, event, numeric_event), + ensures crate::flat::verify::test_sem(source.tests@, id, request, event, eq) + == crate::flat::verify::test_sem(target.tests@, id, numeric_request, numeric_event, numeric_equality()), + decreases id, +{ + match (source.tests@[id as int], target.tests@[id as int]) { + (FlatTest::Atom { field, term: FlatTerm::Constant(value), .. }, + FlatTest::Atom { term: FlatTerm::Constant(value_id), .. }) => { + let f = field_index(field); + assert(field_at(f) == field); + if f < event.len() { + lemma_encoded_equality(maps, eq, domain, field, event[f], value, numeric_event[f], value_id); + } + }, + (FlatTest::Atom { field, term: FlatTerm::Variable(variable), .. }, _) => { + assert(field == variable); + let f = field_index(field); + assert(field_at(f) == field); + if f < event.len() { + lemma_encoded_equality(maps, eq, domain, field, event[f], request[f], numeric_event[f], numeric_request[f]); + } + }, + (FlatTest::And(children), _) | (FlatTest::Or(children), _) => { + assert forall|i: int| 0 <= i < children@.len() implies + crate::flat::verify::test_sem(source.tests@, children@[i] as nat, request, event, eq) + == crate::flat::verify::test_sem(target.tests@, children@[i] as nat, numeric_request, numeric_event, numeric_equality()) by { + lemma_test_preservation(source, target, children@[i] as nat, maps, eq, domain, + request, numeric_request, event, numeric_event); + } + }, + _ => {}, + } +} + +pub proof fn lemma_lang_preservation(source: FlatPair, target: FlatPair, id: nat, + maps: Codebook, eq: Equality, domain: Domain, request: Seq, numeric_request: Seq, + word: Seq>, numeric_word: Seq>) + requires crate::flat::verify::structural_wf(source), lowering(source, target, maps, eq), + id < source.regexes@.len(), maps_wf(maps, eq, domain), constants_in_domain(source, domain), + event_encoded(maps, eq, domain, request, numeric_request), + word_encoded(maps, eq, domain, word, numeric_word), + ensures crate::flat::verify::flat_lang(source.tests@, source.regexes@, id, request, word, eq) + == crate::flat::verify::flat_lang(target.tests@, target.regexes@, id, numeric_request, numeric_word, numeric_equality()), + decreases id, +{ + lemma_topology_wf(source, target); + assert(regex_same(source.regexes@[id as int], target.regexes@[id as int])); + assert forall|i: int| 0 <= i < word.len() implies crate::flat::verify::event_wf(#[trigger] word[i], request.len()) by { + assert(event_encoded(maps, eq, domain, word[i], numeric_word[i])); + } + assert forall|i: int| 0 <= i < numeric_word.len() implies crate::flat::verify::event_wf(#[trigger] numeric_word[i], numeric_request.len()) by { + assert(event_encoded(maps, eq, domain, word[i], numeric_word[i])); + } + match source.regexes@[id as int] { + FlatRegex::Test(test) => { + if word.len() == 1 { + lemma_test_preservation(source, target, test as nat, maps, eq, domain, + request, numeric_request, word[0], numeric_word[0]); + } + assert(crate::flat::verify::flat_lang(source.tests@, source.regexes@, id, request, word, eq) + == crate::flat::verify::flat_lang(target.tests@, target.regexes@, id, numeric_request, numeric_word, numeric_equality())); + }, + FlatRegex::Union(children) | FlatRegex::Intersect(children) => { + assert forall|i: int| 0 <= i < children@.len() implies + crate::flat::verify::flat_lang(source.tests@, source.regexes@, children@[i] as nat, request, word, eq) + == crate::flat::verify::flat_lang(target.tests@, target.regexes@, children@[i] as nat, numeric_request, numeric_word, numeric_equality()) by { + lemma_lang_preservation(source, target, children@[i] as nat, maps, eq, domain, + request, numeric_request, word, numeric_word); + } + assert(crate::flat::verify::flat_lang(source.tests@, source.regexes@, id, request, word, eq) + == crate::flat::verify::flat_lang(target.tests@, target.regexes@, id, numeric_request, numeric_word, numeric_equality())); + }, + FlatRegex::Complement(child) => { + lemma_lang_preservation(source, target, child as nat, maps, eq, domain, + request, numeric_request, word, numeric_word); + assert(crate::flat::verify::flat_lang(source.tests@, source.regexes@, id, request, word, eq) + == crate::flat::verify::flat_lang(target.tests@, target.regexes@, id, numeric_request, numeric_word, numeric_equality())); + }, + FlatRegex::Concat(children) => { + if crate::flat::verify::flat_lang(source.tests@, source.regexes@, id, request, word, eq) { + let parts = choose|parts: Seq>>| parts.len() == children@.len() + && word == parts.flatten() && forall|i: int| 0 <= i < children@.len() ==> + crate::flat::verify::flat_lang(source.tests@, source.regexes@, children@[i] as nat, request, parts[i], eq); + let relation = |n: Seq, r: Seq| event_encoded(maps, eq, domain, r, n); + assert(pointwise(numeric_word, word, relation)); + lemma_partition_lift(numeric_word, word, parts, relation); + let lifted = choose|lifted: Seq>>| lifted.len() == parts.len() + && numeric_word == lifted.flatten() + && forall|i: int| 0 <= i < parts.len() ==> pointwise(lifted[i], parts[i], relation); + assert forall|i: int| 0 <= i < children@.len() implies + crate::flat::verify::flat_lang(target.tests@, target.regexes@, children@[i] as nat, numeric_request, lifted[i], numeric_equality()) by { + assert(word_encoded(maps, eq, domain, parts[i], lifted[i])); + lemma_lang_preservation(source, target, children@[i] as nat, maps, eq, domain, + request, numeric_request, parts[i], lifted[i]); + } + } + if crate::flat::verify::flat_lang(target.tests@, target.regexes@, id, numeric_request, numeric_word, numeric_equality()) { + let parts = choose|parts: Seq>>| parts.len() == children@.len() + && numeric_word == parts.flatten() && forall|i: int| 0 <= i < children@.len() ==> + crate::flat::verify::flat_lang(target.tests@, target.regexes@, children@[i] as nat, numeric_request, parts[i], numeric_equality()); + let relation = |r: Seq, n: Seq| event_encoded(maps, eq, domain, r, n); + lemma_partition_lift(word, numeric_word, parts, relation); + let lifted = choose|lifted: Seq>>| lifted.len() == parts.len() + && word == lifted.flatten() + && forall|i: int| 0 <= i < parts.len() ==> pointwise(lifted[i], parts[i], relation); + assert forall|i: int| 0 <= i < children@.len() implies + crate::flat::verify::flat_lang(source.tests@, source.regexes@, children@[i] as nat, request, lifted[i], eq) by { + assert(word_encoded(maps, eq, domain, lifted[i], parts[i])); + lemma_lang_preservation(source, target, children@[i] as nat, maps, eq, domain, + request, numeric_request, lifted[i], parts[i]); + } + } + assert(crate::flat::verify::flat_lang(source.tests@, source.regexes@, id, request, word, eq) + == crate::flat::verify::flat_lang(target.tests@, target.regexes@, id, numeric_request, numeric_word, numeric_equality())); + }, + FlatRegex::Star(child) => { + if crate::flat::verify::flat_lang(source.tests@, source.regexes@, id, request, word, eq) { + let parts = choose|parts: Seq>>| word == parts.flatten() + && forall|i: int| 0 <= i < parts.len() ==> + crate::flat::verify::flat_lang(source.tests@, source.regexes@, child as nat, request, parts[i], eq); + let relation = |n: Seq, r: Seq| event_encoded(maps, eq, domain, r, n); + assert(pointwise(numeric_word, word, relation)); + lemma_partition_lift(numeric_word, word, parts, relation); + let lifted = choose|lifted: Seq>>| lifted.len() == parts.len() + && numeric_word == lifted.flatten() + && forall|i: int| 0 <= i < parts.len() ==> pointwise(lifted[i], parts[i], relation); + assert forall|i: int| 0 <= i < parts.len() implies + crate::flat::verify::flat_lang(target.tests@, target.regexes@, child as nat, numeric_request, lifted[i], numeric_equality()) by { + assert(word_encoded(maps, eq, domain, parts[i], lifted[i])); + lemma_lang_preservation(source, target, child as nat, maps, eq, domain, + request, numeric_request, parts[i], lifted[i]); + } + } + if crate::flat::verify::flat_lang(target.tests@, target.regexes@, id, numeric_request, numeric_word, numeric_equality()) { + let parts = choose|parts: Seq>>| numeric_word == parts.flatten() + && forall|i: int| 0 <= i < parts.len() ==> + crate::flat::verify::flat_lang(target.tests@, target.regexes@, child as nat, numeric_request, parts[i], numeric_equality()); + let relation = |r: Seq, n: Seq| event_encoded(maps, eq, domain, r, n); + lemma_partition_lift(word, numeric_word, parts, relation); + let lifted = choose|lifted: Seq>>| lifted.len() == parts.len() + && word == lifted.flatten() + && forall|i: int| 0 <= i < parts.len() ==> pointwise(lifted[i], parts[i], relation); + assert forall|i: int| 0 <= i < parts.len() implies + crate::flat::verify::flat_lang(source.tests@, source.regexes@, child as nat, request, lifted[i], eq) by { + assert(word_encoded(maps, eq, domain, lifted[i], parts[i])); + lemma_lang_preservation(source, target, child as nat, maps, eq, domain, + request, numeric_request, lifted[i], parts[i]); + } + } + assert(crate::flat::verify::flat_lang(source.tests@, source.regexes@, id, request, word, eq) + == crate::flat::verify::flat_lang(target.tests@, target.regexes@, id, numeric_request, numeric_word, numeric_equality())); + }, + _ => { + assert(crate::flat::verify::flat_lang(source.tests@, source.regexes@, id, request, word, eq) + == crate::flat::verify::flat_lang(target.tests@, target.regexes@, id, numeric_request, numeric_word, numeric_equality())); + }, + } +} + +/// The request/history may introduce values after compilation. Only extension and +/// coverage are required; semantic equivalence is the conclusion, never a premise. +pub proof fn lemma_later_maps_preservation(source: FlatPair, target: FlatPair, + compiled_maps: Codebook, later_maps: Codebook, eq: Equality, domain: Domain, + request: Seq, numeric_request: Seq, word: Seq>, numeric_word: Seq>) + requires crate::flat::verify::structural_wf(source), lowering(source, target, compiled_maps, eq), + extends(compiled_maps, later_maps, eq), maps_wf(later_maps, eq, domain), + constants_in_domain(source, domain), event_encoded(later_maps, eq, domain, request, numeric_request), + word_encoded(later_maps, eq, domain, word, numeric_word), + ensures crate::flat::verify::head_matches(source.head@, request, eq) + == crate::flat::verify::head_matches(target.head@, numeric_request, numeric_equality()), + crate::flat::verify::flat_lang(source.tests@, source.regexes@, source.root as nat, request, word, eq) + == crate::flat::verify::flat_lang(target.tests@, target.regexes@, target.root as nat, numeric_request, numeric_word, numeric_equality()), +{ + lemma_lowering_extends(source, target, compiled_maps, later_maps, eq); + lemma_head_preservation(source, target, later_maps, eq, domain, request, numeric_request); + lemma_lang_preservation(source, target, source.root as nat, later_maps, eq, domain, + request, numeric_request, word, numeric_word); +} + + +/// Composition leaves only native component equality/projection and codebook +/// correspondence conditional; neither lowering's semantic equation is assumed. +pub proof fn lemma_dsl_later_maps_preservation( + rule: history_syntax::syntax::Rule, + flattened_rule: crate::flat::FlatRule, + numeric: FlatPair, + compiled_maps: Codebook, + later_maps: Codebook, + domain: Domain, + request: Seq, + history: Seq>, + numeric_request: Seq, numeric_history: Seq>, +) + requires crate::verify::flatten::flattened::(rule, flattened_rule), + request.len() == rule.head@.len(), + lowering(flattened_rule.source, numeric, compiled_maps, crate::verify::flatten::component_equality::()), + extends(compiled_maps, later_maps, crate::verify::flatten::component_equality::()), + maps_wf(later_maps, crate::verify::flatten::component_equality::(), domain), + constants_in_domain(flattened_rule.source, domain), + event_encoded(later_maps, crate::verify::flatten::component_equality::(), domain, + request, numeric_request), + word_encoded(later_maps, crate::verify::flatten::component_equality::(), domain, + history, numeric_history), + ensures crate::spec::semantics::head_matches(rule.head@, request) + == crate::flat::verify::head_matches(numeric.head@, numeric_request, numeric_equality()), + crate::spec::semantics::lang(rule.tail@, rule.head@, request, history) + == crate::flat::verify::flat_lang(numeric.tests@, numeric.regexes@, numeric.root as nat, + numeric_request, numeric_history, numeric_equality()), +{ + assert forall|i: int| 0 <= i < history.len() implies history[i].len() == request.len() by { + assert(event_encoded(later_maps, crate::verify::flatten::component_equality::(), domain, + history[i], numeric_history[i])); + } + crate::verify::flatten::flattening_preserves_semantics::(rule, flattened_rule, request, history); + lemma_later_maps_preservation(flattened_rule.source, numeric, compiled_maps, later_maps, + crate::verify::flatten::component_equality::(), domain, + request, numeric_request, history, numeric_history); +} + +} diff --git a/src/junco-core/src/verify/flatten.rs b/src/junco-core/src/verify/flatten.rs new file mode 100644 index 000000000..beba1ca2c --- /dev/null +++ b/src/junco-core/src/verify/flatten.rs @@ -0,0 +1,1056 @@ +//! Structural and semantic clients of the actual iterative owned-source lowering. + +use crate::errors::CompileError; +use crate::flat::verify as flat; +use crate::flat::{FlatHead, FlatRegex, FlatRule, FlatTerm, FlatTest}; +use crate::flatten::Work; +use crate::limits::Limits; +use crate::observation::ObservationWorld; +use crate::scope::VariableScope; +use crate::spec::semantics as dsl; +use history_syntax::Event; +use history_syntax::event::specs::EventSpec; +use history_syntax::spec::events::{AtomView, HeadView, PatternView, RegexView, TestView, arity}; +use history_syntax::syntax::{ + Component, ComponentPattern, Head, RegexExpr, Rule, RuleMode, TestExpr, +}; +use vstd::prelude::*; +use vstd::std_specs::cmp::PartialEqSpec; + +verus! { +type SourceHead = HeadView<::Component>; +type SourceTest = TestView<::Component>; +type SourceRegex = RegexView<::Component>; +type SourceEvent = Seq<::Component>; + +broadcast use {vstd::std_specs::vec::group_vec_axioms, vstd::seq::group_seq_lemmas}; + +/// Tagged component equality is already the event type's own equality contract. +pub open spec fn component_eq(_field: Component, left: E::Component, right: E::Component) -> bool { + left.eq_spec(&right) +} + +pub open spec fn component_equality() -> spec_fn(Component, E::Component, E::Component) -> bool { + |field: Component, left: E::Component, right: E::Component| component_eq::(field, left, right) +} + +/// A typed constant belongs only to its declared product coordinate. +pub open spec fn component_domain() -> crate::verify::encoding::Domain { + |field: Component, value: E::Component| E::coordinate_spec(value) == field.0 as nat +} + +pub open spec fn head_coordinates_wf(head: SourceHead) -> bool { + head.len() == arity::() && forall|i: int| 0 <= i < head.len() ==> match #[trigger] head[i] { + PatternView::Constant(value) => E::coordinate_spec(value) == i, + _ => true, + } +} + +pub(crate) proof fn lemma_rule_head_coordinates( + rule: history_syntax::spec::events::RuleView, +) + requires rule.head.len() == arity::(), dsl::rule_constants_tagged::(rule), + ensures head_coordinates_wf::(rule.head), +{ + assert forall|i: int| 0 <= i < rule.head.len() implies match #[trigger] rule.head[i] { + PatternView::Constant(value) => E::coordinate_spec(value) == i, + _ => true, + } by { + if let PatternView::Constant(value) = rule.head[i] { + assert(crate::spec::questions::head_constants(rule.head)[i].contains(value)); + assert(crate::spec::questions::rule_constants(rule)[i].contains(value)); + } + } +} + +pub open spec fn atom_coordinates_wf(atom: AtomView) -> bool { + atom.component < arity::() && match atom.pattern { + PatternView::Constant(value) => E::coordinate_spec(value) == atom.component, + _ => true, + } +} + +pub open spec fn head_slot_represents(flat: FlatHead, source: PatternView) -> bool { + match (flat, source) { + (FlatHead::Constant(a), PatternView::Constant(b)) => a == b, + (FlatHead::Bind, PatternView::Variable(_)) => true, + _ => false, + } +} + +pub open spec fn head_represents(flat: Seq>, head: SourceHead) -> bool { + flat.len() == head.len() && head.len() == arity::() + && 1 <= head.len() <= history_syntax::MAX_ARITY + && forall|i: int| 0 <= i < head.len() ==> head_slot_represents(#[trigger] flat[i], head[i]) +} + +pub open spec fn scope_matches(scope: VariableScope<'_>, head: SourceHead) -> bool { + scope.wf() && scope.arity_spec() == head.len() && head.len() == arity::() + && 1 <= head.len() <= history_syntax::MAX_ARITY + && forall|i: int| 0 <= i < head.len() ==> match scope.name_spec(Component(i as u8)) { + Some(name) => dsl::pattern_name(#[trigger] head[i]) == Some(name@), + None => dsl::pattern_name(#[trigger] head[i]) is None, + } +} + +pub open spec fn atom_term_represents(field: Component, term: FlatTerm, + atom: AtomView, head: SourceHead) -> bool +{ + field.0 as nat == atom.component && atom.component < head.len() && match (term, atom.pattern) { + (FlatTerm::Constant(a), PatternView::Constant(b)) => a == b, + (FlatTerm::Variable(bound), PatternView::Variable(name)) => bound == field + && dsl::pattern_name(head[atom.component as int]) == Some(name), + _ => false, + } +} + +#[verifier::opaque] +pub open spec fn test_operands(node: FlatTest) -> Seq { + match node { FlatTest::And(ids) | FlatTest::Or(ids) => ids@, _ => Seq::empty() } +} + +#[verifier::opaque] +pub open spec fn regex_operands(node: FlatRegex) -> Seq { + match node { FlatRegex::Concat(ids) | FlatRegex::Union(ids) | FlatRegex::Intersect(ids) => ids@, _ => Seq::empty() } +} + +pub proof fn lemma_test_operands(node: FlatTest) + ensures test_operands(node) == match node { FlatTest::And(ids) | FlatTest::Or(ids) => ids@, _ => Seq::empty() }, +{ reveal(test_operands); } + +pub proof fn lemma_regex_operands(node: FlatRegex) + ensures regex_operands(node) == match node { + FlatRegex::Concat(ids) | FlatRegex::Union(ids) | FlatRegex::Intersect(ids) => ids@, _ => Seq::empty(), + }, +{ reveal(regex_operands); } + +/// This is a structural relation, not the semantic equivalence that the bridge must prove. +pub open spec fn test_represents(tests: Seq>, id: nat, + source: SourceTest, head: SourceHead) -> bool + decreases source, +{ + id < tests.len() && dsl::test_scoped(source, head) && match source { + TestView::True => tests[id as int] == FlatTest::Bool(true), + TestView::False => tests[id as int] == FlatTest::Bool(false), + TestView::Atom { comparison, pattern } => match tests[id as int] { + FlatTest::Atom { field, term, positive } => positive == (comparison is Eq) + && atom_term_represents::(field, term, pattern, head), + _ => false, + }, + TestView::And(children) | TestView::Or(children) => { + let ids = test_operands(tests[id as int]); + ((source is And && tests[id as int] is And) || (source is Or && tests[id as int] is Or)) + && children.len() == ids.len() && flat::references_before(ids, id) + && forall|i: int| #![trigger ids[i]] 0 <= i < children.len() ==> + test_represents::(tests, ids[i] as nat, children[i], head) + }, + } +} + +pub open spec fn regex_represents(tests: Seq>, regexes: Seq, id: nat, + source: SourceRegex, head: SourceHead) -> bool + decreases source, +{ + id < regexes.len() && dsl::regex_scoped(source, head) && match source { + RegexView::Empty => regexes[id as int] is Empty, + RegexView::All => regexes[id as int] is All, + RegexView::Epsilon => regexes[id as int] is Epsilon, + RegexView::Test(test) => match regexes[id as int] { + FlatRegex::Test(test_id) => test_represents::(tests, test_id as nat, test, head), + _ => false, + }, + RegexView::Concat(children) | RegexView::Union(children) | RegexView::Intersect(children) => { + let ids = regex_operands(regexes[id as int]); + ((source is Concat && regexes[id as int] is Concat) + || (source is Union && regexes[id as int] is Union) + || (source is Intersect && regexes[id as int] is Intersect)) + && children.len() == ids.len() && flat::references_before(ids, id) + && forall|i: int| #![trigger ids[i]] 0 <= i < children.len() ==> + regex_represents::(tests, regexes, ids[i] as nat, children[i], head) + }, + RegexView::Star(child) | RegexView::Not(child) => + ((source is Star && regexes[id as int] is Star) || (source is Not && regexes[id as int] is Complement)) + && match regexes[id as int] { + FlatRegex::Star(child_id) | FlatRegex::Complement(child_id) => child_id < id + && regex_represents::(tests, regexes, child_id as nat, *child, head), + _ => false, + }, + } +} + +pub open spec fn flattened(rule: Rule, flat_rule: FlatRule) -> bool { + flat_rule.mode == rule.mode && flat::structural_wf(flat_rule.source) + && dsl::head_scoped(rule.head@) && head_represents::(flat_rule.source.head@, rule.head@) + && regex_represents::(flat_rule.source.tests@, flat_rule.source.regexes@, + flat_rule.source.root as nat, rule.tail@, rule.head@) + && forall|i: int| 0 <= i < flat_rule.source.tests@.len() + ==> flat_test_within(#[trigger] flat_rule.source.tests@[i], rule.tail@) +} + +pub open spec fn test_views(children: Seq>) -> Seq> { + children.map(|i: int, child: TestExpr| child@) +} +pub open spec fn regex_views(children: Seq>) -> Seq> { + children.map(|i: int, child: RegexExpr| child@) +} + +pub open spec fn result_stacks(tests: Seq>, regexes: Seq, + test_ids: Seq, regex_ids: Seq, test_sources: Seq>, regex_sources: Seq>, + head: SourceHead) -> bool +{ + test_ids.len() == test_sources.len() && regex_ids.len() == regex_sources.len() + && (forall|i: int| 0 <= i < test_ids.len() ==> + #[trigger] test_represents::(tests, test_ids[i] as nat, test_sources[i], head)) + && (forall|i: int| 0 <= i < regex_ids.len() ==> + #[trigger] regex_represents::(tests, regexes, regex_ids[i] as nat, regex_sources[i], head)) +} + +/// Pending source visits inherit scope; finish frames retain that same source. +#[verifier::opaque] +pub(crate) open spec fn work_scoped(work: Seq>, head: SourceHead) -> bool { + forall|i: int| 0 <= i < work.len() ==> match #[trigger] work[i] { + Work::Regex(source) | Work::FinishRegex(source, _) => dsl::regex_scoped(source@, head), + Work::Test(source) | Work::FinishTest(source, _) => dsl::test_scoped(source@, head), + } +} + +pub(crate) proof fn lemma_work_scoped_push<'a, E: Event>(work: Seq>, + task: Work<'a, E>, head: SourceHead) + requires work_scoped::(work, head), match task { + Work::Regex(source) | Work::FinishRegex(source, _) => dsl::regex_scoped(source@, head), + Work::Test(source) | Work::FinishTest(source, _) => dsl::test_scoped(source@, head), + }, + ensures work_scoped::(work.push(task), head), +{ + reveal(work_scoped); + assert forall|i: int| 0 <= i < work.push(task).len() implies match #[trigger] work.push(task)[i] { + Work::Regex(source) | Work::FinishRegex(source, _) => dsl::regex_scoped(source@, head), + Work::Test(source) | Work::FinishTest(source, _) => dsl::test_scoped(source@, head), + } by { + if i < work.len() { assert(work.push(task)[i] == work[i]); } + else { assert(i == work.len()); } + } +} + +pub(crate) proof fn lemma_work_scoped_pop(work: Seq>, head: SourceHead) + requires work_scoped::(work, head), work.len() > 0, + ensures work_scoped::(work.drop_last(), head), match work.last() { + Work::Regex(source) | Work::FinishRegex(source, _) => dsl::regex_scoped(source@, head), + Work::Test(source) | Work::FinishTest(source, _) => dsl::test_scoped(source@, head), + }, +{ + reveal(work_scoped); + assert forall|i: int| 0 <= i < work.drop_last().len() implies match #[trigger] work.drop_last()[i] { + Work::Regex(source) | Work::FinishRegex(source, _) => dsl::regex_scoped(source@, head), + Work::Test(source) | Work::FinishTest(source, _) => dsl::test_scoped(source@, head), + } by { assert(work.drop_last()[i] == work[i]); } +} + +// ----- the constants a flattening may intern are the rule's (the analyzer's `known`) ----- + +/// `source` compares each coordinate only against constants `tail` does (a sub-term of `tail`). +pub open spec fn regex_constants_within(source: RegexView, tail: RegexView) -> bool { + forall|k: int| (#[trigger] crate::spec::questions::regex_constant_at(source, k)) + .subset_of(crate::spec::questions::regex_constant_at(tail, k)) +} + +pub open spec fn test_constants_within(source: TestView, tail: RegexView) -> bool { + forall|k: int| (#[trigger] crate::spec::questions::test_constant_at(source, k)) + .subset_of(crate::spec::questions::regex_constant_at(tail, k)) +} + +/// A flat atom's constant is one `tail` compares its field against. +pub open spec fn flat_test_within(test: FlatTest, tail: RegexView) -> bool { + match test { + FlatTest::Atom { field, term: FlatTerm::Constant(value), .. } => + crate::spec::questions::regex_constant_at(tail, field.0 as int).contains(value), + _ => true, + } +} + +/// Every pending source is a sub-term of the tail (its constants are among the tail's). +#[verifier::opaque] +pub(crate) open spec fn work_within(work: Seq>, tail: SourceRegex) -> bool { + forall|i: int| 0 <= i < work.len() ==> match #[trigger] work[i] { + Work::Regex(source) | Work::FinishRegex(source, _) => regex_constants_within(source@, tail), + Work::Test(source) | Work::FinishTest(source, _) => test_constants_within(source@, tail), + } +} + +pub(crate) proof fn lemma_work_within_push<'a, E: Event>(work: Seq>, + task: Work<'a, E>, tail: SourceRegex) + requires work_within::(work, tail), match task { + Work::Regex(source) | Work::FinishRegex(source, _) => regex_constants_within(source@, tail), + Work::Test(source) | Work::FinishTest(source, _) => test_constants_within(source@, tail), + }, + ensures work_within::(work.push(task), tail), +{ + reveal(work_within); + assert forall|i: int| 0 <= i < work.push(task).len() implies match #[trigger] work.push(task)[i] { + Work::Regex(source) | Work::FinishRegex(source, _) => regex_constants_within(source@, tail), + Work::Test(source) | Work::FinishTest(source, _) => test_constants_within(source@, tail), + } by { + if i < work.len() { assert(work.push(task)[i] == work[i]); } + else { assert(i == work.len()); } + } +} + +pub(crate) proof fn lemma_work_within_pop(work: Seq>, tail: SourceRegex) + requires work_within::(work, tail), work.len() > 0, + ensures work_within::(work.drop_last(), tail), match work.last() { + Work::Regex(source) | Work::FinishRegex(source, _) => regex_constants_within(source@, tail), + Work::Test(source) | Work::FinishTest(source, _) => test_constants_within(source@, tail), + }, +{ + reveal(work_within); + assert forall|i: int| 0 <= i < work.drop_last().len() implies match #[trigger] work.drop_last()[i] { + Work::Regex(source) | Work::FinishRegex(source, _) => regex_constants_within(source@, tail), + Work::Test(source) | Work::FinishTest(source, _) => test_constants_within(source@, tail), + } by { assert(work.drop_last()[i] == work[i]); } +} + +/// A member of a forest contributes to the forest's constants. +pub proof fn lemma_regex_forest_member(regexes: Seq>, i: int, k: int) + requires 0 <= i < regexes.len(), + ensures crate::spec::questions::regex_constant_at(regexes[i], k) + .subset_of(crate::spec::questions::regex_constant_forest(regexes, k)), + decreases regexes.len(), +{ + if i < regexes.len() - 1 { + lemma_regex_forest_member(regexes.drop_last(), i, k); + assert(regexes.drop_last()[i] == regexes[i]); + } +} + +pub proof fn lemma_test_forest_member(tests: Seq>, i: int, k: int) + requires 0 <= i < tests.len(), + ensures crate::spec::questions::test_constant_at(tests[i], k) + .subset_of(crate::spec::questions::test_constant_forest(tests, k)), + decreases tests.len(), +{ + if i < tests.len() - 1 { + lemma_test_forest_member(tests.drop_last(), i, k); + assert(tests.drop_last()[i] == tests[i]); + } +} + +/// Children of a composite are sub-terms of it. +pub proof fn lemma_regex_children_within(children: Seq>, source: RegexView, tail: RegexView) + requires regex_constants_within(source, tail), + source == RegexView::Concat(children) || source == RegexView::Union(children) || source == RegexView::Intersect(children), + ensures forall|i: int| 0 <= i < children.len() ==> regex_constants_within(#[trigger] children[i], tail), +{ + assert forall|i: int| 0 <= i < children.len() implies regex_constants_within(#[trigger] children[i], tail) by { + assert forall|k: int| (#[trigger] crate::spec::questions::regex_constant_at(children[i], k)) + .subset_of(crate::spec::questions::regex_constant_at(tail, k)) by { + lemma_regex_forest_member(children, i, k); + assert(crate::spec::questions::regex_constant_at(source, k) + == crate::spec::questions::regex_constant_forest(children, k)); + } + } +} + +pub proof fn lemma_test_children_within(children: Seq>, source: TestView, tail: RegexView) + requires test_constants_within(source, tail), + source == TestView::And(children) || source == TestView::Or(children), + ensures forall|i: int| 0 <= i < children.len() ==> test_constants_within(#[trigger] children[i], tail), +{ + assert forall|i: int| 0 <= i < children.len() implies test_constants_within(#[trigger] children[i], tail) by { + assert forall|k: int| (#[trigger] crate::spec::questions::test_constant_at(children[i], k)) + .subset_of(crate::spec::questions::regex_constant_at(tail, k)) by { + lemma_test_forest_member(children, i, k); + assert(crate::spec::questions::test_constant_at(source, k) + == crate::spec::questions::test_constant_forest(children, k)); + } + } +} + +/// Every constant a flattening can intern is a constant of the rule at that coordinate (the +/// analyzer specification's `known` after `add_rule` is `known_with(.., rule_constants(rule))`). +pub proof fn lemma_flattened_constants(rule: Rule, flat: FlatRule) + requires flattened::(rule, flat), + ensures forall|f: Component, v: E::Component| #[trigger] crate::verify::encoding::source_constant(flat.source, f, v) + ==> f.0 < rule.head@.len() && crate::spec::questions::rule_constants(rule@)[f.0 as int].contains(v), +{ + assert forall|f: Component, v: E::Component| #[trigger] crate::verify::encoding::source_constant(flat.source, f, v) + implies f.0 < rule.head@.len() && crate::spec::questions::rule_constants(rule@)[f.0 as int].contains(v) by { + let source = flat.source; + if exists|i: int| 0 <= i < source.head@.len() && crate::verify::encoding::field_at(i) == f + && (#[trigger] source.head@[i]) == FlatHead::Constant(v) { + let i = choose|i: int| 0 <= i < source.head@.len() && crate::verify::encoding::field_at(i) == f + && (#[trigger] source.head@[i]) == FlatHead::Constant(v); + assert(head_slot_represents(source.head@[i], rule.head@[i])); + assert(rule.head@[i] == PatternView::Constant(v)); + assert(crate::spec::questions::head_constants(rule.head@)[i].contains(v)); + assert(f.0 as int == i); + } else { + let i = choose|i: int| 0 <= i < source.tests@.len() && match #[trigger] source.tests@[i] { + FlatTest::Atom { field: f2, term: FlatTerm::Constant(v2), .. } => f2 == f && v2 == v, + _ => false, + }; + assert(flat_test_within(source.tests@[i], rule.tail@)); + assert(flat::test_wf(source.head@, source.tests@[i], i as nat)); + assert(f.0 < source.head@.len()); + assert(crate::spec::questions::regex_constants(rule.tail@, rule.head@.len())[f.0 as int].contains(v)); + } + } +} + +/// Erased continuation interpreter: visits contribute original views; finish frames check order. +/// It neither evaluates policies nor reconstructs any executable source tree. +#[verifier::opaque] +pub(crate) open spec fn run_work(work: Seq>, tests: Seq>, regexes: Seq>) + -> Option<(Seq>, Seq>)> + decreases work.len(), +{ + if work.len() == 0 { Some((tests, regexes)) } + else { + let rest = work.drop_last(); + match work.last() { + Work::Regex(source) => run_work::(rest, tests, regexes.push(source@)), + Work::Test(source) => run_work::(rest, tests.push(source@), regexes), + Work::FinishTest(source, start) => match source@ { + TestView::And(children) | TestView::Or(children) => + if start <= tests.len() && tests.subrange(start as int, tests.len() as int) == children { + run_work::(rest, tests.take(start as int).push(source@), regexes) + } else { None }, + _ => None, + }, + Work::FinishRegex(source, start) => match source@ { + RegexView::Test(child) => + if tests.len() == start + 1 && tests[start as int] == child { + run_work::(rest, tests.take(start as int), regexes.push(source@)) + } else { None }, + RegexView::Star(child) | RegexView::Not(child) => + if regexes.len() == start + 1 && regexes[start as int] == *child { + run_work::(rest, tests, regexes.take(start as int).push(source@)) + } else { None }, + RegexView::Concat(children) | RegexView::Union(children) | RegexView::Intersect(children) => + if start <= regexes.len() && regexes.subrange(start as int, regexes.len() as int) == children { + run_work::(rest, tests, regexes.take(start as int).push(source@)) + } else { None }, + _ => None, + }, + } + } +} + +/// A successful continuation fixes the next frame's operands and successor stacks. +pub(crate) proof fn lemma_run_work_step(work: Seq>, + tests: Seq>, regexes: Seq>) + requires work.len() > 0, run_work::(work, tests, regexes) is Some, + ensures match work.last() { + Work::Regex(source) => run_work::(work.drop_last(), tests, regexes.push(source@)) + == run_work::(work, tests, regexes), + Work::Test(source) => run_work::(work.drop_last(), tests.push(source@), regexes) + == run_work::(work, tests, regexes), + Work::FinishTest(source, start) => match source@ { + TestView::And(children) | TestView::Or(children) => start <= tests.len() + && tests.subrange(start as int, tests.len() as int) == children + && run_work::(work.drop_last(), tests.take(start as int).push(source@), regexes) + == run_work::(work, tests, regexes), + _ => false, + }, + Work::FinishRegex(source, start) => match source@ { + RegexView::Test(child) => tests.len() == start + 1 && tests[start as int] == child + && run_work::(work.drop_last(), tests.take(start as int), regexes.push(source@)) + == run_work::(work, tests, regexes), + RegexView::Star(child) | RegexView::Not(child) => regexes.len() == start + 1 + && regexes[start as int] == *child + && run_work::(work.drop_last(), tests, regexes.take(start as int).push(source@)) + == run_work::(work, tests, regexes), + RegexView::Concat(children) | RegexView::Union(children) | RegexView::Intersect(children) => + start <= regexes.len() + && regexes.subrange(start as int, regexes.len() as int) == children + && run_work::(work.drop_last(), tests, regexes.take(start as int).push(source@)) + == run_work::(work, tests, regexes), + _ => false, + }, + }, +{ + reveal_with_fuel(run_work, 1); +} + +pub(crate) proof fn lemma_finish_test<'a, E: Event>(work: Seq>, source: &'a TestExpr, start: usize, + tests: Seq>, regexes: Seq>, children: Seq>, head: SourceHead, + tail: SourceRegex) + requires start == tests.len(), source@ == TestView::And(children) || source@ == TestView::Or(children), + ensures run_work::(work.push(Work::FinishTest(source, start)), tests + children, regexes) + == run_work::(work, tests.push(source@), regexes), + work_scoped::(work, head) && dsl::test_scoped(source@, head) ==> + work_scoped::(work.push(Work::FinishTest(source, start)), head) + && (forall|i: int| 0 <= i < children.len() ==> dsl::test_scoped(#[trigger] children[i], head)), + work_within::(work, tail) && test_constants_within(source@, tail) ==> + work_within::(work.push(Work::FinishTest(source, start)), tail) + && (forall|i: int| 0 <= i < children.len() ==> test_constants_within(#[trigger] children[i], tail)), +{ + hide(dsl::test_scoped); + if work_scoped::(work, head) && dsl::test_scoped(source@, head) { + assert(forall|i: int| 0 <= i < children.len() ==> dsl::test_scoped(#[trigger] children[i], head)) by { + reveal_with_fuel(dsl::test_scoped, 1); + } + lemma_work_scoped_push::(work, Work::FinishTest(source, start), head); + } + if work_within::(work, tail) && test_constants_within(source@, tail) { + lemma_test_children_within(children, source@, tail); + lemma_work_within_push::(work, Work::FinishTest(source, start), tail); + } + let operands = tests + children; + assert(operands.subrange(start as int, operands.len() as int) =~= children); + assert(operands.take(start as int) =~= tests); + assert(work.push(Work::FinishTest(source, start)).drop_last() =~= work); + reveal_with_fuel(run_work, 2); +} + +pub(crate) proof fn lemma_visit_test_regex<'a, E: Event>(work: Seq>, source: &'a RegexExpr, child: &'a TestExpr, + start: usize, tests: Seq>, regexes: Seq>, head: SourceHead, tail: SourceRegex) + requires start == tests.len(), source@ == RegexView::Test(child@), + ensures run_work::(work.push(Work::FinishRegex(source, start)).push(Work::Test(child)), tests, regexes) + == run_work::(work, tests, regexes.push(source@)), + work_scoped::(work, head) && dsl::regex_scoped(source@, head) ==> + work_scoped::(work.push(Work::FinishRegex(source, start)).push(Work::Test(child)), head), + work_within::(work, tail) && regex_constants_within(source@, tail) ==> + work_within::(work.push(Work::FinishRegex(source, start)).push(Work::Test(child)), tail), +{ + if work_scoped::(work, head) && dsl::regex_scoped(source@, head) { + reveal_with_fuel(dsl::regex_scoped, 1); + lemma_work_scoped_push::(work, Work::FinishRegex(source, start), head); + lemma_work_scoped_push::(work.push(Work::FinishRegex(source, start)), Work::Test(child), head); + } + if work_within::(work, tail) && regex_constants_within(source@, tail) { + assert forall|k: int| (#[trigger] crate::spec::questions::test_constant_at(child@, k)) + .subset_of(crate::spec::questions::regex_constant_at(tail, k)) by { + assert(crate::spec::questions::regex_constant_at(source@, k) == crate::spec::questions::test_constant_at(child@, k)); + } + lemma_work_within_push::(work, Work::FinishRegex(source, start), tail); + lemma_work_within_push::(work.push(Work::FinishRegex(source, start)), Work::Test(child), tail); + } + let finish = work.push(Work::FinishRegex(source, start)); + let program = finish.push(Work::Test(child)); + assert(program.drop_last() =~= finish); + assert(finish.drop_last() =~= work); + assert(tests.push(child@).take(start as int) =~= tests); + reveal_with_fuel(run_work, 3); +} + +pub(crate) proof fn lemma_visit_unary_regex<'a, E: Event>(work: Seq>, source: &'a RegexExpr, child: &'a RegexExpr, + start: usize, tests: Seq>, regexes: Seq>, head: SourceHead, tail: SourceRegex) + requires start == regexes.len(), source@ == RegexView::Star(alloc::boxed::Box::new(child@)) + || source@ == RegexView::Not(alloc::boxed::Box::new(child@)), + ensures run_work::(work.push(Work::FinishRegex(source, start)).push(Work::Regex(child)), tests, regexes) + == run_work::(work, tests, regexes.push(source@)), + work_scoped::(work, head) && dsl::regex_scoped(source@, head) ==> + work_scoped::(work.push(Work::FinishRegex(source, start)).push(Work::Regex(child)), head), + work_within::(work, tail) && regex_constants_within(source@, tail) ==> + work_within::(work.push(Work::FinishRegex(source, start)).push(Work::Regex(child)), tail), +{ + if work_scoped::(work, head) && dsl::regex_scoped(source@, head) { + reveal_with_fuel(dsl::regex_scoped, 1); + lemma_work_scoped_push::(work, Work::FinishRegex(source, start), head); + lemma_work_scoped_push::(work.push(Work::FinishRegex(source, start)), Work::Regex(child), head); + } + if work_within::(work, tail) && regex_constants_within(source@, tail) { + assert forall|k: int| (#[trigger] crate::spec::questions::regex_constant_at(child@, k)) + .subset_of(crate::spec::questions::regex_constant_at(tail, k)) by { + assert(crate::spec::questions::regex_constant_at(source@, k) == crate::spec::questions::regex_constant_at(child@, k)); + } + lemma_work_within_push::(work, Work::FinishRegex(source, start), tail); + lemma_work_within_push::(work.push(Work::FinishRegex(source, start)), Work::Regex(child), tail); + } + let finish = work.push(Work::FinishRegex(source, start)); + let program = finish.push(Work::Regex(child)); + assert(program.drop_last() =~= finish); + assert(finish.drop_last() =~= work); + assert(regexes.push(child@).take(start as int) =~= regexes); + reveal_with_fuel(run_work, 3); +} + +pub(crate) proof fn lemma_finish_many_regex<'a, E: Event>(work: Seq>, source: &'a RegexExpr, start: usize, + tests: Seq>, regexes: Seq>, children: Seq>, head: SourceHead, + tail: SourceRegex) + requires start == regexes.len(), source@ == RegexView::Concat(children) + || source@ == RegexView::Union(children) || source@ == RegexView::Intersect(children), + ensures run_work::(work.push(Work::FinishRegex(source, start)), tests, regexes + children) + == run_work::(work, tests, regexes.push(source@)), + work_scoped::(work, head) && dsl::regex_scoped(source@, head) ==> + work_scoped::(work.push(Work::FinishRegex(source, start)), head) + && (forall|i: int| 0 <= i < children.len() ==> dsl::regex_scoped(#[trigger] children[i], head)), + work_within::(work, tail) && regex_constants_within(source@, tail) ==> + work_within::(work.push(Work::FinishRegex(source, start)), tail) + && (forall|i: int| 0 <= i < children.len() ==> regex_constants_within(#[trigger] children[i], tail)), +{ + hide(dsl::regex_scoped); + if work_scoped::(work, head) && dsl::regex_scoped(source@, head) { + assert(forall|i: int| 0 <= i < children.len() ==> dsl::regex_scoped(#[trigger] children[i], head)) by { + reveal_with_fuel(dsl::regex_scoped, 1); + } + lemma_work_scoped_push::(work, Work::FinishRegex(source, start), head); + } + if work_within::(work, tail) && regex_constants_within(source@, tail) { + lemma_regex_children_within(children, source@, tail); + lemma_work_within_push::(work, Work::FinishRegex(source, start), tail); + } + let operands = regexes + children; + assert(operands.subrange(start as int, operands.len() as int) =~= children); + assert(operands.take(start as int) =~= regexes); + assert(work.push(Work::FinishRegex(source, start)).drop_last() =~= work); + reveal_with_fuel(run_work, 2); +} + +pub open spec fn test_cost(test: SourceTest) -> nat + decreases test, +{ + match test { + TestView::And(children) | TestView::Or(children) => 2 + test_forest_cost::(children), + _ => 1, + } +} +pub open spec fn test_forest_cost(tests: Seq>) -> nat + decreases tests, +{ + if tests.len() == 0 { 0 } else { test_forest_cost::(tests.drop_last()) + test_cost::(tests.last()) } +} +pub open spec fn regex_cost(regex: SourceRegex) -> nat + decreases regex, +{ + match regex { + RegexView::Test(test) => 2 + test_cost::(test), + RegexView::Star(child) | RegexView::Not(child) => 2 + regex_cost::(*child), + RegexView::Concat(children) | RegexView::Union(children) | RegexView::Intersect(children) => 2 + regex_forest_cost::(children), + _ => 1, + } +} +pub open spec fn regex_forest_cost(regexes: Seq>) -> nat + decreases regexes, +{ + if regexes.len() == 0 { 0 } else { regex_forest_cost::(regexes.drop_last()) + regex_cost::(regexes.last()) } +} +pub(crate) open spec fn work_cost(work: Seq>) -> nat + decreases work.len(), +{ + if work.len() == 0 { 0 } + else { work_cost::(work.drop_last()) + match work.last() { + Work::Regex(source) => regex_cost::(source@), + Work::Test(source) => test_cost::(source@), + _ => 1, + } } +} + +pub(crate) proof fn lemma_work_cost_push<'a, E: Event>(work: Seq>, task: Work<'a, E>) + ensures work_cost::(work.push(task)) == work_cost::(work) + match task { + Work::Regex(source) => regex_cost::(source@), + Work::Test(source) => test_cost::(source@), + _ => 1, + }, +{ + assert(work.push(task).drop_last() =~= work); + assert(work.push(task).last() == task); + reveal_with_fuel(work_cost, 1); +} + + +pub proof fn lemma_test_forest_cost_append(left: Seq>, right: Seq>) + ensures test_forest_cost::(left + right) == test_forest_cost::(left) + test_forest_cost::(right), + decreases right.len(), +{ + if right.len() > 0 { + lemma_test_forest_cost_append::(left, right.drop_last()); + assert((left + right).drop_last() =~= left + right.drop_last()); + } else { assert(left + right =~= left); } +} + +pub proof fn lemma_regex_forest_cost_append(left: Seq>, right: Seq>) + ensures regex_forest_cost::(left + right) == regex_forest_cost::(left) + regex_forest_cost::(right), + decreases right.len(), +{ + if right.len() > 0 { + lemma_regex_forest_cost_append::(left, right.drop_last()); + assert((left + right).drop_last() =~= left + right.drop_last()); + } else { assert(left + right =~= left); } +} + +pub proof fn lemma_test_extension(tests: Seq>, more: Seq>, + id: nat, source: SourceTest, head: SourceHead) + requires more.len() >= tests.len(), more.take(tests.len() as int) == tests, + test_represents::(tests, id, source, head), + ensures test_represents::(more, id, source, head), + decreases source, +{ + reveal_with_fuel(test_represents, 2); + assert(more[id as int] == tests[id as int]); + match source { + TestView::And(children) | TestView::Or(children) => { + let ids = test_operands(tests[id as int]); + assert(ids.len() == children.len()); + assert(flat::references_before(ids, id)); + assert forall|i: int| 0 <= i < children.len() implies + test_represents::(tests, ids[i] as nat, children[i], head) by {} + assert forall|i: int| 0 <= i < children.len() implies + test_represents::(more, ids[i] as nat, children[i], head) by { + lemma_test_extension::(tests, more, ids[i] as nat, children[i], head); + } + }, + _ => {}, + } +} + +pub proof fn lemma_regex_extension(tests: Seq>, more_tests: Seq>, + regexes: Seq, more_regexes: Seq, id: nat, source: SourceRegex, head: SourceHead) + requires more_tests.len() >= tests.len(), more_tests.take(tests.len() as int) == tests, + more_regexes.len() >= regexes.len(), more_regexes.take(regexes.len() as int) == regexes, + regex_represents::(tests, regexes, id, source, head), + ensures regex_represents::(more_tests, more_regexes, id, source, head), + decreases source, +{ + reveal_with_fuel(regex_represents, 2); + assert(more_regexes[id as int] == regexes[id as int]); + match source { + RegexView::Test(test) => match regexes[id as int] { + FlatRegex::Test(test_id) => lemma_test_extension::(tests, more_tests, test_id as nat, test, head), + _ => {}, + }, + RegexView::Concat(children) | RegexView::Union(children) | RegexView::Intersect(children) => { + let ids = regex_operands(regexes[id as int]); + assert forall|i: int| 0 <= i < children.len() implies + regex_represents::(more_tests, more_regexes, ids[i] as nat, children[i], head) by { + lemma_regex_extension::(tests, more_tests, regexes, more_regexes, ids[i] as nat, children[i], head); + } + }, + RegexView::Star(child) | RegexView::Not(child) => match regexes[id as int] { + FlatRegex::Star(child_id) | FlatRegex::Complement(child_id) => + lemma_regex_extension::(tests, more_tests, regexes, more_regexes, child_id as nat, *child, head), + _ => {}, + }, + _ => {}, + } +} + +pub proof fn lemma_stack_extension(tests: Seq>, more_tests: Seq>, + regexes: Seq, more_regexes: Seq, test_ids: Seq, regex_ids: Seq, + test_sources: Seq>, regex_sources: Seq>, head: SourceHead) + requires more_tests.len() >= tests.len(), more_tests.take(tests.len() as int) == tests, + more_regexes.len() >= regexes.len(), more_regexes.take(regexes.len() as int) == regexes, + result_stacks::(tests, regexes, test_ids, regex_ids, test_sources, regex_sources, head), + ensures result_stacks::(more_tests, more_regexes, test_ids, regex_ids, test_sources, regex_sources, head), +{ + assert forall|i: int| 0 <= i < test_ids.len() implies + test_represents::(more_tests, test_ids[i] as nat, test_sources[i], head) by { + lemma_test_extension::(tests, more_tests, test_ids[i] as nat, test_sources[i], head); + } + assert forall|i: int| 0 <= i < regex_ids.len() implies + regex_represents::(more_tests, more_regexes, regex_ids[i] as nat, regex_sources[i], head) by { + lemma_regex_extension::(tests, more_tests, regexes, more_regexes, regex_ids[i] as nat, regex_sources[i], head); + } +} + +pub proof fn lemma_head_semantics(head: Seq>, source: SourceHead, candidate: SourceEvent) + requires head_represents::(head, source), + ensures flat::head_matches(head, candidate, component_equality::()) + == dsl::head_matches(source, candidate), +{ + if head.len() == candidate.len() { + assert forall|i: int| 0 <= i < head.len() implies + (match head[i] { + FlatHead::Constant(expected) => component_equality::()(Component(i as u8), candidate[i], expected), + _ => true, + }) == dsl::head_pattern_matches(source[i], candidate[i]) by { + assert(head_slot_represents(head[i], source[i])); + match source[i] { PatternView::Constant(_) => {}, PatternView::Variable(_) => {} } + } + } +} + +pub proof fn lemma_test_semantics(tests: Seq>, id: nat, source: SourceTest, + head: SourceHead, candidate: SourceEvent, event: SourceEvent) + requires test_represents::(tests, id, source, head), + candidate.len() == head.len(), event.len() == candidate.len(), + ensures flat::test_sem(tests, id, candidate, event, component_equality::()) + == dsl::test_sem(source, head, candidate, event), + decreases source, +{ + reveal_with_fuel(flat::test_sem, 2); + reveal_with_fuel(dsl::test_sem, 2); + lemma_test_operands(tests[id as int]); + reveal_with_fuel(test_represents, 2); + match source { + TestView::Atom { comparison, pattern } => { + match tests[id as int] { + FlatTest::Atom { field, term, positive } => { + match pattern.pattern { + PatternView::Constant(_) => {}, + PatternView::Variable(_) => { + match head[pattern.component as int] { + PatternView::Constant(_) => {}, PatternView::Variable(_) => {}, + } + }, + } + }, + _ => {}, + } + assert(flat::test_sem(tests, id, candidate, event, component_equality::()) + == dsl::test_sem(source, head, candidate, event)); + }, + TestView::And(children) => { + let ids = test_operands(tests[id as int]); + if dsl::test_sem(source, head, candidate, event) { + assert forall|i: int| 0 <= i < ids.len() implies + flat::test_sem(tests, ids[i] as nat, candidate, event, component_equality::()) by { + assert(dsl::test_sem(children[i], head, candidate, event)); + lemma_test_semantics::(tests, ids[i] as nat, children[i], head, candidate, event); + } + assert(flat::test_sem(tests, id, candidate, event, component_equality::())); + } + if flat::test_sem(tests, id, candidate, event, component_equality::()) { + assert forall|i: int| 0 <= i < children.len() implies dsl::test_sem(children[i], head, candidate, event) by { + assert(flat::test_sem(tests, ids[i] as nat, candidate, event, component_equality::())); + lemma_test_semantics::(tests, ids[i] as nat, children[i], head, candidate, event); + } + assert(dsl::test_sem(source, head, candidate, event)); + } + }, + TestView::Or(children) => { + let ids = test_operands(tests[id as int]); + if dsl::test_sem(source, head, candidate, event) { + let i = choose|i: int| 0 <= i < children.len() && dsl::test_sem(children[i], head, candidate, event); + lemma_test_semantics::(tests, ids[i] as nat, children[i], head, candidate, event); + assert(flat::test_sem(tests, ids[i] as nat, candidate, event, component_equality::())); + assert(flat::test_sem(tests, id, candidate, event, component_equality::())); + } + if flat::test_sem(tests, id, candidate, event, component_equality::()) { + let i = choose|i: int| 0 <= i < ids.len() + && flat::test_sem(tests, ids[i] as nat, candidate, event, component_equality::()); + lemma_test_semantics::(tests, ids[i] as nat, children[i], head, candidate, event); + assert(dsl::test_sem(children[i], head, candidate, event)); + assert(dsl::test_sem(source, head, candidate, event)); + } + }, + _ => {}, + } +} + +/// Every event in a partition retains the original word's coordinate count. +pub proof fn lemma_partition_arity(parts: Seq>>, arity: nat) + requires forall|i: int| 0 <= i < parts.flatten().len() ==> parts.flatten()[i].len() == arity, + ensures forall|i: int, j: int| 0 <= i < parts.len() && 0 <= j < parts[i].len() + ==> parts[i][j].len() == arity, + decreases parts.len(), +{ + if parts.len() > 0 { + assert(parts =~= parts.drop_last().push(parts.last())); + parts.drop_last().lemma_flatten_push(parts.last()); + let prefix = parts.drop_last().flatten(); + assert forall|j: int| 0 <= j < prefix.len() implies prefix[j].len() == arity by { + assert(prefix[j] == parts.flatten()[j]); + } + lemma_partition_arity(parts.drop_last(), arity); + assert forall|i: int, j: int| 0 <= i < parts.len() && 0 <= j < parts[i].len() + implies parts[i][j].len() == arity by { + if i < parts.len() - 1 { assert(parts[i] == parts.drop_last()[i]); } + else { + assert(parts[i] == parts.last()); + assert(parts[i][j] == parts.flatten()[prefix.len() as int + j]); + } + } + } +} + +pub proof fn lemma_regex_semantics(tests: Seq>, regexes: Seq, id: nat, + source: SourceRegex, head: SourceHead, candidate: SourceEvent, word: Seq>) + requires regex_represents::(tests, regexes, id, source, head), + candidate.len() == head.len(), + forall|i: int| 0 <= i < word.len() ==> word[i].len() == candidate.len(), + ensures flat::flat_lang(tests, regexes, id, candidate, word, component_equality::()) + == dsl::lang(source, head, candidate, word), + decreases source, +{ + reveal_with_fuel(flat::flat_lang, 2); + reveal_with_fuel(dsl::lang, 2); + lemma_regex_operands(regexes[id as int]); + reveal_with_fuel(regex_represents, 2); + match source { + RegexView::Test(test) => match regexes[id as int] { + FlatRegex::Test(test_id) => { if word.len() == 1 { + lemma_test_semantics::(tests, test_id as nat, test, head, candidate, word[0]); + } }, + _ => {}, + }, + RegexView::Union(children) => { + let ids = regex_operands(regexes[id as int]); + if dsl::lang(source, head, candidate, word) { + let i = choose|i: int| 0 <= i < children.len() && dsl::lang(children[i], head, candidate, word); + lemma_regex_semantics::(tests, regexes, ids[i] as nat, children[i], head, candidate, word); + assert(flat::flat_lang(tests, regexes, ids[i] as nat, candidate, word, component_equality::())); + assert(flat::flat_lang(tests, regexes, id, candidate, word, component_equality::())); + } + if flat::flat_lang(tests, regexes, id, candidate, word, component_equality::()) { + let i = choose|i: int| 0 <= i < ids.len() + && flat::flat_lang(tests, regexes, ids[i] as nat, candidate, word, component_equality::()); + lemma_regex_semantics::(tests, regexes, ids[i] as nat, children[i], head, candidate, word); + assert(dsl::lang(children[i], head, candidate, word)); + assert(dsl::lang(source, head, candidate, word)); + } + }, + RegexView::Intersect(children) => { + let ids = regex_operands(regexes[id as int]); + if dsl::lang(source, head, candidate, word) { + assert forall|i: int| 0 <= i < ids.len() implies + flat::flat_lang(tests, regexes, ids[i] as nat, candidate, word, component_equality::()) by { + assert(dsl::lang(children[i], head, candidate, word)); + lemma_regex_semantics::(tests, regexes, ids[i] as nat, children[i], head, candidate, word); + } + assert(flat::flat_lang(tests, regexes, id, candidate, word, component_equality::())); + } + if flat::flat_lang(tests, regexes, id, candidate, word, component_equality::()) { + assert forall|i: int| 0 <= i < children.len() implies dsl::lang(children[i], head, candidate, word) by { + assert(flat::flat_lang(tests, regexes, ids[i] as nat, candidate, word, component_equality::())); + lemma_regex_semantics::(tests, regexes, ids[i] as nat, children[i], head, candidate, word); + } + assert(dsl::lang(source, head, candidate, word)); + } + }, + RegexView::Not(child) => match regexes[id as int] { + FlatRegex::Complement(child_id) => lemma_regex_semantics::(tests, regexes, child_id as nat, *child, head, candidate, word), + _ => {}, + }, + RegexView::Concat(children) => { + let ids = regex_operands(regexes[id as int]); + if dsl::lang(source, head, candidate, word) { + let parts = choose|parts: Seq>>| parts.len() == children.len() + && word == parts.flatten() && forall|i: int| 0 <= i < children.len() ==> dsl::lang(children[i], head, candidate, parts[i]); + lemma_partition_arity(parts, candidate.len()); + assert forall|i: int| 0 <= i < children.len() implies + flat::flat_lang(tests, regexes, ids[i] as nat, candidate, parts[i], component_equality::()) by { + lemma_regex_semantics::(tests, regexes, ids[i] as nat, children[i], head, candidate, parts[i]); + } + assert(flat::flat_lang(tests, regexes, id, candidate, word, component_equality::())); + } + if flat::flat_lang(tests, regexes, id, candidate, word, component_equality::()) { + let parts = choose|parts: Seq>>| parts.len() == ids.len() + && word == parts.flatten() && forall|i: int| 0 <= i < ids.len() ==> + flat::flat_lang(tests, regexes, ids[i] as nat, candidate, parts[i], component_equality::()); + lemma_partition_arity(parts, candidate.len()); + assert forall|i: int| 0 <= i < children.len() implies dsl::lang(children[i], head, candidate, parts[i]) by { + lemma_regex_semantics::(tests, regexes, ids[i] as nat, children[i], head, candidate, parts[i]); + } + assert(dsl::lang(source, head, candidate, word)); + } + }, + RegexView::Star(child) => { + let child_id = match regexes[id as int] { FlatRegex::Star(child_id) => child_id, _ => arbitrary() }; + if dsl::lang(source, head, candidate, word) { + let parts = choose|parts: Seq>>| word == parts.flatten() + && forall|i: int| 0 <= i < parts.len() ==> dsl::lang(*child, head, candidate, parts[i]); + lemma_partition_arity(parts, candidate.len()); + assert forall|i: int| 0 <= i < parts.len() implies + flat::flat_lang(tests, regexes, child_id as nat, candidate, parts[i], component_equality::()) by { + lemma_regex_semantics::(tests, regexes, child_id as nat, *child, head, candidate, parts[i]); + } + assert(flat::flat_lang(tests, regexes, id, candidate, word, component_equality::())); + } + if flat::flat_lang(tests, regexes, id, candidate, word, component_equality::()) { + let parts = choose|parts: Seq>>| word == parts.flatten() + && forall|i: int| 0 <= i < parts.len() ==> + flat::flat_lang(tests, regexes, child_id as nat, candidate, parts[i], component_equality::()); + lemma_partition_arity(parts, candidate.len()); + assert forall|i: int| 0 <= i < parts.len() implies dsl::lang(*child, head, candidate, parts[i]) by { + lemma_regex_semantics::(tests, regexes, child_id as nat, *child, head, candidate, parts[i]); + } + assert(dsl::lang(source, head, candidate, word)); + } + }, + _ => {}, + } +} + +/// The structural result of the executable compiler implies both independent semantic equations. +pub proof fn flattening_preserves_semantics(rule: Rule, lowered: FlatRule, + candidate: SourceEvent, history: Seq>) + requires flattened::(rule, lowered), candidate.len() == rule.head@.len(), + forall|i: int| 0 <= i < history.len() ==> history[i].len() == candidate.len(), + ensures + flat::head_matches(lowered.source.head@, candidate, component_equality::()) + == dsl::head_matches(rule.head@, candidate), + flat::flat_lang(lowered.source.tests@, lowered.source.regexes@, lowered.source.root as nat, + candidate, history, component_equality::()) + == dsl::lang(rule.tail@, rule.head@, candidate, history), +{ + lemma_head_semantics::(lowered.source.head@, rule.head@, candidate); + lemma_regex_semantics::(lowered.source.tests@, lowered.source.regexes@, lowered.source.root as nat, + rule.tail@, rule.head@, candidate, history); +} + +/// A client of the executable body obtains the semantic bridge without a correctness precondition. +pub fn flattening_client(rule: &Rule, limits: &mut L, world: &mut ObservationWorld, + Ghost(candidate): Ghost>, Ghost(history): Ghost>>) + -> (result: Result, CompileError>) + requires candidate.len() == rule.head@.len(), + forall|i: int| 0 <= i < history.len() ==> history[i].len() == candidate.len(), + ensures crate::verify::history_specs::no_invariant_compile_failure(result), + dsl::head_scoped(rule.head@) && dsl::regex_scoped(rule.tail@, rule.head@) + ==> !(result matches Err(CompileError::VariableComponentConflict { .. })) + && !(result matches Err(CompileError::UnboundVariable { .. })), + result matches Ok(lowered) ==> + dsl::head_scoped(rule.head@) && dsl::regex_scoped(rule.tail@, rule.head@) + && flat::head_matches(lowered.source.head@, candidate, component_equality::()) + == dsl::head_matches(rule.head@, candidate) + && flat::flat_lang(lowered.source.tests@, lowered.source.regexes@, lowered.source.root as nat, + candidate, history, component_equality::()) + == dsl::lang(rule.tail@, rule.head@, candidate, history), +{ + let result = crate::flatten::flatten_rule(rule, limits, world); + proof { + match &result { + Ok(lowered) => flattening_preserves_semantics::(*rule, *lowered, candidate, history), + Err(_) => {}, + } + } + result +} + +/// A named-variable proof client works at any declared event arity. +pub fn named_variable_client(head: Head, name: alloc::string::String, + component: Component, limits: &mut L, world: &mut ObservationWorld) + -> (result: Result, CompileError>) + requires dsl::head_scoped(head@), component.0 < head@.len(), + dsl::pattern_name(head@[component.0 as int]) == Some(name@), + ensures crate::verify::history_specs::no_invariant_compile_failure(result), + !(result matches Err(CompileError::VariableComponentConflict { .. })), + !(result matches Err(CompileError::UnboundVariable { .. })), + result matches Ok(lowered) ==> + lowered.source.head@[component.0 as int] is Bind && lowered.mode == RuleMode::Require + && match lowered.source.regexes@[lowered.source.root as int] { + FlatRegex::Test(id) => lowered.source.tests@[id as int] == (FlatTest::Atom { field: component, + term: FlatTerm::Variable(component), positive: true }), + _ => false, + }, +{ + let source = Rule::new(RuleMode::Require, head, + RegexExpr::test(TestExpr::atom(history_syntax::syntax::Comparison::Eq, + history_syntax::syntax::AtomPattern::new(component, ComponentPattern::Variable(name))))); + let result = crate::flatten::flatten_rule(&source, limits, world); + proof { + reveal_with_fuel(history_syntax::spec::events::regex_view, 2); + reveal_with_fuel(history_syntax::spec::events::test_view, 2); + reveal_with_fuel(regex_represents, 2); + reveal_with_fuel(test_represents, 2); + } + source.dispose(); + result +} + +/// Constant-only heads need no invented head-binding premise. +pub fn constant_head_client(head: Head, limits: &mut L, world: &mut ObservationWorld) + -> (result: Result, CompileError>) + requires forall|i: int| 0 <= i < head@.len() ==> head@[i] is Constant, + ensures crate::verify::history_specs::no_invariant_compile_failure(result), + !(result matches Err(CompileError::VariableComponentConflict { .. })), + !(result matches Err(CompileError::UnboundVariable { .. })), + !(result matches Err(CompileError::Runtime(crate::errors::HistoryError::InvalidPolicy { .. }))), +{ + let source = Rule::new(RuleMode::Require, head, RegexExpr::all()); + let result = crate::flatten::flatten_rule(&source, limits, world); + source.dispose(); + result +} + +} diff --git a/src/junco-core/src/verify/history_assumptions.rs b/src/junco-core/src/verify/history_assumptions.rs new file mode 100644 index 000000000..4fe52432b --- /dev/null +++ b/src/junco-core/src/verify/history_assumptions.rs @@ -0,0 +1,227 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Trusted native boundary for history correctness. +//! +//! Allowed leaves: reservation adapters; +//! exact SmallVec sequence operations; concrete successor-cache wrappers +//! (including their opaque default hasher type); the exact native Iterator::position +//! selector for retained cursor keys (the pinned vstd lacks its specification); +//! sort_unstable, dedup and strictly-sorted binary_search, each requiring vstd's +//! `obeys_cmp`/`obeys_eq` laws (a total order, an equivalence) of the element type. +//! +//! Reservations preserve logical contents on success and failure. Cache contracts +//! permit eviction, never a fabricated entry. Event coordinates and bindings are +//! fixed u64 identities; classification needs no Value or path-selection assumptions. +//! hashconsius/bumpus pointer tables and hash buckets grow with infallible +//! alloc::vec::Vec (OOM aborts; bounded by MAX_GRAPH_BYTES per store); their +//! contracts are verified in the pinned versions. The native ArenaStorage Drop +//! adapter takes its owned tables and calls verified ArenaTables::release; +//! implicit destructor invocation is outside the Verus model. +//! Native allocator Send/Sync markers rely on exclusive chunk ownership, +//! immutable shared access, and the corresponding element-type bounds outside SMT. +//! History owners isolate borrowed UTF-8 operations, const/static installation and +//! reference identity, mutex callbacks, and Arc/record mechanics in native leaves. +//! Coordinate, history-key and store-ID transitions check successor arithmetic, +//! key absence, exact authority insertion, and consumed-ID failure behavior. +//! Retained persistent receipts prove issuer and independent-owner separation; +//! exclusive registry births and receipt agreement prove foreign checkpoint rejection. +//! Byte interner insertion/rollback and typed history mutation have checked bodies. +//! Full byte-record mutation/read refinement remains a native boundary. +//! Ordered policy/validator construction, selection and transactions are checked; +//! field unpacking and context/diagnostic invocation remain native callback leaves. +//! ArenaStorage inherent operation and KernelStore trait contracts are implemented +//! by verified bodies, not trusted implementations. No compiler, normalizer, derivative, +//! interpreter, matcher, replay, or evaluator may be external_body or assume_specification. + +use crate::kernel::verify::Graph; +use crate::observation::{ObservationWorld, SmallVecSpecFns}; +use alloc::sync::Arc; +use alloc::vec::Vec; +use core::{alloc::Allocator, ops::Deref}; +use smallvec::SmallVec; +use vstd::laws_cmp::obeys_cmp; +use vstd::laws_eq::obeys_eq; +use vstd::prelude::*; +use vstd::std_specs::cmp::{OrdSpec, PartialEqSpec}; + +verus! { +// Identity fidelity. Verus erases `Arc` and `&T` to `T` in spec (vstd's `Arc::new` ensures +// `*v == t`; `*a == *b` proves `a == b`), so both functions below depend only on the pointee's +// value: two distinct allocations with equal contents would have equal identities while +// `Arc::ptr_eq`/`core::ptr::eq` say they differ. The external_body wrappers that equate the two +// (`share_store`, `borrow_store`, `share_numeric_owner`, `borrow_numeric_owner`, +// `same_numeric_reference`, `CompiledRule::same_owner`) are faithful because every compared type +// has a unique-per-allocation value: `HistoryStore` is constructed only by `HistoryStore::new`, +// one static singleton per arity, and stores of different arity differ in `domains@.len()`; +// `Store` is constructed only by `Store::new`, whose `id` comes from the verified never-recycled +// store-id allocator, and neither type is `Clone`. Keep both facts when adding constructors. +pub uninterp spec fn arc_identity(arc: Arc) -> vstd::resource::Loc; +pub uninterp spec fn reference_identity(value: &T) -> vstd::resource::Loc; + + +pub assume_specification[ alloc::string::String::try_reserve ]( + value: &mut alloc::string::String, additional: usize, +) -> Result<(), alloc::collections::TryReserveError> + ensures final(value)@ == old(value)@; + + + + +pub assume_specification[ SmallVec::::new ]() -> (v: SmallVec) + ensures v.view() == Seq::::empty(); + +pub open spec fn spec_smallvec_len(v: &SmallVec) -> usize { + v.view().len() as usize +} + +#[verifier::when_used_as_spec(spec_smallvec_len)] +pub assume_specification[ SmallVec::::len ](v: &SmallVec) + -> (n: usize) + ensures n == v.view().len(), n == spec_smallvec_len(v); + +pub open spec fn spec_smallvec_is_empty(v: &SmallVec) -> bool { + v.view().len() == 0 +} + +#[verifier::when_used_as_spec(spec_smallvec_is_empty)] +pub assume_specification[ SmallVec::::is_empty ](v: &SmallVec) + -> (r: bool) + ensures r == (v.view().len() == 0); + +pub assume_specification[ SmallVec::::push ]( + v: &mut SmallVec, value: A::Item, +) + ensures final(v).view() == old(v).view().push(value); + +// SmallVec's Copy-only implementation uses raw copying, not Clone dispatch. +pub assume_specification[ SmallVec::::extend_from_slice ]( + v: &mut SmallVec, values: &[A::Item], +) + where A::Item: Copy, + ensures final(v).view() == old(v).view() + values@; + +pub assume_specification[ SmallVec::::remove ]( + v: &mut SmallVec, index: usize, +) -> (result: A::Item) + requires index < old(v).view().len(), + ensures result == old(v).view()[index as int], + final(v).view() == old(v).view().remove(index as int); + +pub assume_specification[ SmallVec::::pop ](v: &mut SmallVec) + -> (r: Option) + ensures + old(v).view().len() == 0 ==> r is None && final(v).view() == old(v).view(), + old(v).view().len() > 0 ==> r == Some(old(v).view().last()) + && final(v).view() == old(v).view().drop_last(); + +pub assume_specification[ SmallVec::::truncate ]( + v: &mut SmallVec, len: usize, +) + ensures + len <= old(v).view().len() ==> final(v).view() == old(v).view().subrange(0, len as int), + len > old(v).view().len() ==> final(v).view() == old(v).view(); + +// Match vstd's Vec::resize: arbitrary Clone implementations need not be identity. +pub assume_specification[ SmallVec::::resize ]( + v: &mut SmallVec, len: usize, value: A::Item, +) + where A::Item: Clone + ensures + len <= old(v).view().len() ==> final(v).view() == old(v).view().subrange(0, len as int), + len > old(v).view().len() ==> { + &&& final(v).view().len() == len + &&& final(v).view().subrange(0, old(v).view().len() as int) == old(v).view() + &&& forall|i: int| #![all_triggers] old(v).view().len() <= i < len + ==> cloned::(value, final(v).view()[i]) + }; + +pub assume_specification[ SmallVec::::try_reserve_exact ]( + v: &mut SmallVec, additional: usize, +) -> Result<(), smallvec::CollectionAllocErr> + ensures final(v).view() == old(v).view(); + +// get/get_mut/first/last are slice methods, covered by these views and vstd. +pub assume_specification[ as Deref>::deref ]( + v: &SmallVec, +) -> (s: &[A::Item]) + ensures s@ == v.view(), v.view().len() <= usize::MAX; + +// Mutable autoderef triggers the pinned verifier's anyhow dyn-target importer bug. +// The native slice accessor is the same borrow, without importing DerefMut. +pub assume_specification[ SmallVec::::as_mut_slice ]( + v: &mut SmallVec, +) -> (s: &mut [A::Item]) + ensures s@ == old(v).view(), final(s)@ == final(v).view(); + + + + +pub open spec fn strictly_sorted(s: Seq) -> bool { + forall|i: int, j: int| 0 <= i < j < s.len() ==> s[i].cmp_spec(&s[j]) is Less +} + +// Rust's `Ord` contract: a total order; without one, `sort_unstable` may panic. +pub assume_specification[ <[T]>::sort_unstable ](s: &mut [T]) + requires obeys_cmp::(), + ensures + final(s)@.to_multiset() == old(s)@.to_multiset(), + forall|i: int, j: int| 0 <= i < j < final(s)@.len() + ==> !(final(s)@[i].cmp_spec(&final(s)@[j]) is Greater); + +pub open spec fn dedup_spec(s: Seq) -> Seq + decreases s.len(), +{ + if s.len() <= 1 { + s + } else if s[s.len() - 1].eq_spec(&s[s.len() - 2]) { + dedup_spec(s.drop_last()) + } else { + dedup_spec(s.drop_last()).push(s.last()) + } +} + +// std compares each element with the last one kept; for an equivalence that is the +// same as comparing neighbours, which `dedup_spec` does. +pub assume_specification[ Vec::::dedup ](v: &mut Vec) + requires obeys_eq::(), + ensures final(v)@ == dedup_spec(old(v)@); + +pub assume_specification[ <[T]>::binary_search ](s: &[T], value: &T) + -> (r: Result) + requires obeys_cmp::(), strictly_sorted(s@), + ensures + r matches Ok(i) ==> i < s@.len() && s@[i as int].cmp_spec(value) is Equal, + r is Err ==> forall|i: int| 0 <= i < s@.len() ==> !(s@[i].cmp_spec(value) is Equal); + +// Used by kernel slice comparisons; pinned vstd specifies cloned, not copied. +pub assume_specification<'a, T: Copy>[ Option::<&'a T>::copied ](v: Option<&'a T>) + -> (r: Option) + ensures r == match v { Some(value) => Some(*value), None => None }; + +// The pinned vstd lacks these native calls; neither changes logical contents. +pub assume_specification[ Vec::::into_boxed_slice ]( + values: Vec, +) -> (result: alloc::boxed::Box<[T], A>) + ensures result@ == values@; + +pub assume_specification[ core::mem::drop ](value: T); + + +/// Proof observations for checked kernel stores. Error exclusions are opt-in; +/// custom stores that omit a capability retain arbitrary errors in that class. +pub trait KernelStoreSpec { + spec fn graph(&self) -> Graph; + spec fn valid_store(&self) -> bool; + open spec fn errors_are_non_owner(&self) -> bool { false } + open spec fn errors_are_non_invariant(&self) -> bool { false } + open spec fn errors_are_non_invalid_policy(&self) -> bool { false } + /// Valid operations report only graph, allocation, exhaustion, or host-limit errors. + open spec fn errors_are_resource(&self) -> bool { false } + + // Preserve the abstract store restored when a nested mutable borrow ends. + #[verifier::prophetic] + spec fn restoration(&self) -> (Graph, bool); +} + +} // verus! diff --git a/src/junco-core/src/verify/history_specs.rs b/src/junco-core/src/verify/history_specs.rs new file mode 100644 index 000000000..082394a37 --- /dev/null +++ b/src/junco-core/src/verify/history_specs.rs @@ -0,0 +1,891 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Independent pair-language semantics: request is the head, followed by history +//! in oldest-to-newest order. Runtime errors carry no Boolean interpretation. + +use alloc::boxed::Box; +use alloc::vec::Vec; +use history_syntax::{MAX_ARITY, syntax::Component}; +use vstd::prelude::*; +use vstd::std_specs::iter::IteratorSpec; + +verus! { + +/// Resource failures and policy rejection remain distinct from impossible internal failures. +pub open spec fn no_invariant_failure(result: Result) -> bool { + !(result matches Err(crate::errors::HistoryError::Invariant { .. })) +} + +pub open spec fn no_invariant_compile_failure(result: Result) -> bool { + !(result matches Err(crate::errors::CompileError::Runtime(crate::errors::HistoryError::Invariant { .. }))) +} + + +/// Exact yielded items for conversions whose result obeys the prophetic iterator laws. +#[verifier::prophetic] +pub open spec fn into_iter_yields(input: I, items: Seq) -> bool { + forall|iter: I::IntoIter| + #[trigger] call_ensures(I::into_iter, (input,), iter) + ==> iter.obeys_prophetic_iter_laws() && iter.remaining() == items +} + +/// Owned vectors convert without changing their exact item sequence. +pub proof fn lemma_vec_into_iter_yields(input: Vec) + ensures into_iter_yields(input, input@), +{ + assert forall|iter: alloc::vec::IntoIter| + #[trigger] call_ensures(Vec::::into_iter, (input,), iter) + implies iter.obeys_prophetic_iter_laws() && iter.remaining() == input@ by { + assert(iter.remaining() == input@); + } +} + +/// Iterator identity conversion preserves the caller's established prophetic laws. +pub proof fn lemma_iterator_into_iter_yields(input: I) + requires input.obeys_prophetic_iter_laws(), + ensures into_iter_yields(input, input.remaining()), +{ + assert forall|iter: I| + #[trigger] call_ensures(I::into_iter, (input,), iter) + implies iter.obeys_prophetic_iter_laws() && iter.remaining() == input.remaining() by { + assert(iter == input); + } +} + +/// Numeric event coordinates; zero is reserved for an unbound binding coordinate. +pub type EventView = Seq; + +pub type Subst = EventView; + +pub open spec fn event_wf(event: EventView, arity: nat) -> bool { + event.len() == arity && forall|i: int| 0 <= i < event.len() ==> event[i] <= u64::MAX +} + +pub open spec fn field_value(event: EventView, field: Component) -> nat { + event[field.0 as int] +} + +pub enum Regex { + Empty, All, Epsilon, Test(L), Union(Seq>), Concat(Seq>), + Star(Box>), Intersect(Seq>), Not(Box>), +} + +pub enum Transition { + Const(Regex), If(L, Box>, Box>), + Union(Seq>), Intersect(Seq>), + Not(Box>), Append(Box>, Seq>), +} + +pub open spec fn nullable(r: Regex) -> bool decreases r { + match r { + Regex::Empty | Regex::Test(_) => false, + Regex::All | Regex::Epsilon | Regex::Star(_) => true, + Regex::Union(cs) => exists|i: int| 0 <= i < cs.len() && nullable(cs[i]), + Regex::Concat(cs) => forall|i: int| 0 <= i < cs.len() ==> nullable(cs[i]), + Regex::Intersect(cs) => forall|i: int| 0 <= i < cs.len() ==> nullable(cs[i]), + Regex::Not(c) => !nullable(*c), + } +} + +pub open spec fn numeric_lang(sem: spec_fn(L, EventView) -> bool, r: Regex, w: Seq) -> bool decreases r { + match r { + Regex::Empty => false, + Regex::All => true, + Regex::Epsilon => w.len() == 0, + Regex::Test(l) => w.len() == 1 && sem(l, w[0]), + Regex::Union(cs) => exists|i: int| 0 <= i < cs.len() && numeric_lang(sem, cs[i], w), + Regex::Intersect(cs) => forall|i: int| 0 <= i < cs.len() ==> numeric_lang(sem, cs[i], w), + Regex::Not(c) => !numeric_lang(sem, *c, w), + Regex::Concat(cs) => exists|parts: Seq>| parts.len() == cs.len() && w == parts.flatten() + && forall|i: int| 0 <= i < cs.len() ==> numeric_lang(sem, cs[i], parts[i]), + Regex::Star(c) => exists|parts: Seq>| w == parts.flatten() + && forall|i: int| 0 <= i < parts.len() ==> numeric_lang(sem, *c, parts[i]), + } +} + +pub open spec fn derivative(sem: spec_fn(L, EventView) -> bool, e: EventView, r: Regex) -> Regex + decreases r, 1nat, 0nat, +{ + match r { + Regex::Empty | Regex::Epsilon => Regex::Empty, + Regex::All => Regex::All, + Regex::Test(l) => if sem(l, e) { Regex::Epsilon } else { Regex::Empty }, + Regex::Union(cs) => Regex::Union(Seq::new(cs.len(), |i: int| if 0 <= i < cs.len() { derivative(sem, e, cs[i]) } else { Regex::Empty })), + Regex::Intersect(cs) => Regex::Intersect(Seq::new(cs.len(), |i: int| if 0 <= i < cs.len() { derivative(sem, e, cs[i]) } else { Regex::Empty })), + Regex::Not(c) => Regex::Not(Box::new(derivative(sem, e, *c))), + Regex::Star(c) => Regex::Concat(seq![derivative(sem, e, *c), Regex::Star(c)]), + Regex::Concat(cs) => derivative_concat(sem, e, r, cs), + } +} + +pub open spec fn derivative_concat(sem: spec_fn(L, EventView) -> bool, e: EventView, bound: Regex, cs: Seq>) -> Regex + decreases bound, 0nat, cs.len(), + when forall|i: int| 0 <= i < cs.len() ==> is_smaller_than(cs[i], bound) +{ + if cs.len() == 0 { Regex::Empty } + else { + Regex::Union(seq![Regex::Concat(seq![derivative(sem, e, cs[0])] + cs.drop_first())] + + if nullable(cs[0]) { seq![derivative_concat(sem, e, bound, cs.drop_first())] } else { Seq::empty() }) + } +} + +pub open spec fn derive_word(sem: spec_fn(L, EventView) -> bool, w: Seq, r: Regex) -> Regex + decreases w.len(), +{ + if w.len() == 0 { r } + else { derive_word(sem, w.drop_first(), derivative(sem, w[0], r)) } +} + +pub open spec fn interp_transition(sem: spec_fn(L, EventView) -> bool, e: EventView, t: Transition) -> Regex + decreases t, +{ + match t { + Transition::Const(r) => r, + Transition::If(l, a, b) => if sem(l, e) { interp_transition(sem, e, *a) } else { interp_transition(sem, e, *b) }, + Transition::Union(cs) => Regex::Union(Seq::new(cs.len(), |i: int| if 0 <= i < cs.len() { interp_transition(sem, e, cs[i]) } else { Regex::Empty })), + Transition::Intersect(cs) => Regex::Intersect(Seq::new(cs.len(), |i: int| if 0 <= i < cs.len() { interp_transition(sem, e, cs[i]) } else { Regex::Empty })), + Transition::Not(c) => Regex::Not(Box::new(interp_transition(sem, e, *c))), + Transition::Append(c, suffix) => Regex::Concat(seq![interp_transition(sem, e, *c)] + suffix), + } +} + +pub proof fn lemma_flatten_empty(parts: Seq>) + ensures parts.flatten().len() == 0 <==> forall|i: int| 0 <= i < parts.len() ==> parts[i].len() == 0, + decreases parts.len(), +{ + if parts.len() > 0 { + lemma_flatten_empty(parts.drop_first()); + if parts.flatten().len() == 0 { + assert forall|i: int| 0 <= i < parts.len() implies parts[i].len() == 0 by { + if i > 0 { assert(parts[i] == parts.drop_first()[i - 1]); } + } + } + if forall|i: int| 0 <= i < parts.len() ==> parts[i].len() == 0 { + assert forall|i: int| 0 <= i < parts.drop_first().len() implies parts.drop_first()[i].len() == 0 by { + assert(parts.drop_first()[i] == parts[i + 1]); + } + } + } +} + +pub proof fn lemma_concat_uncons(sem: spec_fn(L, EventView) -> bool, cs: Seq>, w: Seq) + requires cs.len() > 0, + ensures numeric_lang(sem, Regex::Concat(cs), w) <==> exists|a: Seq, b: Seq| + w == a + b && numeric_lang(sem, cs[0], a) && numeric_lang(sem, Regex::Concat(cs.drop_first()), b), +{ + if numeric_lang(sem, Regex::Concat(cs), w) { + let parts = choose|parts: Seq>| parts.len() == cs.len() && w == parts.flatten() + && forall|i: int| 0 <= i < cs.len() ==> numeric_lang(sem, cs[i], parts[i]); + let a = parts[0]; + let tail = parts.drop_first(); + let b = tail.flatten(); + assert forall|i: int| 0 <= i < cs.drop_first().len() implies numeric_lang(sem, cs.drop_first()[i], tail[i]) by { + assert(cs.drop_first()[i] == cs[i + 1]); + assert(tail[i] == parts[i + 1]); + } + assert(numeric_lang(sem, Regex::Concat(cs.drop_first()), b)); + assert(w == a + b); + } + if exists|a: Seq, b: Seq| w == a + b && numeric_lang(sem, cs[0], a) && numeric_lang(sem, Regex::Concat(cs.drop_first()), b) { + let (a, b) = choose|a: Seq, b: Seq| w == a + b && numeric_lang(sem, cs[0], a) && numeric_lang(sem, Regex::Concat(cs.drop_first()), b); + let tail = choose|tail: Seq>| tail.len() == cs.drop_first().len() && b == tail.flatten() + && forall|i: int| 0 <= i < cs.drop_first().len() ==> numeric_lang(sem, cs.drop_first()[i], tail[i]); + let parts = seq![a] + tail; + assert(parts.drop_first() =~= tail); + assert(parts.flatten() == w); + assert forall|i: int| 0 <= i < cs.len() implies numeric_lang(sem, cs[i], parts[i]) by { + if i > 0 { assert(cs[i] == cs.drop_first()[i - 1]); assert(parts[i] == tail[i - 1]); } + } + assert(numeric_lang(sem, Regex::Concat(cs), w)); + } +} + +pub proof fn lemma_nullable_iff_nil(sem: spec_fn(L, EventView) -> bool, r: Regex) + ensures nullable(r) <==> numeric_lang(sem, r, Seq::empty()), + decreases r, +{ + match r { + Regex::Union(cs) => { + assert forall|i: int| 0 <= i < cs.len() implies nullable(cs[i]) == numeric_lang(sem, cs[i], Seq::empty()) by { + lemma_nullable_iff_nil(sem, cs[i]); + } + }, + Regex::Intersect(cs) => { + assert forall|i: int| 0 <= i < cs.len() implies nullable(cs[i]) == numeric_lang(sem, cs[i], Seq::empty()) by { + lemma_nullable_iff_nil(sem, cs[i]); + } + }, + Regex::Not(c) => lemma_nullable_iff_nil(sem, *c), + Regex::Concat(cs) => { + assert forall|i: int| 0 <= i < cs.len() implies nullable(cs[i]) == numeric_lang(sem, cs[i], Seq::empty()) by { + lemma_nullable_iff_nil(sem, cs[i]); + } + if numeric_lang(sem, r, Seq::empty()) { + let parts = choose|parts: Seq>| parts.len() == cs.len() && Seq::::empty() == parts.flatten() + && forall|i: int| 0 <= i < cs.len() ==> numeric_lang(sem, cs[i], parts[i]); + lemma_flatten_empty(parts); + assert forall|i: int| 0 <= i < cs.len() implies nullable(cs[i]) by { + assert(parts[i] =~= Seq::::empty()); + } + } + if nullable(r) { + let parts = Seq::new(cs.len(), |i: int| Seq::::empty()); + lemma_flatten_empty(parts); + assert(parts.flatten() =~= Seq::::empty()); + assert forall|i: int| 0 <= i < cs.len() implies numeric_lang(sem, cs[i], parts[i]) by { + lemma_nullable_iff_nil(sem, cs[i]); + assert(nullable(cs[i])); + assert(parts[i] == Seq::::empty()); + } + assert(numeric_lang(sem, r, Seq::empty())); + } + }, + Regex::Star(c) => { + let parts = Seq::>::empty(); + assert(numeric_lang(sem, r, parts.flatten())); + }, + _ => {}, + } +} + + +pub proof fn lemma_concat_prepend(sem: spec_fn(L, EventView) -> bool, c: Regex, cs: Seq>, w: Seq) + ensures numeric_lang(sem, Regex::Concat(seq![c] + cs), w) <==> exists|a: Seq, b: Seq| + w == a + b && numeric_lang(sem, c, a) && numeric_lang(sem, Regex::Concat(cs), b), +{ + lemma_concat_uncons(sem, seq![c] + cs, w); + assert((seq![c] + cs).drop_first() =~= cs); +} + +pub proof fn lemma_cons_split(e: EventView, w: Seq, a: Seq, b: Seq) + requires seq![e] + w == a + b, a.len() > 0, + ensures a == seq![e] + a.drop_first(), w == a.drop_first() + b, +{ + broadcast use vstd::seq::group_seq_lemmas; + assert((seq![e] + w).len() == 1 + w.len()); + assert((a + b).len() == a.len() + b.len()); + assert(seq![e] + w == a + b); + assert(1 + w.len() == a.len() + b.len()); + assert((seq![e] + w)[0] == e); + assert((a + b)[0] == a[0]); + assert(a[0] == e); + assert(a =~= seq![e] + a.drop_first()); + assert forall|i: int| 0 <= i < w.len() implies w[i] == (a.drop_first() + b)[i] by { + assert((seq![e] + w)[i + 1] == w[i]); + assert((a + b)[i + 1] == if i + 1 < a.len() { a[i + 1] } else { b[i + 1 - a.len()] }); + } + assert(w =~= a.drop_first() + b); +} + +pub proof fn lemma_star_parts_cons(sem: spec_fn(L, EventView) -> bool, c: Regex, parts: Seq>, e: EventView, w: Seq) + requires parts.flatten() == seq![e] + w, + forall|i: int| 0 <= i < parts.len() ==> numeric_lang(sem, c, parts[i]), + ensures exists|a: Seq, b: Seq| w == a + b && numeric_lang(sem, c, seq![e] + a) + && numeric_lang(sem, Regex::Star(Box::new(c)), b), + decreases parts.len(), +{ + assert(parts.len() > 0); + let tail = parts.drop_first(); + assert forall|i: int| 0 <= i < tail.len() implies numeric_lang(sem, c, tail[i]) by { + assert(tail[i] == parts[i + 1]); + } + if parts[0].len() == 0 { + assert(parts[0] =~= Seq::::empty()); + lemma_star_parts_cons(sem, c, tail, e, w); + } else { + let a = parts[0].drop_first(); + let b = tail.flatten(); + lemma_cons_split(e, w, parts[0], b); + assert(numeric_lang(sem, Regex::Star(Box::new(c)), b)); + assert(w == a + b && numeric_lang(sem, c, seq![e] + a) && numeric_lang(sem, Regex::Star(Box::new(c)), b)); + } +} + +pub proof fn lemma_star_cons(sem: spec_fn(L, EventView) -> bool, c: Regex, e: EventView, w: Seq) + ensures numeric_lang(sem, Regex::Star(Box::new(c)), seq![e] + w) <==> exists|a: Seq, b: Seq| + w == a + b && numeric_lang(sem, c, seq![e] + a) && numeric_lang(sem, Regex::Star(Box::new(c)), b), +{ + if numeric_lang(sem, Regex::Star(Box::new(c)), seq![e] + w) { + let parts = choose|parts: Seq>| seq![e] + w == parts.flatten() + && forall|i: int| 0 <= i < parts.len() ==> numeric_lang(sem, c, parts[i]); + lemma_star_parts_cons(sem, c, parts, e, w); + } + if exists|a: Seq, b: Seq| w == a + b && numeric_lang(sem, c, seq![e] + a) && numeric_lang(sem, Regex::Star(Box::new(c)), b) { + let (a, b) = choose|a: Seq, b: Seq| w == a + b && numeric_lang(sem, c, seq![e] + a) && numeric_lang(sem, Regex::Star(Box::new(c)), b); + let tail = choose|tail: Seq>| b == tail.flatten() + && forall|i: int| 0 <= i < tail.len() ==> numeric_lang(sem, c, tail[i]); + let parts = seq![seq![e] + a] + tail; + assert(parts.drop_first() =~= tail); + assert(parts.flatten() =~= seq![e] + w); + assert forall|i: int| 0 <= i < parts.len() implies numeric_lang(sem, c, parts[i]) by { + if i > 0 { assert(parts[i] == tail[i - 1]); } + } + assert(numeric_lang(sem, Regex::Star(Box::new(c)), seq![e] + w)); + } +} + +pub proof fn lemma_lang_union(sem: spec_fn(L, EventView) -> bool, cs: Seq>, w: Seq) + ensures numeric_lang(sem, Regex::Union(cs), w) == (exists|i: int| 0 <= i < cs.len() && numeric_lang(sem, cs[i], w)), +{ + reveal_with_fuel(numeric_lang, 2); + assert(Regex::Union(cs)->Union_0 == cs); +} + +pub proof fn lemma_union_optional(sem: spec_fn(L, EventView) -> bool, a: Regex, b: Regex, flag: bool, w: Seq) + ensures numeric_lang(sem, Regex::Union(seq![a] + if flag { seq![b] } else { Seq::empty() }), w) + == (numeric_lang(sem, a, w) || (flag && numeric_lang(sem, b, w))), +{ + broadcast use vstd::seq::group_seq_lemmas; + reveal_with_fuel(numeric_lang, 2); + let cs = seq![a] + if flag { seq![b] } else { Seq::empty() }; + lemma_lang_union(sem, cs, w); + if numeric_lang(sem, Regex::Union(cs), w) { + let i = choose|i: int| 0 <= i < cs.len() && numeric_lang(sem, cs[i], w); + assert(i == 0 || (flag && i == 1)); + if i == 0 { assert(cs[i] == a); } else { assert(cs[i] == b); } + } + if numeric_lang(sem, a, w) { + assert(cs.len() >= 1); + assert(cs[0] == a); + assert(0 <= 0int < cs.len() && numeric_lang(sem, cs[0], w)); + assert(exists|i: int| 0 <= i < cs.len() && numeric_lang(sem, cs[i], w)); + assert(numeric_lang(sem, Regex::Union(cs), w)); + } + if flag && numeric_lang(sem, b, w) { + assert(cs.len() == 2); + assert(cs[1] == b); + assert(exists|i: int| 0 <= i < cs.len() && numeric_lang(sem, cs[i], w)); + assert(numeric_lang(sem, Regex::Union(cs), w)); + } +} + +pub proof fn lemma_lang_intersect(sem: spec_fn(L, EventView) -> bool, cs: Seq>, w: Seq) + ensures numeric_lang(sem, Regex::Intersect(cs), w) == (forall|i: int| 0 <= i < cs.len() ==> numeric_lang(sem, cs[i], w)), +{ + reveal_with_fuel(numeric_lang, 2); + assert(Regex::Intersect(cs)->Intersect_0 == cs); + if numeric_lang(sem, Regex::Intersect(cs), w) { + assert forall|i: int| 0 <= i < cs.len() implies numeric_lang(sem, cs[i], w) by { + assert(numeric_lang(sem, Regex::Intersect(cs), w)); + } + } +} + +pub proof fn lemma_derivative_concat(sem: spec_fn(L, EventView) -> bool, e: EventView, bound: Regex, cs: Seq>, w: Seq) + requires + forall|i: int| 0 <= i < cs.len() ==> is_smaller_than(cs[i], bound), + forall|i: int, v: Seq| 0 <= i < cs.len() ==> numeric_lang(sem, derivative(sem, e, cs[i]), v) == numeric_lang(sem, cs[i], seq![e] + v), + ensures numeric_lang(sem, derivative_concat(sem, e, bound, cs), w) == numeric_lang(sem, Regex::Concat(cs), seq![e] + w), + decreases cs.len(), +{ + if cs.len() == 0 { + if numeric_lang(sem, Regex::Concat(cs), seq![e] + w) { + let parts = choose|parts: Seq>| parts.len() == cs.len() && seq![e] + w == parts.flatten() + && forall|i: int| 0 <= i < cs.len() ==> numeric_lang(sem, cs[i], parts[i]); + assert(parts =~= Seq::>::empty()); + } + } else { + let c = cs[0]; + let rest = cs.drop_first(); + assert forall|i: int| 0 <= i < rest.len() implies is_smaller_than(rest[i], bound) by { + assert(rest[i] == cs[i + 1]); + } + assert forall|i: int, v: Seq| 0 <= i < rest.len() implies numeric_lang(sem, derivative(sem, e, rest[i]), v) == numeric_lang(sem, rest[i], seq![e] + v) by { + assert(rest[i] == cs[i + 1]); + } + lemma_derivative_concat(sem, e, bound, rest, w); + lemma_nullable_iff_nil(sem, c); + let dc = derivative(sem, e, c); + let dr = derivative_concat(sem, e, bound, rest); + let left = Regex::Concat(seq![dc] + rest); + lemma_union_optional(sem, left, dr, nullable(c), w); + lemma_concat_prepend(sem, dc, rest, w); + lemma_concat_uncons(sem, cs, seq![e] + w); + if numeric_lang(sem, derivative_concat(sem, e, bound, cs), w) { + if numeric_lang(sem, left, w) { + let (a, b) = choose|a: Seq, b: Seq| w == a + b && numeric_lang(sem, dc, a) && numeric_lang(sem, Regex::Concat(rest), b); + assert(numeric_lang(sem, c, seq![e] + a)); + assert(seq![e] + w =~= (seq![e] + a) + b); + assert(exists|a0: Seq, b0: Seq| seq![e] + w == a0 + b0 && numeric_lang(sem, c, a0) && numeric_lang(sem, Regex::Concat(rest), b0)); + } else { + assert(nullable(c) && numeric_lang(sem, dr, w)); + let a = Seq::::empty(); + let b = seq![e] + w; + assert(a + b =~= b); + assert(numeric_lang(sem, c, a) && numeric_lang(sem, Regex::Concat(rest), b)); + assert(exists|a0: Seq, b0: Seq| seq![e] + w == a0 + b0 && numeric_lang(sem, c, a0) && numeric_lang(sem, Regex::Concat(rest), b0)); + } + assert(numeric_lang(sem, Regex::Concat(cs), seq![e] + w)); + } + if numeric_lang(sem, Regex::Concat(cs), seq![e] + w) { + let (a, b) = choose|a: Seq, b: Seq| seq![e] + w == a + b && numeric_lang(sem, c, a) && numeric_lang(sem, Regex::Concat(rest), b); + if a.len() == 0 { + assert(a =~= Seq::::empty()); + assert(b =~= seq![e] + w); + assert(nullable(c)); + assert(numeric_lang(sem, dr, w)); + } else { + lemma_cons_split(e, w, a, b); + let v = a.drop_first(); + assert(numeric_lang(sem, dc, v)); + assert(exists|a0: Seq, b0: Seq| w == a0 + b0 && numeric_lang(sem, dc, a0) && numeric_lang(sem, Regex::Concat(rest), b0)); + assert(numeric_lang(sem, left, w)); + } + assert(numeric_lang(sem, derivative_concat(sem, e, bound, cs), w)); + } + } +} + +pub proof fn lemma_concat_singleton(sem: spec_fn(L, EventView) -> bool, r: Regex, w: Seq) + ensures numeric_lang(sem, Regex::Concat(seq![r]), w) == numeric_lang(sem, r, w), +{ + if numeric_lang(sem, Regex::Concat(seq![r]), w) { + let parts = choose|parts: Seq>| parts.len() == 1 && w == parts.flatten() + && forall|i: int| 0 <= i < 1 ==> numeric_lang(sem, seq![r][i], parts[i]); + parts.lemma_flatten_one_element(); + assert(numeric_lang(sem, r, w)); + } + if numeric_lang(sem, r, w) { + let parts = seq![w]; + parts.lemma_flatten_one_element(); + assert forall|i: int| 0 <= i < 1 implies numeric_lang(sem, seq![r][i], parts[i]) by { assert(i == 0); } + assert(numeric_lang(sem, Regex::Concat(seq![r]), w)); + } +} + +pub proof fn lemma_concat_pair(sem: spec_fn(L, EventView) -> bool, a: Regex, b: Regex, w: Seq) + ensures numeric_lang(sem, Regex::Concat(seq![a, b]), w) <==> exists|u: Seq, v: Seq| + w == u + v && numeric_lang(sem, a, u) && numeric_lang(sem, b, v), +{ + assert(seq![a, b] =~= seq![a] + seq![b]); + lemma_concat_prepend(sem, a, seq![b], w); + assert forall|v: Seq| numeric_lang(sem, Regex::Concat(seq![b]), v) == numeric_lang(sem, b, v) by { + lemma_concat_singleton(sem, b, v); + } +} + +pub proof fn lemma_derivative_correct(sem: spec_fn(L, EventView) -> bool, e: EventView, r: Regex, w: Seq) + ensures numeric_lang(sem, derivative(sem, e, r), w) <==> numeric_lang(sem, r, seq![e] + w), + decreases r, +{ + match r { + Regex::Union(cs) => { + let ds = Seq::new(cs.len(), |i: int| if 0 <= i < cs.len() { derivative(sem, e, cs[i]) } else { Regex::Empty }); + assert(ds.len() == cs.len()); + assert(derivative(sem, e, r)->Union_0 =~= ds); + assert(derivative(sem, e, r) == Regex::Union(ds)); + lemma_lang_union(sem, ds, w); + lemma_lang_union(sem, cs, seq![e] + w); + assert forall|i: int| 0 <= i < cs.len() implies numeric_lang(sem, ds[i], w) == numeric_lang(sem, cs[i], seq![e] + w) by { + lemma_derivative_correct(sem, e, cs[i], w); + } + assert(numeric_lang(sem, derivative(sem, e, r), w) == numeric_lang(sem, r, seq![e] + w)); + }, + Regex::Intersect(cs) => { + let ds = Seq::new(cs.len(), |i: int| if 0 <= i < cs.len() { derivative(sem, e, cs[i]) } else { Regex::Empty }); + assert(ds.len() == cs.len()); + assert(derivative(sem, e, r)->Intersect_0 =~= ds); + assert(derivative(sem, e, r) == Regex::Intersect(ds)); + lemma_lang_intersect(sem, ds, w); + lemma_lang_intersect(sem, cs, seq![e] + w); + assert forall|i: int| 0 <= i < cs.len() implies numeric_lang(sem, ds[i], w) == numeric_lang(sem, cs[i], seq![e] + w) by { + lemma_derivative_correct(sem, e, cs[i], w); + } + assert(numeric_lang(sem, derivative(sem, e, r), w) == numeric_lang(sem, r, seq![e] + w)); + }, + Regex::Not(c) => lemma_derivative_correct(sem, e, *c, w), + Regex::Star(c) => { + lemma_star_cons(sem, *c, e, w); + lemma_concat_pair(sem, derivative(sem, e, *c), Regex::Star(c), w); + assert forall|a: Seq| numeric_lang(sem, derivative(sem, e, *c), a) == numeric_lang(sem, *c, seq![e] + a) by { + lemma_derivative_correct(sem, e, *c, a); + } + assert(numeric_lang(sem, derivative(sem, e, r), w) == numeric_lang(sem, r, seq![e] + w)); + }, + Regex::Concat(cs) => { + assert forall|i: int| 0 <= i < cs.len() implies is_smaller_than(cs[i], r) by { } + assert forall|i: int, v: Seq| 0 <= i < cs.len() implies numeric_lang(sem, derivative(sem, e, cs[i]), v) == numeric_lang(sem, cs[i], seq![e] + v) by { + lemma_derivative_correct(sem, e, cs[i], v); + } + lemma_derivative_concat(sem, e, r, cs, w); + }, + Regex::Test(_) => { assert((seq![e] + w)[0] == e); }, + _ => {}, + } +} + +pub proof fn lemma_derive_word_correct(sem: spec_fn(L, EventView) -> bool, prefix: Seq, r: Regex, suffix: Seq) + ensures numeric_lang(sem, derive_word(sem, prefix, r), suffix) == numeric_lang(sem, r, prefix + suffix), + decreases prefix.len(), +{ + if prefix.len() == 0 { assert(prefix + suffix =~= suffix); } + else { + lemma_derive_word_correct(sem, prefix.drop_first(), derivative(sem, prefix[0], r), suffix); + lemma_derivative_correct(sem, prefix[0], r, prefix.drop_first() + suffix); + assert(seq![prefix[0]] + (prefix.drop_first() + suffix) =~= prefix + suffix); + } +} + +pub proof fn lemma_derive_word_nullable(sem: spec_fn(L, EventView) -> bool, w: Seq, r: Regex) + ensures nullable(derive_word(sem, w, r)) == numeric_lang(sem, r, w), +{ + lemma_nullable_iff_nil(sem, derive_word(sem, w, r)); + lemma_derive_word_correct(sem, w, r, Seq::empty()); + assert(w + Seq::::empty() =~= w); +} + +pub proof fn lemma_interp_const(sem: spec_fn(L, EventView) -> bool, e: EventView, r: Regex) + ensures interp_transition(sem, e, Transition::Const(r)) == r, +{ } + +pub proof fn lemma_interp_if(sem: spec_fn(L, EventView) -> bool, e: EventView, l: L, a: Transition, b: Transition) + ensures interp_transition(sem, e, Transition::If(l, Box::new(a), Box::new(b))) + == if sem(l, e) { interp_transition(sem, e, a) } else { interp_transition(sem, e, b) }, +{ } + +pub proof fn lemma_interp_union(sem: spec_fn(L, EventView) -> bool, e: EventView, cs: Seq>, w: Seq) + ensures numeric_lang(sem, interp_transition(sem, e, Transition::Union(cs)), w) + == (exists|i: int| 0 <= i < cs.len() && numeric_lang(sem, interp_transition(sem, e, cs[i]), w)), +{ + let r = interp_transition(sem, e, Transition::Union(cs)); + assert(r is Union); + assert((r->Union_0).len() == cs.len()); + lemma_lang_union(sem, r->Union_0, w); + assert forall|i: int| 0 <= i < cs.len() implies (r->Union_0)[i] == interp_transition(sem, e, cs[i]) by { } + assert forall|i: int| 0 <= i < cs.len() implies numeric_lang(sem, (r->Union_0)[i], w) == numeric_lang(sem, interp_transition(sem, e, cs[i]), w) by { + assert((r->Union_0)[i] == interp_transition(sem, e, cs[i])); + } + if numeric_lang(sem, r, w) { + let i = choose|i: int| 0 <= i < (r->Union_0).len() && numeric_lang(sem, (r->Union_0)[i], w); + assert(numeric_lang(sem, interp_transition(sem, e, cs[i]), w)); + assert(exists|j: int| 0 <= j < cs.len() && numeric_lang(sem, interp_transition(sem, e, cs[j]), w)); + } + if exists|i: int| 0 <= i < cs.len() && numeric_lang(sem, interp_transition(sem, e, cs[i]), w) { + let i = choose|i: int| 0 <= i < cs.len() && numeric_lang(sem, interp_transition(sem, e, cs[i]), w); + assert(numeric_lang(sem, (r->Union_0)[i], w)); + assert(exists|j: int| 0 <= j < (r->Union_0).len() && numeric_lang(sem, (r->Union_0)[j], w)); + assert(numeric_lang(sem, r, w)); + } +} + +pub proof fn lemma_interp_intersect(sem: spec_fn(L, EventView) -> bool, e: EventView, cs: Seq>, w: Seq) + ensures numeric_lang(sem, interp_transition(sem, e, Transition::Intersect(cs)), w) + == (forall|i: int| 0 <= i < cs.len() ==> numeric_lang(sem, interp_transition(sem, e, cs[i]), w)), +{ + let r = interp_transition(sem, e, Transition::Intersect(cs)); + assert(r is Intersect); + assert((r->Intersect_0).len() == cs.len()); + lemma_lang_intersect(sem, r->Intersect_0, w); + assert forall|i: int| 0 <= i < cs.len() implies (r->Intersect_0)[i] == interp_transition(sem, e, cs[i]) by { } + assert forall|i: int| 0 <= i < cs.len() implies numeric_lang(sem, (r->Intersect_0)[i], w) == numeric_lang(sem, interp_transition(sem, e, cs[i]), w) by { + assert((r->Intersect_0)[i] == interp_transition(sem, e, cs[i])); + } + if numeric_lang(sem, r, w) { + assert forall|i: int| 0 <= i < cs.len() implies numeric_lang(sem, interp_transition(sem, e, cs[i]), w) by { + assert(numeric_lang(sem, (r->Intersect_0)[i], w)); + } + } + if forall|i: int| 0 <= i < cs.len() ==> numeric_lang(sem, interp_transition(sem, e, cs[i]), w) { + assert forall|i: int| 0 <= i < (r->Intersect_0).len() implies numeric_lang(sem, (r->Intersect_0)[i], w) by { + assert(numeric_lang(sem, interp_transition(sem, e, cs[i]), w)); + } + assert(numeric_lang(sem, r, w)); + } +} + +pub proof fn lemma_interp_not(sem: spec_fn(L, EventView) -> bool, e: EventView, t: Transition) + ensures interp_transition(sem, e, Transition::Not(Box::new(t))) == Regex::Not(Box::new(interp_transition(sem, e, t))), +{ } + +pub proof fn lemma_interp_append(sem: spec_fn(L, EventView) -> bool, e: EventView, t: Transition, suffix: Seq>) + ensures interp_transition(sem, e, Transition::Append(Box::new(t), suffix)) == Regex::Concat(seq![interp_transition(sem, e, t)] + suffix), +{ } + +pub enum Term { + Constant(nat), + Variable(Component), +} + +pub enum SrcTest { + Bool(bool), + And(Seq), + Or(Seq), + Eq(Component, Term), + Neq(Component, Term), +} + +pub enum HeadField { Any, Constant(nat), Bind } + +pub type Head = Seq; + +pub open spec fn head_field(head: Head, field: Component) -> HeadField { + head[field.0 as int] +} + +pub open spec fn head_field_match(head: HeadField, request: nat, binding: nat) -> bool { + match head { + HeadField::Any => binding == 0, + HeadField::Constant(value) => request == value && binding == 0, + HeadField::Bind => binding == request, + } +} + +pub open spec fn head_match(head: Head, request: EventView, theta: Subst) -> bool { + head.len() == request.len() && head.len() == theta.len() + && forall|i: int| 0 <= i < head.len() ==> head_field_match(head[i], request[i], theta[i]) +} + +pub open spec fn head_bindings(head: Head, request: EventView) -> Subst { + Seq::new(head.len(), |i: int| if head[i] is Bind { request[i] } else { 0 }) +} + +pub open spec fn term_value(theta: Subst, term: Term) -> nat { + match term { + Term::Constant(value) => value, + Term::Variable(field) => field_value(theta, field), + } +} + +pub open spec fn src_test_holds(theta: Subst, test: SrcTest, event: EventView) -> bool + decreases test, +{ + match test { + SrcTest::Bool(value) => value, + SrcTest::And(children) => forall|i: int| 0 <= i < children.len() + ==> src_test_holds(theta, children[i], event), + SrcTest::Or(children) => exists|i: int| 0 <= i < children.len() + && src_test_holds(theta, children[i], event), + SrcTest::Eq(field, term) => field_value(event, field) == term_value(theta, term), + SrcTest::Neq(field, term) => field_value(event, field) != term_value(theta, term), + } +} + +pub open spec fn term_wf(field: Component, term: Term, head: Head) -> bool { + field.0 < head.len() && match term { + Term::Constant(value) => 0 < value <= u64::MAX, + Term::Variable(variable) => variable == field && head_field(head, field) is Bind, + } +} + +pub open spec fn head_wf(head: Head) -> bool { + 1 <= head.len() <= MAX_ARITY && forall|i: int| 0 <= i < head.len() ==> match #[trigger] head[i] { + HeadField::Constant(value) => 0 < value <= u64::MAX, + _ => true, + } +} + +pub open spec fn test_wf(test: SrcTest, head: Head) -> bool + decreases test, +{ + match test { + SrcTest::Bool(_) => true, + SrcTest::And(children) | SrcTest::Or(children) => forall|i: int| + 0 <= i < children.len() ==> test_wf(children[i], head), + SrcTest::Eq(field, term) | SrcTest::Neq(field, term) => term_wf(field, term, head), + } +} + +pub open spec fn tail_wf(tail: Regex, head: Head) -> bool + decreases tail, +{ + match tail { + Regex::Test(test) => test_wf(test, head), + Regex::Union(children) | Regex::Concat(children) | Regex::Intersect(children) => + forall|i: int| 0 <= i < children.len() ==> tail_wf(children[i], head), + Regex::Star(child) | Regex::Not(child) => tail_wf(*child, head), + _ => true, + } +} + +pub open spec fn pair_lang(head: Head, tail: Regex, request: EventView, history: Seq) -> bool { + exists|theta: Subst| head_match(head, request, theta) + && numeric_lang(|test: SrcTest, event: EventView| src_test_holds(theta, test, event), tail, history) +} + +pub proof fn lemma_head_match_unique_subst(head: Head, request: EventView, left: Subst, right: Subst) + requires head_match(head, request, left), head_match(head, request, right), + ensures left == right, +{ + assert forall|i: int| 0 <= i < head.len() implies left[i] == right[i] by { + match head[i] { HeadField::Any => {}, HeadField::Constant(_) => {}, HeadField::Bind => {} } + } + assert(left =~= right); +} + +pub proof fn lemma_pair_lang_substitutions(head: Head, tail: Regex, request: EventView, + history: Seq, theta: Subst) + requires head_match(head, request, theta), + ensures pair_lang(head, tail, request, history) + == numeric_lang(|test: SrcTest, event: EventView| src_test_holds(theta, test, event), tail, history), +{ + if pair_lang(head, tail, request, history) { + let other = choose|other: Subst| head_match(head, request, other) + && numeric_lang(|test: SrcTest, event: EventView| src_test_holds(other, test, event), tail, history); + lemma_head_match_unique_subst(head, request, theta, other); + } + if numeric_lang(|test: SrcTest, event: EventView| src_test_holds(theta, test, event), tail, history) { + assert(exists|other: Subst| head_match(head, request, other) + && numeric_lang(|test: SrcTest, event: EventView| src_test_holds(other, test, event), tail, history)); + } +} + +/// The selected batch is compositional; nullable is used only at the fixed target. +pub proof fn lemma_derive_word_append(sem: spec_fn(L, EventView) -> bool, + xs: Seq, ys: Seq, root: Regex) + ensures derive_word(sem, xs + ys, root) == derive_word(sem, ys, derive_word(sem, xs, root)), + decreases xs.len(), +{ + if xs.len() == 0 { + assert(xs + ys =~= ys); + } else { + assert((xs + ys)[0] == xs[0]); + assert((xs + ys).drop_first() =~= xs.drop_first() + ys); + lemma_derive_word_append(sem, xs.drop_first(), ys, derivative(sem, xs[0], root)); + } +} + +pub open spec fn selected_end(consumed: nat, target: nat, batch_size: nat) -> nat { + consumed + if batch_size < target - consumed { batch_size } else { (target - consumed) as nat } +} + +pub proof fn lemma_selected_end(consumed: nat, target: nat, batch_size: nat) + requires consumed <= target, batch_size > 0, + ensures consumed <= selected_end(consumed, target, batch_size) <= target, + consumed < target ==> consumed < selected_end(consumed, target, batch_size), + selected_end(consumed, target, batch_size) - consumed <= batch_size, + target - consumed <= batch_size ==> selected_end(consumed, target, batch_size) == target, +{ } + +pub proof fn lemma_batch_prefix_composition(sem: spec_fn(L, EventView) -> bool, + history: Seq, root: Regex, consumed: nat, end: nat) + requires consumed <= end <= history.len(), + ensures derive_word(sem, history.subrange(consumed as int, end as int), + derive_word(sem, history.take(consumed as int), root)) + == derive_word(sem, history.take(end as int), root), +{ + assert(history.take(consumed as int) + history.subrange(consumed as int, end as int) + =~= history.take(end as int)); + lemma_derive_word_append(sem, history.take(consumed as int), + history.subrange(consumed as int, end as int), root); +} + +pub proof fn lemma_full_target_answer(sem: spec_fn(L, EventView) -> bool, + history: Seq, root: Regex, target: nat) + requires target <= history.len(), + ensures nullable(derive_word(sem, history.take(target as int), root)) + == numeric_lang(sem, root, history.take(target as int)), +{ + lemma_derive_word_nullable(sem, history.take(target as int), root); +} + +pub struct HistoryStateView { + pub events: Seq, + pub revision: nat, +} + +/// Successful locked mutations either append, do nothing, or truncate with a checked revision. +pub open spec fn history_mutation(before: HistoryStateView, after: HistoryStateView) -> bool { + before.revision <= u64::MAX && after.revision <= u64::MAX && ( + (before.revision == after.revision && before.events.is_prefix_of(after.events)) + || (before.revision < u64::MAX && after.revision == before.revision + 1 + && after.events.len() < before.events.len() + && after.events == before.events.take(after.events.len() as int))) +} + +pub proof fn lemma_revision_chain_preserves_prefix(states: Seq) + requires states.len() > 0, + forall|i: int| 0 < i < states.len() ==> #[trigger] history_mutation(states[i - 1], states[i]), + ensures states.first().revision <= states.last().revision, + states.first().revision == states.last().revision + ==> states.first().events.is_prefix_of(states.last().events), + decreases states.len(), +{ + if states.len() > 1 { + let prior = states.drop_last(); + assert forall|i: int| 0 < i < prior.len() implies #[trigger] history_mutation(prior[i - 1], prior[i]) by { + assert(prior[i - 1] == states[i - 1]); + assert(prior[i] == states[i]); + } + lemma_revision_chain_preserves_prefix(prior); + assert(history_mutation(prior.last(), states.last())); + if states.first().revision == states.last().revision { + assert(prior.first().revision == prior.last().revision); + assert(prior.last().events.is_prefix_of(states.last().events)); + assert(states.last().events.take(states.first().events.len() as int) + =~= states.first().events); + } + } +} + +/// Same-revision snapshots refer to an immutable prefix, not to the current length. +pub open spec fn snapshot_valid(captured: Seq, revision: nat, + current: Seq, current_revision: nat) -> bool { + revision == current_revision && captured.is_prefix_of(current) +} + +pub proof fn lemma_append_preserves_snapshot(captured: Seq, revision: nat, + current: Seq, suffix: Seq) + requires snapshot_valid(captured, revision, current, revision), + ensures snapshot_valid(captured, revision, current + suffix, revision), +{ + assert(captured.len() <= current.len()); + assert((current + suffix).take(captured.len() as int) =~= captured); +} + +pub proof fn lemma_truncate_invalidates_snapshot(captured: Seq, revision: nat, + current: Seq, keep: nat) + requires keep < current.len(), revision < u64::MAX, + ensures !snapshot_valid(captured, revision, current.take(keep as int), revision + 1), +{ } + +pub proof fn lemma_exact_utf8_equality(left: Seq, right: Seq) + ensures (vstd::utf8::encode_utf8(left) == vstd::utf8::encode_utf8(right)) == (left == right), +{ + vstd::utf8::encode_utf8_decode_utf8(left); + vstd::utf8::encode_utf8_decode_utf8(right); +} + +/// Mutex linearization composes the checked executable allocator's consecutive states. +pub proof fn lemma_allocator_nonreuse(first: nat, after_first: nat, before_later: nat, later: nat) + requires after_first == first + 1, after_first <= before_later, later == before_later, + ensures first < later, +{ } + +/// Exact UTF-8 bytes are keys; no normalization or ancestry relation is modeled. +pub open spec fn interner_wf(paths: Map, nat>, next: nat) -> bool { + 0 < next <= u64::MAX + && (forall|path: Seq| paths.contains_key(path) ==> 0 < paths[path] < next) + && (forall|left: Seq, right: Seq| paths.contains_key(left) + && paths.contains_key(right) && paths[left] == paths[right] ==> left == right) +} + +pub proof fn lemma_interner_raise_frontier(paths: Map, nat>, before: nat, after: nat) + requires interner_wf(paths, before), before <= after <= u64::MAX, + ensures interner_wf(paths, after), +{ } + +pub proof fn lemma_interner_exact_equality(paths: Map, nat>, next: nat, + left: Seq, right: Seq) + requires interner_wf(paths, next), paths.contains_key(left), paths.contains_key(right), + ensures (paths[left] == paths[right]) == (left == right), +{ } + +pub proof fn lemma_interner_fresh_nonreuse(paths: Map, nat>, next: nat, + path: Seq, allocated: nat) + requires interner_wf(paths, next), !paths.contains_key(path), + next <= allocated < u64::MAX, + ensures interner_wf(paths.insert(path, allocated), allocated + 1), + forall|old_path: Seq| paths.contains_key(old_path) + ==> paths.insert(path, allocated)[old_path] == paths[old_path] + && paths[old_path] != allocated, +{ + assert forall|left: Seq, right: Seq| paths.insert(path, allocated).contains_key(left) + && paths.insert(path, allocated).contains_key(right) + && paths.insert(path, allocated)[left] == paths.insert(path, allocated)[right] + implies left == right by { + if left != path && right != path { assert(paths[left] == paths[right]); } + } +} + +} diff --git a/src/junco-core/src/verify/hypotheses.rs b/src/junco-core/src/verify/hypotheses.rs new file mode 100644 index 000000000..41a3e4bb7 --- /dev/null +++ b/src/junco-core/src/verify/hypotheses.rs @@ -0,0 +1,180 @@ +//! Concrete witnesses for `event_obligations` (`junco_core::spec::hypotheses`): the built-in key +//! and event types satisfy every conjunct; nothing here is trusted. + +use crate::spec::hypotheses::{eq_equivalence, event_obligations, hash_respects_eq, key_laws}; +use core::fmt::Debug; +use core::hash::Hash; +use history_syntax::KeyHash; +use history_syntax::event::{Component2, Component3, Component4}; +use history_syntax::key_hash::specs::KeyHashSpec; +use history_syntax::verify::events::{ + lemma_event_laws_pair, lemma_event_laws_quad, lemma_event_laws_triple, +}; +use vstd::prelude::*; +use vstd::std_specs::cmp::PartialEqSpec; + +/// Primitive keys: vstd's `eq_spec` is `==` and `hash_spec` is a function of the value. +macro_rules! primitive_key_laws { + ($($lemma:ident: $t:ty),+ $(,)?) => {$( + verus! { + pub proof fn $lemma() + ensures key_laws::<$t>(), + { + } + } + )+}; +} + +primitive_key_laws!( + lemma_key_laws_bool: bool, + lemma_key_laws_u8: u8, + lemma_key_laws_u16: u16, + lemma_key_laws_u32: u32, + lemma_key_laws_u64: u64, + lemma_key_laws_usize: usize, +); + +verus! { + +/// A pair is a hash key when its components are: vstd's tuple `eq_spec` is componentwise and +/// `hash_spec` mixes the components' hashes. +pub proof fn lemma_key_laws_pair() + requires key_laws::(), key_laws::(), + ensures key_laws::<(A, B)>(), +{ +} + +/// A tagged pair component is a hash key when its payloads are. +pub proof fn lemma_key_laws_component2() + requires key_laws::(), key_laws::(), + ensures key_laws::>(), +{ + assert forall|a: Component2, b: Component2, c: Component2| + #[trigger] a.eq_spec(&b) && #[trigger] b.eq_spec(&c) implies a.eq_spec(&c) by { + match (a, b, c) { + (Component2::C0(x), Component2::C0(y), Component2::C0(z)) => assert(x.eq_spec(&z)), + (Component2::C1(x), Component2::C1(y), Component2::C1(z)) => assert(x.eq_spec(&z)), + _ => {} + } + } + assert forall|a: Component2, b: Component2| #[trigger] a.eq_spec(&b) + implies a.hash_spec() == b.hash_spec() by { + match (a, b) { + (Component2::C0(x), Component2::C0(y)) => assert(x.hash_spec() == y.hash_spec()), + (Component2::C1(x), Component2::C1(y)) => assert(x.hash_spec() == y.hash_spec()), + _ => {} + } + } +} + +/// A tagged triple component is a hash key when its payloads are. +pub proof fn lemma_key_laws_component3() + requires key_laws::(), key_laws::(), key_laws::(), + ensures key_laws::>(), +{ + assert forall|a: Component3, b: Component3, c: Component3| + #[trigger] a.eq_spec(&b) && #[trigger] b.eq_spec(&c) implies a.eq_spec(&c) by { + match (a, b, c) { + (Component3::C0(x), Component3::C0(y), Component3::C0(z)) => assert(x.eq_spec(&z)), + (Component3::C1(x), Component3::C1(y), Component3::C1(z)) => assert(x.eq_spec(&z)), + (Component3::C2(x), Component3::C2(y), Component3::C2(z)) => assert(x.eq_spec(&z)), + _ => {} + } + } + assert forall|a: Component3, b: Component3| #[trigger] a.eq_spec(&b) + implies a.hash_spec() == b.hash_spec() by { + match (a, b) { + (Component3::C0(x), Component3::C0(y)) => assert(x.hash_spec() == y.hash_spec()), + (Component3::C1(x), Component3::C1(y)) => assert(x.hash_spec() == y.hash_spec()), + (Component3::C2(x), Component3::C2(y)) => assert(x.hash_spec() == y.hash_spec()), + _ => {} + } + } +} + +/// A tagged quadruple component is a hash key when its payloads are. +pub proof fn lemma_key_laws_component4() + requires key_laws::(), key_laws::(), key_laws::(), key_laws::(), + ensures key_laws::>(), +{ + assert forall|a: Component4, b: Component4, c: Component4| + #[trigger] a.eq_spec(&b) && #[trigger] b.eq_spec(&c) implies a.eq_spec(&c) by { + match (a, b, c) { + (Component4::C0(x), Component4::C0(y), Component4::C0(z)) => assert(x.eq_spec(&z)), + (Component4::C1(x), Component4::C1(y), Component4::C1(z)) => assert(x.eq_spec(&z)), + (Component4::C2(x), Component4::C2(y), Component4::C2(z)) => assert(x.eq_spec(&z)), + (Component4::C3(x), Component4::C3(y), Component4::C3(z)) => assert(x.eq_spec(&z)), + _ => {} + } + } + assert forall|a: Component4, b: Component4| #[trigger] a.eq_spec(&b) + implies a.hash_spec() == b.hash_spec() by { + match (a, b) { + (Component4::C0(x), Component4::C0(y)) => assert(x.hash_spec() == y.hash_spec()), + (Component4::C1(x), Component4::C1(y)) => assert(x.hash_spec() == y.hash_spec()), + (Component4::C2(x), Component4::C2(y)) => assert(x.hash_spec() == y.hash_spec()), + (Component4::C3(x), Component4::C3(y)) => assert(x.hash_spec() == y.hash_spec()), + _ => {} + } + } +} + +/// `event_obligations` for a pair event whose payloads are hash keys. +pub proof fn lemma_pair_event_hypotheses() + requires key_laws::(), key_laws::(), + ensures event_obligations::<(A, B)>(), +{ + lemma_event_laws_pair::(); + lemma_key_laws_component2::(); +} + +/// `event_obligations` for a triple event whose payloads are hash keys. +pub proof fn lemma_triple_event_hypotheses() + requires key_laws::(), key_laws::(), key_laws::(), + ensures event_obligations::<(A, B, C)>(), +{ + lemma_event_laws_triple::(); + lemma_key_laws_component3::(); +} + +/// `event_obligations` for a quadruple event whose payloads are hash keys. +pub proof fn lemma_quad_event_hypotheses() + requires key_laws::(), key_laws::(), key_laws::(), key_laws::(), + ensures event_obligations::<(A, B, C, D)>(), +{ + lemma_event_laws_quad::(); + lemma_key_laws_component4::(); +} + +/// `(u32, u64)` events satisfy `event_obligations` outright. +pub proof fn lemma_u32_u64_event_hypotheses() + ensures event_obligations::<(u32, u64)>(), +{ + lemma_key_laws_u32(); + lemma_key_laws_u64(); + lemma_pair_event_hypotheses::(); +} + +/// `(u8, u8, u8)` events satisfy `event_obligations` outright. +pub proof fn lemma_u8_triple_event_hypotheses() + ensures event_obligations::<(u8, u8, u8)>(), +{ + lemma_key_laws_u8(); + lemma_triple_event_hypotheses::(); +} + +/// `(u32, u8, bool)` events satisfy `event_obligations` outright. +pub proof fn lemma_u32_mixed_event_hypotheses() + ensures event_obligations::<(u32, u8, bool)>(), +{ + lemma_key_laws_u32(); + lemma_key_laws_u8(); + lemma_key_laws_bool(); + lemma_triple_event_hypotheses::(); +} + +} // verus! diff --git a/src/junco-core/src/verify/mod.rs b/src/junco-core/src/verify/mod.rs new file mode 100644 index 000000000..52a542aad --- /dev/null +++ b/src/junco-core/src/verify/mod.rs @@ -0,0 +1,8 @@ +pub mod capacity; +pub mod dsl; +pub mod encoding; +pub mod flatten; +#[cfg(feature = "runtime")] +pub mod history_assumptions; +pub mod history_specs; +pub mod hypotheses; diff --git a/src/junco-core/tests/dsl.rs b/src/junco-core/tests/dsl.rs new file mode 100644 index 000000000..c434f5089 --- /dev/null +++ b/src/junco-core/tests/dsl.rs @@ -0,0 +1,479 @@ +use history_syntax::{ + AtomPattern, Comparison, Component, Component3, ComponentPattern, Event, Head, N3, RegexExpr, + Rule, RuleMode, TestExpr, +}; +use junco_core::scope::VariableScope; +use junco_core::{CompileError, Grant, Request}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +struct DocumentEvent { + principal: u8, + action: u8, + resource: u8, + payload: u16, +} + +impl Event for DocumentEvent { + type Component = Component3; + type Arity = N3; + fn component(self, index: usize) -> Self::Component { + match index { + 0 => Component3::C0(self.principal), + 1 => Component3::C1(self.action), + _ => Component3::C2(self.resource), + } + } + fn coordinate(component: Self::Component) -> usize { + match component { + Component3::C0(_) => 0, + Component3::C1(_) => 1, + Component3::C2(_) => 2, + } + } +} + +fn head() -> Head { + Head::new([ + ComponentPattern::variable("actor"), + ComponentPattern::constant(Component3::C1(2_u8)), + ComponentPattern::variable("document"), + ]) +} + +fn action(value: u8) -> RegexExpr { + RegexExpr::test(TestExpr::atom( + Comparison::Eq, + AtomPattern::new( + Component(1), + ComponentPattern::constant(Component3::C1(value)), + ), + )) +} + +#[test] +fn borrowed_scope_binds_same_coordinate_and_rejects_cross_domain_reuse() { + let mut scope = VariableScope::new(3); + scope.bind(Component(0), "actor").unwrap(); + scope.bind(Component(1), "operation").unwrap(); + scope.bind(Component(2), "document").unwrap(); + scope.bind(Component(0), "actor").unwrap(); + assert_eq!(scope.resolve(Component(0), "actor"), Ok(Component(0))); + assert_eq!(scope.resolve(Component(1), "operation"), Ok(Component(1))); + assert_eq!(scope.resolve(Component(2), "document"), Ok(Component(2))); + assert_eq!( + scope.bind(Component(2), "actor"), + Err(CompileError::VariableComponentConflict { + name: "actor".into(), + }) + ); + assert_eq!(scope.name(Component(2)), Some("document")); + assert_eq!( + scope.resolve(Component(2), "actor"), + Err(CompileError::VariableComponentConflict { + name: "actor".into(), + }) + ); + assert_eq!( + scope.resolve(Component(0), "missing"), + Err(CompileError::UnboundVariable { + name: "missing".into(), + }) + ); +} + +#[test] +fn request_and_grant_preserve_event_and_opaque_metadata() { + let event = DocumentEvent { + principal: 1, + action: 2, + resource: 3, + payload: 99, + }; + let right = event; + let request = Request::new(right, String::from("opaque")); + let grant = Grant { + event: request.event, + metadata: request.metadata, + }; + assert_eq!(grant.event, right); + assert_eq!(grant.metadata, "opaque"); +} + +fn flatten( + rule: &Rule, +) -> Result>, CompileError> { + junco_core::flatten_rule( + rule, + &mut junco_core::limits::Unmetered, + &mut junco_core::observation::ObservationWorld, + ) +} + +#[test] +fn flattening_resolves_names_and_retains_concrete_component_tags() { + use junco_core::flat::{FlatHead, FlatRegex, FlatTerm, FlatTest}; + let rule = Rule::new( + RuleMode::Forbid, + head(), + RegexExpr::test(TestExpr::and([ + TestExpr::atom( + Comparison::Eq, + AtomPattern::new(Component(0), ComponentPattern::variable("actor")), + ), + TestExpr::atom( + Comparison::Neq, + AtomPattern::new(Component(2), ComponentPattern::variable("document")), + ), + TestExpr::atom( + Comparison::Eq, + AtomPattern::new( + Component(1), + ComponentPattern::constant(Component3::C1(1_u8)), + ), + ), + ])), + ); + let flat = flatten(&rule).unwrap(); + assert_eq!(flat.mode, RuleMode::Forbid); + assert_eq!( + flat.source.head, + vec![ + FlatHead::Bind, + FlatHead::Constant(Component3::C1(2)), + FlatHead::Bind + ] + ); + assert_eq!( + flat.source.tests, + vec![ + FlatTest::Atom { + field: Component(0), + term: FlatTerm::Variable(Component(0)), + positive: true + }, + FlatTest::Atom { + field: Component(2), + term: FlatTerm::Variable(Component(2)), + positive: false + }, + FlatTest::Atom { + field: Component(1), + term: FlatTerm::Constant(Component3::C1(1)), + positive: true + }, + FlatTest::And(vec![0, 1, 2]), + ] + ); + assert_eq!(flat.source.regexes, vec![FlatRegex::Test(3)]); + assert_eq!(flat.source.root, 0); + assert_eq!(flat.source.validate(), Ok(())); + assert_eq!( + rule.tail, + RegexExpr::test(TestExpr::and([ + TestExpr::atom( + Comparison::Eq, + AtomPattern::new(Component(0), ComponentPattern::variable("actor")) + ), + TestExpr::atom( + Comparison::Neq, + AtomPattern::new(Component(2), ComponentPattern::variable("document")) + ), + TestExpr::atom( + Comparison::Eq, + AtomPattern::new( + Component(1), + ComponentPattern::constant(Component3::C1(1_u8)) + ) + ), + ])) + ); +} + +#[test] +fn flattening_reports_scope_errors_without_consuming_the_rule() { + let unbound = Rule::new( + RuleMode::Require, + head(), + RegexExpr::test(TestExpr::atom( + Comparison::Eq, + AtomPattern::new(Component(0), ComponentPattern::variable("missing")), + )), + ); + assert_eq!( + flatten(&unbound), + Err(CompileError::UnboundVariable { + name: "missing".into() + }) + ); + let wrong_coordinate = Rule::new( + RuleMode::Require, + head(), + RegexExpr::test(TestExpr::atom( + Comparison::Eq, + AtomPattern::new(Component(2), ComponentPattern::variable("actor")), + )), + ); + assert_eq!( + flatten(&wrong_coordinate), + Err(CompileError::VariableComponentConflict { + name: "actor".into() + }) + ); + let conflicting_head = Rule::::new( + RuleMode::Require, + Head::new([ + ComponentPattern::variable("same"), + ComponentPattern::variable("same"), + ComponentPattern::variable("same"), + ]), + RegexExpr::empty(), + ); + assert_eq!( + flatten(&conflicting_head), + Err(CompileError::VariableComponentConflict { + name: "same".into() + }) + ); + assert_eq!(unbound.mode, RuleMode::Require); + assert_eq!(wrong_coordinate.head, head()); + unbound.dispose(); + wrong_coordinate.dispose(); + conflicting_head.dispose(); +} + +#[test] +fn flattening_keeps_empty_identities_complement_and_concat_source_order() { + use junco_core::flat::{FlatRegex, FlatTest}; + let rule = Rule::new( + RuleMode::Require, + head(), + RegexExpr::concat([ + RegexExpr::test(TestExpr::and([])), + RegexExpr::test(TestExpr::or([])), + RegexExpr::concat([]), + RegexExpr::union([]), + RegexExpr::intersect([]), + RegexExpr::complement(RegexExpr::epsilon()), + RegexExpr::star(RegexExpr::all()), + RegexExpr::empty(), + ]), + ); + let flat = flatten(&rule).unwrap(); + assert_eq!( + flat.source.tests, + vec![FlatTest::And(vec![]), FlatTest::Or(vec![])] + ); + assert_eq!( + flat.source.regexes, + vec![ + FlatRegex::Test(0), + FlatRegex::Test(1), + FlatRegex::Concat(vec![]), + FlatRegex::Union(vec![]), + FlatRegex::Intersect(vec![]), + FlatRegex::Epsilon, + FlatRegex::Complement(5), + FlatRegex::All, + FlatRegex::Star(7), + FlatRegex::Empty, + FlatRegex::Concat(vec![0, 1, 2, 3, 4, 6, 8, 9]), + ] + ); + assert_eq!(flat.source.root, 10); + assert_eq!(flat.source.validate(), Ok(())); + let ordered = Rule::new( + RuleMode::Require, + head(), + RegexExpr::concat([action(1), action(2)]), + ); + let reversed = Rule::new( + RuleMode::Require, + head(), + RegexExpr::concat([action(2), action(1)]), + ); + assert_ne!(flatten(&ordered).unwrap(), flatten(&reversed).unwrap()); +} + +#[test] +fn component_equality_uses_native_identity_not_representation() { + use core::hash::{Hash, Hasher}; + #[derive(Clone, Copy, Debug)] + struct Identity { + key: u8, + payload: u8, + } + impl PartialEq for Identity { + fn eq(&self, other: &Self) -> bool { + self.key == other.key + } + } + impl Eq for Identity {} + impl Hash for Identity { + fn hash(&self, state: &mut H) { + 0_u8.hash(state); + } + } + impl history_syntax::KeyHash for Identity { + fn key_hash(&self) -> u64 { + history_syntax::key_hash::hash_via_std(self) + } + } + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] + struct IdentityEvent(Identity); + impl Event for IdentityEvent { + type Component = Component3; + type Arity = N3; + fn component(self, index: usize) -> Self::Component { + match index { + 0 => Component3::C0(self.0), + 1 => Component3::C1(self.0), + _ => Component3::C2(self.0), + } + } + fn coordinate(component: Self::Component) -> usize { + match component { + Component3::C0(_) => 0, + Component3::C1(_) => 1, + Component3::C2(_) => 2, + } + } + } + let original = Identity { key: 7, payload: 1 }; + let equal = Identity { key: 7, payload: 2 }; + let unequal = Identity { key: 8, payload: 1 }; + assert_ne!(original.payload, equal.payload); + assert_eq!(IdentityEvent(original).component(0), Component3::C0(equal)); + assert_ne!( + IdentityEvent(original).component(0), + Component3::C0(unequal) + ); + assert_ne!( + IdentityEvent(original).component(0), + Component3::C2(original) + ); +} + +#[test] +fn deep_borrowed_lowering_keeps_success_and_failure_teardown_iterative() { + let mut valid = RegexExpr::epsilon(); + let mut invalid = RegexExpr::test(TestExpr::atom( + Comparison::Eq, + AtomPattern::new(Component(0), ComponentPattern::variable("missing")), + )); + for _ in 0..4096 { + valid = RegexExpr::complement(valid); + invalid = RegexExpr::star(invalid); + } + let valid = Rule::new(RuleMode::Require, head(), valid); + let invalid = Rule::new(RuleMode::Require, head(), invalid); + let flat = flatten(&valid).unwrap(); + assert_eq!(flat.source.regexes.len(), 4097); + assert_eq!(flat.source.root, 4096); + assert_eq!( + flatten(&invalid), + Err(CompileError::UnboundVariable { + name: "missing".into() + }) + ); + valid.dispose(); + invalid.dispose(); +} + +#[test] +fn lowering_propagates_resource_errors_without_consuming_source() { + use junco_core::limits::{LimitError, Limits}; + use junco_core::{HistoryError, flatten_rule}; + struct Exhausted; + impl Limits for Exhausted { + fn checkpoint(&mut self) -> Result<(), LimitError> { + Err(LimitError::MemoryLimitExceeded { usage: 2, limit: 1 }) + } + fn publication_checkpoint(&mut self) -> Result<(), LimitError> { + self.checkpoint() + } + fn enforce_memory(&mut self) -> Result<(), LimitError> { + self.checkpoint() + } + } + let rule = Rule::new(RuleMode::Require, head(), action(1)); + let result = flatten_rule( + &rule, + &mut Exhausted, + &mut junco_core::observation::ObservationWorld, + ); + assert_eq!( + result, + Err(CompileError::Runtime(HistoryError::Limit( + LimitError::MemoryLimitExceeded { usage: 2, limit: 1 } + ))) + ); + assert_eq!(rule.tail, action(1)); + rule.dispose(); +} + +#[test] +fn flattening_boolean_leaves_and_nested_operands_keep_postorder() { + use junco_core::flat::{FlatRegex, FlatTest}; + let rule = Rule::new( + RuleMode::Require, + head(), + RegexExpr::test(TestExpr::or([ + TestExpr::and([TestExpr::true_test(), TestExpr::false_test()]), + TestExpr::true_test(), + ])), + ); + let flat = flatten(&rule).unwrap(); + assert_eq!( + flat.source.tests, + vec![ + FlatTest::Bool(true), + FlatTest::Bool(false), + FlatTest::And(vec![0, 1]), + FlatTest::Bool(true), + FlatTest::Or(vec![2, 3]) + ] + ); + assert_eq!(flat.source.regexes, vec![FlatRegex::Test(4)]); + assert_eq!(flat.source.validate(), Ok(())); +} + +#[test] +fn flattening_rejects_a_head_with_the_wrong_arity() { + let rule = Rule::::new( + RuleMode::Require, + Head::new([ + ComponentPattern::variable("actor"), + ComponentPattern::variable("document"), + ]), + RegexExpr::epsilon(), + ); + assert_eq!( + flatten(&rule), + Err(CompileError::HeadArity { + expected: 3, + found: 2 + }) + ); + rule.dispose(); +} + +#[test] +fn flattening_rejects_a_head_constant_from_another_coordinate() { + let rule = Rule::::new( + RuleMode::Require, + Head::new([ + ComponentPattern::constant(Component3::C1(2)), + ComponentPattern::variable("operation"), + ComponentPattern::variable("document"), + ]), + RegexExpr::epsilon(), + ); + assert_eq!( + flatten(&rule), + Err(CompileError::ComponentCoordinate { + component: 0, + coordinate: 1 + }) + ); + rule.dispose(); +} diff --git a/src/junco-core/tests/encoding.rs b/src/junco-core/tests/encoding.rs new file mode 100644 index 000000000..34bc1d81c --- /dev/null +++ b/src/junco-core/tests/encoding.rs @@ -0,0 +1,345 @@ +use std::collections::HashMap; +use std::hash::{Hash, Hasher}; + +use history_syntax::{Component, Component3, Event, N3}; +use junco_core::HistoryError; +use junco_core::compile::{FlatEncoder, lower_flat, validate_component}; +use junco_core::flat::{FlatHead, FlatPair, FlatRegex, FlatTerm, FlatTest}; +use junco_core::limits::{LimitError, Limits, Unmetered}; +use junco_core::observation::ObservationWorld; + +// Deliberately neither Copy nor Clone: lowering must borrow stored constants. +#[derive(Debug)] +struct Value { + identity: u8, + payload: u8, +} + +impl PartialEq for Value { + fn eq(&self, other: &Self) -> bool { + self.identity == other.identity + } +} +impl Eq for Value {} +impl Hash for Value { + fn hash(&self, state: &mut H) { + 0u8.hash(state); + } +} + +fn value(identity: u8, payload: u8) -> Value { + Value { identity, payload } +} + +// A deterministic test fixture, not a production codebook implementation. +#[derive(Default)] +struct Encoder { + maps: [HashMap; 3], + calls: Vec<(Component, u8, u8)>, + fail_at: Option, +} + +impl FlatEncoder for Encoder { + fn encode(&mut self, field: Component, value: &Value) -> Result { + self.calls.push((field, value.identity, value.payload)); + if self.fail_at == Some(self.calls.len()) { + return Err(HistoryError::AllocationFailed); + } + let map = &mut self.maps[field.index()]; + if let Some(id) = map.get(value) { + return Ok(*id); + } + // Disjoint numeric ranges make an accidental coordinate mix-up observable. + let id = (field.index() as u64 + 1) * 100 + map.len() as u64 + 1; + map.insert( + Value { + identity: value.identity, + payload: value.payload, + }, + id, + ); + Ok(id) + } +} + +#[test] +fn custom_encoder_may_report_structural_errors() { + struct CustomEncoder; + impl FlatEncoder for CustomEncoder { + fn encode(&mut self, _: Component, _: &Value) -> Result { + Err(HistoryError::invariant("custom encoder failure")) + } + } + assert_eq!( + lower_flat( + &source(), + &mut CustomEncoder, + &mut Unmetered, + &mut ObservationWorld + ), + Err(HistoryError::invariant("custom encoder failure")), + ); +} + +fn source() -> FlatPair { + FlatPair { + head: vec![ + FlatHead::Constant(value(7, 1)), + FlatHead::Constant(value(7, 11)), + FlatHead::Bind, + ], + tests: vec![ + FlatTest::Atom { + field: Component(0), + term: FlatTerm::Constant(value(7, 2)), + positive: true, + }, + FlatTest::Atom { + field: Component(0), + term: FlatTerm::Constant(value(8, 3)), + positive: false, + }, + FlatTest::Atom { + field: Component(1), + term: FlatTerm::Constant(value(7, 12)), + positive: true, + }, + FlatTest::Atom { + field: Component(2), + term: FlatTerm::Variable(Component(2)), + positive: false, + }, + FlatTest::And(vec![0, 0, 1]), + FlatTest::Or(vec![]), + // Unreachable stored constants still pass through the single encoding pass. + FlatTest::Atom { + field: Component(2), + term: FlatTerm::Constant(value(7, 21)), + positive: true, + }, + ], + regexes: vec![ + FlatRegex::Epsilon, + FlatRegex::Test(4), + FlatRegex::Concat(vec![0, 0]), + FlatRegex::Complement(2), + FlatRegex::Star(3), + FlatRegex::Union(vec![1, 4, 1]), + FlatRegex::Intersect(vec![]), + ], + root: 5, + } +} + +#[test] +fn one_pass_preserves_equality_domains_and_exact_topology() { + let source = source(); + let mut encoder = Encoder::default(); + let numeric = lower_flat(&source, &mut encoder, &mut Unmetered, &mut ObservationWorld).unwrap(); + assert_eq!( + numeric.head, + vec![ + FlatHead::Constant(101), + FlatHead::Constant(201), + FlatHead::Bind + ] + ); + assert_eq!( + numeric.tests, + vec![ + FlatTest::Atom { + field: Component(0), + term: FlatTerm::Constant(101), + positive: true + }, + FlatTest::Atom { + field: Component(0), + term: FlatTerm::Constant(102), + positive: false + }, + FlatTest::Atom { + field: Component(1), + term: FlatTerm::Constant(201), + positive: true + }, + FlatTest::Atom { + field: Component(2), + term: FlatTerm::Variable(Component(2)), + positive: false + }, + FlatTest::And(vec![0, 0, 1]), + FlatTest::Or(vec![]), + FlatTest::Atom { + field: Component(2), + term: FlatTerm::Constant(301), + positive: true + }, + ] + ); + assert_eq!(numeric.regexes, source.regexes); + assert_eq!(numeric.root, 5); + assert_eq!( + encoder.calls, + vec![ + (Component(0), 7, 1), + (Component(1), 7, 11), + (Component(0), 7, 2), + (Component(0), 8, 3), + (Component(1), 7, 12), + (Component(2), 7, 21), + ] + ); + assert_eq!(encoder.maps[0].len(), 2); + assert_eq!(encoder.maps[1].len(), 1); + assert_eq!(encoder.maps[2].len(), 1); + match &source.head[0] { + FlatHead::Constant(value) => assert_eq!(value.payload, 1), + _ => panic!("source head changed"), + } +} + +#[test] +fn every_structural_failure_precedes_interning() { + for invalid in 0..6 { + let mut source = source(); + match invalid { + 0 => source.tests[0] = FlatTest::And(vec![0]), + 1 => source.regexes[0] = FlatRegex::Star(1), + 2 => source.regexes[0] = FlatRegex::Test(99), + 3 => source.root = 99, + 4 => { + source.tests[0] = FlatTest::Atom { + field: Component(0), + term: FlatTerm::Variable(Component(2)), + positive: true, + } + } + _ => { + source.tests[0] = FlatTest::Atom { + field: Component(0), + term: FlatTerm::Variable(Component(0)), + positive: true, + } + } + } + let mut encoder = Encoder::default(); + assert_eq!( + lower_flat(&source, &mut encoder, &mut Unmetered, &mut ObservationWorld), + Err(HistoryError::InvalidPolicy { + path: "$".into(), + message: "invalid portable history source" + }) + ); + assert!(encoder.calls.is_empty()); + assert!(encoder.maps.iter().all(HashMap::is_empty)); + } +} + +#[test] +fn failure_keeps_old_associations_and_later_values_do_not_renumber_constants() { + let mut encoder = Encoder::default(); + assert_eq!(encoder.encode(Component(0), &value(42, 0)), Ok(101)); + encoder.fail_at = Some(3); + assert_eq!( + lower_flat( + &source(), + &mut encoder, + &mut Unmetered, + &mut ObservationWorld + ), + Err(HistoryError::AllocationFailed) + ); + assert_eq!(encoder.maps[0].get(&value(42, 99)), Some(&101)); + assert_eq!(encoder.maps[0].get(&value(7, 99)), Some(&102)); + encoder.fail_at = None; + let numeric = lower_flat( + &source(), + &mut encoder, + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + let compiled = numeric.head[0].clone(); + assert_eq!(encoder.encode(Component(0), &value(99, 0)), Ok(104)); + assert_eq!(encoder.encode(Component(0), &value(7, 255)), Ok(102)); + assert_eq!(numeric.head[0], compiled); +} + +struct RejectMemory; +impl Limits for RejectMemory { + fn checkpoint(&mut self) -> Result<(), LimitError> { + Ok(()) + } + fn publication_checkpoint(&mut self) -> Result<(), LimitError> { + Ok(()) + } + fn enforce_memory(&mut self) -> Result<(), LimitError> { + Err(LimitError::MemoryLimitExceeded { usage: 2, limit: 1 }) + } +} + +#[test] +fn builder_limit_errors_remain_errors_and_keep_existing_encodings() { + let mut encoder = Encoder::default(); + assert_eq!(encoder.encode(Component(0), &value(7, 0)), Ok(101)); + let error = lower_flat( + &source(), + &mut encoder, + &mut RejectMemory, + &mut ObservationWorld, + ) + .unwrap_err(); + assert_eq!( + error, + HistoryError::Limit(LimitError::MemoryLimitExceeded { usage: 2, limit: 1 }) + ); + assert_eq!(encoder.maps[0].get(&value(7, 255)), Some(&101)); +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] +struct Product; +impl Event for Product { + type Component = Component3; + type Arity = N3; + fn component(self, index: usize) -> Self::Component { + match index { + 0 => Component3::C0(1), + 1 => Component3::C1(2), + _ => Component3::C2(3), + } + } + fn coordinate(component: Self::Component) -> usize { + match component { + Component3::C0(_) => 0, + Component3::C1(_) => 1, + Component3::C2(_) => 2, + } + } +} + +#[test] +fn typed_constants_reject_every_mismatched_coordinate() { + let values = [ + Component3::::C0(7), + Component3::C1(7), + Component3::C2(7), + ]; + for (field_index, field) in [Component(0), Component(1), Component(2)] + .into_iter() + .enumerate() + { + for (value_index, value) in values.iter().enumerate() { + if field_index == value_index { + assert_eq!(validate_component::(field, value), Ok(())); + } else { + assert_eq!( + validate_component::(field, value), + Err(HistoryError::InvalidPolicy { + path: "$".into(), + message: "constant belongs to another component", + }) + ); + } + } + } +} diff --git a/src/junco-core/tests/flat.rs b/src/junco-core/tests/flat.rs new file mode 100644 index 000000000..4a73f2b4b --- /dev/null +++ b/src/junco-core/tests/flat.rs @@ -0,0 +1,468 @@ +use history_syntax::{Component, RuleMode}; +use junco_core::HistoryError; +use junco_core::flat::{FlatBuilder, FlatHead, FlatPair, FlatRegex, FlatRule, FlatTerm, FlatTest}; +use junco_core::limits::{LimitError, Limits, Unmetered}; +use junco_core::observation::ObservationWorld; + +fn pair() -> FlatPair { + FlatPair { + head: vec![FlatHead::Any, FlatHead::Any, FlatHead::Any], + tests: Vec::new(), + regexes: vec![FlatRegex::Epsilon], + root: 0, + } +} + +#[test] +fn rejects_forward_cycles_and_missing_tests() { + let mut source = pair::(); + assert_eq!(source.validate(), Ok(())); + source.regexes = vec![FlatRegex::Star(0)]; + assert!(source.validate().is_err()); + source.regexes = vec![FlatRegex::Test(0)]; + assert!(source.validate().is_err()); + source.tests = vec![FlatTest::And(vec![0])]; + assert!(source.validate().is_err()); + source.tests = vec![FlatTest::Bool(true)]; + assert_eq!(source.validate(), Ok(())); + source.root = 1; + assert!(source.validate().is_err()); +} + +#[test] +fn rejects_cross_domain_and_unbound_variables() { + let mut source = pair::(); + source.tests.push(FlatTest::Atom { + field: Component(1), + term: FlatTerm::Variable(Component(0)), + positive: true, + }); + assert!(source.validate().is_err()); + source.tests.clear(); + source.tests.push(FlatTest::Atom { + field: Component(0), + term: FlatTerm::Variable(Component(0)), + positive: false, + }); + assert!(source.validate().is_err()); + source.head[0] = FlatHead::Bind; + assert_eq!(source.validate(), Ok(())); +} + +#[test] +fn validation_preserves_exact_errors_and_precedence() { + let mut source = pair::<()>(); + source.root = u32::MAX; + source.regexes = vec![FlatRegex::Test(u32::MAX)]; + source.tests = vec![FlatTest::Or(vec![0])]; + assert_eq!( + source.validate().unwrap_err(), + "history test reference must point to an earlier node" + ); + source.tests = vec![FlatTest::Atom { + field: Component(2), + term: FlatTerm::Variable(Component(2)), + positive: true, + }]; + assert_eq!( + source.validate().unwrap_err(), + "history variable must bind its own head domain" + ); + source.head[2] = FlatHead::Bind; + assert_eq!( + source.validate().unwrap_err(), + "history regex test reference is out of bounds" + ); + source.regexes = vec![FlatRegex::Complement(1), FlatRegex::Star(0)]; + assert_eq!( + source.validate().unwrap_err(), + "history regex reference must point to an earlier node" + ); + source.regexes = vec![FlatRegex::Epsilon]; + assert_eq!( + source.validate().unwrap_err(), + "history regex root is out of bounds" + ); +} + +#[test] +fn checks_every_reference_variant() { + for test in [FlatTest::<()>::And(vec![1]), FlatTest::Or(vec![u32::MAX])] { + let mut source = pair(); + source.tests = vec![test, FlatTest::Bool(true)]; + assert_eq!( + source.validate().unwrap_err(), + "history test reference must point to an earlier node" + ); + } + for regex in [ + FlatRegex::Concat(vec![1]), + FlatRegex::Union(vec![u32::MAX]), + FlatRegex::Intersect(vec![0]), + FlatRegex::Star(0), + FlatRegex::Complement(1), + ] { + let mut source = pair::<()>(); + source.regexes = vec![regex, FlatRegex::Epsilon]; + assert_eq!( + source.validate().unwrap_err(), + "history regex reference must point to an earlier node" + ); + } + for field in [Component(0), Component(1), Component(2)] { + for variable in [Component(0), Component(1), Component(2)] { + let mut source = pair::<()>(); + source.head = vec![FlatHead::Bind, FlatHead::Bind, FlatHead::Bind]; + source.tests = vec![FlatTest::Atom { + field, + term: FlatTerm::Variable(variable), + positive: false, + }]; + assert_eq!(source.validate().is_ok(), field == variable); + } + } +} + +#[test] +fn accepts_repeated_edges_unused_nodes_and_non_last_root() { + let source = FlatPair::<()> { + head: vec![FlatHead::Any, FlatHead::Bind, FlatHead::Any], + tests: vec![ + FlatTest::Bool(true), + FlatTest::And(vec![0, 0]), + FlatTest::Or(vec![0, 1, 0]), + ], + regexes: vec![ + FlatRegex::Epsilon, + FlatRegex::Concat(vec![0, 0]), + FlatRegex::Union(vec![0, 1, 0]), + FlatRegex::Test(2), + FlatRegex::Intersect(vec![0, 1]), + FlatRegex::Star(4), + FlatRegex::Complement(5), + ], + root: 1, + }; + assert_eq!(source.validate(), Ok(())); + assert_eq!(source.regexes.len(), 7); + assert_eq!(source.regexes[1], FlatRegex::Concat(vec![0, 0])); +} + +#[test] +fn empty_operators_and_generic_constants_need_no_runtime_or_equality() { + struct Opaque; + let source = FlatPair { + head: vec![FlatHead::Constant(Opaque), FlatHead::Any, FlatHead::Bind], + tests: vec![ + FlatTest::And(vec![]), + FlatTest::Or(vec![]), + FlatTest::Atom { + field: Component(1), + term: FlatTerm::Constant(Opaque), + positive: false, + }, + ], + regexes: vec![ + FlatRegex::Empty, + FlatRegex::All, + FlatRegex::Epsilon, + FlatRegex::Concat(vec![]), + FlatRegex::Union(vec![]), + FlatRegex::Intersect(vec![]), + ], + root: 3, + }; + assert_eq!(source.validate(), Ok(())); + let rule = FlatRule { + mode: RuleMode::Require, + source, + }; + assert_eq!(rule.mode, RuleMode::Require); + let empty = FlatPair:: { + regexes: vec![], + ..pair() + }; + assert_eq!( + empty.validate().unwrap_err(), + "history regex root is out of bounds" + ); +} + +#[derive(Default)] +struct ProbeLimits { + fail_checkpoint: bool, + fail_memory: bool, +} + +impl Limits for ProbeLimits { + fn checkpoint(&mut self) -> Result<(), LimitError> { + if self.fail_checkpoint { + Err(LimitError::RegexSizeLimitExceeded { limit: 0 }) + } else { + Ok(()) + } + } + + fn publication_checkpoint(&mut self) -> Result<(), LimitError> { + panic!("flat construction must not publish a decision") + } + + fn enforce_memory(&mut self) -> Result<(), LimitError> { + if self.fail_memory { + Err(LimitError::MemoryLimitExceeded { usage: 1, limit: 0 }) + } else { + Ok(()) + } + } +} + +#[test] +fn builder_preserves_supplied_topology_and_allows_any_valid_root() { + let mut builder = FlatBuilder::<()>::new(vec![FlatHead::Any, FlatHead::Any, FlatHead::Any]); + let mut limits = ProbeLimits::default(); + let mut world = ObservationWorld; + assert_eq!( + builder.test(FlatTest::Bool(true), &mut limits, &mut world), + Ok(0) + ); + assert_eq!( + builder.test(FlatTest::And(vec![0, 0]), &mut limits, &mut world), + Ok(1) + ); + assert_eq!( + builder.regex(FlatRegex::Epsilon, &mut limits, &mut world), + Ok(0) + ); + assert_eq!( + builder.regex(FlatRegex::Concat(vec![0, 0]), &mut limits, &mut world), + Ok(1) + ); + assert_eq!( + builder.regex(FlatRegex::Test(1), &mut limits, &mut world), + Ok(2) + ); + let source = builder.finish(1).unwrap(); + assert_eq!(source.validate(), Ok(())); + assert_eq!( + source.tests, + vec![FlatTest::Bool(true), FlatTest::And(vec![0, 0])] + ); + assert_eq!( + source.regexes, + vec![ + FlatRegex::Epsilon, + FlatRegex::Concat(vec![0, 0]), + FlatRegex::Test(1) + ] + ); +} + +#[test] +fn builder_rejects_bad_nodes_without_mutating_prefixes() { + let mut builder = FlatBuilder::<()>::new(vec![FlatHead::Any, FlatHead::Bind, FlatHead::Any]); + let mut limits = Unmetered; + let mut world = ObservationWorld; + let invalid = HistoryError::InvalidPolicy { + path: "$".into(), + message: "invalid portable history source", + }; + for node in [ + FlatTest::And(vec![0]), + FlatTest::Or(vec![u32::MAX]), + FlatTest::Atom { + field: Component(1), + term: FlatTerm::Variable(Component(0)), + positive: true, + }, + FlatTest::Atom { + field: Component(2), + term: FlatTerm::Variable(Component(2)), + positive: false, + }, + ] { + assert_eq!( + builder.test(node, &mut limits, &mut world), + Err(invalid.clone()) + ); + assert!(builder.tests().is_empty()); + assert!(builder.regexes().is_empty()); + assert_eq!( + builder.head(), + &[FlatHead::Any, FlatHead::Bind, FlatHead::Any] + ); + } + for node in [ + FlatRegex::Test(0), + FlatRegex::Concat(vec![0]), + FlatRegex::Union(vec![1]), + FlatRegex::Intersect(vec![0]), + FlatRegex::Star(0), + FlatRegex::Complement(0), + ] { + assert_eq!( + builder.regex(node, &mut limits, &mut world), + Err(invalid.clone()) + ); + assert!(builder.tests().is_empty()); + assert!(builder.regexes().is_empty()); + } + assert_eq!( + builder.test( + FlatTest::Atom { + field: Component(1), + term: FlatTerm::Variable(Component(1)), + positive: true, + }, + &mut limits, + &mut world + ), + Ok(0) + ); + assert_eq!( + builder.regex(FlatRegex::Test(0), &mut limits, &mut world), + Ok(0) + ); + assert_eq!(builder.finish(1), Err(invalid)); +} + +#[test] +fn builder_limit_failures_preserve_all_existing_nodes() { + let mut builder = FlatBuilder::<()>::new(vec![FlatHead::Any, FlatHead::Any, FlatHead::Any]); + let mut limits = ProbeLimits::default(); + let mut world = ObservationWorld; + builder + .test(FlatTest::Bool(true), &mut limits, &mut world) + .unwrap(); + builder + .regex(FlatRegex::Epsilon, &mut limits, &mut world) + .unwrap(); + for checkpoint in [true, false] { + limits.fail_checkpoint = checkpoint; + limits.fail_memory = !checkpoint; + assert!(matches!( + builder.test(FlatTest::Or(vec![0]), &mut limits, &mut world), + Err(HistoryError::Limit(_)) + )); + assert!(matches!( + builder.regex(FlatRegex::Star(0), &mut limits, &mut world), + Err(HistoryError::Limit(_)) + )); + assert_eq!(builder.tests(), &vec![FlatTest::Bool(true)]); + assert_eq!(builder.regexes(), &vec![FlatRegex::Epsilon]); + } + limits.fail_checkpoint = false; + limits.fail_memory = false; + assert_eq!( + builder.test(FlatTest::And(vec![0, 0]), &mut limits, &mut world), + Ok(1) + ); + assert_eq!( + builder.regex(FlatRegex::Concat(vec![0, 0]), &mut limits, &mut world), + Ok(1) + ); + assert_eq!(builder.finish(0).unwrap().validate(), Ok(())); +} + +#[test] +fn deep_shared_dag_stays_flat() { + let mut builder = FlatBuilder::<()>::new(vec![FlatHead::Any, FlatHead::Any, FlatHead::Any]); + let mut limits = Unmetered; + let mut world = ObservationWorld; + builder + .regex(FlatRegex::Epsilon, &mut limits, &mut world) + .unwrap(); + for index in 1..4096 { + assert_eq!( + builder.regex( + FlatRegex::Concat(vec![index - 1, index - 1]), + &mut limits, + &mut world + ), + Ok(index) + ); + } + let source = builder.finish(4095).unwrap(); + assert_eq!(source.validate(), Ok(())); + assert_eq!(source.regexes.len(), 4096); + assert_eq!( + source + .regexes + .iter() + .map(|node| match node { + FlatRegex::Concat(ids) => ids.len(), + _ => 0, + }) + .sum::(), + 8190 + ); +} + +#[cfg(feature = "serde")] +#[test] +fn serde_keeps_version_nine_names_variant_order_and_field_order() { + let source = FlatPair { + head: vec![ + FlatHead::Any, + FlatHead::Constant(String::from("x")), + FlatHead::Bind, + ], + tests: vec![ + FlatTest::Bool(true), + FlatTest::Atom { + field: Component(1), + term: FlatTerm::Constant(String::from("a")), + positive: false, + }, + FlatTest::And(vec![0, 1]), + FlatTest::Or(vec![]), + ], + regexes: vec![ + FlatRegex::Empty, + FlatRegex::All, + FlatRegex::Epsilon, + FlatRegex::Test(1), + FlatRegex::Concat(vec![2, 3]), + FlatRegex::Union(vec![]), + FlatRegex::Intersect(vec![]), + FlatRegex::Star(4), + FlatRegex::Complement(7), + ], + root: 3, + }; + assert_eq!(source.validate(), Ok(())); + let json = r#"{"head":["Any",{"Constant":"x"},"Bind"],"tests":[{"Bool":true},{"Atom":{"field":1,"term":{"Constant":"a"},"positive":false}},{"And":[0,1]},{"Or":[]}],"regexes":["Empty","All","Epsilon",{"Test":1},{"Concat":[2,3]},{"Union":[]},{"Intersect":[]},{"Star":4},{"Complement":7}],"root":3}"#; + assert_eq!(serde_json::to_string(&source).unwrap(), json); + assert_eq!( + serde_json::from_str::>(json).unwrap(), + source + ); + // Literal version-9 bytes, including the head length and numeric coordinate. + let bytes = [ + 3, 0, 1, 1, b'x', 2, 4, 0, 1, 1, 1, 0, 1, b'a', 0, 2, 2, 0, 1, 3, 0, 9, 0, 1, 2, 3, 1, 4, + 2, 2, 3, 5, 0, 6, 0, 7, 4, 8, 7, 3, + ]; + assert_eq!(postcard::to_allocvec(&source).unwrap(), bytes); + assert_eq!( + postcard::from_bytes::>(&bytes).unwrap(), + source + ); + for (field, ordinal) in [(Component(0), 0), (Component(1), 1), (Component(2), 2)] { + assert_eq!( + postcard::to_allocvec(&FlatTerm::::Variable(field)).unwrap(), + vec![1, ordinal] + ); + } + for (mode, ordinal) in [(RuleMode::Require, 0), (RuleMode::Forbid, 1)] { + let rule = FlatRule { + mode, + source: source.clone(), + }; + let mut expected = vec![ordinal]; + expected.extend_from_slice(&bytes); + assert_eq!(postcard::to_allocvec(&rule).unwrap(), expected); + assert_eq!( + postcard::from_bytes::>(&expected).unwrap(), + rule + ); + } +} diff --git a/src/languages/history_table/limits.rs b/src/languages/history_table/limits.rs new file mode 100644 index 000000000..bc2e2bf10 --- /dev/null +++ b/src/languages/history_table/limits.rs @@ -0,0 +1,50 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +use crate::utils::limits::{ + check_memory_limit_if_needed, enforce_memory_limit, monotonic_now, ExecutionTimer, LimitError, +}; +use junco_core::limits::Limits; +use vstd::prelude::*; + +#[verus_verify] +pub struct RegorusLimits<'a> { + pub(crate) timer: &'a mut ExecutionTimer, +} + +#[verus_verify] +impl RegorusLimits<'_> { + #[cold] + #[inline(never)] + fn deadline_check(&mut self) -> Result<(), LimitError> { + if let Some(now) = monotonic_now() { + self.timer.check_now(now)?; + } + Ok(()) + } +} + +#[verus_verify] +impl Limits for RegorusLimits<'_> { + #[inline(always)] + fn checkpoint(&mut self) -> Result<(), LimitError> { + if self.timer.accumulate(1) { + self.deadline_check()?; + } + check_memory_limit_if_needed()?; + Ok(()) + } + + fn publication_checkpoint(&mut self) -> Result<(), LimitError> { + if self.timer.config().is_some() { + if let Some(now) = monotonic_now() { + self.timer.check_now(now)?; + } + } + self.checkpoint() + } + + fn enforce_memory(&mut self) -> Result<(), LimitError> { + enforce_memory_limit() + } +} diff --git a/src/languages/history_table/mod.rs b/src/languages/history_table/mod.rs new file mode 100644 index 000000000..2e0f23db8 --- /dev/null +++ b/src/languages/history_table/mod.rs @@ -0,0 +1,162 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Rego history rules (`history.require`/`history.forbid`) lowered by the RVM +//! compiler onto one process-wide typed store; this module owns the store +//! facade, limits adapter and portable-source lowering. + +pub(crate) mod limits; +pub(crate) mod store; + +pub use history_syntax::Component; +pub use junco_core::HistoryError; +pub use store::{Event, HistoryHandle, HistoryStore}; + +use crate::rvm::program::HistoryTableRule; +use crate::utils::limits::ExecutionTimer; +use alloc::string::String; +use alloc::vec::Vec; +use junco_core::flat::{FlatHead, FlatPair, FlatTerm, FlatTest}; +use junco_core::limits::Limits as _; +use junco_core::observation::ObservationWorld; +use junco_core::CompileError; + +/// Principal coordinate of store events. +pub const PRINCIPAL: Component = Component(0); +/// Action coordinate of store events. +pub const ACTION: Component = Component(1); +/// Resource coordinate of store events. +pub const RESOURCE: Component = Component(2); + +/// Borrowed-string authoring event of a lowered Rego history rule. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) struct SourceEvent<'a> { + pub(crate) principal: &'a str, + pub(crate) action: &'a str, + pub(crate) resource: &'a str, +} + +/// Tagged coordinate of a [`SourceEvent`]; constants in rules carry their coordinate. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) enum SourceComponent<'a> { + Principal(&'a str), + Action(&'a str), + Resource(&'a str), +} + +impl history_syntax::KeyHash for SourceComponent<'_> { + fn key_hash(&self) -> u64 { + history_syntax::key_hash::hash_via_std(self) + } +} + +impl<'a> history_syntax::Event for SourceEvent<'a> { + type Component = SourceComponent<'a>; + type Arity = history_syntax::N3; + + fn component(self, index: usize) -> SourceComponent<'a> { + match index { + 0 => SourceComponent::Principal(self.principal), + 1 => SourceComponent::Action(self.action), + _ => SourceComponent::Resource(self.resource), + } + } + + fn coordinate(component: SourceComponent<'a>) -> usize { + match component { + SourceComponent::Principal(_) => 0, + SourceComponent::Action(_) => 1, + SourceComponent::Resource(_) => 2, + } + } +} + +/// Flatten one borrowed rule and copy its constants into a store-independent table rule. +pub(crate) fn table_rule( + rule: &history_syntax::Rule>, +) -> Result { + let mut timer = ExecutionTimer::new(None); + let mut limits = limits::RegorusLimits { timer: &mut timer }; + let mut world = ObservationWorld; + let flat = junco_core::flatten_rule(rule, &mut limits, &mut world)?; + let source = into_portable_source(flat.source, &mut limits, &mut world) + .map_err(CompileError::Runtime)?; + Ok(HistoryTableRule { + mode: flat.mode, + source, + }) +} + +/// Copy borrowed constants into a store-independent source, moving every other table unchanged. +fn into_portable_source( + source: FlatPair>, + limits: &mut limits::RegorusLimits<'_>, + world: &mut ObservationWorld, +) -> Result, HistoryError> { + let FlatPair { + head, + tests, + regexes, + root, + } = source; + let mut owned_head = Vec::new(); + world + .try_reserve_vec_exact(&mut owned_head, head.len()) + .map_err(|_| HistoryError::AllocationFailed)?; + limits.enforce_memory()?; + for slot in head { + owned_head.push(match slot { + FlatHead::Any => FlatHead::Any, + FlatHead::Bind => FlatHead::Bind, + FlatHead::Constant(value) => FlatHead::Constant(own_constant(value, limits)?), + }); + } + let mut owned = Vec::new(); + world + .try_reserve_vec_exact(&mut owned, tests.len()) + .map_err(|_| HistoryError::AllocationFailed)?; + limits.enforce_memory()?; + for test in tests { + limits.checkpoint()?; + owned.push(match test { + FlatTest::Bool(value) => FlatTest::Bool(value), + FlatTest::Atom { + field, + term, + positive, + } => FlatTest::Atom { + field, + term: match term { + FlatTerm::Constant(value) => FlatTerm::Constant(own_constant(value, limits)?), + FlatTerm::Variable(variable) => FlatTerm::Variable(variable), + }, + positive, + }, + FlatTest::And(children) => FlatTest::And(children), + FlatTest::Or(children) => FlatTest::Or(children), + }); + } + Ok(FlatPair { + head: owned_head, + tests: owned, + regexes, + root, + }) +} + +/// Copy one constant's exact bytes into an owned string; flattening already checked its coordinate. +fn own_constant( + value: SourceComponent<'_>, + limits: &mut limits::RegorusLimits<'_>, +) -> Result { + let (SourceComponent::Principal(text) + | SourceComponent::Action(text) + | SourceComponent::Resource(text)) = value; + let mut owned = String::new(); + owned + .try_reserve_exact(text.len()) + .map_err(|_| HistoryError::AllocationFailed)?; + limits.enforce_memory()?; + owned.push_str(text); + Ok(owned) +} diff --git a/src/languages/history_table/store.rs b/src/languages/history_table/store.rs new file mode 100644 index 000000000..749842a5a --- /dev/null +++ b/src/languages/history_table/store.rs @@ -0,0 +1,427 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +//! Core-owned byte identities and histories with the shared Program-keyed graph cache. + +#![allow(clippy::redundant_pub_crate)] + +use super::limits::RegorusLimits; +use super::HistoryError; +use crate::rvm::program::Program; +use crate::utils::limits::ExecutionTimer; +use alloc::string::String; +use alloc::sync::Arc; +use alloc::vec::Vec; +use history_semantics::runtime::RuleRuntime; +pub use history_store::store::{Event, HistoryHandle}; +use history_store::store::{HistoryRecord, HistoryStore as CoreHistoryStore}; +use history_syntax::{Component, RuleMode}; +use junco_core::compile::{lower_flat, FlatEncoder}; +use junco_core::flat::FlatPair; +use junco_core::limits::Limits as _; +use junco_core::observation::ObservationWorld; +#[cfg(feature = "std")] +use parking_lot::Mutex; +#[cfg(not(feature = "std"))] +use spin::Mutex; +use vstd::prelude::*; + +const HISTORY_CACHE_CAPACITY: usize = 16; +/// Coordinates per event: principal, action, resource. +const ARITY: usize = 3; + +/// A Program-keyed table cache over the process-wide arity-3 history store. Identities and +/// histories are shared by every wrapper; wrapper construction is not an isolation boundary. +#[cfg_attr(not(verus_keep_ghost), derive(Debug))] +pub struct HistoryStore { + core: Arc, + tables: Mutex>, +} + +impl Default for HistoryStore { + fn default() -> Self { + Self { + core: CoreHistoryStore::new(ARITY), + tables: Mutex::new(Vec::new()), + } + } +} + +/// A retained program Arc prevents pointer identity from being reused while cached. +#[derive(Debug)] +struct TableCacheEntry { + program: Arc, + table: usize, + runtime: Arc, +} + +#[derive(Debug)] +pub(crate) struct HistoryTableRuntime { + pub(crate) rules: Vec, +} + +#[derive(Debug)] +pub(crate) struct HistoryRuleSlot { + pub(crate) mode: RuleMode, + pub(crate) template: FlatPair, + pub(crate) current: Mutex>>, +} + +impl HistoryRuleSlot { + /// Replace only the exhausted generation; other callers may already have won. + pub(crate) fn replace( + &self, + exhausted: &Arc>, + replacement: Arc>, + ) -> Arc> { + let mut current = self.current.lock(); + if Arc::ptr_eq(¤t, exhausted) { + // Residual IDs belong to one graph; a replacement replays from its new root. + *current = replacement; + } + Arc::clone(¤t) + } +} + +// Only external encoding accesses the native store; its internals carry no ghost model. +#[verus_verify(external_body)] +struct ByteEncoder<'a> { + store: &'a HistoryStore, +} + +verus! { +impl FlatEncoder for ByteEncoder<'_> { + open spec fn equality() -> junco_core::verify::encoding::Equality { + |_, left: String, right: String| left@ == right@ + } + open spec fn domain() -> junco_core::verify::encoding::Domain { + |_, _| true + } + open spec fn maps(&self) -> junco_core::verify::encoding::Codebook { + Seq::empty() + } + // Native byte-store locking/encoding is not a blanket proof opt-in. + open spec fn obeys_encoding_spec(&self) -> bool { false } + open spec fn encoding_calls(&self) -> nat { 0 } + #[verifier::prophetic] + open spec fn restoration(&self) -> (junco_core::verify::encoding::Codebook, bool) { + (Seq::empty(), false) + } + + // The byte interner stays in core; this native adapter routes each coordinate to its domain. + #[verifier::external_body] + fn encode(&mut self, field: Component, value: &String) -> Result { + self.store.intern(field, value) + } +} +} + +impl HistoryStore { + /// Create an empty table cache over the process-wide identities and histories. + pub fn new() -> Self { + Self::default() + } + + /// Intern the complete UTF-8 bytes of one coordinate without normalization or prefix matching. + pub fn intern(&self, component: Component, path: &str) -> Result { + self.core.intern( + component, + path.as_bytes(), + &mut RegorusLimits { + timer: &mut ExecutionTimer::new(None), + }, + &mut ObservationWorld, + ) + } + + /// Build a validated event from one interned ID per coordinate (`[principal, action, resource]`). + pub fn event(&self, slots: &[u64]) -> Result { + self.core.event(slots) + } + + pub(crate) fn table_runtime( + &self, + program: &Arc, + table: usize, + ) -> Result, HistoryError> { + { + let mut tables = self.tables.lock(); + if let Some(position) = tables + .iter() + .position(|entry| Arc::ptr_eq(&entry.program, program) && entry.table == table) + { + let entry = tables.remove(position); + let runtime = Arc::clone(&entry.runtime); + tables.insert(0, entry); + return Ok(runtime); + } + } + let source = program + .history_tables + .get(table) + .ok_or(HistoryError::Invariant { + message: "invalid history table index", + })?; + let mut rules = Vec::new(); + rules + .try_reserve_exact(source.rules.len()) + .map_err(|_| HistoryError::AllocationFailed)?; + let mut timer = ExecutionTimer::new(None); + let mut limits = RegorusLimits { timer: &mut timer }; + let mut world = ObservationWorld; + for rule in &source.rules { + // Deserialized programs may carry any validated arity; bindings would silently skip it. + if rule.source.head.len() != self.core.arity() { + return Err(HistoryError::invalid_policy( + "head", + "history head arity does not match the store", + )); + } + let template = lower_flat( + &rule.source, + &mut ByteEncoder { store: self }, + &mut limits, + &mut world, + )?; + let runtime = RuleRuntime::new(&self.core, &template, true, &mut limits, &mut world)?; + rules.push(HistoryRuleSlot { + mode: rule.mode, + template, + current: Mutex::new(Arc::new(Mutex::new(runtime))), + }); + } + let runtime = Arc::new(HistoryTableRuntime { rules }); + limits.enforce_memory()?; + let mut tables = self.tables.lock(); + // Compilation ran unlocked; another caller may already have populated this entry. + if let Some(position) = tables + .iter() + .position(|entry| Arc::ptr_eq(&entry.program, program) && entry.table == table) + { + let entry = tables.remove(position); + let cached = Arc::clone(&entry.runtime); + tables.insert(0, entry); + return Ok(cached); + } + if tables.len() < HISTORY_CACHE_CAPACITY { + tables + .try_reserve(1) + .map_err(|_| HistoryError::AllocationFailed)?; + } + limits.enforce_memory()?; + if tables.len() >= HISTORY_CACHE_CAPACITY { + tables.pop(); + } + tables.insert( + 0, + TableCacheEntry { + program: Arc::clone(program), + table, + runtime: Arc::clone(&runtime), + }, + ); + Ok(runtime) + } + + /// Create a history kept alive by its handles and read-only records. + pub fn new_history(self: &Arc) -> Result { + self.core.new_history( + &mut RegorusLimits { + timer: &mut ExecutionTimer::new(None), + }, + &mut ObservationWorld, + ) + } + + pub(crate) fn validate_event(&self, event: &Event) -> Result<(), HistoryError> { + self.core.validate_event(event) + } + + pub(crate) fn history_record( + &self, + history: &HistoryHandle, + ) -> Result { + self.core.history_record(history) + } + + /// Atomically append validated events, preserving the history revision. + pub fn append(&self, history: &HistoryHandle, events: &[Event]) -> Result<(), HistoryError> { + self.core.append( + history, + events, + &mut RegorusLimits { + timer: &mut ExecutionTimer::new(None), + }, + &mut ObservationWorld, + ) + } + + /// Remove a suffix, invalidating prior snapshots only when events are removed. + pub fn truncate(&self, history: &HistoryHandle, len: usize) -> Result<(), HistoryError> { + self.core.truncate(history, len) + } + + /// Return the current event count after verifying ownership. + pub fn len(&self, history: &HistoryHandle) -> Result { + self.core.len(history) + } +} + +#[cfg(test)] +mod tests { + #![allow( + clippy::unwrap_used, + clippy::indexing_slicing, + clippy::arithmetic_side_effects + )] + + use super::super::{ACTION, PRINCIPAL, RESOURCE}; + use super::*; + use alloc::collections::BTreeSet; + + fn event(store: &HistoryStore) -> Event { + store + .event(&[ + store.intern(PRINCIPAL, "alice").unwrap(), + store.intern(ACTION, "edit").unwrap(), + store.intern(RESOURCE, "doc").unwrap(), + ]) + .unwrap() + } + + #[test] + fn exact_identities_and_large_domain() { + let store = HistoryStore::new(); + let paths = ["a", "A", "/a", "a/", "a\0", "é", "e\u{301}"]; + let mut ids = BTreeSet::new(); + for path in paths { + let id = store.intern(PRINCIPAL, path).unwrap(); + assert_eq!(id, store.intern(PRINCIPAL, path).unwrap()); + assert!(ids.insert(id)); + } + let first = store.intern(RESOURCE, "common/prefix/0").unwrap(); + let mut resources = BTreeSet::from([first]); + for index in 1..5000 { + assert!(resources.insert( + store + .intern(RESOURCE, &alloc::format!("common/prefix/{index}")) + .unwrap() + )); + } + assert_eq!(first, store.intern(RESOURCE, "common/prefix/0").unwrap()); + assert_eq!(resources.len(), 5000); + let action = store.intern(ACTION, "a").unwrap(); + store.intern(PRINCIPAL, "new").unwrap(); + assert_eq!(action, store.intern(ACTION, "a").unwrap()); + let long = "x".repeat(4096); + assert_ne!( + store.intern(RESOURCE, &long).unwrap(), + store.intern(RESOURCE, &(long + "/")).unwrap() + ); + } + + fn typed_only_event() -> Event { + #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] + struct Typed; + impl history_syntax::Event for Typed { + type Component = history_syntax::Component3<(), (), ()>; + type Arity = history_syntax::N3; + fn component(self, index: usize) -> Self::Component { + match index { + 0 => history_syntax::Component3::C0(()), + 1 => history_syntax::Component3::C1(()), + _ => history_syntax::Component3::C2(()), + } + } + fn coordinate(component: Self::Component) -> usize { + match component { + history_syntax::Component3::C0(()) => 0, + history_syntax::Component3::C1(()) => 1, + history_syntax::Component3::C2(()) => 2, + } + } + } + let store = Arc::new(history_store::Store::::new().unwrap()); + let history = history_store::History::from_events(store, [Typed]).unwrap(); + history.numeric().as_slice()[0] + } + + #[test] + fn ownership_atomic_append_and_revisions() { + let store = Arc::new(HistoryStore::new()); + let peer = Arc::new(HistoryStore::new()); + let history = store.new_history().unwrap(); + let valid = event(&store); + // Wrappers are caches over one process-wide identity and history store. + assert_eq!(event(&peer), valid); + peer.append(&history, &[]).unwrap(); + assert_eq!(peer.len(&history).unwrap(), 0); + let typed = typed_only_event(); + // Event fields are private: each typed-only coordinate is rejected while building. + for index in 0..3 { + let mut slots = [valid.component(0), valid.component(1), valid.component(2)]; + slots[index] = typed.component(index); + assert!(matches!( + store.event(&slots), + Err(HistoryError::UnknownId { domain: "component", id }) if id == typed.component(index) + )); + } + assert!(matches!( + store.append(&history, &[valid, typed]), + Err(HistoryError::UnknownId { + domain: "component", + .. + }) + )); + assert!(matches!( + peer.validate_event(&typed), + Err(HistoryError::UnknownId { + domain: "component", + .. + }) + )); + assert_eq!(store.len(&history).unwrap(), 0); + // Generic interning stays within the arity-3 store. + assert!(matches!( + store.intern(Component(3), "x"), + Err(HistoryError::InvalidPolicy { .. }) + )); + assert!(matches!( + store.event(&[valid.component(0), valid.component(1)]), + Err(HistoryError::InvalidPolicy { .. }) + )); + store.append(&history, &[valid, valid]).unwrap(); + assert_eq!(store.len(&history.clone()).unwrap(), 2); + let record = store.history_record(&history).unwrap(); + assert_eq!(record.read().revision(), 0); + store.truncate(&history, 3).unwrap(); + store.truncate(&history, 2).unwrap(); + assert_eq!(record.read().revision(), 0); + store.truncate(&history, 1).unwrap(); + assert_eq!(record.read().revision(), 1); + } + + #[cfg(feature = "std")] + #[test] + fn synchronized_interning_shares_one_identity() { + fn assert_send_sync() {} + assert_send_sync::(); + let store = Arc::new(HistoryStore::new()); + let barrier = Arc::new(std::sync::Barrier::new(8)); + let threads: Vec<_> = (0..8) + .map(|_| { + let store = Arc::clone(&store); + let barrier = Arc::clone(&barrier); + std::thread::spawn(move || { + barrier.wait(); + event(&store) + }) + }) + .collect(); + let events: Vec<_> = threads + .into_iter() + .map(|thread| thread.join().unwrap()) + .collect(); + assert!(events.iter().all(|event| *event == events[0])); + } +} diff --git a/src/languages/rego/compiler/function_calls.rs b/src/languages/rego/compiler/function_calls.rs index d7ecbe45b..7d6418ec5 100644 --- a/src/languages/rego/compiler/function_calls.rs +++ b/src/languages/rego/compiler/function_calls.rs @@ -66,6 +66,10 @@ impl<'a> Compiler<'a> { .map_err(|_| CompilerError::InvalidFunctionExpression.at(&span))?; let original_fcn_path = fcn_path.clone(); + #[cfg(feature = "history")] + if let Some(mode) = super::history::history_mode(&original_fcn_path) { + return self.compile_history_rule(mode, params, &span); + } let full_fcn_path = if self.policy.inner.rules.contains_key(&fcn_path) { fcn_path } else if let Some(resolved) = self.resolve_fcn_path_through_imports(&original_fcn_path) { diff --git a/src/languages/rego/compiler/history.rs b/src/languages/rego/compiler/history.rs new file mode 100644 index 000000000..b21b6fff2 --- /dev/null +++ b/src/languages/rego/compiler/history.rs @@ -0,0 +1,293 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Lowering of `history.require(request, language)` / `history.forbid(...)` +//! into one typed history-table rule evaluated by a single `HistoryStep`. + +#![allow(clippy::pattern_type_mismatch)] + +use super::{Compiler, CompilerError, Register, Result, SpannedCompilerError}; +use crate::ast::{ArithOp, BinOp, BoolOp, Expr, ExprRef}; +use crate::languages::history_table::{ + table_rule, SourceComponent, SourceEvent, ACTION, PRINCIPAL, RESOURCE, +}; +use crate::lexer::Span; +use crate::rvm::instructions::HistoryStepParams; +use crate::rvm::program::HistoryTable; +use crate::rvm::Instruction; +use crate::value::Value; +use alloc::format; +use alloc::string::String; +use alloc::vec::Vec; +use history_syntax::{ + AtomPattern, Comparison, Component, ComponentPattern, Head, RegexExpr, Rule, RuleMode, TestExpr, +}; + +/// Maximum number of history events one `HistoryStep` dispatch consumes. +pub const HISTORY_BATCH_SIZE: u32 = 256; + +const COORDINATES: [(&str, Component); 3] = [ + ("principal", PRINCIPAL), + ("action", ACTION), + ("resource", RESOURCE), +]; + +type Event<'a> = SourceEvent<'a>; + +pub(super) fn history_mode(path: &str) -> Option { + match path { + "history.require" => Some(RuleMode::Require), + "history.forbid" => Some(RuleMode::Forbid), + _ => None, + } +} + +impl Compiler<'_> { + pub(super) fn compile_history_rule( + &mut self, + mode: RuleMode, + params: &[ExprRef], + span: &Span, + ) -> Result { + let [request, language] = params else { + return Err(general( + "history.require and history.forbid take two arguments: a request pattern and a history expression", + ) + .at(span)); + }; + let rule = Rule::new(mode, lower_request(request)?, lower_language(language)?); + let table_rule = table_rule(&rule) + .map_err(|error| general(format!("invalid history rule: {error}")).at(span))?; + if self.program.history_tables.is_empty() { + self.program + .add_history_table(HistoryTable { rules: Vec::new() }); + } + let rules = &mut self + .program + .history_tables + .first_mut() + .ok_or_else(|| general("missing history table").at(span))? + .rules; + let rule_index = + u16::try_from(rules.len()).map_err(|_| general("too many history rules").at(span))?; + rules.push(table_rule); + let dest = self.alloc_register()?; + let params_index = self.program.add_history_step_params(HistoryStepParams { + table: 0, + rule: rule_index, + batch_size: HISTORY_BATCH_SIZE, + dest, + }); + self.emit_instruction(Instruction::HistoryStep { params_index }, span); + Ok(dest) + } +} + +fn general(message: impl Into) -> CompilerError { + CompilerError::General { + message: message.into(), + } +} + +fn invalid(expr: &Expr, message: impl Into) -> SpannedCompilerError { + general(message).at(expr.span()) +} + +fn text(value: &Value) -> Option<&str> { + match value { + Value::String(text) => Some(text), + _ => None, + } +} + +fn var_name(expr: &Expr) -> Option<&str> { + match expr { + Expr::Var { value, .. } => text(value), + _ => None, + } +} + +fn string_literal(expr: &Expr) -> Option<&str> { + match expr { + Expr::String { value, .. } | Expr::RawString { value, .. } => text(value), + _ => None, + } +} + +fn coordinate(name: &str) -> Option { + COORDINATES + .iter() + .find(|&&(coordinate, _)| coordinate == name) + .map(|&(_, component)| component) +} + +fn tagged(component: Component, text: &str) -> SourceComponent<'_> { + match component { + PRINCIPAL => SourceComponent::Principal(text), + ACTION => SourceComponent::Action(text), + _ => SourceComponent::Resource(text), + } +} + +fn lower_request(expr: &Expr) -> Result>> { + const SHAPE: &str = + "request pattern must be an object with string keys principal, action, resource"; + let Expr::Object { fields, .. } = expr else { + return Err(invalid(expr, SHAPE)); + }; + let mut slots: [Option>>; 3] = [None, None, None]; + for (_, key, value) in fields { + let (name, component) = string_literal(key) + .and_then(|name| Some((name, coordinate(name)?))) + .ok_or_else(|| invalid(key, SHAPE))?; + let slot = slots + .get_mut(component.index()) + .ok_or_else(|| invalid(key, SHAPE))?; + if slot.is_some() { + return Err(invalid( + key, + format!("duplicate request coordinate `{name}`"), + )); + } + *slot = Some(if let Some(constant) = string_literal(value) { + ComponentPattern::constant(tagged(component, constant)) + } else { + match var_name(value) { + Some("_") => continue, + Some(variable) if coordinate(variable).is_some() => { + return Err(invalid( + value, + format!("variable `{variable}` shadows the coordinate name; rename it"), + )); + } + Some("any") => { + return Err(invalid( + value, + "variable `any` names the universal history; rename it", + )); + } + Some(variable) => ComponentPattern::variable(variable), + None => { + return Err(invalid( + value, + format!( + "request coordinate `{name}` must be a string constant or a variable" + ), + )); + } + } + }); + } + // `$` never occurs in Rego identifiers, so wildcard slots bind unreachable variables. + let [principal, action, resource] = slots; + Ok(Head::new([ + principal.unwrap_or_else(|| ComponentPattern::variable("$principal")), + action.unwrap_or_else(|| ComponentPattern::variable("$action")), + resource.unwrap_or_else(|| ComponentPattern::variable("$resource")), + ])) +} + +fn lower_language(expr: &Expr) -> Result>> { + Ok(match expr { + Expr::Var { .. } => match var_name(expr) { + Some("any") => RegexExpr::all(), + name => { + return Err(invalid( + expr, + format!( + "unknown name `{}` in history expression", + name.unwrap_or_default() + ), + )); + } + }, + Expr::Bool { + value: Value::Bool(value), + .. + } => RegexExpr::test(if *value { + TestExpr::true_test() + } else { + TestExpr::false_test() + }), + Expr::Set { items, .. } => RegexExpr::test(TestExpr::and( + items + .iter() + .map(|item| lower_atom(item)) + .collect::>>()?, + )), + Expr::Array { items, .. } => RegexExpr::concat( + items + .iter() + .map(|item| lower_language(item)) + .collect::>>()?, + ), + Expr::BinExpr { op, lhs, rhs, .. } => { + let pair = [lower_language(lhs)?, lower_language(rhs)?]; + match op { + BinOp::Union => RegexExpr::union(pair), + BinOp::Intersection => RegexExpr::intersect(pair), + } + } + Expr::ArithExpr { + op: ArithOp::Sub, + lhs, + rhs, + .. + } => RegexExpr::intersect([ + lower_language(lhs)?, + RegexExpr::complement(lower_language(rhs)?), + ]), + Expr::Call { fcn, params, .. } if var_name(fcn) == Some("star") => { + let [inner] = params.as_slice() else { + return Err(invalid(expr, "star takes one argument")); + }; + RegexExpr::star(lower_language(inner)?) + } + // `set()` is the empty set literal: one event with no constraint. + Expr::Call { fcn, params, .. } if var_name(fcn) == Some("set") && params.is_empty() => { + RegexExpr::test(TestExpr::and([])) + } + _ => { + return Err(invalid( + expr, + "unsupported history expression; expected any, true, false, a set of comparisons, an array, a | b, a & b, a - b, or star(a)", + )); + } + }) +} + +fn lower_atom(expr: &Expr) -> Result>> { + const SHAPE: &str = "comparison must be `principal|action|resource == term` or `!= term`"; + let Expr::BoolExpr { op, lhs, rhs, .. } = expr else { + return Err(invalid(expr, SHAPE)); + }; + let comparison = match op { + BoolOp::Eq => Comparison::Eq, + BoolOp::Ne => Comparison::Neq, + _ => return Err(invalid(expr, SHAPE)), + }; + let component = var_name(lhs) + .and_then(coordinate) + .ok_or_else(|| invalid(expr, SHAPE))?; + let pattern = if let Some(constant) = string_literal(rhs) { + ComponentPattern::constant(tagged(component, constant)) + } else { + match var_name(rhs) { + Some(variable) + if variable != "_" && variable != "any" && coordinate(variable).is_none() => + { + ComponentPattern::variable(variable) + } + _ => { + return Err(invalid( + rhs, + "comparison term must be a string constant or a request variable", + )); + } + } + }; + Ok(TestExpr::atom( + comparison, + AtomPattern::new(component, pattern), + )) +} diff --git a/src/languages/rego/compiler/mod.rs b/src/languages/rego/compiler/mod.rs index e6b4a04d1..e8fa3f3a2 100644 --- a/src/languages/rego/compiler/mod.rs +++ b/src/languages/rego/compiler/mod.rs @@ -12,6 +12,8 @@ mod destructuring; mod error; mod expressions; mod function_calls; +#[cfg(feature = "history")] +mod history; mod loops; mod program; mod queries; @@ -19,6 +21,8 @@ mod references; mod rules; pub use error::{CompilerError, Result, SpannedCompilerError}; +#[cfg(feature = "history")] +pub use history::HISTORY_BATCH_SIZE; use crate::ast::ExprRef; use crate::lexer::{Source, Span}; diff --git a/src/lib.rs b/src/lib.rs index c65198180..a47d4bce3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,6 +12,7 @@ // Verus needs to name it to give it a specification. Verification builds use the // Verus toolchain, so this gate never applies to shipped code. #![cfg_attr(verus_keep_ghost, feature(fmt_arguments_from_str))] +#![cfg_attr(verus_keep_ghost, feature(allocator_api))] // Loop invariants are attached with `#[verus_spec(invariant ...)]` on the loop // statement itself. Applying a proc-macro attribute in statement position is // still unstable, so verification builds opt in. Shipped builds strip the @@ -151,6 +152,10 @@ pub mod languages { #[cfg(feature = "azure-rbac")] pub mod azure_rbac; + #[cfg(all(feature = "rvm", feature = "history"))] + #[cfg_attr(docsrs, doc(cfg(all(feature = "rvm", feature = "history"))))] + pub mod history_table; + #[cfg(feature = "rvm")] pub mod rego; } diff --git a/src/rvm/instructions/display.rs b/src/rvm/instructions/display.rs index 1b8a00fd2..5c441034c 100644 --- a/src/rvm/instructions/display.rs +++ b/src/rvm/instructions/display.rs @@ -291,6 +291,9 @@ impl core::fmt::Display for Instruction { |k| format!("COMPREHENSION_YIELD R({}) R({})", k, value_reg), ), Instruction::ComprehensionEnd {} => String::from("COMPREHENSION_END"), + Instruction::HistoryStep { params_index } => { + format!("HISTORY_STEP P({})", params_index) + } // Azure Policy consolidated instruction Instruction::PolicyCondition { diff --git a/src/rvm/instructions/mod.rs b/src/rvm/instructions/mod.rs index df305d08a..e5187a1e9 100644 --- a/src/rvm/instructions/mod.rs +++ b/src/rvm/instructions/mod.rs @@ -7,8 +7,8 @@ mod types; pub use params::{ ArrayCreateParams, BuiltinCallParams, ChainedIndexParams, ComprehensionBeginParams, - FunctionCallParams, InstructionData, LoopStartParams, ObjectCreateParams, SetCreateParams, - VirtualDataDocumentLookupParams, + FunctionCallParams, HistoryStepParams, InstructionData, LoopStartParams, ObjectCreateParams, + SetCreateParams, VirtualDataDocumentLookupParams, }; pub use types::{ ComprehensionMode, GuardMode, LiteralOrRegister, LogicalBlockMode, LoopMode, PolicyOp, @@ -417,6 +417,14 @@ pub enum Instruction { /// Register that accumulates the result. result: u8, }, + + /// Advance one ordered history rule by at most its configured batch size. + /// + /// Last variant so that version-6 programs keep their postcard variant indices. + HistoryStep { + /// Index into `instruction_data.history_step_params`. + params_index: u16, + }, } impl Instruction { diff --git a/src/rvm/instructions/params.rs b/src/rvm/instructions/params.rs index ab2ed3f0d..66ffc694c 100644 --- a/src/rvm/instructions/params.rs +++ b/src/rvm/instructions/params.rs @@ -274,6 +274,20 @@ pub struct ComprehensionBeginParams { pub comprehension_end: u16, } +/// Parameters for one bounded history rule step. +#[repr(C)] +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct HistoryStepParams { + /// Index into `Program::history_tables`. + pub table: u16, + /// Ordered rule index within the table. + pub rule: u16, + /// Maximum number of history events consumed by this dispatch. + pub batch_size: u32, + /// Register receiving the Boolean outcome. + pub dest: u8, +} + /// Instruction data container for complex instruction parameters #[derive(Debug, Clone, Serialize, Deserialize)] pub struct InstructionData { @@ -295,6 +309,10 @@ pub struct InstructionData { pub chained_index_params: Vec, /// Comprehension parameter table for ComprehensionBegin instructions pub comprehension_begin_params: Vec, + /// Bounded history rule step parameters. Serialized in the binary history section and + /// as an explicit JSON key, so version-6 program structures still decode. + #[serde(skip)] + pub history_step_params: Vec, } impl InstructionData { @@ -315,6 +333,7 @@ impl InstructionData { virtual_data_document_lookup_params: Vec::new(), chained_index_params: Vec::new(), comprehension_begin_params: Vec::new(), + history_step_params: Vec::new(), } } @@ -325,6 +344,13 @@ impl InstructionData { index } + /// Add bounded history step parameters and return the index. + pub fn add_history_step_params(&mut self, params: HistoryStepParams) -> u16 { + let index = Self::ensure_u16_index(self.history_step_params.len()); + self.history_step_params.push(params); + index + } + /// Add builtin call parameters and return the index pub fn add_builtin_call_params(&mut self, params: BuiltinCallParams) -> u16 { let index = Self::ensure_u16_index(self.builtin_call_params.len()); diff --git a/src/rvm/program/core.rs b/src/rvm/program/core.rs index 3b3a6ffb6..b3b077aac 100644 --- a/src/rvm/program/core.rs +++ b/src/rvm/program/core.rs @@ -9,7 +9,7 @@ use indexmap::IndexMap; use serde::{Deserialize, Serialize}; use super::metadata::ProgramMetadata; -use super::types::{BuiltinInfo, RuleInfo, SourceFile, SpanInfo}; +use super::types::{BuiltinInfo, HistoryTable, RuleInfo, SourceFile, SpanInfo}; use crate::builtins::BuiltinFcn; use crate::rvm::instructions::InstructionData; use crate::rvm::Instruction; @@ -85,11 +85,16 @@ pub struct Program { /// Serialized separately in the artifact section for guaranteed availability #[serde(skip, default)] pub rego_v0: bool, + + /// History tables judged by ordered `HistoryStep` instructions. + /// Serialized separately (binary history section, explicit JSON key). + #[serde(skip, default)] + pub history_tables: Vec, } impl Program { /// Current serialization format version - pub const SERIALIZATION_VERSION: u32 = 6; + pub const SERIALIZATION_VERSION: u32 = 7; /// Magic bytes to identify Regorus program files pub const MAGIC: [u8; 4] = *b"REGO"; /// Maximum instructions supported (matches u16 jump targets) @@ -135,6 +140,7 @@ impl Program { has_host_await: false, needs_recompilation: false, rego_v0: false, // Default to Rego v1 + history_tables: Vec::new(), } } @@ -217,6 +223,54 @@ impl Program { } } + if self.history_tables.len() > usize::from(u16::MAX) { + return Err("Too many history tables".to_string()); + } + for (t, table) in self.history_tables.iter().enumerate() { + if table.rules.len() > usize::from(u16::MAX) { + return Err(format!("History table {t} has too many rules")); + } + for (i, rule) in table.rules.iter().enumerate() { + rule.source.validate().map_err(|error| { + format!("History table {t} rule {i} has invalid source: {error}") + })?; + } + } + if self.instruction_data.history_step_params.len() > usize::from(u16::MAX) { + return Err("Too many history step parameters".to_string()); + } + for (index, params) in self.instruction_data.history_step_params.iter().enumerate() { + if params.batch_size == 0 { + return Err(format!( + "History step parameter {index} has zero batch_size" + )); + } + let table = self + .history_tables + .get(usize::from(params.table)) + .ok_or_else(|| { + format!( + "History step parameter {index} references table {} out of range", + params.table + ) + })?; + if usize::from(params.rule) >= table.rules.len() { + return Err(format!( + "History step parameter {index} references rule {} out of range", + params.rule + )); + } + } + for (pc, instruction) in self.instructions.iter().enumerate() { + if let Instruction::HistoryStep { params_index } = *instruction { + if usize::from(params_index) >= self.instruction_data.history_step_params.len() { + return Err(format!( + "History step at {pc} references parameter {params_index} out of range" + )); + } + } + } + Ok(()) } @@ -269,6 +323,21 @@ impl Program { self.instruction_data.add_function_call_params(params) } + /// Add bounded history step parameters and return the index. + pub fn add_history_step_params( + &mut self, + params: crate::rvm::instructions::HistoryStepParams, + ) -> u16 { + self.instruction_data.add_history_step_params(params) + } + + /// Add a history table and return its index + pub fn add_history_table(&mut self, table: HistoryTable) -> u16 { + let index = self.history_tables.len(); + self.history_tables.push(table); + u16::try_from(index).unwrap_or(u16::MAX) + } + /// Add builtin info and return the index pub fn add_builtin_info(&mut self, builtin_info: BuiltinInfo) -> u16 { let index = self.builtin_info_table.len(); diff --git a/src/rvm/program/listing.rs b/src/rvm/program/listing.rs index cdaf5a08b..b820ff732 100644 --- a/src/rvm/program/listing.rs +++ b/src/rvm/program/listing.rs @@ -917,6 +917,18 @@ fn format_instruction_readable( let base = format!("{}}} CompEnd", indent); align_comment(&base, "End comprehension block", config.comment_column) } + Instruction::HistoryStep { params_index } => instruction_data + .history_step_params + .get(usize::from(params_index)) + .map_or_else( + || format!("{}HistoryStep P({}) ", indent, params_index), + |p| { + format!( + "{}HistoryStep table[{}].rule[{}] batch_size={} dest=r{}", + indent, p.table, p.rule, p.batch_size, p.dest + ) + }, + ), // Azure Policy & allOf/anyOf instructions — use Display impl instruction @ Instruction::PolicyCondition { .. } @@ -1060,6 +1072,7 @@ const fn get_instruction_name(instruction: &Instruction) -> &'static str { Instruction::ComprehensionBegin { .. } => "COMP_BEGIN", Instruction::ComprehensionYield { .. } => "COMP_YIELD", Instruction::ComprehensionEnd {} => "COMP_END", + Instruction::HistoryStep { .. } => "HISTORY_STEP", // Azure Policy instructions Instruction::PolicyCondition { op, .. } => op.compact_name(), // AllOf / AnyOf diff --git a/src/rvm/program/mod.rs b/src/rvm/program/mod.rs index 813bcabd4..5ca0bbdd8 100644 --- a/src/rvm/program/mod.rs +++ b/src/rvm/program/mod.rs @@ -15,6 +15,9 @@ pub use listing::{ }; pub(crate) use serialization::value::{binaries_to_values, BinaryValue}; pub use serialization::{DeserializationResult, VersionedProgram}; -pub use types::{BuiltinInfo, FunctionInfo, RuleInfo, RuleType, SourceFile, SpanInfo}; +pub use types::{ + BuiltinInfo, FunctionInfo, HistoryTable, HistoryTableRule, RuleInfo, RuleType, SourceFile, + SpanInfo, +}; pub use metadata::ProgramMetadata; diff --git a/src/rvm/program/serialization/binary.rs b/src/rvm/program/serialization/binary.rs index 45258f6f2..991bd4c8a 100644 --- a/src/rvm/program/serialization/binary.rs +++ b/src/rvm/program/serialization/binary.rs @@ -7,6 +7,9 @@ use alloc::vec::Vec; use postcard::{take_from_bytes, to_allocvec}; use serde::de::DeserializeOwned; +use crate::rvm::instructions::HistoryStepParams; +use crate::rvm::program::HistoryTable; + use super::{DeserializationResult, Program}; use super::value::{ @@ -103,6 +106,12 @@ impl Program { let binary_data = to_allocvec(self) .map_err(|e| format!("Program structure binary serialization failed: {}", e))?; + let history_bin = to_allocvec(&( + &self.history_tables, + &self.instruction_data.history_step_params, + )) + .map_err(|e| format!("History postcard serialization failed: {}", e))?; + buffer.extend_from_slice( &u32::try_from(entry_points_bin.len()) .map_err(|_| "Entry points size too large")? @@ -137,6 +146,14 @@ impl Program { ); buffer.extend_from_slice(&binary_data); + // Version 7 appends the history section after the version-6 layout. + buffer.extend_from_slice( + &u32::try_from(history_bin.len()) + .map_err(|_| "History size too large")? + .to_le_bytes(), + ); + buffer.extend_from_slice(&history_bin); + Ok(buffer) } @@ -168,7 +185,8 @@ impl Program { program.rego_v0 = Self::legacy_rego_v0(data, version).unwrap_or(false); Ok(DeserializationResult::Partial(program)) } - 6 => { + // Version 7 is version 6 plus a trailing history section. + 6 | 7 => { if data.len() < 29 { return Err("Data too short for header".to_string()); } @@ -201,10 +219,23 @@ impl Program { let binary_start = binary_offset.advance(binary_len)?; let binary_end = binary_offset.current(); - if data.len() < binary_end { + let history_range = if version >= 7 { + if data.len() < binary_end.checked_add(4).ok_or("Offset overflow")? { + return Err("Data too short for history length".to_string()); + } + let history_len = Self::read_u32_as_usize(data, binary_end)?; + binary_offset.advance(4)?; + let history_start = binary_offset.advance(history_len)?; + Some((history_start, binary_offset.current())) + } else { + None + }; + let end = binary_offset.current(); + + if data.len() < end { return Err("Data truncated".to_string()); } - if data.len() > binary_end { + if data.len() > end { return Err("Unexpected trailing data".to_string()); } @@ -238,6 +269,16 @@ impl Program { program.rego_v0 = rego_v0; program.needs_recompilation = false; + if let Some((history_start, history_end)) = history_range { + let (history_tables, history_step_params) = + Self::deserialize_section::<(Vec, Vec)>( + Self::get_slice(data, history_start, history_end)?, + "History", + )?; + program.history_tables = history_tables; + program.instruction_data.history_step_params = history_step_params; + } + // Apply the same supported bounds as compilation and serialization. program.validate_limits()?; @@ -271,7 +312,7 @@ impl Program { let version = Self::read_u32(data, 4).ok(); match version { - Some(1..=6) => Ok(true), + Some(1..=7) => Ok(true), _ => Ok(false), } } @@ -358,6 +399,10 @@ mod tests { } blob.extend_from_slice(&len_of(§ions.artifact)); blob.extend_from_slice(§ions.artifact); + let history: (Vec, Vec) = (Vec::new(), Vec::new()); + let history = to_allocvec(&history).expect("history section"); + blob.extend_from_slice(&len_of(&history)); + blob.extend_from_slice(&history); blob } diff --git a/src/rvm/program/serialization/json.rs b/src/rvm/program/serialization/json.rs index eb15f6631..1d7880265 100644 --- a/src/rvm/program/serialization/json.rs +++ b/src/rvm/program/serialization/json.rs @@ -53,7 +53,8 @@ impl Program { "set_create_params": self.instruction_data.set_create_params, "virtual_data_document_lookup_params": self.instruction_data.virtual_data_document_lookup_params, "chained_index_params": self.instruction_data.chained_index_params, - "comprehension_begin_params": self.instruction_data.comprehension_begin_params + "comprehension_begin_params": self.instruction_data.comprehension_begin_params, + "history_step_params": self.instruction_data.history_step_params }, "literals": literals, "builtin_info_table": self.builtin_info_table, @@ -61,7 +62,8 @@ impl Program { "sources": self.sources, "rule_infos": self.rule_infos, "instruction_spans": self.instruction_spans, - "rule_tree": rule_tree + "rule_tree": rule_tree, + "history_tables": self.history_tables }); serde_json::to_string_pretty(&json_data) @@ -165,9 +167,15 @@ impl Program { let instruction_data_json = json_data .get("instruction_data") .ok_or("Missing instruction_data section")?; - let instruction_data: InstructionData = + let mut instruction_data: InstructionData = serde_json::from_value(instruction_data_json.clone()) .map_err(|e| format!("Failed to deserialize instruction_data: {}", e))?; + instruction_data.history_step_params = instruction_data_json + .get("history_step_params") + .map(|v| serde_json::from_value(v.clone())) + .transpose() + .map_err(|e| format!("Failed to deserialize history_step_params: {}", e))? + .unwrap_or_default(); let literals: Vec = json_data .get("literals") @@ -208,6 +216,13 @@ impl Program { .map_err(|e| format!("Rule tree deserialization failed: {e}"))? .unwrap_or_else(Value::new_object); + let history_tables = json_data + .get("history_tables") + .map(|v| serde_json::from_value(v.clone())) + .transpose() + .map_err(|e| format!("Failed to deserialize history_tables: {}", e))? + .unwrap_or_default(); + let mut program = Program { instructions, literals, @@ -234,6 +249,7 @@ impl Program { has_host_await, needs_recompilation, rego_v0, + history_tables, }; // Recompute has_host_await when it was not provided in the JSON input diff --git a/src/rvm/program/types.rs b/src/rvm/program/types.rs index 37e3817c8..7cea4b161 100644 --- a/src/rvm/program/types.rs +++ b/src/rvm/program/types.rs @@ -2,6 +2,8 @@ // Licensed under the MIT License. use alloc::string::String; use alloc::vec::Vec; +use history_syntax::RuleMode; +use junco_core::flat::FlatPair; use serde::{Deserialize, Serialize}; /// Builtin function information stored in program's builtin info table @@ -187,3 +189,16 @@ impl SourceFile { Self { name, content } } } + +/// One ordered history rule and its portable, store-independent source. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct HistoryTableRule { + pub mode: RuleMode, + pub source: FlatPair, +} + +/// Ordered rules judged by `HistoryStep`; the first violated rule wins. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct HistoryTable { + pub rules: Vec, +} diff --git a/src/rvm/tests/instruction_parser.rs b/src/rvm/tests/instruction_parser.rs index 5d3237524..bf20ac93f 100644 --- a/src/rvm/tests/instruction_parser.rs +++ b/src/rvm/tests/instruction_parser.rs @@ -72,6 +72,7 @@ pub fn parse_instruction(text: &str) -> Result { "AssertNotUndefined" => parse_guard(params_text, GuardMode::NotUndefined), "BuiltinCall" => parse_builtin_call(params_text), "FunctionCall" => parse_function_call(params_text), + "HistoryStep" => parse_history_step(params_text), "CallRule" => parse_call_rule(params_text), "VirtualDataDocumentLookup" => parse_virtual_data_document_lookup(params_text), "HostAwait" => parse_host_await(params_text), @@ -679,6 +680,12 @@ fn parse_function_call(params_text: &str) -> Result { Ok(Instruction::FunctionCall { params_index }) } +fn parse_history_step(params_text: &str) -> Result { + let params = parse_params(params_text)?; + let params_index = get_param_u16(¶ms, "params_index")?; + Ok(Instruction::HistoryStep { params_index }) +} + fn parse_call_rule(params_text: &str) -> Result { let params = parse_params(params_text)?; let dest = get_param_u16(¶ms, "dest")?; diff --git a/src/rvm/vm/dispatch.rs b/src/rvm/vm/dispatch.rs index 16a815aa9..d75a18607 100644 --- a/src/rvm/vm/dispatch.rs +++ b/src/rvm/vm/dispatch.rs @@ -12,11 +12,17 @@ use super::execution_model::{ExecutionMode, SuspendReason}; use super::loops::LoopParams; use super::machine::RegoVM; +#[derive(Debug)] pub(super) enum InstructionOutcome { Continue, + /// Dispatch the same instruction again, keeping the frame on it. + #[cfg(feature = "history")] + Repeat, Return(Value), Break, - Suspend { reason: SuspendReason }, + Suspend { + reason: SuspendReason, + }, } impl RegoVM { @@ -1270,6 +1276,17 @@ impl RegoVM { self.execute_comprehension_end()?; Ok(InstructionOutcome::Continue) } + HistoryStep { params_index } => { + #[cfg(feature = "history")] + { + self.execute_history_step(params_index) + } + #[cfg(not(feature = "history"))] + { + let _ = params_index; + Err(VmError::HistoryFeatureDisabled { pc: self.pc }) + } + } unexpected => Err(VmError::UnhandledInstruction { instruction: alloc::format!("{:?}", unexpected), pc: self.pc, diff --git a/src/rvm/vm/errors.rs b/src/rvm/vm/errors.rs index 9713d8712..10be93c64 100644 --- a/src/rvm/vm/errors.rs +++ b/src/rvm/vm/errors.rs @@ -45,6 +45,41 @@ pub enum VmError { #[error("Compiled regex exceeded size limit ({limit} bytes, pc={pc})")] RegexSizeLimitExceeded { limit: usize, pc: usize }, + #[error("history_step requires the `history` feature (pc={pc})")] + HistoryFeatureDisabled { pc: usize }, + + /// Typed native history failures are never ordinary rule failures. + #[cfg(feature = "history")] + #[error("{source} (pc={pc})")] + History { + source: crate::languages::history_table::HistoryError, + pc: usize, + }, + + #[cfg(feature = "history")] + #[error("History attachment and typed input are required (pc={pc})")] + HistoryContextMissing { pc: usize }, + + #[cfg(feature = "history")] + #[error("History execution is active (pc={pc})")] + HistoryExecutionActive { pc: usize }, + + #[cfg(feature = "history")] + #[error("history_step params index {index} out of bounds (pc={pc})")] + InvalidHistoryStepParams { index: u16, pc: usize }, + + #[cfg(feature = "history")] + #[error("History table index {index} out of bounds (pc={pc})")] + InvalidHistoryTableIndex { index: u16, pc: usize }, + + #[cfg(feature = "history")] + #[error("History table {table} rule index {rule} out of bounds (pc={pc})")] + InvalidHistoryRuleIndex { table: u16, rule: u16, pc: usize }, + + #[cfg(feature = "history")] + #[error("history_step batch_size {batch_size} must be greater than zero (pc={pc})")] + InvalidHistoryBatchSize { batch_size: u32, pc: usize }, + #[error("Value serialization exceeds {limit} nested containers (pc={pc})")] SerializationDepthExceeded { limit: usize, pc: usize }, @@ -353,6 +388,21 @@ impl core::fmt::Debug for VmError { "MemoryBudgetUnsupportedInSuspendableExecution" } Self::RegexSizeLimitExceeded { .. } => "RegexSizeLimitExceeded", + Self::HistoryFeatureDisabled { .. } => "HistoryFeatureDisabled", + #[cfg(feature = "history")] + Self::History { .. } => "History", + #[cfg(feature = "history")] + Self::HistoryContextMissing { .. } => "HistoryContextMissing", + #[cfg(feature = "history")] + Self::HistoryExecutionActive { .. } => "HistoryExecutionActive", + #[cfg(feature = "history")] + Self::InvalidHistoryStepParams { .. } => "InvalidHistoryStepParams", + #[cfg(feature = "history")] + Self::InvalidHistoryTableIndex { .. } => "InvalidHistoryTableIndex", + #[cfg(feature = "history")] + Self::InvalidHistoryRuleIndex { .. } => "InvalidHistoryRuleIndex", + #[cfg(feature = "history")] + Self::InvalidHistoryBatchSize { .. } => "InvalidHistoryBatchSize", Self::SerializationDepthExceeded { .. } => "SerializationDepthExceeded", Self::LiteralIndexOutOfBounds { .. } => "LiteralIndexOutOfBounds", Self::RegisterNotObject { .. } => "RegisterNotObject", diff --git a/src/rvm/vm/execution.rs b/src/rvm/vm/execution.rs index 2538631d2..9ff72bc75 100644 --- a/src/rvm/vm/execution.rs +++ b/src/rvm/vm/execution.rs @@ -73,6 +73,8 @@ impl RegoVM { .jump_to(entry_point_pc_u32) .map_err(|err| self.apply_memory_budget_precedence(err))?; self.check_memory_budget()?; + #[cfg(feature = "history")] + self.finish_history_execution()?; Ok(result) })(); match result { @@ -132,6 +134,8 @@ impl RegoVM { .jump_to(entry_point_pc_u32) .map_err(|err| self.apply_memory_budget_precedence(err))?; self.check_memory_budget()?; + #[cfg(feature = "history")] + self.finish_history_execution()?; Ok(result) })(); match result { @@ -179,6 +183,8 @@ impl RegoVM { InstructionOutcome::Continue => { self.pc = self.pc.saturating_add(1); } + #[cfg(feature = "history")] + InstructionOutcome::Repeat => {} InstructionOutcome::Return(value) => { return Ok(value); } @@ -212,6 +218,8 @@ impl RegoVM { .map_err(|err| self.apply_memory_budget_precedence(err)) .and_then(|value| { self.check_memory_budget()?; + #[cfg(feature = "history")] + self.finish_history_execution()?; Ok(value) }) })(); @@ -414,16 +422,7 @@ impl RegoVM { let program = self.program.clone(); self.run_stackless_loop(&program, &mut last_result)?; - - if matches!(self.execution_state, ExecutionState::Suspended { .. }) { - Ok(last_result) - } else { - self.execution_stack.clear(); - self.execution_state = ExecutionState::Completed { - result: last_result.clone(), - }; - Ok(last_result) - } + self.finish_stackless_execution(last_result) } fn run_stackless_from(&mut self, start_pc: usize) -> Result { @@ -435,16 +434,26 @@ impl RegoVM { let mut last_result = self.registers.first().cloned().unwrap_or(Value::Undefined); self.run_stackless_loop(&program, &mut last_result)?; + self.finish_stackless_execution(last_result) + } + fn finish_stackless_execution(&mut self, result: Value) -> Result { if matches!(self.execution_state, ExecutionState::Suspended { .. }) { - Ok(last_result) - } else { - self.execution_stack.clear(); - self.execution_state = ExecutionState::Completed { - result: last_result.clone(), + return Ok(result); + } + self.execution_stack.clear(); + // A completed decision is published only if its pinned history prefix still holds. + #[cfg(feature = "history")] + if let Err(error) = self.finish_history_execution() { + self.execution_state = ExecutionState::Error { + error: error.clone(), }; - Ok(last_result) + return Err(error); } + self.execution_state = ExecutionState::Completed { + result: result.clone(), + }; + Ok(result) } fn run_stackless_loop(&mut self, program: &Program, last_result: &mut Value) -> Result<()> { @@ -584,6 +593,15 @@ impl RegoVM { return Ok(()); } } + #[cfg(feature = "history")] + Ok(InstructionOutcome::Repeat) => { + // A repeated dispatch charges budgets normally but keeps the frame PC. + self.frame_pc_overridden = true; + if self.step_mode { + self.handle_instruction_suspend(SuspendReason::Step, &*last_result); + return Ok(()); + } + } Ok(InstructionOutcome::Return(value)) => { self.handle_instruction_return(value, last_result)?; if self.execution_stack.is_empty() { @@ -597,6 +615,13 @@ impl RegoVM { } } Ok(InstructionOutcome::Suspend { reason }) => { + // Only an explicit suspension leaves the frame on its own instruction; + // Continue already advanced it, and a pushed callee frame owns its pc. + if let Some(frame) = self.execution_stack.last_mut() { + if !self.frame_pc_overridden && frame.pc <= self.pc { + frame.pc = self.pc.saturating_add(1); + } + } self.handle_instruction_suspend(reason, last_result); return Ok(()); } @@ -617,12 +642,6 @@ impl RegoVM { } fn handle_instruction_suspend(&mut self, reason: SuspendReason, last_result: &Value) { - if let Some(frame) = self.execution_stack.last_mut() { - if !self.frame_pc_overridden && frame.pc <= self.pc { - frame.pc = self.pc.saturating_add(1); - } - } - self.snapshot_execution_timer_on_suspend(); self.execution_state = ExecutionState::Suspended { reason, diff --git a/src/rvm/vm/history_tables.rs b/src/rvm/vm/history_tables.rs new file mode 100644 index 000000000..4e304ca72 --- /dev/null +++ b/src/rvm/vm/history_tables.rs @@ -0,0 +1,1177 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Bounded typed history steps. A decision pins one revision/prefix and each active +//! rule pins its graph generation; no synchronization guard survives a dispatch. + +use super::dispatch::InstructionOutcome; +use super::errors::{Result, VmError}; +use super::execution_model::ExecutionState; +use super::machine::RegoVM; +use crate::languages::history_table::limits::RegorusLimits; +use crate::languages::history_table::store::HistoryTableRuntime; +use crate::languages::history_table::{Event, HistoryError, HistoryHandle, HistoryStore}; +use crate::rvm::program::Program; +use crate::utils::limits::LimitError; +use crate::value::Value; +use alloc::sync::Arc; +use alloc::vec::Vec; +use history_semantics::runtime::{BatchCursor, RuleRuntime}; +use history_store::history::StoredHistory; +use history_store::store::HistoryRecord; +use history_syntax::RuleMode; +use junco_core::kernel::Bindings; +use junco_core::limits::Limits as _; +use junco_core::observation::ObservationWorld; +#[cfg(feature = "std")] +use parking_lot::Mutex; +#[cfg(not(feature = "std"))] +use spin::Mutex; + +// Core history stores, handles and records implement Debug only outside Verus builds. +#[cfg_attr(not(verus_keep_ghost), derive(Debug))] +pub(super) struct HistoryAttachment { + store: Arc, + tables: Vec>, +} + +#[cfg_attr(not(verus_keep_ghost), derive(Debug))] +pub(super) struct HistoryDecision { + record: HistoryRecord, + revision: u64, + target_len: usize, + request: Event, +} + +#[derive(Debug)] +pub(super) struct ActiveHistoryRule { + pc: usize, + bindings: Bindings, + instance: Arc>, + cursor: BatchCursor, + retried: bool, +} + +impl HistoryAttachment { + fn new( + store: Arc, + program: &Arc, + ) -> core::result::Result { + let mut tables = Vec::new(); + tables + .try_reserve_exact(program.history_tables.len()) + .map_err(|_| HistoryError::AllocationFailed)?; + for table in 0..program.history_tables.len() { + tables.push(store.table_runtime(program, table)?); + } + Ok(Self { store, tables }) + } +} + +impl HistoryDecision { + fn check( + &self, + stored: &StoredHistory, + limits: &mut RegorusLimits<'_>, + ) -> core::result::Result<(), HistoryError> { + limits.publication_checkpoint()?; + if stored.revision() != self.revision || stored.len() < self.target_len { + return Err(HistoryError::HistoryChanged { + expected: self.revision, + actual: stored.revision(), + }); + } + Ok(()) + } +} + +impl VmError { + pub(super) fn from_history(error: HistoryError, pc: usize) -> Self { + match error { + HistoryError::Limit(LimitError::TimeLimitExceeded { elapsed, limit }) => { + VmError::TimeLimitExceeded { elapsed, limit, pc } + } + HistoryError::Limit(LimitError::MemoryLimitExceeded { usage, limit }) => { + VmError::MemoryLimitExceeded { usage, limit, pc } + } + HistoryError::Limit(LimitError::RegexSizeLimitExceeded { limit }) => { + VmError::RegexSizeLimitExceeded { limit, pc } + } + source => VmError::History { source, pc }, + } + } +} +impl RegoVM { + /// Attach the application-owned history service after loading the program. + /// Numeric templates and initial graphs are prepared outside decision timing. + pub fn attach_history(&mut self, store: Arc) -> Result<()> { + self.ensure_history_idle()?; + let attachment = HistoryAttachment::new(store, &self.program) + .map_err(|error| VmError::from_history(error, self.pc))?; + self.history_attachment = Some(attachment); + self.history_input = None; + self.clear_history_execution(); + Ok(()) + } + + /// Stage a typed request without appending it to the supplied history. + pub fn set_history_input(&mut self, history: HistoryHandle, request: Event) -> Result<()> { + self.ensure_history_idle()?; + let attachment = self + .history_attachment + .as_ref() + .ok_or(VmError::HistoryContextMissing { pc: self.pc })?; + attachment + .store + .history_record(&history) + .map_err(|error| VmError::from_history(error, self.pc))?; + attachment + .store + .validate_event(&request) + .map_err(|error| VmError::from_history(error, self.pc))?; + self.history_input = Some((history, request)); + self.clear_history_execution(); + Ok(()) + } + + const fn ensure_history_idle(&self) -> Result<()> { + // A failed suspendable run may leave a stale `Running` state; only suspension or an + // unpublished decision means a history execution is still live. + if matches!(self.execution_state, ExecutionState::Suspended { .. }) + || self.history_decision.is_some() + { + return Err(VmError::HistoryExecutionActive { pc: self.pc }); + } + Ok(()) + } + + pub(super) fn clear_history_execution(&mut self) { + self.history_decision = None; + self.history_active_rule = None; + } + + fn capture_history_decision(&mut self) -> Result<()> { + if self.history_decision.is_some() { + return Ok(()); + } + let attachment = self + .history_attachment + .as_ref() + .ok_or(VmError::HistoryContextMissing { pc: self.pc })?; + let staged = self + .history_input + .as_ref() + .ok_or(VmError::HistoryContextMissing { pc: self.pc })?; + let record = attachment + .store + .history_record(&staged.0) + .map_err(|error| VmError::from_history(error, self.pc))?; + let stored = record.read(); + RegorusLimits { + timer: &mut self.execution_timer, + } + .publication_checkpoint() + .map_err(|error| VmError::from_history(error.into(), self.pc))?; + let revision = stored.revision(); + let target_len = stored.len(); + drop(stored); + self.history_decision = Some(HistoryDecision { + record, + revision, + target_len, + request: staged.1, + }); + Ok(()) + } + + pub(super) fn finish_history_execution(&mut self) -> Result<()> { + let result = if let Some(decision) = self.history_decision.as_ref() { + let stored = decision.record.read(); + // Revalidate even terminal decisions: truncation may invalidate a pinned prefix. + decision + .check( + &stored, + &mut RegorusLimits { + timer: &mut self.execution_timer, + }, + ) + .map_err(|error| VmError::from_history(error, self.pc)) + } else { + Ok(()) + }; + self.clear_history_execution(); + result + } + + pub(super) fn execute_history_step(&mut self, params_index: u16) -> Result { + let pc = self.pc; + let params = self + .program + .instruction_data + .history_step_params + .get(usize::from(params_index)) + .ok_or(VmError::InvalidHistoryStepParams { + index: params_index, + pc, + })? + .clone(); + let table = self + .program + .history_tables + .get(usize::from(params.table)) + .ok_or(VmError::InvalidHistoryTableIndex { + index: params.table, + pc, + })?; + table + .rules + .get(usize::from(params.rule)) + .ok_or(VmError::InvalidHistoryRuleIndex { + table: params.table, + rule: params.rule, + pc, + })?; + if params.batch_size == 0 { + return Err(VmError::InvalidHistoryBatchSize { + batch_size: params.batch_size, + pc, + }); + } + let batch_size = usize::try_from(params.batch_size).map_err(|_| { + VmError::from_history( + HistoryError::Invariant { + message: "history batch_size does not fit usize", + }, + pc, + ) + })?; + self.capture_history_decision()?; + let attachment = self + .history_attachment + .as_ref() + .ok_or(VmError::HistoryContextMissing { pc })?; + let runtime = attachment + .tables + .get(usize::from(params.table)) + .cloned() + .ok_or(VmError::InvalidHistoryTableIndex { + index: params.table, + pc, + })?; + let slot = runtime.rules.get(usize::from(params.rule)).ok_or( + VmError::InvalidHistoryRuleIndex { + table: params.table, + rule: params.rule, + pc, + }, + )?; + let decision = self + .history_decision + .as_ref() + .ok_or(VmError::HistoryContextMissing { pc })?; + // A loaded program fixes parameters at each PC; loading another clears active execution. + if self + .history_active_rule + .as_ref() + .is_some_and(|active| active.pc != pc) + { + return Err(VmError::from_history( + HistoryError::Invariant { + message: "history continuation belongs to another instruction", + }, + pc, + )); + } + let mut world = ObservationWorld; + let mut limits = RegorusLimits { + timer: &mut self.execution_timer, + }; + let mut unmatched = false; + if self.history_active_rule.is_none() { + let instance = Arc::clone(&slot.current.lock()); + // Lock graph before history consistently; retain both guards through validation. + let mut graph = instance.lock(); + let stored = decision.record.read(); + decision + .check(&stored, &mut limits) + .map_err(|error| VmError::from_history(error, pc))?; + if let Some(bindings) = RuleRuntime::bindings(&slot.template, &decision.request) { + // Native provenance: this locked record is the staged history, and + // same-revision observations extend its previously recorded word. + let cursor = graph.resume_cursor(&bindings, &stored, decision.target_len); + drop(stored); + drop(graph); + self.history_active_rule = Some(ActiveHistoryRule { + pc, + bindings, + instance, + cursor, + retried: false, + }); + } else { + unmatched = true; + } + } + if unmatched { + // A request outside the head leaves the rule vacuously honored. + self.set_register(params.dest, Value::Bool(true))?; + return Ok(InstructionOutcome::Continue); + } + let active = self + .history_active_rule + .as_mut() + .ok_or(VmError::HistoryContextMissing { pc })?; + // Keep graph-before-history order through the fold and successful publication. + let mut graph = active.instance.lock(); + let stored = decision.record.read(); + decision + .check(&stored, &mut limits) + .map_err(|error| VmError::from_history(error, pc))?; + let outcome = graph.advance_cursor( + &mut active.cursor, + &active.bindings, + &stored, + decision.target_len, + batch_size, + &mut limits, + &mut world, + ); + match outcome { + Ok(answer) => { + drop(stored); + drop(graph); + match answer { + None => Ok(InstructionOutcome::Repeat), + Some(answer) => { + self.history_active_rule = None; + let violated = match slot.mode { + RuleMode::Require => !answer, + RuleMode::Forbid => answer, + }; + self.set_register(params.dest, Value::Bool(!violated))?; + Ok(InstructionOutcome::Continue) + } + } + } + Err(HistoryError::GraphBudget { .. } | HistoryError::GraphIndex) if !active.retried => { + let exhausted = Arc::clone(&active.instance); + let numeric_store = Arc::clone(graph.store()); + drop(stored); + drop(graph); + let replacement = RuleRuntime::new( + &numeric_store, + &slot.template, + false, + &mut limits, + &mut world, + ) + .map_err(|error| VmError::from_history(error, pc))?; + let replacement = slot.replace(&exhausted, Arc::new(Mutex::new(replacement))); + let cursor = replacement.lock().root_cursor(); + active.instance = replacement; + active.cursor = cursor; + active.retried = true; + Ok(InstructionOutcome::Repeat) + } + Err(error) => Err(VmError::from_history(error, pc)), + } + } +} + +#[cfg(test)] +mod tests { + #![allow( + clippy::unwrap_used, + clippy::indexing_slicing, + clippy::arithmetic_side_effects + )] + + use super::*; + use crate::languages::history_table::{ACTION, PRINCIPAL, RESOURCE}; + use crate::languages::rego::compiler::Compiler; + use crate::rvm::program::Program; + use crate::rvm::vm::ExecutionMode; + use crate::utils::limits::ExecutionTimer; + use junco_core::limits::MAX_GRAPH_BYTES; + + const ANY: &str = "{}"; + const ACTOR: &str = r#"{"principal": actor}"#; + const EQUALITY: &str = "{principal == actor}"; + const THREE_ACTIONS: &str = r#"[{action == "a"}, {action == "b"}, {action == "c"}]"#; + + /// One-rule `require` program `data.t.r0` with every step patched to `batch`. + fn program(request: &str, language: &str, batch: u32) -> Arc { + let mut engine = crate::Engine::new(); + engine + .add_policy( + "t.rego".into(), + alloc::format!( + "package t\nimport rego.v1\nr0 := history.require({request}, {language})\n" + ), + ) + .unwrap(); + let policy = engine.compile_with_entrypoint(&"data.t.r0".into()).unwrap(); + let mut program = + (*Compiler::compile_from_policy(&policy, &["data.t.r0"]).unwrap()).clone(); + for params in &mut program.instruction_data.history_step_params { + params.batch_size = batch; + } + Arc::new(program) + } + + fn event(store: &HistoryStore, principal: &str, action: &str) -> Event { + store + .event(&[ + store.intern(PRINCIPAL, principal).unwrap(), + store.intern(ACTION, action).unwrap(), + store.intern(RESOURCE, "doc").unwrap(), + ]) + .unwrap() + } + + fn vm(store: &Arc, history: &HistoryHandle, program: &Arc) -> RegoVM { + let mut vm = RegoVM::new(); + vm.load_program(Arc::clone(program)); + vm.attach_history(Arc::clone(store)).unwrap(); + vm.set_history_input(history.clone(), event(store, "alice", "release")) + .unwrap(); + vm + } + + fn lazy_instance(vm: &RegoVM) -> Arc> { + let table = &vm.history_attachment.as_ref().unwrap().tables[0]; + let slot = &table.rules[0]; + let instance = Arc::new(Mutex::new( + RuleRuntime::new( + &history_store::store::HistoryStore::new(3), + &slot.template, + false, + &mut RegorusLimits { + timer: &mut ExecutionTimer::new(None), + }, + &mut ObservationWorld, + ) + .unwrap(), + )); + *slot.current.lock() = Arc::clone(&instance); + instance + } + + fn atoms_or(atoms: impl Iterator) -> alloc::string::String { + // A balanced tree keeps expression nesting under the parser's limit of 32; one + // alternative per line because the lexer caps lines at 1024 columns. + let mut level: Vec<_> = atoms.collect(); + while level.len() > 1 { + level = level + .chunks(2) + .map(|pair| match *pair { + [ref left, ref right] => alloc::format!("({left} |\n{right})"), + _ => pair[0].clone(), + }) + .collect(); + } + level.pop().unwrap_or_default() + } + + fn decide( + vm: &mut RegoVM, + store: &HistoryStore, + history: &HistoryHandle, + events: &[Event], + request: Event, + ) -> Value { + store.truncate(history, 0).unwrap(); + store.append(history, events).unwrap(); + vm.set_history_input(history.clone(), request).unwrap(); + vm.execute_entry_point_by_name("data.t.r0").unwrap() + } + + #[test] + fn negative_tests_cache_one_positive_equality_without_presence_atoms() { + let store = Arc::new(HistoryStore::new()); + let history = store.new_history().unwrap(); + let program = program(ACTOR, r#"{principal != "alice"}"#, 256); + let mut vm = vm(&store, &history, &program); + vm.set_execution_mode(ExecutionMode::RunToCompletion); + let instance = lazy_instance(&vm); + let alice = event(&store, "alice", "read"); + let bob = event(&store, "bob", "read"); + assert_eq!( + decide(&mut vm, &store, &history, &[bob], alice), + Value::Bool(true) + ); + assert_eq!( + decide(&mut vm, &store, &history, &[alice], alice), + Value::Bool(false) + ); + assert_eq!(instance.lock().work_counters().successor_misses, 2); + } + + #[test] + fn absorbing_states_skip_event_caches() { + for (regex, expected, visits, count) in [ + ("true", Value::Bool(true), 1, 1), + ("any", Value::Bool(true), 0, 2), + ("false", Value::Bool(false), 0, 2), + ] { + let store = Arc::new(HistoryStore::new()); + let history = store.new_history().unwrap(); + let program = program(ACTOR, regex, 256); + let mut vm = vm(&store, &history, &program); + vm.set_execution_mode(ExecutionMode::RunToCompletion); + let instance = lazy_instance(&vm); + let alice = event(&store, "alice", "read"); + assert_eq!( + decide(&mut vm, &store, &history, &[alice, alice][..count], alice), + expected + ); + let runtime = instance.lock(); + assert_eq!(runtime.work_counters().events, visits); + assert_eq!(runtime.work_counters().successor_misses, 0); + assert_eq!(runtime.work_counters().event_classes, 0); + } + } + + #[test] + fn derivative_cycles_keep_distinct_residuals_and_stabilize() { + let store = Arc::new(HistoryStore::new()); + let history = store.new_history().unwrap(); + let program = program( + ACTOR, + r#"star([{principal == "alice"}, {principal == "bob"}])"#, + 256, + ); + let mut vm = vm(&store, &history, &program); + vm.set_execution_mode(ExecutionMode::RunToCompletion); + let instance = lazy_instance(&vm); + let alice = event(&store, "alice", "read"); + let bob = event(&store, "bob", "read"); + assert_eq!( + decide(&mut vm, &store, &history, &[alice, bob], alice), + Value::Bool(true) + ); + let before = { + let runtime = instance.lock(); + runtime.work_counters().derivative_misses + }; + for _ in 0..64 { + assert_eq!( + decide(&mut vm, &store, &history, &[alice, bob], alice), + Value::Bool(true) + ); + } + { + let runtime = instance.lock(); + assert_eq!(runtime.work_counters().derivative_misses, before); + } + assert_eq!( + decide(&mut vm, &store, &history, &[alice], alice), + Value::Bool(false) + ); + assert_eq!( + decide(&mut vm, &store, &history, &[alice, alice], alice), + Value::Bool(false) + ); + assert_eq!( + decide(&mut vm, &store, &history, &[alice, bob, alice, bob], alice), + Value::Bool(true) + ); + } + + #[test] + fn folding_batches_matches_whole_word_without_answering_prefixes() { + for batch in [1, 2, 3] { + let store = Arc::new(HistoryStore::new()); + let history = store.new_history().unwrap(); + let program = program( + ACTOR, + &alloc::format!("[{EQUALITY}, {EQUALITY}, {EQUALITY}]"), + batch, + ); + let mut vm = vm(&store, &history, &program); + vm.set_execution_mode(ExecutionMode::RunToCompletion); + let alice = event(&store, "alice", "read"); + let bob = event(&store, "bob", "read"); + for events in [[alice, alice, alice], [alice, bob, alice]] { + let whole = decide(&mut vm, &store, &history, &events, alice); + assert_eq!( + whole, + if events[1] == alice { + Value::Bool(true) + } else { + Value::Bool(false) + } + ); + for split in 0..=events.len() { + let prefix = decide(&mut vm, &store, &history, &events[..split], alice); + assert_eq!( + prefix, + if split == 3 { + whole.clone() + } else { + Value::Bool(false) + } + ); + store.append(&history, &events[split..]).unwrap(); + vm.set_history_input(history.clone(), alice).unwrap(); + assert_eq!(vm.execute_entry_point_by_name("data.t.r0").unwrap(), whole); + } + } + let star_program = + super::tests::program(ACTOR, &alloc::format!("star({EQUALITY})"), batch); + let mut star_vm = super::tests::vm(&store, &history, &star_program); + star_vm.set_execution_mode(ExecutionMode::RunToCompletion); + assert_eq!( + decide(&mut star_vm, &store, &history, &[alice], alice), + Value::Bool(true) + ); + assert_eq!( + decide(&mut star_vm, &store, &history, &[alice, bob], alice), + Value::Bool(false) + ); + } + } + + #[test] + fn retained_residuals_avoid_replay_without_changing_answers() { + for mode in [ExecutionMode::RunToCompletion, ExecutionMode::Suspendable] { + let store = Arc::new(HistoryStore::new()); + let history = store.new_history().unwrap(); + let matching = event(&store, "alice", "edit"); + let rejecting = event(&store, "alice", "read"); + store.append(&history, &[matching; 256]).unwrap(); + let program = program(ANY, r#"star({action == "edit"})"#, 64); + let mut vm = vm(&store, &history, &program); + vm.set_execution_mode(mode); + let mut instance = lazy_instance(&vm); + assert_eq!( + vm.execute_entry_point_by_name("data.t.r0").unwrap(), + Value::Bool(true) + ); + + let mut compare = |length, reused_events, expected: Value| { + for retain in [true, false] { + if !retain { + // A fresh runtime has an empty cursor cache, forcing a full replay. + instance = lazy_instance(&vm); + } + instance.lock().reset_work_events(); + assert_eq!( + vm.execute_entry_point_by_name("data.t.r0").unwrap(), + expected + ); + assert_eq!( + instance.lock().work_counters().events, + if retain { reused_events } else { length }, + ); + } + }; + compare(256, 0, Value::Bool(true)); + store.append(&history, &[matching]).unwrap(); + compare(257, 1, Value::Bool(true)); + store.append(&history, &[rejecting]).unwrap(); + compare(258, 1, Value::Bool(false)); + } + } + + #[cfg(feature = "cache")] + #[test] + fn precompile_keeps_the_typed_lazy_language() { + let store = Arc::new(HistoryStore::new()); + let history = store.new_history().unwrap(); + let regex = alloc::format!("[any, {EQUALITY}, star({EQUALITY})]"); + let eager_program = program(ACTOR, ®ex, 256); + let lazy_program = program(ACTOR, ®ex, 256); + let mut eager = vm(&store, &history, &eager_program); + let mut lazy = vm(&store, &history, &lazy_program); + eager.set_execution_mode(ExecutionMode::RunToCompletion); + lazy.set_execution_mode(ExecutionMode::RunToCompletion); + let eager_instance = Arc::clone( + &eager.history_attachment.as_ref().unwrap().tables[0].rules[0] + .current + .lock(), + ); + let _lazy_instance = lazy_instance(&lazy); + // Precompilation may already count misses; decisions must add none. + let (derivative_misses, successor_misses) = { + let runtime = eager_instance.lock(); + let counters = runtime.work_counters(); + (counters.derivative_misses, counters.successor_misses) + }; + let alice = event(&store, "alice", "read"); + let bob = event(&store, "bob", "read"); + for (events, expected) in [ + (&[][..], Value::Bool(false)), + (&[alice][..], Value::Bool(true)), + (&[bob, alice, alice][..], Value::Bool(true)), + (&[alice, bob][..], Value::Bool(false)), + ] { + assert_eq!( + decide(&mut eager, &store, &history, events, alice), + expected + ); + assert_eq!(decide(&mut lazy, &store, &history, events, alice), expected); + } + let runtime = eager_instance.lock(); + assert_eq!(runtime.work_counters().derivative_misses, derivative_misses); + assert_eq!(runtime.work_counters().successor_misses, successor_misses); + } + + #[test] + fn event_class_lru_keeps_its_256_entry_ceiling() { + let tests = atoms_or((0..17).flat_map(|id| { + [ + alloc::format!(r#"{{principal == "identity-{id}"}}"#), + alloc::format!(r#"{{action == "identity-{id}"}}"#), + ] + })); + let store = Arc::new(HistoryStore::new()); + let history = store.new_history().unwrap(); + let program = program(ACTOR, &tests, 256); + let mut vm = vm(&store, &history, &program); + vm.set_execution_mode(ExecutionMode::RunToCompletion); + let instance = lazy_instance(&vm); + let mut first = None; + for principal in 0..17 { + for action in 0..17 { + let event = event( + &store, + &alloc::format!("identity-{principal}"), + &alloc::format!("identity-{action}"), + ); + first.get_or_insert(event); + assert_eq!( + decide(&mut vm, &store, &history, &[event], event), + Value::Bool(true) + ); + } + } + { + let runtime = instance.lock(); + assert_eq!(runtime.work_counters().successor_misses, 289); + } + let first = first.unwrap(); + assert_eq!( + decide(&mut vm, &store, &history, &[first], first), + Value::Bool(true) + ); + let runtime = instance.lock(); + assert_eq!(runtime.work_counters().successor_misses, 290); + } + + #[cfg(feature = "cache")] + #[test] + fn precompile_leaves_wide_typed_transitions_lazy() { + for count in [9, 8] { + let tests = atoms_or( + (0..count).map(|id| alloc::format!(r#"{{principal == "identity-{id}"}}"#)), + ); + let store = Arc::new(HistoryStore::new()); + let history = store.new_history().unwrap(); + let program = program(ACTOR, &tests, 256); + let mut vm = vm(&store, &history, &program); + vm.set_execution_mode(ExecutionMode::RunToCompletion); + let instance = Arc::clone( + &vm.history_attachment.as_ref().unwrap().tables[0].rules[0] + .current + .lock(), + ); + let before = instance.lock().work_counters().successor_misses; + let matching = event(&store, "identity-0", "read"); + let nonmatching = event(&store, "outside", "read"); + assert_eq!( + decide(&mut vm, &store, &history, &[matching], matching), + Value::Bool(true) + ); + assert_eq!( + decide(&mut vm, &store, &history, &[nonmatching], nonmatching), + Value::Bool(false) + ); + assert_eq!( + instance.lock().work_counters().successor_misses == before, + count == 8 + ); + } + } + + #[test] + fn compiled_runtime_uses_send_dependencies() { + fn assert_send() {} + assert_send::(); + } + + #[test] + fn batch_cursor_ends_and_retained_prefix_are_exact() { + let store = Arc::new(HistoryStore::new()); + let history = store.new_history().unwrap(); + let event = event(&store, "alice", "edit"); + store.append(&history, &[event; 7]).unwrap(); + let program = program(ANY, "any", 3); + let mut first = vm(&store, &history, &program); + let instance = lazy_instance(&first); + assert!(matches!( + first.execute_history_step(0).unwrap(), + InstructionOutcome::Repeat + )); + assert_eq!( + first + .history_active_rule + .as_ref() + .unwrap() + .cursor + .consumed(), + 3 + ); + assert_eq!(instance.lock().cursor_positions()[0].3, 3); + let mut second = vm(&store, &history, &program); + assert!(matches!( + second.execute_history_step(0).unwrap(), + InstructionOutcome::Repeat + )); + assert_eq!( + second + .history_active_rule + .as_ref() + .unwrap() + .cursor + .consumed(), + 6 + ); + assert!(matches!( + second.execute_history_step(0).unwrap(), + InstructionOutcome::Continue + )); + assert_eq!(instance.lock().cursor_positions()[0].3, 7); + // A slower decision cannot replace the shared longer committed prefix. + assert!(matches!( + first.execute_history_step(0).unwrap(), + InstructionOutcome::Repeat + )); + assert_eq!( + first + .history_active_rule + .as_ref() + .unwrap() + .cursor + .consumed(), + 6 + ); + assert_eq!(instance.lock().cursor_positions()[0].3, 7); + assert!(matches!( + first.execute_history_step(0).unwrap(), + InstructionOutcome::Continue + )); + assert!(first.history_active_rule.is_none()); + assert_eq!(instance.lock().cursor_positions()[0].3, 7); + } + + #[test] + fn failed_batch_and_final_answer_never_publish() { + let store = Arc::new(HistoryStore::new()); + let history = store.new_history().unwrap(); + let mut empty_vm = vm(&store, &history, &program(ANY, "[]", 3)); + let empty_instance = lazy_instance(&empty_vm); + empty_instance.lock().set_answer_checkpoint_failure(true); + let pc = empty_vm.pc; + assert!( + matches!(empty_vm.execute_history_step(0).unwrap_err(), VmError::TimeLimitExceeded { pc: actual, .. } if actual == pc) + ); + assert_eq!( + empty_vm + .history_active_rule + .as_ref() + .unwrap() + .cursor + .consumed(), + 0 + ); + assert!(empty_instance.lock().cursor_positions().is_empty()); + empty_instance.lock().set_answer_checkpoint_failure(false); + assert!(matches!( + empty_vm.execute_history_step(0).unwrap(), + InstructionOutcome::Continue + )); + assert_eq!(empty_instance.lock().cursor_positions()[0].3, 0); + + let event = event(&store, "alice", "edit"); + store.append(&history, &[event; 2]).unwrap(); + let mut final_vm = vm(&store, &history, &program(ANY, "any", 1)); + let final_instance = lazy_instance(&final_vm); + assert!(matches!( + final_vm.execute_history_step(0).unwrap(), + InstructionOutcome::Repeat + )); + let entry = final_vm.history_active_rule.as_ref().unwrap().cursor; + let retained = final_instance.lock().cursor_positions(); + final_instance.lock().set_answer_checkpoint_failure(true); + let final_pc = final_vm.pc; + assert!( + matches!(final_vm.execute_history_step(0).unwrap_err(), VmError::TimeLimitExceeded { pc: actual, .. } if actual == final_pc) + ); + let final_cursor = final_vm.history_active_rule.as_ref().unwrap().cursor; + assert_eq!(final_cursor.consumed(), entry.consumed()); + assert_eq!(final_instance.lock().cursor_positions(), retained); + final_instance.lock().set_answer_checkpoint_failure(false); + assert!(matches!( + final_vm.execute_history_step(0).unwrap(), + InstructionOutcome::Continue + )); + assert_eq!(final_instance.lock().cursor_positions()[0].3, 2); + } + + #[test] + fn graph_replacement_keeps_two_old_continuations_valid() { + let store = Arc::new(HistoryStore::new()); + let history = store.new_history().unwrap(); + store + .append( + &history, + &[ + event(&store, "alice", "a"), + event(&store, "alice", "b"), + event(&store, "alice", "c"), + ], + ) + .unwrap(); + let program = program(ANY, THREE_ACTIONS, 1); + let mut first = vm(&store, &history, &program); + let old = lazy_instance(&first); + let mut second = vm(&store, &history, &program); + let old_weak = Arc::downgrade(&old); + assert!(matches!( + first.execute_history_step(0).unwrap(), + InstructionOutcome::Repeat + )); + assert!(matches!( + second.execute_history_step(0).unwrap(), + InstructionOutcome::Repeat + )); + assert_eq!( + first + .history_active_rule + .as_ref() + .unwrap() + .cursor + .consumed(), + 1 + ); + assert_eq!( + second + .history_active_rule + .as_ref() + .unwrap() + .cursor + .consumed(), + 2 + ); + assert!(Arc::ptr_eq( + &first.history_active_rule.as_ref().unwrap().instance, + &old + )); + assert!(Arc::ptr_eq( + &second.history_active_rule.as_ref().unwrap().instance, + &old + )); + let previous_bytes = old.lock().replace_graph_byte_pressure(MAX_GRAPH_BYTES); + assert!(matches!( + second.execute_history_step(0).unwrap(), + InstructionOutcome::Repeat + )); + let replacement = Arc::clone(&second.history_active_rule.as_ref().unwrap().instance); + assert!(!Arc::ptr_eq(&replacement, &old)); + assert_eq!( + second + .history_active_rule + .as_ref() + .unwrap() + .cursor + .consumed(), + 0 + ); + assert!(second.history_active_rule.as_ref().unwrap().retried); + assert!(old_weak.upgrade().is_some()); + + old.lock().replace_graph_byte_pressure(previous_bytes); + assert!(matches!( + first.execute_history_step(0).unwrap(), + InstructionOutcome::Repeat + )); + assert!(matches!( + first.execute_history_step(0).unwrap(), + InstructionOutcome::Continue + )); + assert!(old_weak.upgrade().is_some()); + drop(old); + assert!(old_weak.upgrade().is_none()); + for expected in [1, 2] { + assert!(matches!( + second.execute_history_step(0).unwrap(), + InstructionOutcome::Repeat + )); + assert_eq!( + second + .history_active_rule + .as_ref() + .unwrap() + .cursor + .consumed(), + expected + ); + } + assert!(matches!( + second.execute_history_step(0).unwrap(), + InstructionOutcome::Continue + )); + assert_eq!(replacement.lock().cursor_positions()[0].3, 3); + } + + #[test] + fn graph_recovery_has_one_retry_and_losing_replacements_drop() { + let store = Arc::new(HistoryStore::new()); + let history = store.new_history().unwrap(); + store + .append( + &history, + &[ + event(&store, "alice", "a"), + event(&store, "alice", "b"), + event(&store, "alice", "c"), + ], + ) + .unwrap(); + let program = program(ANY, THREE_ACTIONS, 1); + let mut vm = vm(&store, &history, &program); + let old = lazy_instance(&vm); + old.lock().replace_graph_byte_pressure(MAX_GRAPH_BYTES); + assert!(matches!( + vm.execute_history_step(0).unwrap(), + InstructionOutcome::Repeat + )); + let winner = Arc::clone(&vm.history_active_rule.as_ref().unwrap().instance); + let table = Arc::clone(&vm.history_attachment.as_ref().unwrap().tables[0]); + let slot = &table.rules[0]; + let losing = RuleRuntime::new( + &history_store::store::HistoryStore::new(3), + &slot.template, + false, + &mut RegorusLimits { + timer: &mut ExecutionTimer::new(None), + }, + &mut ObservationWorld, + ) + .unwrap(); + let losing = Arc::new(Mutex::new(losing)); + let losing_weak = Arc::downgrade(&losing); + let selected = slot.replace(&old, losing); + assert!(Arc::ptr_eq(&selected, &winner)); + assert!(losing_weak.upgrade().is_none()); + // Recovery rebinds the replacement to the exhausted runtime's numeric store. + assert!(Arc::ptr_eq(winner.lock().store(), old.lock().store())); + winner.lock().replace_graph_byte_pressure(MAX_GRAPH_BYTES); + let error = vm.execute_history_step(0).unwrap_err(); + assert!(matches!( + error, + VmError::History { + source: HistoryError::GraphBudget { .. }, + .. + } + )); + assert_eq!( + vm.history_active_rule.as_ref().unwrap().cursor.consumed(), + 0 + ); + assert!(winner.lock().cursor_positions().is_empty()); + } + + #[test] + fn table_eviction_reclaims_only_unpinned_graphs() { + let store = Arc::new(HistoryStore::new()); + let history = store.new_history().unwrap(); + let event = event(&store, "alice", "edit"); + let first = store.table_runtime(&program(ANY, "any", 1), 0).unwrap(); + let weak = Arc::downgrade(&first); + let pinned = Arc::clone(&first.rules[0].current.lock()); + let pinned_weak = Arc::downgrade(&pinned); + drop(first); + for _ in 0..17 { + store.table_runtime(&program(ANY, "any", 1), 0).unwrap(); + } + assert!(weak.upgrade().is_none()); + assert!(pinned_weak.upgrade().is_some()); + store.append(&history, &[event]).unwrap(); + assert_eq!(store.len(&history).unwrap(), 1); + assert_eq!(store.intern(ACTION, "edit").unwrap(), event.component(1)); + drop(pinned); + assert!(pinned_weak.upgrade().is_none()); + } + + #[test] + fn terminal_snapshot_failure_retains_only_successful_batches() { + let store = Arc::new(HistoryStore::new()); + let history = store.new_history().unwrap(); + let event = event(&store, "alice", "edit"); + store.append(&history, &[event; 2]).unwrap(); + let mut vm = vm(&store, &history, &program(ANY, "any", 1)); + let instance = lazy_instance(&vm); + assert!(matches!( + vm.execute_history_step(0).unwrap(), + InstructionOutcome::Repeat + )); + assert!(matches!( + vm.execute_history_step(0).unwrap(), + InstructionOutcome::Continue + )); + assert_eq!(instance.lock().cursor_positions()[0].3, 2); + store.truncate(&history, 0).unwrap(); + let error = vm.finish_history_execution().unwrap_err(); + assert!(matches!( + error, + VmError::History { + source: HistoryError::HistoryChanged { + expected: 0, + actual: 1 + }, + .. + } + )); + assert!(vm.history_decision.is_none()); + assert!(vm.history_active_rule.is_none()); + assert_eq!(instance.lock().cursor_positions()[0].3, 2); + assert_eq!(instance.lock().cursor_positions()[0].2, 0); + } + + #[test] + fn retained_cursor_lru_is_bounded_and_keeps_recent_histories() { + let store = Arc::new(HistoryStore::new()); + let program = program(ANY, "any", 3); + let first = store.new_history().unwrap(); + let initial = vm(&store, &first, &program); + let instance = lazy_instance(&initial); + let mut keys = Vec::new(); + for _ in 0..17 { + let history = store.new_history().unwrap(); + keys.push(history.index()); + let mut vm = vm(&store, &history, &program); + assert!(matches!( + vm.execute_history_step(0).unwrap(), + InstructionOutcome::Continue + )); + } + let runtime = instance.lock(); + let positions = runtime.cursor_positions(); + assert_eq!(positions.len(), 16); + assert_eq!(positions[0].0, keys[16]); + assert_eq!(positions[15].0, keys[1]); + assert!(positions.iter().all(|cursor| cursor.1 == positions[0].1)); + } + + #[cfg(feature = "std")] + #[test] + fn typed_history_runtime_is_thread_safe() { + fn send() {} + fn send_sync() {} + send_sync::(); + send::(); + send::(); + } +} diff --git a/src/rvm/vm/machine.rs b/src/rvm/vm/machine.rs index 9ecb75c8e..f26261d9a 100644 --- a/src/rvm/vm/machine.rs +++ b/src/rvm/vm/machine.rs @@ -42,7 +42,8 @@ pub(super) enum MemoryBudgetLifecycle { } /// The Rego Virtual Machine -#[derive(Debug)] +// History handles and records implement Debug only outside Verus builds. +#[cfg_attr(not(verus_keep_ghost), derive(Debug))] pub struct RegoVM { /// Registers for storing values during execution pub(super) registers: Vec, @@ -161,6 +162,19 @@ pub struct RegoVM { /// Cooperative execution timer used to enforce wall-clock limits pub(super) execution_timer: ExecutionTimer, + /// Attachment/input survive ordinary executions, never program replacement. + #[cfg(feature = "history")] + pub(super) history_attachment: Option, + #[cfg(feature = "history")] + pub(super) history_input: Option<( + crate::languages::history_table::HistoryHandle, + crate::languages::history_table::Event, + )>, + #[cfg(feature = "history")] + pub(super) history_decision: Option, + #[cfg(feature = "history")] + pub(super) history_active_rule: Option, + /// Elapsed wall-clock time recorded when the VM entered a suspended state pub(super) execution_timer_elapsed_at_suspend: Option, @@ -286,6 +300,14 @@ impl RegoVM { builtins_cache: BTreeMap::new(), execution_timer_config: None, execution_timer: ExecutionTimer::new(fallback_timer), + #[cfg(feature = "history")] + history_attachment: None, + #[cfg(feature = "history")] + history_input: None, + #[cfg(feature = "history")] + history_decision: None, + #[cfg(feature = "history")] + history_active_rule: None, execution_timer_elapsed_at_suspend: None, #[cfg(all(feature = "allocator-memory-limits", not(miri)))] memory_budget_config: None, @@ -318,16 +340,23 @@ impl RegoVM { /// Load a complete program for execution pub fn load_program(&mut self, program: Arc) { + // Loading cancels even a suspended execution; resuming the old program is invalid. + self.release_previous_execution_state(); #[cfg(all(feature = "allocator-memory-limits", not(miri)))] if matches!( self.memory_budget_lifecycle, MemoryBudgetLifecycle::SuspendableExecution ) { - self.release_previous_execution_state(); self.finish_active_memory_budget_execution(); } self.program = program.clone(); + #[cfg(feature = "history")] + { + self.history_attachment = None; + self.history_input = None; + self.clear_history_execution(); + } self.program_tree_error = crate::utils::depth::check_value(&program.rule_tree, Program::MAX_PATH_DEPTH).err(); diff --git a/src/rvm/vm/mod.rs b/src/rvm/vm/mod.rs index e7254c456..6afd91c87 100644 --- a/src/rvm/vm/mod.rs +++ b/src/rvm/vm/mod.rs @@ -12,6 +12,8 @@ mod execution_model; #[cfg(feature = "explanations")] mod explain; mod functions; +#[cfg(feature = "history")] +pub(crate) mod history_tables; mod loops; mod machine; mod rules; diff --git a/src/rvm/vm/rules.rs b/src/rvm/vm/rules.rs index af898272c..dc8d64bfe 100644 --- a/src/rvm/vm/rules.rs +++ b/src/rvm/vm/rules.rs @@ -17,21 +17,32 @@ use super::execution_model::{ use super::machine::RegoVM; impl RegoVM { - /// Returns true if the error represents a resource-limit violation that - /// must never be silently absorbed by rule evaluation. + /// Returns true if the error represents a resource-limit violation or a history + /// failure that must never be silently absorbed by rule evaluation. pub(super) const fn is_fatal_vm_error(&self, err: &VmError) -> bool { - self.builtin_limit_exceeded - || matches!( - err, - VmError::TimeLimitExceeded { .. } - | VmError::RuleCallDepthExceeded { .. } - | VmError::MemoryLimitExceeded { .. } - | VmError::MemoryBudgetExceeded { .. } - | VmError::RegexSizeLimitExceeded { .. } - | VmError::SerializationDepthExceeded { .. } - | VmError::InstructionLimitExceeded { .. } - | VmError::NumericOverflow { .. } - ) + if self.builtin_limit_exceeded { + return true; + } + match *err { + VmError::TimeLimitExceeded { .. } + | VmError::RuleCallDepthExceeded { .. } + | VmError::MemoryLimitExceeded { .. } + | VmError::MemoryBudgetExceeded { .. } + | VmError::RegexSizeLimitExceeded { .. } + | VmError::SerializationDepthExceeded { .. } + | VmError::InstructionLimitExceeded { .. } + | VmError::NumericOverflow { .. } + | VmError::HistoryFeatureDisabled { .. } => true, + #[cfg(feature = "history")] + VmError::History { .. } + | VmError::HistoryContextMissing { .. } + | VmError::HistoryExecutionActive { .. } + | VmError::InvalidHistoryStepParams { .. } + | VmError::InvalidHistoryTableIndex { .. } + | VmError::InvalidHistoryRuleIndex { .. } + | VmError::InvalidHistoryBatchSize { .. } => true, + _ => false, + } } /// Restore VM state that was swapped out for rule execution. diff --git a/src/rvm/vm/state.rs b/src/rvm/vm/state.rs index 89f376d26..a5d697f86 100644 --- a/src/rvm/vm/state.rs +++ b/src/rvm/vm/state.rs @@ -29,6 +29,8 @@ impl RegoVM { } pub(super) fn release_previous_execution_state(&mut self) { + #[cfg(feature = "history")] + self.clear_history_execution(); self.evaluated = Value::Undefined; self.execution_state = ExecutionState::Ready; self.execution_stack.clear(); @@ -81,6 +83,9 @@ impl RegoVM { /// Resource failures also release state; other unbudgeted errors preserve legacy state. #[cfg(all(feature = "allocator-memory-limits", not(miri)))] pub(super) fn fail_suspendable_execution(&mut self, error: VmError) -> VmError { + // A failed execution never leaves a history decision for a later run to publish. + #[cfg(feature = "history")] + self.clear_history_execution(); if matches!( error, VmError::RuleCallDepthExceeded { .. } @@ -104,6 +109,9 @@ impl RegoVM { #[cfg(any(miri, not(feature = "allocator-memory-limits")))] pub(super) fn fail_suspendable_execution(&mut self, error: VmError) -> VmError { + // A failed execution never leaves a history decision for a later run to publish. + #[cfg(feature = "history")] + self.clear_history_execution(); if matches!( error, VmError::RuleCallDepthExceeded { .. } diff --git a/src/utils/limits/memory.rs b/src/utils/limits/memory.rs index 89ad6d84a..266befa23 100644 --- a/src/utils/limits/memory.rs +++ b/src/utils/limits/memory.rs @@ -1,7 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -use super::error::LimitError; +use super::LimitError; use core::cell::Cell; use core::num::NonZeroU64; use core::sync::atomic::{AtomicU64, Ordering}; diff --git a/src/utils/limits/mod.rs b/src/utils/limits/mod.rs index f299d694f..0fbf0870f 100644 --- a/src/utils/limits/mod.rs +++ b/src/utils/limits/mod.rs @@ -5,14 +5,13 @@ #![allow(dead_code)] -mod error; mod length; #[cfg(all(feature = "allocator-memory-limits", not(miri)))] mod memory; mod time; #[allow(unused_imports)] -pub use error::LimitError; +pub use junco_core::limits::LimitError; #[allow(unused_imports)] #[cfg(all(feature = "allocator-memory-limits", not(miri)))] diff --git a/src/verify/history_host.rs b/src/verify/history_host.rs new file mode 100644 index 000000000..ab4eaf32e --- /dev/null +++ b/src/verify/history_host.rs @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +//! Native clock, timer and configured-memory observations for the shared history engine. + +use crate::languages::history_table::limits::RegorusLimits; +use crate::utils::limits::{ + check_memory_limit_if_needed, enforce_memory_limit, monotonic_now, ExecutionTimer, + ExecutionTimerConfig, LimitError, +}; +use alloc::sync::Arc; +use core::time::Duration; +use history_semantics::runtime::{verify as runtime, BatchCursor, RuleRuntime}; +use history_store::history::StoredHistory; +use history_store::store::HistoryStore as CoreHistoryStore; +use junco_core::{ + errors::HistoryError, flat::FlatPair, kernel::Bindings, observation::ObservationWorld, +}; +use vstd::prelude::*; + +verus! { + +#[verifier::external_type_specification] +#[verifier::external_body] +pub struct ExExecutionTimer(ExecutionTimer); + +#[verifier::external_type_specification] +#[verifier::external_body] +pub struct ExExecutionTimerConfig(ExecutionTimerConfig); + +pub assume_specification[ ExecutionTimer::config ](timer: &ExecutionTimer) -> Option; + +pub assume_specification[ ExecutionTimer::accumulate ]( + timer: &mut ExecutionTimer, work_units: u32, +) -> bool; + +pub assume_specification[ ExecutionTimer::check_now ]( + timer: &mut ExecutionTimer, now: Duration, +) -> Result<(), LimitError>; + +pub assume_specification[ check_memory_limit_if_needed ]() -> Result<(), LimitError>; +pub assume_specification[ enforce_memory_limit ]() -> Result<(), LimitError>; +pub assume_specification[ monotonic_now ]() -> Option; + +// Instantiate the shared verified bodies with the real host budget adapter. +pub fn construct_with_host_limits( + store: &Arc, template: &FlatPair, precompile: bool, + timer: &mut ExecutionTimer, world: &mut ObservationWorld, +) -> (result: Result) + ensures runtime::constructor_result(result, *store, *template), + result matches Ok(engine) ==> runtime::runtime_wf(engine) && engine.spec_store() == *store, +{ + let mut limits = RegorusLimits { timer }; + let result = RuleRuntime::new(store, template, precompile, &mut limits, world); + proof { + if let Ok(engine) = &result { + runtime::lemma_constructor_runtime_wf(*engine, *store, *template); + } + } + result +} + +// The cache key is the locked record's own immutable ID, never a caller-supplied index. +pub fn resume_with_host_provenance( + engine: &mut RuleRuntime, bindings: &Bindings, + stored: &StoredHistory, target_len: usize, +) -> (cursor: BatchCursor) + requires runtime::resume_requires(*old(engine), *bindings, *stored, target_len), + ensures runtime::resume_ensures(*old(engine), *final(engine), cursor, + *bindings, *stored, target_len), + runtime::advance_requires(*final(engine), cursor, *bindings, *stored), + final(engine).spec_store() == old(engine).spec_store(), +{ + let ghost before = *engine; + let cursor = engine.resume_cursor(bindings, stored, target_len); + proof { + runtime::lemma_resume_can_advance(before, *engine, cursor, *bindings, *stored, target_len); + } + cursor +} + +pub fn advance_with_host_limits( + engine: &mut RuleRuntime, cursor: &mut BatchCursor, + bindings: &Bindings, stored: &StoredHistory, + target_len: usize, batch_size: usize, + timer: &mut ExecutionTimer, world: &mut ObservationWorld, +) -> (result: Result, HistoryError>) + requires runtime::advance_requires(*old(engine), *old(cursor), *bindings, *stored), + ensures runtime::advance_ensures(*old(engine), *final(engine), *old(cursor), *final(cursor), + *bindings, *stored, target_len, batch_size, result), + runtime::runtime_wf(*final(engine)), + runtime::runtime_frame(*old(engine), *final(engine)), + final(engine).spec_store() == old(engine).spec_store(), + result is Err ==> runtime::cursor_consumed(*final(cursor)) == runtime::cursor_consumed(*old(cursor)) + && runtime::cursor_cache_unchanged(*old(engine), *final(engine)), + result matches Ok(None) ==> runtime::cursor_consumed(*final(cursor)) < target_len, + result matches Ok(Some(_)) ==> runtime::cursor_consumed(*final(cursor)) == target_len, +{ + let mut limits = RegorusLimits { timer }; + let ghost before = *engine; + let ghost start = *cursor; + let result = engine.advance_cursor(cursor, bindings, stored, target_len, batch_size, &mut limits, world); + proof { + runtime::lemma_advance_result_facts(before, *engine, start, *cursor, + *bindings, *stored, target_len, batch_size, result); + } + result +} + +} diff --git a/src/verify/mod.rs b/src/verify/mod.rs index 5a26bccea..870119fdf 100644 --- a/src/verify/mod.rs +++ b/src/verify/mod.rs @@ -6,6 +6,8 @@ pub(crate) mod bigint_proofs; pub(crate) mod f64_assumptions; #[cfg(test)] mod f64_tests; +#[cfg(all(verus_keep_ghost, feature = "history"))] +pub(crate) mod history_host; #[cfg(verus_keep_ghost)] pub(crate) mod num_assumptions; #[cfg(verus_keep_ghost)] diff --git a/tests/fixtures/history_table_v7.bin b/tests/fixtures/history_table_v7.bin new file mode 100644 index 000000000..5eed31b84 Binary files /dev/null and b/tests/fixtures/history_table_v7.bin differ diff --git a/tests/fixtures/history_table_v7.json b/tests/fixtures/history_table_v7.json new file mode 100644 index 000000000..07da2aed2 --- /dev/null +++ b/tests/fixtures/history_table_v7.json @@ -0,0 +1,230 @@ +{ + "builtin_info_table": [], + "entry_points": { + "data.t.r0": 0 + }, + "history_tables": [ + { + "rules": [ + { + "mode": "Require", + "source": { + "head": [ + "Bind", + { + "Constant": "release" + }, + "Bind" + ], + "regexes": [ + "All", + { + "Test": 3 + }, + "All", + { + "Concat": [ + 0, + 1, + 2 + ] + } + ], + "root": 3, + "tests": [ + { + "Atom": { + "field": 0, + "positive": true, + "term": { + "Variable": 0 + } + } + }, + { + "Atom": { + "field": 1, + "positive": true, + "term": { + "Constant": "edit" + } + } + }, + { + "Atom": { + "field": 2, + "positive": true, + "term": { + "Variable": 2 + } + } + }, + { + "And": [ + 0, + 1, + 2 + ] + } + ] + } + } + ] + } + ], + "instruction_data": { + "array_create_params": [], + "builtin_call_params": [], + "chained_index_params": [], + "comprehension_begin_params": [], + "function_call_params": [], + "history_step_params": [ + { + "batch_size": 1, + "dest": 1, + "rule": 0, + "table": 0 + } + ], + "loop_params": [], + "object_create_params": [], + "set_create_params": [], + "virtual_data_document_lookup_params": [] + }, + "instruction_spans": [ + { + "column": 0, + "length": 0, + "line": 0, + "source_index": 0 + }, + { + "column": 0, + "length": 0, + "line": 0, + "source_index": 0 + }, + { + "column": 22, + "length": 144, + "line": 3, + "source_index": 0 + }, + { + "column": 22, + "length": 144, + "line": 3, + "source_index": 0 + }, + { + "column": 22, + "length": 144, + "line": 3, + "source_index": 0 + }, + { + "column": 22, + "length": 144, + "line": 3, + "source_index": 0 + }, + { + "column": 22, + "length": 144, + "line": 3, + "source_index": 0 + } + ], + "instructions": [ + { + "CallRule": { + "dest": 1, + "rule_index": 0 + } + }, + { + "Return": { + "value": 1 + } + }, + { + "RuleInit": { + "result_reg": 0, + "rule_index": 0 + } + }, + { + "HistoryStep": { + "params_index": 0 + } + }, + { + "Guard": { + "mode": "NotUndefined", + "register": 1 + } + }, + { + "Move": { + "dest": 0, + "src": 1 + } + }, + { + "RuleReturn": {} + } + ], + "literals": [], + "metadata": { + "annotations": {}, + "compiled_at": "unknown", + "compiler_version": "0.15.0", + "has_host_await": false, + "language": "", + "needs_recompilation": false, + "needs_runtime_recursion_check": false, + "optimization_level": 0, + "rego_v0": false, + "source_info": "unknown" + }, + "program_structure": { + "dispatch_window_size": 2, + "main_entry_point": 0, + "max_rule_window_size": 2 + }, + "rule_infos": [ + { + "default_literal_index": null, + "definitions": [ + [ + 2 + ] + ], + "destructuring_blocks": [ + null + ], + "early_exit_on_first_success": false, + "else_bodies": [ + [] + ], + "function_info": null, + "name": "data.t.r0", + "num_registers": 2, + "result_reg": 0, + "rule_type": "Complete" + } + ], + "rule_tree": { + "data": { + "t": { + "r0": 0 + } + } + }, + "sources": [ + { + "content": "package t\nimport rego.v1\nr0 := history.require({\"action\": \"release\", \"principal\": actor, \"resource\": doc}, [any, {principal == actor, action == \"edit\", resource == doc}, any])\n", + "name": "t.rego" + } + ] +} \ No newline at end of file diff --git a/tests/gate_blob_consume.rs b/tests/gate_blob_consume.rs index d1e1525d9..cc2d50ba0 100644 --- a/tests/gate_blob_consume.rs +++ b/tests/gate_blob_consume.rs @@ -147,12 +147,14 @@ fn trailing_data_is_rejected() { fn trailing_data_inside_each_section_is_rejected() { let blob = sample(); let (entry_points, sources, literals, rule_tree) = sections(&blob); + let structure_end = rule_tree.end + 4 + u32_at(&blob, rule_tree.end); for (name, length_offset, end) in [ ("Entry points", 8, entry_points.end), ("Sources", 12, sources.end), ("Literals", 16, literals.end), ("Rule tree", 20, rule_tree.end), - ("Program structure", rule_tree.end, blob.len()), + ("Program structure", rule_tree.end, structure_end), + ("History", structure_end, blob.len()), ] { let mut corrupt = blob.clone(); corrupt.insert(end, 0x99); diff --git a/tests/history_table.rs b/tests/history_table.rs new file mode 100644 index 000000000..e84e7f3e2 --- /dev/null +++ b/tests/history_table.rs @@ -0,0 +1,2308 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +#![cfg(all(feature = "rvm", feature = "history"))] + +use history_semantics::CompiledRule; +use history_store::{History, Store}; +use history_syntax::{ + AtomPattern, Comparison, Component, ComponentPattern, Event as _, Head, RegexExpr, Rule, + RuleMode, TestExpr, +}; +use junco_core::flat::{FlatHead, FlatPair, FlatRegex, FlatTerm, FlatTest}; +use junco_core::limits::Unmetered; +use junco_core::observation::{fail_reservations_after, ObservationWorld}; +use junco_core::reference::{head_matches, Lang}; +use junco_core::{lower_flat, FlatEncoder}; +use regorus::languages::history_table::{ + Event, HistoryError, HistoryHandle, HistoryStore, ACTION, PRINCIPAL, RESOURCE, +}; +use regorus::languages::rego::compiler::{Compiler, CompilerError, HISTORY_BATCH_SIZE}; +use regorus::rvm::program::{ + generate_assembly_listing, AssemblyListingConfig, DeserializationResult, Program, +}; +use regorus::rvm::vm::{ExecutionMode, ExecutionState, RegoVM, SuspendReason, VmError}; +use regorus::rvm::Instruction; +use regorus::{Engine, Value}; +use serde_json::Value as Json; +use std::fmt::Write as _; +use std::sync::Arc; + +const MODES: [ExecutionMode; 2] = [ExecutionMode::RunToCompletion, ExecutionMode::Suspendable]; +const BATCHES: [u32; 5] = [1, 2, 64, 256, 1024]; +const ACTIONS: [&str; 4] = ["edit", "read", "release", "remove"]; +const OWNED: [&str; 3] = ["edit", "release", "remove"]; +const READ: [&str; 2] = ["read", "remove"]; +type Sample = (usize, &'static str, usize); +/// History rule as Rego source: (`require` | `forbid`, request pattern, language). +type RuleSource = (&'static str, String, String); + +fn event(store: &HistoryStore, principal: &str, action: &str, resource: &str) -> Event { + store + .event(&[ + store.intern(PRINCIPAL, principal).unwrap(), + store.intern(ACTION, action).unwrap(), + store.intern(RESOURCE, resource).unwrap(), + ]) + .unwrap() +} + +struct Fixture { + store: Arc, + history: HistoryHandle, + vm: RegoVM, + program: Arc, + entry: &'static str, +} + +impl Fixture { + fn sample(&self, e: Sample) -> Event { + event(&self.store, &format!("a{}", e.0), e.1, &format!("f{}", e.2)) + } + + fn new(program: &Arc, mode: ExecutionMode) -> Self { + Self::with_store(program, mode, Arc::new(HistoryStore::new())) + } + + fn with_store(program: &Arc, mode: ExecutionMode, store: Arc) -> Self { + let history = store.new_history().unwrap(); + let mut vm = RegoVM::new(); + vm.load_program(program.clone()); + vm.set_execution_mode(mode); + vm.attach_history(store.clone()).unwrap(); + Self { + store, + history, + vm, + program: program.clone(), + entry: "data.t.first", + } + } + + fn with_entry(mut self, entry: &'static str) -> Self { + self.entry = entry; + self + } + + fn replace(&self, events: &[Event]) { + self.store.truncate(&self.history, 0).unwrap(); + self.store.append(&self.history, events).unwrap(); + } + + fn decide(&mut self, request: Event) -> Result { + self.vm.set_history_input(self.history.clone(), request)?; + self.vm.execute_entry_point_by_name(self.entry) + } + + fn run_to_history(&mut self) -> usize { + run_to_history(&mut self.vm, &self.program) + } +} + +/// Compile a Rego module through the engine and the RVM compiler. +fn program(source: &str, entry_points: &[&str]) -> Arc { + let mut engine = Engine::new(); + engine.add_policy("t.rego".into(), source.into()).unwrap(); + let policy = engine + .compile_with_entrypoint(&entry_points[0].into()) + .unwrap(); + Compiler::compile_from_policy(&policy, entry_points).unwrap() +} + +fn rule(mode: &'static str, request: &str, language: &str) -> RuleSource { + (mode, request.into(), language.into()) +} + +/// Rules `r`, `first` = least violated index (undefined when all hold), `allow` = all hold. +fn module(rules: &[RuleSource]) -> String { + let mut source = String::from("package t\nimport rego.v1\n"); + for (index, (mode, request, language)) in rules.iter().enumerate() { + writeln!(source, "r{index} := history.{mode}({request}, {language})").unwrap(); + writeln!(source, "violated contains {index} if not r{index}").unwrap(); + } + source.push_str("first := min(violated)\nallow if {\n"); + for index in 0..rules.len() { + writeln!(source, " r{index}").unwrap(); + } + source.push_str("}\n"); + source +} + +fn table(rules: &[RuleSource], batch: u32) -> Arc { + let rule_entries: Vec = (0..rules.len()).map(|i| format!("data.t.r{i}")).collect(); + let mut entry_points = vec!["data.t.first", "data.t.allow"]; + entry_points.extend(rule_entries.iter().map(String::as_str)); + with_batch(&program(&module(rules), &entry_points), batch) +} + +fn with_batch(program: &Arc, batch: u32) -> Arc { + let mut program = (**program).clone(); + for params in &mut program.instruction_data.history_step_params { + params.batch_size = batch; + } + Arc::new(program) +} + +fn step_pc(program: &Program) -> usize { + program + .instructions + .iter() + .position(|instruction| matches!(instruction, Instruction::HistoryStep { .. })) + .unwrap() +} + +fn expected(index: Option) -> Value { + index.map_or(Value::Undefined, Value::from) +} + +fn prior_edit_rule(release: &str, edit: &str) -> RuleSource { + rule( + "require", + &format!(r#"{{"action": "{release}", "principal": actor, "resource": doc}}"#), + &format!(r#"[any, {{principal == actor, action == "{edit}", resource == doc}}, any]"#), + ) +} + +#[test] +fn prior_edit_requires_same_principal_and_resource_without_appending_candidate() { + let program = table(&[prior_edit_rule("release", "edit")], 256); + for mode in MODES { + let mut f = Fixture::new(&program, mode); + let edit = event(&f.store, "alice", "edit", "doc"); + let release = event(&f.store, "alice", "release", "doc"); + let bob = event(&f.store, "bob", "release", "doc"); + let other = event(&f.store, "alice", "release", "other"); + assert_eq!(f.decide(release).unwrap(), Value::from(0usize)); + f.store.append(&f.history, &[edit]).unwrap(); + assert_eq!(f.decide(release).unwrap(), Value::Undefined); + assert_eq!(f.decide(bob).unwrap(), Value::from(0usize)); + assert_eq!(f.decide(other).unwrap(), Value::from(0usize)); + assert_eq!(f.decide(edit).unwrap(), Value::Undefined); + assert_eq!(f.store.len(&f.history).unwrap(), 1); + // Ordinary repeated execution keeps the staged typed input. + assert_eq!( + f.vm.execute_entry_point_by_name("data.t.first").unwrap(), + Value::Undefined + ); + } +} + +#[test] +fn cached_prefixes_preserve_history_revision_and_binding_semantics() { + let program = table(&[prior_edit_rule("release", "edit")], 1); + for mode in MODES { + let store = Arc::new(HistoryStore::new()); + let mut a = Fixture::with_store(&program, mode, store.clone()); + let mut b = Fixture::with_store(&program, mode, store.clone()); + let alice_edit = event(&store, "alice", "edit", "doc"); + let bob_edit = event(&store, "bob", "edit", "doc"); + let alice_release = event(&store, "alice", "release", "doc"); + let bob_release = event(&store, "bob", "release", "doc"); + store.append(&a.history, &[alice_edit]).unwrap(); + store.append(&b.history, &[bob_edit]).unwrap(); + + let assert_verdict = |f: &mut Fixture, request: Event, granted: bool| { + let len = f.store.len(&f.history).unwrap(); + assert_eq!( + f.decide(request).unwrap(), + expected((!granted).then_some(0)) + ); + assert_eq!(f.store.len(&f.history).unwrap(), len); + }; + + for _ in 0..2 { + assert_verdict(&mut a, alice_release, true); + assert_verdict(&mut a, bob_release, false); + assert_verdict(&mut b, alice_release, false); + assert_verdict(&mut b, bob_release, true); + } + + store.append(&b.history, &[alice_edit]).unwrap(); + assert_verdict(&mut b, alice_release, true); + assert_verdict(&mut b, bob_release, true); + + a.replace(&[bob_edit]); + assert_eq!(store.len(&a.history).unwrap(), 1); + assert_verdict(&mut a, alice_release, false); + assert_verdict(&mut a, bob_release, true); + assert_verdict(&mut b, alice_release, true); + assert_verdict(&mut b, bob_release, true); + + for _ in 0..17 { + let mut other = Fixture::with_store(&program, mode, store.clone()); + store.append(&other.history, &[alice_edit]).unwrap(); + assert_verdict(&mut other, alice_release, true); + assert_verdict(&mut other, bob_release, false); + } + + assert_verdict(&mut a, alice_release, false); + assert_verdict(&mut a, bob_release, true); + assert_verdict(&mut b, alice_release, true); + assert_verdict(&mut b, bob_release, true); + } +} + +#[test] +fn wrappers_share_histories_without_sharing_residuals() { + let program = table(&[prior_edit_rule("release", "edit")], 1); + for mode in MODES { + let peer = Arc::new(HistoryStore::new()); + // The VM caches tables in its own wrapper; histories and requests come from `peer`. + let mut f = Fixture::new(&program, mode); + let alice_edit = event(&peer, "alice", "edit", "doc"); + let bob_edit = event(&peer, "bob", "edit", "doc"); + let alice_release = event(&peer, "alice", "release", "doc"); + let bob_release = event(&peer, "bob", "release", "doc"); + let other_release = event(&peer, "alice", "release", "other"); + let history = peer.new_history().unwrap(); + let interleaved = peer.new_history().unwrap(); + let mut decide = |history: &HistoryHandle, request: Event| { + f.vm.set_history_input(history.clone(), request).unwrap(); + f.vm.execute_entry_point_by_name(f.entry).unwrap() + }; + let deny = Value::from(0usize); + assert_eq!(decide(&history, alice_release), deny); + // Equal lengths, revisions and bindings: only the record key separates residuals. + peer.append(&history, &[alice_edit]).unwrap(); + peer.append(&interleaved, &[bob_edit]).unwrap(); + for _ in 0..2 { + assert_eq!(decide(&history, alice_release), Value::Undefined); + assert_eq!(decide(&interleaved, alice_release), deny); + assert_eq!(decide(&history, bob_release), deny); + assert_eq!(decide(&interleaved, bob_release), Value::Undefined); + assert_eq!(decide(&history, other_release), deny); + } + peer.truncate(&history, 0).unwrap(); + peer.append(&history, &[bob_edit]).unwrap(); + assert_eq!(decide(&history, alice_release), deny); + assert_eq!(decide(&history, bob_release), Value::Undefined); + assert_eq!(peer.len(&history).unwrap(), 1); + assert_eq!(peer.len(&interleaved).unwrap(), 1); + } +} + +fn approval_rule() -> RuleSource { + let no_edit = r#"star({resource != doc} | {action != "edit"})"#; + rule( + "require", + r#"{"action": "release", "principal": actor, "resource": doc}"#, + &format!( + r#"[any, {{resource == doc, action == "edit", principal == actor}}, {no_edit}, {{resource == doc, action == "approve", principal != actor}}, {no_edit}]"# + ), + ) +} + +#[test] +fn approval_must_follow_edit_be_other_actor_and_not_be_stale() { + let program = table(&[approval_rule()], 256); + for mode in MODES { + let mut f = Fixture::new(&program, mode); + let edit = event(&f.store, "alice", "edit", "doc"); + let approve = event(&f.store, "bob", "approve", "doc"); + let self_approve = event(&f.store, "alice", "approve", "doc"); + let wrong = event(&f.store, "bob", "approve", "other"); + let unrelated = event(&f.store, "alice", "edit", "other"); + let request = event(&f.store, "alice", "release", "doc"); + for (history, grant) in [ + (vec![], false), + (vec![edit], false), + (vec![approve, edit], false), + (vec![edit, self_approve], false), + (vec![edit, wrong], false), + (vec![edit, approve], true), + (vec![edit, approve, edit], false), + (vec![edit, approve, unrelated], true), + (vec![edit, approve, edit, approve], true), + ] { + f.replace(&history); + assert_eq!( + f.decide(request).unwrap(), + expected((!grant).then_some(0)), + "{history:?}" + ); + } + f.replace(&[edit, approve, edit]); + assert_eq!(f.decide(request).unwrap(), Value::from(0usize)); + f.store.truncate(&f.history, 2).unwrap(); + assert_eq!(f.decide(request).unwrap(), Value::Undefined); + } +} + +fn lock_rule(action: &str, setter: &str, changes: &[&str]) -> RuleSource { + let unchanged = changes + .iter() + .map(|change| format!(r#"action != "{change}""#)) + .collect::>() + .join(", "); + rule( + "forbid", + &format!(r#"{{"action": "{action}", "principal": p, "resource": r}}"#), + &format!( + r#"[any, {{resource == r, action == "{setter}", principal != p}}, star({{resource != r}} | {{{unchanged}}})]"# + ), + ) +} + +fn lock_table() -> Arc { + table( + &[ + lock_rule("edit", "edit", &OWNED), + lock_rule("edit", "read", &READ), + lock_rule("release", "edit", &OWNED), + lock_rule("remove", "edit", &OWNED), + lock_rule("remove", "read", &READ), + ], + 256, + ) +} + +// Enumerate setters and inspect their suffixes, independently of regex derivatives. +fn lock_oracle(history: &[Sample], candidate: Sample) -> Option { + let rules: [(&str, &str, &[&str]); 5] = [ + ("edit", "edit", &OWNED), + ("edit", "read", &READ), + ("release", "edit", &OWNED), + ("remove", "edit", &OWNED), + ("remove", "read", &READ), + ]; + rules.iter().position(|&(action, setter, changes)| { + action == candidate.1 + && history.iter().enumerate().any(|(i, e)| { + e.2 == candidate.2 + && e.1 == setter + && e.0 != candidate.0 + && history[i + 1..] + .iter() + .all(|f| f.2 != candidate.2 || !changes.contains(&f.1)) + }) + }) +} + +struct Generator(u64); +impl Generator { + fn below(&mut self, upper: usize) -> usize { + self.0 = self + .0 + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407); + usize::try_from(self.0 >> 32).unwrap() % upper + } + fn event(&mut self) -> Sample { + (self.below(3), ACTIONS[self.below(4)], self.below(3)) + } +} + +#[test] +fn lock_table_matches_independent_oracle_in_both_runners() { + for mode in MODES { + let mut f = Fixture::new(&lock_table(), mode); + let mut rng = Generator(7); + let mut denials = 0; + for _ in 0..3000 { + let len = rng.below(25); + let history: Vec<_> = (0..len).map(|_| rng.event()).collect(); + let candidate = rng.event(); + let events: Vec<_> = history.iter().map(|&e| f.sample(e)).collect(); + let request = f.sample(candidate); + f.replace(&events); + let want = lock_oracle(&history, candidate); + denials += usize::from(want.is_some()); + assert_eq!( + f.decide(request).unwrap(), + expected(want), + "{history:?} {candidate:?}" + ); + } + assert!(denials > 3000 / 100, "only {denials} denials"); + } +} + +#[test] +fn incremental_append_truncate_and_repeated_candidates_match_scratch() { + let program = lock_table(); + for mode in MODES { + let mut f = Fixture::new(&program, mode); + let mut history = Vec::new(); + let mut rng = Generator(11); + for _ in 0..500 { + match rng.below(3) { + 0 => { + let count = 1 + rng.below(8); + let batch: Vec<_> = (0..count).map(|_| rng.event()).collect(); + let events: Vec<_> = batch.iter().map(|&e| f.sample(e)).collect(); + f.store.append(&f.history, &events).unwrap(); + history.extend(batch); + } + 1 => { + let len = rng.below(history.len() + 1); + f.store.truncate(&f.history, len).unwrap(); + history.truncate(len); + } + _ => { + let candidate = rng.event(); + let request = f.sample(candidate); + let got = f.decide(request).unwrap(); + let mut fresh = Fixture::new(&program, mode); + let events: Vec<_> = history.iter().map(|&e| fresh.sample(e)).collect(); + let fresh_request = fresh.sample(candidate); + fresh.replace(&events); + assert_eq!(got, fresh.decide(fresh_request).unwrap()); + assert_eq!(got, expected(lock_oracle(&history, candidate))); + assert_eq!(f.decide(request).unwrap(), got); + } + } + assert_eq!(f.store.len(&f.history).unwrap(), history.len()); + } + } +} + +#[test] +fn require_forbid_order_returns_first_violated_rule() { + let programs = [ + table( + &[rule("require", "{}", "false"), rule("forbid", "{}", "any")], + 256, + ), + table( + &[ + rule("forbid", r#"{"action": "skip"}"#, "any"), + rule("require", "{}", "false"), + rule("forbid", "{}", "any"), + ], + 256, + ), + ]; + for mode in MODES { + for (index, program) in programs.iter().enumerate() { + let mut f = Fixture::new(program, mode); + let request = event(&f.store, "alice", "read", "doc"); + assert_eq!(f.decide(request).unwrap(), Value::from(index)); + f.entry = "data.t.allow"; + assert_eq!(f.decide(request).unwrap(), Value::Undefined); + } + } +} + +#[derive(Clone, Debug)] +enum Test { + Bool(bool), + Compare { + field: usize, + unequal: bool, + variable: bool, + literal: usize, + }, + And(Vec), + Or(Vec), +} + +#[derive(Clone, Debug)] +enum Regex { + Empty, + All, + Epsilon, + Test(Test), + Union(Vec), + Concat(Vec), + Star(Box), + Intersect(Vec), + Not(Box), +} + +type WordEvent = [usize; 3]; +const IDS: [&str; 3] = ["id0", "id1", "id2"]; +const VARIABLES: [&str; 3] = ["p", "a", "r"]; +const COORDINATES: [&str; 3] = ["principal", "action", "resource"]; +const ORACLE_REQUEST: &str = r#"{"principal": p, "action": a, "resource": r}"#; + +/// Borrowed-string event for the typed-semantics side of the oracle comparison. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +struct TestEvent<'a> { + principal: &'a str, + action: &'a str, + resource: &'a str, +} + +/// Tagged coordinate of a [`TestEvent`]; constants in rules carry their coordinate. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +enum TestComponent<'a> { + Principal(&'a str), + Action(&'a str), + Resource(&'a str), +} + +impl history_syntax::KeyHash for TestComponent<'_> { + fn key_hash(&self) -> u64 { + history_syntax::key_hash::hash_via_std(self) + } +} + +impl<'a> history_syntax::Event for TestEvent<'a> { + type Component = TestComponent<'a>; + type Arity = history_syntax::N3; + + fn component(self, index: usize) -> TestComponent<'a> { + match index { + 0 => TestComponent::Principal(self.principal), + 1 => TestComponent::Action(self.action), + _ => TestComponent::Resource(self.resource), + } + } + + fn coordinate(component: TestComponent<'a>) -> usize { + match component { + TestComponent::Principal(_) => 0, + TestComponent::Action(_) => 1, + TestComponent::Resource(_) => 2, + } + } +} + +fn source_event(word: WordEvent) -> TestEvent<'static> { + TestEvent { + principal: IDS[word[0]], + action: IDS[word[1]], + resource: IDS[word[2]], + } +} + +fn join(children: &[T], separator: &str, render: impl Fn(&T) -> String) -> String { + children + .iter() + .map(render) + .collect::>() + .join(separator) +} + +impl Test { + fn owned(&self) -> TestExpr> { + match self { + Self::Bool(true) => TestExpr::True, + Self::Bool(false) => TestExpr::False, + Self::Compare { + field, + unequal, + variable, + literal, + } => { + let pattern = if *variable { + ComponentPattern::variable(VARIABLES[*field]) + } else { + // Tag the constant with this coordinate through the authoring event. + ComponentPattern::constant(source_event([*literal; 3]).component(*field)) + }; + TestExpr::Atom { + comparison: if *unequal { + Comparison::Neq + } else { + Comparison::Eq + }, + pattern: AtomPattern::new(Component(u8::try_from(*field).unwrap()), pattern), + } + } + Self::And(children) => TestExpr::And(children.iter().map(Self::owned).collect()), + Self::Or(children) => TestExpr::Or(children.iter().map(Self::owned).collect()), + } + } + + /// One-event tests become one-event languages: `∧` is `&`, `∨` is `|`. + fn rego(&self) -> String { + match self { + Self::Bool(value) => value.to_string(), + Self::Compare { + field, + unequal, + variable, + literal, + } => { + let term = if *variable { + VARIABLES[*field].to_string() + } else { + format!("\"{}\"", IDS[*literal]) + }; + let op = if *unequal { "!=" } else { "==" }; + format!("{{{} {op} {term}}}", COORDINATES[*field]) + } + Self::And(children) if children.is_empty() => "set()".into(), + Self::And(children) => format!("({})", join(children, " & ", Self::rego)), + Self::Or(children) if children.is_empty() => "false".into(), + Self::Or(children) => format!("({})", join(children, " | ", Self::rego)), + } + } + + fn matches(&self, event: &WordEvent, binding: &WordEvent) -> bool { + match self { + Test::Bool(value) => *value, + Test::Compare { + field, + unequal, + variable, + literal, + } => (event[*field] == if *variable { binding[*field] } else { *literal }) != *unequal, + Test::And(children) => children.iter().all(|t| t.matches(event, binding)), + Test::Or(children) => children.iter().any(|t| t.matches(event, binding)), + } + } +} + +impl Regex { + fn owned(&self) -> RegexExpr> { + match self { + Self::Empty => RegexExpr::Empty, + Self::All => RegexExpr::All, + Self::Epsilon => RegexExpr::Epsilon, + Self::Test(test) => RegexExpr::Test(test.owned()), + Self::Union(children) => RegexExpr::union(children.iter().map(Self::owned)), + Self::Concat(children) => RegexExpr::concat(children.iter().map(Self::owned)), + Self::Intersect(children) => RegexExpr::intersect(children.iter().map(Self::owned)), + Self::Star(inner) => RegexExpr::star(inner.owned()), + Self::Not(inner) => RegexExpr::complement(inner.owned()), + } + } + + /// Rego history expression; binary operators are always parenthesized. + fn rego(&self) -> String { + match self { + Self::Empty => "false".into(), + Self::All => "any".into(), + Self::Epsilon => "[]".into(), + Self::Test(test) => test.rego(), + Self::Union(children) if children.is_empty() => "false".into(), + Self::Union(children) => format!("({})", join(children, " | ", Self::rego)), + Self::Concat(children) => format!("[{}]", join(children, ", ", Self::rego)), + Self::Intersect(children) if children.is_empty() => "any".into(), + Self::Intersect(children) => format!("({})", join(children, " & ", Self::rego)), + Self::Star(inner) => format!("star({})", inner.rego()), + Self::Not(inner) => format!("(any - {})", inner.rego()), + } + } + + // Bounded recursive oracle enumerates word splits; it shares no production + // normalization, nullable, derivative, graph or cache implementation. + fn accepts(&self, history: &[WordEvent], binding: &WordEvent) -> bool { + match self { + Regex::Empty => false, + Regex::All => true, + Regex::Epsilon => history.is_empty(), + Regex::Test(test) => matches!(history, [e] if test.matches(e, binding)), + Regex::Union(children) => children.iter().any(|r| r.accepts(history, binding)), + Regex::Intersect(children) => children.iter().all(|r| r.accepts(history, binding)), + Regex::Not(inner) => !inner.accepts(history, binding), + Regex::Concat(factors) => Self::accepts_concat(factors, history, binding), + Regex::Star(inner) => { + history.is_empty() + || (1..=history.len()).any(|split| { + inner.accepts(&history[..split], binding) + && self.accepts(&history[split..], binding) + }) + } + } + } + + fn accepts_concat(factors: &[Self], history: &[WordEvent], binding: &WordEvent) -> bool { + match factors { + [] => history.is_empty(), + [first, rest @ ..] => (0..=history.len()).any(|split| { + first.accepts(&history[..split], binding) + && Self::accepts_concat(rest, &history[split..], binding) + }), + } + } + + fn derivative(&self, event: &WordEvent, binding: &WordEvent) -> Self { + match self { + Regex::Empty | Regex::Epsilon => Regex::Empty, + Regex::All => Regex::All, + Regex::Test(test) => { + if test.matches(event, binding) { + Regex::Epsilon + } else { + Regex::Empty + } + } + Regex::Union(children) => Regex::Union( + children + .iter() + .map(|r| r.derivative(event, binding)) + .collect(), + ), + Regex::Intersect(children) => Regex::Intersect( + children + .iter() + .map(|r| r.derivative(event, binding)) + .collect(), + ), + Regex::Not(inner) => Regex::Not(Box::new(inner.derivative(event, binding))), + Regex::Star(inner) => { + Regex::Concat(vec![inner.derivative(event, binding), self.clone()]) + } + Regex::Concat(children) => { + let mut alternatives = Vec::new(); + for (index, child) in children.iter().enumerate() { + let mut factors = vec![child.derivative(event, binding)]; + factors.extend_from_slice(&children[index + 1..]); + alternatives.push(Regex::Concat(factors)); + if !child.accepts(&[], binding) { + break; + } + } + Regex::Union(alternatives) + } + } + } +} + +impl Generator { + fn test(&mut self, depth: usize) -> Test { + if depth > 0 { + match self.below(4) { + 0 => return Test::And(vec![self.test(depth - 1), self.test(depth - 1)]), + 1 => return Test::Or(vec![self.test(depth - 1), self.test(depth - 1)]), + _ => {} + } + } + match self.below(6) { + 0 => Test::Bool(true), + 1 => Test::Bool(false), + n => Test::Compare { + field: self.below(3), + unequal: n % 2 == 0, + variable: n >= 4, + literal: 1, + }, + } + } + fn regex(&mut self, depth: usize) -> Regex { + if depth == 0 { + return match self.below(5) { + 0 => Regex::Empty, + 1 => Regex::All, + 2 => Regex::Epsilon, + _ => Regex::Test(self.test(1)), + }; + } + match self.below(9) { + 0 => Regex::Empty, + 1 => Regex::All, + 2 => Regex::Epsilon, + 3 => Regex::Test(self.test(1)), + 4 => Regex::Union(vec![self.regex(depth - 1), self.regex(depth - 1)]), + 5 => Regex::Concat(vec![self.regex(depth - 1), self.regex(depth - 1)]), + 6 => Regex::Star(Box::new(self.regex(depth - 1))), + 7 => Regex::Intersect(vec![self.regex(depth - 1), self.regex(depth - 1)]), + _ => Regex::Not(Box::new(self.regex(depth - 1))), + } + } +} + +fn oracle_corpus_and_words() -> (Vec, [WordEvent; 3], Vec>) { + let leaf = Regex::Test(Test::Compare { + field: 0, + unequal: false, + variable: true, + literal: 1, + }); + let mut corpus = vec![ + Regex::Empty, + Regex::All, + Regex::Epsilon, + leaf.clone(), + Regex::Union(vec![]), + Regex::Concat(vec![]), + Regex::Intersect(vec![]), + Regex::Star(Box::new(leaf.clone())), + Regex::Not(Box::new(leaf.clone())), + Regex::Union(vec![leaf.clone(), Regex::Epsilon]), + Regex::Concat(vec![leaf.clone(), leaf.clone()]), + Regex::Intersect(vec![leaf, Regex::All]), + Regex::Test(Test::And(vec![])), + Regex::Test(Test::Or(vec![])), + Regex::Concat(vec![ + Regex::Union(vec![]), + Regex::Intersect(vec![]), + Regex::Test(Test::And(vec![])), + Regex::Test(Test::Or(vec![])), + ]), + ]; + let mut generator = Generator(0x5eed_cafe_f00d_beef); + corpus.extend((0..500).map(|_| generator.regex(2))); + let alphabet = [[1, 1, 1], [2, 2, 2], [1, 2, 1]]; + let mut words = vec![vec![]]; + let mut layer = vec![vec![]]; + for _ in 0..3 { + layer = layer + .iter() + .flat_map(|prefix| { + alphabet.iter().map(move |e| { + let mut word = prefix.clone(); + word.push(*e); + word + }) + }) + .collect(); + words.extend(layer.iter().cloned()); + } + (corpus, alphabet, words) +} + +fn mode_name(mode: RuleMode) -> &'static str { + match mode { + RuleMode::Require => "require", + RuleMode::Forbid => "forbid", + } +} + +fn oracle_head(action: Option<&'static str>) -> Head> { + Head::new([ + ComponentPattern::variable("p"), + action.map_or_else( + || ComponentPattern::variable("a"), + |action| ComponentPattern::constant(TestComponent::Action(action)), + ), + ComponentPattern::variable("r"), + ]) +} + +/// Interns portable constants exactly as `RegoVM::attach_history` does. +struct StoreEncoder<'a>(&'a HistoryStore); + +impl FlatEncoder for StoreEncoder<'_> { + fn encode(&mut self, field: Component, value: &String) -> Result { + self.0.intern(field, value) + } +} + +/// Whether the rule holds according to the unverified `junco_core::reference` evaluator. +fn reference_holds( + pair: &FlatPair, + mode: RuleMode, + request: &[u64], + events: &[[u64; 3]], +) -> bool { + if !head_matches(&pair.head, request) { + return true; + } + let mut lang = Lang::inflate(pair, &mut Unmetered).unwrap(); + for event in events { + lang = lang.step(pair, event, request, &mut Unmetered).unwrap(); + } + lang.nullable() == (mode == RuleMode::Require) +} + +#[test] +fn exhaustive_typed_words_match_split_oracle_and_concrete_derivatives() { + let (corpus, alphabet, words) = oracle_corpus_and_words(); + let store = HistoryStore::new(); + let slots = [["id1"; 3], ["id2"; 3], ["id1", "id2", "id1"]].map(|[p, a, r]| { + [ + store.intern(PRINCIPAL, p).unwrap(), + store.intern(ACTION, a).unwrap(), + store.intern(RESOURCE, r).unwrap(), + ] + }); + for regex in corpus { + let base = table(&[rule("require", ORACLE_REQUEST, ®ex.rego())], 256); + let source = &base.history_tables[0].rules[0]; + let pair = lower_flat( + &source.source, + &mut StoreEncoder(&store), + &mut Unmetered, + &mut ObservationWorld, + ) + .unwrap(); + for binding in [[1, 1, 1], [2, 2, 2]] { + for word in &words { + let events: Vec<_> = word + .iter() + .map(|e| slots[alphabet.iter().position(|a| a == e).unwrap()]) + .collect(); + assert_eq!( + reference_holds(&pair, source.mode, &slots[binding[0] - 1], &events), + regex.accepts(word, &binding), + "reference evaluator: {regex:?} {word:?} {binding:?}" + ); + } + } + for batch_size in BATCHES { + let program = with_batch(&base, batch_size); + for mode in MODES { + let mut f = Fixture::new(&program, mode); + let ids = [ + event(&f.store, "id1", "id1", "id1"), + event(&f.store, "id2", "id2", "id2"), + event(&f.store, "id1", "id2", "id1"), + ]; + for binding in [[1, 1, 1], [2, 2, 2]] { + let request = ids[binding[0] - 1]; + for word in &words { + let events: Vec<_> = word + .iter() + .map(|e| ids[alphabet.iter().position(|a| a == e).unwrap()]) + .collect(); + f.replace(&events); + let want = regex.accepts(word, &binding); + assert_eq!( + f.decide(request).unwrap(), + expected((!want).then_some(0)), + "{regex:?} {word:?} {binding:?} batch={batch_size} mode={mode:?}" + ); + assert_eq!( + f.decide(request).unwrap(), + expected((!want).then_some(0)), + "warm repeat" + ); + if let Some((first, tail)) = word.split_first() { + assert_eq!( + regex.derivative(first, &binding).accepts(tail, &binding), + want + ); + } + } + } + } + } + } +} + +fn assert_shared_decision( + regex: &Regex, + mode: RuleMode, + fixture: &mut Fixture, + compiled: &mut CompiledRule>, + history: &History>, + word: &[WordEvent], + binding: WordEvent, +) { + let inside = regex.accepts(word, &binding); + let violation = match mode { + RuleMode::Require => !inside, + RuleMode::Forbid => inside, + }; + let request = event( + &fixture.store, + &format!("id{}", binding[0]), + &format!("id{}", binding[1]), + &format!("id{}", binding[2]), + ); + for _ in 0..2 { + assert_eq!( + compiled + .accepts_history(history, &source_event(binding)) + .unwrap(), + Some(inside), + "typed semantics: {regex:?} {word:?} {binding:?} {mode:?}" + ); + assert_eq!( + fixture.decide(request).unwrap(), + Value::Bool(!violation), + "Rego history rule: {regex:?} {word:?} {binding:?} {mode:?}" + ); + assert_eq!(fixture.store.len(&fixture.history).unwrap(), word.len()); + assert_eq!(history.len(), word.len()); + } +} + +#[test] +fn typed_semantics_and_rego_history_rules_agree() { + let (corpus, alphabet, words) = oracle_corpus_and_words(); + for regex in corpus { + for rule_mode in [RuleMode::Require, RuleMode::Forbid] { + let base = table( + &[rule(mode_name(rule_mode), ORACLE_REQUEST, ®ex.rego())], + 256, + ); + for batch_size in BATCHES { + let program = with_batch(&base, batch_size); + for execution_mode in MODES { + // The rule's own Boolean: `first`/`allow` composition is covered elsewhere. + let mut fixture = + Fixture::new(&program, execution_mode).with_entry("data.t.r0"); + let store = Arc::new(Store::new().unwrap()); + let mut compiled = CompiledRule::new( + store.clone(), + Rule::new(rule_mode, oracle_head(None), regex.owned()), + ) + .unwrap(); + let mut history = History::new(store).unwrap(); + let ids: Vec<_> = alphabet + .iter() + .map(|e| { + event( + &fixture.store, + &format!("id{}", e[0]), + &format!("id{}", e[1]), + &format!("id{}", e[2]), + ) + }) + .collect(); + for binding in [[1, 1, 1], [2, 2, 2]] { + for word in &words { + history.truncate(0).unwrap(); + fixture.replace(&[]); + assert_shared_decision( + ®ex, + rule_mode, + &mut fixture, + &mut compiled, + &history, + &[], + binding, + ); + for e in word { + history.push(source_event(*e)).unwrap(); + fixture + .store + .append( + &fixture.history, + &[ids[alphabet.iter().position(|a| a == e).unwrap()]], + ) + .unwrap(); + } + assert_shared_decision( + ®ex, + rule_mode, + &mut fixture, + &mut compiled, + &history, + word, + binding, + ); + if let Some((last, prefix)) = word.split_last() { + history.truncate(prefix.len()).unwrap(); + fixture + .store + .truncate(&fixture.history, prefix.len()) + .unwrap(); + assert_shared_decision( + ®ex, + rule_mode, + &mut fixture, + &mut compiled, + &history, + prefix, + binding, + ); + let replacement = alphabet.iter().position(|e| e != last).unwrap(); + history.push(source_event(alphabet[replacement])).unwrap(); + fixture + .store + .append(&fixture.history, &[ids[replacement]]) + .unwrap(); + let mut replaced = prefix.to_vec(); + replaced.push(alphabet[replacement]); + assert_shared_decision( + ®ex, + rule_mode, + &mut fixture, + &mut compiled, + &history, + &replaced, + binding, + ); + } + } + } + } + } + } + } + + // A constant action head does not fire, independently of the tail's answer or mode. + let regex = Regex::Test(Test::Compare { + field: 0, + unequal: false, + variable: true, + literal: 1, + }); + for rule_mode in [RuleMode::Require, RuleMode::Forbid] { + let base = table( + &[rule( + mode_name(rule_mode), + &format!( + r#"{{"principal": p, "action": "{}", "resource": r}}"#, + IDS[1] + ), + ®ex.rego(), + )], + 256, + ); + for batch_size in BATCHES { + let program = with_batch(&base, batch_size); + for execution_mode in MODES { + let mut fixture = Fixture::new(&program, execution_mode); + let store = Arc::new(Store::new().unwrap()); + let mut compiled = CompiledRule::new( + store.clone(), + Rule::new(rule_mode, oracle_head(Some(IDS[1])), regex.owned()), + ) + .unwrap(); + let mut history = History::new(store).unwrap(); + for word in [vec![], vec![[1, 1, 1]]] { + fixture.replace(&[]); + history.truncate(0).unwrap(); + for e in word { + history.push(source_event(e)).unwrap(); + let recorded = event(&fixture.store, "id1", "id1", "id1"); + fixture.store.append(&fixture.history, &[recorded]).unwrap(); + } + let mismatch = event(&fixture.store, "id1", "id2", "id1"); + for _ in 0..2 { + assert_eq!( + compiled + .accepts_history(&history, &source_event([1, 2, 1])) + .unwrap(), + None + ); + assert_eq!(fixture.decide(mismatch).unwrap(), Value::Undefined); + assert_eq!(fixture.store.len(&fixture.history).unwrap(), history.len()); + } + } + } + } + } +} + +fn assert_flat_epsilon_language(source: FlatPair, nodes: usize, edges: usize) { + source.validate().unwrap(); + let assert_shape = |program: &Program| { + let stored = &program.history_tables[0].rules[0].source; + assert_eq!(stored, &source); + assert_eq!(stored.regexes.len(), nodes); + assert_eq!( + stored + .regexes + .iter() + .map(|node| match node { + FlatRegex::Concat(children) + | FlatRegex::Union(children) + | FlatRegex::Intersect(children) => children.len(), + FlatRegex::Star(_) | FlatRegex::Complement(_) => 1, + _ => 0, + }) + .sum::(), + edges + ); + }; + let base = table(&[rule("require", "{}", "[]")], 256); + for batch_size in BATCHES { + let mut program = (*with_batch(&base, batch_size)).clone(); + program.history_tables[0].rules[0].source = source.clone(); + assert_shape(&program); + let json_program = Program::deserialize_json(&program.serialize_json().unwrap()).unwrap(); + let DeserializationResult::Complete(binary_program) = + Program::deserialize_binary(&program.serialize_binary().unwrap()).unwrap() + else { + panic!("current version must deserialize completely"); + }; + for restored in [program, json_program, binary_program] { + assert_shape(&restored); + let restored = Arc::new(restored); + for mode in MODES { + let mut fixture = Fixture::new(&restored, mode); + let probe = event(&fixture.store, "alice", "read", "doc"); + for _ in 0..2 { + assert_eq!(fixture.decide(probe).unwrap(), Value::Undefined); + } + fixture.store.append(&fixture.history, &[probe]).unwrap(); + for _ in 0..2 { + assert_eq!(fixture.decide(probe).unwrap(), Value::from(0usize)); + assert_eq!(fixture.store.len(&fixture.history).unwrap(), 1); + } + assert_shape(&restored); + } + } + } +} + +#[test] +fn flat_shared_dag_roundtrips_and_executes_without_unfolding() { + let mut regexes = vec![FlatRegex::Epsilon]; + for index in 1..4096 { + regexes.push(FlatRegex::Concat(vec![index - 1, index - 1])); + } + assert_flat_epsilon_language( + FlatPair { + head: vec![FlatHead::Any, FlatHead::Any, FlatHead::Any], + tests: vec![], + regexes, + root: 4095, + }, + 4096, + 8190, + ); +} + +#[test] +fn flat_deep_unary_and_non_last_root_preserve_topology() { + let mut regexes = vec![FlatRegex::Epsilon]; + for index in 1..4096 { + regexes.push(FlatRegex::Star(index - 1)); + } + assert_flat_epsilon_language( + FlatPair { + head: vec![FlatHead::Any, FlatHead::Any, FlatHead::Any], + tests: vec![], + regexes, + root: 4095, + }, + 4096, + 4095, + ); + assert_flat_epsilon_language( + FlatPair { + head: vec![FlatHead::Any, FlatHead::Any, FlatHead::Any], + tests: vec![FlatTest::Bool(false)], + regexes: vec![ + FlatRegex::Epsilon, + FlatRegex::All, + FlatRegex::Test(0), + FlatRegex::Star(1), + ], + root: 0, + }, + 4, + 1, + ); +} + +fn read_star(batch_size: u32) -> Arc { + table( + &[rule("require", "{}", r#"star({action == "read"})"#)], + batch_size, + ) +} + +fn assert_step(vm: &RegoVM, pc: usize) { + assert!( + matches!(vm.execution_state(), ExecutionState::Suspended { + reason: SuspendReason::Step, pc: actual, .. + } if *actual == pc), + "{:?}", + vm.execution_state() + ); + assert_eq!(vm.get_pc(), pc); +} + +/// Step a suspended VM until it is about to dispatch a `HistoryStep`; returns that PC. +fn run_to_history(vm: &mut RegoVM, program: &Program) -> usize { + loop { + let pc = vm.get_pc(); + if matches!( + program.instructions.get(pc), + Some(Instruction::HistoryStep { .. }) + ) { + assert_step(vm, pc); + return pc; + } + vm.resume(None).unwrap(); + } +} + +fn finish(vm: &mut RegoVM) -> Result { + while matches!(vm.execution_state(), ExecutionState::Suspended { .. }) { + vm.resume(None)?; + } + match vm.execution_state() { + ExecutionState::Completed { result } => Ok(result.clone()), + state => panic!("expected completion, got {state:?}"), + } +} + +#[test] +fn batch_edges_repeat_one_pc_and_charge_every_dispatch() { + let program = read_star(3); + assert_eq!( + program + .instructions + .iter() + .filter(|instruction| matches!(instruction, Instruction::HistoryStep { .. })) + .count(), + 1 + ); + let step = step_pc(&program); + // Smallest instruction budget for a one-dispatch (empty-history) decision. + let bases = MODES.map(|mode| { + (1..) + .find(|&limit| { + let mut f = Fixture::new(&program, mode).with_entry("data.t.r0"); + let read = event(&f.store, "alice", "read", "doc"); + f.vm.set_max_instructions(limit); + f.decide(read).is_ok() + }) + .unwrap() + }); + for len in [0usize, 1, 2, 3, 4, 6, 7] { + let batches = len.div_ceil(3).max(1); + let mut f = Fixture::new(&program, ExecutionMode::Suspendable).with_entry("data.t.r0"); + let read = event(&f.store, "alice", "read", "doc"); + f.replace(&vec![read; len]); + f.vm.set_step_mode(true); + f.decide(read).unwrap(); + assert_eq!(f.run_to_history(), step); + for index in 0..batches { + assert_step(&f.vm, step); + if index + 1 < batches { + f.vm.resume(None).unwrap(); + } + } + f.vm.resume(None).unwrap(); + assert_step(&f.vm, step + 1); + assert_eq!(finish(&mut f.vm).unwrap(), Value::Bool(true)); + for (mode, base) in MODES.into_iter().zip(bases) { + let mut limited = Fixture::new(&program, mode).with_entry("data.t.r0"); + let read = event(&limited.store, "alice", "read", "doc"); + limited.replace(&vec![read; len]); + limited.vm.set_max_instructions(base + batches - 2); + assert!(matches!( + limited.decide(read), + Err(VmError::InstructionLimitExceeded { .. }) + )); + limited.vm.set_max_instructions(base + batches - 1); + assert_eq!(limited.decide(read).unwrap(), Value::Bool(true)); + } + } +} + +#[test] +fn nullable_intermediate_prefix_cannot_grant_before_rejecting_suffix() { + for mode in MODES { + let mut f = Fixture::new(&read_star(1), mode); + let read = event(&f.store, "alice", "read", "doc"); + let edit = event(&f.store, "alice", "edit", "doc"); + f.replace(&[read, edit]); + if mode == ExecutionMode::Suspendable { + f.vm.set_step_mode(true); + f.decide(read).unwrap(); + f.run_to_history(); + assert_eq!(finish(&mut f.vm).unwrap(), Value::from(0usize)); + } else { + assert_eq!(f.decide(read).unwrap(), Value::from(0usize)); + } + } +} + +#[test] +fn append_after_snapshot_is_excluded_but_fresh_decision_includes_it() { + let mut f = Fixture::new(&read_star(3), ExecutionMode::Suspendable); + let read = event(&f.store, "alice", "read", "doc"); + let edit = event(&f.store, "alice", "edit", "doc"); + f.replace(&[read; 4]); + f.vm.set_step_mode(true); + f.decide(read).unwrap(); + let step = f.run_to_history(); + // The first dispatch pins the decision's prefix. + f.vm.resume(None).unwrap(); + assert_step(&f.vm, step); + f.store.append(&f.history, &[edit]).unwrap(); + assert_eq!(finish(&mut f.vm).unwrap(), Value::Undefined); + f.vm.set_step_mode(false); + assert_eq!(f.decide(read).unwrap(), Value::from(0usize)); +} + +#[test] +fn newer_shared_cache_prefix_cannot_seed_an_older_decision_target() { + let program = table( + &[ + rule("require", "{}", "any"), + rule("require", "{}", r#"star({action == "read"})"#), + ], + 1, + ); + let mut old = Fixture::new(&program, ExecutionMode::Suspendable); + let read = event(&old.store, "alice", "read", "doc"); + let edit = event(&old.store, "alice", "edit", "doc"); + old.replace(&[read; 3]); + old.vm.set_step_mode(true); + old.decide(read).unwrap(); + old.run_to_history(); + // The first dispatch pins the decision's prefix. + old.vm.resume(None).unwrap(); + old.store.append(&old.history, &[edit]).unwrap(); + let mut newer = RegoVM::new(); + newer.load_program(program); + newer.attach_history(old.store.clone()).unwrap(); + newer.set_history_input(old.history.clone(), read).unwrap(); + assert_eq!( + newer.execute_entry_point_by_name("data.t.first").unwrap(), + Value::from(1usize) + ); + assert_eq!(finish(&mut old.vm).unwrap(), Value::Undefined); + old.vm.set_step_mode(false); + assert_eq!(old.decide(read).unwrap(), Value::from(1usize)); +} + +#[test] +fn truncate_reappend_invalidates_batch_and_both_terminal_boundaries() { + for resumes in 0..3 { + let mut f = Fixture::new(&read_star(3), ExecutionMode::Suspendable); + let read = event(&f.store, "alice", "read", "doc"); + f.replace(&[read; 4]); + f.vm.set_step_mode(true); + f.decide(read).unwrap(); + f.run_to_history(); + // The first dispatch pins revision 0; later resumes finish the step and leave it. + for _ in 0..resumes { + f.vm.resume(None).unwrap(); + } + assert_step(&f.vm, step_pc(&f.program) + usize::from(resumes == 2)); + // Preserve length and bytes: only the revision can detect this rewrite. + f.store.truncate(&f.history, 0).unwrap(); + f.store.append(&f.history, &[read; 4]).unwrap(); + assert!(matches!( + finish(&mut f.vm), + Err(VmError::History { + source: HistoryError::HistoryChanged { + expected: 0, + actual: 1 + }, + .. + }) + )); + assert!(!matches!( + f.vm.execution_state(), + ExecutionState::Completed { .. } + )); + f.vm.set_step_mode(false); + assert_eq!(f.decide(read).unwrap(), Value::Undefined); + } +} + +#[test] +fn suspended_execution_rejects_restaging_and_reattachment() { + let mut f = Fixture::new(&read_star(1), ExecutionMode::Suspendable); + let read = event(&f.store, "alice", "read", "doc"); + f.replace(&[read; 3]); + f.vm.set_step_mode(true); + f.decide(read).unwrap(); + assert!(matches!( + f.vm.set_history_input(f.history.clone(), read), + Err(VmError::HistoryExecutionActive { .. }) + )); + assert!(matches!( + f.vm.attach_history(f.store.clone()), + Err(VmError::HistoryExecutionActive { .. }) + )); + assert!(matches!( + f.vm.attach_history(Arc::new(HistoryStore::new())), + Err(VmError::HistoryExecutionActive { .. }) + )); + assert_eq!(finish(&mut f.vm).unwrap(), Value::Undefined); +} + +#[test] +fn load_program_cancels_suspension_and_drops_typed_context_not_shared_history() { + let program = read_star(1); + let mut f = Fixture::new(&program, ExecutionMode::Suspendable); + let read = event(&f.store, "alice", "read", "doc"); + f.replace(&[read; 3]); + let mut peer = RegoVM::new(); + peer.load_program(program.clone()); + peer.attach_history(f.store.clone()).unwrap(); + peer.set_history_input(f.history.clone(), read).unwrap(); + f.vm.set_step_mode(true); + f.decide(read).unwrap(); + f.run_to_history(); + f.vm.resume(None).unwrap(); + f.vm.load_program(program); + assert!(matches!(f.vm.execution_state(), ExecutionState::Ready)); + assert!(matches!( + f.vm.resume(None), + Err(VmError::InvalidResumeState { .. }) + )); + f.vm.set_step_mode(false); + assert!(matches!( + f.vm.execute_entry_point_by_name("data.t.first"), + Err(VmError::HistoryContextMissing { .. }) + )); + f.vm.attach_history(f.store.clone()).unwrap(); + assert!(matches!( + f.vm.execute_entry_point_by_name("data.t.first"), + Err(VmError::HistoryContextMissing { .. }) + )); + f.vm.set_history_input(f.history.clone(), read).unwrap(); + assert_eq!( + f.vm.execute_entry_point_by_name("data.t.first").unwrap(), + Value::Undefined + ); + assert_eq!(f.store.len(&f.history).unwrap(), 3); + assert_eq!( + peer.execute_entry_point_by_name("data.t.first").unwrap(), + Value::Undefined + ); +} + +#[test] +fn staging_requires_attachment_and_each_domain_membership() { + let program = read_star(256); + let store = Arc::new(HistoryStore::new()); + let peer = Arc::new(HistoryStore::new()); + let history = peer.new_history().unwrap(); + let own = event(&peer, "alice", "read", "doc"); + // Typed views encode through dictionaries the byte domains never contain. + let typed = + History::from_events(Arc::new(Store::new().unwrap()), [source_event([0; 3])]).unwrap(); + let other = typed.numeric().as_slice()[0]; + let mut vm = RegoVM::new(); + vm.load_program(program); + assert!(matches!( + vm.set_history_input(history.clone(), own), + Err(VmError::HistoryContextMissing { .. }) + )); + vm.attach_history(store.clone()).unwrap(); + // Wrappers share one process-wide store, so a peer's handle and identities stage. + vm.set_history_input(history.clone(), own).unwrap(); + // Event fields are private: each typed-only coordinate is rejected while building. + for index in 0..3 { + let mut slots = [own.component(0), own.component(1), own.component(2)]; + slots[index] = other.component(index); + assert!(matches!( + peer.event(&slots), + Err(HistoryError::UnknownId { + domain: "component", + .. + }) + )); + } + assert!(matches!( + vm.set_history_input(history.clone(), other), + Err(VmError::History { + source: HistoryError::UnknownId { + domain: "component", + .. + }, + .. + }) + )); + // Failed requests leave the previously staged input intact. + assert_eq!( + vm.execute_entry_point_by_name("data.t.first").unwrap(), + Value::Undefined + ); +} + +#[test] +fn zero_batch_is_rejected_before_head_mismatch_shortcut() { + for mode in MODES { + for matching in [false, true] { + let request = if matching { + r#"{"action": "read"}"# + } else { + r#"{"action": "release"}"# + }; + let program = with_batch(&table(&[rule("require", request, "any")], 256), 0); + assert!(program + .validate_limits() + .unwrap_err() + .contains("zero batch_size")); + let mut f = Fixture::new(&program, mode); + let request = event(&f.store, "alice", "read", "doc"); + assert!(matches!( + f.decide(request), + Err(VmError::InvalidHistoryBatchSize { batch_size: 0, .. }) + )); + } + } +} + +#[test] +fn current_binary_and_json_reintern_constants_in_fresh_store() { + // Compiled constants own their bytes after the policy source is gone. + let program = { + let (release, edit) = (String::from("release"), String::from("edit")); + table(&[prior_edit_rule(&release, &edit)], 256) + }; + let mut original = Fixture::new(&program, ExecutionMode::RunToCompletion); + let old_edit = event(&original.store, "alice", "edit", "doc"); + let old_request = event(&original.store, "alice", "release", "doc"); + original.replace(&[old_edit]); + assert_eq!(original.decide(old_request).unwrap(), Value::Undefined); + let bytes = program.serialize_binary().unwrap(); + assert_eq!(Program::SERIALIZATION_VERSION, 7); + assert_eq!(&bytes[4..8], &7u32.to_le_bytes()); + let DeserializationResult::Complete(binary) = Program::deserialize_binary(&bytes).unwrap() + else { + panic!("current version must deserialize completely"); + }; + let json_program = Program::deserialize_json(&program.serialize_json().unwrap()).unwrap(); + for restored in [binary, json_program] { + let store = Arc::new(HistoryStore::new()); + let edit = event(&store, "alice", "edit", "doc"); + let request = event(&store, "alice", "release", "doc"); + // Wrappers share process-wide identities: restored byte constants reintern to them. + assert_eq!(edit, old_edit); + assert_eq!(request, old_request); + let mut f = Fixture::with_store(&Arc::new(restored), ExecutionMode::RunToCompletion, store); + assert_eq!(f.decide(request).unwrap(), Value::from(0usize)); + f.replace(&[edit]); + assert_eq!(f.decide(request).unwrap(), Value::Undefined); + let other = event(&f.store, "bob", "release", "doc"); + assert_eq!(f.decide(other).unwrap(), Value::from(0usize)); + } + assert_eq!(std::mem::size_of::(), 6); +} + +/// `header`'s binary header and sections followed by `program`'s unchecked payload. +fn unchecked_binary(header: &Program, program: &Program) -> Vec { + let mut bytes = header.serialize_binary().unwrap(); + let section_bytes: usize = (8..24) + .step_by(4) + .map(|offset| u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap()) as usize) + .sum(); + bytes.truncate(25 + section_bytes); + let payload = postcard::to_allocvec(program).unwrap(); + bytes.extend_from_slice(&u32::try_from(payload.len()).unwrap().to_le_bytes()); + bytes.extend_from_slice(&payload); + bytes +} + +#[test] +fn malformed_source_nodes_variables_and_indexes_are_rejected() { + let base = (*table(&[prior_edit_rule("release", "edit")], 256)).clone(); + let base_json: Json = serde_json::from_str(&base.serialize_json().unwrap()).unwrap(); + let mut invalid = Vec::new(); + let mut p = base.clone(); + p.history_tables[0].rules[0].source.regexes = vec![FlatRegex::Star(0)]; + p.history_tables[0].rules[0].source.root = 0; + invalid.push(p); + let mut p = base.clone(); + p.history_tables[0].rules[0].source.regexes = vec![FlatRegex::Test(u32::MAX)]; + p.history_tables[0].rules[0].source.root = 0; + invalid.push(p); + let mut p = base.clone(); + p.history_tables[0].rules[0].source.root = u32::MAX; + invalid.push(p); + let mut p = base.clone(); + p.history_tables[0].rules[0].source.tests = vec![FlatTest::And(vec![0])]; + invalid.push(p); + let mut p = base.clone(); + p.history_tables[0].rules[0].source.tests = vec![FlatTest::Atom { + field: PRINCIPAL, + term: FlatTerm::Variable(RESOURCE), + positive: true, + }]; + invalid.push(p); + let mut p = base.clone(); + p.history_tables[0].rules[0].source.tests = vec![FlatTest::Atom { + field: ACTION, + term: FlatTerm::Variable(ACTION), + positive: true, + }]; + invalid.push(p); // Action is Constant in the head, not Bind. + let mut p = base.clone(); + p.instruction_data.history_step_params[0].table = u16::MAX; + invalid.push(p); + let mut p = base.clone(); + p.instruction_data.history_step_params[0].rule = u16::MAX; + invalid.push(p); + let mut p = base.clone(); + let step = step_pc(&p); + p.instructions[step] = Instruction::HistoryStep { + params_index: u16::MAX, + }; + invalid.push(p); + let mut p = base.clone(); + p.instruction_data.history_step_params[0].batch_size = 0; + invalid.push(p); + for program in invalid { + assert!(program.validate_limits().is_err()); + assert!(program.serialize_binary().is_err()); + let mut serialized = base_json.clone(); + serialized["history_tables"] = serde_json::to_value(&program.history_tables).unwrap(); + serialized["instructions"] = serde_json::to_value(&program.instructions).unwrap(); + serialized["instruction_data"] = serde_json::to_value(&program.instruction_data).unwrap(); + assert!(Program::deserialize_json(&serialized.to_string()).is_err()); + assert!(!matches!( + Program::deserialize_binary(&unchecked_binary(&base, &program)), + Ok(DeserializationResult::Complete(_)) + )); + let invalid_source = program.history_tables[0].rules[0] + .source + .validate() + .is_err(); + let store = Arc::new(HistoryStore::new()); + let history = store.new_history().unwrap(); + let request = event(&store, "alice", "release", "doc"); + let mut vm = RegoVM::new(); + vm.load_program(Arc::new(program)); + if invalid_source { + assert!(vm.attach_history(store).is_err()); + } else { + vm.attach_history(store).unwrap(); + vm.set_history_input(history, request).unwrap(); + assert!(matches!( + vm.execute_entry_point_by_name("data.t.first"), + Err(VmError::InvalidHistoryStepParams { .. } + | VmError::InvalidHistoryTableIndex { .. } + | VmError::InvalidHistoryRuleIndex { .. } + | VmError::InvalidHistoryBatchSize { .. }) + )); + } + } +} + +/// Compile `r0 := history.` and return the RVM compiler's error message. +fn history_rule_error(call: &str) -> String { + let mut engine = Engine::new(); + engine + .add_policy( + "t.rego".into(), + format!("package t\nimport rego.v1\nr0 := history.{call}\n"), + ) + .unwrap(); + let policy = engine.compile_with_entrypoint(&"data.t.r0".into()).unwrap(); + Compiler::compile_from_policy(&policy, &["data.t.r0"]) + .unwrap_err() + .to_string() +} + +#[test] +fn malformed_history_rules_report_compile_errors() { + for (call, message) in [ + ( + r#"require({"actor": a}, any)"#, + "request pattern must be an object", + ), + (r#"require([], any)"#, "request pattern must be an object"), + ( + r#"require({"action": "a", "action": "b"}, any)"#, + "duplicate request coordinate", + ), + ( + r#"require({"principal": action}, any)"#, + "shadows the coordinate name", + ), + ( + r#"require({"principal": 1}, any)"#, + "must be a string constant or a variable", + ), + ( + r#"require({}, [any, {action < "x"}])"#, + "comparison must be", + ), + ( + r#"require({}, [any, {"edit" == action}])"#, + "comparison must be", + ), + ( + r#"require({}, [any, {"action": "edit"}, any])"#, + "unsupported history expression", + ), + (r#"require({}, everything)"#, "unknown name `everything`"), + (r#"require({}, star())"#, "star takes one argument"), + (r#"require({})"#, "take two arguments"), + (r#"forbid({}, any, any)"#, "take two arguments"), + ( + r#"require({}, {principal == any})"#, + "comparison term must be", + ), + ( + r#"require({}, {principal == action})"#, + "comparison term must be", + ), + ( + r#"require({"action": "release", "principal": x}, {resource == x})"#, + "invalid history rule", + ), + ( + r#"require({}, {principal == missing})"#, + "invalid history rule", + ), + ] { + let error = history_rule_error(call); + assert!(error.contains(message), "{call}: {error}"); + } + + // A failed reservation leaves nothing behind: the same source then compiles and decides. + let rule = prior_edit_rule("release", "edit"); + let call = format!("require({}, {})", rule.1, rule.2); + let failing = fail_reservations_after(0); + let error = history_rule_error(&call); + assert!(error.contains("invalid history rule"), "{error}"); + drop(failing); + let mut f = Fixture::new(&table(&[rule], 256), ExecutionMode::RunToCompletion); + let edit = event(&f.store, "alice", "edit", "doc"); + let release = event(&f.store, "alice", "release", "doc"); + assert_eq!(f.decide(release).unwrap(), Value::from(0usize)); + f.replace(&[edit]); + assert_eq!(f.decide(release).unwrap(), Value::Undefined); +} + +#[test] +fn removed_history_builtin_is_unknown_in_interpreter_and_rvm_compilation() { + const SOURCE: &str = "package removed\nimport rego.v1\nresult := history.match({}, [], {})"; + let mut engine = Engine::new(); + engine + .add_policy("removed.rego".into(), SOURCE.into()) + .unwrap(); + assert!(engine.eval_rule("data.removed.result".into()).is_err()); + let mut engine = Engine::new(); + engine + .add_policy("removed.rego".into(), SOURCE.into()) + .unwrap(); + let policy = engine + .compile_with_entrypoint(&"data.removed.result".into()) + .unwrap(); + let error = Compiler::compile_from_policy(&policy, &["data.removed.result"]).unwrap_err(); + assert!(matches!(error.error, + CompilerError::UnknownFunction { ref name } + if name == "history.match")); +} + +#[cfg(feature = "std")] +#[test] +fn concurrent_vms_share_identities_and_fixed_prefix_without_sharing_candidates() { + use std::sync::Barrier; + let program = table( + &[rule( + "require", + r#"{"principal": p}"#, + "star({principal == p})", + )], + 1, + ); + let store = Arc::new(HistoryStore::new()); + let history = store.new_history().unwrap(); + let alice = event(&store, "alice", "read", "doc"); + let bob = event(&store, "bob", "read", "doc"); + store.append(&history, &[alice; 3]).unwrap(); + let ready = Arc::new(Barrier::new(3)); + let appended = Arc::new(Barrier::new(3)); + let threads: Vec<_> = [alice, bob] + .into_iter() + .map(|request| { + let store = store.clone(); + let history = history.clone(); + let program = program.clone(); + let ready = ready.clone(); + let appended = appended.clone(); + std::thread::spawn(move || { + assert_eq!(event(&store, "alice", "read", "doc"), alice); + let mut vm = RegoVM::new(); + vm.load_program(program.clone()); + vm.set_execution_mode(ExecutionMode::Suspendable); + vm.set_step_mode(true); + vm.attach_history(store.clone()).unwrap(); + vm.set_history_input(history, request).unwrap(); + vm.execute_entry_point_by_name("data.t.first").unwrap(); + run_to_history(&mut vm, &program); + // The first dispatch pins the decision's prefix. + vm.resume(None).unwrap(); + ready.wait(); + appended.wait(); + let first = finish(&mut vm).unwrap(); + vm.set_step_mode(false); + let fresh = vm.execute_entry_point_by_name("data.t.first").unwrap(); + (request, first, fresh) + }) + }) + .collect(); + ready.wait(); + store.append(&history, &[bob]).unwrap(); + appended.wait(); + for worker in threads { + let (request, first, fresh) = worker.join().unwrap(); + assert_eq!(first, expected((request == bob).then_some(0))); + assert_eq!(fresh, Value::from(0usize)); + } + assert_eq!(store.len(&history).unwrap(), 4); +} + +#[test] +fn decision_captures_history_at_its_first_history_step() { + let mut f = Fixture::new(&read_star(1), ExecutionMode::Suspendable); + let read = event(&f.store, "alice", "read", "doc"); + let edit = event(&f.store, "alice", "edit", "doc"); + f.replace(&[read]); + f.vm.set_step_mode(true); + f.decide(read).unwrap(); + // Stop on the RuleInit just before the first HistoryStep: ordinary Rego + // instructions ran, no history dispatch has, so this append is captured. + while !matches!( + f.program.instructions.get(f.vm.get_pc() + 1), + Some(Instruction::HistoryStep { .. }) + ) { + f.vm.resume(None).unwrap(); + } + assert!(matches!( + f.program.instructions.get(f.vm.get_pc()), + Some(Instruction::RuleInit { .. }) + )); + f.store.append(&f.history, &[edit]).unwrap(); + assert_eq!(finish(&mut f.vm).unwrap(), Value::from(0usize)); +} + +#[cfg(feature = "std")] +#[test] +fn concurrent_rewrite_invalidates_both_pinned_decisions() { + use std::sync::Barrier; + let program = read_star(1); + let store = Arc::new(HistoryStore::new()); + let history = store.new_history().unwrap(); + let read = event(&store, "alice", "read", "doc"); + store.append(&history, &[read; 3]).unwrap(); + let paused = Arc::new(Barrier::new(3)); + let rewritten = Arc::new(Barrier::new(3)); + let workers: Vec<_> = (0..2) + .map(|_| { + let store = store.clone(); + let history = history.clone(); + let program = program.clone(); + let paused = paused.clone(); + let rewritten = rewritten.clone(); + std::thread::spawn(move || { + let mut vm = RegoVM::new(); + vm.load_program(program.clone()); + vm.set_execution_mode(ExecutionMode::Suspendable); + vm.set_step_mode(true); + vm.attach_history(store).unwrap(); + vm.set_history_input(history, read).unwrap(); + vm.execute_entry_point_by_name("data.t.first").unwrap(); + run_to_history(&mut vm, &program); + // The first dispatch pins revision 0. + vm.resume(None).unwrap(); + paused.wait(); + rewritten.wait(); + assert!(matches!( + finish(&mut vm), + Err(VmError::History { + source: HistoryError::HistoryChanged { + expected: 0, + actual: 1 + }, + .. + }) + )); + }) + }) + .collect(); + paused.wait(); + store.truncate(&history, 0).unwrap(); + store.append(&history, &[read; 3]).unwrap(); + rewritten.wait(); + for worker in workers { + worker.join().unwrap(); + } +} + +#[test] +fn fixed_head_compares_all_three_exact_byte_identities() { + let program = table( + &[rule( + "require", + r#"{"principal": "alice/\u0000é", "action": "edit", "resource": "doc/é"}"#, + "false", + )], + 256, + ); + for mode in MODES { + let mut f = Fixture::new(&program, mode); + let exact = event(&f.store, "alice/\0é", "edit", "doc/é"); + let other_principal = event(&f.store, "alice/\0e\u{301}", "edit", "doc/é"); + let other_action = event(&f.store, "alice/\0é", "Edit", "doc/é"); + let other_resource = event(&f.store, "alice/\0é", "edit", "doc//é"); + assert_eq!(f.decide(exact).unwrap(), Value::from(0usize)); + for request in [other_principal, other_action, other_resource] { + assert_eq!(f.decide(request).unwrap(), Value::Undefined); + } + } +} + +/// The policy shown in `docs/builtins.md`. +const APPROVALS: &str = r#"package approvals +import rego.v1 + +# require: deny when the committed history is outside the language. +edit_before_release := history.require( + {"action": "release", "principal": actor, "resource": doc}, + [any, {action == "edit", principal == actor, resource == doc}, any], +) +# forbid: deny when the committed history is inside the language. +never_remove_locked := history.forbid({"action": "remove", "resource": doc}, [any, {action == "lock", resource == doc}, any]) +approve_by_other := history.require( + {"action": "approve", "principal": approver, "resource": doc}, + [any, {action == "submit", resource == doc, principal != approver}, any], +) +first_action_is_create := history.require({"action": "create"}, []) # history must be empty +only_reads_so_far := history.require({"action": "audit"}, star({action == "read"})) + +allow if { + edit_before_release + never_remove_locked + approve_by_other +} +deny contains "release requires a prior edit by the same actor" if not edit_before_release +deny contains "locked resources cannot be removed" if not never_remove_locked +"#; + +fn approvals_program() -> Arc { + let mut engine = Engine::new(); + engine + .add_policy("approvals.rego".into(), APPROVALS.into()) + .unwrap(); + let entries = [ + "data.approvals.allow", + "data.approvals.deny", + "data.approvals.approve_by_other", + "data.approvals.first_action_is_create", + "data.approvals.only_reads_so_far", + ]; + let policy = engine.compile_with_entrypoint(&entries[0].into()).unwrap(); + Compiler::compile_from_policy(&policy, &entries).unwrap() +} + +fn assert_approvals(program: &Arc, mode: ExecutionMode) { + let store = Arc::new(HistoryStore::new()); + let history = store.new_history().unwrap(); + let e = |principal, action| event(&store, principal, action, "doc"); + let mut vm = RegoVM::new(); + vm.load_program(program.clone()); + vm.set_execution_mode(mode); + vm.attach_history(store.clone()).unwrap(); + let mut eval = |events: &[Event], request: Event, rule: &str| { + store.truncate(&history, 0).unwrap(); + store.append(&history, events).unwrap(); + vm.set_history_input(history.clone(), request).unwrap(); + vm.execute_entry_point_by_name(&format!("data.approvals.{rule}")) + .unwrap() + }; + let messages = |value: Value| -> Vec { + value + .as_set() + .unwrap() + .iter() + .map(|message| message.as_string().unwrap().to_string()) + .collect() + }; + let (alice_release, alice_edit) = (e("alice", "release"), e("alice", "edit")); + assert_eq!( + eval(&[alice_edit], alice_release, "allow"), + Value::Bool(true) + ); + assert!(messages(eval(&[alice_edit], alice_release, "deny")).is_empty()); + let bob_edit = e("bob", "edit"); + assert_eq!(eval(&[bob_edit], alice_release, "allow"), Value::Undefined); + assert_eq!( + messages(eval(&[bob_edit], alice_release, "deny")), + ["release requires a prior edit by the same actor"] + ); + let (lock, remove) = (e("alice", "lock"), e("alice", "remove")); + assert_eq!(eval(&[lock], remove, "allow"), Value::Undefined); + assert_eq!( + messages(eval(&[lock], remove, "deny")), + ["locked resources cannot be removed"] + ); + let submit = e("alice", "submit"); + assert_eq!( + eval(&[submit], e("bob", "approve"), "approve_by_other"), + Value::Bool(true) + ); + assert_eq!( + eval(&[submit], e("alice", "approve"), "approve_by_other"), + Value::Bool(false) + ); + let (create, read) = (e("alice", "create"), e("alice", "read")); + assert_eq!( + eval(&[], create, "first_action_is_create"), + Value::Bool(true) + ); + assert_eq!( + eval(&[read], create, "first_action_is_create"), + Value::Bool(false) + ); + let audit = e("alice", "audit"); + assert_eq!( + eval(&[read, read], audit, "only_reads_so_far"), + Value::Bool(true) + ); + assert_eq!( + eval(&[read, alice_edit], audit, "only_reads_so_far"), + Value::Bool(false) + ); + // Longer than one batch: the step repeats inside the rule frame. + let long = vec![alice_edit; 600]; + assert_eq!(eval(&long, alice_release, "allow"), Value::Bool(true)); +} + +#[test] +fn rego_history_rules_compose_with_ordinary_rules_in_both_modes() { + let program = approvals_program(); + assert_eq!(program.history_tables.len(), 1); + assert_eq!(program.history_tables[0].rules.len(), 5); + let steps = &program.instruction_data.history_step_params; + assert_eq!(steps.len(), 5); + assert!(steps + .iter() + .all(|step| step.batch_size == HISTORY_BATCH_SIZE)); + let listing = generate_assembly_listing(&program, &AssemblyListingConfig::default()); + assert!( + listing.contains("HistoryStep table[0].rule[0] batch_size=256 dest=r1"), + "{listing}" + ); + let DeserializationResult::Complete(restored) = + Program::deserialize_binary(&program.serialize_binary().unwrap()).unwrap() + else { + panic!("current version must deserialize completely"); + }; + let restored = Arc::new(restored); + for mode in MODES { + assert_approvals(&program, mode); + assert_approvals(&restored, mode); + // Without a staged request the first history rule fails. + let mut vm = RegoVM::new(); + vm.load_program(program.clone()); + vm.set_execution_mode(mode); + vm.attach_history(Arc::new(HistoryStore::new())).unwrap(); + assert!(matches!( + vm.execute_entry_point_by_name("data.approvals.allow"), + Err(VmError::HistoryContextMissing { .. }) + )); + } + // History rules are RVM-only. + let mut engine = Engine::new(); + engine + .add_policy("approvals.rego".into(), APPROVALS.into()) + .unwrap(); + assert!(engine.eval_rule("data.approvals.allow".into()).is_err()); +} + +const PRIOR_EDIT_REQUEST: &str = r#"{"action": "release", "principal": actor, "resource": doc}"#; +const PRIOR_EDIT_LANGUAGE: &str = + r#"[any, {principal == actor, action == "edit", resource == doc}, any]"#; + +fn rego_module(body: &str) -> String { + format!("package t\nimport rego.v1\n{body}") +} + +fn prior_edit_source() -> FlatPair { + FlatPair { + head: vec![ + FlatHead::Bind, + FlatHead::Constant("release".to_owned()), + FlatHead::Bind, + ], + tests: vec![ + FlatTest::Atom { + field: Component(0), + term: FlatTerm::Variable(Component(0)), + positive: true, + }, + FlatTest::Atom { + field: Component(1), + term: FlatTerm::Constant("edit".to_owned()), + positive: true, + }, + FlatTest::Atom { + field: Component(2), + term: FlatTerm::Variable(Component(2)), + positive: true, + }, + FlatTest::And(vec![0, 1, 2]), + ], + regexes: vec![ + FlatRegex::All, + FlatRegex::Test(3), + FlatRegex::All, + FlatRegex::Concat(vec![0, 1, 2]), + ], + root: 3, + } +} + +fn history_steps(program: &Program) -> usize { + program + .instructions + .iter() + .filter(|instruction| matches!(instruction, Instruction::HistoryStep { .. })) + .count() +} + +/// A `require` row followed by a `forbid` row. +fn two_rules() -> Arc { + program( + ®o_module(&format!( + "r0 := history.require({PRIOR_EDIT_REQUEST}, {PRIOR_EDIT_LANGUAGE})\n\ + r1 := history.forbid({{\"principal\": p}}, star({{principal == p}}))\n" + )), + &["data.t.r0", "data.t.r1"], + ) +} + +#[test] +fn rego_history_rules_lower_to_one_table_and_history_step() { + let program = program( + ®o_module(&format!( + "r0 := history.require({PRIOR_EDIT_REQUEST}, {PRIOR_EDIT_LANGUAGE})\n" + )), + &["data.t.r0"], + ); + assert_eq!(program.history_tables.len(), 1); + let rules = &program.history_tables[0].rules; + assert_eq!(rules.len(), 1); + assert_eq!(rules[0].mode, RuleMode::Require); + assert_eq!(rules[0].source, prior_edit_source()); + let steps = &program.instruction_data.history_step_params; + assert_eq!(steps.len(), 1); + assert_eq!( + (steps[0].table, steps[0].rule, steps[0].batch_size), + (0, 0, HISTORY_BATCH_SIZE) + ); + assert_eq!(history_steps(&program), 1); + let listing = generate_assembly_listing(&program, &AssemblyListingConfig::default()); + assert!( + listing.contains(&format!( + "HistoryStep table[0].rule[0] batch_size={HISTORY_BATCH_SIZE} dest=r{}", + steps[0].dest + )), + "{listing}" + ); + + // Each call adds one ordered row to the same table and one step instruction. + let program = two_rules(); + assert_eq!(program.history_tables.len(), 1); + let modes: Vec<_> = program.history_tables[0] + .rules + .iter() + .map(|rule| rule.mode) + .collect(); + assert_eq!(modes, [RuleMode::Require, RuleMode::Forbid]); + let rows: Vec<_> = program + .instruction_data + .history_step_params + .iter() + .map(|step| (step.table, step.rule)) + .collect(); + assert_eq!(rows, [(0, 0), (0, 1)]); + assert_eq!(history_steps(&program), 2); +} + +#[test] +fn compiled_programs_roundtrip_history_tables() { + let program = two_rules(); + let DeserializationResult::Complete(binary) = + Program::deserialize_binary(&program.serialize_binary().unwrap()).unwrap() + else { + panic!("current version must deserialize completely"); + }; + let json = Program::deserialize_json(&program.serialize_json().unwrap()).unwrap(); + for restored in [binary, json] { + assert_eq!(restored.history_tables.len(), 1); + for (restored, original) in restored.history_tables[0] + .rules + .iter() + .zip(&program.history_tables[0].rules) + { + assert_eq!(restored.mode, original.mode); + assert_eq!(restored.source, original.source); + } + let steps = |program: &Program| -> Vec<_> { + program + .instruction_data + .history_step_params + .iter() + .map(|step| (step.table, step.rule, step.batch_size, step.dest)) + .collect() + }; + assert_eq!(steps(&restored), steps(&program)); + assert_eq!(restored.instructions.len(), program.instructions.len()); + assert_eq!(history_steps(&restored), 2); + } +} diff --git a/tests/history_table_format.rs b/tests/history_table_format.rs new file mode 100644 index 000000000..1d8aa98d8 --- /dev/null +++ b/tests/history_table_format.rs @@ -0,0 +1,395 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. +#![cfg(feature = "rvm")] + +use history_syntax::{Component, RuleMode}; +use junco_core::flat::{FlatHead, FlatPair, FlatRegex, FlatTerm, FlatTest}; +use regorus::rvm::program::{DeserializationResult, Program}; +use serde_json::{json, Value as Json}; + +// Rego compiler output for `r0 := history.require({"action": "release", "principal": actor, +// "resource": doc}, [any, {principal == actor, action == "edit", resource == doc}, any])`, +// entry point `data.t.r0`, with batch size 1. +const BINARY: &[u8] = include_bytes!("fixtures/history_table_v7.bin"); +const JSON: &str = include_str!("fixtures/history_table_v7.json"); + +fn binary_program(bytes: &[u8]) -> Program { + match Program::deserialize_binary(bytes).unwrap() { + DeserializationResult::Complete(program) => program, + DeserializationResult::Partial(_) => panic!("version-7 fixture must decode completely"), + } +} + +fn fixture() -> Program { + Program::deserialize_json(JSON).unwrap() +} + +#[test] +fn v7_fixtures_preserve_bytes_schema_and_topology() { + assert_eq!(Program::SERIALIZATION_VERSION, 7); + assert_eq!(BINARY.len(), 434); + assert_eq!(JSON.len(), 4409); + assert_eq!(&BINARY[4..8], &7u32.to_le_bytes()); + let expected = FlatPair { + head: vec![ + FlatHead::Bind, + FlatHead::Constant("release".to_owned()), + FlatHead::Bind, + ], + tests: vec![ + FlatTest::Atom { + field: Component(0), + term: FlatTerm::Variable(Component(0)), + positive: true, + }, + FlatTest::Atom { + field: Component(1), + term: FlatTerm::Constant("edit".to_owned()), + positive: true, + }, + FlatTest::Atom { + field: Component(2), + term: FlatTerm::Variable(Component(2)), + positive: true, + }, + FlatTest::And(vec![0, 1, 2]), + ], + regexes: vec![ + FlatRegex::All, + FlatRegex::Test(3), + FlatRegex::All, + FlatRegex::Concat(vec![0, 1, 2]), + ], + root: 3, + }; + for program in [binary_program(BINARY), fixture()] { + assert_eq!(program.history_tables.len(), 1); + assert_eq!(program.history_tables[0].rules.len(), 1); + let rule = &program.history_tables[0].rules[0]; + assert_eq!(rule.mode, RuleMode::Require); + assert_eq!(rule.source, expected); + let step = &program.instruction_data.history_step_params[0]; + assert_eq!( + (step.table, step.rule, step.batch_size, step.dest), + (0, 0, 1, 1) + ); + assert_eq!(program.serialize_binary().unwrap(), BINARY); + assert_eq!(program.serialize_json().unwrap(), JSON); + let schema: Json = serde_json::from_str(&program.serialize_json().unwrap()).unwrap(); + assert_eq!( + schema["history_tables"][0]["rules"][0], + json!({"mode": "Require", "source": { + "head": ["Bind", {"Constant": "release"}, "Bind"], + "tests": [ + {"Atom": {"field": 0, "term": {"Variable": 0}, "positive": true}}, + {"Atom": {"field": 1, "term": {"Constant": "edit"}, "positive": true}}, + {"Atom": {"field": 2, "term": {"Variable": 2}, "positive": true}}, + {"And": [0, 1, 2]} + ], + "regexes": ["All", {"Test": 3}, "All", {"Concat": [0, 1, 2]}], + "root": 3 + }}) + ); + } +} + +// Replace only the trailing history section; preserve the fixture's real v7 header, sections +// and program structure. Program's public serializers deliberately refuse malformed sources. +fn unchecked_binary(program: &Program) -> Vec { + let read = + |offset: usize| u32::from_le_bytes(BINARY[offset..offset + 4].try_into().unwrap()) as usize; + let structure_len_at = 25 + (8..24).step_by(4).map(read).sum::(); + let history_len_at = structure_len_at + 4 + read(structure_len_at); + let mut bytes = BINARY[..history_len_at].to_vec(); + let payload = postcard::to_allocvec(&( + &program.history_tables, + &program.instruction_data.history_step_params, + )) + .unwrap(); + bytes.extend_from_slice(&u32::try_from(payload.len()).unwrap().to_le_bytes()); + bytes.extend_from_slice(&payload); + bytes +} + +fn unchecked_json(program: &Program) -> String { + let mut document: Json = serde_json::from_str(JSON).unwrap(); + document["history_tables"] = serde_json::to_value(&program.history_tables).unwrap(); + document.to_string() +} + +fn pair(tests: Vec>, regexes: Vec, root: u32) -> FlatPair { + FlatPair { + head: vec![FlatHead::Bind, FlatHead::Any, FlatHead::Bind], + tests, + regexes, + root, + } +} + +#[test] +fn untrusted_artifacts_reject_invalid_sources_without_history_runtime() { + let cases = [ + ("empty regex table", pair(vec![], vec![], 0)), + ( + "root out of bounds", + pair(vec![], vec![FlatRegex::Epsilon], 1), + ), + ("maximum root", pair(vec![], vec![FlatRegex::All], u32::MAX)), + ("self reference", pair(vec![], vec![FlatRegex::Star(0)], 0)), + ( + "forward reference", + pair(vec![], vec![FlatRegex::Complement(1), FlatRegex::All], 0), + ), + ( + "cycle", + pair( + vec![], + vec![FlatRegex::Union(vec![1]), FlatRegex::Concat(vec![0])], + 1, + ), + ), + ( + "concat self reference", + pair(vec![], vec![FlatRegex::Concat(vec![0])], 0), + ), + ( + "intersection forward reference", + pair( + vec![], + vec![FlatRegex::Intersect(vec![1]), FlatRegex::All], + 1, + ), + ), + ("missing test", pair(vec![], vec![FlatRegex::Test(0)], 0)), + ( + "test out of bounds", + pair(vec![FlatTest::Bool(true)], vec![FlatRegex::Test(1)], 0), + ), + ( + "test self reference", + pair(vec![FlatTest::And(vec![0])], vec![FlatRegex::Test(0)], 0), + ), + ( + "test forward reference", + pair( + vec![FlatTest::Or(vec![1]), FlatTest::Bool(true)], + vec![FlatRegex::Test(1)], + 0, + ), + ), + ( + "test cycle", + pair( + vec![FlatTest::And(vec![1]), FlatTest::Or(vec![0])], + vec![FlatRegex::Test(1)], + 0, + ), + ), + ( + "wrong coordinate", + pair( + vec![FlatTest::Atom { + field: Component(0), + term: FlatTerm::Variable(Component(2)), + positive: true, + }], + vec![FlatRegex::Test(0)], + 0, + ), + ), + ( + "unbound wildcard head", + pair( + vec![FlatTest::Atom { + field: Component(1), + term: FlatTerm::Variable(Component(1)), + positive: false, + }], + vec![FlatRegex::Test(0)], + 0, + ), + ), + ( + "invalid unreachable regex", + pair(vec![], vec![FlatRegex::Epsilon, FlatRegex::Star(1)], 0), + ), + ( + "invalid unused test", + pair(vec![FlatTest::And(vec![0])], vec![FlatRegex::Epsilon], 0), + ), + ( + "head arity zero", + FlatPair { + head: vec![], + tests: vec![], + regexes: vec![FlatRegex::All], + root: 0, + }, + ), + ]; + let mut invalid = cases.to_vec(); + let mut constant_head = pair( + vec![FlatTest::Atom { + field: Component(0), + term: FlatTerm::Variable(Component(0)), + positive: true, + }], + vec![FlatRegex::Test(0)], + 0, + ); + constant_head.head[0] = FlatHead::Constant("alice".to_owned()); + invalid.push(("unbound constant head", constant_head)); + for (name, source) in invalid { + let mut program = fixture(); + program.history_tables[0].rules[0].source = source; + assert!(program.validate_limits().is_err(), "{name}"); + assert!(program.serialize_json().is_err(), "{name}"); + assert!(program.serialize_binary().is_err(), "{name}"); + assert!( + Program::deserialize_json(&unchecked_json(&program)).is_err(), + "{name}" + ); + assert!( + Program::deserialize_binary(&unchecked_binary(&program)).is_err(), + "{name}" + ); + } +} + +#[test] +fn valid_shared_dags_empty_operators_and_non_last_roots_roundtrip_unchanged() { + let source = pair( + vec![ + FlatTest::Bool(false), + FlatTest::And(vec![]), + FlatTest::Or(vec![]), + FlatTest::And(vec![0, 0]), + FlatTest::Or(vec![1, 2, 1]), + ], + vec![ + FlatRegex::Epsilon, + FlatRegex::Empty, + FlatRegex::All, + FlatRegex::Concat(vec![]), + FlatRegex::Union(vec![]), + FlatRegex::Intersect(vec![]), + FlatRegex::Test(3), + FlatRegex::Test(4), + FlatRegex::Concat(vec![0, 0]), + FlatRegex::Union(vec![8, 8]), + FlatRegex::Intersect(vec![9, 9]), + FlatRegex::Star(10), + FlatRegex::Complement(11), + ], + 0, + ); + let mut sources = vec![pair(vec![], vec![FlatRegex::Epsilon], 0)]; + for root in 0..source.regexes.len() { + let mut rooted = source.clone(); + rooted.root = u32::try_from(root).unwrap(); + sources.push(rooted); + } + for source in sources { + let mut program = fixture(); + program.history_tables[0].rules[0].mode = RuleMode::Forbid; + program.history_tables[0].rules[0].source = source.clone(); + program.validate_limits().unwrap(); + let binary = program.serialize_binary().unwrap(); + let json = program.serialize_json().unwrap(); + for restored in [ + binary_program(&binary), + Program::deserialize_json(&json).unwrap(), + ] { + assert_eq!(restored.history_tables[0].rules[0].source, source); + assert_eq!(restored.history_tables[0].rules[0].mode, RuleMode::Forbid); + assert_eq!(restored.serialize_binary().unwrap(), binary); + assert_eq!(restored.serialize_json().unwrap(), json); + } + } +} + +#[test] +fn canonical_enum_discriminants_and_atom_fields_keep_v7_order() { + for (index, head) in [FlatHead::Any, FlatHead::Constant("x"), FlatHead::Bind] + .iter() + .enumerate() + { + assert_eq!( + postcard::to_allocvec(head).unwrap()[0], + u8::try_from(index).unwrap() + ); + } + for (index, term) in [FlatTerm::Constant("x"), FlatTerm::Variable(Component(0))] + .iter() + .enumerate() + { + assert_eq!( + postcard::to_allocvec(term).unwrap()[0], + u8::try_from(index).unwrap() + ); + } + for (index, component) in [Component(0), Component(1), Component(2)] + .iter() + .enumerate() + { + assert_eq!( + postcard::to_allocvec(component).unwrap(), + [u8::try_from(index).unwrap()] + ); + } + assert_eq!(postcard::to_allocvec(&RuleMode::Require).unwrap(), [0]); + assert_eq!(postcard::to_allocvec(&RuleMode::Forbid).unwrap(), [1]); + let atom = FlatTest::Atom { + field: Component(2), + term: FlatTerm::::Variable(Component(2)), + positive: true, + }; + // Atom discriminant, field, term discriminant, variable coordinate, polarity. + assert_eq!(postcard::to_allocvec(&atom).unwrap(), [1, 2, 1, 2, 1]); + for (index, test) in [ + FlatTest::Bool(false), + atom, + FlatTest::And(vec![]), + FlatTest::Or(vec![]), + ] + .iter() + .enumerate() + { + assert_eq!( + postcard::to_allocvec(test).unwrap()[0], + u8::try_from(index).unwrap() + ); + } + for (index, regex) in [ + FlatRegex::Empty, + FlatRegex::All, + FlatRegex::Epsilon, + FlatRegex::Test(0), + FlatRegex::Concat(vec![]), + FlatRegex::Union(vec![]), + FlatRegex::Intersect(vec![]), + FlatRegex::Star(0), + FlatRegex::Complement(0), + ] + .iter() + .enumerate() + { + assert_eq!( + postcard::to_allocvec(regex).unwrap()[0], + u8::try_from(index).unwrap() + ); + } +} + +#[cfg(not(feature = "history"))] +#[test] +fn history_step_requires_the_history_feature() { + use regorus::rvm::vm::{RegoVM, VmError}; + + let mut vm = RegoVM::new(); + vm.load_program(std::sync::Arc::new(binary_program(BINARY))); + assert!(matches!( + vm.execute_entry_point_by_name("data.t.r0"), + Err(VmError::HistoryFeatureDisabled { .. }) + )); +} diff --git a/tests/rvm/vm/suites/call_rule.yaml b/tests/rvm/vm/suites/call_rule.yaml index f1b60ed36..5e46da5ad 100644 --- a/tests/rvm/vm/suites/call_rule.yaml +++ b/tests/rvm/vm/suites/call_rule.yaml @@ -115,3 +115,26 @@ cases: - "Load { dest: 1, literal_idx: 0 }" - "RuleReturn {}" want_result: 99 + + - note: call_rule_callee_laid_out_before_caller + description: Step mode keeps a pushed callee's entry pc when its code precedes the caller + literals: + - 1 + rule_infos: + - rule_type: Complete + definitions: + - [5] + - rule_type: Complete + definitions: + - [2] + instructions: + - "CallRule { dest: 0, rule_index: 0 }" + - "Return { value: 0 }" + - "RuleInit { result_reg: 1, rule_index: 1 }" + - "Load { dest: 1, literal_idx: 0 }" + - "RuleReturn {}" + - "RuleInit { result_reg: 1, rule_index: 0 }" + - "CallRule { dest: 2, rule_index: 1 }" + - "Move { dest: 1, src: 2 }" + - "RuleReturn {}" + want_result: 1 diff --git a/xtask/src/tasks/ci/mod.rs b/xtask/src/tasks/ci/mod.rs index 73827b950..267f4ff76 100644 --- a/xtask/src/tasks/ci/mod.rs +++ b/xtask/src/tasks/ci/mod.rs @@ -242,6 +242,37 @@ fn run_ci_suite(config: CiSuiteConfig) -> Result<()> { )?; } + run_ci_cargo_step( + &workspace, + "test", + config.release, + config.frozen, + None, + &["--features", "history"], + "cargo test --features history (ci)", + )?; + + run_ci_cargo_step( + &workspace, + "test", + config.release, + config.frozen, + None, + &[ + "-p", + "history-syntax", + "-p", + "junco-core", + "-p", + "history-store", + "-p", + "history-semantics", + "--features", + "history-semantics/test-util,history-store/test-util", + ], + "cargo test -p history-syntax -p junco-core -p history-store -p history-semantics (ci)", + )?; + if config.include_azure_rbac { run_ci_cargo_step( &workspace, @@ -408,6 +439,8 @@ fn check_feature_combinations(workspace: &Path, release: bool, frozen: bool) -> "std,arc,rvm,coverage,cache,regex,time", // Default-off explanations (implies rvm) without full-opa. "std,arc,explanations", + // Default-off history rules (implies rvm) without full-opa. + "std,arc,history", ]; for features in combos {