From 11b1cf06c1898373fb395e953fe7f2a7ab17fa37 Mon Sep 17 00:00:00 2001 From: Duncan Ogilvie Date: Tue, 24 Nov 2026 19:18:40 +0100 Subject: [PATCH 1/8] Rename smt-server to bv-server The project is a bit-vector expression service: it solves, optimizes and simplifies QF_BV expressions. "smt-server" made people think it was only an SMT solver front-end. Mechanical rename only; behaviour and the wire format are unchanged: - crates: smt-server -> bv-server, smt-wire -> bv-wire, smt-qfbv-smtlib -> bv-smtlib (qfbvsmtrs keeps its name) - Python: smt_wire -> bv_wire (examples use `import bv_wire as bv`), smt_z3_server.py -> bv_z3_server.py - C++: header, namespace and CMake package smt_wire -> bv_wire, base exception smt_error -> bv_error - environment variables SMT_SERVER_* -> BV_SERVER_* - default data directory ~/.smt-server -> ~/.bv-server - docs/smt-wire-protocol.md -> docs/bv-wire-protocol.md --- .github/workflows/ci.yml | 12 +- Cargo.lock | 56 ++-- Cargo.toml | 12 +- README.md | 60 ++-- cpp/CMakeLists.txt | 44 +-- cpp/cmake/bv_wireConfig.cmake.in | 5 + cpp/cmake/smt_wireConfig.cmake.in | 5 - .../smt_wire.hpp => bv_wire/bv_wire.hpp} | 22 +- cpp/tests/example.cpp | 32 +- cpp/tests/smoke.cpp | 46 +-- crates/{smt-server => bv-server}/Cargo.toml | 8 +- .../{smt-server => bv-server}/src/backend.rs | 24 +- .../src/binbit_backend.rs | 56 ++-- crates/{smt-server => bv-server}/src/cache.rs | 2 +- .../src/command_router.rs | 6 +- crates/{smt-server => bv-server}/src/lib.rs | 2 +- crates/{smt-server => bv-server}/src/main.rs | 8 +- crates/{smt-server => bv-server}/src/pool.rs | 4 +- .../{smt-server => bv-server}/src/protocol.rs | 33 +- .../src/qfbvsmtrs_backend.rs | 26 +- .../{smt-server => bv-server}/src/racing.rs | 4 +- .../src/recording.rs | 26 +- .../src/rumba_backend.rs | 52 +-- .../{smt-server => bv-server}/src/server.rs | 6 +- crates/{smt-server => bv-server}/src/smt2.rs | 24 +- .../{smt-server => bv-server}/src/smtlib.rs | 66 ++-- .../src/z3_backend.rs | 64 ++-- .../tests/phase2_server.rs | 10 +- .../tests/phase4_5_text_and_racing.rs | 14 +- .../tests/phase6_simplify_optimize.rs | 10 +- .../tests/phase7_cache.rs | 6 +- .../tests/phase8_e2e.rs | 4 +- .../tests/rumba_island_simplify.rs | 6 +- .../tests/rumba_simplify.rs | 26 +- .../{smt-qfbv-smtlib => bv-smtlib}/Cargo.toml | 2 +- .../{smt-qfbv-smtlib => bv-smtlib}/src/lib.rs | 0 crates/{smt-wire => bv-wire}/Cargo.toml | 6 +- .../{smt-wire => bv-wire}/examples/example.rs | 10 +- crates/{smt-wire => bv-wire}/src/api.rs | 0 crates/{smt-wire => bv-wire}/src/builder.rs | 0 crates/{smt-wire => bv-wire}/src/client.rs | 2 +- crates/{smt-wire => bv-wire}/src/constants.rs | 0 crates/{smt-wire => bv-wire}/src/error.rs | 2 +- crates/{smt-wire => bv-wire}/src/expr.rs | 0 crates/{smt-wire => bv-wire}/src/le.rs | 0 crates/{smt-wire => bv-wire}/src/lib.rs | 2 +- crates/{smt-wire => bv-wire}/src/request.rs | 0 crates/{smt-wire => bv-wire}/src/response.rs | 0 crates/{smt-wire => bv-wire}/src/types.rs | 0 .../tests/phase0_golden.rs | 2 +- .../tests/phase1_codecs.rs | 10 +- crates/qfbvsmtrs/Cargo.toml | 6 +- crates/qfbvsmtrs/fuzz/Cargo.lock | 4 +- crates/qfbvsmtrs/src/frontend.rs | 2 +- crates/qfbvsmtrs/src/lib.rs | 2 +- crates/qfbvsmtrs/src/wire.rs | 12 +- docs/architecture.md | 28 +- ...t-wire-protocol.md => bv-wire-protocol.md} | 4 +- docs/client-api.md | 30 +- docs/qfbvsmtrs-design.md | 8 +- docs/qfbvsmtrs-validation.md | 8 +- docs/smtlib-frontend.md | 12 +- python/README.md | 16 +- python/{smt_wire.py => bv_wire.py} | 6 +- python/{smt_z3_server.py => bv_z3_server.py} | 314 +++++++++--------- python/example.py | 20 +- python/pyproject.toml | 8 +- python/tests/test_live_server.py | 46 +-- python/tests/test_python_client.py | 134 ++++---- python/tests/test_z3_server.py | 26 +- python/uv.lock | 2 +- 71 files changed, 749 insertions(+), 756 deletions(-) create mode 100644 cpp/cmake/bv_wireConfig.cmake.in delete mode 100644 cpp/cmake/smt_wireConfig.cmake.in rename cpp/include/{smt_wire/smt_wire.hpp => bv_wire/bv_wire.hpp} (98%) rename crates/{smt-server => bv-server}/Cargo.toml (71%) rename crates/{smt-server => bv-server}/src/backend.rs (96%) rename crates/{smt-server => bv-server}/src/binbit_backend.rs (94%) rename crates/{smt-server => bv-server}/src/cache.rs (97%) rename crates/{smt-server => bv-server}/src/command_router.rs (89%) rename crates/{smt-server => bv-server}/src/lib.rs (95%) rename crates/{smt-server => bv-server}/src/main.rs (87%) rename crates/{smt-server => bv-server}/src/pool.rs (92%) rename crates/{smt-server => bv-server}/src/protocol.rs (92%) rename crates/{smt-server => bv-server}/src/qfbvsmtrs_backend.rs (90%) rename crates/{smt-server => bv-server}/src/racing.rs (97%) rename crates/{smt-server => bv-server}/src/recording.rs (94%) rename crates/{smt-server => bv-server}/src/rumba_backend.rs (92%) rename crates/{smt-server => bv-server}/src/server.rs (96%) rename crates/{smt-server => bv-server}/src/smt2.rs (96%) rename crates/{smt-server => bv-server}/src/smtlib.rs (87%) rename crates/{smt-server => bv-server}/src/z3_backend.rs (94%) rename crates/{smt-server => bv-server}/tests/phase2_server.rs (98%) rename crates/{smt-server => bv-server}/tests/phase4_5_text_and_racing.rs (97%) rename crates/{smt-server => bv-server}/tests/phase6_simplify_optimize.rs (97%) rename crates/{smt-server => bv-server}/tests/phase7_cache.rs (92%) rename crates/{smt-server => bv-server}/tests/phase8_e2e.rs (96%) rename crates/{smt-server => bv-server}/tests/rumba_island_simplify.rs (94%) rename crates/{smt-server => bv-server}/tests/rumba_simplify.rs (94%) rename crates/{smt-qfbv-smtlib => bv-smtlib}/Cargo.toml (89%) rename crates/{smt-qfbv-smtlib => bv-smtlib}/src/lib.rs (100%) rename crates/{smt-wire => bv-wire}/Cargo.toml (74%) rename crates/{smt-wire => bv-wire}/examples/example.rs (89%) rename crates/{smt-wire => bv-wire}/src/api.rs (100%) rename crates/{smt-wire => bv-wire}/src/builder.rs (100%) rename crates/{smt-wire => bv-wire}/src/client.rs (98%) rename crates/{smt-wire => bv-wire}/src/constants.rs (100%) rename crates/{smt-wire => bv-wire}/src/error.rs (97%) rename crates/{smt-wire => bv-wire}/src/expr.rs (100%) rename crates/{smt-wire => bv-wire}/src/le.rs (100%) rename crates/{smt-wire => bv-wire}/src/lib.rs (97%) rename crates/{smt-wire => bv-wire}/src/request.rs (100%) rename crates/{smt-wire => bv-wire}/src/response.rs (100%) rename crates/{smt-wire => bv-wire}/src/types.rs (100%) rename crates/{smt-wire => bv-wire}/tests/phase0_golden.rs (96%) rename crates/{smt-wire => bv-wire}/tests/phase1_codecs.rs (98%) rename docs/{smt-wire-protocol.md => bv-wire-protocol.md} (97%) rename python/{smt_wire.py => bv_wire.py} (99%) rename python/{smt_z3_server.py => bv_z3_server.py} (78%) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index de6ca62..01a53af 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -49,13 +49,13 @@ jobs: - name: Python package install smoke run: | python -m pip install ./python --target python-pkg-smoke - python -c "import sys; sys.path.insert(0, 'python-pkg-smoke'); import smt_wire; ctx = smt_wire.Context(); assert ctx.bv_var('x', 8).width == 8" + python -c "import sys; sys.path.insert(0, 'python-pkg-smoke'); import bv_wire; ctx = bv_wire.Context(); assert ctx.bv_var('x', 8).width == 8" - name: Live server end-to-end run: python python/tests/test_live_server.py - name: C++ client CMake smoke shell: bash run: | - cargo build --locked -p smt-server + cargo build --locked -p bv-server cd cpp cmake -B build -DCMAKE_BUILD_TYPE=Debug cmake --build build --config Debug @@ -79,9 +79,9 @@ jobs: if z3_dirs: for var in ("PATH", "LD_LIBRARY_PATH", "DYLD_LIBRARY_PATH"): env[var] = os.pathsep.join(z3_dirs + [env.get(var, "")]) - env["SMT_SERVER_ADDRESS"] = "127.0.0.1:9123" + env["BV_SERVER_ADDRESS"] = "127.0.0.1:9123" - exe = root / "target" / "debug" / ("smt-server.exe" if os.name == "nt" else "smt-server") + exe = root / "target" / "debug" / ("bv-server.exe" if os.name == "nt" else "bv-server") log_path = root / "target" / "cpp-e2e-server.log" with log_path.open("wb") as log: proc = subprocess.Popen([str(exe), "127.0.0.1:9123"], cwd=root, env=env, stdout=log, stderr=log) @@ -90,7 +90,7 @@ jobs: last_error = None while time.time() < deadline: if proc.poll() is not None: - raise RuntimeError(f"smt-server exited early with {proc.returncode}") + raise RuntimeError(f"bv-server exited early with {proc.returncode}") try: with socket.create_connection(("127.0.0.1", 9123), timeout=0.2): break @@ -98,7 +98,7 @@ jobs: last_error = exc time.sleep(0.05) else: - raise TimeoutError(f"smt-server did not start: {last_error}") + raise TimeoutError(f"bv-server did not start: {last_error}") subprocess.check_call(["ctest", "--test-dir", str(root / "cpp" / "build"), "--output-on-failure", "-C", "Debug"], env=env) except Exception: log.flush() diff --git a/Cargo.lock b/Cargo.lock index 3b7af70..a971a70 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -204,6 +204,32 @@ version = "3.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d20789868f4b01b2f2caec9f5c4e0213b41e3e5702a50157d699ae31ced2fcb" +[[package]] +name = "bv-server" +version = "0.1.0" +dependencies = [ + "binbit", + "blake3", + "bv-smtlib", + "bv-wire", + "qfbvsmtrs", + "rumba-core", + "rusqlite", + "z3", +] + +[[package]] +name = "bv-smtlib" +version = "0.1.0" +dependencies = [ + "dashu", + "yaspar", +] + +[[package]] +name = "bv-wire" +version = "0.1.0" + [[package]] name = "bytes" version = "1.11.1" @@ -1502,8 +1528,8 @@ dependencies = [ name = "qfbvsmtrs" version = "0.1.0" dependencies = [ - "smt-qfbv-smtlib", - "smt-wire", + "bv-smtlib", + "bv-wire", "splr", "varisat", "z3", @@ -1931,32 +1957,6 @@ version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" -[[package]] -name = "smt-qfbv-smtlib" -version = "0.1.0" -dependencies = [ - "dashu", - "yaspar", -] - -[[package]] -name = "smt-server" -version = "0.1.0" -dependencies = [ - "binbit", - "blake3", - "qfbvsmtrs", - "rumba-core", - "rusqlite", - "smt-qfbv-smtlib", - "smt-wire", - "z3", -] - -[[package]] -name = "smt-wire" -version = "0.1.0" - [[package]] name = "socket2" version = "0.6.3" diff --git a/Cargo.toml b/Cargo.toml index 2fbdaf0..3012b09 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,9 +1,9 @@ [workspace] members = [ - "crates/smt-wire", - "crates/smt-server", + "crates/bv-wire", + "crates/bv-server", "crates/qfbvsmtrs", - "crates/smt-qfbv-smtlib", + "crates/bv-smtlib", ] resolver = "2" @@ -16,11 +16,11 @@ license = "MIT OR Apache-2.0" # Workspace members. `crates/qfbvsmtrs/fuzz` declares its own `[workspace]` and so # sits outside this one; it keeps a plain path dependency on qfbvsmtrs. qfbvsmtrs = { path = "crates/qfbvsmtrs" } -smt-qfbv-smtlib = { path = "crates/smt-qfbv-smtlib" } -smt-wire = { path = "crates/smt-wire" } +bv-smtlib = { path = "crates/bv-smtlib" } +bv-wire = { path = "crates/bv-wire" } # External. z3 has to stay on a single version across the workspace: it is a -# normal dependency of smt-server and a dev-dependency of qfbvsmtrs, and the +# normal dependency of bv-server and a dev-dependency of qfbvsmtrs, and the # gh-release feature downloads a matching prebuilt solver for each. binbit = { git = "https://github.com/bint-disasm/binbit", rev = "b4996145c06f39ce5bbc79a959975d7d20b6cf5e" } blake3 = "1" diff --git a/README.md b/README.md index 705ce7a..4eb933a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ -# SMT Server +# bv-server -SMT Server lets analysis tools build `QF_BV` formulas with small client libraries and delegate solving or simplification to a separate server. +bv-server lets analysis tools build `QF_BV` formulas with small client libraries and delegate solving or simplification to a separate server. It targets binary analysis, lifting, symbolic execution, and IR experiments where client projects need bit-vector queries but should avoid embedding solver build systems. A client constructs a flat binary DAG, sends a length-prefixed request, and receives a model, unsat core, optimum value, or simplified expression. The server owns the solver and simplifier integrations. @@ -8,7 +8,7 @@ It targets binary analysis, lifting, symbolic execution, and IR experiments wher - C++: header-only C++17 package under `cpp/`. - Python: dependency-free package under `python/`, installable with pip's `#subdirectory=python` support. -- Rust: `smt-wire` crate with an idiomatic `Context`/term/`Client` API; protocol internals are isolated for the server. +- Rust: `bv-wire` crate with an idiomatic `Context`/term/`Client` API; protocol internals are isolated for the server. ## Backends @@ -40,10 +40,10 @@ cargo build --workspace ## Run the server ```sh -cargo run -p smt-server -- 127.0.0.1:9123 +cargo run -p bv-server -- 127.0.0.1:9123 ``` -If no address is provided, the server listens on `127.0.0.1:9123`. Clients use `SMT_SERVER_ADDRESS=:` as their default connection target, falling back to `127.0.0.1:9123` when the variable is unset. +If no address is provided, the server listens on `127.0.0.1:9123`. Clients use `BV_SERVER_ADDRESS=:` as their default connection target, falling back to `127.0.0.1:9123` when the variable is unset. Requests use length-prefixed frames: @@ -54,7 +54,7 @@ payload bytes Payload formats: -- binary `SMTQ` request produced by `smt-wire` or one of the clients; +- binary `SMTQ` request produced by `bv-wire` or one of the clients; - SMT-LIB script as UTF-8 text. ## Request recording @@ -64,47 +64,47 @@ The server records every handled binary request/response pair to a local SQLite Default database: ```text -~/.smt-server/recordings.db +~/.bv-server/recordings.db ``` -Override the database with `SMT_SERVER_RECORD_DB`: +Override the database with `BV_SERVER_RECORD_DB`: ```sh -SMT_SERVER_RECORD_DB=/tmp/smt-recordings.db cargo run -p smt-server -- 127.0.0.1:9123 +BV_SERVER_RECORD_DB=/tmp/bv-recordings.db cargo run -p bv-server -- 127.0.0.1:9123 ``` -Set `SMT_SERVER_RECORD_DB` to an empty value to disable recording: +Set `BV_SERVER_RECORD_DB` to an empty value to disable recording: ```sh -SMT_SERVER_RECORD_DB= cargo run -p smt-server -- 127.0.0.1:9123 +BV_SERVER_RECORD_DB= cargo run -p bv-server -- 127.0.0.1:9123 ``` Rows are deduplicated by the BLAKE3 hash of the canonical binary request, with request and response `request_id` fields zeroed so equivalent requests share one entry. Existing rows are left unchanged. -To import the old file-tree corpus from `~/.smt-server/requests` into the SQLite database: +To import the old file-tree corpus from `~/.bv-server/requests` into the SQLite database: ```sh -cargo run -p smt-server -- migrate-recordings +cargo run -p bv-server -- migrate-recordings ``` Custom migration paths are supported: ```sh -cargo run -p smt-server -- migrate-recordings /path/to/requests /tmp/smt-recordings.db +cargo run -p bv-server -- migrate-recordings /path/to/requests /tmp/bv-recordings.db ``` ## Python client example -The Python client can be installed with `pip install 'git+https://github.com/LLVMParty/smt-server.git#subdirectory=python'` or used directly by adding `python/` to `PYTHONPATH`. +The Python client can be installed with `pip install 'git+https://github.com/LLVMParty/bv-server.git#subdirectory=python'` or used directly by adding `python/` to `PYTHONPATH`. ```python -import smt_wire as smt +import bv_wire as bv -ctx = smt.Context() +ctx = bv.Context() x = ctx.bv_var("x", 8) ctx.assert_(ctx.bv_eq(x, 42)) -with smt.Client() as client: +with bv.Client() as client: response = client.solve(ctx) # want_model=True by default print(response.status) # Status.SAT @@ -121,13 +121,13 @@ print(ctx.to_smt2()) # includes check-sat/get-model by default `SIMPLIFY` requests send one expression root and return a typed term in a fresh result context: ```python -import smt_wire as smt +import bv_wire as bv -ctx = smt.Context() +ctx = bv.Context() x = ctx.bv_var("x", 64) target = x + 0 -with smt.Client() as client: +with bv.Client() as client: simplified = client.simplify(target) if simplified.term is not None: @@ -151,7 +151,7 @@ A text frame can contain an SMT-LIB script: The text frontend supports declarations, assertions, named assertions, `check-sat`, `check-sat-assuming`, `get-model`, `get-value`, `get-unsat-core`, `let`, and common bit-vector operations. It rejects stateful incremental commands such as `push` and `pop`. ```python -with smt.Client() as client: +with bv.Client() as client: print(client.smt2(script)) ``` @@ -160,7 +160,7 @@ The full Python walkthrough is in `python/example.py`. ## Rust client ```rust -use smt_wire::{Client, Context, Status}; +use bv_wire::{Client, Context, Status}; let ctx = Context::new(); let x = ctx.bv_var("x", 8).unwrap(); @@ -176,20 +176,20 @@ if response.status == Status::Sat { } ``` -A matching Rust walkthrough is in `crates/smt-wire/examples/example.rs`. +A matching Rust walkthrough is in `crates/bv-wire/examples/example.rs`. ## C++ client The C++ helper is a dependency-free C++17 header: ```cpp -#include +#include -smt_wire::Context ctx; +bv_wire::Context ctx; auto x = ctx.bv_var("x", 8); ctx.assert_(ctx.bv_eq(x, 42u)); -smt_wire::Client client; +bv_wire::Client client; auto response = client.solve(ctx); ``` @@ -223,14 +223,14 @@ See `docs/qfbvsmtrs-validation.md` for maintainer validation gates and corpus-ru ## Repository layout -- `crates/smt-wire` — Rust high-level client API plus server-side wire-format internals and validators. +- `crates/bv-wire` — Rust high-level client API plus server-side wire-format internals and validators. - `crates/qfbvsmtrs` — standalone pure-Rust `QF_BV` bit-blasting solver crate and CLI. -- `crates/smt-server` — TCP server, Rumba simplifier integration, solver backend integration, SMT-LIB frontend. +- `crates/bv-server` — TCP server, Rumba simplifier integration, solver backend integration, SMT-LIB frontend. - `python` — Python client package and tests. - `cpp` — C++17 header-only package, CMake target, and tests. - `docs/architecture.md` — current crate/server/backend architecture. - `docs/client-api.md` — Python, C++, and Rust client API notes. -- `docs/smt-wire-protocol.md` — binary wire protocol reference. +- `docs/bv-wire-protocol.md` — binary wire protocol reference. - `docs/smtlib-frontend.md` — shared QF_BV SMT-LIB frontend behavior. - `docs/qfbvsmtrs-design.md` — pure-Rust solver design. - `docs/qfbvsmtrs-validation.md` — validation gates and latest corpus status. diff --git a/cpp/CMakeLists.txt b/cpp/CMakeLists.txt index 8ba860d..fa3cfbf 100644 --- a/cpp/CMakeLists.txt +++ b/cpp/CMakeLists.txt @@ -1,30 +1,30 @@ cmake_minimum_required(VERSION 3.21) -project(smt_wire VERSION 0.1.0 LANGUAGES CXX) +project(bv_wire VERSION 0.1.0 LANGUAGES CXX) include(CMakePackageConfigHelpers) include(GNUInstallDirs) -option(SMT_WIRE_CPP_BUILD_TESTS "Build smt-wire C++ tests" ${PROJECT_IS_TOP_LEVEL}) +option(BV_WIRE_CPP_BUILD_TESTS "Build bv-wire C++ tests" ${PROJECT_IS_TOP_LEVEL}) -add_library(smt_wire INTERFACE) -add_library(smt_wire::smt_wire ALIAS smt_wire) +add_library(bv_wire INTERFACE) +add_library(bv_wire::bv_wire ALIAS bv_wire) -target_compile_features(smt_wire INTERFACE cxx_std_17) +target_compile_features(bv_wire INTERFACE cxx_std_17) target_include_directories( - smt_wire + bv_wire INTERFACE $ $ ) if(WIN32) - target_link_libraries(smt_wire INTERFACE ws2_32) + target_link_libraries(bv_wire INTERFACE ws2_32) endif() install( - TARGETS smt_wire - EXPORT smt_wireTargets + TARGETS bv_wire + EXPORT bv_wireTargets INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} ) install( @@ -32,36 +32,36 @@ install( DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} ) install( - EXPORT smt_wireTargets - NAMESPACE smt_wire:: - DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/smt_wire + EXPORT bv_wireTargets + NAMESPACE bv_wire:: + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/bv_wire ) configure_package_config_file( - cmake/smt_wireConfig.cmake.in - ${CMAKE_CURRENT_BINARY_DIR}/smt_wireConfig.cmake - INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/smt_wire + cmake/bv_wireConfig.cmake.in + ${CMAKE_CURRENT_BINARY_DIR}/bv_wireConfig.cmake + INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/bv_wire ) write_basic_package_version_file( - ${CMAKE_CURRENT_BINARY_DIR}/smt_wireConfigVersion.cmake + ${CMAKE_CURRENT_BINARY_DIR}/bv_wireConfigVersion.cmake VERSION ${PROJECT_VERSION} COMPATIBILITY SameMajorVersion ) install( FILES - ${CMAKE_CURRENT_BINARY_DIR}/smt_wireConfig.cmake - ${CMAKE_CURRENT_BINARY_DIR}/smt_wireConfigVersion.cmake - DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/smt_wire + ${CMAKE_CURRENT_BINARY_DIR}/bv_wireConfig.cmake + ${CMAKE_CURRENT_BINARY_DIR}/bv_wireConfigVersion.cmake + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/bv_wire ) -if(SMT_WIRE_CPP_BUILD_TESTS) +if(BV_WIRE_CPP_BUILD_TESTS) enable_testing() set(CMAKE_EXPORT_COMPILE_COMMANDS ON) add_executable(smoke tests/smoke.cpp) - target_link_libraries(smoke PRIVATE smt_wire::smt_wire) + target_link_libraries(smoke PRIVATE bv_wire::bv_wire) add_test(NAME smoke COMMAND $) add_executable(example tests/example.cpp) - target_link_libraries(example PRIVATE smt_wire::smt_wire) + target_link_libraries(example PRIVATE bv_wire::bv_wire) add_test(NAME example COMMAND $) endif() diff --git a/cpp/cmake/bv_wireConfig.cmake.in b/cpp/cmake/bv_wireConfig.cmake.in new file mode 100644 index 0000000..469eed6 --- /dev/null +++ b/cpp/cmake/bv_wireConfig.cmake.in @@ -0,0 +1,5 @@ +@PACKAGE_INIT@ + +include("${CMAKE_CURRENT_LIST_DIR}/bv_wireTargets.cmake") + +check_required_components(bv_wire) diff --git a/cpp/cmake/smt_wireConfig.cmake.in b/cpp/cmake/smt_wireConfig.cmake.in deleted file mode 100644 index b482ef9..0000000 --- a/cpp/cmake/smt_wireConfig.cmake.in +++ /dev/null @@ -1,5 +0,0 @@ -@PACKAGE_INIT@ - -include("${CMAKE_CURRENT_LIST_DIR}/smt_wireTargets.cmake") - -check_required_components(smt_wire) diff --git a/cpp/include/smt_wire/smt_wire.hpp b/cpp/include/bv_wire/bv_wire.hpp similarity index 98% rename from cpp/include/smt_wire/smt_wire.hpp rename to cpp/include/bv_wire/bv_wire.hpp index 1c0297d..49df1a3 100644 --- a/cpp/include/smt_wire/smt_wire.hpp +++ b/cpp/include/bv_wire/bv_wire.hpp @@ -37,13 +37,13 @@ #undef ERROR #endif -namespace smt_wire { +namespace bv_wire { constexpr uint32_t BOOL_BIT = 0x80000000u; constexpr uint32_t INDEX_MASK = 0x7fffffffu; constexpr uint32_t MAX_WIDTH = 65536u; constexpr size_t DEFAULT_MAX_RESPONSE_BYTES = 64u * 1024u * 1024u; -constexpr const char* SERVER_ADDRESS_ENV = "SMT_SERVER_ADDRESS"; +constexpr const char* SERVER_ADDRESS_ENV = "BV_SERVER_ADDRESS"; constexpr const char* DEFAULT_SERVER_HOST = "127.0.0.1"; constexpr uint16_t DEFAULT_SERVER_PORT = 9123; @@ -494,11 +494,11 @@ class TcpTransport { } // namespace detail -class smt_error : public std::runtime_error { public: using std::runtime_error::runtime_error; }; -class sort_error : public smt_error { public: using smt_error::smt_error; }; -class width_mismatch_error : public smt_error { public: using smt_error::smt_error; }; -class context_mismatch_error : public smt_error { public: using smt_error::smt_error; }; -class protocol_error : public smt_error { public: using smt_error::smt_error; }; +class bv_error : public std::runtime_error { public: using std::runtime_error::runtime_error; }; +class sort_error : public bv_error { public: using bv_error::bv_error; }; +class width_mismatch_error : public bv_error { public: using bv_error::bv_error; }; +class context_mismatch_error : public bv_error { public: using bv_error::bv_error; }; +class protocol_error : public bv_error { public: using bv_error::bv_error; }; enum class Sort { BV, Bool }; enum class Status : uint8_t { Simplified = detail::status::OK, Sat = detail::status::SAT, Unsat = detail::status::UNSAT, Unknown = detail::status::UNKNOWN, Error = detail::status::ERROR }; @@ -567,9 +567,9 @@ class Term { std::shared_ptr context_state() const { return state_; } Sort sort() const { return detail::is_bool_ref(ref_) ? Sort::Bool : Sort::BV; } Op op() const { require(); return static_cast(state_->b.nodes.at(id()).tag); } - std::string name() const { auto n = node(); if (n.tag != detail::tag::BV_VAR && n.tag != detail::tag::BOOL_VAR) throw smt_error("term is not a variable"); return blob_string(state_->b, n.payload); } - bool bool_value() const { auto n = node(); if (n.tag == detail::tag::BOOL_TRUE) return true; if (n.tag == detail::tag::BOOL_FALSE) return false; throw smt_error("term is not a Bool constant"); } - uint64_t value() const { auto n = node(); if (n.tag != detail::tag::BV_CONST) throw smt_error("term is not a BV constant"); if (n.width > 64) throw smt_error("wide constant does not fit in uint64_t"); return n.width == 64 ? n.payload : (n.payload & ((uint64_t(1) << n.width) - 1)); } + std::string name() const { auto n = node(); if (n.tag != detail::tag::BV_VAR && n.tag != detail::tag::BOOL_VAR) throw bv_error("term is not a variable"); return blob_string(state_->b, n.payload); } + bool bool_value() const { auto n = node(); if (n.tag == detail::tag::BOOL_TRUE) return true; if (n.tag == detail::tag::BOOL_FALSE) return false; throw bv_error("term is not a Bool constant"); } + uint64_t value() const { auto n = node(); if (n.tag != detail::tag::BV_CONST) throw bv_error("term is not a BV constant"); if (n.width > 64) throw bv_error("wide constant does not fit in uint64_t"); return n.width == 64 ? n.payload : (n.payload & ((uint64_t(1) << n.width) - 1)); } uint32_t width() const { auto n = node(); if (op_is_bool(n.tag)) throw sort_error("Bool term has no BV width"); return n.width; } std::vector children() const { auto n = node(); std::vector out; for (uint32_t i = 0; i < n.arity; ++i) out.push_back(Term(state_, state_->b.children[n.children + i])); return out; } std::vector params() const { auto n = node(); if (n.tag == detail::tag::BV_EXTRACT) return {n.aux_hi, n.aux_lo}; if (n.tag == detail::tag::BV_ZEXT || n.tag == detail::tag::BV_SEXT || n.tag == detail::tag::BV_SELECT) return {n.aux_hi}; return {}; } @@ -720,4 +720,4 @@ class Client { OptimizationResult optimization_response(const detail::ResponsePayload& raw, const detail::RequestState& req) { OptimizationResult r; r.request_id=raw.request_id; r.status=Status(raw.status); r.flags=raw.flags; if(raw.status==detail::status::ERROR || raw.status==detail::status::UNKNOWN){ r.message=std::string(raw.payload.begin(), raw.payload.end()); return r; } if(raw.status==detail::status::UNSAT) return r; if(raw.status!=detail::status::SAT) throw protocol_error("unexpected optimization status"); if((raw.flags & detail::response_flags::HAS_VALUE)==0) throw protocol_error("optimization SAT response missing value"); auto block=detail::parse_optimization_payload(raw.payload, (raw.flags & detail::response_flags::HAS_MODEL) != 0); r.optimum=block.optimum; r.has_value=true; if(block.has_model){ r.model=model_from_entries(block.model, req); r.has_model=true; } return r; } }; -} // namespace smt_wire +} // namespace bv_wire diff --git a/cpp/tests/example.cpp b/cpp/tests/example.cpp index e7eac0d..35c873a 100644 --- a/cpp/tests/example.cpp +++ b/cpp/tests/example.cpp @@ -1,4 +1,4 @@ -#include +#include #include #include @@ -7,22 +7,22 @@ #include #include -std::string status_name(smt_wire::Status status) { +std::string status_name(bv_wire::Status status) { switch (status) { - case smt_wire::Status::Simplified: return "Status::Simplified"; - case smt_wire::Status::Sat: return "Status::Sat"; - case smt_wire::Status::Unsat: return "Status::Unsat"; - case smt_wire::Status::Unknown: return "Status::Unknown"; - case smt_wire::Status::Error: return "Status::Error"; + case bv_wire::Status::Simplified: return "Status::Simplified"; + case bv_wire::Status::Sat: return "Status::Sat"; + case bv_wire::Status::Unsat: return "Status::Unsat"; + case bv_wire::Status::Unknown: return "Status::Unknown"; + case bv_wire::Status::Error: return "Status::Error"; } return "Status::"; } -std::string to_rpn(const smt_wire::Term& term) { +std::string to_rpn(const bv_wire::Term& term) { switch (term.op()) { - case smt_wire::Op::BV_VAR: + case bv_wire::Op::BV_VAR: return term.name(); - case smt_wire::Op::BV_CONST: + case bv_wire::Op::BV_CONST: return std::to_string(term.value()) + ":" + std::to_string(term.width()); default: break; @@ -32,7 +32,7 @@ std::string to_rpn(const smt_wire::Term& term) { for (const auto& child : term.children()) { parts.push_back(to_rpn(child)); } - parts.push_back(smt_wire::op_symbol(static_cast(term.op()))); + parts.push_back(bv_wire::op_symbol(static_cast(term.op()))); std::ostringstream out; for (size_t i = 0; i < parts.size(); ++i) { @@ -43,7 +43,7 @@ std::string to_rpn(const smt_wire::Term& term) { } int main() { - smt_wire::Context ctx; + bv_wire::Context ctx; std::cout << "Context#" << ctx.id() << "\n"; auto x = ctx.bv_var("x", 32); @@ -66,12 +66,12 @@ int main() { std::cout << "RPN: " << to_rpn(mba.as_term()) << "\n"; // Start the server first: - // cargo run -p smt-server -- 127.0.0.1:9123 - // Or set SMT_SERVER_ADDRESS=: to choose a different default. - smt_wire::Client client; + // cargo run -p bv-server -- 127.0.0.1:9123 + // Or set BV_SERVER_ADDRESS=: to choose a different default. + bv_wire::Client client; auto resp = client.solve(ctx); std::cout << status_name(resp.status) << "\n"; - if (resp.status == smt_wire::Status::Sat && resp.has_model) { + if (resp.status == bv_wire::Status::Sat && resp.has_model) { auto items = resp.model.items(); std::sort(items.begin(), items.end(), [](const auto& a, const auto& b) { return a.first.name() < b.first.name(); diff --git a/cpp/tests/smoke.cpp b/cpp/tests/smoke.cpp index bcda83e..800e242 100644 --- a/cpp/tests/smoke.cpp +++ b/cpp/tests/smoke.cpp @@ -1,4 +1,4 @@ -#include +#include #include #include #include @@ -6,7 +6,7 @@ #include int main() { - smt_wire::Context ctx; + bv_wire::Context ctx; auto x = ctx.bv_var("x", 8); assert(ctx.bv_var("x", 8) == x.as_term()); bool bad_symbol_threw = false; @@ -22,47 +22,47 @@ int main() { ctx.assert_(ctx.bv_eq(x, 1u)); assert(ctx.to_smt2().find("(check-sat)") != std::string::npos); - smt_wire::Context bools; + bv_wire::Context bools; auto p = bools.bool_var("p"); assert(bools.bool_var("p") == p.as_term()); auto rotated = ctx.bv_rotate_left(x, 3); - assert(rotated.sort() == smt_wire::Sort::BV); + assert(rotated.sort() == bv_wire::Sort::BV); std::vector raw_wide(9, 0xff); - smt_wire::Context masked; + bv_wire::Context masked; auto wide = masked.bv_const_wide(raw_wide, 65); assert(wide.width() == 65); - auto parsed_address = smt_wire::parse_server_address("example.com:1234"); + auto parsed_address = bv_wire::parse_server_address("example.com:1234"); assert(parsed_address.host == "example.com"); assert(parsed_address.port == 1234); - parsed_address = smt_wire::parse_server_address("[::1]:9123"); + parsed_address = bv_wire::parse_server_address("[::1]:9123"); assert(parsed_address.host == "::1"); assert(parsed_address.port == 9123); - assert((smt_wire::ScalarValue{0, {1}}).to_u64() == 1); - assert((smt_wire::ScalarValue{0, {1}}).to_i64() == 1); - assert((smt_wire::ScalarValue{8, {0xff}}).to_u64() == 255); - assert((smt_wire::ScalarValue{8, {0xff}}).to_i64() == -1); - assert((smt_wire::ScalarValue{8, {0x80}}).to_i64() == -128); - assert((smt_wire::ScalarValue{12, {0xff, 0x0f}}).to_u64() == 4095); - assert((smt_wire::ScalarValue{12, {0xff, 0x0f}}).to_i64() == -1); - assert((smt_wire::ScalarValue{12, {0x00, 0x08}}).to_i64() == -2048); - assert((smt_wire::ScalarValue{12, {0xff, 0x07}}).to_i64() == 2047); - assert((smt_wire::ScalarValue{64, {0, 0, 0, 0, 0, 0, 0, 0x80}}).to_i64() == std::numeric_limits::min()); + assert((bv_wire::ScalarValue{0, {1}}).to_u64() == 1); + assert((bv_wire::ScalarValue{0, {1}}).to_i64() == 1); + assert((bv_wire::ScalarValue{8, {0xff}}).to_u64() == 255); + assert((bv_wire::ScalarValue{8, {0xff}}).to_i64() == -1); + assert((bv_wire::ScalarValue{8, {0x80}}).to_i64() == -128); + assert((bv_wire::ScalarValue{12, {0xff, 0x0f}}).to_u64() == 4095); + assert((bv_wire::ScalarValue{12, {0xff, 0x0f}}).to_i64() == -1); + assert((bv_wire::ScalarValue{12, {0x00, 0x08}}).to_i64() == -2048); + assert((bv_wire::ScalarValue{12, {0xff, 0x07}}).to_i64() == 2047); + assert((bv_wire::ScalarValue{64, {0, 0, 0, 0, 0, 0, 0, 0x80}}).to_i64() == std::numeric_limits::min()); - assert((smt_wire::ScalarValue{65, std::vector(9, 0)}).to_u64() == 0); - assert((smt_wire::ScalarValue{65, std::vector(9, 0)}).to_i64() == 0); - assert((smt_wire::ScalarValue{65, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01}}).to_i64() == -1); + assert((bv_wire::ScalarValue{65, std::vector(9, 0)}).to_u64() == 0); + assert((bv_wire::ScalarValue{65, std::vector(9, 0)}).to_i64() == 0); + assert((bv_wire::ScalarValue{65, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01}}).to_i64() == -1); bool scalar_threw = false; - try { (void)(smt_wire::ScalarValue{65, {0, 0, 0, 0, 0, 0, 0, 0, 1}}).to_u64(); } catch (const std::overflow_error&) { scalar_threw = true; } + try { (void)(bv_wire::ScalarValue{65, {0, 0, 0, 0, 0, 0, 0, 0, 1}}).to_u64(); } catch (const std::overflow_error&) { scalar_threw = true; } assert(scalar_threw); scalar_threw = false; - try { (void)(smt_wire::ScalarValue{65, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0}}).to_i64(); } catch (const std::overflow_error&) { scalar_threw = true; } + try { (void)(bv_wire::ScalarValue{65, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0}}).to_i64(); } catch (const std::overflow_error&) { scalar_threw = true; } assert(scalar_threw); scalar_threw = false; - try { (void)(smt_wire::ScalarValue{9, {0, 2}}).to_u64(); } catch (const std::invalid_argument&) { scalar_threw = true; } + try { (void)(bv_wire::ScalarValue{9, {0, 2}}).to_u64(); } catch (const std::invalid_argument&) { scalar_threw = true; } assert(scalar_threw); bool threw = false; diff --git a/crates/smt-server/Cargo.toml b/crates/bv-server/Cargo.toml similarity index 71% rename from crates/smt-server/Cargo.toml rename to crates/bv-server/Cargo.toml index ad9b377..b3e0d31 100644 --- a/crates/smt-server/Cargo.toml +++ b/crates/bv-server/Cargo.toml @@ -1,16 +1,16 @@ [package] -name = "smt-server" +name = "bv-server" version.workspace = true edition.workspace = true -description = "Reference SMT wire-format server and backends" +description = "Reference bv-wire server and backends" license.workspace = true [dependencies] binbit.workspace = true qfbvsmtrs = { workspace = true, features = ["wire"] } rumba-core.workspace = true -smt-qfbv-smtlib.workspace = true -smt-wire.workspace = true +bv-smtlib.workspace = true +bv-wire.workspace = true blake3.workspace = true rusqlite.workspace = true z3.workspace = true diff --git a/crates/smt-server/src/backend.rs b/crates/bv-server/src/backend.rs similarity index 96% rename from crates/smt-server/src/backend.rs rename to crates/bv-server/src/backend.rs index 21db076..207c423 100644 --- a/crates/smt-server/src/backend.rs +++ b/crates/bv-server/src/backend.rs @@ -4,7 +4,7 @@ use std::sync::{ Arc, }; -use smt_wire::raw::{ +use bv_wire::raw::{ expr::validate_node_ref, request_flags, BinaryRequest, Command, ModelBlock, OptimizationValueBlock, SimplifyBlock, Sort, UnsatCoreBlock, WireError, }; @@ -103,7 +103,7 @@ impl QueryResult { status_matches_command && self.validate_artifacts_for(request).is_ok() } - pub fn validate_artifacts_for(&self, request: &BinaryRequest) -> smt_wire::Result<()> { + pub fn validate_artifacts_for(&self, request: &BinaryRequest) -> bv_wire::Result<()> { match request.envelope.command { Command::Solve => self.validate_solve_artifacts(request), Command::Simplify => self.validate_simplify_artifacts(request), @@ -111,7 +111,7 @@ impl QueryResult { } } - fn validate_solve_artifacts(&self, request: &BinaryRequest) -> smt_wire::Result<()> { + fn validate_solve_artifacts(&self, request: &BinaryRequest) -> bv_wire::Result<()> { let want_model = (request.envelope.flags & request_flags::WANT_MODEL) != 0; let want_core = (request.envelope.flags & request_flags::WANT_CORE) != 0; match self.status { @@ -133,7 +133,7 @@ impl QueryResult { } } - fn validate_simplify_artifacts(&self, request: &BinaryRequest) -> smt_wire::Result<()> { + fn validate_simplify_artifacts(&self, request: &BinaryRequest) -> bv_wire::Result<()> { match self.status { QueryStatus::Simplified => { let simplify = self.simplify.as_ref().ok_or_else(|| { @@ -149,7 +149,7 @@ impl QueryResult { } } - fn validate_optimization_artifacts(&self, request: &BinaryRequest) -> smt_wire::Result<()> { + fn validate_optimization_artifacts(&self, request: &BinaryRequest) -> bv_wire::Result<()> { match self.status { QueryStatus::Sat => { let optimization = self.optimization.as_ref().ok_or_else(|| { @@ -174,12 +174,12 @@ impl QueryResult { } } -fn validate_model(request: &BinaryRequest, model: &ModelBlock) -> smt_wire::Result<()> { +fn validate_model(request: &BinaryRequest, model: &ModelBlock) -> bv_wire::Result<()> { let expr = request.expression_view()?; model.validate_against_expr(&expr) } -fn validate_unsat_core(request: &BinaryRequest, core: &UnsatCoreBlock) -> smt_wire::Result<()> { +fn validate_unsat_core(request: &BinaryRequest, core: &UnsatCoreBlock) -> bv_wire::Result<()> { let expr = request.expression_view()?; let mut allowed = HashSet::with_capacity(request.named_assertion_refs.len()); for name_ref in &request.named_assertion_refs { @@ -206,7 +206,7 @@ fn validate_unsat_core(request: &BinaryRequest, core: &UnsatCoreBlock) -> smt_wi fn validate_simplify_result( request: &BinaryRequest, simplify: &SimplifyBlock, -) -> smt_wire::Result<()> { +) -> bv_wire::Result<()> { simplify.validate()?; let request_target = request .target_ref() @@ -241,7 +241,7 @@ fn validate_simplify_result( fn validate_optimization( request: &BinaryRequest, optimization: &OptimizationValueBlock, -) -> smt_wire::Result<()> { +) -> bv_wire::Result<()> { optimization.optimum.validate()?; let expr = request.expression_view()?; let target = request @@ -324,13 +324,13 @@ pub trait Backend: Send + Sync { false } - fn handle(&self, request: &smt_wire::raw::BinaryRequest) -> smt_wire::Result; + fn handle(&self, request: &bv_wire::raw::BinaryRequest) -> bv_wire::Result; fn handle_with_context( &self, - request: &smt_wire::raw::BinaryRequest, + request: &bv_wire::raw::BinaryRequest, context: &SolveContext, - ) -> smt_wire::Result { + ) -> bv_wire::Result { if context.is_cancelled() { Ok(QueryResult::unknown( "backend request cancelled before start", diff --git a/crates/smt-server/src/binbit_backend.rs b/crates/bv-server/src/binbit_backend.rs similarity index 94% rename from crates/smt-server/src/binbit_backend.rs rename to crates/bv-server/src/binbit_backend.rs index b5e23a6..815b9f7 100644 --- a/crates/smt-server/src/binbit_backend.rs +++ b/crates/bv-server/src/binbit_backend.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use std::time::{Duration, Instant}; use binbit::{BoolTerm, BvTerm, SmtResult, SmtSolver}; -use smt_wire::raw::{ +use bv_wire::raw::{ request_flags, tag, BinaryRequest, BlobRef, Command, ModelBlock, ModelEntry, NodeRef, OptimizationValueBlock, ScalarValue, SimplifyBlock, Sort, UnsatCoreBlock, WireError, }; @@ -17,7 +17,7 @@ impl Backend for BinbitBackend { "binbit" } - fn handle(&self, request: &BinaryRequest) -> smt_wire::Result { + fn handle(&self, request: &BinaryRequest) -> bv_wire::Result { match request.envelope.command { Command::Simplify => Ok(QueryResult::simplified(SimplifyBlock { expression: request.expression.clone(), @@ -34,7 +34,7 @@ impl Backend for BinbitBackend { &self, request: &BinaryRequest, context: &SolveContext, - ) -> smt_wire::Result { + ) -> bv_wire::Result { if context.is_cancelled() { return Ok(QueryResult::unknown( "binbit request cancelled before start", @@ -65,7 +65,7 @@ struct BinbitTranslation { } impl BinbitTranslation { - fn bv(&self, reference: NodeRef) -> smt_wire::Result { + fn bv(&self, reference: NodeRef) -> bv_wire::Result { if !reference.is_bv() { return Err(WireError::invalid( "binbit translation", @@ -78,7 +78,7 @@ impl BinbitTranslation { .ok_or_else(|| WireError::invalid("binbit translation", "missing BV term")) } - fn bool(&self, reference: NodeRef) -> smt_wire::Result { + fn bool(&self, reference: NodeRef) -> bv_wire::Result { if !reference.is_bool() { return Err(WireError::invalid( "binbit translation", @@ -92,14 +92,14 @@ impl BinbitTranslation { } } -fn translate(request: &BinaryRequest) -> smt_wire::Result { +fn translate(request: &BinaryRequest) -> bv_wire::Result { translate_with_context(request, None) } fn translate_with_context( request: &BinaryRequest, context: Option<&SolveContext>, -) -> smt_wire::Result { +) -> bv_wire::Result { let expr = request.expression_view()?; let mut out = BinbitTranslation { solver: SmtSolver::new(), @@ -348,21 +348,21 @@ fn translate_with_context( Ok(out) } -fn solve(request: &BinaryRequest) -> smt_wire::Result { +fn solve(request: &BinaryRequest) -> bv_wire::Result { solve_inner(request, None) } fn solve_with_context( request: &BinaryRequest, context: &SolveContext, -) -> smt_wire::Result { +) -> bv_wire::Result { solve_inner(request, Some(context)) } fn solve_inner( request: &BinaryRequest, context: Option<&SolveContext>, -) -> smt_wire::Result { +) -> bv_wire::Result { let expr = request.expression_view()?; let mut translation = match translate_with_context(request, context) { Ok(translation) => translation, @@ -390,7 +390,7 @@ fn solve_inner( .assumption_roots .iter() .map(|root| translation.bool(*root)) - .collect::>>()?; + .collect::>>()?; let result = solve_binbit( &mut translation.solver, @@ -469,7 +469,7 @@ fn solve_binbit( } } -fn optimize(request: &BinaryRequest) -> smt_wire::Result { +fn optimize(request: &BinaryRequest) -> bv_wire::Result { if request.envelope.budget_ms != 0 { return Ok(QueryResult::unknown( "binbit optimization currently supports unbounded searches only", @@ -511,28 +511,28 @@ fn optimize(request: &BinaryRequest) -> smt_wire::Result { } fn child_bv( - expr: &smt_wire::raw::ExprView<'_>, + expr: &bv_wire::raw::ExprView<'_>, translation: &BinbitTranslation, - node: &smt_wire::raw::RawNode, + node: &bv_wire::raw::RawNode, offset: u32, -) -> smt_wire::Result { +) -> bv_wire::Result { translation.bv(expr.child_ref(node.children + offset)?) } fn child_bool( - expr: &smt_wire::raw::ExprView<'_>, + expr: &bv_wire::raw::ExprView<'_>, translation: &BinbitTranslation, - node: &smt_wire::raw::RawNode, + node: &bv_wire::raw::RawNode, offset: u32, -) -> smt_wire::Result { +) -> bv_wire::Result { translation.bool(expr.child_ref(node.children + offset)?) } fn child_bv2( - expr: &smt_wire::raw::ExprView<'_>, + expr: &bv_wire::raw::ExprView<'_>, translation: &BinbitTranslation, - node: &smt_wire::raw::RawNode, -) -> smt_wire::Result<(BvTerm, BvTerm)> { + node: &bv_wire::raw::RawNode, +) -> bv_wire::Result<(BvTerm, BvTerm)> { Ok(( child_bv(expr, translation, node, 0)?, child_bv(expr, translation, node, 1)?, @@ -540,10 +540,10 @@ fn child_bv2( } fn child_bool2( - expr: &smt_wire::raw::ExprView<'_>, + expr: &bv_wire::raw::ExprView<'_>, translation: &BinbitTranslation, - node: &smt_wire::raw::RawNode, -) -> smt_wire::Result<(BoolTerm, BoolTerm)> { + node: &bv_wire::raw::RawNode, +) -> bv_wire::Result<(BoolTerm, BoolTerm)> { Ok(( child_bool(expr, translation, node, 0)?, child_bool(expr, translation, node, 1)?, @@ -552,10 +552,10 @@ fn child_bool2( fn binbit_bv_const( solver: &mut SmtSolver, - expr: &smt_wire::raw::ExprView<'_>, + expr: &bv_wire::raw::ExprView<'_>, width: u32, payload: u64, -) -> smt_wire::Result { +) -> bv_wire::Result { if width <= 128 { let value = if width <= 64 { payload as u128 @@ -570,7 +570,7 @@ fn binbit_bv_const( } } -fn build_model(translation: &mut BinbitTranslation) -> smt_wire::Result { +fn build_model(translation: &mut BinbitTranslation) -> bv_wire::Result { let mut entries = Vec::with_capacity(translation.variables.len()); for variable in translation.variables.clone() { let value = match variable.sort { @@ -608,7 +608,7 @@ fn bytes_to_limbs(bytes: &[u8], width: u32) -> Vec { limbs } -fn scalar_from_limbs(width: u32, limbs: &[u64]) -> smt_wire::Result { +fn scalar_from_limbs(width: u32, limbs: &[u64]) -> bv_wire::Result { let mut bytes = vec![0u8; (width as usize).div_ceil(8)]; for (index, byte) in bytes.iter_mut().enumerate() { *byte = ((limbs[index / 8] >> ((index % 8) * 8)) & 0xff) as u8; diff --git a/crates/smt-server/src/cache.rs b/crates/bv-server/src/cache.rs similarity index 97% rename from crates/smt-server/src/cache.rs rename to crates/bv-server/src/cache.rs index 12125f2..c1b113a 100644 --- a/crates/smt-server/src/cache.rs +++ b/crates/bv-server/src/cache.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; use std::sync::Mutex; -use smt_wire::raw::{constants::RESPONSE_MAGIC, request::is_binary_request_payload}; +use bv_wire::raw::{constants::RESPONSE_MAGIC, request::is_binary_request_payload}; pub const DEFAULT_MAX_CACHE_ENTRIES: usize = 4096; pub const DEFAULT_MAX_CACHE_KEY_BYTES: usize = 1024 * 1024; diff --git a/crates/smt-server/src/command_router.rs b/crates/bv-server/src/command_router.rs similarity index 89% rename from crates/smt-server/src/command_router.rs rename to crates/bv-server/src/command_router.rs index 9f44d69..23d5492 100644 --- a/crates/smt-server/src/command_router.rs +++ b/crates/bv-server/src/command_router.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use smt_wire::raw::{BinaryRequest, Command}; +use bv_wire::raw::{BinaryRequest, Command}; use crate::backend::{Backend, QueryResult, SolveContext}; @@ -27,7 +27,7 @@ impl Backend for CommandRouterBackend { self.solver.supports_qfbvsmtrs_text_fallback() } - fn handle(&self, request: &BinaryRequest) -> smt_wire::Result { + fn handle(&self, request: &BinaryRequest) -> bv_wire::Result { match request.envelope.command { Command::Simplify => self.simplifier.handle(request), Command::Solve | Command::Minimize | Command::Maximize => self.solver.handle(request), @@ -38,7 +38,7 @@ impl Backend for CommandRouterBackend { &self, request: &BinaryRequest, context: &SolveContext, - ) -> smt_wire::Result { + ) -> bv_wire::Result { match request.envelope.command { Command::Simplify => self.simplifier.handle_with_context(request, context), Command::Solve | Command::Minimize | Command::Maximize => { diff --git a/crates/smt-server/src/lib.rs b/crates/bv-server/src/lib.rs similarity index 95% rename from crates/smt-server/src/lib.rs rename to crates/bv-server/src/lib.rs index 87410ce..4a67d64 100644 --- a/crates/smt-server/src/lib.rs +++ b/crates/bv-server/src/lib.rs @@ -1,4 +1,4 @@ -//! Reference server-side implementation for the SMT wire protocol. +//! Reference server-side implementation for the bv-wire protocol. //! //! The crate provides a small TCP server, binary request handling, native Z3 //! and binbit solver backends, backend racing, request/response caching, and a diff --git a/crates/smt-server/src/main.rs b/crates/bv-server/src/main.rs similarity index 87% rename from crates/smt-server/src/main.rs rename to crates/bv-server/src/main.rs index 3df090b..9c0551f 100644 --- a/crates/smt-server/src/main.rs +++ b/crates/bv-server/src/main.rs @@ -1,7 +1,7 @@ use std::path::PathBuf; use std::sync::Arc; -use smt_server::{ +use bv_server::{ default_legacy_recording_tree, migrate_recording_tree, recording_db_path, serve_tcp, BinbitBackend, CommandRouterBackend, QfbvsmtrsBackend, RacingBackend, RumbaBackend, ServerConfig, Z3Backend, @@ -25,7 +25,7 @@ fn main() -> std::io::Result<()> { ); let backend = Arc::new(CommandRouterBackend::new(Arc::new(RumbaBackend), solver)); eprintln!( - "smt-server listening on {addr} with rumba simplifier + racing solver (z3 crate + binbit + qfbvsmtrs)" + "bv-server listening on {addr} with rumba simplifier + racing solver (z3 crate + binbit + qfbvsmtrs)" ); serve_tcp(addr, ServerConfig::new(backend)) } @@ -39,7 +39,7 @@ fn migrate_recordings_command(mut args: impl Iterator) -> std::io if args.next().is_some() { return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, - "usage: smt-server migrate-recordings [SOURCE_DIR] [DB_PATH]", + "usage: bv-server migrate-recordings [SOURCE_DIR] [DB_PATH]", )); } @@ -58,7 +58,7 @@ fn migrate_recordings_command(mut args: impl Iterator) -> std::io let report = migrate_recording_tree(&source, &db)?; eprintln!( - "smt-server: migrated {} recording(s), {} duplicate(s), {} skipped ({} scanned)", + "bv-server: migrated {} recording(s), {} duplicate(s), {} skipped ({} scanned)", report.inserted, report.duplicates, report.skipped(), diff --git a/crates/smt-server/src/pool.rs b/crates/bv-server/src/pool.rs similarity index 92% rename from crates/smt-server/src/pool.rs rename to crates/bv-server/src/pool.rs index 625734a..3aac727 100644 --- a/crates/smt-server/src/pool.rs +++ b/crates/bv-server/src/pool.rs @@ -2,7 +2,7 @@ use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use std::sync::Arc; -use smt_wire::raw::BinaryRequest; +use bv_wire::raw::BinaryRequest; use crate::backend::{Backend, QueryResult}; @@ -40,7 +40,7 @@ impl Backend for PooledBackend { "pooled" } - fn handle(&self, request: &BinaryRequest) -> smt_wire::Result { + fn handle(&self, request: &BinaryRequest) -> bv_wire::Result { let Some(index) = self.route_index(request) else { return Ok(QueryResult::unknown("backend pool is empty")); }; diff --git a/crates/smt-server/src/protocol.rs b/crates/bv-server/src/protocol.rs similarity index 92% rename from crates/smt-server/src/protocol.rs rename to crates/bv-server/src/protocol.rs index 2120c5f..88251a1 100644 --- a/crates/smt-server/src/protocol.rs +++ b/crates/bv-server/src/protocol.rs @@ -1,6 +1,6 @@ use std::collections::HashSet; -use smt_wire::raw::{ +use bv_wire::raw::{ expr::validate_node_ref, request::is_binary_request_payload, response_flags, BinaryRequest, BinaryResponse, Command, ModelBlock, OptimizationValueBlock, SimplifyBlock, Sort, Status, UnsatCoreBlock, WireError, @@ -13,7 +13,7 @@ use crate::backend::{Backend, QueryResult, QueryStatus}; pub fn handle_binary_frame( frame_payload: &[u8], backend: &dyn Backend, -) -> smt_wire::Result { +) -> bv_wire::Result { if !is_binary_request_payload(frame_payload) { return BinaryResponse::error(0, "frame payload is not a binary SMTQ request"); } @@ -26,7 +26,7 @@ pub fn handle_binary_frame( pub fn handle_binary_request( request: &BinaryRequest, backend: &dyn Backend, -) -> smt_wire::Result { +) -> bv_wire::Result { match backend.handle(request) { Ok(result) => response_from_query_result(request, result), Err(err) => BinaryResponse::error(request.envelope.request_id, &err.to_string()), @@ -36,7 +36,7 @@ pub fn handle_binary_request( pub fn response_from_query_result( request: &BinaryRequest, result: QueryResult, -) -> smt_wire::Result { +) -> bv_wire::Result { match request.envelope.command { Command::Solve => solve_response(request, result), Command::Simplify => simplify_response(request, result), @@ -44,13 +44,10 @@ pub fn response_from_query_result( } } -fn solve_response( - request: &BinaryRequest, - result: QueryResult, -) -> smt_wire::Result { +fn solve_response(request: &BinaryRequest, result: QueryResult) -> bv_wire::Result { let request_id = request.envelope.request_id; - let want_model = (request.envelope.flags & smt_wire::raw::request_flags::WANT_MODEL) != 0; - let want_core = (request.envelope.flags & smt_wire::raw::request_flags::WANT_CORE) != 0; + let want_model = (request.envelope.flags & bv_wire::raw::request_flags::WANT_MODEL) != 0; + let want_core = (request.envelope.flags & bv_wire::raw::request_flags::WANT_CORE) != 0; match result.status { QueryStatus::Sat => { if want_model { @@ -103,7 +100,7 @@ fn solve_response( } } -fn unknown_response(request_id: u32, message: Option) -> smt_wire::Result { +fn unknown_response(request_id: u32, message: Option) -> bv_wire::Result { if let Some(message) = message.filter(|message| !message.is_empty()) { BinaryResponse::new( request_id, @@ -119,7 +116,7 @@ fn unknown_response(request_id: u32, message: Option) -> smt_wire::Resul fn simplify_response( request: &BinaryRequest, result: QueryResult, -) -> smt_wire::Result { +) -> bv_wire::Result { let request_id = request.envelope.request_id; match result.status { QueryStatus::Simplified => { @@ -149,12 +146,12 @@ fn simplify_response( } } -fn validate_model(request: &BinaryRequest, model: &ModelBlock) -> smt_wire::Result<()> { +fn validate_model(request: &BinaryRequest, model: &ModelBlock) -> bv_wire::Result<()> { let expr = request.expression_view()?; model.validate_against_expr(&expr) } -fn validate_unsat_core(request: &BinaryRequest, core: &UnsatCoreBlock) -> smt_wire::Result<()> { +fn validate_unsat_core(request: &BinaryRequest, core: &UnsatCoreBlock) -> bv_wire::Result<()> { let expr = request.expression_view()?; let mut allowed = HashSet::with_capacity(request.named_assertion_refs.len()); for name_ref in &request.named_assertion_refs { @@ -178,7 +175,7 @@ fn validate_unsat_core(request: &BinaryRequest, core: &UnsatCoreBlock) -> smt_wi Ok(()) } -fn validate_simplify(request: &BinaryRequest, simplify: &SimplifyBlock) -> smt_wire::Result<()> { +fn validate_simplify(request: &BinaryRequest, simplify: &SimplifyBlock) -> bv_wire::Result<()> { simplify.validate()?; let request_target = request .target_ref() @@ -213,7 +210,7 @@ fn validate_simplify(request: &BinaryRequest, simplify: &SimplifyBlock) -> smt_w fn validate_optimization( request: &BinaryRequest, optimization: &OptimizationValueBlock, -) -> smt_wire::Result<()> { +) -> bv_wire::Result<()> { optimization.optimum.validate()?; let expr = request.expression_view()?; let target = request @@ -238,7 +235,7 @@ fn validate_optimization( fn optimize_response( request: &BinaryRequest, result: QueryResult, -) -> smt_wire::Result { +) -> bv_wire::Result { let request_id = request.envelope.request_id; match result.status { QueryStatus::Sat => { @@ -246,7 +243,7 @@ fn optimize_response( WireError::invalid("optimization response", "SAT result without optimum block") })?; let want_model = - (request.envelope.flags & smt_wire::raw::request_flags::WANT_MODEL) != 0; + (request.envelope.flags & bv_wire::raw::request_flags::WANT_MODEL) != 0; if want_model && optimization.model.is_none() { return BinaryResponse::error( request_id, diff --git a/crates/smt-server/src/qfbvsmtrs_backend.rs b/crates/bv-server/src/qfbvsmtrs_backend.rs similarity index 90% rename from crates/smt-server/src/qfbvsmtrs_backend.rs rename to crates/bv-server/src/qfbvsmtrs_backend.rs index 3fd1641..2fdc754 100644 --- a/crates/smt-server/src/qfbvsmtrs_backend.rs +++ b/crates/bv-server/src/qfbvsmtrs_backend.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; use std::time::Duration; -use smt_wire::raw::{ +use bv_wire::raw::{ tag, BinaryRequest, BlobRef, Command, ModelBlock, ModelEntry, OptimizationValueBlock, ScalarValue, SimplifyBlock, Sort, UnsatCoreBlock, WireError, }; @@ -20,7 +20,7 @@ impl Backend for QfbvsmtrsBackend { true } - fn handle(&self, request: &BinaryRequest) -> smt_wire::Result { + fn handle(&self, request: &BinaryRequest) -> bv_wire::Result { match request.envelope.command { Command::Simplify => Ok(QueryResult::simplified(SimplifyBlock { expression: request.expression.clone(), @@ -36,7 +36,7 @@ impl Backend for QfbvsmtrsBackend { &self, request: &BinaryRequest, context: &SolveContext, - ) -> smt_wire::Result { + ) -> bv_wire::Result { if context.is_cancelled() { return Ok(QueryResult::unknown( "qfbvsmtrs request cancelled before start", @@ -51,7 +51,7 @@ impl Backend for QfbvsmtrsBackend { } } -fn scalar_to_wire(value: &qfbvsmtrs::ScalarValue) -> smt_wire::Result { +fn scalar_to_wire(value: &qfbvsmtrs::ScalarValue) -> bv_wire::Result { match value { qfbvsmtrs::ScalarValue::Bool(value) => Ok(ScalarValue::bool(*value)), qfbvsmtrs::ScalarValue::Bv { width, bytes } => ScalarValue::bv(*width, bytes.clone()), @@ -61,7 +61,7 @@ fn scalar_to_wire(value: &qfbvsmtrs::ScalarValue) -> smt_wire::Result smt_wire::Result { +) -> bv_wire::Result { let mut values = HashMap::<(String, Sort, u32), ScalarValue>::new(); for entry in &model.entries { let value = scalar_to_wire(&entry.value)?; @@ -96,7 +96,7 @@ fn model_to_wire_for_request( let key = (name.to_owned(), sort, width); if let Some(value) = values.get(&key).cloned() { entries.push(ModelEntry { - node_ref: smt_wire::raw::NodeRef::new(sort, index)?, + node_ref: bv_wire::raw::NodeRef::new(sort, index)?, value, }); } @@ -112,7 +112,7 @@ fn value_sort(value: &ScalarValue) -> Sort { } } -fn solve(request: &BinaryRequest) -> smt_wire::Result { +fn solve(request: &BinaryRequest) -> bv_wire::Result { let request = request.clone(); let worker = spawn_worker(request, None)?; join_worker(worker) @@ -121,7 +121,7 @@ fn solve(request: &BinaryRequest) -> smt_wire::Result { fn solve_with_context( request: &BinaryRequest, context: &SolveContext, -) -> smt_wire::Result { +) -> bv_wire::Result { let cancellation = qfbvsmtrs::CancellationToken::new(); let worker = spawn_worker(request.clone(), Some(cancellation.clone()))?; loop { @@ -138,17 +138,17 @@ fn solve_with_context( fn spawn_worker( request: BinaryRequest, cancellation: Option, -) -> smt_wire::Result>> { +) -> bv_wire::Result>> { std::thread::Builder::new() .name("qfbvsmtrs-backend".to_owned()) .stack_size(qfbvsmtrs::DEFAULT_WORKER_STACK_BYTES) .spawn(move || solve_on_worker(&request, cancellation)) - .map_err(|err| smt_wire::WireError::invalid("qfbvsmtrs worker", err.to_string())) + .map_err(|err| bv_wire::WireError::invalid("qfbvsmtrs worker", err.to_string())) } fn join_worker( - worker: std::thread::JoinHandle>, -) -> smt_wire::Result { + worker: std::thread::JoinHandle>, +) -> bv_wire::Result { match worker.join() { Ok(result) => result, Err(_) => Ok(QueryResult::unknown("qfbvsmtrs worker panicked")), @@ -158,7 +158,7 @@ fn join_worker( fn solve_on_worker( request: &BinaryRequest, cancellation: Option, -) -> smt_wire::Result { +) -> bv_wire::Result { let query = match qfbvsmtrs::query_from_wire(request) { Ok(query) => query, Err(err) => return Ok(QueryResult::unknown(format!("qfbvsmtrs: {err}"))), diff --git a/crates/smt-server/src/racing.rs b/crates/bv-server/src/racing.rs similarity index 97% rename from crates/smt-server/src/racing.rs rename to crates/bv-server/src/racing.rs index d677613..9184003 100644 --- a/crates/smt-server/src/racing.rs +++ b/crates/bv-server/src/racing.rs @@ -2,7 +2,7 @@ use std::sync::{mpsc, Arc}; use std::thread; use std::time::{Duration, Instant}; -use smt_wire::raw::BinaryRequest; +use bv_wire::raw::BinaryRequest; use crate::backend::{Backend, CancellationToken, QueryResult, SolveContext}; @@ -44,7 +44,7 @@ impl Backend for RacingBackend { .any(|backend| backend.supports_qfbvsmtrs_text_fallback()) } - fn handle(&self, request: &BinaryRequest) -> smt_wire::Result { + fn handle(&self, request: &BinaryRequest) -> bv_wire::Result { if self.backends.is_empty() { return Ok(QueryResult::unknown("no backends configured")); } diff --git a/crates/smt-server/src/recording.rs b/crates/bv-server/src/recording.rs similarity index 94% rename from crates/smt-server/src/recording.rs rename to crates/bv-server/src/recording.rs index aae1eb4..58a522b 100644 --- a/crates/smt-server/src/recording.rs +++ b/crates/bv-server/src/recording.rs @@ -4,13 +4,13 @@ use std::sync::{Mutex, OnceLock}; use rusqlite::{params, Connection}; -use smt_wire::raw::constants::RESPONSE_MAGIC; +use bv_wire::raw::constants::RESPONSE_MAGIC; use crate::cache::cache_key_for_payload; /// Path to the SQLite recording database. Empty disables recording. -/// Defaults to `~/.smt-server/recordings.db`. -pub const RECORD_DB_ENV: &str = "SMT_SERVER_RECORD_DB"; +/// Defaults to `~/.bv-server/recordings.db`. +pub const RECORD_DB_ENV: &str = "BV_SERVER_RECORD_DB"; /// Maximum pairs committed in a single migration transaction. const MAX_BATCH: usize = 256; @@ -78,7 +78,7 @@ pub fn record_binary_pair(request: &[u8], response: &[u8]) { }; let pair = Pair::canonical(request, response); if let Err(err) = recorder.insert(&pair) { - eprintln!("smt-server: failed to persist recording: {err}"); + eprintln!("bv-server: failed to persist recording: {err}"); } } @@ -94,7 +94,7 @@ fn init_recorder() -> Option { conn: Mutex::new(conn), }), Err(err) => { - eprintln!("smt-server: failed to open recording db {path:?}: {err}"); + eprintln!("bv-server: failed to open recording db {path:?}: {err}"); None } } @@ -151,11 +151,11 @@ pub fn recording_db_path() -> Option { } pub fn default_recording_db_path() -> Option { - home_dir().map(|home| home.join(".smt-server").join("recordings.db")) + home_dir().map(|home| home.join(".bv-server").join("recordings.db")) } pub fn default_legacy_recording_tree() -> Option { - home_dir().map(|home| home.join(".smt-server").join("requests")) + home_dir().map(|home| home.join(".bv-server").join("requests")) } fn home_dir() -> Option { @@ -181,8 +181,8 @@ fn canonical_response(response: &[u8]) -> Vec { /// Import the default legacy file-tree corpus into the configured database. /// -/// The source is `~/.smt-server/requests`. The destination is resolved from -/// `SMT_SERVER_RECORD_DB` or defaults to `~/.smt-server/recordings.db`. +/// The source is `~/.bv-server/requests`. The destination is resolved from +/// `BV_SERVER_RECORD_DB` or defaults to `~/.bv-server/recordings.db`. pub fn migrate_default() -> io::Result { let source = default_legacy_recording_tree().ok_or_else(|| { io::Error::new( @@ -313,8 +313,8 @@ fn collect_req_files(dir: &Path, out: &mut Vec) -> io::Result<()> { #[cfg(test)] mod tests { use super::*; + use bv_wire::raw::{BinaryResponse, ExprBuilder}; use rusqlite::OptionalExtension; - use smt_wire::raw::{BinaryResponse, ExprBuilder}; use std::time::{SystemTime, UNIX_EPOCH}; fn temp_root(prefix: &str) -> PathBuf { @@ -337,7 +337,7 @@ mod tests { #[test] fn inserts_canonical_pair_deduped_by_request_id() -> Result<(), Box> { - let root = temp_root("smt-server-recording-test"); + let root = temp_root("bv-server-recording-test"); let db = root.join("recordings.db"); let conn = open_db(&db)?; @@ -369,7 +369,7 @@ mod tests { #[test] fn migrates_legacy_tree_into_db() -> Result<(), Box> { - let root = temp_root("smt-server-migrate-test"); + let root = temp_root("bv-server-migrate-test"); let source = root.join("requests"); let db = root.join("recordings.db"); @@ -410,7 +410,7 @@ mod tests { #[test] fn migration_reports_skipped_legacy_files() -> Result<(), Box> { - let root = temp_root("smt-server-migrate-skip-test"); + let root = temp_root("bv-server-migrate-skip-test"); let source = root.join("requests"); let db = root.join("recordings.db"); std::fs::create_dir_all(&source)?; diff --git a/crates/smt-server/src/rumba_backend.rs b/crates/bv-server/src/rumba_backend.rs similarity index 92% rename from crates/smt-server/src/rumba_backend.rs rename to crates/bv-server/src/rumba_backend.rs index 800a62c..aa554b9 100644 --- a/crates/smt-server/src/rumba_backend.rs +++ b/crates/bv-server/src/rumba_backend.rs @@ -1,12 +1,12 @@ use std::collections::HashMap; +use bv_wire::raw::{ + tag, BinaryRequest, Command, ExprBuilder, ExprView, NodeRef, RawNode, SimplifyBlock, WireError, +}; use rumba_core::{ expr::{Expr as RumbaExpr, VarId}, simplify::simplify_mba, }; -use smt_wire::raw::{ - tag, BinaryRequest, Command, ExprBuilder, ExprView, NodeRef, RawNode, SimplifyBlock, WireError, -}; use crate::backend::{Backend, QueryResult, SolveContext}; @@ -20,7 +20,7 @@ impl Backend for RumbaBackend { "rumba" } - fn handle(&self, request: &BinaryRequest) -> smt_wire::Result { + fn handle(&self, request: &BinaryRequest) -> bv_wire::Result { match request.envelope.command { Command::Simplify => simplify_request(request).map(QueryResult::simplified), Command::Solve | Command::Minimize | Command::Maximize => { @@ -33,7 +33,7 @@ impl Backend for RumbaBackend { &self, request: &BinaryRequest, context: &SolveContext, - ) -> smt_wire::Result { + ) -> bv_wire::Result { if context.is_cancelled() { return Ok(QueryResult::unknown("rumba request cancelled before start")); } @@ -50,7 +50,7 @@ impl Backend for RumbaBackend { /// walks the DAG, copies the structural skeleton verbatim, and hands every maximal /// MBA island to Rumba -- abstracting any non-MBA / wrong-width child of an island as /// a fresh opaque Rumba variable that maps back to the recursively-simplified subtree. -fn simplify_request(request: &BinaryRequest) -> smt_wire::Result { +fn simplify_request(request: &BinaryRequest) -> bv_wire::Result { let target = request .target_ref() .ok_or_else(|| WireError::invalid("simplify request", "missing target_node"))?; @@ -105,7 +105,7 @@ impl<'a> IslandSimplifier<'a> { } } - fn process(&mut self, reference: NodeRef) -> smt_wire::Result { + fn process(&mut self, reference: NodeRef) -> bv_wire::Result { if let Some(&cached) = self.memo.get(&reference) { return Ok(cached); } @@ -114,7 +114,7 @@ impl<'a> IslandSimplifier<'a> { Ok(result) } - fn process_uncached(&mut self, reference: NodeRef) -> smt_wire::Result { + fn process_uncached(&mut self, reference: NodeRef) -> bv_wire::Result { let node = self.view.node(reference.index())?; if reference.is_bv() && is_mba_op(node.tag) && (1..=MAX_RUMBA_WIDTH).contains(&node.width) { if let Some(simplified) = self.try_island(reference, &node)? { @@ -131,7 +131,7 @@ impl<'a> IslandSimplifier<'a> { &mut self, reference: NodeRef, node: &RawNode, - ) -> smt_wire::Result> { + ) -> bv_wire::Result> { let width = node.width; let bits = width as u8; let mut conversion = IslandConversion::new(self.view, width); @@ -154,7 +154,7 @@ impl<'a> IslandSimplifier<'a> { expr: &RumbaExpr, width: u32, vars: &[IslandVar], - ) -> smt_wire::Result { + ) -> bv_wire::Result { let mask = mask_for_width(width); match expr { RumbaExpr::Var(var) => match vars.get(var.0) { @@ -199,8 +199,8 @@ impl<'a> IslandSimplifier<'a> { width: u32, vars: &[IslandVar], identity: u64, - op: fn(&mut ExprBuilder, NodeRef, NodeRef) -> smt_wire::Result, - ) -> smt_wire::Result { + op: fn(&mut ExprBuilder, NodeRef, NodeRef) -> bv_wire::Result, + ) -> bv_wire::Result { if children.is_empty() { return self.builder.bv_const(identity, width); } @@ -215,7 +215,7 @@ impl<'a> IslandSimplifier<'a> { Ok(acc) } - fn src_child(&self, node: &RawNode, offset: u32) -> smt_wire::Result { + fn src_child(&self, node: &RawNode, offset: u32) -> bv_wire::Result { let index = node .children .checked_add(offset) @@ -223,13 +223,13 @@ impl<'a> IslandSimplifier<'a> { self.view.child_ref(index) } - fn processed_child(&mut self, node: &RawNode, offset: u32) -> smt_wire::Result { + fn processed_child(&mut self, node: &RawNode, offset: u32) -> bv_wire::Result { let child = self.src_child(node, offset)?; self.process(child) } /// Rebuild a node verbatim with its children recursively simplified. - fn copy_node(&mut self, _reference: NodeRef, node: &RawNode) -> smt_wire::Result { + fn copy_node(&mut self, _reference: NodeRef, node: &RawNode) -> bv_wire::Result { let width = node.width; match node.tag { tag::BV_VAR => { @@ -337,8 +337,8 @@ impl<'a> IslandSimplifier<'a> { fn copy_nary( &mut self, node: &RawNode, - op: fn(&mut ExprBuilder, NodeRef, NodeRef) -> smt_wire::Result, - ) -> smt_wire::Result { + op: fn(&mut ExprBuilder, NodeRef, NodeRef) -> bv_wire::Result, + ) -> bv_wire::Result { let arity = node.arity as u32; if arity == 0 { return Err(WireError::invalid( @@ -357,14 +357,14 @@ impl<'a> IslandSimplifier<'a> { fn copy_binary( &mut self, node: &RawNode, - op: fn(&mut ExprBuilder, NodeRef, NodeRef) -> smt_wire::Result, - ) -> smt_wire::Result { + op: fn(&mut ExprBuilder, NodeRef, NodeRef) -> bv_wire::Result, + ) -> bv_wire::Result { let a = self.processed_child(node, 0)?; let b = self.processed_child(node, 1)?; op(&mut self.builder, a, b) } - fn copy_select(&mut self, node: &RawNode) -> smt_wire::Result { + fn copy_select(&mut self, node: &RawNode) -> bv_wire::Result { let pairs = node.aux_hi as u32; let mut selectors = Vec::with_capacity(pairs as usize); let mut values = Vec::with_capacity(pairs as usize); @@ -412,7 +412,7 @@ impl<'a> IslandConversion<'a> { /// variable limit to each linear sub-MBA after reduction, and reports it as /// `SolveError::TooManyVariables`. A cap applied here would count island leaves /// before reduction, which is a different (and not conservative) number. - fn convert(&mut self, reference: NodeRef) -> smt_wire::Result { + fn convert(&mut self, reference: NodeRef) -> bv_wire::Result { if !reference.is_bv() { return Ok(self.boundary(reference)); } @@ -440,18 +440,18 @@ impl<'a> IslandConversion<'a> { }) } - fn convert_child(&mut self, node: &RawNode, offset: u32) -> smt_wire::Result { + fn convert_child(&mut self, node: &RawNode, offset: u32) -> bv_wire::Result { let child = self.src_child(node, offset)?; self.convert(child) } - fn children2(&mut self, node: &RawNode) -> smt_wire::Result<(RumbaExpr, RumbaExpr)> { + fn children2(&mut self, node: &RawNode) -> bv_wire::Result<(RumbaExpr, RumbaExpr)> { let a = self.convert_child(node, 0)?; let b = self.convert_child(node, 1)?; Ok((a, b)) } - fn nary(&mut self, root: NodeRef, tag: u8) -> smt_wire::Result> { + fn nary(&mut self, root: NodeRef, tag: u8) -> bv_wire::Result> { let mut stack = vec![root]; let mut terms = Vec::new(); while let Some(reference) = stack.pop() { @@ -467,7 +467,7 @@ impl<'a> IslandConversion<'a> { Ok(terms) } - fn named(&mut self, reference: NodeRef, node: &RawNode) -> smt_wire::Result { + fn named(&mut self, reference: NodeRef, node: &RawNode) -> bv_wire::Result { if let Some(&id) = self.by_ref.get(&reference) { return Ok(RumbaExpr::Var(VarId(id))); } @@ -496,7 +496,7 @@ impl<'a> IslandConversion<'a> { RumbaExpr::Var(VarId(id)) } - fn src_child(&self, node: &RawNode, offset: u32) -> smt_wire::Result { + fn src_child(&self, node: &RawNode, offset: u32) -> bv_wire::Result { let index = node .children .checked_add(offset) diff --git a/crates/smt-server/src/server.rs b/crates/bv-server/src/server.rs similarity index 96% rename from crates/smt-server/src/server.rs rename to crates/bv-server/src/server.rs index 17b6dd3..14f7e7d 100644 --- a/crates/smt-server/src/server.rs +++ b/crates/bv-server/src/server.rs @@ -7,7 +7,7 @@ use std::sync::{ use std::thread; use std::time::Duration; -use smt_wire::raw::{le, BinaryResponse, Status}; +use bv_wire::raw::{le, BinaryResponse, Status}; use crate::backend::Backend; use crate::cache::{ @@ -143,7 +143,7 @@ pub fn dispatch_payload_with_cache( cache: Option<&ResponseCache>, ) -> Vec { if let Some(cache) = cache.filter(|cache| { - smt_wire::raw::request::is_binary_request_payload(payload) && cache.accepts_payload(payload) + bv_wire::raw::request::is_binary_request_payload(payload) && cache.accepts_payload(payload) }) { let key = cache_key_for_payload(payload); let request_id = binary_request_id(payload); @@ -173,7 +173,7 @@ fn is_cacheable_binary_response(response: &[u8]) -> bool { } pub fn dispatch_payload(payload: &[u8], backend: &dyn Backend) -> Vec { - if smt_wire::raw::request::is_binary_request_payload(payload) { + if bv_wire::raw::request::is_binary_request_payload(payload) { let response = match handle_binary_frame(payload, backend).and_then(|response| response.encode()) { Ok(bytes) => bytes, diff --git a/crates/smt-server/src/smt2.rs b/crates/bv-server/src/smt2.rs similarity index 96% rename from crates/smt-server/src/smt2.rs rename to crates/bv-server/src/smt2.rs index c5f69ca..60d9f13 100644 --- a/crates/smt-server/src/smt2.rs +++ b/crates/bv-server/src/smt2.rs @@ -1,6 +1,6 @@ use std::collections::{HashMap, HashSet}; -use smt_wire::raw::{ +use bv_wire::raw::{ request_flags, tag, BinaryRequest, BlobRef, ExprView, NodeRef, Sort, WireError, }; @@ -18,7 +18,7 @@ pub struct Smt2Script { pub variables: Vec, } -pub fn request_to_smt2(request: &BinaryRequest) -> smt_wire::Result { +pub fn request_to_smt2(request: &BinaryRequest) -> bv_wire::Result { let expr = request.expression_view()?; let variables = collect_variables(&expr)?; let mut out = String::new(); @@ -102,7 +102,7 @@ pub fn request_to_smt2(request: &BinaryRequest) -> smt_wire::Result }) } -pub fn collect_variables(expr: &ExprView<'_>) -> smt_wire::Result> { +pub fn collect_variables(expr: &ExprView<'_>) -> bv_wire::Result> { let mut vars = Vec::new(); for index in 0..expr.node_count() { let node = expr.node(index)?; @@ -178,7 +178,7 @@ fn term_ref( expr: &ExprView<'_>, reference: NodeRef, cache: &mut [Option], -) -> smt_wire::Result { +) -> bv_wire::Result { let term = term_node(expr, reference.index(), cache)?; Ok(term) } @@ -187,7 +187,7 @@ fn term_node( expr: &ExprView<'_>, index: u32, cache: &mut [Option], -) -> smt_wire::Result { +) -> bv_wire::Result { if let Some(term) = &cache[index as usize] { return Ok(term.clone()); } @@ -308,7 +308,7 @@ fn child_term( expr: &ExprView<'_>, child_index: u32, cache: &mut [Option], -) -> smt_wire::Result { +) -> bv_wire::Result { term_ref(expr, expr.child_ref(child_index)?, cache) } @@ -317,7 +317,7 @@ fn unary( child_index: u32, cache: &mut [Option], op: &str, -) -> smt_wire::Result { +) -> bv_wire::Result { let child = child_term(expr, child_index, cache)?; Ok(format!("({op} {child})")) } @@ -327,13 +327,13 @@ fn binary( child_index: u32, cache: &mut [Option], op: &str, -) -> smt_wire::Result { +) -> bv_wire::Result { let a = child_term(expr, child_index, cache)?; let b = child_term(expr, child_index + 1, cache)?; Ok(format!("({op} {a} {b})")) } -fn const_to_smt2(expr: &ExprView<'_>, width: u32, payload: u64) -> smt_wire::Result { +fn const_to_smt2(expr: &ExprView<'_>, width: u32, payload: u64) -> bv_wire::Result { let mut bytes = if width <= 64 { let mut raw = payload.to_le_bytes().to_vec(); raw.truncate((width as usize).div_ceil(8)); @@ -363,7 +363,7 @@ fn signed_add_overflow( expr: &ExprView<'_>, child_index: u32, cache: &mut [Option], -) -> smt_wire::Result { +) -> bv_wire::Result { let a_ref = expr.child_ref(child_index)?; let width = expr.node(a_ref.index())?.width; let a = child_term(expr, child_index, cache)?; @@ -384,7 +384,7 @@ fn signed_sub_overflow( expr: &ExprView<'_>, child_index: u32, cache: &mut [Option], -) -> smt_wire::Result { +) -> bv_wire::Result { let a_ref = expr.child_ref(child_index)?; let width = expr.node(a_ref.index())?.width; let a = child_term(expr, child_index, cache)?; @@ -405,7 +405,7 @@ fn signed_mul_overflow( expr: &ExprView<'_>, child_index: u32, cache: &mut [Option], -) -> smt_wire::Result { +) -> bv_wire::Result { let a_ref = expr.child_ref(child_index)?; let width = expr.node(a_ref.index())?.width; let a = child_term(expr, child_index, cache)?; diff --git a/crates/smt-server/src/smtlib.rs b/crates/bv-server/src/smtlib.rs similarity index 87% rename from crates/smt-server/src/smtlib.rs rename to crates/bv-server/src/smtlib.rs index f8ff878..31cb026 100644 --- a/crates/smt-server/src/smtlib.rs +++ b/crates/bv-server/src/smtlib.rs @@ -1,8 +1,8 @@ use std::collections::HashMap; use std::time::Duration; -use smt_qfbv_smtlib::{lower_script, FrontendError, FrontendOptions, QfBvSink}; -use smt_wire::raw::{ +use bv_smtlib::{lower_script, FrontendError, FrontendOptions, QfBvSink}; +use bv_wire::raw::{ BinaryRequest, BinaryResponse, ExprBuilder, ModelBlock, NodeRef, ScalarValue, UnsatCoreBlock, WireError, }; @@ -40,7 +40,7 @@ impl<'a> WireSmtLibSink<'a> { macro_rules! forward_wire_unary { ($name:ident) => { - fn $name(&mut self, x: NodeRef) -> smt_wire::Result { + fn $name(&mut self, x: NodeRef) -> bv_wire::Result { self.builder.$name(x) } }; @@ -48,7 +48,7 @@ macro_rules! forward_wire_unary { macro_rules! forward_wire_binary { ($name:ident) => { - fn $name(&mut self, a: NodeRef, b: NodeRef) -> smt_wire::Result { + fn $name(&mut self, a: NodeRef, b: NodeRef) -> bv_wire::Result { self.builder.$name(a, b) } }; @@ -58,7 +58,7 @@ impl QfBvSink for WireSmtLibSink<'_> { type Node = NodeRef; type Error = WireError; - fn bool_const(&mut self, value: bool) -> smt_wire::Result { + fn bool_const(&mut self, value: bool) -> bv_wire::Result { if value { self.builder.bool_true() } else { @@ -66,15 +66,15 @@ impl QfBvSink for WireSmtLibSink<'_> { } } - fn bv_const(&mut self, bytes_le: &[u8], width: u32) -> smt_wire::Result { + fn bv_const(&mut self, bytes_le: &[u8], width: u32) -> bv_wire::Result { self.builder.bv_const_wide(bytes_le, width) } - fn bool_var(&mut self, name: &str) -> smt_wire::Result { + fn bool_var(&mut self, name: &str) -> bv_wire::Result { self.builder.bool_var(name) } - fn bv_var(&mut self, name: &str, width: u32) -> smt_wire::Result { + fn bv_var(&mut self, name: &str, width: u32) -> bv_wire::Result { self.builder.bv_var(name, width) } @@ -85,7 +85,7 @@ impl QfBvSink for WireSmtLibSink<'_> { forward_wire_binary!(bool_eq); forward_wire_binary!(bool_xor); - fn bool_ite(&mut self, c: NodeRef, t: NodeRef, e: NodeRef) -> smt_wire::Result { + fn bool_ite(&mut self, c: NodeRef, t: NodeRef, e: NodeRef) -> bv_wire::Result { self.builder.bool_ite(c, t, e) } @@ -106,21 +106,21 @@ impl QfBvSink for WireSmtLibSink<'_> { forward_wire_binary!(bv_lshr); forward_wire_binary!(bv_ashr); - fn bv_extract(&mut self, x: NodeRef, hi: u32, lo: u32) -> smt_wire::Result { + fn bv_extract(&mut self, x: NodeRef, hi: u32, lo: u32) -> bv_wire::Result { self.builder.bv_extract(x, hi, lo) } forward_wire_binary!(bv_concat); - fn bv_zext(&mut self, x: NodeRef, amount: u32) -> smt_wire::Result { + fn bv_zext(&mut self, x: NodeRef, amount: u32) -> bv_wire::Result { self.builder.bv_zext(x, checked_u16(amount, "zero_extend")?) } - fn bv_sext(&mut self, x: NodeRef, amount: u32) -> smt_wire::Result { + fn bv_sext(&mut self, x: NodeRef, amount: u32) -> bv_wire::Result { self.builder.bv_sext(x, checked_u16(amount, "sign_extend")?) } - fn bv_repeat(&mut self, x: NodeRef, count: u32) -> smt_wire::Result { + fn bv_repeat(&mut self, x: NodeRef, count: u32) -> bv_wire::Result { if count == 0 { return Err(WireError::invalid( "repeat", @@ -134,15 +134,15 @@ impl QfBvSink for WireSmtLibSink<'_> { Ok(out) } - fn bv_rotate_left(&mut self, x: NodeRef, amount: u32) -> smt_wire::Result { + fn bv_rotate_left(&mut self, x: NodeRef, amount: u32) -> bv_wire::Result { self.builder.bv_rotate_left(x, u64::from(amount)) } - fn bv_rotate_right(&mut self, x: NodeRef, amount: u32) -> smt_wire::Result { + fn bv_rotate_right(&mut self, x: NodeRef, amount: u32) -> bv_wire::Result { self.builder.bv_rotate_right(x, u64::from(amount)) } - fn bv_ite(&mut self, c: NodeRef, t: NodeRef, e: NodeRef) -> smt_wire::Result { + fn bv_ite(&mut self, c: NodeRef, t: NodeRef, e: NodeRef) -> bv_wire::Result { self.builder.bv_ite(c, t, e) } @@ -160,7 +160,7 @@ impl QfBvSink for WireSmtLibSink<'_> { forward_wire_unary!(neg_ovf); forward_wire_binary!(sdiv_ovf); - fn assert(&mut self, root: NodeRef, name: Option<&str>) -> smt_wire::Result<()> { + fn assert(&mut self, root: NodeRef, name: Option<&str>) -> bv_wire::Result<()> { if let Some(name) = name { self.builder.assert_named(name, root) } else { @@ -168,26 +168,26 @@ impl QfBvSink for WireSmtLibSink<'_> { } } - fn assume(&mut self, root: NodeRef) -> smt_wire::Result<()> { + fn assume(&mut self, root: NodeRef) -> bv_wire::Result<()> { self.builder.assume(root) } - fn push(&mut self) -> smt_wire::Result<()> { + fn push(&mut self) -> bv_wire::Result<()> { self.builder.push(); Ok(()) } - fn pop(&mut self) -> smt_wire::Result<()> { + fn pop(&mut self) -> bv_wire::Result<()> { self.builder.pop() } } -fn checked_u16(value: u32, context: &'static str) -> smt_wire::Result { +fn checked_u16(value: u32, context: &'static str) -> bv_wire::Result { u16::try_from(value) .map_err(|_| WireError::invalid(context, format!("amount {value} exceeds u16::MAX"))) } -pub fn parse_smtlib_script(script: &str) -> smt_wire::Result { +pub fn parse_smtlib_script(script: &str) -> bv_wire::Result { let mut builder = ExprBuilder::new(); let lowered = { let mut sink = WireSmtLibSink::new(&mut builder); @@ -203,14 +203,14 @@ pub fn parse_smtlib_script(script: &str) -> smt_wire::Result { }) } -pub fn handle_text_frame(frame_payload: &[u8], backend: &dyn Backend) -> smt_wire::Result> { +pub fn handle_text_frame(frame_payload: &[u8], backend: &dyn Backend) -> bv_wire::Result> { handle_text_frame_inner(frame_payload, backend, false) } pub fn handle_text_frame_recording( frame_payload: &[u8], backend: &dyn Backend, -) -> smt_wire::Result> { +) -> bv_wire::Result> { handle_text_frame_inner(frame_payload, backend, true) } @@ -218,7 +218,7 @@ fn handle_text_frame_inner( frame_payload: &[u8], backend: &dyn Backend, record: bool, -) -> smt_wire::Result> { +) -> bv_wire::Result> { let script = std::str::from_utf8(frame_payload) .map_err(|_| WireError::invalid("SMT-LIB frontend", "text request is not UTF-8"))?; let query = match parse_smtlib_script(script) { @@ -318,13 +318,13 @@ fn handle_qfbvsmtrs_text_fallback_on_worker(script: &str, frontend_error: &str) } fn qfbvsmtrs_text_config() -> std::result::Result { - let budget_ms = match std::env::var("SMT_SERVER_TEXT_QFBVSMTRS_BUDGET_MS") { + let budget_ms = match std::env::var("BV_SERVER_TEXT_QFBVSMTRS_BUDGET_MS") { Ok(value) => value.parse::().map_err(|_| { - "invalid SMT_SERVER_TEXT_QFBVSMTRS_BUDGET_MS: expected integer milliseconds".to_owned() + "invalid BV_SERVER_TEXT_QFBVSMTRS_BUDGET_MS: expected integer milliseconds".to_owned() })?, Err(std::env::VarError::NotPresent) => 30_000, Err(std::env::VarError::NotUnicode(_)) => { - return Err("invalid SMT_SERVER_TEXT_QFBVSMTRS_BUDGET_MS: not UTF-8".to_owned()) + return Err("invalid BV_SERVER_TEXT_QFBVSMTRS_BUDGET_MS: not UTF-8".to_owned()) } }; let budget = (budget_ms != 0).then(|| Duration::from_millis(budget_ms)); @@ -386,13 +386,13 @@ fn format_unknown(message: Option<&str>) -> String { out } -fn format_model(request: &BinaryRequest, model: &ModelBlock) -> smt_wire::Result { +fn format_model(request: &BinaryRequest, model: &ModelBlock) -> bv_wire::Result { let expr = request.expression_view()?; let mut out = "(model\n".to_owned(); for entry in &model.entries { let node = expr.node(entry.node_ref.index())?; let name = expr.blob_str( - smt_wire::raw::BlobRef::from_payload(node.payload), + bv_wire::raw::BlobRef::from_payload(node.payload), "model variable", )?; out.push_str(" (define-fun "); @@ -422,13 +422,13 @@ fn format_get_values( request: &BinaryRequest, model: &ModelBlock, names: &[String], -) -> smt_wire::Result { +) -> bv_wire::Result { let expr = request.expression_view()?; let mut values = HashMap::new(); for entry in &model.entries { let node = expr.node(entry.node_ref.index())?; let name = expr.blob_str( - smt_wire::raw::BlobRef::from_payload(node.payload), + bv_wire::raw::BlobRef::from_payload(node.payload), "model variable", )?; values.insert(name.to_owned(), scalar_to_smt_value(&entry.value)); @@ -504,7 +504,7 @@ mod tests { use super::*; #[test] - fn wire_sink_adapter_builds_basic_request() -> smt_wire::Result<()> { + fn wire_sink_adapter_builds_basic_request() -> bv_wire::Result<()> { let mut builder = ExprBuilder::new(); { let mut sink = WireSmtLibSink::new(&mut builder); diff --git a/crates/smt-server/src/z3_backend.rs b/crates/bv-server/src/z3_backend.rs similarity index 94% rename from crates/smt-server/src/z3_backend.rs rename to crates/bv-server/src/z3_backend.rs index 0db890b..53ba8b5 100644 --- a/crates/smt-server/src/z3_backend.rs +++ b/crates/bv-server/src/z3_backend.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; -use smt_wire::raw::{ +use bv_wire::raw::{ request_flags, tag, BinaryRequest, BlobRef, Command, ModelBlock, ModelEntry, NodeRef, OptimizationValueBlock, ScalarValue, SimplifyBlock, Sort, UnsatCoreBlock, WireError, }; @@ -21,7 +21,7 @@ impl Backend for Z3Backend { "z3" } - fn handle(&self, request: &BinaryRequest) -> smt_wire::Result { + fn handle(&self, request: &BinaryRequest) -> bv_wire::Result { handle_inner(request, None) } @@ -29,7 +29,7 @@ impl Backend for Z3Backend { &self, request: &BinaryRequest, context: &SolveContext, - ) -> smt_wire::Result { + ) -> bv_wire::Result { if context.is_cancelled() { return Ok(QueryResult::unknown("z3 request cancelled before start")); } @@ -40,7 +40,7 @@ impl Backend for Z3Backend { fn handle_inner( request: &BinaryRequest, context: Option<&SolveContext>, -) -> smt_wire::Result { +) -> bv_wire::Result { match request.envelope.command { Command::Simplify => Ok(QueryResult::simplified(SimplifyBlock { expression: request.expression.clone(), @@ -112,7 +112,7 @@ struct Z3Translation { } impl Z3Translation { - fn bv(&self, reference: NodeRef) -> smt_wire::Result { + fn bv(&self, reference: NodeRef) -> bv_wire::Result { if !reference.is_bv() { return Err(WireError::invalid( "Z3 translation", @@ -125,7 +125,7 @@ impl Z3Translation { .ok_or_else(|| WireError::invalid("Z3 translation", "missing BV term")) } - fn bool(&self, reference: NodeRef) -> smt_wire::Result { + fn bool(&self, reference: NodeRef) -> bv_wire::Result { if !reference.is_bool() { return Err(WireError::invalid( "Z3 translation", @@ -139,7 +139,7 @@ impl Z3Translation { } } -fn translate(request: &BinaryRequest) -> smt_wire::Result { +fn translate(request: &BinaryRequest) -> bv_wire::Result { let expr = request.expression_view()?; let mut out = Z3Translation { bvs: vec![None; expr.node_count() as usize], @@ -373,7 +373,7 @@ fn translate(request: &BinaryRequest) -> smt_wire::Result { Ok(out) } -fn solve(request: &BinaryRequest) -> smt_wire::Result { +fn solve(request: &BinaryRequest) -> bv_wire::Result { let deadline = Z3Deadline::from_budget_ms(request.envelope.budget_ms); let expr = request.expression_view()?; let translation = translate(request)?; @@ -400,7 +400,7 @@ fn solve(request: &BinaryRequest) -> smt_wire::Result { .assumption_roots .iter() .map(|root| translation.bool(*root)) - .collect::>>()?; + .collect::>>()?; match check_assumptions_with_deadline(&solver, &assumptions, deadline)? { SatResult::Sat => { @@ -453,7 +453,7 @@ fn check_assumptions_with_deadline( solver: &Solver, assumptions: &[Bool], deadline: Z3Deadline, -) -> smt_wire::Result { +) -> bv_wire::Result { if let Some(timeout) = deadline.remaining_timeout_ms() { let mut params = Params::new(); params.set_u32("timeout", timeout); @@ -470,7 +470,7 @@ fn z3_unknown_reason(solver: &Solver) -> String { .unwrap_or_else(|| "z3 returned unknown".to_owned()) } -fn optimize(request: &BinaryRequest) -> smt_wire::Result { +fn optimize(request: &BinaryRequest) -> bv_wire::Result { let deadline = Z3Deadline::from_budget_ms(request.envelope.budget_ms); let translation = translate(request)?; let solver = Solver::new(); @@ -482,7 +482,7 @@ fn optimize(request: &BinaryRequest) -> smt_wire::Result { .assumption_roots .iter() .map(|root| translation.bool(*root)) - .collect::>>()?; + .collect::>>()?; match check_assumptions_with_deadline(&solver, &fixed, deadline)? { SatResult::Sat => {} @@ -559,28 +559,28 @@ fn optimize(request: &BinaryRequest) -> smt_wire::Result { } fn child_bv( - expr: &smt_wire::raw::ExprView<'_>, + expr: &bv_wire::raw::ExprView<'_>, translation: &Z3Translation, - node: &smt_wire::raw::RawNode, + node: &bv_wire::raw::RawNode, offset: u32, -) -> smt_wire::Result { +) -> bv_wire::Result { translation.bv(expr.child_ref(node.children + offset)?) } fn child_bool( - expr: &smt_wire::raw::ExprView<'_>, + expr: &bv_wire::raw::ExprView<'_>, translation: &Z3Translation, - node: &smt_wire::raw::RawNode, + node: &bv_wire::raw::RawNode, offset: u32, -) -> smt_wire::Result { +) -> bv_wire::Result { translation.bool(expr.child_ref(node.children + offset)?) } fn child_bv2( - expr: &smt_wire::raw::ExprView<'_>, + expr: &bv_wire::raw::ExprView<'_>, translation: &Z3Translation, - node: &smt_wire::raw::RawNode, -) -> smt_wire::Result<(BV, BV)> { + node: &bv_wire::raw::RawNode, +) -> bv_wire::Result<(BV, BV)> { Ok(( child_bv(expr, translation, node, 0)?, child_bv(expr, translation, node, 1)?, @@ -588,21 +588,17 @@ fn child_bv2( } fn child_bool2( - expr: &smt_wire::raw::ExprView<'_>, + expr: &bv_wire::raw::ExprView<'_>, translation: &Z3Translation, - node: &smt_wire::raw::RawNode, -) -> smt_wire::Result<(Bool, Bool)> { + node: &bv_wire::raw::RawNode, +) -> bv_wire::Result<(Bool, Bool)> { Ok(( child_bool(expr, translation, node, 0)?, child_bool(expr, translation, node, 1)?, )) } -fn z3_bv_const( - expr: &smt_wire::raw::ExprView<'_>, - width: u32, - payload: u64, -) -> smt_wire::Result { +fn z3_bv_const(expr: &bv_wire::raw::ExprView<'_>, width: u32, payload: u64) -> bv_wire::Result { if width <= 64 { return Ok(BV::from_u64(payload, width)); } @@ -615,7 +611,7 @@ fn z3_bv_const( BV::from_bits(&bits).ok_or_else(|| WireError::invalid("BV_CONST", "failed to build Z3 BV")) } -fn build_model(translation: &Z3Translation, model: &Model) -> smt_wire::Result { +fn build_model(translation: &Z3Translation, model: &Model) -> bv_wire::Result { let mut entries = Vec::with_capacity(translation.variables.len()); for variable in &translation.variables { let value = match variable.sort { @@ -653,7 +649,7 @@ fn build_core(solver: &Solver, trackers: &[(String, Bool)]) -> UnsatCoreBlock { UnsatCoreBlock { names } } -fn bv_model_value(width: u32, value: &BV) -> smt_wire::Result { +fn bv_model_value(width: u32, value: &BV) -> bv_wire::Result { if width <= 64 { if let Some(value) = value.as_u64() { let mut bytes = value.to_le_bytes().to_vec(); @@ -664,7 +660,7 @@ fn bv_model_value(width: u32, value: &BV) -> smt_wire::Result { parse_bv_literal(&value.to_string(), width) } -fn parse_bv_literal(text: &str, width: u32) -> smt_wire::Result { +fn parse_bv_literal(text: &str, width: u32) -> bv_wire::Result { let mut bytes = vec![0u8; (width as usize).div_ceil(8)]; if let Some(bits) = text.strip_prefix("#b") { for (offset, ch) in bits.chars().rev().enumerate() { @@ -694,14 +690,14 @@ fn parse_bv_literal(text: &str, width: u32) -> smt_wire::Result { ScalarValue::bv(width, bytes) } -fn decimal_to_le_bytes(text: &str, len: usize) -> smt_wire::Result> { +fn decimal_to_le_bytes(text: &str, len: usize) -> bv_wire::Result> { let mut digits = text .bytes() .map(|byte| match byte { b'0'..=b'9' => Ok(byte - b'0'), _ => Err(WireError::invalid("Z3 model", "bad decimal BV literal")), }) - .collect::>>()?; + .collect::>>()?; let mut out = Vec::with_capacity(len); while !digits.is_empty() && out.len() < len { let mut carry = 0u16; diff --git a/crates/smt-server/tests/phase2_server.rs b/crates/bv-server/tests/phase2_server.rs similarity index 98% rename from crates/smt-server/tests/phase2_server.rs rename to crates/bv-server/tests/phase2_server.rs index d33c1b3..7e71d63 100644 --- a/crates/smt-server/tests/phase2_server.rs +++ b/crates/bv-server/tests/phase2_server.rs @@ -4,11 +4,11 @@ use std::sync::Arc; use std::thread; use std::time::Duration; -use smt_server::{ +use bv_server::{ handle_binary_frame, serve_tcp, Backend, BinbitBackend, QfbvsmtrsBackend, QueryResult, ServerConfig, Z3Backend, }; -use smt_wire::raw::{ +use bv_wire::raw::{ le, response_flags, status, tag, BinaryRequest, BinaryResponse, BlobRef, Command, ExprBuilder, ExpressionBuffer, ModelBlock, NodeRef, RawNode, Status, UnsatCoreBlock, }; @@ -64,7 +64,7 @@ fn request_with_duplicate_bv_symbol_model(request_id: u32) -> Vec { BinaryRequest::new( request_id, Command::Solve, - smt_wire::raw::request_flags::WANT_MODEL, + bv_wire::raw::request_flags::WANT_MODEL, 0, expression, vec![NodeRef::bool(3).unwrap()], @@ -327,7 +327,7 @@ impl Backend for MissingModelBackend { "missing-model-test" } - fn handle(&self, _request: &smt_wire::raw::BinaryRequest) -> smt_wire::Result { + fn handle(&self, _request: &bv_wire::raw::BinaryRequest) -> bv_wire::Result { Ok(QueryResult::sat(None)) } } @@ -339,7 +339,7 @@ impl Backend for UnknownMessageBackend { "unknown-message-test" } - fn handle(&self, _request: &smt_wire::raw::BinaryRequest) -> smt_wire::Result { + fn handle(&self, _request: &bv_wire::raw::BinaryRequest) -> bv_wire::Result { Ok(QueryResult::unknown("deadline elapsed")) } } diff --git a/crates/smt-server/tests/phase4_5_text_and_racing.rs b/crates/bv-server/tests/phase4_5_text_and_racing.rs similarity index 97% rename from crates/smt-server/tests/phase4_5_text_and_racing.rs rename to crates/bv-server/tests/phase4_5_text_and_racing.rs index a012fae..19c85a0 100644 --- a/crates/smt-server/tests/phase4_5_text_and_racing.rs +++ b/crates/bv-server/tests/phase4_5_text_and_racing.rs @@ -4,11 +4,11 @@ use std::sync::{ }; use std::time::{Duration, Instant}; -use smt_server::{ +use bv_server::{ handle_text_frame, parse_smtlib_script, request_to_smt2, Backend, BinbitBackend, CancellationToken, QfbvsmtrsBackend, QueryResult, RacingBackend, SolveContext, Z3Backend, }; -use smt_wire::raw::{BinaryRequest, ExprBuilder}; +use bv_wire::raw::{BinaryRequest, ExprBuilder}; #[test] fn smtlib_text_frontend_solves_sat_and_formats_model() { @@ -313,7 +313,7 @@ impl Backend for UnknownBackend { fn name(&self) -> &'static str { "unknown-test" } - fn handle(&self, _request: &BinaryRequest) -> smt_wire::Result { + fn handle(&self, _request: &BinaryRequest) -> bv_wire::Result { Ok(QueryResult::unknown("test unknown")) } } @@ -323,7 +323,7 @@ impl Backend for SlowUnknownBackend { fn name(&self) -> &'static str { "slow-unknown-test" } - fn handle(&self, _request: &BinaryRequest) -> smt_wire::Result { + fn handle(&self, _request: &BinaryRequest) -> bv_wire::Result { std::thread::sleep(Duration::from_millis(250)); Ok(QueryResult::unknown("slow unknown")) } @@ -334,7 +334,7 @@ impl Backend for ImmediateSatBackend { fn name(&self) -> &'static str { "immediate-sat-test" } - fn handle(&self, _request: &BinaryRequest) -> smt_wire::Result { + fn handle(&self, _request: &BinaryRequest) -> bv_wire::Result { Ok(QueryResult::sat(None)) } } @@ -346,14 +346,14 @@ impl Backend for CancellableSlowBackend { fn name(&self) -> &'static str { "cancellable-slow-test" } - fn handle(&self, _request: &BinaryRequest) -> smt_wire::Result { + fn handle(&self, _request: &BinaryRequest) -> bv_wire::Result { Ok(QueryResult::unknown("cancellable backend requires context")) } fn handle_with_context( &self, _request: &BinaryRequest, context: &SolveContext, - ) -> smt_wire::Result { + ) -> bv_wire::Result { let start = Instant::now(); while start.elapsed() < Duration::from_secs(5) { if context.is_cancelled() { diff --git a/crates/smt-server/tests/phase6_simplify_optimize.rs b/crates/bv-server/tests/phase6_simplify_optimize.rs similarity index 97% rename from crates/smt-server/tests/phase6_simplify_optimize.rs rename to crates/bv-server/tests/phase6_simplify_optimize.rs index e65393e..c9dd9fa 100644 --- a/crates/smt-server/tests/phase6_simplify_optimize.rs +++ b/crates/bv-server/tests/phase6_simplify_optimize.rs @@ -1,7 +1,7 @@ -use smt_server::{ +use bv_server::{ handle_binary_frame, Backend, BinbitBackend, QfbvsmtrsBackend, QueryResult, Z3Backend, }; -use smt_wire::raw::{ +use bv_wire::raw::{ response_flags, BinaryRequest, BinaryResponse, ExprBuilder, ModelBlock, ModelEntry, OptimizationValueBlock, ScalarValue, SimplifyBlock, Status, UnsatCoreBlock, }; @@ -172,7 +172,7 @@ impl Backend for BadModelBackend { fn name(&self) -> &'static str { "bad-model-test" } - fn handle(&self, request: &BinaryRequest) -> smt_wire::Result { + fn handle(&self, request: &BinaryRequest) -> bv_wire::Result { Ok(QueryResult::sat(Some(ModelBlock { entries: vec![ModelEntry { node_ref: request.assertion_roots[0], @@ -187,7 +187,7 @@ impl Backend for BadCoreBackend { fn name(&self) -> &'static str { "bad-core-test" } - fn handle(&self, _request: &BinaryRequest) -> smt_wire::Result { + fn handle(&self, _request: &BinaryRequest) -> bv_wire::Result { Ok(QueryResult::unsat(Some(UnsatCoreBlock { names: vec!["not_from_request".to_owned()], }))) @@ -199,7 +199,7 @@ impl Backend for BadOptimizationBackend { fn name(&self) -> &'static str { "bad-optimization-test" } - fn handle(&self, _request: &BinaryRequest) -> smt_wire::Result { + fn handle(&self, _request: &BinaryRequest) -> bv_wire::Result { Ok(QueryResult::sat_optimization(OptimizationValueBlock { optimum: ScalarValue { width: 8, diff --git a/crates/smt-server/tests/phase7_cache.rs b/crates/bv-server/tests/phase7_cache.rs similarity index 92% rename from crates/smt-server/tests/phase7_cache.rs rename to crates/bv-server/tests/phase7_cache.rs index eb92a8c..94e1701 100644 --- a/crates/smt-server/tests/phase7_cache.rs +++ b/crates/bv-server/tests/phase7_cache.rs @@ -1,8 +1,8 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; -use smt_server::{dispatch_payload_with_cache, Backend, PooledBackend, QueryResult, ResponseCache}; -use smt_wire::raw::{request_flags, BinaryRequest, BinaryResponse, ExprBuilder, ModelBlock}; +use bv_server::{dispatch_payload_with_cache, Backend, PooledBackend, QueryResult, ResponseCache}; +use bv_wire::raw::{request_flags, BinaryRequest, BinaryResponse, ExprBuilder, ModelBlock}; struct CountingBackend { count: Arc, @@ -13,7 +13,7 @@ impl Backend for CountingBackend { "counting" } - fn handle(&self, request: &BinaryRequest) -> smt_wire::Result { + fn handle(&self, request: &BinaryRequest) -> bv_wire::Result { self.count.fetch_add(1, Ordering::SeqCst); let model = ((request.envelope.flags & request_flags::WANT_MODEL) != 0) .then(|| ModelBlock { entries: vec![] }); diff --git a/crates/smt-server/tests/phase8_e2e.rs b/crates/bv-server/tests/phase8_e2e.rs similarity index 96% rename from crates/smt-server/tests/phase8_e2e.rs rename to crates/bv-server/tests/phase8_e2e.rs index 8be8714..276f0c1 100644 --- a/crates/smt-server/tests/phase8_e2e.rs +++ b/crates/bv-server/tests/phase8_e2e.rs @@ -3,11 +3,11 @@ use std::sync::Arc; use std::thread; use std::time::Duration; -use smt_server::{ +use bv_server::{ serve_tcp, BinbitBackend, CommandRouterBackend, RacingBackend, RumbaBackend, ServerConfig, Z3Backend, }; -use smt_wire::raw::{response_flags, ExprBuilder, ModelBlock, SimplifyBlock, Status, TcpClient}; +use bv_wire::raw::{response_flags, ExprBuilder, ModelBlock, SimplifyBlock, Status, TcpClient}; fn start_default_test_server() -> SocketAddr { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); diff --git a/crates/smt-server/tests/rumba_island_simplify.rs b/crates/bv-server/tests/rumba_island_simplify.rs similarity index 94% rename from crates/smt-server/tests/rumba_island_simplify.rs rename to crates/bv-server/tests/rumba_island_simplify.rs index 7e92162..0485127 100644 --- a/crates/smt-server/tests/rumba_island_simplify.rs +++ b/crates/bv-server/tests/rumba_island_simplify.rs @@ -2,8 +2,8 @@ //! (`concat`, `ite`, ...). Before island extraction the converter bailed to identity //! whenever any non-MBA node appeared anywhere in the target. -use smt_server::{handle_binary_frame, RumbaBackend}; -use smt_wire::raw::{tag, BinaryResponse, ExprBuilder, SimplifyBlock, Status}; +use bv_server::{handle_binary_frame, RumbaBackend}; +use bv_wire::raw::{tag, BinaryResponse, ExprBuilder, SimplifyBlock, Status}; /// Count occurrences of each tag in the simplified result expression. fn tag_counts(payload: &[u8]) -> Vec { @@ -17,7 +17,7 @@ fn tag_counts(payload: &[u8]) -> Vec { tags } -fn simplify(builder: &ExprBuilder, target: smt_wire::raw::NodeRef) -> Vec { +fn simplify(builder: &ExprBuilder, target: bv_wire::raw::NodeRef) -> Vec { let request = builder.build_simplify_request(1, target).unwrap(); let response = BinaryResponse::parse( &handle_binary_frame(&request, &RumbaBackend) diff --git a/crates/smt-server/tests/rumba_simplify.rs b/crates/bv-server/tests/rumba_simplify.rs similarity index 94% rename from crates/smt-server/tests/rumba_simplify.rs rename to crates/bv-server/tests/rumba_simplify.rs index 9c75e8f..cbd8899 100644 --- a/crates/smt-server/tests/rumba_simplify.rs +++ b/crates/bv-server/tests/rumba_simplify.rs @@ -1,10 +1,10 @@ use std::path::PathBuf; -use rumba_core::{expr::Expr as RumbaExpr, parser::parse_expr}; -use smt_server::{handle_binary_frame, RumbaBackend}; -use smt_wire::raw::{ +use bv_server::{handle_binary_frame, RumbaBackend}; +use bv_wire::raw::{ tag, BinaryResponse, BlobRef, ExprBuilder, ExprView, NodeRef, SimplifyBlock, Status, }; +use rumba_core::{expr::Expr as RumbaExpr, parser::parse_expr}; const WIDTH: u32 = 64; const BITS: u8 = 64; @@ -15,7 +15,7 @@ fn build_rumba_expr( builder: &mut ExprBuilder, expr: &RumbaExpr, width: u32, -) -> smt_wire::Result { +) -> bv_wire::Result { match expr { RumbaExpr::Var(var) => builder.bv_var(&format!("v{}", var.0), width), RumbaExpr::Const(c) => builder.bv_const(c & mask_for_width(width), width), @@ -55,8 +55,8 @@ fn fold_rumba_children( children: &[RumbaExpr], width: u32, identity: u64, - mut op: impl FnMut(&mut ExprBuilder, NodeRef, NodeRef) -> smt_wire::Result, -) -> smt_wire::Result { + mut op: impl FnMut(&mut ExprBuilder, NodeRef, NodeRef) -> bv_wire::Result, +) -> bv_wire::Result { let mut iter = children.iter(); let Some(first) = iter.next() else { return builder.bv_const(identity, width); @@ -104,7 +104,7 @@ struct CompiledWireExpr { } impl CompiledWireExpr { - fn compile(view: &ExprView<'_>, target: NodeRef) -> smt_wire::Result { + fn compile(view: &ExprView<'_>, target: NodeRef) -> bv_wire::Result { assert!(target.is_bv(), "dataset simplification target must be BV"); let mut nodes = Vec::with_capacity(view.node_count() as usize); for index in 0..view.node_count() { @@ -117,7 +117,7 @@ impl CompiledWireExpr { .strip_prefix('v') .and_then(|suffix| suffix.parse::().ok()) .ok_or_else(|| { - smt_wire::WireError::invalid("test variable", name.to_owned()) + bv_wire::WireError::invalid("test variable", name.to_owned()) })?; EvalNode::Var { id, mask } } @@ -161,7 +161,7 @@ impl CompiledWireExpr { mask, }, _ => { - return Err(smt_wire::WireError::invalid( + return Err(bv_wire::WireError::invalid( "test wire evaluator", format!("unsupported returned tag {}", node.tag), )) @@ -198,9 +198,9 @@ impl CompiledWireExpr { fn child_index( view: &ExprView<'_>, - node: &smt_wire::raw::RawNode, + node: &bv_wire::raw::RawNode, offset: usize, -) -> smt_wire::Result { +) -> bv_wire::Result { Ok(view.child_ref(node.children + offset as u32)?.index() as usize) } @@ -241,7 +241,7 @@ const INLINE_RUMBA_SAMPLES: &[(&str, &str)] = &[ #[test] fn rumba_csv_dataset_samples_through_binary_simplify() { - let full = std::env::var_os("SMT_SERVER_RUMBA_FULL_DATASET").is_some(); + let full = std::env::var_os("BV_SERVER_RUMBA_FULL_DATASET").is_some(); if !full { for (line_index, (mba, ground_truth)) in INLINE_RUMBA_SAMPLES.iter().enumerate() { check_rumba_dataset_row("inline", line_index, mba, ground_truth); @@ -325,7 +325,7 @@ fn check_rumba_dataset_row(filename: &str, line_index: usize, mba: &str, ground_ } fn dataset_dir() -> PathBuf { - std::env::var_os("SMT_SERVER_RUMBA_DATASET_DIR") + std::env::var_os("BV_SERVER_RUMBA_DATASET_DIR") .map(PathBuf::from) .unwrap_or_else(|| { PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../../rumba/third_party/dataset") diff --git a/crates/smt-qfbv-smtlib/Cargo.toml b/crates/bv-smtlib/Cargo.toml similarity index 89% rename from crates/smt-qfbv-smtlib/Cargo.toml rename to crates/bv-smtlib/Cargo.toml index c0e0550..afaa512 100644 --- a/crates/smt-qfbv-smtlib/Cargo.toml +++ b/crates/bv-smtlib/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "smt-qfbv-smtlib" +name = "bv-smtlib" version.workspace = true edition.workspace = true description = "Shared sink-oriented QF_BV SMT-LIB frontend utilities" diff --git a/crates/smt-qfbv-smtlib/src/lib.rs b/crates/bv-smtlib/src/lib.rs similarity index 100% rename from crates/smt-qfbv-smtlib/src/lib.rs rename to crates/bv-smtlib/src/lib.rs diff --git a/crates/smt-wire/Cargo.toml b/crates/bv-wire/Cargo.toml similarity index 74% rename from crates/smt-wire/Cargo.toml rename to crates/bv-wire/Cargo.toml index f9add4e..330b096 100644 --- a/crates/smt-wire/Cargo.toml +++ b/crates/bv-wire/Cargo.toml @@ -1,10 +1,10 @@ [package] -name = "smt-wire" +name = "bv-wire" version.workspace = true edition.workspace = true -description = "Rust codecs, views, validation, and builders for the SMT v1 wire format" +description = "Rust codecs, views, validation, and builders for the bv-wire v1 format" license.workspace = true [lib] -name = "smt_wire" +name = "bv_wire" path = "src/lib.rs" diff --git a/crates/smt-wire/examples/example.rs b/crates/bv-wire/examples/example.rs similarity index 89% rename from crates/smt-wire/examples/example.rs rename to crates/bv-wire/examples/example.rs index 94ce7a5..90806ff 100644 --- a/crates/smt-wire/examples/example.rs +++ b/crates/bv-wire/examples/example.rs @@ -1,4 +1,4 @@ -use smt_wire::{Client, Context, Op, Status, Term}; +use bv_wire::{Client, Context, Op, Status, Term}; fn status_name(status: Status) -> &'static str { match status { @@ -10,7 +10,7 @@ fn status_name(status: Status) -> &'static str { } } -fn to_rpn(term: &Term, mut args: Vec) -> smt_wire::Result { +fn to_rpn(term: &Term, mut args: Vec) -> bv_wire::Result { match term.op()? { Op::BvVar => term.name(), Op::BvConst => { @@ -57,8 +57,8 @@ fn main() -> Result<(), Box> { println!("RPN: {}", mba.as_term().visit(&mut lower)?); // Start the server first: - // cargo run -p smt-server -- 127.0.0.1:9123 - // Or set SMT_SERVER_ADDRESS=: to choose a different default. + // cargo run -p bv-server -- 127.0.0.1:9123 + // Or set BV_SERVER_ADDRESS=: to choose a different default. let mut client = Client::connect_default()?; let resp = client.solve(&ctx)?; println!("{}", status_name(resp.status)); @@ -67,7 +67,7 @@ fn main() -> Result<(), Box> { let mut items = model .iter() .map(|(var, value)| Ok((var.name()?, value.as_u128()?))) - .collect::>>()?; + .collect::>>()?; items.sort_by(|a, b| a.0.cmp(&b.0)); for (name, value) in items { println!("{name} = 0x{value:x}"); diff --git a/crates/smt-wire/src/api.rs b/crates/bv-wire/src/api.rs similarity index 100% rename from crates/smt-wire/src/api.rs rename to crates/bv-wire/src/api.rs diff --git a/crates/smt-wire/src/builder.rs b/crates/bv-wire/src/builder.rs similarity index 100% rename from crates/smt-wire/src/builder.rs rename to crates/bv-wire/src/builder.rs diff --git a/crates/smt-wire/src/client.rs b/crates/bv-wire/src/client.rs similarity index 98% rename from crates/smt-wire/src/client.rs rename to crates/bv-wire/src/client.rs index d378885..fcffdf3 100644 --- a/crates/smt-wire/src/client.rs +++ b/crates/bv-wire/src/client.rs @@ -8,7 +8,7 @@ use crate::response::BinaryResponse; use crate::WireError; pub const DEFAULT_MAX_RESPONSE_BYTES: usize = 64 * 1024 * 1024; -pub const SERVER_ADDRESS_ENV: &str = "SMT_SERVER_ADDRESS"; +pub const SERVER_ADDRESS_ENV: &str = "BV_SERVER_ADDRESS"; pub const DEFAULT_SERVER_ADDRESS: &str = "127.0.0.1:9123"; pub fn default_server_address() -> String { diff --git a/crates/smt-wire/src/constants.rs b/crates/bv-wire/src/constants.rs similarity index 100% rename from crates/smt-wire/src/constants.rs rename to crates/bv-wire/src/constants.rs diff --git a/crates/smt-wire/src/error.rs b/crates/bv-wire/src/error.rs similarity index 97% rename from crates/smt-wire/src/error.rs rename to crates/bv-wire/src/error.rs index 2230c99..5704250 100644 --- a/crates/smt-wire/src/error.rs +++ b/crates/bv-wire/src/error.rs @@ -78,7 +78,7 @@ impl fmt::Display for WireError { expected, actual ), WireError::UnsupportedVersion(version) => { - write!(f, "unsupported SMT wire version {version}") + write!(f, "unsupported bv-wire version {version}") } WireError::IntegerOverflow(context) => { write!(f, "integer overflow while computing {context}") diff --git a/crates/smt-wire/src/expr.rs b/crates/bv-wire/src/expr.rs similarity index 100% rename from crates/smt-wire/src/expr.rs rename to crates/bv-wire/src/expr.rs diff --git a/crates/smt-wire/src/le.rs b/crates/bv-wire/src/le.rs similarity index 100% rename from crates/smt-wire/src/le.rs rename to crates/bv-wire/src/le.rs diff --git a/crates/smt-wire/src/lib.rs b/crates/bv-wire/src/lib.rs similarity index 97% rename from crates/smt-wire/src/lib.rs rename to crates/bv-wire/src/lib.rs index f71ffdc..d1c8f05 100644 --- a/crates/smt-wire/src/lib.rs +++ b/crates/bv-wire/src/lib.rs @@ -1,4 +1,4 @@ -//! Rust support for the SMT v1 binary wire format. +//! Rust support for the bv-wire v1 binary format. //! //! The public client API is context-oriented: build formulas through //! [`Context`], pass typed [`BvTerm`]/[`BoolTerm`] handles around, and use diff --git a/crates/smt-wire/src/request.rs b/crates/bv-wire/src/request.rs similarity index 100% rename from crates/smt-wire/src/request.rs rename to crates/bv-wire/src/request.rs diff --git a/crates/smt-wire/src/response.rs b/crates/bv-wire/src/response.rs similarity index 100% rename from crates/smt-wire/src/response.rs rename to crates/bv-wire/src/response.rs diff --git a/crates/smt-wire/src/types.rs b/crates/bv-wire/src/types.rs similarity index 100% rename from crates/smt-wire/src/types.rs rename to crates/bv-wire/src/types.rs diff --git a/crates/smt-wire/tests/phase0_golden.rs b/crates/bv-wire/tests/phase0_golden.rs similarity index 96% rename from crates/smt-wire/tests/phase0_golden.rs rename to crates/bv-wire/tests/phase0_golden.rs index 497c5f9..b3829ac 100644 --- a/crates/smt-wire/tests/phase0_golden.rs +++ b/crates/bv-wire/tests/phase0_golden.rs @@ -1,4 +1,4 @@ -use smt_wire::raw::{constants::tag, le, ExprView, ExpressionBuffer, NodeRef, RawNode}; +use bv_wire::raw::{constants::tag, le, ExprView, ExpressionBuffer, NodeRef, RawNode}; #[test] fn empty_expression_buffer_golden_bytes() { diff --git a/crates/smt-wire/tests/phase1_codecs.rs b/crates/bv-wire/tests/phase1_codecs.rs similarity index 98% rename from crates/smt-wire/tests/phase1_codecs.rs rename to crates/bv-wire/tests/phase1_codecs.rs index 2f8fc6f..cc81880 100644 --- a/crates/smt-wire/tests/phase1_codecs.rs +++ b/crates/bv-wire/tests/phase1_codecs.rs @@ -1,9 +1,9 @@ -use smt_wire::raw::{ +use bv_wire::raw::{ request_flags, response_flags, status, tag, BinaryRequest, BinaryResponse, BlobRef, ClientError, Command, ExprBuilder, ExprView, ExpressionBuffer, ModelBlock, ModelEntry, NodeRef, OptimizationValueBlock, RawNode, SimplifyBlock, TcpClient, UnsatCoreBlock, }; -use smt_wire::{Context, ScalarValue, Sort, Status, WalkOrder}; +use bv_wire::{Context, ScalarValue, Sort, Status, WalkOrder}; fn hex_bytes(input: &str) -> Vec { let compact = input.split_whitespace().collect::(); @@ -429,16 +429,16 @@ fn high_level_context_matches_python_style_api() { #[test] fn transport_frames_are_little_endian_and_exact_length() { let payload = b"SMTQ-example"; - let frame = smt_wire::raw::le::encode_transport_frame(payload).unwrap(); + let frame = bv_wire::raw::le::encode_transport_frame(payload).unwrap(); assert_eq!(&frame[..4], &(payload.len() as u32).to_le_bytes()); assert_eq!( - smt_wire::raw::le::decode_transport_frame(&frame).unwrap(), + bv_wire::raw::le::decode_transport_frame(&frame).unwrap(), payload ); let mut too_long = frame.clone(); too_long.push(0); - assert!(smt_wire::raw::le::decode_transport_frame(&too_long).is_err()); + assert!(bv_wire::raw::le::decode_transport_frame(&too_long).is_err()); assert_eq!(status::SAT, 1); assert_eq!(Sort::Bool.sort_bit(), 0x8000_0000); diff --git a/crates/qfbvsmtrs/Cargo.toml b/crates/qfbvsmtrs/Cargo.toml index 6412a34..f08a4f7 100644 --- a/crates/qfbvsmtrs/Cargo.toml +++ b/crates/qfbvsmtrs/Cargo.toml @@ -7,11 +7,11 @@ license.workspace = true [features] default = [] -wire = ["dep:smt-wire"] +wire = ["dep:bv-wire"] [dependencies] -smt-qfbv-smtlib.workspace = true -smt-wire = { workspace = true, optional = true } +bv-smtlib.workspace = true +bv-wire = { workspace = true, optional = true } varisat.workspace = true splr.workspace = true diff --git a/crates/qfbvsmtrs/fuzz/Cargo.lock b/crates/qfbvsmtrs/fuzz/Cargo.lock index 004ac27..12165c7 100644 --- a/crates/qfbvsmtrs/fuzz/Cargo.lock +++ b/crates/qfbvsmtrs/fuzz/Cargo.lock @@ -677,7 +677,7 @@ dependencies = [ name = "qfbvsmtrs" version = "0.1.0" dependencies = [ - "smt-qfbv-smtlib", + "bv-smtlib", "splr", "varisat", ] @@ -829,7 +829,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" [[package]] -name = "smt-qfbv-smtlib" +name = "bv-smtlib" version = "0.1.0" dependencies = [ "dashu", diff --git a/crates/qfbvsmtrs/src/frontend.rs b/crates/qfbvsmtrs/src/frontend.rs index b5655bc..60bc8ad 100644 --- a/crates/qfbvsmtrs/src/frontend.rs +++ b/crates/qfbvsmtrs/src/frontend.rs @@ -5,7 +5,7 @@ use crate::model::{scalar_to_smt, Model, ScalarValue}; use crate::query::Query; use crate::solver::{SolveResult, SolveStatus}; use crate::{Config, Solver}; -use smt_qfbv_smtlib::{lower_script, FrontendError, FrontendOptions, QfBvSink}; +use bv_smtlib::{lower_script, FrontendError, FrontendOptions, QfBvSink}; pub struct QfbvSmtLibSink<'a> { builder: &'a mut Builder, diff --git a/crates/qfbvsmtrs/src/lib.rs b/crates/qfbvsmtrs/src/lib.rs index 61f5777..7f92fed 100644 --- a/crates/qfbvsmtrs/src/lib.rs +++ b/crates/qfbvsmtrs/src/lib.rs @@ -4,7 +4,7 @@ /// /// Large SMT-LIB generated formulas can be deeply nested enough to overflow /// Rust's default thread stack during frontend/simplification traversals. The -/// standalone CLI and smt-server adapter use this stack size for qfbvsmtrs +/// standalone CLI and bv-server adapter use this stack size for qfbvsmtrs /// worker threads so those cases degrade to `unknown`/timeout instead of /// aborting the process. pub const DEFAULT_WORKER_STACK_BYTES: usize = 512 * 1024 * 1024; diff --git a/crates/qfbvsmtrs/src/wire.rs b/crates/qfbvsmtrs/src/wire.rs index 7ff02f2..3cfa51d 100644 --- a/crates/qfbvsmtrs/src/wire.rs +++ b/crates/qfbvsmtrs/src/wire.rs @@ -8,7 +8,7 @@ use crate::ir::TermId; use crate::model::{Model, ScalarValue as QScalarValue}; use crate::query::{Command as QCommand, Query}; -use smt_wire::raw::{ +use bv_wire::raw::{ request_flags, tag, BinaryRequest, BlobRef, Command, ExprView, ModelBlock, ModelEntry, NodeRef, RawNode, ScalarValue, }; @@ -16,7 +16,7 @@ use smt_wire::raw::{ pub fn query_from_wire(request: &BinaryRequest) -> Result { let expr = request .expression_view() - .map_err(|err| Error::invalid("smt-wire expression", err.to_string()))?; + .map_err(|err| Error::invalid("bv-wire expression", err.to_string()))?; let mut builder = Builder::new(); let mut terms = vec![None; expr.node_count() as usize]; let mut bv_vars = HashMap::<(String, u32), TermId>::new(); @@ -25,12 +25,12 @@ pub fn query_from_wire(request: &BinaryRequest) -> Result { for index in 0..expr.node_count() { let node = expr .node(index) - .map_err(|err| Error::invalid("smt-wire node", err.to_string()))?; + .map_err(|err| Error::invalid("bv-wire node", err.to_string()))?; let term = match node.tag { tag::BV_VAR => { let name = expr .blob_str(BlobRef::from_payload(node.payload), "BV variable") - .map_err(|err| Error::invalid("smt-wire BV variable", err.to_string()))? + .map_err(|err| Error::invalid("bv-wire BV variable", err.to_string()))? .to_owned(); if let Some(term) = bv_vars.get(&(name.clone(), node.width)).copied() { term @@ -51,7 +51,7 @@ pub fn query_from_wire(request: &BinaryRequest) -> Result { tag::BOOL_VAR => { let name = expr .blob_str(BlobRef::from_payload(node.payload), "Bool variable") - .map_err(|err| Error::invalid("smt-wire Bool variable", err.to_string()))? + .map_err(|err| Error::invalid("bv-wire Bool variable", err.to_string()))? .to_owned(); if let Some(term) = bool_vars.get(&name).copied() { term @@ -241,7 +241,7 @@ pub fn query_from_wire(request: &BinaryRequest) -> Result { let (a, b) = child2(&expr, &terms, &node)?; builder.sdiv_ovf(a, b)? } - other => return Err(Error::unsupported(format!("smt-wire tag {other}"))), + other => return Err(Error::unsupported(format!("bv-wire tag {other}"))), }; terms[index as usize] = Some(term); } diff --git a/docs/architecture.md b/docs/architecture.md index b081130..baefd80 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -3,8 +3,8 @@ This repository has three layers: 1. **Client libraries** build typed QF_BV/Bool formulas without linking to a solver. -2. **`smt-wire`** serializes those formulas into a compact, validated binary protocol. -3. **`smt-server`** owns solver/simplifier backends and returns models, cores, simplified terms, or optimum values. +2. **`bv-wire`** serializes those formulas into a compact, validated binary protocol. +3. **`bv-server`** owns solver/simplifier backends and returns models, cores, simplified terms, or optimum values. The server is intentionally stateless at the protocol boundary. Every request contains the complete expression DAG, assertions, assumptions, command, flags, and budget. That makes requests cacheable, replayable, and easy to compare across backends. @@ -12,12 +12,12 @@ The server is intentionally stateless at the protocol boundary. Every request co | Path | Role | |---|---| -| `crates/smt-wire` | Rust protocol/client crate. It owns wire constants, expression validation, request/response codecs, high-level Rust `Context`/term APIs, and a TCP client. | -| `crates/smt-server` | TCP server, binary/text dispatch, response cache, backend trait, backend racing, and integrations for Z3, binbit, qfbvsmtrs, and Rumba. | -| `crates/smt-qfbv-smtlib` | Shared solver-agnostic QF_BV/Bool SMT-LIB frontend. It parses with `yaspar` and lowers through a sink trait. | -| `crates/qfbvsmtrs` | Standalone pure-Rust QF_BV solver. It can be used directly, through its SMT-LIB frontend, or as a server backend through the `smt-wire` bridge. | -| `python` | Dependency-free Python client package (`smt_wire.py`) plus examples/tests. Install from this repo with pip's `#subdirectory=python` support. | -| `cpp` | Header-only C++17 client package exposing the `smt_wire::smt_wire` CMake `INTERFACE` target plus examples/tests. | +| `crates/bv-wire` | Rust protocol/client crate. It owns wire constants, expression validation, request/response codecs, high-level Rust `Context`/term APIs, and a TCP client. | +| `crates/bv-server` | TCP server, binary/text dispatch, response cache, backend trait, backend racing, and integrations for Z3, binbit, qfbvsmtrs, and Rumba. | +| `crates/bv-smtlib` | Shared solver-agnostic QF_BV/Bool SMT-LIB frontend. It parses with `yaspar` and lowers through a sink trait. | +| `crates/qfbvsmtrs` | Standalone pure-Rust QF_BV solver. It can be used directly, through its SMT-LIB frontend, or as a server backend through the `bv-wire` bridge. | +| `python` | Dependency-free Python client package (`bv_wire.py`) plus examples/tests. Install from this repo with pip's `#subdirectory=python` support. | +| `cpp` | Header-only C++17 client package exposing the `bv_wire::bv_wire` CMake `INTERFACE` target plus examples/tests. | ## Request flow @@ -27,13 +27,13 @@ The server is intentionally stateless at the protocol boundary. Every request co Python / C++ / Rust Context | v -smt-wire expression buffer + request envelope +bv-wire expression buffer + request envelope | v length-prefixed TCP frame | v -smt-server binary decoder + validator +bv-server binary decoder + validator | v optional response cache @@ -53,7 +53,7 @@ The binary path is the primary API. Clients construct a typed DAG and send one l one complete SMT-LIB script | v -shared QF_BV frontend (`smt-qfbv-smtlib`) +shared QF_BV frontend (`bv-smtlib`) | v wire request or qfbvsmtrs fallback query @@ -69,7 +69,7 @@ Text requests are for compatibility with external tools and tests. They use the ## Default server backend graph -The shipped binary in `crates/smt-server/src/main.rs` builds this backend stack: +The shipped binary in `crates/bv-server/src/main.rs` builds this backend stack: ```text CommandRouterBackend @@ -102,9 +102,9 @@ The server has explicit bounds for hostile or accidental large inputs: - optional read/write timeouts; - per-request backend budgets. -The server also records handled binary request/response pairs into a SQLite database at `~/.smt-server/recordings.db` by default. `SMT_SERVER_RECORD_DB` overrides the path; setting it to an empty value disables recording. Each row is keyed by the BLAKE3 hash of the canonical request (`INSERT OR IGNORE` dedupes, leaving existing rows unchanged), and stores the canonical request and response blobs. SMT-LIB text requests are recorded after lowering to binary wire requests. The recorder zeroes request/response IDs before hashing or storage. +The server also records handled binary request/response pairs into a SQLite database at `~/.bv-server/recordings.db` by default. `BV_SERVER_RECORD_DB` overrides the path; setting it to an empty value disables recording. Each row is keyed by the BLAKE3 hash of the canonical request (`INSERT OR IGNORE` dedupes, leaving existing rows unchanged), and stores the canonical request and response blobs. SMT-LIB text requests are recorded after lowering to binary wire requests. The recorder zeroes request/response IDs before hashing or storage. -Recording is synchronous: the server attempts the SQLite insert before returning the response from the dispatcher. The database opens in WAL mode with `synchronous=NORMAL` and a busy timeout, so multiple server instances on the same host can write to the same file (writes serialize; readers don't block). WAL relies on local filesystem locking and is not safe over network mounts. The one-time importer reads the legacy `~/.smt-server/requests` file tree: run `smt-server migrate-recordings [SOURCE_DIR] [DB_PATH]` to fold an existing tree into the database. +Recording is synchronous: the server attempts the SQLite insert before returning the response from the dispatcher. The database opens in WAL mode with `synchronous=NORMAL` and a busy timeout, so multiple server instances on the same host can write to the same file (writes serialize; readers don't block). WAL relies on local filesystem locking and is not safe over network mounts. The one-time importer reads the legacy `~/.bv-server/requests` file tree: run `bv-server migrate-recordings [SOURCE_DIR] [DB_PATH]` to fold an existing tree into the database. The client libraries also enforce sort/width/context checks during construction so malformed requests are normally caught before serialization. diff --git a/docs/smt-wire-protocol.md b/docs/bv-wire-protocol.md similarity index 97% rename from docs/smt-wire-protocol.md rename to docs/bv-wire-protocol.md index 2f6c04f..30ea9f6 100644 --- a/docs/smt-wire-protocol.md +++ b/docs/bv-wire-protocol.md @@ -1,6 +1,6 @@ -# SMT wire protocol reference +# bv-wire protocol reference -`smt-wire` is a little-endian, length-prefixed protocol for stateless QF_BV/Bool queries. The Rust implementation in `crates/smt-wire` is the executable specification; this document records the stable v1 layout and semantics. +`bv-wire` is a little-endian, length-prefixed protocol for stateless QF_BV/Bool queries. The Rust implementation in `crates/bv-wire` is the executable specification; this document records the stable v1 layout and semantics. ## Transport diff --git a/docs/client-api.md b/docs/client-api.md index 7d78cce..4403400 100644 --- a/docs/client-api.md +++ b/docs/client-api.md @@ -10,20 +10,20 @@ The user-facing clients expose the same model: a `Context` owns an append-only t - Integer operands are coerced to bit-vector constants using the width of the bit-vector operand. - `push`/`pop` are client-side assertion-scope operations; the server still receives one complete stateless request. - Serialization, DAG compaction, request envelopes, TCP framing, and response payload parsing are implementation details behind `Client`. -- When no address is passed, clients read `SMT_SERVER_ADDRESS=:` and otherwise fall back to `127.0.0.1:9123`. +- When no address is passed, clients read `BV_SERVER_ADDRESS=:` and otherwise fall back to `127.0.0.1:9123`. The full side-by-side walkthroughs are: - Python: `python/example.py` - C++: `cpp/tests/example.cpp` -- Rust: `crates/smt-wire/examples/example.rs` +- Rust: `crates/bv-wire/examples/example.rs` ## Python Install from this repository: ```sh -pip install 'git+https://github.com/LLVMParty/smt-server.git#subdirectory=python' +pip install 'git+https://github.com/LLVMParty/bv-server.git#subdirectory=python' ``` Or use directly from a checkout: @@ -35,13 +35,13 @@ PYTHONPATH=python python3 python/example.py Minimal usage: ```python -import smt_wire as smt +import bv_wire as bv -ctx = smt.Context() +ctx = bv.Context() x = ctx.bv_var("x", 8) ctx.assert_(ctx.bv_eq(x, 42)) -with smt.Client() as client: +with bv.Client() as client: response = client.solve(ctx) print(response.status) @@ -52,23 +52,23 @@ if response.model is not None: ## C++ -The C++ client is header-only C++17 and exposes the CMake target `smt_wire::smt_wire` from `cpp/CMakeLists.txt`: +The C++ client is header-only C++17 and exposes the CMake target `bv_wire::bv_wire` from `cpp/CMakeLists.txt`: ```cmake -add_subdirectory(path/to/smt-server/cpp) -target_link_libraries(my_tool PRIVATE smt_wire::smt_wire) +add_subdirectory(path/to/bv-server/cpp) +target_link_libraries(my_tool PRIVATE bv_wire::bv_wire) ``` Minimal usage: ```cpp -#include +#include -smt_wire::Context ctx; +bv_wire::Context ctx; auto x = ctx.bv_var("x", 8); ctx.assert_(ctx.bv_eq(x, 42u)); -smt_wire::Client client; +bv_wire::Client client; auto response = client.solve(ctx); ``` @@ -76,10 +76,10 @@ On Windows/MSVC the header requests `Ws2_32.lib` automatically. With MinGW, link ## Rust -Use the `smt-wire` crate in this workspace: +Use the `bv-wire` crate in this workspace: ```rust -use smt_wire::{Client, Context, Status}; +use bv_wire::{Client, Context, Status}; let ctx = Context::new(); let x = ctx.bv_var("x", 8)?; @@ -94,4 +94,4 @@ if response.status == Status::Sat { } ``` -Protocol internals remain available under `smt_wire::raw` for the server and conformance tests, but normal client code should use `Context`, typed terms, and `Client`. +Protocol internals remain available under `bv_wire::raw` for the server and conformance tests, but normal client code should use `Context`, typed terms, and `Client`. diff --git a/docs/qfbvsmtrs-design.md b/docs/qfbvsmtrs-design.md index 26ecd58..9cc3e8c 100644 --- a/docs/qfbvsmtrs-design.md +++ b/docs/qfbvsmtrs-design.md @@ -1,11 +1,11 @@ # qfbvsmtrs design -`qfbvsmtrs` is a standalone pure-Rust solver for quantifier-free bit-vector formulas. It is also integrated into `smt-server` as `QfbvsmtrsBackend`, but the solver crate does not depend on the server crate. +`qfbvsmtrs` is a standalone pure-Rust solver for quantifier-free bit-vector formulas. It is also integrated into `bv-server` as `QfbvsmtrsBackend`, but the solver crate does not depend on the server crate. ## Pipeline ```text -Native builder / SMT-LIB / smt-wire bridge +Native builder / SMT-LIB / bv-wire bridge | v qfbvsmtrs Query IR @@ -44,7 +44,7 @@ Core crate: `crates/qfbvsmtrs`. | `query.rs` | assertions, assumptions, commands, optimization target, output requests | | `builder.rs` | native builder API and eager local simplification | | `frontend.rs` | adapter from shared SMT-LIB frontend into qfbvsmtrs IR and SMT-LIB response formatting | -| `wire.rs` | optional `smt-wire` bridge for server integration | +| `wire.rs` | optional `bv-wire` bridge for server integration | | `gates.rs` | Boolean gate arena with structural hashing | | `circuits.rs` | bit-vector circuits over Boolean gates | | `blast.rs` | reachable IR to gate graph | @@ -56,7 +56,7 @@ Core crate: `crates/qfbvsmtrs`. | `eval.rs` | evaluator used to validate cheap SAT witnesses | | `simplify.rs` | simplification module hook/documentation | -The shared SMT-LIB parser is in `crates/smt-qfbv-smtlib`; qfbvsmtrs only supplies a sink adapter. +The shared SMT-LIB parser is in `crates/bv-smtlib`; qfbvsmtrs only supplies a sink adapter. ## Public entry points diff --git a/docs/qfbvsmtrs-validation.md b/docs/qfbvsmtrs-validation.md index 08c8edb..861a4b2 100644 --- a/docs/qfbvsmtrs-validation.md +++ b/docs/qfbvsmtrs-validation.md @@ -12,7 +12,7 @@ A production-complete claim for this crate would require: - budgets, process timeouts, and memory-heavy failure modes are documented and respected; - unsupported SMT-LIB constructs are rejected rather than mis-solved; - remaining corpus `unknown`/timeout cases are either solved or explicitly accepted as outside the guarantee; -- `smt-server` integration correctly handles `sat`, `unsat`, `unknown`, model, core, simplification, optimization, cache, and text/binary formatting paths while qfbvsmtrs remains standalone. +- `bv-server` integration correctly handles `sat`, `unsat`, `unknown`, model, core, simplification, optimization, cache, and text/binary formatting paths while qfbvsmtrs remains standalone. Current status: no wrong conclusive answers in the recorded corpus runs, but the merged SMT-LIB QF_BV tail still contains `3,266` `unknown` results and `15` process timeouts. @@ -29,12 +29,12 @@ python3 python/tests/test_python_client.py python3 python/tests/test_live_server.py cmake -S cpp -B /tmp/smt_cpp_cmake cmake --build /tmp/smt_cpp_cmake -cargo build -p smt-server -target/debug/smt-server 127.0.0.1:9123 & +cargo build -p bv-server +target/debug/bv-server 127.0.0.1:9123 & server_pid=$! trap 'kill "$server_pid" 2>/dev/null || true' EXIT sleep 1 -SMT_SERVER_ADDRESS=127.0.0.1:9123 ctest --test-dir /tmp/smt_cpp_cmake --output-on-failure +BV_SERVER_ADDRESS=127.0.0.1:9123 ctest --test-dir /tmp/smt_cpp_cmake --output-on-failure ``` The checked-in suite includes exhaustive 4-bit circuit tests, randomized circuit properties, Tseitin truth-table tests across SAT backends, known-answer SMT-LIB fixtures, Rust Z3 differential smoke tests, standalone qfbvsmtrs tests, server binary/text/cache/racing tests, live client tests, and C++/Python smoke tests. diff --git a/docs/smtlib-frontend.md b/docs/smtlib-frontend.md index e73759e..6e2bd97 100644 --- a/docs/smtlib-frontend.md +++ b/docs/smtlib-frontend.md @@ -1,8 +1,8 @@ # Shared SMT-LIB frontend -SMT-LIB parsing lives in `crates/smt-qfbv-smtlib`. It is intentionally solver-agnostic: the crate parses one script with `yaspar`, normalizes common QF_BV/Bool constructs, and lowers through the `QfBvSink` trait. The same parser is used by: +SMT-LIB parsing lives in `crates/bv-smtlib`. It is intentionally solver-agnostic: the crate parses one script with `yaspar`, normalizes common QF_BV/Bool constructs, and lowers through the `QfBvSink` trait. The same parser is used by: -- `crates/smt-server/src/smtlib.rs`, where `WireSmtLibSink` builds an `smt-wire` request; +- `crates/bv-server/src/smtlib.rs`, where `WireSmtLibSink` builds an `bv-wire` request; - `crates/qfbvsmtrs/src/frontend.rs`, where `QfbvSmtLibSink` builds qfbvsmtrs IR. This avoids keeping separate SMT-LIB parsers in sync. @@ -13,7 +13,7 @@ This avoids keeping separate SMT-LIB parsers in sync. | Option set | Logic policy | `push`/`pop` | Typical use | |---|---|---|---| -| `FrontendOptions::server_text()` | accepts `QF_BV` | rejects incremental commands | `smt-server` text frames lowered to one stateless wire request | +| `FrontendOptions::server_text()` | accepts `QF_BV` | rejects incremental commands | `bv-server` text frames lowered to one stateless wire request | | `FrontendOptions::standalone()` | accepts `QF_BV` or `ALL` | simulates scopes in the sink | qfbvsmtrs CLI/API | Both modes require a `check-sat` command before response-oriented commands are considered complete. @@ -63,11 +63,11 @@ The frontend is limited to QF_BV/Bool. Arrays, floating point, quantifiers, unin Server text frames are still stateless. The server reads exactly one length-prefixed script and returns one SMT-LIB text response. In server text mode: -1. `smt-qfbv-smtlib` tries to lower the script into an `smt-wire` `SOLVE` request. +1. `bv-smtlib` tries to lower the script into an `bv-wire` `SOLVE` request. 2. The selected backend handles that request and returns a `QueryResult`. -3. `smt-server` formats `sat`/`unsat`/`unknown`, plus `(model ...)`, `get-value`, or unsat-core output when requested. +3. `bv-server` formats `sat`/`unsat`/`unknown`, plus `(model ...)`, `get-value`, or unsat-core output when requested. -When the selected backend supports qfbvsmtrs text fallback and the server wire-lowering frontend rejects a script, the server can invoke qfbvsmtrs' standalone parser/solver on a worker thread. The fallback uses a default 30s budget, overrideable with `SMT_SERVER_TEXT_QFBVSMTRS_BUDGET_MS`; a nonzero fallback budget selects qfbvsmtrs' polling DPLL backend to avoid in-process timeout overruns. +When the selected backend supports qfbvsmtrs text fallback and the server wire-lowering frontend rejects a script, the server can invoke qfbvsmtrs' standalone parser/solver on a worker thread. The fallback uses a default 30s budget, overrideable with `BV_SERVER_TEXT_QFBVSMTRS_BUDGET_MS`; a nonzero fallback budget selects qfbvsmtrs' polling DPLL backend to avoid in-process timeout overruns. ## Error model diff --git a/python/README.md b/python/README.md index f8bc9af..78469d5 100644 --- a/python/README.md +++ b/python/README.md @@ -1,13 +1,13 @@ -# smt-wire Python client +# bv-wire Python client -Typed dependency-free Python client for the SMT v1 wire protocol. The optional `smt_z3_server` module provides an in-process Z3-backed TCP server for experiments. +Typed dependency-free Python client for the bv-wire v1 protocol. The optional `bv_z3_server` module provides an in-process Z3-backed TCP server for experiments. -`Client()` connects to `SMT_SERVER_ADDRESS=:` when set, otherwise `127.0.0.1:9123`. +`Client()` connects to `BV_SERVER_ADDRESS=:` when set, otherwise `127.0.0.1:9123`. Install from this repository with pip using the Python subdirectory: ```sh -pip install 'git+https://github.com/LLVMParty/smt-server.git#subdirectory=python' +pip install 'git+https://github.com/LLVMParty/bv-server.git#subdirectory=python' ``` Install the optional Z3 server dependency from the Python subdirectory: @@ -19,11 +19,11 @@ pip install -e 'python[z3]' Start a random-port in-process server from Python: ```python -import smt_wire as smt -from smt_z3_server import Z3Server +import bv_wire as bv +from bv_z3_server import Z3Server with Z3Server.start(port=0) as server: - with smt.Client(server.host, server.port) as client: + with bv.Client(server.host, server.port) as client: # use the existing client API pass ``` @@ -31,7 +31,7 @@ with Z3Server.start(port=0) as server: Or run it as a module; it prints the selected address after binding: ```sh -python -m smt_z3_server --port 0 +python -m bv_z3_server --port 0 ``` For local development from the repository root: diff --git a/python/smt_wire.py b/python/bv_wire.py similarity index 99% rename from python/smt_wire.py rename to python/bv_wire.py index 1ffbefa..07cc98c 100644 --- a/python/smt_wire.py +++ b/python/bv_wire.py @@ -1,4 +1,4 @@ -"""Typed Python client for the SMT v1 wire protocol. +"""Typed Python client for the bv-wire v1 protocol. The public API is intentionally context-oriented: users build formulas through ``Context`` and send them through ``Client``. ``Term`` objects are thin typed @@ -25,7 +25,7 @@ INDEX_MASK = 0x7FFFFFFF MAX_WIDTH = 65536 DEFAULT_MAX_RESPONSE_BYTES = 64 * 1024 * 1024 -SERVER_ADDRESS_ENV = "SMT_SERVER_ADDRESS" +SERVER_ADDRESS_ENV = "BV_SERVER_ADDRESS" DEFAULT_SERVER_HOST = "127.0.0.1" DEFAULT_SERVER_PORT = 9123 @@ -1579,7 +1579,7 @@ class OptimizationResult: class Client: - """Blocking TCP client for the SMT server transport.""" + """Blocking TCP client for the bv-server transport.""" def __init__( self, diff --git a/python/smt_z3_server.py b/python/bv_z3_server.py similarity index 78% rename from python/smt_z3_server.py rename to python/bv_z3_server.py index c7802f0..089caab 100644 --- a/python/smt_z3_server.py +++ b/python/bv_z3_server.py @@ -1,8 +1,8 @@ -"""Experimental in-process Z3 server for the SMT v1 wire protocol. +"""Experimental in-process Z3 server for the bv-wire v1 protocol. -The module is separate from ``smt_wire`` so the Python client remains usable -without Z3. Install the optional dependency with ``smt-wire[z3]`` before using -``Z3Server`` or running ``python -m smt_z3_server``. +The module is separate from ``bv_wire`` so the Python client remains usable +without Z3. Install the optional dependency with ``bv-wire[z3]`` before using +``Z3Server`` or running ``python -m bv_z3_server``. """ from __future__ import annotations @@ -15,7 +15,7 @@ import time from typing import Any, Optional -import smt_wire as smt +import bv_wire as bv BOOL_BIT = 0x80000000 INDEX_MASK = 0x7FFFFFFF @@ -24,16 +24,16 @@ DEFAULT_MAX_RESPONSE_BYTES = 64 * 1024 * 1024 DEFAULT_MAX_CONNECTIONS = 128 -REQ_WANT_MODEL = int(smt.RequestFlag.WANT_MODEL) -REQ_WANT_CORE = int(smt.RequestFlag.WANT_CORE) -REQ_SIGNED = int(smt.RequestFlag.SIGNED) +REQ_WANT_MODEL = int(bv.RequestFlag.WANT_MODEL) +REQ_WANT_CORE = int(bv.RequestFlag.WANT_CORE) +REQ_SIGNED = int(bv.RequestFlag.SIGNED) REQ_ALL_FLAGS = REQ_WANT_MODEL | REQ_WANT_CORE | REQ_SIGNED -RESP_HAS_MODEL = int(smt.ResponseFlag.HAS_MODEL) -RESP_HAS_CORE = int(smt.ResponseFlag.HAS_CORE) -RESP_HAS_EXPR = int(smt.ResponseFlag.HAS_EXPR) -RESP_HAS_VALUE = int(smt.ResponseFlag.HAS_VALUE) -RESP_HAS_MESSAGE = int(smt.ResponseFlag.HAS_MESSAGE) +RESP_HAS_MODEL = int(bv.ResponseFlag.HAS_MODEL) +RESP_HAS_CORE = int(bv.ResponseFlag.HAS_CORE) +RESP_HAS_EXPR = int(bv.ResponseFlag.HAS_EXPR) +RESP_HAS_VALUE = int(bv.ResponseFlag.HAS_VALUE) +RESP_HAS_MESSAGE = int(bv.ResponseFlag.HAS_MESSAGE) def _load_z3() -> Any: @@ -41,8 +41,8 @@ def _load_z3() -> Any: import z3 # type: ignore[import-not-found] except ImportError as exc: # pragma: no cover - depends on environment raise ImportError( - "smt_z3_server requires the optional z3 dependency; " - "install with `pip install 'smt-wire[z3]'` or `pip install z3-solver`" + "bv_z3_server requires the optional z3 dependency; " + "install with `pip install 'bv-wire[z3]'` or `pip install z3-solver`" ) from exc return z3 @@ -68,8 +68,8 @@ def _blob_ref(payload: int) -> tuple[int, int]: def _bytes_for_width(width: int) -> int: - if not 1 <= width <= smt.MAX_WIDTH: - raise smt.WidthMismatchError(f"invalid BV width {width}") + if not 1 <= width <= bv.MAX_WIDTH: + raise bv.WidthMismatchError(f"invalid BV width {width}") return (width + 7) // 8 @@ -77,11 +77,11 @@ def _bytes_for_width(width: int) -> int: class _BinaryRequest: payload: bytes request_id: int - command: smt.Command + command: bv.Command flags: int budget_ms: int expression: bytes - context: smt.Context + context: bv.Context assertion_roots: list[int] named_assertion_names: list[str] assumption_roots: list[int] @@ -103,7 +103,7 @@ def signed(self) -> bool: @dataclass(frozen=True) class _Z3Variable: node_ref: int - sort: smt.Sort + sort: bv.Sort width: int @@ -116,18 +116,18 @@ class _Z3Translation: def bv(self, ref: int) -> Any: if _is_bool_ref(ref): - raise smt.ProtocolError("Z3 translation expected BV reference") + raise bv.ProtocolError("Z3 translation expected BV reference") index = _ref_index(ref) if index >= len(self.bvs) or self.bvs[index] is None: - raise smt.ProtocolError(f"Z3 translation missing BV term #{index}") + raise bv.ProtocolError(f"Z3 translation missing BV term #{index}") return self.bvs[index] def bool(self, ref: int) -> Any: if not _is_bool_ref(ref): - raise smt.ProtocolError("Z3 translation expected Bool reference") + raise bv.ProtocolError("Z3 translation expected Bool reference") index = _ref_index(ref) if index >= len(self.bools) or self.bools[index] is None: - raise smt.ProtocolError(f"Z3 translation missing Bool term #{index}") + raise bv.ProtocolError(f"Z3 translation missing Bool term #{index}") return self.bools[index] @@ -151,13 +151,13 @@ def __init__(self) -> None: self.z3 = _load_z3() def handle(self, request: _BinaryRequest) -> bytes: - if request.command is smt.Command.SIMPLIFY: + if request.command is bv.Command.SIMPLIFY: return _simplify_response(request) - if request.command is smt.Command.SOLVE: + if request.command is bv.Command.SOLVE: return self._solve(request) - if request.command in (smt.Command.MINIMIZE, smt.Command.MAXIMIZE): + if request.command in (bv.Command.MINIMIZE, bv.Command.MAXIMIZE): return self._optimize(request) - raise smt.ProtocolError(f"unsupported command {request.command}") + raise bv.ProtocolError(f"unsupported command {request.command}") def _solve(self, request: _BinaryRequest) -> bytes: z3 = self.z3 @@ -184,14 +184,14 @@ def _solve(self, request: _BinaryRequest) -> bytes: model = solver.model() payload = _encode_model(translation, model) flags |= RESP_HAS_MODEL - return _response(request.request_id, smt.Status.SAT, flags, payload) + return _response(request.request_id, bv.Status.SAT, flags, payload) if status == z3.unsat: payload = b"" flags = 0 if request.want_core: payload = _encode_core(_build_core(solver, trackers)) flags |= RESP_HAS_CORE - return _response(request.request_id, smt.Status.UNSAT, flags, payload) + return _response(request.request_id, bv.Status.UNSAT, flags, payload) return _unknown_response(request.request_id, _unknown_reason(solver)) def _optimize(self, request: _BinaryRequest) -> bytes: @@ -205,14 +205,14 @@ def _optimize(self, request: _BinaryRequest) -> bytes: fixed = [translation.bool(root) for root in request.assumption_roots] status = _check_with_deadline(z3, solver, fixed, deadline) if status == z3.unsat: - return _response(request.request_id, smt.Status.UNSAT, 0, b"") + return _response(request.request_id, bv.Status.UNSAT, 0, b"") if status != z3.sat: return _unknown_response(request.request_id, _unknown_reason(solver)) target = translation.bv(request.target_node) width = target.size() optimum = bytearray(_bytes_for_width(width)) - minimize = request.command is smt.Command.MINIMIZE + minimize = request.command is bv.Command.MINIMIZE for bit in range(width - 1, -1, -1): sign_bit = bit == width - 1 @@ -237,7 +237,7 @@ def _optimize(self, request: _BinaryRequest) -> bytes: status = _check_with_deadline(z3, solver, fixed, deadline) if status == z3.unsat: - return _response(request.request_id, smt.Status.UNSAT, 0, b"") + return _response(request.request_id, bv.Status.UNSAT, 0, b"") if status != z3.sat: return _unknown_response(request.request_id, _unknown_reason(solver)) @@ -246,7 +246,7 @@ def _optimize(self, request: _BinaryRequest) -> bytes: if request.want_model: payload += _encode_model(translation, solver.model()) flags |= RESP_HAS_MODEL - return _response(request.request_id, smt.Status.SAT, flags, payload) + return _response(request.request_id, bv.Status.SAT, flags, payload) class Z3Server: @@ -280,14 +280,14 @@ def __init__( self._serve_error: Optional[BaseException] = None self._thread = threading.Thread( target=self._serve, - name=f"smt-z3-server-{self.host}:{self.port}", + name=f"bv-z3-server-{self.host}:{self.port}", daemon=True, ) @classmethod def start( cls, - host: str = smt.DEFAULT_SERVER_HOST, + host: str = bv.DEFAULT_SERVER_HOST, port: int = 0, *, max_frame_bytes: int = DEFAULT_MAX_FRAME_BYTES, @@ -327,9 +327,9 @@ def client( self, *, timeout: Optional[float] = None, - max_response_bytes: int = smt.DEFAULT_MAX_RESPONSE_BYTES, - ) -> smt.Client: - return smt.Client( + max_response_bytes: int = bv.DEFAULT_MAX_RESPONSE_BYTES, + ) -> bv.Client: + return bv.Client( self.host, self.port, timeout=timeout, @@ -386,7 +386,7 @@ def _serve(self) -> None: thread = threading.Thread( target=self._handle_connection, args=(conn,), - name=f"smt-z3-client-{self.host}:{self.port}", + name=f"bv-z3-client-{self.host}:{self.port}", daemon=True, ) with self._lock: @@ -438,7 +438,7 @@ def _handle_connection(self, conn: socket.socket) -> None: pass def _dispatch_payload(self, payload: bytes) -> bytes: - if not payload.startswith(smt.REQUEST_MAGIC): + if not payload.startswith(bv.REQUEST_MAGIC): return _text_error("Python Z3 server only supports binary SMTQ frames") try: request = _parse_binary_request(payload) @@ -451,7 +451,7 @@ def _dispatch_payload(self, payload: bytes) -> bytes: def start_z3_server( - host: str = smt.DEFAULT_SERVER_HOST, + host: str = bv.DEFAULT_SERVER_HOST, port: int = 0, *, max_frame_bytes: int = DEFAULT_MAX_FRAME_BYTES, @@ -487,13 +487,13 @@ def _bind_listener(host: str, port: int) -> socket.socket: def _parse_binary_request(payload: bytes) -> _BinaryRequest: - if len(payload) < REQUEST_HEADER_SIZE or payload[:4] != smt.REQUEST_MAGIC: - raise smt.ProtocolError("bad request envelope") + if len(payload) < REQUEST_HEADER_SIZE or payload[:4] != bv.REQUEST_MAGIC: + raise bv.ProtocolError("bad request envelope") request_id = struct.unpack_from(" _BinaryRequest: target_node = struct.unpack_from(" assertion_count: - raise smt.ProtocolError("named assertion count exceeds assertion count") + raise bv.ProtocolError("named assertion count exceeds assertion count") offset = REQUEST_HEADER_SIZE expected = ( @@ -518,16 +518,16 @@ def _parse_binary_request(payload: bytes) -> _BinaryRequest: + assumption_count * 4 ) if len(payload) != expected: - raise smt.ProtocolError("request length mismatch") + raise bv.ProtocolError("request length mismatch") expression = bytes(payload[offset : offset + expr_len]) offset += expr_len - ctx = smt.Context._from_expr_bytes(expression) + ctx = bv.Context._from_expr_bytes(expression) assertion_roots: list[int] = [] for _ in range(assertion_count): (root,) = struct.unpack_from(" _BinaryRequest: for _ in range(assumption_count): (root,) = struct.unpack_from(" _BinaryRequest: def _expect_ref( - ctx: smt.Context, ref: int, expected_sort: Optional[smt.Sort], context: str + ctx: bv.Context, ref: int, expected_sort: Optional[bv.Sort], context: str ) -> None: try: meta = ctx._meta_for_ref(ref) - except smt.SmtError as exc: - raise smt.ProtocolError(f"bad {context}: {exc}") from exc + except bv.SmtError as exc: + raise bv.ProtocolError(f"bad {context}: {exc}") from exc if expected_sort is not None and meta.sort is not expected_sort: - raise smt.ProtocolError( + raise bv.ProtocolError( f"bad {context}: expected {expected_sort.value}, got {meta.sort.value}" ) -def _blob_bytes(ctx: smt.Context, offset: int, length: int, context: str) -> bytes: +def _blob_bytes(ctx: bv.Context, offset: int, length: int, context: str) -> bytes: if offset > len(ctx._blob) or length > len(ctx._blob) - offset: - raise smt.ProtocolError(f"{context} blob reference out of range") + raise bv.ProtocolError(f"{context} blob reference out of range") return bytes(ctx._blob[offset : offset + length]) @@ -620,82 +620,82 @@ def _translate(request: _BinaryRequest, z3: Any) -> _Z3Translation: for index, node in enumerate(ctx._nodes): _validate_node_shape(node) tag = node.tag - if tag is smt.Op.BV_VAR: + if tag is bv.Op.BV_VAR: name = _node_blob(ctx, node, "BV variable").decode("utf-8") term = bv_vars.get((name, node.width)) if term is None: term = z3.BitVec(f"bv_{index}", node.width, ctx=z3_ctx) bv_vars[(name, node.width)] = term - out.variables.append(_Z3Variable(_bv_ref(index), smt.Sort.BV, node.width)) + out.variables.append(_Z3Variable(_bv_ref(index), bv.Sort.BV, node.width)) out.bvs[index] = term - elif tag is smt.Op.BV_CONST: + elif tag is bv.Op.BV_CONST: out.bvs[index] = _z3_bv_const(ctx, node, z3, z3_ctx) - elif tag is smt.Op.BV_NOT: + elif tag is bv.Op.BV_NOT: x = _child_bv(ctx, out, node, 0) out.bvs[index] = ~x - elif tag is smt.Op.BV_NEG: + elif tag is bv.Op.BV_NEG: x = _child_bv(ctx, out, node, 0) out.bvs[index] = -x - elif tag is smt.Op.BV_AND: + elif tag is bv.Op.BV_AND: a, b = _child_bv2(ctx, out, node) out.bvs[index] = a & b - elif tag is smt.Op.BV_OR: + elif tag is bv.Op.BV_OR: a, b = _child_bv2(ctx, out, node) out.bvs[index] = a | b - elif tag is smt.Op.BV_XOR: + elif tag is bv.Op.BV_XOR: a, b = _child_bv2(ctx, out, node) out.bvs[index] = a ^ b - elif tag is smt.Op.BV_ADD: + elif tag is bv.Op.BV_ADD: a, b = _child_bv2(ctx, out, node) out.bvs[index] = a + b - elif tag is smt.Op.BV_SUB: + elif tag is bv.Op.BV_SUB: a, b = _child_bv2(ctx, out, node) out.bvs[index] = a - b - elif tag is smt.Op.BV_MUL: + elif tag is bv.Op.BV_MUL: a, b = _child_bv2(ctx, out, node) out.bvs[index] = a * b - elif tag is smt.Op.BV_UDIV: + elif tag is bv.Op.BV_UDIV: a, b = _child_bv2(ctx, out, node) out.bvs[index] = z3.UDiv(a, b) - elif tag is smt.Op.BV_UREM: + elif tag is bv.Op.BV_UREM: a, b = _child_bv2(ctx, out, node) out.bvs[index] = z3.URem(a, b) - elif tag is smt.Op.BV_SDIV: + elif tag is bv.Op.BV_SDIV: a, b = _child_bv2(ctx, out, node) out.bvs[index] = a / b - elif tag is smt.Op.BV_SREM: + elif tag is bv.Op.BV_SREM: a, b = _child_bv2(ctx, out, node) out.bvs[index] = z3.SRem(a, b) - elif tag is smt.Op.BV_SMOD: + elif tag is bv.Op.BV_SMOD: a, b = _child_bv2(ctx, out, node) out.bvs[index] = _bvsmod(a, b, z3) - elif tag is smt.Op.BV_SHL: + elif tag is bv.Op.BV_SHL: a, b = _child_bv2(ctx, out, node) out.bvs[index] = a << b - elif tag is smt.Op.BV_LSHR: + elif tag is bv.Op.BV_LSHR: a, b = _child_bv2(ctx, out, node) out.bvs[index] = z3.LShR(a, b) - elif tag is smt.Op.BV_ASHR: + elif tag is bv.Op.BV_ASHR: a, b = _child_bv2(ctx, out, node) out.bvs[index] = a >> b - elif tag is smt.Op.BV_EXTRACT: + elif tag is bv.Op.BV_EXTRACT: x = _child_bv(ctx, out, node, 0) out.bvs[index] = z3.Extract(node.aux_hi, node.aux_lo, x) - elif tag is smt.Op.BV_CONCAT: + elif tag is bv.Op.BV_CONCAT: a, b = _child_bv2(ctx, out, node) out.bvs[index] = z3.Concat(a, b) - elif tag is smt.Op.BV_ZEXT: + elif tag is bv.Op.BV_ZEXT: x = _child_bv(ctx, out, node, 0) out.bvs[index] = z3.ZeroExt(node.aux_hi, x) - elif tag is smt.Op.BV_SEXT: + elif tag is bv.Op.BV_SEXT: x = _child_bv(ctx, out, node, 0) out.bvs[index] = z3.SignExt(node.aux_hi, x) - elif tag is smt.Op.BV_ITE: + elif tag is bv.Op.BV_ITE: c = _child_bool(ctx, out, node, 0) t = _child_bv(ctx, out, node, 1) e = _child_bv(ctx, out, node, 2) out.bvs[index] = z3.If(c, t, e) - elif tag is smt.Op.BV_SELECT: + elif tag is bv.Op.BV_SELECT: pairs = node.aux_hi result = _child_bv(ctx, out, node, pairs * 2) for pair in range(pairs - 1, -1, -1): @@ -703,140 +703,140 @@ def _translate(request: _BinaryRequest, z3: Any) -> _Z3Translation: value = _child_bv(ctx, out, node, pair * 2 + 1) result = z3.If(selector, value, result) out.bvs[index] = result - elif tag is smt.Op.BOOL_TRUE: + elif tag is bv.Op.BOOL_TRUE: out.bools[index] = z3.BoolVal(True, ctx=z3_ctx) - elif tag is smt.Op.BOOL_FALSE: + elif tag is bv.Op.BOOL_FALSE: out.bools[index] = z3.BoolVal(False, ctx=z3_ctx) - elif tag is smt.Op.BOOL_VAR: + elif tag is bv.Op.BOOL_VAR: name = _node_blob(ctx, node, "Bool variable").decode("utf-8") term = bool_vars.get(name) if term is None: term = z3.Bool(f"bool_{index}", ctx=z3_ctx) bool_vars[name] = term - out.variables.append(_Z3Variable(_bool_ref(index), smt.Sort.BOOL, 0)) + out.variables.append(_Z3Variable(_bool_ref(index), bv.Sort.BOOL, 0)) out.bools[index] = term - elif tag is smt.Op.BOOL_NOT: + elif tag is bv.Op.BOOL_NOT: x = _child_bool(ctx, out, node, 0) out.bools[index] = z3.Not(x) - elif tag is smt.Op.BOOL_AND: + elif tag is bv.Op.BOOL_AND: a, b = _child_bool2(ctx, out, node) out.bools[index] = z3.And(a, b) - elif tag is smt.Op.BOOL_OR: + elif tag is bv.Op.BOOL_OR: a, b = _child_bool2(ctx, out, node) out.bools[index] = z3.Or(a, b) - elif tag is smt.Op.BOOL_IMPLIES: + elif tag is bv.Op.BOOL_IMPLIES: a, b = _child_bool2(ctx, out, node) out.bools[index] = z3.Implies(a, b) - elif tag is smt.Op.BV_EQ: + elif tag is bv.Op.BV_EQ: a, b = _child_bv2(ctx, out, node) out.bools[index] = a == b - elif tag is smt.Op.BV_ULT: + elif tag is bv.Op.BV_ULT: a, b = _child_bv2(ctx, out, node) out.bools[index] = z3.ULT(a, b) - elif tag is smt.Op.BV_ULE: + elif tag is bv.Op.BV_ULE: a, b = _child_bv2(ctx, out, node) out.bools[index] = z3.ULE(a, b) - elif tag is smt.Op.BV_SLT: + elif tag is bv.Op.BV_SLT: a, b = _child_bv2(ctx, out, node) out.bools[index] = a < b - elif tag is smt.Op.BV_SLE: + elif tag is bv.Op.BV_SLE: a, b = _child_bv2(ctx, out, node) out.bools[index] = a <= b - elif tag is smt.Op.UADD_OVF: + elif tag is bv.Op.UADD_OVF: a, b = _child_bv2(ctx, out, node) out.bools[index] = z3.ULT(a + b, a) - elif tag is smt.Op.SADD_OVF: + elif tag is bv.Op.SADD_OVF: a, b = _child_bv2(ctx, out, node) out.bools[index] = _signed_add_overflow(a, b, z3) - elif tag is smt.Op.USUB_OVF: + elif tag is bv.Op.USUB_OVF: a, b = _child_bv2(ctx, out, node) out.bools[index] = z3.ULT(a, b) - elif tag is smt.Op.SSUB_OVF: + elif tag is bv.Op.SSUB_OVF: a, b = _child_bv2(ctx, out, node) out.bools[index] = _signed_sub_overflow(a, b, z3) - elif tag is smt.Op.UMUL_OVF: + elif tag is bv.Op.UMUL_OVF: a, b = _child_bv2(ctx, out, node) out.bools[index] = _unsigned_mul_overflow(a, b, z3) - elif tag is smt.Op.SMUL_OVF: + elif tag is bv.Op.SMUL_OVF: a, b = _child_bv2(ctx, out, node) out.bools[index] = _signed_mul_overflow(a, b, z3) - elif tag is smt.Op.NEG_OVF: + elif tag is bv.Op.NEG_OVF: a = _child_bv(ctx, out, node, 0) out.bools[index] = a == _signed_min_bv(a.size(), z3, z3_ctx) - elif tag is smt.Op.SDIV_OVF: + elif tag is bv.Op.SDIV_OVF: a, b = _child_bv2(ctx, out, node) out.bools[index] = z3.And( a == _signed_min_bv(a.size(), z3, z3_ctx), b == _ones_bv(b.size(), z3, z3_ctx), ) else: # pragma: no cover - Op enum should cover all tags - raise smt.ProtocolError(f"unsupported operation {tag}") + raise bv.ProtocolError(f"unsupported operation {tag}") return out -def _validate_node_shape(node: smt.Node) -> None: +def _validate_node_shape(node: bv.Node) -> None: tag = node.tag - result_sort = smt.Sort.BV if tag <= smt.Op.BV_SELECT else smt.Sort.BOOL - if result_sort is smt.Sort.BOOL and node.width != 0: - raise smt.ProtocolError(f"Bool node {tag.name} has non-zero width") - if result_sort is smt.Sort.BV and not 1 <= node.width <= smt.MAX_WIDTH: - raise smt.ProtocolError(f"BV node {tag.name} has invalid width {node.width}") + result_sort = bv.Sort.BV if tag <= bv.Op.BV_SELECT else bv.Sort.BOOL + if result_sort is bv.Sort.BOOL and node.width != 0: + raise bv.ProtocolError(f"Bool node {tag.name} has non-zero width") + if result_sort is bv.Sort.BV and not 1 <= node.width <= bv.MAX_WIDTH: + raise bv.ProtocolError(f"BV node {tag.name} has invalid width {node.width}") expected: Optional[int] - if tag in (smt.Op.BV_VAR, smt.Op.BV_CONST, smt.Op.BOOL_TRUE, smt.Op.BOOL_FALSE, smt.Op.BOOL_VAR): + if tag in (bv.Op.BV_VAR, bv.Op.BV_CONST, bv.Op.BOOL_TRUE, bv.Op.BOOL_FALSE, bv.Op.BOOL_VAR): expected = 0 elif tag in ( - smt.Op.BV_NOT, - smt.Op.BV_NEG, - smt.Op.BV_EXTRACT, - smt.Op.BV_ZEXT, - smt.Op.BV_SEXT, - smt.Op.BOOL_NOT, - smt.Op.NEG_OVF, + bv.Op.BV_NOT, + bv.Op.BV_NEG, + bv.Op.BV_EXTRACT, + bv.Op.BV_ZEXT, + bv.Op.BV_SEXT, + bv.Op.BOOL_NOT, + bv.Op.NEG_OVF, ): expected = 1 - elif tag is smt.Op.BV_ITE: + elif tag is bv.Op.BV_ITE: expected = 3 - elif tag is smt.Op.BV_SELECT: + elif tag is bv.Op.BV_SELECT: expected = node.aux_hi * 2 + 1 else: expected = 2 if node.arity != expected: - raise smt.ProtocolError( + raise bv.ProtocolError( f"node {tag.name} has arity {node.arity}, expected {expected}" ) - if tag is smt.Op.BV_EXTRACT and node.aux_lo > node.aux_hi: - raise smt.ProtocolError("extract low bit exceeds high bit") + if tag is bv.Op.BV_EXTRACT and node.aux_lo > node.aux_hi: + raise bv.ProtocolError("extract low bit exceeds high bit") -def _child_ref(ctx: smt.Context, node: smt.Node, offset: int) -> int: +def _child_ref(ctx: bv.Context, node: bv.Node, offset: int) -> int: if offset >= node.arity: - raise smt.ProtocolError(f"child offset {offset} exceeds arity {node.arity}") + raise bv.ProtocolError(f"child offset {offset} exceeds arity {node.arity}") return ctx._children[node.children + offset] -def _child_bv(ctx: smt.Context, translation: _Z3Translation, node: smt.Node, offset: int) -> Any: +def _child_bv(ctx: bv.Context, translation: _Z3Translation, node: bv.Node, offset: int) -> Any: return translation.bv(_child_ref(ctx, node, offset)) -def _child_bool(ctx: smt.Context, translation: _Z3Translation, node: smt.Node, offset: int) -> Any: +def _child_bool(ctx: bv.Context, translation: _Z3Translation, node: bv.Node, offset: int) -> Any: return translation.bool(_child_ref(ctx, node, offset)) -def _child_bv2(ctx: smt.Context, translation: _Z3Translation, node: smt.Node) -> tuple[Any, Any]: +def _child_bv2(ctx: bv.Context, translation: _Z3Translation, node: bv.Node) -> tuple[Any, Any]: return _child_bv(ctx, translation, node, 0), _child_bv(ctx, translation, node, 1) -def _child_bool2(ctx: smt.Context, translation: _Z3Translation, node: smt.Node) -> tuple[Any, Any]: +def _child_bool2(ctx: bv.Context, translation: _Z3Translation, node: bv.Node) -> tuple[Any, Any]: return _child_bool(ctx, translation, node, 0), _child_bool(ctx, translation, node, 1) -def _node_blob(ctx: smt.Context, node: smt.Node, context: str) -> bytes: +def _node_blob(ctx: bv.Context, node: bv.Node, context: str) -> bytes: offset, length = _blob_ref(node.payload) return _blob_bytes(ctx, offset, length, context) -def _z3_bv_const(ctx: smt.Context, node: smt.Node, z3: Any, z3_ctx: Any) -> Any: +def _z3_bv_const(ctx: bv.Context, node: bv.Node, z3: Any, z3_ctx: Any) -> Any: if node.width <= 64: mask = (1 << node.width) - 1 if node.width < 64 else (1 << 64) - 1 value = node.payload & mask @@ -844,7 +844,7 @@ def _z3_bv_const(ctx: smt.Context, node: smt.Node, z3: Any, z3_ctx: Any) -> Any: data = _node_blob(ctx, node, "wide BV constant") expected = _bytes_for_width(node.width) if len(data) != expected: - raise smt.ProtocolError("wide BV constant length does not match width") + raise bv.ProtocolError("wide BV constant length does not match width") value = int.from_bytes(data, "little") return z3.BitVecVal(value, node.width, ctx=z3_ctx) @@ -940,7 +940,7 @@ def _encode_model(translation: _Z3Translation, model: Any) -> bytes: entries = bytearray(struct.pack(" bytes: def _encode_scalar_bv(width: int, data: bytes) -> bytes: expected = _bytes_for_width(width) if len(data) != expected: - raise smt.ProtocolError("BV scalar length does not match width") + raise bv.ProtocolError("BV scalar length does not match width") return struct.pack(" bytes: struct.pack(" bytes: if message: return _response( request_id, - smt.Status.UNKNOWN, + bv.Status.UNKNOWN, RESP_HAS_MESSAGE, message.encode("utf-8"), ) - return _response(request_id, smt.Status.UNKNOWN, 0, b"") + return _response(request_id, bv.Status.UNKNOWN, 0, b"") def _error_response(request_id: int, message: str) -> bytes: return _response( request_id, - smt.Status.ERROR, + bv.Status.ERROR, RESP_HAS_MESSAGE, message.encode("utf-8", "replace"), ) -def _response(request_id: int, status: smt.Status, flags: int, payload: bytes) -> bytes: +def _response(request_id: int, status: bv.Status, flags: int, payload: bytes) -> bytes: if len(payload) > 0xFFFFFFFF: - raise smt.ProtocolError("response payload too large") + raise bv.ProtocolError("response payload too large") return ( - smt.RESPONSE_MAGIC + bv.RESPONSE_MAGIC + struct.pack(" bytes: if len(payload) > 0xFFFFFFFF: - raise smt.ProtocolError("frame payload too large") + raise bv.ProtocolError("frame payload too large") return struct.pack(" None: def main(argv: Optional[list[str]] = None) -> int: - parser = argparse.ArgumentParser(description="Run the experimental Python Z3 SMT server") - parser.add_argument("--host", default=smt.DEFAULT_SERVER_HOST) + parser = argparse.ArgumentParser(description="Run the experimental Python Z3 bv-server") + parser.add_argument("--host", default=bv.DEFAULT_SERVER_HOST) parser.add_argument("--port", type=int, default=0) parser.add_argument("--max-frame-bytes", type=int, default=DEFAULT_MAX_FRAME_BYTES) parser.add_argument("--max-response-bytes", type=int, default=DEFAULT_MAX_RESPONSE_BYTES) diff --git a/python/example.py b/python/example.py index a8c44e7..5f49849 100644 --- a/python/example.py +++ b/python/example.py @@ -1,7 +1,7 @@ -import smt_wire as smt +import bv_wire as bv -ctx = smt.Context() +ctx = bv.Context() print(ctx) # Context#1, Context#2, ... x = ctx.bv_var("x", 32) @@ -26,11 +26,11 @@ # A visitor can lower a returned/simplified DAG into your own IR. This one # prints a small reverse Polish notation string for the MBA expression. -def to_rpn(term: smt.Term, args: tuple[str, ...]) -> str: - if term.op is smt.Op.BV_VAR: +def to_rpn(term: bv.Term, args: tuple[str, ...]) -> str: + if term.op is bv.Op.BV_VAR: return term.name - if term.op is smt.Op.BV_CONST: - assert isinstance(term, smt.BVTerm) + if term.op is bv.Op.BV_CONST: + assert isinstance(term, bv.BVTerm) return f"{term.value}:{term.width}" return " ".join((*args, term.op.symbol)) @@ -38,11 +38,11 @@ def to_rpn(term: smt.Term, args: tuple[str, ...]) -> str: print("RPN:", mba.visit(to_rpn)) # Start the server first: -# cargo run -p smt-server -- 127.0.0.1:9123 -with smt.Client() as client: +# cargo run -p bv-server -- 127.0.0.1:9123 +with bv.Client() as client: resp = client.solve(ctx) print(resp.status) - if resp.status is smt.Status.SAT and resp.model is not None: + if resp.status is bv.Status.SAT and resp.model is not None: for var, value in resp.model.items(): print(f"{var.name} = {hex(int(value))}") @@ -55,6 +55,6 @@ def to_rpn(term: smt.Term, args: tuple[str, ...]) -> str: ctx_smt2 = ctx.to_smt2() print(ctx_smt2) -with smt.Client() as client: +with bv.Client() as client: smt_resp = client.smt2(ctx_smt2) print(smt_resp) \ No newline at end of file diff --git a/python/pyproject.toml b/python/pyproject.toml index dd2f0ff..51fbef6 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -3,13 +3,13 @@ requires = ["setuptools>=61"] build-backend = "setuptools.build_meta" [project] -name = "smt-wire" +name = "bv-wire" version = "0.1.0" -description = "Typed Python client for the SMT v1 wire protocol" +description = "Typed Python client for the bv-wire v1 protocol" readme = "README.md" requires-python = ">=3.10" license = { text = "MIT OR Apache-2.0" } -authors = [{ name = "SMT Server contributors" }] +authors = [{ name = "bv-server contributors" }] classifiers = [ "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", @@ -23,4 +23,4 @@ z3 = [ ] [tool.setuptools] -py-modules = ["smt_wire", "smt_z3_server"] +py-modules = ["bv_wire", "bv_z3_server"] diff --git a/python/tests/test_live_server.py b/python/tests/test_live_server.py index 45e1a32..539e487 100644 --- a/python/tests/test_live_server.py +++ b/python/tests/test_live_server.py @@ -1,4 +1,4 @@ -"""Live end-to-end tests against the smt-server binary. +"""Live end-to-end tests against the bv-server binary. This intentionally uses only the standard library plus the local Python client module so it can run directly in CI without pytest. @@ -16,7 +16,7 @@ PYTHON_ROOT = REPO_ROOT / "python" sys.path.insert(0, str(PYTHON_ROOT)) -import smt_wire as smt # noqa: E402 +import bv_wire as bv # noqa: E402 def unused_local_port() -> int: @@ -26,8 +26,8 @@ def unused_local_port() -> int: def server_binary() -> pathlib.Path: - subprocess.check_call(["cargo", "build", "-p", "smt-server"], cwd=REPO_ROOT) - exe = "smt-server.exe" if os.name == "nt" else "smt-server" + subprocess.check_call(["cargo", "build", "-p", "bv-server"], cwd=REPO_ROOT) + exe = "bv-server.exe" if os.name == "nt" else "bv-server" return REPO_ROOT / "target" / "debug" / exe @@ -65,14 +65,14 @@ def __enter__(self) -> "LiveServer": while time.time() < deadline: if self.proc.poll() is not None: stderr = self.proc.stderr.read().decode("utf-8", "replace") if self.proc.stderr else "" - raise RuntimeError(f"smt-server exited early with {self.proc.returncode}: {stderr}") + raise RuntimeError(f"bv-server exited early with {self.proc.returncode}: {stderr}") try: with socket.create_connection(("127.0.0.1", self.port), timeout=0.2): return self except OSError as exc: last_error = exc time.sleep(0.05) - raise TimeoutError(f"smt-server did not listen on port {self.port}: {last_error}") + raise TimeoutError(f"bv-server did not listen on port {self.port}: {last_error}") def __exit__(self, *exc_info: object) -> None: if self.proc is None: @@ -86,33 +86,33 @@ def __exit__(self, *exc_info: object) -> None: def test_python_client_env_default_round_trip(port: int) -> None: - old = os.environ.get(smt.SERVER_ADDRESS_ENV) - os.environ[smt.SERVER_ADDRESS_ENV] = f"127.0.0.1:{port}" + old = os.environ.get(bv.SERVER_ADDRESS_ENV) + os.environ[bv.SERVER_ADDRESS_ENV] = f"127.0.0.1:{port}" try: - with smt.Client(timeout=5) as client: + with bv.Client(timeout=5) as client: test_python_client_binary_round_trip(client) finally: if old is None: - os.environ.pop(smt.SERVER_ADDRESS_ENV, None) + os.environ.pop(bv.SERVER_ADDRESS_ENV, None) else: - os.environ[smt.SERVER_ADDRESS_ENV] = old + os.environ[bv.SERVER_ADDRESS_ENV] = old -def test_python_client_binary_round_trip(client: smt.Client) -> None: - ctx = smt.Context() +def test_python_client_binary_round_trip(client: bv.Client) -> None: + ctx = bv.Context() x = ctx.bv_var("x", 4) ctx.assert_(ctx.bv_eq(x, 2)) response = client.solve(ctx, request_id=0x1001) assert response.request_id == 0x1001 - assert response.status is smt.Status.SAT + assert response.status is bv.Status.SAT assert response.model is not None assert response.model[x].width == 4 assert response.model[x].as_int() == 2 -def test_binary_cache_rebinds_response_ids(client: smt.Client) -> None: - ctx = smt.Context() +def test_binary_cache_rebinds_response_ids(client: bv.Client) -> None: + ctx = bv.Context() x = ctx.bv_var("cached", 3) ctx.assert_(ctx.bv_eq(x, 5)) @@ -120,25 +120,25 @@ def test_binary_cache_rebinds_response_ids(client: smt.Client) -> None: second = client.solve(ctx, request_id=0x2002) assert first.request_id == 0x2001 assert second.request_id == 0x2002 - assert first.status is smt.Status.SAT - assert second.status is smt.Status.SAT + assert first.status is bv.Status.SAT + assert second.status is bv.Status.SAT -def test_python_client_optimization_round_trip(client: smt.Client) -> None: - ctx = smt.Context() +def test_python_client_optimization_round_trip(client: bv.Client) -> None: + ctx = bv.Context() x = ctx.bv_var("opt", 4) ctx.assert_(ctx.bv_uge(x, 5)) result = client.minimize(x, request_id=0x3001) assert result.request_id == 0x3001 - assert result.status is smt.Status.SAT + assert result.status is bv.Status.SAT assert result.optimum is not None assert result.optimum.width == 4 assert result.optimum.as_int() == 5 assert result.model is not None -def test_text_smtlib_round_trip(client: smt.Client) -> None: +def test_text_smtlib_round_trip(client: bv.Client) -> None: script = """ #| yaspar parses this block comment in the live text path |# (set-logic QF_BV) @@ -155,7 +155,7 @@ def test_text_smtlib_round_trip(client: smt.Client) -> None: def main() -> None: with LiveServer() as server: test_python_client_env_default_round_trip(server.port) - with smt.Client("127.0.0.1", server.port, timeout=5) as client: + with bv.Client("127.0.0.1", server.port, timeout=5) as client: test_python_client_binary_round_trip(client) test_binary_cache_rebinds_response_ids(client) test_python_client_optimization_round_trip(client) diff --git a/python/tests/test_python_client.py b/python/tests/test_python_client.py index b049aaf..174f594 100644 --- a/python/tests/test_python_client.py +++ b/python/tests/test_python_client.py @@ -5,7 +5,7 @@ ROOT = pathlib.Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) -import smt_wire as smt +import bv_wire as bv def hex_bytes(s: str) -> bytes: @@ -13,7 +13,7 @@ def hex_bytes(s: str) -> bytes: def test_python_client_matches_simple_sat_golden_vector(): - ctx = smt.Context() + ctx = bv.Context() x = ctx.bv_var("x", 8) one = ctx.bv_const(1, 8) ctx.assert_(ctx.bv_eq(x, one)) @@ -28,106 +28,106 @@ def test_python_client_matches_simple_sat_golden_vector(): def test_default_server_address_uses_environment(): - old = os.environ.get(smt.SERVER_ADDRESS_ENV) + old = os.environ.get(bv.SERVER_ADDRESS_ENV) try: - os.environ.pop(smt.SERVER_ADDRESS_ENV, None) - assert smt.default_server_address() == ("127.0.0.1", 9123) - os.environ[smt.SERVER_ADDRESS_ENV] = "example.com:1234" - assert smt.default_server_address() == ("example.com", 1234) - os.environ[smt.SERVER_ADDRESS_ENV] = "[::1]:9123" - assert smt.default_server_address() == ("::1", 9123) - os.environ[smt.SERVER_ADDRESS_ENV] = "missing-port" + os.environ.pop(bv.SERVER_ADDRESS_ENV, None) + assert bv.default_server_address() == ("127.0.0.1", 9123) + os.environ[bv.SERVER_ADDRESS_ENV] = "example.com:1234" + assert bv.default_server_address() == ("example.com", 1234) + os.environ[bv.SERVER_ADDRESS_ENV] = "[::1]:9123" + assert bv.default_server_address() == ("::1", 9123) + os.environ[bv.SERVER_ADDRESS_ENV] = "missing-port" try: - smt.default_server_address() + bv.default_server_address() raise AssertionError("expected bad server address to be rejected") except ValueError: pass finally: if old is None: - os.environ.pop(smt.SERVER_ADDRESS_ENV, None) + os.environ.pop(bv.SERVER_ADDRESS_ENV, None) else: - os.environ[smt.SERVER_ADDRESS_ENV] = old + os.environ[bv.SERVER_ADDRESS_ENV] = old def test_context_ids_and_repr_are_debug_friendly(): - a = smt.Context() - b = smt.Context() + a = bv.Context() + b = bv.Context() assert b.id == a.id + 1 assert str(a) == f"Context#{a.id}" assert repr(a).startswith(f"Context#{a.id}(nodes=0, assertions=0)") def test_int_enums_print_symbolically(): - assert str(smt.Status.SAT) == "Status.SAT" - assert f"{smt.Status.SIMPLIFIED}" == "Status.SIMPLIFIED" - assert str(smt.Op.BV_ADD) == "Op.BV_ADD" - assert str(smt.Command.SOLVE) == "Command.SOLVE" - assert str(smt.ResponseFlag.HAS_MODEL) == "ResponseFlag.HAS_MODEL" - assert str(smt.ResponseFlag.HAS_MODEL | smt.ResponseFlag.HAS_VALUE) == "ResponseFlag.HAS_MODEL|HAS_VALUE" + assert str(bv.Status.SAT) == "Status.SAT" + assert f"{bv.Status.SIMPLIFIED}" == "Status.SIMPLIFIED" + assert str(bv.Op.BV_ADD) == "Op.BV_ADD" + assert str(bv.Command.SOLVE) == "Command.SOLVE" + assert str(bv.ResponseFlag.HAS_MODEL) == "ResponseFlag.HAS_MODEL" + assert str(bv.ResponseFlag.HAS_MODEL | bv.ResponseFlag.HAS_VALUE) == "ResponseFlag.HAS_MODEL|HAS_VALUE" def test_terms_use_handle_equality_and_hashing(): - ctx = smt.Context() + ctx = bv.Context() x = ctx.bv_var("x", 8) assert x == ctx.bv_var("x", 8) - assert x != smt.Context().bv_var("x", 8) + assert x != bv.Context().bv_var("x", 8) assert {x, ctx.bv_var("x", 8)} == {x} def test_terms_validate_width_sort_and_context(): - ctx = smt.Context() + ctx = bv.Context() a = ctx.bv_var("a", 8) c = ctx.bv_var("c", 16) assert ctx.bv_var("a", 8) is a try: ctx.bv_var("a", 16) raise AssertionError("expected symbol width error") - except smt.SortError: + except bv.SortError: pass try: ctx.bool_var("a") raise AssertionError("expected symbol sort error") - except smt.SortError: + except bv.SortError: pass p = ctx.bool_var("p") assert ctx.bool_var("p") is p assert not hasattr(a, "add") assert not hasattr(p, "and_") rotated = ctx.bv_rotate_left(a, 3) - assert isinstance(rotated, smt.BVTerm) + assert isinstance(rotated, bv.BVTerm) assert ctx._build_minimize_request(3, a, signed=True, want_model=True).payload.startswith(b"SMTQ") try: a + c raise AssertionError("expected width error") - except smt.WidthMismatchError: + except bv.WidthMismatchError: pass - assert isinstance(a + 1, smt.BVTerm) - assert isinstance(0xFF & a, smt.BVTerm) + assert isinstance(a + 1, bv.BVTerm) + assert isinstance(0xFF & a, bv.BVTerm) try: a + True # type: ignore[operator] raise AssertionError("expected bool coercion error") - except smt.SortError: + except bv.SortError: pass try: True + a # type: ignore[operator] raise AssertionError("expected bool coercion error") - except smt.SortError: + except bv.SortError: pass try: ctx.bool_and(p, a) # type: ignore[arg-type] raise AssertionError("expected sort error") - except smt.SortError: + except bv.SortError: pass - other = smt.Context().bv_var("other", 8) + other = bv.Context().bv_var("other", 8) try: a + other raise AssertionError("expected context error") - except smt.ContextMismatchError: + except bv.ContextMismatchError: pass def test_to_smt2_depth_limited_rendering(): - ctx = smt.Context() + ctx = bv.Context() x = ctx.bv_var("x", 32) y = ctx.bv_var("y", 32) mba = (x ^ y) + (ctx.bv_const(2, 32) * (x & y)) @@ -142,7 +142,7 @@ def test_to_smt2_depth_limited_rendering(): def test_context_to_smt2_renders_self_contained_script(): - ctx = smt.Context() + ctx = bv.Context() x = ctx.bv_var("x y", 8) p = ctx.bool_var("p") named = ctx.bool_or(p, ctx.bv_eq(x, 42)) @@ -165,14 +165,14 @@ def test_context_to_smt2_renders_self_contained_script(): def test_to_smt2_quotes_symbols_and_formats_non_nibble_constants(): - ctx = smt.Context() + ctx = bv.Context() weird = ctx.bv_var("x y", 3) expr = weird + 5 assert expr.to_smt2(depth=-1) == "(bvadd |x y| #b101) ; #2" def test_to_smt2_renders_parameterized_bv_ops(): - ctx = smt.Context() + ctx = bv.Context() x = ctx.bv_var("x", 16) low = ctx.bv_extract(x, 7, 0) assert low.to_smt2(depth=-1) == "((_ extract 7 0) x) ; #1" @@ -182,7 +182,7 @@ def test_to_smt2_renders_parameterized_bv_ops(): def test_python_ints_are_coerced_to_bv_constants(): - ctx = smt.Context() + ctx = bv.Context() x = ctx.bv_var("x", 8) expr = (0xFF & x) + 3 assert expr.to_smt2(depth=-1) == "(bvadd (bvand x #xff) #x03) ; #4" @@ -191,22 +191,22 @@ def test_python_ints_are_coerced_to_bv_constants(): def test_term_visit_lowers_result_dag_shape(): - ctx = smt.Context() + ctx = bv.Context() x = ctx.bv_var("x", 8) sub = x + 1 expr = sub * sub - assert int(smt.Op.BV_ADD) == 7 - assert smt.Op.BV_ADD.symbol == "bvadd" - assert [term.op for term in expr.walk()] == [smt.Op.BV_VAR, smt.Op.BV_CONST, smt.Op.BV_ADD, smt.Op.BV_MUL] + assert int(bv.Op.BV_ADD) == 7 + assert bv.Op.BV_ADD.symbol == "bvadd" + assert [term.op for term in expr.walk()] == [bv.Op.BV_VAR, bv.Op.BV_CONST, bv.Op.BV_ADD, bv.Op.BV_MUL] def lower(term, args): - if term.op is smt.Op.BV_VAR: + if term.op is bv.Op.BV_VAR: return f"var({term.name}:{term.width})" - if term.op is smt.Op.BV_CONST: + if term.op is bv.Op.BV_CONST: return f"const({term.value}:{term.width})" - if term.op is smt.Op.BV_ADD: + if term.op is bv.Op.BV_ADD: return f"add({args[0]}, {args[1]})" - if term.op is smt.Op.BV_MUL: + if term.op is bv.Op.BV_MUL: return f"mul({args[0]}, {args[1]})" raise AssertionError(term.op) @@ -215,7 +215,7 @@ def lower(term, args): def test_python_wide_integer_constant_uses_blob_encoding_and_masks_to_width(): - ctx = smt.Context() + ctx = bv.Context() ctx.bv_const((1 << 80) | (1 << 64) | 3, 65) expr = ctx._expr_bytes(ctx._nodes, ctx._children, ctx._blob) assert int.from_bytes(expr[16:20], "little") == 9 # blob_len @@ -224,22 +224,22 @@ def test_python_wide_integer_constant_uses_blob_encoding_and_masks_to_width(): def test_python_response_parser_and_model_mapping(): - response = b"SMTR" + (7).to_bytes(4, "little") + bytes([smt.Status.ERROR, 16]) + (3).to_bytes(4, "little") + b"\0\0bad" - parsed = smt._parse_response(response) + response = b"SMTR" + (7).to_bytes(4, "little") + bytes([bv.Status.ERROR, 16]) + (3).to_bytes(4, "little") + b"\0\0bad" + parsed = bv._parse_response(response) assert parsed.request_id == 7 - assert parsed.status is smt.Status.ERROR + assert parsed.status is bv.Status.ERROR assert parsed.payload == b"bad" assert parsed.message() == "bad" - ctx = smt.Context() + ctx = bv.Context() x = ctx.bv_var("x", 8) ctx.assert_(ctx.bv_eq(x, 42)) request = ctx._build_solve_request(8) compacted_x = request.old_to_new[x.id] scalar = (8).to_bytes(4, "little") + (1).to_bytes(4, "little") + b"*" model_payload = (1).to_bytes(4, "little") + compacted_x.to_bytes(4, "little") + scalar - raw = smt._parse_response(b"SMTR" + (8).to_bytes(4, "little") + bytes([smt.Status.SAT, 1]) + len(model_payload).to_bytes(4, "little") + b"\0\0" + model_payload) - client = smt.Client.from_socket(_FakeSocket.empty()) + raw = bv._parse_response(b"SMTR" + (8).to_bytes(4, "little") + bytes([bv.Status.SAT, 1]) + len(model_payload).to_bytes(4, "little") + b"\0\0" + model_payload) + client = bv.Client.from_socket(_FakeSocket.empty()) model = client._solve_response(raw, request).model assert model is not None assert model[x].width == 8 @@ -248,29 +248,29 @@ def test_python_response_parser_and_model_mapping(): assert hex(model[x]) == "0x2a" core_payload = (1).to_bytes(4, "little") + (2).to_bytes(4, "little") + b"a0" - assert smt._parse_core(core_payload) == ["a0"] + assert bv._parse_core(core_payload) == ["a0"] def test_python_response_parser_rejects_bad_status_flag_combinations(): - bad_error = b"SMTR" + (1).to_bytes(4, "little") + bytes([smt.Status.ERROR, 0]) + (0).to_bytes(4, "little") + b"\0\0" + bad_error = b"SMTR" + (1).to_bytes(4, "little") + bytes([bv.Status.ERROR, 0]) + (0).to_bytes(4, "little") + b"\0\0" try: - smt._parse_response(bad_error) + bv._parse_response(bad_error) raise AssertionError("expected bad ERROR response to be rejected") - except smt.ProtocolError: + except bv.ProtocolError: pass - bad_sat = b"SMTR" + (1).to_bytes(4, "little") + bytes([smt.Status.SAT, 2]) + (0).to_bytes(4, "little") + b"\0\0" + bad_sat = b"SMTR" + (1).to_bytes(4, "little") + bytes([bv.Status.SAT, 2]) + (0).to_bytes(4, "little") + b"\0\0" try: - smt._parse_response(bad_sat) + bv._parse_response(bad_sat) raise AssertionError("expected bad SAT flags to be rejected") - except smt.ProtocolError: + except bv.ProtocolError: pass - bad_simplified = b"SMTR" + (1).to_bytes(4, "little") + bytes([smt.Status.SIMPLIFIED, 0]) + (0).to_bytes(4, "little") + b"\0\0" + bad_simplified = b"SMTR" + (1).to_bytes(4, "little") + bytes([bv.Status.SIMPLIFIED, 0]) + (0).to_bytes(4, "little") + b"\0\0" try: - smt._parse_response(bad_simplified) + bv._parse_response(bad_simplified) raise AssertionError("expected bad SIMPLIFIED flags to be rejected") - except smt.ProtocolError: + except bv.ProtocolError: pass @@ -301,12 +301,12 @@ def settimeout(self, timeout): def test_python_client_rejects_oversized_response_before_allocation(): - client = smt.Client.from_socket(_FakeSocket((1024).to_bytes(4, "little"))) + client = bv.Client.from_socket(_FakeSocket((1024).to_bytes(4, "little"))) client.set_max_response_bytes(8) try: client._send_payload(b"x") raise AssertionError("expected oversized response frame to be rejected") - except smt.ProtocolError: + except bv.ProtocolError: pass diff --git a/python/tests/test_z3_server.py b/python/tests/test_z3_server.py index 6e7cc1c..5d7046a 100644 --- a/python/tests/test_z3_server.py +++ b/python/tests/test_z3_server.py @@ -8,8 +8,8 @@ ROOT = pathlib.Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) -import smt_wire as smt # noqa: E402 -from smt_z3_server import Z3Server # noqa: E402 +import bv_wire as bv # noqa: E402 +from bv_z3_server import Z3Server # noqa: E402 def test_z3_server_uses_random_tcp_port() -> None: @@ -21,7 +21,7 @@ def test_z3_server_uses_random_tcp_port() -> None: def test_z3_server_simple_sat_model_round_trip() -> None: with Z3Server.start(port=0) as server: - ctx = smt.Context() + ctx = bv.Context() x = ctx.bv_var("x", 4) ctx.assert_(ctx.bv_eq(x, 2)) @@ -29,14 +29,14 @@ def test_z3_server_simple_sat_model_round_trip() -> None: response = client.solve(ctx, request_id=0xA001) assert response.request_id == 0xA001 - assert response.status is smt.Status.SAT + assert response.status is bv.Status.SAT assert response.model is not None assert response.model[x].as_int() == 2 def test_z3_server_unsat_core_round_trip() -> None: with Z3Server.start(port=0) as server: - ctx = smt.Context() + ctx = bv.Context() x = ctx.bv_var("x", 4) ctx.assert_named("x_is_1", ctx.bv_eq(x, 1)) ctx.assert_named("x_is_2", ctx.bv_eq(x, 2)) @@ -44,14 +44,14 @@ def test_z3_server_unsat_core_round_trip() -> None: with server.client(timeout=5) as client: response = client.solve(ctx, want_model=False, want_core=True) - assert response.status is smt.Status.UNSAT + assert response.status is bv.Status.UNSAT assert response.core is not None assert set(response.core) == {"x_is_1", "x_is_2"} def test_z3_server_assumptions_affect_solve() -> None: with Z3Server.start(port=0) as server: - ctx = smt.Context() + ctx = bv.Context() p = ctx.bool_var("p") ctx.assume(p) ctx.assert_(ctx.bool_not(p)) @@ -59,12 +59,12 @@ def test_z3_server_assumptions_affect_solve() -> None: with server.client(timeout=5) as client: response = client.solve(ctx, want_model=False) - assert response.status is smt.Status.UNSAT + assert response.status is bv.Status.UNSAT def test_z3_server_simplify_is_noop_but_protocol_compatible() -> None: with Z3Server.start(port=0) as server: - ctx = smt.Context() + ctx = bv.Context() x = ctx.bv_var("x", 8) target = x + 0 @@ -72,14 +72,14 @@ def test_z3_server_simplify_is_noop_but_protocol_compatible() -> None: result = client.simplify(target, request_id=0xA002) assert result.request_id == 0xA002 - assert result.status is smt.Status.SIMPLIFIED + assert result.status is bv.Status.SIMPLIFIED assert result.term is not None assert result.term.to_smt2(depth=-1) == "(bvadd x #x00) ; #2" def test_z3_server_minimize_and_maximize_round_trip() -> None: with Z3Server.start(port=0) as server: - ctx = smt.Context() + ctx = bv.Context() x = ctx.bv_var("x", 4) ctx.assert_(ctx.bv_uge(x, 5)) ctx.assert_(ctx.bv_ule(x, 9)) @@ -88,12 +88,12 @@ def test_z3_server_minimize_and_maximize_round_trip() -> None: minimum = client.minimize(x, want_model=True) maximum = client.maximize(x, want_model=False) - assert minimum.status is smt.Status.SAT + assert minimum.status is bv.Status.SAT assert minimum.optimum is not None assert minimum.optimum.as_int() == 5 assert minimum.model is not None assert minimum.model[x].as_int() == 5 - assert maximum.status is smt.Status.SAT + assert maximum.status is bv.Status.SAT assert maximum.optimum is not None assert maximum.optimum.as_int() == 9 diff --git a/python/uv.lock b/python/uv.lock index 4297429..63d0fd6 100644 --- a/python/uv.lock +++ b/python/uv.lock @@ -3,7 +3,7 @@ revision = 3 requires-python = ">=3.10" [[package]] -name = "smt-wire" +name = "bv-wire" version = "0.1.0" source = { editable = "." } dependencies = [ From 42e383045a48ec380d73e1b49208a43935e4f4ba Mon Sep 17 00:00:00 2001 From: Duncan Ogilvie Date: Tue, 24 Nov 2026 19:19:17 +0100 Subject: [PATCH 2/8] Switch wire magics with legacy compatibility; record answering backend New magics: BVSQ (request), BVSR (response), BV\0\0 (expression buffer). Clients emit only these. Legacy compatibility (bv_wire::raw::legacy): - The server accepts SMTQ requests: it upgrades the request and embedded expression magics, dispatches normally, and downgrades the response (and the expression magic in a HAS_EXPR simplify block) back to SMTR/SMT\0, so already-built clients keep working. The Python Z3 server does the same. - The cache and recordings only ever see current magics, so legacy and current clients share cache entries and recorded rows. Recordings: - If ~/.bv-server/recordings.db does not exist but ~/.smt-server/recordings.db does, copy it into place on startup (read-only VACUUM INTO + no-clobber hard link); the old file is never modified. - Versioned upgrade via PRAGMA user_version, run once at startup before accepting connections: v0 (smt-server) rows are rewritten to the new magics and re-keyed; v2 adds a nullable `backend` column. - migrate-recordings accepts legacy-magic file trees and defaults to ~/.smt-server/requests again. - SMT_SERVER_RECORD_DB is still honoured (with a deprecation warning) when BV_SERVER_RECORD_DB is unset. Backend attribution: - QueryResult gains `backend`, filled in by wrapper backends (router, pool, racing) via `attributed_to`, so it names the leaf that answered: the race winner (z3/binbit/qfbvsmtrs) or the simplifier (rumba). - Recorded in the new `backend` column for binary and SMT-LIB text requests; NULL for errors and pre-existing rows. First recording wins. Docs: README "Upgrading from smt-server" section and new project description; protocol doc documents the legacy magics. --- README.md | 23 +- cpp/include/bv_wire/bv_wire.hpp | 12 +- crates/bv-server/src/backend.rs | 16 + crates/bv-server/src/command_router.rs | 22 +- crates/bv-server/src/lib.rs | 6 +- crates/bv-server/src/main.rs | 5 +- crates/bv-server/src/pool.rs | 5 +- crates/bv-server/src/protocol.rs | 37 +- crates/bv-server/src/racing.rs | 14 +- crates/bv-server/src/recording.rs | 433 +++++++++++++++++- crates/bv-server/src/server.rs | 61 ++- crates/bv-server/src/smtlib.rs | 5 +- crates/bv-server/tests/backend_attribution.rs | 80 ++++ crates/bv-server/tests/legacy_magic.rs | 116 +++++ crates/bv-wire/src/constants.rs | 6 +- crates/bv-wire/src/legacy.rs | 109 +++++ crates/bv-wire/src/lib.rs | 5 + crates/bv-wire/tests/phase0_golden.rs | 4 +- crates/bv-wire/tests/phase1_codecs.rs | 18 +- docs/architecture.md | 4 +- docs/bv-wire-protocol.md | 12 +- python/bv_wire.py | 6 +- python/bv_z3_server.py | 36 +- python/tests/test_python_client.py | 16 +- python/tests/test_z3_server.py | 22 + 25 files changed, 972 insertions(+), 101 deletions(-) create mode 100644 crates/bv-server/tests/backend_attribution.rs create mode 100644 crates/bv-server/tests/legacy_magic.rs create mode 100644 crates/bv-wire/src/legacy.rs diff --git a/README.md b/README.md index 4eb933a..8b63c93 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # bv-server -bv-server lets analysis tools build `QF_BV` formulas with small client libraries and delegate solving or simplification to a separate server. +bv-server is a bit-vector expression service for binary analysis. Tools that lift machine code, for symbolic execution, deobfuscation, or IR experiments, send `QF_BV` expressions as a compact DAG, and the server solves, optimizes, or simplifies them. -It targets binary analysis, lifting, symbolic execution, and IR experiments where client projects need bit-vector queries but should avoid embedding solver build systems. A client constructs a flat binary DAG, sends a length-prefixed request, and receives a model, unsat core, optimum value, or simplified expression. The server owns the solver and simplifier integrations. +It targets projects where client projects need bit-vector queries but should avoid embedding solver build systems. A client constructs a flat binary DAG, sends a length-prefixed request, and receives a model, unsat core, optimum value, or simplified expression. The server owns the solver and simplifier integrations. ## Clients @@ -54,7 +54,7 @@ payload bytes Payload formats: -- binary `SMTQ` request produced by `bv-wire` or one of the clients; +- binary `BVSQ` request produced by `bv-wire` or one of the clients; - SMT-LIB script as UTF-8 text. ## Request recording @@ -81,7 +81,13 @@ BV_SERVER_RECORD_DB= cargo run -p bv-server -- 127.0.0.1:9123 Rows are deduplicated by the BLAKE3 hash of the canonical binary request, with request and response `request_id` fields zeroed so equivalent requests share one entry. Existing rows are left unchanged. -To import the old file-tree corpus from `~/.bv-server/requests` into the SQLite database: +The `backend` column names the backend that produced the response: the winner of the solver race (`z3`, `binbit`, `qfbvsmtrs`) or the simplifier (`rumba`). It is NULL for error responses, requests rejected before reaching a backend, and rows recorded before the column existed. For example: + +```sh +sqlite3 ~/.bv-server/recordings.db "SELECT backend, count(*) FROM recordings GROUP BY backend" +``` + +To import the old file-tree corpus from `~/.smt-server/requests` into the SQLite database: ```sh cargo run -p bv-server -- migrate-recordings @@ -93,6 +99,15 @@ Custom migration paths are supported: cargo run -p bv-server -- migrate-recordings /path/to/requests /tmp/bv-recordings.db ``` +## Upgrading from smt-server + +This project used to be called smt-server, and its wire format used the magics `SMTQ` (request), `SMTR` (response) and `SMT\0` (expression buffer). The current magics are `BVSQ`, `BVSR` and `BV\0\0`; the protocol is otherwise unchanged. + +- **Old clients keep working.** The server accepts `SMTQ` requests and answers them with `SMTR` responses (and `SMT\0` expression buffers). Clients from this repository send only the new magics, so they need a bv-server, not an old smt-server. +- **Recordings carry over.** On startup, if `~/.bv-server/recordings.db` does not exist but `~/.smt-server/recordings.db` does, the server copies the old database into place; the old file is left unchanged. Any database opened by the server is then upgraded once (tracked by `PRAGMA user_version`): rows are rewritten to the new magics and re-keyed, so old and new clients share recordings and cache entries. +- **Environment variables** were renamed from `SMT_SERVER_*` to `BV_SERVER_*`. `SMT_SERVER_RECORD_DB` is still honoured, with a deprecation warning, when `BV_SERVER_RECORD_DB` is unset; the others (`SMT_SERVER_ADDRESS`, `SMT_SERVER_TEXT_QFBVSMTRS_BUDGET_MS`) must be renamed. +- **Package names:** `smt-wire` → `bv-wire` (Rust crate; Python package and module `bv_wire`; C++ header ``, namespace `bv_wire`, CMake package `bv_wire`), `smt-qfbv-smtlib` → `bv-smtlib`, `smt_z3_server.py` → `bv_z3_server.py`. The C++ base exception `smt_error` is now `bv_error`. + ## Python client example The Python client can be installed with `pip install 'git+https://github.com/LLVMParty/bv-server.git#subdirectory=python'` or used directly by adding `python/` to `PYTHONPATH`. diff --git a/cpp/include/bv_wire/bv_wire.hpp b/cpp/include/bv_wire/bv_wire.hpp index 49df1a3..2ce8dde 100644 --- a/cpp/include/bv_wire/bv_wire.hpp +++ b/cpp/include/bv_wire/bv_wire.hpp @@ -298,11 +298,11 @@ class BuilderImpl { uint32_t bool_binary(uint8_t t, uint32_t a, uint32_t b) { expect_bool(a); expect_bool(b); return add(t, 0, {a,b}); } uint32_t bv_cmp(uint8_t t, uint32_t a, uint32_t b) { same_bv(a,b); return add(t, 0, {a,b}); } - static std::vector expr_bytes(const std::vector& ns, const std::vector& cs, const std::vector& bl) { std::vector out; out.insert(out.end(), {'S','M','T',0,1,0,0,0}); u32(out, uint32_t(ns.size())); u32(out, uint32_t(cs.size())); u32(out, uint32_t(bl.size())); for (int i=0;i<12;++i) u8(out,0); for (const auto& n: ns) { u8(out,n.tag); u8(out,n.arity); u16(out,n.aux_hi); u32(out,n.width); u32(out,n.aux_lo); u32(out,n.children); u64(out,n.payload); } for (auto c: cs) u32(out,c); out.insert(out.end(), bl.begin(), bl.end()); return out; } + static std::vector expr_bytes(const std::vector& ns, const std::vector& cs, const std::vector& bl) { std::vector out; out.insert(out.end(), {'B','V',0,0,1,0,0,0}); u32(out, uint32_t(ns.size())); u32(out, uint32_t(cs.size())); u32(out, uint32_t(bl.size())); for (int i=0;i<12;++i) u8(out,0); for (const auto& n: ns) { u8(out,n.tag); u8(out,n.arity); u16(out,n.aux_hi); u32(out,n.width); u32(out,n.aux_lo); u32(out,n.children); u64(out,n.payload); } for (auto c: cs) u32(out,c); out.insert(out.end(), bl.begin(), bl.end()); return out; } void mark(uint32_t ref, std::vector& live) const { uint32_t idx = ref_index(ref); if (idx >= nodes.size()) throw std::invalid_argument("bad root ref"); if (live[idx]) return; live[idx] = 1; const Node& n = nodes[idx]; for (uint32_t i = 0; i < n.arity; ++i) mark(children[n.children + i], live); } std::vector compact_expr(const std::vector& roots, std::vector& old_to_new) const { std::vector live(nodes.size(), 0); for (auto r: roots) mark(r, live); old_to_new.assign(nodes.size(), UINT32_MAX); uint32_t next = 0; for (size_t old = 0; old < nodes.size(); ++old) if (live[old]) old_to_new[old] = meta[old].is_bool ? bool_ref(next++) : bv_ref(next++); std::vector ns; std::vector cs; for (size_t old = 0; old < nodes.size(); ++old) if (live[old]) { Node n = nodes[old]; uint32_t start = n.arity ? uint32_t(cs.size()) : 0; for (uint32_t i = 0; i < n.arity; ++i) cs.push_back(old_to_new[ref_index(children[n.children + i])]); n.children = start; ns.push_back(n); } return expr_bytes(ns, cs, blob); } uint32_t remap(uint32_t ref, const std::vector& old_to_new) const { uint32_t idx = ref_index(ref); if (idx >= old_to_new.size() || old_to_new[idx] == UINT32_MAX) throw std::invalid_argument("dead node ref"); return old_to_new[idx]; } - std::vector build_request(uint32_t request_id, uint8_t cmd, uint8_t flags, uint32_t budget, uint32_t target, bool has_target) const { std::vector named, ordered; std::vector request_assumptions; if (cmd != command::SIMPLIFY) { std::vector unnamed; for (auto a: assertions) (a.named ? named : unnamed).push_back(a); ordered = named; ordered.insert(ordered.end(), unnamed.begin(), unnamed.end()); request_assumptions = assumptions; } else if (!has_target) { throw std::invalid_argument("SIMPLIFY requires a target expression"); } std::vector roots; for (auto a: ordered) roots.push_back(a.root); roots.insert(roots.end(), request_assumptions.begin(), request_assumptions.end()); if (has_target) roots.push_back(target); std::vector old_to_new; auto expr = compact_expr(roots, old_to_new); std::vector out; out.insert(out.end(), {'S','M','T','Q'}); u32(out, request_id); u8(out, cmd); u8(out, flags); u32(out, budget); u32(out, uint32_t(expr.size())); u16(out, uint16_t(ordered.size())); u16(out, uint16_t(named.size())); u16(out, uint16_t(request_assumptions.size())); u32(out, has_target ? remap(target, old_to_new) : 0); u32(out, 0); out.insert(out.end(), expr.begin(), expr.end()); for (auto a: ordered) u32(out, remap(a.root, old_to_new)); for (auto a: named) { u32(out, a.name_offset); u32(out, a.name_len); } for (auto a: request_assumptions) u32(out, remap(a, old_to_new)); return out; } + std::vector build_request(uint32_t request_id, uint8_t cmd, uint8_t flags, uint32_t budget, uint32_t target, bool has_target) const { std::vector named, ordered; std::vector request_assumptions; if (cmd != command::SIMPLIFY) { std::vector unnamed; for (auto a: assertions) (a.named ? named : unnamed).push_back(a); ordered = named; ordered.insert(ordered.end(), unnamed.begin(), unnamed.end()); request_assumptions = assumptions; } else if (!has_target) { throw std::invalid_argument("SIMPLIFY requires a target expression"); } std::vector roots; for (auto a: ordered) roots.push_back(a.root); roots.insert(roots.end(), request_assumptions.begin(), request_assumptions.end()); if (has_target) roots.push_back(target); std::vector old_to_new; auto expr = compact_expr(roots, old_to_new); std::vector out; out.insert(out.end(), {'B','V','S','Q'}); u32(out, request_id); u8(out, cmd); u8(out, flags); u32(out, budget); u32(out, uint32_t(expr.size())); u16(out, uint16_t(ordered.size())); u16(out, uint16_t(named.size())); u16(out, uint16_t(request_assumptions.size())); u32(out, has_target ? remap(target, old_to_new) : 0); u32(out, 0); out.insert(out.end(), expr.begin(), expr.end()); for (auto a: ordered) u32(out, remap(a.root, old_to_new)); for (auto a: named) { u32(out, a.name_offset); u32(out, a.name_len); } for (auto a: request_assumptions) u32(out, remap(a, old_to_new)); return out; } }; inline std::vector frame(const std::vector& payload) { if (payload.size() > UINT32_MAX) throw std::invalid_argument("frame payload too large"); std::vector out; u32(out, uint32_t(payload.size())); out.insert(out.end(), payload.begin(), payload.end()); return out; } @@ -343,7 +343,7 @@ inline void validate_response_payload(uint8_t st, uint8_t flags, const std::vect } } inline ResponsePayload parse_response(const std::vector& data) { - if (data.size() < 16 || data[0] != 'S' || data[1] != 'M' || data[2] != 'T' || data[3] != 'R') throw std::invalid_argument("bad response"); + if (data.size() < 16 || data[0] != 'B' || data[1] != 'V' || data[2] != 'S' || data[3] != 'R') throw std::invalid_argument("bad response"); uint32_t len = read_u32(data, 10); if (read_u16(data, 14) != 0) throw std::invalid_argument("response reserved field is not zero"); if (data.size() != 16u + len) throw std::invalid_argument("response length mismatch"); @@ -648,16 +648,16 @@ class Context { detail::RequestState build_minimize_request(uint32_t request_id, const BVTerm& target, bool signed_order=false, uint32_t budget_ms=0, bool want_model=true) const { return build_request(request_id, detail::command::MINIMIZE, uint8_t((signed_order?detail::request_flags::SIGNED:0)|(want_model?detail::request_flags::WANT_MODEL:0)), budget_ms, target.raw_ref(), true); } detail::RequestState build_maximize_request(uint32_t request_id, const BVTerm& target, bool signed_order=false, uint32_t budget_ms=0, bool want_model=true) const { return build_request(request_id, detail::command::MAXIMIZE, uint8_t((signed_order?detail::request_flags::SIGNED:0)|(want_model?detail::request_flags::WANT_MODEL:0)), budget_ms, target.raw_ref(), true); } Term term_from_ref(uint32_t ref) const { return Term(state_, ref); } - static Context from_expr_bytes(const std::vector& bytes) { Context c; c.state_->b.reset(); if (bytes.size() < 32 || bytes[0] != 'S' || bytes[1] != 'M' || bytes[2] != 'T' || bytes[3] != 0 || bytes[4] != 1) throw protocol_error("bad expression"); uint32_t nodes = detail::read_u32(bytes,8), child_count = detail::read_u32(bytes,12), blob_len = detail::read_u32(bytes,16); size_t expected = 32 + size_t(nodes)*24 + size_t(child_count)*4 + blob_len; if (bytes.size() != expected) throw protocol_error("expression length mismatch"); size_t off=32; for(uint32_t i=0;ib.nodes.push_back(n); c.state_->b.meta.push_back({op_is_bool(n.tag), n.width}); off+=24; } for(uint32_t i=0;ib.children.push_back(detail::read_u32(bytes,off)); off+=4; } c.state_->b.blob.assign(bytes.begin()+off, bytes.end()); return c; } + static Context from_expr_bytes(const std::vector& bytes) { Context c; c.state_->b.reset(); if (bytes.size() < 32 || bytes[0] != 'B' || bytes[1] != 'V' || bytes[2] != 0 || bytes[3] != 0 || bytes[4] != 1) throw protocol_error("bad expression"); uint32_t nodes = detail::read_u32(bytes,8), child_count = detail::read_u32(bytes,12), blob_len = detail::read_u32(bytes,16); size_t expected = 32 + size_t(nodes)*24 + size_t(child_count)*4 + blob_len; if (bytes.size() != expected) throw protocol_error("expression length mismatch"); size_t off=32; for(uint32_t i=0;ib.nodes.push_back(n); c.state_->b.meta.push_back({op_is_bool(n.tag), n.width}); off+=24; } for(uint32_t i=0;ib.children.push_back(detail::read_u32(bytes,off)); off+=4; } c.state_->b.blob.assign(bytes.begin()+off, bytes.end()); return c; } private: std::shared_ptr state_; friend class BVTerm; friend class BoolTerm; friend class Term; friend class Client; friend class Model; BVTerm bv_term(uint32_t r) const { if (detail::is_bool_ref(r)) throw sort_error("expected BV term"); return BVTerm(state_, r); } BoolTerm bool_term(uint32_t r) const { if (!detail::is_bool_ref(r)) throw sort_error("expected Bool term"); return BoolTerm(state_, r); } void check_same(const Term& t) const { if (t.state_ != state_) throw context_mismatch_error("term from a different Context"); } uint32_t expect_bv(const BVTerm& t) const { if (t.state_ != state_) throw context_mismatch_error("BV term from a different Context"); if (detail::is_bool_ref(t.raw_ref())) throw sort_error("expected BV"); return t.raw_ref(); } void expect_bool(const BoolTerm& t) const { if (t.state_ != state_) throw context_mismatch_error("Bool term from a different Context"); if (!detail::is_bool_ref(t.raw_ref())) throw sort_error("expected Bool"); } BVTerm bv_bin(const BVTerm& a, const BVTerm& b, uint32_t (detail::BuilderImpl::*fn)(uint32_t,uint32_t)) { return bv_term((state_->b.*fn)(expect_bv(a), expect_bv(b))); } - static std::vector expr_bytes(const std::vector& ns,const std::vector& cs,const std::vector& bl){ std::vector out; out.insert(out.end(), {'S','M','T',0,1,0,0,0}); detail::u32(out,uint32_t(ns.size())); detail::u32(out,uint32_t(cs.size())); detail::u32(out,uint32_t(bl.size())); for(int i=0;i<12;++i) detail::u8(out,0); for(const auto& n:ns){ detail::u8(out,n.tag); detail::u8(out,n.arity); detail::u16(out,n.aux_hi); detail::u32(out,n.width); detail::u32(out,n.aux_lo); detail::u32(out,n.children); detail::u64(out,n.payload);} for(auto c:cs) detail::u32(out,c); out.insert(out.end(), bl.begin(), bl.end()); return out; } + static std::vector expr_bytes(const std::vector& ns,const std::vector& cs,const std::vector& bl){ std::vector out; out.insert(out.end(), {'B','V',0,0,1,0,0,0}); detail::u32(out,uint32_t(ns.size())); detail::u32(out,uint32_t(cs.size())); detail::u32(out,uint32_t(bl.size())); for(int i=0;i<12;++i) detail::u8(out,0); for(const auto& n:ns){ detail::u8(out,n.tag); detail::u8(out,n.arity); detail::u16(out,n.aux_hi); detail::u32(out,n.width); detail::u32(out,n.aux_lo); detail::u32(out,n.children); detail::u64(out,n.payload);} for(auto c:cs) detail::u32(out,c); out.insert(out.end(), bl.begin(), bl.end()); return out; } void mark(uint32_t ref, std::vector& live) const { uint32_t idx=detail::ref_index(ref); if(idx>=state_->b.nodes.size()) throw protocol_error("bad node ref"); if(live[idx]) return; live[idx]=1; const detail::Node& n=state_->b.nodes[idx]; for(uint32_t i=0;ib.children[n.children+i], live); } - detail::RequestState build_request(uint32_t request_id,uint8_t cmd,uint8_t flags,uint32_t budget,uint32_t target,bool has_target) const { std::vector named, ordered; std::vector assumptions; if(cmd != detail::command::SIMPLIFY){ std::vector unnamed; for(auto a: state_->b.assertions) (a.named?named:unnamed).push_back(a); ordered=named; ordered.insert(ordered.end(), unnamed.begin(), unnamed.end()); assumptions=state_->b.assumptions; } std::vector roots; for(auto a:ordered) roots.push_back(a.root); roots.insert(roots.end(), assumptions.begin(), assumptions.end()); if(has_target) roots.push_back(target); std::vector live(state_->b.nodes.size()); for(auto r:roots) mark(r,live); std::vector old_to_new(state_->b.nodes.size(), UINT32_MAX); std::unordered_map new_to_old; uint32_t next=0; for(size_t i=0;ib.meta[i].is_bool?detail::bool_ref(next++):detail::bv_ref(next++); old_to_new[i]=nr; new_to_old[nr]=state_->b.meta[i].is_bool?detail::bool_ref(uint32_t(i)):detail::bv_ref(uint32_t(i)); } std::vector ns; std::vector cs; for(size_t i=0;ib.nodes[i]; uint32_t start=n.arity?uint32_t(cs.size()):0; for(uint32_t j=0;jb.children[n.children+j])]); n.children=start; ns.push_back(n);} auto expr=expr_bytes(ns,cs,state_->b.blob); auto remap=[&](uint32_t r){ uint32_t v=old_to_new[detail::ref_index(r)]; if(v==UINT32_MAX) throw protocol_error("dead node"); return v;}; std::vector out; out.insert(out.end(), {'S','M','T','Q'}); detail::u32(out,request_id); detail::u8(out,cmd); detail::u8(out,flags); detail::u32(out,budget); detail::u32(out,uint32_t(expr.size())); detail::u16(out,uint16_t(ordered.size())); detail::u16(out,uint16_t(named.size())); detail::u16(out,uint16_t(assumptions.size())); detail::u32(out,has_target?remap(target):0); detail::u32(out,0); out.insert(out.end(),expr.begin(),expr.end()); for(auto a:ordered) detail::u32(out,remap(a.root)); for(auto a:named){detail::u32(out,a.name_offset);detail::u32(out,a.name_len);} for(auto a:assumptions) detail::u32(out,remap(a)); return {out,state_,new_to_old}; } + detail::RequestState build_request(uint32_t request_id,uint8_t cmd,uint8_t flags,uint32_t budget,uint32_t target,bool has_target) const { std::vector named, ordered; std::vector assumptions; if(cmd != detail::command::SIMPLIFY){ std::vector unnamed; for(auto a: state_->b.assertions) (a.named?named:unnamed).push_back(a); ordered=named; ordered.insert(ordered.end(), unnamed.begin(), unnamed.end()); assumptions=state_->b.assumptions; } std::vector roots; for(auto a:ordered) roots.push_back(a.root); roots.insert(roots.end(), assumptions.begin(), assumptions.end()); if(has_target) roots.push_back(target); std::vector live(state_->b.nodes.size()); for(auto r:roots) mark(r,live); std::vector old_to_new(state_->b.nodes.size(), UINT32_MAX); std::unordered_map new_to_old; uint32_t next=0; for(size_t i=0;ib.meta[i].is_bool?detail::bool_ref(next++):detail::bv_ref(next++); old_to_new[i]=nr; new_to_old[nr]=state_->b.meta[i].is_bool?detail::bool_ref(uint32_t(i)):detail::bv_ref(uint32_t(i)); } std::vector ns; std::vector cs; for(size_t i=0;ib.nodes[i]; uint32_t start=n.arity?uint32_t(cs.size()):0; for(uint32_t j=0;jb.children[n.children+j])]); n.children=start; ns.push_back(n);} auto expr=expr_bytes(ns,cs,state_->b.blob); auto remap=[&](uint32_t r){ uint32_t v=old_to_new[detail::ref_index(r)]; if(v==UINT32_MAX) throw protocol_error("dead node"); return v;}; std::vector out; out.insert(out.end(), {'B','V','S','Q'}); detail::u32(out,request_id); detail::u8(out,cmd); detail::u8(out,flags); detail::u32(out,budget); detail::u32(out,uint32_t(expr.size())); detail::u16(out,uint16_t(ordered.size())); detail::u16(out,uint16_t(named.size())); detail::u16(out,uint16_t(assumptions.size())); detail::u32(out,has_target?remap(target):0); detail::u32(out,0); out.insert(out.end(),expr.begin(),expr.end()); for(auto a:ordered) detail::u32(out,remap(a.root)); for(auto a:named){detail::u32(out,a.name_offset);detail::u32(out,a.name_len);} for(auto a:assumptions) detail::u32(out,remap(a)); return {out,state_,new_to_old}; } }; inline Context context_from_state(std::shared_ptr s) { return Context(std::move(s)); } diff --git a/crates/bv-server/src/backend.rs b/crates/bv-server/src/backend.rs index 207c423..47fdc32 100644 --- a/crates/bv-server/src/backend.rs +++ b/crates/bv-server/src/backend.rs @@ -27,6 +27,10 @@ pub struct QueryResult { pub simplify: Option, pub optimization: Option, pub message: Option, + /// Name of the backend that produced this result: the leaf backend, not a + /// wrapper such as the racing or command-router backend. Set by wrappers + /// via [`QueryResult::attributed_to`]; leaf backends may leave it `None`. + pub backend: Option<&'static str>, } impl QueryResult { @@ -38,6 +42,7 @@ impl QueryResult { simplify: None, optimization: None, message: None, + backend: None, } } @@ -49,6 +54,7 @@ impl QueryResult { simplify: None, optimization: None, message: None, + backend: None, } } @@ -60,6 +66,7 @@ impl QueryResult { simplify: None, optimization: None, message: Some(message.into()), + backend: None, } } @@ -71,6 +78,7 @@ impl QueryResult { simplify: Some(simplify), optimization: None, message: None, + backend: None, } } @@ -82,9 +90,17 @@ impl QueryResult { simplify: None, optimization: Some(optimization), message: None, + backend: None, } } + /// Record `backend` as the producer of this result unless an inner backend + /// already did. + pub fn attributed_to(mut self, backend: &'static str) -> Self { + self.backend.get_or_insert(backend); + self + } + pub fn is_conclusive(&self) -> bool { matches!( self.status, diff --git a/crates/bv-server/src/command_router.rs b/crates/bv-server/src/command_router.rs index 23d5492..c53df63 100644 --- a/crates/bv-server/src/command_router.rs +++ b/crates/bv-server/src/command_router.rs @@ -29,8 +29,14 @@ impl Backend for CommandRouterBackend { fn handle(&self, request: &BinaryRequest) -> bv_wire::Result { match request.envelope.command { - Command::Simplify => self.simplifier.handle(request), - Command::Solve | Command::Minimize | Command::Maximize => self.solver.handle(request), + Command::Simplify => self + .simplifier + .handle(request) + .map(|result| result.attributed_to(self.simplifier.name())), + Command::Solve | Command::Minimize | Command::Maximize => self + .solver + .handle(request) + .map(|result| result.attributed_to(self.solver.name())), } } @@ -40,10 +46,14 @@ impl Backend for CommandRouterBackend { context: &SolveContext, ) -> bv_wire::Result { match request.envelope.command { - Command::Simplify => self.simplifier.handle_with_context(request, context), - Command::Solve | Command::Minimize | Command::Maximize => { - self.solver.handle_with_context(request, context) - } + Command::Simplify => self + .simplifier + .handle_with_context(request, context) + .map(|result| result.attributed_to(self.simplifier.name())), + Command::Solve | Command::Minimize | Command::Maximize => self + .solver + .handle_with_context(request, context) + .map(|result| result.attributed_to(self.solver.name())), } } } diff --git a/crates/bv-server/src/lib.rs b/crates/bv-server/src/lib.rs index 4a67d64..ace1b19 100644 --- a/crates/bv-server/src/lib.rs +++ b/crates/bv-server/src/lib.rs @@ -28,9 +28,9 @@ pub use protocol::{handle_binary_frame, handle_binary_request, response_from_que pub use qfbvsmtrs_backend::QfbvsmtrsBackend; pub use racing::RacingBackend; pub use recording::{ - default_legacy_recording_tree, default_recording_db_path, - migrate_default as migrate_recordings, migrate_tree as migrate_recording_tree, - recording_db_path, MigrationReport, + default_legacy_recording_tree, default_recording_db_path, init_recording, + legacy_default_recording_db_path, migrate_default as migrate_recordings, + migrate_tree as migrate_recording_tree, recording_db_path, MigrationReport, }; pub use rumba_backend::RumbaBackend; pub use server::{dispatch_payload, dispatch_payload_with_cache, serve_tcp, ServerConfig}; diff --git a/crates/bv-server/src/main.rs b/crates/bv-server/src/main.rs index 9c0551f..4150c0d 100644 --- a/crates/bv-server/src/main.rs +++ b/crates/bv-server/src/main.rs @@ -2,8 +2,8 @@ use std::path::PathBuf; use std::sync::Arc; use bv_server::{ - default_legacy_recording_tree, migrate_recording_tree, recording_db_path, serve_tcp, - BinbitBackend, CommandRouterBackend, QfbvsmtrsBackend, RacingBackend, RumbaBackend, + default_legacy_recording_tree, init_recording, migrate_recording_tree, recording_db_path, + serve_tcp, BinbitBackend, CommandRouterBackend, QfbvsmtrsBackend, RacingBackend, RumbaBackend, ServerConfig, Z3Backend, }; @@ -27,6 +27,7 @@ fn main() -> std::io::Result<()> { eprintln!( "bv-server listening on {addr} with rumba simplifier + racing solver (z3 crate + binbit + qfbvsmtrs)" ); + init_recording(); serve_tcp(addr, ServerConfig::new(backend)) } diff --git a/crates/bv-server/src/pool.rs b/crates/bv-server/src/pool.rs index 3aac727..c56a68b 100644 --- a/crates/bv-server/src/pool.rs +++ b/crates/bv-server/src/pool.rs @@ -44,6 +44,9 @@ impl Backend for PooledBackend { let Some(index) = self.route_index(request) else { return Ok(QueryResult::unknown("backend pool is empty")); }; - self.backends[index].handle(request) + let backend = &self.backends[index]; + backend + .handle(request) + .map(|result| result.attributed_to(backend.name())) } } diff --git a/crates/bv-server/src/protocol.rs b/crates/bv-server/src/protocol.rs index 88251a1..9ef3927 100644 --- a/crates/bv-server/src/protocol.rs +++ b/crates/bv-server/src/protocol.rs @@ -14,12 +14,25 @@ pub fn handle_binary_frame( frame_payload: &[u8], backend: &dyn Backend, ) -> bv_wire::Result { + handle_binary_frame_attributed(frame_payload, backend).0 +} + +/// Like [`handle_binary_frame`], also returning the name of the backend that +/// produced the result (`None` if the request was rejected before reaching a +/// backend or the backend failed). +pub(crate) fn handle_binary_frame_attributed( + frame_payload: &[u8], + backend: &dyn Backend, +) -> (bv_wire::Result, Option<&'static str>) { if !is_binary_request_payload(frame_payload) { - return BinaryResponse::error(0, "frame payload is not a binary SMTQ request"); + return ( + BinaryResponse::error(0, "frame payload is not a binary request"), + None, + ); } match BinaryRequest::parse(frame_payload) { - Ok(request) => handle_binary_request(&request, backend), - Err(err) => BinaryResponse::error(0, &err.to_string()), + Ok(request) => handle_binary_request_attributed(&request, backend), + Err(err) => (BinaryResponse::error(0, &err.to_string()), None), } } @@ -27,9 +40,23 @@ pub fn handle_binary_request( request: &BinaryRequest, backend: &dyn Backend, ) -> bv_wire::Result { + handle_binary_request_attributed(request, backend).0 +} + +fn handle_binary_request_attributed( + request: &BinaryRequest, + backend: &dyn Backend, +) -> (bv_wire::Result, Option<&'static str>) { match backend.handle(request) { - Ok(result) => response_from_query_result(request, result), - Err(err) => BinaryResponse::error(request.envelope.request_id, &err.to_string()), + Ok(result) => { + let result = result.attributed_to(backend.name()); + let name = result.backend; + (response_from_query_result(request, result), name) + } + Err(err) => ( + BinaryResponse::error(request.envelope.request_id, &err.to_string()), + None, + ), } } diff --git a/crates/bv-server/src/racing.rs b/crates/bv-server/src/racing.rs index 9184003..4e59cbd 100644 --- a/crates/bv-server/src/racing.rs +++ b/crates/bv-server/src/racing.rs @@ -49,7 +49,10 @@ impl Backend for RacingBackend { return Ok(QueryResult::unknown("no backends configured")); } if self.backends.len() == 1 { - return self.backends[0].handle(request); + let backend = &self.backends[0]; + return backend + .handle(request) + .map(|result| result.attributed_to(backend.name())); } let effective_budget_ms = if request.envelope.budget_ms == 0 { self.default_budget_ms.unwrap_or(0) @@ -69,7 +72,9 @@ impl Backend for RacingBackend { let context = SolveContext::new(cancellation.clone()); cancellation_tokens.push(cancellation); thread::spawn(move || { - let result = backend.handle_with_context(&request, &context); + let result = backend + .handle_with_context(&request, &context) + .map(|result| result.attributed_to(backend.name())); let _ = tx.send((backend.name(), result)); }); } @@ -103,13 +108,16 @@ impl Backend for RacingBackend { QueryResult::unknown( "backend returned conclusive result without requested artifact", ) + .attributed_to(name) }); } else { first_unknown.get_or_insert(result); } } Err(err) => { - first_unknown.get_or_insert_with(|| QueryResult::unknown(err.to_string())); + first_unknown.get_or_insert_with(|| { + QueryResult::unknown(err.to_string()).attributed_to(name) + }); } } } diff --git a/crates/bv-server/src/recording.rs b/crates/bv-server/src/recording.rs index 58a522b..d4f40dc 100644 --- a/crates/bv-server/src/recording.rs +++ b/crates/bv-server/src/recording.rs @@ -2,21 +2,45 @@ use std::io; use std::path::{Path, PathBuf}; use std::sync::{Mutex, OnceLock}; -use rusqlite::{params, Connection}; +use rusqlite::{params, Connection, OpenFlags}; use bv_wire::raw::constants::RESPONSE_MAGIC; +use bv_wire::raw::legacy::{ + is_legacy_request_payload, upgrade_request_in_place, upgrade_response_in_place, +}; use crate::cache::cache_key_for_payload; +use bv_wire::raw::request::is_binary_request_payload; /// Path to the SQLite recording database. Empty disables recording. /// Defaults to `~/.bv-server/recordings.db`. pub const RECORD_DB_ENV: &str = "BV_SERVER_RECORD_DB"; +/// Pre-rename name of [`RECORD_DB_ENV`], still honoured when the new name is unset. +pub const LEGACY_RECORD_DB_ENV: &str = "SMT_SERVER_RECORD_DB"; + +/// `PRAGMA user_version` of an up-to-date recording database. +/// +/// - 0: written by smt-server; rows use the legacy magics. +/// - 1: rows use the current magics. +/// - 2: adds the nullable `backend` column (the backend that produced the +/// response; NULL for rows recorded before it existed, errors, and requests +/// rejected before reaching a backend). +const SCHEMA_VERSION: i64 = 2; + /// Maximum pairs committed in a single migration transaction. const MAX_BATCH: usize = 256; const INSERT_SQL: &str = - "INSERT OR IGNORE INTO recordings(hash, request, response) VALUES (?1, ?2, ?3)"; + "INSERT OR IGNORE INTO recordings(hash, request, response, backend) VALUES (?1, ?2, ?3, ?4)"; + +const CREATE_TABLE_SQL: &str = "CREATE TABLE IF NOT EXISTS recordings ( + hash BLOB PRIMARY KEY CHECK(length(hash) = 32), + request BLOB NOT NULL, + response BLOB NOT NULL, + created INTEGER NOT NULL DEFAULT (unixepoch()), + backend TEXT +) STRICT;"; #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub struct MigrationReport { @@ -38,12 +62,17 @@ struct Pair { hash: [u8; 32], request: Vec, response: Vec, + backend: Option<&'static str>, } impl Pair { fn canonical(request: &[u8], response: &[u8]) -> Self { - let request = cache_key_for_payload(request); - let response = canonical_response(response); + let mut request = request.to_vec(); + upgrade_request_in_place(&mut request); + let request = cache_key_for_payload(&request); + let mut response = response.to_vec(); + upgrade_response_in_place(&mut response); + let response = canonical_response(&response); Self::from_canonical(request, response) } @@ -53,6 +82,7 @@ impl Pair { hash, request, response, + backend: None, } } } @@ -71,12 +101,15 @@ impl Recorder { } } -/// Persist a canonicalized request/response pair. -pub fn record_binary_pair(request: &[u8], response: &[u8]) { +/// Persist a canonicalized request/response pair, noting which backend +/// produced the response when known. An existing row for the same request is +/// left unchanged. +pub fn record_binary_pair(request: &[u8], response: &[u8], backend: Option<&'static str>) { let Some(recorder) = recorder() else { return; }; - let pair = Pair::canonical(request, response); + let mut pair = Pair::canonical(request, response); + pair.backend = backend; if let Err(err) = recorder.insert(&pair) { eprintln!("bv-server: failed to persist recording: {err}"); } @@ -87,8 +120,23 @@ fn recorder() -> Option<&'static Recorder> { RECORDER.get_or_init(init_recorder).as_ref() } +/// Open the recording database now instead of on the first request. +/// +/// Opening may import the pre-rename default database and upgrade an old +/// database's rows to the current magics, which can take a while for a large +/// corpus, so the server does it before accepting connections. +pub fn init_recording() { + recorder(); +} + fn init_recorder() -> Option { let path = recording_db_path()?; + if default_recording_db_path().as_deref() == Some(path.as_path()) { + let legacy = legacy_default_recording_db_path().filter(|legacy| legacy.is_file()); + if let Err(err) = legacy.map_or(Ok(()), |legacy| import_legacy_db(&legacy, &path)) { + eprintln!("bv-server: failed to import pre-rename recordings into {path:?}: {err}"); + } + } match open_db(&path) { Ok(conn) => Some(Recorder { conn: Mutex::new(conn), @@ -100,10 +148,124 @@ fn init_recorder() -> Option { } } +/// If `path` does not exist yet, copy the pre-rename database `legacy` +/// (normally `~/.smt-server/recordings.db`) into place. The old +/// file is left unchanged; [`open_db`] then upgrades the copy's rows. +fn import_legacy_db(legacy: &Path, path: &Path) -> io::Result<()> { + if path.exists() { + return Ok(()); + } + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent)?; + } + let mut tmp = path.as_os_str().to_owned(); + tmp.push(format!(".import-{}", std::process::id())); + let tmp = PathBuf::from(tmp); + let _ = std::fs::remove_file(&tmp); + + // VACUUM INTO takes a consistent snapshot (including any WAL contents) and + // works on a read-only connection, so the old database is never written. + let source = Connection::open_with_flags(legacy, OpenFlags::SQLITE_OPEN_READ_ONLY) + .map_err(sqlite_error)?; + source + .execute("VACUUM INTO ?1", params![tmp.to_string_lossy()]) + .map_err(sqlite_error)?; + drop(source); + + // hard_link refuses to replace an existing file, so if another server + // process won the race its copy (and anything it has recorded since) stays. + let linked = std::fs::hard_link(&tmp, path); + let _ = std::fs::remove_file(&tmp); + match linked { + Ok(()) => { + eprintln!( + "bv-server: imported recordings from {legacy:?} into {path:?} (the old file is unchanged)" + ); + Ok(()) + } + Err(err) if err.kind() == io::ErrorKind::AlreadyExists => Ok(()), + Err(err) => Err(err), + } +} + +/// Bring a database written by an older version up to [`SCHEMA_VERSION`] +/// (see there for what each version changed). +/// +/// Version 0 rows use the legacy `SMTQ`/`SMTR`/`SMT\0` magics. Their magics are +/// rewritten and their hashes recomputed, so legacy and current requests for +/// the same query share one row. +fn upgrade_schema(conn: &mut Connection) -> rusqlite::Result<()> { + let version: i64 = conn.query_row("PRAGMA user_version", [], |row| row.get(0))?; + if version >= SCHEMA_VERSION { + return Ok(()); + } + // IMMEDIATE takes the write lock up front; re-check the version under it in + // case another server process upgraded the database meanwhile. + let tx = rusqlite::Transaction::new(conn, rusqlite::TransactionBehavior::Immediate)?; + let version: i64 = tx.query_row("PRAGMA user_version", [], |row| row.get(0))?; + if version >= SCHEMA_VERSION { + return Ok(()); + } + let legacy_rows: i64 = if version < 1 { + tx.query_row( + "SELECT count(*) FROM recordings WHERE substr(request, 1, 4) = CAST('SMTQ' AS BLOB)", + [], + |row| row.get(0), + )? + } else { + 0 + }; + if legacy_rows > 0 { + eprintln!("bv-server: upgrading {legacy_rows} recording(s) to the bv-wire magics..."); + tx.execute_batch( + &CREATE_TABLE_SQL.replace("IF NOT EXISTS recordings (", "recordings_upgraded ("), + )?; + { + let mut select = + tx.prepare("SELECT request, response, created FROM recordings ORDER BY created")?; + let mut insert = tx.prepare( + "INSERT OR IGNORE INTO recordings_upgraded(hash, request, response, created) + VALUES (?1, ?2, ?3, ?4)", + )?; + let mut rows = select.query([])?; + while let Some(row) = rows.next()? { + let request: Vec = row.get(0)?; + let response: Vec = row.get(1)?; + let created: i64 = row.get(2)?; + let pair = Pair::canonical(&request, &response); + insert.execute(params![ + &pair.hash[..], + &pair.request, + &pair.response, + created + ])?; + } + } + tx.execute_batch( + "DROP TABLE recordings; + ALTER TABLE recordings_upgraded RENAME TO recordings;", + )?; + } + let has_backend: bool = tx.query_row( + "SELECT count(*) FROM pragma_table_info('recordings') WHERE name = 'backend'", + [], + |row| row.get::<_, i64>(0).map(|count| count > 0), + )?; + if !has_backend { + tx.execute_batch("ALTER TABLE recordings ADD COLUMN backend TEXT;")?; + } + tx.pragma_update(None, "user_version", SCHEMA_VERSION)?; + tx.commit()?; + if legacy_rows > 0 { + eprintln!("bv-server: recording upgrade complete"); + } + Ok(()) +} + fn insert_pair(conn: &Connection, pair: &Pair) -> rusqlite::Result { conn.execute( INSERT_SQL, - params![&pair.hash[..], &pair.request, &pair.response], + params![&pair.hash[..], &pair.request, &pair.response, pair.backend], ) } @@ -113,6 +275,12 @@ fn insert_pair(conn: &Connection, pair: &Pair) -> rusqlite::Result { /// database. The busy timeout makes a process wait briefly for a serialized write /// lock instead of failing immediately. fn open_db(path: &Path) -> io::Result { + let mut conn = open_db_without_upgrade(path)?; + upgrade_schema(&mut conn).map_err(sqlite_error)?; + Ok(conn) +} + +fn open_db_without_upgrade(path: &Path) -> io::Result { if let Some(parent) = path .parent() .filter(|parent| !parent.as_os_str().is_empty()) @@ -126,15 +294,7 @@ fn open_db(path: &Path) -> io::Result { .map_err(sqlite_error)?; conn.busy_timeout(std::time::Duration::from_secs(5)) .map_err(sqlite_error)?; - conn.execute_batch( - "CREATE TABLE IF NOT EXISTS recordings ( - hash BLOB PRIMARY KEY CHECK(length(hash) = 32), - request BLOB NOT NULL, - response BLOB NOT NULL, - created INTEGER NOT NULL DEFAULT (unixepoch()) - ) STRICT;", - ) - .map_err(sqlite_error)?; + conn.execute_batch(CREATE_TABLE_SQL).map_err(sqlite_error)?; Ok(conn) } @@ -143,7 +303,12 @@ fn sqlite_error(err: rusqlite::Error) -> io::Error { } pub fn recording_db_path() -> Option { - match std::env::var_os(RECORD_DB_ENV) { + let value = std::env::var_os(RECORD_DB_ENV).or_else(|| { + let legacy = std::env::var_os(LEGACY_RECORD_DB_ENV)?; + eprintln!("bv-server: {LEGACY_RECORD_DB_ENV} is deprecated; use {RECORD_DB_ENV}"); + Some(legacy) + }); + match value { Some(value) if value.as_os_str().is_empty() => None, Some(value) => Some(PathBuf::from(value)), None => default_recording_db_path(), @@ -154,8 +319,15 @@ pub fn default_recording_db_path() -> Option { home_dir().map(|home| home.join(".bv-server").join("recordings.db")) } +/// The pre-rename default database, imported into +/// [`default_recording_db_path`] the first time the server starts. +pub fn legacy_default_recording_db_path() -> Option { + home_dir().map(|home| home.join(".smt-server").join("recordings.db")) +} + +/// The file-tree corpus written by early smt-server versions. pub fn default_legacy_recording_tree() -> Option { - home_dir().map(|home| home.join(".bv-server").join("requests")) + home_dir().map(|home| home.join(".smt-server").join("requests")) } fn home_dir() -> Option { @@ -181,7 +353,7 @@ fn canonical_response(response: &[u8]) -> Vec { /// Import the default legacy file-tree corpus into the configured database. /// -/// The source is `~/.bv-server/requests`. The destination is resolved from +/// The source is `~/.smt-server/requests`. The destination is resolved from /// `BV_SERVER_RECORD_DB` or defaults to `~/.bv-server/recordings.db`. pub fn migrate_default() -> io::Result { let source = default_legacy_recording_tree().ok_or_else(|| { @@ -239,27 +411,35 @@ fn read_legacy_pair(req_path: &Path, report: &mut MigrationReport) -> Option cache_key_for_payload(&bytes), + Ok(bytes) => bytes, Err(_) => { report.read_errors += 1; return None; } }; let response = match std::fs::read(&res_path) { - Ok(bytes) => canonical_response(&bytes), + Ok(bytes) => bytes, Err(_) => { report.read_errors += 1; return None; } }; - let actual_hash = blake3::hash(&request).to_hex().to_string(); + // File names hash the request as it was recorded (legacy magics, zeroed + // request_id); the stored pair is re-keyed after upgrading the magics. + let mut recorded_key = request.clone(); + if (is_legacy_request_payload(&request) || is_binary_request_payload(&request)) + && recorded_key.len() >= 8 + { + recorded_key[4..8].fill(0); + } + let actual_hash = blake3::hash(&recorded_key).to_hex().to_string(); if hash != actual_hash { report.bad_hash += 1; return None; } - Some(Pair::from_canonical(request, response)) + Some(Pair::canonical(&request, &response)) } fn legacy_hash_from_req_path(path: &Path) -> Option<&str> { @@ -278,7 +458,12 @@ fn insert_batch_counted(conn: &mut Connection, batch: &[Pair]) -> rusqlite::Resu { let mut stmt = tx.prepare_cached(INSERT_SQL)?; for pair in batch { - match stmt.execute(params![&pair.hash[..], &pair.request, &pair.response])? { + match stmt.execute(params![ + &pair.hash[..], + &pair.request, + &pair.response, + pair.backend + ])? { 0 => duplicates += 1, n => inserted += n, } @@ -408,6 +593,204 @@ mod tests { Ok(()) } + /// Create a database exactly as smt-server did: no `backend` column and + /// `user_version` 0. + fn create_smt_server_db(path: &Path) -> Result> { + std::fs::create_dir_all(path.parent().unwrap())?; + let conn = Connection::open(path)?; + conn.pragma_update(None, "journal_mode", "WAL")?; + conn.execute_batch( + "CREATE TABLE recordings ( + hash BLOB PRIMARY KEY CHECK(length(hash) = 32), + request BLOB NOT NULL, + response BLOB NOT NULL, + created INTEGER NOT NULL DEFAULT (unixepoch()) + ) STRICT;", + )?; + Ok(conn) + } + + fn backend_of(conn: &Connection, hash: &[u8]) -> Option { + conn.query_row( + "SELECT backend FROM recordings WHERE hash = ?1", + params![hash], + |row| row.get(0), + ) + .unwrap() + } + + /// A canonical (zeroed request_id) solve request and an error response, both + /// with the legacy smt-server magics, as smt-server recorded them. + fn legacy_pair(message: &str) -> Result<(Vec, Vec), Box> { + use bv_wire::raw::legacy::{ + downgrade_response_in_place, LEGACY_EXPR_MAGIC, LEGACY_REQUEST_MAGIC, + }; + let mut builder = ExprBuilder::new(); + let assertion = builder.bool_true()?; + builder.assert(assertion)?; + let mut request = cache_key_for_payload(&builder.build_solve_request(7, 0, false, false)?); + request[..4].copy_from_slice(&LEGACY_REQUEST_MAGIC); + request[32..36].copy_from_slice(&LEGACY_EXPR_MAGIC); + let mut response = canonical_response(&BinaryResponse::error(7, message)?.encode()?); + assert!(downgrade_response_in_place(&mut response)); + Ok((request, response)) + } + + #[test] + fn opening_pre_rename_db_upgrades_rows_to_current_magics( + ) -> Result<(), Box> { + let root = temp_root("bv-server-upgrade-test"); + let db = root.join("recordings.db"); + + let (legacy_request, legacy_response) = legacy_pair("legacy")?; + let legacy_hash = *blake3::hash(&legacy_request).as_bytes(); + let conn = create_smt_server_db(&db)?; + conn.execute( + "INSERT INTO recordings(hash, request, response, created) VALUES (?1, ?2, ?3, 1234)", + params![&legacy_hash[..], &legacy_request, &legacy_response], + )?; + drop(conn); + + let conn = open_db(&db)?; + let version: i64 = conn.query_row("PRAGMA user_version", [], |row| row.get(0))?; + assert_eq!(version, SCHEMA_VERSION); + assert!(read_pair(&conn, &legacy_hash).is_none()); + + let expected = Pair::canonical(&legacy_request, &legacy_response); + assert_eq!(&expected.request[..4], b"BVSQ"); + assert_eq!(&expected.request[32..36], b"BV\0\0"); + assert_eq!(&expected.response[..4], b"BVSR"); + let (stored_req, stored_res) = read_pair(&conn, &expected.hash).expect("upgraded row"); + assert_eq!(stored_req, expected.request); + assert_eq!(stored_res, expected.response); + let created: i64 = + conn.query_row("SELECT created FROM recordings", [], |row| row.get(0))?; + assert_eq!(created, 1234); + assert_eq!(backend_of(&conn, &expected.hash), None); + + // Recording the same query from a current client hits the upgraded row. + assert_eq!(insert_pair(&conn, &expected)?, 0); + drop(conn); + + // Reopening does not redo the upgrade. + let conn = open_db(&db)?; + let count: i64 = conn.query_row("SELECT COUNT(*) FROM recordings", [], |row| row.get(0))?; + assert_eq!(count, 1); + + drop(conn); + let _ = std::fs::remove_dir_all(&root); + Ok(()) + } + + #[test] + fn imports_pre_rename_db_without_modifying_it() -> Result<(), Box> { + let root = temp_root("bv-server-import-test"); + let legacy_db = root.join("old").join("recordings.db"); + let db = root.join("new").join("recordings.db"); + + // Keep the writer open so the row is still only in the WAL file. + let (request, response) = legacy_pair("from old db")?; + let legacy_hash = *blake3::hash(&request).as_bytes(); + let writer = create_smt_server_db(&legacy_db)?; + writer.execute( + "INSERT INTO recordings(hash, request, response) VALUES (?1, ?2, ?3)", + params![&legacy_hash[..], &request, &response], + )?; + let legacy_bytes = std::fs::read(&legacy_db)?; + + import_legacy_db(&legacy_db, &db)?; + let conn = open_db(&db)?; + let expected = Pair::canonical(&request, &response); + assert!(read_pair(&conn, &expected.hash).is_some()); + drop(conn); + + // The old database is untouched and still has its legacy row. + assert_eq!(std::fs::read(&legacy_db)?, legacy_bytes); + assert!(read_pair(&writer, &legacy_hash).is_some()); + + // An existing database is never replaced. + let before = std::fs::read(&db)?; + import_legacy_db(&legacy_db, &db)?; + assert_eq!(std::fs::read(&db)?, before); + + drop(writer); + let _ = std::fs::remove_dir_all(&root); + Ok(()) + } + + #[test] + fn records_backend_and_keeps_first_attribution() -> Result<(), Box> { + let root = temp_root("bv-server-backend-test"); + let conn = open_db(&root.join("recordings.db"))?; + + let mut builder = ExprBuilder::new(); + let assertion = builder.bool_true()?; + builder.assert(assertion)?; + let request = builder.build_solve_request(1, 0, false, false)?; + let response = + BinaryResponse::new(1, bv_wire::raw::Status::Sat, 0, Vec::new())?.encode()?; + + let mut pair = Pair::canonical(&request, &response); + pair.backend = Some("z3"); + assert_eq!(insert_pair(&conn, &pair)?, 1); + pair.backend = Some("binbit"); + assert_eq!(insert_pair(&conn, &pair)?, 0); + assert_eq!(backend_of(&conn, &pair.hash).as_deref(), Some("z3")); + + drop(conn); + let _ = std::fs::remove_dir_all(&root); + Ok(()) + } + + #[test] + fn version_1_db_gains_backend_column() -> Result<(), Box> { + let root = temp_root("bv-server-v1-test"); + let db = root.join("recordings.db"); + let conn = create_smt_server_db(&db)?; + conn.pragma_update(None, "user_version", 1)?; + drop(conn); + + let conn = open_db(&db)?; + let version: i64 = conn.query_row("PRAGMA user_version", [], |row| row.get(0))?; + assert_eq!(version, SCHEMA_VERSION); + let (request, response) = legacy_pair("v1")?; + let mut pair = Pair::canonical(&request, &response); + pair.backend = Some("rumba"); + assert_eq!(insert_pair(&conn, &pair)?, 1); + assert_eq!(backend_of(&conn, &pair.hash).as_deref(), Some("rumba")); + + drop(conn); + let _ = std::fs::remove_dir_all(&root); + Ok(()) + } + + #[test] + fn migrates_legacy_magic_tree_into_db() -> Result<(), Box> { + let root = temp_root("bv-server-migrate-legacy-magic-test"); + let source = root.join("requests"); + let db = root.join("recordings.db"); + + let (request, response) = legacy_pair("legacy magic")?; + let hash = blake3::hash(&request).to_hex().to_string(); + std::fs::create_dir_all(&source)?; + std::fs::write(source.join(format!("{hash}.req.bin")), &request)?; + std::fs::write(source.join(format!("{hash}.res.bin")), &response)?; + + let report = migrate_tree(&source, &db)?; + assert_eq!(report.inserted, 1); + assert_eq!(report.skipped(), 0); + + let conn = open_db(&db)?; + let expected = Pair::canonical(&request, &response); + let (stored_req, stored_res) = read_pair(&conn, &expected.hash).expect("migrated row"); + assert_eq!(&stored_req[..4], b"BVSQ"); + assert_eq!(&stored_res[..4], b"BVSR"); + + drop(conn); + let _ = std::fs::remove_dir_all(&root); + Ok(()) + } + #[test] fn migration_reports_skipped_legacy_files() -> Result<(), Box> { let root = temp_root("bv-server-migrate-skip-test"); diff --git a/crates/bv-server/src/server.rs b/crates/bv-server/src/server.rs index 14f7e7d..6801ef4 100644 --- a/crates/bv-server/src/server.rs +++ b/crates/bv-server/src/server.rs @@ -13,9 +13,12 @@ use crate::backend::Backend; use crate::cache::{ binary_request_id, cache_key_for_payload, rebind_cached_response, ResponseCache, }; -use crate::protocol::handle_binary_frame; +use crate::protocol::handle_binary_frame_attributed; use crate::recording::record_binary_pair; use crate::smtlib::handle_text_frame_recording; +use bv_wire::raw::legacy::{ + downgrade_response_in_place, is_legacy_request_payload, upgrade_request_in_place, +}; pub const DEFAULT_MAX_FRAME_BYTES: usize = 64 * 1024 * 1024; pub const DEFAULT_MAX_RESPONSE_BYTES: usize = 64 * 1024 * 1024; @@ -137,10 +140,42 @@ fn handle_connection(mut stream: TcpStream, config: Arc) -> std::i } } +/// Dispatch one frame payload, consulting `cache` for binary requests. +/// +/// Requests using the legacy `SMTQ` magics are upgraded to the current magics +/// before dispatch, so the cache and the recordings only ever see current +/// magics, and the response is downgraded back for the legacy client. pub fn dispatch_payload_with_cache( payload: &[u8], backend: &dyn Backend, cache: Option<&ResponseCache>, +) -> Vec { + with_legacy_magics(payload, |payload| { + dispatch_current_with_cache(payload, backend, cache) + }) +} + +/// Dispatch one frame payload without a cache. See [`dispatch_payload_with_cache`] +/// for how legacy-magic requests are handled. +pub fn dispatch_payload(payload: &[u8], backend: &dyn Backend) -> Vec { + with_legacy_magics(payload, |payload| dispatch_current(payload, backend)) +} + +fn with_legacy_magics(payload: &[u8], dispatch: impl FnOnce(&[u8]) -> Vec) -> Vec { + if !is_legacy_request_payload(payload) { + return dispatch(payload); + } + let mut upgraded = payload.to_vec(); + upgrade_request_in_place(&mut upgraded); + let mut response = dispatch(&upgraded); + downgrade_response_in_place(&mut response); + response +} + +fn dispatch_current_with_cache( + payload: &[u8], + backend: &dyn Backend, + cache: Option<&ResponseCache>, ) -> Vec { if let Some(cache) = cache.filter(|cache| { bv_wire::raw::request::is_binary_request_payload(payload) && cache.accepts_payload(payload) @@ -149,16 +184,18 @@ pub fn dispatch_payload_with_cache( let request_id = binary_request_id(payload); if let Some(response) = cache.lookup(&key) { let response = rebind_cached_response(response, request_id); - record_binary_pair(payload, &response); + // The miss that filled this entry already recorded the pair with its + // backend; this insert only matters if that one failed. + record_binary_pair(payload, &response, None); return response; } - let response = dispatch_payload(payload, backend); + let response = dispatch_current(payload, backend); if is_cacheable_binary_response(&response) { cache.insert(key, response.clone()); } return response; } - dispatch_payload(payload, backend) + dispatch_current(payload, backend) } fn is_cacheable_binary_response(response: &[u8]) -> bool { @@ -172,14 +209,14 @@ fn is_cacheable_binary_response(response: &[u8]) -> bool { .unwrap_or(false) } -pub fn dispatch_payload(payload: &[u8], backend: &dyn Backend) -> Vec { +fn dispatch_current(payload: &[u8], backend: &dyn Backend) -> Vec { if bv_wire::raw::request::is_binary_request_payload(payload) { - let response = - match handle_binary_frame(payload, backend).and_then(|response| response.encode()) { - Ok(bytes) => bytes, - Err(err) => binary_error_response(&err.to_string()), - }; - record_binary_pair(payload, &response); + let (response, answered_by) = handle_binary_frame_attributed(payload, backend); + let response = match response.and_then(|response| response.encode()) { + Ok(bytes) => bytes, + Err(err) => binary_error_response(&err.to_string()), + }; + record_binary_pair(payload, &response, answered_by); response } else { match handle_text_frame_recording(payload, backend) { @@ -193,5 +230,5 @@ fn binary_error_response(message: &str) -> Vec { BinaryResponse::error(0, message) .and_then(|response| response.encode()) .or_else(|_| BinaryResponse::new(0, Status::Unknown, 0, Vec::new())?.encode()) - .unwrap_or_else(|_| b"SMTR\0\0\0\0\x03\0\0\0\0\0\0\0".to_vec()) + .unwrap_or_else(|_| b"BVSR\0\0\0\0\x03\0\0\0\0\0\0\0".to_vec()) } diff --git a/crates/bv-server/src/smtlib.rs b/crates/bv-server/src/smtlib.rs index 31cb026..e11a01a 100644 --- a/crates/bv-server/src/smtlib.rs +++ b/crates/bv-server/src/smtlib.rs @@ -232,6 +232,7 @@ fn handle_text_frame_inner( }; match backend.handle(&query.request) { Ok(result) => { + let result = result.attributed_to(backend.name()); if record { record_text_binary_pair(&query, &result); } @@ -255,7 +256,7 @@ fn record_text_binary_pair(query: &TextQuery, result: &QueryResult) { else { return; }; - record_binary_pair(&request, &response); + record_binary_pair(&request, &response, result.backend); } fn record_text_binary_error(query: &TextQuery, message: &str) { @@ -267,7 +268,7 @@ fn record_text_binary_error(query: &TextQuery, message: &str) { else { return; }; - record_binary_pair(&request, &response); + record_binary_pair(&request, &response, None); } fn allows_qfbvsmtrs_text_fallback(backend: &dyn Backend) -> bool { diff --git a/crates/bv-server/tests/backend_attribution.rs b/crates/bv-server/tests/backend_attribution.rs new file mode 100644 index 0000000..b34e4d4 --- /dev/null +++ b/crates/bv-server/tests/backend_attribution.rs @@ -0,0 +1,80 @@ +//! Results carry the name of the leaf backend that produced them, through the +//! command router and the racing backend, so recordings can store it. + +use std::sync::Arc; +use std::time::Duration; + +use bv_server::{Backend, CommandRouterBackend, QueryResult, RacingBackend}; +use bv_wire::raw::{BinaryRequest, ExprBuilder, SimplifyBlock}; + +struct Fixed { + name: &'static str, + delay_ms: u64, + conclusive: bool, +} + +impl Backend for Fixed { + fn name(&self) -> &'static str { + self.name + } + + fn handle(&self, request: &BinaryRequest) -> bv_wire::Result { + std::thread::sleep(Duration::from_millis(self.delay_ms)); + Ok(match (request.target_ref(), self.conclusive) { + (_, false) => QueryResult::unknown("gave up"), + (Some(target_node), true) => QueryResult::simplified(SimplifyBlock { + expression: request.expression.clone(), + target_node, + }), + (None, true) => QueryResult::sat(None), + }) + } +} + +fn fixed(name: &'static str, delay_ms: u64, conclusive: bool) -> Arc { + Arc::new(Fixed { + name, + delay_ms, + conclusive, + }) +} + +fn server(solvers: Vec>) -> CommandRouterBackend { + CommandRouterBackend::new( + fixed("simplifier", 0, true), + Arc::new(RacingBackend::new(solvers)), + ) +} + +fn requests() -> (BinaryRequest, BinaryRequest) { + let mut builder = ExprBuilder::new(); + let x = builder.bv_var("x", 8).unwrap(); + let t = builder.bool_true().unwrap(); + builder.assert(t).unwrap(); + let solve = BinaryRequest::parse(&builder.build_solve_request(1, 0, false, false).unwrap()); + let simplify = BinaryRequest::parse(&builder.build_simplify_request(2, x).unwrap()); + (solve.unwrap(), simplify.unwrap()) +} + +#[test] +fn racing_winner_is_reported_through_router() { + let backend = server(vec![fixed("slow", 500, true), fixed("fast", 0, true)]); + let (solve, simplify) = requests(); + assert_eq!(backend.handle(&solve).unwrap().backend, Some("fast")); + assert_eq!( + backend.handle(&simplify).unwrap().backend, + Some("simplifier") + ); +} + +#[test] +fn inconclusive_race_reports_backend_that_answered_unknown() { + let (solve, _) = requests(); + let result = RacingBackend::new(vec![ + fixed("quitter", 0, false), + fixed("quitter2", 50, false), + ]) + .handle(&solve) + .unwrap(); + assert_eq!(result.backend, Some("quitter")); +} diff --git a/crates/bv-server/tests/legacy_magic.rs b/crates/bv-server/tests/legacy_magic.rs new file mode 100644 index 0000000..508f448 --- /dev/null +++ b/crates/bv-server/tests/legacy_magic.rs @@ -0,0 +1,116 @@ +//! Clients built before the smt-server -> bv-server rename send `SMTQ` requests +//! and expect `SMTR` responses with `SMT\0` expression buffers. + +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; + +use bv_server::{dispatch_payload_with_cache, Backend, QueryResult, ResponseCache}; +use bv_wire::raw::constants::{EXPR_MAGIC, REQUEST_MAGIC, RESPONSE_MAGIC}; +use bv_wire::raw::legacy::{ + upgrade_response_in_place, LEGACY_EXPR_MAGIC, LEGACY_REQUEST_MAGIC, LEGACY_RESPONSE_MAGIC, +}; +use bv_wire::raw::{BinaryRequest, BinaryResponse, ExprBuilder, SimplifyBlock, Status}; + +/// Answers SOLVE with SAT and SIMPLIFY by echoing the request's expression. +struct EchoBackend { + count: Arc, +} + +impl Backend for EchoBackend { + fn name(&self) -> &'static str { + "echo" + } + + fn handle(&self, request: &BinaryRequest) -> bv_wire::Result { + self.count.fetch_add(1, Ordering::SeqCst); + // Backends only ever see current magics. + assert_eq!(request.expression[..4], EXPR_MAGIC); + Ok(match request.target_ref() { + Some(target_node) => QueryResult::simplified(SimplifyBlock { + expression: request.expression.clone(), + target_node, + }), + None => QueryResult::sat(None), + }) + } +} + +fn to_legacy_request(mut payload: Vec) -> Vec { + assert_eq!(payload[..4], REQUEST_MAGIC); + assert_eq!(payload[32..36], EXPR_MAGIC); + payload[..4].copy_from_slice(&LEGACY_REQUEST_MAGIC); + payload[32..36].copy_from_slice(&LEGACY_EXPR_MAGIC); + payload +} + +#[test] +fn legacy_solve_gets_legacy_response_and_shares_cache_with_current() { + let count = Arc::new(AtomicUsize::new(0)); + let backend = EchoBackend { + count: Arc::clone(&count), + }; + let cache = ResponseCache::new(); + + let mut builder = ExprBuilder::new(); + let t = builder.bool_true().unwrap(); + builder.assert(t).unwrap(); + let legacy = to_legacy_request(builder.build_solve_request(1, 0, false, false).unwrap()); + let current = builder.build_solve_request(2, 0, false, false).unwrap(); + + let mut legacy_response = dispatch_payload_with_cache(&legacy, &backend, Some(&cache)); + assert_eq!(legacy_response[..4], LEGACY_RESPONSE_MAGIC); + assert!(upgrade_response_in_place(&mut legacy_response)); + let legacy_response = BinaryResponse::parse(&legacy_response).unwrap(); + assert_eq!(legacy_response.envelope.status, Status::Sat); + assert_eq!(legacy_response.envelope.request_id, 1); + + let current_response = dispatch_payload_with_cache(¤t, &backend, Some(&cache)); + assert_eq!(current_response[..4], RESPONSE_MAGIC); + let current_response = BinaryResponse::parse(¤t_response).unwrap(); + assert_eq!(current_response.envelope.request_id, 2); + + assert_eq!( + count.load(Ordering::SeqCst), + 1, + "second request is a cache hit" + ); + assert_eq!(cache.len(), 1); +} + +#[test] +fn legacy_simplify_response_uses_legacy_expression_magic() { + let backend = EchoBackend { + count: Arc::new(AtomicUsize::new(0)), + }; + let cache = ResponseCache::new(); + + let mut builder = ExprBuilder::new(); + let x = builder.bv_var("x", 8).unwrap(); + let request = builder.build_simplify_request(9, x).unwrap(); + + // A cache miss for the legacy client, then a hit for each kind of client. + for _ in 0..2 { + let legacy = to_legacy_request(request.clone()); + let mut response = dispatch_payload_with_cache(&legacy, &backend, Some(&cache)); + assert_eq!(response[..4], LEGACY_RESPONSE_MAGIC); + assert_eq!(response[24..28], LEGACY_EXPR_MAGIC); + assert!(upgrade_response_in_place(&mut response)); + let response = BinaryResponse::parse(&response).unwrap(); + assert_eq!(response.envelope.status, Status::Simplified); + assert_eq!(response.envelope.request_id, 9); + + let response = dispatch_payload_with_cache(&request, &backend, Some(&cache)); + assert_eq!(response[..4], RESPONSE_MAGIC); + assert_eq!(response[24..28], EXPR_MAGIC); + BinaryResponse::parse(&response).unwrap(); + } +} + +#[test] +fn malformed_legacy_request_gets_legacy_error_response() { + let backend = EchoBackend { + count: Arc::new(AtomicUsize::new(0)), + }; + let response = bv_server::dispatch_payload(b"SMTQ-truncated", &backend); + assert_eq!(response[..4], LEGACY_RESPONSE_MAGIC); +} diff --git a/crates/bv-wire/src/constants.rs b/crates/bv-wire/src/constants.rs index adc60e5..231b544 100644 --- a/crates/bv-wire/src/constants.rs +++ b/crates/bv-wire/src/constants.rs @@ -1,8 +1,8 @@ use crate::types::Sort; -pub const EXPR_MAGIC: [u8; 4] = *b"SMT\0"; -pub const REQUEST_MAGIC: [u8; 4] = *b"SMTQ"; -pub const RESPONSE_MAGIC: [u8; 4] = *b"SMTR"; +pub const EXPR_MAGIC: [u8; 4] = *b"BV\0\0"; +pub const REQUEST_MAGIC: [u8; 4] = *b"BVSQ"; +pub const RESPONSE_MAGIC: [u8; 4] = *b"BVSR"; pub const VERSION: u8 = 1; pub const EXPR_HEADER_LEN: usize = 32; diff --git a/crates/bv-wire/src/legacy.rs b/crates/bv-wire/src/legacy.rs new file mode 100644 index 0000000..37b4f63 --- /dev/null +++ b/crates/bv-wire/src/legacy.rs @@ -0,0 +1,109 @@ +//! Compatibility with the magics used before the project was renamed from +//! `smt-server`/`smt-wire` to `bv-server`/`bv-wire`. +//! +//! The legacy protocol is byte-for-byte identical to the current one apart from +//! the three 4-byte magics, so converting between them is a matter of rewriting +//! those magics in place: the request/response envelope magic and the magic of +//! the expression buffer embedded in a request or a simplify response. + +use crate::constants::{ + response_flags, EXPR_MAGIC, REQUEST_ENVELOPE_LEN, REQUEST_MAGIC, RESPONSE_ENVELOPE_LEN, + RESPONSE_MAGIC, +}; + +pub const LEGACY_EXPR_MAGIC: [u8; 4] = *b"SMT\0"; +pub const LEGACY_REQUEST_MAGIC: [u8; 4] = *b"SMTQ"; +pub const LEGACY_RESPONSE_MAGIC: [u8; 4] = *b"SMTR"; + +/// Byte offset of the embedded expression buffer in a request payload. +const REQUEST_EXPR_OFFSET: usize = REQUEST_ENVELOPE_LEN; +/// Byte offset of the `expr_len` field in a request envelope. +const REQUEST_EXPR_LEN_OFFSET: usize = 14; +/// Byte offset of the response flags in a response envelope. +const RESPONSE_FLAGS_OFFSET: usize = 9; +/// Byte offset of the embedded expression buffer in a simplify response +/// (after the envelope and the simplify block's `expr_len`/`target_node`). +const RESPONSE_EXPR_OFFSET: usize = RESPONSE_ENVELOPE_LEN + 8; + +pub fn is_legacy_request_payload(payload: &[u8]) -> bool { + payload.len() >= 4 && payload[..4] == LEGACY_REQUEST_MAGIC +} + +pub fn is_legacy_response_payload(payload: &[u8]) -> bool { + payload.len() >= 4 && payload[..4] == LEGACY_RESPONSE_MAGIC +} + +/// Rewrite a legacy (`SMTQ`) request to current magics in place. +/// Returns `false` and leaves `payload` untouched if it is not a legacy request. +pub fn upgrade_request_in_place(payload: &mut [u8]) -> bool { + if !is_legacy_request_payload(payload) { + return false; + } + payload[..4].copy_from_slice(&REQUEST_MAGIC); + let expr_len = payload + .get(REQUEST_EXPR_LEN_OFFSET..REQUEST_EXPR_LEN_OFFSET + 4) + .map(|bytes| u32::from_le_bytes(bytes.try_into().unwrap()) as usize) + .unwrap_or(0); + if expr_len >= 4 { + rewrite_magic( + payload, + REQUEST_EXPR_OFFSET, + &LEGACY_EXPR_MAGIC, + &EXPR_MAGIC, + ); + } + true +} + +/// Rewrite a legacy (`SMTR`) response to current magics in place. +/// Returns `false` and leaves `payload` untouched if it is not a legacy response. +pub fn upgrade_response_in_place(payload: &mut [u8]) -> bool { + convert_response( + payload, + &LEGACY_RESPONSE_MAGIC, + &RESPONSE_MAGIC, + &LEGACY_EXPR_MAGIC, + &EXPR_MAGIC, + ) +} + +/// Rewrite a current (`BVSR`) response to legacy magics in place, for replying +/// to a client that sent a legacy request. +/// Returns `false` and leaves `payload` untouched if it is not a current response. +pub fn downgrade_response_in_place(payload: &mut [u8]) -> bool { + convert_response( + payload, + &RESPONSE_MAGIC, + &LEGACY_RESPONSE_MAGIC, + &EXPR_MAGIC, + &LEGACY_EXPR_MAGIC, + ) +} + +fn convert_response( + payload: &mut [u8], + from: &[u8; 4], + to: &[u8; 4], + from_expr: &[u8; 4], + to_expr: &[u8; 4], +) -> bool { + if payload.len() < 4 || payload[..4] != *from { + return false; + } + payload[..4].copy_from_slice(to); + let has_expr = payload + .get(RESPONSE_FLAGS_OFFSET) + .is_some_and(|flags| flags & response_flags::HAS_EXPR != 0); + if has_expr { + rewrite_magic(payload, RESPONSE_EXPR_OFFSET, from_expr, to_expr); + } + true +} + +fn rewrite_magic(payload: &mut [u8], offset: usize, from: &[u8; 4], to: &[u8; 4]) { + if let Some(magic) = payload.get_mut(offset..offset + 4) { + if magic == from { + magic.copy_from_slice(to); + } + } +} diff --git a/crates/bv-wire/src/lib.rs b/crates/bv-wire/src/lib.rs index d1c8f05..ed264f5 100644 --- a/crates/bv-wire/src/lib.rs +++ b/crates/bv-wire/src/lib.rs @@ -14,6 +14,7 @@ mod constants; mod error; mod expr; mod le; +mod legacy; mod request; mod response; mod types; @@ -54,6 +55,10 @@ pub mod raw { pub use crate::le::*; } + pub mod legacy { + pub use crate::legacy::*; + } + pub use crate::builder::{Assertion, CompactedExpression, ExprBuilder}; pub use crate::client::{ default_server_address, ClientError, ClientResult, TcpClient, DEFAULT_MAX_RESPONSE_BYTES, diff --git a/crates/bv-wire/tests/phase0_golden.rs b/crates/bv-wire/tests/phase0_golden.rs index b3829ac..e6930d5 100644 --- a/crates/bv-wire/tests/phase0_golden.rs +++ b/crates/bv-wire/tests/phase0_golden.rs @@ -4,7 +4,7 @@ use bv_wire::raw::{constants::tag, le, ExprView, ExpressionBuffer, NodeRef, RawN fn empty_expression_buffer_golden_bytes() { let empty = ExpressionBuffer::empty(); let expected = [ - b'S', b'M', b'T', 0, // magic + b'B', b'V', 0, 0, // magic 1, 0, 0, 0, // version + pad 0, 0, 0, 0, // node_count 0, 0, 0, 0, // child_count @@ -24,7 +24,7 @@ fn simple_expression_buffer_golden_bytes() { let children = [NodeRef::bv(0).unwrap(), NodeRef::bv(0).unwrap()]; let expr = ExpressionBuffer::from_parts(&nodes, &children, b"x").unwrap(); let expected = [ - b'S', b'M', b'T', 0, 1, 0, 0, 0, // header magic/version + b'B', b'V', 0, 0, 1, 0, 0, 0, // header magic/version 2, 0, 0, 0, // node_count 2, 0, 0, 0, // child_count 1, 0, 0, 0, // blob_len diff --git a/crates/bv-wire/tests/phase1_codecs.rs b/crates/bv-wire/tests/phase1_codecs.rs index cc81880..53779c1 100644 --- a/crates/bv-wire/tests/phase1_codecs.rs +++ b/crates/bv-wire/tests/phase1_codecs.rs @@ -26,8 +26,8 @@ fn simple_sat_request_golden_vector() { .build_solve_request(0x0102_0304, 500, true, false) .unwrap(); let expected = hex_bytes( - "53 4d 54 51 04 03 02 01 00 01 f4 01 00 00 71 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 \ - 53 4d 54 00 01 00 00 00 03 00 00 00 02 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 \ + "42 56 53 51 04 03 02 01 00 01 f4 01 00 00 71 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 \ + 42 56 00 00 01 00 00 00 03 00 00 00 02 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 \ 00 00 00 00 08 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 \ 01 00 00 00 08 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 \ 1f 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 \ @@ -52,8 +52,8 @@ fn simple_unsat_request_golden_vector() { let bytes = builder.build_solve_request(5, 0, false, false).unwrap(); let expected = hex_bytes( - "53 4d 54 51 05 00 00 00 00 00 00 00 00 00 38 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 \ - 53 4d 54 00 01 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 \ + "42 56 53 51 05 00 00 00 00 00 00 00 00 00 38 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 \ + 42 56 00 00 01 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 \ 19 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 80", ); assert_eq!(bytes, expected); @@ -72,7 +72,7 @@ fn wide_constant_golden_vector() { .unwrap(); let bytes = builder.to_bytes().unwrap(); let expected = hex_bytes( - "53 4d 54 00 01 00 00 00 01 00 00 00 00 00 00 00 10 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 \ + "42 56 00 00 01 00 00 00 01 00 00 00 00 00 00 00 10 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 \ 01 00 00 00 80 00 00 00 00 00 00 00 00 00 00 00 10 00 00 00 00 00 00 00 \ 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f 10", ); @@ -116,8 +116,8 @@ fn named_assertion_and_unsat_core_golden_vectors() { builder.assert_named("a0", p).unwrap(); let bytes = builder.build_solve_request(7, 0, false, true).unwrap(); let expected_request = hex_bytes( - "53 4d 54 51 07 00 00 00 00 02 00 00 00 00 3b 00 00 00 01 00 01 00 00 00 00 00 00 00 00 00 00 00 \ - 53 4d 54 00 01 00 00 00 01 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 \ + "42 56 53 51 07 00 00 00 00 02 00 00 00 00 3b 00 00 00 01 00 01 00 00 00 00 00 00 00 00 00 00 00 \ + 42 56 00 00 01 00 00 00 01 00 00 00 00 00 00 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 \ 1a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 \ 70 61 30 00 00 00 80 01 00 00 00 02 00 00 00", ); @@ -148,7 +148,7 @@ fn named_assertion_and_unsat_core_golden_vectors() { .encode() .unwrap(); let expected_response = - hex_bytes("53 4d 54 52 07 00 00 00 02 02 0a 00 00 00 00 00 01 00 00 00 02 00 00 00 61 30"); + hex_bytes("42 56 53 52 07 00 00 00 02 02 0a 00 00 00 00 00 01 00 00 00 02 00 00 00 61 30"); assert_eq!(response, expected_response); let parsed_response = BinaryResponse::parse(&response).unwrap(); assert_eq!(parsed_response.envelope.status, Status::Unsat); @@ -417,7 +417,7 @@ fn high_level_context_matches_python_style_api() { let request = ctx .build_solve_request(0x0102_0304, 500, true, false) .unwrap(); - assert_eq!(request[0..4], *b"SMTQ"); + assert_eq!(request[0..4], *b"BVSQ"); assert_eq!( ctx.to_smt2().unwrap().lines().next().unwrap(), "(set-logic QF_BV)" diff --git a/docs/architecture.md b/docs/architecture.md index baefd80..93ae27f 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -102,9 +102,9 @@ The server has explicit bounds for hostile or accidental large inputs: - optional read/write timeouts; - per-request backend budgets. -The server also records handled binary request/response pairs into a SQLite database at `~/.bv-server/recordings.db` by default. `BV_SERVER_RECORD_DB` overrides the path; setting it to an empty value disables recording. Each row is keyed by the BLAKE3 hash of the canonical request (`INSERT OR IGNORE` dedupes, leaving existing rows unchanged), and stores the canonical request and response blobs. SMT-LIB text requests are recorded after lowering to binary wire requests. The recorder zeroes request/response IDs before hashing or storage. +The server also records handled binary request/response pairs into a SQLite database at `~/.bv-server/recordings.db` by default. `BV_SERVER_RECORD_DB` overrides the path; setting it to an empty value disables recording. Each row is keyed by the BLAKE3 hash of the canonical request (`INSERT OR IGNORE` dedupes, leaving existing rows unchanged), and stores the canonical request and response blobs plus the name of the backend that produced the response (`QueryResult::backend`, filled in by wrapper backends such as the racing and command-router backends via `QueryResult::attributed_to`, so it names the leaf that actually answered). SMT-LIB text requests are recorded after lowering to binary wire requests. The recorder zeroes request/response IDs before hashing or storage. -Recording is synchronous: the server attempts the SQLite insert before returning the response from the dispatcher. The database opens in WAL mode with `synchronous=NORMAL` and a busy timeout, so multiple server instances on the same host can write to the same file (writes serialize; readers don't block). WAL relies on local filesystem locking and is not safe over network mounts. The one-time importer reads the legacy `~/.bv-server/requests` file tree: run `bv-server migrate-recordings [SOURCE_DIR] [DB_PATH]` to fold an existing tree into the database. +Recording is synchronous: the server attempts the SQLite insert before returning the response from the dispatcher. The database opens in WAL mode with `synchronous=NORMAL` and a busy timeout, so multiple server instances on the same host can write to the same file (writes serialize; readers don't block). WAL relies on local filesystem locking and is not safe over network mounts. Stored rows always use the current magics: legacy `SMTQ` requests are upgraded before they reach the cache or the recorder, and a database written by smt-server (`PRAGMA user_version` 0) is rewritten and re-keyed once when opened. If the default database does not exist, the server first copies `~/.smt-server/recordings.db` into place (read-only, via `VACUUM INTO`). The one-time importer reads the legacy `~/.smt-server/requests` file tree: run `bv-server migrate-recordings [SOURCE_DIR] [DB_PATH]` to fold an existing tree into the database. The client libraries also enforce sort/width/context checks during construction so malformed requests are normally caught before serialization. diff --git a/docs/bv-wire-protocol.md b/docs/bv-wire-protocol.md index 30ea9f6..8155233 100644 --- a/docs/bv-wire-protocol.md +++ b/docs/bv-wire-protocol.md @@ -11,7 +11,11 @@ u32_le frame_len u8[frame_len] frame_payload ``` -If `frame_payload` starts with `"SMTQ"`, it is a binary request. Otherwise the payload is treated as one complete UTF-8 SMT-LIB script. Binary responses start with `"SMTR"`; text responses are UTF-8 SMT-LIB output in the same transport frame. +If `frame_payload` starts with `"BVSQ"`, it is a binary request. Otherwise the payload is treated as one complete UTF-8 SMT-LIB script. Binary responses start with `"BVSR"`; text responses are UTF-8 SMT-LIB output in the same transport frame. + +### Legacy magics + +Before the project was renamed from smt-server, the same layout used the magics `"SMTQ"` (request), `"SMTR"` (response) and `"SMT\0"` (expression buffer). The reference server still accepts `"SMTQ"` requests: it rewrites the request and embedded expression magics to the current ones, handles the request normally, and rewrites the response magic (and the expression magic in a `HAS_EXPR` simplify block) back to the legacy ones. Clients only emit the current magics. See `bv_wire::raw::legacy`. ## Expression buffer @@ -28,7 +32,7 @@ Blob table blob_len bytes | Field | Size | Description | |---|---:|---| -| `magic` | 4 | `"SMT\0"` | +| `magic` | 4 | `"BV\0\0"` | | `version` | 1 | currently `1` | | padding | 3 | zero when encoded | | `node_count` | 4 | number of node records | @@ -130,7 +134,7 @@ A binary frame payload starts with a 32-byte request envelope: | Field | Size | Description | |---|---:|---| -| `magic` | 4 | `"SMTQ"` | +| `magic` | 4 | `"BVSQ"` | | `request_id` | 4 | echoed by the response | | `command` | 1 | command value | | `flags` | 1 | request flags | @@ -174,7 +178,7 @@ A binary response payload starts with a 16-byte response envelope: | Field | Size | Description | |---|---:|---| -| `magic` | 4 | `"SMTR"` | +| `magic` | 4 | `"BVSR"` | | `request_id` | 4 | copied from the request | | `status` | 1 | status value | | `flags` | 1 | response flags | diff --git a/python/bv_wire.py b/python/bv_wire.py index 07cc98c..f6eecb0 100644 --- a/python/bv_wire.py +++ b/python/bv_wire.py @@ -17,9 +17,9 @@ import struct from typing import Any, Callable, Iterable, Iterator, Literal, Optional, TypeVar -EXPR_MAGIC = b"SMT\0" -REQUEST_MAGIC = b"SMTQ" -RESPONSE_MAGIC = b"SMTR" +EXPR_MAGIC = b"BV\0\0" +REQUEST_MAGIC = b"BVSQ" +RESPONSE_MAGIC = b"BVSR" VERSION = 1 BOOL_BIT = 0x80000000 INDEX_MASK = 0x7FFFFFFF diff --git a/python/bv_z3_server.py b/python/bv_z3_server.py index 089caab..88c977f 100644 --- a/python/bv_z3_server.py +++ b/python/bv_z3_server.py @@ -438,8 +438,14 @@ def _handle_connection(self, conn: socket.socket) -> None: pass def _dispatch_payload(self, payload: bytes) -> bytes: + if payload.startswith(LEGACY_REQUEST_MAGIC): + # Clients from before the smt-server -> bv-server rename: answer in kind. + return _downgrade_response(self._dispatch_current(_upgrade_request(payload))) + return self._dispatch_current(payload) + + def _dispatch_current(self, payload: bytes) -> bytes: if not payload.startswith(bv.REQUEST_MAGIC): - return _text_error("Python Z3 server only supports binary SMTQ frames") + return _text_error("Python Z3 server only supports binary bv-wire frames") try: request = _parse_binary_request(payload) except Exception as exc: @@ -486,6 +492,34 @@ def _bind_listener(host: str, port: int) -> socket.socket: raise OSError(f"could not resolve bind address {host!r}:{port}") +LEGACY_EXPR_MAGIC = b"SMT\0" +LEGACY_REQUEST_MAGIC = b"SMTQ" +LEGACY_RESPONSE_MAGIC = b"SMTR" + + +def _replace_magic(data: bytearray, offset: int, old: bytes, new: bytes) -> None: + if data[offset : offset + 4] == old: + data[offset : offset + 4] = new + + +def _upgrade_request(payload: bytes) -> bytes: + data = bytearray(payload) + data[:4] = bv.REQUEST_MAGIC + if len(data) >= 18 and struct.unpack_from("= 4: + _replace_magic(data, REQUEST_HEADER_SIZE, LEGACY_EXPR_MAGIC, bv.EXPR_MAGIC) + return bytes(data) + + +def _downgrade_response(payload: bytes) -> bytes: + if not payload.startswith(bv.RESPONSE_MAGIC): + return payload + data = bytearray(payload) + data[:4] = LEGACY_RESPONSE_MAGIC + if len(data) > 9 and data[9] & RESP_HAS_EXPR: + _replace_magic(data, 24, bv.EXPR_MAGIC, LEGACY_EXPR_MAGIC) + return bytes(data) + + def _parse_binary_request(payload: bytes) -> _BinaryRequest: if len(payload) < REQUEST_HEADER_SIZE or payload[:4] != bv.REQUEST_MAGIC: raise bv.ProtocolError("bad request envelope") diff --git a/python/tests/test_python_client.py b/python/tests/test_python_client.py index 174f594..4a26a29 100644 --- a/python/tests/test_python_client.py +++ b/python/tests/test_python_client.py @@ -18,8 +18,8 @@ def test_python_client_matches_simple_sat_golden_vector(): one = ctx.bv_const(1, 8) ctx.assert_(ctx.bv_eq(x, one)) assert ctx._build_solve_request(0x01020304, 500, True, False).payload == hex_bytes( - "53 4d 54 51 04 03 02 01 00 01 f4 01 00 00 71 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00" - "53 4d 54 00 01 00 00 00 03 00 00 00 02 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00" + "42 56 53 51 04 03 02 01 00 01 f4 01 00 00 71 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00" + "42 56 00 00 01 00 00 00 03 00 00 00 02 00 00 00 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00" "00 00 00 00 08 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00" "01 00 00 00 08 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00" "1f 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00" @@ -95,7 +95,7 @@ def test_terms_validate_width_sort_and_context(): assert not hasattr(p, "and_") rotated = ctx.bv_rotate_left(a, 3) assert isinstance(rotated, bv.BVTerm) - assert ctx._build_minimize_request(3, a, signed=True, want_model=True).payload.startswith(b"SMTQ") + assert ctx._build_minimize_request(3, a, signed=True, want_model=True).payload.startswith(b"BVSQ") try: a + c raise AssertionError("expected width error") @@ -224,7 +224,7 @@ def test_python_wide_integer_constant_uses_blob_encoding_and_masks_to_width(): def test_python_response_parser_and_model_mapping(): - response = b"SMTR" + (7).to_bytes(4, "little") + bytes([bv.Status.ERROR, 16]) + (3).to_bytes(4, "little") + b"\0\0bad" + response = b"BVSR" + (7).to_bytes(4, "little") + bytes([bv.Status.ERROR, 16]) + (3).to_bytes(4, "little") + b"\0\0bad" parsed = bv._parse_response(response) assert parsed.request_id == 7 assert parsed.status is bv.Status.ERROR @@ -238,7 +238,7 @@ def test_python_response_parser_and_model_mapping(): compacted_x = request.old_to_new[x.id] scalar = (8).to_bytes(4, "little") + (1).to_bytes(4, "little") + b"*" model_payload = (1).to_bytes(4, "little") + compacted_x.to_bytes(4, "little") + scalar - raw = bv._parse_response(b"SMTR" + (8).to_bytes(4, "little") + bytes([bv.Status.SAT, 1]) + len(model_payload).to_bytes(4, "little") + b"\0\0" + model_payload) + raw = bv._parse_response(b"BVSR" + (8).to_bytes(4, "little") + bytes([bv.Status.SAT, 1]) + len(model_payload).to_bytes(4, "little") + b"\0\0" + model_payload) client = bv.Client.from_socket(_FakeSocket.empty()) model = client._solve_response(raw, request).model assert model is not None @@ -252,21 +252,21 @@ def test_python_response_parser_and_model_mapping(): def test_python_response_parser_rejects_bad_status_flag_combinations(): - bad_error = b"SMTR" + (1).to_bytes(4, "little") + bytes([bv.Status.ERROR, 0]) + (0).to_bytes(4, "little") + b"\0\0" + bad_error = b"BVSR" + (1).to_bytes(4, "little") + bytes([bv.Status.ERROR, 0]) + (0).to_bytes(4, "little") + b"\0\0" try: bv._parse_response(bad_error) raise AssertionError("expected bad ERROR response to be rejected") except bv.ProtocolError: pass - bad_sat = b"SMTR" + (1).to_bytes(4, "little") + bytes([bv.Status.SAT, 2]) + (0).to_bytes(4, "little") + b"\0\0" + bad_sat = b"BVSR" + (1).to_bytes(4, "little") + bytes([bv.Status.SAT, 2]) + (0).to_bytes(4, "little") + b"\0\0" try: bv._parse_response(bad_sat) raise AssertionError("expected bad SAT flags to be rejected") except bv.ProtocolError: pass - bad_simplified = b"SMTR" + (1).to_bytes(4, "little") + bytes([bv.Status.SIMPLIFIED, 0]) + (0).to_bytes(4, "little") + b"\0\0" + bad_simplified = b"BVSR" + (1).to_bytes(4, "little") + bytes([bv.Status.SIMPLIFIED, 0]) + (0).to_bytes(4, "little") + b"\0\0" try: bv._parse_response(bad_simplified) raise AssertionError("expected bad SIMPLIFIED flags to be rejected") diff --git a/python/tests/test_z3_server.py b/python/tests/test_z3_server.py index 5d7046a..86afad0 100644 --- a/python/tests/test_z3_server.py +++ b/python/tests/test_z3_server.py @@ -109,3 +109,25 @@ def main() -> None: if __name__ == "__main__": main() + + +def _legacy_request(payload: bytes) -> bytes: + assert payload[:4] == bv.REQUEST_MAGIC and payload[32:36] == bv.EXPR_MAGIC + return b"SMTQ" + payload[4:32] + b"SMT\0" + payload[36:] + + +def test_z3_server_answers_legacy_clients_with_legacy_magics() -> None: + with Z3Server.start(port=0) as server: + ctx = bv.Context() + x = ctx.bv_var("x", 8) + ctx.assert_(ctx.bv_eq(x, 3)) + + solve = _legacy_request(ctx._build_solve_request(0xA010).payload) + response = server._dispatch_payload(solve) + assert response[:4] == b"SMTR" + assert bv._parse_response(b"BVSR" + response[4:]).status is bv.Status.SAT + + simplify = _legacy_request(ctx._build_simplify_request(0xA011, x + 0).payload) + response = server._dispatch_payload(simplify) + assert response[:4] == b"SMTR" + assert response[24:28] == b"SMT\0" From c70d7f9ad534aa81e2ba97b7188f7e99e6da97e8 Mon Sep 17 00:00:00 2001 From: Duncan Ogilvie Date: Tue, 24 Nov 2026 19:25:07 +0100 Subject: [PATCH 3/8] Fix clippy failures on Rust 1.100 CI runs clippy with -D warnings on the latest stable, which added two diagnostics in existing code: - clippy::chunks_exact_to_as_chunks in bv-smtlib's annotation parsing: use `as_chunks::<2>()` and destructure the keyword/value pair. - `AtomicUsize::fetch_update` is deprecated in favour of `try_update`, which older toolchains lack; use an equivalent compare_exchange_weak loop. --- crates/bv-server/src/server.rs | 20 +- crates/bv-smtlib/src/lib.rs | 4224 ++++++++++++++++---------------- 2 files changed, 2127 insertions(+), 2117 deletions(-) diff --git a/crates/bv-server/src/server.rs b/crates/bv-server/src/server.rs index 6801ef4..a411f5f 100644 --- a/crates/bv-server/src/server.rs +++ b/crates/bv-server/src/server.rs @@ -79,11 +79,21 @@ fn try_acquire_connection(active_connections: &AtomicUsize, max_connections: usi if max_connections == 0 { return false; } - active_connections - .fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| { - (current < max_connections).then_some(current + 1) - }) - .is_ok() + // Hand-rolled rather than `fetch_update`, which newer Rust deprecates in + // favour of `try_update`, which older toolchains don't have. + let mut current = active_connections.load(Ordering::Acquire); + while current < max_connections { + match active_connections.compare_exchange_weak( + current, + current + 1, + Ordering::AcqRel, + Ordering::Acquire, + ) { + Ok(_) => return true, + Err(actual) => current = actual, + } + } + false } struct ConnectionPermit { diff --git a/crates/bv-smtlib/src/lib.rs b/crates/bv-smtlib/src/lib.rs index 0de22a9..b169cff 100644 --- a/crates/bv-smtlib/src/lib.rs +++ b/crates/bv-smtlib/src/lib.rs @@ -1,2112 +1,2112 @@ -//! Shared QF_BV/Bool SMT-LIB frontend utilities. -//! -//! This crate is intentionally solver-agnostic. It owns the yaspar-based -//! S-expression parser and common frontend policy/sink types; solver crates -//! lower parsed commands through their own adapters. - -use std::{collections::HashMap, fmt}; - -use dashu::{float::DBig, integer::UBig}; -use yaspar::{ - action::{ - ActionOnAttribute, ActionOnConstant, ActionOnIdentifier, ActionOnIndex, ActionOnSort, - ActionOnString, ActionOnTerm, ParsingAction, ParsingResult, Pattern, - }, - ast::{DatatypeDec, DatatypeDef, FunctionDef, Keyword}, - position::Range, -}; - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum SExpr { - Atom(String), - List(Vec), -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum SmtSort { - Bool, - Bv(u32), -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum AcceptedLogics { - QfBvOnly, - QfBvOrAll, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum IncrementalPolicy { - RejectPushPop, - SimulatePushPop, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum GetValuePolicy { - SymbolsOnly, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct FrontendOptions { - pub accepted_logics: AcceptedLogics, - pub incremental_policy: IncrementalPolicy, - pub get_value_policy: GetValuePolicy, - pub require_check_sat: bool, - pub max_macro_expansion_depth: usize, -} - -impl FrontendOptions { - pub fn server_text() -> Self { - Self { - accepted_logics: AcceptedLogics::QfBvOnly, - incremental_policy: IncrementalPolicy::RejectPushPop, - get_value_policy: GetValuePolicy::SymbolsOnly, - require_check_sat: true, - max_macro_expansion_depth: 64, - } - } - - pub fn standalone() -> Self { - Self { - accepted_logics: AcceptedLogics::QfBvOrAll, - incremental_policy: IncrementalPolicy::SimulatePushPop, - get_value_policy: GetValuePolicy::SymbolsOnly, - require_check_sat: true, - max_macro_expansion_depth: 64, - } - } -} - -impl Default for FrontendOptions { - fn default() -> Self { - Self::server_text() - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum FrontendError { - Parse(String), - Unsupported(String), - Invalid { - context: &'static str, - message: String, - }, - Sink(String), -} - -impl FrontendError { - pub fn invalid(context: &'static str, message: impl Into) -> Self { - Self::Invalid { - context, - message: message.into(), - } - } -} - -impl fmt::Display for FrontendError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - FrontendError::Parse(message) => write!(f, "SMT-LIB parse error: {message}"), - FrontendError::Unsupported(message) => { - write!(f, "unsupported SMT-LIB construct: {message}") - } - FrontendError::Invalid { context, message } => { - write!(f, "invalid {context}: {message}") - } - FrontendError::Sink(message) => write!(f, "frontend sink error: {message}"), - } - } -} - -impl std::error::Error for FrontendError {} - -pub type Result = std::result::Result; - -pub trait QfBvSink { - type Node: Copy; - type Error: fmt::Display; - - fn bool_const(&mut self, value: bool) -> std::result::Result; - fn bv_const( - &mut self, - bytes_le: &[u8], - width: u32, - ) -> std::result::Result; - - fn bool_var(&mut self, name: &str) -> std::result::Result; - fn bv_var(&mut self, name: &str, width: u32) -> std::result::Result; - - fn bool_not(&mut self, x: Self::Node) -> std::result::Result; - fn bool_and( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn bool_or( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn bool_implies( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn bool_eq( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn bool_xor( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn bool_ite( - &mut self, - c: Self::Node, - t: Self::Node, - e: Self::Node, - ) -> std::result::Result; - - fn bv_not(&mut self, x: Self::Node) -> std::result::Result; - fn bv_neg(&mut self, x: Self::Node) -> std::result::Result; - fn bv_and( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn bv_or( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn bv_xor( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn bv_add( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn bv_sub( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn bv_mul( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn bv_udiv( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn bv_urem( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn bv_sdiv( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn bv_srem( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn bv_smod( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn bv_shl( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn bv_lshr( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn bv_ashr( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - - fn bv_extract( - &mut self, - x: Self::Node, - hi: u32, - lo: u32, - ) -> std::result::Result; - fn bv_concat( - &mut self, - high: Self::Node, - low: Self::Node, - ) -> std::result::Result; - fn bv_zext( - &mut self, - x: Self::Node, - amount: u32, - ) -> std::result::Result; - fn bv_sext( - &mut self, - x: Self::Node, - amount: u32, - ) -> std::result::Result; - fn bv_repeat( - &mut self, - x: Self::Node, - count: u32, - ) -> std::result::Result; - fn bv_rotate_left( - &mut self, - x: Self::Node, - amount: u32, - ) -> std::result::Result; - fn bv_rotate_right( - &mut self, - x: Self::Node, - amount: u32, - ) -> std::result::Result; - fn bv_ite( - &mut self, - c: Self::Node, - t: Self::Node, - e: Self::Node, - ) -> std::result::Result; - - fn bv_eq( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn bv_ult( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn bv_ule( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn bv_slt( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn bv_sle( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - - fn uadd_ovf( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn sadd_ovf( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn usub_ovf( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn ssub_ovf( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn umul_ovf( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn smul_ovf( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - fn neg_ovf(&mut self, x: Self::Node) -> std::result::Result; - fn sdiv_ovf( - &mut self, - a: Self::Node, - b: Self::Node, - ) -> std::result::Result; - - fn assert( - &mut self, - root: Self::Node, - name: Option<&str>, - ) -> std::result::Result<(), Self::Error>; - fn assume(&mut self, root: Self::Node) -> std::result::Result<(), Self::Error>; - - fn push(&mut self) -> std::result::Result<(), Self::Error>; - fn pop(&mut self) -> std::result::Result<(), Self::Error>; -} - -pub fn parse_sexprs(input: &str) -> Result> { - let mut action = SExprAction; - yaspar::smtlib2::ScriptParser::new() - .parse(&mut action, yaspar::tokenize_str(input, true)) - .map_err(|err| FrontendError::Parse(err.to_string())) -} - -pub fn atom(expr: &SExpr) -> Result<&str> { - match expr { - SExpr::Atom(atom) => Ok(atom), - SExpr::List(_) => Err(FrontendError::invalid("SMT-LIB atom", "expected atom")), - } -} - -pub fn parse_u32_atom(expr: &SExpr, context: &'static str) -> Result { - atom(expr)? - .parse::() - .map_err(|_| FrontendError::invalid(context, "expected u32 numeral")) -} - -pub fn parse_function_params(expr: &SExpr) -> Result> { - let SExpr::List(args) = expr else { - return Err(FrontendError::invalid( - "define-fun", - "expected argument list", - )); - }; - let mut params = Vec::with_capacity(args.len()); - for arg in args { - let SExpr::List(pair) = arg else { - return Err(FrontendError::invalid( - "define-fun", - "argument is not a pair", - )); - }; - expect_len(pair, 2, "define-fun")?; - let name = atom(&pair[0])?.to_owned(); - if params.iter().any(|(existing, _)| existing == &name) { - return Err(FrontendError::invalid( - "define-fun", - format!("duplicate argument {name:?}"), - )); - } - params.push((name, parse_sort(&pair[1])?)); - } - Ok(params) -} - -pub fn parse_sort(expr: &SExpr) -> Result { - match expr { - SExpr::Atom(atom) if atom == "Bool" => Ok(SmtSort::Bool), - SExpr::List(items) - if items.len() == 3 && atom(&items[0])? == "_" && atom(&items[1])? == "BitVec" => - { - let width = atom(&items[2])? - .parse::() - .map_err(|_| FrontendError::invalid("sort", "invalid BitVec width"))?; - validate_bv_width(width, "sort")?; - Ok(SmtSort::Bv(width)) - } - _ => Err(FrontendError::invalid( - "sort", - "expected Bool or (_ BitVec n)", - )), - } -} - -pub fn validate_bv_width(width: u32, context: &'static str) -> Result<()> { - if (1..=65_536).contains(&width) { - Ok(()) - } else { - Err(FrontendError::invalid( - context, - format!("invalid BitVec width {width}"), - )) - } -} - -pub fn decimal_to_le_bytes(text: &str, len: usize) -> Result> { - let mut digits = text - .bytes() - .map(|byte| match byte { - b'0'..=b'9' => Ok(byte - b'0'), - _ => Err(FrontendError::invalid( - "bv literal", - "invalid decimal value", - )), - }) - .collect::>>()?; - let mut out = Vec::with_capacity(len); - while !digits.is_empty() && out.len() < len { - let mut carry = 0u16; - let mut quotient = Vec::new(); - for digit in digits { - let n = carry * 10 + u16::from(digit); - let q = (n / 256) as u8; - carry = n % 256; - if !quotient.is_empty() || q != 0 { - quotient.push(q); - } - } - out.push(carry as u8); - digits = quotient; - } - out.resize(len, 0); - Ok(out) -} - -pub fn indexed_bv_literal_bytes(items: &[SExpr]) -> Result<(Vec, u32)> { - let literal = if items.len() == 4 && atom(&items[1])? == "bv" { - Some((atom(&items[2])?, atom(&items[3])?)) - } else if items.len() == 3 { - let symbol = atom(&items[1])?; - if let Some(value) = symbol.strip_prefix("bv") { - Some((value, atom(&items[2])?)) - } else { - None - } - } else { - None - }; - let Some((value, width)) = literal else { - return Err(FrontendError::invalid( - "indexed literal", - "expected (_ bvN W)", - )); - }; - if value.is_empty() { - return Err(FrontendError::invalid("bv literal", "missing value")); - } - let width = width - .parse::() - .map_err(|_| FrontendError::invalid("bv literal", "invalid width"))?; - validate_bv_width(width, "bv literal")?; - let mut bytes = decimal_to_le_bytes(value, (width as usize).div_ceil(8))?; - mask_unused_high_bits(width, &mut bytes); - Ok((bytes, width)) -} - -pub fn literal_bytes(digits: &str, radix: u32, width: u32, original: &str) -> Result> { - validate_bv_width(width, "bv literal")?; - let mut bytes = vec![0u8; (width as usize).div_ceil(8)]; - for (pos, ch) in digits.chars().rev().enumerate() { - let value = ch.to_digit(radix).ok_or_else(|| { - FrontendError::invalid("bv literal", format!("invalid digit in {original}")) - })?; - if radix == 2 { - if value != 0 { - bytes[pos / 8] |= 1u8 << (pos % 8); - } - } else { - bytes[pos / 2] |= (value as u8) << ((pos % 2) * 4); - } - } - mask_unused_high_bits(width, &mut bytes); - Ok(bytes) -} - -pub fn parse_annotation(items: &[SExpr]) -> Result)>> { - if items.is_empty() || atom(&items[0])? != "!" { - return Ok(None); - } - if items.len() < 4 || !(items.len() - 2).is_multiple_of(2) { - return Err(FrontendError::invalid( - "annotation", - "expected annotated term followed by keyword/value pairs", - )); - } - let mut name = None; - for pair in items[2..].chunks_exact(2) { - let key = atom(&pair[0])?; - if !key.starts_with(':') { - return Err(FrontendError::invalid( - "annotation", - "expected annotation keyword", - )); - } - if key == ":named" { - name = Some(atom(&pair[1])?.to_owned()); - } - } - Ok(Some((&items[1], name))) -} - -pub fn named_annotation(expr: &SExpr) -> Result> { - let SExpr::List(items) = expr else { - return Ok(None); - }; - let Some((inner, name)) = parse_annotation(items)? else { - return Ok(None); - }; - let Some(name) = name else { - return Ok(None); - }; - Ok(Some((inner, name))) -} - -pub fn expect_len(items: &[SExpr], len: usize, context: &'static str) -> Result<()> { - if items.len() != len { - return Err(FrontendError::invalid( - context, - format!("expected {len} items"), - )); - } - Ok(()) -} - -pub fn expect_sort(actual: SmtSort, expected: SmtSort, context: &'static str) -> Result<()> { - if actual != expected { - return Err(FrontendError::invalid( - context, - format!("expected {expected:?}, got {actual:?}"), - )); - } - Ok(()) -} - -pub fn mask_unused_high_bits(width: u32, bytes: &mut [u8]) { - let valid_bits = width % 8; - if valid_bits != 0 { - if let Some(last) = bytes.last_mut() { - *last &= (1u8 << valid_bits) - 1; - } - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct LoweredScript { - pub want_model: bool, - pub want_core: bool, - pub get_values: Vec, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct LoweredExpr { - pub node: N, - pub sort: SmtSort, -} - -#[derive(Debug, Clone)] -struct FunctionBinding { - params: Vec<(String, SmtSort)>, - result: SmtSort, - body: SExpr, -} - -pub fn lower_script( - script: &str, - sink: &mut S, - options: &FrontendOptions, -) -> Result { - let exprs = parse_sexprs(script)?; - let mut lowerer = ScriptLowerer::new(sink, options.clone()); - lowerer.lower_script(exprs) -} - -fn sink_result(result: std::result::Result) -> Result { - result.map_err(|err| FrontendError::Sink(err.to_string())) -} - -type UnarySinkOp = fn( - &mut S, - ::Node, -) -> std::result::Result<::Node, ::Error>; -type BinarySinkOp = fn( - &mut S, - ::Node, - ::Node, -) -> std::result::Result<::Node, ::Error>; - -struct ScriptLowerer<'a, S: QfBvSink> { - sink: &'a mut S, - options: FrontendOptions, - env: HashMap>, - declared_symbols: HashMap, - functions: HashMap, - expansion_depth: usize, - want_model: bool, - want_core: bool, - get_values: Vec, - saw_check_sat: bool, -} - -impl<'a, S: QfBvSink> ScriptLowerer<'a, S> { - fn new(sink: &'a mut S, options: FrontendOptions) -> Self { - Self { - sink, - options, - env: HashMap::new(), - declared_symbols: HashMap::new(), - functions: HashMap::new(), - expansion_depth: 0, - want_model: false, - want_core: false, - get_values: Vec::new(), - saw_check_sat: false, - } - } - - fn lower_script(&mut self, exprs: Vec) -> Result { - for expr in exprs { - let list = match expr { - SExpr::List(list) => list, - SExpr::Atom(atom) => { - return Err(FrontendError::invalid( - "SMT-LIB command", - format!("top-level atom {atom:?}"), - )) - } - }; - if list.is_empty() { - continue; - } - self.command(&list)?; - } - if self.options.require_check_sat && !self.saw_check_sat { - return Err(FrontendError::invalid( - "SMT-LIB script", - "script does not contain check-sat", - )); - } - Ok(LoweredScript { - want_model: self.want_model, - want_core: self.want_core, - get_values: std::mem::take(&mut self.get_values), - }) - } - - fn command(&mut self, list: &[SExpr]) -> Result<()> { - let cmd = atom(&list[0])?; - match cmd { - "set-logic" => self.set_logic(list), - "set-option" | "set-info" | "echo" | "exit" => Ok(()), - "push" => self.push_command(list), - "pop" => self.pop_command(list), - "reset" | "reset-assertions" => Err(FrontendError::Unsupported(format!( - "command {cmd} is not supported" - ))), - "declare-const" => self.declare_const(list), - "declare-fun" => self.declare_fun(list), - "define-const" => self.define_const(list), - "define-fun" => self.define_fun(list), - "assert" => self.assert_command(list), - "check-sat" => { - expect_len(list, 1, "check-sat")?; - self.saw_check_sat = true; - Ok(()) - } - "check-sat-assuming" => self.check_sat_assuming(list), - "get-model" => { - expect_len(list, 1, "get-model")?; - self.want_model = true; - Ok(()) - } - "get-value" => self.get_value_command(list), - "get-unsat-core" => { - expect_len(list, 1, "get-unsat-core")?; - self.want_core = true; - Ok(()) - } - other => Err(FrontendError::Unsupported(format!( - "SMT-LIB command {other}" - ))), - } - } - - fn set_logic(&self, list: &[SExpr]) -> Result<()> { - expect_len(list, 2, "set-logic")?; - let logic = atom(&list[1])?; - let accepted = match self.options.accepted_logics { - AcceptedLogics::QfBvOnly => logic == "QF_BV", - AcceptedLogics::QfBvOrAll => logic == "QF_BV" || logic == "ALL", - }; - if accepted { - Ok(()) - } else { - Err(FrontendError::invalid( - "set-logic", - format!("unsupported logic {logic:?}"), - )) - } - } - - fn command_level(&self, list: &[SExpr], context: &'static str) -> Result { - if list.len() == 1 { - return Ok(1); - } - if list.len() != 2 { - return Err(FrontendError::invalid(context, "expected optional level")); - } - parse_u32_atom(&list[1], context) - } - - fn push_command(&mut self, list: &[SExpr]) -> Result<()> { - let levels = self.command_level(list, "push")?; - match self.options.incremental_policy { - IncrementalPolicy::RejectPushPop => Err(FrontendError::invalid( - "SMT-LIB incremental command", - "push is not supported on this frontend", - )), - IncrementalPolicy::SimulatePushPop => { - for _ in 0..levels { - sink_result(self.sink.push())?; - } - Ok(()) - } - } - } - - fn pop_command(&mut self, list: &[SExpr]) -> Result<()> { - let levels = self.command_level(list, "pop")?; - match self.options.incremental_policy { - IncrementalPolicy::RejectPushPop => Err(FrontendError::invalid( - "SMT-LIB incremental command", - "pop is not supported on this frontend", - )), - IncrementalPolicy::SimulatePushPop => { - for _ in 0..levels { - sink_result(self.sink.pop())?; - } - Ok(()) - } - } - } - - fn declare_const(&mut self, list: &[SExpr]) -> Result<()> { - expect_len(list, 3, "declare-const")?; - let name = atom(&list[1])?.to_owned(); - let sort = parse_sort(&list[2])?; - let node = match sort { - SmtSort::Bool => sink_result(self.sink.bool_var(&name))?, - SmtSort::Bv(width) => sink_result(self.sink.bv_var(&name, width))?, - }; - self.env.insert(name.clone(), LoweredExpr { node, sort }); - self.declared_symbols.insert(name, sort); - Ok(()) - } - - fn declare_fun(&mut self, list: &[SExpr]) -> Result<()> { - expect_len(list, 4, "declare-fun")?; - match &list[2] { - SExpr::List(args) if args.is_empty() => {} - _ => { - return Err(FrontendError::Unsupported( - "only 0-arity declare-fun is supported".to_owned(), - )) - } - } - self.declare_const(&[list[0].clone(), list[1].clone(), list[3].clone()]) - } - - fn define_const(&mut self, list: &[SExpr]) -> Result<()> { - expect_len(list, 4, "define-const")?; - let name = atom(&list[1])?.to_owned(); - let declared = parse_sort(&list[2])?; - let binding = self.expr_with_locals(&list[3], &mut HashMap::new())?; - expect_sort(binding.sort, declared, "define-const")?; - self.env.insert(name, binding); - Ok(()) - } - - fn define_fun(&mut self, list: &[SExpr]) -> Result<()> { - expect_len(list, 5, "define-fun")?; - let name = atom(&list[1])?.to_owned(); - let params = parse_function_params(&list[2])?; - if params.is_empty() { - return self.define_const(&[ - list[0].clone(), - list[1].clone(), - list[3].clone(), - list[4].clone(), - ]); - } - let result = parse_sort(&list[3])?; - self.functions.insert( - name, - FunctionBinding { - params, - result, - body: list[4].clone(), - }, - ); - Ok(()) - } - - fn assert_command(&mut self, list: &[SExpr]) -> Result<()> { - expect_len(list, 2, "assert")?; - let (expr, name) = match named_annotation(&list[1])? { - Some((inner, name)) => (inner, Some(name)), - None => (&list[1], None), - }; - let binding = self.expr_with_locals(expr, &mut HashMap::new())?; - expect_sort(binding.sort, SmtSort::Bool, "assert")?; - sink_result(self.sink.assert(binding.node, name.as_deref())) - } - - fn check_sat_assuming(&mut self, list: &[SExpr]) -> Result<()> { - expect_len(list, 2, "check-sat-assuming")?; - let assumptions = match &list[1] { - SExpr::List(items) => items, - _ => { - return Err(FrontendError::invalid( - "check-sat-assuming", - "expected assumption list", - )) - } - }; - for item in assumptions { - let binding = self.expr_with_locals(item, &mut HashMap::new())?; - expect_sort(binding.sort, SmtSort::Bool, "check-sat-assuming")?; - sink_result(self.sink.assume(binding.node))?; - } - self.saw_check_sat = true; - Ok(()) - } - - fn get_value_command(&mut self, list: &[SExpr]) -> Result<()> { - expect_len(list, 2, "get-value")?; - let terms = match &list[1] { - SExpr::List(items) => items, - _ => return Err(FrontendError::invalid("get-value", "expected term list")), - }; - self.want_model = true; - for term in terms { - match (self.options.get_value_policy, term) { - (GetValuePolicy::SymbolsOnly, SExpr::Atom(name)) => { - if !self.declared_symbols.contains_key(name) { - return Err(FrontendError::invalid( - "get-value", - format!("unknown declared symbol {name:?}"), - )); - } - let binding = self.env.get(name).copied().ok_or_else(|| { - FrontendError::invalid("get-value", format!("undefined symbol {name:?}")) - })?; - let tautology = self.equality_node(binding, binding, "get-value")?; - sink_result(self.sink.assert(tautology, None))?; - self.get_values.push(name.clone()); - } - (GetValuePolicy::SymbolsOnly, _) => { - return Err(FrontendError::Unsupported( - "get-value currently supports declared symbols".to_owned(), - )) - } - } - } - Ok(()) - } - - fn expr_with_locals( - &mut self, - expr: &SExpr, - locals: &mut HashMap>, - ) -> Result> { - match expr { - SExpr::Atom(value) => self.atom_expr(value, locals), - SExpr::List(items) => self.list_expr(items, locals), - } - } - - fn atom_expr( - &mut self, - value: &str, - locals: &HashMap>, - ) -> Result> { - if value == "true" { - return Ok(LoweredExpr { - node: sink_result(self.sink.bool_const(true))?, - sort: SmtSort::Bool, - }); - } - if value == "false" { - return Ok(LoweredExpr { - node: sink_result(self.sink.bool_const(false))?, - sort: SmtSort::Bool, - }); - } - if let Some((digits, radix)) = value - .strip_prefix("#b") - .map(|s| (s, 2)) - .or_else(|| value.strip_prefix("#x").map(|s| (s, 16))) - { - let width = if radix == 2 { - digits.len() as u32 - } else { - digits.len() as u32 * 4 - }; - let bytes = literal_bytes(digits, radix, width, value)?; - return Ok(LoweredExpr { - node: sink_result(self.sink.bv_const(&bytes, width))?, - sort: SmtSort::Bv(width), - }); - } - locals - .get(value) - .or_else(|| self.env.get(value)) - .copied() - .ok_or_else(|| { - FrontendError::invalid("SMT-LIB symbol", format!("undefined symbol {value:?}")) - }) - } - - fn list_expr( - &mut self, - items: &[SExpr], - locals: &mut HashMap>, - ) -> Result> { - if items.is_empty() { - return Err(FrontendError::invalid("SMT-LIB expression", "empty list")); - } - if let SExpr::List(op_items) = &items[0] { - return self.indexed_op(op_items, &items[1..], locals); - } - if atom(&items[0])? == "_" { - return self.indexed_literal(items); - } - let op = atom(&items[0])?; - if let Some(function) = self.functions.get(op).cloned() { - return self.function_call(op, &function, &items[1..], locals); - } - match op { - "!" => { - let Some((term, _)) = parse_annotation(items)? else { - return Err(FrontendError::invalid("annotation", "expected annotation")); - }; - self.expr_with_locals(term, locals) - } - "let" => self.let_expr(items, locals), - "ite" => self.ite_expr(items, locals), - "=" => self.equals(&items[1..], locals), - "distinct" => self.distinct(&items[1..], locals), - "not" => self.unary_bool(items, locals, S::bool_not), - "and" => self.fold_bool(&items[1..], locals, true, S::bool_and), - "or" => self.fold_bool(&items[1..], locals, false, S::bool_or), - "=>" => self.binary_bool(items, locals, S::bool_implies), - "xor" => self.binary_bool(items, locals, S::bool_xor), - "bvnot" => self.unary_bv(items, locals, S::bv_not), - "bvneg" => self.unary_bv(items, locals, S::bv_neg), - "bvand" => self.fold_bv(items, locals, S::bv_and), - "bvnand" => self.inverted_fold_bv(items, locals, S::bv_and), - "bvor" => self.fold_bv(items, locals, S::bv_or), - "bvnor" => self.inverted_fold_bv(items, locals, S::bv_or), - "bvxor" => self.fold_bv(items, locals, S::bv_xor), - "bvxnor" => self.inverted_fold_bv(items, locals, S::bv_xor), - "bvadd" => self.fold_bv(items, locals, S::bv_add), - "bvsub" => self.binary_bv(items, locals, S::bv_sub), - "bvmul" => self.fold_bv(items, locals, S::bv_mul), - "bvudiv" => self.binary_bv(items, locals, S::bv_udiv), - "bvurem" => self.binary_bv(items, locals, S::bv_urem), - "bvsdiv" => self.binary_bv(items, locals, S::bv_sdiv), - "bvsrem" => self.binary_bv(items, locals, S::bv_srem), - "bvsmod" => self.binary_bv(items, locals, S::bv_smod), - "bvshl" => self.binary_bv(items, locals, S::bv_shl), - "bvlshr" => self.binary_bv(items, locals, S::bv_lshr), - "bvashr" => self.binary_bv(items, locals, S::bv_ashr), - "bvcomp" => self.bvcomp(items, locals), - "concat" => self.concat(items, locals), - "bvult" => self.bv_cmp(items, locals, S::bv_ult), - "bvule" => self.bv_cmp(items, locals, S::bv_ule), - "bvugt" => self.bv_cmp(items, locals, |sink, a, b| sink.bv_ult(b, a)), - "bvuge" => self.bv_cmp(items, locals, |sink, a, b| sink.bv_ule(b, a)), - "bvslt" => self.bv_cmp(items, locals, S::bv_slt), - "bvsle" => self.bv_cmp(items, locals, S::bv_sle), - "bvsgt" => self.bv_cmp(items, locals, |sink, a, b| sink.bv_slt(b, a)), - "bvsge" => self.bv_cmp(items, locals, |sink, a, b| sink.bv_sle(b, a)), - "bvuaddo" | "uaddo" => self.overflow_cmp(items, locals, S::uadd_ovf), - "bvsaddo" | "saddo" => self.overflow_cmp(items, locals, S::sadd_ovf), - "bvusubo" | "usubo" => self.overflow_cmp(items, locals, S::usub_ovf), - "bvssubo" | "ssubo" => self.overflow_cmp(items, locals, S::ssub_ovf), - "bvumulo" | "umulo" => self.overflow_cmp(items, locals, S::umul_ovf), - "bvsmulo" | "smulo" => self.overflow_cmp(items, locals, S::smul_ovf), - "bvsdivo" | "sdivo" => self.overflow_cmp(items, locals, S::sdiv_ovf), - "bvnego" | "nego" => self.unary_overflow(items, locals, S::neg_ovf), - other => Err(FrontendError::Unsupported(format!( - "SMT-LIB operator {other}" - ))), - } - } - - fn function_call( - &mut self, - name: &str, - function: &FunctionBinding, - args: &[SExpr], - locals: &mut HashMap>, - ) -> Result> { - if args.len() != function.params.len() { - return Err(FrontendError::invalid( - "define-fun application", - format!( - "{name} expected {} arguments, got {}", - function.params.len(), - args.len() - ), - )); - } - if self.expansion_depth >= self.options.max_macro_expansion_depth { - return Err(FrontendError::invalid( - "define-fun application", - "macro expansion depth exceeded", - )); - } - let mut expansion_locals = HashMap::with_capacity(function.params.len()); - for ((param_name, param_sort), arg) in function.params.iter().zip(args) { - let binding = self.expr_with_locals(arg, locals)?; - expect_sort(binding.sort, *param_sort, "define-fun application")?; - expansion_locals.insert(param_name.clone(), binding); - } - self.expansion_depth += 1; - let result = self.expr_with_locals(&function.body, &mut expansion_locals); - self.expansion_depth -= 1; - let binding = result?; - expect_sort(binding.sort, function.result, "define-fun result")?; - Ok(binding) - } - - fn indexed_literal(&mut self, items: &[SExpr]) -> Result> { - let (bytes, width) = indexed_bv_literal_bytes(items)?; - Ok(LoweredExpr { - node: sink_result(self.sink.bv_const(&bytes, width))?, - sort: SmtSort::Bv(width), - }) - } - - fn indexed_op( - &mut self, - op_items: &[SExpr], - args: &[SExpr], - locals: &mut HashMap>, - ) -> Result> { - if op_items.len() == 4 && atom(&op_items[0])? == "_" && atom(&op_items[1])? == "extract" { - if args.len() != 1 { - return Err(FrontendError::invalid("extract", "expected one argument")); - } - let hi = parse_u32_atom(&op_items[2], "extract high")?; - let lo = parse_u32_atom(&op_items[3], "extract low")?; - let x = self.expr_with_locals(&args[0], locals)?; - let SmtSort::Bv(_) = x.sort else { - return Err(FrontendError::invalid("extract", "argument is not BV")); - }; - let result_width = hi - .checked_sub(lo) - .and_then(|value| value.checked_add(1)) - .ok_or_else(|| FrontendError::invalid("extract", "invalid bounds"))?; - return Ok(LoweredExpr { - node: sink_result(self.sink.bv_extract(x.node, hi, lo))?, - sort: SmtSort::Bv(result_width), - }); - } - if op_items.len() == 3 && atom(&op_items[0])? == "_" { - if args.len() != 1 { - return Err(FrontendError::invalid( - "indexed operator", - "expected one argument", - )); - } - let amount = parse_u32_atom(&op_items[2], "indexed amount")?; - let x = self.expr_with_locals(&args[0], locals)?; - let SmtSort::Bv(width) = x.sort else { - return Err(FrontendError::invalid( - "indexed operator", - "argument is not BV", - )); - }; - return match atom(&op_items[1])? { - "zero_extend" => { - Ok(LoweredExpr { - node: sink_result(self.sink.bv_zext(x.node, amount))?, - sort: SmtSort::Bv(width.checked_add(amount).ok_or_else(|| { - FrontendError::invalid("zero_extend", "width overflow") - })?), - }) - } - "sign_extend" => { - Ok(LoweredExpr { - node: sink_result(self.sink.bv_sext(x.node, amount))?, - sort: SmtSort::Bv(width.checked_add(amount).ok_or_else(|| { - FrontendError::invalid("sign_extend", "width overflow") - })?), - }) - } - "repeat" => { - if amount == 0 { - return Err(FrontendError::invalid("repeat", "count must be positive")); - } - Ok(LoweredExpr { - node: sink_result(self.sink.bv_repeat(x.node, amount))?, - sort: SmtSort::Bv( - width.checked_mul(amount).ok_or_else(|| { - FrontendError::invalid("repeat", "width overflow") - })?, - ), - }) - } - "rotate_left" => Ok(LoweredExpr { - node: sink_result(self.sink.bv_rotate_left(x.node, amount))?, - sort: SmtSort::Bv(width), - }), - "rotate_right" => Ok(LoweredExpr { - node: sink_result(self.sink.bv_rotate_right(x.node, amount))?, - sort: SmtSort::Bv(width), - }), - _ => Err(FrontendError::Unsupported("indexed operator".to_owned())), - }; - } - Err(FrontendError::Unsupported("indexed operator".to_owned())) - } - - fn let_expr( - &mut self, - items: &[SExpr], - locals: &mut HashMap>, - ) -> Result> { - expect_len(items, 3, "let")?; - let bindings = match &items[1] { - SExpr::List(items) => items, - _ => return Err(FrontendError::invalid("let", "expected binding list")), - }; - let mut parsed_bindings = Vec::with_capacity(bindings.len()); - for binding in bindings { - let pair = match binding { - SExpr::List(pair) if pair.len() == 2 => pair, - _ => return Err(FrontendError::invalid("let", "bad binding")), - }; - let name = atom(&pair[0])?.to_owned(); - if parsed_bindings - .iter() - .any(|(existing, _): &(String, LoweredExpr)| existing == &name) - { - return Err(FrontendError::invalid( - "let", - format!("duplicate binding {name:?}"), - )); - } - let value = self.expr_with_locals(&pair[1], locals)?; - parsed_bindings.push((name, value)); - } - let mut nested = locals.clone(); - for (name, value) in parsed_bindings { - nested.insert(name, value); - } - self.expr_with_locals(&items[2], &mut nested) - } - - fn ite_expr( - &mut self, - items: &[SExpr], - locals: &mut HashMap>, - ) -> Result> { - expect_len(items, 4, "ite")?; - let c = self.expr_with_locals(&items[1], locals)?; - let t = self.expr_with_locals(&items[2], locals)?; - let e = self.expr_with_locals(&items[3], locals)?; - expect_sort(c.sort, SmtSort::Bool, "ite condition")?; - match (t.sort, e.sort) { - (SmtSort::Bool, SmtSort::Bool) => Ok(LoweredExpr { - node: sink_result(self.sink.bool_ite(c.node, t.node, e.node))?, - sort: SmtSort::Bool, - }), - (SmtSort::Bv(w1), SmtSort::Bv(w2)) if w1 == w2 => Ok(LoweredExpr { - node: sink_result(self.sink.bv_ite(c.node, t.node, e.node))?, - sort: SmtSort::Bv(w1), - }), - _ => Err(FrontendError::invalid("ite", "branch sorts differ")), - } - } - - fn equals( - &mut self, - args: &[SExpr], - locals: &mut HashMap>, - ) -> Result> { - if args.len() < 2 { - return Err(FrontendError::invalid( - "=", - "expected at least two arguments", - )); - } - let mut result = sink_result(self.sink.bool_const(true))?; - let mut previous = self.expr_with_locals(&args[0], locals)?; - for arg in &args[1..] { - let next = self.expr_with_locals(arg, locals)?; - let eq = self.equality_node(previous, next, "=")?; - result = sink_result(self.sink.bool_and(result, eq))?; - previous = next; - } - Ok(LoweredExpr { - node: result, - sort: SmtSort::Bool, - }) - } - - fn distinct( - &mut self, - args: &[SExpr], - locals: &mut HashMap>, - ) -> Result> { - if args.len() < 2 { - return Err(FrontendError::invalid( - "distinct", - "expected at least two arguments", - )); - } - let values = args - .iter() - .map(|arg| self.expr_with_locals(arg, locals)) - .collect::>>()?; - let mut result = sink_result(self.sink.bool_const(true))?; - for i in 0..values.len() { - for j in (i + 1)..values.len() { - let eq = self.equality_node(values[i], values[j], "distinct")?; - let ne = sink_result(self.sink.bool_not(eq))?; - result = sink_result(self.sink.bool_and(result, ne))?; - } - } - Ok(LoweredExpr { - node: result, - sort: SmtSort::Bool, - }) - } - - fn equality_node( - &mut self, - a: LoweredExpr, - b: LoweredExpr, - context: &'static str, - ) -> Result { - match (a.sort, b.sort) { - (SmtSort::Bool, SmtSort::Bool) => sink_result(self.sink.bool_eq(a.node, b.node)), - (SmtSort::Bv(w1), SmtSort::Bv(w2)) if w1 == w2 => { - sink_result(self.sink.bv_eq(a.node, b.node)) - } - _ => Err(FrontendError::invalid(context, "argument sorts differ")), - } - } - - fn unary_bool( - &mut self, - items: &[SExpr], - locals: &mut HashMap>, - f: UnarySinkOp, - ) -> Result> { - expect_len(items, 2, "unary bool")?; - let x = self.expr_with_locals(&items[1], locals)?; - expect_sort(x.sort, SmtSort::Bool, "unary bool")?; - Ok(LoweredExpr { - node: sink_result(f(self.sink, x.node))?, - sort: SmtSort::Bool, - }) - } - - fn binary_bool( - &mut self, - items: &[SExpr], - locals: &mut HashMap>, - f: BinarySinkOp, - ) -> Result> { - expect_len(items, 3, "binary bool")?; - let a = self.expr_with_locals(&items[1], locals)?; - let b = self.expr_with_locals(&items[2], locals)?; - expect_sort(a.sort, SmtSort::Bool, "binary bool")?; - expect_sort(b.sort, SmtSort::Bool, "binary bool")?; - Ok(LoweredExpr { - node: sink_result(f(self.sink, a.node, b.node))?, - sort: SmtSort::Bool, - }) - } - - fn fold_bool( - &mut self, - args: &[SExpr], - locals: &mut HashMap>, - identity: bool, - f: BinarySinkOp, - ) -> Result> { - if args.is_empty() { - return Ok(LoweredExpr { - node: sink_result(self.sink.bool_const(identity))?, - sort: SmtSort::Bool, - }); - } - let mut cur = self.expr_with_locals(&args[0], locals)?; - expect_sort(cur.sort, SmtSort::Bool, "fold bool")?; - for arg in &args[1..] { - let next = self.expr_with_locals(arg, locals)?; - expect_sort(next.sort, SmtSort::Bool, "fold bool")?; - cur = LoweredExpr { - node: sink_result(f(self.sink, cur.node, next.node))?, - sort: SmtSort::Bool, - }; - } - Ok(cur) - } - - fn unary_bv( - &mut self, - items: &[SExpr], - locals: &mut HashMap>, - f: UnarySinkOp, - ) -> Result> { - expect_len(items, 2, "unary BV")?; - let x = self.expr_with_locals(&items[1], locals)?; - let SmtSort::Bv(width) = x.sort else { - return Err(FrontendError::invalid("unary BV", "argument is not BV")); - }; - Ok(LoweredExpr { - node: sink_result(f(self.sink, x.node))?, - sort: SmtSort::Bv(width), - }) - } - - fn binary_bv( - &mut self, - items: &[SExpr], - locals: &mut HashMap>, - f: BinarySinkOp, - ) -> Result> { - expect_len(items, 3, "binary BV")?; - let a = self.expr_with_locals(&items[1], locals)?; - let b = self.expr_with_locals(&items[2], locals)?; - self.binary_bv_bindings(a, b, f, "binary BV") - } - - fn fold_bv( - &mut self, - items: &[SExpr], - locals: &mut HashMap>, - f: BinarySinkOp, - ) -> Result> { - if items.len() < 2 { - return Err(FrontendError::invalid( - "BV fold", - "expected at least one argument", - )); - } - let mut cur = self.expr_with_locals(&items[1], locals)?; - let SmtSort::Bv(_) = cur.sort else { - return Err(FrontendError::invalid("BV fold", "argument is not BV")); - }; - for item in &items[2..] { - let next = self.expr_with_locals(item, locals)?; - cur = self.binary_bv_bindings(cur, next, f, "BV fold")?; - } - Ok(cur) - } - - fn inverted_fold_bv( - &mut self, - items: &[SExpr], - locals: &mut HashMap>, - f: BinarySinkOp, - ) -> Result> { - let value = self.fold_bv(items, locals, f)?; - Ok(LoweredExpr { - node: sink_result(self.sink.bv_not(value.node))?, - sort: value.sort, - }) - } - - fn binary_bv_bindings( - &mut self, - a: LoweredExpr, - b: LoweredExpr, - f: BinarySinkOp, - context: &'static str, - ) -> Result> { - let (SmtSort::Bv(w1), SmtSort::Bv(w2)) = (a.sort, b.sort) else { - return Err(FrontendError::invalid(context, "argument is not BV")); - }; - if w1 != w2 { - return Err(FrontendError::invalid(context, "width mismatch")); - } - Ok(LoweredExpr { - node: sink_result(f(self.sink, a.node, b.node))?, - sort: SmtSort::Bv(w1), - }) - } - - fn bvcomp( - &mut self, - items: &[SExpr], - locals: &mut HashMap>, - ) -> Result> { - expect_len(items, 3, "bvcomp")?; - let a = self.expr_with_locals(&items[1], locals)?; - let b = self.expr_with_locals(&items[2], locals)?; - let (SmtSort::Bv(w1), SmtSort::Bv(w2)) = (a.sort, b.sort) else { - return Err(FrontendError::invalid("bvcomp", "argument is not BV")); - }; - if w1 != w2 { - return Err(FrontendError::invalid("bvcomp", "width mismatch")); - } - let eq = sink_result(self.sink.bv_eq(a.node, b.node))?; - let one = sink_result(self.sink.bv_const(&[1], 1))?; - let zero = sink_result(self.sink.bv_const(&[0], 1))?; - Ok(LoweredExpr { - node: sink_result(self.sink.bv_ite(eq, one, zero))?, - sort: SmtSort::Bv(1), - }) - } - - fn concat( - &mut self, - items: &[SExpr], - locals: &mut HashMap>, - ) -> Result> { - expect_len(items, 3, "concat")?; - let a = self.expr_with_locals(&items[1], locals)?; - let b = self.expr_with_locals(&items[2], locals)?; - let (SmtSort::Bv(w1), SmtSort::Bv(w2)) = (a.sort, b.sort) else { - return Err(FrontendError::invalid("concat", "argument is not BV")); - }; - Ok(LoweredExpr { - node: sink_result(self.sink.bv_concat(a.node, b.node))?, - sort: SmtSort::Bv( - w1.checked_add(w2) - .ok_or_else(|| FrontendError::invalid("concat", "width overflow"))?, - ), - }) - } - - fn bv_cmp( - &mut self, - items: &[SExpr], - locals: &mut HashMap>, - f: BinarySinkOp, - ) -> Result> { - let value = self.binary_bv(items, locals, f)?; - Ok(LoweredExpr { - node: value.node, - sort: SmtSort::Bool, - }) - } - - fn overflow_cmp( - &mut self, - items: &[SExpr], - locals: &mut HashMap>, - f: BinarySinkOp, - ) -> Result> { - self.bv_cmp(items, locals, f) - } - - fn unary_overflow( - &mut self, - items: &[SExpr], - locals: &mut HashMap>, - f: UnarySinkOp, - ) -> Result> { - let value = self.unary_bv(items, locals, f)?; - Ok(LoweredExpr { - node: value.node, - sort: SmtSort::Bool, - }) - } -} - -struct SExprAction; - -fn sexpr_atom(value: impl Into) -> SExpr { - SExpr::Atom(value.into()) -} - -fn sexpr_list(items: impl IntoIterator) -> SExpr { - SExpr::List(items.into_iter().collect()) -} - -fn indexed_symbol(symbol: String, indices: Vec) -> SExpr { - if indices.is_empty() { - sexpr_atom(symbol) - } else { - let mut items = Vec::with_capacity(indices.len() + 2); - items.push(sexpr_atom("_")); - items.push(sexpr_atom(symbol)); - items.extend(indices); - sexpr_list(items) - } -} - -fn byte_bits(bytes: &[u8], len: usize) -> String { - let mut out = String::with_capacity(len + 2); - out.push_str("#b"); - for bit in (0..len).rev() { - let byte = bytes[bit / 8]; - out.push(if ((byte >> (bit % 8)) & 1) != 0 { - '1' - } else { - '0' - }); - } - out -} - -fn byte_hex(bytes: &[u8], len: usize) -> String { - let mut out = String::with_capacity(len + 2); - out.push_str("#x"); - for nibble in (0..len).rev() { - let byte = bytes[nibble / 2]; - let value = (byte >> ((nibble % 2) * 4)) & 0xf; - out.push(char::from_digit(u32::from(value), 16).expect("hex digit")); - } - out -} - -fn command(name: &str, args: impl IntoIterator) -> SExpr { - let mut items = vec![sexpr_atom(name)]; - items.extend(args); - sexpr_list(items) -} - -fn vars_to_sexpr(vars: Vec<(String, SExpr)>) -> SExpr { - sexpr_list( - vars.into_iter() - .map(|(name, sort)| sexpr_list([sexpr_atom(name), sort])), - ) -} - -impl ActionOnString for SExprAction { - type Str = String; - - fn on_string(&mut self, _range: Range, s: String) -> ParsingResult { - Ok(s) - } -} - -impl ActionOnConstant for SExprAction { - type Constant = SExpr; - - fn on_constant_binary( - &mut self, - _range: Range, - bytes: Vec, - len: usize, - ) -> ParsingResult { - Ok(sexpr_atom(byte_bits(&bytes, len))) - } - - fn on_constant_hexadecimal( - &mut self, - _range: Range, - bytes: Vec, - len: usize, - ) -> ParsingResult { - Ok(sexpr_atom(byte_hex(&bytes, len))) - } - - fn on_constant_decimal( - &mut self, - _range: Range, - decimal: DBig, - ) -> ParsingResult { - Ok(sexpr_atom(decimal.to_string())) - } - - fn on_constant_numeral( - &mut self, - _range: Range, - numeral: UBig, - ) -> ParsingResult { - Ok(sexpr_atom(numeral.to_string())) - } - - fn on_constant_string( - &mut self, - _range: Range, - string: Self::Str, - ) -> ParsingResult { - Ok(sexpr_atom(string)) - } - - fn on_constant_bool(&mut self, _range: Range, boolean: bool) -> ParsingResult { - Ok(sexpr_atom(if boolean { "true" } else { "false" })) - } -} - -impl ActionOnIndex for SExprAction { - type Index = SExpr; - - fn on_index_numeral(&mut self, _range: Range, index: UBig) -> ParsingResult { - Ok(sexpr_atom(index.to_string())) - } - - fn on_index_symbol(&mut self, _range: Range, index: Self::Str) -> ParsingResult { - Ok(sexpr_atom(index)) - } - - fn on_index_hexadecimal( - &mut self, - _range: Range, - bytes: Vec, - len: usize, - ) -> ParsingResult { - Ok(sexpr_atom(byte_hex(&bytes, len))) - } -} - -impl ActionOnIdentifier for SExprAction { - type Identifier = SExpr; - - fn on_identifier( - &mut self, - _range: Range, - symbol: Self::Str, - indices: Vec, - ) -> ParsingResult { - Ok(indexed_symbol(symbol, indices)) - } -} - -impl ActionOnAttribute for SExprAction { - type Term = SExpr; - type Attribute = SExpr; - - fn on_attribute_keyword( - &mut self, - _range: Range, - keyword: Keyword, - ) -> ParsingResult { - Ok(sexpr_list([sexpr_atom(keyword.to_string())])) - } - - fn on_attribute_constant( - &mut self, - _range: Range, - keyword: Keyword, - constant: Self::Constant, - ) -> ParsingResult { - Ok(sexpr_list([sexpr_atom(keyword.to_string()), constant])) - } - - fn on_attribute_symbol( - &mut self, - _range: Range, - keyword: Keyword, - symbol: Self::Str, - ) -> ParsingResult { - Ok(sexpr_list([ - sexpr_atom(keyword.to_string()), - sexpr_atom(symbol), - ])) - } - - fn on_attribute_named( - &mut self, - _range: Range, - name: Self::Str, - ) -> ParsingResult { - Ok(sexpr_list([sexpr_atom(":named"), sexpr_atom(name)])) - } - - fn on_attribute_pattern( - &mut self, - _range: Range, - patterns: Vec, - ) -> ParsingResult { - Ok(command(":pattern", patterns)) - } -} - -impl ActionOnSort for SExprAction { - type Sort = SExpr; - - fn on_sort( - &mut self, - _range: Range, - identifier: Self::Identifier, - args: Vec, - ) -> ParsingResult { - if args.is_empty() { - Ok(identifier) - } else { - let mut items = vec![identifier]; - items.extend(args); - Ok(sexpr_list(items)) - } - } -} - -impl ActionOnTerm for SExprAction { - fn on_term_constant( - &mut self, - _range: Range, - constant: Self::Constant, - ) -> ParsingResult { - Ok(constant) - } - - fn on_term_identifier( - &mut self, - _range: Range, - identifier: Self::Identifier, - sort: Option, - ) -> ParsingResult { - Ok(match sort { - Some(sort) => command("as", [identifier, sort]), - None => identifier, - }) - } - - fn on_term_app( - &mut self, - _range: Range, - identifier: Self::Identifier, - sort: Option, - args: Vec, - ) -> ParsingResult { - let head = match sort { - Some(sort) => command("as", [identifier, sort]), - None => identifier, - }; - let mut items = vec![head]; - items.extend(args); - Ok(sexpr_list(items)) - } - - fn on_term_let( - &mut self, - _range: Range, - bindings: Vec<(Self::Str, Self::Term)>, - body: Self::Term, - ) -> ParsingResult { - let binding_list = sexpr_list( - bindings - .into_iter() - .map(|(name, term)| sexpr_list([sexpr_atom(name), term])), - ); - Ok(command("let", [binding_list, body])) - } - - fn on_term_lambda( - &mut self, - _range: Range, - names: Vec<(Self::Str, Self::Sort)>, - body: Self::Term, - ) -> ParsingResult { - Ok(command("lambda", [vars_to_sexpr(names), body])) - } - - fn on_term_exists( - &mut self, - _range: Range, - names: Vec<(Self::Str, Self::Sort)>, - body: Self::Term, - ) -> ParsingResult { - Ok(command("exists", [vars_to_sexpr(names), body])) - } - - fn on_term_forall( - &mut self, - _range: Range, - names: Vec<(Self::Str, Self::Sort)>, - body: Self::Term, - ) -> ParsingResult { - Ok(command("forall", [vars_to_sexpr(names), body])) - } - - fn on_term_match( - &mut self, - _range: Range, - scrutinee: Self::Term, - cases: Vec<(Pattern, Self::Term)>, - ) -> ParsingResult { - let case_exprs = cases.into_iter().map(|(_, body)| body); - Ok(command("match", [scrutinee, sexpr_list(case_exprs)])) - } - - fn on_term_annotated( - &mut self, - _range: Range, - t: Self::Term, - attributes: Vec, - ) -> ParsingResult { - let mut items = vec![sexpr_atom("!"), t]; - for attribute in attributes { - match attribute { - SExpr::List(values) => items.extend(values), - atom @ SExpr::Atom(_) => items.push(atom), - } - } - Ok(sexpr_list(items)) - } -} - -impl ParsingAction for SExprAction { - type Command = SExpr; - - fn on_command_assert(&mut self, _range: Range, t: Self::Term) -> ParsingResult { - Ok(command("assert", [t])) - } - - fn on_command_check_sat(&mut self, _range: Range) -> ParsingResult { - Ok(command("check-sat", [])) - } - - fn on_command_check_sat_assuming( - &mut self, - _range: Range, - terms: Vec, - ) -> ParsingResult { - Ok(command("check-sat-assuming", [sexpr_list(terms)])) - } - - fn on_command_declare_const( - &mut self, - _range: Range, - name: Self::Str, - sort: Self::Sort, - ) -> ParsingResult { - Ok(command("declare-const", [sexpr_atom(name), sort])) - } - - fn on_command_declare_datatype( - &mut self, - _range: Range, - name: Self::Str, - _datatype: DatatypeDec, - ) -> ParsingResult { - Ok(command("declare-datatype", [sexpr_atom(name)])) - } - - fn on_command_declare_datatypes( - &mut self, - _range: Range, - _defs: Vec>, - ) -> ParsingResult { - Ok(command("declare-datatypes", [])) - } - - fn on_command_declare_fun( - &mut self, - _range: Range, - name: Self::Str, - input_sorts: Vec, - out_sort: Self::Sort, - ) -> ParsingResult { - Ok(command( - "declare-fun", - [sexpr_atom(name), sexpr_list(input_sorts), out_sort], - )) - } - - fn on_command_declare_sort( - &mut self, - _range: Range, - name: Self::Str, - arity: UBig, - ) -> ParsingResult { - Ok(command( - "declare-sort", - [sexpr_atom(name), sexpr_atom(arity.to_string())], - )) - } - - fn on_command_declare_sort_parameter( - &mut self, - _range: Range, - name: Self::Str, - ) -> ParsingResult { - Ok(command("declare-sort-parameter", [sexpr_atom(name)])) - } - - fn on_command_define_const( - &mut self, - _range: Range, - name: Self::Str, - sort: Self::Sort, - term: Self::Term, - ) -> ParsingResult { - Ok(command("define-const", [sexpr_atom(name), sort, term])) - } - - fn on_command_define_fun( - &mut self, - _range: Range, - definition: FunctionDef, - ) -> ParsingResult { - Ok(command( - "define-fun", - [ - sexpr_atom(definition.name), - vars_to_sexpr(definition.vars), - definition.out_sort, - definition.body, - ], - )) - } - - fn on_command_define_fun_rec( - &mut self, - _range: Range, - definition: FunctionDef, - ) -> ParsingResult { - Ok(command( - "define-fun-rec", - [ - sexpr_atom(definition.name), - vars_to_sexpr(definition.vars), - definition.out_sort, - definition.body, - ], - )) - } - - fn on_command_define_funs_rec( - &mut self, - _range: Range, - _definitions: Vec>, - ) -> ParsingResult { - Ok(command("define-funs-rec", [])) - } - - fn on_command_define_sort( - &mut self, - _range: Range, - name: Self::Str, - params: Vec, - sort: Self::Sort, - ) -> ParsingResult { - Ok(command( - "define-sort", - [ - sexpr_atom(name), - sexpr_list(params.into_iter().map(sexpr_atom)), - sort, - ], - )) - } - - fn on_command_echo(&mut self, _range: Range, s: Self::Str) -> ParsingResult { - Ok(command("echo", [sexpr_atom(s)])) - } - - fn on_command_exit(&mut self, _range: Range) -> ParsingResult { - Ok(command("exit", [])) - } - - fn on_command_get_assertions(&mut self, _range: Range) -> ParsingResult { - Ok(command("get-assertions", [])) - } - - fn on_command_get_assignment(&mut self, _range: Range) -> ParsingResult { - Ok(command("get-assignment", [])) - } - - fn on_command_get_info(&mut self, _range: Range, kw: Keyword) -> ParsingResult { - Ok(command("get-info", [sexpr_atom(kw.to_string())])) - } - - fn on_command_get_model(&mut self, _range: Range) -> ParsingResult { - Ok(command("get-model", [])) - } - - fn on_command_get_option( - &mut self, - _range: Range, - kw: Keyword, - ) -> ParsingResult { - Ok(command("get-option", [sexpr_atom(kw.to_string())])) - } - - fn on_command_get_proof(&mut self, _range: Range) -> ParsingResult { - Ok(command("get-proof", [])) - } - - fn on_command_get_unsat_assumptions(&mut self, _range: Range) -> ParsingResult { - Ok(command("get-unsat-assumptions", [])) - } - - fn on_command_get_unsat_core(&mut self, _range: Range) -> ParsingResult { - Ok(command("get-unsat-core", [])) - } - - fn on_command_get_value( - &mut self, - _range: Range, - ts: Vec, - ) -> ParsingResult { - Ok(command("get-value", [sexpr_list(ts)])) - } - - fn on_command_pop(&mut self, _range: Range, lvl: UBig) -> ParsingResult { - Ok(command("pop", [sexpr_atom(lvl.to_string())])) - } - - fn on_command_push(&mut self, _range: Range, lvl: UBig) -> ParsingResult { - Ok(command("push", [sexpr_atom(lvl.to_string())])) - } - - fn on_command_reset(&mut self, _range: Range) -> ParsingResult { - Ok(command("reset", [])) - } - - fn on_command_reset_assertions(&mut self, _range: Range) -> ParsingResult { - Ok(command("reset-assertions", [])) - } - - fn on_command_set_info( - &mut self, - _range: Range, - attributes: Self::Attribute, - ) -> ParsingResult { - Ok(command("set-info", [attributes])) - } - - fn on_command_set_logic( - &mut self, - _range: Range, - logic: Self::Str, - ) -> ParsingResult { - Ok(command("set-logic", [sexpr_atom(logic)])) - } - - fn on_command_set_option( - &mut self, - _range: Range, - attribute: Self::Attribute, - ) -> ParsingResult { - Ok(command("set-option", [attribute])) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parser_normalizes_indexed_literals_and_annotations() { - let exprs = parse_sexprs( - r#" - (set-logic QF_BV) - (declare-const |x y| (_ BitVec 4)) - (assert (! (= |x y| #xf) :named a0 :foo bar)) - (check-sat) - "#, - ) - .unwrap(); - assert!( - matches!(&exprs[0], SExpr::List(items) if matches!(&items[0], SExpr::Atom(s) if s == "set-logic")) - ); - assert!(format!("{exprs:?}").contains(":named")); - assert!(format!("{exprs:?}").contains("#xf")); - } - - #[test] - fn parser_handles_block_comments() { - let exprs = parse_sexprs("#| comment |# (check-sat)").unwrap(); - assert_eq!( - exprs, - vec![SExpr::List(vec![SExpr::Atom("check-sat".to_owned())])] - ); - } -} +//! Shared QF_BV/Bool SMT-LIB frontend utilities. +//! +//! This crate is intentionally solver-agnostic. It owns the yaspar-based +//! S-expression parser and common frontend policy/sink types; solver crates +//! lower parsed commands through their own adapters. + +use std::{collections::HashMap, fmt}; + +use dashu::{float::DBig, integer::UBig}; +use yaspar::{ + action::{ + ActionOnAttribute, ActionOnConstant, ActionOnIdentifier, ActionOnIndex, ActionOnSort, + ActionOnString, ActionOnTerm, ParsingAction, ParsingResult, Pattern, + }, + ast::{DatatypeDec, DatatypeDef, FunctionDef, Keyword}, + position::Range, +}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SExpr { + Atom(String), + List(Vec), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SmtSort { + Bool, + Bv(u32), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AcceptedLogics { + QfBvOnly, + QfBvOrAll, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum IncrementalPolicy { + RejectPushPop, + SimulatePushPop, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GetValuePolicy { + SymbolsOnly, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FrontendOptions { + pub accepted_logics: AcceptedLogics, + pub incremental_policy: IncrementalPolicy, + pub get_value_policy: GetValuePolicy, + pub require_check_sat: bool, + pub max_macro_expansion_depth: usize, +} + +impl FrontendOptions { + pub fn server_text() -> Self { + Self { + accepted_logics: AcceptedLogics::QfBvOnly, + incremental_policy: IncrementalPolicy::RejectPushPop, + get_value_policy: GetValuePolicy::SymbolsOnly, + require_check_sat: true, + max_macro_expansion_depth: 64, + } + } + + pub fn standalone() -> Self { + Self { + accepted_logics: AcceptedLogics::QfBvOrAll, + incremental_policy: IncrementalPolicy::SimulatePushPop, + get_value_policy: GetValuePolicy::SymbolsOnly, + require_check_sat: true, + max_macro_expansion_depth: 64, + } + } +} + +impl Default for FrontendOptions { + fn default() -> Self { + Self::server_text() + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum FrontendError { + Parse(String), + Unsupported(String), + Invalid { + context: &'static str, + message: String, + }, + Sink(String), +} + +impl FrontendError { + pub fn invalid(context: &'static str, message: impl Into) -> Self { + Self::Invalid { + context, + message: message.into(), + } + } +} + +impl fmt::Display for FrontendError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + FrontendError::Parse(message) => write!(f, "SMT-LIB parse error: {message}"), + FrontendError::Unsupported(message) => { + write!(f, "unsupported SMT-LIB construct: {message}") + } + FrontendError::Invalid { context, message } => { + write!(f, "invalid {context}: {message}") + } + FrontendError::Sink(message) => write!(f, "frontend sink error: {message}"), + } + } +} + +impl std::error::Error for FrontendError {} + +pub type Result = std::result::Result; + +pub trait QfBvSink { + type Node: Copy; + type Error: fmt::Display; + + fn bool_const(&mut self, value: bool) -> std::result::Result; + fn bv_const( + &mut self, + bytes_le: &[u8], + width: u32, + ) -> std::result::Result; + + fn bool_var(&mut self, name: &str) -> std::result::Result; + fn bv_var(&mut self, name: &str, width: u32) -> std::result::Result; + + fn bool_not(&mut self, x: Self::Node) -> std::result::Result; + fn bool_and( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn bool_or( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn bool_implies( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn bool_eq( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn bool_xor( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn bool_ite( + &mut self, + c: Self::Node, + t: Self::Node, + e: Self::Node, + ) -> std::result::Result; + + fn bv_not(&mut self, x: Self::Node) -> std::result::Result; + fn bv_neg(&mut self, x: Self::Node) -> std::result::Result; + fn bv_and( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn bv_or( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn bv_xor( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn bv_add( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn bv_sub( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn bv_mul( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn bv_udiv( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn bv_urem( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn bv_sdiv( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn bv_srem( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn bv_smod( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn bv_shl( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn bv_lshr( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn bv_ashr( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + + fn bv_extract( + &mut self, + x: Self::Node, + hi: u32, + lo: u32, + ) -> std::result::Result; + fn bv_concat( + &mut self, + high: Self::Node, + low: Self::Node, + ) -> std::result::Result; + fn bv_zext( + &mut self, + x: Self::Node, + amount: u32, + ) -> std::result::Result; + fn bv_sext( + &mut self, + x: Self::Node, + amount: u32, + ) -> std::result::Result; + fn bv_repeat( + &mut self, + x: Self::Node, + count: u32, + ) -> std::result::Result; + fn bv_rotate_left( + &mut self, + x: Self::Node, + amount: u32, + ) -> std::result::Result; + fn bv_rotate_right( + &mut self, + x: Self::Node, + amount: u32, + ) -> std::result::Result; + fn bv_ite( + &mut self, + c: Self::Node, + t: Self::Node, + e: Self::Node, + ) -> std::result::Result; + + fn bv_eq( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn bv_ult( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn bv_ule( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn bv_slt( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn bv_sle( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + + fn uadd_ovf( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn sadd_ovf( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn usub_ovf( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn ssub_ovf( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn umul_ovf( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn smul_ovf( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + fn neg_ovf(&mut self, x: Self::Node) -> std::result::Result; + fn sdiv_ovf( + &mut self, + a: Self::Node, + b: Self::Node, + ) -> std::result::Result; + + fn assert( + &mut self, + root: Self::Node, + name: Option<&str>, + ) -> std::result::Result<(), Self::Error>; + fn assume(&mut self, root: Self::Node) -> std::result::Result<(), Self::Error>; + + fn push(&mut self) -> std::result::Result<(), Self::Error>; + fn pop(&mut self) -> std::result::Result<(), Self::Error>; +} + +pub fn parse_sexprs(input: &str) -> Result> { + let mut action = SExprAction; + yaspar::smtlib2::ScriptParser::new() + .parse(&mut action, yaspar::tokenize_str(input, true)) + .map_err(|err| FrontendError::Parse(err.to_string())) +} + +pub fn atom(expr: &SExpr) -> Result<&str> { + match expr { + SExpr::Atom(atom) => Ok(atom), + SExpr::List(_) => Err(FrontendError::invalid("SMT-LIB atom", "expected atom")), + } +} + +pub fn parse_u32_atom(expr: &SExpr, context: &'static str) -> Result { + atom(expr)? + .parse::() + .map_err(|_| FrontendError::invalid(context, "expected u32 numeral")) +} + +pub fn parse_function_params(expr: &SExpr) -> Result> { + let SExpr::List(args) = expr else { + return Err(FrontendError::invalid( + "define-fun", + "expected argument list", + )); + }; + let mut params = Vec::with_capacity(args.len()); + for arg in args { + let SExpr::List(pair) = arg else { + return Err(FrontendError::invalid( + "define-fun", + "argument is not a pair", + )); + }; + expect_len(pair, 2, "define-fun")?; + let name = atom(&pair[0])?.to_owned(); + if params.iter().any(|(existing, _)| existing == &name) { + return Err(FrontendError::invalid( + "define-fun", + format!("duplicate argument {name:?}"), + )); + } + params.push((name, parse_sort(&pair[1])?)); + } + Ok(params) +} + +pub fn parse_sort(expr: &SExpr) -> Result { + match expr { + SExpr::Atom(atom) if atom == "Bool" => Ok(SmtSort::Bool), + SExpr::List(items) + if items.len() == 3 && atom(&items[0])? == "_" && atom(&items[1])? == "BitVec" => + { + let width = atom(&items[2])? + .parse::() + .map_err(|_| FrontendError::invalid("sort", "invalid BitVec width"))?; + validate_bv_width(width, "sort")?; + Ok(SmtSort::Bv(width)) + } + _ => Err(FrontendError::invalid( + "sort", + "expected Bool or (_ BitVec n)", + )), + } +} + +pub fn validate_bv_width(width: u32, context: &'static str) -> Result<()> { + if (1..=65_536).contains(&width) { + Ok(()) + } else { + Err(FrontendError::invalid( + context, + format!("invalid BitVec width {width}"), + )) + } +} + +pub fn decimal_to_le_bytes(text: &str, len: usize) -> Result> { + let mut digits = text + .bytes() + .map(|byte| match byte { + b'0'..=b'9' => Ok(byte - b'0'), + _ => Err(FrontendError::invalid( + "bv literal", + "invalid decimal value", + )), + }) + .collect::>>()?; + let mut out = Vec::with_capacity(len); + while !digits.is_empty() && out.len() < len { + let mut carry = 0u16; + let mut quotient = Vec::new(); + for digit in digits { + let n = carry * 10 + u16::from(digit); + let q = (n / 256) as u8; + carry = n % 256; + if !quotient.is_empty() || q != 0 { + quotient.push(q); + } + } + out.push(carry as u8); + digits = quotient; + } + out.resize(len, 0); + Ok(out) +} + +pub fn indexed_bv_literal_bytes(items: &[SExpr]) -> Result<(Vec, u32)> { + let literal = if items.len() == 4 && atom(&items[1])? == "bv" { + Some((atom(&items[2])?, atom(&items[3])?)) + } else if items.len() == 3 { + let symbol = atom(&items[1])?; + if let Some(value) = symbol.strip_prefix("bv") { + Some((value, atom(&items[2])?)) + } else { + None + } + } else { + None + }; + let Some((value, width)) = literal else { + return Err(FrontendError::invalid( + "indexed literal", + "expected (_ bvN W)", + )); + }; + if value.is_empty() { + return Err(FrontendError::invalid("bv literal", "missing value")); + } + let width = width + .parse::() + .map_err(|_| FrontendError::invalid("bv literal", "invalid width"))?; + validate_bv_width(width, "bv literal")?; + let mut bytes = decimal_to_le_bytes(value, (width as usize).div_ceil(8))?; + mask_unused_high_bits(width, &mut bytes); + Ok((bytes, width)) +} + +pub fn literal_bytes(digits: &str, radix: u32, width: u32, original: &str) -> Result> { + validate_bv_width(width, "bv literal")?; + let mut bytes = vec![0u8; (width as usize).div_ceil(8)]; + for (pos, ch) in digits.chars().rev().enumerate() { + let value = ch.to_digit(radix).ok_or_else(|| { + FrontendError::invalid("bv literal", format!("invalid digit in {original}")) + })?; + if radix == 2 { + if value != 0 { + bytes[pos / 8] |= 1u8 << (pos % 8); + } + } else { + bytes[pos / 2] |= (value as u8) << ((pos % 2) * 4); + } + } + mask_unused_high_bits(width, &mut bytes); + Ok(bytes) +} + +pub fn parse_annotation(items: &[SExpr]) -> Result)>> { + if items.is_empty() || atom(&items[0])? != "!" { + return Ok(None); + } + if items.len() < 4 || !(items.len() - 2).is_multiple_of(2) { + return Err(FrontendError::invalid( + "annotation", + "expected annotated term followed by keyword/value pairs", + )); + } + let mut name = None; + for [key, value] in items[2..].as_chunks::<2>().0 { + let key = atom(key)?; + if !key.starts_with(':') { + return Err(FrontendError::invalid( + "annotation", + "expected annotation keyword", + )); + } + if key == ":named" { + name = Some(atom(value)?.to_owned()); + } + } + Ok(Some((&items[1], name))) +} + +pub fn named_annotation(expr: &SExpr) -> Result> { + let SExpr::List(items) = expr else { + return Ok(None); + }; + let Some((inner, name)) = parse_annotation(items)? else { + return Ok(None); + }; + let Some(name) = name else { + return Ok(None); + }; + Ok(Some((inner, name))) +} + +pub fn expect_len(items: &[SExpr], len: usize, context: &'static str) -> Result<()> { + if items.len() != len { + return Err(FrontendError::invalid( + context, + format!("expected {len} items"), + )); + } + Ok(()) +} + +pub fn expect_sort(actual: SmtSort, expected: SmtSort, context: &'static str) -> Result<()> { + if actual != expected { + return Err(FrontendError::invalid( + context, + format!("expected {expected:?}, got {actual:?}"), + )); + } + Ok(()) +} + +pub fn mask_unused_high_bits(width: u32, bytes: &mut [u8]) { + let valid_bits = width % 8; + if valid_bits != 0 { + if let Some(last) = bytes.last_mut() { + *last &= (1u8 << valid_bits) - 1; + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LoweredScript { + pub want_model: bool, + pub want_core: bool, + pub get_values: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct LoweredExpr { + pub node: N, + pub sort: SmtSort, +} + +#[derive(Debug, Clone)] +struct FunctionBinding { + params: Vec<(String, SmtSort)>, + result: SmtSort, + body: SExpr, +} + +pub fn lower_script( + script: &str, + sink: &mut S, + options: &FrontendOptions, +) -> Result { + let exprs = parse_sexprs(script)?; + let mut lowerer = ScriptLowerer::new(sink, options.clone()); + lowerer.lower_script(exprs) +} + +fn sink_result(result: std::result::Result) -> Result { + result.map_err(|err| FrontendError::Sink(err.to_string())) +} + +type UnarySinkOp = fn( + &mut S, + ::Node, +) -> std::result::Result<::Node, ::Error>; +type BinarySinkOp = fn( + &mut S, + ::Node, + ::Node, +) -> std::result::Result<::Node, ::Error>; + +struct ScriptLowerer<'a, S: QfBvSink> { + sink: &'a mut S, + options: FrontendOptions, + env: HashMap>, + declared_symbols: HashMap, + functions: HashMap, + expansion_depth: usize, + want_model: bool, + want_core: bool, + get_values: Vec, + saw_check_sat: bool, +} + +impl<'a, S: QfBvSink> ScriptLowerer<'a, S> { + fn new(sink: &'a mut S, options: FrontendOptions) -> Self { + Self { + sink, + options, + env: HashMap::new(), + declared_symbols: HashMap::new(), + functions: HashMap::new(), + expansion_depth: 0, + want_model: false, + want_core: false, + get_values: Vec::new(), + saw_check_sat: false, + } + } + + fn lower_script(&mut self, exprs: Vec) -> Result { + for expr in exprs { + let list = match expr { + SExpr::List(list) => list, + SExpr::Atom(atom) => { + return Err(FrontendError::invalid( + "SMT-LIB command", + format!("top-level atom {atom:?}"), + )) + } + }; + if list.is_empty() { + continue; + } + self.command(&list)?; + } + if self.options.require_check_sat && !self.saw_check_sat { + return Err(FrontendError::invalid( + "SMT-LIB script", + "script does not contain check-sat", + )); + } + Ok(LoweredScript { + want_model: self.want_model, + want_core: self.want_core, + get_values: std::mem::take(&mut self.get_values), + }) + } + + fn command(&mut self, list: &[SExpr]) -> Result<()> { + let cmd = atom(&list[0])?; + match cmd { + "set-logic" => self.set_logic(list), + "set-option" | "set-info" | "echo" | "exit" => Ok(()), + "push" => self.push_command(list), + "pop" => self.pop_command(list), + "reset" | "reset-assertions" => Err(FrontendError::Unsupported(format!( + "command {cmd} is not supported" + ))), + "declare-const" => self.declare_const(list), + "declare-fun" => self.declare_fun(list), + "define-const" => self.define_const(list), + "define-fun" => self.define_fun(list), + "assert" => self.assert_command(list), + "check-sat" => { + expect_len(list, 1, "check-sat")?; + self.saw_check_sat = true; + Ok(()) + } + "check-sat-assuming" => self.check_sat_assuming(list), + "get-model" => { + expect_len(list, 1, "get-model")?; + self.want_model = true; + Ok(()) + } + "get-value" => self.get_value_command(list), + "get-unsat-core" => { + expect_len(list, 1, "get-unsat-core")?; + self.want_core = true; + Ok(()) + } + other => Err(FrontendError::Unsupported(format!( + "SMT-LIB command {other}" + ))), + } + } + + fn set_logic(&self, list: &[SExpr]) -> Result<()> { + expect_len(list, 2, "set-logic")?; + let logic = atom(&list[1])?; + let accepted = match self.options.accepted_logics { + AcceptedLogics::QfBvOnly => logic == "QF_BV", + AcceptedLogics::QfBvOrAll => logic == "QF_BV" || logic == "ALL", + }; + if accepted { + Ok(()) + } else { + Err(FrontendError::invalid( + "set-logic", + format!("unsupported logic {logic:?}"), + )) + } + } + + fn command_level(&self, list: &[SExpr], context: &'static str) -> Result { + if list.len() == 1 { + return Ok(1); + } + if list.len() != 2 { + return Err(FrontendError::invalid(context, "expected optional level")); + } + parse_u32_atom(&list[1], context) + } + + fn push_command(&mut self, list: &[SExpr]) -> Result<()> { + let levels = self.command_level(list, "push")?; + match self.options.incremental_policy { + IncrementalPolicy::RejectPushPop => Err(FrontendError::invalid( + "SMT-LIB incremental command", + "push is not supported on this frontend", + )), + IncrementalPolicy::SimulatePushPop => { + for _ in 0..levels { + sink_result(self.sink.push())?; + } + Ok(()) + } + } + } + + fn pop_command(&mut self, list: &[SExpr]) -> Result<()> { + let levels = self.command_level(list, "pop")?; + match self.options.incremental_policy { + IncrementalPolicy::RejectPushPop => Err(FrontendError::invalid( + "SMT-LIB incremental command", + "pop is not supported on this frontend", + )), + IncrementalPolicy::SimulatePushPop => { + for _ in 0..levels { + sink_result(self.sink.pop())?; + } + Ok(()) + } + } + } + + fn declare_const(&mut self, list: &[SExpr]) -> Result<()> { + expect_len(list, 3, "declare-const")?; + let name = atom(&list[1])?.to_owned(); + let sort = parse_sort(&list[2])?; + let node = match sort { + SmtSort::Bool => sink_result(self.sink.bool_var(&name))?, + SmtSort::Bv(width) => sink_result(self.sink.bv_var(&name, width))?, + }; + self.env.insert(name.clone(), LoweredExpr { node, sort }); + self.declared_symbols.insert(name, sort); + Ok(()) + } + + fn declare_fun(&mut self, list: &[SExpr]) -> Result<()> { + expect_len(list, 4, "declare-fun")?; + match &list[2] { + SExpr::List(args) if args.is_empty() => {} + _ => { + return Err(FrontendError::Unsupported( + "only 0-arity declare-fun is supported".to_owned(), + )) + } + } + self.declare_const(&[list[0].clone(), list[1].clone(), list[3].clone()]) + } + + fn define_const(&mut self, list: &[SExpr]) -> Result<()> { + expect_len(list, 4, "define-const")?; + let name = atom(&list[1])?.to_owned(); + let declared = parse_sort(&list[2])?; + let binding = self.expr_with_locals(&list[3], &mut HashMap::new())?; + expect_sort(binding.sort, declared, "define-const")?; + self.env.insert(name, binding); + Ok(()) + } + + fn define_fun(&mut self, list: &[SExpr]) -> Result<()> { + expect_len(list, 5, "define-fun")?; + let name = atom(&list[1])?.to_owned(); + let params = parse_function_params(&list[2])?; + if params.is_empty() { + return self.define_const(&[ + list[0].clone(), + list[1].clone(), + list[3].clone(), + list[4].clone(), + ]); + } + let result = parse_sort(&list[3])?; + self.functions.insert( + name, + FunctionBinding { + params, + result, + body: list[4].clone(), + }, + ); + Ok(()) + } + + fn assert_command(&mut self, list: &[SExpr]) -> Result<()> { + expect_len(list, 2, "assert")?; + let (expr, name) = match named_annotation(&list[1])? { + Some((inner, name)) => (inner, Some(name)), + None => (&list[1], None), + }; + let binding = self.expr_with_locals(expr, &mut HashMap::new())?; + expect_sort(binding.sort, SmtSort::Bool, "assert")?; + sink_result(self.sink.assert(binding.node, name.as_deref())) + } + + fn check_sat_assuming(&mut self, list: &[SExpr]) -> Result<()> { + expect_len(list, 2, "check-sat-assuming")?; + let assumptions = match &list[1] { + SExpr::List(items) => items, + _ => { + return Err(FrontendError::invalid( + "check-sat-assuming", + "expected assumption list", + )) + } + }; + for item in assumptions { + let binding = self.expr_with_locals(item, &mut HashMap::new())?; + expect_sort(binding.sort, SmtSort::Bool, "check-sat-assuming")?; + sink_result(self.sink.assume(binding.node))?; + } + self.saw_check_sat = true; + Ok(()) + } + + fn get_value_command(&mut self, list: &[SExpr]) -> Result<()> { + expect_len(list, 2, "get-value")?; + let terms = match &list[1] { + SExpr::List(items) => items, + _ => return Err(FrontendError::invalid("get-value", "expected term list")), + }; + self.want_model = true; + for term in terms { + match (self.options.get_value_policy, term) { + (GetValuePolicy::SymbolsOnly, SExpr::Atom(name)) => { + if !self.declared_symbols.contains_key(name) { + return Err(FrontendError::invalid( + "get-value", + format!("unknown declared symbol {name:?}"), + )); + } + let binding = self.env.get(name).copied().ok_or_else(|| { + FrontendError::invalid("get-value", format!("undefined symbol {name:?}")) + })?; + let tautology = self.equality_node(binding, binding, "get-value")?; + sink_result(self.sink.assert(tautology, None))?; + self.get_values.push(name.clone()); + } + (GetValuePolicy::SymbolsOnly, _) => { + return Err(FrontendError::Unsupported( + "get-value currently supports declared symbols".to_owned(), + )) + } + } + } + Ok(()) + } + + fn expr_with_locals( + &mut self, + expr: &SExpr, + locals: &mut HashMap>, + ) -> Result> { + match expr { + SExpr::Atom(value) => self.atom_expr(value, locals), + SExpr::List(items) => self.list_expr(items, locals), + } + } + + fn atom_expr( + &mut self, + value: &str, + locals: &HashMap>, + ) -> Result> { + if value == "true" { + return Ok(LoweredExpr { + node: sink_result(self.sink.bool_const(true))?, + sort: SmtSort::Bool, + }); + } + if value == "false" { + return Ok(LoweredExpr { + node: sink_result(self.sink.bool_const(false))?, + sort: SmtSort::Bool, + }); + } + if let Some((digits, radix)) = value + .strip_prefix("#b") + .map(|s| (s, 2)) + .or_else(|| value.strip_prefix("#x").map(|s| (s, 16))) + { + let width = if radix == 2 { + digits.len() as u32 + } else { + digits.len() as u32 * 4 + }; + let bytes = literal_bytes(digits, radix, width, value)?; + return Ok(LoweredExpr { + node: sink_result(self.sink.bv_const(&bytes, width))?, + sort: SmtSort::Bv(width), + }); + } + locals + .get(value) + .or_else(|| self.env.get(value)) + .copied() + .ok_or_else(|| { + FrontendError::invalid("SMT-LIB symbol", format!("undefined symbol {value:?}")) + }) + } + + fn list_expr( + &mut self, + items: &[SExpr], + locals: &mut HashMap>, + ) -> Result> { + if items.is_empty() { + return Err(FrontendError::invalid("SMT-LIB expression", "empty list")); + } + if let SExpr::List(op_items) = &items[0] { + return self.indexed_op(op_items, &items[1..], locals); + } + if atom(&items[0])? == "_" { + return self.indexed_literal(items); + } + let op = atom(&items[0])?; + if let Some(function) = self.functions.get(op).cloned() { + return self.function_call(op, &function, &items[1..], locals); + } + match op { + "!" => { + let Some((term, _)) = parse_annotation(items)? else { + return Err(FrontendError::invalid("annotation", "expected annotation")); + }; + self.expr_with_locals(term, locals) + } + "let" => self.let_expr(items, locals), + "ite" => self.ite_expr(items, locals), + "=" => self.equals(&items[1..], locals), + "distinct" => self.distinct(&items[1..], locals), + "not" => self.unary_bool(items, locals, S::bool_not), + "and" => self.fold_bool(&items[1..], locals, true, S::bool_and), + "or" => self.fold_bool(&items[1..], locals, false, S::bool_or), + "=>" => self.binary_bool(items, locals, S::bool_implies), + "xor" => self.binary_bool(items, locals, S::bool_xor), + "bvnot" => self.unary_bv(items, locals, S::bv_not), + "bvneg" => self.unary_bv(items, locals, S::bv_neg), + "bvand" => self.fold_bv(items, locals, S::bv_and), + "bvnand" => self.inverted_fold_bv(items, locals, S::bv_and), + "bvor" => self.fold_bv(items, locals, S::bv_or), + "bvnor" => self.inverted_fold_bv(items, locals, S::bv_or), + "bvxor" => self.fold_bv(items, locals, S::bv_xor), + "bvxnor" => self.inverted_fold_bv(items, locals, S::bv_xor), + "bvadd" => self.fold_bv(items, locals, S::bv_add), + "bvsub" => self.binary_bv(items, locals, S::bv_sub), + "bvmul" => self.fold_bv(items, locals, S::bv_mul), + "bvudiv" => self.binary_bv(items, locals, S::bv_udiv), + "bvurem" => self.binary_bv(items, locals, S::bv_urem), + "bvsdiv" => self.binary_bv(items, locals, S::bv_sdiv), + "bvsrem" => self.binary_bv(items, locals, S::bv_srem), + "bvsmod" => self.binary_bv(items, locals, S::bv_smod), + "bvshl" => self.binary_bv(items, locals, S::bv_shl), + "bvlshr" => self.binary_bv(items, locals, S::bv_lshr), + "bvashr" => self.binary_bv(items, locals, S::bv_ashr), + "bvcomp" => self.bvcomp(items, locals), + "concat" => self.concat(items, locals), + "bvult" => self.bv_cmp(items, locals, S::bv_ult), + "bvule" => self.bv_cmp(items, locals, S::bv_ule), + "bvugt" => self.bv_cmp(items, locals, |sink, a, b| sink.bv_ult(b, a)), + "bvuge" => self.bv_cmp(items, locals, |sink, a, b| sink.bv_ule(b, a)), + "bvslt" => self.bv_cmp(items, locals, S::bv_slt), + "bvsle" => self.bv_cmp(items, locals, S::bv_sle), + "bvsgt" => self.bv_cmp(items, locals, |sink, a, b| sink.bv_slt(b, a)), + "bvsge" => self.bv_cmp(items, locals, |sink, a, b| sink.bv_sle(b, a)), + "bvuaddo" | "uaddo" => self.overflow_cmp(items, locals, S::uadd_ovf), + "bvsaddo" | "saddo" => self.overflow_cmp(items, locals, S::sadd_ovf), + "bvusubo" | "usubo" => self.overflow_cmp(items, locals, S::usub_ovf), + "bvssubo" | "ssubo" => self.overflow_cmp(items, locals, S::ssub_ovf), + "bvumulo" | "umulo" => self.overflow_cmp(items, locals, S::umul_ovf), + "bvsmulo" | "smulo" => self.overflow_cmp(items, locals, S::smul_ovf), + "bvsdivo" | "sdivo" => self.overflow_cmp(items, locals, S::sdiv_ovf), + "bvnego" | "nego" => self.unary_overflow(items, locals, S::neg_ovf), + other => Err(FrontendError::Unsupported(format!( + "SMT-LIB operator {other}" + ))), + } + } + + fn function_call( + &mut self, + name: &str, + function: &FunctionBinding, + args: &[SExpr], + locals: &mut HashMap>, + ) -> Result> { + if args.len() != function.params.len() { + return Err(FrontendError::invalid( + "define-fun application", + format!( + "{name} expected {} arguments, got {}", + function.params.len(), + args.len() + ), + )); + } + if self.expansion_depth >= self.options.max_macro_expansion_depth { + return Err(FrontendError::invalid( + "define-fun application", + "macro expansion depth exceeded", + )); + } + let mut expansion_locals = HashMap::with_capacity(function.params.len()); + for ((param_name, param_sort), arg) in function.params.iter().zip(args) { + let binding = self.expr_with_locals(arg, locals)?; + expect_sort(binding.sort, *param_sort, "define-fun application")?; + expansion_locals.insert(param_name.clone(), binding); + } + self.expansion_depth += 1; + let result = self.expr_with_locals(&function.body, &mut expansion_locals); + self.expansion_depth -= 1; + let binding = result?; + expect_sort(binding.sort, function.result, "define-fun result")?; + Ok(binding) + } + + fn indexed_literal(&mut self, items: &[SExpr]) -> Result> { + let (bytes, width) = indexed_bv_literal_bytes(items)?; + Ok(LoweredExpr { + node: sink_result(self.sink.bv_const(&bytes, width))?, + sort: SmtSort::Bv(width), + }) + } + + fn indexed_op( + &mut self, + op_items: &[SExpr], + args: &[SExpr], + locals: &mut HashMap>, + ) -> Result> { + if op_items.len() == 4 && atom(&op_items[0])? == "_" && atom(&op_items[1])? == "extract" { + if args.len() != 1 { + return Err(FrontendError::invalid("extract", "expected one argument")); + } + let hi = parse_u32_atom(&op_items[2], "extract high")?; + let lo = parse_u32_atom(&op_items[3], "extract low")?; + let x = self.expr_with_locals(&args[0], locals)?; + let SmtSort::Bv(_) = x.sort else { + return Err(FrontendError::invalid("extract", "argument is not BV")); + }; + let result_width = hi + .checked_sub(lo) + .and_then(|value| value.checked_add(1)) + .ok_or_else(|| FrontendError::invalid("extract", "invalid bounds"))?; + return Ok(LoweredExpr { + node: sink_result(self.sink.bv_extract(x.node, hi, lo))?, + sort: SmtSort::Bv(result_width), + }); + } + if op_items.len() == 3 && atom(&op_items[0])? == "_" { + if args.len() != 1 { + return Err(FrontendError::invalid( + "indexed operator", + "expected one argument", + )); + } + let amount = parse_u32_atom(&op_items[2], "indexed amount")?; + let x = self.expr_with_locals(&args[0], locals)?; + let SmtSort::Bv(width) = x.sort else { + return Err(FrontendError::invalid( + "indexed operator", + "argument is not BV", + )); + }; + return match atom(&op_items[1])? { + "zero_extend" => { + Ok(LoweredExpr { + node: sink_result(self.sink.bv_zext(x.node, amount))?, + sort: SmtSort::Bv(width.checked_add(amount).ok_or_else(|| { + FrontendError::invalid("zero_extend", "width overflow") + })?), + }) + } + "sign_extend" => { + Ok(LoweredExpr { + node: sink_result(self.sink.bv_sext(x.node, amount))?, + sort: SmtSort::Bv(width.checked_add(amount).ok_or_else(|| { + FrontendError::invalid("sign_extend", "width overflow") + })?), + }) + } + "repeat" => { + if amount == 0 { + return Err(FrontendError::invalid("repeat", "count must be positive")); + } + Ok(LoweredExpr { + node: sink_result(self.sink.bv_repeat(x.node, amount))?, + sort: SmtSort::Bv( + width.checked_mul(amount).ok_or_else(|| { + FrontendError::invalid("repeat", "width overflow") + })?, + ), + }) + } + "rotate_left" => Ok(LoweredExpr { + node: sink_result(self.sink.bv_rotate_left(x.node, amount))?, + sort: SmtSort::Bv(width), + }), + "rotate_right" => Ok(LoweredExpr { + node: sink_result(self.sink.bv_rotate_right(x.node, amount))?, + sort: SmtSort::Bv(width), + }), + _ => Err(FrontendError::Unsupported("indexed operator".to_owned())), + }; + } + Err(FrontendError::Unsupported("indexed operator".to_owned())) + } + + fn let_expr( + &mut self, + items: &[SExpr], + locals: &mut HashMap>, + ) -> Result> { + expect_len(items, 3, "let")?; + let bindings = match &items[1] { + SExpr::List(items) => items, + _ => return Err(FrontendError::invalid("let", "expected binding list")), + }; + let mut parsed_bindings = Vec::with_capacity(bindings.len()); + for binding in bindings { + let pair = match binding { + SExpr::List(pair) if pair.len() == 2 => pair, + _ => return Err(FrontendError::invalid("let", "bad binding")), + }; + let name = atom(&pair[0])?.to_owned(); + if parsed_bindings + .iter() + .any(|(existing, _): &(String, LoweredExpr)| existing == &name) + { + return Err(FrontendError::invalid( + "let", + format!("duplicate binding {name:?}"), + )); + } + let value = self.expr_with_locals(&pair[1], locals)?; + parsed_bindings.push((name, value)); + } + let mut nested = locals.clone(); + for (name, value) in parsed_bindings { + nested.insert(name, value); + } + self.expr_with_locals(&items[2], &mut nested) + } + + fn ite_expr( + &mut self, + items: &[SExpr], + locals: &mut HashMap>, + ) -> Result> { + expect_len(items, 4, "ite")?; + let c = self.expr_with_locals(&items[1], locals)?; + let t = self.expr_with_locals(&items[2], locals)?; + let e = self.expr_with_locals(&items[3], locals)?; + expect_sort(c.sort, SmtSort::Bool, "ite condition")?; + match (t.sort, e.sort) { + (SmtSort::Bool, SmtSort::Bool) => Ok(LoweredExpr { + node: sink_result(self.sink.bool_ite(c.node, t.node, e.node))?, + sort: SmtSort::Bool, + }), + (SmtSort::Bv(w1), SmtSort::Bv(w2)) if w1 == w2 => Ok(LoweredExpr { + node: sink_result(self.sink.bv_ite(c.node, t.node, e.node))?, + sort: SmtSort::Bv(w1), + }), + _ => Err(FrontendError::invalid("ite", "branch sorts differ")), + } + } + + fn equals( + &mut self, + args: &[SExpr], + locals: &mut HashMap>, + ) -> Result> { + if args.len() < 2 { + return Err(FrontendError::invalid( + "=", + "expected at least two arguments", + )); + } + let mut result = sink_result(self.sink.bool_const(true))?; + let mut previous = self.expr_with_locals(&args[0], locals)?; + for arg in &args[1..] { + let next = self.expr_with_locals(arg, locals)?; + let eq = self.equality_node(previous, next, "=")?; + result = sink_result(self.sink.bool_and(result, eq))?; + previous = next; + } + Ok(LoweredExpr { + node: result, + sort: SmtSort::Bool, + }) + } + + fn distinct( + &mut self, + args: &[SExpr], + locals: &mut HashMap>, + ) -> Result> { + if args.len() < 2 { + return Err(FrontendError::invalid( + "distinct", + "expected at least two arguments", + )); + } + let values = args + .iter() + .map(|arg| self.expr_with_locals(arg, locals)) + .collect::>>()?; + let mut result = sink_result(self.sink.bool_const(true))?; + for i in 0..values.len() { + for j in (i + 1)..values.len() { + let eq = self.equality_node(values[i], values[j], "distinct")?; + let ne = sink_result(self.sink.bool_not(eq))?; + result = sink_result(self.sink.bool_and(result, ne))?; + } + } + Ok(LoweredExpr { + node: result, + sort: SmtSort::Bool, + }) + } + + fn equality_node( + &mut self, + a: LoweredExpr, + b: LoweredExpr, + context: &'static str, + ) -> Result { + match (a.sort, b.sort) { + (SmtSort::Bool, SmtSort::Bool) => sink_result(self.sink.bool_eq(a.node, b.node)), + (SmtSort::Bv(w1), SmtSort::Bv(w2)) if w1 == w2 => { + sink_result(self.sink.bv_eq(a.node, b.node)) + } + _ => Err(FrontendError::invalid(context, "argument sorts differ")), + } + } + + fn unary_bool( + &mut self, + items: &[SExpr], + locals: &mut HashMap>, + f: UnarySinkOp, + ) -> Result> { + expect_len(items, 2, "unary bool")?; + let x = self.expr_with_locals(&items[1], locals)?; + expect_sort(x.sort, SmtSort::Bool, "unary bool")?; + Ok(LoweredExpr { + node: sink_result(f(self.sink, x.node))?, + sort: SmtSort::Bool, + }) + } + + fn binary_bool( + &mut self, + items: &[SExpr], + locals: &mut HashMap>, + f: BinarySinkOp, + ) -> Result> { + expect_len(items, 3, "binary bool")?; + let a = self.expr_with_locals(&items[1], locals)?; + let b = self.expr_with_locals(&items[2], locals)?; + expect_sort(a.sort, SmtSort::Bool, "binary bool")?; + expect_sort(b.sort, SmtSort::Bool, "binary bool")?; + Ok(LoweredExpr { + node: sink_result(f(self.sink, a.node, b.node))?, + sort: SmtSort::Bool, + }) + } + + fn fold_bool( + &mut self, + args: &[SExpr], + locals: &mut HashMap>, + identity: bool, + f: BinarySinkOp, + ) -> Result> { + if args.is_empty() { + return Ok(LoweredExpr { + node: sink_result(self.sink.bool_const(identity))?, + sort: SmtSort::Bool, + }); + } + let mut cur = self.expr_with_locals(&args[0], locals)?; + expect_sort(cur.sort, SmtSort::Bool, "fold bool")?; + for arg in &args[1..] { + let next = self.expr_with_locals(arg, locals)?; + expect_sort(next.sort, SmtSort::Bool, "fold bool")?; + cur = LoweredExpr { + node: sink_result(f(self.sink, cur.node, next.node))?, + sort: SmtSort::Bool, + }; + } + Ok(cur) + } + + fn unary_bv( + &mut self, + items: &[SExpr], + locals: &mut HashMap>, + f: UnarySinkOp, + ) -> Result> { + expect_len(items, 2, "unary BV")?; + let x = self.expr_with_locals(&items[1], locals)?; + let SmtSort::Bv(width) = x.sort else { + return Err(FrontendError::invalid("unary BV", "argument is not BV")); + }; + Ok(LoweredExpr { + node: sink_result(f(self.sink, x.node))?, + sort: SmtSort::Bv(width), + }) + } + + fn binary_bv( + &mut self, + items: &[SExpr], + locals: &mut HashMap>, + f: BinarySinkOp, + ) -> Result> { + expect_len(items, 3, "binary BV")?; + let a = self.expr_with_locals(&items[1], locals)?; + let b = self.expr_with_locals(&items[2], locals)?; + self.binary_bv_bindings(a, b, f, "binary BV") + } + + fn fold_bv( + &mut self, + items: &[SExpr], + locals: &mut HashMap>, + f: BinarySinkOp, + ) -> Result> { + if items.len() < 2 { + return Err(FrontendError::invalid( + "BV fold", + "expected at least one argument", + )); + } + let mut cur = self.expr_with_locals(&items[1], locals)?; + let SmtSort::Bv(_) = cur.sort else { + return Err(FrontendError::invalid("BV fold", "argument is not BV")); + }; + for item in &items[2..] { + let next = self.expr_with_locals(item, locals)?; + cur = self.binary_bv_bindings(cur, next, f, "BV fold")?; + } + Ok(cur) + } + + fn inverted_fold_bv( + &mut self, + items: &[SExpr], + locals: &mut HashMap>, + f: BinarySinkOp, + ) -> Result> { + let value = self.fold_bv(items, locals, f)?; + Ok(LoweredExpr { + node: sink_result(self.sink.bv_not(value.node))?, + sort: value.sort, + }) + } + + fn binary_bv_bindings( + &mut self, + a: LoweredExpr, + b: LoweredExpr, + f: BinarySinkOp, + context: &'static str, + ) -> Result> { + let (SmtSort::Bv(w1), SmtSort::Bv(w2)) = (a.sort, b.sort) else { + return Err(FrontendError::invalid(context, "argument is not BV")); + }; + if w1 != w2 { + return Err(FrontendError::invalid(context, "width mismatch")); + } + Ok(LoweredExpr { + node: sink_result(f(self.sink, a.node, b.node))?, + sort: SmtSort::Bv(w1), + }) + } + + fn bvcomp( + &mut self, + items: &[SExpr], + locals: &mut HashMap>, + ) -> Result> { + expect_len(items, 3, "bvcomp")?; + let a = self.expr_with_locals(&items[1], locals)?; + let b = self.expr_with_locals(&items[2], locals)?; + let (SmtSort::Bv(w1), SmtSort::Bv(w2)) = (a.sort, b.sort) else { + return Err(FrontendError::invalid("bvcomp", "argument is not BV")); + }; + if w1 != w2 { + return Err(FrontendError::invalid("bvcomp", "width mismatch")); + } + let eq = sink_result(self.sink.bv_eq(a.node, b.node))?; + let one = sink_result(self.sink.bv_const(&[1], 1))?; + let zero = sink_result(self.sink.bv_const(&[0], 1))?; + Ok(LoweredExpr { + node: sink_result(self.sink.bv_ite(eq, one, zero))?, + sort: SmtSort::Bv(1), + }) + } + + fn concat( + &mut self, + items: &[SExpr], + locals: &mut HashMap>, + ) -> Result> { + expect_len(items, 3, "concat")?; + let a = self.expr_with_locals(&items[1], locals)?; + let b = self.expr_with_locals(&items[2], locals)?; + let (SmtSort::Bv(w1), SmtSort::Bv(w2)) = (a.sort, b.sort) else { + return Err(FrontendError::invalid("concat", "argument is not BV")); + }; + Ok(LoweredExpr { + node: sink_result(self.sink.bv_concat(a.node, b.node))?, + sort: SmtSort::Bv( + w1.checked_add(w2) + .ok_or_else(|| FrontendError::invalid("concat", "width overflow"))?, + ), + }) + } + + fn bv_cmp( + &mut self, + items: &[SExpr], + locals: &mut HashMap>, + f: BinarySinkOp, + ) -> Result> { + let value = self.binary_bv(items, locals, f)?; + Ok(LoweredExpr { + node: value.node, + sort: SmtSort::Bool, + }) + } + + fn overflow_cmp( + &mut self, + items: &[SExpr], + locals: &mut HashMap>, + f: BinarySinkOp, + ) -> Result> { + self.bv_cmp(items, locals, f) + } + + fn unary_overflow( + &mut self, + items: &[SExpr], + locals: &mut HashMap>, + f: UnarySinkOp, + ) -> Result> { + let value = self.unary_bv(items, locals, f)?; + Ok(LoweredExpr { + node: value.node, + sort: SmtSort::Bool, + }) + } +} + +struct SExprAction; + +fn sexpr_atom(value: impl Into) -> SExpr { + SExpr::Atom(value.into()) +} + +fn sexpr_list(items: impl IntoIterator) -> SExpr { + SExpr::List(items.into_iter().collect()) +} + +fn indexed_symbol(symbol: String, indices: Vec) -> SExpr { + if indices.is_empty() { + sexpr_atom(symbol) + } else { + let mut items = Vec::with_capacity(indices.len() + 2); + items.push(sexpr_atom("_")); + items.push(sexpr_atom(symbol)); + items.extend(indices); + sexpr_list(items) + } +} + +fn byte_bits(bytes: &[u8], len: usize) -> String { + let mut out = String::with_capacity(len + 2); + out.push_str("#b"); + for bit in (0..len).rev() { + let byte = bytes[bit / 8]; + out.push(if ((byte >> (bit % 8)) & 1) != 0 { + '1' + } else { + '0' + }); + } + out +} + +fn byte_hex(bytes: &[u8], len: usize) -> String { + let mut out = String::with_capacity(len + 2); + out.push_str("#x"); + for nibble in (0..len).rev() { + let byte = bytes[nibble / 2]; + let value = (byte >> ((nibble % 2) * 4)) & 0xf; + out.push(char::from_digit(u32::from(value), 16).expect("hex digit")); + } + out +} + +fn command(name: &str, args: impl IntoIterator) -> SExpr { + let mut items = vec![sexpr_atom(name)]; + items.extend(args); + sexpr_list(items) +} + +fn vars_to_sexpr(vars: Vec<(String, SExpr)>) -> SExpr { + sexpr_list( + vars.into_iter() + .map(|(name, sort)| sexpr_list([sexpr_atom(name), sort])), + ) +} + +impl ActionOnString for SExprAction { + type Str = String; + + fn on_string(&mut self, _range: Range, s: String) -> ParsingResult { + Ok(s) + } +} + +impl ActionOnConstant for SExprAction { + type Constant = SExpr; + + fn on_constant_binary( + &mut self, + _range: Range, + bytes: Vec, + len: usize, + ) -> ParsingResult { + Ok(sexpr_atom(byte_bits(&bytes, len))) + } + + fn on_constant_hexadecimal( + &mut self, + _range: Range, + bytes: Vec, + len: usize, + ) -> ParsingResult { + Ok(sexpr_atom(byte_hex(&bytes, len))) + } + + fn on_constant_decimal( + &mut self, + _range: Range, + decimal: DBig, + ) -> ParsingResult { + Ok(sexpr_atom(decimal.to_string())) + } + + fn on_constant_numeral( + &mut self, + _range: Range, + numeral: UBig, + ) -> ParsingResult { + Ok(sexpr_atom(numeral.to_string())) + } + + fn on_constant_string( + &mut self, + _range: Range, + string: Self::Str, + ) -> ParsingResult { + Ok(sexpr_atom(string)) + } + + fn on_constant_bool(&mut self, _range: Range, boolean: bool) -> ParsingResult { + Ok(sexpr_atom(if boolean { "true" } else { "false" })) + } +} + +impl ActionOnIndex for SExprAction { + type Index = SExpr; + + fn on_index_numeral(&mut self, _range: Range, index: UBig) -> ParsingResult { + Ok(sexpr_atom(index.to_string())) + } + + fn on_index_symbol(&mut self, _range: Range, index: Self::Str) -> ParsingResult { + Ok(sexpr_atom(index)) + } + + fn on_index_hexadecimal( + &mut self, + _range: Range, + bytes: Vec, + len: usize, + ) -> ParsingResult { + Ok(sexpr_atom(byte_hex(&bytes, len))) + } +} + +impl ActionOnIdentifier for SExprAction { + type Identifier = SExpr; + + fn on_identifier( + &mut self, + _range: Range, + symbol: Self::Str, + indices: Vec, + ) -> ParsingResult { + Ok(indexed_symbol(symbol, indices)) + } +} + +impl ActionOnAttribute for SExprAction { + type Term = SExpr; + type Attribute = SExpr; + + fn on_attribute_keyword( + &mut self, + _range: Range, + keyword: Keyword, + ) -> ParsingResult { + Ok(sexpr_list([sexpr_atom(keyword.to_string())])) + } + + fn on_attribute_constant( + &mut self, + _range: Range, + keyword: Keyword, + constant: Self::Constant, + ) -> ParsingResult { + Ok(sexpr_list([sexpr_atom(keyword.to_string()), constant])) + } + + fn on_attribute_symbol( + &mut self, + _range: Range, + keyword: Keyword, + symbol: Self::Str, + ) -> ParsingResult { + Ok(sexpr_list([ + sexpr_atom(keyword.to_string()), + sexpr_atom(symbol), + ])) + } + + fn on_attribute_named( + &mut self, + _range: Range, + name: Self::Str, + ) -> ParsingResult { + Ok(sexpr_list([sexpr_atom(":named"), sexpr_atom(name)])) + } + + fn on_attribute_pattern( + &mut self, + _range: Range, + patterns: Vec, + ) -> ParsingResult { + Ok(command(":pattern", patterns)) + } +} + +impl ActionOnSort for SExprAction { + type Sort = SExpr; + + fn on_sort( + &mut self, + _range: Range, + identifier: Self::Identifier, + args: Vec, + ) -> ParsingResult { + if args.is_empty() { + Ok(identifier) + } else { + let mut items = vec![identifier]; + items.extend(args); + Ok(sexpr_list(items)) + } + } +} + +impl ActionOnTerm for SExprAction { + fn on_term_constant( + &mut self, + _range: Range, + constant: Self::Constant, + ) -> ParsingResult { + Ok(constant) + } + + fn on_term_identifier( + &mut self, + _range: Range, + identifier: Self::Identifier, + sort: Option, + ) -> ParsingResult { + Ok(match sort { + Some(sort) => command("as", [identifier, sort]), + None => identifier, + }) + } + + fn on_term_app( + &mut self, + _range: Range, + identifier: Self::Identifier, + sort: Option, + args: Vec, + ) -> ParsingResult { + let head = match sort { + Some(sort) => command("as", [identifier, sort]), + None => identifier, + }; + let mut items = vec![head]; + items.extend(args); + Ok(sexpr_list(items)) + } + + fn on_term_let( + &mut self, + _range: Range, + bindings: Vec<(Self::Str, Self::Term)>, + body: Self::Term, + ) -> ParsingResult { + let binding_list = sexpr_list( + bindings + .into_iter() + .map(|(name, term)| sexpr_list([sexpr_atom(name), term])), + ); + Ok(command("let", [binding_list, body])) + } + + fn on_term_lambda( + &mut self, + _range: Range, + names: Vec<(Self::Str, Self::Sort)>, + body: Self::Term, + ) -> ParsingResult { + Ok(command("lambda", [vars_to_sexpr(names), body])) + } + + fn on_term_exists( + &mut self, + _range: Range, + names: Vec<(Self::Str, Self::Sort)>, + body: Self::Term, + ) -> ParsingResult { + Ok(command("exists", [vars_to_sexpr(names), body])) + } + + fn on_term_forall( + &mut self, + _range: Range, + names: Vec<(Self::Str, Self::Sort)>, + body: Self::Term, + ) -> ParsingResult { + Ok(command("forall", [vars_to_sexpr(names), body])) + } + + fn on_term_match( + &mut self, + _range: Range, + scrutinee: Self::Term, + cases: Vec<(Pattern, Self::Term)>, + ) -> ParsingResult { + let case_exprs = cases.into_iter().map(|(_, body)| body); + Ok(command("match", [scrutinee, sexpr_list(case_exprs)])) + } + + fn on_term_annotated( + &mut self, + _range: Range, + t: Self::Term, + attributes: Vec, + ) -> ParsingResult { + let mut items = vec![sexpr_atom("!"), t]; + for attribute in attributes { + match attribute { + SExpr::List(values) => items.extend(values), + atom @ SExpr::Atom(_) => items.push(atom), + } + } + Ok(sexpr_list(items)) + } +} + +impl ParsingAction for SExprAction { + type Command = SExpr; + + fn on_command_assert(&mut self, _range: Range, t: Self::Term) -> ParsingResult { + Ok(command("assert", [t])) + } + + fn on_command_check_sat(&mut self, _range: Range) -> ParsingResult { + Ok(command("check-sat", [])) + } + + fn on_command_check_sat_assuming( + &mut self, + _range: Range, + terms: Vec, + ) -> ParsingResult { + Ok(command("check-sat-assuming", [sexpr_list(terms)])) + } + + fn on_command_declare_const( + &mut self, + _range: Range, + name: Self::Str, + sort: Self::Sort, + ) -> ParsingResult { + Ok(command("declare-const", [sexpr_atom(name), sort])) + } + + fn on_command_declare_datatype( + &mut self, + _range: Range, + name: Self::Str, + _datatype: DatatypeDec, + ) -> ParsingResult { + Ok(command("declare-datatype", [sexpr_atom(name)])) + } + + fn on_command_declare_datatypes( + &mut self, + _range: Range, + _defs: Vec>, + ) -> ParsingResult { + Ok(command("declare-datatypes", [])) + } + + fn on_command_declare_fun( + &mut self, + _range: Range, + name: Self::Str, + input_sorts: Vec, + out_sort: Self::Sort, + ) -> ParsingResult { + Ok(command( + "declare-fun", + [sexpr_atom(name), sexpr_list(input_sorts), out_sort], + )) + } + + fn on_command_declare_sort( + &mut self, + _range: Range, + name: Self::Str, + arity: UBig, + ) -> ParsingResult { + Ok(command( + "declare-sort", + [sexpr_atom(name), sexpr_atom(arity.to_string())], + )) + } + + fn on_command_declare_sort_parameter( + &mut self, + _range: Range, + name: Self::Str, + ) -> ParsingResult { + Ok(command("declare-sort-parameter", [sexpr_atom(name)])) + } + + fn on_command_define_const( + &mut self, + _range: Range, + name: Self::Str, + sort: Self::Sort, + term: Self::Term, + ) -> ParsingResult { + Ok(command("define-const", [sexpr_atom(name), sort, term])) + } + + fn on_command_define_fun( + &mut self, + _range: Range, + definition: FunctionDef, + ) -> ParsingResult { + Ok(command( + "define-fun", + [ + sexpr_atom(definition.name), + vars_to_sexpr(definition.vars), + definition.out_sort, + definition.body, + ], + )) + } + + fn on_command_define_fun_rec( + &mut self, + _range: Range, + definition: FunctionDef, + ) -> ParsingResult { + Ok(command( + "define-fun-rec", + [ + sexpr_atom(definition.name), + vars_to_sexpr(definition.vars), + definition.out_sort, + definition.body, + ], + )) + } + + fn on_command_define_funs_rec( + &mut self, + _range: Range, + _definitions: Vec>, + ) -> ParsingResult { + Ok(command("define-funs-rec", [])) + } + + fn on_command_define_sort( + &mut self, + _range: Range, + name: Self::Str, + params: Vec, + sort: Self::Sort, + ) -> ParsingResult { + Ok(command( + "define-sort", + [ + sexpr_atom(name), + sexpr_list(params.into_iter().map(sexpr_atom)), + sort, + ], + )) + } + + fn on_command_echo(&mut self, _range: Range, s: Self::Str) -> ParsingResult { + Ok(command("echo", [sexpr_atom(s)])) + } + + fn on_command_exit(&mut self, _range: Range) -> ParsingResult { + Ok(command("exit", [])) + } + + fn on_command_get_assertions(&mut self, _range: Range) -> ParsingResult { + Ok(command("get-assertions", [])) + } + + fn on_command_get_assignment(&mut self, _range: Range) -> ParsingResult { + Ok(command("get-assignment", [])) + } + + fn on_command_get_info(&mut self, _range: Range, kw: Keyword) -> ParsingResult { + Ok(command("get-info", [sexpr_atom(kw.to_string())])) + } + + fn on_command_get_model(&mut self, _range: Range) -> ParsingResult { + Ok(command("get-model", [])) + } + + fn on_command_get_option( + &mut self, + _range: Range, + kw: Keyword, + ) -> ParsingResult { + Ok(command("get-option", [sexpr_atom(kw.to_string())])) + } + + fn on_command_get_proof(&mut self, _range: Range) -> ParsingResult { + Ok(command("get-proof", [])) + } + + fn on_command_get_unsat_assumptions(&mut self, _range: Range) -> ParsingResult { + Ok(command("get-unsat-assumptions", [])) + } + + fn on_command_get_unsat_core(&mut self, _range: Range) -> ParsingResult { + Ok(command("get-unsat-core", [])) + } + + fn on_command_get_value( + &mut self, + _range: Range, + ts: Vec, + ) -> ParsingResult { + Ok(command("get-value", [sexpr_list(ts)])) + } + + fn on_command_pop(&mut self, _range: Range, lvl: UBig) -> ParsingResult { + Ok(command("pop", [sexpr_atom(lvl.to_string())])) + } + + fn on_command_push(&mut self, _range: Range, lvl: UBig) -> ParsingResult { + Ok(command("push", [sexpr_atom(lvl.to_string())])) + } + + fn on_command_reset(&mut self, _range: Range) -> ParsingResult { + Ok(command("reset", [])) + } + + fn on_command_reset_assertions(&mut self, _range: Range) -> ParsingResult { + Ok(command("reset-assertions", [])) + } + + fn on_command_set_info( + &mut self, + _range: Range, + attributes: Self::Attribute, + ) -> ParsingResult { + Ok(command("set-info", [attributes])) + } + + fn on_command_set_logic( + &mut self, + _range: Range, + logic: Self::Str, + ) -> ParsingResult { + Ok(command("set-logic", [sexpr_atom(logic)])) + } + + fn on_command_set_option( + &mut self, + _range: Range, + attribute: Self::Attribute, + ) -> ParsingResult { + Ok(command("set-option", [attribute])) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parser_normalizes_indexed_literals_and_annotations() { + let exprs = parse_sexprs( + r#" + (set-logic QF_BV) + (declare-const |x y| (_ BitVec 4)) + (assert (! (= |x y| #xf) :named a0 :foo bar)) + (check-sat) + "#, + ) + .unwrap(); + assert!( + matches!(&exprs[0], SExpr::List(items) if matches!(&items[0], SExpr::Atom(s) if s == "set-logic")) + ); + assert!(format!("{exprs:?}").contains(":named")); + assert!(format!("{exprs:?}").contains("#xf")); + } + + #[test] + fn parser_handles_block_comments() { + let exprs = parse_sexprs("#| comment |# (check-sat)").unwrap(); + assert_eq!( + exprs, + vec![SExpr::List(vec![SExpr::Atom("check-sat".to_owned())])] + ); + } +} From b7e2eda7dbd147dedff3367759e25cb6b90122a8 Mon Sep 17 00:00:00 2001 From: Duncan Ogilvie Date: Tue, 24 Nov 2026 19:37:45 +0100 Subject: [PATCH 4/8] Report z3 library directories when the live-server test's server fails to start On Windows the server exits with STATUS_DLL_NOT_FOUND and an empty stderr, which says nothing about where the test looked for libz3.dll. --- python/tests/test_live_server.py | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/python/tests/test_live_server.py b/python/tests/test_live_server.py index 539e487..bfb6529 100644 --- a/python/tests/test_live_server.py +++ b/python/tests/test_live_server.py @@ -31,14 +31,26 @@ def server_binary() -> pathlib.Path: return REPO_ROOT / "target" / "debug" / exe -def server_environment() -> dict[str, str]: - env = os.environ.copy() +def z3_library_dirs() -> list[str]: build_dir = REPO_ROOT / "target" / "debug" / "build" - z3_dirs = [ + return [ str(path) for pattern in ("z3-sys-*/out/z3-*/bin", "z3-sys-*/out/z3-*/lib") for path in build_dir.glob(pattern) ] + + +def describe_z3_library_dirs() -> str: + lines = [] + for directory in z3_library_dirs(): + names = sorted(p.name for p in pathlib.Path(directory).iterdir() if "z3" in p.name.lower()) + lines.append(f" {directory}: {', '.join(names) or '(no z3 files)'}") + return "\n".join(lines) or " (none found)" + + +def server_environment() -> dict[str, str]: + env = os.environ.copy() + z3_dirs = z3_library_dirs() if z3_dirs: sep = os.pathsep env["PATH"] = sep.join(z3_dirs + [env.get("PATH", "")]) @@ -65,7 +77,11 @@ def __enter__(self) -> "LiveServer": while time.time() < deadline: if self.proc.poll() is not None: stderr = self.proc.stderr.read().decode("utf-8", "replace") if self.proc.stderr else "" - raise RuntimeError(f"bv-server exited early with {self.proc.returncode}: {stderr}") + raise RuntimeError( + f"bv-server exited early with {self.proc.returncode}: {stderr}\n" + f"z3 library directories added to the server's search path:\n" + f"{describe_z3_library_dirs()}" + ) try: with socket.create_connection(("127.0.0.1", self.port), timeout=0.2): return self From fd51ac59ac89d3dbf71fd88ca1e651fb9ecac0e2 Mon Sep 17 00:00:00 2001 From: Duncan Ogilvie Date: Tue, 24 Nov 2026 19:43:31 +0100 Subject: [PATCH 5/8] Find z3 DLLs in Cargo's new build-script output layout Newer Cargo puts build-script output in target/debug/build///out instead of target/debug/build/-/out. The live-server test and the C++ CI step only globbed the old layout, so on Windows (the one platform where z3 is a DLL that must be on PATH) they found nothing and the server exited with STATUS_DLL_NOT_FOUND. Match both layouts. --- .github/workflows/ci.yml | 4 +++- python/tests/test_live_server.py | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 01a53af..7d924d7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -72,7 +72,9 @@ jobs: build_dir = root / "target" / "debug" / "build" z3_dirs = [ str(path) - for pattern in ("z3-sys-*/out/z3-*/bin", "z3-sys-*/out/z3-*/lib") + # Older Cargo: build/z3-sys-/out; newer: build/z3-sys//out. + for prefix in ("z3-sys-*", "z3-sys/*") + for pattern in (f"{prefix}/out/z3-*/bin", f"{prefix}/out/z3-*/lib") for path in build_dir.glob(pattern) ] env = os.environ.copy() diff --git a/python/tests/test_live_server.py b/python/tests/test_live_server.py index bfb6529..c6bbb76 100644 --- a/python/tests/test_live_server.py +++ b/python/tests/test_live_server.py @@ -35,7 +35,9 @@ def z3_library_dirs() -> list[str]: build_dir = REPO_ROOT / "target" / "debug" / "build" return [ str(path) - for pattern in ("z3-sys-*/out/z3-*/bin", "z3-sys-*/out/z3-*/lib") + # Older Cargo: build/z3-sys-/out; newer: build/z3-sys//out. + for prefix in ("z3-sys-*", "z3-sys/*") + for pattern in (f"{prefix}/out/z3-*/bin", f"{prefix}/out/z3-*/lib") for path in build_dir.glob(pattern) ] From 4516e5afbb7e07ba1a0b3ad3d80530bc1360be04 Mon Sep 17 00:00:00 2001 From: Duncan Ogilvie Date: Tue, 24 Nov 2026 23:05:16 +0100 Subject: [PATCH 6/8] Downgrade the oversized-response error for legacy clients handle_connection replaced an over-limit response with a BVSR error after dispatch had already downgraded it, so SMTQ clients got a frame they could not parse. --- crates/bv-server/src/server.rs | 5 +++ crates/bv-server/tests/legacy_magic.rs | 49 ++++++++++++++++++++++++-- 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/crates/bv-server/src/server.rs b/crates/bv-server/src/server.rs index a411f5f..6c59211 100644 --- a/crates/bv-server/src/server.rs +++ b/crates/bv-server/src/server.rs @@ -143,6 +143,11 @@ fn handle_connection(mut stream: TcpStream, config: Arc) -> std::i response_payload.len(), config.max_response_bytes )); + // The replacement is built with the current magics; a legacy client + // still needs one it can parse. + if is_legacy_request_payload(&payload) { + downgrade_response_in_place(&mut response_payload); + } } let frame = le::encode_transport_frame(&response_payload) .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))?; diff --git a/crates/bv-server/tests/legacy_magic.rs b/crates/bv-server/tests/legacy_magic.rs index 508f448..a744cdd 100644 --- a/crates/bv-server/tests/legacy_magic.rs +++ b/crates/bv-server/tests/legacy_magic.rs @@ -1,15 +1,21 @@ //! Clients built before the smt-server -> bv-server rename send `SMTQ` requests //! and expect `SMTR` responses with `SMT\0` expression buffers. +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; +use std::thread; +use std::time::Duration; -use bv_server::{dispatch_payload_with_cache, Backend, QueryResult, ResponseCache}; +use bv_server::{ + dispatch_payload_with_cache, serve_tcp, Backend, QueryResult, ResponseCache, ServerConfig, +}; use bv_wire::raw::constants::{EXPR_MAGIC, REQUEST_MAGIC, RESPONSE_MAGIC}; use bv_wire::raw::legacy::{ upgrade_response_in_place, LEGACY_EXPR_MAGIC, LEGACY_REQUEST_MAGIC, LEGACY_RESPONSE_MAGIC, }; -use bv_wire::raw::{BinaryRequest, BinaryResponse, ExprBuilder, SimplifyBlock, Status}; +use bv_wire::raw::{le, BinaryRequest, BinaryResponse, ExprBuilder, SimplifyBlock, Status}; /// Answers SOLVE with SAT and SIMPLIFY by echoing the request's expression. struct EchoBackend { @@ -114,3 +120,42 @@ fn malformed_legacy_request_gets_legacy_error_response() { let response = bv_server::dispatch_payload(b"SMTQ-truncated", &backend); assert_eq!(response[..4], LEGACY_RESPONSE_MAGIC); } + +#[test] +fn oversized_legacy_response_is_replaced_with_legacy_error() { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + drop(listener); + thread::spawn(move || { + let mut config = ServerConfig::new(Arc::new(EchoBackend { + count: Arc::new(AtomicUsize::new(0)), + })); + config.max_response_bytes = 15; + let _ = serve_tcp(addr, config); + }); + + let mut builder = ExprBuilder::new(); + let t = builder.bool_true().unwrap(); + builder.assert(t).unwrap(); + let request = to_legacy_request(builder.build_solve_request(5, 0, false, false).unwrap()); + + let mut stream = (0..100) + .find_map(|_| { + TcpStream::connect(addr) + .map_err(|_| thread::sleep(Duration::from_millis(10))) + .ok() + }) + .expect("server did not start listening"); + stream + .write_all(&le::encode_transport_frame(&request).unwrap()) + .unwrap(); + let mut len = [0u8; 4]; + stream.read_exact(&mut len).unwrap(); + let mut response = vec![0u8; u32::from_le_bytes(len) as usize]; + stream.read_exact(&mut response).unwrap(); + + assert_eq!(response[..4], LEGACY_RESPONSE_MAGIC); + assert!(upgrade_response_in_place(&mut response)); + let response = BinaryResponse::parse(&response).unwrap(); + assert_eq!(response.envelope.status, Status::Error); +} From 468c2a29e2640681b59eb52f6d786500b5f3e64f Mon Sep 17 00:00:00 2001 From: Duncan Ogilvie Date: Tue, 24 Nov 2026 23:27:26 +0100 Subject: [PATCH 7/8] Downgrade the Python Z3 server's oversized-response error for legacy clients Same bug as the Rust server: the size-limit replacement used BVSR. Also run the legacy-magic tests from the script's main(), which had skipped them. --- python/bv_z3_server.py | 4 +++ python/tests/test_z3_server.py | 51 +++++++++++++++++++++++++--------- 2 files changed, 42 insertions(+), 13 deletions(-) diff --git a/python/bv_z3_server.py b/python/bv_z3_server.py index 88c977f..636639c 100644 --- a/python/bv_z3_server.py +++ b/python/bv_z3_server.py @@ -427,6 +427,10 @@ def _handle_connection(self, conn: socket.socket) -> None: 0, f"response payload length {len(response)} exceeds configured maximum {self._max_response_bytes}", ) + # The replacement uses the current magics; a legacy client + # still needs one it can parse. + if payload.startswith(LEGACY_REQUEST_MAGIC): + response = _downgrade_response(response) _safe_send(conn, _frame(response)) except (EOFError, OSError): return diff --git a/python/tests/test_z3_server.py b/python/tests/test_z3_server.py index 86afad0..511ac69 100644 --- a/python/tests/test_z3_server.py +++ b/python/tests/test_z3_server.py @@ -98,19 +98,6 @@ def test_z3_server_minimize_and_maximize_round_trip() -> None: assert maximum.optimum.as_int() == 9 -def main() -> None: - test_z3_server_uses_random_tcp_port() - test_z3_server_simple_sat_model_round_trip() - test_z3_server_unsat_core_round_trip() - test_z3_server_assumptions_affect_solve() - test_z3_server_simplify_is_noop_but_protocol_compatible() - test_z3_server_minimize_and_maximize_round_trip() - - -if __name__ == "__main__": - main() - - def _legacy_request(payload: bytes) -> bytes: assert payload[:4] == bv.REQUEST_MAGIC and payload[32:36] == bv.EXPR_MAGIC return b"SMTQ" + payload[4:32] + b"SMT\0" + payload[36:] @@ -131,3 +118,41 @@ def test_z3_server_answers_legacy_clients_with_legacy_magics() -> None: response = server._dispatch_payload(simplify) assert response[:4] == b"SMTR" assert response[24:28] == b"SMT\0" + + +def test_z3_server_oversized_legacy_response_is_legacy_error() -> None: + with Z3Server.start(port=0, max_response_bytes=15) as server: + ctx = bv.Context() + x = ctx.bv_var("x", 8) + ctx.assert_(ctx.bv_eq(x, 3)) + request = _legacy_request(ctx._build_solve_request(0xA012).payload) + with socket.create_connection(server.address, timeout=5) as sock: + sock.sendall(len(request).to_bytes(4, "little") + request) + length = int.from_bytes(_recv_exact(sock, 4), "little") + response = _recv_exact(sock, length) + assert response[:4] == b"SMTR" + assert bv._parse_response(b"BVSR" + response[4:]).status is bv.Status.ERROR + + +def _recv_exact(sock: socket.socket, size: int) -> bytes: + data = b"" + while len(data) < size: + chunk = sock.recv(size - len(data)) + assert chunk, "server closed the connection" + data += chunk + return data + + +def main() -> None: + test_z3_server_uses_random_tcp_port() + test_z3_server_simple_sat_model_round_trip() + test_z3_server_unsat_core_round_trip() + test_z3_server_assumptions_affect_solve() + test_z3_server_simplify_is_noop_but_protocol_compatible() + test_z3_server_minimize_and_maximize_round_trip() + test_z3_server_answers_legacy_clients_with_legacy_magics() + test_z3_server_oversized_legacy_response_is_legacy_error() + + +if __name__ == "__main__": + main() From bd679cfcfcfdf0d97c062c5940bf13d7dccbec51 Mon Sep 17 00:00:00 2001 From: Duncan Ogilvie Date: Tue, 24 Nov 2026 23:36:40 +0100 Subject: [PATCH 8/8] Run the Python Z3 server tests in CI --- .github/workflows/ci.yml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7d924d7..7ade1a4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -50,6 +50,13 @@ jobs: run: | python -m pip install ./python --target python-pkg-smoke python -c "import sys; sys.path.insert(0, 'python-pkg-smoke'); import bv_wire; ctx = bv_wire.Context(); assert ctx.bv_var('x', 8).width == 8" + - name: Python Z3 server + shell: bash + run: | + # Installs the package's z3 extra into a private directory; the test + # still imports bv_wire and bv_z3_server from python/ itself. + python -m pip install "./python[z3]" --target python-z3-deps + PYTHONPATH=python-z3-deps python python/tests/test_z3_server.py - name: Live server end-to-end run: python python/tests/test_live_server.py - name: C++ client CMake smoke