diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c5c121875..bf953556b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -175,7 +175,8 @@ jobs: # Release legs build without running tests and are the slowest jobs in # the workflow, so pull requests get the two debug legs, which build # and test, and master pushes add the release legs. - preset: ${{ fromJSON(github.event_name == 'pull_request' && '["cl-debug", "clangcl-debug"]' || '["cl-debug", "cl-release", "clangcl-debug", "clangcl-release"]') }} + # The shared-library legs build and test morph::morph as a DLL. + preset: ${{ fromJSON(github.event_name == 'pull_request' && '["cl-debug", "clangcl-debug", "cl-shared-debug", "clangcl-shared-debug"]' || '["cl-debug", "cl-release", "clangcl-debug", "clangcl-release", "cl-shared-debug", "clangcl-shared-debug"]') }} steps: - uses: actions/checkout@v4 @@ -219,7 +220,7 @@ jobs: run: cmake --build --preset ${{ matrix.preset }} - name: Test - if: matrix.preset == 'cl-debug' || matrix.preset == 'clangcl-debug' + if: endsWith(matrix.preset, '-debug') run: ctest --preset ${{ matrix.preset }} # Picks a self-hosted lastrada-docker runner for the Linux legs when one is @@ -314,7 +315,9 @@ jobs: matrix: # No gcc-debug leg: linux-qt configures gcc-debug with Qt on and runs # the whole suite, which covers everything a plain gcc-debug leg would. - preset: [gcc-release, clang-debug, clang-release] + # clang-shared-debug builds morph::morph as a shared library with its + # symbols hidden by default, so an unexported symbol is a link error. + preset: [gcc-release, clang-debug, clang-release, clang-shared-debug] steps: - uses: actions/checkout@v4 @@ -2405,6 +2408,15 @@ jobs: CXX: g++-15 run: bash scripts/check_install_export.sh + # The same check with morph::morph built as a shared library: the + # installed package must carry the shared target and a consumer must + # link and run against it. + - name: Install morph as a shared library and build a consumer against the prefix + env: + CC: gcc-15 + CXX: g++-15 + run: bash scripts/check_install_export.sh --shared + # ── The master compiler cache ───────────────────────────────────────── # Merges the entries every Linux job used on this push into the one cache # entry all jobs restore, then deletes every older sccache entry. Runs after diff --git a/CMakeLists.txt b/CMakeLists.txt index 42e48515c..aae1fd063 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -32,6 +32,32 @@ if(CMAKE_GENERATOR MATCHES "Ninja" AND MORPH_LINK_JOBS GREATER 0) endif() option(MORPH_BUILD_TESTS "Build tests" ON) +option(MORPH_BUILD_SHARED "Build morph::morph as a shared library (MORPH_API marks what it exports; symbols are hidden by default)" OFF) +# A shared morph links a shared core-cpp (CORE_CPP_BUILD_SHARED): core-cpp keeps +# process and thread state of its own, such as the current executor, and a +# static copy in both libmorph and the executable would be two. Static +# libraries this tree links into the shared morph are position-independent. +if(MORPH_BUILD_SHARED) + set(CMAKE_POSITION_INDEPENDENT_CODE ON) + # Windows finds a DLL only beside the executable (or on PATH), and a test + # binary also runs at build time, to list its cases. One flat directory for + # every executable, morph.dll and core-cpp's DLLs is what makes both work. + if(WIN32 AND NOT CMAKE_RUNTIME_OUTPUT_DIRECTORY) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin") + endif() + # An installed libmorph needs core-cpp's libraries, and each of those needs + # the others; all are installed into one directory. A search path relative + # to the library itself finds them wherever the prefix lands, instead of + # relying on the program's own search path, which the loader does not apply + # to a library's dependencies. + if(NOT DEFINED CMAKE_INSTALL_RPATH) + if(APPLE) + set(CMAKE_INSTALL_RPATH "@loader_path") + elseif(UNIX) + set(CMAKE_INSTALL_RPATH "$ORIGIN") + endif() + endif() +endif() option(MORPH_BUILD_EXAMPLES "Build examples" ON) option(MORPH_BUILD_BANK_EXAMPLE "Build the SQLite/Lightweight bank example (heavy deps)" OFF) option(MORPH_BUILD_HMAC_EXAMPLES "Build vetted-HMAC adapter examples (libsodium/OpenSSL, heavy deps)" OFF) @@ -350,7 +376,7 @@ endif() # is off while morph installs: CMake leaves an excluded subdirectory's install # rules out of the parent's install, so `cmake --install` would install # morph's package without the core-cpp package it depends on. -set(MORPH_CORE_CPP_VERSION 0.21) +set(MORPH_CORE_CPP_VERSION 0.22) option(MORPH_INSTALL "Generate morph's install and export rules" ${PROJECT_IS_TOP_LEVEL}) if(NOT DEFINED AF_SANITIZER) find_package(core-cpp ${MORPH_CORE_CPP_VERSION} CONFIG QUIET) @@ -369,17 +395,36 @@ if(NOT core-cpp_FOUND) CPMAddPackage( NAME core-cpp GITHUB_REPOSITORY contour-terminal/core-cpp - GIT_TAG v0.21.0 - VERSION 0.21.0 + GIT_TAG v0.22.0 + VERSION 0.22.0 SYSTEM YES EXCLUDE_FROM_ALL ${_morph_core_cpp_exclude_from_all} OPTIONS "CORE_CPP_TESTING OFF" "CORE_CPP_BUILD_EXAMPLES OFF" "CORE_CPP_WITH_TUI ${MORPH_BUILD_TUI}" "CORE_CPP_WITH_IMAGES OFF" "CORE_CPP_WITH_TLS OFF" "CORE_CPP_WITH_SYSTEMD OFF" "CORE_CPP_FETCH_DEPS OFF" - "CORE_CPP_INSTALL ${MORPH_INSTALL}") + "CORE_CPP_INSTALL ${MORPH_INSTALL}" "CORE_CPP_BUILD_SHARED ${MORPH_BUILD_SHARED}") unset(_morph_core_cpp_exclude_from_all) endif() +# A shared morph needs a shared core-cpp, and one found installed may be static. +# Linked anyway, libmorph and the executable would each carry core-cpp's state, +# and an executor scope one of them enters would be invisible to the other. +if(MORPH_BUILD_SHARED) + get_target_property(_morph_core_cpp_type core::base TYPE) + if(NOT _morph_core_cpp_type STREQUAL "SHARED_LIBRARY") + if(core-cpp_FOUND) + set(_morph_core_cpp_from "the installed one at ${core-cpp_DIR}") + else() + set(_morph_core_cpp_from "the one fetched into this build") + endif() + message(FATAL_ERROR + "MORPH_BUILD_SHARED=ON needs a shared core-cpp, but ${_morph_core_cpp_from} is ${_morph_core_cpp_type}. " + "Install a core-cpp built with CORE_CPP_BUILD_SHARED=ON, or take it off CMAKE_PREFIX_PATH so morph " + "fetches one.") + endif() + unset(_morph_core_cpp_type) +endif() + # A core-cpp found installed brings whatever modules it was built with. One # built with CORE_CPP_WITH_TUI=OFF has no core::tui, and morph::tui would fail # much later, at link time, naming a target nobody created. @@ -419,11 +464,17 @@ if(NOT WIN32 AND NOT EMSCRIPTEN) endif() # ── Library target ─────────────────────────────────────────────────────────── -# A static library: the templates and the macro-sensitive core headers stay in -# headers, and what does not depend on a consumer's configuration is compiled -# once, in src/ui. +# Static by default, shared with MORPH_BUILD_SHARED: the templates and the +# macro-sensitive core headers stay in headers, and what does not depend on a +# consumer's configuration is compiled once, in src/ui. include(GenerateExportHeader) -add_library(morph STATIC +if(MORPH_BUILD_SHARED) + set(_morph_library_type SHARED) +else() + set(_morph_library_type STATIC) +endif() +add_library(morph ${_morph_library_type} + src/ui/process_state.cpp src/ui/document.cpp src/ui/expression.cpp src/ui/interpreter.cpp @@ -467,13 +518,30 @@ endif() # MORPH_API marks what a consumer calls into the compiled library. A static # build defines MORPH_STATIC_DEFINE for the library and its consumers, which -# makes the macro empty. +# makes the macro empty. A shared build hides every symbol that MORPH_API does +# not mark, on every platform, so a missing mark is a link error on Linux too +# and not only on Windows. generate_export_header(morph BASE_NAME MORPH EXPORT_MACRO_NAME MORPH_API EXPORT_FILE_NAME "${CMAKE_CURRENT_BINARY_DIR}/generated/morph/export.hpp" ) -target_compile_definitions(morph PUBLIC MORPH_STATIC_DEFINE) +if(MORPH_BUILD_SHARED) + set_target_properties(morph PROPERTIES + CXX_VISIBILITY_PRESET hidden + VISIBILITY_INLINES_HIDDEN ON + ) + if(MSVC) + # C4251 and C4275 fire on an exported class whose member or base is a + # standard-library type. Those types are header-defined and compiled + # identically on both sides under one toolchain version, which is the + # only combination a DLL and its consumer are supported in, so the + # warning reports nothing actionable. + target_compile_options(morph PUBLIC /wd4251 /wd4275) + endif() +else() + target_compile_definitions(morph PUBLIC MORPH_STATIC_DEFINE) +endif() apply_warnings(morph) # Every consumer of this archive carries an AF_SANITIZER block of its own, which is what makes instrumenting a static # library safe: the link options are PRIVATE and do not propagate out of a static library. @@ -1323,6 +1391,8 @@ if(MORPH_INSTALL) FILE_SET morph_detail_headers DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" FILE_SET morph_generated_headers DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" + LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" + RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" ) # Optional components ship only when this configuration actually created diff --git a/CMakePresets.json b/CMakePresets.json index 5e9a80bdc..6d09495d6 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -93,6 +93,20 @@ "binaryDir": "${sourceDir}/build/clangcl-release", "cacheVariables": { "CMAKE_BUILD_TYPE": "Release" } }, + { + "name": "cl-shared-debug", + "displayName": "Debug, morph as a shared library (MSVC)", + "inherits": "cl-debug", + "binaryDir": "${sourceDir}/build/cl-shared-debug", + "cacheVariables": { "MORPH_BUILD_SHARED": "ON" } + }, + { + "name": "clangcl-shared-debug", + "displayName": "Debug, morph as a shared library (clang-cl)", + "inherits": "clangcl-debug", + "binaryDir": "${sourceDir}/build/clangcl-shared-debug", + "cacheVariables": { "MORPH_BUILD_SHARED": "ON" } + }, { "name": "windows-everything", "displayName": "Every optional feature (clang-cl release, Windows)", @@ -143,6 +157,13 @@ "binaryDir": "${sourceDir}/build/clang-release", "cacheVariables": { "CMAKE_BUILD_TYPE": "Release" } }, + { + "name": "clang-shared-debug", + "displayName": "Debug, morph as a shared library (Clang, Linux)", + "inherits": "clang-debug", + "binaryDir": "${sourceDir}/build/clang-shared-debug", + "cacheVariables": { "MORPH_BUILD_SHARED": "ON" } + }, { "name": "linux-everything", "displayName": "Every optional feature (Clang release, Linux)", @@ -212,11 +233,14 @@ { "name": "cl-qt-release", "configurePreset": "cl-qt-release", "jobs": 0 }, { "name": "clangcl-debug", "configurePreset": "clangcl-debug", "jobs": 0 }, { "name": "clangcl-release", "configurePreset": "clangcl-release", "jobs": 0 }, + { "name": "cl-shared-debug", "configurePreset": "cl-shared-debug", "jobs": 0 }, + { "name": "clangcl-shared-debug", "configurePreset": "clangcl-shared-debug", "jobs": 0 }, { "name": "windows-everything", "configurePreset": "windows-everything", "jobs": 0 }, { "name": "gcc-debug", "configurePreset": "gcc-debug", "jobs": 0 }, { "name": "gcc-release", "configurePreset": "gcc-release", "jobs": 0 }, { "name": "clang-debug", "configurePreset": "clang-debug", "jobs": 0 }, { "name": "clang-release", "configurePreset": "clang-release", "jobs": 0 }, + { "name": "clang-shared-debug", "configurePreset": "clang-shared-debug", "jobs": 0 }, { "name": "linux-everything", "configurePreset": "linux-everything", "jobs": 0 }, { "name": "clang-asan", "configurePreset": "clang-asan", "jobs": 0 }, { "name": "clang-tsan", "configurePreset": "clang-tsan", "jobs": 0 }, @@ -235,11 +259,14 @@ { "name": "cl-qt-debug", "configurePreset": "cl-qt-debug", "inherits": "base-test" }, { "name": "cl-qt-release", "configurePreset": "cl-qt-release", "inherits": "base-test" }, { "name": "clangcl-debug", "configurePreset": "clangcl-debug", "inherits": "base-test" }, + { "name": "cl-shared-debug", "configurePreset": "cl-shared-debug", "inherits": "base-test" }, + { "name": "clangcl-shared-debug", "configurePreset": "clangcl-shared-debug", "inherits": "base-test" }, { "name": "windows-everything","configurePreset": "windows-everything","inherits": "base-test" }, { "name": "gcc-debug", "configurePreset": "gcc-debug", "inherits": "base-test" }, { "name": "gcc-release", "configurePreset": "gcc-release", "inherits": "base-test" }, { "name": "clang-debug", "configurePreset": "clang-debug", "inherits": "base-test" }, { "name": "clang-release", "configurePreset": "clang-release", "inherits": "base-test" }, + { "name": "clang-shared-debug", "configurePreset": "clang-shared-debug", "inherits": "base-test" }, { "name": "linux-everything", "configurePreset": "linux-everything", "inherits": "base-test" }, { "name": "clang-asan", diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index aa883be47..1f7c2110b 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -4,7 +4,7 @@ `morph` is a typed, asynchronous bridge between a GUI thread and business-object models. Models may live in-process (local mode) or in a remote server process (remote mode). The GUI code is identical in both cases — only the backend implementation changes. -The core library, `morph::morph`, is a compiled static library (C++23, namespace `morph`); its templates and the macro-sensitive core headers stay in headers. It depends on Glaze for JSON reflection and on [core-cpp](https://github.com/contour-terminal/core-cpp) for its event-loop timers, base64 and wakeup primitive; core-cpp's `core::base`, `core::net` and `core::platform` are static libraries, so a project that links `morph::morph` also builds those. The optional parts are separate targets, and some are compiled: the Qt integration (`morph::qt`), the terminal frontend (`morph::tui`), the Qt Quick frontend (`morph::qt_quick`) and the generic client (`morph::client`) are static libraries with sources under `src/`. +The core library, `morph::morph`, is a compiled library (C++23, namespace `morph`), static by default and shared with `MORPH_BUILD_SHARED=ON`; its templates and the macro-sensitive core headers stay in headers. It depends on Glaze for JSON reflection and on [core-cpp](https://github.com/contour-terminal/core-cpp) for its event-loop timers, base64 and wakeup primitive; core-cpp's `core::base`, `core::net` and `core::platform` are static libraries, so a project that links `morph::morph` also builds those. The optional parts are separate targets, and some are compiled: the Qt integration (`morph::qt`), the terminal frontend (`morph::tui`), the Qt Quick frontend (`morph::qt_quick`) and the generic client (`morph::client`) are static libraries with sources under `src/`. > **New to morph?** `docs/GETTING-STARTED.md` is the step-by-step tutorial that > comes before this document: it builds one small app end to end diff --git a/docs/BUILDING.md b/docs/BUILDING.md index c70ad5e3d..158e8c74c 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -9,10 +9,11 @@ - **[Glaze](https://github.com/stephenberry/glaze) 7.4** for JSON reflection, found with `find_package` (for example from the `vcpkg.json` manifest) or fetched through CPM. -- **[core-cpp](https://github.com/contour-terminal/core-cpp) 0.21**, fetched +- **[core-cpp](https://github.com/contour-terminal/core-cpp) 0.22**, fetched through CPM. morph's timers run on its event loop, coroutines build on its `Task`, and `morph::net` takes its base64 and wakeup primitive from it. - `morph::morph` is a static library (templates and the macro-sensitive core + `morph::morph` is a static library by default, or a shared one with + `MORPH_BUILD_SHARED=ON` (templates and the macro-sensitive core headers stay in headers), and `core::base`, `core::net` and `core::platform` are static libraries too, so a project that links `morph::morph` builds them too. @@ -43,6 +44,7 @@ need `VCPKG_ROOT` set. | Option | Default | What it builds | |---|---|---| | `MORPH_BUILD_TESTS` | `ON` | The unit tests | +| `MORPH_BUILD_SHARED` | `OFF` | Build `morph::morph` as a shared library. Every symbol is hidden unless `MORPH_API` marks it, on every platform; see below | | `MORPH_BUILD_EXAMPLES` | `ON` | The dependency-free examples (forms, concepts, gallery, LIMS gallery); the generic client when a frontend is on | | `MORPH_BUILD_CLIENT` | `ON` | `morph::client`, the generic client's source and shell | | `MORPH_BUILD_QT` | `OFF` | The Qt 6 WebSocket transport and executor | @@ -123,6 +125,18 @@ next to morph's. target. `MORPH_INSTALL` defaults to `PROJECT_IS_TOP_LEVEL`, so a vendored morph adds nothing to your project's install. +### Building morph as a shared library + +`-DMORPH_BUILD_SHARED=ON` builds `morph::morph` as a shared library (`libmorph.so`, `morph.dll`). The library is +compiled with hidden symbol visibility, so what a consumer can call is exactly what `MORPH_API` +(``) marks, on Linux and Windows alike. The process-wide state that header code reaches through a +function (the registries, the logger, the thread-local dispatch slots) is defined in the library, so the library and +the executable share one copy. core-cpp is built shared too (`CORE_CPP_BUILD_SHARED`), for the same reason: it keeps +process and thread state of its own, such as the current executor. A configure that finds an installed static core-cpp +stops and says so. On Windows every executable, `morph.dll` and core-cpp's DLLs go to `/bin`, because Windows loads a DLL only from beside the +executable. `find_package(morph CONFIG)` works in both modes; an installed shared `morph` is found with its +`libmorph.so` or `morph.dll`. + ### A bare include path (not supported) `-I/include` is not enough: morph::morph is a compiled static library, and diff --git a/include/morph/core/bridge.hpp b/include/morph/core/bridge.hpp index a43662452..7d494238a 100644 --- a/include/morph/core/bridge.hpp +++ b/include/morph/core/bridge.hpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -139,7 +140,7 @@ class ActionExecuteRegistry { /// @brief Returns the process-level singleton registry. /// @return Reference to the singleton `ActionExecuteRegistry`. - static ActionExecuteRegistry& instance(); + MORPH_API static ActionExecuteRegistry& instance(); private: // The stored key: the registry owns its ids, because nothing else outlives @@ -206,11 +207,6 @@ class ActionExecuteRegistry { std::unordered_map _types; }; -inline ActionExecuteRegistry& ActionExecuteRegistry::instance() { - static ActionExecuteRegistry inst; - return inst; -} - } // namespace morph::bridge namespace morph::model::detail { diff --git a/include/morph/core/detail/owner_probe.hpp b/include/morph/core/detail/owner_probe.hpp index e3db4990d..3ee94571e 100644 --- a/include/morph/core/detail/owner_probe.hpp +++ b/include/morph/core/detail/owner_probe.hpp @@ -5,6 +5,7 @@ #include #include #include +#include /// @file /// @brief The check every loop-owned body makes on entry: "am I on my owner?" @@ -28,10 +29,7 @@ using OwnerProbe = void (*)(char const* site, ::core::async::IExecutor const& ow /// @brief The installed probe, or null. /// @return The process-wide probe slot. -[[nodiscard]] inline std::atomic& ownerProbe() noexcept { - static std::atomic probe{nullptr}; - return probe; -} +[[nodiscard]] MORPH_API std::atomic& ownerProbe() noexcept; /// @brief Records that @p site is running a body that must run on @p owner. /// diff --git a/include/morph/core/detail/result_walker.hpp b/include/morph/core/detail/result_walker.hpp index 46f33f3b0..164d8d531 100644 --- a/include/morph/core/detail/result_walker.hpp +++ b/include/morph/core/detail/result_walker.hpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -187,10 +188,7 @@ template /// @brief The process-level map of action result slots, filled by static registrars. /// @return The mutable map. -inline ActionResultSlotMap& mutableActionResultSlots() { - static ActionResultSlotMap entries; - return entries; -} +MORPH_API ActionResultSlotMap& mutableActionResultSlots(); /// @brief Every registered action's result slots, by action id. /// @return The map, unmatched against records. @@ -198,10 +196,7 @@ inline ActionResultSlotMap const& actionResultSlots() { return mutableActionResu /// @brief The process-level list of action ids registered by more than one action type. /// @return The mutable list. -inline std::vector& mutableActionResultConflicts() { - static std::vector ids; - return ids; -} +MORPH_API std::vector& mutableActionResultConflicts(); /// @brief The action ids that a second, different action type registered under. /// diff --git a/include/morph/core/detail/task_handler.hpp b/include/morph/core/detail/task_handler.hpp index 81fe8f7cc..5e62bedb6 100644 --- a/include/morph/core/detail/task_handler.hpp +++ b/include/morph/core/detail/task_handler.hpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -146,10 +147,7 @@ class ActionGate { [[nodiscard]] static std::size_t overlapsObserved() noexcept { return overlapCounter().load(); } private: - static std::atomic& overlapCounter() noexcept { - static std::atomic counter{0}; - return counter; - } + MORPH_API static std::atomic& overlapCounter() noexcept; /// Marks the calling thread as inside the gate for the scope's lifetime, /// and counts it if another thread already is. Reentry on the same thread, diff --git a/include/morph/core/effects.hpp b/include/morph/core/effects.hpp index af7618df4..1ad493be4 100644 --- a/include/morph/core/effects.hpp +++ b/include/morph/core/effects.hpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -260,10 +261,7 @@ inline void addAddedEffects(AddedEffectsMap& map, std::string_view actionId, /// @brief The process-level effects registry, appended to by static registrars. /// @return The mutable map. -inline EffectsMap& mutableEffectsRegistry() { - static EffectsMap entries; - return entries; -} +MORPH_API EffectsMap& mutableEffectsRegistry(); /// @brief Static-init helper for `BRIDGE_REGISTER_EFFECTS`. /// @tparam Action The action type; `ActionTraits` must be visible. @@ -285,10 +283,7 @@ inline bool registerEffectsOnce() noexcept { /// @brief The process-level list of time-derived facts, appended to by static registrars. /// @return The mutable list. -inline std::vector& mutableChangeTimesRegistry() { - static std::vector entries; - return entries; -} +MORPH_API std::vector& mutableChangeTimesRegistry(); /// @brief Adds a time-derived fact, unless an equal one is already there. /// @param list The registry to add to. @@ -327,10 +322,7 @@ inline bool registerChangeTimeOnce() noexcept { /// @brief The process-level registry of added effects, appended to by static registrars. /// @return The mutable map. -inline AddedEffectsMap& mutableAddedEffectsRegistry() { - static AddedEffectsMap entries; - return entries; -} +MORPH_API AddedEffectsMap& mutableAddedEffectsRegistry(); /// @brief Static-init helper for `BRIDGE_ADD_EFFECTS`. /// @tparam Action The action type; `ActionTraits` must be visible. @@ -691,28 +683,7 @@ inline void findDerivationCycles(std::vector const& records, /// on every call. /// @return The resolved registries. /// @throws morph::model::EffectsRegistrationError when the registered configuration is invalid. -[[nodiscard]] inline Resolved const& resolved() { - model::detail::noteRegistryRead(true); - struct State { - std::once_flag once; - std::optional value; - std::optional error; - }; - static State state; - std::call_once(state.once, [] { - try { - state.value.emplace(resolve(record::detail::recordRegistry(), model::detail::actionResultSlots(), - mutableEffectsRegistry(), model::detail::actionResultConflicts(), - mutableAddedEffectsRegistry(), mutableChangeTimesRegistry())); - } catch (model::EffectsRegistrationError const& error) { - state.error.emplace(error); - } - }); - if (state.error) { - throw *state.error; - } - return *state.value; -} +[[nodiscard]] MORPH_API Resolved const& resolved(); } // namespace detail diff --git a/include/morph/core/executor.hpp b/include/morph/core/executor.hpp index d61419c55..fc2b344ce 100644 --- a/include/morph/core/executor.hpp +++ b/include/morph/core/executor.hpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include #include @@ -404,10 +405,7 @@ class InlineExecutor : public IExecutor { /// A function-local static, so it is constructed on first use and outlives /// everything built over it. /// @return Reference to the shared inline executor. -inline IExecutor& inlineExecutor() { - static InlineExecutor executor; - return executor; -} +MORPH_API IExecutor& inlineExecutor(); } // namespace detail diff --git a/include/morph/core/logger.hpp b/include/morph/core/logger.hpp index 1aaf2648a..90af82de0 100644 --- a/include/morph/core/logger.hpp +++ b/include/morph/core/logger.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -128,10 +129,7 @@ struct LogState { std::atomic dropped{0}; }; -inline LogState& logState() { - static LogState state; - return state; -} +MORPH_API LogState& logState(); /// @brief Internal emit entry point used by the public level helpers. /// diff --git a/include/morph/core/observability.hpp b/include/morph/core/observability.hpp index 88a8352e9..cefc72e79 100644 --- a/include/morph/core/observability.hpp +++ b/include/morph/core/observability.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -105,10 +106,7 @@ struct ObserveState { /// @brief Returns the process-wide `ObserveState` singleton (Meyers singleton, /// thread-safe first-use construction — mirrors `morph::log::detail::logState`). -inline ObserveState& observeState() { - static ObserveState state; - return state; -} +MORPH_API ObserveState& observeState(); /// @brief Emits @p metric if a sink is installed; a single relaxed atomic load /// (no mutex, no `MetricEvent` construction) if not. diff --git a/include/morph/core/records.hpp b/include/morph/core/records.hpp index 6f919cde8..eebf236af 100644 --- a/include/morph/core/records.hpp +++ b/include/morph/core/records.hpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include #include @@ -181,10 +182,7 @@ void applyKey(RecordInfo& info) { /// @brief The process-level record list, appended to by static registrars. /// @return The mutable list. -inline std::vector& mutableRecordRegistry() { - static std::vector entries; - return entries; -} +MORPH_API std::vector& mutableRecordRegistry(); /// @brief The records declared so far, raw and unvalidated. /// @return The entries in registration order. diff --git a/include/morph/core/registry.hpp b/include/morph/core/registry.hpp index b06055060..182297a59 100644 --- a/include/morph/core/registry.hpp +++ b/include/morph/core/registry.hpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -75,10 +76,7 @@ namespace detail { /// /// @return Reference to the process-wide flag; `true` once the registration /// phase has closed. -[[nodiscard]] inline std::atomic& registrationPhaseFlag() noexcept { - static std::atomic closed{false}; - return closed; -} +[[nodiscard]] MORPH_API std::atomic& registrationPhaseFlag() noexcept; } // namespace detail @@ -747,9 +745,16 @@ template return kDesc; } -// Forward declarations so instance() methods inside the classes can reference them. -inline class ActionDispatcher& defaultDispatcher(); -inline class ModelRegistryFactory& defaultRegistry(); +class ActionDispatcher; +class ModelRegistryFactory; + +/// @brief Returns the process-level `ActionDispatcher` singleton. +/// @return The one dispatcher shared by every module of the process. +MORPH_API ActionDispatcher& defaultDispatcher(); + +/// @brief Returns the process-level `ModelRegistryFactory` singleton. +/// @return The one registry shared by every module of the process. +MORPH_API ModelRegistryFactory& defaultRegistry(); /// @brief Registry that maps (modelId, actionId) pairs to type-erased runner functions. /// @@ -1535,18 +1540,6 @@ class ModelRegistryFactory { std::unordered_map _types; }; -/// @brief Returns the process-level `ActionDispatcher` singleton. -inline ActionDispatcher& defaultDispatcher() { - static ActionDispatcher inst; - return inst; -} - -/// @brief Returns the process-level `ModelRegistryFactory` singleton. -inline ModelRegistryFactory& defaultRegistry() { - static ModelRegistryFactory inst; - return inst; -} - // The three `register*Once` helpers are `noexcept` while allocating, and that // is a decision rather than an oversight. Their only caller is the // initialiser of a namespace-scope variable generated by `BRIDGE_REGISTER_*`, diff --git a/include/morph/forms/views.hpp b/include/morph/forms/views.hpp index 8345aa7f7..5c913d139 100644 --- a/include/morph/forms/views.hpp +++ b/include/morph/forms/views.hpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -619,10 +620,7 @@ class ViewRegistry { /// @brief Returns the process-level singleton registry. /// @return Reference to the singleton. - static ViewRegistry& instance() { - static ViewRegistry inst; - return inst; - } + MORPH_API static ViewRegistry& instance(); private: std::unordered_map> _providers; diff --git a/include/morph/journal/action_log.hpp b/include/morph/journal/action_log.hpp index 33e200baf..beb25a851 100644 --- a/include/morph/journal/action_log.hpp +++ b/include/morph/journal/action_log.hpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -394,10 +395,7 @@ namespace detail { /// @brief Process-wide slot holding the default action log, plus the mutex /// guarding it. A function-local static, not a namespace-scope global, /// so it's safe regardless of translation-unit init order. -inline std::pair>& defaultActionLogState() { - static std::pair> state; - return state; -} +MORPH_API std::pair>& defaultActionLogState(); } // namespace detail diff --git a/include/morph/journal/journal.hpp b/include/morph/journal/journal.hpp index 0bf9a33a6..51558bd13 100644 --- a/include/morph/journal/journal.hpp +++ b/include/morph/journal/journal.hpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #include #include @@ -155,10 +156,7 @@ class PayloadMigrationRegistry { /// @brief Returns the process-level migration registry `replay()` uses by /// default. Empty until an application adds to it. /// @return Reference to the process-wide registry. -[[nodiscard]] inline PayloadMigrationRegistry& defaultPayloadMigrations() { - static PayloadMigrationRegistry registry; - return registry; -} +[[nodiscard]] MORPH_API PayloadMigrationRegistry& defaultPayloadMigrations(); namespace detail { @@ -171,10 +169,7 @@ namespace detail { /// plus an RAII guard that restores the previous value on scope exit), applied /// to a `bool` instead of a `const Context*`. Model/rule code never touches /// this directly; it reads the public accessor `isReplaying()`. -inline bool& tlsIsReplaying() { - thread_local bool tls = false; - return tls; -} +MORPH_API bool& tlsIsReplaying(); /// @brief RAII helper that sets the thread-local replay flag for its scope, /// restoring the previous value on destruction. diff --git a/include/morph/session/session.hpp b/include/morph/session/session.hpp index c7ed5b872..9867c86cc 100644 --- a/include/morph/session/session.hpp +++ b/include/morph/session/session.hpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -311,10 +312,7 @@ struct AllowAllAuthorizer : IAuthorizer { }; /// @brief Returns the process-wide allow-all authorizer (used as the default). -inline std::shared_ptr allowAllAuthorizer() { - static auto instance = std::make_shared(); - return instance; -} +MORPH_API std::shared_ptr allowAllAuthorizer(); namespace detail { @@ -325,10 +323,7 @@ namespace detail { /// `ScopedContext` that clears it again on scope exit. `ActionDispatcher::dispatch` /// itself does not touch this pointer. Models that opt in to session-aware logic /// call `current()` to read it. -inline const Context*& tlsCurrent() { - thread_local const Context* tls = nullptr; - return tls; -} +MORPH_API const Context*& tlsCurrent(); /// @brief RAII helper that sets the thread-local `Context` for its scope. class ScopedContext { @@ -349,10 +344,7 @@ class ScopedContext { /// @brief Thread-local pointer to the `RunOrigin` of the currently dispatched action. /// @return The slot; it holds null for a run the server gave no origin. -inline const RunOrigin*& tlsOrigin() { - thread_local const RunOrigin* tls = nullptr; - return tls; -} +MORPH_API const RunOrigin*& tlsOrigin(); /// @brief RAII helper that sets the thread-local `RunOrigin` for its scope. class ScopedOrigin { diff --git a/include/morph/session/session_auth.hpp b/include/morph/session/session_auth.hpp index 8178a83d8..d19c0e98a 100644 --- a/include/morph/session/session_auth.hpp +++ b/include/morph/session/session_auth.hpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -631,10 +632,7 @@ class SigningAuthorizer : public IAuthorizer { }; /// @brief The verification the running `admit` on this thread made, if any. - static const Verification*& active() noexcept { - thread_local const Verification* current = nullptr; - return current; - } + MORPH_API static const Verification*& active() noexcept; /// @brief Installs a verification for the length of one `admit`, and /// restores the one it replaced, on return or on a throw. diff --git a/include/morph/ui/author.hpp b/include/morph/ui/author.hpp index 34afeefbb..b9c46ba09 100644 --- a/include/morph/ui/author.hpp +++ b/include/morph/ui/author.hpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -6185,10 +6186,7 @@ class ScreenRegistry { /// @brief The process's screen registry, which `MORPH_REGISTER_SCREEN` enrols into. /// @return The registry. -[[nodiscard]] inline ScreenRegistry& screenRegistry() noexcept { - static ScreenRegistry registry; - return registry; -} +[[nodiscard]] MORPH_API ScreenRegistry& screenRegistry() noexcept; /// @brief Enrols a screen into the process's registry; what `MORPH_REGISTER_SCREEN` runs. /// @tparam Make A callable that returns the `Screen`. diff --git a/include/morph/ui/interpreter.hpp b/include/morph/ui/interpreter.hpp index 5d3e97c80..6f613c37e 100644 --- a/include/morph/ui/interpreter.hpp +++ b/include/morph/ui/interpreter.hpp @@ -2567,7 +2567,9 @@ class MORPH_API Screen { friend class Interpreter; friend class Inspector; - Screen() = default; + // Out of line: an exported class emits its inline members in every module, and this one destroys a + // `std::unique_ptr` on a throw, which needs `Mounted` complete. + Screen(); /// Evaluates a head expression of runs; a run the head cannot read is dropped and reported. [[nodiscard]] std::vector headSpans(ExprPtr const& expr) const; @@ -2627,7 +2629,7 @@ class MORPH_API Screen { /// a binding on one updates, and `{"set": "app.name", …}` writes the app document's state. A query of the app /// document runs once however many screens read it. Destroying the root runs its `onUnmount`, takes its scope off the /// session and releases its model instances; a host does that before it clears the session on sign-out. -class AppRoot { +class MORPH_API AppRoot { public: AppRoot(AppRoot const&) = delete; AppRoot& operator=(AppRoot const&) = delete; diff --git a/include/morph/ui/shell_frame.hpp b/include/morph/ui/shell_frame.hpp index 6d873a971..a56531ed8 100644 --- a/include/morph/ui/shell_frame.hpp +++ b/include/morph/ui/shell_frame.hpp @@ -321,7 +321,7 @@ class MORPH_API ShellFrame { }; // The widgets of one results column, a panel under the field or the compact overlay's body. - struct MORPH_API ResultsColumn { + struct ResultsColumn { std::vector> texts; std::vector rows; void clear(); diff --git a/include/morph/util/datetime.hpp b/include/morph/util/datetime.hpp index 016d18497..c9ea5dd1d 100644 --- a/include/morph/util/datetime.hpp +++ b/include/morph/util/datetime.hpp @@ -38,6 +38,7 @@ #include #include #include +#include #include #include #include @@ -52,15 +53,15 @@ namespace detail { /// @brief Process-wide override for `DateTime::now()`, guarded by a mutex. /// -/// Mirrors `morph::journal::detail::defaultActionLogState()` — the same -/// "mutex-guarded function-local static" shape used for the action-log and -/// logger override seams elsewhere in the codebase. An empty `std::function` -/// (the default) means "no override installed"; `DateTime::now()` falls back -/// to `std::chrono::system_clock::now()` in that case. Forward-declared here -/// (before `DateTime` is a complete type -- a function signature only needs -/// `DateTime` to be declared, not defined) and defined out-of-line just after -/// the `DateTime` struct, before `DateTime::now()`'s first caller needs it. -[[nodiscard]] std::pair>& nowOverrideState(); +/// Mirrors `morph::journal::detail::defaultActionLogState()`. An empty +/// `std::function` (the default) means "no override installed"; +/// `DateTime::now()` falls back to `std::chrono::system_clock::now()` in that +/// case. Defined in the compiled library, so a shared morph and the program +/// using it see one override rather than one each. Declared before `DateTime` +/// is complete: a function signature only needs `DateTime` declared. +/// @return Reference to the process-wide `(mutex, override callable)` pair; +/// the callable is empty when no override is installed. +[[nodiscard]] MORPH_API std::pair>& nowOverrideState(); } // namespace detail @@ -283,21 +284,6 @@ struct DateTime { } }; -namespace detail { - -/// @brief Function-local static backing `DateTime::now()`'s override seam. -/// -/// Defined out-of-line (after `DateTime` is a complete type) since the state -/// is keyed on `std::function`. -/// @return Reference to the process-wide `(mutex, override callable)` pair; -/// the callable is empty when no override is installed. -inline std::pair>& nowOverrideState() { - static std::pair> state; - return state; -} - -} // namespace detail - /// @brief Installs @p clock as the process-wide override for `DateTime::now()` /// (and therefore `Timestamp::now()`, which delegates to it). /// diff --git a/include/morph/util/rational.hpp b/include/morph/util/rational.hpp index 1a7fdae40..6a2480ccd 100644 --- a/include/morph/util/rational.hpp +++ b/include/morph/util/rational.hpp @@ -106,6 +106,7 @@ #include #include #include +#include #include #include #include @@ -197,10 +198,7 @@ namespace detail { /// @brief Per-thread clamp counter, scoped by `WireClampScope`. /// @return Reference to this thread's counter. -[[nodiscard]] inline std::size_t& wireClampCounter() noexcept { - static thread_local std::size_t clamped = 0; - return clamped; -} +[[nodiscard]] MORPH_API std::size_t& wireClampCounter() noexcept; } // namespace detail diff --git a/scripts/branch_partial_allowlist.json b/scripts/branch_partial_allowlist.json index f0a8c7ca3..fe5fb0d2e 100644 --- a/scripts/branch_partial_allowlist.json +++ b/scripts/branch_partial_allowlist.json @@ -41,57 +41,57 @@ "entries": [ { "file": "include/morph/util/rational.hpp", - "line": 272, + "line": 270, "source": "assert(rawDecimalPlaces <= kMaxDecimalPlaces);", "reason": "assert()'s false arm calls abort(). Reaching it means violating the precondition and terminating the process, so no test in a Catch2 binary can observe it and still report; a death test would prove only that assert() works. The decision the assert guards is checked by the caller-side tests that stay inside kMaxDecimalPlaces." }, { "file": "include/morph/util/rational.hpp", - "line": 851, + "line": 849, "source": "if (!std::is_constant_evaluated()) {", "context": "/// @brief Logs an overflow that `operator+=`/`-=`/`*=` saturated instead", "reason": "The false arm is the constant-evaluated one, and constant evaluation does not execute instrumented code -- no counter can increment during it. So in every run this branch is true, structurally, and its other arm is not a gap in the tests but a gap in what runtime instrumentation can see. reportOverflow's constexpr behaviour is exercised by the constexpr Rational arithmetic in tests/test_rational.cpp; what cannot be exercised is llvm-cov's counter." }, { "file": "include/morph/util/rational.hpp", - "line": 885, + "line": 883, "source": "if (!std::is_constant_evaluated()) {", "context": "[[nodiscard]] constexpr int compareForSaturation(const Rational& rhs, bool addition) const noexcept {", "reason": "reportClamp's copy of the same shape as line 851 above, and uncoverable for the same reason: the untaken arm is constant evaluation, which increments no counters." }, { "file": "include/morph/util/datetime.hpp", - "line": 161, + "line": 162, "source": "if (!allowSign && count > 0 && offset < text.size() && (text[offset] == '-' || text[offset] == '+')) {", "reason": "Both the `count > 0` false arm and the `offset < text.size()` false arm are unreachable. This lambda has exactly 6 call sites, all in fromIso8601 (lines 180-185), each passing a literal `count` of 4 (year, allowSign=true) or 2 (month/day/hour/minute/second, allowSign=false); `count > 0` is a compile-time-true invariant of every call site, never 0. `offset < text.size()` is likewise always true whenever this branch even executes (it is gated by `!allowSign`): every allowSign=false call site has `offset + count <= 19` (offsets 5/8/11/14/17, each with count=2, so max offset+count is 19), and the function already returns std::nullopt earlier if `text.size() < 19`. So by the time any allowSign=false call runs, text.size() >= 19 >= offset + count, making `offset < text.size()` always true. Both are defensive bounds-checks inside a private lambda whose only callers are fixed, audited literals -- there is no way to reach either false arm without changing the call sites themselves." }, { "file": "include/morph/util/rational.hpp", - "line": 911, + "line": 909, "source": "return std::is_gt(ordering) ? 1 : 0;", "reason": "The false arm (a tie, returning 0) is unreachable. compareForSaturation has exactly two call sites, both from the saturating branch of operator+=/operator-=, and both are guarded by addWouldOverflow/subWouldOverflow having just returned true. A tie in compareForSaturation (*this == -rhs for +=, or *this == rhs for -=) requires -- since operator== compares canonical numerator/denominator pairs directly -- identical denominators. With equal denominators, addWouldOverflow/subWouldOverflow's own scaling factors collapse to rightScaled == leftScaled == 1 (gcd(D, D) == D), so the cross-multiplication checks reduce to numerator +/- rhs.numerator directly on already-canonical (so already in-range) int64_t values whose sum/difference is provably 0 -- never an overflow (and canonicalise() already forbids either component from being INT64_MIN, so negating one to check the other is always representable). So whenever the two operands could produce a tie, the overflow predicate that gates the call to compareForSaturation is always false, and the saturating path -- hence compareForSaturation's tie return -- is never reached with a tied pair. Shares this root cause with saturateToward's sign == 0 arm at line 775 below." }, { "file": "include/morph/util/rational.hpp", - "line": 929, + "line": 927, "source": "numerator = sign == 0 ? 0 : (sign < 0 ? -maxValue : maxValue);", "reason": "The sign == 0 arm is unreachable, for the same root cause as compareForSaturation's tie return at line 911 above: saturateToward is only ever called with the sign compareForSaturation returned, and compareForSaturation can only return 0 (a tie) for a pair whose overflow predicate is provably false -- so the saturating path that calls saturateToward is never entered with a tied pair, and sign is never 0 when this line runs." }, { "file": "include/morph/util/rational.hpp", - "line": 1054, + "line": 1052, "source": "if (crossDivisorOne == 0 || crossDivisorTwo == 0) {", "reason": "Both disjuncts are unreachable, and the body they guard (the zero-numerator short-circuit `return false;` right below) is correspondingly dead. crossDivisorOne = gcd(|numerator|, rhs.denominator), crossDivisorTwo = gcd(|rhs.numerator|, denominator). std::gcd(a, b) == 0 iff both a == 0 and b == 0. denominator/rhs.denominator can never be 0: every constructor path (Rational(Numerator, Denominator, DecimalPlaces)) calls canonicalise(), which clamps a 0 denominator to 1 before returning, and every mutating operation either recomputes the denominator as a product of positive denominators or calls canonicalise() again. So denominator > 0 (and rhs.denominator > 0) is a whole-class invariant, making crossDivisorOne/crossDivisorTwo == 0 impossible regardless of numerator/rhs.numerator." }, { "file": "include/morph/util/rational.hpp", - "line": 1799, + "line": 1797, "source": "if (ctx.begin() == ctx.end() || *ctx.begin() == '}') {", "reason": "The ctx.begin() == ctx.end() true arm is unreachable. This is the textbook cppreference-style custom-formatter parse() idiom. Empirically verified on this toolchain (libc++, via a standalone probe compiled with clang++ -std=c++23 -stdlib=libc++): for both std::format(\"{}\", x) and std::format(\"{:}\", x), ctx.end() always points past the terminating '}', so ctx.begin() == ctx.end() is false and the terminator is always reachable via *ctx.begin() == '}' -- matching the observed 0/14 split exactly. std::format's top-level parser (and std::vformat's, which performs the same replacement-field validation before dispatching to a type's parse()) rejects an unterminated '{...' before ever calling into formatter::parse, so this function is never invoked with an already-exhausted range. The first disjunct is defensive boilerplate that this standard library's implementation (and the standard's own guarantee about validated replacement fields) makes structurally unreachable." }, { "file": "include/morph/util/rational.hpp", - "line": 1568, + "line": 1566, "source": "if (!detail::addOverflows(whole, step)) {", "reason": "The false arm (the overflow-would-occur case, declining to step) is unreachable, contrary to Task 2's initial classification of this line as testable -- verified both mathematically and empirically (a standalone probe sweeping denominators/precisions found 476 cases where the scale-up saturated to whole == INT64_MAX, and every one had a fractional remainder of exactly 0, never >= 0.5) before writing this entry. A Rational's magnitude can never exceed INT64_MAX: its value is numerator/denominator with denominator >= 1 and numerator in [-INT64_MAX, INT64_MAX] (canonicalise() clamps INT64_MIN away), so |value| <= |numerator| <= INT64_MAX always. `whole` is trunc(scaled), so whole == INT64_MAX forces scaled == INT64_MAX/1 exactly -- there is no room for scaled to be in (INT64_MAX, INT64_MAX + 1) the way an unbounded rational could land. With scaled == whole exactly, `fraction` (scaled minus whole) is always 0, so `roundAway` (set from comparing fraction against 1/2) is always false when whole == INT64_MAX, and stepping never happens on that side. On the other side, step == -1 would need whole == INT64_MIN to overflow, but whole's range is [-INT64_MAX, INT64_MAX] (INT64_MIN is never a valid Rational magnitude), so that direction cannot overflow either. The guard is defensive: reachable only if a future change let a Rational's magnitude exceed INT64_MAX, which the type's invariants currently forbid everywhere else in this file." }, @@ -109,7 +109,7 @@ }, { "file": "include/morph/core/bridge.hpp", - "line": 2225, + "line": 2221, "source": "if (_executeDeadline.count() <= 0 || !_timeoutScheduler) {", "reason": "The `!_timeoutScheduler` disjunct is unreachable by construction. `setExecuteDeadline` is the only writer of both `_executeDeadline` and `_timeoutScheduler`, and it creates `_timeoutScheduler` in the same call that makes `_executeDeadline` positive; nothing resets `_timeoutScheduler` to null afterwards (setting the deadline back to 0 only stops new calls from arming it, per that method's doc comment). So `_executeDeadline > 0 && !_timeoutScheduler` cannot hold once any positive deadline has been set." }, diff --git a/scripts/check_install_export.sh b/scripts/check_install_export.sh index 7038fd6ec..fea809120 100755 --- a/scripts/check_install_export.sh +++ b/scripts/check_install_export.sh @@ -35,6 +35,9 @@ # `find_package`. Every assertion below therefore has a consumer-visible # consequence behind it. # +# `--shared` builds, installs and consumes morph::morph as a shared library +# (MORPH_BUILD_SHARED=ON); the default is the static library. +# # `--skip-header-set-verification` drops the one slow phase (compiling every # header in morph's interface header sets standalone, ~44 translation units). # It exists for scripts/test_check_install_export.sh, which needs the fast @@ -49,6 +52,7 @@ set -euo pipefail skip_header_set_verification=0 +shared=0 repo_root="" while [ "$#" -gt 0 ]; do @@ -57,6 +61,10 @@ while [ "$#" -gt 0 ]; do skip_header_set_verification=1 shift ;; + --shared) + shared=1 + shift + ;; -*) printf 'error: unknown option %s\n' "$1" >&2 exit 2 @@ -73,7 +81,7 @@ if [ -z "$repo_root" ]; then else repo_root="$(cd "$repo_root" && pwd)" fi -readonly repo_root skip_header_set_verification +readonly repo_root skip_header_set_verification shared failures=0 @@ -131,7 +139,8 @@ if ! run_step "the library did not configure" \ -DCMAKE_BUILD_TYPE=Release \ -DMORPH_BUILD_TESTS=OFF \ -DMORPH_BUILD_EXAMPLES=OFF \ - -DMORPH_BUILD_NET=ON; then + -DMORPH_BUILD_NET=ON \ + -DMORPH_BUILD_SHARED="$([ "$shared" -eq 1 ] && echo ON || echo OFF)"; then printf '\n%d install/export check(s) failed.\n' "$failures" >&2 exit 1 fi @@ -152,8 +161,7 @@ if [ "$skip_header_set_verification" -eq 0 ]; then fi fi -# morph::morph is a static library that links core-cpp's static modules, and -# morph's install installs them with core-cpp's package. They have to be built +# morph::morph links core-cpp's static modules, and morph's install installs them with core-cpp's package. They have to be built # first: installing an unbuilt tree fails with "file INSTALL cannot find". run_step "the library did not build" \ cmake --build "$build_dir" || true @@ -186,6 +194,20 @@ if [ -f "$targets_file" ]; then fail "an optional target is exported as '$(grep -o 'morph::morph_[a-z_]*' "$targets_file" | head -1)' rather than under its alias name -- install(EXPORT NAMESPACE morph::) prefixes the target name, so each optional target needs EXPORT_NAME" fi + # The mode under test must be the mode installed: a --shared run that + # installed the archive would pass every later step while proving nothing + # about a shared library. + if [ "$shared" -eq 1 ]; then + if ! grep -q '^add_library(morph::morph SHARED IMPORTED' "$targets_file"; then + fail "--shared was given but morph::morph is not exported as a SHARED imported target" + fi + if ! compgen -G "${prefix}/lib/libmorph.so*" >/dev/null && ! compgen -G "${prefix}/lib/libmorph*.dylib" >/dev/null; then + fail "--shared was given but no libmorph shared object was installed" + fi + elif ! grep -q '^add_library(morph::morph STATIC IMPORTED' "$targets_file"; then + fail "morph::morph is not exported as a STATIC imported target" + fi + # morph::client is built by default and is a compiled archive: an install # without it would leave the generic client's consumers with headers and no # library, or with neither. @@ -323,6 +345,14 @@ if run_step "the consumer project could not configure against the install prefix if run_step "the consumer binary did not run" "${consumer_build}/consumer"; then note "the consumer binary runs" + elif command -v readelf >/dev/null 2>&1; then + # A loader failure names the library it missed, not the object that + # needed it or the paths it searched; these do. + for object in "${consumer_build}/consumer" "$prefix"/lib*/lib*.so*; do + [[ -f "$object" && ! -L "$object" ]] || continue + printf -- '-- %s\n' "$object" >&2 + readelf -d "$object" 2>/dev/null | grep -E 'NEEDED|RPATH|RUNPATH' >&2 || true + done fi fi fi diff --git a/src/ui/interpreter.cpp b/src/ui/interpreter.cpp index c3210b903..be08ca207 100644 --- a/src/ui/interpreter.cpp +++ b/src/ui/interpreter.cpp @@ -1048,6 +1048,8 @@ void Session::applyFacts(std::string locale) { setFormatting(std::move(next)); } +Screen::Screen() = default; + Screen::~Screen() { try { if (Commands const* const commands = lifecycleList("onUnmount")) { diff --git a/src/ui/process_state.cpp b/src/ui/process_state.cpp new file mode 100644 index 000000000..5eb724b36 --- /dev/null +++ b/src/ui/process_state.cpp @@ -0,0 +1,245 @@ +// The process-wide state that header code reaches through a function. Each +// piece lives here, in the library, so that a shared build has one copy: a +// function-local static in an inline header function is instantiated once per +// module, and the library and an executable would each register into, and read +// from, their own. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace morph::bridge { + +ActionExecuteRegistry& ActionExecuteRegistry::instance() { + static ActionExecuteRegistry inst; + return inst; +} + +} // namespace morph::bridge + +namespace morph::model { + +std::atomic& detail::ActionGate::overlapCounter() noexcept { + static std::atomic counter{0}; + return counter; +} + +} // namespace morph::model + +namespace morph::model::detail { + +ActionResultSlotMap& mutableActionResultSlots() { + static ActionResultSlotMap entries; + return entries; +} + +std::vector& mutableActionResultConflicts() { + static std::vector ids; + return ids; +} + +ModelRegistryFactory& defaultRegistry() { + static ModelRegistryFactory inst; + return inst; +} + +ActionDispatcher& defaultDispatcher() { + static ActionDispatcher inst; + return inst; +} + +std::atomic& registrationPhaseFlag() noexcept { + static std::atomic closed{false}; + return closed; +} + +} // namespace morph::model::detail + +namespace morph::exec::detail { + +IExecutor& inlineExecutor() { + static InlineExecutor executor; + return executor; +} + +std::atomic& ownerProbe() noexcept { + static std::atomic probe{nullptr}; + return probe; +} + +} // namespace morph::exec::detail + +namespace morph::journal { + +PayloadMigrationRegistry& defaultPayloadMigrations() { + static PayloadMigrationRegistry registry; + return registry; +} + +} // namespace morph::journal + +namespace morph::journal::detail { + +bool& tlsIsReplaying() { + thread_local bool tls = false; + return tls; +} + +std::pair>& defaultActionLogState() { + static std::pair> state; + return state; +} + +} // namespace morph::journal::detail + +namespace morph::log::detail { + +LogState& logState() { + static LogState state; + return state; +} + +} // namespace morph::log::detail + +namespace morph::observe::detail { + +ObserveState& observeState() { + static ObserveState state; + return state; +} + +} // namespace morph::observe::detail + +namespace morph::session { + +std::shared_ptr allowAllAuthorizer() { + static auto const instance = std::make_shared(); + return instance; +} + +const SigningAuthorizer::Verification*& SigningAuthorizer::active() noexcept { + thread_local const Verification* current = nullptr; + return current; +} + +} // namespace morph::session + +namespace morph::session::detail { + +const Context*& tlsCurrent() { + thread_local const Context* tls = nullptr; + return tls; +} + +const RunOrigin*& tlsOrigin() { + thread_local const RunOrigin* tls = nullptr; + return tls; +} + +} // namespace morph::session::detail + +namespace morph::effects::detail { + +EffectsMap& mutableEffectsRegistry() { + static EffectsMap entries; + return entries; +} + +std::vector& mutableChangeTimesRegistry() { + static std::vector entries; + return entries; +} + +AddedEffectsMap& mutableAddedEffectsRegistry() { + static AddedEffectsMap entries; + return entries; +} + +Resolved const& resolved() { + model::detail::noteRegistryRead(true); + struct State { + std::once_flag once; + std::optional value; + std::optional error; + }; + static State state; + std::call_once(state.once, [] { + try { + state.value.emplace(resolve(record::detail::recordRegistry(), model::detail::actionResultSlots(), + mutableEffectsRegistry(), model::detail::actionResultConflicts(), + mutableAddedEffectsRegistry(), mutableChangeTimesRegistry())); + } catch (model::EffectsRegistrationError const& error) { + state.error.emplace(error); + } + }); + if (state.error) { + // The error is stored once and rethrown on every call, so it is copied each time. + // NOLINTNEXTLINE(cert-err09-cpp,cert-err61-cpp,misc-throw-by-value-catch-by-reference,bugprone-exception-copy-constructor-throws,cert-err60-cpp) + throw model::EffectsRegistrationError{*state.error}; + } + // call_once either filled the value or recorded the error thrown above. + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + return state.value.value(); +} + +} // namespace morph::effects::detail + +namespace morph::record::detail { + +std::vector& mutableRecordRegistry() { + static std::vector entries; + return entries; +} + +} // namespace morph::record::detail + +namespace morph::time::detail { + +std::pair>& nowOverrideState() { + static std::pair> state; + return state; +} + +} // namespace morph::time::detail + +namespace morph::math::detail { + +std::size_t& wireClampCounter() noexcept { + static thread_local std::size_t clamped = 0; + return clamped; +} + +} // namespace morph::math::detail + +namespace morph::ui::author { + +ScreenRegistry& screenRegistry() noexcept { + static ScreenRegistry registry; + return registry; +} + +} // namespace morph::ui::author + +namespace morph::views { + +ViewRegistry& ViewRegistry::instance() { + static ViewRegistry inst; + return inst; +} + +} // namespace morph::views diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index ca7e77715..7555e699c 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -466,7 +466,7 @@ if(CMAKE_CXX_COMPILER_ID MATCHES "^(GNU|Clang|AppleClang)$" AND NOT CMAKE_CXX_CO # a $. morph's own include directory is named directly # rather than unwrapped from the target, so a change to how that target is # declared cannot quietly leave this pointing at an installed copy. - set(MORPH_FORMS_DAG_INCLUDE_DIRS "${CMAKE_SOURCE_DIR}/include") + set(MORPH_FORMS_DAG_INCLUDE_DIRS "${CMAKE_SOURCE_DIR}/include" "${PROJECT_BINARY_DIR}/generated") get_target_property(_morph_forms_dag_glaze_includes glaze::glaze INTERFACE_INCLUDE_DIRECTORIES) foreach(_dir IN LISTS _morph_forms_dag_glaze_includes) string(REGEX REPLACE "^\\$$" "\\1" _dir "${_dir}") @@ -664,6 +664,19 @@ target_link_libraries(morph_guard_probe_deps INTERFACE glaze::glaze core::base core::async core::net core::platform $) +# The process-wide state the headers reach through a function is defined in +# src/ui/process_state.cpp. A probe that does not link morph::morph links its +# own static copy, built without any consumer macro. +add_library(morph_guard_probe_state STATIC ${PROJECT_SOURCE_DIR}/src/ui/process_state.cpp) +target_include_directories(morph_guard_probe_state PUBLIC + "${PROJECT_SOURCE_DIR}/include" "${PROJECT_BINARY_DIR}/generated") +target_compile_definitions(morph_guard_probe_state PUBLIC MORPH_STATIC_DEFINE) +target_compile_features(morph_guard_probe_state PUBLIC cxx_std_23) +target_link_libraries(morph_guard_probe_state PUBLIC + glaze::glaze core::base core::async core::net core::platform + $) +target_link_libraries(morph_guard_probe_deps INTERFACE morph_guard_probe_state) + add_executable(morph_client_only_guard_links compile_checks/client_only_no_model_link.cpp) target_compile_definitions(morph_client_only_guard_links PRIVATE MORPH_CLIENT_ONLY) target_link_libraries(morph_client_only_guard_links PRIVATE morph_guard_probe_deps) @@ -812,7 +825,7 @@ set_tests_properties(morph_client_only_facade PROPERTIES TIMEOUT 60) if(DEFINED AF_SANITIZER) foreach(_morph_guard_probe IN ITEMS morph_client_only_guard_links morph_client_only_runtime_throw morph_client_only_facade morph_declare_source_canary - morph_effects_unseen_links) + morph_effects_unseen_links morph_duplicate_model_id) apply_sanitizers(${_morph_guard_probe} ${AF_SANITIZER}) endforeach() unset(_morph_guard_probe)