diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d9e0a6b..cc054ff 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -57,27 +57,6 @@ jobs: - name: Test run: ctest --preset=test - - name: Build and Install - run: | - cmake --preset=default - cmake --build --preset=default - cmake --install build/default --prefix "${{ runner.temp }}/install" - env: - CC: ${{ matrix.cc }} - CXX: ${{ matrix.cxx }} - if: ${{ matrix.cc }} - - - name: Build and Install - run: | - cmake --preset=default - cmake --build --preset=default - cmake --install build/default --prefix "${{ runner.temp }}/install" - if: ${{ !matrix.cc }} - - - name: Check installed package artifacts - run: | - cmake "-DPACKAGE_TEST_PREFIX=${{ runner.temp }}/install" -P build/default/cpp-library-test-package.cmake - clang-tidy: runs-on: ubuntu-latest diff --git a/.scout/memory/index.md b/.scout/memory/index.md index 75a0811..6841c3d 100644 --- a/.scout/memory/index.md +++ b/.scout/memory/index.md @@ -5,5 +5,5 @@ - [[knowledge/detect-metadata-last-ownership-atomically-and-detach-every-child-before-deletion.md|Detect metadata last ownership atomically and detach every child before deletion]] (decision, 1.00) `ownership` `retirement` `concurrency` `metadata` - [[knowledge/keep-scout-knowledge-filenames-discoverable.md|Keep Scout knowledge filenames discoverable]] (discovery, 0.80) `scout` `memory` `search` `file-classification` `filenames` - [[knowledge/let-cpp-library-own-documentation-generation.md|Let cpp-library own documentation generation]] (observation, 0.80) `cmake` `cpp-library` `cpp-library-setup` `documentation` `docs-target` `post-build` -- [[knowledge/portable-private-cpp-thread-linkage.md|Keep resource_test thread linkage portable and private]] (observation, 0.80) `cmake` `resource-test` `threads` `threads-threads` `std-jthread` `std-latch` `pthread` +- [[knowledge/portable-private-cpp-thread-linkage.md|Use cpp-library default portable thread linkage]] (observation, 0.80) `cmake` `resource-test` `threads` `threads-threads` `std-jthread` `std-latch` `pthread` - [[knowledge/preflight-deferred-callable-ownership-before-copying-represented-bytes-while-preserving-empty-arrays.md|Preflight deferred callable ownership before copying represented bytes while preserving empty arrays]] (decision, 1.00) `cloning` `deferred-callables` `arrays` `exception-safety` diff --git a/.scout/memory/knowledge/detect-metadata-last-ownership-atomically-and-detach-every-child-before-deletion.md b/.scout/memory/knowledge/detect-metadata-last-ownership-atomically-and-detach-every-child-before-deletion.md index ef05369..91a9818 100644 --- a/.scout/memory/knowledge/detect-metadata-last-ownership-atomically-and-detach-every-child-before-deletion.md +++ b/.scout/memory/knowledge/detect-metadata-last-ownership-atomically-and-detach-every-child-before-deletion.md @@ -9,9 +9,10 @@ access_count: 1 sources: - "include/cel/runtime/detail/retirement.hpp:14-80" - "src/value_type.cpp:28-33" - - "src/value_type.cpp:67-84" - - "tests/resource_test.cpp:71" - - "tests/resource_test.cpp:144" + - "src/value_type.cpp:68-81" + - "src/value_type.cpp:577" + - "src/value_type.cpp:609" + - "tests/resource_test.cpp:52" tags: ["ownership", "retirement", "concurrency", "metadata"] tier: knowledge source: written @@ -23,4 +24,4 @@ Preserve allocation-free, constant-stack metadata destruction under concurrent r Every concrete disposal callback must detach ALL runtime-owned child edges into the supplied queue before deleting its node. For `type_plan`, this includes field/parameter descriptors, the optional array/range element, and the optional callable result. Leaving even one child to ordinary recursive member destruction defeats the stack bound. Reuse dying nodes' embedded links rather than allocating traversal storage. These ownership operations do not synchronize mutable client callbacks. -Regression evidence is in `tests/resource_test.cpp`: concurrent last-owner disposal counts and callback depth, deferred queue draining, and concurrent root/interior-alias releases preserving shared descendants. Scheduling stress alone is not a deterministic proof of the historical race; preserve the atomic-selection and complete-detachment invariants as well as the tests. +Regression evidence for concurrent last-owner disposal counts and callback depth is in `src/value_type.cpp:577`; deferred queue draining is in `src/value_type.cpp:609`. These guarded in-source cases run in `runtime_in_source_tests`. Concurrent root/interior-alias releases preserving shared descendants remain in `tests/resource_test.cpp:52`, run by `resource_test`. Configure with `cmake --preset test` before building if needed, build with `cmake --build --preset test --target runtime_in_source_tests resource_test`, then run `ctest --preset test -R '^(runtime_in_source_tests|resource_test)$'`. Scheduling stress alone is not a deterministic proof of the historical race; preserve the atomic-selection and complete-detachment invariants as well as the tests. diff --git a/.scout/memory/knowledge/portable-private-cpp-thread-linkage.md b/.scout/memory/knowledge/portable-private-cpp-thread-linkage.md index 91fe5b7..d895745 100644 --- a/.scout/memory/knowledge/portable-private-cpp-thread-linkage.md +++ b/.scout/memory/knowledge/portable-private-cpp-thread-linkage.md @@ -1,5 +1,5 @@ --- -title: "Keep resource_test thread linkage portable and private" +title: "Use cpp-library default portable thread linkage" entity_type: observation confidence: 0.80 created: 2026-11-19T22:24:03Z @@ -7,8 +7,9 @@ last_accessed: 2026-11-19T22:24:03Z last_reinforced: 2026-11-19T22:24:03Z access_count: 1 sources: - - "CMakeLists.txt:31-38" - - "tests/resource_test.cpp:23-36" + - "CMakeLists.txt:6-7" + - "CMakeLists.txt:18-29" + - "docs/runtime-milestone.md:78-88" tags: ["cmake", "resource-test", "threads", "threads-threads", "std-jthread", "std-latch", "pthread"] tier: knowledge source: inferred @@ -17,8 +18,20 @@ relationships: target: "Keep Scout knowledge filenames discoverable" --- -# Keep resource_test thread linkage portable and private +# Use cpp-library default portable thread linkage -Within PROJECT_IS_TOP_LEVEL AND BUILD_TESTING, CMakeLists.txt:31-38 finds Threads and links resource_test PRIVATE to Threads::Threads. The run_concurrently helper in tests/resource_test.cpp:23-36 creates two std::jthread workers behind a std::latch start gate. +The cpp-library 6.2.0 setup enables portable thread support by default. +`CMakeLists.txt` pins that release and calls `cpp_library_setup()` without +opting out. Its setup finds Threads and links the compiled runtime publicly +to `Threads::Threads`; generated test implementations and runners inherit +the requirement. Do not restore the former resource_test-only manual link. -Preserve portable, target-scoped thread linkage while this test uses these facilities. Standard C++ thread APIs do not remove platform compiler/linker requirements such as -pthread; CMake's FindThreads imported target encapsulates those requirements, even when it expands to no additional flags on macOS or another platform. A successful build on such a platform is not evidence that the dependency is redundant. Keep this a private test requirement, not a public dependency for every consumer. Future cpp-library centralization is compatible with this lesson if it supplies the same portable target-scoped requirement. +The metadata and retirement concurrency tests use two `std::jthread` workers +behind a `std::latch` start gate. Public metadata coverage remains in +`tests/resource_test.cpp`; private retirement coverage lives in guarded +in-source tests in `src/value_type.cpp`. + +Standard C++ thread APIs do not remove platform compiler/linker requirements +such as `-pthread`. CMake's imported target encapsulates those requirements, +even when it adds no flags on macOS. A passing build on such a platform does +not establish that the dependency is redundant. diff --git a/.scout/memory/knowledge/preflight-deferred-callable-ownership-before-copying-represented-bytes-while-preserving-empty-arrays.md b/.scout/memory/knowledge/preflight-deferred-callable-ownership-before-copying-represented-bytes-while-preserving-empty-arrays.md index 476f9d1..22e4ff5 100644 --- a/.scout/memory/knowledge/preflight-deferred-callable-ownership-before-copying-represented-bytes-while-preserving-empty-arrays.md +++ b/.scout/memory/knowledge/preflight-deferred-callable-ownership-before-copying-represented-bytes-while-preserving-empty-arrays.md @@ -7,10 +7,13 @@ last_accessed: 2026-11-19T22:26:06Z last_reinforced: 2026-11-19T22:26:06Z access_count: 1 sources: - - "src/value_ops.hpp:54-73" - - "src/value.cpp:182-246" - - "tests/value_test.cpp:723" - - "tests/value_test.cpp:798" + - "src/value_ops.hpp:54-70" + - "src/value.cpp:183-282" + - "src/value.cpp:936" + - "src/value.cpp:946" + - "src/value.cpp:978" + - "src/value.cpp:1000" + - "src/value.cpp:1021" tags: ["cloning", "deferred-callables", "arrays", "exception-safety"] tier: knowledge source: written @@ -22,4 +25,4 @@ When cloning raw canonical values, reject callable values lacking installed clon Preflight fixed callable carriers before bulk copying fixed payload bytes. At each nonempty array boundary, use the REQUESTED element descriptor to check direct callable ownership before copying any packed element bytes; do not substitute the source array owner's installed descriptor, which could bypass the requested type's rejection. Recurse through array structure iteratively as needed. Empty arrays do not require ownership operations for an element value that does not exist. -On failure, release every initialized sibling/prefix and leave the destination uninitialized. Preserve the before-read, nested-array, partial-cleanup, and empty/nested-empty cases in `tests/value_test.cpp`. Do not replace these behavioral checks with type-only rejection of every descriptor containing a deferred callable. +On failure, release every initialized sibling/prefix and leave the destination uninitialized. Preserve the fixed-aggregate before-read case in `src/value.cpp:936`, the packed-array before-read case at `:946`, nested-array rejection at `:978`, initialized-prefix cleanup at `:1000`, and empty/nested-empty arrays at `:1021`. These guarded in-source cases run in `runtime_in_source_tests`. Configure with `cmake --preset test`, build with `cmake --build --preset test --target runtime_in_source_tests`, then run `ctest --preset test -R '^runtime_in_source_tests$'`. Do not replace these behavioral checks with type-only rejection of every descriptor containing a deferred callable. diff --git a/CMakeLists.txt b/CMakeLists.txt index 586a6dd..a5cd15d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -3,7 +3,7 @@ cmake_minimum_required(VERSION 3.24) include(cmake/CPM.cmake) # Fetch cpp-library before project() -CPMAddPackage("gh:stlab/cpp-library@6.1.0") +CPMAddPackage("gh:stlab/cpp-library@6.2.0") include(${cpp-library_SOURCE_DIR}/cpp-library.cmake) # Enable dependency tracking before project() @@ -28,12 +28,10 @@ cpp_library_setup( DOCS_OPTIONS "USE_MDFILE_AS_MAINPAGE = ${CMAKE_CURRENT_SOURCE_DIR}/README.md" ) -if(PROJECT_IS_TOP_LEVEL AND BUILD_TESTING) - foreach(test storage_test raw_execution_test value_test resource_test segment_test - callable_test executable_retirement_test composite_execution_test) - target_include_directories(${test} PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src") - endforeach() - - find_package(Threads REQUIRED) - target_link_libraries(resource_test PRIVATE Threads::Threads) -endif() +# Same-directory includes suffice; do not propagate private headers to standalone tests. +get_property(runtime_targets DIRECTORY PROPERTY BUILDSYSTEM_TARGETS) +foreach(runtime_target IN LISTS runtime_targets) + get_property(runtime_includes TARGET "${runtime_target}" PROPERTY INCLUDE_DIRECTORIES) + list(REMOVE_ITEM runtime_includes "${CMAKE_CURRENT_SOURCE_DIR}/src") + set_property(TARGET "${runtime_target}" PROPERTY INCLUDE_DIRECTORIES "${runtime_includes}") +endforeach() diff --git a/CMakePresets.json b/CMakePresets.json index f6d7e7a..2efd009 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -8,6 +8,7 @@ "binaryDir": "${sourceDir}/build/default", "generator": "Ninja", "cacheVariables": { + "CEL_INSTALL": "OFF", "CMAKE_BUILD_TYPE": "Release", "BUILD_TESTING": "OFF", "CMAKE_EXPORT_COMPILE_COMMANDS": "ON", @@ -22,6 +23,7 @@ "binaryDir": "${sourceDir}/build/test", "generator": "Ninja", "cacheVariables": { + "CEL_INSTALL": "OFF", "CMAKE_BUILD_TYPE": "Debug", "BUILD_TESTING": "ON", "CMAKE_EXPORT_COMPILE_COMMANDS": "ON", @@ -36,6 +38,7 @@ "binaryDir": "${sourceDir}/build/docs", "generator": "Ninja", "cacheVariables": { + "CEL_INSTALL": "OFF", "CMAKE_BUILD_TYPE": "Release", "BUILD_TESTING": "OFF", "BUILD_DOCS": "ON", @@ -51,6 +54,7 @@ "binaryDir": "${sourceDir}/build/clang-tidy", "generator": "Ninja", "cacheVariables": { + "CEL_INSTALL": "OFF", "CMAKE_BUILD_TYPE": "Debug", "BUILD_TESTING": "ON", "CMAKE_EXPORT_COMPILE_COMMANDS": "ON", @@ -66,6 +70,7 @@ "binaryDir": "${sourceDir}/build/init", "generator": "Ninja", "cacheVariables": { + "CEL_INSTALL": "OFF", "CMAKE_BUILD_TYPE": "Release", "BUILD_TESTING": "OFF", "CMAKE_EXPORT_COMPILE_COMMANDS": "ON", @@ -81,6 +86,7 @@ "binaryDir": "${sourceDir}/build/install", "generator": "Ninja", "cacheVariables": { + "CEL_INSTALL": "ON", "CMAKE_BUILD_TYPE": "Release", "BUILD_TESTING": "OFF", "CMAKE_EXPORT_COMPILE_COMMANDS": "ON", diff --git a/docs/parity.md b/docs/parity.md index 7cbd4a5..5ba6f8c 100644 --- a/docs/parity.md +++ b/docs/parity.md @@ -7,6 +7,19 @@ The Rust baseline is C++ source links identify checkout tests by name or line. Update the links and revision when changing a contract, then run its linked tests. +Private implementation cases live in guarded test blocks in `src/*.cpp` and run +in `runtime_in_source_tests`; public-interface cases remain in `tests/*.cpp`. +Configure with `cmake --preset test` first if the build tree does not exist. +To build and run the in-source cases, use: + +```sh +cmake --build --preset test --target runtime_in_source_tests +ctest --preset test -R '^runtime_in_source_tests$' +``` + +The CTest command reports one passing test when all in-source cases pass. +Use `ctest --preset test` to include the standalone suites. + Windows CI uses the `test` preset's Debug configuration, which enables [MSVC iterator debugging](https://learn.microsoft.com/en-us/cpp/standard-library/iterator-debug-level) at its default `_ITERATOR_DEBUG_LEVEL=2`. Tests do not replace global allocation @@ -18,29 +31,29 @@ The following entries cover the retained runtime surfaces: | Contract | C++ contract tests | Rust evidence | Status | | --- | --- | --- | --- | -| Raw aligned stack; reverse owner retirement; byte/depth checkpoints | [storage tests](../tests/storage_test.cpp), [raw execution tests](../tests/raw_execution_test.cpp), including “empty frames and mixed leaves preserve stack order and cursor” | [raw_stack.rs:24–76][rust-stack] | Implemented; C++ canonical-only storage adaptation | -| Raw operation sequence; retained real captures; source-order dispatch; error cleanup | [raw execution tests](../tests/raw_execution_test.cpp), including “canonical instruction captures retain descriptors and clean failed clone suffixes” | [raw_segment.rs:68–90,393–433][rust-raw] | Implemented; C++ exception transport | +| Raw aligned stack; reverse owner retirement; byte/depth checkpoints | [in-source storage tests](../src/storage.cpp#L108), [in-source raw stack tests](../src/raw_stack.cpp#L334), including “empty frames and mixed leaves preserve stack order and cursor”; [public layout test](../tests/storage_test.cpp) | [raw_stack.rs:24–76][rust-stack] | Implemented; C++ canonical-only storage adaptation | +| Raw operation sequence; retained real captures; source-order dispatch; error cleanup | [in-source raw execution tests](../src/raw_stack.cpp#L607), including “canonical instruction captures retain descriptors and clean failed clone suffixes” | [raw_segment.rs:68–90,393–433][rust-raw] | Implemented; C++ exception transport | | Dynamic checked construction; preflight before effects; single-result freeze | [segment tests](../tests/segment_test.cpp), “checked signatures reject errors before callback effects” and “dynamic ordered mixed operations freeze reads and literals” | [dyn_segment.rs:757–789][rust-dyn], [prepared_segment.rs:16–75][rust-prepared] | Implemented | | Static stack effects and declared initial operands | Not part of the client interface | [segment.rs:57–73,90–122,188–239,350–415][rust-typed] | Not retained; clients compile source or use checked dynamic builders | -| Complete identity, layout, and separately checked ownership capabilities | [value tests](../tests/value_test.cpp), including “private callable ownership installation preserves shape and validates operation pairs”; [resource tests](../tests/resource_test.cpp) for shared descriptor DAGs | [value_type.rs:1–9,47–74][rust-types], [prepared_segment.rs:16–75][rust-prepared] | Implemented | -| Code-independent canonical ownership binding for complete immutable type DAGs, including empty callable composites and higher-order result witnesses | [callable tests](../tests/callable_test.cpp): ownership binding, deep/shared DAGs, foreign-operation rejection | C++ semantic-descriptor/canonical-carrier adaptation; no same-named Rust API claim | Implemented; semantic Fn declarations remain unbound | -| Recursive independent aggregate copies, native boundary adapters, over-aligned client roots | [segment tests](../tests/segment_test.cpp): “typed composite calls borrow inputs and return disjoint nested results”, “valid over-aligned client root arguments and results are admitted”; [value tests](../tests/value_test.cpp) | [prepared_segment.rs:96–225][rust-prepared] | Implemented; native C++ facades differ | +| Complete identity, layout, and separately checked ownership capabilities | [public value tests](../tests/value_test.cpp); [in-source ownership tests](../src/value.cpp#L817), including “private callable ownership installation preserves shape and validates operation pairs”; [resource tests](../tests/resource_test.cpp) for shared descriptor DAGs | [value_type.rs:1–9,47–74][rust-types], [prepared_segment.rs:16–75][rust-prepared] | Implemented | +| Code-independent canonical ownership binding for complete immutable type DAGs, including empty callable composites and higher-order result witnesses | [public callable tests](../tests/callable_test.cpp) and [in-source callable tests](../src/callable.cpp#L176): ownership binding, deep/shared DAGs, foreign-operation rejection | C++ semantic-descriptor/canonical-carrier adaptation; no same-named Rust API claim | Implemented; semantic Fn declarations remain unbound | +| Recursive independent aggregate copies, native boundary adapters, over-aligned client roots | [in-source composite call test](../src/dyn_segment.cpp#L795): “typed composite calls borrow inputs and return disjoint nested results”; [public segment tests](../tests/segment_test.cpp): “valid over-aligned client root arguments and results are admitted”; [value tests](../tests/value_test.cpp) | [prepared_segment.rs:96–225][rust-prepared] | Implemented; native C++ facades differ | | Tuple packing at exact origin; source-order ownership transfer | [structural tests](../tests/composite_execution_test.cpp): “nested packing consumes source order and preserves exact owners” | [dyn_segment.rs:792–825][rust-dyn] | Implemented; origin includes logical depth | | Typed arrays, empty arrays, zero-byte elements, nested owning payloads | [structural tests](../tests/composite_execution_test.cpp) packing and invalid-shape cases; [value tests](../tests/value_test.cpp) | [dyn_segment.rs:852–916][rust-dyn] | Implemented | | Record packing and source-to-schema permutation validation | [structural tests](../tests/composite_execution_test.cpp): “record schema permutation leaves expression effects source ordered”, invalid shapes/permutations, duplicate/wrong-length rejection | [registered_ops.rs:41–90,176–255][rust-record] | Implemented runtime emitter; Rust emitter is parser-side | -| Consuming tuple projection; sibling retirement without selected-child cloning | [structural tests](../tests/composite_execution_test.cpp): “consuming projection transfers selected owners and retires siblings without cloning” | [dyn_segment.rs:931–955][rust-dyn] | Implemented/tested | -| Consuming canonical record projection; sibling retirement without selected-child cloning | [structural tests](../tests/composite_execution_test.cpp): “consuming projection transfers selected owners and retires siblings without cloning” | [lib.rs:1809–1826][rust-member-parser], [registered_ops.rs:414–435][rust-member-emitter], [geometry.rs:48–58,160–178][rust-native-fields] | Implemented/tested; canonical carrier/interface adaptation of registered field selection | +| Consuming tuple projection; sibling retirement without selected-child cloning | [in-source projection test](../src/dyn_segment.cpp#L581): “consuming projection transfers selected owners and retires siblings without cloning” | [dyn_segment.rs:931–955][rust-dyn] | Implemented/tested | +| Consuming canonical record projection; sibling retirement without selected-child cloning | [in-source projection test](../src/dyn_segment.cpp#L581): “consuming projection transfers selected owners and retires siblings without cloning”; [public structural tests](../tests/composite_execution_test.cpp) | [lib.rs:1809–1826][rust-member-parser], [registered_ops.rs:414–435][rust-member-emitter], [geometry.rs:48–58,160–178][rust-native-fields] | Implemented/tested; canonical carrier/interface adaptation of registered field selection | | Consuming array indexing; safe f64 rejection and prefix restoration | [structural tests](../tests/composite_execution_test.cpp): “invalid floating indices reject safely and restore prefixes” | [dyn_segment.rs:958–985][rust-dyn] | Implemented; deliberate f64 index adaptation | | Bounded, inclusive, from, to, to-inclusive, full ranges; endpoint order and complete form identity | [structural tests](../tests/composite_execution_test.cpp): “every range kind retains endpoint metadata and source order”; [value tests](../tests/value_test.cpp) | [op_table.rs:929–1018,1525–1583,1623–1643][rust-ranges] | All six implemented; no floating iteration law | | Dependent origins; lazy conditional/and/or; exact result join; merged reads and selected effects | [structural tests](../tests/composite_execution_test.cpp), including lazy read/preflight and logical-or cases | [dyn_segment.rs:189–229,1149–1162,1460–1509][rust-dyn] | Implemented; byte/depth origin adaptation | | Independent closure bodies; explicit unused parameters; full preflight; unrestricted complete results | [callable tests](../tests/callable_test.cpp): “callable full declarations include unused composite parameters”, client-leaf/nested/callable result cases | [dyn_closure.rs:1–4,438–486,526–547][rust-closure] | Implemented | | Reference-semantic carriers; same-carrier exclusion through acquisition/cleanup; distinct nesting | [callable tests](../tests/callable_test.cpp), callback reentry rejection and distinct-carrier nesting | [callable.rs:14–18][rust-callable] | Implemented; allocation-hook acquisition probes are not tested | | Stable source-ordered guarded dynamic invocation across nested stack growth | [callable tests](../tests/callable_test.cpp), nested-growth reread and throwing dynamic-body tests | [dyn_segment.rs:1367–1457][rust-dyn] | Implemented; stable C++ canonical staging | -| Nonallocating stack-independent callable/program retirement; deep literals, lazy bodies, and shared children | [executable retirement tests](../tests/executable_retirement_test.cpp), depth-12000 normal/unwinding and last-owner retirement | C++ ownership contract; no speculative Rust destruction claim | Deep retirement tested; allocation counts are not measured | -| Complete higher-order result ownership before effects or raw binding | [callable tests](../tests/callable_test.cpp): “higher order results reject foreign ownership before checked execution and binding”, independently bound canonical higher-order witnesses | Complete checked ownership contract; foreign C++ ABI fixture has no Rust equivalent | Corrected; prepared execution remains comparison-free | -| Typed/raw preparation; no repeated descriptor comparison; caller-owned raw result retirement | [segment tests](../tests/segment_test.cpp) | [prepared_segment.rs:16–168,228–255][rust-prepared] | Implemented; raw result retirement tested in segment suite | -| Intermediate alignment, prefix totals, zero-byte depth, selected/known-callee peaks | [segment tests](../tests/segment_test.cpp), [structural tests](../tests/composite_execution_test.cpp), [callable tests](../tests/callable_test.cpp) | [raw_segment.rs:117–130][rust-raw] gives alignment/frame metadata | Implemented/tested; published C++ reservation helper is an adaptation, not claimed Rust API parity | -| Exception suffix cleanup, preserved prefixes, construction rollback, partial-owner retirement, reusable stack | [raw execution tests](../tests/raw_execution_test.cpp), [segment tests](../tests/segment_test.cpp), structural/callable callback exceptions and invalid-construction rollback cases | [raw_stack.rs:67–76][rust-stack], [raw_segment.rs:411–433][rust-raw], [dyn_segment.rs:1367–1457][rust-dyn] | Implemented; allocation-failure injection is not tested | +| Nonallocating stack-independent callable/program retirement; deep literals, lazy bodies, and shared children | [public executable retirement tests](../tests/executable_retirement_test.cpp), depth-12000 normal/unwinding; [in-source last-owner retirement test](../src/raw_segment.cpp#L106) | C++ ownership contract; no speculative Rust destruction claim | Deep retirement tested; allocation counts are not measured | +| Complete higher-order result ownership before effects or raw binding | [in-source higher-order ownership test](../src/callable.cpp#L302): “higher order results reject foreign ownership before checked execution and binding”; [public callable tests](../tests/callable_test.cpp) for independently bound canonical higher-order witnesses | Complete checked ownership contract; foreign C++ ABI fixture has no Rust equivalent | Corrected; prepared execution remains comparison-free | +| Typed/raw preparation; no repeated descriptor comparison; caller-owned raw result retirement | [public segment tests](../tests/segment_test.cpp), [in-source raw result retirement test](../src/dyn_segment.cpp#L1025) | [prepared_segment.rs:16–168,228–255][rust-prepared] | Implemented; raw result retirement tested in in-source runner | +| Intermediate alignment, prefix totals, zero-byte depth, selected/known-callee peaks | [in-source reservation tests](../src/dyn_segment.cpp#L1151), [public segment tests](../tests/segment_test.cpp), [structural tests](../tests/composite_execution_test.cpp), [callable tests](../tests/callable_test.cpp) | [raw_segment.rs:117–130][rust-raw] gives alignment/frame metadata | Implemented/tested; published C++ reservation helper is an adaptation, not claimed Rust API parity | +| Exception suffix cleanup, preserved prefixes, construction rollback, partial-owner retirement, reusable stack | [in-source raw execution tests](../src/raw_stack.cpp#L607), [in-source raw destination rollback test](../src/dyn_segment.cpp#L884), [public segment tests](../tests/segment_test.cpp), structural/callable callback exceptions and invalid-construction rollback cases | [raw_stack.rs:67–76][rust-stack], [raw_segment.rs:411–433][rust-raw], [dyn_segment.rs:1367–1457][rust-dyn] | Implemented; allocation-failure injection is not tested | | Runnable cached example | [example](../examples/getting_started.cpp) | C++ packaging adaptation; no Rust package-equivalence claim | Implemented | ## Deliberate scope and mechanism adaptations diff --git a/docs/runtime-milestone.md b/docs/runtime-milestone.md index 4deac0e..87f59f1 100644 --- a/docs/runtime-milestone.md +++ b/docs/runtime-milestone.md @@ -75,10 +75,17 @@ Independent final port review and remote/platform validation remain pending. ## Reproduce local validation -The pinned cpp-library release is `v6.1.0` at revision -`13ff79ac9fbbf575bbab0ab3dee0c752b4501fcc`. Its presets, doctest/CTest, -compile-fail gates, Doxygen, exports, installation, and generated CI remain in -use. +The pinned cpp-library release is `v6.2.0` at revision +`4f60491f7550cb058af855346decc71ce0d5365e`. Its presets, doctest/CTest, +compile-fail gates, Doxygen, and generated source-build CI remain in use. +Thread support comes from cpp-library's default library linkage. + +Private tests live beside their implementations in `src/*.cpp`, guarded by +`#if CPP_LIBRARY_TESTING()` after including ``. +CTest runs them through the generated `runtime_in_source_tests` executable. +Standalone `tests/*_test.cpp` files retain public API coverage without the +private source include directory. Production builds disable the guarded tests +and do not require doctest. Run Debug and lint checks from the checkout: @@ -127,10 +134,10 @@ regressions and rejects higher-order foreign result ownership before effects or raw preparation. Runtime-managed literals, array/tuple children, and lazy bodies retire through one nonallocating last-owner worklist; shared code and invocation guards retain their original semantics. -The shipped `tests/executable_retirement_test.cpp` and `tests/callable_test.cpp` -retain the corresponding regressions. Use the Debug, Release, and sanitizer -commands on this page to reproduce them against this checkout, then install -normal and instrumented packages separately for parser validation. +The shipped `tests/executable_retirement_test.cpp`, `tests/callable_test.cpp`, +and guarded cases in `src/raw_segment.cpp` and `src/callable.cpp` retain the +corresponding regressions. Use the Debug, Release, and sanitizer commands on +this page to reproduce them against this checkout. The API correction adds `native_contract_test`, bringing the suite to 17 CTests. It covers `native_type()`, cached `origin_below(count)` boundaries, and diff --git a/src/callable.cpp b/src/callable.cpp index 6475444..5b2c6fa 100644 --- a/src/callable.cpp +++ b/src/callable.cpp @@ -28,6 +28,7 @@ struct callable_state : retirement_node { delete &state; } }; +namespace { /// A canonical owner of a reference-semantic callable handle. struct callable_carrier { callable* owner; ///< Owns the reference-semantic facade. @@ -35,11 +36,13 @@ struct callable_carrier { static_assert(std::is_trivially_copyable_v); static_assert(sizeof(callable_carrier) == sizeof(void*)); static_assert(alignof(callable_carrier) == alignof(void*)); +} // namespace const callable& callable_access::read(const std::byte* bytes) noexcept { callable_carrier carrier{}; std::memcpy(&carrier, bytes, sizeof(carrier)); return *carrier.owner; } +namespace { /// Initializes a canonical carrier with the supplied owned callable handle. /// /// \pre destination has uninitialized carrier storage and pointer is a live uniquely owned @@ -65,6 +68,7 @@ void clone_callable(const std::byte* source, std::byte* destination) { /// /// Complexity: last-owned code, capture, and binding metadata retirement. void destroy_callable(std::byte* source) noexcept { delete &callable_access::read(source); } +} // namespace bool callable_access::installed(const value_type& type) noexcept { if (type.kind() != type_kind::callable) return false; const auto ops = type_access::operations(type); @@ -145,3 +149,199 @@ callable callable::from_value(const value& source) { return detail::callable_access::read(detail::value_access::data(source)); } } // namespace cel + +#include +#if CPP_LIBRARY_TESTING() +#include +#include +#include +#include + +namespace { +/// Supplies a hidden over-aligned intermediate whose final callable result is scalar. +struct alignas(256) wide_result { + bool flag; ///< Retains the intermediate result. +}; +/// Counts foreign ownership operations to detect access before ABI rejection. +int foreign_clones = 0; +/// Counts foreign canonical retirement. +int foreign_destroys = 0; +/// Copies a foreign opaque carrier without treating its bytes as installed callable code. +void clone_foreign(const std::byte* source, std::byte* destination) { + std::memcpy(destination, source, sizeof(void*)); + ++foreign_clones; +} +/// Retires the resource-free foreign representation without dereferencing it. +void destroy_foreign(std::byte*) noexcept { ++foreign_destroys; } +TEST_CASE("runtime ownership binding preserves deferred signatures and canonical witnesses") { + const auto number = cel::value_type::leaf(); + const auto declared = cel::value_type::callable(std::array{number}, number); + const auto bound = cel::bind_runtime_ownership(declared); + cel::dyn_segment body; + body.push_argument(0, number); + cel::callable actual(std::move(body).finish(), std::array{number}); + CHECK_FALSE(declared.owns_values()); + CHECK(bound.owns_values()); + CHECK(bound.same_shape(declared)); + CHECK(bound.compatible_with(actual.type())); + CHECK_FALSE(declared.compatible_with(actual.type())); + CHECK(cel::bind_runtime_ownership(bound).compatible_with(bound)); + CHECK(cel::detail::type_access::same_plan(cel::bind_runtime_ownership(bound), bound)); + CHECK(cel::detail::type_access::same_plan(cel::bind_runtime_ownership(actual.type()), + actual.type())); + CHECK_THROWS_AS(cel::value_type::callable(std::array{bound}, number), std::invalid_argument); +} +TEST_CASE("binding preserves nested nominal layout client identities and range forms") { + const auto declared = cel::value_type::callable({}, cel::value_type::leaf()); + const auto client = cel::value_type::leaf(); + const auto range = + cel::value_type::range(cel::range_kind::range_inclusive, cel::value_type::leaf()); + const auto tuple = cel::value_type::tuple(std::array{client, declared, range}); + const auto record = cel::value_type::record( + "named", std::array{cel::record_field{"nested", cel::value_type::array(tuple)}, + cel::record_field{"wide", client}}); + const auto bound = cel::bind_runtime_ownership(record); + CHECK_FALSE(record.owns_values()); + CHECK(bound.owns_values()); + CHECK(bound.same_shape(record)); + CHECK(bound.record_identity() == "named"); + CHECK(bound.field_names()[0] == "nested"); + CHECK(bound.field_names()[1] == "wide"); + CHECK(bound.offsets()[0] == record.offsets()[0]); + CHECK(bound.offsets()[1] == record.offsets()[1]); + CHECK(bound.byte_layout().alignment == 256); + CHECK(bound.fields()[1].leaf_identity() == typeid(wide_result)); + CHECK(cel::detail::type_access::same_plan(bound.fields()[1], client)); + CHECK(bound.fields()[0].element().fields()[2].form() == cel::range_kind::range_inclusive); + CHECK_THROWS_AS(cel::value_type::callable(std::array{bound}, client), std::invalid_argument); + cel::dyn_segment builder; + builder.make_array(0, bound, {}); + cel::raw_stack stack; + CHECK(std::move(builder).finish().execute(stack, {}).size() == 0); +} +TEST_CASE("binding rejects foreign operations throughout metadata without invoking owners") { + const auto declared = cel::value_type::callable({}, cel::value_type::leaf()); + const auto foreign = cel::detail::type_access::install_callable_ownership( + declared, {clone_foreign, destroy_foreign}); + cel::dyn_segment body; + body.just(cel::value::from(7.0)); + cel::callable actual(std::move(body).finish(), {}); + const auto aggregate = cel::value_type::tuple(std::array{cel::value_type::array(foreign)}); + const auto nested = cel::value_type::callable({}, aggregate); + const auto installed_nested = cel::detail::type_access::install_callable_ownership( + nested, cel::detail::type_access::operations(actual.type())); + const auto mixed = cel::detail::type_access::install_callable_ownership( + declared, {cel::detail::type_access::operations(actual.type()).clone, destroy_foreign}); + foreign_clones = 0; + foreign_destroys = 0; + for (const auto& input : std::array{foreign, aggregate, nested, installed_nested, mixed}) { + CHECK_THROWS_AS(cel::bind_runtime_ownership(input), std::invalid_argument); + } + CHECK(cel::detail::type_access::operations(foreign).clone == clone_foreign); + CHECK(cel::detail::type_access::operations(foreign).destroy == destroy_foreign); + CHECK(foreign_clones == 0); + CHECK(foreign_destroys == 0); +} +TEST_CASE("binding traverses deep metadata and preserves shared DAGs") { + auto deep = cel::value_type::callable({}, cel::value_type::leaf()); + for (int i = 0; i != 12000; ++i) + deep = cel::value_type::callable({}, cel::value_type::array(deep)); + auto bound = cel::bind_runtime_ownership(deep); + CHECK(bound.same_shape(deep)); + for (int i = 0; i != 12000; ++i) { + REQUIRE(bound.owns_values()); + REQUIRE(bound.result().owns_values()); + bound = bound.result().element(); + } + CHECK(bound.owns_values()); + auto shared = cel::value_type::callable({}, cel::value_type::leaf()); + constexpr int depth = 96; + for (int i = 0; i != depth; ++i) { + const auto edge = cel::value_type::array(shared); + shared = cel::value_type::tuple(std::array{edge, edge}); + } + auto result = cel::bind_runtime_ownership(shared); + CHECK(result.same_shape(shared)); + for (int i = 0; i != depth; ++i) { + REQUIRE(result.owns_values()); + CHECK(cel::detail::type_access::same_plan(result.fields()[0], result.fields()[1])); + result = result.fields()[0].element(); + } + CHECK(result.owns_values()); +} +TEST_CASE("conversion and dynamic invocation reject foreign same shape ownership before access") { + foreign_clones = 0; + foreign_destroys = 0; + int effects = 0; + cel::dyn_segment body; + body.just(cel::value::from(true)); + cel::callable fn(std::move(body).finish(), {}); + const auto foreign = cel::detail::type_access::install_callable_ownership( + fn.type(), {clone_foreign, destroy_foreign}); + alignas(void*) const std::array null_carrier{}; + auto impostor = cel::detail::value_access::take(foreign, null_carrier.data()); + CHECK(impostor.type().same_shape(fn.type())); + CHECK_THROWS_AS(cel::callable::from_value(impostor), std::invalid_argument); + CHECK(foreign_clones == 0); + CHECK(foreign_destroys == 0); + cel::dyn_segment b; + b.just(std::move(impostor)); + b.op0([&effects] { ++effects; }); + const auto original = b.snapshot(); + CHECK_THROWS_AS(b.invoke_closure(0), std::invalid_argument); + CHECK(b.snapshot() == original); + CHECK(effects == 0); + CHECK(foreign_clones == 0); + cel::raw_stack stack; + auto result = std::move(b).finish().execute(stack, {}); + CHECK(result.type().same_shape(fn.type())); + CHECK(effects == 1); + CHECK(foreign_clones == 1); + CHECK_THROWS_AS(cel::callable::from_value(result), std::invalid_argument); +} +TEST_CASE("higher order results reject foreign ownership before checked execution and binding") { + for (bool nested : {false, true}) { + int effects = 0; + cel::dyn_segment inner_body; + inner_body.just(cel::value::from(7.0)); + const auto canonical_inner = cel::callable(std::move(inner_body).finish(), {}).to_value(); + const auto foreign_inner = cel::detail::type_access::install_callable_ownership( + canonical_inner.type(), {clone_foreign, destroy_foreign}); + alignas(void*) const std::array carrier{}; + auto result = cel::detail::value_access::take(foreign_inner, carrier.data()); + if (nested) { + std::array children{std::move(result)}; + result = cel::value::tuple(children); + } + cel::dyn_segment foreign_body; + foreign_body.just(std::move(result)); + const auto foreign_outer = cel::callable(std::move(foreign_body).finish(), {}).to_value(); + const auto expected_result = + nested ? cel::value_type::tuple(std::array{canonical_inner.type()}) : + canonical_inner.type(); + const auto expected = + cel::bind_runtime_ownership(cel::value_type::callable({}, expected_result)); + CHECK(foreign_outer.type().same_shape(expected)); + CHECK_FALSE(foreign_outer.type().compatible_with(expected)); + cel::dyn_segment reader; + reader.push_argument(0, expected); + reader.op0([&effects] { ++effects; }); + const auto program = std::move(reader).finish(); + cel::raw_stack stack; + stack.push(true); + CHECK_THROWS_AS(program.execute(stack, std::array{foreign_outer}), std::invalid_argument); + CHECK(effects == 0); + CHECK(stack.depth() == 1); + CHECK(stack.pop()); + CHECK_THROWS_AS(cel::detail::segment_access::prepare_raw( + program, std::array{foreign_outer.type()}, expected), + std::invalid_argument); + CHECK_THROWS_AS(cel::detail::segment_access::prepare_raw(program, std::array{expected}, + foreign_outer.type()), + std::invalid_argument); + CHECK(effects == 0); + } +} +} // namespace + +#endif diff --git a/src/dyn_segment.cpp b/src/dyn_segment.cpp index 38253fe..6950406 100644 --- a/src/dyn_segment.cpp +++ b/src/dyn_segment.cpp @@ -42,6 +42,7 @@ struct frozen_program : retirement_node { delete &program; } }; +namespace { /// An owned literal that supplies independent results under value's copy semantics. struct literal_instruction { value literal; ///< Owns one complete literal, independent of execution results. @@ -71,6 +72,7 @@ struct branch_instruction { no.retire(queue); } }; +} // namespace void segment_access::retire(cel::compiled_segment& segment, retirement_queue& queue) noexcept { segment._program.retire(queue); } @@ -536,3 +538,674 @@ void prepared_raw_segment::destroy_result(std::byte* result) const noexcept { detail::destroy_payload(_result, result); } } // namespace cel + +#include +#if CPP_LIBRARY_TESTING() +#include + +namespace { +/// Tracks opaque result owners to detect sibling cleanup and accidental projection cloning. +int opaque_owners = 0; +/// Counts canonical opaque clones, independently of outer-storage allocation. +int opaque_clones = 0; +/// Identifies one live opaque owner in canonical bytes. +struct opaque_carrier { + int* owner; ///< Owns one test resource. +}; +/// Clones a test resource into an independent canonical carrier. +void clone_opaque(const std::byte* source, std::byte* destination) { + opaque_carrier input{}; + std::memcpy(&input, source, sizeof(input)); + auto owner = std::make_unique(*input.owner); + const opaque_carrier output{owner.release()}; + std::memcpy(destination, &output, sizeof(output)); + ++opaque_owners; + ++opaque_clones; +} +/// Destroys one live canonical resource. +void destroy_opaque(std::byte* source) noexcept { + opaque_carrier input{}; + std::memcpy(&input, source, sizeof(input)); + delete input.owner; + --opaque_owners; +} +/// Builds a trusted opaque owner with the specified installed complete witness. +cel::value make_opaque(const cel::value_type& type) { + auto owner = std::make_unique(4); + const opaque_carrier input{owner.get()}; + auto result = cel::detail::value_access::take(type, reinterpret_cast(&input)); + [[maybe_unused]] auto* retired_source = owner.release(); + ++opaque_owners; + return result; +} +TEST_CASE("consuming projection transfers selected owners and retires siblings without cloning") { + const auto signature = cel::detail::type_access::install_callable_ownership( + cel::value_type::callable({}, cel::value_type::leaf()), + {clone_opaque, destroy_opaque}); + { + cel::dyn_segment b; + b.just(make_opaque(signature)); + b.just(make_opaque(signature)); + b.make_array(2, signature, {}); + b.make_tuple(1, {}); + b.project_tuple(0); + b.just(cel::value::from(1.0)); + b.index_array(); + auto program = std::move(b).finish(); + cel::raw_stack stack; + const auto clones = opaque_clones; + { + auto result = program.execute(stack, {}); + CHECK(result.type().same_shape(signature)); + CHECK(opaque_clones - clones == 2); + CHECK(opaque_owners == 3); + } + CHECK(opaque_owners == 2); + CHECK(stack.depth() == 0); + } + CHECK(opaque_owners == 0); +} +} // namespace + +#endif + +#include +#if CPP_LIBRARY_TESTING() +#include +#include +#include +#include +#include +#include + +namespace { +/// Counts live synthetic callable-carrier owners without implementing callable bodies. +int live_carriers = 0; +/// Clones an independently owned integer through the foundation's opaque ownership contract. +void clone_carrier(const std::byte* source, std::byte* destination) { + int* pointer = nullptr; + std::memcpy(static_cast(&pointer), source, sizeof(pointer)); + auto owner = std::make_unique(*pointer); + pointer = owner.release(); + std::memcpy(destination, static_cast(&pointer), sizeof(pointer)); + ++live_carriers; +} +/// Retires one initialized synthetic carrier. +void destroy_carrier(std::byte* bytes) noexcept { + int* pointer = nullptr; + std::memcpy(static_cast(&pointer), bytes, sizeof(pointer)); + delete pointer; + --live_carriers; +} +/// Supplies an incompatible ownership pair with the same semantic signature. +void destroy_other_carrier(std::byte* bytes) noexcept { destroy_carrier(bytes); } + +/// Exercises root admission independently of callable-parameter restrictions. +struct alignas(256) client_leaf { + int number; ///< Retains a client-defined scalar. +}; +/// Holds an owned callable field for typed-result lifetime tests. +struct segment_callable_record { + /// Owns one callable value. + cel::value code; +}; + +/// Holds test input for ownership-mismatch adapter regression checks. +struct ownership_gap_payload { + /// Seeds the synthetic callable carrier. + int seed; +}; + +/// Returns the callable descriptor with the primary ownership pair. +const cel::value_type& primary_callable_type() { + static const auto descriptor = cel::detail::type_access::install_callable_ownership( + cel::value_type::callable({}, cel::value_type::leaf()), + {clone_carrier, destroy_carrier}); + return descriptor; +} + +/// Returns the callable descriptor with an incompatible ownership pair. +const cel::value_type& foreign_callable_type() { + static const auto descriptor = cel::detail::type_access::install_callable_ownership( + cel::value_type::callable({}, cel::value_type::leaf()), + {clone_carrier, destroy_other_carrier}); + return descriptor; +} + +/// Returns the declared nominal record descriptor with the primary callable ownership pair. +const cel::value_type& declared_ownership_gap_type() { + static const auto descriptor = cel::value_type::record( + "tests.ownership_gap", std::array{cel::record_field{"code", primary_callable_type()}}); + return descriptor; +} + +/// Returns a same-shape nominal record descriptor with incompatible callable ownership. +const cel::value_type& foreign_ownership_gap_type() { + static const auto descriptor = cel::value_type::record( + "tests.ownership_gap", std::array{cel::record_field{"code", foreign_callable_type()}}); + return descriptor; +} + +/// Returns one callable value with synthetic owned carrier storage. +cel::value make_foreign_callable_value(int seed) { + int payload = seed; + int* pointer = &payload; + std::array carrier{}; + std::memcpy(carrier.data(), static_cast(&pointer), sizeof(pointer)); + return cel::detail::value_access::copy(foreign_callable_type(), carrier.data()); +} + +/// Returns one callable value with the primary ownership pair. +cel::value make_primary_callable_value(int seed) { + int payload = seed; + int* pointer = &payload; + std::array carrier{}; + std::memcpy(carrier.data(), static_cast(&pointer), sizeof(pointer)); + return cel::detail::value_access::copy(primary_callable_type(), carrier.data()); +} +/// Supplies named overloads that require an exact explicit signature selection. +struct overloaded_callback { + /// Doubles one exact operand. + double operator()(double number) const { return number * 2.0; } + /// Adds two exact operands. + double operator()(double a, double b) const { return a + b; } +}; + +/// Exercises invocation through the required const lvalue callback boundary. +struct lvalue_callback { + /// Increments its exact operand through a const lvalue. + double operator()(double number) const& { return number + 1.0; } +}; + +/// Exercises nonthrowing invocation through the same const lvalue boundary. +struct lvalue_noexcept_callback { + /// Increments its exact operand without throwing. + double operator()(double number) const& noexcept { return number + 2.0; } +}; + +/// Supplies an introspection-ineligible invocation through an exact function-pointer conversion. +struct pointer_callback { + using function = double (*)(double); ///< Describes its explicit concrete invocation. + + /// Doubles one exact operand. + static double twice(double number) { return number * 2.0; } + /// Returns its exact function pointer. + operator function() const noexcept { return twice; } +}; + +/// Detects exact explicit member selection without hard introspection errors. +template +concept signature_selectable = requires(F callback) { + cel::with_signature(std::move(callback)); +}; +} // namespace +namespace cel { +template <> +struct record_adapter<::segment_callable_record> { + /// Returns the callable record schema. + static value_type type() { + static const auto descriptor = + value_type::record("tests.segment_callable_record", + std::array{record_field{"code", primary_callable_type()}}); + return descriptor; + } + /// Encodes the callable field as an owned canonical value. + static value to_value(const ::segment_callable_record& source) { + return value::record(type(), std::array{source.code}); + } + /// Copies the owned callable field from a validated record. + static ::segment_callable_record from_value(const value& source) { + if (!source.type().same_shape(type())) + throw std::invalid_argument("wrong callable record type"); + return {.code = source.field("code")}; + } +}; + +template <> +struct record_adapter { + /// Returns the declared nominal descriptor with the primary ownership pair. + static value_type type() { return declared_ownership_gap_type(); } + /// Encodes the payload as a same-shape record with incompatible callable ownership. + static value to_value(const ownership_gap_payload& source) { + auto code = make_foreign_callable_value(source.seed); + return value::record(foreign_ownership_gap_type(), std::array{code}); + } + /// Decodes this payload from a validated record value. + static ownership_gap_payload from_value(const value& source) { + if (!source.type().same_shape(type())) + throw std::invalid_argument("wrong ownership-gap type"); + return {.seed = 0}; + } +}; +} // namespace cel +namespace { +TEST_CASE("recursive preparation mismatch preserves nominal and leaf identity") { + using input = std::tuple, bool>; + cel::dyn_segment builder; + builder.push_argument(0, cel::detail::concrete_adapter::type()); + auto program = std::move(builder).finish(); + CHECK_THROWS_AS((program.prepare, bool>>()), + std::invalid_argument); + CHECK_THROWS_AS((program.prepare, double>, input>()), + std::invalid_argument); + cel::raw_stack stack; + const std::array wrong{cel::value::from(std::tuple{std::vector{true}, true})}; + CHECK_THROWS_AS(program.execute(stack, wrong), std::invalid_argument); +} +TEST_CASE("typed composite calls borrow inputs and return disjoint nested results") { + using input = std::tuple>, bool>; + cel::dyn_segment builder; + builder.push_argument(0, cel::detail::concrete_adapter::type()); + auto prepared = std::move(builder).finish().prepare(); + cel::raw_stack stack; + input source{{{1.0, 2.0}}, true}; + auto first = prepared.call(stack, source); + auto second = prepared.call(stack, source); + std::get<0>(first)[0][0] = 7.0; + CHECK(std::get<0>(source)[0][0] == 1.0); + CHECK(std::get<0>(second)[0][0] == 1.0); + std::get<0>(source)[0][1] = 9.0; + CHECK(std::get<0>(second)[0][1] == 2.0); +} +TEST_CASE("typed zero-sized unit arrays retain nested logical lengths") { + using units = std::vector>>; + cel::dyn_segment builder; + builder.push_argument(0, cel::detail::concrete_adapter::type()); + auto prepared = std::move(builder).finish().prepare(); + const units input{std::vector>(3), {}, std::vector>(1)}; + cel::raw_stack stack; + auto result = prepared.call(stack, input); + REQUIRE(result.size() == 3); + CHECK(result[0].size() == 3); + CHECK(result[1].empty()); + CHECK(result[2].size() == 1); + result[0].clear(); + CHECK(input[0].size() == 3); + CHECK(prepared.call(stack, input)[0].size() == 3); +} +TEST_CASE("runtime-bound owning output has a public retirement boundary") { + cel::dyn_segment builder; + builder.op0>>( + [] { return std::vector>{{2.0}, {3.0}}; }); + auto program = std::move(builder).finish(); + auto prepared = cel::detail::segment_access::prepare_raw(program, {}, program.result_type()); + const auto layout = prepared.result_type().byte_layout(); + auto* destination = + static_cast(::operator new(layout.size, std::align_val_t(layout.alignment))); + cel::raw_stack stack; + prepared.call_into(stack, {}, destination); + auto first = cel::detail::borrowed_value{prepared.result_type(), destination} + .as>>(); + prepared.destroy_result(destination); + first[0][0] = 8.0; + prepared.call_into(stack, {}, destination); + CHECK(cel::detail::borrowed_value{prepared.result_type(), destination} + .as>>()[0][0] == 2.0); + prepared.destroy_result(destination); + ::operator delete(destination, std::align_val_t(layout.alignment)); + CHECK(stack.depth() == 0); +} + +TEST_CASE("runtime-bound exact record identity and shared deep metadata") { + const std::array fields{cel::record_field{"flag", cel::value_type::leaf()}}; + auto type = cel::value_type::record("named", fields); + cel::dyn_segment builder; + builder.push_argument(0, type); + auto program = std::move(builder).finish(); + const std::array wrong{cel::value_type::record("other", fields)}; + CHECK_THROWS_AS(cel::detail::segment_access::prepare_raw(program, wrong, type), + std::invalid_argument); + const std::array arguments{type}; + auto prepared = cel::detail::segment_access::prepare_raw(program, arguments, type); + const std::array contents{cel::value::from(true)}; + auto source = cel::value::record(type, contents); + const std::array views{ + cel::detail::borrowed_value{type, cel::detail::value_access::data(source)}}; + alignas(bool) std::array result{}; + cel::raw_stack stack; + prepared.call_into(stack, views, result.data()); + CHECK(cel::detail::value_access::copy(type, result.data()).field("flag").as()); + prepared.destroy_result(result.data()); + auto deep = cel::value_type::leaf(); + auto same = cel::value_type::leaf(); + for (int i = 0; i != 32; ++i) { + const std::array left{deep, deep}; + const std::array right{same, same}; + deep = cel::value_type::tuple(left); + same = cel::value_type::tuple(right); + } + cel::dyn_segment shared; + shared.push_argument(0, deep); + auto shared_program = std::move(shared).finish(); + const std::array shared_arguments{same}; + CHECK_NOTHROW(cel::detail::segment_access::prepare_raw(shared_program, shared_arguments, same)); +} + +TEST_CASE("throwing callbacks preserve caller prefix and reusable raw destination") { + bool fail = true; + cel::dyn_segment builder; + builder.push_argument(0, cel::value_type::leaf()); + builder.op1([&fail](double n) { + if (fail) throw std::runtime_error("callback"); + return n + 1.0; + }); + auto program = std::move(builder).finish(); + const std::array types{cel::value_type::leaf()}; + auto prepared = cel::detail::segment_access::prepare_raw(program, types, types[0]); + cel::raw_stack stack; + stack.push(std::vector{7.0}); + const auto cursor = stack.cursor(); + double input = 2.0; + const std::array views{ + cel::detail::borrowed_value{types[0], reinterpret_cast(&input)}}; + alignas(double) std::array result{}; + result.fill(std::byte{0x5a}); + CHECK_THROWS_AS(prepared.call_into(stack, views, result.data()), std::runtime_error); + CHECK(result[0] == std::byte{0x5a}); + CHECK(stack.depth() == 1); + CHECK(stack.cursor() == cursor); + fail = false; + prepared.call_into(stack, views, result.data()); + CHECK(cel::detail::borrowed_value{types[0], result.data()}.as() == 3.0); + prepared.destroy_result(result.data()); + CHECK(stack.pop>() == std::vector{7.0}); +} +TEST_CASE("typed record results retire their canonical owned fields") { + auto code = make_primary_callable_value(17); + cel::dyn_segment builder; + builder.op0( + [code = std::move(code)] { return segment_callable_record{.code = code}; }); + auto prepared = std::move(builder).finish().prepare(); + cel::raw_stack stack; + const auto live = live_carriers; + { + const auto result = prepared.call(stack); + CHECK(result.code.type().same_shape(primary_callable_type())); + CHECK(live_carriers == live + 1); + } + CHECK(live_carriers == live); +} + +TEST_CASE("typed record adapter rejects same-shape incompatible ownership before transfer") { + cel::dyn_segment builder; + builder.op0([] { return ownership_gap_payload{.seed = 7}; }); + auto program = std::move(builder).finish(); + const auto result_type = cel::native_type(); + auto prepared = cel::detail::segment_access::prepare_raw(program, {}, result_type); + const auto layout = result_type.byte_layout(); + auto* destination = + static_cast(::operator new(layout.size, std::align_val_t(layout.alignment))); + std::fill(destination, destination + layout.size, std::byte{0x5a}); + cel::raw_stack stack; + stack.push(std::vector{9.0}); + const auto cursor = stack.cursor(); + const auto depth = stack.depth(); + const auto live = live_carriers; + bool threw = false; + try { + prepared.call_into(stack, {}, destination); + } catch (const std::invalid_argument&) { + threw = true; + } + if (!threw) prepared.destroy_result(destination); + CHECK(threw); + if (threw) CHECK(destination[0] == std::byte{0x5a}); + CHECK(live_carriers == live); + CHECK(stack.depth() == depth); + CHECK(stack.cursor() == cursor); + CHECK(stack.pop>() == std::vector{9.0}); + ::operator delete(destination, std::align_val_t(layout.alignment)); +} +TEST_CASE("reserved typed and runtime-bound scalar calls reuse the stack") { + cel::dyn_segment builder; + builder.push_argument(0, cel::value_type::leaf()); + builder.just(cel::value::from(3.0)); + builder.op2([](double a, double b) { return a - b; }); + auto program = std::move(builder).finish(); + auto typed = program.prepare(); + const std::array types{cel::value_type::leaf()}; + auto raw = cel::detail::segment_access::prepare_raw(program, types, types[0]); + cel::raw_stack stack; + const auto reservation = typed.requirements().for_prefix(stack.cursor(), stack.depth()); + stack.reserve(reservation.bytes.size, reservation.bytes.alignment); + stack.reserve_depth(reservation.slots); + CHECK(typed.call(stack, 5.0) == 2.0); + double input = 8.0; + const std::array views{ + cel::detail::borrowed_value{types[0], reinterpret_cast(&input)}}; + alignas(double) std::array bytes{}; + raw.call_into(stack, views, bytes.data()); + raw.destroy_result(bytes.data()); + double typed_total = 0.0; + double raw_total = 0.0; + for (int i = 0; i != 1000; ++i) { + typed_total += typed.call(stack, input); + raw.call_into(stack, views, bytes.data()); + raw_total += cel::detail::concrete_adapter::read(types[0], bytes.data()); + raw.destroy_result(bytes.data()); + } + CHECK(typed_total == 5000.0); + CHECK(raw_total == 5000.0); + CHECK(stack.depth() == 0); +} +TEST_CASE("raw calls preserve composite arguments and caller prefix") { + int effects = 0; + cel::dyn_segment builder; + const auto type = cel::detail::concrete_adapter>::type(); + builder.push_argument(0, type); + builder.push_argument(0, type); + builder.op2, std::vector>( + [&effects](std::vector a, std::vector b) { + ++effects; + return a[0] + b[0]; + }); + auto program = std::move(builder).finish(); + const std::array types{type}; + auto bound = + cel::detail::segment_access::prepare_raw(program, types, cel::value_type::leaf()); + const auto owner = cel::value::from(std::vector{2.0}); + const std::array views{ + cel::detail::borrowed_value{type, cel::detail::value_access::data(owner)}}; + cel::raw_stack stack; + stack.reserve(4096, 256); + stack.push(std::vector{9.0}); + const auto prefix = stack.cursor(); + alignas(double) std::array bytes{}; + CHECK(effects == 0); + bound.call_into(stack, views, bytes.data()); + CHECK(cel::detail::borrowed_value{bound.result_type(), bytes.data()}.as() == 4.0); + bound.destroy_result(bytes.data()); + CHECK(effects == 1); + CHECK(owner.as>() == std::vector{2.0}); + CHECK(stack.cursor() == prefix); + CHECK(stack.depth() == 1); + CHECK(stack.pop>() == std::vector{9.0}); +} + +TEST_CASE("frozen raw callable results bind complete ownership and retire independently") { + const auto signature = cel::value_type::callable({}, cel::value_type::leaf()); + const auto type = cel::detail::type_access::install_callable_ownership( + signature, {clone_carrier, destroy_carrier}); + const auto other = cel::detail::type_access::install_callable_ownership( + signature, {clone_carrier, destroy_other_carrier}); + const auto composite = cel::value_type::array(type); + const auto incompatible = cel::value_type::array(other); + int number = 42; + int* pointer = &number; + alignas(void*) std::array bytes{}; + std::memcpy(bytes.data(), static_cast(&pointer), sizeof(pointer)); + CHECK(live_carriers == 0); + { + const auto owner = cel::detail::value_access::copy(type, bytes.data()); + const std::array elements{owner}; + auto literal = cel::value::array(type, elements); + cel::dyn_segment builder; + builder.just(std::move(literal)); + auto program = std::move(builder).finish(); + CHECK_THROWS_AS(cel::detail::segment_access::prepare_raw(program, {}, incompatible), + std::invalid_argument); + CHECK_THROWS_AS(cel::detail::segment_access::prepare_raw(program, {}, + cel::value_type::array(signature)), + std::invalid_argument); + auto bound = cel::detail::segment_access::prepare_raw(program, {}, composite); + const auto layout = composite.byte_layout(); + auto* result = static_cast( + ::operator new(layout.size, std::align_val_t(layout.alignment))); + cel::raw_stack stack; + const auto baseline = live_carriers; + bound.call_into(stack, {}, result); + CHECK(live_carriers == baseline + 1); + bound.destroy_result(result); + CHECK(live_carriers == baseline); + bound.call_into(stack, {}, result); + CHECK(live_carriers == baseline + 1); + bound.destroy_result(result); + CHECK(live_carriers == baseline); + ::operator delete(result, std::align_val_t(layout.alignment)); + } + CHECK(live_carriers == 0); +} + +TEST_CASE("checked callable read pairs and range identities reject before effects") { + const auto signature = cel::value_type::callable({}, cel::value_type::leaf()); + const auto type = cel::detail::type_access::install_callable_ownership( + signature, {clone_carrier, destroy_carrier}); + const auto other = cel::detail::type_access::install_callable_ownership( + signature, {clone_carrier, destroy_other_carrier}); + int effects = 0; + cel::dyn_segment builder; + builder.op0([&effects] { ++effects; }); + builder.push_argument(0, type); + CHECK_THROWS_AS(builder.push_argument(0, other), std::invalid_argument); + auto program = std::move(builder).finish(); + const std::array wrong_types{other}; + CHECK_THROWS_AS(cel::detail::segment_access::prepare_raw(program, wrong_types, type), + std::invalid_argument); + int number = 3; + int* pointer = &number; + alignas(void*) std::array bytes{}; + std::memcpy(bytes.data(), static_cast(&pointer), sizeof(pointer)); + const std::array wrong_values{cel::detail::value_access::copy(other, bytes.data())}; + cel::raw_stack stack; + CHECK_THROWS_AS(program.execute(stack, wrong_values), std::invalid_argument); + CHECK(effects == 0); + const auto range = + cel::value_type::range(cel::range_kind::range_full, cel::value_type::leaf()); + cel::dyn_segment ranges; + ranges.push_argument(0, range); + auto range_program = std::move(ranges).finish(); + const std::array wrong_range{ + cel::value_type::range(cel::range_kind::range_full, cel::value_type::leaf())}; + CHECK_THROWS_AS(cel::detail::segment_access::prepare_raw(range_program, wrong_range, range), + std::invalid_argument); + const std::array right_range{range}; + auto bound = cel::detail::segment_access::prepare_raw(range_program, right_range, range); + const std::array range_input{cel::detail::borrowed_value{range, nullptr}}; + CHECK_NOTHROW(bound.call_into(stack, range_input, nullptr)); + bound.destroy_result(nullptr); + CHECK(stack.depth() == 0); +} + +TEST_CASE("zero-byte non-unit raw arguments retain complete recursive identity") { + using zero = std::tuple, std::tuple<>>; + const auto type = cel::detail::concrete_adapter::type(); + cel::dyn_segment builder; + builder.push_argument(0, type); + auto program = std::move(builder).finish(); + CHECK_THROWS_AS((program.prepare, zero>()), std::invalid_argument); + const std::array types{type}; + auto bound = cel::detail::segment_access::prepare_raw(program, types, type); + const std::array inputs{cel::detail::borrowed_value{type, nullptr}}; + cel::raw_stack stack; + CHECK_NOTHROW(bound.call_into(stack, inputs, nullptr)); + bound.destroy_result(nullptr); + CHECK(program.prepare().call(stack, zero{}) == zero{}); +} +TEST_CASE("exact callback selection rejects ambiguous conversions and accepts const lvalues") { + static_assert(!signature_selectable); + static_assert(!cel::detail::exact_callback()); + static_assert(!signature_selectable); + cel::dyn_segment builder; + builder.just(cel::value::from(3.0)); + builder.op1(cel::with_signature(overloaded_callback{})); + builder.op1(lvalue_callback{}); + builder.op1(lvalue_noexcept_callback{}); + cel::raw_stack stack; + CHECK(std::move(builder).finish().prepare().call(stack) == 9.0); + cel::dyn_segment binary; + binary.just(cel::value::from(2.0)); + binary.just(cel::value::from(5.0)); + binary.op2( + cel::with_signature(overloaded_callback{})); + CHECK(std::move(binary).finish().prepare().call(stack) == 7.0); + cel::dyn_segment pointer; + pointer.just(cel::value::from(4.0)); + pointer.op1(static_cast(pointer_callback{})); + pointer.op1(pointer_callback::twice); + CHECK(std::move(pointer).finish().prepare().call(stack) == 16.0); + cel::dyn_segment qualified; + qualified.just(cel::value::from(3.0)); + qualified.op1(cel::with_signature(lvalue_noexcept_callback{})); + CHECK(std::move(qualified).finish().prepare().call(stack) == 5.0); +} +TEST_CASE("published reservations cover hidden intermediate alignment and caller padding") { + cel::dyn_segment builder; + builder.op0([] { return 2.0; }); + builder.op0([] { return client_leaf{7}; }); + builder.op1( + [](const client_leaf& source) { return double(source.number); }); + builder.op2([](double a, double b) { return a + b; }); + auto program = std::move(builder).finish(); + CHECK(program.result_type().byte_layout().alignment == alignof(double)); + const auto& requirements = program.requirements(); + CHECK(requirements.alignment == alignof(client_leaf)); + CHECK(requirements.frame_extent == 512); + CHECK(requirements.live_slots == 2); + auto typed = program.prepare(); + auto raw = cel::detail::segment_access::prepare_raw(program, {}, program.result_type()); + CHECK(&typed.requirements() == &program.requirements()); + CHECK(&raw.requirements() == &program.requirements()); + cel::raw_stack stack; + stack.push(true); + const auto prefix_cursor = stack.cursor(); + const auto prefix_depth = stack.depth(); + const auto reservation = typed.requirements().for_prefix(prefix_cursor, prefix_depth); + CHECK(reservation.bytes.size == 768); + CHECK(reservation.slots == 3); + stack.reserve(reservation.bytes.size, reservation.bytes.alignment); + stack.reserve_depth(reservation.slots); + alignas(double) std::array bytes{}; + const auto result = typed.call(stack); + raw.call_into(stack, {}, bytes.data()); + raw.destroy_result(bytes.data()); + CHECK(result == 9.0); + CHECK(stack.cursor() == prefix_cursor); + CHECK(stack.depth() == prefix_depth); + CHECK(stack.pop()); +} +TEST_CASE("published reservations check prefix arithmetic and reject construction overflow") { + cel::dyn_segment builder; + builder.op0([] { return 2.0; }); + auto program = std::move(builder).finish(); + const auto maximum = std::numeric_limits::max(); + CHECK_THROWS_AS(program.requirements().for_prefix(maximum, 0), std::overflow_error); + CHECK_THROWS_AS(program.requirements().for_prefix(0, maximum), std::overflow_error); + auto malformed = program.requirements(); + malformed.alignment = 3; + CHECK_THROWS_AS(malformed.for_prefix(0, 0), std::invalid_argument); + auto huge = cel::value_type::leaf(); + for (int i = 0; i != std::numeric_limits::digits - 1; ++i) { + const std::array fields{huge, huge}; + huge = cel::value_type::tuple(fields); + } + cel::dyn_segment wide; + wide.push_argument(0, huge); + CHECK_THROWS_AS(wide.push_argument(1, huge), std::overflow_error); + auto frozen = std::move(wide).finish(); + CHECK_NOTHROW(cel::detail::segment_access::prepare_raw(frozen, std::array{huge}, huge)); + CHECK(frozen.requirements().frame_extent == huge.byte_layout().size); + CHECK(frozen.requirements().live_slots == 1); +} +} // namespace + +#endif diff --git a/src/frame.hpp b/src/frame.hpp index 5281341..f8a063d 100644 --- a/src/frame.hpp +++ b/src/frame.hpp @@ -1,32 +1,9 @@ // SPDX-License-Identifier: BSL-1.0 #ifndef CEL_RUNTIME_FRAME_HPP #define CEL_RUNTIME_FRAME_HPP -#include "storage.hpp" #include -#include namespace cel::detail { -/// A live canonical operand with retained destruction metadata. -struct stack_slot { - value_type type; ///< Retains the complete descriptor until payload retirement. - std::size_t previous; ///< Restores the cursor, including preceding padding. - std::size_t offset; ///< Locates canonical bytes in reusable storage. -}; -/// The exclusive state of a reusable operand stack and its evaluation scopes. -/// -/// Zero-byte operands remain distinct live slots. Only the innermost frame mutates the -/// stack, and canonical phases exclude reentrant mutation, extraction, and frame entry. -struct stack_state { - // [knowledge] slots describes exactly the initialized live owners. cursor excludes - // spare initialized bytes; each slot.previous restores the prior byte cursor, - // including padding. active borrows the innermost frame, and phase_active belongs - // to the one current canonical ownership operation. - storage bytes; ///< Owns bytewise-transferable canonical storage. - std::vector slots; ///< Owns exactly the initialized operand slots. - std::size_t cursor = 0; ///< Marks active bytes, not spare initialized storage. - frame* active = nullptr; ///< Borrows the innermost live frame. - bool phase_active = false; ///< Excludes reentry while canonical bytes/slots are unstable. -}; /// Trusted canonical access for signature-checked instructions. /// /// Operand views acquire no ownership and expire on stack mutation or destruction. @@ -50,20 +27,7 @@ struct frame_access { /// /// Complexity: growth costs, including newly initialized spare bytes; no main-stack /// allocation when byte, alignment, and slot reservations suffice. - static void reserve_result(frame& scope, const value_type& result, std::size_t consumed) { - scope.require_active(); - auto& data = scope._stack->state(); - if (consumed > data.slots.size() - scope._checkpoint) - throw std::out_of_range("transfer operand underflow"); - raw_stack::phase_guard phase(*scope._stack); - const auto remaining = data.slots.size() - consumed; - const auto cursor = consumed == 0 ? data.cursor : data.slots[remaining].previous; - const auto bytes = result.byte_layout(); - const auto extent = checked_add(align_offset(cursor, bytes.alignment), bytes.size); - data.slots.reserve(checked_add(remaining, 1)); - data.bytes.reserve(extent, bytes.alignment); - if (extent > data.bytes.size()) data.bytes.resize(extent); - } + static void reserve_result(frame& scope, const value_type& result, std::size_t consumed); /// An operand view borrowed for one canonical acquisition. /// /// The enclosing acquire call bounds every use; copies do not extend that lifetime. diff --git a/src/instruction.hpp b/src/instruction.hpp index ca1b0f2..74ec569 100644 --- a/src/instruction.hpp +++ b/src/instruction.hpp @@ -2,54 +2,12 @@ #ifndef CEL_RUNTIME_INSTRUCTION_HPP #define CEL_RUNTIME_INSTRUCTION_HPP #include -#include -#include namespace cel { class compiled_segment; } // namespace cel namespace cel::detail { class prepared_raw_segment; -/// A borrowed capture with its typed execution, destruction, and retirement operations. -/// -/// The capture owner must retain the live object until destruction. -struct instruction { - const void* capture; ///< Borrows its stable capture object. - void (*execute)(const void*, frame&); ///< Dispatches through the typed thunk. - void (*destroy)(const void*) noexcept; ///< Destroys the actual capture type. - void (*retire)(const void*, retirement_queue&) noexcept; ///< Detaches runtime ownership edges. -}; -/// Stable capture storage with exactly-once destruction of constructed operations. -struct instruction_storage : retirement_node { - std::pmr::monotonic_buffer_resource arena; ///< Owns stable aligned object storage. - std::vector instructions; ///< Owns dispatch/destruction records. - /// Creates empty capture storage with last-owner retirement. - instruction_storage() : retirement_node(dispose_storage) {} - /// Destroys stored captures and releases their storage, deferring managed descendant - /// retirement. - /// - /// \pre base is the live instruction_storage selected by its retirement callback. - /// - /// Complexity: O(instruction count + capture retirement/destruction work) time without - /// traversal allocation. - static void dispose_storage(retirement_node& base, retirement_queue& queue) noexcept { - auto& storage = static_cast(base); - for (auto it = storage.instructions.rbegin(); it != storage.instructions.rend(); ++it) { - if (it->retire) it->retire(it->capture, queue); - it->destroy(it->capture); - } - storage.instructions.clear(); - delete &storage; - } - /// Destroys captures before releasing their arena, in reverse construction order. - /// - /// Complexity: O(instructions + capture destruction work). - ~instruction_storage() { - // Captures have real object lifetimes; arena release alone cannot destroy them. - for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) - it->destroy(it->capture); - } -}; /// Checked preparation and trusted canonical capture publication. struct segment_access { /// Binds canonical execution for internal callers; follows the checked preparation contract. @@ -59,9 +17,7 @@ struct segment_access { std::span arguments, const value_type& result); /// Releases a mutable sequence into the supplied retirement operation. - static void retire(raw_segment& segment, retirement_queue& queue) noexcept { - segment._storage.retire(queue); - } + static void retire(raw_segment& segment, retirement_queue& queue) noexcept; /// Releases frozen code into the supplied retirement operation without recursive destruction. static void retire(cel::compiled_segment& segment, retirement_queue& queue) noexcept; /// Releases a prepared binding's code, leaving its signature metadata owned by the binding. diff --git a/src/raw_segment.cpp b/src/raw_segment.cpp index 6ec8ad5..1c89dce 100644 --- a/src/raw_segment.cpp +++ b/src/raw_segment.cpp @@ -1,9 +1,56 @@ // SPDX-License-Identifier: BSL-1.0 #include "instruction.hpp" #include +#include #include +#include namespace cel::detail { +namespace { +/// A borrowed capture with its typed execution, destruction, and retirement operations. +/// +/// The capture owner must retain the live object until destruction. +struct instruction { + const void* capture; ///< Borrows its stable capture object. + void (*execute)(const void*, frame&); ///< Dispatches through the typed thunk. + void (*destroy)(const void*) noexcept; ///< Destroys the actual capture type. + void (*retire)(const void*, retirement_queue&) noexcept; ///< Detaches runtime ownership edges. +}; +} // namespace +/// Stable capture storage with exactly-once destruction of constructed operations. +struct instruction_storage : retirement_node { + std::pmr::monotonic_buffer_resource arena; ///< Owns stable aligned object storage. + std::vector instructions; ///< Owns dispatch/destruction records. + /// Creates empty capture storage with last-owner retirement. + instruction_storage() : retirement_node(dispose_storage) {} + /// Destroys stored captures and releases their storage, deferring managed descendant + /// retirement. + /// + /// \pre base is the live instruction_storage selected by its retirement callback. + /// + /// Complexity: O(instruction count + capture retirement/destruction work) time without + /// traversal allocation. + static void dispose_storage(retirement_node& base, retirement_queue& queue) noexcept { + auto& storage = static_cast(base); + for (auto it = storage.instructions.rbegin(); it != storage.instructions.rend(); ++it) { + if (it->retire) it->retire(it->capture, queue); + it->destroy(it->capture); + } + storage.instructions.clear(); + delete &storage; + } + /// Destroys captures before releasing their arena, in reverse construction order. + /// + /// Complexity: O(instructions + capture destruction work). + ~instruction_storage() { + // Captures have real object lifetimes; arena release alone cannot destroy them. + for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) + it->destroy(it->capture); + } +}; +void segment_access::retire(raw_segment& segment, retirement_queue& queue) noexcept { + segment._storage.retire(queue); +} raw_segment::raw_segment() noexcept = default; raw_segment::~raw_segment() = default; raw_segment::raw_segment(raw_segment&& other) noexcept = default; @@ -36,3 +83,37 @@ void raw_segment::execute(frame& scope) const { } } } // namespace cel::detail + +#include +#if CPP_LIBRARY_TESTING() +#include +#include + +namespace { +/// Creates lazy executable ownership without evaluating nested branches. +/// Complexity: O(depth) time and owned space. +cel::compiled_segment lazy_chain(int depth) { + cel::dyn_segment base; + base.just(cel::value::from(true)); + for (int i = 0; i != depth; ++i) { + cel::dyn_segment next; + next.just(cel::value::from(true)); + next.logical_and(std::move(base)); + base = std::move(next); + } + return std::move(base).finish(); +} +TEST_CASE("deep lazy code retained by a prepared binding retires on its last release") { + auto program = lazy_chain(12000); + auto prepared = + cel::detail::segment_access::prepare_raw(program, {}, cel::value_type::leaf()); + cel::dyn_segment empty; + auto replacement = std::move(empty).finish(); + auto replacement_binding = + cel::detail::segment_access::prepare_raw(replacement, {}, cel::value_type{}); + program = std::move(replacement); + CHECK_NOTHROW(prepared = std::move(replacement_binding)); +} +} // namespace + +#endif diff --git a/src/raw_stack.cpp b/src/raw_stack.cpp index 59e34e9..c72d577 100644 --- a/src/raw_stack.cpp +++ b/src/raw_stack.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: BSL-1.0 #include "frame.hpp" +#include "storage.hpp" #include "type_ops.hpp" #include "value_ops.hpp" #include @@ -11,6 +12,47 @@ #include #include #include +#include + +namespace cel::detail { +namespace { +/// A live canonical operand with retained destruction metadata. +struct stack_slot { + value_type type; ///< Retains the complete descriptor until payload retirement. + std::size_t previous; ///< Restores the cursor, including preceding padding. + std::size_t offset; ///< Locates canonical bytes in reusable storage. +}; +} // namespace +/// The exclusive state of a reusable operand stack and its evaluation scopes. +/// +/// Zero-byte operands remain distinct live slots. Only the innermost frame mutates the +/// stack, and canonical phases exclude reentrant mutation, extraction, and frame entry. +struct stack_state { + // [knowledge] slots describes exactly the initialized live owners. cursor excludes + // spare initialized bytes; each slot.previous restores the prior byte cursor, + // including padding. active borrows the innermost frame, and phase_active belongs + // to the one current canonical ownership operation. + storage bytes; ///< Owns bytewise-transferable canonical storage. + std::vector slots; ///< Owns exactly the initialized operand slots. + std::size_t cursor = 0; ///< Marks active bytes, not spare initialized storage. + frame* active = nullptr; ///< Borrows the innermost live frame. + bool phase_active = false; ///< Excludes reentry while canonical bytes/slots are unstable. +}; +void frame_access::reserve_result(frame& scope, const value_type& result, std::size_t consumed) { + scope.require_active(); + auto& data = scope._stack->state(); + if (consumed > data.slots.size() - scope._checkpoint) + throw std::out_of_range("transfer operand underflow"); + raw_stack::phase_guard phase(*scope._stack); + const auto remaining = data.slots.size() - consumed; + const auto cursor = consumed == 0 ? data.cursor : data.slots[remaining].previous; + const auto bytes = result.byte_layout(); + const auto extent = checked_add(align_offset(cursor, bytes.alignment), bytes.size); + data.slots.reserve(checked_add(remaining, 1)); + data.bytes.reserve(extent, bytes.alignment); + if (extent > data.bytes.size()) data.bytes.resize(extent); +} +} // namespace cel::detail namespace cel { using detail::align_offset; @@ -268,3 +310,666 @@ value frame::pop_value() { return _stack->extract(_checkpoint); } } // namespace cel + +#include +#if CPP_LIBRARY_TESTING() +#include "instruction.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +/// Exercises a client leaf requiring a larger alignment than built-ins. +struct alignas(256) aligned_leaf { + double number; ///< Stores the test's observable client payload. +}; + +/// Verifies empty scope lifetime and mixed canonical layout. +TEST_CASE("empty frames and mixed leaves preserve stack order and cursor") { + cel::raw_stack stack; + CHECK(stack.depth() == 0); + CHECK(stack.cursor() == 0); + cel::detail::raw_segment empty; + { + cel::detail::frame scope(stack); + empty.execute(scope); + scope.push(true); + scope.push(4.0); + scope.push(aligned_leaf{9.0}); + CHECK(scope.pop().number == 9.0); + CHECK(scope.pop() == 4.0); + CHECK(scope.pop()); + CHECK(stack.cursor() == 0); + } + + CHECK(stack.depth() == 0); + stack.push(7.0); + { + cel::detail::frame scope(stack); + scope.push(false); + } + CHECK(stack.pop() == 7.0); +} + +/// Verifies source operand order, zero arguments, and extensible arity. +TEST_CASE("stored operations preserve noncommutative operand order at every arity") { + cel::raw_stack stack; + cel::detail::raw_segment segment; + segment.push_op0([](cel::detail::frame&) { return 12.0; }); + segment.push_op0([](cel::detail::frame&) { return 3.0; }); + segment.push_op2( + [](cel::detail::frame&, double a, double b) { return a / b; }); + segment.push_op1([](cel::detail::frame&, double a) { return a + 1.0; }); + segment.push_op0([](cel::detail::frame&) { return 2.0; }); + segment.push_op0([](cel::detail::frame&) { return 1.0; }); + segment.push_op3( + [](cel::detail::frame&, double a, double b, double c) { return a - b - c; }); + cel::detail::frame scope(stack); + segment.execute(scope); + CHECK(scope.pop() == 2.0); + cel::detail::raw_segment arbitrary; + arbitrary.push_op( + [](cel::detail::frame&, double a, double b, double c, double d, double e) { + return a - b - c - d - e; + }); + for (auto n : {20.0, 1.0, 2.0, 3.0, 4.0}) + scope.push(n); + arbitrary.execute(scope); + CHECK(scope.pop() == 10.0); + cel::detail::raw_segment unit; + unit.push_op0([](cel::detail::frame&) {}); + unit.execute(scope); + CHECK(scope.depth() == 0); +} + +/// Owns a nontrivial capture whose address must remain stable after construction. +struct alignas(256) owning_capture { + std::unique_ptr owner; ///< Owns a callback resource. + int* released; ///< Borrows the release counter until segment destruction. + mutable const owning_capture* address = nullptr; ///< Records first execution address. + /// Acquires one exclusive resource. + explicit owning_capture(int& count) : owner(std::make_unique(8)), released(&count) {} + /// Transfers construction ownership normally. + owning_capture(owning_capture&&) noexcept = default; + /// Counts only destruction of the final resource owner. + ~owning_capture() { + if (owner) ++*released; + } + /// Returns the captured number, rejecting relocation after the first call. + double operator()(cel::detail::frame&) const { + if (address && address != this) throw std::runtime_error("relocated capture"); + if (reinterpret_cast(this) % alignof(owning_capture) != 0) + throw std::runtime_error("misaligned capture"); + address = this; + return *owner; + } +}; + +/// Supplies a copyable, nonmovable over-aligned callback with independent state. +struct alignas(256) copy_only_capture { + double number; ///< Owns the callback's result. + /// Initializes the result. + explicit copy_only_capture(double input) : number(input) {} + /// Copies the result independently. + copy_only_capture(const copy_only_capture&) = default; + /// Disallows move construction. + copy_only_capture(copy_only_capture&&) = delete; + /// Returns the owned result. + double operator()(cel::detail::frame&) const { return number; } +}; + +TEST_CASE("raw operations copy nonmovable lvalue captures independently") { + copy_only_capture input(7.0); + cel::detail::raw_segment segment; + segment.push_op0(input); + input.number = 99.0; + cel::raw_stack stack; + cel::detail::frame scope(stack); + segment.execute(scope); + CHECK(scope.pop() == 7.0); +} + +/// Verifies independent instruction ownership and stable nontrivial capture addresses. +TEST_CASE("captures survive input owners segment growth and segment moves") { + int released = 0; + cel::raw_stack stack; + { + cel::detail::raw_segment segment; + segment.push_op0(owning_capture(released)); + { + cel::detail::frame scope(stack); + segment.execute(scope); + CHECK(scope.pop() == 8.0); + } + for (int i = 0; i != 200; ++i) + segment.push_op0([](cel::detail::frame&) {}); + cel::detail::raw_segment moved(std::move(segment)); + cel::detail::frame scope(stack); + moved.execute(scope); + CHECK(scope.pop() == 8.0); + CHECK(released == 0); + } + CHECK(released == 1); +} + +/// Verifies reservation covers both payload bytes and active slot bookkeeping. +TEST_CASE("reserved scalar execution reuses one stack") { + cel::raw_stack stack; + stack.reserve(1024, 256); + cel::detail::raw_segment number; + number.push_op0([](cel::detail::frame&) { return 6.0; }); + number.push_op1([](cel::detail::frame&, double n) { return n / 2.0; }); + cel::detail::raw_segment boolean; + boolean.push_op0([](cel::detail::frame&) { return true; }); + boolean.push_op1([](cel::detail::frame&, bool n) { return !n; }); + { + cel::detail::frame scope(stack); + number.execute(scope); + CHECK(scope.pop() == 3.0); + boolean.execute(scope); + CHECK_FALSE(scope.pop()); + } + bool correct = true; + { + for (int i = 0; i != 2000; ++i) { + cel::detail::frame scope(stack); + number.execute(scope); + correct = correct && scope.pop() == 3.0; + boolean.execute(scope); + correct = correct && !scope.pop(); + } + } + CHECK(correct); + CHECK(stack.depth() == 0); +} + +/// Verifies explicit arguments/context and nested suffix isolation. +TEST_CASE("nested evaluations preserve outer arguments and live temporaries") { + cel::raw_stack stack; + const std::array arguments{cel::value::from(11.0)}; + int context = 7; + cel::detail::raw_segment nested; + nested.push_op0( + [](cel::detail::frame& scope) { return scope.argument(0).as(); }); + cel::detail::raw_segment outer; + outer.push_op1([&](cel::detail::frame& scope, double input) { + scope.push(5.0); + cel::detail::frame inner(stack, scope.arguments(), scope.context()); + nested.execute(inner); + const auto result = inner.pop(); + CHECK(scope.argument(0).as() == 11.0); + CHECK(scope.context() == &context); + return result + input; + }); + cel::detail::frame scope(stack, arguments, &context); + scope.push(3.0); + outer.execute(scope); + CHECK(scope.pop() == 14.0); + CHECK(scope.pop() == 5.0); + CHECK_THROWS_AS(scope.argument(1), std::out_of_range); +} + +/// Counts a synthetic opaque canonical resource independently of outer byte storage. +int live_resources = 0; +/// Selects which clone throws after earlier suffix ownership has been acquired. +int clones_before_failure = -1; +/// Clones one synthetic carrier, throwing without leaving partial ownership. +void clone_resource(const std::byte* source, std::byte* target) { + if (clones_before_failure == 0) throw std::runtime_error("clone failed"); + if (clones_before_failure > 0) --clones_before_failure; + std::memcpy(target, source, sizeof(void*)); + ++live_resources; +} +/// Releases one synthetic owner without allocating. +void destroy_resource(std::byte*) noexcept { --live_resources; } + +/// Verifies frame boundaries report malformed external requests before accessing memory. +TEST_CASE("checked stack boundaries reject underflow type mismatch and active-frame mutation") { + cel::raw_stack stack; + CHECK_THROWS_AS(stack.pop(), std::out_of_range); + CHECK_THROWS_AS(stack.reserve(10, 3), std::invalid_argument); + stack.push(2.0); + CHECK_THROWS_AS(stack.pop(), std::invalid_argument); + CHECK_THROWS_AS(stack.pop(), std::invalid_argument); + CHECK(stack.depth() == 1); + { + cel::detail::frame scope(stack); + CHECK_THROWS_AS(scope.pop(), std::out_of_range); + CHECK_THROWS_AS(stack.clear(), std::logic_error); + CHECK_THROWS_AS(stack.push(true), std::logic_error); + CHECK_THROWS_AS(stack.reserve(1024, 256), std::logic_error); + CHECK_THROWS_AS(stack.reserve_depth(1024), std::logic_error); + CHECK_THROWS_AS(cel::raw_stack(std::move(stack)), std::logic_error); + cel::raw_stack destination; + // NOLINTNEXTLINE(bugprone-use-after-move): rejected move preserves source. + CHECK_THROWS_AS(destination = std::move(stack), std::logic_error); + // NOLINTNEXTLINE(bugprone-use-after-move): rejected moves preserve frames. + cel::detail::frame inner(stack); + CHECK_THROWS_AS(scope.push(true), std::logic_error); + } + CHECK(stack.pop() == 2.0); + stack.clear(); +} + +/// Verifies preparation of zero-byte slots, reusable moved-from stacks, and segment assignment. +TEST_CASE("zero byte units and over-aligned operations reuse explicitly reserved depth") { + cel::raw_stack stack; + stack.reserve(1024, 256); + stack.reserve_depth(200); + cel::detail::raw_segment segment; + segment.push_op0([](cel::detail::frame&) { return aligned_leaf{13.0}; }); + segment.push_op0>([](cel::detail::frame&) { return std::tuple{}; }); + { + cel::detail::frame scope(stack); + segment.execute(scope); + CHECK(scope.pop>() == std::tuple{}); + CHECK(scope.pop().number == 13.0); + CHECK(&scope.stack() == &stack); + } + bool correct = true; + { + for (int i = 0; i != 100; ++i) { + cel::detail::frame scope(stack); + segment.execute(scope); + correct = correct && scope.pop>() == std::tuple{}; + correct = correct && scope.pop().number == 13.0; + for (int j = 0; j != 200; ++j) + scope.push(std::tuple{}); + } + } + CHECK(correct); + int released = 0; + { + cel::detail::raw_segment replaced; + replaced.push_op0(owning_capture(released)); + replaced = std::move(segment); + CHECK(released == 1); + cel::detail::frame scope(stack); + replaced.execute(scope); + CHECK(scope.pop>() == std::tuple{}); + CHECK(scope.pop().number == 13.0); + } + cel::raw_stack moved(std::move(stack)); + // NOLINTNEXTLINE(bugprone-use-after-move): the public contract promises reusable source stacks. + stack.push(17.0); + // NOLINTNEXTLINE(bugprone-use-after-move): observes the promised reused source. + CHECK(stack.pop() == 17.0); + CHECK(moved.depth() == 0); +} + +/// Verifies the canonical arbitrary-arity bridge and clone exceptions under execute rollback. +TEST_CASE("canonical instruction captures retain descriptors and clean failed clone suffixes") { + const auto opaque = cel::detail::type_access::install_callable_ownership( + cel::value_type::callable({}, cel::value_type::leaf()), + {clone_resource, destroy_resource}); + std::array bytes{}; + auto child = cel::detail::value_access::copy(opaque, bytes.data()); + auto aggregate = cel::value::tuple(std::array{child, child}); + const auto baseline = live_resources; + cel::raw_stack stack; + stack.push_clone(child); + { + cel::detail::raw_segment sequence; + cel::detail::segment_access::append(sequence, [owner = std::move(aggregate)]( + cel::detail::frame& scope) { + cel::detail::frame_access::push( + scope, owner.type(), cel::detail::value_access::data(owner), + [](const void* source, const cel::value_type& type, std::byte* target) { + cel::detail::clone_payload(type, static_cast(source), target); + }); + }); + // A separate matching bridge sequence demonstrates its unchecked signature contract. + cel::detail::raw_segment scalar; + cel::detail::segment_access::append(scalar, [](cel::detail::frame& scope) { + const auto type = cel::value_type::leaf(); + const auto* operand = cel::detail::frame_access::operand(scope, 0, type); + double result{}; + std::memcpy(&result, operand, sizeof(result)); + cel::detail::frame_access::discard(scope, 1); + scope.push(result / 2.0); + }); + cel::detail::frame scope(stack); + scope.push(12.0); + scalar.execute(scope); + CHECK(scope.pop() == 6.0); + scope.push(std::vector{1.0, 2.0}); + clones_before_failure = 1; + CHECK_THROWS_AS(sequence.execute(scope), std::runtime_error); + clones_before_failure = -1; + CHECK(scope.depth() == 0); + CHECK(live_resources == baseline + 1); + scope.push(18.0); + scalar.execute(scope); + CHECK(scope.pop() == 9.0); + } + CHECK(stack.depth() == 1); + stack.clear(); +} +/// Verifies throwing callbacks and clone failures retire only the acquired suffix. +TEST_CASE("throwing execution and composite cloning preserve the live prefix") { + cel::raw_stack stack; + auto prefix = cel::value::from(std::vector>{{1.0, 2.0}, {3.0}}); + stack.push_take(prefix); + CHECK(prefix.type().kind() == cel::type_kind::tuple); + cel::detail::raw_segment failure; + failure.push_op0>( + [](cel::detail::frame&) { return std::vector{7.0, 8.0}; }); + failure.push_op1>( + [](cel::detail::frame& scope, std::vector) -> double { + scope.push(std::vector{9.0}); + throw std::runtime_error("callback failed"); + }); + { + cel::detail::frame scope(stack); + CHECK_THROWS_AS(failure.execute(scope), std::runtime_error); + CHECK(scope.depth() == 0); + scope.push(true); + CHECK(scope.pop()); + } + CHECK(stack.depth() == 1); + CHECK(stack.pop>>() == + std::vector>{{1.0, 2.0}, {3.0}}); + + const auto opaque = cel::detail::type_access::install_callable_ownership( + cel::value_type::callable({}, cel::value_type::leaf()), + {clone_resource, destroy_resource}); + std::array bytes{}; + auto child = cel::detail::value_access::copy(opaque, bytes.data()); + const std::array children{child, child}; + auto owned = cel::value::tuple(children); + const auto baseline = live_resources; + stack.push(42.0); + { + cel::detail::frame scope(stack); + scope.push_clone(owned); + clones_before_failure = 1; + CHECK_THROWS_AS(scope.push_clone(owned), std::runtime_error); + CHECK(scope.depth() == 1); + CHECK(live_resources == baseline + 2); + clones_before_failure = -1; + } + CHECK(live_resources == baseline); + CHECK(stack.pop() == 42.0); +} +/// Verifies borrowed canonical input slots are read lazily and results transfer without boxes. +TEST_CASE("explicit canonical frames clone emitted reads and extract independent results") { + const auto scalar_type = cel::value_type::leaf(); + double input = 23.0; + const std::array scalar_arguments{ + cel::detail::borrowed_value{scalar_type, reinterpret_cast(&input)}}; + cel::detail::raw_segment reads; + cel::detail::segment_access::append(reads, + [](cel::detail::frame& scope) { scope.push_argument(0); }); + cel::raw_stack stack; + stack.reserve(1024, 256); + int context = 5; + double output = 0; + { + cel::detail::frame scope(stack, scalar_arguments, &context); + reads.execute(scope); + cel::detail::frame_access::release_result(scope, scalar_type, + reinterpret_cast(&output)); + CHECK(output == 23.0); + CHECK(scope.depth() == 0); + CHECK(scope.argument(0).as() == 23.0); + } + bool correct = true; + { + for (int i = 0; i != 1000; ++i) { + cel::detail::frame scope(stack, scalar_arguments, &context); + reads.execute(scope); + cel::detail::frame nested(stack, scope.canonical_arguments(), scope.context()); + reads.execute(nested); + cel::detail::frame_access::release_result(nested, scalar_type, + reinterpret_cast(&output)); + correct = correct && output == 23.0; + } + } + CHECK(correct); + + auto owner = cel::value::from(std::vector>{{1.0, 2.0}}); + const std::array borrowed{ + cel::detail::borrowed_value{owner.type(), cel::detail::value_access::data(owner)}}; + { + cel::detail::frame scope(stack, borrowed); + reads.execute(scope); + auto copy = scope.pop_value(); + copy.set(0, cel::value::from(std::vector{8.0})); + CHECK(owner.at(0).at(0).as() == 1.0); + CHECK(copy.at(0).at(0).as() == 8.0); + CHECK_THROWS_AS(scope.push_argument(1), std::out_of_range); + cel::detail::storage result; + const auto layout = owner.type().byte_layout(); + result.reserve(layout.size, layout.alignment); + result.resize(layout.size); + reads.execute(scope); + cel::detail::frame_access::release_result(scope, owner.type(), result.data()); + owner.set(0, cel::value::from(std::vector{6.0})); + auto independent = cel::detail::value_access::take(owner.type(), result.data()); + CHECK(independent.at(0).at(0).as() == 1.0); + CHECK(owner.at(0).at(0).as() == 6.0); + } + const std::array missing{cel::detail::borrowed_value{scalar_type, nullptr}}; + CHECK_THROWS_AS(cel::detail::frame(stack, missing), std::invalid_argument); + alignas(double) std::array unaligned{}; + const std::array misaligned{cel::detail::borrowed_value{scalar_type, unaligned.data() + 1}}; + CHECK_THROWS_AS(cel::detail::frame(stack, misaligned), std::invalid_argument); + cel::detail::frame scope(stack); + CHECK(scope.depth() == 0); +} +/// Records bounded hook reentry attempts without relying on an invalid raw signature. +struct reentry_state { + cel::raw_stack& stack; ///< Borrows the tested stack. + cel::detail::frame* scope; ///< Borrows the active scope, or null during direct clear. + int rejected = 0; ///< Counts documented logic-error rejections. + bool unexpected = false; ///< Records any other exception from noexcept destruction probes. + bool propagate = false; ///< Lets a clone rejection escape to test rollback. + bool clone_attempted = false; ///< Bounds clone reentry to one attempt. + bool destroy_attempted = false; ///< Bounds retirement reentry to one attempt. + /// Attempts same-owner mutation and both forms of nested frame entry. + void probe() { + try { + if (scope) + scope->push(99.0); + else + stack.push(99.0); + } catch (const std::logic_error&) { + ++rejected; + if (propagate) throw; + } + try { + cel::detail::frame nested(stack); + } catch (const std::logic_error&) { + ++rejected; + } + try { + cel::detail::frame nested(stack, std::span{}); + } catch (const std::logic_error&) { + ++rejected; + } + } +}; +/// Enables hooks only during their bounded test scopes, never as production context. +reentry_state* active_reentry = nullptr; +/// Restores the test hook context before its borrowed state dies, including on exceptions. +struct reentry_scope { + reentry_state* previous; ///< Retains the prior single-threaded hook context. + /// Borrows the state for this bounded probe scope. + explicit reentry_scope(reentry_state& state) : previous(active_reentry) { + active_reentry = &state; + } + /// Disallows duplicated hook-scope ownership. + reentry_scope(const reentry_scope&) = delete; + /// Disallows reassigned hook-scope ownership. + reentry_scope& operator=(const reentry_scope&) = delete; + /// Restores the prior context. + ~reentry_scope() { active_reentry = previous; } +}; +/// Clones a synthetic owner after a bounded construction reentry attempt. +void clone_reentry(const std::byte* source, std::byte* target) { + if (active_reentry && !active_reentry->clone_attempted) { + active_reentry->clone_attempted = true; + active_reentry->probe(); + } + std::memcpy(target, source, sizeof(void*)); + ++live_resources; +} +/// Retires a synthetic owner while catching rejection inside its noexcept hook. +void destroy_reentry(std::byte*) noexcept { + if (active_reentry && !active_reentry->destroy_attempted) { + active_reentry->destroy_attempted = true; + try { + active_reentry->probe(); + } catch (...) { + active_reentry->unexpected = true; + } + } + --live_resources; +} +/// Catches clone/write offset reuse and retiring-slot mutation at safe boundaries. +TEST_CASE("payload clone and noexcept retirement hooks reject reentry") { + const auto type = cel::detail::type_access::install_callable_ownership( + cel::value_type::callable({}, cel::value_type::leaf()), + {clone_reentry, destroy_reentry}); + std::array bytes{}; + auto source = cel::detail::value_access::copy(type, bytes.data()); + const auto baseline = live_resources; + cel::raw_stack stack; + stack.reserve(1024, 256); + stack.push(17.0); + { + cel::detail::frame scope(stack); + reentry_state attempts{stack, &scope}; + reentry_scope enabled(attempts); + scope.push_clone(source); + CHECK(attempts.rejected == 3); + CHECK(scope.depth() == 1); + cel::detail::frame_access::discard(scope, scope.depth()); + CHECK(attempts.rejected == 6); + CHECK_FALSE(attempts.unexpected); + active_reentry = nullptr; + CHECK(live_resources == baseline); + scope.push(8.0); + CHECK(scope.pop() == 8.0); + } + CHECK(stack.pop() == 17.0); + stack.push_clone(source); + reentry_state direct{stack, nullptr}; + direct.clone_attempted = true; + reentry_scope enabled_direct(direct); + stack.clear(); + active_reentry = nullptr; + CHECK(direct.rejected == 3); + CHECK_FALSE(direct.unexpected); + CHECK(stack.depth() == 0); + stack.push(true); + CHECK(stack.pop()); +} + +/// Catches a gate left held after a rejected clone callback unwinds through execute. +TEST_CASE("rejected clone reentry rolls back only the frame suffix and restores access") { + const auto type = cel::detail::type_access::install_callable_ownership( + cel::value_type::callable({}, cel::value_type::leaf()), + {clone_reentry, destroy_reentry}); + std::array bytes{}; + auto source = cel::detail::value_access::copy(type, bytes.data()); + cel::raw_stack stack; + stack.reserve(1024, 256); + stack.push(std::vector{4.0, 5.0}); + cel::detail::raw_segment sequence; + cel::detail::segment_access::append( + sequence, [&source](cel::detail::frame& scope) { scope.push_clone(source); }); + { + cel::detail::frame scope(stack); + scope.push(std::vector{9.0}); + reentry_state attempts{stack, &scope}; + attempts.propagate = true; + reentry_scope enabled(attempts); + CHECK_THROWS_AS(sequence.execute(scope), std::logic_error); + active_reentry = nullptr; + CHECK(scope.depth() == 0); + scope.push(7.0); + CHECK(scope.pop() == 7.0); + cel::detail::frame nested(stack); + nested.push(false); + CHECK_FALSE(nested.pop()); + } + CHECK(stack.pop>() == std::vector{4.0, 5.0}); +} + +/// Verifies null bytes preserve non-unit zero-byte aggregate identity and stack effects. +TEST_CASE("borrowed non-unit zero-byte aggregates preserve complete shape") { + using aggregate = std::tuple, std::tuple<>>; + const auto type = cel::detail::concrete_adapter::type(); + const std::array inputs{cel::detail::borrowed_value{type, nullptr}}; + cel::raw_stack stack; + cel::detail::frame scope(stack, inputs); + CHECK(type.byte_layout().size == 0); + CHECK(type.fields().size() == 2); + CHECK_FALSE(type.same_shape(cel::value_type{})); + CHECK(scope.argument(0).as() == aggregate{}); + scope.push_argument(0); + auto owner = scope.pop_value(); + CHECK(owner.type().same_shape(type)); + CHECK(owner.size() == 2); + scope.push_take(owner); + CHECK(scope.pop() == aggregate{}); + CHECK(scope.depth() == 0); + CHECK(stack.cursor() == 0); +} + +/// Verifies allocating raw reads share the phase gate and release it on reader failure. +TEST_CASE("scoped canonical acquisition and direct writers contain reentry") { + cel::raw_stack stack; + stack.reserve(1024, 256); + stack.push(15.0); + { + cel::detail::frame scope(stack); + scope.push(std::vector{7.0, 8.0}); + const auto type = cel::detail::concrete_adapter>::type(); + reentry_state attempts{stack, &scope}; + reentry_scope enabled(attempts); + const auto acquired = cel::detail::frame_access::acquire(scope, [&](const auto& operands) { + attempts.probe(); + return cel::detail::value_access::copy(type, operands.operand(0, type)); + }); + active_reentry = nullptr; + CHECK(attempts.rejected == 3); + CHECK(acquired.as>() == std::vector{7.0, 8.0}); + CHECK(scope.depth() == 1); + CHECK_THROWS_AS(cel::detail::frame_access::acquire(scope, + [&](const auto& operands) -> double { + (void)operands.operand(0, type); + throw std::runtime_error( + "reader failed"); + }), + std::runtime_error); + CHECK(scope.pop>() == std::vector{7.0, 8.0}); + reentry_state writer{stack, &scope}; + reentry_scope enabled_writer(writer); + const auto scalar_type = cel::value_type::leaf(); + const double input = 3.0; + cel::detail::frame_access::push( + scope, scalar_type, &input, + [](const void* source, const cel::value_type&, std::byte* target) { + active_reentry->probe(); + std::memcpy(target, source, sizeof(double)); + }); + active_reentry = nullptr; + CHECK(writer.rejected == 3); + CHECK(scope.pop() == 3.0); + cel::detail::frame nested(stack); + nested.push(false); + CHECK_FALSE(nested.pop()); + } + CHECK(stack.pop() == 15.0); +} +} // namespace + +#endif diff --git a/src/storage.cpp b/src/storage.cpp index 3957feb..8cd9fc9 100644 --- a/src/storage.cpp +++ b/src/storage.cpp @@ -32,6 +32,7 @@ std::size_t checked_add(std::size_t left, std::size_t right) { std::size_t align_offset(std::size_t offset, std::size_t alignment) { validate_alignment(alignment); + // NOLINTNEXTLINE(clang-analyzer-core.DivideZero): validation rejects zero alignment. const auto remainder = offset % alignment; return remainder == 0 ? offset : detail::checked_add(offset, alignment - remainder); } @@ -84,3 +85,234 @@ void storage::resize(std::size_t bytes) { } } // namespace cel::detail + +#include +#if CPP_LIBRARY_TESTING() +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +/// Supplies a trivially copyable, over-aligned payload. +struct alignas(256) leaf { + /// Stores a scalar whose representation survives byte transfer. + std::uint64_t value; +}; +/// Catches incorrect rounding of zero, already-aligned, and unaligned offsets. +TEST_CASE("align_offset rounds upward without changing aligned offsets") { + CHECK(cel::detail::align_offset(0, 64) == 0); + CHECK(cel::detail::align_offset(1, 64) == 64); + CHECK(cel::detail::align_offset(64, 64) == 64); + CHECK(cel::detail::align_offset(65, 64) == 128); + CHECK(cel::detail::align_offset(7, 1) == 7); + CHECK(cel::detail::align_offset(std::numeric_limits::max(), 1) == + std::numeric_limits::max()); +} + +/// Catches unchecked alignment and offset overflow at the safe boundary. +TEST_CASE("align_offset rejects invalid alignment and arithmetic overflow") { + CHECK_THROWS_AS(cel::detail::align_offset(1, 0), std::invalid_argument); + CHECK_THROWS_AS(cel::detail::align_offset(1, 3), std::invalid_argument); + CHECK_THROWS_AS(cel::detail::align_offset(std::numeric_limits::max(), 64), + std::overflow_error); + constexpr auto highest = std::numeric_limits::max() / 2 + 1; + CHECK(cel::detail::align_offset(highest, highest) == highest); + CHECK_THROWS_AS(cel::detail::align_offset(highest + 1, highest), std::overflow_error); +} + +/// Catches accidental allocation for zero bytes or forgotten empty-state alignment. +TEST_CASE("empty storage remains allocation-free and remembers alignment") { + cel::detail::storage bytes; + CHECK(bytes.data() == nullptr); + CHECK(bytes.size() == 0); + CHECK(bytes.capacity() == 0); + bytes.reserve(0, 256); + CHECK(bytes.data() == nullptr); + CHECK(bytes.capacity() == 0); + CHECK(bytes.alignment() >= 256); + bytes.resize(1); + CHECK(reinterpret_cast(bytes.data()) % 256 == 0); + CHECK(bytes.data()[0] == std::byte{0}); +} + +/// Catches loss of initialized bytes, reserve changing size, or narrowing alignment. +TEST_CASE("reserve preserves initialized bytes through growth and realignment") { + cel::detail::storage bytes; + bytes.resize(4); + const std::array payload{std::byte{0x11}, std::byte{0x22}, std::byte{0x33}, std::byte{0x44}}; + std::memcpy(bytes.data(), payload.data(), payload.size()); + const auto growth_request = bytes.capacity() + 1; + bytes.reserve(growth_request, 64); + CHECK(bytes.capacity() >= growth_request); + CHECK(bytes.size() == 4); + CHECK(std::memcmp(bytes.data(), payload.data(), payload.size()) == 0); + const auto capacity = bytes.capacity(); + bytes.reserve(4, 256); + CHECK(bytes.capacity() >= capacity); + CHECK(bytes.alignment() >= 256); + CHECK(reinterpret_cast(bytes.data()) % 256 == 0); + CHECK(std::memcmp(bytes.data(), payload.data(), payload.size()) == 0); + auto* const address = bytes.data(); + bytes.reserve(1, 1); + CHECK(bytes.data() == address); + CHECK(bytes.alignment() >= 256); + CHECK(bytes.size() == 4); + const auto& view = bytes; + CHECK(view.data()[3] == std::byte{0x44}); +} + +/// Catches uninitialized exposed bytes or shrinking that loses the retained prefix. +TEST_CASE("resize initializes growth and retains capacity on shrink") { + cel::detail::storage bytes; + bytes.resize(2); + bytes.data()[0] = std::byte{0x55}; + bytes.data()[1] = std::byte{0x66}; + const auto growth_request = bytes.capacity() + 3; + bytes.resize(growth_request); + CHECK(bytes.size() == growth_request); + CHECK(bytes.capacity() >= growth_request); + CHECK(bytes.data()[0] == std::byte{0x55}); + CHECK(bytes.data()[1] == std::byte{0x66}); + CHECK(std::all_of(bytes.data() + 2, bytes.data() + growth_request, + [](std::byte value) { return value == std::byte{0}; })); + const auto capacity = bytes.capacity(); + bytes.resize(1); + CHECK(bytes.capacity() == capacity); + bytes.resize(2); + CHECK(bytes.data()[0] == std::byte{0x55}); + CHECK(bytes.data()[1] == std::byte{0}); + bytes.resize(0); + CHECK(bytes.size() == 0); + CHECK(bytes.capacity() == capacity); +} + +/// Catches silent arithmetic failure or mutation before an unsuccessful reserve. +TEST_CASE("storage reports invalid alignment and allocation arithmetic overflow") { + cel::detail::storage bytes; + bytes.resize(1); + bytes.data()[0] = std::byte{0x77}; + auto* const address = bytes.data(); + const auto capacity = bytes.capacity(); + const auto alignment = bytes.alignment(); + CHECK_THROWS_AS(bytes.reserve(1, 0), std::invalid_argument); + CHECK_THROWS_AS(bytes.reserve(1, 3), std::invalid_argument); + CHECK_THROWS_AS(bytes.reserve(std::numeric_limits::max(), 64), + std::overflow_error); + CHECK_THROWS_AS(bytes.resize(std::numeric_limits::max()), std::overflow_error); + CHECK(bytes.data() == address); + CHECK(bytes.capacity() == capacity); + CHECK(bytes.alignment() == alignment); + CHECK(bytes.size() == 1); + CHECK(bytes.data()[0] == std::byte{0x77}); +} + +// The analyzer assumes an address-space-sized allocation succeeds instead of throwing. +// NOLINTBEGIN(clang-analyzer-cplusplus.NewDelete,clang-analyzer-security.ArrayBound) +/// Catches allocation failures converted into success or loss of prior ownership. +TEST_CASE("storage propagates allocation failure without changing initialized bytes") { + cel::detail::storage bytes; + bytes.resize(1); + bytes.data()[0] = std::byte{0x99}; + auto* const address = bytes.data(); + const auto capacity = bytes.capacity(); + const auto alignment = bytes.alignment(); + // This representable, aligned extent exceeds the available address space. + constexpr auto impossible = std::numeric_limits::max() - 255; + CHECK_THROWS_AS(bytes.reserve(impossible, 256), std::bad_alloc); + CHECK(bytes.data() == address); + CHECK(bytes.size() == 1); + CHECK(bytes.capacity() == capacity); + CHECK(bytes.alignment() == alignment); + CHECK(bytes.data()[0] == std::byte{0x99}); +} + +// NOLINTEND(clang-analyzer-cplusplus.NewDelete,clang-analyzer-security.ArrayBound) + +/// Catches misaligned allocation or byte transfer that corrupts implicit-lifetime payloads. +TEST_CASE("storage holds and transfers an alignas 256 trivially copyable leaf") { + static_assert(std::is_trivially_copyable_v); + cel::detail::storage bytes; + bytes.reserve(sizeof(leaf), alignof(leaf)); + CHECK(bytes.capacity() >= sizeof(leaf)); + bytes.resize(sizeof(leaf)); + const leaf original{0x123456789abcdef0}; + std::memcpy(bytes.data(), &original, sizeof(original)); + CHECK(reinterpret_cast(bytes.data()) % 256 == 0); + CHECK(reinterpret_cast(bytes.data())->value == original.value); + const auto growth_request = bytes.capacity() + 1; + bytes.reserve(growth_request, 1); + CHECK(bytes.capacity() >= growth_request); + CHECK(reinterpret_cast(bytes.data()) % 256 == 0); + CHECK(reinterpret_cast(bytes.data())->value == original.value); + leaf restored{}; + std::memcpy(&restored, bytes.data(), sizeof(restored)); + CHECK(restored.value == original.value); +} + +// Moved-from observations verify storage's documented empty and reusable state. +// NOLINTBEGIN(bugprone-use-after-move,clang-analyzer-cplusplus.Move) +/// Catches duplicated ownership, stale moved-from metadata, or lost destination cleanup. +TEST_CASE("storage moves unique ownership and leaves its source reusable") { + static_assert(!std::is_copy_constructible_v); + static_assert(!std::is_copy_assignable_v); + static_assert(std::is_nothrow_move_constructible_v); + static_assert(std::is_nothrow_move_assignable_v); + cel::detail::storage source; + source.reserve(4, 256); + source.resize(4); + source.data()[0] = std::byte{0x88}; + auto* const address = source.data(); + cel::detail::storage moved(std::move(source)); + CHECK(moved.data() == address); + CHECK(moved.size() == 4); + CHECK(moved.alignment() >= 256); + CHECK(source.data() == nullptr); + CHECK(source.size() == 0); + CHECK(source.capacity() == 0); + source.resize(1); + CHECK(source.data()[0] == std::byte{0}); + source = std::move(moved); + CHECK(source.data() == address); + CHECK(source.data()[0] == std::byte{0x88}); + CHECK(moved.data() == nullptr); + CHECK(moved.size() == 0); + CHECK(moved.capacity() == 0); + auto& alias = source; + source = std::move(alias); + CHECK(source.data() == address); + cel::detail::storage empty; + source = std::move(empty); + CHECK(source.data() == nullptr); + CHECK(source.size() == 0); + CHECK(source.capacity() == 0); +} +// NOLINTEND(bugprone-use-after-move,clang-analyzer-cplusplus.Move) + +// Moved-from alignment observations verify the documented reset. +// NOLINTBEGIN(bugprone-use-after-move,clang-analyzer-cplusplus.Move) +/// Catches alignment metadata lost while moving allocation-free storage. +TEST_CASE("storage moves alignment even when no allocation exists") { + cel::detail::storage source; + source.reserve(0, 256); + cel::detail::storage destination(std::move(source)); + CHECK(destination.data() == nullptr); + CHECK(destination.size() == 0); + CHECK(destination.capacity() == 0); + CHECK(destination.alignment() >= 256); + CHECK(source.alignment() == alignof(std::max_align_t)); + source = std::move(destination); + CHECK(source.alignment() >= 256); + CHECK(destination.alignment() == alignof(std::max_align_t)); + source.resize(1); + CHECK(reinterpret_cast(source.data()) % 256 == 0); +} +// NOLINTEND(bugprone-use-after-move,clang-analyzer-cplusplus.Move) +} // namespace + +#endif diff --git a/src/value.cpp b/src/value.cpp index 1715ee6..1a84546 100644 --- a/src/value.cpp +++ b/src/value.cpp @@ -19,6 +19,7 @@ namespace cel::detail { struct array_owner; +namespace { /// A byte-transferable canonical packed array owner. /// /// Bytewise relocation transfers ownership and retires its source, never clones it. @@ -58,6 +59,7 @@ Byte* byte_at(Byte* data, std::size_t offset) noexcept { return data ? data + offset : nullptr; } +} // namespace /// Exclusive ownership of a partially initialized packed canonical array. /// /// Destruction retires complete elements and any acquired resources in the next element. @@ -93,6 +95,7 @@ struct array_owner { ~array_owner(); }; +namespace { /// Retires a traversal-order ownership-carrier prefix into enclosing retirement operations. /// /// \pre Exactly the first count ownership carriers in data are valid and exclusively @@ -168,6 +171,7 @@ void drain_arrays(array_owner*& pending, retirement_queue& queue) noexcept { } } +} // namespace array_owner::~array_owner() { retirement_queue queue; array_owner* pending = nullptr; @@ -175,6 +179,7 @@ array_owner::~array_owner() { drain_arrays(pending, queue); } +namespace { /// Validates cloning support for callable carriers outside arrays. /// /// Throws std::invalid_argument if a direct callable lacks installed clone operations. @@ -237,6 +242,7 @@ void clone_resources(const value_type& type, } } +} // namespace void clone_payload(const value_type& type, const std::byte* source, std::byte* destination) { require_clone_operations(type); const auto extent = type.byte_layout().size; @@ -285,6 +291,7 @@ void destroy_payload(const value_type& type, std::byte* data, retirement_queue& drain_arrays(pending, queue); } +namespace { /// Borrows a source-order fixed-aggregate child. /// /// \pre type is a tuple, record, or range and index is in bounds. @@ -306,6 +313,7 @@ void destroy_prefix(const value_type& type, std::byte* data, std::size_t count) } } +} // namespace /// Exclusive ownership of a partially initialized canonical value. struct owned_payload { // [knowledge] initialized counts complete aggregate fields, or one complete @@ -335,6 +343,7 @@ struct owned_payload { } }; +namespace { /// Returns the field count for fixed aggregates, or one for other canonical owners. std::size_t outer_count(const value_type& type) { return type.kind() == type_kind::tuple || type.kind() == type_kind::record || @@ -343,6 +352,7 @@ std::size_t outer_count(const value_type& type) { 1; } +} // namespace const std::byte* value_access::data(const value& owner) noexcept { return owner._payload ? owner._payload->bytes.data() : nullptr; } @@ -425,6 +435,7 @@ void value_access::project(const value_type& type, } } +namespace { /// Returns the source-order index of a named record field. /// /// Throws std::invalid_argument for a non-record or missing name. @@ -436,6 +447,7 @@ std::size_t field_index(const value_type& type, std::string_view name) { return static_cast(found - names.begin()); } +} // namespace } // namespace cel::detail namespace cel { @@ -620,3 +632,427 @@ void value::set_field(std::string_view name, const value& replacement) { } } // namespace cel + +#include +#if CPP_LIBRARY_TESTING() +#include "canonical.hpp" +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(__has_feature) +#if __has_feature(address_sanitizer) +#include +#endif +#elif defined(__SANITIZE_ADDRESS__) +#include +#endif + +namespace { +/// Requests a test callback failure after acquiring a temporary resource. +bool fail_test_clone = false; +/// Counts live resources created by the synthetic opaque clone callback. +int live_test_owners = 0; +/// Requests a failure after a known initialized ownership prefix. +int test_clones_until_failure = -1; +/// Identifies a synthetic clone failure without allocating a diagnostic. +struct test_clone_error : std::exception { + /// Returns a fixed diagnostic without allocating. + const char* what() const noexcept override { return "synthetic clone failure"; } +}; + +/// Clones a synthetic opaque owner without implementing a callable object. +void clone_test_owner(const std::byte* source, std::byte* destination) { + int* pointer = nullptr; + std::memcpy(static_cast(&pointer), source, sizeof(pointer)); + auto copy = std::make_unique(*pointer); + if (fail_test_clone) throw std::runtime_error("synthetic clone failure"); + if (test_clones_until_failure == 0) { + throw test_clone_error{}; + } + if (test_clones_until_failure > 0) --test_clones_until_failure; + ++live_test_owners; + pointer = copy.release(); + std::memcpy(destination, static_cast(&pointer), sizeof(pointer)); +} + +/// Destroys a synthetic opaque owner without allocating. +void destroy_test_owner(std::byte* data) noexcept { + int* pointer = nullptr; + std::memcpy(static_cast(&pointer), data, sizeof(pointer)); + delete pointer; + --live_test_owners; +} + +/// Supplies a distinct installed operation pair to test representation admission. +void destroy_test_owner_alternative(std::byte* data) noexcept { destroy_test_owner(data); } + +/// Catches repeating complete comparisons for every empty element with shared metadata. +TEST_CASE("checked arrays reuse equivalent descriptor comparisons across elements") { + constexpr std::size_t depth = 128; + constexpr std::size_t count = 128; + auto expected = cel::value_type::leaf(); + auto actual = cel::value_type::leaf(); + for (std::size_t i = 0; i != depth; ++i) { + expected = cel::value_type::array(expected); + actual = cel::value_type::array(actual); + } + const auto empty = cel::value::array(actual.element(), {}); + const std::vector children(count, empty); + cel::value result; + result = cel::value::array(expected, children); + CHECK(result.size() == count); + CHECK(result.at(count - 1).size() == 0); + + auto consumed = children; + result = cel::detail::value_access::take_array(expected, consumed); + for (const auto& child : consumed) + CHECK(child.type().same_shape(cel::value{}.type())); + + cel::detail::compatibility_context comparisons; + std::size_t work = 0; + for (const auto& child : children) + work += comparisons.require(expected, child.type()); + CHECK(work > 0); + CHECK(work <= 2 * (depth + 1)); + + for (std::size_t i = 0; i != count; ++i) { + const auto distinct = cel::value::array(actual.element(), {}); + work += comparisons.require(expected, distinct.type()); + } + CHECK(work <= 2 * (depth + count + 1)); +} + +/// Catches memo entries authorizing unequal shapes or foreign operations after a failed check. +TEST_CASE("operation comparison caches keep shape and ownership checks independent") { + const auto signature = cel::value_type::callable({}, cel::value_type::leaf()); + const auto expected = cel::detail::type_access::install_callable_ownership( + signature, {clone_test_owner, destroy_test_owner}); + cel::detail::compatibility_context comparisons; + for (int i = 0; i != 128; ++i) { + const auto actual = cel::detail::type_access::install_callable_ownership( + signature, + {clone_test_owner, i % 2 == 0 ? destroy_test_owner : destroy_test_owner_alternative}); + if (i % 2 == 0) { + CHECK_NOTHROW(comparisons.require(expected, actual)); + } else { + CHECK_THROWS_AS(comparisons.require(expected, actual), std::invalid_argument); + CHECK_THROWS_AS(comparisons.require(expected, actual), std::invalid_argument); + } + } + const auto one = cel::value_type::tuple(std::array{expected}); + const auto two = cel::value_type::tuple(std::array{expected, expected}); + CHECK_THROWS_AS(comparisons.require(one, two), std::invalid_argument); + CHECK_THROWS_AS(comparisons.require(one, two), std::invalid_argument); + CHECK_NOTHROW(comparisons.require(one, cel::value_type::tuple(std::array{expected}))); + + const auto foreign = cel::detail::type_access::install_callable_ownership( + signature, {clone_test_owner, destroy_test_owner_alternative}); + const auto valid_empty = cel::value::array(expected, {}); + const auto foreign_empty = cel::value::array(foreign, {}); + CHECK_THROWS_AS(cel::value::array(valid_empty.type(), std::array{valid_empty, foreign_empty}), + std::invalid_argument); + auto destination = cel::value::array(valid_empty.type(), std::array{valid_empty}); + CHECK_THROWS_AS(destination.set(0, foreign_empty), std::invalid_argument); + CHECK(destination.at(0).type().compatible_with(valid_empty.type())); +} + +/// Catches leaking a partially cloned traversal-order prefix. +TEST_CASE("partial ownership traversal cleans its initialized prefix") { + const auto installed = cel::detail::type_access::install_callable_ownership( + cel::value_type::callable({}, cel::value_type::leaf()), + {clone_test_owner, destroy_test_owner}); + int number = 42; + int* pointer = &number; + std::array bytes; + std::memcpy(bytes.data(), static_cast(&pointer), sizeof(pointer)); + const auto callable = cel::detail::value_access::copy(installed, bytes.data()); + const auto array = cel::value::from(std::vector{2.0, 3.0}); + const auto source = + cel::value::tuple(std::array{callable, array, callable, array, callable, array}); + const auto live = live_test_owners; + test_clones_until_failure = 2; + bool caught = false; + try { + auto copy = source; + } catch (const test_clone_error&) { + caught = true; + } + test_clones_until_failure = -1; + CHECK(caught); + CHECK(live_test_owners == live); + CHECK(source.at(1).at(0).as() == 2.0); +} +/// Catches conflating semantic signatures with stored opaque representation compatibility. +TEST_CASE("public compatibility rejects nested foreign callable ownership operations") { + const auto signature = cel::value_type::callable({}, cel::value_type::leaf()); + const auto installed = cel::detail::type_access::install_callable_ownership( + signature, {clone_test_owner, destroy_test_owner}); + const auto foreign = cel::detail::type_access::install_callable_ownership( + signature, {clone_test_owner, destroy_test_owner_alternative}); + CHECK(signature.compatible_with(signature)); + CHECK_FALSE(signature.owns_values()); + CHECK(installed.compatible_with(installed)); + CHECK(installed.same_shape(foreign)); + CHECK_FALSE(installed.compatible_with(foreign)); + CHECK_FALSE(foreign.compatible_with(installed)); + const auto nested = cel::value_type::array(cel::value_type::record( + "callbacks", + std::array{cel::record_field{"stored", cel::value_type::tuple(std::array{installed})}})); + const auto nested_foreign = cel::value_type::array(cel::value_type::record( + "callbacks", + std::array{cel::record_field{"stored", cel::value_type::tuple(std::array{foreign})}})); + CHECK(nested.same_shape(nested_foreign)); + CHECK_FALSE(nested.compatible_with(nested_foreign)); + CHECK_FALSE(nested_foreign.compatible_with(nested)); + CHECK(live_test_owners == 0); +} + +/// Catches accepting incomplete opaque operations or mutating shared capability metadata. +TEST_CASE("private callable ownership installation preserves shape and validates operation pairs") { + const auto signature = cel::value_type::callable({}, cel::value_type::leaf()); + CHECK_THROWS_AS(cel::detail::require_ownership(signature), std::invalid_argument); + cel::detail::storage destination_bytes; + destination_bytes.reserve(signature.byte_layout().size, signature.byte_layout().alignment); + destination_bytes.resize(signature.byte_layout().size); + CHECK_THROWS_AS(cel::detail::clone_payload(signature, nullptr, destination_bytes.data()), + std::invalid_argument); + CHECK_THROWS_AS(cel::detail::type_access::install_callable_ownership( + signature, {clone_test_owner, nullptr}), + std::invalid_argument); + CHECK_THROWS_AS(cel::detail::type_access::install_callable_ownership( + cel::value_type::leaf(), {clone_test_owner, destroy_test_owner}), + std::invalid_argument); + const auto installed = cel::detail::type_access::install_callable_ownership( + signature, {clone_test_owner, destroy_test_owner}); + CHECK_FALSE(signature.owns_values()); + CHECK(installed.owns_values()); + CHECK(signature.same_shape(installed)); + CHECK_NOTHROW(cel::detail::require_ownership(installed)); + CHECK_THROWS_AS(cel::detail::require_ownership(cel::value_type::array(signature)), + std::invalid_argument); + CHECK(live_test_owners == 0); + { + auto original = std::make_unique(42); + int* pointer = original.get(); + std::array carrier{}; + std::memcpy(carrier.data(), static_cast(&pointer), sizeof(pointer)); + auto owner = cel::detail::value_access::copy(installed, carrier.data()); + *original = 99; + auto copy = owner; + int* owned = nullptr; + int* copied = nullptr; + std::memcpy(static_cast(&owned), cel::detail::value_access::data(owner), + sizeof(owned)); + std::memcpy(static_cast(&copied), cel::detail::value_access::data(copy), + sizeof(copied)); + CHECK(*owned == 42); + CHECK(*copied == 42); + *owned = 17; + CHECK(*copied == 42); + *copied = 18; + CHECK(*owned == 17); + const auto deferred_record = + cel::value_type::record("code", std::array{cel::record_field{"body", signature}}); + CHECK_THROWS_AS(cel::value::record(deferred_record, std::array{owner}), + std::invalid_argument); + const auto owned_record = + cel::value_type::record("code", std::array{cel::record_field{"body", installed}}); + CHECK( + cel::value::record(owned_record, std::array{owner}).type().same_shape(deferred_record)); + const auto alternative = cel::detail::type_access::install_callable_ownership( + signature, {clone_test_owner, destroy_test_owner_alternative}); + CHECK(alternative.same_shape(installed)); + CHECK_THROWS_AS( + cel::value::record( + cel::value_type::record("code", std::array{cel::record_field{"body", alternative}}), + std::array{owner}), + std::invalid_argument); + auto children = std::array{cel::value::from(std::vector{1.0, 2.0}), owner}; + const auto failing_record = cel::value_type::record( + "partial", std::array{cel::record_field{"items", children[0].type()}, + cel::record_field{"code", installed}}); + const auto good_record = cel::value::record(failing_record, children); + const auto packed_records = + cel::value::array(failing_record, std::array{good_record, good_record}); + auto replacement_record = good_record; + auto replacement_array = cel::value::array(installed, std::array{owner}); + const auto live_before = live_test_owners; + auto destination = cel::value::from(false); + fail_test_clone = true; + CHECK_THROWS_AS(cel::value::record(failing_record, children), std::runtime_error); + CHECK_THROWS_AS(cel::value{good_record}, std::runtime_error); + CHECK_THROWS_AS(cel::value{packed_records}, std::runtime_error); + CHECK_THROWS_AS(destination = good_record, std::runtime_error); + CHECK_THROWS_AS(replacement_record.set_field("code", owner), std::runtime_error); + CHECK_THROWS_AS(replacement_array.set(0, owner), std::runtime_error); + fail_test_clone = false; + CHECK(live_test_owners == live_before); + CHECK_FALSE(destination.as()); + int* preserved = nullptr; + auto preserved_field = replacement_record.field("code"); + std::memcpy(static_cast(&preserved), + cel::detail::value_access::data(preserved_field), sizeof(preserved)); + CHECK(*preserved == 17); + preserved_field = replacement_array.at(0); + std::memcpy(static_cast(&preserved), + cel::detail::value_access::data(preserved_field), sizeof(preserved)); + CHECK(*preserved == 17); + } + CHECK(live_test_owners == 0); +} +/// Owns a raw clone solely to verify private raw ownership contracts. +struct raw_owner { + cel::value_type type; ///< Retains immutable destruction metadata. + cel::detail::storage bytes; ///< Owns aligned outer storage. + bool initialized = false; ///< Tracks whether payload destruction is required. + /// Clones a canonical payload with clone_payload's source requirements. + /// + /// Complexity: linear in source value area, plus held clone costs; new owned storage. + raw_owner(const cel::value_type& shape, const std::byte* source) : type(shape) { + const auto layout = type.byte_layout(); + bytes.reserve(layout.size, layout.alignment); + bytes.resize(layout.size); + cel::detail::clone_payload(type, source, bytes.data()); + initialized = true; + } + /// Copies a public value into raw canonical storage. + /// Complexity: O(payload size) time and space. + explicit raw_owner(const cel::value& source) : + raw_owner(source.type(), cel::detail::value_access::data(source)) {} + /// Destroys exactly one raw payload without allocating. + /// Complexity: O(payload size) time and O(shape depth) call space. + ~raw_owner() { + if (initialized) cel::detail::destroy_payload(type, bytes.data()); + } +}; + +/// Catches reading a fixed aggregate before checking its deferred callable carriers. +TEST_CASE("deferred callable cloning rejects fixed aggregates before reading source") { + const auto deferred = cel::value_type::callable({}, cel::value_type::leaf()); + const auto tuple = cel::value_type::tuple(std::array{cel::value_type::leaf(), deferred}); + const auto record = + cel::value_type::record("callbacks", std::array{cel::record_field{"nested", tuple}}); + CHECK_THROWS_AS(raw_owner(tuple, nullptr), std::invalid_argument); + CHECK_THROWS_AS(raw_owner(record, nullptr), std::invalid_argument); +} + +/// Catches copying packed element bytes before rejecting their deferred callable descriptor. +TEST_CASE("deferred callable cloning rejects array elements before reading their bytes") { + const auto deferred = cel::value_type::callable({}, cel::value_type::leaf()); + const auto installed = cel::detail::type_access::install_callable_ownership( + deferred, {clone_test_owner, destroy_test_owner}); + int number = 42; + int* pointer = &number; + std::array carrier; + std::memcpy(carrier.data(), static_cast(&pointer), sizeof(pointer)); + cel::detail::canonical_owner source(cel::value_type::array(installed)); + cel::detail::array_builder builder(installed, 1); + auto* element = builder.destination(); + cel::detail::clone_payload(installed, carrier.data(), element); + builder.initialized(); + builder.release_to(source.bytes.data()); + source.live = true; + const auto live = live_test_owners; + +#ifdef ASAN_POISON_MEMORY_REGION + ASAN_POISON_MEMORY_REGION(element, installed.byte_layout().size); + // Restore readability before source destruction, including on an unexpected exception. + const auto unpoison = [size = installed.byte_layout().size](std::byte* data) noexcept { + ASAN_UNPOISON_MEMORY_REGION(data, size); + }; + const std::unique_ptr readable_on_exit(element, unpoison); +#endif + + CHECK_THROWS_AS(raw_owner(cel::value_type::array(deferred), source.bytes.data()), + std::invalid_argument); + CHECK(live_test_owners == live); +} + +/// Catches replacing a requested deferred descriptor with installed source-owner metadata. +TEST_CASE("deferred callable cloning rejects fixed aggregates inside nested arrays") { + const auto deferred = cel::value_type::callable({}, cel::value_type::leaf()); + const auto installed = cel::detail::type_access::install_callable_ownership( + deferred, {clone_test_owner, destroy_test_owner}); + int number = 42; + int* pointer = &number; + std::array carrier; + std::memcpy(carrier.data(), static_cast(&pointer), sizeof(pointer)); + const auto callable = cel::detail::value_access::copy(installed, carrier.data()); + auto source = cel::value::tuple(std::array{cel::value::from(true), callable}); + auto requested = cel::value_type::tuple(std::array{cel::value_type::leaf(), deferred}); + for (int depth = 0; depth != 3; ++depth) { + source = cel::value::array(source.type(), std::array{source}); + requested = cel::value_type::array(requested); + const auto live = live_test_owners; + CHECK_THROWS_AS(raw_owner(requested, cel::detail::value_access::data(source)), + std::invalid_argument); + CHECK(live_test_owners == live); + } +} + +/// Catches retaining an earlier sibling clone after a nested deferred-callable rejection. +TEST_CASE("deferred callable cloning releases the initialized sibling prefix") { + const auto deferred = cel::value_type::callable({}, cel::value_type::leaf()); + const auto installed = cel::detail::type_access::install_callable_ownership( + deferred, {clone_test_owner, destroy_test_owner}); + int number = 42; + int* pointer = &number; + std::array carrier; + std::memcpy(carrier.data(), static_cast(&pointer), sizeof(pointer)); + const auto callable = cel::detail::value_access::copy(installed, carrier.data()); + const auto array = cel::value::array(installed, std::array{callable}); + const auto source = cel::value::tuple(std::array{callable, array}); + const auto requested = + cel::value_type::tuple(std::array{installed, cel::value_type::array(deferred)}); + const auto live = live_test_owners; + CHECK_THROWS_AS(raw_owner(requested, cel::detail::value_access::data(source)), + std::invalid_argument); + CHECK(live_test_owners == live); + CHECK(source.at(1).size() == 1); +} + +/// Catches rejecting uninhabited deferred element types, including beneath a nonempty array. +TEST_CASE("deferred callable cloning preserves empty and nested empty arrays") { + const auto deferred = cel::value_type::callable({}, cel::value_type::leaf()); + const auto empty = cel::value::array(deferred, {}); + raw_owner empty_copy(empty); + CHECK(cel::detail::value_access::array_size(empty_copy.bytes.data()) == 0); + const auto nested = cel::value::array(empty.type(), std::array{empty}); + raw_owner nested_copy(nested); + const auto result = cel::detail::value_access::copy(nested_copy.type, nested_copy.bytes.data()); + CHECK(result.size() == 1); + CHECK(result.at(0).size() == 0); + CHECK(result.type().element().element().kind() == cel::type_kind::callable); +} + +/// Catches raw clones sharing mutable arrays and duplicate destruction after byte transfer. +TEST_CASE("private canonical clone destruction and transfer preserve exactly one owner") { + auto source = cel::value::from(std::tuple{std::vector{1.0, 2.0}, true}); + raw_owner raw(source); + auto copied = cel::detail::value_access::copy(raw.type, raw.bytes.data()); + auto child = source.at(0); + child.set(0, cel::value::from(8.0)); + source.set(0, child); + CHECK(copied.at(0).at(0).as() == 1.0); + CHECK(cel::detail::value_access::copy(raw.type, raw.bytes.data()).at(0).at(0).as() == + 1.0); + cel::detail::storage transferred; + const auto extent = raw.type.byte_layout(); + transferred.reserve(extent.size, extent.alignment); + transferred.resize(extent.size); + std::memcpy(transferred.data(), raw.bytes.data(), extent.size); + raw.initialized = false; + CHECK(cel::detail::value_access::copy(raw.type, transferred.data()).at(1).as()); + cel::detail::destroy_payload(raw.type, transferred.data()); + raw_owner empty(cel::value{}); + CHECK(cel::detail::value_access::copy(empty.type, empty.bytes.data()).size() == 0); +} +} // namespace + +#endif diff --git a/src/value_type.cpp b/src/value_type.cpp index bf93dfe..cda872c 100644 --- a/src/value_type.cpp +++ b/src/value_type.cpp @@ -80,6 +80,7 @@ void type_access::retire(value_type& type, retirement_queue& queue) noexcept { type._plan.retire(queue); } +namespace { /// Compiles reusable carrier ranges from complete canonical fields. /// /// \pre plan is unpublished and its fields and offsets agree. @@ -108,6 +109,7 @@ void compile_ownership(type_plan& plan) { if (!plan.ownership.empty()) std::swap(plan.ownership[largest], plan.ownership.back()); } +} // namespace std::size_t plan_pair_hash::operator()( const std::pair& pair) const noexcept { const auto a = std::hash{}(pair.first); @@ -313,6 +315,7 @@ std::size_t compatibility_context::require(const value_type& expected, const val return _compared - before; } +namespace { /// Extends a plan's canonical layout and complete aggregate capabilities with source-order fields. /// /// \pre plan has a valid canonical prefix. @@ -343,6 +346,7 @@ void canonical_layout(type_plan& plan, std::span fields) { /// Returns whether the type satisfies built-in/composite callable parameter admission. bool parameter_allowed(const value_type& type) { return type_access::parameter_allowed(type); } +} // namespace } // namespace cel::detail namespace cel { @@ -500,3 +504,233 @@ const value_type& value_type::result() const { } } // namespace cel + +#include +#if CPP_LIBRARY_TESTING() +#include "value_ops.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +/// Runs two nonthrowing callbacks on separate threads behind one start gate and joins them. +/// +/// Thread-start failures propagate after releasing any already started worker. +/// Complexity: callback work plus thread startup and joining; O(1) auxiliary space. +template +void run_concurrently(First first, Second second) { + std::latch start{1}; + std::array threads; + const auto release = [](std::latch* gate) noexcept { gate->count_down(); }; + const std::unique_ptr release_on_exit(&start, release); + threads[0] = std::jthread([&] { + start.wait(); + first(); + }); + threads[1] = std::jthread([&] { + start.wait(); + second(); + }); +} + +/// Records actual node disposal and reentrant callbacks across independent retirement queues. +struct retirement_counts { + std::atomic disposed{0}; ///< Counts destroyed nodes. + std::atomic nested{false}; ///< Records nesting within one thread. +}; + +/// An owned chain node for checking the retirement primitive used by type metadata. +struct retirement_probe : cel::detail::retirement_node { + retirement_counts& counts; ///< Borrows counters until every worker has joined. + cel::detail::retirement_ptr child; ///< Retains the next chain node. + static inline thread_local std::size_t depth = 0; ///< Counts active callbacks on this thread. + + /// Adopts one child edge and retains the disposal counters. + retirement_probe(retirement_counts& state, cel::detail::retirement_ptr next) : + retirement_node(dispose_node), counts(state), child(std::move(next)) {} + + /// Records disposal, detaches the child into queue, and deletes this node. + /// + /// \pre base is an exclusively retiring retirement_probe. + static void dispose_node(cel::detail::retirement_node& base, + cel::detail::retirement_queue& queue) noexcept { + auto& node = static_cast(base); + ++depth; + if (depth != 1) node.counts.nested.store(true, std::memory_order_relaxed); + node.child.retire(queue); + node.counts.disposed.fetch_add(1, std::memory_order_relaxed); + delete &node; + --depth; + } +}; + +/// Catches premature disposal or wrong last-owner selection during concurrent edge releases. +TEST_CASE("concurrent last owners retire each node once without nested callbacks") { + constexpr std::size_t count = 12000; + retirement_counts counts; + cel::detail::retirement_ptr root; + CHECK(root.get() == nullptr); + std::vector> aliases; + // Retain interior aliases so independent queues also compete below the root. + for (std::size_t i = 0; i != count; ++i) { + auto next = std::make_unique(counts, std::move(root)); + root = cel::detail::retirement_ptr(next.release()); + if (i % 2 == 0) aliases.push_back(root); + } + { + auto copy = root; + CHECK(copy == root); + CHECK(copy.get() == root.get()); + auto moved = std::move(copy); + // NOLINTNEXTLINE(bugprone-use-after-move): moves promise an empty source handle. + CHECK_FALSE(copy); + CHECK(moved == root); + } + CHECK(counts.disposed.load() == 0); + run_concurrently([owner = std::move(root)]() mutable { owner = {}; }, + [owners = std::move(aliases)]() mutable { + while (!owners.empty()) + owners.pop_back(); + }); + CHECK(counts.disposed.load() == count); + CHECK_FALSE(counts.nested.load()); +} + +/// Catches disposing metadata before its last-owner queue drains. +TEST_CASE("queued metadata retains borrowed views until disposal") { + const auto boolean = cel::value_type::leaf(); + auto type = cel::value_type::record( + "queued", std::array{cel::record_field{"items", cel::value_type::array(boolean)}, + cel::record_field{"code", cel::value_type::callable( + std::array{boolean}, + cel::value_type::leaf())}}); + const auto fields = type.fields(); + const auto names = type.field_names(); + const auto identity = type.record_identity(); + const auto& element = fields[0].element(); + const auto parameters = fields[1].parameters(); + const auto& result = fields[1].result(); + cel::detail::retirement_queue queue; + cel::detail::type_access::retire(type, queue); + CHECK(identity == "queued"); + CHECK(names[0] == "items"); + CHECK(names[1] == "code"); + CHECK(element.same_shape(boolean)); + CHECK(parameters[0].same_shape(boolean)); + CHECK(result.same_shape(cel::value_type::leaf())); +} +/// Checks every carrier offset and a linear bound on constant-time traversal steps. +/// Complexity: O(count log count) time and O(count) temporary space. +void check_ownership_traversal(const cel::value_type& type, std::size_t count) { + cel::detail::ownership_cursor cursor(type); + std::vector offsets; + std::size_t steps = 0; + while (!cursor.empty()) { + if (const auto slot = cursor.next()) { + CHECK((slot->type->kind() == cel::type_kind::array)); + offsets.push_back(slot->offset); + } + ++steps; + } + REQUIRE((offsets.size() == count)); + CHECK((steps <= 3 * count)); + std::sort(offsets.begin(), offsets.end()); + for (std::size_t i = 0; i != count; ++i) + CHECK((offsets[i] == i * sizeof(void*))); +} + +/// Catches repeated root searches and expanded metadata at every skewed descriptor. +TEST_CASE("ownership ranges traverse wide and skewed aggregates in linear work") { + constexpr std::size_t count = 2048; + const auto element = cel::value::from(std::vector{3.0}); + const cel::value_type unit; + const std::vector fields(count, element); + const auto flat = cel::value::tuple(fields); + check_ownership_traversal(flat.type(), count); + + for (const bool heavy_first : {false, true}) { + auto type = element.type(); + std::size_t ranges = 0; + std::size_t range_bytes = 0; + for (std::size_t i = 1; i != count; ++i) { + const auto children = + heavy_first ? std::array{type, element.type()} : std::array{element.type(), type}; + type = cel::value_type::tuple(children); + const auto compiled = cel::detail::type_access::ownership_ranges(type); + ranges += compiled.size(); + range_bytes += compiled.size_bytes(); + } + CHECK(ranges <= 2 * count); + CHECK(range_bytes <= 2 * count * sizeof(cel::detail::ownership_slot)); + check_ownership_traversal(type, count); + auto original = + cel::detail::value_access::copy(type, cel::detail::value_access::data(flat)); + auto copy = original; + original = cel::value{}; + auto restored = + cel::detail::value_access::copy(flat.type(), cel::detail::value_access::data(copy)); + CHECK(restored.at(0).at(0).as() == 3.0); + CHECK(restored.at(count - 1).at(0).as() == 3.0); + copy = cel::value{}; + restored = cel::value{}; + type = unit; + } +} +/// Catches expansion of shared ranges and traversal proportional to unary nesting. +TEST_CASE("ownership ranges reuse shared descendants and collapse unary paths") { + auto type = cel::value_type::array(cel::value_type::leaf()); + std::size_t ranges = 0; + for (std::size_t i = 0; i != 12; ++i) { + type = cel::value_type::tuple(std::array{type, type}); + ranges += cel::detail::type_access::ownership_ranges(type).size(); + } + CHECK(ranges <= 24); + check_ownership_traversal(type, 4096); + for (std::size_t i = 0; i != 50000; ++i) + type = cel::value_type::tuple(std::array{type}); + check_ownership_traversal(type, 4096); +} +/// Catches recursive cloning and destruction of owned array trees. +TEST_CASE("deep owned array trees clone release and unwind without recursive cleanup") { + auto source = cel::value::from(true); + for (std::size_t i = 0; i != 50000; ++i) + source = cel::detail::value_access::take_array(source.type(), std::span(&source, 1)); + auto copy = source; + CHECK(copy.type().same_shape(source.type())); + CHECK(copy.size() == 1); + copy = cel::value{}; + source = cel::value{}; + CHECK_THROWS_AS( + [] { + auto tree = cel::value::from(false); + for (std::size_t i = 0; i != 50000; ++i) + tree = cel::detail::value_access::take_array(tree.type(), std::span(&tree, 1)); + throw std::runtime_error("unwind packed ownership"); + }(), + std::runtime_error); +} + +/// Catches recursion through deeply nested inline fields even when only one carrier exists. +TEST_CASE("deep inline aggregate ownership paths are stack independent") { + const auto leaf_array = cel::value::from(std::vector{2.0, 3.0}); + auto type = leaf_array.type(); + for (std::size_t i = 0; i != 50000; ++i) + type = cel::value_type::tuple(std::array{type}); + auto owner = cel::detail::value_access::copy(type, cel::detail::value_access::data(leaf_array)); + auto copy = owner; + CHECK(copy.type().same_shape(type)); + owner = cel::value{}; + copy = cel::value{}; +} +} // namespace + +#endif diff --git a/tests/callable_test.cpp b/tests/callable_test.cpp index e634246..892f417 100644 --- a/tests/callable_test.cpp +++ b/tests/callable_test.cpp @@ -1,12 +1,8 @@ // SPDX-License-Identifier: BSL-1.0 -#include "instruction.hpp" -#include "type_ops.hpp" -#include "value_ops.hpp" +#include #include #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN -#include #include - /// Supplies a valid client-defined closure result, not a parameter. struct client_result { int number; ///< Retains client data. @@ -15,35 +11,6 @@ struct client_result { struct alignas(256) wide_result { bool flag; ///< Retains the intermediate result. }; -/// Counts foreign ownership operations to detect access before ABI rejection. -int foreign_clones = 0; -/// Counts foreign canonical retirement. -int foreign_destroys = 0; -/// Copies a foreign opaque carrier without treating its bytes as installed callable code. -void clone_foreign(const std::byte* source, std::byte* destination) { - std::memcpy(destination, source, sizeof(void*)); - ++foreign_clones; -} -/// Retires the resource-free foreign representation without dereferencing it. -void destroy_foreign(std::byte*) noexcept { ++foreign_destroys; } -TEST_CASE("runtime ownership binding preserves deferred signatures and canonical witnesses") { - const auto number = cel::value_type::leaf(); - const auto declared = cel::value_type::callable(std::array{number}, number); - const auto bound = cel::bind_runtime_ownership(declared); - cel::dyn_segment body; - body.push_argument(0, number); - cel::callable actual(std::move(body).finish(), std::array{number}); - CHECK_FALSE(declared.owns_values()); - CHECK(bound.owns_values()); - CHECK(bound.same_shape(declared)); - CHECK(bound.compatible_with(actual.type())); - CHECK_FALSE(declared.compatible_with(actual.type())); - CHECK(cel::bind_runtime_ownership(bound).compatible_with(bound)); - CHECK(cel::detail::type_access::same_plan(cel::bind_runtime_ownership(bound), bound)); - CHECK(cel::detail::type_access::same_plan(cel::bind_runtime_ownership(actual.type()), - actual.type())); - CHECK_THROWS_AS(cel::value_type::callable(std::array{bound}, number), std::invalid_argument); -} TEST_CASE("bound empty callable arrays retain ownership beyond compiler metadata lifetimes") { const auto declared = cel::value_type::callable({}, cel::value_type::leaf()); cel::dyn_segment rejected; @@ -69,34 +36,6 @@ TEST_CASE("bound empty callable arrays retain ownership beyond compiler metadata cel::callable factory(std::move(closure_body).finish(), {}); CHECK(factory.call(stack, {}).size() == 0); } -TEST_CASE("binding preserves nested nominal layout client identities and range forms") { - const auto declared = cel::value_type::callable({}, cel::value_type::leaf()); - const auto client = cel::value_type::leaf(); - const auto range = - cel::value_type::range(cel::range_kind::range_inclusive, cel::value_type::leaf()); - const auto tuple = cel::value_type::tuple(std::array{client, declared, range}); - const auto record = cel::value_type::record( - "named", std::array{cel::record_field{"nested", cel::value_type::array(tuple)}, - cel::record_field{"wide", client}}); - const auto bound = cel::bind_runtime_ownership(record); - CHECK_FALSE(record.owns_values()); - CHECK(bound.owns_values()); - CHECK(bound.same_shape(record)); - CHECK(bound.record_identity() == "named"); - CHECK(bound.field_names()[0] == "nested"); - CHECK(bound.field_names()[1] == "wide"); - CHECK(bound.offsets()[0] == record.offsets()[0]); - CHECK(bound.offsets()[1] == record.offsets()[1]); - CHECK(bound.byte_layout().alignment == 256); - CHECK(bound.fields()[1].leaf_identity() == typeid(wide_result)); - CHECK(cel::detail::type_access::same_plan(bound.fields()[1], client)); - CHECK(bound.fields()[0].element().fields()[2].form() == cel::range_kind::range_inclusive); - CHECK_THROWS_AS(cel::value_type::callable(std::array{bound}, client), std::invalid_argument); - cel::dyn_segment builder; - builder.make_array(0, bound, {}); - cel::raw_stack stack; - CHECK(std::move(builder).finish().execute(stack, {}).size() == 0); -} TEST_CASE("binding covers higher order result witnesses and populated callable arrays") { const auto number = cel::value_type::leaf(); const auto inner_type = cel::value_type::callable({}, number); @@ -130,56 +69,6 @@ TEST_CASE("binding covers higher order result witnesses and populated callable a empty.make_array(0, bound, {}); CHECK(std::move(empty).finish().execute(stack, {}).size() == 0); } -TEST_CASE("binding rejects foreign operations throughout metadata without invoking owners") { - const auto declared = cel::value_type::callable({}, cel::value_type::leaf()); - const auto foreign = cel::detail::type_access::install_callable_ownership( - declared, {clone_foreign, destroy_foreign}); - cel::dyn_segment body; - body.just(cel::value::from(7.0)); - cel::callable actual(std::move(body).finish(), {}); - const auto aggregate = cel::value_type::tuple(std::array{cel::value_type::array(foreign)}); - const auto nested = cel::value_type::callable({}, aggregate); - const auto installed_nested = cel::detail::type_access::install_callable_ownership( - nested, cel::detail::type_access::operations(actual.type())); - const auto mixed = cel::detail::type_access::install_callable_ownership( - declared, {cel::detail::type_access::operations(actual.type()).clone, destroy_foreign}); - foreign_clones = 0; - foreign_destroys = 0; - for (const auto& input : std::array{foreign, aggregate, nested, installed_nested, mixed}) { - CHECK_THROWS_AS(cel::bind_runtime_ownership(input), std::invalid_argument); - } - CHECK(cel::detail::type_access::operations(foreign).clone == clone_foreign); - CHECK(cel::detail::type_access::operations(foreign).destroy == destroy_foreign); - CHECK(foreign_clones == 0); - CHECK(foreign_destroys == 0); -} -TEST_CASE("binding traverses deep metadata and preserves shared DAGs") { - auto deep = cel::value_type::callable({}, cel::value_type::leaf()); - for (int i = 0; i != 12000; ++i) - deep = cel::value_type::callable({}, cel::value_type::array(deep)); - auto bound = cel::bind_runtime_ownership(deep); - CHECK(bound.same_shape(deep)); - for (int i = 0; i != 12000; ++i) { - REQUIRE(bound.owns_values()); - REQUIRE(bound.result().owns_values()); - bound = bound.result().element(); - } - CHECK(bound.owns_values()); - auto shared = cel::value_type::callable({}, cel::value_type::leaf()); - constexpr int depth = 96; - for (int i = 0; i != depth; ++i) { - const auto edge = cel::value_type::array(shared); - shared = cel::value_type::tuple(std::array{edge, edge}); - } - auto result = cel::bind_runtime_ownership(shared); - CHECK(result.same_shape(shared)); - for (int i = 0; i != depth; ++i) { - REQUIRE(result.owns_values()); - CHECK(cel::detail::type_access::same_plan(result.fields()[0], result.fields()[1])); - result = result.fields()[0].element(); - } - CHECK(result.owns_values()); -} TEST_CASE("callable full declarations include unused composite parameters") { int effects = 0; cel::dyn_segment b; @@ -367,79 +256,6 @@ TEST_CASE("distinct callable carriers nest inside a guarded dynamic invocation") CHECK(outer_effects == 1); CHECK(stack.pop>() == std::vector{6.0}); } -TEST_CASE("conversion and dynamic invocation reject foreign same shape ownership before access") { - foreign_clones = 0; - foreign_destroys = 0; - int effects = 0; - cel::dyn_segment body; - body.just(cel::value::from(true)); - cel::callable fn(std::move(body).finish(), {}); - const auto foreign = cel::detail::type_access::install_callable_ownership( - fn.type(), {clone_foreign, destroy_foreign}); - alignas(void*) const std::array null_carrier{}; - auto impostor = cel::detail::value_access::take(foreign, null_carrier.data()); - CHECK(impostor.type().same_shape(fn.type())); - CHECK_THROWS_AS(cel::callable::from_value(impostor), std::invalid_argument); - CHECK(foreign_clones == 0); - CHECK(foreign_destroys == 0); - cel::dyn_segment b; - b.just(std::move(impostor)); - b.op0([&effects] { ++effects; }); - const auto original = b.snapshot(); - CHECK_THROWS_AS(b.invoke_closure(0), std::invalid_argument); - CHECK(b.snapshot() == original); - CHECK(effects == 0); - CHECK(foreign_clones == 0); - cel::raw_stack stack; - auto result = std::move(b).finish().execute(stack, {}); - CHECK(result.type().same_shape(fn.type())); - CHECK(effects == 1); - CHECK(foreign_clones == 1); - CHECK_THROWS_AS(cel::callable::from_value(result), std::invalid_argument); -} -TEST_CASE("higher order results reject foreign ownership before checked execution and binding") { - for (bool nested : {false, true}) { - int effects = 0; - cel::dyn_segment inner_body; - inner_body.just(cel::value::from(7.0)); - const auto canonical_inner = cel::callable(std::move(inner_body).finish(), {}).to_value(); - const auto foreign_inner = cel::detail::type_access::install_callable_ownership( - canonical_inner.type(), {clone_foreign, destroy_foreign}); - alignas(void*) const std::array carrier{}; - auto result = cel::detail::value_access::take(foreign_inner, carrier.data()); - if (nested) { - std::array children{std::move(result)}; - result = cel::value::tuple(children); - } - cel::dyn_segment foreign_body; - foreign_body.just(std::move(result)); - const auto foreign_outer = cel::callable(std::move(foreign_body).finish(), {}).to_value(); - const auto expected_result = - nested ? cel::value_type::tuple(std::array{canonical_inner.type()}) : - canonical_inner.type(); - const auto expected = - cel::bind_runtime_ownership(cel::value_type::callable({}, expected_result)); - CHECK(foreign_outer.type().same_shape(expected)); - CHECK_FALSE(foreign_outer.type().compatible_with(expected)); - cel::dyn_segment reader; - reader.push_argument(0, expected); - reader.op0([&effects] { ++effects; }); - const auto program = std::move(reader).finish(); - cel::raw_stack stack; - stack.push(true); - CHECK_THROWS_AS(program.execute(stack, std::array{foreign_outer}), std::invalid_argument); - CHECK(effects == 0); - CHECK(stack.depth() == 1); - CHECK(stack.pop()); - CHECK_THROWS_AS(cel::detail::segment_access::prepare_raw( - program, std::array{foreign_outer.type()}, expected), - std::invalid_argument); - CHECK_THROWS_AS(cel::detail::segment_access::prepare_raw(program, std::array{expected}, - foreign_outer.type()), - std::invalid_argument); - CHECK(effects == 0); - } -} TEST_CASE("closure construction validates reads parameters and independence") { cel::dyn_segment b; b.push_argument(1, cel::value_type::leaf()); diff --git a/tests/composite_execution_test.cpp b/tests/composite_execution_test.cpp index 3b7987a..de1cff3 100644 --- a/tests/composite_execution_test.cpp +++ b/tests/composite_execution_test.cpp @@ -1,47 +1,9 @@ // SPDX-License-Identifier: BSL-1.0 -#include "type_ops.hpp" -#include "value_ops.hpp" +#include #include +#include #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN -#include #include -#include - -/// Tracks opaque result owners to detect sibling cleanup and accidental projection cloning. -int opaque_owners = 0; -/// Counts canonical opaque clones, independently of outer-storage allocation. -int opaque_clones = 0; -/// Identifies one live opaque owner in canonical bytes. -struct opaque_carrier { - int* owner; ///< Owns one test resource. -}; -/// Clones a test resource into an independent canonical carrier. -void clone_opaque(const std::byte* source, std::byte* destination) { - opaque_carrier input{}; - std::memcpy(&input, source, sizeof(input)); - auto owner = std::make_unique(*input.owner); - const opaque_carrier output{owner.release()}; - std::memcpy(destination, &output, sizeof(output)); - ++opaque_owners; - ++opaque_clones; -} -/// Destroys one live canonical resource. -void destroy_opaque(std::byte* source) noexcept { - opaque_carrier input{}; - std::memcpy(&input, source, sizeof(input)); - delete input.owner; - --opaque_owners; -} -/// Builds a trusted opaque owner with the specified installed complete witness. -cel::value make_opaque(const cel::value_type& type) { - auto owner = std::make_unique(4); - const opaque_carrier input{owner.get()}; - auto result = cel::detail::value_access::take(type, reinterpret_cast(&input)); - [[maybe_unused]] auto* retired_source = owner.release(); - ++opaque_owners; - return result; -} - TEST_CASE("nested packing consumes source order and preserves exact owners") { cel::dyn_segment b; b.just(cel::value::from(std::vector{2.0, 3.0})); @@ -313,30 +275,3 @@ TEST_CASE("nested record array packing and projection preserve caller prefix") { } CHECK(stack.pop>() == std::vector{9.0}); } -TEST_CASE("consuming projection transfers selected owners and retires siblings without cloning") { - const auto signature = cel::detail::type_access::install_callable_ownership( - cel::value_type::callable({}, cel::value_type::leaf()), - {clone_opaque, destroy_opaque}); - { - cel::dyn_segment b; - b.just(make_opaque(signature)); - b.just(make_opaque(signature)); - b.make_array(2, signature, {}); - b.make_tuple(1, {}); - b.project_tuple(0); - b.just(cel::value::from(1.0)); - b.index_array(); - auto program = std::move(b).finish(); - cel::raw_stack stack; - const auto clones = opaque_clones; - { - auto result = program.execute(stack, {}); - CHECK(result.type().same_shape(signature)); - CHECK(opaque_clones - clones == 2); - CHECK(opaque_owners == 3); - } - CHECK(opaque_owners == 2); - CHECK(stack.depth() == 0); - } - CHECK(opaque_owners == 0); -} diff --git a/tests/executable_retirement_test.cpp b/tests/executable_retirement_test.cpp index 50fa6a3..2210a4e 100644 --- a/tests/executable_retirement_test.cpp +++ b/tests/executable_retirement_test.cpp @@ -1,10 +1,8 @@ // SPDX-License-Identifier: BSL-1.0 -#include "instruction.hpp" #include #include #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include - /// Identifies the original nonallocating exception used by retirement unwinding tests. struct unwind_error : std::exception { int tag = 17; ///< Preserves the caller's exception witness. @@ -88,15 +86,3 @@ TEST_CASE("array tuple and executable ownership edges share one retirement opera auto root = create(); CHECK_NOTHROW(root = cel::value{}); } - -TEST_CASE("deep lazy code retained by a prepared binding retires on its last release") { - auto program = lazy_chain(12000); - auto prepared = - cel::detail::segment_access::prepare_raw(program, {}, cel::value_type::leaf()); - cel::dyn_segment empty; - auto replacement = std::move(empty).finish(); - auto replacement_binding = - cel::detail::segment_access::prepare_raw(replacement, {}, cel::value_type{}); - program = std::move(replacement); - CHECK_NOTHROW(prepared = std::move(replacement_binding)); -} diff --git a/tests/raw_execution_test.cpp b/tests/raw_execution_test.cpp index a3737a0..7e0a23a 100644 --- a/tests/raw_execution_test.cpp +++ b/tests/raw_execution_test.cpp @@ -1,394 +1,9 @@ // SPDX-License-Identifier: BSL-1.0 -#include "frame.hpp" -#include "instruction.hpp" -#include "type_ops.hpp" -#include "value_ops.hpp" -#include - +#include #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include - -#include -#include -#include -#include -#include #include #include - -/// Exercises a client leaf requiring a larger alignment than built-ins. -struct alignas(256) aligned_leaf { - double number; ///< Stores the test's observable client payload. -}; - -/// Verifies empty scope lifetime and mixed canonical layout. -TEST_CASE("empty frames and mixed leaves preserve stack order and cursor") { - cel::raw_stack stack; - CHECK(stack.depth() == 0); - CHECK(stack.cursor() == 0); - cel::detail::raw_segment empty; - { - cel::detail::frame scope(stack); - empty.execute(scope); - scope.push(true); - scope.push(4.0); - scope.push(aligned_leaf{9.0}); - CHECK(scope.pop().number == 9.0); - CHECK(scope.pop() == 4.0); - CHECK(scope.pop()); - CHECK(stack.cursor() == 0); - } - - CHECK(stack.depth() == 0); - stack.push(7.0); - { - cel::detail::frame scope(stack); - scope.push(false); - } - CHECK(stack.pop() == 7.0); -} - -/// Verifies source operand order, zero arguments, and extensible arity. -TEST_CASE("stored operations preserve noncommutative operand order at every arity") { - cel::raw_stack stack; - cel::detail::raw_segment segment; - segment.push_op0([](cel::detail::frame&) { return 12.0; }); - segment.push_op0([](cel::detail::frame&) { return 3.0; }); - segment.push_op2( - [](cel::detail::frame&, double a, double b) { return a / b; }); - segment.push_op1([](cel::detail::frame&, double a) { return a + 1.0; }); - segment.push_op0([](cel::detail::frame&) { return 2.0; }); - segment.push_op0([](cel::detail::frame&) { return 1.0; }); - segment.push_op3( - [](cel::detail::frame&, double a, double b, double c) { return a - b - c; }); - cel::detail::frame scope(stack); - segment.execute(scope); - CHECK(scope.pop() == 2.0); - cel::detail::raw_segment arbitrary; - arbitrary.push_op( - [](cel::detail::frame&, double a, double b, double c, double d, double e) { - return a - b - c - d - e; - }); - for (auto n : {20.0, 1.0, 2.0, 3.0, 4.0}) - scope.push(n); - arbitrary.execute(scope); - CHECK(scope.pop() == 10.0); - cel::detail::raw_segment unit; - unit.push_op0([](cel::detail::frame&) {}); - unit.execute(scope); - CHECK(scope.depth() == 0); -} - -/// Owns a nontrivial capture whose address must remain stable after construction. -struct alignas(256) owning_capture { - std::unique_ptr owner; ///< Owns a callback resource. - int* released; ///< Borrows the release counter until segment destruction. - mutable const owning_capture* address = nullptr; ///< Records first execution address. - /// Acquires one exclusive resource. - explicit owning_capture(int& count) : owner(std::make_unique(8)), released(&count) {} - /// Transfers construction ownership normally. - owning_capture(owning_capture&&) noexcept = default; - /// Counts only destruction of the final resource owner. - ~owning_capture() { - if (owner) ++*released; - } - /// Returns the captured number, rejecting relocation after the first call. - double operator()(cel::detail::frame&) const { - if (address && address != this) throw std::runtime_error("relocated capture"); - if (reinterpret_cast(this) % alignof(owning_capture) != 0) - throw std::runtime_error("misaligned capture"); - address = this; - return *owner; - } -}; - -/// Supplies a copyable, nonmovable over-aligned callback with independent state. -struct alignas(256) copy_only_capture { - double number; ///< Owns the callback's result. - /// Initializes the result. - explicit copy_only_capture(double input) : number(input) {} - /// Copies the result independently. - copy_only_capture(const copy_only_capture&) = default; - /// Disallows move construction. - copy_only_capture(copy_only_capture&&) = delete; - /// Returns the owned result. - double operator()(cel::detail::frame&) const { return number; } -}; - -TEST_CASE("raw operations copy nonmovable lvalue captures independently") { - copy_only_capture input(7.0); - cel::detail::raw_segment segment; - segment.push_op0(input); - input.number = 99.0; - cel::raw_stack stack; - cel::detail::frame scope(stack); - segment.execute(scope); - CHECK(scope.pop() == 7.0); -} - -/// Verifies independent instruction ownership and stable nontrivial capture addresses. -TEST_CASE("captures survive input owners segment growth and segment moves") { - int released = 0; - cel::raw_stack stack; - { - cel::detail::raw_segment segment; - segment.push_op0(owning_capture(released)); - { - cel::detail::frame scope(stack); - segment.execute(scope); - CHECK(scope.pop() == 8.0); - } - for (int i = 0; i != 200; ++i) - segment.push_op0([](cel::detail::frame&) {}); - cel::detail::raw_segment moved(std::move(segment)); - cel::detail::frame scope(stack); - moved.execute(scope); - CHECK(scope.pop() == 8.0); - CHECK(released == 0); - } - CHECK(released == 1); -} - -/// Verifies reservation covers both payload bytes and active slot bookkeeping. -TEST_CASE("reserved scalar execution reuses one stack") { - cel::raw_stack stack; - stack.reserve(1024, 256); - cel::detail::raw_segment number; - number.push_op0([](cel::detail::frame&) { return 6.0; }); - number.push_op1([](cel::detail::frame&, double n) { return n / 2.0; }); - cel::detail::raw_segment boolean; - boolean.push_op0([](cel::detail::frame&) { return true; }); - boolean.push_op1([](cel::detail::frame&, bool n) { return !n; }); - { - cel::detail::frame scope(stack); - number.execute(scope); - CHECK(scope.pop() == 3.0); - boolean.execute(scope); - CHECK_FALSE(scope.pop()); - } - bool correct = true; - { - for (int i = 0; i != 2000; ++i) { - cel::detail::frame scope(stack); - number.execute(scope); - correct = correct && scope.pop() == 3.0; - boolean.execute(scope); - correct = correct && !scope.pop(); - } - } - CHECK(correct); - CHECK(stack.depth() == 0); -} - -/// Verifies explicit arguments/context and nested suffix isolation. -TEST_CASE("nested evaluations preserve outer arguments and live temporaries") { - cel::raw_stack stack; - const std::array arguments{cel::value::from(11.0)}; - int context = 7; - cel::detail::raw_segment nested; - nested.push_op0( - [](cel::detail::frame& scope) { return scope.argument(0).as(); }); - cel::detail::raw_segment outer; - outer.push_op1([&](cel::detail::frame& scope, double input) { - scope.push(5.0); - cel::detail::frame inner(stack, scope.arguments(), scope.context()); - nested.execute(inner); - const auto result = inner.pop(); - CHECK(scope.argument(0).as() == 11.0); - CHECK(scope.context() == &context); - return result + input; - }); - cel::detail::frame scope(stack, arguments, &context); - scope.push(3.0); - outer.execute(scope); - CHECK(scope.pop() == 14.0); - CHECK(scope.pop() == 5.0); - CHECK_THROWS_AS(scope.argument(1), std::out_of_range); -} - -/// Counts a synthetic opaque canonical resource independently of outer byte storage. -int live_resources = 0; -/// Selects which clone throws after earlier suffix ownership has been acquired. -int clones_before_failure = -1; -/// Clones one synthetic carrier, throwing without leaving partial ownership. -void clone_resource(const std::byte* source, std::byte* target) { - if (clones_before_failure == 0) throw std::runtime_error("clone failed"); - if (clones_before_failure > 0) --clones_before_failure; - std::memcpy(target, source, sizeof(void*)); - ++live_resources; -} -/// Releases one synthetic owner without allocating. -void destroy_resource(std::byte*) noexcept { --live_resources; } - -/// Verifies frame boundaries report malformed external requests before accessing memory. -TEST_CASE("checked stack boundaries reject underflow type mismatch and active-frame mutation") { - cel::raw_stack stack; - CHECK_THROWS_AS(stack.pop(), std::out_of_range); - CHECK_THROWS_AS(stack.reserve(10, 3), std::invalid_argument); - stack.push(2.0); - CHECK_THROWS_AS(stack.pop(), std::invalid_argument); - CHECK_THROWS_AS(stack.pop(), std::invalid_argument); - CHECK(stack.depth() == 1); - { - cel::detail::frame scope(stack); - CHECK_THROWS_AS(scope.pop(), std::out_of_range); - CHECK_THROWS_AS(stack.clear(), std::logic_error); - CHECK_THROWS_AS(stack.push(true), std::logic_error); - CHECK_THROWS_AS(stack.reserve(1024, 256), std::logic_error); - CHECK_THROWS_AS(stack.reserve_depth(1024), std::logic_error); - CHECK_THROWS_AS(cel::raw_stack(std::move(stack)), std::logic_error); - cel::raw_stack destination; - // NOLINTNEXTLINE(bugprone-use-after-move): rejected move preserves source. - CHECK_THROWS_AS(destination = std::move(stack), std::logic_error); - // NOLINTNEXTLINE(bugprone-use-after-move): rejected moves preserve frames. - cel::detail::frame inner(stack); - CHECK_THROWS_AS(scope.push(true), std::logic_error); - } - CHECK(stack.pop() == 2.0); - stack.clear(); -} - -/// Verifies preparation of zero-byte slots, reusable moved-from stacks, and segment assignment. -TEST_CASE("zero byte units and over-aligned operations reuse explicitly reserved depth") { - cel::raw_stack stack; - stack.reserve(1024, 256); - stack.reserve_depth(200); - cel::detail::raw_segment segment; - segment.push_op0([](cel::detail::frame&) { return aligned_leaf{13.0}; }); - segment.push_op0>([](cel::detail::frame&) { return std::tuple{}; }); - { - cel::detail::frame scope(stack); - segment.execute(scope); - CHECK(scope.pop>() == std::tuple{}); - CHECK(scope.pop().number == 13.0); - CHECK(&scope.stack() == &stack); - } - bool correct = true; - { - for (int i = 0; i != 100; ++i) { - cel::detail::frame scope(stack); - segment.execute(scope); - correct = correct && scope.pop>() == std::tuple{}; - correct = correct && scope.pop().number == 13.0; - for (int j = 0; j != 200; ++j) - scope.push(std::tuple{}); - } - } - CHECK(correct); - int released = 0; - { - cel::detail::raw_segment replaced; - replaced.push_op0(owning_capture(released)); - replaced = std::move(segment); - CHECK(released == 1); - cel::detail::frame scope(stack); - replaced.execute(scope); - CHECK(scope.pop>() == std::tuple{}); - CHECK(scope.pop().number == 13.0); - } - cel::raw_stack moved(std::move(stack)); - // NOLINTNEXTLINE(bugprone-use-after-move): the public contract promises reusable source stacks. - stack.push(17.0); - // NOLINTNEXTLINE(bugprone-use-after-move): observes the promised reused source. - CHECK(stack.pop() == 17.0); - CHECK(moved.depth() == 0); -} - -/// Verifies the canonical arbitrary-arity bridge and clone exceptions under execute rollback. -TEST_CASE("canonical instruction captures retain descriptors and clean failed clone suffixes") { - const auto opaque = cel::detail::type_access::install_callable_ownership( - cel::value_type::callable({}, cel::value_type::leaf()), - {clone_resource, destroy_resource}); - std::array bytes{}; - auto child = cel::detail::value_access::copy(opaque, bytes.data()); - auto aggregate = cel::value::tuple(std::array{child, child}); - const auto baseline = live_resources; - cel::raw_stack stack; - stack.push_clone(child); - { - cel::detail::raw_segment sequence; - cel::detail::segment_access::append(sequence, [owner = std::move(aggregate)]( - cel::detail::frame& scope) { - cel::detail::frame_access::push( - scope, owner.type(), cel::detail::value_access::data(owner), - [](const void* source, const cel::value_type& type, std::byte* target) { - cel::detail::clone_payload(type, static_cast(source), target); - }); - }); - // A separate matching bridge sequence demonstrates its unchecked signature contract. - cel::detail::raw_segment scalar; - cel::detail::segment_access::append(scalar, [](cel::detail::frame& scope) { - const auto type = cel::value_type::leaf(); - const auto* operand = cel::detail::frame_access::operand(scope, 0, type); - double result{}; - std::memcpy(&result, operand, sizeof(result)); - cel::detail::frame_access::discard(scope, 1); - scope.push(result / 2.0); - }); - cel::detail::frame scope(stack); - scope.push(12.0); - scalar.execute(scope); - CHECK(scope.pop() == 6.0); - scope.push(std::vector{1.0, 2.0}); - clones_before_failure = 1; - CHECK_THROWS_AS(sequence.execute(scope), std::runtime_error); - clones_before_failure = -1; - CHECK(scope.depth() == 0); - CHECK(live_resources == baseline + 1); - scope.push(18.0); - scalar.execute(scope); - CHECK(scope.pop() == 9.0); - } - CHECK(stack.depth() == 1); - stack.clear(); -} -/// Verifies throwing callbacks and clone failures retire only the acquired suffix. -TEST_CASE("throwing execution and composite cloning preserve the live prefix") { - cel::raw_stack stack; - auto prefix = cel::value::from(std::vector>{{1.0, 2.0}, {3.0}}); - stack.push_take(prefix); - CHECK(prefix.type().kind() == cel::type_kind::tuple); - cel::detail::raw_segment failure; - failure.push_op0>( - [](cel::detail::frame&) { return std::vector{7.0, 8.0}; }); - failure.push_op1>( - [](cel::detail::frame& scope, std::vector) -> double { - scope.push(std::vector{9.0}); - throw std::runtime_error("callback failed"); - }); - { - cel::detail::frame scope(stack); - CHECK_THROWS_AS(failure.execute(scope), std::runtime_error); - CHECK(scope.depth() == 0); - scope.push(true); - CHECK(scope.pop()); - } - CHECK(stack.depth() == 1); - CHECK(stack.pop>>() == - std::vector>{{1.0, 2.0}, {3.0}}); - - const auto opaque = cel::detail::type_access::install_callable_ownership( - cel::value_type::callable({}, cel::value_type::leaf()), - {clone_resource, destroy_resource}); - std::array bytes{}; - auto child = cel::detail::value_access::copy(opaque, bytes.data()); - const std::array children{child, child}; - auto owned = cel::value::tuple(children); - const auto baseline = live_resources; - stack.push(42.0); - { - cel::detail::frame scope(stack); - scope.push_clone(owned); - clones_before_failure = 1; - CHECK_THROWS_AS(scope.push_clone(owned), std::runtime_error); - CHECK(scope.depth() == 1); - CHECK(live_resources == baseline + 2); - clones_before_failure = -1; - } - CHECK(live_resources == baseline); - CHECK(stack.pop() == 42.0); -} - /// Verifies packed ownership can cross the raw boundary without aliasing or double release. TEST_CASE("packed composites transfer to and from reusable stacks with complete metadata") { cel::raw_stack stack; @@ -407,74 +22,6 @@ TEST_CASE("packed composites transfer to and from reusable stacks with complete assigned = std::move(moved); CHECK(assigned.depth() == 0); } - -/// Verifies borrowed canonical input slots are read lazily and results transfer without boxes. -TEST_CASE("explicit canonical frames clone emitted reads and extract independent results") { - const auto scalar_type = cel::value_type::leaf(); - double input = 23.0; - const std::array scalar_arguments{ - cel::detail::borrowed_value{scalar_type, reinterpret_cast(&input)}}; - cel::detail::raw_segment reads; - cel::detail::segment_access::append(reads, - [](cel::detail::frame& scope) { scope.push_argument(0); }); - cel::raw_stack stack; - stack.reserve(1024, 256); - int context = 5; - double output = 0; - { - cel::detail::frame scope(stack, scalar_arguments, &context); - reads.execute(scope); - cel::detail::frame_access::release_result(scope, scalar_type, - reinterpret_cast(&output)); - CHECK(output == 23.0); - CHECK(scope.depth() == 0); - CHECK(scope.argument(0).as() == 23.0); - } - bool correct = true; - { - for (int i = 0; i != 1000; ++i) { - cel::detail::frame scope(stack, scalar_arguments, &context); - reads.execute(scope); - cel::detail::frame nested(stack, scope.canonical_arguments(), scope.context()); - reads.execute(nested); - cel::detail::frame_access::release_result(nested, scalar_type, - reinterpret_cast(&output)); - correct = correct && output == 23.0; - } - } - CHECK(correct); - - auto owner = cel::value::from(std::vector>{{1.0, 2.0}}); - const std::array borrowed{ - cel::detail::borrowed_value{owner.type(), cel::detail::value_access::data(owner)}}; - { - cel::detail::frame scope(stack, borrowed); - reads.execute(scope); - auto copy = scope.pop_value(); - copy.set(0, cel::value::from(std::vector{8.0})); - CHECK(owner.at(0).at(0).as() == 1.0); - CHECK(copy.at(0).at(0).as() == 8.0); - CHECK_THROWS_AS(scope.push_argument(1), std::out_of_range); - cel::detail::storage result; - const auto layout = owner.type().byte_layout(); - result.reserve(layout.size, layout.alignment); - result.resize(layout.size); - reads.execute(scope); - cel::detail::frame_access::release_result(scope, owner.type(), result.data()); - owner.set(0, cel::value::from(std::vector{6.0})); - auto independent = cel::detail::value_access::take(owner.type(), result.data()); - CHECK(independent.at(0).at(0).as() == 1.0); - CHECK(owner.at(0).at(0).as() == 6.0); - } - const std::array missing{cel::detail::borrowed_value{scalar_type, nullptr}}; - CHECK_THROWS_AS(cel::detail::frame(stack, missing), std::invalid_argument); - alignas(double) std::array unaligned{}; - const std::array misaligned{cel::detail::borrowed_value{scalar_type, unaligned.data() + 1}}; - CHECK_THROWS_AS(cel::detail::frame(stack, misaligned), std::invalid_argument); - cel::detail::frame scope(stack); - CHECK(scope.depth() == 0); -} - /// Catches conservative type-capability rejection of valid uninhabited packed owners. TEST_CASE("empty deferred-element arrays retain their legal ownership across raw transfers") { const auto deferred = cel::value_type::callable({}, cel::value_type::leaf()); @@ -487,211 +34,3 @@ TEST_CASE("empty deferred-element arrays retain their legal ownership across raw CHECK(stack.pop_value().type().element().kind() == cel::type_kind::callable); CHECK(stack.depth() == 0); } - -/// Records bounded hook reentry attempts without relying on an invalid raw signature. -struct reentry_state { - cel::raw_stack& stack; ///< Borrows the tested stack. - cel::detail::frame* scope; ///< Borrows the active scope, or null during direct clear. - int rejected = 0; ///< Counts documented logic-error rejections. - bool unexpected = false; ///< Records any other exception from noexcept destruction probes. - bool propagate = false; ///< Lets a clone rejection escape to test rollback. - bool clone_attempted = false; ///< Bounds clone reentry to one attempt. - bool destroy_attempted = false; ///< Bounds retirement reentry to one attempt. - /// Attempts same-owner mutation and both forms of nested frame entry. - void probe() { - try { - if (scope) - scope->push(99.0); - else - stack.push(99.0); - } catch (const std::logic_error&) { - ++rejected; - if (propagate) throw; - } - try { - cel::detail::frame nested(stack); - } catch (const std::logic_error&) { - ++rejected; - } - try { - cel::detail::frame nested(stack, std::span{}); - } catch (const std::logic_error&) { - ++rejected; - } - } -}; -/// Enables hooks only during their bounded test scopes, never as production context. -reentry_state* active_reentry = nullptr; -/// Restores the test hook context before its borrowed state dies, including on exceptions. -struct reentry_scope { - reentry_state* previous; ///< Retains the prior single-threaded hook context. - /// Borrows the state for this bounded probe scope. - explicit reentry_scope(reentry_state& state) : previous(active_reentry) { - active_reentry = &state; - } - /// Disallows duplicated hook-scope ownership. - reentry_scope(const reentry_scope&) = delete; - /// Disallows reassigned hook-scope ownership. - reentry_scope& operator=(const reentry_scope&) = delete; - /// Restores the prior context. - ~reentry_scope() { active_reentry = previous; } -}; -/// Clones a synthetic owner after a bounded construction reentry attempt. -void clone_reentry(const std::byte* source, std::byte* target) { - if (active_reentry && !active_reentry->clone_attempted) { - active_reentry->clone_attempted = true; - active_reentry->probe(); - } - std::memcpy(target, source, sizeof(void*)); - ++live_resources; -} -/// Retires a synthetic owner while catching rejection inside its noexcept hook. -void destroy_reentry(std::byte*) noexcept { - if (active_reentry && !active_reentry->destroy_attempted) { - active_reentry->destroy_attempted = true; - try { - active_reentry->probe(); - } catch (...) { - active_reentry->unexpected = true; - } - } - --live_resources; -} -/// Catches clone/write offset reuse and retiring-slot mutation at safe boundaries. -TEST_CASE("payload clone and noexcept retirement hooks reject reentry") { - const auto type = cel::detail::type_access::install_callable_ownership( - cel::value_type::callable({}, cel::value_type::leaf()), - {clone_reentry, destroy_reentry}); - std::array bytes{}; - auto source = cel::detail::value_access::copy(type, bytes.data()); - const auto baseline = live_resources; - cel::raw_stack stack; - stack.reserve(1024, 256); - stack.push(17.0); - { - cel::detail::frame scope(stack); - reentry_state attempts{stack, &scope}; - reentry_scope enabled(attempts); - scope.push_clone(source); - CHECK(attempts.rejected == 3); - CHECK(scope.depth() == 1); - cel::detail::frame_access::discard(scope, scope.depth()); - CHECK(attempts.rejected == 6); - CHECK_FALSE(attempts.unexpected); - active_reentry = nullptr; - CHECK(live_resources == baseline); - scope.push(8.0); - CHECK(scope.pop() == 8.0); - } - CHECK(stack.pop() == 17.0); - stack.push_clone(source); - reentry_state direct{stack, nullptr}; - direct.clone_attempted = true; - reentry_scope enabled_direct(direct); - stack.clear(); - active_reentry = nullptr; - CHECK(direct.rejected == 3); - CHECK_FALSE(direct.unexpected); - CHECK(stack.depth() == 0); - stack.push(true); - CHECK(stack.pop()); -} - -/// Catches a gate left held after a rejected clone callback unwinds through execute. -TEST_CASE("rejected clone reentry rolls back only the frame suffix and restores access") { - const auto type = cel::detail::type_access::install_callable_ownership( - cel::value_type::callable({}, cel::value_type::leaf()), - {clone_reentry, destroy_reentry}); - std::array bytes{}; - auto source = cel::detail::value_access::copy(type, bytes.data()); - cel::raw_stack stack; - stack.reserve(1024, 256); - stack.push(std::vector{4.0, 5.0}); - cel::detail::raw_segment sequence; - cel::detail::segment_access::append( - sequence, [&source](cel::detail::frame& scope) { scope.push_clone(source); }); - { - cel::detail::frame scope(stack); - scope.push(std::vector{9.0}); - reentry_state attempts{stack, &scope}; - attempts.propagate = true; - reentry_scope enabled(attempts); - CHECK_THROWS_AS(sequence.execute(scope), std::logic_error); - active_reentry = nullptr; - CHECK(scope.depth() == 0); - scope.push(7.0); - CHECK(scope.pop() == 7.0); - cel::detail::frame nested(stack); - nested.push(false); - CHECK_FALSE(nested.pop()); - } - CHECK(stack.pop>() == std::vector{4.0, 5.0}); -} - -/// Verifies null bytes preserve non-unit zero-byte aggregate identity and stack effects. -TEST_CASE("borrowed non-unit zero-byte aggregates preserve complete shape") { - using aggregate = std::tuple, std::tuple<>>; - const auto type = cel::detail::concrete_adapter::type(); - const std::array inputs{cel::detail::borrowed_value{type, nullptr}}; - cel::raw_stack stack; - cel::detail::frame scope(stack, inputs); - CHECK(type.byte_layout().size == 0); - CHECK(type.fields().size() == 2); - CHECK_FALSE(type.same_shape(cel::value_type{})); - CHECK(scope.argument(0).as() == aggregate{}); - scope.push_argument(0); - auto owner = scope.pop_value(); - CHECK(owner.type().same_shape(type)); - CHECK(owner.size() == 2); - scope.push_take(owner); - CHECK(scope.pop() == aggregate{}); - CHECK(scope.depth() == 0); - CHECK(stack.cursor() == 0); -} - -/// Verifies allocating raw reads share the phase gate and release it on reader failure. -TEST_CASE("scoped canonical acquisition and direct writers contain reentry") { - cel::raw_stack stack; - stack.reserve(1024, 256); - stack.push(15.0); - { - cel::detail::frame scope(stack); - scope.push(std::vector{7.0, 8.0}); - const auto type = cel::detail::concrete_adapter>::type(); - reentry_state attempts{stack, &scope}; - reentry_scope enabled(attempts); - const auto acquired = cel::detail::frame_access::acquire(scope, [&](const auto& operands) { - attempts.probe(); - return cel::detail::value_access::copy(type, operands.operand(0, type)); - }); - active_reentry = nullptr; - CHECK(attempts.rejected == 3); - CHECK(acquired.as>() == std::vector{7.0, 8.0}); - CHECK(scope.depth() == 1); - CHECK_THROWS_AS(cel::detail::frame_access::acquire(scope, - [&](const auto& operands) -> double { - (void)operands.operand(0, type); - throw std::runtime_error( - "reader failed"); - }), - std::runtime_error); - CHECK(scope.pop>() == std::vector{7.0, 8.0}); - reentry_state writer{stack, &scope}; - reentry_scope enabled_writer(writer); - const auto scalar_type = cel::value_type::leaf(); - const double input = 3.0; - cel::detail::frame_access::push( - scope, scalar_type, &input, - [](const void* source, const cel::value_type&, std::byte* target) { - active_reentry->probe(); - std::memcpy(target, source, sizeof(double)); - }); - active_reentry = nullptr; - CHECK(writer.rejected == 3); - CHECK(scope.pop() == 3.0); - cel::detail::frame nested(stack); - nested.push(false); - CHECK_FALSE(nested.pop()); - } - CHECK(stack.pop() == 15.0); -} diff --git a/tests/resource_test.cpp b/tests/resource_test.cpp index ae1a10a..97f7ec3 100644 --- a/tests/resource_test.cpp +++ b/tests/resource_test.cpp @@ -1,14 +1,10 @@ // SPDX-License-Identifier: BSL-1.0 -#include "type_ops.hpp" -#include "value_ops.hpp" #include - #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN -#include - #include #include #include +#include #include #include #include @@ -35,94 +31,6 @@ void run_concurrently(First first, Second second) { second(); }); } - -/// Records actual node disposal and reentrant callbacks across independent retirement queues. -struct retirement_counts { - std::atomic disposed{0}; ///< Counts destroyed nodes. - std::atomic nested{false}; ///< Records nesting within one thread. -}; - -/// An owned chain node for checking the retirement primitive used by type metadata. -struct retirement_probe : cel::detail::retirement_node { - retirement_counts& counts; ///< Borrows counters until every worker has joined. - cel::detail::retirement_ptr child; ///< Retains the next chain node. - static inline thread_local std::size_t depth = 0; ///< Counts active callbacks on this thread. - - /// Adopts one child edge and retains the disposal counters. - retirement_probe(retirement_counts& state, cel::detail::retirement_ptr next) : - retirement_node(dispose_node), counts(state), child(std::move(next)) {} - - /// Records disposal, detaches the child into queue, and deletes this node. - /// - /// \pre base is an exclusively retiring retirement_probe. - static void dispose_node(cel::detail::retirement_node& base, - cel::detail::retirement_queue& queue) noexcept { - auto& node = static_cast(base); - ++depth; - if (depth != 1) node.counts.nested.store(true, std::memory_order_relaxed); - node.child.retire(queue); - node.counts.disposed.fetch_add(1, std::memory_order_relaxed); - delete &node; - --depth; - } -}; - -/// Catches premature disposal or wrong last-owner selection during concurrent edge releases. -TEST_CASE("concurrent last owners retire each node once without nested callbacks") { - constexpr std::size_t count = 12000; - retirement_counts counts; - cel::detail::retirement_ptr root; - CHECK(root.get() == nullptr); - std::vector> aliases; - // Retain interior aliases so independent queues also compete below the root. - for (std::size_t i = 0; i != count; ++i) { - auto next = std::make_unique(counts, std::move(root)); - root = cel::detail::retirement_ptr(next.release()); - if (i % 2 == 0) aliases.push_back(root); - } - { - auto copy = root; - CHECK(copy == root); - CHECK(copy.get() == root.get()); - auto moved = std::move(copy); - // NOLINTNEXTLINE(bugprone-use-after-move): moves promise an empty source handle. - CHECK_FALSE(copy); - CHECK(moved == root); - } - CHECK(counts.disposed.load() == 0); - run_concurrently([owner = std::move(root)]() mutable { owner = {}; }, - [owners = std::move(aliases)]() mutable { - while (!owners.empty()) - owners.pop_back(); - }); - CHECK(counts.disposed.load() == count); - CHECK_FALSE(counts.nested.load()); -} - -/// Catches disposing metadata before its last-owner queue drains. -TEST_CASE("queued metadata retains borrowed views until disposal") { - const auto boolean = cel::value_type::leaf(); - auto type = cel::value_type::record( - "queued", std::array{cel::record_field{"items", cel::value_type::array(boolean)}, - cel::record_field{"code", cel::value_type::callable( - std::array{boolean}, - cel::value_type::leaf())}}); - const auto fields = type.fields(); - const auto names = type.field_names(); - const auto identity = type.record_identity(); - const auto& element = fields[0].element(); - const auto parameters = fields[1].parameters(); - const auto& result = fields[1].result(); - cel::detail::retirement_queue queue; - cel::detail::type_access::retire(type, queue); - CHECK(identity == "queued"); - CHECK(names[0] == "items"); - CHECK(names[1] == "code"); - CHECK(element.same_shape(boolean)); - CHECK(parameters[0].same_shape(boolean)); - CHECK(result.same_shape(cel::value_type::leaf())); -} - /// Adds an array, shared aggregate, or callable-result edge. /// /// Complexity: O(1) time and new metadata space. @@ -164,65 +72,6 @@ TEST_CASE("concurrent metadata release preserves retained shared descendants") { CHECK(survivor.same_shape(expected)); CHECK(survivor.result().kind() == cel::type_kind::record); } - -/// Checks every carrier offset and a linear bound on constant-time traversal steps. -/// Complexity: O(count log count) time and O(count) temporary space. -void check_ownership_traversal(const cel::value_type& type, std::size_t count) { - cel::detail::ownership_cursor cursor(type); - std::vector offsets; - std::size_t steps = 0; - while (!cursor.empty()) { - if (const auto slot = cursor.next()) { - CHECK((slot->type->kind() == cel::type_kind::array)); - offsets.push_back(slot->offset); - } - ++steps; - } - REQUIRE((offsets.size() == count)); - CHECK((steps <= 3 * count)); - std::sort(offsets.begin(), offsets.end()); - for (std::size_t i = 0; i != count; ++i) - CHECK((offsets[i] == i * sizeof(void*))); -} - -/// Catches repeated root searches and expanded metadata at every skewed descriptor. -TEST_CASE("ownership ranges traverse wide and skewed aggregates in linear work") { - constexpr std::size_t count = 2048; - const auto element = cel::value::from(std::vector{3.0}); - const cel::value_type unit; - const std::vector fields(count, element); - const auto flat = cel::value::tuple(fields); - check_ownership_traversal(flat.type(), count); - - for (const bool heavy_first : {false, true}) { - auto type = element.type(); - std::size_t ranges = 0; - std::size_t range_bytes = 0; - for (std::size_t i = 1; i != count; ++i) { - const auto children = - heavy_first ? std::array{type, element.type()} : std::array{element.type(), type}; - type = cel::value_type::tuple(children); - const auto compiled = cel::detail::type_access::ownership_ranges(type); - ranges += compiled.size(); - range_bytes += compiled.size_bytes(); - } - CHECK(ranges <= 2 * count); - CHECK(range_bytes <= 2 * count * sizeof(cel::detail::ownership_slot)); - check_ownership_traversal(type, count); - auto original = - cel::detail::value_access::copy(type, cel::detail::value_access::data(flat)); - auto copy = original; - original = cel::value{}; - auto restored = - cel::detail::value_access::copy(flat.type(), cel::detail::value_access::data(copy)); - CHECK(restored.at(0).at(0).as() == 3.0); - CHECK(restored.at(count - 1).at(0).as() == 3.0); - copy = cel::value{}; - restored = cel::value{}; - type = unit; - } -} - /// Supplies a nonowning client field with extended alignment. struct alignas(256) ownership_aligned_leaf { std::array bytes; ///< Stores a trivially copyable opaque payload. @@ -244,21 +93,6 @@ TEST_CASE("record ownership ranges preserve canonical offsets around nonowning f original = cel::value{}; copy = cel::value{}; } - -/// Catches expansion of shared ranges and traversal proportional to unary nesting. -TEST_CASE("ownership ranges reuse shared descendants and collapse unary paths") { - auto type = cel::value_type::array(cel::value_type::leaf()); - std::size_t ranges = 0; - for (std::size_t i = 0; i != 12; ++i) { - type = cel::value_type::tuple(std::array{type, type}); - ranges += cel::detail::type_access::ownership_ranges(type).size(); - } - CHECK(ranges <= 24); - check_ownership_traversal(type, 4096); - for (std::size_t i = 0; i != 50000; ++i) - type = cel::value_type::tuple(std::array{type}); - check_ownership_traversal(type, 4096); -} /// Catches recursive last-reference release, including during exception cleanup. TEST_CASE("deep descriptor release and exception unwinding are stack independent") { const cel::value_type unit; @@ -336,36 +170,3 @@ TEST_CASE("nonowning tuple array elements preserve their values") { CHECK(small.as>>() == small_input); CHECK(large.at(4095).as>() == std::tuple{false, 3.0}); } - -/// Catches recursive cloning and destruction of owned array trees. -TEST_CASE("deep owned array trees clone release and unwind without recursive cleanup") { - auto source = cel::value::from(true); - for (std::size_t i = 0; i != 50000; ++i) - source = cel::detail::value_access::take_array(source.type(), std::span(&source, 1)); - auto copy = source; - CHECK(copy.type().same_shape(source.type())); - CHECK(copy.size() == 1); - copy = cel::value{}; - source = cel::value{}; - CHECK_THROWS_AS( - [] { - auto tree = cel::value::from(false); - for (std::size_t i = 0; i != 50000; ++i) - tree = cel::detail::value_access::take_array(tree.type(), std::span(&tree, 1)); - throw std::runtime_error("unwind packed ownership"); - }(), - std::runtime_error); -} - -/// Catches recursion through deeply nested inline fields even when only one carrier exists. -TEST_CASE("deep inline aggregate ownership paths are stack independent") { - const auto leaf_array = cel::value::from(std::vector{2.0, 3.0}); - auto type = leaf_array.type(); - for (std::size_t i = 0; i != 50000; ++i) - type = cel::value_type::tuple(std::array{type}); - auto owner = cel::detail::value_access::copy(type, cel::detail::value_access::data(leaf_array)); - auto copy = owner; - CHECK(copy.type().same_shape(type)); - owner = cel::value{}; - copy = cel::value{}; -} diff --git a/tests/segment_test.cpp b/tests/segment_test.cpp index 87bfdfb..3eb2884 100644 --- a/tests/segment_test.cpp +++ b/tests/segment_test.cpp @@ -1,9 +1,5 @@ // SPDX-License-Identifier: BSL-1.0 -#include "instruction.hpp" -#include "type_ops.hpp" -#include "value_ops.hpp" #include - #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include #include @@ -12,27 +8,6 @@ #include #include -/// Counts live synthetic callable-carrier owners without implementing callable bodies. -int live_carriers = 0; -/// Clones an independently owned integer through the foundation's opaque ownership contract. -void clone_carrier(const std::byte* source, std::byte* destination) { - int* pointer = nullptr; - std::memcpy(static_cast(&pointer), source, sizeof(pointer)); - auto owner = std::make_unique(*pointer); - pointer = owner.release(); - std::memcpy(destination, static_cast(&pointer), sizeof(pointer)); - ++live_carriers; -} -/// Retires one initialized synthetic carrier. -void destroy_carrier(std::byte* bytes) noexcept { - int* pointer = nullptr; - std::memcpy(static_cast(&pointer), bytes, sizeof(pointer)); - delete pointer; - --live_carriers; -} -/// Supplies an incompatible ownership pair with the same semantic signature. -void destroy_other_carrier(std::byte* bytes) noexcept { destroy_carrier(bytes); } - /// Exercises root admission independently of callable-parameter restrictions. struct alignas(256) client_leaf { int number; ///< Retains a client-defined scalar. @@ -62,66 +37,6 @@ struct segment_reordered_point { double x; }; -/// Holds an owned callable field for typed-result lifetime tests. -struct segment_callable_record { - /// Owns one callable value. - cel::value code; -}; - -/// Holds test input for ownership-mismatch adapter regression checks. -struct ownership_gap_payload { - /// Seeds the synthetic callable carrier. - int seed; -}; - -/// Returns the callable descriptor with the primary ownership pair. -const cel::value_type& primary_callable_type() { - static const auto descriptor = cel::detail::type_access::install_callable_ownership( - cel::value_type::callable({}, cel::value_type::leaf()), - {clone_carrier, destroy_carrier}); - return descriptor; -} - -/// Returns the callable descriptor with an incompatible ownership pair. -const cel::value_type& foreign_callable_type() { - static const auto descriptor = cel::detail::type_access::install_callable_ownership( - cel::value_type::callable({}, cel::value_type::leaf()), - {clone_carrier, destroy_other_carrier}); - return descriptor; -} - -/// Returns the declared nominal record descriptor with the primary callable ownership pair. -const cel::value_type& declared_ownership_gap_type() { - static const auto descriptor = cel::value_type::record( - "tests.ownership_gap", std::array{cel::record_field{"code", primary_callable_type()}}); - return descriptor; -} - -/// Returns a same-shape nominal record descriptor with incompatible callable ownership. -const cel::value_type& foreign_ownership_gap_type() { - static const auto descriptor = cel::value_type::record( - "tests.ownership_gap", std::array{cel::record_field{"code", foreign_callable_type()}}); - return descriptor; -} - -/// Returns one callable value with synthetic owned carrier storage. -cel::value make_foreign_callable_value(int seed) { - int payload = seed; - int* pointer = &payload; - std::array carrier{}; - std::memcpy(carrier.data(), static_cast(&pointer), sizeof(pointer)); - return cel::detail::value_access::copy(foreign_callable_type(), carrier.data()); -} - -/// Returns one callable value with the primary ownership pair. -cel::value make_primary_callable_value(int seed) { - int payload = seed; - int* pointer = &payload; - std::array carrier{}; - std::memcpy(carrier.data(), static_cast(&pointer), sizeof(pointer)); - return cel::detail::value_access::copy(primary_callable_type(), carrier.data()); -} - namespace cel { template <> struct record_adapter { @@ -192,43 +107,6 @@ struct record_adapter<::segment_reordered_point> { } }; -template <> -struct record_adapter<::segment_callable_record> { - /// Returns the callable record schema. - static value_type type() { - static const auto descriptor = - value_type::record("tests.segment_callable_record", - std::array{record_field{"code", primary_callable_type()}}); - return descriptor; - } - /// Encodes the callable field as an owned canonical value. - static value to_value(const ::segment_callable_record& source) { - return value::record(type(), std::array{source.code}); - } - /// Copies the owned callable field from a validated record. - static ::segment_callable_record from_value(const value& source) { - if (!source.type().same_shape(type())) - throw std::invalid_argument("wrong callable record type"); - return {.code = source.field("code")}; - } -}; - -template <> -struct record_adapter { - /// Returns the declared nominal descriptor with the primary ownership pair. - static value_type type() { return declared_ownership_gap_type(); } - /// Encodes the payload as a same-shape record with incompatible callable ownership. - static value to_value(const ownership_gap_payload& source) { - auto code = make_foreign_callable_value(source.seed); - return value::record(foreign_ownership_gap_type(), std::array{code}); - } - /// Decodes this payload from a validated record value. - static ownership_gap_payload from_value(const value& source) { - if (!source.type().same_shape(type())) - throw std::invalid_argument("wrong ownership-gap type"); - return {.seed = 0}; - } -}; } // namespace cel /// Catches byte-based counting, reversed suffixes, and inclusion of ambient operands. @@ -357,20 +235,6 @@ TEST_CASE("construction rejects underflow mismatches and conflicting reads") { CHECK(program.prepare().call(stack, true)); } -TEST_CASE("recursive preparation mismatch preserves nominal and leaf identity") { - using input = std::tuple, bool>; - cel::dyn_segment builder; - builder.push_argument(0, cel::detail::concrete_adapter::type()); - auto program = std::move(builder).finish(); - CHECK_THROWS_AS((program.prepare, bool>>()), - std::invalid_argument); - CHECK_THROWS_AS((program.prepare, double>, input>()), - std::invalid_argument); - cel::raw_stack stack; - const std::array wrong{cel::value::from(std::tuple{std::vector{true}, true})}; - CHECK_THROWS_AS(program.execute(stack, wrong), std::invalid_argument); -} - TEST_CASE("frozen captures and literals outlive their builders and sources") { auto prepared = [] { cel::dyn_segment builder; @@ -389,23 +253,6 @@ TEST_CASE("frozen captures and literals outlive their builders and sources") { CHECK(prepared.call(stack) == std::vector{8.0, 3.0}); CHECK(first[0] == 99.0); } - -TEST_CASE("typed composite calls borrow inputs and return disjoint nested results") { - using input = std::tuple>, bool>; - cel::dyn_segment builder; - builder.push_argument(0, cel::detail::concrete_adapter::type()); - auto prepared = std::move(builder).finish().prepare(); - cel::raw_stack stack; - input source{{{1.0, 2.0}}, true}; - auto first = prepared.call(stack, source); - auto second = prepared.call(stack, source); - std::get<0>(first)[0][0] = 7.0; - CHECK(std::get<0>(source)[0][0] == 1.0); - CHECK(std::get<0>(second)[0][0] == 1.0); - std::get<0>(source)[0][1] = 9.0; - CHECK(std::get<0>(second)[0][1] == 2.0); -} - /// Owns an over-aligned factor that can be copied but not moved. struct alignas(256) copy_only_factor { double factor; ///< Owns the multiplication factor. @@ -446,23 +293,6 @@ TEST_CASE("dynamic and selected callbacks copy nonmovable lvalues independently" CHECK(std::move(explicit_signature).finish().prepare().call(stack) == 12.0); } -TEST_CASE("typed zero-sized unit arrays retain nested logical lengths") { - using units = std::vector>>; - cel::dyn_segment builder; - builder.push_argument(0, cel::detail::concrete_adapter::type()); - auto prepared = std::move(builder).finish().prepare(); - const units input{std::vector>(3), {}, std::vector>(1)}; - cel::raw_stack stack; - auto result = prepared.call(stack, input); - REQUIRE(result.size() == 3); - CHECK(result[0].size() == 3); - CHECK(result[1].empty()); - CHECK(result[2].size() == 1); - result[0].clear(); - CHECK(input[0].size() == 3); - CHECK(prepared.call(stack, input)[0].size() == 3); -} - TEST_CASE("selected callable wrappers preserve independent lvalue copies") { auto selected = cel::with_signature(adaptable_factor(2.0)); auto copied = selected; @@ -494,95 +324,6 @@ TEST_CASE("finalization rejects silent leftover operand discard") { builder.just(cel::value::from(2.0)); CHECK_THROWS_AS(std::move(builder).finish(), std::invalid_argument); } - -TEST_CASE("runtime-bound owning output has a public retirement boundary") { - cel::dyn_segment builder; - builder.op0>>( - [] { return std::vector>{{2.0}, {3.0}}; }); - auto program = std::move(builder).finish(); - auto prepared = cel::detail::segment_access::prepare_raw(program, {}, program.result_type()); - const auto layout = prepared.result_type().byte_layout(); - auto* destination = - static_cast(::operator new(layout.size, std::align_val_t(layout.alignment))); - cel::raw_stack stack; - prepared.call_into(stack, {}, destination); - auto first = cel::detail::borrowed_value{prepared.result_type(), destination} - .as>>(); - prepared.destroy_result(destination); - first[0][0] = 8.0; - prepared.call_into(stack, {}, destination); - CHECK(cel::detail::borrowed_value{prepared.result_type(), destination} - .as>>()[0][0] == 2.0); - prepared.destroy_result(destination); - ::operator delete(destination, std::align_val_t(layout.alignment)); - CHECK(stack.depth() == 0); -} - -TEST_CASE("runtime-bound exact record identity and shared deep metadata") { - const std::array fields{cel::record_field{"flag", cel::value_type::leaf()}}; - auto type = cel::value_type::record("named", fields); - cel::dyn_segment builder; - builder.push_argument(0, type); - auto program = std::move(builder).finish(); - const std::array wrong{cel::value_type::record("other", fields)}; - CHECK_THROWS_AS(cel::detail::segment_access::prepare_raw(program, wrong, type), - std::invalid_argument); - const std::array arguments{type}; - auto prepared = cel::detail::segment_access::prepare_raw(program, arguments, type); - const std::array contents{cel::value::from(true)}; - auto source = cel::value::record(type, contents); - const std::array views{ - cel::detail::borrowed_value{type, cel::detail::value_access::data(source)}}; - alignas(bool) std::array result{}; - cel::raw_stack stack; - prepared.call_into(stack, views, result.data()); - CHECK(cel::detail::value_access::copy(type, result.data()).field("flag").as()); - prepared.destroy_result(result.data()); - auto deep = cel::value_type::leaf(); - auto same = cel::value_type::leaf(); - for (int i = 0; i != 32; ++i) { - const std::array left{deep, deep}; - const std::array right{same, same}; - deep = cel::value_type::tuple(left); - same = cel::value_type::tuple(right); - } - cel::dyn_segment shared; - shared.push_argument(0, deep); - auto shared_program = std::move(shared).finish(); - const std::array shared_arguments{same}; - CHECK_NOTHROW(cel::detail::segment_access::prepare_raw(shared_program, shared_arguments, same)); -} - -TEST_CASE("throwing callbacks preserve caller prefix and reusable raw destination") { - bool fail = true; - cel::dyn_segment builder; - builder.push_argument(0, cel::value_type::leaf()); - builder.op1([&fail](double n) { - if (fail) throw std::runtime_error("callback"); - return n + 1.0; - }); - auto program = std::move(builder).finish(); - const std::array types{cel::value_type::leaf()}; - auto prepared = cel::detail::segment_access::prepare_raw(program, types, types[0]); - cel::raw_stack stack; - stack.push(std::vector{7.0}); - const auto cursor = stack.cursor(); - double input = 2.0; - const std::array views{ - cel::detail::borrowed_value{types[0], reinterpret_cast(&input)}}; - alignas(double) std::array result{}; - result.fill(std::byte{0x5a}); - CHECK_THROWS_AS(prepared.call_into(stack, views, result.data()), std::runtime_error); - CHECK(result[0] == std::byte{0x5a}); - CHECK(stack.depth() == 1); - CHECK(stack.cursor() == cursor); - fail = false; - prepared.call_into(stack, views, result.data()); - CHECK(cel::detail::borrowed_value{types[0], result.data()}.as() == 3.0); - prepared.destroy_result(result.data()); - CHECK(stack.pop>() == std::vector{7.0}); -} - TEST_CASE("typed operations accept nominal record adapters and propagate callback failures") { CHECK(cel::native_type().record_identity() == "tests.segment_widget"); bool fail = true; @@ -625,53 +366,6 @@ TEST_CASE("typed record operands preserve canonical field order") { CHECK(result.y == doctest::Approx(2.0)); } -TEST_CASE("typed record results retire their canonical owned fields") { - auto code = make_primary_callable_value(17); - cel::dyn_segment builder; - builder.op0( - [code = std::move(code)] { return segment_callable_record{.code = code}; }); - auto prepared = std::move(builder).finish().prepare(); - cel::raw_stack stack; - const auto live = live_carriers; - { - const auto result = prepared.call(stack); - CHECK(result.code.type().same_shape(primary_callable_type())); - CHECK(live_carriers == live + 1); - } - CHECK(live_carriers == live); -} - -TEST_CASE("typed record adapter rejects same-shape incompatible ownership before transfer") { - cel::dyn_segment builder; - builder.op0([] { return ownership_gap_payload{.seed = 7}; }); - auto program = std::move(builder).finish(); - const auto result_type = cel::native_type(); - auto prepared = cel::detail::segment_access::prepare_raw(program, {}, result_type); - const auto layout = result_type.byte_layout(); - auto* destination = - static_cast(::operator new(layout.size, std::align_val_t(layout.alignment))); - std::fill(destination, destination + layout.size, std::byte{0x5a}); - cel::raw_stack stack; - stack.push(std::vector{9.0}); - const auto cursor = stack.cursor(); - const auto depth = stack.depth(); - const auto live = live_carriers; - bool threw = false; - try { - prepared.call_into(stack, {}, destination); - } catch (const std::invalid_argument&) { - threw = true; - } - if (!threw) prepared.destroy_result(destination); - CHECK(threw); - if (threw) CHECK(destination[0] == std::byte{0x5a}); - CHECK(live_carriers == live); - CHECK(stack.depth() == depth); - CHECK(stack.cursor() == cursor); - CHECK(stack.pop>() == std::vector{9.0}); - ::operator delete(destination, std::align_val_t(layout.alignment)); -} - TEST_CASE("typed calls accept unused composite arguments") { cel::dyn_segment builder; builder.op0([] { return 5.0; }); @@ -681,40 +375,6 @@ TEST_CASE("typed calls accept unused composite arguments") { const std::vector unused(100, 7.0); CHECK(bound.call(stack, unused) == 5.0); } - -TEST_CASE("reserved typed and runtime-bound scalar calls reuse the stack") { - cel::dyn_segment builder; - builder.push_argument(0, cel::value_type::leaf()); - builder.just(cel::value::from(3.0)); - builder.op2([](double a, double b) { return a - b; }); - auto program = std::move(builder).finish(); - auto typed = program.prepare(); - const std::array types{cel::value_type::leaf()}; - auto raw = cel::detail::segment_access::prepare_raw(program, types, types[0]); - cel::raw_stack stack; - const auto reservation = typed.requirements().for_prefix(stack.cursor(), stack.depth()); - stack.reserve(reservation.bytes.size, reservation.bytes.alignment); - stack.reserve_depth(reservation.slots); - CHECK(typed.call(stack, 5.0) == 2.0); - double input = 8.0; - const std::array views{ - cel::detail::borrowed_value{types[0], reinterpret_cast(&input)}}; - alignas(double) std::array bytes{}; - raw.call_into(stack, views, bytes.data()); - raw.destroy_result(bytes.data()); - double typed_total = 0.0; - double raw_total = 0.0; - for (int i = 0; i != 1000; ++i) { - typed_total += typed.call(stack, input); - raw.call_into(stack, views, bytes.data()); - raw_total += cel::detail::concrete_adapter::read(types[0], bytes.data()); - raw.destroy_result(bytes.data()); - } - CHECK(typed_total == 5000.0); - CHECK(raw_total == 5000.0); - CHECK(stack.depth() == 0); -} - TEST_CASE("arbitrary arity repeated reads and reference results remain exact") { cel::dyn_segment builder; builder.push_argument(0, cel::value_type::leaf()); @@ -735,141 +395,6 @@ TEST_CASE("arbitrary arity repeated reads and reference results remain exact") { copied[0] = 7.0; CHECK(source[0] == 3.0); } - -TEST_CASE("raw calls preserve composite arguments and caller prefix") { - int effects = 0; - cel::dyn_segment builder; - const auto type = cel::detail::concrete_adapter>::type(); - builder.push_argument(0, type); - builder.push_argument(0, type); - builder.op2, std::vector>( - [&effects](std::vector a, std::vector b) { - ++effects; - return a[0] + b[0]; - }); - auto program = std::move(builder).finish(); - const std::array types{type}; - auto bound = - cel::detail::segment_access::prepare_raw(program, types, cel::value_type::leaf()); - const auto owner = cel::value::from(std::vector{2.0}); - const std::array views{ - cel::detail::borrowed_value{type, cel::detail::value_access::data(owner)}}; - cel::raw_stack stack; - stack.reserve(4096, 256); - stack.push(std::vector{9.0}); - const auto prefix = stack.cursor(); - alignas(double) std::array bytes{}; - CHECK(effects == 0); - bound.call_into(stack, views, bytes.data()); - CHECK(cel::detail::borrowed_value{bound.result_type(), bytes.data()}.as() == 4.0); - bound.destroy_result(bytes.data()); - CHECK(effects == 1); - CHECK(owner.as>() == std::vector{2.0}); - CHECK(stack.cursor() == prefix); - CHECK(stack.depth() == 1); - CHECK(stack.pop>() == std::vector{9.0}); -} - -TEST_CASE("frozen raw callable results bind complete ownership and retire independently") { - const auto signature = cel::value_type::callable({}, cel::value_type::leaf()); - const auto type = cel::detail::type_access::install_callable_ownership( - signature, {clone_carrier, destroy_carrier}); - const auto other = cel::detail::type_access::install_callable_ownership( - signature, {clone_carrier, destroy_other_carrier}); - const auto composite = cel::value_type::array(type); - const auto incompatible = cel::value_type::array(other); - int number = 42; - int* pointer = &number; - alignas(void*) std::array bytes{}; - std::memcpy(bytes.data(), static_cast(&pointer), sizeof(pointer)); - CHECK(live_carriers == 0); - { - const auto owner = cel::detail::value_access::copy(type, bytes.data()); - const std::array elements{owner}; - auto literal = cel::value::array(type, elements); - cel::dyn_segment builder; - builder.just(std::move(literal)); - auto program = std::move(builder).finish(); - CHECK_THROWS_AS(cel::detail::segment_access::prepare_raw(program, {}, incompatible), - std::invalid_argument); - CHECK_THROWS_AS(cel::detail::segment_access::prepare_raw(program, {}, - cel::value_type::array(signature)), - std::invalid_argument); - auto bound = cel::detail::segment_access::prepare_raw(program, {}, composite); - const auto layout = composite.byte_layout(); - auto* result = static_cast( - ::operator new(layout.size, std::align_val_t(layout.alignment))); - cel::raw_stack stack; - const auto baseline = live_carriers; - bound.call_into(stack, {}, result); - CHECK(live_carriers == baseline + 1); - bound.destroy_result(result); - CHECK(live_carriers == baseline); - bound.call_into(stack, {}, result); - CHECK(live_carriers == baseline + 1); - bound.destroy_result(result); - CHECK(live_carriers == baseline); - ::operator delete(result, std::align_val_t(layout.alignment)); - } - CHECK(live_carriers == 0); -} - -TEST_CASE("checked callable read pairs and range identities reject before effects") { - const auto signature = cel::value_type::callable({}, cel::value_type::leaf()); - const auto type = cel::detail::type_access::install_callable_ownership( - signature, {clone_carrier, destroy_carrier}); - const auto other = cel::detail::type_access::install_callable_ownership( - signature, {clone_carrier, destroy_other_carrier}); - int effects = 0; - cel::dyn_segment builder; - builder.op0([&effects] { ++effects; }); - builder.push_argument(0, type); - CHECK_THROWS_AS(builder.push_argument(0, other), std::invalid_argument); - auto program = std::move(builder).finish(); - const std::array wrong_types{other}; - CHECK_THROWS_AS(cel::detail::segment_access::prepare_raw(program, wrong_types, type), - std::invalid_argument); - int number = 3; - int* pointer = &number; - alignas(void*) std::array bytes{}; - std::memcpy(bytes.data(), static_cast(&pointer), sizeof(pointer)); - const std::array wrong_values{cel::detail::value_access::copy(other, bytes.data())}; - cel::raw_stack stack; - CHECK_THROWS_AS(program.execute(stack, wrong_values), std::invalid_argument); - CHECK(effects == 0); - const auto range = - cel::value_type::range(cel::range_kind::range_full, cel::value_type::leaf()); - cel::dyn_segment ranges; - ranges.push_argument(0, range); - auto range_program = std::move(ranges).finish(); - const std::array wrong_range{ - cel::value_type::range(cel::range_kind::range_full, cel::value_type::leaf())}; - CHECK_THROWS_AS(cel::detail::segment_access::prepare_raw(range_program, wrong_range, range), - std::invalid_argument); - const std::array right_range{range}; - auto bound = cel::detail::segment_access::prepare_raw(range_program, right_range, range); - const std::array range_input{cel::detail::borrowed_value{range, nullptr}}; - CHECK_NOTHROW(bound.call_into(stack, range_input, nullptr)); - bound.destroy_result(nullptr); - CHECK(stack.depth() == 0); -} - -TEST_CASE("zero-byte non-unit raw arguments retain complete recursive identity") { - using zero = std::tuple, std::tuple<>>; - const auto type = cel::detail::concrete_adapter::type(); - cel::dyn_segment builder; - builder.push_argument(0, type); - auto program = std::move(builder).finish(); - CHECK_THROWS_AS((program.prepare, zero>()), std::invalid_argument); - const std::array types{type}; - auto bound = cel::detail::segment_access::prepare_raw(program, types, type); - const std::array inputs{cel::detail::borrowed_value{type, nullptr}}; - cel::raw_stack stack; - CHECK_NOTHROW(bound.call_into(stack, inputs, nullptr)); - bound.destroy_result(nullptr); - CHECK(program.prepare().call(stack, zero{}) == zero{}); -} - TEST_CASE("ordinary callbacks execute outside acquisition and retirement gates") { cel::dyn_segment nested_builder; nested_builder.op0([] { return 4.0; }); @@ -898,43 +423,6 @@ TEST_CASE("typed composite results retain caller prefix") { CHECK(bound.call(stack) == std::vector{3.0}); CHECK(stack.pop>() == std::vector{7.0}); } - -/// Supplies named overloads that require an exact explicit signature selection. -struct overloaded_callback { - /// Doubles one exact operand. - double operator()(double number) const { return number * 2.0; } - /// Adds two exact operands. - double operator()(double a, double b) const { return a + b; } -}; - -/// Exercises invocation through the required const lvalue callback boundary. -struct lvalue_callback { - /// Increments its exact operand through a const lvalue. - double operator()(double number) const& { return number + 1.0; } -}; - -/// Exercises nonthrowing invocation through the same const lvalue boundary. -struct lvalue_noexcept_callback { - /// Increments its exact operand without throwing. - double operator()(double number) const& noexcept { return number + 2.0; } -}; - -/// Supplies an introspection-ineligible invocation through an exact function-pointer conversion. -struct pointer_callback { - using function = double (*)(double); ///< Describes its explicit concrete invocation. - - /// Doubles one exact operand. - static double twice(double number) { return number * 2.0; } - /// Returns its exact function pointer. - operator function() const noexcept { return twice; } -}; - -/// Detects exact explicit member selection without hard introspection errors. -template -concept signature_selectable = requires(F callback) { - cel::with_signature(std::move(callback)); -}; - /// Retains a fixed concrete operand even though its callback is a function template. struct defaulted_generic { /// Returns its exact double operand independently of its defaulted template parameter. @@ -952,35 +440,6 @@ struct nondeduced_generic { return number; } }; - -TEST_CASE("exact callback selection rejects ambiguous conversions and accepts const lvalues") { - static_assert(!signature_selectable); - static_assert(!cel::detail::exact_callback()); - static_assert(!signature_selectable); - cel::dyn_segment builder; - builder.just(cel::value::from(3.0)); - builder.op1(cel::with_signature(overloaded_callback{})); - builder.op1(lvalue_callback{}); - builder.op1(lvalue_noexcept_callback{}); - cel::raw_stack stack; - CHECK(std::move(builder).finish().prepare().call(stack) == 9.0); - cel::dyn_segment binary; - binary.just(cel::value::from(2.0)); - binary.just(cel::value::from(5.0)); - binary.op2( - cel::with_signature(overloaded_callback{})); - CHECK(std::move(binary).finish().prepare().call(stack) == 7.0); - cel::dyn_segment pointer; - pointer.just(cel::value::from(4.0)); - pointer.op1(static_cast(pointer_callback{})); - pointer.op1(pointer_callback::twice); - CHECK(std::move(pointer).finish().prepare().call(stack) == 16.0); - cel::dyn_segment qualified; - qualified.just(cel::value::from(3.0)); - qualified.op1(cel::with_signature(lvalue_noexcept_callback{})); - CHECK(std::move(qualified).finish().prepare().call(stack) == 5.0); -} - TEST_CASE("provably exact generic callbacks retain source operand identities") { cel::dyn_segment builder; builder.just(cel::value::from(true)); @@ -1013,43 +472,6 @@ TEST_CASE("provably exact generic callbacks retain source operand identities") { struct large_temporary { std::array data{}; ///< Owns a trivially copyable client payload. }; - -TEST_CASE("published reservations cover hidden intermediate alignment and caller padding") { - cel::dyn_segment builder; - builder.op0([] { return 2.0; }); - builder.op0([] { return client_leaf{7}; }); - builder.op1( - [](const client_leaf& source) { return double(source.number); }); - builder.op2([](double a, double b) { return a + b; }); - auto program = std::move(builder).finish(); - CHECK(program.result_type().byte_layout().alignment == alignof(double)); - const auto& requirements = program.requirements(); - CHECK(requirements.alignment == alignof(client_leaf)); - CHECK(requirements.frame_extent == 512); - CHECK(requirements.live_slots == 2); - auto typed = program.prepare(); - auto raw = cel::detail::segment_access::prepare_raw(program, {}, program.result_type()); - CHECK(&typed.requirements() == &program.requirements()); - CHECK(&raw.requirements() == &program.requirements()); - cel::raw_stack stack; - stack.push(true); - const auto prefix_cursor = stack.cursor(); - const auto prefix_depth = stack.depth(); - const auto reservation = typed.requirements().for_prefix(prefix_cursor, prefix_depth); - CHECK(reservation.bytes.size == 768); - CHECK(reservation.slots == 3); - stack.reserve(reservation.bytes.size, reservation.bytes.alignment); - stack.reserve_depth(reservation.slots); - alignas(double) std::array bytes{}; - const auto result = typed.call(stack); - raw.call_into(stack, {}, bytes.data()); - raw.destroy_result(bytes.data()); - CHECK(result == 9.0); - CHECK(stack.cursor() == prefix_cursor); - CHECK(stack.depth() == prefix_depth); - CHECK(stack.pop()); -} - TEST_CASE("published reservation covers larger temporary canonical extents") { cel::dyn_segment builder; builder.op0([] { return large_temporary{}; }); @@ -1089,27 +511,3 @@ TEST_CASE("published zero-byte peak reserves live slots independently of byte ex CHECK(stack.pop() == unit{}); CHECK(stack.pop() == unit{}); } - -TEST_CASE("published reservations check prefix arithmetic and reject construction overflow") { - cel::dyn_segment builder; - builder.op0([] { return 2.0; }); - auto program = std::move(builder).finish(); - const auto maximum = std::numeric_limits::max(); - CHECK_THROWS_AS(program.requirements().for_prefix(maximum, 0), std::overflow_error); - CHECK_THROWS_AS(program.requirements().for_prefix(0, maximum), std::overflow_error); - auto malformed = program.requirements(); - malformed.alignment = 3; - CHECK_THROWS_AS(malformed.for_prefix(0, 0), std::invalid_argument); - auto huge = cel::value_type::leaf(); - for (int i = 0; i != std::numeric_limits::digits - 1; ++i) { - const std::array fields{huge, huge}; - huge = cel::value_type::tuple(fields); - } - cel::dyn_segment wide; - wide.push_argument(0, huge); - CHECK_THROWS_AS(wide.push_argument(1, huge), std::overflow_error); - auto frozen = std::move(wide).finish(); - CHECK_NOTHROW(cel::detail::segment_access::prepare_raw(frozen, std::array{huge}, huge)); - CHECK(frozen.requirements().frame_extent == huge.byte_layout().size); - CHECK(frozen.requirements().live_slots == 1); -} diff --git a/tests/storage_test.cpp b/tests/storage_test.cpp index 43b914c..0cb8eac 100644 --- a/tests/storage_test.cpp +++ b/tests/storage_test.cpp @@ -1,19 +1,8 @@ // SPDX-License-Identifier: BSL-1.0 -#include "storage.hpp" #include - +#include #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include - -#include -#include -#include -#include -#include -#include -#include -#include - /// Supplies a trivially copyable, over-aligned payload. struct alignas(256) leaf { /// Stores a scalar whose representation survives byte transfer. @@ -26,209 +15,3 @@ TEST_CASE("layout describes an over-aligned leaf") { CHECK(shape.size == 256); CHECK(shape.alignment == 256); } - -/// Catches incorrect rounding of zero, already-aligned, and unaligned offsets. -TEST_CASE("align_offset rounds upward without changing aligned offsets") { - CHECK(cel::detail::align_offset(0, 64) == 0); - CHECK(cel::detail::align_offset(1, 64) == 64); - CHECK(cel::detail::align_offset(64, 64) == 64); - CHECK(cel::detail::align_offset(65, 64) == 128); - CHECK(cel::detail::align_offset(7, 1) == 7); - CHECK(cel::detail::align_offset(std::numeric_limits::max(), 1) == - std::numeric_limits::max()); -} - -/// Catches unchecked alignment and offset overflow at the safe boundary. -TEST_CASE("align_offset rejects invalid alignment and arithmetic overflow") { - CHECK_THROWS_AS(cel::detail::align_offset(1, 0), std::invalid_argument); - CHECK_THROWS_AS(cel::detail::align_offset(1, 3), std::invalid_argument); - CHECK_THROWS_AS(cel::detail::align_offset(std::numeric_limits::max(), 64), - std::overflow_error); - constexpr auto highest = std::numeric_limits::max() / 2 + 1; - CHECK(cel::detail::align_offset(highest, highest) == highest); - CHECK_THROWS_AS(cel::detail::align_offset(highest + 1, highest), std::overflow_error); -} - -/// Catches accidental allocation for zero bytes or forgotten empty-state alignment. -TEST_CASE("empty storage remains allocation-free and remembers alignment") { - cel::detail::storage bytes; - CHECK(bytes.data() == nullptr); - CHECK(bytes.size() == 0); - CHECK(bytes.capacity() == 0); - bytes.reserve(0, 256); - CHECK(bytes.data() == nullptr); - CHECK(bytes.capacity() == 0); - CHECK(bytes.alignment() >= 256); - bytes.resize(1); - CHECK(reinterpret_cast(bytes.data()) % 256 == 0); - CHECK(bytes.data()[0] == std::byte{0}); -} - -/// Catches loss of initialized bytes, reserve changing size, or narrowing alignment. -TEST_CASE("reserve preserves initialized bytes through growth and realignment") { - cel::detail::storage bytes; - bytes.resize(4); - const std::array payload{std::byte{0x11}, std::byte{0x22}, std::byte{0x33}, std::byte{0x44}}; - std::memcpy(bytes.data(), payload.data(), payload.size()); - const auto growth_request = bytes.capacity() + 1; - bytes.reserve(growth_request, 64); - CHECK(bytes.capacity() >= growth_request); - CHECK(bytes.size() == 4); - CHECK(std::memcmp(bytes.data(), payload.data(), payload.size()) == 0); - const auto capacity = bytes.capacity(); - bytes.reserve(4, 256); - CHECK(bytes.capacity() >= capacity); - CHECK(bytes.alignment() >= 256); - CHECK(reinterpret_cast(bytes.data()) % 256 == 0); - CHECK(std::memcmp(bytes.data(), payload.data(), payload.size()) == 0); - auto* const address = bytes.data(); - bytes.reserve(1, 1); - CHECK(bytes.data() == address); - CHECK(bytes.alignment() >= 256); - CHECK(bytes.size() == 4); - const auto& view = bytes; - CHECK(view.data()[3] == std::byte{0x44}); -} - -/// Catches uninitialized exposed bytes or shrinking that loses the retained prefix. -TEST_CASE("resize initializes growth and retains capacity on shrink") { - cel::detail::storage bytes; - bytes.resize(2); - bytes.data()[0] = std::byte{0x55}; - bytes.data()[1] = std::byte{0x66}; - const auto growth_request = bytes.capacity() + 3; - bytes.resize(growth_request); - CHECK(bytes.size() == growth_request); - CHECK(bytes.capacity() >= growth_request); - CHECK(bytes.data()[0] == std::byte{0x55}); - CHECK(bytes.data()[1] == std::byte{0x66}); - CHECK(std::all_of(bytes.data() + 2, bytes.data() + growth_request, - [](std::byte value) { return value == std::byte{0}; })); - const auto capacity = bytes.capacity(); - bytes.resize(1); - CHECK(bytes.capacity() == capacity); - bytes.resize(2); - CHECK(bytes.data()[0] == std::byte{0x55}); - CHECK(bytes.data()[1] == std::byte{0}); - bytes.resize(0); - CHECK(bytes.size() == 0); - CHECK(bytes.capacity() == capacity); -} - -/// Catches silent arithmetic failure or mutation before an unsuccessful reserve. -TEST_CASE("storage reports invalid alignment and allocation arithmetic overflow") { - cel::detail::storage bytes; - bytes.resize(1); - bytes.data()[0] = std::byte{0x77}; - auto* const address = bytes.data(); - const auto capacity = bytes.capacity(); - const auto alignment = bytes.alignment(); - CHECK_THROWS_AS(bytes.reserve(1, 0), std::invalid_argument); - CHECK_THROWS_AS(bytes.reserve(1, 3), std::invalid_argument); - CHECK_THROWS_AS(bytes.reserve(std::numeric_limits::max(), 64), - std::overflow_error); - CHECK_THROWS_AS(bytes.resize(std::numeric_limits::max()), std::overflow_error); - CHECK(bytes.data() == address); - CHECK(bytes.capacity() == capacity); - CHECK(bytes.alignment() == alignment); - CHECK(bytes.size() == 1); - CHECK(bytes.data()[0] == std::byte{0x77}); -} - -/// Catches allocation failures converted into success or loss of prior ownership. -TEST_CASE("storage propagates allocation failure without changing initialized bytes") { - cel::detail::storage bytes; - bytes.resize(1); - bytes.data()[0] = std::byte{0x99}; - auto* const address = bytes.data(); - const auto capacity = bytes.capacity(); - const auto alignment = bytes.alignment(); - // This representable, aligned extent exceeds the available address space. - constexpr auto impossible = std::numeric_limits::max() - 255; - CHECK_THROWS_AS(bytes.reserve(impossible, 256), std::bad_alloc); - CHECK(bytes.data() == address); - CHECK(bytes.size() == 1); - CHECK(bytes.capacity() == capacity); - CHECK(bytes.alignment() == alignment); - CHECK(bytes.data()[0] == std::byte{0x99}); -} - -/// Catches misaligned allocation or byte transfer that corrupts implicit-lifetime payloads. -TEST_CASE("storage holds and transfers an alignas 256 trivially copyable leaf") { - static_assert(std::is_trivially_copyable_v); - cel::detail::storage bytes; - bytes.reserve(sizeof(leaf), alignof(leaf)); - CHECK(bytes.capacity() >= sizeof(leaf)); - bytes.resize(sizeof(leaf)); - const leaf original{0x123456789abcdef0}; - std::memcpy(bytes.data(), &original, sizeof(original)); - CHECK(reinterpret_cast(bytes.data()) % 256 == 0); - CHECK(reinterpret_cast(bytes.data())->value == original.value); - const auto growth_request = bytes.capacity() + 1; - bytes.reserve(growth_request, 1); - CHECK(bytes.capacity() >= growth_request); - CHECK(reinterpret_cast(bytes.data()) % 256 == 0); - CHECK(reinterpret_cast(bytes.data())->value == original.value); - leaf restored{}; - std::memcpy(&restored, bytes.data(), sizeof(restored)); - CHECK(restored.value == original.value); -} - -// Moved-from observations verify storage's documented empty and reusable state. -// NOLINTBEGIN(bugprone-use-after-move,clang-analyzer-cplusplus.Move) -/// Catches duplicated ownership, stale moved-from metadata, or lost destination cleanup. -TEST_CASE("storage moves unique ownership and leaves its source reusable") { - static_assert(!std::is_copy_constructible_v); - static_assert(!std::is_copy_assignable_v); - static_assert(std::is_nothrow_move_constructible_v); - static_assert(std::is_nothrow_move_assignable_v); - cel::detail::storage source; - source.reserve(4, 256); - source.resize(4); - source.data()[0] = std::byte{0x88}; - auto* const address = source.data(); - cel::detail::storage moved(std::move(source)); - CHECK(moved.data() == address); - CHECK(moved.size() == 4); - CHECK(moved.alignment() >= 256); - CHECK(source.data() == nullptr); - CHECK(source.size() == 0); - CHECK(source.capacity() == 0); - source.resize(1); - CHECK(source.data()[0] == std::byte{0}); - source = std::move(moved); - CHECK(source.data() == address); - CHECK(source.data()[0] == std::byte{0x88}); - CHECK(moved.data() == nullptr); - CHECK(moved.size() == 0); - CHECK(moved.capacity() == 0); - auto& alias = source; - source = std::move(alias); - CHECK(source.data() == address); - cel::detail::storage empty; - source = std::move(empty); - CHECK(source.data() == nullptr); - CHECK(source.size() == 0); - CHECK(source.capacity() == 0); -} -// NOLINTEND(bugprone-use-after-move,clang-analyzer-cplusplus.Move) - -// Moved-from alignment observations verify the documented reset. -// NOLINTBEGIN(bugprone-use-after-move,clang-analyzer-cplusplus.Move) -/// Catches alignment metadata lost while moving allocation-free storage. -TEST_CASE("storage moves alignment even when no allocation exists") { - cel::detail::storage source; - source.reserve(0, 256); - cel::detail::storage destination(std::move(source)); - CHECK(destination.data() == nullptr); - CHECK(destination.size() == 0); - CHECK(destination.capacity() == 0); - CHECK(destination.alignment() >= 256); - CHECK(source.alignment() == alignof(std::max_align_t)); - source = std::move(destination); - CHECK(source.alignment() >= 256); - CHECK(destination.alignment() == alignof(std::max_align_t)); - source.resize(1); - CHECK(reinterpret_cast(source.data()) % 256 == 0); -} -// NOLINTEND(bugprone-use-after-move,clang-analyzer-cplusplus.Move) diff --git a/tests/value_test.cpp b/tests/value_test.cpp index c896ec9..140be07 100644 --- a/tests/value_test.cpp +++ b/tests/value_test.cpp @@ -1,29 +1,15 @@ // SPDX-License-Identifier: BSL-1.0 -#include "canonical.hpp" -#include "storage.hpp" -#include "type_ops.hpp" -#include "value_ops.hpp" #include - #define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN -#include - #include #include #include +#include #include #include #include #include -#if defined(__has_feature) -#if __has_feature(address_sanitizer) -#include -#endif -#elif defined(__SANITIZE_ADDRESS__) -#include -#endif - /// Exercises concrete identity independently of layout. struct alignas(256) aligned_leaf { /// Stores a client scalar. @@ -100,142 +86,6 @@ struct record_adapter { } }; } // namespace cel - -/// Requests a test callback failure after acquiring a temporary resource. -bool fail_test_clone = false; -/// Counts live resources created by the synthetic opaque clone callback. -int live_test_owners = 0; -/// Requests a failure after a known initialized ownership prefix. -int test_clones_until_failure = -1; -/// Identifies a synthetic clone failure without allocating a diagnostic. -struct test_clone_error : std::exception { - /// Returns a fixed diagnostic without allocating. - const char* what() const noexcept override { return "synthetic clone failure"; } -}; - -/// Clones a synthetic opaque owner without implementing a callable object. -void clone_test_owner(const std::byte* source, std::byte* destination) { - int* pointer = nullptr; - std::memcpy(static_cast(&pointer), source, sizeof(pointer)); - auto copy = std::make_unique(*pointer); - if (fail_test_clone) throw std::runtime_error("synthetic clone failure"); - if (test_clones_until_failure == 0) { - throw test_clone_error{}; - } - if (test_clones_until_failure > 0) --test_clones_until_failure; - ++live_test_owners; - pointer = copy.release(); - std::memcpy(destination, static_cast(&pointer), sizeof(pointer)); -} - -/// Destroys a synthetic opaque owner without allocating. -void destroy_test_owner(std::byte* data) noexcept { - int* pointer = nullptr; - std::memcpy(static_cast(&pointer), data, sizeof(pointer)); - delete pointer; - --live_test_owners; -} - -/// Supplies a distinct installed operation pair to test representation admission. -void destroy_test_owner_alternative(std::byte* data) noexcept { destroy_test_owner(data); } - -/// Catches repeating complete comparisons for every empty element with shared metadata. -TEST_CASE("checked arrays reuse equivalent descriptor comparisons across elements") { - constexpr std::size_t depth = 128; - constexpr std::size_t count = 128; - auto expected = cel::value_type::leaf(); - auto actual = cel::value_type::leaf(); - for (std::size_t i = 0; i != depth; ++i) { - expected = cel::value_type::array(expected); - actual = cel::value_type::array(actual); - } - const auto empty = cel::value::array(actual.element(), {}); - const std::vector children(count, empty); - cel::value result; - result = cel::value::array(expected, children); - CHECK(result.size() == count); - CHECK(result.at(count - 1).size() == 0); - - auto consumed = children; - result = cel::detail::value_access::take_array(expected, consumed); - for (const auto& child : consumed) - CHECK(child.type().same_shape(cel::value{}.type())); - - cel::detail::compatibility_context comparisons; - std::size_t work = 0; - for (const auto& child : children) - work += comparisons.require(expected, child.type()); - CHECK(work > 0); - CHECK(work <= 2 * (depth + 1)); - - for (std::size_t i = 0; i != count; ++i) { - const auto distinct = cel::value::array(actual.element(), {}); - work += comparisons.require(expected, distinct.type()); - } - CHECK(work <= 2 * (depth + count + 1)); -} - -/// Catches memo entries authorizing unequal shapes or foreign operations after a failed check. -TEST_CASE("operation comparison caches keep shape and ownership checks independent") { - const auto signature = cel::value_type::callable({}, cel::value_type::leaf()); - const auto expected = cel::detail::type_access::install_callable_ownership( - signature, {clone_test_owner, destroy_test_owner}); - cel::detail::compatibility_context comparisons; - for (int i = 0; i != 128; ++i) { - const auto actual = cel::detail::type_access::install_callable_ownership( - signature, - {clone_test_owner, i % 2 == 0 ? destroy_test_owner : destroy_test_owner_alternative}); - if (i % 2 == 0) { - CHECK_NOTHROW(comparisons.require(expected, actual)); - } else { - CHECK_THROWS_AS(comparisons.require(expected, actual), std::invalid_argument); - CHECK_THROWS_AS(comparisons.require(expected, actual), std::invalid_argument); - } - } - const auto one = cel::value_type::tuple(std::array{expected}); - const auto two = cel::value_type::tuple(std::array{expected, expected}); - CHECK_THROWS_AS(comparisons.require(one, two), std::invalid_argument); - CHECK_THROWS_AS(comparisons.require(one, two), std::invalid_argument); - CHECK_NOTHROW(comparisons.require(one, cel::value_type::tuple(std::array{expected}))); - - const auto foreign = cel::detail::type_access::install_callable_ownership( - signature, {clone_test_owner, destroy_test_owner_alternative}); - const auto valid_empty = cel::value::array(expected, {}); - const auto foreign_empty = cel::value::array(foreign, {}); - CHECK_THROWS_AS(cel::value::array(valid_empty.type(), std::array{valid_empty, foreign_empty}), - std::invalid_argument); - auto destination = cel::value::array(valid_empty.type(), std::array{valid_empty}); - CHECK_THROWS_AS(destination.set(0, foreign_empty), std::invalid_argument); - CHECK(destination.at(0).type().compatible_with(valid_empty.type())); -} - -/// Catches leaking a partially cloned traversal-order prefix. -TEST_CASE("partial ownership traversal cleans its initialized prefix") { - const auto installed = cel::detail::type_access::install_callable_ownership( - cel::value_type::callable({}, cel::value_type::leaf()), - {clone_test_owner, destroy_test_owner}); - int number = 42; - int* pointer = &number; - std::array bytes; - std::memcpy(bytes.data(), static_cast(&pointer), sizeof(pointer)); - const auto callable = cel::detail::value_access::copy(installed, bytes.data()); - const auto array = cel::value::from(std::vector{2.0, 3.0}); - const auto source = - cel::value::tuple(std::array{callable, array, callable, array, callable, array}); - const auto live = live_test_owners; - test_clones_until_failure = 2; - bool caught = false; - try { - auto copy = source; - } catch (const test_clone_error&) { - caught = true; - } - test_clones_until_failure = -1; - CHECK(caught); - CHECK(live_test_owners == live); - CHECK(source.at(1).at(0).as() == 2.0); -} - /// Catches layout-only comparison and ownership traversal before unequal-shape rejection. TEST_CASE("public compatibility requires complete semantic shapes") { const auto scalar = cel::value_type::leaf(); @@ -258,126 +108,6 @@ TEST_CASE("public compatibility requires complete semantic shapes") { CHECK_FALSE(nested.compatible_with(cel::value_type::array(cel::value_type::array( cel::value_type::tuple(std::array{cel::value_type::leaf()}))))); } - -/// Catches conflating semantic signatures with stored opaque representation compatibility. -TEST_CASE("public compatibility rejects nested foreign callable ownership operations") { - const auto signature = cel::value_type::callable({}, cel::value_type::leaf()); - const auto installed = cel::detail::type_access::install_callable_ownership( - signature, {clone_test_owner, destroy_test_owner}); - const auto foreign = cel::detail::type_access::install_callable_ownership( - signature, {clone_test_owner, destroy_test_owner_alternative}); - CHECK(signature.compatible_with(signature)); - CHECK_FALSE(signature.owns_values()); - CHECK(installed.compatible_with(installed)); - CHECK(installed.same_shape(foreign)); - CHECK_FALSE(installed.compatible_with(foreign)); - CHECK_FALSE(foreign.compatible_with(installed)); - const auto nested = cel::value_type::array(cel::value_type::record( - "callbacks", - std::array{cel::record_field{"stored", cel::value_type::tuple(std::array{installed})}})); - const auto nested_foreign = cel::value_type::array(cel::value_type::record( - "callbacks", - std::array{cel::record_field{"stored", cel::value_type::tuple(std::array{foreign})}})); - CHECK(nested.same_shape(nested_foreign)); - CHECK_FALSE(nested.compatible_with(nested_foreign)); - CHECK_FALSE(nested_foreign.compatible_with(nested)); - CHECK(live_test_owners == 0); -} - -/// Catches accepting incomplete opaque operations or mutating shared capability metadata. -TEST_CASE("private callable ownership installation preserves shape and validates operation pairs") { - const auto signature = cel::value_type::callable({}, cel::value_type::leaf()); - CHECK_THROWS_AS(cel::detail::require_ownership(signature), std::invalid_argument); - cel::detail::storage destination_bytes; - destination_bytes.reserve(signature.byte_layout().size, signature.byte_layout().alignment); - destination_bytes.resize(signature.byte_layout().size); - CHECK_THROWS_AS(cel::detail::clone_payload(signature, nullptr, destination_bytes.data()), - std::invalid_argument); - CHECK_THROWS_AS(cel::detail::type_access::install_callable_ownership( - signature, {clone_test_owner, nullptr}), - std::invalid_argument); - CHECK_THROWS_AS(cel::detail::type_access::install_callable_ownership( - cel::value_type::leaf(), {clone_test_owner, destroy_test_owner}), - std::invalid_argument); - const auto installed = cel::detail::type_access::install_callable_ownership( - signature, {clone_test_owner, destroy_test_owner}); - CHECK_FALSE(signature.owns_values()); - CHECK(installed.owns_values()); - CHECK(signature.same_shape(installed)); - CHECK_NOTHROW(cel::detail::require_ownership(installed)); - CHECK_THROWS_AS(cel::detail::require_ownership(cel::value_type::array(signature)), - std::invalid_argument); - CHECK(live_test_owners == 0); - { - auto original = std::make_unique(42); - int* pointer = original.get(); - std::array carrier{}; - std::memcpy(carrier.data(), static_cast(&pointer), sizeof(pointer)); - auto owner = cel::detail::value_access::copy(installed, carrier.data()); - *original = 99; - auto copy = owner; - int* owned = nullptr; - int* copied = nullptr; - std::memcpy(static_cast(&owned), cel::detail::value_access::data(owner), - sizeof(owned)); - std::memcpy(static_cast(&copied), cel::detail::value_access::data(copy), - sizeof(copied)); - CHECK(*owned == 42); - CHECK(*copied == 42); - *owned = 17; - CHECK(*copied == 42); - *copied = 18; - CHECK(*owned == 17); - const auto deferred_record = - cel::value_type::record("code", std::array{cel::record_field{"body", signature}}); - CHECK_THROWS_AS(cel::value::record(deferred_record, std::array{owner}), - std::invalid_argument); - const auto owned_record = - cel::value_type::record("code", std::array{cel::record_field{"body", installed}}); - CHECK( - cel::value::record(owned_record, std::array{owner}).type().same_shape(deferred_record)); - const auto alternative = cel::detail::type_access::install_callable_ownership( - signature, {clone_test_owner, destroy_test_owner_alternative}); - CHECK(alternative.same_shape(installed)); - CHECK_THROWS_AS( - cel::value::record( - cel::value_type::record("code", std::array{cel::record_field{"body", alternative}}), - std::array{owner}), - std::invalid_argument); - auto children = std::array{cel::value::from(std::vector{1.0, 2.0}), owner}; - const auto failing_record = cel::value_type::record( - "partial", std::array{cel::record_field{"items", children[0].type()}, - cel::record_field{"code", installed}}); - const auto good_record = cel::value::record(failing_record, children); - const auto packed_records = - cel::value::array(failing_record, std::array{good_record, good_record}); - auto replacement_record = good_record; - auto replacement_array = cel::value::array(installed, std::array{owner}); - const auto live_before = live_test_owners; - auto destination = cel::value::from(false); - fail_test_clone = true; - CHECK_THROWS_AS(cel::value::record(failing_record, children), std::runtime_error); - CHECK_THROWS_AS(cel::value{good_record}, std::runtime_error); - CHECK_THROWS_AS(cel::value{packed_records}, std::runtime_error); - CHECK_THROWS_AS(destination = good_record, std::runtime_error); - CHECK_THROWS_AS(replacement_record.set_field("code", owner), std::runtime_error); - CHECK_THROWS_AS(replacement_array.set(0, owner), std::runtime_error); - fail_test_clone = false; - CHECK(live_test_owners == live_before); - CHECK_FALSE(destination.as()); - int* preserved = nullptr; - auto preserved_field = replacement_record.field("code"); - std::memcpy(static_cast(&preserved), - cel::detail::value_access::data(preserved_field), sizeof(preserved)); - CHECK(*preserved == 17); - preserved_field = replacement_array.at(0); - std::memcpy(static_cast(&preserved), - cel::detail::value_access::data(preserved_field), sizeof(preserved)); - CHECK(*preserved == 17); - } - CHECK(live_test_owners == 0); -} - /// Catches lost scalar bits, insufficient alignment, and layout-based casts. TEST_CASE("concrete adapters preserve scalar values and reject wrong identities") { CHECK(cel::value::from(true).as()); @@ -682,151 +412,3 @@ TEST_CASE("callable results retain every valid result category") { cel::value_type::record("closure", std::array{cel::record_field{"code", results.back()}}); CHECK_FALSE(deferred.owns_values()); } - -/// Owns a raw clone solely to verify private raw ownership contracts. -struct raw_owner { - cel::value_type type; ///< Retains immutable destruction metadata. - cel::detail::storage bytes; ///< Owns aligned outer storage. - bool initialized = false; ///< Tracks whether payload destruction is required. - /// Clones a canonical payload with clone_payload's source requirements. - /// - /// Complexity: linear in source value area, plus held clone costs; new owned storage. - raw_owner(const cel::value_type& shape, const std::byte* source) : type(shape) { - const auto layout = type.byte_layout(); - bytes.reserve(layout.size, layout.alignment); - bytes.resize(layout.size); - cel::detail::clone_payload(type, source, bytes.data()); - initialized = true; - } - /// Copies a public value into raw canonical storage. - /// Complexity: O(payload size) time and space. - explicit raw_owner(const cel::value& source) : - raw_owner(source.type(), cel::detail::value_access::data(source)) {} - /// Destroys exactly one raw payload without allocating. - /// Complexity: O(payload size) time and O(shape depth) call space. - ~raw_owner() { - if (initialized) cel::detail::destroy_payload(type, bytes.data()); - } -}; - -/// Catches reading a fixed aggregate before checking its deferred callable carriers. -TEST_CASE("deferred callable cloning rejects fixed aggregates before reading source") { - const auto deferred = cel::value_type::callable({}, cel::value_type::leaf()); - const auto tuple = cel::value_type::tuple(std::array{cel::value_type::leaf(), deferred}); - const auto record = - cel::value_type::record("callbacks", std::array{cel::record_field{"nested", tuple}}); - CHECK_THROWS_AS(raw_owner(tuple, nullptr), std::invalid_argument); - CHECK_THROWS_AS(raw_owner(record, nullptr), std::invalid_argument); -} - -/// Catches copying packed element bytes before rejecting their deferred callable descriptor. -TEST_CASE("deferred callable cloning rejects array elements before reading their bytes") { - const auto deferred = cel::value_type::callable({}, cel::value_type::leaf()); - const auto installed = cel::detail::type_access::install_callable_ownership( - deferred, {clone_test_owner, destroy_test_owner}); - int number = 42; - int* pointer = &number; - std::array carrier; - std::memcpy(carrier.data(), static_cast(&pointer), sizeof(pointer)); - cel::detail::canonical_owner source(cel::value_type::array(installed)); - cel::detail::array_builder builder(installed, 1); - auto* element = builder.destination(); - cel::detail::clone_payload(installed, carrier.data(), element); - builder.initialized(); - builder.release_to(source.bytes.data()); - source.live = true; - const auto live = live_test_owners; - -#ifdef ASAN_POISON_MEMORY_REGION - ASAN_POISON_MEMORY_REGION(element, installed.byte_layout().size); - // Restore readability before source destruction, including on an unexpected exception. - const auto unpoison = [size = installed.byte_layout().size](std::byte* data) noexcept { - ASAN_UNPOISON_MEMORY_REGION(data, size); - }; - const std::unique_ptr readable_on_exit(element, unpoison); -#endif - - CHECK_THROWS_AS(raw_owner(cel::value_type::array(deferred), source.bytes.data()), - std::invalid_argument); - CHECK(live_test_owners == live); -} - -/// Catches replacing a requested deferred descriptor with installed source-owner metadata. -TEST_CASE("deferred callable cloning rejects fixed aggregates inside nested arrays") { - const auto deferred = cel::value_type::callable({}, cel::value_type::leaf()); - const auto installed = cel::detail::type_access::install_callable_ownership( - deferred, {clone_test_owner, destroy_test_owner}); - int number = 42; - int* pointer = &number; - std::array carrier; - std::memcpy(carrier.data(), static_cast(&pointer), sizeof(pointer)); - const auto callable = cel::detail::value_access::copy(installed, carrier.data()); - auto source = cel::value::tuple(std::array{cel::value::from(true), callable}); - auto requested = cel::value_type::tuple(std::array{cel::value_type::leaf(), deferred}); - for (int depth = 0; depth != 3; ++depth) { - source = cel::value::array(source.type(), std::array{source}); - requested = cel::value_type::array(requested); - const auto live = live_test_owners; - CHECK_THROWS_AS(raw_owner(requested, cel::detail::value_access::data(source)), - std::invalid_argument); - CHECK(live_test_owners == live); - } -} - -/// Catches retaining an earlier sibling clone after a nested deferred-callable rejection. -TEST_CASE("deferred callable cloning releases the initialized sibling prefix") { - const auto deferred = cel::value_type::callable({}, cel::value_type::leaf()); - const auto installed = cel::detail::type_access::install_callable_ownership( - deferred, {clone_test_owner, destroy_test_owner}); - int number = 42; - int* pointer = &number; - std::array carrier; - std::memcpy(carrier.data(), static_cast(&pointer), sizeof(pointer)); - const auto callable = cel::detail::value_access::copy(installed, carrier.data()); - const auto array = cel::value::array(installed, std::array{callable}); - const auto source = cel::value::tuple(std::array{callable, array}); - const auto requested = - cel::value_type::tuple(std::array{installed, cel::value_type::array(deferred)}); - const auto live = live_test_owners; - CHECK_THROWS_AS(raw_owner(requested, cel::detail::value_access::data(source)), - std::invalid_argument); - CHECK(live_test_owners == live); - CHECK(source.at(1).size() == 1); -} - -/// Catches rejecting uninhabited deferred element types, including beneath a nonempty array. -TEST_CASE("deferred callable cloning preserves empty and nested empty arrays") { - const auto deferred = cel::value_type::callable({}, cel::value_type::leaf()); - const auto empty = cel::value::array(deferred, {}); - raw_owner empty_copy(empty); - CHECK(cel::detail::value_access::array_size(empty_copy.bytes.data()) == 0); - const auto nested = cel::value::array(empty.type(), std::array{empty}); - raw_owner nested_copy(nested); - const auto result = cel::detail::value_access::copy(nested_copy.type, nested_copy.bytes.data()); - CHECK(result.size() == 1); - CHECK(result.at(0).size() == 0); - CHECK(result.type().element().element().kind() == cel::type_kind::callable); -} - -/// Catches raw clones sharing mutable arrays and duplicate destruction after byte transfer. -TEST_CASE("private canonical clone destruction and transfer preserve exactly one owner") { - auto source = cel::value::from(std::tuple{std::vector{1.0, 2.0}, true}); - raw_owner raw(source); - auto copied = cel::detail::value_access::copy(raw.type, raw.bytes.data()); - auto child = source.at(0); - child.set(0, cel::value::from(8.0)); - source.set(0, child); - CHECK(copied.at(0).at(0).as() == 1.0); - CHECK(cel::detail::value_access::copy(raw.type, raw.bytes.data()).at(0).at(0).as() == - 1.0); - cel::detail::storage transferred; - const auto extent = raw.type.byte_layout(); - transferred.reserve(extent.size, extent.alignment); - transferred.resize(extent.size); - std::memcpy(transferred.data(), raw.bytes.data(), extent.size); - raw.initialized = false; - CHECK(cel::detail::value_access::copy(raw.type, transferred.data()).at(1).as()); - cel::detail::destroy_payload(raw.type, transferred.data()); - raw_owner empty(cel::value{}); - CHECK(cel::detail::value_access::copy(empty.type, empty.bytes.data()).size() == 0); -}