diff --git a/.clang-format b/.clang-format index d256b10..838c1aa 100644 --- a/.clang-format +++ b/.clang-format @@ -128,7 +128,7 @@ IndentCaseBlocks: false IndentCaseLabels: false IndentExternBlock: AfterExternBlock IndentGotoLabels: true -IndentPPDirectives: None +IndentPPDirectives: BeforeHash IndentRequiresClause: true IndentWidth: 4 IndentWrappedFunctionNames: false diff --git a/.github/workflows/ci_tests.yml b/.github/workflows/ci_tests.yml index 9a463d5..cc3e30b 100644 --- a/.github/workflows/ci_tests.yml +++ b/.github/workflows/ci_tests.yml @@ -10,14 +10,13 @@ on: workflow_dispatch: schedule: - cron: '30 15 * * *' - - cron: "0 0 * * 0" jobs: beman-submodule-check: - uses: ./.github/workflows/reusable-beman-submodule-check.yml + uses: bemanproject/infra-workflows/.github/workflows/reusable-beman-submodule-check.yml@1.3.0 preset-test: - uses: ./.github/workflows/reusable-beman-preset-test.yml + uses: bemanproject/infra-workflows/.github/workflows/reusable-beman-preset-test.yml@1.3.0 with: matrix_config: > [ @@ -25,10 +24,14 @@ jobs: {"preset": "gcc-release", "image": "ghcr.io/bemanproject/infra-containers-gcc:latest"}, {"preset": "llvm-debug", "image": "ghcr.io/bemanproject/infra-containers-clang:latest"}, {"preset": "llvm-release", "image": "ghcr.io/bemanproject/infra-containers-clang:latest"}, + {"preset": "appleclang-debug", "runner": "macos-latest"}, + {"preset": "appleclang-release", "runner": "macos-latest"}, + {"preset": "msvc-debug", "runner": "windows-latest"}, + {"preset": "msvc-release", "runner": "windows-latest"} ] build-and-test: - uses: ./.github/workflows/reusable-beman-build-and-test.yml + uses: bemanproject/infra-workflows/.github/workflows/reusable-beman-build-and-test.yml@1.3.0 with: matrix_config: > { @@ -39,9 +42,9 @@ jobs: "tests": [ { "stdlibs": ["libstdc++"], "tests": [ - "Debug.Default", "Release.Default", "Release.TSan", - "Release.MaxSan", "Debug.Werror", "Debug.Dynamic", - "Debug.Coverage" + "Debug.Default", "Release.Default", "Release.MaxSan", + "Debug.Coverage", "Debug.Werror", + "Debug.Dynamic", "Release.Dynamic" ] } ] @@ -51,7 +54,7 @@ jobs: } ] }, - { "versions": ["14", "13"], + { "versions": ["14"], "tests": [ { "cxxversions": ["c++26", "c++23", "c++20"], "tests": [{ "stdlibs": ["libstdc++"], "tests": ["Release.Default"]}] @@ -60,30 +63,54 @@ jobs: } ], "clang": [ - { "versions": ["20"], + { "versions": ["21"], "tests": [ {"cxxversions": ["c++26"], "tests": [ - { "stdlibs": ["libstdc++"], + { "stdlibs": ["libc++"], "tests": [ - "Debug.Default", "Release.Default", "Release.TSan", - "Release.MaxSan", "Debug.Werror", "Debug.Dynamic" + "Debug.Default", "Release.Default", "Release.MaxSan", + "Debug.Dynamic", "Release.Dynamic" ] } ] }, { "cxxversions": ["c++23", "c++20"], "tests": [ - {"stdlibs": ["libstdc++"], "tests": ["Release.Default"]} + {"stdlibs": ["libc++"], "tests": ["Release.Default"]} ] } ] }, - { "versions": ["19"], + { "versions": ["20", "19"], "tests": [ { "cxxversions": ["c++26", "c++23", "c++20"], "tests": [ - {"stdlibs": ["libstdc++"], "tests": ["Release.Default"]} + {"stdlibs": ["libc++"], "tests": ["Release.Default"]} + ] + } + ] + } + ], + "appleclang": [ + { "versions": ["latest"], + "tests": [ + { "cxxversions": ["c++23", "c++20"], + "tests": [{ "stdlibs": ["libc++"], "tests": ["Release.Default"]}] + } + ] + } + ], + "msvc": [ + { "versions": ["latest"], + "tests": [ + { "cxxversions": ["c++23"], + "tests": [ + { "stdlibs": ["stl"], + "tests": ["Debug.Default", "Release.Default", "Release.MaxSan", + "Debug.Dynamic", "Release.Dynamic" + ] + } ] } ] @@ -93,9 +120,5 @@ jobs: create-issue-when-fault: needs: [preset-test, build-and-test] - if: failure() && github.event.schedule == '30 15 * * *' - uses: ./.github/workflows/reusable-beman-create-issue-when-fault.yml - - auto-update-pre-commit: - if: github.event.schedule == '00 16 * * 0' - uses: ./.github/workflows/reusable-beman-update-pre-commit.yml + if: failure() && github.event_name == 'schedule' + uses: bemanproject/infra-workflows/.github/workflows/reusable-beman-create-issue-when-fault.yml@1.3.0 diff --git a/.github/workflows/cmake.yml b/.github/workflows/cmake.yml new file mode 100644 index 0000000..2f52cbf --- /dev/null +++ b/.github/workflows/cmake.yml @@ -0,0 +1,79 @@ +--- +name: CMake + +on: + push: + branches: ["develop"] + pull_request: + branches: ["develop"] + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + schedule: + # run at 15:30 on day-of-month 7. + - cron: '30 15 7 * *' + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + # Customize the CMake build type here (Release, Debug, RelWithDebInfo, etc.) + BUILD_TYPE: release + CTEST_OUTPUT_ON_FAILURE: 1 + +jobs: + build: + strategy: + fail-fast: false + + matrix: + os: [windows] + include: + - { os: macos, uname: appleclang } + # XXX - { os: ubuntu, uname: gcc } + - { os: ubuntu, uname: llvm } + - { os: windows, uname: msvc } + + # TODO(CK): + # type: [shared, static] + # include: + # - { type: shared, shared: YES } + # - { type: static, shared: NO } + + runs-on: ${{ matrix.os }}-latest + + steps: + - uses: actions/checkout@v4 + - name: Setup build environment + uses: lukka/get-cmake@latest + with: + cmakeVersion: "~4.2.1" + ninjaVersion: "^1.13.0" + + - name: Setup MSVC + if: startsWith(matrix.os, 'windows') + uses: TheMrMilchmann/setup-msvc-dev@v3 + with: + arch: x64 + + - name: Setup Cpp + if: matrix.os != 'windows' + uses: aminya/setup-cpp@v1 + with: + # XXX compiler: ${{matrix.uname}} + compiler: llvm + + - name: Configure CMake + run: cmake --preset ${{matrix.uname}}-${{env.BUILD_TYPE}} --log-level=VERBOSE # XXX -Wdev + + - name: Build + # Build your program with the given configuration + run: cmake --build --preset ${{matrix.uname}}-${{env.BUILD_TYPE}} + + - name: Test + # Execute tests defined by the CMake configuration + run: ctest --preset ${{matrix.uname}}-${{env.BUILD_TYPE}} + + # - name: Install + # # Install the project artefacts to CMAKE_INSTALL_PREFIX + # run: cmake --build --preset ${{matrix.uname}}-${{env.BUILD_TYPE}} --target install diff --git a/.github/workflows/pre-commit-check.yml b/.github/workflows/pre-commit-check.yml new file mode 100644 index 0000000..2f91103 --- /dev/null +++ b/.github/workflows/pre-commit-check.yml @@ -0,0 +1,13 @@ +name: Lint Check (pre-commit) + +on: + # We have to use pull_request_target here as pull_request does not grant + # enough permission for reviewdog + pull_request_target: + push: + branches: + - main + +jobs: + pre-commit: + uses: bemanproject/infra-workflows/.github/workflows/reusable-beman-pre-commit.yml@1.3.0 diff --git a/.github/workflows/pre-commit-update.yml b/.github/workflows/pre-commit-update.yml new file mode 100644 index 0000000..930b750 --- /dev/null +++ b/.github/workflows/pre-commit-update.yml @@ -0,0 +1,15 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +name: Weekly pre-commit autoupdate + +on: + workflow_dispatch: + schedule: + - cron: "0 16 * * 0" + +jobs: + auto-update-pre-commit: + uses: bemanproject/infra-workflows/.github/workflows/reusable-beman-update-pre-commit.yml@1.3.0 + secrets: + APP_ID: ${{ secrets.AUTO_PR_BOT_APP_ID }} + PRIVATE_KEY: ${{ secrets.AUTO_PR_BOT_PRIVATE_KEY }} diff --git a/.gitignore b/.gitignore index baadefc..0e4b215 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,11 @@ -.cache +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + /compile_commands.json +/CMakeUserPresets.json /build +**/_deps/ +**/CMakeFiles/ +/cmake/presets # ignore emacs temp files *~ @@ -8,3 +13,4 @@ # ignore vscode settings .vscode +.cache diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index a4daacd..0e5fdfd 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,39 +4,39 @@ repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v6.0.0 hooks: - - id: trailing-whitespace - - id: end-of-file-fixer - - id: check-yaml + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml exclude: ^\.clang-(format|tidy)$ - - id: check-added-large-files + - id: check-added-large-files # Clang-format for C++ # This brings in a portable version of clang-format. # See also: https://github.com/ssciwr/clang-format-wheel - repo: https://github.com/pre-commit/mirrors-clang-format - rev: v21.1.6 + rev: v22.1.1 hooks: - - id: clang-format - types_or: [c++, c, json] + - id: clang-format + types_or: [c++, c, json] # CMake linting and formatting - repo: https://github.com/BlankSpruce/gersemi - rev: 0.23.1 + rev: 0.26.1 hooks: - - id: gersemi - name: CMake linting - exclude: ^.*/tests/.*/data/ # Exclude test data directories + - id: gersemi + name: CMake linting + exclude: ^.*/tests/.*/data/ # Exclude test data directories # Markdown linting # Config file: .markdownlint.yaml - # Commented out to disable this by default. Uncomment to enable markdown linting. + # Commented out to disable this by default. Uncomment to enable markdown linting. # - repo: https://github.com/igorshubovych/markdownlint-cli - # rev: v0.46.0 + # rev: v0.47.0 # hooks: - # - id: markdownlint + # - id: markdownlint - repo: https://github.com/codespell-project/codespell - rev: v2.4.1 + rev: v2.4.2 hooks: - id: codespell args: ["--ignore-words-list=wil"] diff --git a/CMakeLists.txt b/CMakeLists.txt index 7b36f29..12ca2eb 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,26 +1,30 @@ # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -cmake_minimum_required(VERSION 3.28...4.2) +cmake_minimum_required(VERSION 3.30...4.3) + +include(./cmake/prelude.cmake) project( beman.scope DESCRIPTION "Generic Scope Guard" LANGUAGES CXX - VERSION 0.0.1 + VERSION 0.1.0 ) -# gersemi: off +# Modules opt in only on compilers that support it: msvc, g++-15 and clang-20+ +include(./cmake/cxx-modules-rules.cmake) + +#=============================================================================== +if(BEMAN_USE_MODULES) + option(BUILD_SHARED_LIBS "Build using shared libraries" OFF) -# Modules opt in only on compilers that support g++-15 and clang-20+ -if (CMAKE_CXX_COMPILER_ID STREQUAL "Clang" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 20) - set(CMAKE_CXX_SCAN_FOR_MODULES 1) -elseif (CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 15) - set(CMAKE_CXX_SCAN_FOR_MODULES 1) -else() - set(CMAKE_CXX_SCAN_FOR_MODULES 0) + set(CMAKE_CXX_SCAN_FOR_MODULES ON) + set(CMAKE_CXX_VISIBILITY_PRESET hidden) + set(CMAKE_VISIBILITY_INLINES_HIDDEN ON) endif() +#=============================================================================== -set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +# gersemi: off # [CMAKE.SKIP_TESTS] option( @@ -42,90 +46,142 @@ option( ${PROJECT_IS_TOP_LEVEL} ) -message( - "Compiler is: ${CMAKE_CXX_COMPILER_ID} version: ${CMAKE_CXX_COMPILER_VERSION}" -) -message( - "cmake is: ${CMAKE_VERSION} modules scan : ${CMAKE_CXX_SCAN_FOR_MODULES}" -) +message(STATUS "Compiler is: ${CMAKE_CXX_COMPILER_ID} version: ${CMAKE_CXX_COMPILER_VERSION}") +message(STATUS "Cmake is: ${CMAKE_VERSION} modules scan: ${CMAKE_CXX_SCAN_FOR_MODULES}") + +# gersemi: on + +set(BEMAN_SCOPE_TARGETS beman.scope_headers) + +if(BEMAN_USE_MODULES) + option(BEMAN_SCOPE_IMPORT_STD "Use import std;" ${BEMAN_HAS_IMPORT_STD}) -if(CMAKE_CXX_SCAN_FOR_MODULES) add_library(beman.scope) + include(GenerateExportHeader) + generate_export_header( + beman.scope + BASE_NAME beman.scope + EXPORT_FILE_NAME beman/scope/modules_export.hpp + ) + + if(CMAKE_CXX_COMPILER_ID MATCHES "Clang") + # --------------------------------------------------------------------------- + # TODO(daniela): I do mean C++20 + # --------------------------------------------------------------------------- + target_compile_options( + beman.scope + PUBLIC + -fsized-deallocation + -faligned-allocation + -Wno-include-angled-in-module-purview + ) + endif() + + if(BEMAN_SCOPE_IMPORT_STD) + # --------------------------------------------------------------------------- + # Ensure binaries find the correct libstdc++ at runtime when using a + # non-system GCC (e.g. /opt/gcc-16). Without this, CTest fails because the + # dynamic linker finds the system's older libstdc++ which lacks required + # GLIBCXX symbols. + # --------------------------------------------------------------------------- + if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + set(_suffix .so) + if(APPLE) + set(_suffix .dylib) + endif() + execute_process( + COMMAND + ${CMAKE_CXX_COMPILER} -print-file-name=libstdc++${_suffix} + OUTPUT_VARIABLE _gcc_stdcxx_path + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + if(_gcc_stdcxx_path) + cmake_path(GET _gcc_stdcxx_path PARENT_PATH _gcc_lib_dir) + get_filename_component(_gcc_lib_dir "${_gcc_lib_dir}" REALPATH) + list(APPEND CMAKE_BUILD_RPATH "${_gcc_lib_dir}") + message(STATUS "GCC libstdc++ rpath: ${_gcc_lib_dir}") + endif() + endif() + set_target_properties(beman.scope PROPERTIES CXX_MODULE_STD ON) + target_compile_definitions(beman.scope PUBLIC BEMAN_SCOPE_IMPORT_STD) + endif() + if(BEMAN_SCOPE_USE_DANIELA_ADVICE) + target_compile_definitions( + beman.scope + PUBLIC BEMAN_SCOPE_USE_DANIELA_ADVICE + ) + endif() + add_library(beman::scope ALIAS beman.scope) + target_sources( beman.scope PUBLIC FILE_SET HEADERS - BASE_DIRS include - FILES include/beman/scope/scope.hpp + BASE_DIRS include ${CMAKE_CURRENT_BINARY_DIR} + FILES + include/beman/scope/scope.hpp + include/beman/scope/scope_impl.hpp + ${CMAKE_CURRENT_BINARY_DIR}/beman/scope/modules_export.hpp PUBLIC FILE_SET CXX_MODULES - BASE_DIRS include - FILES include/beman/scope/beman.scope.cppm - ) -else() - add_library(beman.scope INTERFACE) - target_sources( - beman.scope - INTERFACE - FILE_SET HEADERS - BASE_DIRS include - FILES include/beman/scope/scope.hpp + BASE_DIRS include + FILES include/beman/scope/beman.scope.cppm ) + + # --------------------------------------------------------------------------- + # CMake requires the language standard to be specified as compile feature + # when a target provides C++23 modules and the target will be installed + # --------------------------------------------------------------------------- + target_compile_features(beman.scope PUBLIC cxx_std_${CMAKE_CXX_STANDARD}) + + # --------------------------------------------------------------------------- + # FIXME: Quickfix only to prevent linker problems on windows with dll + # it should not needed and it does not help? CK + # We have NO exported symbols and so NO generated .lib on windows! + # --------------------------------------------------------------------------- + if(WIN32 AND BUILD_SHARED_LIBS) + set_target_properties( + beman.scope + PROPERTIES WINDOWS_EXPORT_ALL_SYMBOLS ON + ) + endif() + + set_target_properties(beman.scope PROPERTIES EXPORT_NAME scope) + list(APPEND BEMAN_SCOPE_TARGETS beman.scope) endif() -add_library(beman::scope ALIAS beman.scope) +add_library(beman.scope_headers INTERFACE) +target_sources( + beman.scope_headers + INTERFACE + FILE_SET HEADERS + BASE_DIRS include ${CMAKE_CURRENT_BINARY_DIR} + FILES + include/beman/scope/scope.hpp + include/beman/scope/scope_impl.hpp +) + +add_library(beman::scope_headers ALIAS beman.scope_headers) set_target_properties( - beman.scope + beman.scope_headers PROPERTIES - VERIFY_INTERFACE_HEADER_SETS ON - EXPORT_NAME scope + VERIFY_INTERFACE_HEADER_SETS ${PROJECT_IS_TOP_LEVEL} + EXPORT_NAME scope_headers ) -include(GNUInstallDirs) +# +# Install the libraries and its FILE_SET's. +# +include(cmake/beman-install-library.cmake) +beman_install_library(beman.scope TARGETS beman.scope beman.scope_headers) -install( - TARGETS beman.scope - COMPONENT beman.scope - EXPORT beman.scope-targets - - FILE_SET CXX_MODULES - DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} - CXX_MODULES_BMI - DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/beman.scope/bmi-${CMAKE_CXX_COMPILER_ID}_$ - FILE_SET HEADERS -) - -# gersemi: on - -if(BEMAN_SCOPE_INSTALL_CONFIG_FILE_PACKAGE) - include(CMakePackageConfigHelpers) - - write_basic_package_version_file( - ${CMAKE_CURRENT_BINARY_DIR}/beman.scope-config-version.cmake - COMPATIBILITY ExactVersion - ) - - install( - FILES - cmake/beman.scope-config.cmake - ${CMAKE_CURRENT_BINARY_DIR}/beman.scope-config-version.cmake - DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/beman.scope - COMPONENT beman.scope - ) - - install( - EXPORT beman.scope-targets - DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/beman.scope - NAMESPACE beman:: - CXX_MODULES_DIRECTORY - cxx-modules - COMPONENT beman.scope - ) -endif() +# --------------------------------------------------------------------------- +# NOTE: we use ctest in examples too! CK +# --------------------------------------------------------------------------- +enable_testing() if(BEMAN_SCOPE_BUILD_TESTS) - enable_testing() add_subdirectory(tests) endif() diff --git a/CMakePresets.json b/CMakePresets.json index 483e1a3..649e838 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -7,14 +7,32 @@ "generator": "Ninja", "binaryDir": "${sourceDir}/build/${presetName}", "cacheVariables": { - "CMAKE_CXX_STANDARD": "20", - "CMAKE_EXPORT_COMPILE_COMMANDS": "ON", - "CMAKE_PROJECT_TOP_LEVEL_INCLUDES": "./infra/cmake/use-fetch-content.cmake" + "BEMAN_SCOPE_USE_DANIELA_ADVICE": true, + "BEMAN_USE_MODULES": true, + "BEMAN_USE_STD_MODULE": true, + "CMAKE_CXX_STANDARD": "23", + "CMAKE_CXX_EXTENSIONS": true, + "CMAKE_CXX_STANDARD_REQUIRED": true, + "CMAKE_EXPORT_COMPILE_COMMANDS": true, + "CMAKE_INSTALL_MESSAGE": "LAZY", + "CMAKE_SKIP_TEST_ALL_DEPENDENCY": false, + "CMAKE_PROJECT_TOP_LEVEL_INCLUDES": "infra/cmake/use-fetch-content.cmake" } }, { "name": "_debug-base", "hidden": true, + "warnings": { + "dev": true, + "deprecated": true, + "uninitialized": true, + "unusedCli": true, + "systemVars": false + }, + "errors": { + "dev": false, + "deprecated": false + }, "cacheVariables": { "CMAKE_BUILD_TYPE": "Debug", "BEMAN_BUILDSYS_SANITIZER": "MaxSan" @@ -57,7 +75,11 @@ "_debug-base" ], "cacheVariables": { - "CMAKE_TOOLCHAIN_FILE": "infra/cmake/llvm-toolchain.cmake" + "CMAKE_TOOLCHAIN_FILE": "infra/cmake/llvm-libc++-toolchain.cmake" + }, + "environment": { + "CXX": "clang++", + "CMAKE_CXX_FLAGS": "-stdlib=libc++" } }, { @@ -68,7 +90,11 @@ "_release-base" ], "cacheVariables": { - "CMAKE_TOOLCHAIN_FILE": "infra/cmake/llvm-toolchain.cmake" + "CMAKE_TOOLCHAIN_FILE": "infra/cmake/llvm-libc++-toolchain.cmake" + }, + "environment": { + "CXX": "clang++", + "CMAKE_CXX_FLAGS": "-stdlib=libc++" } }, { @@ -79,6 +105,8 @@ "_debug-base" ], "cacheVariables": { + "BEMAN_USE_STD_MODULE": false, + "BEMAN_USE_MODULES": false, "CMAKE_TOOLCHAIN_FILE": "infra/cmake/appleclang-toolchain.cmake" } }, @@ -90,6 +118,8 @@ "_release-base" ], "cacheVariables": { + "BEMAN_USE_STD_MODULE": false, + "BEMAN_USE_MODULES": false, "CMAKE_TOOLCHAIN_FILE": "infra/cmake/appleclang-toolchain.cmake" } }, @@ -102,6 +132,11 @@ ], "cacheVariables": { "CMAKE_TOOLCHAIN_FILE": "infra/cmake/msvc-toolchain.cmake" + }, + "condition": { + "type": "equals", + "lhs": "${hostSystemName}", + "rhs": "Windows" } }, { @@ -113,6 +148,11 @@ ], "cacheVariables": { "CMAKE_TOOLCHAIN_FILE": "infra/cmake/msvc-toolchain.cmake" + }, + "condition": { + "type": "equals", + "lhs": "${hostSystemName}", + "rhs": "Windows" } } ], diff --git a/README.md b/README.md index ca73ed5..05fd129 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ SPDX-License-Identifier: CC0-1.0 **Status**: [Under development and not yet ready for production use.](https://github.com/bemanproject/beman/blob/main/docs/beman_library_maturity_model.md#under-development-and-not-yet-ready-for-production-use) -# Overview +## Overview During the C++20 cycle [P0052 Generic Scope Guard and RAII Wrapper for the Standard Library](https://wg21.link/P0052) added 4 types: `scope_exit`, `scope_fail`, `scope_success` @@ -80,18 +80,22 @@ but with different checked conditions on exiting the scope. Full runnable examples can be found in `examples/`. - ## Integrate beman.scope into your project -Beman.scope is a header-only library that currently relies on TS implementations -for `unique_resource` and is thus currently available only on g++-13 and up, or -clang 19 and up -- in C++20 mode. +`Beman.scope_headers` is a header-only library that builds with modern compilers +in C++20 mode. + +| C++ Version | Compilers | Note | +|-------------|------------------------------------|-------------------| +| 20 | gcc13+, clang19+, msvc, appleclang | No modules | +| 23-26 | gcc15+, clang19+, msvc | modules supported | + +Note that `CXX_MODULES` support is currently tested only on msvc, clang++-19, +and above and g++-15. -Note that modules support is currently tested only on clang++-19 and above and g++-15, and -is not supported if the C++ standard is below C++23. -As a header only library no building is required to use in a project -- simply make -the `include` directory available add add the following to your source. +As a header only library no building is required to use in a project -- simply +make the `include` directory available add add the following to your source. ```cpp #include @@ -100,6 +104,7 @@ the `include` directory available add add the following to your source. import beman.scope; ``` + With modules import needs to be after any includes to avoid compilation errors. ## Building beman.scope @@ -132,17 +137,18 @@ Build-time dependencies: from root of repo: ```shell -mkdir build; cd build; -cmake .. -DCMAKE_CXX_COMPILER=g++-15 -DCMAKE_CXX_STANDARD=26 -G=Ninja -ninja -j 5 -v; ctest +cmake -S . -B build -G Ninja -DCMAKE_CXX_COMPILER=g++-15 -DCMAKE_CXX_STANDARD=26 +ninja -v -C build all ``` or using cmake presets + ```shell cmake --workflow --preset gcc-release cmake --install build/gcc-release --prefix /opt/beman.scope ``` -# License + +## License Source is licensed with the Apache License v2.0 with LLVM Exceptions. @@ -154,10 +160,11 @@ Documentation and associated papers are licensed with the Creative Commons Attri The intent is that the source and documentation are available for use by people how they wish. -The README itself is licensed with CC0 1.0 Universal. Copy the contents and incorporate in your own work as you see fit. +The README itself is licensed with CC0 1.0 Universal. Copy the contents and incorporate in your own work as you see +fit. // SPDX-License-Identifier: CC0-1.0 -# Contributing +## Contributing Please do! Issues and pull requests are appreciated. diff --git a/cmake/Config.cmake.in b/cmake/Config.cmake.in new file mode 100644 index 0000000..81adf80 --- /dev/null +++ b/cmake/Config.cmake.in @@ -0,0 +1,12 @@ +# cmake/Config.cmake.in -*-makefile-*- +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +include(CMakeFindDependencyMacro) + +@BEMAN_FIND_DEPENDENCIES@ + +@PACKAGE_INIT@ + +include(${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@-targets.cmake) + +check_required_components(@PROJECT_NAME@) diff --git a/cmake/beman-install-library.cmake b/cmake/beman-install-library.cmake new file mode 100644 index 0000000..919df9b --- /dev/null +++ b/cmake/beman-install-library.cmake @@ -0,0 +1,322 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +include_guard(GLOBAL) + +include(CMakePackageConfigHelpers) +include(GNUInstallDirs) + +# beman_install_library +# ===================== +# +# Installs a library (or set of targets) along with headers, C++ modules, +# and optional CMake package configuration files. +# +# Usage: +# ------ +# beman_install_library( +# TARGETS [ ...] +# [DEPENDENCIES [ ...]] +# [NAMESPACE ] +# [EXPORT_NAME ] +# [DESTINATION ] +# ) +# +# Arguments: +# ---------- +# +# name +# Logical package name (e.g. "beman.utility"). +# Used to derive config file names and cache variable prefixes. +# +# TARGETS (required) +# List of CMake targets to install. +# +# DEPENDENCIES (optional) +# Semicolon-separated list, one dependency per entry. +# Each entry is a valid find_dependency() argument list. +# Note: you must use the bracket form for quoting if not only a package name is used! +# "[===[beman.inplace_vector 1.0.0]===] [===[beman.scope 0.0.1 EXACT]===] fmt" +# +# NAMESPACE (optional) +# Namespace for exported targets. +# Defaults to "beman::". +# +# EXPORT_NAME (optional) +# Name of the CMake export set. +# Defaults to "-targets". +# +# DESTINATION (optional) +# The install destination for CXX_MODULES. +# Defaults to ${CMAKE_INSTALL_LIBDIR}/cmake/${name}/modules. +# +# Brief +# ----- +# +# This function installs the specified project TARGETS and its FILE_SET +# HEADERS to the default CMAKE install destination. +# +# It also handles the installation of the CMake config package files if +# needed. If the given targets has a PUBLIC FILE_SET CXX_MODULE, it will also +# installed to the given DESTINATION +# +# Cache variables: +# ---------------- +# +# BEMAN_INSTALL_CONFIG_FILE_PACKAGES +# List of package names for which config files should be installed. +# +# _INSTALL_CONFIG_FILE_PACKAGE +# Per-package override to enable/disable config file installation. +# is the uppercased package name with dots replaced by underscores. +# +# Caveats +# ------- +# +# **Only one `PUBLIC FILE_SET CXX_MODULES` is yet supported to install with this +# function!** +# +# **Only header files contained in a `PUBLIC FILE_SET TYPE HEADERS` will be +# install with this function!** + +function(beman_install_library name) + # ---------------------------- + # Argument parsing + # ---------------------------- + set(oneValueArgs NAMESPACE EXPORT_NAME DESTINATION) + set(multiValueArgs TARGETS DEPENDENCIES) + + cmake_parse_arguments( + BEMAN + "${options}" + "${oneValueArgs}" + "${multiValueArgs}" + ${ARGN} + ) + + if(NOT BEMAN_TARGETS) + message( + FATAL_ERROR + "beman_install_library(${name}): TARGETS must be specified" + ) + endif() + + if(CMAKE_SKIP_INSTALL_RULES) + message( + WARNING + "beman_install_library(${name}): not installing targets '${BEMAN_TARGETS}' due to CMAKE_SKIP_INSTALL_RULES" + ) + return() + endif() + + set(_config_install_dir "${CMAKE_INSTALL_LIBDIR}/cmake/${name}") + + # ---------------------------- + # Defaults + # ---------------------------- + if(NOT BEMAN_NAMESPACE) + set(BEMAN_NAMESPACE "beman::") + endif() + + if(NOT BEMAN_EXPORT_NAME) + set(BEMAN_EXPORT_NAME "${name}-targets") + endif() + + if(NOT BEMAN_DESTINATION) + set(BEMAN_DESTINATION "${_config_install_dir}/modules") + endif() + + string(REPLACE "beman." "" install_component_name "${name}") + message( + VERBOSE + "beman-install-library(${name}): COMPONENT '${install_component_name}'" + ) + + # -------------------------------------------------- + # Install each target with all of its file sets + # -------------------------------------------------- + foreach(_tgt IN LISTS BEMAN_TARGETS) + if(NOT TARGET "${_tgt}") + message( + WARNING + "beman_install_library(${name}): '${_tgt}' is not a target" + ) + continue() + endif() + + # Given foo.bar, the component name is bar + string(REPLACE "." ";" name_parts "${_tgt}") + # fail if the name doesn't look like foo.bar + list(LENGTH name_parts name_parts_length) + if(NOT name_parts_length EQUAL 2) + message( + FATAL_ERROR + "beman_install_library(${name}): expects a name of the form 'beman.', got '${_tgt}'" + ) + endif() + list(GET name_parts -1 component_name) + set_target_properties( + "${_tgt}" + PROPERTIES EXPORT_NAME "${component_name}" + ) + message( + VERBOSE + "beman_install_library(${name}): EXPORT_NAME ${component_name} for TARGET '${_tgt}'" + ) + + # Get the list of interface header sets, exact one expected! + set(_install_header_set_args) + get_target_property( + _available_header_sets + ${_tgt} + INTERFACE_HEADER_SETS + ) + if(_available_header_sets) + message( + VERBOSE + "beman-install-library(${name}): '${_tgt}' has INTERFACE_HEADER_SETS=${_available_header_sets}" + ) + foreach(_install_header_set IN LISTS _available_header_sets) + list( + APPEND _install_header_set_args + FILE_SET + "${_install_header_set}" + COMPONENT + "${install_component_name}_Development" + ) + endforeach() + else() + set(_install_header_set_args FILE_SET HEADERS) # Note: empty FILE_SET in this case! CK + endif() + + # Detect presence of PUBLIC C++ module file sets. Note: exact one is expected! + get_target_property(_module_sets "${_tgt}" INTERFACE_CXX_MODULE_SETS) + if(_module_sets) + message( + VERBOSE + "beman-install-library(${name}): '${_tgt}' has INTERFACE_CXX_MODULE_SETS=${_module_sets}" + ) + install( + TARGETS "${_tgt}" + EXPORT ${BEMAN_EXPORT_NAME} + ARCHIVE COMPONENT "${install_component_name}_Development" + LIBRARY + COMPONENT "${install_component_name}_Runtime" + NAMELINK_COMPONENT "${install_component_name}_Development" + RUNTIME COMPONENT "${install_component_name}_Runtime" + ${_install_header_set_args} + FILE_SET ${_module_sets} + DESTINATION "${BEMAN_DESTINATION}" + COMPONENT "${install_component_name}_Development" + # NOTE: There's currently no convention for this location! CK + CXX_MODULES_BMI + DESTINATION + ${_config_install_dir}/bmi-${CMAKE_CXX_COMPILER_ID}_$ + COMPONENT "${install_component_name}_Development" + ) + else() + install( + TARGETS "${_tgt}" + EXPORT ${BEMAN_EXPORT_NAME} + ARCHIVE COMPONENT "${install_component_name}_Development" + LIBRARY + COMPONENT "${install_component_name}_Runtime" + NAMELINK_COMPONENT "${install_component_name}_Development" + RUNTIME COMPONENT "${install_component_name}_Runtime" + ${_install_header_set_args} + ) + endif() + endforeach() + + # -------------------------------------------------- + # Export targets + # -------------------------------------------------- + # gersemi: off + install( + EXPORT ${BEMAN_EXPORT_NAME} + NAMESPACE ${BEMAN_NAMESPACE} + CXX_MODULES_DIRECTORY cxx-modules + DESTINATION ${_config_install_dir} + COMPONENT "${install_component_name}_Development" + ) + # gersemi: on + + # ---------------------------------------- + # Config file installation logic + # + # Precedence (highest to lowest): + # 1. Per-package variable _INSTALL_CONFIG_FILE_PACKAGE + # 2. Allow-list BEMAN_INSTALL_CONFIG_FILE_PACKAGES (if defined) + # 3. Default: ON + # ---------------------------------------- + string(TOUPPER "${name}" _pkg_upper) + string(REPLACE "." "_" _pkg_prefix "${_pkg_upper}") + + option( + ${_pkg_prefix}_INSTALL_CONFIG_FILE_PACKAGE + "Enable creating and installing a CMake config-file package. Default: ON. Values: { ON, OFF }." + ON + ) + + set(_pkg_var "${_pkg_prefix}_INSTALL_CONFIG_FILE_PACKAGE") + + # Default: install config files + set(_install_config ON) + + # If the allow-list is defined, only install for packages in the list + if(DEFINED BEMAN_INSTALL_CONFIG_FILE_PACKAGES) + if(NOT "${name}" IN_LIST BEMAN_INSTALL_CONFIG_FILE_PACKAGES) + set(_install_config OFF) + endif() + endif() + + # Per-package override takes highest precedence + if(DEFINED ${_pkg_var}) + set(_install_config ${${_pkg_var}}) + endif() + + # ---------------------------------------- + # expand dependencies + # ---------------------------------------- + set(_beman_find_deps "") + foreach(dep IN LISTS BEMAN_DEPENDENCIES) + message( + VERBOSE + "beman-install-library(${name}): Add find_dependency(${dep})" + ) + string(APPEND _beman_find_deps "find_dependency(${dep})\n") + endforeach() + set(BEMAN_FIND_DEPENDENCIES "${_beman_find_deps}") + + # ---------------------------------------- + # Generate + install config files + # ---------------------------------------- + if(_install_config) + configure_package_config_file( + "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/Config.cmake.in" + "${CMAKE_CURRENT_BINARY_DIR}/${name}-config.cmake" + INSTALL_DESTINATION ${_config_install_dir} + ) + + write_basic_package_version_file( + "${CMAKE_CURRENT_BINARY_DIR}/${name}-config-version.cmake" + VERSION ${PROJECT_VERSION} + COMPATIBILITY SameMajorVersion + ) + + install( + FILES + "${CMAKE_CURRENT_BINARY_DIR}/${name}-config.cmake" + "${CMAKE_CURRENT_BINARY_DIR}/${name}-config-version.cmake" + DESTINATION ${_config_install_dir} + COMPONENT "${install_component_name}_Development" + ) + else() + message( + WARNING + "beman-install-library(${name}): Not installing a config package for '${name}'" + ) + endif() +endfunction() + +set(CPACK_GENERATOR TGZ) +include(CPack) diff --git a/cmake/beman.scope-config.cmake b/cmake/beman.scope-config.cmake deleted file mode 100644 index e4102c5..0000000 --- a/cmake/beman.scope-config.cmake +++ /dev/null @@ -1,8 +0,0 @@ -include(${CMAKE_CURRENT_LIST_DIR}/beman.scope-targets.cmake) - -foreach(comp IN LISTS beman.scope_FIND_COMPONENTS) - if(beman.scope_FIND_REQUIRED_${comp}) - set(beman.scope_FOUND FALSE) - return() - endif() -endforeach() diff --git a/cmake/cxx-modules-rules.cmake b/cmake/cxx-modules-rules.cmake new file mode 100644 index 0000000..91939b3 --- /dev/null +++ b/cmake/cxx-modules-rules.cmake @@ -0,0 +1,155 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# +# A CMake language file to be included as the last step of all project() command calls. +# This file must be included/used as CMAKE_PROJECT_INCLUDE -> after project() +# + +# ---- The include guard applies within the current directory and below ---- +include_guard(DIRECTORY) + +if(NOT PROJECT_NAME) + message( + FATAL_ERROR + "This CMake file has to be included as the last step of all project() command calls!" + ) +endif() + +# Use modules? default NO! +if(NOT DEFINED CMAKE_CXX_SCAN_FOR_MODULES) + set(CMAKE_CXX_SCAN_FOR_MODULES OFF) +endif() + +# Control whether the test target depends on the all target. +set(CMAKE_SKIP_TEST_ALL_DEPENDENCY OFF) + +# gersemi: off +option(CMAKE_EXPORT_COMPILE_COMMANDS "Prepare run-clang-tidy" ${PROJECT_IS_TOP_LEVEL}) +if(CMAKE_EXPORT_COMPILE_COMMANDS) + message( + STATUS + "CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES=${CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES}" + ) + set(CMAKE_CXX_STANDARD_INCLUDE_DIRECTORIES ${CMAKE_CXX_IMPLICIT_INCLUDE_DIRECTORIES}) +endif() +# gersemi: on + +# Ensure non-empty default build type for single-config +get_property(isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(NOT isMultiConfig) + set(CMAKE_BUILD_TYPE Debug CACHE STRING "Build type") +endif() +set(CMAKE_DEBUG_POSTFIX _d) + +# ------------------------------------------------------------------------------ +# This property setting also needs to be consistent between the installed shared +# library and its consumer, otherwise most toolchains will once again reject the +# consumer's generated BMI. +# ------------------------------------------------------------------------------ +if(NOT DEFINED CMAKE_CXX_STANDARD) + set(CMAKE_CXX_STANDARD 23) +endif() + +# Neither of these two are technically needed, but they make the expectation clear +set(CMAKE_CXX_EXTENSIONS ON) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +# NOTE: only with Ninja generator install of bmi files works yet! +if(CMAKE_GENERATOR MATCHES "Ninja") + if( + CMAKE_CXX_COMPILER_ID STREQUAL "Clang" + AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 19.0 + ) + set(CMAKE_CXX_SCAN_FOR_MODULES ON) + + if(NOT LINUX) + string(APPEND CMAKE_CXX_MODULE_MAP_FLAG " -fmodules-reduced-bmi") + endif() + + add_compile_options($ENV{CXXFLAGS}) + add_link_options($ENV{CXXFLAGS}) + elseif( + CMAKE_CXX_COMPILER_ID STREQUAL "GNU" + AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 15.0 + ) + set(CMAKE_CXX_SCAN_FOR_MODULES ON) + elseif(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") + set(CMAKE_CXX_SCAN_FOR_MODULES ON) + else() + set(CMAKE_CXX_SCAN_FOR_MODULES OFF) + endif() +endif() + +if(CMAKE_CXX_STDLIB_MODULES_JSON) + message( + STATUS + "CMAKE_CXX_STDLIB_MODULES_JSON=${CMAKE_CXX_STDLIB_MODULES_JSON}" + ) +endif() + +if(NOT DEFINED CMAKE_CXX_MODULE_STD) + set(CMAKE_CXX_MODULE_STD OFF) +endif() + +if(CMAKE_CXX_STANDARD GREATER_EQUAL 20) + option(BEMAN_USE_MODULES "Build CXX_MODULES" ${CMAKE_CXX_SCAN_FOR_MODULES}) +endif() +message(STATUS "BEMAN_USE_MODULES=${BEMAN_USE_MODULES}") + +option( + BEMAN_USE_STD_MODULE + "Check if 'import std;' is possible with the toolchain?" + OFF +) +message(STATUS "BEMAN_USE_STD_MODULE=${BEMAN_USE_STD_MODULE}") + +if(BEMAN_USE_MODULES AND BEMAN_USE_STD_MODULE) + # ------------------------------------------------------------------------- + # Tell CMake that we explicitly want `import std`. + # This will initialize the property on all targets declared after this to 1 + # ------------------------------------------------------------------------- + message( + STATUS + "CMAKE_CXX_COMPILER_IMPORT_STD=${CMAKE_CXX_COMPILER_IMPORT_STD}" + ) + if(${CMAKE_CXX_STANDARD} IN_LIST CMAKE_CXX_COMPILER_IMPORT_STD) + set(CMAKE_CXX_MODULE_STD ON) + set(CMAKE_CXX_SCAN_FOR_MODULES ON) + option( + BEMAN_HAS_IMPORT_STD + "Build with import std; is possible and used!" + ${CMAKE_CXX_MODULE_STD} + ) + message(STATUS "CMAKE_CXX_MODULE_STD=${CMAKE_CXX_MODULE_STD}") + else() + set(CMAKE_CXX_MODULE_STD OFF) + message(WARNING "CMAKE_CXX_MODULE_STD=${CMAKE_CXX_MODULE_STD}") + endif() + message(STATUS "BEMAN_HAS_IMPORT_STD=${BEMAN_HAS_IMPORT_STD}") +endif() + +if(NOT BEMAN_USE_MODULES) + set(CMAKE_CXX_SCAN_FOR_MODULES OFF) +endif() +message(STATUS "CMAKE_CXX_SCAN_FOR_MODULES=${CMAKE_CXX_SCAN_FOR_MODULES}") + +# ------------------------------------------------------------------------------ +# Avoid creating CMAKE_..._OUTPUT_DIRECTORY as cache variables, they should not +# be under the control of the developer. They should be controlled by the +# project because parts of the project may make assumptions about the relative +# layout of the binaries. More importantly, leaving them as ordinary variables +# also means they can be unset within subdirectories where test executables are +# defined, allowing them to avoid being collected with the other main binaries +# and cluttering up that area. +# ------------------------------------------------------------------------------ +set(stageDir ${CMAKE_CURRENT_BINARY_DIR}/stagedir) +include(GNUInstallDirs) + +if(NOT CMAKE_RUNTIME_OUTPUT_DIRECTORY) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${stageDir}/${CMAKE_INSTALL_BINDIR}) +endif() +if(NOT CMAKE_LIBRARY_OUTPUT_DIRECTORY) + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${stageDir}/${CMAKE_INSTALL_LIBDIR}) +endif() +if(NOT CMAKE_ARCHIVE_OUTPUT_DIRECTORY) + set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${stageDir}/${CMAKE_INSTALL_LIBDIR}) +endif() diff --git a/cmake/prelude.cmake b/cmake/prelude.cmake new file mode 100644 index 0000000..c0394e2 --- /dev/null +++ b/cmake/prelude.cmake @@ -0,0 +1,131 @@ +# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +# +# This file must be included/used as CMAKE_PROJECT_TOP_LEVEL_INCLUDES -> before project() is called! +# + +# ---- The include guard applies globally to the whole build ---- +include_guard(GLOBAL) + +if(CMAKE_SOURCE_DIR STREQUAL CMAKE_BINARY_DIR) + message( + FATAL_ERROR + "In-source builds are not supported. " + "Please read the BUILDING document before trying to build this project. " + "You may need to delete 'CMakeCache.txt' and 'CMakeFiles/' first." + ) +endif() + +list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_LIST_DIR}) + +# gersemi: off +# --------------------------------------------------------------------------- +# The CMAKE_EXPERIMENTAL_CXX_IMPORT_STD is not longer needed except for OSX +# --------------------------------------------------------------------------- +if(NOT BEMAN_USE_STD_MODULE OR CMAKE_VERSION VERSION_GREATER_EQUAL 4.4) + if(NOT APPLE) + return() + endif() +endif() +# --------------------------------------------------------------------------- + +# --------------------------------------------------------------------------- +# check if import std; is supported by CMAKE_CXX_COMPILER +# --------------------------------------------------------------------------- +if(CMAKE_VERSION VERSION_GREATER_EQUAL 4.2 AND CMAKE_VERSION VERSION_LESS 4.4) + if(PROJECT_NAME) + message( + WARNING + "This CMake file has to be included before first project() command call!" + ) + endif() +endif() + +# --------------------------------------------------------------------------- +# check if import std; is supported by CMAKE_CXX_COMPILER +# --------------------------------------------------------------------------- +if(CMAKE_VERSION VERSION_GREATER_EQUAL 4.3 AND CMAKE_VERSION VERSION_LESS 4.4) + set(CMAKE_EXPERIMENTAL_CXX_IMPORT_STD "451f2fe2-a8a2-47c3-bc32-94786d8fc91b") +elseif(CMAKE_VERSION VERSION_GREATER_EQUAL 4.2 AND CMAKE_VERSION VERSION_LESS 4.3) + set(CMAKE_EXPERIMENTAL_CXX_IMPORT_STD "d0edc3af-4c50-42ea-a356-e2862fe7a444") +endif() +# gersemi: on + +# --------------------------------------------------------------------------- +# TODO(CK): Do we need this HACK still for linux too? +# --------------------------------------------------------------------------- +if(NOT APPLE) + return() +endif() + +# FIXME: clang++ we still needs to export CXX=clang++ +if("$ENV{CXX}" STREQUAL "" AND CMAKE_CXX_COMPILER) + message(WARNING "\$CXX is not set") + set(ENV{CXX} ${CMAKE_CXX_COMPILER}) +endif() + +# --------------------------------------------------------------------------- +# Workaround needed for CMAKE and clang++ to find the libc++.modules.json file +# --------------------------------------------------------------------------- +if( + CMAKE_VERSION VERSION_GREATER_EQUAL 4.2 + AND ("$ENV{CXX}" MATCHES "clang" OR CMAKE_CXX_COMPILER MATCHES "clang") +) + # NOTE: Always use libc++ + # see https://releases.llvm.org/19.1.0/projects/libcxx/docs/index.html + set(ENV{CXXFLAGS} -stdlib=libc++) + message(STATUS "CXXFLAGS=-stdlib=libc++") + + if(APPLE) + execute_process( + OUTPUT_VARIABLE LLVM_PREFIX + COMMAND brew --prefix llvm + COMMAND_ECHO STDOUT + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + file(REAL_PATH ${LLVM_PREFIX} LLVM_DIR) + set(LLVM_DIR ${LLVM_DIR} CACHE FILEPATH "") + + message(STATUS "LLVM_DIR=${LLVM_DIR}") + add_link_options(-L${LLVM_DIR}/lib/c++) + include_directories(SYSTEM ${LLVM_DIR}/include) + + # /usr/local/Cellar/llvm/21.1.8_1/lib/c++/libc++.modules.json + # "/usr/local/Cellar/llvm/21.1.8_1/share/libc++/v1/std.cppm", + set(CMAKE_CXX_STDLIB_MODULES_JSON + ${LLVM_DIR}/lib/c++/libc++.modules.json + ) + elseif(LINUX) + execute_process( + OUTPUT_VARIABLE LLVM_MODULES + COMMAND clang++ -print-file-name=libc++.modules.json + COMMAND_ECHO STDOUT + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + if(NOT CMAKE_CXX_STDLIB_MODULES_JSON) + set(CMAKE_CXX_STDLIB_MODULES_JSON ${LLVM_MODULES}) + endif() + message( + STATUS + "CMAKE_CXX_STDLIB_MODULES_JSON=${CMAKE_CXX_STDLIB_MODULES_JSON}" + ) + endif() + + if(EXISTS ${CMAKE_CXX_STDLIB_MODULES_JSON}) + message( + STATUS + "CMAKE_CXX_STDLIB_MODULES_JSON=${CMAKE_CXX_STDLIB_MODULES_JSON}" + ) + # gersemi: off + set(CACHE{CMAKE_CXX_STDLIB_MODULES_JSON} + TYPE FILEPATH + HELP "Result of: clang++ -print-file-name=c++/libc++.modules.json" + VALUE ${CMAKE_CXX_STDLIB_MODULES_JSON} + ) + # gersemi: on + else() + message( + FATAL_ERROR + "File does NOT EXISTS! ${CMAKE_CXX_STDLIB_MODULES_JSON}" + ) + endif() +endif() diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 23ffaf7..2bfb138 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -1,16 +1,39 @@ # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -set(ALL_EXAMPLES scope_example unique_resource unique_resource-file) +cmake_minimum_required(VERSION 3.30...4.3) -# module tests will only compile with gcc15 or clang20 and above -if(CMAKE_CXX_SCAN_FOR_MODULES AND CMAKE_CXX_MODULE_STD) - list(APPEND ALL_EXAMPLES scope-module) +include(../cmake/prelude.cmake) + +project(beman.scope.example LANGUAGES CXX) + +if(PROJECT_IS_TOP_LEVEL) + include(../cmake/cxx-modules-rules.cmake) + + find_package(beman.scope 0.1.0 EXACT REQUIRED) + + option(BEMAN_SCOPE_IMPORT_STD "Use import std;" ${BEMAN_HAS_IMPORT_STD}) + + enable_testing() endif() +set(ALL_EXAMPLES scope_example unique_resource unique_resource-file) + message("Examples to be built: ${ALL_EXAMPLES}") foreach(example ${ALL_EXAMPLES}) add_executable(${example}) target_sources(${example} PRIVATE ${example}.cpp) - target_link_libraries(${example} PRIVATE beman::scope) + target_link_libraries(${example} PRIVATE beman::scope_headers) + add_test(NAME ${example} COMMAND ${example}) endforeach() + +# module tests will only compile with gcc15 or clang20 and above +# NOTE: needs C++23 or newer! CK +if(BEMAN_USE_MODULES) + add_executable(scope_module scope-module.cpp) + target_link_libraries(scope_module PRIVATE beman::scope) + if(BEMAN_SCOPE_IMPORT_STD) + set_target_properties(scope_module PROPERTIES CXX_MODULE_STD ON) + endif() + add_test(NAME scope_module COMMAND scope_module) +endif() diff --git a/examples/scope-module.cpp b/examples/scope-module.cpp index 22dd6d3..1d1dbc6 100644 --- a/examples/scope-module.cpp +++ b/examples/scope-module.cpp @@ -15,34 +15,51 @@ // destroy noisy // scope exit: true success: true fail: false -// #ifdef HAS_MODULE_STD +// NOTE: not included in gcc-15 libstdc++ std module? CK +#include + +// for g++-15 the order is important -- import after #includes +#ifdef BEMAN_SCOPE_IMPORT_STD +// NOTE: this needs C++23! CK import std; -// #else -// NOTE: this needs C++23! -// #include -// #endif +#endif import beman.scope; -// clang-format off -struct noisy_resource { - noisy_resource() { std::print( "construct noisy\n" ); } - ~noisy_resource() { std::print( "destroy noisy\n" ); } +namespace { + +struct DummyResource { + bool& cleaned; + + DummyResource(bool& flag) : cleaned(flag) { cleaned = false; } + + [[nodiscard]] bool is_clean() const { return cleaned; } }; +} // namespace + int main() { - bool exit_ran, success_ran, fail_ran = false; + bool exit_ran{}; + bool success_ran{}; + bool fail_ran{}; + bool cleaned{true}; { - std::print("--> scope start\n"); - beman::scope::scope_exit _([&exit_ran] { exit_ran = true; }); - beman::scope::scope_success _([&success_ran] { success_ran = true; }); - beman::scope::scope_fail _([&fail_ran] { fail_ran = true; }); - auto resource_ptr = beman::scope::unique_resource(new noisy_resource(), - // Cleanup function - [](noisy_resource* ptr) { delete ptr; }); - std::print("--> scope end\n"); + // clang-format off + beman::scope::scope_exit const _se([&exit_ran] { exit_ran = true; }); + beman::scope::scope_success const _ss([&success_ran] { success_ran = true; }); + beman::scope::scope_fail const _sf([&fail_ran] { fail_ran = true; }); + auto resource_ptr = beman::scope::unique_resource(new DummyResource(cleaned), + [](DummyResource* ptr) { ptr->cleaned = true; delete ptr; }); + // clang-format on + + assert(cleaned == false); + assert(resource_ptr->is_clean() == false); } // Normal scope exit - std::print("scope exit: {} success: {} fail: {} \n", exit_ran, success_ran, fail_ran); + assert(exit_ran == true); + assert(success_ran == true); + assert(fail_ran == false); + assert(cleaned == true); } +// clang-format on diff --git a/examples/scope_example.cpp b/examples/scope_example.cpp index 9746049..744ce73 100644 --- a/examples/scope_example.cpp +++ b/examples/scope_example.cpp @@ -16,12 +16,14 @@ void print_exit_status(std::string_view name, bool exit_status, bool did_throw) // Randomly throw an exception (50% chance) void maybe_throw() { - if (std::rand() >= RAND_MAX / 2) + if (std::rand() >= RAND_MAX / 2) { throw std::exception{}; + } } int main() { - bool exit_status{false}, did_throw{false}; + bool exit_status{false}; + bool did_throw{false}; // Manual handling at "end of scope" try { diff --git a/examples/unique_resource-file.cpp b/examples/unique_resource-file.cpp index ed76cda..2130979 100644 --- a/examples/unique_resource-file.cpp +++ b/examples/unique_resource-file.cpp @@ -19,7 +19,7 @@ int main() { } ); - if (!file.get()) { + if (file.get() == nullptr) { std::cerr << "Failed to open file.\n"; return 1; } diff --git a/examples/unique_resource.cpp b/examples/unique_resource.cpp index ea26a98..b9e2f76 100644 --- a/examples/unique_resource.cpp +++ b/examples/unique_resource.cpp @@ -14,7 +14,7 @@ int main() { ( new int[arr_size], // acquire array resource // Cleanup function - [](int* ptr) { delete[] ptr; + [](const int* ptr) { delete[] ptr; std::cout << "Array deleted.\n"; } ); diff --git a/gcovr.cfg b/gcovr.cfg new file mode 100644 index 0000000..52add0f --- /dev/null +++ b/gcovr.cfg @@ -0,0 +1,21 @@ +root = . +search-path = build + +filter = examples/* +# filter = src/* +filter = include/* + +exclude-directories = stagedir +exclude-directories = build/*/*/_deps +exclude-directories = tests +exclude-directories = conan + +gcov-ignore-parse-errors = all +print-summary = yes + +html-details = build/coverage/index.html + +cobertura-pretty = yes +cobertura = build/cobertura.xml + +#TBD delete-gcov-files = yes diff --git a/include/beman/scope/beman.scope.cppm b/include/beman/scope/beman.scope.cppm index 59ce381..3385d96 100644 --- a/include/beman/scope/beman.scope.cppm +++ b/include/beman/scope/beman.scope.cppm @@ -3,13 +3,75 @@ // g++-15 -std=c++26 -O2 -fmodules -fmodule-only -c ${scopetop}/include/beman/scope/beman.scope.cppm module; -#include "scope.hpp" +// Put all implementation-provided headers into the global module fragment +// to prevent attachment to this module. +#ifdef BEMAN_SCOPE_IMPORT_STD +import std; +#else + #include + #include + #include + +// warning: '#include ' attaches the declarations to the named +// module 'beman.scope', which is not usually intended; consider moving that +// directive before the module declaration +// [-Winclude-angled-in-module-purview] +// TODO(CK): #include +#endif + +#ifndef BEMAN_SCOPE_USE_DANIELA_ADVICE + #include +#endif export module beman.scope; +#ifdef BEMAN_SCOPE_USE_DANIELA_ADVICE + #define BEMAN_SCOPE_MODULE_EXPORT export + #define BEMAN_SCOPE_MODULE_BEGIN_EXPORT export { + #define BEMAN_SCOPE_MODULE_END_EXPORT } + + // If you define BEMAN_SCOPE_ATTACH_TO_GLOBAL_MODULE + // - all declarations are detached from module 'beman.scope' + // - the module behaves like a traditional static library, too + // - all library symbols are mangled traditionally + // - you can mix TUs with either importing or #including the {beman.scope} API + #ifdef BEMAN_SCOPE_ATTACH_TO_GLOBAL_MODULE +extern "C++" { + #endif + +// NOTE: this export all implementation details too! CK +export { + + // FIXME: warning: '#include ' attaches the declarations to the named + // module 'beman.scope', which is not usually intended; consider moving that + // directive before the module declaration [-Winclude-angled-in-module-purview] + + #include + +} // end of export + + #ifdef BEMAN_SCOPE_ATTACH_TO_GLOBAL_MODULE +} + #endif + +#else +// ========================================================== +// Note: not needed because of using `module attachment`! +// ========================================================== + export namespace beman::scope { using ::beman::scope::scope_exit; using ::beman::scope::scope_fail; using ::beman::scope::scope_success; using ::beman::scope::unique_resource; } // namespace beman::scope + +// ========================================================== +#endif + +// TODO(CK): g++-15: sorry, unimplemented: private module fragment +// XXX module :private; + +// FIXME: /usr/local/Cellar/gcc/15.2.0_1/include/c++/15/bits/refwrap.h:310:11: +// error: conflicting declaration of 'class std::reference_wrapper<_Tp>' in module 'beman.scope' +// XXX /usr/local/Cellar/gcc/15.2.0_1/include/c++/15/type_traits:75:11: note: previously declared in global module diff --git a/include/beman/scope/scope.hpp b/include/beman/scope/scope.hpp index 7d33b2c..e1ab6bb 100644 --- a/include/beman/scope/scope.hpp +++ b/include/beman/scope/scope.hpp @@ -5,17 +5,38 @@ #include #include +#include #include #include #include // clang-format off -#if __cplusplus < 202002L +#include + +#if defined(__cpp_concepts) && __cpp_concepts >= 201907L + // C++20 concepts supported +#elif __cplusplus < 202002L #error "C++20 or later is required" #endif -// clang-format on -#include //todo unconditional for unique_resource +// detect standard header first, then experimental, otherwise use local implementation +#if defined(__has_include) +# if __has_include() +# include +# define BEMAN_SCOPE_USE_STD +# elif __has_include() +# include +# define BEMAN_SCOPE_USE_STD_EXPERIMENTAL +# else +// no std scope header — fall through to local implementation below +# endif +#elif defined(__cpp_lib_scope) && __cpp_lib_scope >= 2023xxxxL +# include +# define BEMAN_SCOPE_USE_STD +#else +# warning "Missing feature __cpp_lib_scope" +#endif +// clang-format on #ifdef BEMAN_SCOPE_USE_STD_EXPERIMENTAL @@ -31,19 +52,19 @@ template using scope_success = std::experimental::scope_success; // todo temporary -// template -// using unique_resource = std::experimental::unique_resource; +template +using unique_resource = std::experimental::fundamentals_v3::unique_resource; -// template > -// unique_resource, std::decay_t> -// make_unique_resource_checked(R&& r, const S& invalid, D&& d) noexcept(noexcept( -// std::experimental::make_unique_resource_checked(std::forward(r), std::forward(invalid), std::forward(d)))) { -// return std::experimental::make_unique_resource_checked(std::forward(r), std::forward(invalid), std::forward(d)); -//} +template > +unique_resource, std::decay_t> +make_unique_resource_checked(R&& r, const S& invalid, D&& d) noexcept(noexcept( + std::experimental::make_unique_resource_checked(std::forward(r), std::forward(invalid), std::forward(d)))) { + return std::experimental::make_unique_resource_checked(std::forward(r), std::forward(invalid), std::forward(d)); +} } // namespace beman::scope -#else // ! BEMAN_SCOPE__USE_STD_EXPERIMENTAL +#elif defined(BEMAN_SCOPE_USE_STD) namespace beman::scope { @@ -52,8 +73,8 @@ template using unique_resource = std::experimental::unique_resource; // todo temporary -template > -unique_resource, std::decay_t > +template > +unique_resource, std::decay_t> make_unique_resource_checked(R&& r, const S& invalid, D&& d) noexcept(noexcept( std::experimental::make_unique_resource_checked(std::forward(r), std::forward(invalid), std::forward(d)))) { return std::experimental::make_unique_resource_checked(std::forward(r), std::forward(invalid), std::forward(d)); @@ -421,6 +442,9 @@ using scope_fail = scope_guard + +#endif // BEMAN_SCOPE_USE_STD_EXPERIMENTAL #endif // BEMAN_SCOPE_HPP diff --git a/include/beman/scope/scope_impl.hpp b/include/beman/scope/scope_impl.hpp new file mode 100644 index 0000000..6f3923e --- /dev/null +++ b/include/beman/scope/scope_impl.hpp @@ -0,0 +1,336 @@ +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#ifndef SCOPE_IMPL_HPP +#define SCOPE_IMPL_HPP + +#define BEMAN_SCOPE_USE_FALLBACK + +#ifndef BEMAN_SCOPE_IMPORT_STD + #include + + #if defined(__cpp_concepts) && __cpp_concepts >= 201907L + // C++20 concepts supported + #elif __cplusplus < 202002L + #error "C++20 or later is required" + #endif + + // detect standard header first, then experimental, otherwise use local implementation + #ifndef BEMAN_SCOPE_USE_FALLBACK + #ifdef __has_include + #if __has_include() + #include + #define BEMAN_SCOPE_USE_STD + // XXX #warning "Set BEMAN_SCOPE_USE_STD" + #elif __has_include() + #include + #define BEMAN_SCOPE_USE_STD_EXPERIMENTAL + // XXX #warning "Set BEMAN_SCOPE_USE_STD_EXPERIMENTAL" + #else + #define BEMAN_SCOPE_USE_FALLBACK + #endif + #else + #define BEMAN_SCOPE_USE_FALLBACK + #endif + #endif + + #ifdef BEMAN_SCOPE_USE_STD + #if !defined(__cpp_lib_scope_exit) + #error "Standard present but __cpp_lib_scope_exit not defined" + #endif + #endif +#endif + +#ifdef BEMAN_SCOPE_USE_FALLBACK + #if __has_include("beman/scope/modules_export.hpp") + #include "beman/scope/modules_export.hpp" + #else + #define BEMAN_SCOPE_EXPORT + #endif + + #ifndef BEMAN_SCOPE_IMPORT_STD + #include + #include + #include + #endif + +namespace beman::scope { + +// TODO(CK): make a std::experimental::scope_exit::scope_exit conform +// implementation +template +class [[nodiscard]] BEMAN_SCOPE_EXPORT scope_exit { + F f; + bool active = true; + + public: + constexpr explicit scope_exit(F func) noexcept(std::is_nothrow_move_constructible_v) : f(std::move(func)) {} + + // Move constructor + constexpr scope_exit(scope_exit&& other) noexcept(std::is_nothrow_move_constructible_v) + : f(std::move(other.f)), active(other.active) { + other.active = false; + } + + // Deleted copy + auto operator=(const scope_exit&) -> scope_exit& = delete; + scope_exit(const scope_exit&) = delete; + + // Deleted move assignment + // Does scope_exit need to be move-assignable? LEWG: NO! + constexpr auto operator=(scope_exit&& other) noexcept(std::is_nothrow_move_assignable_v) + -> scope_exit& = delete; + + // Destructor: call only if scope is exiting normally + ~scope_exit() noexcept(noexcept(f())) { + if (active) { + f(); + } + } + + // Release to prevent execution + constexpr auto release() -> void { active = false; } + + // Helper to tests if active + constexpr auto is_active() -> bool { return active; } +}; + +// Factory helper +// NOLINTNEXTLINE(misc-use-anonymous-namespace) +template +auto make_scope_exit(F f) -> scope_exit { + return scope_exit(std::move(f)); +} + +// TODO(CK): make a std::experimental::scope_fail::scope_fail conform +// implementation +template +class [[nodiscard]] BEMAN_SCOPE_EXPORT scope_fail { + F f; + bool active = true; + int exception_count{}; + + public: + // Constructor: capture current uncaught exceptions + constexpr explicit scope_fail(F func) noexcept(std::is_nothrow_move_constructible_v) + : f(std::move(func)), exception_count(std::uncaught_exceptions()) {} + + // Move constructor + constexpr scope_fail(scope_fail&& other) noexcept(std::is_nothrow_move_constructible_v) + : f(std::move(other.f)), active(other.active), exception_count(other.exception_count) { + other.active = false; + } + + // Deleted copy + scope_fail(const scope_fail&) = delete; + auto operator=(const scope_fail&) -> scope_fail& = delete; + + // Deleted move assignment + // Move assignment + constexpr auto operator=(scope_fail&& other) noexcept(std::is_nothrow_move_assignable_v) + -> scope_fail& = delete; + #if MOVE_ASSIGNMENT_NEEDED + G { + if (this != &other) { + f = std::move(other.f); + active = other.active; + exception_count = other.exception_count; + other.active = false; + } + return *this; + } + #endif + + // Destructor: call if scope is exiting due to an exception + ~scope_fail() noexcept(noexcept(f())) { + if (active && std::uncaught_exceptions() > exception_count) { + f(); + } + } + + // Release to prevent execution + constexpr auto release() -> void { active = false; } + + // Helper to tests if active + constexpr auto is_active() -> bool { return active; } +}; + +// Factory helper +// NOLINTNEXTLINE(misc-use-anonymous-namespace) +template +constexpr auto make_scope_fail(F&& f) -> scope_fail> { + return scope_fail>(std::forward(f)); +} + +// TODO(CK): make a std::experimental::scope_success::scope_success conform +// implementation +template +class [[nodiscard]] BEMAN_SCOPE_EXPORT scope_success { + F f; + bool active = true; + int exception_count{}; + + public: + // Constructor: capture current uncaught exceptions + constexpr explicit scope_success(F func) noexcept(std::is_nothrow_move_constructible_v) + : f(std::move(func)), exception_count(std::uncaught_exceptions()) {} + + // Move constructor + constexpr scope_success(scope_success&& other) noexcept(std::is_nothrow_move_constructible_v) + : f(std::move(other.f)), active(other.active), exception_count(other.exception_count) { + other.active = false; + } + + // Deleted copy + scope_success(const scope_success&) = delete; + auto operator=(const scope_success&) -> scope_success& = delete; + + // Deleted move assignment + // Move assignment + constexpr auto operator=(scope_success&& other) noexcept(std::is_nothrow_move_assignable_v) + -> scope_success& = delete; + #if MOVE_ASSIGNMENT_NEEDED + { + if (this != &other) { + f = std::move(other.f); + active = other.active; + exception_count = other.exception_count; + other.active = false; + } + return *this; + } + #endif + + // Destructor: call only if scope is exiting normally + ~scope_success() noexcept(noexcept(f())) { + if (active && std::uncaught_exceptions() == exception_count) { + f(); + } + } + + // Release to prevent execution + constexpr auto release() -> void { active = false; } + + // Helper to tests if active + constexpr auto is_active() -> bool { return active; } +}; + +// Factory helper +// NOLINTNEXTLINE(misc-use-anonymous-namespace) +template +constexpr auto make_scope_success(F&& f) -> scope_success> { + return scope_success>(std::forward(f)); +} + +template +class [[nodiscard]] BEMAN_SCOPE_EXPORT unique_resource { + Resource resource; + Deleter deleter; + bool active = true; + + public: + // Constructor + constexpr unique_resource(Resource r, Deleter d) noexcept(std::is_nothrow_move_constructible_v) + : resource(std::move(r)), deleter(std::move(d)) {} + + // Move constructor + constexpr unique_resource(unique_resource&& other) noexcept(std::is_nothrow_move_constructible_v) + : resource(std::move(other.resource)), deleter(std::move(other.deleter)) { + active = std::exchange(other.active, false); + } + + // Move assignment + constexpr auto operator=(unique_resource&& other) noexcept(std::is_nothrow_move_assignable_v) + -> unique_resource& { + if (this != &other) { + reset(std::move(other.resource)); + deleter = std::move(other.deleter); + active = std::exchange(other.active, false); + } + return *this; + } + + // Deleted copy operations + unique_resource(const unique_resource&) = delete; + auto operator=(const unique_resource&) -> unique_resource& = delete; + + // Destructor + ~unique_resource() noexcept(noexcept(deleter(resource))) { reset(); } + + // Release ownership + constexpr void release() noexcept { active = false; } + + // Reset resource + constexpr void reset() noexcept(noexcept(deleter(resource))) { + if (active) { + active = false; + deleter(resource); + } + } + + // Reset the resource and call deleter if engaged + constexpr void reset(Resource new_resource) noexcept(noexcept(deleter(resource))) { + if (active) { + deleter(resource); + } + resource = std::move(new_resource); + active = true; + } + + // Accessors + constexpr auto get() const -> const Resource& { return resource; } + constexpr auto get() -> Resource& { return resource; } + + // operator* — only for non-void pointer resources + constexpr auto operator*() const noexcept -> std::add_lvalue_reference_t> + requires(std::is_pointer_v && !std::is_void_v>) + { + return *resource; + } + + // Optional pointer convenience + constexpr auto operator->() const noexcept -> Resource + requires std::is_pointer_v + { + return resource; + } + + // TODO(CK): missing usecase? + constexpr auto get_deleter() const noexcept -> Deleter; + + // Helper to tests is_active() + // NOTE: check if active; not required from LWG? + constexpr explicit operator bool() const noexcept { return active; } +}; + +// Deduction guide +template +unique_resource(Resource&&, Deleter&&) -> unique_resource, std::decay_t>; + +// Factory: conditionally engaged +// NOLINTNEXTLINE(misc-use-anonymous-namespace) +template +constexpr auto make_unique_resource_checked(R&& r, const Invalid& invalid, D&& d) { + using resource_type = std::decay_t; + using deleter_type = std::decay_t; + + unique_resource ur(resource_type{}, std::forward(d)); + if (r == invalid) { + ur.release(); // disengage immediately + } + return ur; +} + +} // namespace beman::scope + +#elif defined(BEMAN_SCOPE_USE_STD_EXPERIMENTAL) + +namespace beman::scope { +using ::std::experimental::scope_exit; +using ::std::experimental::scope_fail; +using ::std::experimental::scope_success; +using ::std::experimental::unique_resource; +} // namespace beman::scope + +#endif // BEMAN_SCOPE_USE_FALLBACK + +#endif // SCOPE_IMPL_HPP diff --git a/infra/.beman_submodule b/infra/.beman_submodule index bfed167..10ea6a3 100644 --- a/infra/.beman_submodule +++ b/infra/.beman_submodule @@ -1,3 +1,3 @@ [beman_submodule] remote=https://github.com/bemanproject/infra.git -commit_hash=bb58b2a1cc894d58a55bf745be78f5d27029e245 +commit_hash=b3545a45640abd1fedc01441ca3f220d9ac5a8e3 diff --git a/infra/.pre-commit-config.yaml b/infra/.pre-commit-config.yaml index e806e59..bc4dd84 100644 --- a/infra/.pre-commit-config.yaml +++ b/infra/.pre-commit-config.yaml @@ -19,14 +19,3 @@ repos: - id: gersemi name: CMake linting exclude: ^.*/tests/.*/data/ # Exclude test data directories - - # Python linting and formatting - # config file: ruff.toml (not currently present but add if needed) - # https://docs.astral.sh/ruff/configuration/ - - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.13.2 - hooks: - - id: ruff-check - files: ^tools/beman-tidy/ - - id: ruff-format - files: ^tools/beman-tidy/ diff --git a/infra/.pre-commit-hooks.yaml b/infra/.pre-commit-hooks.yaml deleted file mode 100644 index d327587..0000000 --- a/infra/.pre-commit-hooks.yaml +++ /dev/null @@ -1,7 +0,0 @@ -- id: beman-tidy - name: "beman-tidy: bemanification your repo" - entry: ./tools/beman-tidy/beman-tidy - language: script - pass_filenames: false - always_run: true - args: [".", "--verbose"] diff --git a/infra/cmake/beman-install-library-config.cmake b/infra/cmake/beman-install-library-config.cmake index e7fd0ad..c40959d 100644 --- a/infra/cmake/beman-install-library-config.cmake +++ b/infra/cmake/beman-install-library-config.cmake @@ -84,8 +84,8 @@ function(beman_install_library name) option( ${project_prefix}_INSTALL_CONFIG_FILE_PACKAGE - "Enable building examples. Default: ${PROJECT_IS_TOP_LEVEL}. Values: { ON, OFF }." - ${PROJECT_IS_TOP_LEVEL} + "Enable creating and installing a CMake config-file package. Default: ON. Values: { ON, OFF }." + ON ) # By default, install the config package @@ -121,7 +121,7 @@ function(beman_install_library name) find_file( config_file_template NAMES "${package_name}-config.cmake.in" - PATHS "${CMAKE_CURRENT_SOURCE_DIR}" + PATHS "${PROJECT_SOURCE_DIR}/cmake" NO_DEFAULT_PATH NO_CACHE REQUIRED diff --git a/makefile b/makefile new file mode 100644 index 0000000..bff6854 --- /dev/null +++ b/makefile @@ -0,0 +1,80 @@ +# Standard stuff + +.SUFFIXES: + +MAKEFLAGS+= --no-builtin-rules # Disable the built-in implicit rules. +MAKEFLAGS+= --warn-undefined-variables # Warn when an undefined variable is referenced. + +export hostSystemName=$(shell uname) + +ifeq (${hostSystemName},Darwin) + export LLVM_PREFIX:=$(shell brew --prefix llvm) + export LLVM_DIR:=$(shell realpath ${LLVM_PREFIX}) + export PATH:=${LLVM_DIR}/bin:${PATH} + + export CMAKE_CXX_STDLIB_MODULES_JSON:=${LLVM_DIR}/lib/c++/libc++.modules.json + export CXXFLAGS:=-stdlib=libc++ + export LDFLAGS:=-L$(LLVM_DIR)/lib/c++ -lc++abi # XXX -lc++ + export CXX:=clang++ + export GCOV:="llvm-cov gcov" + + ### TODO: to test g++-15: + export GCC_PREFIX:=$(shell brew --prefix gcc) + export GCC_DIR:=$(shell realpath ${GCC_PREFIX}) + + # export CMAKE_CXX_STDLIB_MODULES_JSON:=${GCC_DIR}/lib/gcc/current/libstdc++.modules.json + # export CXXFLAGS:=-stdlib=libstdc++ + # export LDFLAGS:=-L$(GCC_DIR)/lib/gcc/current # XXX -lstdc++ -lstdc++exp + # export CXX:=g++-15 + # export GCOV:="gcov" +else ifeq (${hostSystemName},Linux) + export LLVM_DIR:=/usr/lib/llvm-20 + export PATH:=${LLVM_DIR}/bin:${PATH} + export CXX:=clang++-20 +endif + +.PHONY: all ctest cinstall coverage gclean distclean format + +all: build/compile_commands.json + ln -sf $< . + ninja -C build all all_verify_interface_header_sets + ninja -C build test + +ctest: + ctest --test-dir build --verbose --rerun-failed --output-on-failure + +build/compile_commands.json: CMakeLists.txt makefile + cmake -S . -B build -G Ninja --log-level=VERBOSE -D CMAKE_BUILD_TYPE=Release \ + -D CMAKE_CXX_STDLIB_MODULES_JSON=${CMAKE_CXX_STDLIB_MODULES_JSON} \ + -D CMAKE_CXX_STANDARD=26 -D CMAKE_CXX_EXTENSIONS=YES -D CMAKE_CXX_STANDARD_REQUIRED=YES \ + -D CMAKE_INSTALL_MESSAGE=LAZY \ + -D BEMAN_USE_MODULES=YES \ + -D BEMAN_USE_STD_MODULE=YES \ + -D BEMAN_SCOPE_USE_DANIELA_ADVICE=YES \ + -D CMAKE_SKIP_TEST_ALL_DEPENDENCY=NO \ + # XXX -D CMAKE_CXX_FLAGS='-fno-inline --coverage' \ + # XXX -D CMAKE_SKIP_INSTALL_RULES=YES # --fresh + +cinstall: build/cmake_install.cmake + cmake --install build + +distclean: # XXX clean + rm -rf build compile_commands.json + find . -name '*~' -delete + +gclean: clean + find build -name '*.gc..' -delete + +build/coverage: test + mkdir -p $@ + +coverage: build/coverage + gcovr --merge-mode-functions separate + +format: distclean + pre-commit autoupdate + pre-commit run --all + +# Anything we don't know how to build will use this rule. +% :: + ninja -C build $(@) diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index a7cbcfc..f84de11 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -2,32 +2,82 @@ include(FetchContent) +if(APPLE AND CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + set(_FIND_PACKAGE_ARGS) +else() + set(_FIND_PACKAGE_ARGS FIND_PACKAGE_ARGS 3.13) +endif() + FetchContent_Declare( Catch2 GIT_REPOSITORY https://github.com/catchorg/Catch2.git - GIT_TAG v3.11.0 + GIT_TAG v3.13.0 EXCLUDE_FROM_ALL - # FIND_PACKAGE_ARGS 3.11 + ${_FIND_PACKAGE_ARGS} ) FetchContent_MakeAvailable(Catch2) -set(ALL_TESTNAMES scope_success scope_exit scope_fail unique_resource) +set(ALL_TESTNAMES + scope_success + scope_exit + scope_fail + unique_resource + unique_resource_2 +) + +include(Catch) # module tests will only compile with gcc15 or clang20 and above -if(CMAKE_CXX_SCAN_FOR_MODULES) - list(APPEND ALL_TESTNAMES module) +if(BEMAN_USE_MODULES) + add_executable(test.module module.test.cpp) + target_link_libraries( + test.module + PRIVATE Catch2::Catch2WithMain beman::scope + ) + if(BEMAN_SCOPE_IMPORT_STD) + set_target_properties(test.module PROPERTIES CXX_MODULE_STD ON) + endif() + # NO! add_test(NAME test.module COMMAND test.module) + catch_discover_tests(test.module) endif() message("Tests to be built: ${ALL_TESTNAMES}") -include(Catch) - foreach(testname ${ALL_TESTNAMES}) add_executable(test.${testname}) target_sources(test.${testname} PRIVATE ${testname}.test.cpp) target_link_libraries( test.${testname} - PRIVATE Catch2::Catch2WithMain beman::scope + PRIVATE Catch2::Catch2WithMain beman::scope_headers ) catch_discover_tests(test.${testname}) endforeach() + +if(BEMAN_SCOPE_INSTALL_CONFIG_FILE_PACKAGE) + # test if the targets are usable from the install directory + add_test( + NAME install-to-stagedir + COMMAND + ${CMAKE_COMMAND} --install ${CMAKE_BINARY_DIR} --prefix + ${CMAKE_BINARY_DIR}/stagedir --config $ + ) + add_test( + NAME find-package-test + COMMAND + ${CMAKE_CTEST_COMMAND} # --verbose + --output-on-failure -C $ --build-and-test + "${CMAKE_SOURCE_DIR}/examples" + "${CMAKE_CURRENT_BINARY_DIR}/find-package-test" --build-generator + ${CMAKE_GENERATOR} --build-makeprogram ${CMAKE_MAKE_PROGRAM} + --build-options # + "-D BEMAN_SCOPE_IMPORT_STD=${BEMAN_SCOPE_IMPORT_STD}" + "-D BEMAN_SCOPE_USE_DANIELA_ADVICE=${BEMAN_SCOPE_USE_DANIELA_ADVICE}" + "-D BEMAN_USE_STD_MODULE=${BEMAN_USE_STD_MODULE}" + "-D CMAKE_BUILD_TYPE=$" + "-D CMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}" + "-D CMAKE_CXX_EXTENSIONS=${CMAKE_CXX_EXTENSIONS}" + "-D CMAKE_CXX_STANDARD=${CMAKE_CXX_STANDARD}" + "-D CMAKE_PREFIX_PATH=${CMAKE_BINARY_DIR}/stagedir" + "-D CMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE}" + ) +endif() diff --git a/tests/module.test.cpp b/tests/module.test.cpp index a4b22fc..a72bfb1 100644 --- a/tests/module.test.cpp +++ b/tests/module.test.cpp @@ -3,35 +3,44 @@ #define CATCH_CONFIG_MAIN #include -// for g++-15 the order is important -- import after includes +// for g++-15 the order is important -- import after #includes +#ifdef BEMAN_SCOPE_IMPORT_STD +import std; +#endif import beman.scope; +namespace { + struct DummyResource { bool& cleaned; DummyResource(bool& flag) : cleaned(flag) { cleaned = false; } - bool is_clean() const { return cleaned; } + [[nodiscard]] bool is_clean() const { return cleaned; } }; +} // namespace + TEST_CASE("module-test", "[scope_module_test]") { - bool exit_ran, success_ran, fail_ran = false; - bool cleaned = true; + bool exit_ran{}; + bool success_ran{}; + bool fail_ran{}; + bool cleaned{true}; { // clang-format off beman::scope::scope_exit _se([&exit_ran] { exit_ran = true; }); beman::scope::scope_success _ss([&success_ran] { success_ran = true; }); beman::scope::scope_fail _sf([&fail_ran] { fail_ran = true; }); - auto resource_ptr = beman::scope::unique_resource(new DummyResource(cleaned), - [](DummyResource* ptr) { ptr->cleaned =true; delete ptr; }); - REQUIRE(cleaned == false); - REQUIRE(resource_ptr->is_clean() == false); + auto resource_ptr = beman::scope::unique_resource(new DummyResource(cleaned), + [](DummyResource* ptr) { ptr->cleaned = true; delete ptr; }); // clang-format on + + REQUIRE(cleaned == false); + REQUIRE(resource_ptr->is_clean() == false); } // Normal scope exit REQUIRE(exit_ran == true); REQUIRE(success_ran == true); REQUIRE(fail_ran == false); REQUIRE(cleaned == true); - } diff --git a/tests/scope_exit.test.cpp b/tests/scope_exit.test.cpp index 65acf7a..51a4477 100644 --- a/tests/scope_exit.test.cpp +++ b/tests/scope_exit.test.cpp @@ -125,6 +125,25 @@ TEST_CASE("scope_exit handles nested guards in correct order", "[scope_exit][adv REQUIRE(trace == "second first "); } +// fails +// #include +// +// TEST_CASE("scope_exit move assignment transfers ownership", "[scope_exit][advanced]") { +// bool cleanup_ran = false; +// +// { +// scope_exit> guard1([&]{ cleanup_ran = true; }); +// scope_exit> guard2([&]{}); +// +// guard2 = std::move(guard1); +// +// REQUIRE_FALSE(guard1.is_active()); +// REQUIRE(guard2.is_active()); +// } +// +// REQUIRE(cleanup_ran == false); +// } + // fails // TEST_CASE("scope_exit cleanup handles custom object with side effects", "[scope_exit][advanced]") { // struct Tracer { diff --git a/tests/unique_resource.test.cpp b/tests/unique_resource.test.cpp index 48f611d..9edd61e 100644 --- a/tests/unique_resource.test.cpp +++ b/tests/unique_resource.test.cpp @@ -68,7 +68,7 @@ TEST_CASE("unique_resource does not clean up after release", "[unique_resource]" [](DummyResource r) { *(r.cleanedUp) = true; } ); - res.release(); //no cleanup run + res.release(); // no cleanup run } REQUIRE(cleaned == false); diff --git a/tests/unique_resource_2.test.cpp b/tests/unique_resource_2.test.cpp new file mode 100644 index 0000000..b613d5c --- /dev/null +++ b/tests/unique_resource_2.test.cpp @@ -0,0 +1,277 @@ +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception + +#include "beman/scope/scope.hpp" + +#include +#include +#include + +namespace { + +struct Counter { + int value = 0; +}; + +struct CountingDeleter { + // NOLINTNEXTLINE(misc-non-private-member-variables-in-classes) + Counter* counter{nullptr}; + + void operator()(int& /*unused*/) const noexcept { ++counter->value; } +}; + +} // namespace + +TEST_CASE("Construct file unique_resource", "[unique_resource]") { + bool open_file_good = false; + bool close_file_good = false; + + { + auto file = beman::scope::unique_resource(fopen("example.txt", "w"), // Acquire the FILE* + [&close_file_good](FILE* f) -> void { + if (f) { + (void)fclose(f); // Release (cleanup) the resource + close_file_good = true; + } + }); + + if (file.get() == nullptr) { + throw std::runtime_error("file didn't open"); + } + open_file_good = true; + } + + REQUIRE(open_file_good == true); + REQUIRE(close_file_good == true); +} + +TEST_CASE("unique_resource basic construction and engagement", "[unique_resource]") { + Counter c{}; // NOLINT(misc-const-correctness) + { + beman::scope::unique_resource r(42, CountingDeleter{&c}); + + // XXX REQUIRE(static_cast(r)); + REQUIRE(r.get() == 42); + REQUIRE(c.value == 0); + } + + REQUIRE(c.value == 1); +} + +TEST_CASE("unique_resource release disengages without deleting", "[unique_resource]") { + Counter c{}; // NOLINT(misc-const-correctness) + { + beman::scope::unique_resource r(7, CountingDeleter{&c}); + + r.release(); + + // XXX REQUIRE_FALSE(r); + } + + REQUIRE(c.value == 0); +} + +TEST_CASE("unique_resource reset() destroys current resource", "[unique_resource]") { + Counter c{}; // NOLINT(misc-const-correctness) + + { + beman::scope::unique_resource r(1, CountingDeleter{&c}); + + r.reset(); + // XXX REQUIRE_FALSE(r); + REQUIRE(c.value == 1); + } + + REQUIRE(c.value == 1); +} + +TEST_CASE("unique_resource reset(new_resource) replaces resource", "[unique_resource]") { + Counter c{}; // NOLINT(misc-const-correctness) + + { + beman::scope::unique_resource r(1, CountingDeleter{&c}); + + r.reset(2); + + // XXX REQUIRE(r); + REQUIRE(r.get() == 2); + REQUIRE(c.value == 1); + } + + REQUIRE(c.value == 2); +} + +TEST_CASE("unique_resource move constructor transfers ownership", "[unique_resource]") { + Counter c{}; // NOLINT(misc-const-correctness) + + beman::scope::unique_resource r1(10, CountingDeleter{&c}); + beman::scope::unique_resource r2(std::move(r1)); + + // XXX REQUIRE_FALSE(r1); + // XXX REQUIRE(r2); + REQUIRE(r2.get() == 10); + + r2.reset(); + REQUIRE(c.value == 1); +} + +TEST_CASE("unique_resource move assignment destroys target before transfer", "[unique_resource]") { + Counter c1{}; // NOLINT(misc-const-correctness) + Counter c2{}; // NOLINT(misc-const-correctness) + + beman::scope::unique_resource r1(1, CountingDeleter{&c1}); + beman::scope::unique_resource r2(2, CountingDeleter{&c2}); + + r2 = std::move(r1); + + // XXX REQUIRE_FALSE(r1); + // XXX REQUIRE(r2); + REQUIRE(r2.get() == 1); + + REQUIRE(c2.value == 1); // old r2 destroyed + REQUIRE(c1.value == 0); + + r2.reset(); + REQUIRE(c1.value == 1); +} + +TEST_CASE("unique_resource destructor is idempotent after release", "[unique_resource]") { + Counter c{}; // NOLINT(misc-const-correctness) + + { + beman::scope::unique_resource r(99, CountingDeleter{&c}); + + r.release(); + } + + REQUIRE(c.value == 0); +} +#ifdef BEMAN_SCOPE_USE_FALLBACK +TEST_CASE("make_unique_resource_checked disengages on invalid", "[unique_resource]") { + Counter c{}; // NOLINT(misc-const-correctness) + + { + auto r = beman::scope::make_unique_resource_checked(-1, -1, CountingDeleter{&c}); + + // XXX REQUIRE_FALSE(r); + } + + REQUIRE(c.value == 0); +} + +TEST_CASE("make_unique_resource_checked engages on valid", "[unique_resource]") { + Counter c{}; // NOLINT(misc-const-correctness) + + { + auto r = beman::scope::make_unique_resource_checked(3, -1, CountingDeleter{&c}); + + // XXX REQUIRE(r); + } + + REQUIRE(c.value == 1); +} + +TEST_CASE("Open a nonexisting file with make_unique_resource_checked", "[unique_resource]") { + bool open_file_good = false; + bool close_file_good = false; + + { + auto file = + beman::scope::make_unique_resource_checked(fopen("nonexisting.txt", "r"), // Acquire the FILE* + nullptr, + [&close_file_good](FILE* f) -> void { + if (f) { + (void)fclose(f); // Release (cleanup) the resource + close_file_good = true; + } + }); + + if (file.get() != nullptr) { + open_file_good = true; + } + } + + REQUIRE(open_file_good == false); + REQUIRE(close_file_good == false); +} +#endif + +TEST_CASE("unique_resource supports deduction guide", "[unique_resource]") { + Counter c{}; // NOLINT(misc-const-correctness) + + beman::scope::unique_resource r(123, CountingDeleter{&c}); + + static_assert(std::is_same_v>); + + r.reset(); + REQUIRE(c.value == 1); +} + +TEST_CASE("unique_resource does not double-delete after move", "[unique_resource]") { + Counter c{}; // NOLINT(misc-const-correctness) + + { + beman::scope::unique_resource r1(1, CountingDeleter{&c}); + + { + auto r2 = std::move(r1); + } + + REQUIRE(c.value == 1); + } + + REQUIRE(c.value == 1); +} + +TEST_CASE("unique_resource operator* returns reference to resource", "[unique_resource]") { + int value = 42; + + // Define the deleter type explicitly (function pointer) + using DeleterType = void (*)(int*); + + // Empty deleter + auto empty_deleter = [](int*) {}; + + // Create unique_resource instance (modifiable) + beman::scope::unique_resource r(&value, empty_deleter); + + // operator* should return a reference + int& ref = *r; + + // Check that the reference refers to the original value + REQUIRE(&ref == &value); + REQUIRE(ref == 42); + + // Modify the value through the reference + ref = 100; + REQUIRE(value == 100); + + // Create a const unique_resource instance + const beman::scope::unique_resource r2(&value, empty_deleter); + + // operator* should return const reference + const int& cref = *r2; + REQUIRE(cref == 100); + + // Modifying through cref would fail to compile (correct) +} + +struct Foo { + int value = 0; +}; + +TEST_CASE("unique_resource operator-> works", "[unique_resource]") { + bool deleted = false; + Foo* raw = new Foo{42}; + + // Use std::function for the deleter + beman::scope::unique_resource> r(raw, [&](Foo* p) { + deleted = true; + delete p; + }); + + REQUIRE(r->value == 42); + r->value = 100; + REQUIRE(r->value == 100); + + REQUIRE_FALSE(deleted); // deleter not called yet +}