diff --git a/.drone.jsonnet b/.drone.jsonnet new file mode 100644 index 00000000..867f472d --- /dev/null +++ b/.drone.jsonnet @@ -0,0 +1,234 @@ +# Copyright 2022 Peter Dimov +# Distributed under the Boost Software License, Version 1.0. +# https://www.boost.org/LICENSE_1_0.txt + +local library = "leaf"; + +local triggers = +{ + branch: [ "master", "develop", "feature/*" ] +}; + +local ubsan = { UBSAN: '1', UBSAN_OPTIONS: 'print_stacktrace=1' }; +local asan = { ASAN: '1' }; + +local linux_pipeline(name, image, environment, packages = "", sources = [], arch = "amd64") = +{ + name: name, + kind: "pipeline", + type: "docker", + trigger: triggers, + platform: + { + os: "linux", + arch: arch + }, + steps: + [ + { + name: "everything", + image: image, + environment: environment, + commands: + [ + 'set -e', + 'wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key | apt-key add -', + ] + + (if sources != [] then [ ('apt-add-repository "' + source + '"') for source in sources ] else []) + + (if packages != "" then [ 'apt-get update', 'apt-get -y install ' + packages ] else []) + + [ + 'export LIBRARY=' + library, + './.drone/drone.sh', + ] + } + ] +}; + +local macos_pipeline(name, environment, xcode_version = "14.1", osx_version = "monterey", arch = "arm64") = +{ + name: name, + kind: "pipeline", + type: "exec", + trigger: triggers, + platform: { + "os": "darwin", + "arch": arch + }, + node: { + "os": osx_version + }, + steps: [ + { + name: "everything", + environment: environment + { "DEVELOPER_DIR": "/Applications/Xcode-" + xcode_version + ".app/Contents/Developer" }, + commands: + [ + 'export LIBRARY=' + library, + './.drone/drone.sh', + ] + } + ] +}; + +local windows_pipeline(name, image, environment, arch = "amd64") = +{ + name: name, + kind: "pipeline", + type: "docker", + trigger: triggers, + platform: + { + os: "windows", + arch: arch + }, + "steps": + [ + { + name: "everything", + image: image, + environment: environment, + commands: + [ + 'cmd /C .drone\\\\drone.bat ' + library, + ] + } + ] +}; + +[ + linux_pipeline( + "Linux 16.04 GCC 5*", + "cppalliance/droneubuntu1604:1", + { TOOLSET: 'gcc', COMPILER: 'g++', CXXSTD: '11,14' }, + ), + + linux_pipeline( + "Linux 18.04 GCC 6", + "cppalliance/droneubuntu1804:1", + { TOOLSET: 'gcc', COMPILER: 'g++-6', CXXSTD: '11,14' }, + "g++-6", + ), + + linux_pipeline( + "Linux 18.04 GCC 7* 32", + "cppalliance/droneubuntu1804:1", + { TOOLSET: 'gcc', COMPILER: 'g++', CXXSTD: '11,14', ADDRMD: '32' }, + ), + + linux_pipeline( + "Linux 18.04 GCC 7* 64", + "cppalliance/droneubuntu1804:1", + { TOOLSET: 'gcc', COMPILER: 'g++', CXXSTD: '11,14', ADDRMD: '64' }, + ), + + linux_pipeline( + "Linux 18.04 GCC 8", + "cppalliance/droneubuntu1804:1", + { TOOLSET: 'gcc', COMPILER: 'g++-8', CXXSTD: '11,14,17' }, + "g++-8", + ), + + linux_pipeline( + "Linux 20.04 GCC 9* 32", + "cppalliance/droneubuntu2004:1", + { TOOLSET: 'gcc', COMPILER: 'g++', CXXSTD: '11,14,17,2a', ADDRMD: '32' }, + ), + + linux_pipeline( + "Linux 20.04 GCC 9* 64", + "cppalliance/droneubuntu2004:1", + { TOOLSET: 'gcc', COMPILER: 'g++', CXXSTD: '11,14,17,2a', ADDRMD: '64' }, + ), + + linux_pipeline( + "Linux 20.04 GCC 9 ARM64 32/64", + "cppalliance/droneubuntu2004:multiarch", + { TOOLSET: 'gcc', COMPILER: 'g++', CXXSTD: '11,14,17,2a', ADDRMD: '32,64' }, + arch="arm64", + ), + + linux_pipeline( + "Linux 20.04 GCC 10 32 ASAN", + "cppalliance/droneubuntu2004:1", + { TOOLSET: 'gcc', COMPILER: 'g++-10', CXXSTD: '11,14,17,20', ADDRMD: '32' } + asan, + "g++-10-multilib", + ), + + linux_pipeline( + "Linux 20.04 GCC 10 64 ASAN", + "cppalliance/droneubuntu2004:1", + { TOOLSET: 'gcc', COMPILER: 'g++-10', CXXSTD: '11,14,17,20', ADDRMD: '64' } + asan, + "g++-10-multilib", + ), + + linux_pipeline( + "Linux 16.04 Clang 3.6", + "cppalliance/droneubuntu1604:1", + { TOOLSET: 'clang', COMPILER: 'clang++-3.6', CXXSTD: '11,14' }, + "clang-3.6", + ), + + linux_pipeline( + "Linux 16.04 Clang 3.7", + "cppalliance/droneubuntu1604:1", + { TOOLSET: 'clang', COMPILER: 'clang++-3.7', CXXSTD: '11,14' }, + "clang-3.7", + ), + + linux_pipeline( + "Linux 16.04 Clang 3.8", + "cppalliance/droneubuntu1604:1", + { TOOLSET: 'clang', COMPILER: 'clang++-3.8', CXXSTD: '11,14' }, + "clang-3.8", + ), + + linux_pipeline( + "Linux 20.04 Clang 13", + "cppalliance/droneubuntu2004:1", + { TOOLSET: 'clang', COMPILER: 'clang++-13', CXXSTD: '11,14,17,20' }, + "clang-13", + ["deb http://apt.llvm.org/focal/ llvm-toolchain-focal-13 main"], + ), + + linux_pipeline( + "Linux 22.04 Clang 14 UBSAN", + "cppalliance/droneubuntu2204:1", + { TOOLSET: 'clang', COMPILER: 'clang++-14', CXXSTD: '11,14,17,20' } + ubsan, + "clang-14", + ), + + linux_pipeline( + "Linux 22.04 Clang 14 ASAN", + "cppalliance/droneubuntu2204:1", + { TOOLSET: 'clang', COMPILER: 'clang++-14', CXXSTD: '11,14,17,20' } + asan, + "clang-14", + ), + + macos_pipeline( + "MacOS 12.5.1 Xcode 14.1 UBSAN", + { TOOLSET: 'clang', COMPILER: 'clang++', CXXSTD: '14,17,20' } + ubsan, + ), + + macos_pipeline( + "MacOS 12.5.1 Xcode 14.1 ASAN", + { TOOLSET: 'clang', COMPILER: 'clang++', CXXSTD: '14,17,20' } + asan, + ), + + windows_pipeline( + "Windows VS2017 msvc-14.1", + "cppalliance/dronevs2017", + { TOOLSET: 'msvc-14.1', CXXSTD: '14,17,latest' }, + ), + + windows_pipeline( + "Windows VS2019 msvc-14.2", + "cppalliance/dronevs2019", + { TOOLSET: 'msvc-14.2', CXXSTD: '14,17,20,latest' }, + ), + + windows_pipeline( + "Windows VS2022 msvc-14.3", + "cppalliance/dronevs2022:1", + { TOOLSET: 'msvc-14.3', CXXSTD: '14,17,20,latest' }, + ), +] diff --git a/.drone.star b/.drone.star deleted file mode 100644 index 2d1b15aa..00000000 --- a/.drone.star +++ /dev/null @@ -1,55 +0,0 @@ -# Use, modification, and distribution are -# subject to the Boost Software License, Version 1.0. (See accompanying -# file LICENSE.txt) -# -# Copyright Rene Rivera 2020. - -# For Drone CI we use the Starlark scripting language to reduce duplication. -# As the yaml syntax for Drone CI is rather limited. -# -# -globalenv={} -linuxglobalimage="cppalliance/droneubuntu1404:1" -windowsglobalimage="cppalliance/dronevs2019" - -def main(ctx): - return [ - osx_cxx("UBSAN=1 TOOLSET=clang COMPILER=clang++ CXXSTD Job 1", "clang++", packages="", buildtype="boost", buildscript="drone", environment={'UBSAN': '1', 'TOOLSET': 'clang', 'COMPILER': 'clang++', 'CXXSTD': '11,14', 'UBSAN_OPTIONS': 'print_stacktrace=1', 'DRONE_JOB_UUID': '356a192b79'}, globalenv=globalenv), - osx_cxx("UBSAN=1 TOOLSET=clang COMPILER=clang++ CXXSTD Job 2", "clang++", packages="", buildtype="boost", buildscript="drone", environment={'UBSAN': '1', 'TOOLSET': 'clang', 'COMPILER': 'clang++', 'CXXSTD': '1z,2a', 'UBSAN_OPTIONS': 'print_stacktrace=1', 'DRONE_JOB_UUID': 'da4b9237ba'}, globalenv=globalenv), - osx_cxx("TOOLSET=clang COMPILER=clang++ CXXSTD=11,14,1 Job 3", "clang++", packages="", buildtype="boost", buildscript="drone", xcode_version="11.5", environment={'TOOLSET': 'clang', 'COMPILER': 'clang++', 'CXXSTD': '11,14,1z', 'DRONE_JOB_UUID': '77de68daec'}, globalenv=globalenv), - osx_cxx("TOOLSET=clang COMPILER=clang++ CXXSTD=11,14,1 Job 4", "clang++", packages="", buildtype="boost", buildscript="drone", xcode_version="11.4", environment={'TOOLSET': 'clang', 'COMPILER': 'clang++', 'CXXSTD': '11,14,1z', 'DRONE_JOB_UUID': '1b64538924'}, globalenv=globalenv), - osx_cxx("TOOLSET=clang COMPILER=clang++ CXXSTD=11,14,1 Job 5", "clang++", packages="", buildtype="boost", buildscript="drone", xcode_version="11.3", environment={'TOOLSET': 'clang', 'COMPILER': 'clang++', 'CXXSTD': '11,14,1z', 'DRONE_JOB_UUID': 'ac3478d69a'}, globalenv=globalenv), - osx_cxx("TOOLSET=clang COMPILER=clang++ CXXSTD=11,14,1 Job 6", "clang++", packages="", buildtype="boost", buildscript="drone", xcode_version="11.2", environment={'TOOLSET': 'clang', 'COMPILER': 'clang++', 'CXXSTD': '11,14,1z', 'DRONE_JOB_UUID': 'c1dfd96eea'}, globalenv=globalenv), - osx_cxx("TOOLSET=clang COMPILER=clang++ CXXSTD=11,14,1 Job 7", "clang++", packages="", buildtype="boost", buildscript="drone", xcode_version="11.1", environment={'TOOLSET': 'clang', 'COMPILER': 'clang++', 'CXXSTD': '11,14,1z', 'DRONE_JOB_UUID': '902ba3cda1'}, globalenv=globalenv), - osx_cxx("TOOLSET=clang COMPILER=clang++ CXXSTD=11,14,1 Job 8", "clang++", packages="", buildtype="boost", buildscript="drone", xcode_version="11", environment={'TOOLSET': 'clang', 'COMPILER': 'clang++', 'CXXSTD': '11,14,1z', 'DRONE_JOB_UUID': 'fe5dbbcea5'}, globalenv=globalenv), - osx_cxx("TOOLSET=clang COMPILER=clang++ CXXSTD=11,14,1 Job 9", "clang++", packages="", buildtype="boost", buildscript="drone", xcode_version="10.3", environment={'TOOLSET': 'clang', 'COMPILER': 'clang++', 'CXXSTD': '11,14,1z', 'DRONE_JOB_UUID': '0ade7c2cf9'}, globalenv=globalenv), - osx_cxx("TOOLSET=clang COMPILER=clang++ CXXSTD=11,14,1 Job 10", "clang++", packages="", buildtype="boost", buildscript="drone", xcode_version="10.2", environment={'TOOLSET': 'clang', 'COMPILER': 'clang++', 'CXXSTD': '11,14,1z', 'DRONE_JOB_UUID': 'b1d5781111'}, globalenv=globalenv), - osx_cxx("TOOLSET=clang COMPILER=clang++ CXXSTD=11,14,1 Job 11", "clang++", packages="", buildtype="boost", buildscript="drone", xcode_version="10.1", environment={'TOOLSET': 'clang', 'COMPILER': 'clang++', 'CXXSTD': '11,14,1z', 'DRONE_JOB_UUID': '17ba079149'}, globalenv=globalenv), - linux_cxx("UBSAN=1 TOOLSET=gcc COMPILER=g++-9 CXXSTD=11, Job 12", "g++-9", packages="g++-9", buildtype="boost", buildscript="drone", image=linuxglobalimage, environment={'UBSAN': '1', 'TOOLSET': 'gcc', 'COMPILER': 'g++-9', 'CXXSTD': '11,14', 'UBSAN_OPTIONS': 'print_stacktrace=1', 'LINKFLAGS': '-fuse-ld=gold', 'DRONE_JOB_UUID': '7b52009b64'}, globalenv=globalenv), - linux_cxx("UBSAN=1 TOOLSET=gcc COMPILER=g++-9 CXXSTD=17, Job 13", "g++-9", packages="g++-9", buildtype="boost", buildscript="drone", image=linuxglobalimage, environment={'UBSAN': '1', 'TOOLSET': 'gcc', 'COMPILER': 'g++-9', 'CXXSTD': '17,2a', 'UBSAN_OPTIONS': 'print_stacktrace=1', 'LINKFLAGS': '-fuse-ld=gold', 'DRONE_JOB_UUID': 'bd307a3ec3'}, globalenv=globalenv), - linux_cxx("TOOLSET=gcc COMPILER=g++-9 CXXSTD=11,14,17,2a Job 14", "g++-9", packages="g++-9", buildtype="boost", buildscript="drone", image=linuxglobalimage, environment={'TOOLSET': 'gcc', 'COMPILER': 'g++-9', 'CXXSTD': '11,14,17,2a', 'DRONE_JOB_UUID': 'fa35e19212'}, globalenv=globalenv), - linux_cxx("TOOLSET=gcc COMPILER=g++-8 CXXSTD=11,14,17 Job 15", "g++-8", packages="g++-8", buildtype="boost", buildscript="drone", image=linuxglobalimage, environment={'TOOLSET': 'gcc', 'COMPILER': 'g++-8', 'CXXSTD': '11,14,17', 'DRONE_JOB_UUID': 'f1abd67035'}, globalenv=globalenv), - linux_cxx("TOOLSET=gcc COMPILER=g++-7 CXXSTD=11,14 Job 16", "g++-7", packages="g++-7", buildtype="boost", buildscript="drone", image=linuxglobalimage, environment={'TOOLSET': 'gcc', 'COMPILER': 'g++-7', 'CXXSTD': '11,14', 'DRONE_JOB_UUID': '1574bddb75'}, globalenv=globalenv), - linux_cxx("TOOLSET=gcc COMPILER=g++-6 CXXSTD=11,14 Job 17", "g++-6", packages="g++-6", buildtype="boost", buildscript="drone", image=linuxglobalimage, environment={'TOOLSET': 'gcc', 'COMPILER': 'g++-6', 'CXXSTD': '11,14', 'DRONE_JOB_UUID': '0716d9708d'}, globalenv=globalenv), - linux_cxx("TOOLSET=gcc COMPILER=g++-5 CXXSTD=11,14 Job 18", "g++-5", packages="g++-5", buildtype="boost", buildscript="drone", image=linuxglobalimage, environment={'TOOLSET': 'gcc', 'COMPILER': 'g++-5', 'CXXSTD': '11,14', 'DRONE_JOB_UUID': '9e6a55b6b4'}, globalenv=globalenv), - linux_cxx("TOOLSET=gcc COMPILER=g++-4.9 CXXSTD=11 Job 19", "g++-4.9", packages="g++-4.9", buildtype="boost", buildscript="drone", image=linuxglobalimage, environment={'TOOLSET': 'gcc', 'COMPILER': 'g++-4.9', 'CXXSTD': '11', 'DRONE_JOB_UUID': 'b3f0c7f6bb'}, globalenv=globalenv), - linux_cxx("UBSAN=1 TOOLSET=clang COMPILER=clang++-8 CXXS Job 20", "clang++-8", packages="clang-8", llvm_os="trusty", llvm_ver="8", buildtype="boost", buildscript="drone", image=linuxglobalimage, environment={'UBSAN': '1', 'TOOLSET': 'clang', 'COMPILER': 'clang++-8', 'CXXSTD': '11,14', 'UBSAN_OPTIONS': 'print_stacktrace=1', 'DRONE_JOB_UUID': '91032ad7bb'}, globalenv=globalenv), - linux_cxx("UBSAN=1 TOOLSET=clang COMPILER=clang++-8 CXXS Job 21", "clang++-8", packages="clang-8", llvm_os="trusty", llvm_ver="8", buildtype="boost", buildscript="drone", image=linuxglobalimage, environment={'UBSAN': '1', 'TOOLSET': 'clang', 'COMPILER': 'clang++-8', 'CXXSTD': '17,2a', 'UBSAN_OPTIONS': 'print_stacktrace=1', 'DRONE_JOB_UUID': '472b07b9fc'}, globalenv=globalenv), - linux_cxx("TOOLSET=clang COMPILER=clang++-10 CXXSTD=11,1 Job 22", "clang++-10", packages="clang-10", llvm_os="xenial", llvm_ver="10", buildtype="boost", buildscript="drone", image="cppalliance/droneubuntu1604:1", environment={'TOOLSET': 'clang', 'COMPILER': 'clang++-10', 'CXXSTD': '11,14,17,2a', 'DRONE_JOB_UUID': '12c6fc06c9'}, globalenv=globalenv), - linux_cxx("TOOLSET=clang COMPILER=clang++-9 CXXSTD=11,14 Job 23", "clang++-9", packages="clang-9", llvm_os="xenial", llvm_ver="9", buildtype="boost", buildscript="drone", image="cppalliance/droneubuntu1604:1", environment={'TOOLSET': 'clang', 'COMPILER': 'clang++-9', 'CXXSTD': '11,14,17,2a', 'DRONE_JOB_UUID': 'd435a6cdd7'}, globalenv=globalenv), - linux_cxx("TOOLSET=clang COMPILER=clang++-8 CXXSTD=11,14 Job 24", "clang++-8", packages="clang-8", llvm_os="trusty", llvm_ver="8", buildtype="boost", buildscript="drone", image=linuxglobalimage, environment={'TOOLSET': 'clang', 'COMPILER': 'clang++-8', 'CXXSTD': '11,14,17,2a', 'DRONE_JOB_UUID': '4d134bc072'}, globalenv=globalenv), - linux_cxx("TOOLSET=clang COMPILER=clang++-7 CXXSTD=11,14 Job 25", "clang++-7", packages="clang-7", llvm_os="trusty", llvm_ver="7", buildtype="boost", buildscript="drone", image=linuxglobalimage, environment={'TOOLSET': 'clang', 'COMPILER': 'clang++-7', 'CXXSTD': '11,14,17,2a', 'DRONE_JOB_UUID': 'f6e1126ced'}, globalenv=globalenv), - linux_cxx("TOOLSET=clang COMPILER=clang++-6.0 CXXSTD=11, Job 26", "clang++-6.0", packages="clang-6.0", llvm_os="trusty", llvm_ver="6.0", buildtype="boost", buildscript="drone", image=linuxglobalimage, environment={'TOOLSET': 'clang', 'COMPILER': 'clang++-6.0', 'CXXSTD': '11,14,17', 'DRONE_JOB_UUID': '887309d048'}, globalenv=globalenv), - linux_cxx("TOOLSET=clang COMPILER=clang++-5.0 CXXSTD=11, Job 27", "clang++-5.0", packages="clang-5.0", llvm_os="trusty", llvm_ver="5.0", buildtype="boost", buildscript="drone", image=linuxglobalimage, environment={'TOOLSET': 'clang', 'COMPILER': 'clang++-5.0', 'CXXSTD': '11,14,1z', 'DRONE_JOB_UUID': 'bc33ea4e26'}, globalenv=globalenv), - linux_cxx("TOOLSET=clang COMPILER=clang++-4.0 CXXSTD=11, Job 28", "clang++-4.0", packages="clang-4.0", llvm_os="trusty", llvm_ver="4.0", buildtype="boost", buildscript="drone", image=linuxglobalimage, environment={'TOOLSET': 'clang', 'COMPILER': 'clang++-4.0', 'CXXSTD': '11,14,1z', 'DRONE_JOB_UUID': '0a57cb53ba'}, globalenv=globalenv), - linux_cxx("TOOLSET=clang COMPILER=clang++-3.9 CXXSTD=11, Job 29", "clang++-3.9", packages="clang-3.9 libstdc++-4.9-dev", buildtype="boost", buildscript="drone", image=linuxglobalimage, environment={'TOOLSET': 'clang', 'COMPILER': 'clang++-3.9', 'CXXSTD': '11,14,1z', 'DRONE_JOB_UUID': '7719a1c782'}, globalenv=globalenv), - linux_cxx("TOOLSET=clang COMPILER=clang++-3.8 CXXSTD=11, Job 30", "clang++-3.8", packages="clang-3.8 libstdc++-4.9-dev", buildtype="boost", buildscript="drone", image=linuxglobalimage, environment={'TOOLSET': 'clang', 'COMPILER': 'clang++-3.8', 'CXXSTD': '11,14,1z', 'DRONE_JOB_UUID': '22d200f867'}, globalenv=globalenv), - linux_cxx("TOOLSET=clang COMPILER=clang++-3.7 CXXSTD=11, Job 31", "clang++-3.7", packages="clang-3.7", llvm_os="precise", llvm_ver="3.7", buildtype="boost", buildscript="drone", image=linuxglobalimage, environment={'TOOLSET': 'clang', 'COMPILER': 'clang++-3.7', 'CXXSTD': '11,14,1z', 'DRONE_JOB_UUID': '632667547e'}, globalenv=globalenv), - linux_cxx("TOOLSET=clang COMPILER=clang++-3.6 CXXSTD=11, Job 32", "clang++-3.6", packages="clang-3.6 libstdc++-4.9-dev", buildtype="boost", buildscript="drone", image=linuxglobalimage, environment={'TOOLSET': 'clang', 'COMPILER': 'clang++-3.6', 'CXXSTD': '11,14,1z', 'DRONE_JOB_UUID': 'cb4e5208b4'}, globalenv=globalenv), - linux_cxx("TOOLSET=clang COMPILER=clang++-3.5 CXXSTD=11, Job 33", "clang++-3.5", packages="clang-3.5 libstdc++-4.9-dev", buildtype="boost", buildscript="drone", image=linuxglobalimage, environment={'TOOLSET': 'clang', 'COMPILER': 'clang++-3.5', 'CXXSTD': '11,14,1z', 'DRONE_JOB_UUID': 'b6692ea5df'}, globalenv=globalenv), - linux_cxx("TOOLSET=clang COMPILER=/usr/bin/clang++ CXXST Job 34", "/usr/bin/clang++", packages="clang-3.4", llvm_os="precise", llvm_ver="3.8", buildtype="boost", buildscript="drone", image=linuxglobalimage, environment={'TOOLSET': 'clang', 'COMPILER': '/usr/bin/clang++', 'CXXSTD': '11', 'DRONE_JOB_UUID': 'f1f836cb4e'}, globalenv=globalenv), - linux_cxx("TOOLSET=clang COMPILER=/usr/bin/clang++ CXXST Job 35", "/usr/bin/clang++", packages="clang-3.3", llvm_os="precise", llvm_ver="3.8", buildtype="boost", buildscript="drone", image=linuxglobalimage, environment={'TOOLSET': 'clang', 'COMPILER': '/usr/bin/clang++', 'CXXSTD': '11', 'DRONE_JOB_UUID': '972a67c481'}, globalenv=globalenv), - ] - -# from https://github.com/boostorg/boost-ci -load("@boost_ci//ci/drone/:functions.star", "linux_cxx","windows_cxx","osx_cxx","freebsd_cxx") diff --git a/.drone/drone.bat b/.drone/drone.bat new file mode 100644 index 00000000..84d22a86 --- /dev/null +++ b/.drone/drone.bat @@ -0,0 +1,28 @@ +@REM Copyright 2022 Peter Dimov +@REM Distributed under the Boost Software License, Version 1.0. +@REM https://www.boost.org/LICENSE_1_0.txt + +@ECHO ON + +set LIBRARY=%1 +set DRONE_BUILD_DIR=%CD% + +set BOOST_BRANCH=develop +if "%DRONE_BRANCH%" == "master" set BOOST_BRANCH=master +cd .. +git clone -b %BOOST_BRANCH% --depth 1 https://github.com/boostorg/boost.git boost-root +cd boost-root +git submodule update --init tools/boostdep +xcopy /s /e /q %DRONE_BUILD_DIR% libs\%LIBRARY%\ +python tools/boostdep/depinst/depinst.py %LIBRARY% +cmd /c bootstrap +b2 -d0 headers + +echo "Generating single header" +cd libs/%LIBRARY% +python gen/generate_single_header.py -i include/boost/leaf/detail/all.hpp -p include -o test/leaf.hpp boost/leaf + +echo "Testing" +if not "%CXXSTD%" == "" set CXXSTD=cxxstd=%CXXSTD% +if not "%ADDRMD%" == "" set ADDRMD=address-model=%ADDRMD% +..\..\b2 -j3 test toolset=%TOOLSET% %CXXSTD% %ADDRMD% embed-manifest-via=linker link=shared,static variant=debug,release,leaf_debug_capture0,leaf_release_capture0,leaf_debug_diag0,leaf_release_diag0,leaf_debug_embedded,leaf_release_embedded,leaf_debug_single_header,leaf_release_single_header diff --git a/.drone/drone.sh b/.drone/drone.sh index 481bb8f1..b7c59eca 100755 --- a/.drone/drone.sh +++ b/.drone/drone.sh @@ -1,42 +1,30 @@ #!/bin/bash -# Copyright 2020 Rene Rivera, Sam Darwin +# Copyright 2022 Peter Dimov # Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE.txt or copy at http://boost.org/LICENSE_1_0.txt) +# https://www.boost.org/LICENSE_1_0.txt -set -e -export TRAVIS_BUILD_DIR=$(pwd) -export DRONE_BUILD_DIR=$(pwd) -export TRAVIS_BRANCH=$DRONE_BRANCH -export VCS_COMMIT_ID=$DRONE_COMMIT -export GIT_COMMIT=$DRONE_COMMIT -export REPO_NAME=$DRONE_REPO -export PATH=~/.local/bin:/usr/local/bin:$PATH +set -ex -if [ "$DRONE_JOB_BUILDTYPE" == "boost" ]; then +DRONE_BUILD_DIR=$(pwd) +export PATH=~/.local/bin:/usr/local/bin:$PATH -echo '==================================> INSTALL' +BOOST_BRANCH=develop +if [ "$DRONE_BRANCH" = "master" ]; then BOOST_BRANCH=master; fi cd .. -git clone -b master --depth 1 https://github.com/boostorg/boost.git boost-root +git clone -b $BOOST_BRANCH --depth 1 https://github.com/boostorg/boost.git boost-root cd boost-root -git submodule update --init tools/build -git submodule update --init tools/inspect -git submodule update --init libs/config git submodule update --init tools/boostdep -mkdir -p libs/leaf -cp -r $TRAVIS_BUILD_DIR/* libs/leaf -python tools/boostdep/depinst/depinst.py leaf -I example +cp -r $DRONE_BUILD_DIR/* libs/$LIBRARY +python tools/boostdep/depinst/depinst.py $LIBRARY ./bootstrap.sh -./b2 headers -cd libs/leaf +./b2 -d0 headers -echo '==================================> SCRIPT' +echo "Generating single header" +cd libs/$LIBRARY +python gen/generate_single_header.py -i include/boost/leaf/detail/all.hpp -p include -o test/leaf.hpp boost/leaf +echo "Testing" echo "using $TOOLSET : : $COMPILER ;" > ~/user-config.jam -../../b2 test toolset=$TOOLSET cxxstd=$CXXSTD variant=debug,release,leaf_debug_diag0,leaf_release_diag0 ${UBSAN:+cxxflags=-fsanitize=undefined cxxflags=-fno-sanitize-recover=undefined linkflags=-fsanitize=undefined debug-symbols=on} ${LINKFLAGS:+linkflags=$LINKFLAGS} -../../b2 exception-handling=off rtti=off test toolset=$TOOLSET cxxstd=$CXXSTD variant=debug,release,leaf_debug_diag0,leaf_release_diag0 ${UBSAN:+cxxflags=-fsanitize=undefined cxxflags=-fno-sanitize-recover=undefined linkflags=-fsanitize=undefined debug-symbols=on} ${LINKFLAGS:+linkflags=$LINKFLAGS} -../../b2 threading=single test toolset=$TOOLSET cxxstd=$CXXSTD variant=debug,release,leaf_debug_diag0,leaf_release_diag0 ${UBSAN:+cxxflags=-fsanitize=undefined cxxflags=-fno-sanitize-recover=undefined linkflags=-fsanitize=undefined debug-symbols=on} ${LINKFLAGS:+linkflags=$LINKFLAGS} -../../b2 threading=single exception-handling=off rtti=off test toolset=$TOOLSET cxxstd=$CXXSTD variant=debug,release,leaf_debug_diag0,leaf_release_diag0 ${UBSAN:+cxxflags=-fsanitize=undefined cxxflags=-fno-sanitize-recover=undefined linkflags=-fsanitize=undefined debug-symbols=on} ${LINKFLAGS:+linkflags=$LINKFLAGS} - -fi +../../b2 -j3 test $LINKFLAGS toolset=$TOOLSET cxxstd=$CXXSTD ${ADDRMD:+address-model=$ADDRMD} ${UBSAN:+undefined-sanitizer=norecover debug-symbols=on} ${ASAN:+address-sanitizer=norecover debug-symbols=on} ${LINKFLAGS:+linkflags=$LINKFLAGS} link=shared,static variant=debug,release,leaf_debug_capture0,leaf_release_capture0,leaf_debug_diag0,leaf_release_diag0,leaf_debug_embedded,leaf_release_embedded,leaf_debug_single_header,leaf_release_single_header diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f0d6acd5..f466d778 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,173 +16,324 @@ jobs: strategy: fail-fast: false matrix: - include: - - toolset: gcc-4.8 - cxxstd: "11" - os: ubuntu-18.04 - install: g++-4.8 + config: + - variant: "debug,release" + - name: No capture + variant: "leaf_debug_capture0,leaf_release_capture0" + - name: No diagnostics + variant: "leaf_debug_diag0,leaf_release_diag0" + - name: Embedded + variant: "leaf_debug_embedded,leaf_release_embedded" + - name: Single header + variant: "leaf_debug_single_header,leaf_release_single_header" + platform: - toolset: gcc-5 cxxstd: "11,14,1z" - os: ubuntu-18.04 + container: ubuntu:18.04 + os: ubuntu-latest install: g++-5 - toolset: gcc-6 cxxstd: "11,14,1z" - os: ubuntu-18.04 + container: ubuntu:18.04 + os: ubuntu-latest install: g++-6 - toolset: gcc-7 cxxstd: "11,14" - os: ubuntu-18.04 + container: ubuntu:18.04 + os: ubuntu-latest - toolset: gcc-8 cxxstd: "11,14,17,2a" - os: ubuntu-18.04 + container: ubuntu:20.04 + os: ubuntu-latest install: g++-8 - toolset: gcc-9 cxxstd: "11,14,17,2a" - os: ubuntu-20.04 + container: ubuntu:20.04 + os: ubuntu-latest - toolset: gcc-10 cxxstd: "11,14,17,2a" - os: ubuntu-20.04 + container: ubuntu:20.04 + os: ubuntu-latest install: g++-10 - toolset: gcc-11 cxxstd: "11,14,17,2a" - os: ubuntu-20.04 - install: g++-11 + os: ubuntu-22.04 + - toolset: gcc-12 + cxxstd: "11,14,17,20,2b" + os: ubuntu-22.04 + install: g++-12 + - toolset: gcc-13 + cxxstd: "11,14,17,20,2b" + os: ubuntu-latest + container: ubuntu:24.04 + install: g++-13 + - toolset: gcc-14 + cxxstd: "11,14,17,20,2b" + os: ubuntu-latest + container: ubuntu:24.04 + install: g++-14 + - toolset: gcc-15 + cxxstd: "11,14,17,20,23,2c" + os: ubuntu-latest + container: ubuntu:25.04 + install: g++-15 - toolset: clang compiler: clang++-3.9 cxxstd: "11,14" - os: ubuntu-18.04 + os: ubuntu-latest + container: ubuntu:18.04 install: clang-3.9 - toolset: clang compiler: clang++-4.0 cxxstd: "11,14" - os: ubuntu-18.04 + os: ubuntu-latest + container: ubuntu:18.04 install: clang-4.0 - toolset: clang compiler: clang++-5.0 cxxstd: "11,14,1z" - os: ubuntu-18.04 + os: ubuntu-latest + container: ubuntu:18.04 install: clang-5.0 - toolset: clang compiler: clang++-6.0 cxxstd: "11,14,17" - os: ubuntu-18.04 + container: ubuntu:20.04 + os: ubuntu-latest install: clang-6.0 - toolset: clang compiler: clang++-7 cxxstd: "11,14,17" - os: ubuntu-18.04 + container: ubuntu:20.04 + os: ubuntu-latest install: clang-7 - toolset: clang compiler: clang++-8 cxxstd: "11,14,17" - os: ubuntu-20.04 + container: ubuntu:20.04 + os: ubuntu-latest install: clang-8 - toolset: clang compiler: clang++-9 - cxxstd: "11,14,17,2a" - os: ubuntu-20.04 + cxxstd: "11,14,17" + container: ubuntu:20.04 + os: ubuntu-latest install: clang-9 - toolset: clang compiler: clang++-10 cxxstd: "11,14,17,2a" - os: ubuntu-20.04 + container: ubuntu:20.04 + os: ubuntu-latest install: clang-10 - toolset: clang compiler: clang++-11 cxxstd: "11,14,17,2a" - os: ubuntu-20.04 + container: ubuntu:20.04 + os: ubuntu-latest install: clang-11 - toolset: clang compiler: clang++-12 - cxxstd: "11,14,17,2a" - os: ubuntu-20.04 + cxxstd: "11,14,17,20" + container: ubuntu:20.04 + os: ubuntu-latest install: clang-12 - toolset: clang - cxxstd: "11,14,17,2a" - os: macos-10.15 + compiler: clang++-13 + cxxstd: "11,14,17,20,2b" + container: ubuntu:22.04 + os: ubuntu-latest + install: clang-13 + - toolset: clang + compiler: clang++-14 + cxxstd: "11,14,17,20,2b" + container: ubuntu:22.04 + os: ubuntu-latest + install: clang-14 + - toolset: clang + compiler: clang++-15 + cxxstd: "11,14,17,20,2b" + container: ubuntu:22.04 + os: ubuntu-latest + install: clang-15 + - toolset: clang + compiler: clang++-16 + cxxstd: "11,14,17,20,2b" + container: ubuntu:24.04 + os: ubuntu-latest + install: clang-16 + - toolset: clang + compiler: clang++-17 + cxxstd: "11,14,17,20,2b" + container: ubuntu:24.04 + os: ubuntu-latest + install: clang-17 + - toolset: clang + compiler: clang++-18 + cxxstd: "11,14,17,20,2b" + container: ubuntu:24.04 + os: ubuntu-latest + install: clang-18 + - toolset: clang + compiler: clang++-19 + cxxstd: "11,14,17,20,2b" + container: ubuntu:24.04 + os: ubuntu-latest + install: clang-19 + - toolset: clang + compiler: clang++-20 + cxxstd: "11,14,17,20,23,2c" + container: ubuntu:25.04 + os: ubuntu-latest + install: clang-20 + - toolset: clang + cxxstd: "11,14,17,20,2b" + os: macos-14 + - toolset: clang + cxxstd: "11,14,17,20,2b" + os: macos-15 + - toolset: clang + cxxstd: "11,14,17,20,2b" + os: macos-26 + + name: ${{matrix.platform.os}} / ${{matrix.platform.compiler || matrix.platform.toolset}}${{matrix.config.name && format(' / {0}', matrix.config.name) || ''}} + + runs-on: ${{matrix.platform.os}} - runs-on: ${{matrix.os}} + container: + image: ${{matrix.platform.container}} + volumes: + - /node20217:/node20217:rw,rshared + - ${{ startsWith(matrix.platform.container, 'ubuntu:1') && '/node20217:/__e/node20:ro,rshared' || ' ' }} + + defaults: + run: + shell: bash steps: - - uses: actions/checkout@v2 + - name: Setup container environment + if: matrix.platform.container + run: | + apt-get update + apt-get -y install sudo python3 git g++ curl xz-utils + + - name: Install nodejs20glibc2.17 + if: ${{ startsWith( matrix.platform.container, 'ubuntu:1' ) }} + run: | + curl -LO https://archives.boost.io/misc/node/node-v20.9.0-linux-x64-glibc-217.tar.xz + tar -xf node-v20.9.0-linux-x64-glibc-217.tar.xz --strip-components 1 -C /node20217 + ldd /__e/node20/bin/node + + - uses: actions/checkout@v4 - name: Install packages - if: matrix.install - run: sudo apt install ${{matrix.install}} + if: matrix.platform.install + run: | + sudo apt-get update + sudo apt-get -y install ${{matrix.platform.install}} - name: Setup Boost run: | + echo GITHUB_REPOSITORY: $GITHUB_REPOSITORY + LIBRARY=${GITHUB_REPOSITORY#*/} + echo LIBRARY: $LIBRARY + echo "LIBRARY=$LIBRARY" >> $GITHUB_ENV + echo GITHUB_BASE_REF: $GITHUB_BASE_REF + echo GITHUB_REF: $GITHUB_REF REF=${GITHUB_BASE_REF:-$GITHUB_REF} + REF=${REF#refs/heads/} + echo REF: $REF BOOST_BRANCH=develop && [ "$REF" == "master" ] && BOOST_BRANCH=master || true + echo BOOST_BRANCH: $BOOST_BRANCH cd .. git clone -b $BOOST_BRANCH --depth 1 https://github.com/boostorg/boost.git boost-root cd boost-root - cp -r $GITHUB_WORKSPACE/* libs/leaf + cp -r $GITHUB_WORKSPACE/* libs/$LIBRARY git submodule update --init tools/boostdep - python tools/boostdep/depinst/depinst.py --git_args "--jobs 3" leaf + python3 tools/boostdep/depinst/depinst.py --git_args "--jobs 3" $LIBRARY ./bootstrap.sh ./b2 -d0 headers - name: Create user-config.jam - if: matrix.compiler + if: matrix.platform.compiler run: | - echo "using ${{matrix.toolset}} : : ${{matrix.compiler}} ;" > ~/user-config.jam + echo "using ${{matrix.platform.toolset}} : : ${{matrix.platform.compiler}} ;" > ~/user-config.jam - name: Generate headers run: | cd ../boost-root/libs/leaf - python gen/generate_single_header.py -i include/boost/leaf/detail/all.hpp -p include -o test/leaf.hpp boost/leaf + python3 gen/generate_single_header.py -i include/boost/leaf/detail/all.hpp -p include -o test/leaf.hpp boost/leaf - name: Run tests run: | cd ../boost-root - ./b2 -j3 libs/leaf/test toolset=${{matrix.toolset}} cxxstd=${{matrix.cxxstd}} link=shared,static variant=debug,release,leaf_debug_leaf_hpp,leaf_release_leaf_hpp,leaf_debug_diag0,leaf_release_diag0,leaf_debug_embedded,leaf_release_embedded + ./b2 -j3 libs/$LIBRARY/test toolset=${{matrix.platform.toolset}} cxxstd=${{matrix.platform.cxxstd}} ${ADDRMD:+address-model=$ADDRMD} link=shared,static variant=${{matrix.config.variant}} + ./b2 -j3 libs/$LIBRARY/test toolset=${{matrix.platform.toolset}} cxxstd=${{matrix.platform.cxxstd}} ${ADDRMD:+address-model=$ADDRMD} link=shared,static variant=${{matrix.config.variant}} exception-handling=off rtti=off windows: strategy: fail-fast: false matrix: - include: - - toolset: msvc-14.1 - cxxstd: "14,17,latest" + config: + - variant: "debug,release" + - name: No capture + variant: "leaf_debug_capture0,leaf_release_capture0" + - name: No diagnostics + variant: "leaf_debug_diag0,leaf_release_diag0" + - name: Embedded + variant: "leaf_debug_embedded,leaf_release_embedded" + - name: Single header + variant: "leaf_debug_single_header,leaf_release_single_header" + platform: + - toolset: msvc-14.3 + cxxstd: "14,17,20,latest" addrmd: 32,64 - os: windows-2016 - - toolset: msvc-14.2 - cxxstd: "14,17,latest" - addrmd: 32,64 - os: windows-2019 + os: windows-2022 + - toolset: clang-win + cxxstd: "14,17,20,latest" + addrmd: 64 + os: windows-2022 - toolset: gcc cxxstd: "11,14,17,2a" addrmd: 64 - os: windows-2019 + os: windows-2022 + + name: ${{matrix.platform.os}} / ${{matrix.platform.compiler || matrix.platform.toolset}}${{matrix.config.name && format(' / {0}', matrix.config.name) || ''}} - runs-on: ${{matrix.os}} + runs-on: ${{matrix.platform.os}} steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - name: Setup Boost shell: cmd run: | + echo GITHUB_REPOSITORY: %GITHUB_REPOSITORY% + for /f %%i in ("%GITHUB_REPOSITORY%") do set LIBRARY=%%~nxi + echo LIBRARY: %LIBRARY% + echo LIBRARY=%LIBRARY%>>%GITHUB_ENV% + echo GITHUB_BASE_REF: %GITHUB_BASE_REF% + echo GITHUB_REF: %GITHUB_REF% if "%GITHUB_BASE_REF%" == "" set GITHUB_BASE_REF=%GITHUB_REF% set BOOST_BRANCH=develop - if "%GITHUB_BASE_REF%" == "master" set BOOST_BRANCH=master + for /f %%i in ("%GITHUB_BASE_REF%") do if "%%~nxi" == "master" set BOOST_BRANCH=master + echo BOOST_BRANCH: %BOOST_BRANCH% cd .. git clone -b %BOOST_BRANCH% --depth 1 https://github.com/boostorg/boost.git boost-root cd boost-root - xcopy /s /e /q %GITHUB_WORKSPACE% libs\leaf\ + xcopy /s /e /q %GITHUB_WORKSPACE% libs\%LIBRARY%\ git submodule update --init tools/boostdep - python tools/boostdep/depinst/depinst.py --git_args "--jobs 3" leaf + python tools/boostdep/depinst/depinst.py --git_args "--jobs 3" %LIBRARY% cmd /c bootstrap b2 -d0 headers - name: Generate headers run: | cd ../boost-root/libs/leaf - python gen/generate_single_header.py -i include/boost/leaf/detail/all.hpp -p include -o test/leaf.hpp boost/leaf + python3 gen/generate_single_header.py -i include/boost/leaf/detail/all.hpp -p include -o test/leaf.hpp boost/leaf - name: Run tests shell: cmd run: | cd ../boost-root - b2 -j3 libs/leaf/test toolset=${{matrix.toolset}} cxxstd=${{matrix.cxxstd}} address-model=${{matrix.addrmd}} variant=debug,release,leaf_debug_leaf_hpp,leaf_release_leaf_hpp,leaf_debug_diag0,leaf_release_diag0,leaf_debug_embedded,leaf_release_embedded + b2 -j3 --abbreviate-paths libs/%LIBRARY%/test toolset=${{matrix.platform.toolset}} cxxstd=${{matrix.platform.cxxstd}} address-model=${{matrix.platform.addrmd}} link=shared,static variant=${{matrix.config.variant}} + b2 -j3 --abbreviate-paths libs/%LIBRARY%/test toolset=${{matrix.platform.toolset}} cxxstd=${{matrix.platform.cxxstd}} address-model=${{matrix.platform.addrmd}} link=shared,static variant=${{matrix.config.variant}} exception-handling=off rtti=off diff --git a/.github/workflows/gh-pages.yml b/.github/workflows/gh-pages.yml index 05108aaf..2744801b 100644 --- a/.github/workflows/gh-pages.yml +++ b/.github/workflows/gh-pages.yml @@ -4,12 +4,13 @@ on: push: branches: - master + - feature/gha_fixes jobs: publish: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - name: Install packages run: | @@ -24,6 +25,7 @@ jobs: cd boost-root cp -r $GITHUB_WORKSPACE/* libs/leaf git submodule update --init tools/build + git submodule update --init tools/boost_install git submodule update --init libs/config ./bootstrap.sh @@ -43,8 +45,8 @@ jobs: python gen/generate_single_header.py -i include/boost/leaf/detail/all.hpp -p include -o doc/html/leaf.hpp boost/leaf --hash "$REF" - name: Deploy to GitHub Pages - uses: JamesIves/github-pages-deploy-action@3.7.1 + uses: JamesIves/github-pages-deploy-action@4.0.0 with: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - BRANCH: gh-pages - FOLDER: ../boost-root/libs/leaf/doc/html + token: ${{ secrets.GITHUB_TOKEN }} + branch: gh-pages + folder: ../boost-root/libs/leaf/doc/html diff --git a/.gitignore b/.gitignore index c589ffad..84d0e3de 100644 --- a/.gitignore +++ b/.gitignore @@ -7,13 +7,12 @@ *.opensdf *.db *.opendb -bld/* +_bld/* doc/html/* snippets/* subprojects/*/ .vscode/ipch/* .vscode/settings.json .vscode/c_cpp_properties.json -benchmark/tl/* test/leaf.hpp doc/leaf.html diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 68583bd3..00000000 --- a/.travis.yml +++ /dev/null @@ -1,422 +0,0 @@ -# Copyright 2016-2018 Peter Dimov -# Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at http://boost.org/LICENSE_1_0.txt) - -language: cpp - -sudo: false - -dist: trusty - -python: "2.7" - -os: - - linux - - osx - -branches: - only: - - master - - develop - - /^feature.*/ - -env: - matrix: - - BOGUS_JOB=true - -addons: - apt: - packages: - - g++-4.9 - - g++-5 - - g++-6 - - clang-3.6 - - clang-3.7 - - clang-3.8 - - ruby-full - - ninja-build - - sources: - - ubuntu-toolchain-r-test - - llvm-toolchain-precise - - llvm-toolchain-precise-3.6 - - llvm-toolchain-precise-3.7 - - llvm-toolchain-precise-3.8 - -matrix: - - exclude: - - env: BOGUS_JOB=true - - include: - - - os: linux - env: DOC=1 - install: - - gem install asciidoctor - - gem install asciidoctor-pdf --pre - - gem install rouge - - cd .. - - git clone -b master --depth 1 https://github.com/boostorg/boost.git boost-root - - cd boost-root - - git submodule update --init tools/build - - git submodule update --init libs/config - - mkdir -p libs/leaf - - cp -r $TRAVIS_BUILD_DIR/* libs/leaf - - ./bootstrap.sh - - cd libs/leaf - script: - - |- - echo "using asciidoctor ;" > ~/user-config.jam - - ../../b2 doc - deploy: - local-dir: ../boost-root/libs/leaf/doc/html - provider: pages - skip-cleanup: true - github-token: $GH_PAGES_TOKEN - keep-history: false - on: - branch: master - -################################### - - - os: osx - compiler: clang++ - env: UBSAN=1 TOOLSET=clang COMPILER=clang++ CXXSTD=11,14 UBSAN_OPTIONS=print_stacktrace=1 - - - os: osx - compiler: clang++ - env: UBSAN=1 TOOLSET=clang COMPILER=clang++ CXXSTD=1z,2a UBSAN_OPTIONS=print_stacktrace=1 - - - os: osx - osx_image: xcode11.5 - compiler: clang++ - env: TOOLSET=clang COMPILER=clang++ CXXSTD=11,14,1z - - - os: osx - osx_image: xcode11.4 - compiler: clang++ - env: TOOLSET=clang COMPILER=clang++ CXXSTD=11,14,1z - - - os: osx - osx_image: xcode11.3 - compiler: clang++ - env: TOOLSET=clang COMPILER=clang++ CXXSTD=11,14,1z - - - os: osx - osx_image: xcode11.2 - compiler: clang++ - env: TOOLSET=clang COMPILER=clang++ CXXSTD=11,14,1z - - - os: osx - osx_image: xcode11.1 - compiler: clang++ - env: TOOLSET=clang COMPILER=clang++ CXXSTD=11,14,1z - - - os: osx - osx_image: xcode11 - compiler: clang++ - env: TOOLSET=clang COMPILER=clang++ CXXSTD=11,14,1z - - - os: osx - osx_image: xcode10.3 - compiler: clang++ - env: TOOLSET=clang COMPILER=clang++ CXXSTD=11,14,1z - - - os: osx - osx_image: xcode10.2 - compiler: clang++ - env: TOOLSET=clang COMPILER=clang++ CXXSTD=11,14,1z - - - os: osx - osx_image: xcode10.1 - compiler: clang++ - env: TOOLSET=clang COMPILER=clang++ CXXSTD=11,14,1z - -################################### - - - os: linux - compiler: g++-9 - env: UBSAN=1 TOOLSET=gcc COMPILER=g++-9 CXXSTD=11,14 UBSAN_OPTIONS=print_stacktrace=1 LINKFLAGS=-fuse-ld=gold - addons: - apt: - packages: - - g++-9 - sources: - - ubuntu-toolchain-r-test - - - os: linux - compiler: g++-9 - env: UBSAN=1 TOOLSET=gcc COMPILER=g++-9 CXXSTD=17,2a UBSAN_OPTIONS=print_stacktrace=1 LINKFLAGS=-fuse-ld=gold - addons: - apt: - packages: - - g++-9 - sources: - - ubuntu-toolchain-r-test - - - os: linux - compiler: g++-9 - env: TOOLSET=gcc COMPILER=g++-9 CXXSTD=11,14,17,2a - addons: - apt: - packages: - - g++-9 - sources: - - ubuntu-toolchain-r-test - - - os: linux - compiler: g++-8 - env: TOOLSET=gcc COMPILER=g++-8 CXXSTD=11,14,17 - addons: - apt: - packages: - - g++-8 - sources: - - ubuntu-toolchain-r-test - - - os: linux - compiler: g++-7 - env: TOOLSET=gcc COMPILER=g++-7 CXXSTD=11,14 - addons: - apt: - packages: - - g++-7 - sources: - - ubuntu-toolchain-r-test - - - os: linux - compiler: g++-6 - env: TOOLSET=gcc COMPILER=g++-6 CXXSTD=11,14 - addons: - apt: - packages: - - g++-6 - sources: - - ubuntu-toolchain-r-test - - - os: linux - compiler: g++-5 - env: TOOLSET=gcc COMPILER=g++-5 CXXSTD=11,14 - addons: - apt: - packages: - - g++-5 - sources: - - ubuntu-toolchain-r-test - - - os: linux - compiler: g++-4.9 - env: TOOLSET=gcc COMPILER=g++-4.9 CXXSTD=11 - addons: - apt: - packages: - - g++-4.9 - sources: - - ubuntu-toolchain-r-test - -################################### - - - os: linux - compiler: clang++-8 - env: UBSAN=1 TOOLSET=clang COMPILER=clang++-8 CXXSTD=11,14 UBSAN_OPTIONS=print_stacktrace=1 - addons: - apt: - packages: - - clang-8 - sources: - - ubuntu-toolchain-r-test - - llvm-toolchain-trusty-8 - - - os: linux - compiler: clang++-8 - env: UBSAN=1 TOOLSET=clang COMPILER=clang++-8 CXXSTD=17,2a UBSAN_OPTIONS=print_stacktrace=1 - addons: - apt: - packages: - - clang-8 - sources: - - ubuntu-toolchain-r-test - - llvm-toolchain-trusty-8 - - - os: linux - dist: xenial - compiler: clang++-10 - env: TOOLSET=clang COMPILER=clang++-10 CXXSTD=11,14,17,2a - addons: - apt: - packages: - - clang-10 - sources: - - ubuntu-toolchain-r-test - - sourceline: 'deb https://apt.llvm.org/xenial/ llvm-toolchain-xenial-10 main' - key_url: 'https://apt.llvm.org/llvm-snapshot.gpg.key' - - - os: linux - dist: xenial - compiler: clang++-9 - env: TOOLSET=clang COMPILER=clang++-9 CXXSTD=11,14,17,2a - addons: - apt: - packages: - - clang-9 - sources: - - ubuntu-toolchain-r-test - - sourceline: 'deb https://apt.llvm.org/xenial/ llvm-toolchain-xenial-9 main' - key_url: 'https://apt.llvm.org/llvm-snapshot.gpg.key' - - - os: linux - compiler: clang++-8 - env: TOOLSET=clang COMPILER=clang++-8 CXXSTD=11,14,17,2a - addons: - apt: - packages: - - clang-8 - sources: - - ubuntu-toolchain-r-test - - llvm-toolchain-trusty-8 - - - os: linux - compiler: clang++-7 - env: TOOLSET=clang COMPILER=clang++-7 CXXSTD=11,14,17,2a - addons: - apt: - packages: - - clang-7 - sources: - - ubuntu-toolchain-r-test - - llvm-toolchain-trusty-7 - - - os: linux - compiler: clang++-6.0 - env: TOOLSET=clang COMPILER=clang++-6.0 CXXSTD=11,14,17 - addons: - apt: - packages: - - clang-6.0 - sources: - - ubuntu-toolchain-r-test - - llvm-toolchain-trusty-6.0 - - - os: linux - compiler: clang++-5.0 - env: TOOLSET=clang COMPILER=clang++-5.0 CXXSTD=11,14,1z - addons: - apt: - packages: - - clang-5.0 - sources: - - ubuntu-toolchain-r-test - - llvm-toolchain-trusty-5.0 - - - os: linux - compiler: clang++-4.0 - env: TOOLSET=clang COMPILER=clang++-4.0 CXXSTD=11,14,1z - addons: - apt: - packages: - - clang-4.0 - sources: - - ubuntu-toolchain-r-test - - llvm-toolchain-trusty-4.0 - - - os: linux - compiler: clang++-3.9 - env: TOOLSET=clang COMPILER=clang++-3.9 CXXSTD=11,14,1z - addons: - apt: - packages: - - clang-3.9 - - libstdc++-4.9-dev - sources: - - ubuntu-toolchain-r-test - - - os: linux - compiler: clang++-3.8 - env: TOOLSET=clang COMPILER=clang++-3.8 CXXSTD=11,14,1z - addons: - apt: - packages: - - clang-3.8 - - libstdc++-4.9-dev - sources: - - ubuntu-toolchain-r-test - - - os: linux - compiler: clang++-3.7 - env: TOOLSET=clang COMPILER=clang++-3.7 CXXSTD=11,14,1z - addons: - apt: - packages: - - clang-3.7 - sources: - - ubuntu-toolchain-r-test - - llvm-toolchain-precise-3.7 - - - os: linux - compiler: clang++-3.6 - env: TOOLSET=clang COMPILER=clang++-3.6 CXXSTD=11,14,1z - addons: - apt: - packages: - - clang-3.6 - - libstdc++-4.9-dev - sources: - - ubuntu-toolchain-r-test - - - os: linux - compiler: clang++-3.5 - env: TOOLSET=clang COMPILER=clang++-3.5 CXXSTD=11,14,1z - addons: - apt: - packages: - - clang-3.5 - - libstdc++-4.9-dev - sources: - - ubuntu-toolchain-r-test - - - os: linux - compiler: /usr/bin/clang++ - env: TOOLSET=clang COMPILER=/usr/bin/clang++ CXXSTD=11 - addons: - apt: - packages: - - clang-3.4 - - - os: linux - compiler: /usr/bin/clang++ - env: TOOLSET=clang COMPILER=/usr/bin/clang++ CXXSTD=11 - addons: - apt: - packages: - - clang-3.3 - -################################### - -install: - - cd .. - - git clone -b master --depth 1 https://github.com/boostorg/boost.git boost-root - - cd boost-root - - git submodule update --init tools/build - - git submodule update --init tools/inspect - - git submodule update --init libs/config - - git submodule update --init tools/boostdep - - mkdir -p libs/leaf - - cp -r $TRAVIS_BUILD_DIR/* libs/leaf - - python tools/boostdep/depinst/depinst.py leaf -I example - - ./bootstrap.sh - - ./b2 headers - - cd libs/leaf - -script: - - |- - echo "using $TOOLSET : : $COMPILER ;" > ~/user-config.jam - - ../../b2 test toolset=$TOOLSET cxxstd=$CXXSTD variant=debug,release,leaf_debug_diag0,leaf_release_diag0 ${UBSAN:+cxxflags=-fsanitize=undefined cxxflags=-fno-sanitize-recover=undefined linkflags=-fsanitize=undefined debug-symbols=on} ${LINKFLAGS:+linkflags=$LINKFLAGS} - - ../../b2 exception-handling=off rtti=off test toolset=$TOOLSET cxxstd=$CXXSTD variant=debug,release,leaf_debug_diag0,leaf_release_diag0 ${UBSAN:+cxxflags=-fsanitize=undefined cxxflags=-fno-sanitize-recover=undefined linkflags=-fsanitize=undefined debug-symbols=on} ${LINKFLAGS:+linkflags=$LINKFLAGS} - - ../../b2 threading=single test toolset=$TOOLSET cxxstd=$CXXSTD variant=debug,release,leaf_debug_diag0,leaf_release_diag0 ${UBSAN:+cxxflags=-fsanitize=undefined cxxflags=-fno-sanitize-recover=undefined linkflags=-fsanitize=undefined debug-symbols=on} ${LINKFLAGS:+linkflags=$LINKFLAGS} - - ../../b2 threading=single exception-handling=off rtti=off test toolset=$TOOLSET cxxstd=$CXXSTD variant=debug,release,leaf_debug_diag0,leaf_release_diag0 ${UBSAN:+cxxflags=-fsanitize=undefined cxxflags=-fno-sanitize-recover=undefined linkflags=-fsanitize=undefined debug-symbols=on} ${LINKFLAGS:+linkflags=$LINKFLAGS} - -notifications: - email: - on_success: always diff --git a/.vscode/launch.json b/.vscode/launch.json index abdc4a4c..6b2e39ae 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -4,12 +4,23 @@ // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ + { + "name": "(Windows) Launch", + "type": "cppvsdbg", + "request": "launch", + "program": "${workspaceFolder}/_bld/debug/capture_exception_result_async_test", + "args": [], + "cwd": "${fileDirname}", + "stopAtEntry": false, + "externalConsole": false + }, + { "name": "(lldb) Launch", "type": "cppdbg", "request": "launch", - "program": "${workspaceFolder}/bld/debug/lua_callback_eh", - "args": [ ], + "program": "${workspaceFolder}/_bld/debug/capture_exception_result_async_test", + "args": [], "cwd": "${workspaceFolder}", "stopAtEntry": false, "externalConsole": false, diff --git a/.vscode/tasks.json b/.vscode/tasks.json index d844b069..d366525b 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -4,15 +4,45 @@ "version": "2.0.0", "tasks": [ { - "label": "Configure Meson build directories", + "label": "Setup Meson build directories", "type": "shell", - "command": "cd ${workspaceRoot} && meson -D leaf_boost_examples=true -D leaf_lua_examples=true bld/debug && meson -D leaf_boost_examples=true -D leaf_lua_examples=true -D leaf_hpp=true bld/debug_leaf_hpp && meson -D leaf_boost_examples=true -D leaf_lua_examples=true bld/release --buildtype release && meson -D leaf_boost_examples=true -D leaf_lua_examples=true -D leaf_hpp=true bld/release_leaf_hpp --buildtype release && meson -D leaf_diagnostics=0 -D cpp_eh=none -D b_ndebug=true -D b_lto=true -D leaf_enable_benchmarks=true bld/benchmark --buildtype release", + "command": "cd ${workspaceRoot} && meson setup -D leaf_boost_available=true -D leaf_enable_examples=true _bld/debug && meson setup -D leaf_boost_available=true -D leaf_enable_examples=true -D leaf_single_header=true _bld/debug_single_header && meson setup -D leaf_boost_available=true -D leaf_enable_examples=true _bld/release --buildtype release && meson setup -D leaf_boost_available=true -D leaf_enable_examples=true -D leaf_single_header=true _bld/release_single_header --buildtype release", "problemMatcher": [] }, { - "label": "Configure Meson build directories (no Boost)", + "label": "Setup Meson build directories (no exceptions)", "type": "shell", - "command": "cd ${workspaceRoot} && meson -D leaf_lua_examples=true bld/debug && meson -D leaf_lua_examples=true -D leaf_hpp=true bld/debug_leaf_hpp && meson -D leaf_lua_examples=true bld/release --buildtype release && meson -D leaf_lua_examples=true -D leaf_hpp=true bld/release_leaf_hpp --buildtype release", + "command": "cd ${workspaceRoot} && meson setup -D leaf_boost_available=true -D leaf_enable_examples=true -D cpp_eh=none _bld/debug && meson setup -D leaf_boost_available=true -D leaf_enable_examples=true -D leaf_single_header=true -D cpp_eh=none _bld/debug_single_header && meson setup -D leaf_boost_available=true -D leaf_enable_examples=true -D cpp_eh=none _bld/release --buildtype release && meson setup -D leaf_boost_available=true -D leaf_enable_examples=true -D leaf_single_header=true -D cpp_eh=none _bld/release_single_header --buildtype release", + "problemMatcher": [] + }, + { + "label": "Setup Meson build directories (no diagnostics)", + "type": "shell", + "command": "cd ${workspaceRoot} && meson setup -D leaf_boost_available=true -D leaf_enable_examples=true -D leaf_diagnostics=0 _bld/debug && meson setup -D leaf_boost_available=true -D leaf_enable_examples=true -D leaf_single_header=true -D leaf_diagnostics=0 _bld/debug_single_header && meson setup -D leaf_boost_available=true -D leaf_enable_examples=true -D leaf_diagnostics=0 _bld/release --buildtype release && meson setup -D leaf_boost_available=true -D leaf_enable_examples=true -D leaf_single_header=true -D leaf_diagnostics=0 _bld/release_single_header --buildtype release", + "problemMatcher": [] + }, + { + "label": "Setup Meson build directories (no capture)", + "type": "shell", + "command": "cd ${workspaceRoot} && meson setup -D leaf_boost_available=true -D leaf_enable_examples=true -D leaf_capture=0 _bld/debug && meson setup -D leaf_boost_available=true -D leaf_enable_examples=true -D leaf_single_header=true -D leaf_capture=0 _bld/debug_single_header && meson setup -D leaf_boost_available=true -D leaf_enable_examples=true -D leaf_capture=0 _bld/release --buildtype release && meson setup -D leaf_boost_available=true -D leaf_enable_examples=true -D leaf_single_header=true -D leaf_capture=0 _bld/release_single_header --buildtype release", + "problemMatcher": [] + }, + { + "label": "Setup Meson build directories (no Boost)", + "type": "shell", + "command": "cd ${workspaceRoot} && meson setup -D leaf_boost_available=false -D leaf_enable_examples=true _bld/debug && meson setup -D leaf_boost_available=false -D leaf_enable_examples=true -D leaf_single_header=true _bld/debug_single_header && meson setup -D leaf_boost_available=false -D leaf_enable_examples=true _bld/release --buildtype release && meson setup -D leaf_boost_available=false -D leaf_enable_examples=true -D leaf_single_header=true _bld/release_single_header --buildtype release", + "problemMatcher": [] + }, + { + "label": "Setup Meson build directories (test embedded)", + "type": "shell", + "command": "cd ${workspaceRoot} && meson setup -D leaf_embedded=true -D leaf_diagnostics=0 _bld/debug && meson setup -D leaf_embedded=true -D leaf_diagnostics=0 -D leaf_single_header=true _bld/debug_single_header && meson setup -D leaf_embedded=true -D leaf_diagnostics=0 _bld/release --buildtype release && meson setup -D leaf_embedded=true -D leaf_diagnostics=0 -D leaf_single_header=true _bld/release_single_header --buildtype release", + "problemMatcher": [] + }, + { + "label": "Setup Meson build directories (test embedded, no exceptions)", + "type": "shell", + "command": "cd ${workspaceRoot} && meson setup -D cpp_eh=none -D leaf_embedded=true -D leaf_diagnostics=0 _bld/debug && meson setup -D cpp_eh=none -D leaf_embedded=true -D leaf_diagnostics=0 -D leaf_single_header=true _bld/debug_single_header && meson setup -D cpp_eh=none -D leaf_embedded=true -D leaf_diagnostics=0 _bld/release --buildtype release && meson setup -D cpp_eh=none -D leaf_embedded=true -D leaf_diagnostics=0 -D leaf_single_header=true _bld/release_single_header --buildtype release", "problemMatcher": [] }, { @@ -28,13 +58,22 @@ }, "label": "Build all unit tests and examples (debug)", "type": "shell", - "command": "cd ${workspaceRoot}/bld/debug && ninja", + "command": "cd ${workspaceRoot}/_bld/debug && ninja", "problemMatcher": { "base": "$gcc", "fileLocation": [ "relative", - "${workspaceRoot}/bld/debug" + "${workspaceRoot}/_bld/debug" ] + }, + "windows": { + "problemMatcher": { + "base": "$msCompile", + "fileLocation": [ + "relative", + "${workspaceRoot}/_bld/debug" + ] + } } }, { @@ -44,13 +83,22 @@ "dependsOn": [ "Generate leaf.hpp" ], - "command": "cd ${workspaceRoot}/bld/debug_leaf_hpp && ninja && meson test && cd ${workspaceRoot}/bld/debug && ninja && meson test", + "command": "cd ${workspaceRoot}/_bld/debug && ninja && meson test && cd ${workspaceRoot}/_bld/debug && ninja && meson test", "problemMatcher": { "base": "$gcc", "fileLocation": [ "relative", - "${workspaceRoot}/bld/debug" + "${workspaceRoot}/_bld/debug" ] + }, + "windows": { + "problemMatcher": { + "base": "$msCompile", + "fileLocation": [ + "relative", + "${workspaceRoot}/_bld/debug" + ] + } } }, { @@ -60,13 +108,22 @@ "dependsOn": [ "Generate leaf.hpp" ], - "command": "cd ${workspaceRoot}/bld/release && ninja && meson test && cd ${workspaceRoot}/bld/release_leaf_hpp && ninja && meson test", + "command": "cd ${workspaceRoot}/_bld/release && ninja && meson test && cd ${workspaceRoot}/_bld/release_single_header && ninja && meson test", "problemMatcher": { "base": "$gcc", "fileLocation": [ "relative", - "${workspaceRoot}/bld/release" + "${workspaceRoot}/_bld/release" ] + }, + "windows": { + "problemMatcher": { + "base": "$msCompile", + "fileLocation": [ + "relative", + "${workspaceRoot}/_bld/release" + ] + } } }, { @@ -76,16 +133,23 @@ "dependsOn": [ "Generate leaf.hpp" ], - "command": "../../b2 test link=shared,static variant=debug,release,leaf_debug_diag0,leaf_release_diag0,leaf_debug_leaf_hpp,leaf_release_leaf_hpp exception-handling=on,off cxxstd=11,14,1z,17 && ../../b2 test link=shared,static variant=debug,release,leaf_debug_diag0,leaf_release_diag0,leaf_debug_leaf_hpp,leaf_release_leaf_hpp,leaf_debug_embedded,leaf_release_embedded exception-handling=off rtti=off cxxstd=11,14,1z,17", - "windows": { - "command": "..\\..\\b2 test link=shared,static variant=debug,release,leaf_debug_diag0,leaf_release_diag0,leaf_debug_leaf_hpp,leaf_release_leaf_hpp exception-handling=on,off cxxstd=14,17,latest && ..\\..\\b2 test link=shared,static variant=debug,release,leaf_debug_diag0,leaf_release_diag0,leaf_debug_leaf_hpp,leaf_release_leaf_hpp,leaf_debug_embedded,leaf_release_embedded exception-handling=off rtti=off cxxstd=14,17,latest", - }, + "command": "../../b2 --abbreviate-paths test link=shared,static variant=debug,release,leaf_debug_diag0,leaf_release_diag0,leaf_debug_single_header,leaf_release_single_header,leaf_debug_embedded,leaf_release_embedded exception-handling=off rtti=off cxxstd=11,14,1z,17 && ../../b2 --abbreviate-paths test link=shared,static variant=debug,release,leaf_debug_diag0,leaf_release_diag0,leaf_debug_single_header,leaf_release_single_header exception-handling=on,off cxxstd=11,14,1z,17", "problemMatcher": { "base": "$gcc", "fileLocation": [ "relative", - "${workspaceRoot}/bld/release" + "${workspaceRoot}/_bld/release" ] + }, + "windows": { + "command": "..\\..\\b2 --abbreviate-paths test link=shared,static variant=debug,release,leaf_debug_diag0,leaf_release_diag0,leaf_debug_single_header,leaf_release_single_header,leaf_debug_embedded,leaf_release_embedded exception-handling=off rtti=off cxxstd=14,17,latest && ..\\..\\b2 --abbreviate-paths test link=shared,static variant=debug,release,leaf_debug_diag0,leaf_release_diag0,leaf_debug_single_header,leaf_release_single_header exception-handling=on,off cxxstd=14,17,latest", + "problemMatcher": { + "base": "$msCompile", + "fileLocation": [ + "relative", + "${workspaceRoot}/_bld/release" + ] + } } }, { @@ -95,13 +159,26 @@ }, "label": "Test current editor file", "type": "shell", - "command": "cd ${workspaceRoot}/bld/debug && ninja && { meson test ${fileBasenameNoExtension} || cat ./meson-logs/testlog.txt }", + "command": "cd ${workspaceRoot}/_bld/debug && ninja && { meson test ${fileBasenameNoExtension} || cat ./meson-logs/testlog.txt; }",, + "windows": { + "command": "cd ${workspaceRoot}/_bld/debug && ninja && (meson test ${fileBasenameNoExtension} || type .\\meson-logs\\testlog.txt)", + }, "problemMatcher": { "base": "$gcc", "fileLocation": [ "relative", - "${workspaceRoot}/bld/debug" + "${workspaceRoot}/_bld/debug" ] + }, + "windows": { + "command": "cd ${workspaceRoot}/_bld/debug && ninja && (meson test ${fileBasenameNoExtension} || type .\\meson-logs\\testlog.txt)", + "problemMatcher": { + "base": "$msCompile", + "fileLocation": [ + "relative", + "${workspaceRoot}/_bld/debug" + ] + } } } ] diff --git a/README.md b/README.md index a8241876..53ca5f84 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ https://boostorg.github.io/leaf/ ## Features * Portable single-header format, no dependencies. -* Tiny code size when configured for embedded development. +* Tiny code size, configurable for embedded development. * No dynamic memory allocations, even with very large payloads. * Deterministic unbiased efficiency on the "happy" path and the "sad" path. * Error objects are handled in constant time, independent of call stack depth. @@ -26,6 +26,6 @@ https://boostorg.github.io/leaf/ Besides GitHub, there are two other distribution channels: * LEAF is included in official [Boost](https://www.boost.org/) releases, starting with Boost 1.75. -* For maximum portability, the library is also available in single-header format: simply download [leaf.hpp](https://boostorg.github.io/leaf/leaf.hpp) (direct download link). +* For maximum portability, the library is also available in single-header format: [leaf.hpp](https://raw.githubusercontent.com/boostorg/leaf/gh-pages/leaf.hpp). -Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. Distributed under the http://www.boost.org/LICENSE_1_0.txt[Boost Software License, Version 1.0]. +Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc. Distributed under the http://www.boost.org/LICENSE_1_0.txt[Boost Software License, Version 1.0]. diff --git a/appveyor.yml b/appveyor.yml deleted file mode 100644 index 0b3a7bd3..00000000 --- a/appveyor.yml +++ /dev/null @@ -1,44 +0,0 @@ -# Copyright 2016, 2017 Peter Dimov -# Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. -# Distributed under the Boost Software License, Version 1.0. -# (See accompanying file LICENSE_1_0.txt or copy at http://boost.org/LICENSE_1_0.txt) - -version: 1.0.{build}-{branch} - -shallow_clone: true - -branches: - only: - - master - - develop - -environment: - matrix: - - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2017 - TOOLSET: msvc-14.1,clang-win - CXXSTD: 14,17 - - APPVEYOR_BUILD_WORKER_IMAGE: Visual Studio 2019 - TOOLSET: msvc-14.2 - CXXSTD: 14,17 - -install: - - set BOOST_BRANCH=develop - - if "%APPVEYOR_REPO_BRANCH%" == "master" set BOOST_BRANCH=master - - cd .. - - git clone -b %BOOST_BRANCH% --depth 1 https://github.com/boostorg/boost.git boost-root - - cd boost-root - - git submodule update --init tools/build - - git submodule update --init tools/boost_install - - git submodule update --init libs/config - - git submodule update --init libs/headers - - git submodule update --init tools/boostdep - - xcopy /s /e /q %APPVEYOR_BUILD_FOLDER% libs\leaf\ - - python tools/boostdep/depinst/depinst.py leaf - - cmd /c bootstrap - - b2 headers - -build: off - -test_script: - - if not "%CXXSTD%" == "" set CXXSTD=cxxstd=%CXXSTD% - - b2 -j3 libs/leaf/test toolset=%TOOLSET% exception-handling=on,off variant=debug,release,leaf_debug_diag0,leaf_release_diag0 define=_CRT_SECURE_NO_WARNINGS %CXXSTD% diff --git a/benchmark/b.bat b/benchmark/b.bat deleted file mode 100644 index 1f475c54..00000000 --- a/benchmark/b.bat +++ /dev/null @@ -1,6 +0,0 @@ -ninja -del benchmark.csv -deep_stack_leaf -deep_stack_tl -deep_stack_result -deep_stack_outcome diff --git a/benchmark/b.sh b/benchmark/b.sh deleted file mode 100755 index dcd010e1..00000000 --- a/benchmark/b.sh +++ /dev/null @@ -1,6 +0,0 @@ -ninja -rm benchmark.csv -./deep_stack_leaf -./deep_stack_tl -./deep_stack_result -./deep_stack_outcome diff --git a/benchmark/benchmark.md b/benchmark/benchmark.md deleted file mode 100644 index 0ae9b332..00000000 --- a/benchmark/benchmark.md +++ /dev/null @@ -1,471 +0,0 @@ -# Benchmark - -The LEAF github repository contains two similar benchmarking programs, one using LEAF, the other configurable to use `tl::expected` or Boost Outcome, that simulate transporting error objects across 10 levels of stack frames, measuring the performance of the three libraries. - -Links: -* LEAF: https://boostorg.github.io/leaf -* `tl::expected`: https://github.com/TartanLlama/expected -* Boost Outcome V2: https://www.boost.org/doc/libs/release/libs/outcome/doc/html/index.html - -## Library design considerations - -LEAF serves a similar purpose to other error handling libraries, but its design is very different. The benchmarks are comparing apples and oranges. - -The main design difference is that when using LEAF, error objects are not communicated in return values. In case of a failure, the `leaf::result` object transports only an `int`, the unique error ID. - -Error objects skip the error neutral functions in the call stack and get moved directly to the the error handling scope that needs them. This mechanism does not depend on RVO or any other optimization: as soon as the program passes an error object to LEAF, it moves it to the correct error handling scope. - -Other error handling libraries instead couple the static type of the return value of *all* error neutral functions with the error type an error reporting function may return. This approach suffers from the same problems as statically-enforced exception specifications: - -* It's difficult to use in polymorphic function calls, and -* It impedes interoperability between the many different error types any non-trivial program must handle. - -(The Boost Outcome library is also capable of avoiding such excessive coupling, by passing for the third `P` argument in the `outcome` template a pointer that erases the exact static type of the object being transported. However, this would require a dynamic memory allocation). - -## Syntax - -The most common check-only use case looks almost identically in LEAF and in Boost Outcome (`tl::expected` lacks a similar macro): - -```c++ -// Outcome -{ - BOOST_OUTCOME_TRY(v, f()); // Check for errors, forward failures to the caller - // If control reaches here, v is the successful result (the call succeeded). -} -``` - -```c++ -// LEAF -{ - BOOST_LEAF_AUTO(v, f()); // Check for errors, forward failures to the caller - // If control reaches here, v is the successful result (the call succeeded). -} -``` - -When we want to handle failures, in Boost Outcome and in `tl::expected`, accessing the error object (which is always stored in the return value) is a simple continuation of the error check: - -```c++ -// Outcome, tl::expected -if( auto r = f() ) -{ - auto v = r.value(); - // No error, use v -} -else -{ // Error! - switch( r.error() ) - { - error_enum::error1: - /* handle error_enum::error1 */ - break; - - error_enum::error2: - /* handle error_enum::error2 */ - break; - - default: - /* handle any other failure */ - } -} -``` - -When using LEAF, we must explicitly state our intention to handle errors, not just check for failures: - -```c++ -// LEAF -leaf::try_handle_all - - []() -> leaf::result - { - BOOST_LEAF_AUTO(v, f()); - // No error, use v - }, - - []( leaf::match ) - { - /* handle error_enum::error1 */ - }, - - []( leaf::match ) - { - /* handle error_enum::error2 */ - }, - - [] - { - /* handle any other failure */ - } ); -``` - -The use of `try_handle_all` reserves storage on the stack for the error object types being handled (in this case, `error_enum`). If the failure is either `error_enum::error1` or `error_enum::error2`, the matching error handling lambda is invoked. - -## Code generation considerations - -Benchmarking C++ programs is tricky, because we want to prevent the compiler from optimizing out things it shouldn't normally be able to optimize in a real program, yet we don't want to interfere with "legitimate" optimizations. - -The primary approach we use to prevent the compiler from optimizing everything out to nothing is to base all computations on a call to `std::rand()`. - -When benchmarking error handling, it makes sense to measure the time it takes to return a result or error across multiple stack frames. This calls for disabling inlining. - -The technique used to disable inlining in this benchmark is to mark functions with `__attribute__((noinline))`. This is imperfect, because optimizers can still peek into the body of the function and optimize things out, as is seen in this example: - -```c++ -__attribute__((noinline)) int val() {return 42;} - -int main() -{ - return val(); -} -``` - -Which on clang 9 outputs: - -```x86asm -val(): - mov eax, 42 - ret -main: - mov eax, 42 - ret -``` - -It does not appear that anything like this is occurring in our case, but it is still a possibility. - -> NOTES: -> -> - The benchmarks are compiled with exception handling disabled. -> - LEAF is able to work with external `result<>` types. The benchmark uses `leaf::result`. - -## Show me the code! - -The following source: - -```C++ -leaf::result f(); - -leaf::result g() -{ - BOOST_LEAF_AUTO(x, f()); - return x+1; -} -``` - -Generates this code on clang ([Godbolt](https://godbolt.org/z/v58drTPhq)): - -```x86asm -g(): # @g() - push rbx - sub rsp, 32 - mov rbx, rdi - lea rdi, [rsp + 8] - call f() - mov eax, dword ptr [rsp + 24] - mov ecx, eax - and ecx, 3 - cmp ecx, 3 - jne .LBB0_1 - mov eax, dword ptr [rsp + 8] - add eax, 1 - mov dword ptr [rbx], eax - mov eax, 3 - jmp .LBB0_3 -.LBB0_1: - cmp ecx, 2 - jne .LBB0_3 - mov rax, qword ptr [rsp + 8] - mov qword ptr [rbx], rax - mov rax, qword ptr [rsp + 16] - mov qword ptr [rbx + 8], rax - mov eax, 2 -.LBB0_3: - mov dword ptr [rbx + 16], eax - mov rax, rbx - add rsp, 32 - pop rbx - ret -``` - -> Description: -> -> * The happy path can be recognized by the `add eax, 1` instruction generated for `x + 1`. -> -> * `.LBB0_3`: Regular failure; the returned `result` object holds only the `int` discriminant. -> -> * `.LBB0_1`: Failure; the returned `result` holds the `int` discriminant and a `std::shared_ptr` (used to hold error objects transported from another thread). - -Note that `f` is undefined, hence the `call` instruction. Predictably, if we provide a trivial definition for `f`: - -```C++ -leaf::result f() -{ - return 42; -} - -leaf::result g() -{ - BOOST_LEAF_AUTO(x, f()); - return x+1; -} -``` - -We get: - -```x86asm -g(): # @g() - mov rax, rdi - mov dword ptr [rdi], 43 - mov dword ptr [rdi + 16], 3 - ret -``` - -With a less trivial definition of `f`: - -```C++ -leaf::result f() -{ - if( rand()%2 ) - return 42; - else - return leaf::new_error(); -} - -leaf::result g() -{ - BOOST_LEAF_AUTO(x, f()); - return x+1; -} -``` - -We get ([Godbolt](https://godbolt.org/z/87Kezzrs4)): - -```x86asm -g(): # @g() - push rbx - mov rbx, rdi - call rand - test al, 1 - jne .LBB1_2 - mov eax, 4 - lock xadd dword ptr [rip + boost::leaf::leaf_detail::id_factory::counter], eax - add eax, 4 - mov dword ptr fs:[boost::leaf::leaf_detail::id_factory::current_id@TPOFF], eax - and eax, -4 - or eax, 1 - mov dword ptr [rbx + 16], eax - mov rax, rbx - pop rbx - ret -.LBB1_2: - mov dword ptr [rbx], 43 - mov eax, 3 - mov dword ptr [rbx + 16], eax - mov rax, rbx - pop rbx - ret -``` - -Above, the call to `f()` is inlined: - -* `.LBB1_2`: Success -* The atomic `add` is from the initial error reporting machinery in LEAF, generating a unique error ID for the error being reported. - -## Benchmark matrix dimensions - -The benchmark matrix has 2 dimensions: - -1. Error object type: - - a. The error object transported in case of a failure is of type `e_error_code`, which is a simple `enum`. - - b. The error object transported in case of a failure is of type `struct e_system_error { e_error_code value; std::string what; }`. - - c. The error object transported in case of a failure is of type `e_heavy_payload`, a `struct` of size 4096. - -2. Error rate: 2%, 98% - -Now, transporting a large error object might seem unusual, but this is only because it is impractical to return a large object as *the* return value in case of an error. LEAF has two features that make communicating any, even large error objects, practical: - -* The return type of error neutral functions is not coupled with the error object types that may be reported. This means that in case of a failure, any function can easily contribute any error information it has available. - -* LEAF will only bother with transporting a given error object if an active error handling scope needs it. This means that library functions can and should contribute any and all relevant information when reporting a failure, because if the program doesn't need it, it will simply be discarded. - -## Source code - -[deep_stack_leaf.cpp](deep_stack_leaf.cpp) - -[deep_stack_other.cpp](deep_stack_other.cpp) - -## Godbolt - -Godbolt has built-in support for Boost (Outcome/LEAF), but `tl::expected` both provide a single header, which makes it very easy to use them online as well. To see the generated code for the benchmark program, you can copy and paste the following into Godbolt: - -`leaf::result` ([godbolt](https://godbolt.org/z/1hqqnfhMf)) - -```c++ -#include "https://raw.githubusercontent.com/boostorg/leaf/master/benchmark/deep_stack_leaf.cpp" -``` - -`tl::expected` ([godbolt](https://godbolt.org/z/6dfcdsPcc)) - -```c++ -#include "https://raw.githubusercontent.com/TartanLlama/expected/master/include/tl/expected.hpp" -#include "https://raw.githubusercontent.com/boostorg/leaf/master/benchmark/deep_stack_other.cpp" -``` - -`outcome::result` ([godbolt](https://godbolt.org/z/jMEfGMrW9)) - -```c++ -#define BENCHMARK_WHAT 1 -#include "https://raw.githubusercontent.com/boostorg/leaf/master/benchmark/deep_stack_other.cpp" -``` - -## Build options - -To build both versions of the benchmark program, the compilers are invoked using the following command line options: - -* `-std=c++17`: Required by other libraries (LEAF only requires C++11); -* `-fno-exceptions`: Disable exception handling; -* `-O3`: Maximum optimizations; -* `-DNDEBUG`: Disable asserts. - -In addition, the LEAF version is compiled with: - -* `-DBOOST_LEAF_CFG_DIAGNOSTICS=0`: Disable diagnostic information for error objects not recognized by the program. This is a debugging feature, see [Configuration Macros](https://boostorg.github.io/leaf/#configuration). - -## Results - -Below is the output the benchmark programs running on an old MacBook Pro. The tables show the elapsed time for 10,000,000 iterations of returning a result across 10 stack frames, depending on the error type and the rate of failures. In addition, the programs generate a `benchmark.csv` file in the current working directory. - -### gcc 9.2.0: - -`leaf::result`: - -Error type | 2% (μs) | 98% (μs) -----------------|---------:|--------: -e_error_code | 594965 | 545882 -e_system_error | 614688 | 1203154 -e_heavy_payload | 736701 | 7397756 - -`tl::expected`: - -Error type | 2% (μs) | 98% (μs) -----------------|---------:|--------: -e_error_code | 921410 | 820757 -e_system_error | 670191 | 5593513 -e_heavy_payload | 1331724 | 31560432 - -`outcome::result`: - -Error type | 2% (μs) | 98% (μs) -----------------|---------:|--------: -e_error_code | 1080512 | 773206 -e_system_error | 577403 | 1201693 -e_heavy_payload | 13222387 | 32104693 - -`outcome::outcome`: - -Error type | 2% (μs) | 98% (μs) -----------------|---------:|--------: -e_error_code | 832916 | 1170731 -e_system_error | 947298 | 2330392 -e_heavy_payload | 13342292 | 33837583 - -### clang 11.0.0: - -`leaf::result`: - -Error type | 2% (μs) | 98% (μs) -----------------|---------:|--------: -e_error_code | 570847 | 493538 -e_system_error | 592685 | 982799 -e_heavy_payload | 713966 | 5144523 - -`tl::expected`: - -Error type | 2% (μs) | 98% (μs) -----------------|---------:|--------: -e_error_code | 461639 | 312849 -e_system_error | 620479 | 3534689 -e_heavy_payload | 1037434 | 16078669 - -`outcome::result`: - -Error type | 2% (μs) | 98% (μs) -----------------|---------:|--------: -e_error_code | 431219 | 446854 -e_system_error | 589456 | 1712739 -e_heavy_payload | 12387405 | 16216894 - -`outcome::outcome`: - -Error type | 2% (μs) | 98% (μs) -----------------|---------:|--------: -e_error_code | 711412 | 1477505 -e_system_error | 835691 | 2374919 -e_heavy_payload | 13289404 | 29785353 - -### msvc 19.24.28314: - -`leaf::result`: - -Error type | 2% (μs) | 98% (μs) -----------------|---------:|--------: -e_error_code | 1205327 | 1449117 -e_system_error | 1290277 | 2332414 -e_heavy_payload | 1503103 | 13682308 - -`tl::expected`: - -Error type | 2% (μs) | 98% (μs) -----------------|---------:|--------: -e_error_code | 938839 | 867296 -e_system_error | 1455627 | 8943881 -e_heavy_payload | 2637494 | 49212901 - -`outcome::result`: - -Error type | 2% (μs) | 98% (μs) -----------------|---------:|--------: -e_error_code | 935331 | 1202475 -e_system_error | 1228944 | 2269680 -e_heavy_payload | 15239084 | 55618460 - -`outcome::outcome`: - -Error type | 2% (μs) | 98% (μs) -----------------|---------:|--------: -e_error_code | 1472035 | 2529057 -e_system_error | 1997971 | 4004965 -e_heavy_payload | 16027423 | 64572924 - -## Charts - -The charts below are generated from the results from the previous section, converted from elapsed time in microseconds to millions of calls per second. - -### gcc 9.2.0: - -![](gcc_e_error_code.png) - -![](gcc_e_system_error.png) - -![](gcc_e_heavy_payload.png) - -### clang 11.0.0: - -![](clang_e_error_code.png) - -![](clang_e_system_error.png) - -![](clang_e_heavy_payload.png) - -### msvc 19.24.28314: - -![](msvc_e_error_code.png) - -![](msvc_e_system_error.png) - -![](msvc_e_heavy_payload.png) - -## Thanks - -Thanks for the valuable feedback: Peter Dimov, Glen Fernandes, Sorin Fetche, Niall Douglas, Ben Craig, Vinnie Falco, Jason Dictos diff --git a/benchmark/clang_e_error_code.png b/benchmark/clang_e_error_code.png deleted file mode 100644 index 94a5ee6d..00000000 Binary files a/benchmark/clang_e_error_code.png and /dev/null differ diff --git a/benchmark/clang_e_heavy_payload.png b/benchmark/clang_e_heavy_payload.png deleted file mode 100644 index 88004d5f..00000000 Binary files a/benchmark/clang_e_heavy_payload.png and /dev/null differ diff --git a/benchmark/clang_e_system_error.png b/benchmark/clang_e_system_error.png deleted file mode 100644 index 267f4ec9..00000000 Binary files a/benchmark/clang_e_system_error.png and /dev/null differ diff --git a/benchmark/deep_stack_leaf.cpp b/benchmark/deep_stack_leaf.cpp deleted file mode 100644 index 1c5676a7..00000000 --- a/benchmark/deep_stack_leaf.cpp +++ /dev/null @@ -1,276 +0,0 @@ -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. - -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - -// See benchmark.md - -#include - -#ifndef BOOST_LEAF_NO_EXCEPTIONS -# error Please disable exception handling. -#endif - -#if BOOST_LEAF_CFG_DIAGNOSTICS -# error Please disable diagnostics. -#endif - -#ifdef _MSC_VER -# define NOINLINE __declspec(noinline) -# define ALWAYS_INLINE __forceinline -#else -# define NOINLINE __attribute__((noinline)) -# define ALWAYS_INLINE __attribute__((always_inline)) inline -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost -{ - BOOST_LEAF_NORETURN void throw_exception( std::exception const & e ) - { - std::cerr << "Terminating due to a C++ exception under BOOST_LEAF_NO_EXCEPTIONS: " << e.what(); - std::terminate(); - } - - struct source_location; - BOOST_LEAF_NORETURN void throw_exception( std::exception const & e, boost::source_location const & ) - { - throw_exception(e); - } -} - -////////////////////////////////////// - -namespace leaf = boost::leaf; - -#define USING_RESULT_TYPE "leaf::result" - -////////////////////////////////////// - -enum class e_error_code -{ - ec0, ec1, ec2, ec3 -}; - -struct e_system_error -{ - int value; - std::string what; -}; - -struct e_heavy_payload -{ - std::array value; -}; - -template -leaf::error_id make_error() noexcept; - -template <> -inline leaf::error_id make_error() noexcept -{ - switch(std::rand()%4) - { - default: return leaf::new_error(e_error_code::ec0); - case 1: return leaf::new_error(e_error_code::ec1); - case 2: return leaf::new_error(e_error_code::ec2); - case 3: return leaf::new_error(e_error_code::ec3); - } -} - -template <> -inline leaf::error_id make_error() noexcept -{ - return std::error_code(std::rand(), std::system_category()); -} - -template <> -inline leaf::error_id make_error() noexcept -{ - return leaf::new_error( e_system_error { std::rand(), std::string(std::rand()%32, ' ') } ); -} - -template <> -inline leaf::error_id make_error() noexcept -{ - e_heavy_payload e; - std::fill(e.value.begin(), e.value.end(), std::rand()); - return leaf::new_error(e); -} - -inline bool should_fail( int failure_rate ) noexcept -{ - assert(failure_rate>=0); - assert(failure_rate<=100); - return (std::rand()%100) < failure_rate; -} - -inline int handle_error( e_error_code e ) noexcept -{ - return int(e); -} - -inline int handle_error( std::error_code const & e ) noexcept -{ - return e.value(); -} - -inline int handle_error( e_system_error const & e ) noexcept -{ - return e.value + e.what.size(); -} - -inline int handle_error( e_heavy_payload const & e ) noexcept -{ - return std::accumulate(e.value.begin(), e.value.end(), 0); -} - -////////////////////////////////////// - -// This is used to change the "success" type at each level. -// Generally, functions return values of different types. -template -struct select_result_type; - -template -struct select_result_type -{ - using type = leaf::result; // Does not depend on E -}; - -template -struct select_result_type -{ - using type = leaf::result; // Does not depend on E -}; - -template -using select_result_t = typename select_result_type::type; - -////////////////////////////////////// - -template -struct benchmark -{ - using e_type = E; - - NOINLINE static select_result_t f( int failure_rate ) noexcept - { - BOOST_LEAF_AUTO(x, (benchmark::f(failure_rate))); - return x+1; - } -}; - -template -struct benchmark<1, E> -{ - using e_type = E; - - NOINLINE static select_result_t<1, E> f( int failure_rate ) noexcept - { - if( should_fail(failure_rate) ) - return make_error(); - else - return std::rand(); - } -}; - -////////////////////////////////////// - -template -NOINLINE int runner( int failure_rate ) noexcept -{ - return leaf::try_handle_all( - [=] - { - return Benchmark::f(failure_rate); - }, - []( typename Benchmark::e_type const & e ) - { - return handle_error(e); - }, - [] - { - return -1; - } ); -} - -////////////////////////////////////// - -std::fstream append_csv() -{ - if( FILE * f = fopen("benchmark.csv","rb") ) - { - fclose(f); - return std::fstream("benchmark.csv", std::fstream::out | std::fstream::app); - } - else - { - std::fstream fs("benchmark.csv", std::fstream::out | std::fstream::app); - fs << "\"Result Type\",2%,98%\n"; - return fs; - } -} - -template -int print_elapsed_time( int iteration_count, F && f ) -{ - auto start = std::chrono::steady_clock::now(); - int val = 0; - for( int i = 0; i!=iteration_count; ++i ) - val += std::forward(f)(); - auto stop = std::chrono::steady_clock::now(); - int elapsed = std::chrono::duration_cast(stop-start).count(); - std::cout << std::right << std::setw(9) << elapsed; - append_csv() << ',' << elapsed; - return val; -} - -////////////////////////////////////// - -template -int benchmark_type( char const * type_name, int iteration_count ) -{ - int x=0; - append_csv() << "\"" USING_RESULT_TYPE "\""; - std::cout << '\n' << std::left << std::setw(16) << type_name << '|'; - std::srand(0); - x += print_elapsed_time( iteration_count, [] { return runner>(2); } ); - std::cout << " |"; - std::srand(0); - x += print_elapsed_time( iteration_count, [] { return runner>(98); } ); - append_csv() << '\n'; - return x; -} - -////////////////////////////////////// - -int main() -{ - int const depth = 10; - int const iteration_count = 10000000; - std::cout << - iteration_count << " iterations, call depth " << depth << ", sizeof(e_heavy_payload) = " << sizeof(e_heavy_payload) << "\n" - USING_RESULT_TYPE "\n" - "Error type | 2% (μs) | 98% (μs)\n" - "----------------|----------|---------"; - int r = 0; - r += benchmark_type("e_error_code", iteration_count); - r += benchmark_type("std::error_code", iteration_count); - r += benchmark_type("e_system_error", iteration_count); - r += benchmark_type("e_heavy_payload", iteration_count); - std::cout << '\n'; - // std::cout << std::rand() << '\n'; - return r; -} diff --git a/benchmark/deep_stack_other.cpp b/benchmark/deep_stack_other.cpp deleted file mode 100644 index aa61f67f..00000000 --- a/benchmark/deep_stack_other.cpp +++ /dev/null @@ -1,308 +0,0 @@ -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. - -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - -// See benchmark.md - -#ifndef BENCHMARK_WHAT -# define BENCHMARK_WHAT 0 -#endif - -#if BENCHMARK_WHAT == 0 - -# ifndef TL_EXPECTED_HPP -# include "tl/expected.hpp" -# endif -# define BENCHMARK_SUCCESS(e) e -# define BENCHMARK_FAILURE(e) tl::make_unexpected(e) -# define BENCHMARK_TRY(v,r)\ - auto && _r_##v = r;\ - if( !_r_##v )\ - return BENCHMARK_FAILURE(_r_##v.error());\ - auto && v = _r_##v.value() - -#else - -# include -# include -# define BENCHMARK_SUCCESS(e) boost::outcome_v2::success(e) -# define BENCHMARK_FAILURE(e) boost::outcome_v2::failure(e) -# define BENCHMARK_TRY BOOST_OUTCOME_TRY -# ifndef BOOST_NO_EXCEPTIONS -# error Please disable exception handling. -# endif - -#endif - -#ifdef _MSC_VER -# define NOINLINE __declspec(noinline) -# define ALWAYS_INLINE __forceinline -#else -# define NOINLINE __attribute__((noinline)) -# define ALWAYS_INLINE __attribute__((always_inline)) inline -#endif - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace boost -{ - void throw_exception( std::exception const & e ) - { - std::cerr << "Terminating due to a C++ exception under BOOST_NO_EXCEPTIONS: " << e.what(); - std::terminate(); - } - - struct source_location; - void throw_exception( std::exception const & e, boost::source_location const & ) - { - throw_exception(e); - } -} - -////////////////////////////////////// - -#if BENCHMARK_WHAT == 0 // tl::expected - -# define USING_RESULT_TYPE "tl::expected" - - template - using result = tl::expected; - -#elif BENCHMARK_WHAT == 1 // outcome::result - -# define USING_RESULT_TYPE "outcome::result" - - template - using result = boost::outcome_v2::std_result; - -#elif BENCHMARK_WHAT == 2 // outcome::outcome - -# define USING_RESULT_TYPE "outcome::outcome" - - template - using result = boost::outcome_v2::std_outcome; - -#else -# error Benchmark what? -#endif - -////////////////////////////////////// - -enum class e_error_code -{ - ec0, ec1, ec2, ec3 -}; - -struct e_system_error -{ - int value; - std::string what; -}; - -struct e_heavy_payload -{ - std::array value; -}; - -template -E make_error() noexcept; - -template <> -inline e_error_code make_error() noexcept -{ - switch(std::rand()%4) - { - default: return e_error_code::ec0; - case 1: return e_error_code::ec1; - case 2: return e_error_code::ec2; - case 3: return e_error_code::ec3; - } -} - -template <> -inline std::error_code make_error() noexcept -{ - return std::error_code(std::rand(), std::system_category()); -} - -template <> -inline e_system_error make_error() noexcept -{ - return { std::rand(), std::string(std::rand()%32, ' ') }; -} - -template <> -inline e_heavy_payload make_error() noexcept -{ - e_heavy_payload e; - std::fill(e.value.begin(), e.value.end(), std::rand()); - return e; -} - -inline bool should_fail( int failure_rate ) noexcept -{ - assert(failure_rate>=0); - assert(failure_rate<=100); - return (std::rand()%100) < failure_rate; -} - -inline int handle_error( e_error_code e ) noexcept -{ - return int(e); -} - -inline int handle_error( std::error_code const & e ) noexcept -{ - return e.value(); -} - -inline int handle_error( e_system_error const & e ) noexcept -{ - return e.value + e.what.size(); -} - -inline int handle_error( e_heavy_payload const & e ) noexcept -{ - return std::accumulate(e.value.begin(), e.value.end(), 0); -} - -////////////////////////////////////// - -// This is used to change the "success" type at each level. -// Generally, functions return values of different types. -template -struct select_result_type; - -template -struct select_result_type -{ - using type = result; -}; - -template -struct select_result_type -{ - using type = result; -}; - -template -using select_result_t = typename select_result_type::type; - -////////////////////////////////////// - -template -struct benchmark -{ - using e_type = E; - - NOINLINE static select_result_t f( int failure_rate ) noexcept - { - BENCHMARK_TRY(x, (benchmark::f(failure_rate))); - return BENCHMARK_SUCCESS(x+1); - } -}; - -template -struct benchmark<1, E> -{ - using e_type = E; - - NOINLINE static select_result_t<1, E> f( int failure_rate ) noexcept - { - if( should_fail(failure_rate) ) - return BENCHMARK_FAILURE(make_error()); - else - return BENCHMARK_SUCCESS(std::rand()); - } -}; - -////////////////////////////////////// - -template -NOINLINE int runner( int failure_rate ) noexcept -{ - if( auto r = Benchmark::f(failure_rate) ) - return r.value(); - else - return handle_error(r.error()); -} - -////////////////////////////////////// - -std::fstream append_csv() -{ - if( FILE * f = fopen("benchmark.csv","rb") ) - { - fclose(f); - return std::fstream("benchmark.csv", std::fstream::out | std::fstream::app); - } - else - { - std::fstream fs("benchmark.csv", std::fstream::out | std::fstream::app); - fs << "\"Result Type\",2%,98%\n"; - return fs; - } -} - -template -int print_elapsed_time( int iteration_count, F && f ) -{ - auto start = std::chrono::steady_clock::now(); - int val = 0; - for( int i = 0; i!=iteration_count; ++i ) - val += std::forward(f)(); - auto stop = std::chrono::steady_clock::now(); - int elapsed = std::chrono::duration_cast(stop-start).count(); - std::cout << std::right << std::setw(9) << elapsed; - append_csv() << ',' << elapsed; - return val; -} - -////////////////////////////////////// - -template -int benchmark_type( char const * type_name, int iteration_count ) -{ - int x=0; - append_csv() << "\"" USING_RESULT_TYPE "\""; - std::cout << '\n' << std::left << std::setw(16) << type_name << '|'; - std::srand(0); - x += print_elapsed_time( iteration_count, [] { return runner>(2); } ); - std::cout << " |"; - std::srand(0); - x += print_elapsed_time( iteration_count, [] { return runner>(98); } ); - append_csv() << '\n'; - return x; -} - -////////////////////////////////////// - -int main() -{ - int const depth = 10; - int const iteration_count = 10000000; - std::cout << - iteration_count << " iterations, call depth " << depth << ", sizeof(e_heavy_payload) = " << sizeof(e_heavy_payload) << "\n" - USING_RESULT_TYPE "\n" - "Error type | 2% (μs) | 98% (μs)\n" - "----------------|----------|---------"; - int r = 0; - r += benchmark_type("e_error_code", iteration_count); - r += benchmark_type("std::error_code", iteration_count); - r += benchmark_type("e_system_error", iteration_count); - r += benchmark_type("e_heavy_payload", iteration_count); - std::cout << '\n'; - // std::cout << std::rand() << '\n'; - return r; -} diff --git a/benchmark/gcc_e_error_code.png b/benchmark/gcc_e_error_code.png deleted file mode 100644 index 48a777ab..00000000 Binary files a/benchmark/gcc_e_error_code.png and /dev/null differ diff --git a/benchmark/gcc_e_heavy_payload.png b/benchmark/gcc_e_heavy_payload.png deleted file mode 100644 index 4c19bd9f..00000000 Binary files a/benchmark/gcc_e_heavy_payload.png and /dev/null differ diff --git a/benchmark/gcc_e_system_error.png b/benchmark/gcc_e_system_error.png deleted file mode 100644 index 255fc9d1..00000000 Binary files a/benchmark/gcc_e_system_error.png and /dev/null differ diff --git a/benchmark/msvc_e_error_code.png b/benchmark/msvc_e_error_code.png deleted file mode 100644 index 20962cc7..00000000 Binary files a/benchmark/msvc_e_error_code.png and /dev/null differ diff --git a/benchmark/msvc_e_heavy_payload.png b/benchmark/msvc_e_heavy_payload.png deleted file mode 100644 index e5d10844..00000000 Binary files a/benchmark/msvc_e_heavy_payload.png and /dev/null differ diff --git a/benchmark/msvc_e_system_error.png b/benchmark/msvc_e_system_error.png deleted file mode 100644 index edd70fae..00000000 Binary files a/benchmark/msvc_e_system_error.png and /dev/null differ diff --git a/build.jam b/build.jam new file mode 100644 index 00000000..0fcce930 --- /dev/null +++ b/build.jam @@ -0,0 +1,17 @@ +# Copyright René Ferdinand Rivera Morell 2023-2024 +# Distributed under the Boost Software License, Version 1.0. +# (See accompanying file LICENSE_1_0.txt or copy at +# http://www.boost.org/LICENSE_1_0.txt) + +require-b2 5.2 ; + +project /boost/leaf + ; + +explicit + [ alias boost_leaf : : : : include ] + [ alias all : boost_leaf test ] + ; + +call-if : boost-library leaf + ; diff --git a/conanfile.py b/conanfile.py new file mode 100644 index 00000000..641a70c5 --- /dev/null +++ b/conanfile.py @@ -0,0 +1,80 @@ +from conan import ConanFile +from conan.tools.files import copy +from conan.tools.layout import basic_layout +from conan.tools.build import check_min_cppstd +from conan.errors import ConanInvalidConfiguration +import os + + +required_conan_version = ">=1.50.0" + + +class BoostLEAFConan(ConanFile): + name = "boost-leaf" + version = "1.81.0" + license = "BSL-1.0" + url = "https://github.com/conan-io/conan-center-index" + homepage = "https://github.com/boostorg/leaf" + description = ("Lightweight Error Augmentation Framework") + topics = ("multi-platform", "multi-threading", "cpp11", "error-handling", + "header-only", "low-latency", "no-dependencies", "single-header") + settings = "os", "compiler", "arch", "build_type" + exports_sources = "include/*", "LICENSE_1_0.txt" + no_copy_source = True + + def package_id(self): + self.info.clear() + + @property + def _min_cppstd(self): + return "11" + + @property + def _compilers_minimum_version(self): + return { + "gcc": "4.8", + "Visual Studio": "17", + "msvc": "141", + "clang": "3.9", + "apple-clang": "10.0.0" + } + + def requirements(self): + pass + + def validate(self): + if self.settings.get_safe("compiler.cppstd"): + check_min_cppstd(self, self._min_cppstd) + + def lazy_lt_semver(v1, v2): + lv1 = [int(v) for v in v1.split(".")] + lv2 = [int(v) for v in v2.split(".")] + min_length = min(len(lv1), len(lv2)) + return lv1[:min_length] < lv2[:min_length] + + compiler = str(self.settings.compiler) + version = str(self.settings.compiler.version) + minimum_version = self._compilers_minimum_version.get(compiler, False) + + if minimum_version and lazy_lt_semver(version, minimum_version): + raise ConanInvalidConfiguration( + f"{self.name} {self.version} requires C++{self._min_cppstd}, which your compiler ({compiler}-{version}) does not support") + + def layout(self): + basic_layout(self) + + def package(self): + copy(self, "LICENSE_1_0.txt", dst=os.path.join( + self.package_folder, "licenses"), src=self.source_folder) + copy(self, "*.h", dst=os.path.join(self.package_folder, "include"), + src=os.path.join(self.source_folder, "include")) + copy(self, "*.hpp", dst=os.path.join(self.package_folder, + "include"), src=os.path.join(self.source_folder, "include")) + + def package_info(self): + self.cpp_info.set_property("cmake_target_name", "boost::leaf") + + self.cpp_info.bindirs = [] + self.cpp_info.frameworkdirs = [] + self.cpp_info.libdirs = [] + self.cpp_info.resdirs = [] diff --git a/doc/Jamfile b/doc/Jamfile index e183454f..9840338e 100644 --- a/doc/Jamfile +++ b/doc/Jamfile @@ -1,15 +1,15 @@ # Copyright 2017 Peter Dimov -# Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. +# Copyright 2018-2024 Emil Dotchevski and Reverge Studios, Inc. # # Distributed under the Boost Software License, Version 1.0. # (See accompanying file LICENSE_1_0.txt or copy at # http://www.boost.org/LICENSE_1_0.txt) project doc/leaf ; -import asciidoctor ; +using asciidoctor ; html index.html : leaf.adoc : stylesheet=zajo-dark.css linkcss ; -install html_ : index.html LEAF-1.png LEAF-2.png skin.png zajo-dark.css zajo-light.css rouge-github.css : html ; +install html_ : index.html skin.png zajo-dark.css zajo-light.css rouge-github.css : html ; pdf leaf.pdf : leaf.adoc : book pdf-themesdir=. pdf-theme=leaf ; install pdf_ : leaf.pdf : html ; diff --git a/doc/LEAF-1.png b/doc/LEAF-1.png deleted file mode 100644 index 9aa55b7b..00000000 Binary files a/doc/LEAF-1.png and /dev/null differ diff --git a/doc/LEAF-2.png b/doc/LEAF-2.png deleted file mode 100644 index 1237ef2a..00000000 Binary files a/doc/LEAF-2.png and /dev/null differ diff --git a/doc/leaf.adoc b/doc/leaf.adoc index 7e97d26e..c01f4634 100644 --- a/doc/leaf.adoc +++ b/doc/leaf.adoc @@ -29,7 +29,7 @@ Boost LEAF is a lightweight error handling library for {CPP}11. Features: ==== * Portable single-header format, no dependencies. -* Tiny code size when configured for embedded development. +* Tiny code size, configurable for embedded development. * No dynamic memory allocations, even with very large payloads. @@ -43,16 +43,13 @@ Boost LEAF is a lightweight error handling library for {CPP}11. Features: ifndef::backend-pdf[] [grid=none, frame=none] |==== -| <> \| <> \| https://github.com/boostorg/leaf/blob/master/doc/whitepaper.md[Whitepaper] \| https://github.com/boostorg/leaf/blob/master/benchmark/benchmark.md[Benchmark] >| Reference: <> \| <> \| <> \| <> \| <> +| <> \| <> \| https://github.com/boostorg/leaf/blob/master/doc/whitepaper.md[Whitepaper] >| Reference: <> \| <> \| <> \| <> \| <> |==== endif::[] [[support]] == Support -* https://Cpplang.slack.com[cpplang on Slack] (use the `#boost` channel) -* https://lists.boost.org/mailman/listinfo.cgi/boost-users[Boost Users Mailing List] -* https://lists.boost.org/mailman/listinfo.cgi/boost[Boost Developers Mailing List] * https://github.com/boostorg/leaf/issues[Report issues] on GitHub [[distribution]] @@ -64,38 +61,38 @@ There are three distribution channels: * LEAF is included in official https://www.boost.org/[Boost] releases (starting with Boost 1.75), and therefore available via most package managers. * The source code is hosted on https://github.com/boostorg/leaf[GitHub]. -* For maximum portability, the latest LEAF release is also available in single-header format: simply download link:https://raw.githubusercontent.com/boostorg/leaf/gh-pages/leaf.hpp[leaf.hpp] (direct download link). +* For maximum portability, the latest LEAF release is also available in single-header format: link:https://raw.githubusercontent.com/boostorg/leaf/gh-pages/leaf.hpp[leaf.hpp] (direct download link). NOTE: LEAF does not depend on Boost or other libraries. [[tutorial]] == Tutorial -What is a failure? It is simply the inability of a function to return a valid result, instead producing an error object describing the reason for the failure. +Typically, error handling libraries define a variant result type, e.g. `result`. In LEAF we drop the `E`, using just `result`. -A typical design is to return a variant type, e.g. `result`. Internally, such variant types must store a discriminant (in this case a boolean) to indicate whether the object holds a `T` or an `E`. +In case of success, access to the value `T` is immediate and direct, and we can easily bail out in case of a failure. -The design of LEAF is informed by the observation that the immediate caller must have access to the discriminant in order to determine the availability of a valid `T`, but otherwise it rarely needs to access the `E`. The error object is only needed once an error handling scope is reached. +To handle errors, we use a special syntax, which enables error objects to be transported directly to the error handling scopes that need them. This is more efficient than holding them in result types, and it also allows any given handler to access multiple error objects associated with the same failure. -Therefore what would have been a `result` becomes `result`, which stores the discriminant and (optionally) a `T`, while the `E` is communicated directly to the error handling scope where it is needed. - -The benefit of this decomposition is that `result` becomes extremely lightweight, as it is not coupled with error types; further, error objects are communicated in constant time (independent of the call stack depth). Even very large objects are handled efficiently without dynamic memory allocation. +LEAF is also compatible with exception handling, providing identical functionality but without needing a result type. === Reporting Errors -A function that reports an error is pretty straight-forward: +Let's introduce the `result`-based interface first. + +Report errors with `leaf::new_error`: [source,c++] ---- -enum class err1 { e1, e2, e3 }; +enum class api_error { connect_failed, invalid_request, timeout }; -leaf::result f() +leaf::result connect() { .... - if( error_detected ) - return leaf::new_error( err1::e1 ); // Pass an error object of any type + if( <> ) + return leaf::new_error( api_error::connect_failed ); // Pass error objects of any type - // Produce and return a T. + // Produce and return a connection object. } ---- [.text-right] @@ -106,65 +103,65 @@ leaf::result f() [[checking_for_errors]] === Checking for Errors -Checking for errors communicated by a `leaf::result` works as expected: +To bail out on failure, return `result::error()`: [source,c++] ---- -leaf::result g() +leaf::result connect_and_fetch_data() { - leaf::result r = f(); - if( !r ) - return r.error(); + leaf::result cr = connect(); + if( !cr ) + return cr.error(); + + connection & c = cr.value(); - T const & v = r.value(); - // Use v to produce a valid U + // Use c to fetch and return data } ---- [.text-right] <> -TIP: The the result of `r.error()` is compatible with any instance of the `leaf::result` template. In the example above, note that `g` returns a `leaf::result`, while `r` is of type `leaf::result`. - -The boilerplate `if` statement can be avoided using `BOOST_LEAF_AUTO`: +Use `BOOST_LEAF_AUTO` to avoid the boilerplate `if` statement: [source,c++] ---- -leaf::result g() +leaf::result connect_and_fetch_data() { - BOOST_LEAF_AUTO(v, f()); // Bail out on error + BOOST_LEAF_AUTO(c, connect()); // Bail out on error - // Use v to produce a valid U + // Use c to fetch and return data } ---- [.text-right] <> -`BOOST_LEAF_AUTO` can not be used with `void` results; in that case, to avoid the boilerplate `if` statement, use `BOOST_LEAF_CHECK`: +Use `BOOST_LEAF_CHECK` in case of `void` results: [source,c++] ---- -leaf::result f(); +leaf::result flush(connection & c); +leaf::result bytes_sent(connection & c); -leaf::result g() +leaf::result flush_and_get_bytes_sent(connection & c) { - BOOST_LEAF_CHECK(f()); // Bail out on error - return 42; + BOOST_LEAF_CHECK(flush(c)); // Bail out on error + return bytes_sent(c); } ---- [.text-right] <> -On implementations that define `pass:[__GNUC__]` (e.g. GCC/clang), the `BOOST_LEAF_CHECK` macro definition takes advantage of https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html[GNU C statement expressions]. In this case, in addition to its portable usage with `result`, `BOOST_LEAF_CHECK` can be used in expressions with non-`void` result types: +On implementations that define `pass:[__GNUC__]` (e.g. GCC/clang), `BOOST_LEAF_CHECK` is compatible with non-`void` results as well: [source,c++] ---- -leaf::result f(); +leaf::result count_rows(); -float g(int x); +float update_average(int n); -leaf::result t() +leaf::result average_row_count() { - return g( BOOST_LEAF_CHECK(f()) ); + return update_average( BOOST_LEAF_CHECK(count_rows()) ); } ---- @@ -172,10 +169,10 @@ The following is the portable alternative: [source,c++] ---- -leaf::result t() +leaf::result average_row_count() { - BOOST_LEAF_AUTO(x, f()); - return g(x); + BOOST_LEAF_AUTO(n, count_rows()); + return update_average(n); } ---- @@ -184,88 +181,82 @@ leaf::result t() [[tutorial-error_handling]] === Error Handling -Error handling scopes must use a special syntax to indicate that they need to access error objects. The following excerpt attempts several operations and handles errors of type `err1`: +Error handling scopes use a special syntax to indicate that they need to access error objects: [source,c++] ---- -leaf::result r = leaf::try_handle_some( +leaf::result r = leaf::try_handle_some( - []() -> leaf::result + []() -> leaf::result { - BOOST_LEAF_AUTO(v1, f1()); - BOOST_LEAF_AUTO(v2, f2()); - - return g(v1, v2); + BOOST_LEAF_AUTO(c, connect()); + return fetch(c); }, - []( err1 e ) -> leaf::result + []( api_error e ) -> leaf::result { - if( e == err1::e1 ) - .... // Handle err1::e1 + if( e == api_error::connect_failed ) + .... // Handle api_error::connect_failed else - .... // Handle any other err1 value + .... // Handle any other api_error value } ); ---- [.text-right] <> | <> | <> -The first lambda passed to `try_handle_some` is executed first; it attempts to produce a `result`, but it may fail. +First, `try_handle_some` executes the first function passed to it; it attempts to produce a `result`, but it may fail. -The second lambda is an error handler: it will be called iff the first lambda fails and an error object of type `err1` was communicated to LEAF. That object is stored on the stack, local to the `try_handle_some` function (LEAF knows to allocate this storage because we gave it an error handler that takes an `err1`). Error handlers passed to `leaf::try_handle_some` can return a valid `leaf::result` but are allowed to fail. +The second lambda is an error handler: it will be called iff the first lambda fails with an error object of type `api_error`. That object is stored on the stack, local to the `try_handle_some` function (LEAF knows to allocate this storage because we gave it an error handler that takes an `api_error`). Error handlers passed to `leaf::try_handle_some` can return a valid `leaf::result` but are allowed to fail. -It is possible for an error handler to specify that it can only deal with some values of a given error type: +It is possible for an error handler to declare that it can only handle some specific values of a given error type: [source,c++] ---- -leaf::result r = leaf::try_handle_some( +leaf::result r = leaf::try_handle_some( - []() -> leaf::result + []() -> leaf::result { - BOOST_LEAF_AUTO(v1, f1()); - BOOST_LEAF_AUTO(v2, f2()); - - return g(v1. v2); + BOOST_LEAF_AUTO(c, connect()); + return fetch(c); }, - []( leaf::match ) -> leaf::result + []( leaf::match ) -> leaf::result { - // Handle err::e1 + // Handle api_error::connect_failed or api_error::timeout }, - []( err1 e ) -> leaf::result + []( api_error e ) -> leaf::result { - // Handle any other err1 value + // Handle any other api_error value } ); ---- [.text-right] <> | <> | <> | <> -LEAF considers the provided error handlers in order, and calls the first one for which it can supply arguments, based on the error objects currently being communicated. Above: +LEAF considers the provided error handlers in order, and calls the first one for which it is able to supply arguments, based on the error objects currently being communicated. Above: -* The first error handler uses the predicate `leaf::match` to specify that it should only be considered if an error object of type `err1` is available, and its value is either `err1::e1` or `err1::e3`. +* The first error handler will be called iff an error object of type `api_error` is available, and its value is either `api_error::connect_failed` or `api_error::timeout`. -* Otherwise the second error handler will be called if an error object of type `err1` is available, regardless of its value. +* Otherwise the second error handler will be called iff an error object of type `api_error` is available, regardless of its value. -* Otherwise `leaf::try_handle_some` fails. +* Otherwise `leaf::try_handle_some` is unable to handle the error. -It is possible for an error handler to conditionally leave the current failure unhandled: +It is possible for an error handler to conditionally leave the failure unhandled: [source,c++] ---- -leaf::result r = leaf::try_handle_some( +leaf::result r = leaf::try_handle_some( - []() -> leaf::result + []() -> leaf::result { - BOOST_LEAF_AUTO(v1, f1()); - BOOST_LEAF_AUTO(v2, f2()); - - return g(v1. v2); + BOOST_LEAF_AUTO(c, connect()); + return fetch(c); }, - []( err1 e, leaf::error_info const & ei ) -> leaf::result + []( api_error e, leaf::error_info const & ei ) -> leaf::result { - if( <> ) - return valid_U; + if( e == api_error::timeout ) + return cached_data(); else return ei.error(); } ); @@ -281,27 +272,25 @@ If we want to ensure that all possible failures are handled, we use `leaf::try_h [source,c++] ---- -U r = leaf::try_handle_all( +data r = leaf::try_handle_all( - []() -> leaf::result + []() -> leaf::result { - BOOST_LEAF_AUTO(v1, f1()); - BOOST_LEAF_AUTO(v2, f2()); - - return g(v1. v2); + BOOST_LEAF_AUTO(c, connect()); + return fetch(c); }, - []( leaf::match ) -> U + []( leaf::match ) -> data { - // Handle err::e1 + // Handle api_error::connect_failed }, - []( err1 e ) -> U + []( api_error e ) -> data { - // Handle any other err1 value + // Handle any other api_error value }, - []() -> U + []() -> data { // Handle any other failure } ); @@ -309,7 +298,7 @@ U r = leaf::try_handle_all( [.text-right] <> -The `leaf::try_handle_all` function enforces at compile time that at least one of the supplied error handlers takes no arguments (and therefore is able to handle any failure). In addition, all error handlers are forced to return a valid `U`, rather than a `leaf::result`, so that `leaf::try_handle_all` is guaranteed to succeed, always. +The `leaf::try_handle_all` function enforces at compile time that at least one of the supplied error handlers takes no arguments (and therefore is able to handle any failure). In addition, all error handlers are forced to return a valid object rather than a `leaf::result`, so that `leaf::try_handle_all` is guaranteed to succeed. ''' @@ -319,38 +308,36 @@ It is of course possible to provide different handlers for different error types [source,c++] ---- -enum class err1 { e1, e2, e3 }; -enum class err2 { e1, e2 }; +enum class api_error { connect_failed, invalid_request, timeout }; +enum class auth_error { unauthorized, forbidden }; .... -leaf::result r = leaf::try_handle_some( +leaf::result r = leaf::try_handle_some( - []() -> leaf::result + []() -> leaf::result { - BOOST_LEAF_AUTO(v1, f1()); - BOOST_LEAF_AUTO(v2, f2()); - - return g(v1, v2); + BOOST_LEAF_AUTO(c, connect()); + return fetch(c); }, - []( err1 e ) -> leaf::result + []( api_error e ) -> leaf::result { - // Handle errors of type `err1`. + // Handle errors of type `api_error`. }, - []( err2 e ) -> leaf::result + []( auth_error e ) -> leaf::result { - // Handle errors of type `err2`. + // Handle errors of type `auth_error`. } ); ---- [.text-right] <> | <> | <> -Recall that error handlers are always considered in order: +Error handlers are always considered in order: -* The first error handler will be used if an error object of type `err1` is available; -* otherwise, the second error handler will be used if an error object of type `err2` is available; +* The first error handler will be used if an error object of type `api_error` is available; +* otherwise, the second error handler will be used if an error object of type `auth_error` is available; * otherwise, `leaf::try_handle_some` fails. ''' @@ -363,7 +350,7 @@ The `leaf::new_error` function can be invoked with multiple error objects, for e ---- enum class io_error { open_error, read_error, write_error }; -struct e_file_name { std::string value; } +struct e_file_name { std::string value; }; leaf::result open_file( char const * name ) { @@ -380,20 +367,20 @@ Similarly, error handlers may take multiple error objects as arguments: [source,c++] ---- -leaf::result r = leaf::try_handle_some( +leaf::result r = leaf::try_handle_some( - []() -> leaf::result + []() -> leaf::result { BOOST_LEAF_AUTO(f, open_file(fn)); .... }, - []( io_error ec, e_file_name fn ) -> leaf::result + []( io_error ec, e_file_name fn ) -> leaf::result { - // Handle I/O errors when a file name is available. + // Handle I/O errors when a file name is also available. }, - []( io_error ec ) -> leaf::result + []( io_error ec ) -> leaf::result { // Handle I/O errors when no file name is available. } ); @@ -403,26 +390,26 @@ leaf::result r = leaf::try_handle_some( Once again, error handlers are considered in order: -* The first error handler will be used if an error object of type `io_error` _and_ and error_object of type `e_file_name` are available; -* otherwise, the second error handler will be used if an error object of type `io_error` is avaliable; -* otherwise, `leaf_try_handle_some` fails. +* The first error handler will be used if an error object of type `io_error` _and_ an error object of type `e_file_name` are available; +* otherwise, the second error handler will be used if an error object of type `io_error` is available; +* otherwise, `leaf::try_handle_some` fails. An alternative way to write the above is to provide a single error handler that takes the `e_file_name` argument as a pointer: [source,c++] ---- -leaf::result r = leaf::try_handle_some( +leaf::result r = leaf::try_handle_some( - []() -> leaf::result + []() -> leaf::result { BOOST_LEAF_AUTO(f, open_file(fn)); .... }, - []( io_error ec, e_file_name const * fn ) -> leaf::result + []( io_error ec, e_file_name const * fn ) -> leaf::result { if( fn ) - .... // Handle I/O errors when a file name is available. + .... // Handle I/O errors when a file name is also available. else .... // Handle I/O errors when no file name is available. } ); @@ -430,14 +417,14 @@ leaf::result r = leaf::try_handle_some( [.text-right] <> | <> | <> -An error handler is never dropped for lack of error objects of types which the handler takes as pointers; in this case LEAF simply passes `0` for these arguments. +An error handler is never dropped for lack of error objects of types which the handler takes as pointers; in this case LEAF simply passes `nullptr` for these arguments. -TIP: Error handlers can take arguments by value, by const reference or pointer, and by mutable reference or pointer. It the latter case, changes to the error object state will be propagated up the call stack if the failure is not handled. +TIP: When an error handler takes arguments by mutable reference or pointer, changes to their state are preserved when the error is communicated to the caller. [[tutorial-augmenting_errors]] === Augmenting Errors -Let's say we have a function `parse_line` which could fail due to an `io_error` or a `parse_error`: +Let's say we have a function `parse_line` which could fail due to an `io_error` or a `parse_error`: [source,c++] ---- @@ -469,7 +456,7 @@ leaf::result process_file( FILE * f ) [.text-right] <> | <> -Because `process_file` does not handle errors, it remains neutral to failures, except to attach the `current_line` if something goes wrong. The object returned by `on_error` holds a copy of the `current_line` wrapped in `struct e_line`. If `parse_line` succeeds, the `e_line` object is simply discarded; but if it fails, the `e_line` object will be automatically "attached" to the failure. +Because `process_file` does not handle errors, it remains neutral to failures, except to attach the `current_line` if something goes wrong. The object returned by `on_error` holds a copy of `current_line` wrapped in `struct e_line`. If `parse_line` succeeds, the `e_line` object is simply discarded; if it fails, the `e_line` object will be automatically "attached" to the failure. Such failures can then be handled like so: @@ -518,7 +505,7 @@ leaf::result r = leaf::try_handle_some( []( io_error e, e_line const * current_line ) { - std::cerr << "Parse error"; + std::cerr << "I/O error"; if( current_line ) std::cerr << " at line " << current_line->value; std::cerr << std::endl; @@ -530,7 +517,7 @@ leaf::result r = leaf::try_handle_some( [[tutorial-exception_handling]] === Exception Handling -What happens if an operation throws an exception? Not to worry, both `try_handle_some` and `try_handle_all` catch exceptions and are able to pass them to any compatible error handler: +What happens if an operation throws an exception? Both `try_handle_some` and `try_handle_all` catch exceptions and are able to pass them to any compatible error handler: [source,c++] ---- @@ -553,7 +540,7 @@ leaf::result r = leaf::try_handle_some( []( io_error e, e_line const * l ) { - std::cerr << "Parse error"; + std::cerr << "I/O error"; if( l ) std::cerr << " at line " << l.value; std::cerr << std::endl; @@ -587,7 +574,7 @@ leaf::try_catch( []( io_error e, e_line const * l ) { - std::cerr << "Parse error"; + std::cerr << "I/O error"; if( l ) std::cerr << " at line " << l.value; std::cerr << std::endl; @@ -596,14 +583,14 @@ leaf::try_catch( [.text-right] <> -Remarkably, we did not have to change the error handlers! But how does this work? What kind of exceptions does `process_file` throw? +We did not have to change the error handlers! But how does this work? What kind of exceptions would `process_file` throw? -LEAF enables a novel technique of exception handling, which does not use an exception type hierarchy to classify failures and does not carry data in exception objects. Recall that when failures are communicated via `leaf::result`, we call `leaf::new_error` in a `return` statement, passing any number of error objects which are sent directly to the correct error handling scope: +LEAF enables a novel exception handling technique, which does not require an exception type hierarchy to classify failures and does not carry data in exception objects. Recall that when failures are communicated via `leaf::result`, we call `leaf::new_error` in a `return` statement, passing any number of error objects which are sent directly to the correct error handling scope: [source,c++] ---- -enum class err1 { e1, e2, e3 }; -enum class err2 { e1, e2 }; +enum class api_error { connect_failed, invalid_request, timeout }; +enum class auth_error { unauthorized, forbidden }; .... @@ -611,7 +598,7 @@ leaf::result f() { .... if( error_detected ) - return leaf::new_error(err1::e1, err2::e2); + return leaf::new_error(api_error::connect_failed, auth_error::forbidden); // Produce and return a T. } @@ -623,30 +610,30 @@ When using exception handling this becomes: [source,c++] ---- -enum class err1 { e1, e2, e3 }; -enum class err2 { e1, e2 }; +enum class api_error { connect_failed, invalid_request, timeout }; +enum class auth_error { unauthorized, forbidden }; T f() { if( error_detected ) - throw leaf::exception(err1::e1, err2::e2); + leaf::throw_exception(api_error::connect_failed, auth_error::forbidden); // Produce and return a T. } ---- [.text-right] -<> +<> -The `leaf::exception` function handles the passed error objects just like `leaf::new_error` does, and then returns an object of a type that derives from `std::exception` (which the caller throws). Using this technique, the exception type is not important: `leaf::try_catch` catches all exceptions, then goes through the usual LEAF error handler selection procedure. +The `leaf::throw_exception` function handles the passed error objects just like `leaf::new_error` does, and then throws an object of a type that derives from `std::exception`. Using this technique, the exception type is not important: `leaf::try_catch` catches all exceptions, then goes through the usual LEAF error handler selection routine. -If instead we want to use the legacy convention of throwing different types to indicate different failures, we simply pass an exception object (that is, an object of a type that derives from `std::exception`) as the first argument to `leaf::exception`: +If instead we want to use the standard convention of throwing different types to indicate different failures, we simply pass an exception object (that is, an object of a type that derives from `std::exception`) as the first argument to `leaf::throw_exception`: [source,c++] ---- -throw leaf::exception(std::runtime_error("Error!"), err1::e1, err2::e2); +leaf::throw_exception(std::runtime_error("Error!"), api_error::connect_failed, auth_error::forbidden); ---- -In this case the returned object will be of type that derives from `std::runtime_error`, rather than from `std::exception`. +In this case the thrown exception object will be of a type that derives from `std::runtime_error`, rather than from `std::exception`. Finally, `leaf::on_error` "just works" as well. Here is our `process_file` function rewritten to work with exceptions, rather than return a `leaf::result` (see <>): @@ -701,7 +688,7 @@ leaf::result f() [.text-right] <> | <> -Later we simply call `leaf::try_handle_some` passing an error handler for each type: +Later we simply call `leaf::try_handle_some`, passing an error handler for each type: [source,c++] ---- @@ -721,7 +708,6 @@ leaf::result r = leaf::try_handle_some( { // Handle lib2::error_code } ); -} ---- [.text-right] <> | <> @@ -756,7 +742,7 @@ lib2::result bar(); int g( int a, int b ); -lib3::result f() +lib3::result f() // Note: return type is not leaf::result { auto a = foo(); if( !a ) @@ -792,54 +778,22 @@ lib3::result r = leaf::try_handle_some( { // Handle lib2::error_code } ); -} ---- [.text-right] <> ''' -[[tutorial-model]] -=== Error Communication Model - -==== `noexcept` API - -The following figure illustrates how error objects are transported when using LEAF without exception handling: - -.LEAF noexcept Error Communication Model -image::LEAF-1.png[] - -The arrows pointing down indicate the call stack order for the functions `f1` through `f5`: higher level functions calling lower level functions. - -Note the call to `on_error` in `f3`: it caches the passed error objects of types `E1` and `E3` in the returned object `load`, where they stay ready to be communicated in case any function downstream from `f3` reports an error. Presumably these objects are relevant to any such failure, but are conveniently accessible only in this scope. - -_Figure 1_ depicts the condition where `f5` has detected an error. It calls `leaf::new_error` to create a new, unique `error_id`. The passed error object of type `E2` is immediately loaded in the first active `context` object that provides static storage for it, found in any calling scope (in this case `f1`), and is associated with the newly-generated `error_id` (solid arrow); - -The `error_id` itself is returned to the immediate caller `f4`, usually stored in a `result` object `r`. That object takes the path shown by dashed arrows, as each error neutral function, unable to handle the failure, forwards it to its immediate caller in the returned value -- until an error handling scope is reached. - -When the destructor of the `load` object in `f3` executes, it detects that `new_error` was invoked after its initialization, loads the cached objects of types `E1` and `E3` in the first active `context` object that provides static storage for them, found in any calling scope (in this case `f1`), and associates them with the last generated `error_id` (solid arrow). - -When the error handling scope `f1` is reached, it probes `ctx` for any error objects associated with the `error_id` it received from `f2`, and processes a list of user-provided error handlers, in order, until it finds a handler with arguments that can be supplied using the available (in `ctx`) error objects. That handler is called to deal with the failure. - -==== Exception Handling API - -The following figure illustrates the slightly different error communication model used when errors are reported by throwing exceptions: - -.LEAF Error Communication Model Using Exception Handling -image::LEAF-2.png[] - -The main difference is that the call to `new_error` is implicit in the call to the function template `leaf::exception`, which in this case takes an exception object of type `Ex`, and returns an exception object of unspecified type that derives publicly from `Ex`. - [[tutorial-interoperability]] -==== Interoperability +=== Interoperability Ideally, when an error is detected, a program using LEAF would always call <>, ensuring that each encountered failure is definitely assigned a unique <>, which then is reliably delivered, by an exception or by a `result` object, to the appropriate error handling scope. Alas, this is not always possible. -For example, the error may need to be communicated through uncooperative 3rd-party interfaces. To facilitate this transmission, a error ID may be encoded in a `std::error_code`. As long as a 3rd-party interface is able to transport a `std::error_code`, it should be compatible with LEAF. +For example, the error may need to be communicated through uncooperative 3rd-party interfaces. To facilitate this transmission, an error ID may be encoded in a `std::error_code`. As long as a 3rd-party interface is able to transport a `std::error_code`, it can be compatible with LEAF. -Further, it is sometimes necessary to communicate errors through an interface that does not even use `std::error_code`. An example of this is when an external lower-level library throws an exception, which is unlikely to be able to carry an `error_id`. +Further, it is sometimes necessary to communicate errors through an interface that does not even use `std::error_code`. An example of this is when an external low level library throws an exception, which is unlikely to be able to carry an `error_id`. To support this tricky use case, LEAF provides the function <>, which returns the error ID returned by the most recent call (from this thread) to <>. One possible approach to solving the problem is to use the following logic (implemented by the <> type): @@ -852,14 +806,12 @@ Note that if the above logic is nested (e.g. one function calling another), `new For a detailed tutorial see <>. -TIP: To avoid ambiguities, whenever possible, use the <> function template when throwing exceptions to ensure that the exception object transports a unique `error_id`; better yet, use the <> macro, which in addition will capture `pass:[__FILE__]` and `pass:[__LINE__]`. - ''' [[tutorial-loading]] === Loading of Error Objects -To load an error object is to move it into an active <>, usually local to a <>, a <> or a <> scope in the calling thread, where it becomes uniquely associated with a specific <> -- or discarded if storage is not available. +Recall that error objects communicated to LEAF are stored on the stack, local to the `try_handle_some`, `try_handle_all` or `try_catch` function used to handle errors. To _load_ an error object means to move it into such storage, if available. Various LEAF functions take a list of error objects to load. As an example, if a function `copy_file` that takes the name of the input file and the name of the output file as its arguments detects a failure, it could communicate an error code `ec`, plus the two relevant file names using <>: @@ -897,7 +849,7 @@ Besides error objects, `load` can take function arguments: * If we pass a function that takes no arguments, it is invoked, and the returned error object is loaded. + -Consider that if we pass to `load` an error object that is not needed by any error handler, it will be discarded. If the object is expensive to compute, it would be better if the computation can be skipped as well. Passing a function with no arguments to `load` is an excellent way to achieve this behavior: +Consider that if we pass to `load` an error object that is not used by an error handler, it will be discarded. If instead of an error object we pass a function that returns an error object, that function will only be called if the object it returns is needed, that is, if it will not be discarded. This is helpful when the error object is relatively expensive to produce: + [source,c++] ---- @@ -926,9 +878,9 @@ leaf::result operation( char const * file_name ) noexcept <> | <> + <1> Success! Use `r.value()`. -<2> `try_something` has failed; `compute_info` will only be called if an error handler exists which takes a `info` argument. +<2> `try_something` has failed; `compute_info` will only be called if an error handler exists in the call stack which takes a `info` argument. + -* If we pass a function that takes a single argument of type `E &`, LEAF calls the function with the object of type `E` currently loaded in an active `context`, associated with the error. If no such object is available, a new one is default-initialized and then passed to the function. +* If we pass a function that takes a single argument of some reference type `E &`, LEAF calls the function with the object of type `E` currently loaded in an active `context`, associated with the error. If no such object is available, a new one is default-initialized and then passed to the function. + For example, if an operation that involves many different files fails, a program may provide for collecting all relevant file names in a `e_relevant_file_names` object: + @@ -969,7 +921,7 @@ leaf::result operation( char const * file_name ) noexcept It is not typical for an error reporting function to be able to supply all of the data needed by a suitable error handling function in order to recover from the failure. For example, a function that reports `FILE` failures may not have access to the file name, yet an error handling function needs it in order to print a useful error message. -Of course the file name is typically readily available in the call stack leading to the failed `FILE` operation. Below, while `parse_info` can't report the file name, `parse_file` can and does: +The file name is typically readily available in the call stack leading to the failed `FILE` operation. Below, while `parse_info` can't report the file name, `parse_file` can and does: [source,c++] ---- @@ -993,65 +945,65 @@ leaf::result parse_file( char const * file_name ) noexcept [.text-right] <> | <> | <> -<1> `parse_info` parses `f`, communicating errors using `result`. -<2> Using `on_error` ensures that the file name is included with any error reported out of `parse_file`. All we need to do is hold on to the returned object `load`; when it expires, if an error is being reported, the passed `e_file_name` value will be automatically associated with it. +<1> `parse_info` communicates errors using `leaf::result`. +<2> `on_error` ensures that the file name is included with any error reported out of `parse_file`. When the `load` object expires, if an error is being reported, the passed `e_file_name` value will be automatically associated with it. -TIP: `on_error` -- like `load` -- can be passed any number of arguments. +TIP: `on_error` -- like `new_error` -- can be passed any number of arguments. When we invoke `on_error`, we can pass three kinds of arguments: . Actual error objects (like in the example above); . Functions that take no arguments and return an error object; -. Functions that take an error object by mutable reference. +. Functions that take a single error object by mutable reference. -If we want to use `on_error` to capture `errno`, we can't just pass <> to it, because at that time it hasn't been set (yet). Instead, we'd pass a function that returns it: +For example, if we want to use `on_error` to capture `errno`, we could use the <> type, which is a simple struct that wraps an `int`. But, we can't just pass an <> to `on_error`, because at that time `errno` hasn't been set (yet). Instead, we'd pass a function that returns it: [source,c++] ---- void read_file(FILE * f) { - auto load = leaf::on_error([]{ return e_errno{errno}; }); + auto load = leaf::on_error([]{ return leaf::e_errno{errno}; }); .... size_t nr1=fread(buf1,1,count1,f); if( ferror(f) ) - throw leaf::exception(); + leaf::throw_exception(); size_t nr2=fread(buf2,1,count2,f); if( ferror(f) ) - throw leaf::exception(); + leaf::throw_exception(); size_t nr3=fread(buf3,1,count3,f); if( ferror(f) ) - throw leaf::exception(); + leaf::throw_exception(); .... } ---- -Above, if a `throw` statement is reached, LEAF will invoke the function passed to `on_error` and associate the returned `e_errno` object with the exception. +Above, if an exception is thrown, LEAF will invoke the function passed to `on_error` and associate the returned `e_errno` object with the exception. -The final argument type that can be passed to `on_error` is a function that takes a single mutable error object reference. In this case, `on_error` uses it similarly to how such functions are used by `load`; see <>. +Finally, if `on_error` is passed a function that takes a single error object by mutable reference, the behavior is similar to how such functions are handled by `load`; see <>. ''' [[tutorial-predicates]] === Using Predicates to Handle Errors -Usually, LEAF error handlers are selected based on the type of the arguments they take and the type of the available error objects. When an error handler takes a predicate type as an argument, the <> is able to also take into account the _value_ of the available error objects. +Usually, the compatibility between error handlers and the available error objects is determined based on the type of the arguments they take. When an error handler takes a predicate type as an argument, the <> is able to also take into account the _value_ of the available error objects. Consider this error code enum: [source,c++] ---- -enum class my_error +enum class validation_error { - e1=1, - e2, - e3 + empty_field = 1, + invalid_format, + out_of_range }; ---- -We could handle `my_error` errors like so: +We could handle `validation_error` errors like so: [source,c++] ---- @@ -1059,31 +1011,28 @@ return leaf::try_handle_some( [] { - return f(); // returns leaf::result + return validate_input(); // Returns leaf::result }, - []( my_error e ) - { <1> + []( validation_error e ) + { switch(e) { - case my_error::e1: - ....; <2> + case validation_error::empty_field: + ....; // Handle empty_field errors break; - case my_error::e2: - case my_error::e3: - ....; <3> + case validation_error::invalid_format: + case validation_error::out_of_range: + ....; // Handle invalid_format and out_of_range errors break; default: - ....; <4> + ....; // Handle unexpected validation_error values break; + } } ); ---- -<1> This handler will be selected if we've got a `my_error` object. -<2> Handle `e1` errors. -<3> Handle `e2` and `e3` errors. -<4> Handle bad `my_error` values. -If `my_error` object is available, LEAF will call our error handler. If not, the failure will be forwarded to our caller. +If a `validation_error` object is available, LEAF will call our error handler. If not, the failure will be forwarded to the caller. This can be rewritten using the <> predicate to organize the different cases in different error handlers. The following is equivalent: @@ -1093,29 +1042,26 @@ return leaf::try_handle_some( [] { - return f(); // returns leaf::result + return validate_input(); // Returns leaf::result }, - []( leaf::match m ) - { <1> - assert(m.matched == my_error::e1); + []( leaf::match m ) + { + assert(m.matched == validation_error::empty_field); ....; }, - []( leaf::match m ) - { <2> - assert(m.matched == my_error::e2 || m.matched == my_error::e3); + []( leaf::match m ) + { + assert(m.matched == validation_error::invalid_format || m.matched == validation_error::out_of_range); ....; }, - []( my_error e ) - { <3> + []( validation_error e ) + { ....; } ); ---- -<1> We've got a `my_error` object that compares equal to `e1`. -<2> We`ve got a `my_error` object that compares equal to either `e2` or `e3`. -<3> Handle bad `my_error` values. The first argument to the `match` template generally specifies the type `E` of the error object `e` that must be available for the error handler to be considered at all. Typically, the rest of the arguments are values. The error handler is dropped if `e` does not compare equal to any of them. @@ -1128,7 +1074,7 @@ In particular, `match` works great with `std::error_code`. The following handler } ---- -This, however, requires {CPP}17 or newer, because it is impossible to infer the type of the error enum (in this case, `std::errc`) from the specified type `std::error_code`, and {CPP}11 does not allow `auto` template arguments. LEAF provides the following workaround, compatible with {CPP}11: +This, however, requires {CPP}17 or newer. LEAF provides the following workaround, compatible with {CPP}11: [source,c++] ---- @@ -1137,11 +1083,11 @@ This, however, requires {CPP}17 or newer, because it is impossible to infer the } ---- -In addition, it is possible to select a handler based on `std::error_category`. The following handler will match any `std::error_code` of the `std::generic_category` (requires {CPP}17 or newer): +It is also possible to select a handler based on `std::error_category`. The following handler will match any `std::error_code` of the `std::generic_category` (requires {CPP}17 or newer): [source,c++] ---- -[]( std::error_code, leaf::category> ) +[]( std::error_code, leaf::category ) { } ---- @@ -1152,140 +1098,140 @@ The following predicates are available: * <>: as described above. * <>: where `match` compares the object `e` of type `E` with the values `V...`, `match_value` compare `e.value` with the values `V...`. -* <>: similar to `match_value`, but takes a pointer to the data member to compare; that is, `match_member<&E::value, V...>` is equvialent to `match_value`. Note, however, that `match_member` requires {CPP}17 or newer, while `match_value` does not. -* `<>`: Similar to `match`, but checks whether the caught `std::exception` object can be `dynamic_cast` to any of the `Ex` types. +* <>: similar to `match_value`, but takes a pointer to the data member to compare; that is, `match_member<&E::value, V...>` is equivalent to `match_value`. Note, however, that `match_member` requires {CPP}17 or newer, while `match_value` does not. +* `<>`: Similar to `match`, but checks whether the caught `std::exception` object can be `dynamic_cast` to any of the `Ex...` types. * <> is a special predicate that takes any other predicate `Pred` and requires that an error object of type `E` is available and that `Pred` evaluates to `false`. For example, `if_not>` requires that an object `e` of type `E` is available, and that it does not compare equal to any of the specified `V...`. -Finally, the predicate system is easily extensible, see <>. +The predicate system is easily extensible, see <>. NOTE: See also <>. ''' [[tutorial-binding_handlers]] -=== Binding Error Handlers in a `std::tuple` +=== Reusing Common Error Handlers Consider this snippet: [source,c++] ---- -leaf::try_handle_all( +config cfg = leaf::try_handle_all( [&] { - return f(); // returns leaf::result + return load_config_file(config_path); // returns leaf::result }, - [](my_error_enum x) + [](api_error e) -> config { - ... + .... }, - [](read_file_error_enum y, e_file_name const & fn) + [](io_error e, e_file_name const & fn) -> config { - ... + .... }, - [] + []() -> config { - ... + .... }); ---- [.text-right] <> | <> -Looks pretty simple, but what if we need to attempt a different set of operations yet use the same handlers? We could repeat the same thing with a different function passed as `TryBlock` for `try_handle_all`: +If we need to attempt a different set of operations yet use the same handlers, we could repeat the same thing with a different function passed as the `TryBlock` for `try_handle_all`: [source,c++] ---- -leaf::try_handle_all( +config cfg = leaf::try_handle_all( [&] { - return g(); // returns leaf::result + return load_config_file(fallback_path); // returns leaf::result }, - [](my_error_enum x) + [](api_error e) -> config { - ... + .... }, - [](read_file_error_enum y, e_file_name const & fn) + [](io_error e, e_file_name const & fn) -> config { - ... + .... }, - [] + []() -> config { - ... + .... }); ---- -That works, but it is better to bind our error handlers in a `std::tuple`: +That works, but it is also possible to bind the error handlers in a `std::tuple`: [source,c++] ---- -auto error_handlers = std::make_tuple( +auto load_config_error_handlers = std::make_tuple( - [](my_error_enum x) + [](api_error e) -> config { - ... + .... }, - [](read_file_error_enum y, e_file_name const & fn) + [](io_error e, e_file_name const & fn) -> config { - ... + .... }, - [] + []() -> config { - ... + .... }); ---- -The `error_handlers` tuple can later be used with any error handling function: +The `load_config_error_handlers` tuple can later be used with any error handling function: [source,c++] ---- -leaf::try_handle_all( +config cfg1 = leaf::try_handle_all( [&] { - // Operations which may fail <1> + return load_config_file(config_path); // <1> }, - error_handlers ); + load_config_error_handlers ); -leaf::try_handle_all( +config cfg2 = leaf::try_handle_all( [&] { - // Different operations which may fail <2> + return load_config_file(fallback_path); // <2> }, - error_handlers ); <3> + load_config_error_handlers ); // <3> ---- [.text-right] <> | <> <1> One set of operations which may fail... <2> A different set of operations which may fail... -<3> ... both using the same `error_handlers`. +<3> ... both using the same `load_config_error_handlers`. Error handling functions accept a `std::tuple` of error handlers in place of any error handler. The behavior is as if the tuple is unwrapped in-place. ''' [[tutorial-async]] -=== Transporting Error Objects Between Threads +=== Transporting Errors Between Threads -Error objects are stored on the stack in an instance of the <> class template in the scope of e.g. <>, <> or <> functions. When using concurrency, we need a mechanism to collect error objects in one thread, then use them to handle errors in another thread. +Like exceptions, LEAF error objects are local to a thread. When using concurrency, sometimes we need to collect error objects in one thread, then use them to handle errors in another thread. -LEAF offers two interfaces for this purpose, one using `result`, and another designed for programs that use exception handling. +LEAF supports this functionality with or without exception handling. In both cases error objects are captured and transported in a `leaf::<>` object. [[tutorial-async_result]] -==== Using `result` +==== Transporting Errors Between Threads Without Exception Handling Let's assume we have a `task` that we want to launch asynchronously, which produces a `task_result` but could also fail: @@ -1294,37 +1240,7 @@ Let's assume we have a `task` that we want to launch asynchronously, which produ leaf::result task(); ---- -Because the task will run asynchronously, in case of a failure we need it to capture the relevant error objects but not handle errors. To this end, in the main thread we bind our error handlers in a `std::tuple`, which we will later use to handle errors from each completed asynchronous task (see <>): - -[source,c++] ----- -auto error_handlers = std::make_tuple( - - [](E1 e1, E2 e2) - { - //Deal with E1, E2 - .... - return { }; - }, - - [](E3 e3) - { - //Deal with E3 - .... - return { }; - } ); ----- - -Why did we start with this step? Because we need to create a <> object to collect the error objects we need. We could just instantiate the `context` template with `E1`, `E2` and `E3`, but that would be prone to errors, since it could get out of sync with the handlers we use. Thankfully LEAF can deduce the types we need automatically, we just need to show it our `error_handlers`: - -[source,c++] ----- -std::shared_ptr ctx = leaf::make_shared_context(error_handlers); ----- - -The `polymorphic_context` type is an abstract base class that has the same members as any instance of the `context` class template, allowing us to erase its exact type. In this case what we're holding in `ctx` is a `context`, where `E1`, `E2` and `E3` were deduced automatically from the `error_handlers` tuple we passed to `make_shared_context`. - -We're now ready to launch our asynchronous task: +Because the task will run asynchronously, in case of a failure we need to capture any produced error objects but not handle errors. We do this by invoking `try_capture_all`: [source,c++] ---- @@ -1334,16 +1250,15 @@ std::future> launch_task() noexcept std::launch::async, [&] { - std::shared_ptr ctx = leaf::make_shared_context(error_handlers); - return leaf::capture(ctx, &task); + return leaf::try_capture_all(task); } ); } ---- [.text-right] -<> | <> | <> +<> | <> -That's it! Later when we `get` the `std::future`, we can process the returned `result` in a call to <>, using the `error_handlers` tuple we created earlier: +In case of a failure, the returned from `try_capture_all` `result` object holds all error objects communicated out of the `task`, at the cost of dynamic allocations. The `result` object can then be stashed away or moved to another thread, and later passed to an error-handling function to unload its content and handle errors: [source,c++] ---- @@ -1356,35 +1271,9 @@ return leaf::try_handle_some( { BOOST_LEAF_AUTO(r, fut.get()); //Success! - return { } + return { }; }, - error_handlers ); ----- - -[.text-right] -<> | <> | <> - -The reason this works is that in case the `leaf::result` communicates a failure, it is able to hold a `shared_ptr` object. That is why earlier instead of calling `task()` directly, we called `leaf::capture`: it calls the passed function and, in case that fails, it stores the `shared_ptr` we created in the returned `result`, which now doesn't just communicate the fact that an error has occurred, but also holds the `context` object that `try_handle_some` needs in order to supply a suitable handler with arguments. - -NOTE: Follow this link to see a complete example program: https://github.com/boostorg/leaf/blob/master/example/capture_in_result.cpp?ts=4[capture_in_result.cpp]. - -[[tutorial-async_eh]] -==== Using Exception Handling - -Let's assume we have an asynchronous `task` which produces a `task_result` but could also throw: - -[source,c++] ----- -task_result task(); ----- - -Just like we saw in <>, first we will bind our error handlers in a `std::tuple`: - -[source,c++] ----- -auto handle_errors = std::make_tuple( - [](E1 e1, E2 e2) { //Deal with E1, E2 @@ -1400,49 +1289,72 @@ auto handle_errors = std::make_tuple( } ); ---- -Launching the task looks the same as before, except that we don't use `result`: +[.text-right] +<> | <> | <> + +NOTE: Follow this link to see a complete example program: https://github.com/boostorg/leaf/blob/master/example/try_capture_all_result.cpp?ts=4[try_capture_all_result.cpp]. + +[[tutorial-async_eh]] +==== Transporting Errors Between Threads With Exception Handling + +Let's assume we have an asynchronous `task` which produces a `task_result` but could also throw: + +[source,c++] +---- +task_result task(); +---- + +We use `try_capture_all` to capture all error objects and the `std::current_exception()` in a `result`: [source,c++] ---- -std::future launch_task() +std::future> launch_task() { return std::async( std::launch::async, [&] { - std::shared_ptr ctx = leaf::make_shared_context(&handle_error); - return leaf::capture(ctx, &task); + return leaf::try_capture_all(task); } ); } ---- [.text-right] -<> | <> +<> -That's it! Later when we `get` the `std::future`, we can process the returned `task_result` in a call to <>, using the `error_handlers` we saved earlier, as if it was generated locally: +To handle errors after waiting on the future, we use `try_catch` as usual: [source,c++] ---- -//std::future fut; +//std::future> fut; fut.wait(); return leaf::try_catch( [&] { - task_result r = fut.get(); // Throws on error + leaf::result r = fut.get(); + task_result v = r.value(); // throws on error //Success! }, - error_handlers ); + [](E1 e1, E2 e2) + { + //Deal with E1, E2 + .... + }, + + [](E3 e3) + { + //Deal with E3 + .... + } ); ---- [.text-right] -<> +<> | <> -This works similarly to using `result`, except that the `std::shared_ptr` is transported in an exception object (of unspecified type which <> recognizes and then automatically unwraps the original exception). - -NOTE: Follow this link to see a complete example program: https://github.com/boostorg/leaf/blob/master/example/capture_in_exception.cpp?ts=4[capture_in_exception.cpp]. +NOTE: Follow this link to see a complete example program: https://github.com/boostorg/leaf/blob/master/example/try_capture_all_exceptions.cpp?ts=4[try_capture_all_exceptions.cpp]. ''' @@ -1481,7 +1393,7 @@ It will get called if the value of the `error_code` enum communicated with the f But what if later we add support for detecting and reporting a new type of input error, e.g. `permissions_error`? It is easy to add that to our `error_code` enum; but now our input error handler won't recognize this new input error -- and we have a bug. -If we can use exceptions, the situation is better because exception types can be organized in a hierarchy in order to classify failures: +Using exceptions is an improvement because exception types can be organized in a hierarchy in order to classify failures: [source,c++] ---- @@ -1564,7 +1476,7 @@ leaf::result file_read( FILE & f, void * buf, int size ) <2> In addition, this error is classified as `read_error`. <3> In addition, this error is classified as `eof_error`. -This technique works just as well if we choose to use exception handling, we just call `leaf::exception` instead of `leaf::new_error`: +This technique works just as well if we choose to use exception handling, we just call `leaf::throw_exception` instead of `leaf::new_error`: [source,c++] ---- @@ -1575,16 +1487,16 @@ void file_read( FILE & f, void * buf, int size ) int n = fread(buf, 1, size, &f); if( ferror(&f) ) - throw leaf::exception(read_error{}, leaf::e_errno{errno}); + leaf::throw_exception(read_error{}, leaf::e_errno{errno}); if( n!=size ) - throw leaf::exception(eof_error{}); + leaf::throw_exception(eof_error{}); } ---- [.text-right] -<> | <> | <> +<> | <> | <> -NOTE: If the type of the first argument passed to `leaf::exception` derives from `std::exception`, it will be used to initialize the returned exception object taken by `throw`. Here this is not the case, so the function returns a default-initialized `std::exception` object, while the first (and any other) argument is associated with the failure. +NOTE: If the type of the first argument passed to `leaf::throw_exception` derives from `std::exception`, it will be used to initialize the thrown exception object. Here this is not the case, so the function throws a default-initialized `std::exception` object, while the first (and any other) argument is associated with the failure. Now we can write a future-proof handler for any `input_error`: @@ -1605,68 +1517,31 @@ Remarkably, because the classification of the failure does not depend on error c [[tutorial-exception_to_result]] === Converting Exceptions to `result` -It is sometimes necessary to catch exceptions thrown by a lower-level library function, and report the error through different means, to a higher-level library which may not use exception handling. - -TIP: Error handlers that take arguments of types that derive from `std::exception` work correctly -- regardless of whether the error object itself is thrown as an exception, or <> into a <>. The technique described here is only needed when the exception must be communicated through functions which are not exception-safe, or are compiled with exception handling disabled. - -Suppose we have an exception type hierarchy and a function `compute_answer_throws`: +When integrating a library that throws exceptions into code that uses `result`, use `exception_to_result` to convert exceptions at the boundary: [source,c++] ---- -class error_base: public std::exception { }; -class error_a: public error_base { }; -class error_b: public error_base { }; -class error_c: public error_base { }; - -int compute_answer_throws() -{ - switch( rand()%4 ) - { - default: return 42; - case 1: throw error_a(); - case 2: throw error_b(); - case 3: throw error_c(); - } -} ----- +struct parse_error: std::exception { }; +struct syntax_error: parse_error { }; +struct encoding_error: parse_error { }; -We can write a simple wrapper using `exception_to_result`, which calls `compute_answer_throws` and switches to `result` for error handling: +json_value parse_json(char const * str); // Throws parse_error -[source,c++] ----- -leaf::result compute_answer() noexcept +leaf::result safe_parse_json(char const * str) noexcept { - return leaf::exception_to_result( - [] + return leaf::exception_to_result( + [&] { - return compute_answer_throws(); + return parse_json(str); } ); } ---- - [.text-right] <> | <> -The `exception_to_result` template takes any number of exception types. All exception types thrown by the passed function are caught, and an attempt is made to convert the exception object to each of the specified types. Each successfully-converted slice of the caught exception object, as well as the return value of `std::current_exception`, are copied and <>, and in the end the exception is converted to a `<>` object. - -(In our example, `error_a` and `error_b` slices as communicated as error objects, but `error_c` exceptions will still be captured by `std::exception_ptr`). - -Here is a simple function which prints successfully computed answers, forwarding any error (originally reported by throwing an exception) to its caller: - -[source,c++] ----- -leaf::result print_answer() noexcept -{ - BOOST_LEAF_AUTO(answer, compute_answer()); - std::cout << "Answer: " << answer << std::endl; - return { }; -} ----- - -[.text-right] -<> | <> +The template arguments specify which exception types to capture as error objects. All exceptions are caught, and for each type listed, LEAF attempts a `dynamic_cast` and loads a copy of that slice. The `std::current_exception()` is also captured, so unlisted exception types can still be handled. -Finally, here is a scope that handles the errors -- it will work correctly regardless of whether `error_a` and `error_b` objects are thrown as exceptions or not. +Errors can then be handled normally: [source,c++] ---- @@ -1674,191 +1549,77 @@ leaf::try_handle_all( []() -> leaf::result { - BOOST_LEAF_CHECK(print_answer()); + BOOST_LEAF_AUTO(doc, safe_parse_json(input)); + process(doc); return { }; }, - [](error_a const & e) + [](syntax_error const &) { - std::cerr << "Error A!" << std::endl; + std::cerr << "JSON syntax error" << std::endl; }, - [](error_b const & e) + [](encoding_error const &) { - std::cerr << "Error B!" << std::endl; + std::cerr << "Invalid encoding" << std::endl; }, [] { - std::cerr << "Unknown error!" << std::endl; + std::cerr << "Unknown error" << std::endl; } ); ---- - [.text-right] -<> | <> | <> +<> | <> | <> -NOTE: The complete program illustrating this technique is available https://github.com/boostorg/leaf/blob/master/example/exception_to_result.cpp?ts=4[here]. +TIP: Handlers that take exception types work the same way whether the object was thrown or loaded via `exception_to_result`. ''' [[tutorial-on_error_in_c_callbacks]] -=== Using `error_monitor` to Report Arbitrary Errors from C-callbacks - -Communicating information pertaining to a failure detected in a C callback is tricky, because C callbacks are limited to a specific static signature, which may not use {CPP} types. +=== Using `error_monitor` to Report Errors from C Callbacks -LEAF makes this easy. As an example, we'll write a program that uses Lua and reports a failure from a {CPP} function registered as a C callback, called from a Lua program. The failure will be propagated from {CPP}, through the Lua interpreter (written in C), back to the {CPP} function which called it. +C callbacks have fixed signatures that cannot return {CPP} types like `leaf::result`. The <> class solves this problem. -C/{CPP} functions designed to be invoked from a Lua program must use the following signature: - -[source,c] ----- -int do_work( lua_State * L ) ; ----- - -Arguments are passed on the Lua stack (which is accessible through `L`). Results too are pushed onto the Lua stack. - -First, let's initialize the Lua interpreter and register a function, `do_work`, as a C callback available for Lua programs to call: - -[source,c++] ----- -std::shared_ptr init_lua_state() noexcept -{ - std::shared_ptr L(lua_open(), &lua_close); //<1> - - lua_register(&*L, "do_work", &do_work); //<2> - - luaL_dostring(&*L, "\ //<3> -\n function call_do_work()\ -\n return do_work()\ -\n end"); - - return L; -} ----- -<1> Create a new `lua_State`. We'll use `std::shared_ptr` for automatic cleanup. -<2> Register the `do_work` {CPP} function as a C callback, under the global name `do_work`. With this, calls from Lua programs to `do_work` will land in the `do_work` {CPP} function. -<3> Pass some Lua code as a `C` string literal to Lua. This creates a global Lua function called `call_do_work`, which we will later ask Lua to execute. - -Next, let's define our `enum` used to communicate `do_work` failures: +Consider a C library that invokes a user-provided callback: [source,c++] ---- -enum do_work_error_code -{ - ec1=1, - ec2 -}; ----- +enum class parse_error { unexpected_token, invalid_syntax }; -We're now ready to define the `do_work` callback function: - -[source,c++] ----- -int do_work( lua_State * L ) noexcept +int on_element(void * ctx, char const * data) { - bool success = rand() % 2; <1> - if( success ) - { - lua_pushnumber(L, 42); <2> - return 1; - } - else + if( <> ) { - (void) leaf::new_error(ec1); <3> - return luaL_error(L, "do_work_error"); <4> + leaf::new_error(parse_error::unexpected_token); + return -1; } + return 0; } ---- [.text-right] -<> | <> - -<1> "Sometimes" `do_work` fails. -<2> In case of success, push the result on the Lua stack, return back to Lua. -<3> Generate a new `error_id` and associate a `do_work_error_code` with it. Normally, we'd return this in a `leaf::result`, but the `do_work` function signature (required by Lua) does not permit this. -<4> Tell the Lua interpreter to abort the Lua program. +<> -Now we'll write the function that calls the Lua interpreter to execute the Lua function `call_do_work`, which in turn calls `do_work`. We'll return `<>`, so that our caller can get the answer in case of success, or an error: +The callback calls `new_error` to associate error objects with the failure, then returns an error code to the C library. The wrapper function uses `error_monitor` to retrieve the `error_id`: [source,c++] ---- -leaf::result call_lua( lua_State * L ) +leaf::result parse(char const * input) { - lua_getfield(L, LUA_GLOBALSINDEX, "call_do_work"); - - error_monitor cur_err; - if( int err = lua_pcall(L, 0, 1, 0) ) <1> - { - auto load = leaf::on_error(e_lua_error_message{lua_tostring(L,1)}); <2> - lua_pop(L,1); + leaf::error_monitor cur_err; - return cur_err.assigned_error_id().load(e_lua_pcall_error{err}); <3> - } + if( c_library_parse(input, &on_element, nullptr) != 0 ) + return cur_err.assigned_error_id(); else - { - int answer = lua_tonumber(L, -1); <4> - lua_pop(L, 1); - return answer; - } + return make_document(); } ---- [.text-right] -<> | <> | <> +<> | <> -<1> Ask the Lua interpreter to call the global Lua function `call_do_work`. -<2> `on_error` works as usual. -<3> `load` will use the `error_id` generated in our Lua callback. This is the same `error_id` the `on_error` uses as well. -<4> Success! Just return the `int` answer. +If `new_error` was called inside the callback, `assigned_error_id` returns that `error_id`. Otherwise, it calls `new_error` and returns a fresh `error_id`. Either way, the caller can handle the failure normally. -Finally, here is the `main` function which exercises `call_lua`, each time handling any failure: - -[source,c++] ----- -int main() noexcept -{ - std::shared_ptr L=init_lua_state(); - - for( int i=0; i!=10; ++i ) - { - leaf::try_handle_all( - - [&]() -> leaf::result - { - BOOST_LEAF_AUTO(answer, call_lua(&*L)); - std::cout << "do_work succeeded, answer=" << answer << '\n'; <1> - return { }; - }, - - [](do_work_error_code e) <2> - { - std::cout << "Got do_work_error_code = " << e << "!\n"; - }, - - [](e_lua_pcall_error const & err, e_lua_error_message const & msg) <3> - { - std::cout << "Got e_lua_pcall_error, Lua error code = " << err.value << ", " << msg.value << "\n"; - }, - - [](leaf::error_info const & unmatched) - { - std::cerr << - "Unknown failure detected" << std::endl << - "Cryptic diagnostic information follows" << std::endl << - unmatched; - } ); - } ----- -[.text-right] -<> | <> | <> | <> - -<1> If the call to `call_lua` succeeded, just print the answer. -<2> Handle `do_work` failures. -<3> Handle all other `lua_pcall` failures. - -NOTE: Follow this link to see the complete program: https://github.com/boostorg/leaf/blob/master/example/lua_callback_result.cpp?ts=4[lua_callback_result.cpp]. - -TIP: When using Lua with {CPP}, we need to protect the Lua interpreter from exceptions that may be thrown from {CPP} functions installed as `lua_CFunction` callbacks. Here is the program from this section rewritten to use a {CPP} exception to safely communicate errors out of the `do_work` function: https://github.com/boostorg/leaf/blob/master/example/lua_callback_eh.cpp?ts=4[lua_callback_eh.cpp]. - -'''' +''' [[tutorial-diagnostic_information]] === Diagnostic Information @@ -1879,7 +1640,7 @@ leaf::try_handle_all( []() -> leaf::result <1> { - ... + .... return leaf::new_error( error_code::write_error, leaf::e_file_name{ "file.txt" } ); }, @@ -1888,25 +1649,28 @@ leaf::try_handle_all( std::cerr << "Read error!" << std::endl; }, - []( leaf::verbose_diagnostic_info const & info ) <3> + []( leaf::diagnostic_details const & info ) <3> { - std::cerr << "Unrecognized error detected, cryptic diagnostic information follows.\n" << info; + std::cerr << "Unrecognized error detected\n" << info; } ); ---- <1> We handle all failures that occur in this try block. <2> One or more error handlers that should handle all possible failures. -<3> The "catch all" error handler is required by `try_handle_all`. It will be called if LEAF is unable to use another error handler. +<3> This "catch all" error handler is required by `try_handle_all`. It will be called if LEAF is unable to use another error handler. -The `verbose_diagnostic_info` output for the snippet above tells us that we got an `error_code` with value `1` (`write_error`), and an object of type `e_file_name` with `"file.txt"` stored in its `.value`: +The `diagnostic_details` output for the snippet above tells us that we got an `error_code` with value `1` (`write_error`), and an object of type `e_file_name` with `"file.txt"` stored in its `.value`: ---- -Unrecognized error detected, cryptic diagnostic information follows. -leaf::verbose_diagnostic_info for Error ID = 1: -[with Name = error_code]: 1 -Unhandled error objects: -[with Name = boost::leaf::e_file_name]: file.txt +Unrecognized error detected +Error with serial #1 +Caught: + error_code: 1 +Diagnostic details: + boost::leaf::e_file_name: file.txt ---- +TIP: In the `diagnostic_details` output, the section under `Caught:` lists the objects which error handlers take as arguments -- these are the objects which are stored on the stack. The section under `Diagnostic details:` lists all other objects that were communicated. These are the objects that would have been discarded if we didn't provide a handler that takes `diagnostic_details`. + To print each error object, LEAF attempts to bind an unqualified call to `operator<<`, passing a `std::ostream` and the error object. If that fails, it will also attempt to bind `operator<<` that takes the `.value` of the error type. If that also does not compile, the error object value will not appear in diagnostic messages, though LEAF will still print its type. Even with error types that define a printable `.value`, the user may still want to overload `operator<<` for the enclosing `struct`, e.g.: @@ -1919,16 +1683,16 @@ struct e_errno friend std::ostream & operator<<( std::ostream & os, e_errno const & e ) { - return os << "errno = " << e.value << ", \"" << strerror(e.value) << '"'; + return os << e.value << ", \"" << strerror(e.value) << '"'; } }; ---- -The `e_errno` type above is designed to hold `errno` values. The defined `operator<<` overload will automatically include the output from `strerror` when `e_errno` values are printed (LEAF defines `e_errno` in ``, together with other commonly-used error types). +The `e_errno` type above is designed to hold `errno` values. The defined `operator<<` overload will automatically include the output from `strerror` when `e_errno` values are printed (LEAF defines `e_errno` in ``, together with other commonly used error types). -Using `verbose_diagnostic_info` comes at a cost. Normally, when the program attempts to communicate error objects of types which are not used in any error handling scope in the current call stack, they are discarded, which saves cycles. However, if an error handler is provided that takes `verbose_diagnostic_info` argument, before such objects are discarded, they are printed and appended to a `std::string` (this is the case with `e_file_name` in our example above). Such objects appear under `Unhandled error objects` in the output from `verbose_diagnostic_info`. +Using `diagnostic_details` comes at a cost. Normally, when the program attempts to communicate error objects of types which are not used in any error handling scope in the current call stack, they are discarded, which saves cycles. However, if an error handler is provided that takes `diagnostic_details` argument, such objects are stored on the heap instead of being discarded. -If handling `verbose_diagnostic_info` is considered too costly, use `diagnostic_info` instead: +If handling `diagnostic_details` is considered too costly, use `diagnostic_info` instead: [source,c++] ---- @@ -1936,7 +1700,7 @@ leaf::try_handle_all( []() -> leaf::result { - ... + .... return leaf::new_error( error_code::write_error, leaf::e_file_name{ "file.txt" } ); }, @@ -1947,22 +1711,22 @@ leaf::try_handle_all( []( leaf::diagnostic_info const & info ) { - std::cerr << "Unrecognized error detected, cryptic diagnostic information follows.\n" << info; + std::cerr << "Unrecognized error detected\n" << info; } ); ---- In this case, the output may look like this: ---- -Unrecognized error detected, cryptic diagnostic information follows. -leaf::diagnostic_info for Error ID = 1: -[with Name = error_code]: 1 -Detected 1 attempt to communicate an unexpected error object of type [with Name = boost::leaf::e_file_name] +Unrecognized error detected +Error serial #1 +Caught: + error_code: 1 ---- -Notice how the diagnostic information for `e_file_name` changed: LEAF no longer prints it before discarding it, and so `diagnostic_info` can only inform about the type of the discarded object, but not its value. +Notice how we are missing the `Diagnostic details:` section. That's because the `e_file_name` object was discarded by LEAF, since no error handler needed it. -TIP: The automatically-generated diagnostic messages are developer-friendly, but not user-friendly. Therefore, `operator<<` overloads for error types should only print technical information in English, and should not attempt to localize strings or to format a user-friendly message; this should be done in error handling functions specifically designed for that purpose. +TIP: The automatically generated diagnostic messages are developer-friendly, but not user-friendly. ''' @@ -1971,7 +1735,7 @@ TIP: The automatically-generated diagnostic messages are developer-friendly, but ==== Introduction -The relationship between `std::error_code` and `std::error_condition` is not easily understood from reading the standard specifications. This section explains how they're supposed to be used, and how LEAF interacts with them. +The relationship between `std::error_code` and `std::error_condition` is not easily understood from reading the standard specification. This section explains how they're supposed to be used, and how LEAF interacts with them. The idea behind `std::error_code` is to encode both an integer value representing an error code, as well as the domain of that value. The domain is represented by a `std::error_category` [underline]#reference#. Conceptually, a `std::error_code` is like a `pair`. @@ -1979,35 +1743,35 @@ Let's say we have this `enum`: [source,c++] ---- -enum class libfoo_error +enum class file_error { - e1 = 1, - e2, - e3 + not_found = 1, + permission_denied, + disk_full }; ---- -We want to be able to transport `libfoo_error` values in `std::error_code` objects. This erases their static type, which enables them to travel freely across API boundaries. To this end, we must define a `std::error_category` that represents our `libfoo_error` type: +We want to be able to transport `file_error` values in `std::error_code` objects. This erases their static type, which enables them to travel freely across API boundaries. To this end, we must define a `std::error_category` that represents our `file_error` type: [source,c++] ---- -std::error_category const & libfoo_error_category() +std::error_category const & file_error_category() { struct category: std::error_category { char const * name() const noexcept override { - return "libfoo"; + return "file_error"; } std::string message(int code) const override { - switch( libfoo_error(code) ) + switch( file_error(code) ) { - case libfoo_error::e1: return "e1"; - case libfoo_error::e2: return "e2"; - case libfoo_error::e3: return "e3"; - default: return "error"; + case file_error::not_found: return "file not found"; + case file_error::permission_denied: return "permission denied"; + case file_error::disk_full: return "disk full"; + default: return "unknown file error"; } } }; @@ -2017,39 +1781,39 @@ std::error_category const & libfoo_error_category() } ---- -We also need to inform the standard library that `libfoo_error` is compatible with `std::error_code`, and provide a factory function which can be used to make `std::error_code` objects out of `libfoo_error` values: +We also need to inform the standard library that `file_error` is compatible with `std::error_code`, and provide a factory function which can be used to make `std::error_code` objects out of `file_error` values: [source,c++] ---- namespace std { template <> - struct is_error_code_enum: std::true_type + struct is_error_code_enum: std::true_type { }; } -std::error_code make_error_code(libfoo_error e) +std::error_code make_error_code(file_error e) { - return std::error_code(int(e), libfoo_error_category()); + return std::error_code(int(e), file_error_category()); } ---- -With this in place, if we receive a `std::error_code`, we can easily check if it represents some of the `libfoo_error` values we're interested in: +With this in place, if we receive a `std::error_code`, we can easily check if it represents some of the `file_error` values we're interested in: [source,c++] ---- -std::error_code f(); +std::error_code read_file(); .... -auto ec = f(); -if( ec == libfoo_error::e1 || ec == libfoo_error::e2 ) +auto ec = read_file(); +if( ec == file_error::not_found || ec == file_error::permission_denied ) { - // We got either a libfoo_error::e1 or a libfoo_error::e2 + // We got either file_error::not_found or file_error::permission_denied } ---- -This works because the standard library detects that `std::is_error_code_enum::value` is `true`, and then uses `make_error_code` to create a `std::error_code` object it actually uses to compare to `ec`. +This works because the standard library detects that `std::is_error_code_enum::value` is `true`, and then uses `make_error_code` to create a `std::error_code` object it actually uses to compare to `ec`. So far so good, but remember, the standard library defines another type also, `std::error_condition`. The first confusing thing is that in terms of its physical representation, `std::error_condition` is identical to `std::error_code`; that is, it is also like a pair of `std::error_category` reference and an `int`. Why do we need two different types which use identical physical representation? @@ -2057,67 +1821,66 @@ The key to answering this question is to understand that `std::error_code` objec This leads us to the second confusing thing about `std::error_condition`: it uses the same `std::error_category` type, but for a completely different purpose: to specify what `std::error_code` values are equivalent to what `std::error_condition` values. -Let's say that in addition to `libfoo`, our program uses another library, `libbar`, which communicates failures in terms of `std::error_code` with a different error category. Perhaps `libbar_error` looks like this: +Let's say that in addition to `file_error`, our program uses a network library which communicates failures in terms of `std::error_code` with a different error category: [source,c++] ---- -enum class libbar_error +enum class net_error { - e1 = 1, - e2, - e3, - e4 + connection_refused = 1, + timeout, + host_unreachable, + dns_failed }; // Boilerplate omitted: -// - libbar_error_category() +// - net_error_category() // - specialization of std::is_error_code_enum -// - make_error_code factory function for libbar_error. +// - make_error_code factory function for net_error. ---- -We can now use `std::error_condition` to define the _logical_ error conditions represented by the `std::error_code` values communicated by `libfoo` and `libbar`: +We can now use `std::error_condition` to define _logical_ error conditions that group related `std::error_code` values from both libraries: [source,c++] ---- -enum class my_error_condition <1> +enum class resource_condition <1> { - c1 = 1, - c2 + unavailable = 1, + access_denied }; -std::error_category const & libfoo_error_category() <2> +std::error_category const & resource_condition_category() <2> { struct category: std::error_category { char const * name() const noexcept override { - return "my_error_condition"; + return "resource_condition"; } std::string message(int cond) const override { - switch( my_error_condition(code) ) + switch( resource_condition(cond) ) { - case my_error_condition::c1: return "c1"; - case my_error_condition::c2: return "c2"; - default: return "error"; + case resource_condition::unavailable: return "resource unavailable"; + case resource_condition::access_denied: return "access denied"; + default: return "unknown condition"; } } bool equivalent(std::error_code const & code, int cond) const noexcept { - switch( my_error_condition(cond) ) + switch( resource_condition(cond) ) { - case my_error_condition::c1: <3> + case resource_condition::unavailable: <3> return - code == libfoo_error::e1 || - code == libbar_error::e3 || - code == libbar_error::e4; - case my_error_condition::c2: <4> + code == file_error::not_found || + code == net_error::host_unreachable || + code == net_error::dns_failed; + case resource_condition::access_denied: <4> return - code == libfoo_error::e2 || - code == libbar_error::e1 || - code == libbar_error::e2; + code == file_error::permission_denied || + code == net_error::connection_refused; default: return false; } @@ -2131,40 +1894,40 @@ std::error_category const & libfoo_error_category() <2> namespace std { template <> <5> - class is_error_condition_enum: std::true_type + class is_error_condition_enum: std::true_type { }; } -std::error_condition make_error_condition(my_error_condition e) <6> +std::error_condition make_error_condition(resource_condition e) <6> { - return std::error_condition(int(e), my_error_condition_error_category()); + return std::error_condition(int(e), resource_condition_category()); } ---- -<1> Enumeration of the two logical error conditions, `c1` and `c2`. -<2> Define the `std::error_category` for `std::error_condition` objects that represent a `my_error_condition`. -<3> Here we specify that any of `libfoo:error::e1`, `libbar_error::e3` and `libbar_error::e4` are logically equivalent to `my_error_condition::c1`, and that... -<4> ...any of `libfoo:error::e2`, `libbar_error::e1` and `libbar_error::e2` are logically equivalent to `my_error_condition::c2`. -<5> This specialization tells the standard library that the `my_error_condition` enum is designed to be used with `std::error_condition`. -<6> The factory function to make `std::error_condition` objects out of `my_error_condition` values. +<1> Enumeration of the two logical conditions: `unavailable` and `access_denied`. +<2> Define the `std::error_category` for `std::error_condition` objects that represent a `resource_condition`. +<3> Here we specify that `file_error::not_found`, `net_error::host_unreachable`, and `net_error::dns_failed` are all logically equivalent to `resource_condition::unavailable`, and that... +<4> ...`file_error::permission_denied` and `net_error::connection_refused` are logically equivalent to `resource_condition::access_denied`. +<5> This specialization tells the standard library that the `resource_condition` enum is designed to be used with `std::error_condition`. +<6> The factory function to make `std::error_condition` objects out of `resource_condition` values. Phew! -Now, if we have a `std::error_code` object `ec`, we can easily check if it is equivalent to `my_error_condition::c1` like so: +Now, if we have a `std::error_code` object `ec`, we can easily check if it is equivalent to `resource_condition::unavailable` like so: [source,c++] ---- -if( ec == my_error_condition::c1 ) +if( ec == resource_condition::unavailable ) { - // We have a c1 in our hands + // The resource is unavailable (file not found, host unreachable, or DNS failed) } ---- -Again, remember that beyond defining the `std::error_category` for `std::error_condition` objects initialized with a `my_error_condition` value, we don't need to interact with the actual `std::error_condition` instances: they're created when needed to compare to a `std::error_code`, and that's pretty much all they're good for. +Again, remember that beyond defining the `std::error_category` for `std::error_condition` objects initialized with a `resource_condition` value, we don't need to interact with the actual `std::error_condition` instances: they're created when needed to compare to a `std::error_code`, and that's pretty much all they're good for. ==== Support in LEAF -The `match` predicate can be used as an argument to a LEAF error handler to match a `std::error_code` with a given error condition. For example, to handle `my_error_condition::c1` (see above), we could use: +The `match` predicate can be used as an argument to a LEAF error handler to match a `std::error_code` with a given error condition. For example, to handle `resource_condition::unavailable` (see above), we could use: [source,c++] ---- @@ -2172,12 +1935,12 @@ leaf::try_handle_some( [] { - return f(); // returns leaf::result + return open_resource(); // returns leaf::result }, - []( leaf::match m ) + []( leaf::match m ) { - assert(m.matched == my_error_condition::c1); + assert(m.matched == resource_condition::unavailable); .... } ); ---- @@ -2281,69 +2044,100 @@ A standalone single-header option is available; please see <>. [[synopsis-reporting]] === Error Reporting -[[error.hpp]] -==== `error.hpp` +[[common.hpp]] +==== `common.hpp` ==== -.#include +.#include [source,c++] ---- namespace boost { namespace leaf { - class error_id - { - public: - - error_id() noexcept; - - template - error_id( Enum e, typename std::enable_if::value, Enum>::type * = 0 ) noexcept; - - error_id( std::error_code const & ec ) noexcept; + struct e_api_function { char const * value; }; - int value() const noexcept; - explicit operator bool() const noexcept; + struct e_file_name { std::string value; }; - std::error_code to_error_code() const noexept; + struct e_type_info_name { char const * value; }; - friend bool operator==( error_id a, error_id b ) noexcept; - friend bool operator!=( error_id a, error_id b ) noexcept; - friend bool operator<( error_id a, error_id b ) noexcept; + struct e_at_line { int value; }; - template - error_id load( Item && ... item ) const noexcept; + struct e_errno + { + int value; + explicit e_errno(int value=errno); - friend std::ostream & operator<<( std::ostream & os, error_id x ); + template + friend std::ostream & operator<<( std::basic_ostream &, e_errno const &); }; - bool is_error_id( std::error_code const & ec ) noexcept; + namespace windows + { + struct e_LastError + { + unsigned value; - template - error_id new_error( Item && ... item ) noexcept; + explicit e_LastError(unsigned value); - error_id current_error() noexcept; +#if BOOST_LEAF_CFG_WIN32 + e_LastError(); + + template + friend std::ostream & operator<<( std::basic_ostream &, e_LastError const &); +#endif + }; + } - ////////////////////////////////////////// +} } +---- - class polymorphic_context - { - protected: +[.text-right] +Reference: <> | <> | <> | <> | <> | <> | <> +==== - polymorphic_context() noexcept = default; - ~polymorphic_context() noexcept = default; +[[error.hpp]] +==== `error.hpp` + +==== +.#include +[source,c++] +---- +namespace boost { namespace leaf { + class error_id + { public: - virtual void activate() noexcept = 0; - virtual void deactivate() noexcept = 0; - virtual bool is_active() const noexcept = 0; + error_id() noexcept; + + template + error_id( Enum e, typename std::enable_if::value, Enum>::type * = 0 ) noexcept; + + error_id( std::error_code const & ec ) noexcept; + + int value() const noexcept; + explicit operator bool() const noexcept; + + std::error_code to_error_code() const noexcept; + + friend bool operator==( error_id a, error_id b ) noexcept; + friend bool operator!=( error_id a, error_id b ) noexcept; + friend bool operator<( error_id a, error_id b ) noexcept; - virtual void propagate( error_id ) noexcept = 0; + template + error_id load( Item && ... item ) const noexcept; - virtual void print( std::ostream & ) const = 0; + template + friend std::ostream & operator<<( std::basic_ostream &, error_id ); }; - ////////////////////////////////////////// + bool is_error_id( std::error_code const & ec ) noexcept; + + template + error_id new_error( Item && ... item ) noexcept; + + error_id current_error() noexcept; + + //////////////////////////////////////// template class context_activator @@ -2382,64 +2176,101 @@ namespace boost { namespace leaf { #define BOOST_LEAF_AUTO(v, r)\ BOOST_LEAF_ASSIGN(auto v, r) +#if BOOST_LEAF_CFG_GNUC_STMTEXPR + #define BOOST_LEAF_CHECK(r)\ - auto && <> = r;\ - if( <> )\ - ;\ - else\ - return <>.error() + ({\ + auto && <> = (r);\ + if( !<> )\ + return <>.error();\ + std::move(<>);\ + }).value() + +#else + +#define BOOST_LEAF_CHECK(r)\ + {\ + auto && <> = r;\ + if( !<> )\ + return <>.error()\ + } + +#endif -#define BOOST_LEAF_NEW_ERROR <> ::boost::leaf::new_error +#define BOOST_LEAF_NEW_ERROR <> ---- [.text-right] -Reference: <> | <> | <> | <> | <> | <> | <> | <> | <> | <> | <> | <> +Reference: <> | <> | <> | <> | <> | <> | <> | <> | <> | <> | <> ==== -[[common.hpp]] -==== `common.hpp` +[[exception.hpp]] +==== `exception.hpp` ==== -.#include +.#include [source,c++] ---- namespace boost { namespace leaf { - struct e_api_function { char const * value; }; + template <1> + [[noreturn]] void throw_exception( Ex &&, E && ... ); - struct e_file_name { std::string value; }; + template <2> + [[noreturn]] void throw_exception( E1 &&, E && ... ); - struct e_type_info_name { char const * value; }; + [[noreturn]] void throw_exception(); - struct e_at_line { int value; }; + template <1> + [[noreturn]] void throw_exception( error_id id, Ex &&, E && ... ); - struct e_errno - { - int value; - explicit e_errno(int value=errno); - friend std::ostream & operator<<(std::ostream &, e_errno const &); - }; + template <2> + [[noreturn]] void throw_exception( error_id id, E1 &&, E && ... ); - namespace windows + [[noreturn]] void throw_exception( error_id id ); + + template + <-deduced>> exception_to_result( F && f ) noexcept; + +} } + +#define BOOST_LEAF_THROW_EXCEPTION <> +---- + +[.text-right] +Reference: <> | <> + +<1> Only enabled if std::is_base_of::value. +<2> Only enabled if !std::is_base_of::value. +==== + +[[on_error.hpp]] +==== `on_error.hpp` + +==== +[source,c++] +.#include +---- +namespace boost { namespace leaf { + + template + <> on_error( Item && ... e ) noexcept; + + class error_monitor { - struct e_LastError - { - unsigned value; + public: - explicit e_LastError(unsigned value); + error_monitor() noexcept; -#if BOOST_LEAF_CFG_WIN32 - e_LastError(); - friend std::ostream & operator<<(std::ostream &, e_LastError const &); -#endif - }; - } + error_id check() const noexcept; + error_id assigned_error_id() const noexcept; + }; } } ---- [.text-right] -Reference: <> | <> | <> | <> | <> | <> | <> +Reference: <> | <> ==== [[result.hpp]] @@ -2456,48 +2287,66 @@ namespace boost { namespace leaf { { public: + using value_type = T; + + // NOTE: Copy constructor implicitly deleted. + result( result && r ) noexcept; + + template ::value>::type> + result( result && r ) noexcept; + result() noexcept; + result( T && v ) noexcept; - result( T const & v ); - template - result( U && u, <> ); + result( T const & v ); result( error_id err ) noexcept; - result( std::shared_ptr && ctx ) noexcept; - template - result( Enum e, typename std::enable_if::value, Enum>::type * = 0 ) noexcept; + template ::value>::type> + result( U && u ); + +#if BOOST_LEAF_CFG_STD_SYSTEM_ERROR result( std::error_code const & ec ) noexcept; - result( result && r ) noexcept; + template ::value, int>::type> + result( Enum e ) noexcept; - template - result( result && r ) noexcept; +#endif + // NOTE: Assignment operator implicitly deleted. result & operator=( result && r ) noexcept; - template + template ::value>::type> result & operator=( result && r ) noexcept; bool has_value() const noexcept; bool has_error() const noexcept; explicit operator bool() const noexcept; - T const & value() const; - T & value(); + T const & value() const &; + T & value() &; + T const && value() const &&; + T && value() &&; T const * operator->() const noexcept; T * operator->() noexcept; - T const & operator*() const noexcept; - T & operator*() noexcept; + T const & operator*() const & noexcept; + T & operator*() & noexcept; + T const && operator*() const && noexcept; + T && operator*() && noexcept; <> error() noexcept; template error_id load( Item && ... item ) noexcept; + + void unload(); + + template + friend std::ostream & operator<<( std::basic_ostream &, result const & ); }; template <> @@ -2505,34 +2354,45 @@ namespace boost { namespace leaf { { public: + using value_type = void; + + // NOTE: Copy constructor implicitly deleted. + result( result && r ) noexcept; + result() noexcept; result( error_id err ) noexcept; - result( std::shared_ptr && ctx ) noexcept; - template - result( Enum e, typename std::enable_if::value, Enum>::type * = 0 ) noexcept; +#if BOOST_LEAF_CFG_STD_SYSTEM_ERROR result( std::error_code const & ec ) noexcept; - result( result && r ) noexcept; + template ::value, Enum>::type> + result( Enum e ) noexcept; - template - result( result && r ) noexcept; +#endif + // NOTE: Assignment operator implicitly deleted. result & operator=( result && r ) noexcept; - template - result & operator=( result && r ) noexcept; - explicit operator bool() const noexcept; void value() const; + void const * operator->() const noexcept; + void * operator->() noexcept; + + void operator*() const noexcept; + <> error() noexcept; template error_id load( Item && ... item ) noexcept; + + void unload(); + + template + friend std::ostream & operator<<( std::basic_ostream &, result const &); }; struct bad_result: std::exception { }; @@ -2549,99 +2409,9 @@ namespace boost { namespace leaf { Reference: <> | <> ==== -[[on_error.hpp]] -==== `on_error.hpp` - -==== -[source,c++] -.#include ----- -namespace boost { namespace leaf { - - template - <> on_error( Item && ... e ) noexcept; - - class error_monitor - { - public: - - error_monitor() noexcept; - - error_id check() const noexcept; - error_id assigned_error_id() const noexcept; - }; - -} } ----- - -[.text-right] -Reference: <> | <> -==== - -[[exception.hpp]] -==== `exception.hpp` - -==== -.#include -[source,c++] ----- -namespace boost { namespace leaf { - - template <1> - <> exception( Ex &&, E && ... ) noexcept; - - template <2> - <> exception( E1 &&, E && ... ) noexcept; - - <> exception() noexcept; - - template <1> - <> exception( error_id id, Ex &&, E && ... ) noexcept; - - template <2> - <> exception( error_id id, E1 &&, E && ... ) noexcept; - - <> exception( error_id id ) noexcept; - - template - <-deduced>> exception_to_result( F && f ) noexcept; - -} } - -#define BOOST_LEAF_EXCEPTION <> ::boost::leaf::exception - -#define BOOST_LEAF_THROW_EXCEPTION <> ::boost::leaf::exception ----- - -[.text-right] -Reference: <> | <> | <> - -<1> Only enabled if std::is_base_of::value. -<2> Only enabled if !std::is_base_of::value. -==== - -==== `capture.hpp` - -==== -[source,c++] -.#include ----- -namespace boost { namespace leaf { - - template - decltype(std::declval()(std::forward(std::declval())...)) - capture(std::shared_ptr && ctx, F && f, A... a); - -} } ----- - -[.text-right] -Reference: <> | <> -==== - ''' -[[tutorial-handling]] +[[synopsis-handling]] === Error Handling @@ -2670,16 +2440,17 @@ namespace boost { namespace leaf { void deactivate() noexcept; bool is_active() const noexcept; - void propagate( error_id ) noexcept; + void unload( error_id ) noexcept; void print( std::ostream & os ) const; + template + friend std::ostream & operator<<( std::basic_ostream &, context const & ); + template R handle_error( R &, H && ... ) const; }; - ////////////////////////////////////////// - template using context_type_from_handlers = typename <>::type; @@ -2689,17 +2460,43 @@ namespace boost { namespace leaf { template BOOST_LEAF_CONSTEXPR context_type_from_handlers make_context( H && ... ) noexcept; - template - context_ptr make_shared_context() noexcept; +} } +---- - template - context_ptr make_shared_context( H && ... ) noexcept; +[.text-right] +Reference: <> | <> | <> +==== + +[[diagnostics.hpp]] +==== `diagnostics.hpp` + +==== +.#include +[source,c++] +---- +namespace boost { namespace leaf { + + class diagnostic_info: public error_info + { + //No public constructors + + template + friend std::ostream & operator<<( std::basic_ostream &, diagnostic_info const & ); + }; + + class diagnostic_details: public error_info + { + //No public constructors + + template + friend std::ostream & operator<<( std::basic_ostream &, diagnostic_info const & ); + }; } } ---- [.text-right] -Reference: <> | <> | <> | <> +Reference: <> | <> ==== [[handle_errors.hpp]] @@ -2723,7 +2520,11 @@ namespace boost { namespace leaf { typename std::decay()())>::type try_catch( TryBlock && try_block, H && ... h ); - ////////////////////////////////////////// +#if BOOST_LEAF_CFG_CAPTURE + template + result // T deduced depending on TryBlock return type + try_capture_all( TryBlock && try_block ); +#endif class error_info { @@ -2736,52 +2537,15 @@ namespace boost { namespace leaf { bool exception_caught() const noexcept; std::exception const * exception() const noexcept; - friend std::ostream & operator<<( std::ostream & os, error_info const & x ); - }; - - class diagnostic_info: public error_info - { - //No public constructors - - friend std::ostream & operator<<( std::ostream & os, diagnostic_info const & x ); - }; - - class verbose_diagnostic_info: public error_info - { - //No public constructors - - friend std::ostream & operator<<( std::ostream & os, diagnostic_info const & x ); + template + friend std::ostream & operator<<( std::basic_ostream &, error_info const & ); }; } } ---- [.text-right] -Reference: <> | <> | <> | <> | <> | <> -==== - -[[handle_errors.hpp]] -==== `to_variant.hpp` - -==== -.#include -[source,c++] ----- -namespace boost { namespace leaf { - - // Requires at least C++17 - template - std::variant< - typename std::decay()().value())>::type - std::tuple< - std::optional...>> - to_variant( TryBlock && try_block ); - -} } ----- - -[.text-right] -Reference: <> +Reference: <> | <> | <> | <> | <> ==== [[pred.hpp]] @@ -2828,7 +2592,7 @@ namespace boost { namespace leaf { struct match_member; template - struct member + struct match_member { E matched; @@ -2887,6 +2651,30 @@ namespace boost { namespace leaf { Reference: <> | <> | <> | <> | <> | <> | <> ==== +[[to_variant.hpp]] +==== `to_variant.hpp` + +==== +.#include +[source,c++] +---- +namespace boost { namespace leaf { + + // Requires at least C++17 + template + std::variant< + typename std::decay()().value())>::type, + std::tuple< + std::optional...>> + to_variant( TryBlock && try_block ); + +} } +---- + +[.text-right] +Reference: <> +==== + [[functions]] == Reference: Functions @@ -2920,7 +2708,7 @@ namespace boost { namespace leaf { leaf::context ctx; { - auto active_context = activate_context(ctx); <1> + auto active_context = ctx.raii_activate(); <1> } <2> ---- <1> Activate `ctx`. @@ -2928,46 +2716,6 @@ leaf::context ctx; ''' -[[capture]] -=== `capture` - -.#include -[source,c++] ----- -namespace boost { namespace leaf { - - template - decltype(std::declval()(std::forward(std::declval())...)) - capture(std::shared_ptr && ctx, F && f, A... a); - -} } ----- - -[.text-right] -<> - -This function can be used to capture error objects stored in a <> in one thread and transport them to a different thread for handling, either in a `<>` object or in an exception. - -Returns: :: The same type returned by `F`. - -Effects: :: Uses an internal <> to <> `*ctx`, then invokes `std::forward(f)(std::forward(a)...)`. Then: -+ --- -* If the returned value `r` is not a `result` type (see <>), it is forwarded to the caller. -* Otherwise: -** If `!r`, the return value of `capture` is initialized with `ctx`; -+ -NOTE: An object of type `leaf::<>` can be initialized with a `std::shared_ptr`. -+ -** otherwise, it is initialized with `r`. --- -+ -In case `f` throws, `capture` catches the exception in a `std::exception_ptr`, and throws a different exception of unspecified type that transports both the `std::exception_ptr` as well as `ctx`. This exception type is recognized by <>, which automatically unpacks the original exception and propagates the contents of `*ctx` (presumably, in a different thread). - -TIP: See also <> from the Tutorial. - -''' - [[context_type_from_handlers]] === `context_type_from_handlers` @@ -3002,7 +2750,7 @@ leaf::context_type_from_handlers ctx; <1> ---- <1> `ctx` will be of type `context`, deduced automatically from the specified error handlers. -TIP: Alternatively, a suitable context may be created by calling <>, or allocated dynamically by calling <>. +TIP: Alternatively, a suitable context may be created by calling <>. ''' @@ -3025,82 +2773,6 @@ TIP: See also <>. ''' -[[exception]] -=== `exception` - -[source,c++] -.#include ----- -namespace boost { namespace leaf { - - template <1> - <> exception( Ex && ex, E && ... e ) noexcept; - - template <2> - <> exception( E1 && e1, E && ... e ) noexcept; - - <> exception() noexcept; <3> - - template <4> - <> exception( error_id id, Ex && ex, E && ... e ) noexcept; - - template <5> - <> exception( error_id id, E1 && e1, E && ... e ) noexcept; - - <> exception( error_id id ) noexcept; <6> - -} } ----- -The `exception` function is overloaded: it can be invoked with no arguments, or else there are several alternatives, selected using `std::enable_if` based on the type of the passed arguments: - -<1> Selected if the first argument is not of type `error_id` and is an exception object, that is, iff `Ex` derives publicly from `std::exception`. In this case the return value is of unspecified type which derives publicly from `Ex` *and* from class <>, such that: -* its `Ex` subobject is initialized by `std::forward(ex)`; -* its `error_id` subobject is initialized by `<>(std::forward(e)...`). - -<2> Selected if the first argument is not of type `error_id` and is not an exception object. In this case the return value is of unspecified type which derives publicly from `std::exception` *and* from class `error_id`, such that: -** its `std::exception` subobject is default-initialized; -** its `error_id` subobject is initialized by `<>(std::forward(e1), std::forward(e)...`). - -<3> If the fuction is invoked without arguments, the return value is of unspecified type which derives publicly from `std::exception` *and* from class `error_id`, such that: -** its `std::exception` subobject is default-initialized; -** its `error_id` subobject is initialized by `<>()`. - -<4> Selected if the first argument is of type `error_id` and the second argument is an exception object, that is, iff `Ex` derives publicly from `std::exception`. In this case the return value is of unspecified type which derives publicly from `Ex` *and* from class <>, such that: -** its `Ex` subobject is initialized by `std::forward(ex)`; -** its `error_id` subobject is initialized by `id.<>(std::forward(e)...)`. - -<5> Selected if the first argument is of type `error_id` and the second argument is not an exception object. In this case the return value is of unspecified type which derives publicly from `std::exception` *and* from class `error_id`, such that: -** its `std::exception` subobject is default-initialized; -** its `error_id` subobject is initialized by `id.<>(std::forward(e1), std::forward(e)...`). - -<6> If `exception` is invoked with just an `error_id` object, the return value is of unspecified type which derives publicly from `std::exception` *and* from class `error_id`, such that: -** its `std::exception` subobject is default-initialized; -** its `error_id` subobject is initialized by copying from `id`. - -NOTE: The first three overloads return an exception object that is associated with a new `error_id`. The second three overloads return an exception object that is associated with the specified `error_id`. - -.Example 1: -[source,c++] ----- -struct my_exception: std::exception { }; - -throw leaf::exception(my_exception{}); <1> ----- -<1> Throws an exception of a type that derives from `error_id` and from `my_exception` (because `my_exception` derives from `std::exception`). - -.Example 2: -[source,c++] ----- -enum class my_error { e1=1, e2, e3 }; <1> - -throw leaf::exception(my_error::e1); ----- -<1> Throws an exception of a type that derives from `error_id` and from `std::exception` (because `my_error` does not derive from `std::exception`). - -NOTE: To automatically capture `pass:[__FILE__]`, `pass:[__LINE__]` and `pass:[__FUNCTION__]` with the returned object, use <> instead of `leaf::exception`. - -''' - [[exception_to_result]] === `exception_to_result` @@ -3115,7 +2787,7 @@ namespace boost { namespace leaf { } } ---- -This function can be used to catch exceptions from a lower-level library and convert them to `<>`. +This function can be used to catch exceptions from a lower-level library and convert them to `<>`. Returns: :: Where `f` returns a type `T`, `exception_to_result` returns `leaf::result`. @@ -3134,7 +2806,11 @@ int compute_answer_throws(); //Call compute_answer, convert exceptions to result leaf::result compute_answer() { - return leaf::exception_to_result(compute_answer_throws()); + return leaf::exception_to_result( + [] + { + return compute_answer_throws(); + } ); } ---- @@ -3144,7 +2820,7 @@ At a later time we can invoke <> / <> as usual, ---- return leaf::try_handle_some( - [] -> leaf::result + []() -> leaf::result { BOOST_LEAF_AUTO(answer, compute_answer()); //Use answer @@ -3220,36 +2896,6 @@ auto ctx = leaf::make_context( <1> ''' -[[make_shared_context]] -=== `make_shared_context` - -.#include -[source,c++] ----- -namespace boost { namespace leaf { - - template - context_ptr make_shared_context() noexcept - { - return std::make_shared>>(); - } - - template - context_ptr make_shared_context( H && ... ) noexcept - { - return std::make_shared>>(); - } - -} } ----- - -[.text-right] -<> - -TIP: See also <> from the tutorial. - -''' - [[new_error]] === `new_error` @@ -3323,6 +2969,82 @@ TIP: See <> from the Tutorial. ''' +[[throw_exception]] +=== `throw_exception` + +[source,c++] +.#include +---- +namespace boost { namespace leaf { + + template <1> + [[noreturn]] void throw_exception( Ex && ex, E && ... e ); + + template <2> + [[noreturn]] void throw_exception( E1 && e1, E && ... e ); + + [[noreturn]] void throw_exception(); <3> + + template <4> + [[noreturn]] void throw_exception( error_id id, Ex && ex, E && ... e ); + + template <5> + [[noreturn]] void throw_exception( error_id id, E1 && e1, E && ... e ); + + [[noreturn]] void throw_exception( error_id id ); <6> + +} } +---- +The `throw_exception` function is overloaded: it can be invoked with no arguments, or else there are several alternatives, selected using `std::enable_if` based on the type of the passed arguments. All overloads throw an exception: + +<1> Selected if the first argument is not of type `error_id` and is an exception object, that is, iff `Ex` derives publicly from `std::exception`. In this case the thrown exception is of unspecified type which derives publicly from `Ex` *and* from class <>, such that: +* its `Ex` subobject is initialized by `std::forward(ex)`; +* its `error_id` subobject is initialized by `<>(std::forward(e)...`). + +<2> Selected if the first argument is not of type `error_id` and is not an exception object. In this case the thrown exception is of unspecified type which derives publicly from `std::exception` *and* from class `error_id`, such that: +** its `std::exception` subobject is default-initialized; +** its `error_id` subobject is initialized by `<>(std::forward(e1), std::forward(e)...`). + +<3> If the function is invoked without arguments, the thrown exception is of unspecified type which derives publicly from `std::exception` *and* from class `error_id`, such that: +** its `std::exception` subobject is default-initialized; +** its `error_id` subobject is initialized by `<>()`. + +<4> Selected if the first argument is of type `error_id` and the second argument is an exception object, that is, iff `Ex` derives publicly from `std::exception`. In this case the thrown exception is of unspecified type which derives publicly from `Ex` *and* from class <>, such that: +** its `Ex` subobject is initialized by `std::forward(ex)`; +** its `error_id` subobject is initialized by `id.<>(std::forward(e)...)`. + +<5> Selected if the first argument is of type `error_id` and the second argument is not an exception object. In this case the thrown exception is of unspecified type which derives publicly from `std::exception` *and* from class `error_id`, such that: +** its `std::exception` subobject is default-initialized; +** its `error_id` subobject is initialized by `id.<>(std::forward(e1), std::forward(e)...`). + +<6> If `throw_exception` is invoked with just an `error_id` object, the thrown exception is of unspecified type which derives publicly from `std::exception` *and* from class `error_id`, such that: +** its `std::exception` subobject is default-initialized; +** its `error_id` subobject is initialized by copying from `id`. + +NOTE: The first three overloads throw an exception object that is associated with a new `error_id`. The second three overloads throw an exception object that is associated with the specified `error_id`. + +.Example 1: +[source,c++] +---- +struct my_exception: std::exception { }; + +leaf::throw_exception(my_exception{}); <1> +---- +<1> Throws an exception of a type that derives from `error_id` and from `my_exception` (because `my_exception` derives from `std::exception`). + +.Example 2: +[source,c++] +---- +enum class my_error { e1=1, e2, e3 }; <1> + +leaf::throw_exception(my_error::e1); +---- +<1> Throws an exception of a type that derives from `error_id` and from `std::exception` (because `my_error` does not derive from `std::exception`). + +NOTE: To automatically capture `pass:[__FILE__]`, `pass:[__LINE__]` and `pass:[__FUNCTION__]` with the returned object, use <> instead of `leaf::throw_exception`. + +''' + [[to_variant]] === `to_variant` @@ -3333,7 +3055,7 @@ namespace boost { namespace leaf { template std::variant< - typename std::decay()().value())>::type + typename std::decay()().value())>::type, std::tuple< std::optional...>> to_variant( TryBlock && try_block ); @@ -3345,7 +3067,7 @@ Requires: :: * This function is only available under {CPP}-17 or newer. * The `try_block` function may not take any arguments. -* The type returned by the `try_block` function must be a `result` type (see <>). It is valid for the `try_block` to return `leaf::<>`, however this is not a requirement. +* The type returned by the `try_block` function must be a `result` type (see <>). It is valid for the `try_block` to return `leaf::<>`, however this is not a requirement. The `to_variant` function uses <> internally to invoke the `try_block` and capture the result in a `std::variant`. On success, the variant contains the `T` object from the produced `result`. Otherwise, the variant contains a `std::tuple` where each `std::optional` element contains an object of type `E~i~` from the user-supplied sequence `E...`, or is empty if the failure did not produce an error object of that type. @@ -3378,6 +3100,39 @@ assert(std::get<2>(t).value() == E3::e33); <3> ''' +[[try_capture_all]] +=== `try_capture_all` + +.#include +[source,c++] +---- +#if BOOST_LEAF_CFG_CAPTURE + +namespace boost { namespace leaf { + + template + result // T deduced depending on TryBlock return type + try_capture_all( TryBlock && try_block ) noexcept; + +} } + +#endif +---- + +Return type: :: An instance of `leaf::<>`, where T is deduced depending on the return type `R` of the `TryBlock`: +* If `R` is a some type `Result` for which <> is true, `try_capture_all` returns `leaf::<>`. +* Otherwise it is assumed that the `TryBlock` reports errors by throwing exceptions, and the return value of `try_capture_all` is deduced as `leaf::result`. + +Effects: :: `try_capture_all` executes `try_block`, catching and capturing all exceptions and all communicated error objects in the returned `leaf::result` object. The error objects are allocated dynamically. + +WARNING: Calls to `try_capture_all` must not be nested in `try_handle_all`/`try_handle_some`/`try_catch` or in another `try_capture_all`. + +NOTE: Under `BOOST_LEAF_CFG_CAPTURE=0`, `try_capture_all` is unavailable. + +See also: :: <>. + +''' + [[try_catch]] === `try_catch` @@ -3445,18 +3200,18 @@ namespace boost { namespace leaf { Requires: :: * The `try_block` function may not take any arguments. -* The type `R` returned by the `try_block` function must be a `result` type (see <>). It is valid for the `try_block` to return `leaf::<>`, however this is not a requirement. +* The type `R` returned by the `try_block` function must be a `result` type (see <>). It is valid for the `try_block` to return `leaf::<>`, however this is not a requirement. * Each of the `h...` functions: ** must return a type that can be used to initialize an object of the type `R`; in case R is a `result` (that is, in case of success it does not communicate a value), handlers that return `void` are permitted. If such a handler is selected, the `try_handle_some` return value is initialized by `{}`; ** may take any error objects, by value, by (`const`) reference, or as pointer (to `const`); -** may take arguments, by value, of any predicate type: <>, <>, <>, <>, <>, or of any user-defined predicate type `Pred` for which `<>::value` is `true`; +** may take arguments, by value, of any predicate type: <>, <>, <>, <>, <>, or of any user-defined predicate type `Pred` for which `<>::value` is `true`; ** may take an <> argument by `const &`; ** may take a <> argument by `const &`; -** may take a <> argument by `const &`. +** may take a <> argument by `const &`. Effects: :: -* Creates a local `<>` object `ctx`, where the `E...` types are automatically deduced from the types of arguments taken by each of `h...`, which guarantees that `ctx` is able to store all of the types required to handle errors. +* Creates a local `<>` object `ctx`, where the `E...` types are automatically deduced from the types of arguments taken by each of `h...`, which guarantees that `ctx` is able to store all of the types required to handle errors. * Invokes the `try_block`: ** if the returned object `r` indicates success [.underline]#and# the `try_block` did not throw, `r` is forwarded to the caller. ** otherwise, LEAF considers each of the `h...` handlers, in order, until it finds one that it can supply with arguments using the error objects currently stored in `ctx`, associated with `r.error()`. The first such handler is invoked and its return value is used to initialize the return value of `try_handle_some`, which can indicate success if the handler was able to handle the error, or failure if it was not. @@ -3527,7 +3282,6 @@ try_handle_some( return 1; } ); -} ---- + [.text-right] @@ -3536,7 +3290,7 @@ try_handle_some( <1> This handler can be selected to handle any error, because it takes `e_file_name` as a `const *` (and nothing else). <2> If an `e_file_name` is available with the current error, print it. + -* If `a~i~` is of a predicate type `Pred` (for which `<>::value` is `true`), `E` is deduced as `typename Pred::error_type`, and then: +* If `a~i~` is of a predicate type `Pred` (for which `<>::value` is `true`), `E` is deduced as `typename Pred::error_type`, and then: ** If `E` is not `void`, and an error object `e` of type `E`, associated with `err`, is not currently stored in `ctx`, the handler is dropped; otherwise the handler is dropped if the expression `Pred::evaluate(e)` returns `false`. ** if `E` is `void`, and a `std::exception` was not caught, the handler is dropped; otherwise the handler is dropped if the expression `Pred::evaluate(e)`, where `e` is of type `std::exception const &`, returns `false`. ** To invoke the handler, the `Pred` argument `a~i~` is initialized with `Pred{e}`. @@ -3558,7 +3312,7 @@ try_handle_some( [](leaf::error_info const & info) <1> { - std::cerr << "leaf::error_info:" << std::endl << info; <2> + std::cerr << "leaf::error_info:\n" << info; <2> return info.error(); <3> } ); ---- @@ -3585,7 +3339,7 @@ try_handle_some( [](leaf::diagnostic_info const & info) <1> { - std::cerr << "leaf::diagnostic_information:" << std::endl << info; <2> + std::cerr << "leaf::diagnostic_information:\n" << info; <2> return info.error(); <3> } ); ---- @@ -3597,7 +3351,7 @@ try_handle_some( <2> Print diagnostic information, including limited information about dropped error objects. <3> Return the original error, which will be returned out of `try_handle_some`. + -* If `a~i~` is of type `verbose_diagnostic_info const &`, `try_handle_some` is always able to produce it. +* If `a~i~` is of type `diagnostic_details const &`, `try_handle_some` is always able to produce it. + .Example: [source,c++] @@ -3610,15 +3364,15 @@ try_handle_some( return f(); // throws }, - [](leaf::verbose_diagnostic_info const & info) <1> + [](leaf::diagnostic_details const & info) <1> { - std::cerr << "leaf::verbose_diagnostic_information:" << std::endl << info; <2> + std::cerr << "leaf::diagnostic_details\n" << info; <2> return info.error(); <3> } ); ---- + [.text-right] -<> | <> +<> | <> + <1> This handler matches any error. <2> Print verbose diagnostic information, including values of dropped error objects. @@ -3656,7 +3410,7 @@ namespace boost { namespace leaf { void deactivate() noexcept; bool is_active() const noexcept; - void propagate( error_id ) noexcept; + void unload( error_id ) noexcept; void print( std::ostream & os ) const; @@ -3671,7 +3425,7 @@ namespace boost { namespace leaf { } } ---- [.text-right] -<> | <> | <> | <> | <> | <> | <> | <> +<> | <> | <> | <> | <> | <> | <> | <> The `context` class template provides storage for each of the specified `E...` types. Typically, `context` objects are not used directly; they're created internally when the <>, <> or <> functions are invoked, instantiated with types that are automatically deduced from the types of the arguments of the passed handlers. @@ -3681,7 +3435,7 @@ Even in that case it is recommended that users do not instantiate the `context` To be able to load up error objects in a `context` object, it must be activated. Activating a `context` object `ctx` binds it to the calling thread, setting thread-local pointers of the stored `E...` types to point to the corresponding storage within `ctx`. It is possible, even likely, to have more than one active `context` in any given thread. In this case, activation/deactivation must happen in a LIFO manner. For this reason, it is best to use a <>, which relies on RAII to activate and deactivate a `context`. -When a `context` is deactivated, it detaches from the calling thread, restoring the thread-local pointers to their pre-`activate` values. Typically, at this point the stored error objects, if any, are either discarded (by default) or moved to corresponding storage in other `context` objects active in the calling thread (if available), by calling <>. +When a `context` is deactivated, it detaches from the calling thread, restoring the thread-local pointers to their pre-`activate` values. Typically, at this point the stored error objects, if any, are either discarded (by default) or moved to corresponding storage in other `context` objects active in the calling thread (if available), by calling <>. While error handling typically uses <>, <> or <>, it is also possible to handle errors by calling the member function <>. It takes an <>, and attempts to select an error handler based on the error objects stored in `*this`, associated with the passed `error_id`. @@ -3730,11 +3484,11 @@ namespace boost { namespace leaf { } } ---- -Requires: :: `!<>()`. +Requires: :: `!<>()`. Effects: :: Associates `*this` with the calling thread. -Ensures: :: `<>()`. +Ensures: :: `<>()`. When a context is associated with a thread, thread-local pointers are set to point each `E...` type in its store, while the previous value of each such pointer is preserved in the `context` object, so that the effect of `activate` can be undone by calling `deactivate`. @@ -3757,12 +3511,12 @@ namespace boost { namespace leaf { ---- Requires: :: -* `<>()`; +* `<>()`; * `*this` must be the last activated `context` object in the calling thread. Effects: :: Un-associates `*this` with the calling thread. -Ensures: :: `!<>()`. +Ensures: :: `!<>()`. When a context is deactivated, the thread-local pointers that currently point to each individual error object storage in it are restored to their original value prior to calling <>. @@ -3818,6 +3572,13 @@ namespace boost { namespace leaf { template void context::print( std::ostream & os ) const; + template + friend std::ostream & context::operator<<( std::basic_ostream &, context const & ) + { + ctx.print(os); + return os; + } + } } ---- @@ -3825,8 +3586,8 @@ Effects: :: Prints all error objects currently stored in `*this`, together with ''' -[[context::propagate]] -==== `propagate` +[[context::unload]] +==== `unload` .#include [source,c++] @@ -3834,13 +3595,13 @@ Effects: :: Prints all error objects currently stored in `*this`, together with namespace boost { namespace leaf { template - void context::propagate( error_id id ) noexcept; + void context::unload( error_id id ) noexcept; } } ---- Requires: :: -`!<>()`. +`!<>()`. Effects: :: @@ -3873,53 +3634,89 @@ namespace boost { namespace leaf { `context_activator` is a simple class that activates and deactivates a <> using RAII: -If `<>`() is `true` at the time the `context_activator` is initialized, the constructor and the destructor have no effects. Otherwise: +If `ctx.<>()` is `true` at the time the `context_activator` is initialized, the constructor and the destructor have no effects. Otherwise: -* The constructor stores a reference to `ctx` in `*this` and calls `<>`(). +* The constructor stores a reference to `ctx` in `*this` and calls `ctx.<>()`. * The destructor: ** Has no effects if `ctx.is_active()` is `false` (that is, it is valid to call <> manually, before the `context_activator` object expires); -** Otherwise, calls `<>`(). +** Otherwise, calls `ctx.<>()`. For automatic deduction of `Ctx`, use <>. ''' -[[diagnostic_info]] -=== `diagnostic_info` +[[diagnostic_details]] +=== `diagnostic_details` -.#include +.#include [source,c++] ---- namespace boost { namespace leaf { - class diagnostic_info: public error_info + class diagnostic_details: public error_info { //Constructors unspecified - friend std::ostream & operator<<( std::ostream & os, diagnostic_info const & x ); + template + friend std::ostream & operator<<( std::basic_ostream &, diagnostic_details const & ); }; } } ---- -Handlers passed to <>, <> or <> may take an argument of type `diagnostic_info const &` if they need to print diagnostic information about the error. +Handlers passed to error handling functions such as <>, <> or <> may take an argument of type `diagnostic_details const &` if they need to print diagnostic information about the error. -The message printed by `operator<<` includes the message printed by `error_info`, followed by basic information about error objects that were communicated to LEAF (to be associated with the error) for which there was no storage available in any active <> (these error objects were discarded by LEAF, because no handler needed them). +The message printed by `operator<<` includes the message printed by `error_info`, followed by information about error objects that were communicated to LEAF (to be associated with the error) for which there was no storage available in any active <> (these error objects were discarded by LEAF, because no handler needed them). -The additional information is limited to the type name of the first such error object, as well as their total count. +The additional information includes the types and the values of all such error objects (but see <>). [NOTE] -- -The behavior of `diagnostic_info` (and <>) is affected by the value of the macro `BOOST_LEAF_CFG_DIAGNOSTICS`: +The behavior of `diagnostic_details` (and <>) is affected by the value of the macro `BOOST_LEAF_CFG_DIAGNOSTICS`: -* If it is 1 (the default), LEAF produces `diagnostic_info` but only if an active error handling context on the call stack takes an argument of type `diagnostic_info`; -* If it is 0, the `diagnostic_info` functionality is stubbed out even for error handling contexts that take an argument of type `diagnostic_info`. This could shave a few cycles off the error path in some programs (but it is probably not worth it). +* If it is 1 (the default), LEAF produces `diagnostic_details` but only if an active error handling context on the call stack takes an argument of type `diagnostic_details`; +* If it is 0, the `diagnostic_details` functionality is stubbed out even for error handling contexts that take an argument of type `diagnostic_details`. This could save some cycles on the error path in some programs (but is probably not worth it). -- +WARNING: Using `diagnostic_details` may allocate memory dynamically, but only if an active error handler takes an argument of type `diagnostic_details`. + ''' -[[error_id]] -=== `error_id` +[[diagnostic_info]] +=== `diagnostic_info` + +.#include +[source,c++] +---- +namespace boost { namespace leaf { + + class diagnostic_info: public error_info + { + //Constructors unspecified + + template + friend std::ostream & operator<<( std::basic_ostream &, diagnostic_info const & ); + }; + +} } +---- + +Handlers passed to <>, <> or <> may take an argument of type `diagnostic_info const &` if they need to print diagnostic information about the error. + +The message printed by `operator<<` includes the message printed by `error_info`, followed by basic information about error objects that were communicated to LEAF (to be associated with the error) for which there was no storage available in any active <> (these error objects were discarded by LEAF, because no handler needed them). + +The additional information is limited to the type name of the first such error object, as well as their total count. + +[NOTE] +-- +The behavior of `diagnostic_info` (and <>) is affected by the value of the macro `BOOST_LEAF_CFG_DIAGNOSTICS`: + +* If it is 1 (the default), LEAF produces `diagnostic_info` but only if an active error handling context on the call stack takes an argument of type `diagnostic_info`; +* If it is 0, the `diagnostic_info` functionality is stubbed out even for error handling contexts that take an argument of type `diagnostic_info`. This could shave a few cycles off the error path in some programs (but it is probably not worth it). +-- + +[[error_id]] +=== `error_id` .#include [source,c++] @@ -3933,7 +3730,7 @@ namespace boost { namespace leaf { error_id() noexcept; template - result( Enum e, typename std::enable_if::value, Enum>::type * = 0 ) noexcept; + error_id( Enum e, typename std::enable_if::value, Enum>::type * = 0 ) noexcept; error_id( std::error_code const & ec ) noexcept; @@ -3949,7 +3746,8 @@ namespace boost { namespace leaf { template error_id load( Item && ... item ) const noexcept; - friend std::ostream & operator<<( std::ostream & os, error_id x ); + template + friend std::ostream & operator<<( std::basic_ostream &, error_id ); }; bool is_error_id( std::error_code const & ec ) noexcept; @@ -3998,7 +3796,7 @@ TIP: To check if a given `std::error_code` is actually carrying an `error_id`, u Typically, users create new `error_id` objects by invoking <>. The constructor that takes `std::error_code`, and the one that takes a type `Enum` for which `std::is_error_code_enum::value` is `true`, have the following effects: * If `ec.value()` is `0`, the effect is the same as using the default constructor. -* Otherwise, if `<>(ec)` is `true`, the original `error_id` value is used to initialize `*this`; +* Otherwise, if `<>(ec)` is `true`, the original `error_id` value is used to initialize `*this`; * Otherwise, `*this` is initialized by the value returned by <>, while `ec` is passed to `load`, which enables handlers used with `try_handle_some`, `try_handle_all` or `try_catch` to receive it as an argument of type `std::error_code`. ''' @@ -4037,10 +3835,10 @@ namespace boost { namespace leaf { Requires: :: Each of the `Item...` types must be no-throw movable. Effects: :: -* If `value()==0`, all of `item...` are discarded and no further action is taken. +* If `thispass:[->]value()==0`, all of `item...` are discarded and no further action is taken. * Otherwise, what happens with each `item` depends on its type: ** If it is a function that takes a single argument of some type `E &`, that function is called with the object of type `E` currently associated with `*this`. If no such object exists, a default-initialized object is associated with `*this` and then passed to the function. -** If it is a function that takes no arguments, than function is called to obtain an error object, which is associated with `*this`. +** If it is a function that takes no arguments, that function is called to obtain an error object which is associated with `*this`, except in the special case of a `void` function, in which case it is invoked and no error object is obtained/loaded. ** Otherwise, the `item` itself is assumed to be an error object, which is associated with `*this`. Returns: :: `*this`. @@ -4070,7 +3868,7 @@ namespace boost { namespace leaf { These functions have the usual semantics, comparing `a.value()` and `b.value()`. -NOTE: The exact strict weak ordering implemented by `operator<` is not specified. In particular, if for two `error_id` objects `a` and `b`, `a < b` is true, it does not follow that the failure identified by `a` ocurred earlier than the one identified by `b`. +NOTE: The exact strict weak ordering implemented by `operator<` is not specified. In particular, if for two `error_id` objects `a` and `b`, `a < b` is true, it does not follow that the failure identified by `a` occurred earlier than the one identified by `b`. ''' @@ -4161,7 +3959,7 @@ The common usage of this class is as follows: ---- error_code compute_value( int * out_value ) noexcept; <1> -leaf::error augmenter() noexcept +leaf::result augmenter() noexcept { leaf::error_monitor cur_err; <2> @@ -4236,7 +4034,9 @@ namespace boost { namespace leaf { { int value; explicit e_errno(int value=errno); - friend std::ostream & operator<<( std::ostream & os, e_errno const & err ); + + template + friend std::ostream & operator<<( std::basic_ostream &, e_errno const & ); }; } } @@ -4283,7 +4083,9 @@ namespace boost { namespace leaf { #if BOOST_LEAF_CFG_WIN32 e_LastError(); - friend std::ostream & operator<<(std::ostream &, e_LastError const &); + + template + friend std::ostream & operator<<( std::basic_ostream &, e_LastError const & ); #endif }; } @@ -4309,13 +4111,14 @@ namespace boost { namespace leaf { int line; char const * function; - friend std::ostream & operator<<( std::ostream & os, e_source_location const & x ); + template + friend std::ostream & operator<<( std::basic_ostream &, e_source_location const & ); }; } } ---- -The <>, <> and <> macros capture `pass:[__FILE__]`, `pass:[__LINE__]` and `pass:[__FUNCTION__]` into a `e_source_location` object. +The <> and <> macros capture `pass:[__FILE__]`, `pass:[__LINE__]` and `pass:[__FUNCTION__]` into a `e_source_location` object. ''' @@ -4355,7 +4158,8 @@ namespace boost { namespace leaf { bool exception_caught() const noexcept; std::exception const * exception() const noexcept; - friend std::ostream & operator<<( std::ostream & os, error_info const & x ); + template + friend std::ostream & operator<<( std::basic_ostream &, error_info const & ); }; } } @@ -4375,39 +4179,6 @@ The `operator<<` overload prints diagnostic information about each error object ''' -[[polymorphic_context]] -=== `polymorphic_context` - -.#include -[source,c++] ----- -namespace boost { namespace leaf { - - class polymorphic_context - { - protected: - - polymorphic_context() noexcept; - ~polymorphic_context() noexcept; - - public: - - virtual void activate() noexcept = 0; - virtual void deactivate() noexcept = 0; - virtual bool is_active() const noexcept = 0; - - virtual void propagate( error_id ) noexcept = 0; - - virtual void print( std::ostream & ) const = 0; - }; - -} } ----- - -The `polymorphic_context` class is an abstract base type which can be used to erase the type of the exact instantiation of the <> class template used. See <>. - -''' - [[result]] === `result` @@ -4421,48 +4192,66 @@ namespace boost { namespace leaf { { public: + using value_type = T; + + // NOTE: Copy constructor implicitly deleted. + result( result && r ) noexcept; + + template ::value>::type> + result( result && r ) noexcept; + result() noexcept; + result( T && v ) noexcept; - result( T const & v ); - template - result( U &&, <> ); + result( T const & v ); result( error_id err ) noexcept; - result( std::shared_ptr && ctx ) noexcept; - template - result( Enum e, typename std::enable_if::value, Enum>::type * = 0 ) noexcept; + template ::value>::type> + result( U && u ); + +#if BOOST_LEAF_CFG_STD_SYSTEM_ERROR result( std::error_code const & ec ) noexcept; - result( result && r ) noexcept; + template ::value, int>::type> + result( Enum e ) noexcept; - template - result( result && r ) noexcept; +#endif + // NOTE: Assignment operator implicitly deleted. result & operator=( result && r ) noexcept; - template + template ::value>::type> result & operator=( result && r ) noexcept; bool has_value() const noexcept; bool has_error() const noexcept; explicit operator bool() const noexcept; - T const & value() const; - T & value(); + T const & value() const &; + T & value() &; + T const && value() const &&; + T && value() &&; T const * operator->() const noexcept; T * operator->() noexcept; - T const & operator*() const noexcept; - T & operator*() noexcept; + T const & operator*() const & noexcept; + T & operator*() & noexcept; + T const && operator*() const && noexcept; + T && operator*() && noexcept; <> error() noexcept; template error_id load( Item && ... item ) noexcept; + + void unload(); + + template + friend std::ostream & operator<<( std::basic_ostream &, result const & ); }; template <> @@ -4470,40 +4259,54 @@ namespace boost { namespace leaf { { public: + using value_type = void; + + // NOTE: Copy constructor implicitly deleted. + result( result && r ) noexcept; + result() noexcept; result( error_id err ) noexcept; - result( std::shared_ptr && ctx ) noexcept; - template - result( Enum e, typename std::enable_if::value, Enum>::type * = 0 ) noexcept; +#if BOOST_LEAF_CFG_STD_SYSTEM_ERROR result( std::error_code const & ec ) noexcept; - result( result && r ) noexcept; + template ::value, Enum>::type> + result( Enum e ) noexcept; - template - result( result && r ) noexcept; +#endif + // NOTE: Assignment operator implicitly deleted. result & operator=( result && r ) noexcept; - template - result & operator=( result && r ) noexcept; - - bool has_value() const noexcept; - bool has_error() const noexcept; explicit operator bool() const noexcept; void value() const; + void const * operator->() const noexcept; + void * operator->() noexcept; + + void operator*() const noexcept; + <> error() noexcept; template error_id load( Item && ... item ) noexcept; + + void unload(); + + template + friend std::ostream & operator<<( std::basic_ostream &, result const &); }; struct bad_result: std::exception { }; + template + struct is_result_type>: std::true_type + { + }; + } } ---- [.text-right] @@ -4514,9 +4317,9 @@ The `result` type can be returned by functions which produce a value of type Requires: :: `T` must be movable, and its move constructor may not throw. Invariant: :: A `result` object is in one of three states: -* Value state, in which case it contains an object of type `T`, and <>/<>/<> can be used to access the contained value. +* Value state, in which case it contains an object of type `T`, and <> / <> / <> can be used to access the contained value. * Error state, in which case it contains an error ID, and calling <> throws `leaf::bad_result`. -* Error capture state, which is the same as the Error state, but in addition to the error ID, it holds a `std::shared_ptr<<>>`. +* Dynamic capture state, which is the same as the Error state, but in addition to the error ID, it holds a list of dynamically captured error objects; see <>. `result` objects are nothrow-moveable but are not copyable. @@ -4531,49 +4334,51 @@ Invariant: :: A `result` object is in one of three states: ---- namespace boost { namespace leaf { - template - result::result() noexcept; + // NOTE: Copy constructor implicitly deleted. - template - result::result( T && v ) noexcept; <1> + template + result::result( result && r ) noexcept; - template - result::result( T const & v ); <1> + template + template ::value>::type> + result::result( result && r ) noexcept; - template - result::result( U && u, <> ); <2> + template + result::result() noexcept; - template - result::result( leaf::error_id err ) noexcept; + template + result::result( T && v ) noexcept; - template - template - result::result( Enum e, typename std::enable_if::value, Enum>::type * = 0 ) noexcept; + template + result::result( T const & v ); - template - result::result( std::error_code const & ec ) noexcept; + template + result::result( error_id err ) noexcept; - template - result::result( std::shared_ptr && ctx ) noexcept; + template + template ::value>::type> + result::result( U && u ); - template - result::result( result && ) noexcept; +#if BOOST_LEAF_CFG_STD_SYSTEM_ERROR - template - template - result::result( result && ) noexcept; + template + result::result( std::error_code const & ec ) noexcept; + + template + template ::value, int>::type> + result::result( Enum e ) noexcept; + +#endif } } ---- -<1> Not available if `T` is `void`. -<2> Available if an object of type `T` can be initialized with `std::forward(u)`. This is to enable e.g. `result` to be initialized with a string literal. -- Requires: :: `T` must be movable, and its move constructor may not throw; or `void`. Effects: :: -Establishes the `result` invariant: +Establishes the `result` invariants: + -- * To get a `result` in <>, initialize it with an object of type `T` or use the default constructor. @@ -4584,7 +4389,7 @@ CAUTION: Initializing a `result` with a default-initialized `error_id` object + ** a `std::error_code` object. ** an object of type `Enum` for which `std::is_error_code_enum::value` is `true`. -* To get a `result` in <>, initialize it with a `std::shared_ptr<<>>` (which can be obtained by calling e.g. <>). +* To get a `result` in <>, call <>. -- + When a `result` object is initialized with a `std::error_code` object, it is used to initialize an `error_id` object, then the behavior is the same as if initialized with `error_id`. @@ -4748,6 +4553,23 @@ namespace boost { namespace leaf { } } ---- +Effects: + +* If `*this` is in <>, returns a reference to the stored value. +* If `*this` is in <>, the captured error objects are unloaded, and: +** If `*this` contains a captured exception object `ex`, the behavior is equivalent to `<>(ex)`. +** Otherwise, the behavior is equivalent to `<>(bad_result{})`. +* If `*this` is in any other state, the behavior is equivalent to `<>(bad_result{})`. + +''' + +[[result::value_type]] +==== `value_type` + +A member type of `result`, defined as a synonym for `T`. + +''' + [[result::bad_result]] Effects: :: If `*this` is in <>, returns a reference to the stored value, otherwise throws `bad_result`. @@ -4797,39 +4619,40 @@ Returns :: a reference to the stored value. ''' -[[verbose_diagnostic_info]] -=== `verbose_diagnostic_info` +[[show_in_diagnostics]] +=== `show_in_diagnostics` .#include [source,c++] ---- namespace boost { namespace leaf { - class verbose_diagnostic_info: public error_info - { - //Constructors unspecified - - friend std::ostream & operator<<( std::ostream & os, verbose_diagnostic_info const & x ); - }; +template +struct show_in_diagnostics: std::true_type +{ +}; } } ---- -Handlers passed to error handling functions such as <>, <> or <> may take an argument of type `verbose_diagnostic_info const &` if they need to print diagnostic information about the error. - -The message printed by `operator<<` includes the message printed by `error_info`, followed by information about error objects that were communicated to LEAF (to be associated with the error) for which there was no storage available in any active <> (these error objects were discarded by LEAF, because no handler needed them). +This template can be specialized to prevent error objects of sensitive types from appearing in automatically generated diagnostic messages. Example: -The additional information includes the types and the values of all such error objects. +[source,c++] +---- +struct e_user_name +{ + std::string value; +}; -[NOTE] --- -The behavior of `verbose_diagnostic_info` (and <>) is affected by the value of the macro `BOOST_LEAF_CFG_DIAGNOSTICS`: +namespace boost { namespace leaf { -* If it is 1 (the default), LEAF produces `verbose_diagnostic_info` but only if an active error handling context on the call stack takes an argument of type `verbose_diagnostic_info`; -* If it is 0, the `verbose_diagnostic_info` functionality is stubbed out even for error handling contexts that take an argument of type `verbose_diagnostic_info`. This could save some cycles on the error path in some programs (but is probably not worth it). --- + template <> + struct show_in_diagnostics: std::false_type + { + }; -WARNING: Using `verbose_diagnostic_info` may allocate memory dynamically, but only if an active error handler takes an argument of type `verbose_diagnostic_info`. +} } +---- [[predicates]] == Reference: Predicates @@ -4846,7 +4669,7 @@ The following predicates are available: * <> * <> -In addition, any user-defined type `Pred` for which `<>::value` is `true` is treated as a predicate. In this case, it is required that: +In addition, any user-defined type `Pred` for which `<>::value` is `true` is treated as a predicate. In this case, it is required that: * `Pred` defines an accessible member type `error_type` to specify the error object type it requires; * `Pred` defines an accessible static member function `evaluate`, which returns a boolean type, and can be invoked with an object of type `error_type const &`; @@ -4868,7 +4691,7 @@ struct my_pred static bool evaluate(my_error) noexcept; <2> my_error matched; <3> -} +}; namespace boost { namespace leaf { @@ -4893,7 +4716,7 @@ struct my_pred static bool evaluate(leaf::e_errno const &) noexcept; <2> leaf::e_errno const & matched; <3> -} +}; namespace boost { namespace leaf { @@ -5178,7 +5001,7 @@ leaf::try_handle_some( []( leaf::match, enum_b::b2> m ) { <1> static_assert(std::is_same::value); - assert(&m.matched.category() == &std::error_code(enum_{}).category() || m.matched == enum_b::b2); + assert(&m.matched.category() == &std::error_code(enum_a{}).category() || m.matched == enum_b::b2); .... } ); ---- @@ -5217,7 +5040,7 @@ Instead of a set of values, the `match` template can be given pointers to functi .Example 5: Handling of failures with severity::value greater than a specified threshold (requires at least {CPP}17). [source,c++] ---- -struct severity { int value; } +struct severity { int value; }; template constexpr bool severity_greater_than( severity const & e ) noexcept @@ -5342,7 +5165,7 @@ TIP: The contents of each Reference section are organized alphabetically. === `is_predicate` [source,c++] -.#include > +.#include ---- namespace boost { namespace leaf { @@ -5362,7 +5185,7 @@ The `is_predicate` template is used by the <> +.#include ---- namespace boost { namespace leaf { @@ -5381,7 +5204,7 @@ The error handling functionality provided by <> and <` type R, you must specialize the `is_result_type` template so that `is_result_type::value` evaluates to `true`. -Naturally, the provided `leaf::<>` class template satisfies these requirements. In addition, it allows error objects to be transported across thread boundaries, using a `std::shared_ptr<<>>`. +Naturally, the provided `leaf::<>` class template satisfies these requirements. In addition, it allows error objects to be transported across thread boundaries, using a <>. [[macros]] == Reference: Macros @@ -5524,16 +5347,16 @@ If `BOOST_LEAF_CFG_GNUC_STMTEXPR` is `1` (which is the default under `pass:[__GN ''' -[[BOOST_LEAF_EXCEPTION]] -=== `BOOST_LEAF_EXCEPTION` +[[BOOST_LEAF_THROW_EXCEPTION]] +=== `BOOST_LEAF_THROW_EXCEPTION` [source,c++] .#include ---- -#define BOOST_LEAF_EXCEPTION <> +#define BOOST_LEAF_THROW_EXCEPTION <> ---- -Effects: :: `BOOST_LEAF_EXCEPTION(e...)` is equivalent to `leaf::<>(e...)`, except the current source location is automatically passed, in a `<>` object (in addition to all `e...` objects). +Effects: :: `BOOST_LEAF_THROW_EXCEPTION(e...)` is equivalent to `leaf::<>(e...)`, except the current source location is automatically communicated with the thrown exception, in a `<>` object (in addition to all `e...` objects). ''' @@ -5543,28 +5366,139 @@ Effects: :: `BOOST_LEAF_EXCEPTION(e...)` is equivalent to `leaf::< [source,c++] ---- -#define BOOST_LEAF_NEW_ERROR <> +#define BOOST_LEAF_NEW_ERROR <> ---- -Effects: :: `BOOST_LEAF_NEW_ERROR(e...)` is equivalent to `leaf::<>(e...)`, except the current source location is automatically passed, in a `<>` object (in addition to all `e...` objects). +Effects: :: `BOOST_LEAF_NEW_ERROR(e...)` is equivalent to `leaf::<>(e...)`, except the current source location is automatically passed, in a `<>` object (in addition to all `e...` objects). -''' +[[configuration]] +== Configuration -[[BOOST_LEAF_THROW_EXCEPTION]] -=== `BOOST_LEAF_THROW_EXCEPTION` +The following configuration macros are recognized: + +* `BOOST_LEAF_CFG_DIAGNOSTICS`: Defining this macro as `0` stubs out both <> and <> (if the macro is left undefined, LEAF defines it as `1`). + +* `BOOST_LEAF_CFG_STD_SYSTEM_ERROR`: Defining this macro as `0` disables the `std::error_code` / `std::error_condition` integration. In this case LEAF does not `#include `, which may be too heavy for embedded platforms (if the macro is left undefined, LEAF defines it as `1`). + +* `BOOST_LEAF_CFG_STD_STRING`: Defining this macro as `0` disables all use of `std::string` (this requires `BOOST_LEAF_CFG_DIAGNOSTICS=0` as well). In this case LEAF does not `#include ` which may be too heavy for embedded platforms (if the macro is left undefined, LEAF defines it as `1`). + +* `BOOST_LEAF_CFG_CAPTURE`: Defining this macro as `0` disables <>, which (only if used) allocates memory dynamically (if the macro is left undefined, LEAF defines it as `1`). + +* `BOOST_LEAF_CFG_GNUC_STMTEXPR`: This macro controls whether or not <> is defined in terms of a https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html[GNU C statement expression], which enables its use to check for errors similarly to how the questionmark operator works in some languages (see <>). By default the macro is defined as `1` under `pass:[__GNUC__]`, otherwise as `0`. + +* `BOOST_LEAF_CFG_WIN32`: This macro controls the use of Win32 APIs. If left undefined, LEAF defines it as `0` (even on Windows, since including `windows.h` is generally not desirable). The possible values are: +** `0`: Disables all Win32-specific features. +** `1`: Includes `windows.h` and enables <> support, which is otherwise stubbed out. +** `2`: In addition, switches LEAF to using the Win32 TLS API instead of {CPP}11 `thread_local`, enabling error objects to be used across DLL boundaries. + +* `BOOST_LEAF_NO_EXCEPTIONS`: Disables all exception handling support. If left undefined, LEAF defines it automatically based on the compiler configuration (e.g. `-fno-exceptions`). + +* `BOOST_LEAF_NO_THREADS`: Disables all thread safety in LEAF. + +[[configuring_tls_access]] +=== Configuring TLS Access + +LEAF requires support for thread-local `void` pointers. The available TLS implementations are: + +** {CPP}11 `thread_local` keyword (the default). +** Win32 TLS API: selected by defining `BOOST_LEAF_CFG_WIN32=2`. This enables error objects to be used across DLL boundaries. +** Custom TLS array: selected by defining `BOOST_LEAF_USE_TLS_ARRAY`. This is intended for <> where the {CPP}11 `thread_local` keyword is not available or not suitable. + +When using `BOOST_LEAF_USE_TLS_ARRAY`, the user is required to define the following two functions to implement the required TLS access: [source,c++] -.#include ---- -#define BOOST_LEAF_THROW_EXCEPTION throw BOOST_LEAF_EXCEPTION +namespace boost { namespace leaf { + +namespace tls +{ + void * read_void_ptr( int tls_index ) noexcept; + void write_void_ptr( int tls_index, void * p ) noexcept; +} + +} } ---- -Effects: :: Throws the exception object returned by <>. +TIP: For efficiency, `read_void_ptr` and `write_void_ptr` should be defined `inline`. -[[rationale]] -== Design +Under `BOOST_LEAF_USE_TLS_ARRAY` the following additional configuration macros are recognized: + +* `BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX` specifies the start TLS array index available to LEAF (if the macro is left undefined, LEAF defines it as `0`). + +* `BOOST_LEAF_CFG_TLS_ARRAY_SIZE` may be defined to specify the size of the TLS array. In this case TLS indices are validated via `BOOST_LEAF_ASSERT` before being passed to `read_void_ptr` / `write_void_ptr`. + +* `BOOST_LEAF_CFG_TLS_INDEX_TYPE` may be defined to specify the integral type used to store assigned TLS indices (if the macro is left undefined, LEAF defines it as `unsigned char`). + +TIP: TLS slots are allocated only for types used in error handlers. The minimum size of the TLS pointer array required by LEAF is the total number of different types used as arguments to error handlers (in the entire program), plus one. + +WARNING: Beware of `read_void_ptr`/`write_void_ptr` accessing thread local pointers beyond the static boundaries of the thread local pointer array; this will likely result in undefined behavior. + +[[embedded_platforms]] +=== Embedded Platforms + +Defining `BOOST_LEAF_EMBEDDED` is equivalent to the following: + +[source,c++] +---- +#ifndef BOOST_LEAF_CFG_DIAGNOSTICS +# define BOOST_LEAF_CFG_DIAGNOSTICS 0 +#endif + +#ifndef BOOST_LEAF_CFG_STD_SYSTEM_ERROR +# define BOOST_LEAF_CFG_STD_SYSTEM_ERROR 0 +#endif + +#ifndef BOOST_LEAF_CFG_STD_STRING +# define BOOST_LEAF_CFG_STD_STRING 0 +#endif + +#ifndef BOOST_LEAF_CFG_CAPTURE +# define BOOST_LEAF_CFG_CAPTURE 0 +#endif +---- + +LEAF supports FreeRTOS out of the box, define `BOOST_LEAF_TLS_FREERTOS` (in which case LEAF automatically defines `BOOST_LEAF_EMBEDDED`, if it is not defined already). + +For other embedded platforms, define `BOOST_LEAF_USE_TLS_ARRAY`, see <>. + +If your program does not use concurrency at all, simply define `BOOST_LEAF_NO_THREADS`, which requires no TLS support at all (but is NOT thread-safe). + +TIP: Contrary to popular belief, exception handling works great on embedded platforms. In https://www.youtube.com/watch?v=BGmzMuSDt-Y[this talk] Khalil Estell demonstrates that using exceptions to handle errors leads to a significant reduction in firmware code size (of course LEAF works with or without exception handling). + +[[portability]] +== Portability + +The source code is compatible with {CPP}11 or newer. + +== Running the Unit Tests + +The unit tests can be run with https://mesonbuild.com[Meson Build] or with Boost Build. To run the unit tests: + +=== Meson Build + +Clone LEAF into any local directory and execute: + +[source,sh] +---- +cd leaf +meson setup _bld/debug +cd _bld/debug +meson test +---- + +See `meson_options.txt` found in the root directory for available build options. + +=== Boost Build + +Assuming the current working directory is `/libs/leaf`: + +[source,sh] +---- +../../b2 test +---- -=== Rationale +[[rationale]] +== Design Rationale Definition: :: Objects that carry information about error conditions are called error objects. For example, objects of type `std::error_code` are error objects. @@ -5575,7 +5509,7 @@ Definition: :: Depending on their interaction with error objects, functions can * *Error neutral*: functions that forward to the caller error objects communicated by lower-level functions they call. * *Error handling*: functions that dispose of error objects they have received, recovering normal program operation. -A crucial observation is that _error initiating_ functions are typically low-level functions that lack any context and can not determine, much less dictate, the correct program behavior in response to the errors they may initiate. Error conditions which (correctly) lead to termination in some programs may (correctly) be ignored in others; yet other programs may recover from them and resume normal operation. +A crucial observation is that _error initiating_ functions are typically low level functions that lack any context and can not determine, much less dictate, the correct program behavior in response to the errors they may initiate. Error conditions which (correctly) lead to termination in some programs may (correctly) be ignored in others; yet other programs may recover from them and resume normal operation. The same reasoning applies to _error neutral_ functions, but in this case there is the additional issue that the errors they need to communicate, in general, are initiated by functions multiple levels removed from them in the call chain, functions which usually are -- and should be treated as -- implementation details. An _error neutral_ function should not be coupled with error object types communicated by _error initiating_ functions, for the same reason it should not be coupled with any other aspect of their interface. @@ -5597,499 +5531,77 @@ Fact: :: For example, if a library function is able to communicate an error code but the program does not need to know the exact error code, then that information may be ignored at the time the library function attempts to communicate it. On the other hand, if an _error handling_ function needs that information, the memory needed to store it can be reserved statically in its scope. -The LEAF functions <>, <> and <> implement this idea. Users provide error handling lambda functions, each taking arguments of the types it needs in order to recover from a particular error condition. LEAF simply provides the space needed to store these types (in the form of a `std::tuple`, using automatic storage duration) until they are passed to a suitable handler. +The LEAF functions <>, <> and <> implement this idea. Users provide error handling lambda functions, each taking arguments of the types it needs in order to recover from a particular error condition. LEAF reserves storage for these types (using automatic storage duration) until they are passed to a suitable handler. + +When an error is reported, LEAF checks if storage is available for each error object type: -At the time this space is reserved in the scope of an error handling function, `thread_local` pointers of the required error types are set to point to the corresponding objects within it. Later on, _error initiating_ or _error neutral_ functions wanting to communicate an error object of a given type `E` use the corresponding `thread_local` pointer to detect if there is currently storage available for this type: +* If storage is available, the object is stored directly in the error handling scope, bypassing all _error neutral_ functions in between. +* If storage is not available, the error object is discarded, since no error handling function makes any use of it -- saving resources. -* If the pointer is not null, storage is available and the object is moved into the pointed storage, exactly once -- regardless of how many levels of function calls must unwind before an _error handling_ function is reached. -* If the pointer is null, storage is not available and the error object is discarded, since no error handling function makes any use of it in this program -- saving resources. +Each error occurrence is assigned a unique <>, which prevents handlers from accessing stale error objects from previous failures. To handle a failure, LEAF matches the available error objects (by their `error_id`) with the argument types required by each handler. -This almost works, except we need to make sure that _error handling_ functions are protected from accessing stale error objects stored in response to previous failures, which would be a serious logic error. To this end, each occurrence of an error is assigned a unique <>. Each of the `E...` objects stored in error handling scopes is assigned an `error_id` as well, permanently associating it with a particular failure. +== Dynamic Linking -Thus, to handle a failure we simply match the available error objects (associated with its unique `error_id`) with the argument types required by each user-provided error handling function. In terms of {CPP} exception handling, it is as if we could write something like: +=== POSIX + +When compiling with `-fvisibility=hidden`, error types must be declared with `default` visibility. It is recommended to use `BOOST_LEAF_SYMBOL_VISIBLE`, which expands to the appropriate attribute on POSIX and to nothing on Windows: [source,c++] ---- -try +struct BOOST_LEAF_SYMBOL_VISIBLE my_error_info { - auto r = process_file(); + int value; +}; +---- - //Success, use r: - .... -} +LEAF declares the following types with `BOOST_LEAF_SYMBOL_VISIBLE`: `error_id`, `error_info`, `diagnostic_info`, `diagnostic_details`, `e_api_function`, `e_file_name`, `e_errno`, `e_type_info_name`, `e_at_line`, `e_source_location`, `bad_result`, `result`. -catch(file_read_error &, e_file_name const & fn, e_errno const & err) -{ - std::cerr << - "Could not read " << fn << ", errno=" << err << std::endl; -} +=== Windows -catch(file_read_error &, e_errno const & err) -{ - std::cerr << - "File read error, errno=" << err << std::endl; -} +To use error objects across DLL boundaries, define `BOOST_LEAF_CFG_WIN32=2`. This switches LEAF to using the Win32 TLS API instead of {CPP}11 `thread_local`. Dynamic unloading of DLLs is not supported. -catch(file_read_error &) -{ - std::cerr << "File read error!" << std::endl; -} ----- - -Of course this syntax is not valid, so LEAF uses lambda functions to express the same idea: - -[source,c++] ----- -leaf::try_catch( - - [] - { - auto r = process_file(); //Throws in case of failure, error objects stored inside the try_catch scope - - //Success, use r: - .... - } - - [](file_read_error &, e_file_name const & fn, e_errno const & err) - { - std::cerr << - "Could not read " << fn << ", errno=" << err << std::endl; - }, - - [](file_read_error &, e_errno const & err) - { - std::cerr << - "File read error, errno=" << err << std::endl; - }, - - [](file_read_error &) - { - std::cerr << "File read error!" << std::endl; - } ); ----- - -[.text-right] -<> | <> | <> - -Similar syntax works without exception handling as well. Below is the same snippet, written using `<>`: - -[source,c++] ----- -return leaf::try_handle_some( - - []() -> leaf::result - { - BOOST_LEAF_AUTO(r, process_file()); //In case of errors, error objects are stored inside the try_handle_some scope - - //Success, use r: - .... - - return { }; - } - - [](leaf::match, e_file_name const & fn, e_errno const & err) - { - std::cerr << - "Could not read " << fn << ", errno=" << err << std::endl; - }, - - [](leaf::match, e_errno const & err) - { - std::cerr << - "File read error, errno=" << err << std::endl; - }, - - [](leaf::match) - { - std::cerr << "File read error!" << std::endl; - } ); ----- - -[.text-right] -<> | <> | <> | <> | <> - -NOTE: Please post questions and feedback on the Boost Developers Mailing List. - -''' - -[[exception_specifications]] -=== Critique 1: Error Types Do Not Participate in Function Signatures - -A knee-jerk critique of the LEAF design is that it does not statically enforce that each possible error condition is recognized and handled by the program. One idea I've heard from multiple sources is to add `E...` parameter pack to `result`, essentially turning it into `expected`, so we could write something along these lines: - -[source,c++] ----- -expected f() noexcept; <1> - -expected g() noexcept <2> -{ - if( expected r = f() ) - { - return r; //Success, return the T - } - else - { - return r.handle_error( [] ( .... ) <3> - { - .... - } ); - } -} ----- -<1> `f` may only return error objects of type `E1`, `E2`, `E3`. -<2> `g` narrows that to only `E1` and `E3`. -<3> Because `g` may only return error objects of type `E1` and `E3`, it uses `handle_error` to deal with `E2`. In case `r` contains `E1` or `E3`, `handle_error` simply returns `r`, narrowing the error type parameter pack from `E1, E2, E3` down to `E1, E3`. If `r` contains an `E2`, `handle_error` calls the supplied lambda, which is required to return one of `E1`, `E3` (or a valid `T`). - -The motivation here is to help avoid bugs in functions that handle errors that pop out of `g`: as long as the programmer deals with `E1` and `E3`, he can rest assured that no error is left unhandled. - -Congratulations, we've just discovered exception specifications. The difference is that exception specifications, before being removed from {CPP}, were enforced dynamically, while this idea is equivalent to statically-enforced exception specifications, like they are in Java. - -Why not use the equivalent of exception specifications, even if they are enforced statically? - -"The short answer is that nobody knows how to fix exception specifications in any language, because the dynamic enforcement {CPP} chose has only different (not greater or fewer) problems than the static enforcement Java chose. ... When you go down the Java path, people love exception specifications until they find themselves all too often encouraged, or even forced, to add `throws Exception`, which immediately renders the exception specification entirely meaningless. (Example: Imagine writing a Java generic that manipulates an arbitrary type `T`).footnote:[https://herbsutter.com/2007/01/24/questions-about-exception-specifications/]" --- Herb Sutter - -Consider again the example above: assuming we don't want important error-related information to be lost, values of type `E1` and/or `E3` must be able to encode any `E2` value dynamically. But like Sutter points out, in generic contexts we don't know what errors may result in calling a user-supplied function. The only way around that is to specify a single type (e.g. `std::error_code`) that can communicate any and all errors, which ultimately defeats the idea of using static type checking to enforce correct error handling. - -That said, in every program there are certain _error handling_ functions (e.g. `main`) which are required to handle any error, and it is highly desirable to be able to enforce this requirement at compile-time. In LEAF, the `try_handle_all` function implements this idea: if the user fails to supply at least one handler that will match any error, the result is a compile error. This guarantees that the scope invoking `try_handle_all` is prepared to recover from any failure. - -''' - -[[translation]] -=== Critique 2: LEAF Does Not Facilitate Mapping Between Different Error Types - -Most {CPP} programs use multiple C and {CPP} libraries, and each library may provide its own system of error codes. But because it is difficult to define static interfaces that can communicate arbitrary error code types, a popular idea is to map each library-specific error code to a common program-wide enum. - -For example, if we have -- - -[source,c++,options="nowrap"] ----- -namespace lib_a -{ - enum error - { - ok, - ec1, - ec2, - .... - }; -} ----- - -[source,c++,options="nowrap"] ----- -namespace lib_b -{ - enum error - { - ok, - ec1, - ec2, - .... - }; -} ----- - --- we could define: - -[source,c++] ----- -namespace program -{ - enum error - { - ok, - lib_a_ec1, - lib_a_ec2, - .... - lib_b_ec1, - lib_b_ec2, - .... - }; -} ----- - -An error handling library could provide conversion API that uses the {CPP} static type system to automate the mapping between the different error enums. For example, it may define a class template `result` with value-or-error variant semantics, so that: - -* `lib_a` errors are transported in `result`, -* `lib_b` errors are transported in `result`, -* then both are automatically mapped to `result` once control reaches the appropriate scope. - -There are several problems with this idea: - -* It is prone to errors, both during the initial implementation as well as under maintenance. - -* It does not compose well. For example, if both of `lib_a` and `lib_b` use `lib_c`, errors that originate in `lib_c` would be obfuscated by the different APIs exposed by each of `lib_a` and `lib_b`. - -* It presumes that all errors in the program can be specified by exactly one error code, which is false. - -To elaborate on the last point, consider a program that attempts to read a configuration file from three different locations: in case all of the attempts fail, it should communicate each of the failures. In theory `result` handles this case well: - -[source,c++] ----- -struct attempted_location -{ - std::string path; - error ec; -}; - -struct config_error -{ - attempted_location current_dir, user_dir, app_dir; -}; - -result read_config(); ----- - -This looks nice, until we realize what the `config_error` type means for the automatic mapping API we wanted to define: an `enum` can not represent a `struct`. It is a fact that we can not assume that all error conditions can be fully specified by an `enum`; an error handling library must be able to transport arbitrary static types efficiently. - -[[errors_are_not_implementation_details]] -=== Critique 3: LEAF Does Not Treat Low Level Error Types as Implementation Details - -This critique is a combination of <> and <>, but it deserves special attention. Let's consider this example using LEAF: - -[source,c++] ----- -leaf::result read_line( reader & r ); - -leaf::result parse_line( std::string const & line ); - -leaf::result read_and_parse_line( reader & r ) -{ - BOOST_LEAF_AUTO(line, read_line(r)); <1> - BOOST_LEAF_AUTO(parsed, parse_line(line)); <2> - return parsed; -} ----- -[.text-right] -<> | <> - -<1> Read a line, forward errors to the caller. -<2> Parse the line, forward errors to the caller. - -The objection is that LEAF will forward verbatim the errors that are detected in `read_line` or `parse_line` to the caller of `read_and_parse_line`. The premise of this objection is that such low-level errors are implementation details and should be treated as such. Under this premise, `read_and_parse_line` should act as a translator of sorts, in both directions: - -* When called, it should translate its own arguments to call `read_line` and `parse_line`; -* If an error is detected, it should translate the errors from the error types returned by `read_line` and `parse_line` to a higher-level type. - -The motivation is to isolate the caller of `read_and_parse_line` from its implementation details `read_line` and `parse_line`. - -There are two possible ways to implement this translation: - -*1)* `read_and_parse_line` understands the semantics of *all possible failures* that may be reported by both `read_line` and `parse_line`, implementing a non-trivial mapping which both _erases_ information that is considered not relevant to its caller, as well as encodes _different_ semantics in the error it reports. In this case `read_and_parse_line` assumes full responsibility for describing precisely what went wrong, using its own type specifically designed for the job. - -*2)* `read_and_parse_line` returns an error object that essentially indicates which of the two inner functions failed, and also transports the original error object without understanding its semantics and without any loss of information, wrapping it in a new error type. - -The problem with *1)* is that typically the caller of `read_and_parse_line` is not going to handle the error, but it does need to forward it to its caller. In our attempt to protect the *one* error handling function from "implementation details", we've coupled the interface of *all* intermediate error neutral functions with the static types of errors they do not understand and do not handle. - -Consider the case where `read_line` communicates `errno` in its errors. What is `read_and_parse_line` supposed to do with e.g. `EACCESS`? Turn it into `READ_AND_PARSE_LINE_EACCESS`? To what end, other than to obfuscate the original (already complex and platform-specific) semantics of `errno`? - -And what if the call to `read` is polymorphic, which is also typical? What if it involves a user-supplied function object? What kinds of errors does it return and why should `read_and_parse_line` care? - -Therefore, we're left with *2)*. There's almost nothing wrong with this option, since it passes any and all error-related information from lower level functions without any loss. However, using a wrapper type to grant (presumably dynamic) access to any lower-level error type it may be transporting is cumbersome and (like Niall Douglas <>) in general probably requires dynamic allocations. It is better to use independent error types that communicate the additional information not available in the original error object, while error handlers rely on LEAF to provide efficient access to any and all low-level error types, as needed. +Modules linked against different CRT configurations (static or dynamic) can share LEAF error objects. However, for two modules to share error objects, they must be compiled with the same compiler (not necessarily the same compiler version). For example, if one module is compiled with MSVC and another with GCC, error objects will not be shared between them. == Alternatives to LEAF -* https://www.boost.org/doc/libs/release/libs/exception/doc/boost-exception.html[Boost Exception] +* https://en.cppreference.com/w/cpp/utility/expected[`std::expected`] (C++23) * https://ned14.github.io/outcome[Boost Outcome] -* https://github.com/TartanLlama/expected[`tl::expected`] - -Below we offer a comparison of Boost LEAF to Boost Exception and to Boost Outcome. - -[[boost_exception]] -=== Comparison to Boost Exception - -While LEAF can be used without exception handling, in the use case when errors are communicated by throwing exceptions, it can be viewed as a better, more efficient alternative to Boost Exception. LEAF has the following advantages over Boost Exception: - -* LEAF does not allocate memory dynamically; -* LEAF does not waste system resources communicating error objects not used by specific error handling functions; -* LEAF does not store the error objects in the exception object, and therefore it is able to augment exceptions thrown by external libraries (Boost Exception can only augment exceptions of types that derive from `boost::exception`). - -The following tables outline the differences between the two libraries which should be considered when code that uses Boost Exception is refactored to use LEAF instead. - -NOTE: It is possible to access Boost Exception error information using the LEAF error handling interface. See <>. - -.Defining a custom type for transporting values of type T -[cols="1a,1a",options="header",stripes=none] -|==== -| Boost Exception | LEAF -| -[source,c++,options="nowrap"] ----- -typedef error_info my_info; ----- -[.text-right] -https://www.boost.org/doc/libs/release/libs/exception/doc/error_info.html[`boost::error_info`] -| -[source,c++,options="nowrap"] ----- -struct my_info { T value; }; ----- -|==== - -.Passing arbitrary info at the point of the throw -[cols="1a,1a",options="header",stripes=none] -|==== -| Boost Exception | LEAF -| -[source,c++,options="nowrap"] ----- -throw my_exception() << - my_info(x) << - my_info(y); ----- -[.text-right] -https://www.boost.org/doc/libs/release/libs/exception/doc/exception_operator_shl.html[`operator<<`] -| -[source,c++,options="nowrap"] ----- -throw leaf::exception( my_exception(), - my_info{x}, - my_info{y} ); ----- -[.text-right] -<> -|==== - -.Augmenting exceptions in error neutral contexts -[cols="1a,1a",options="header",stripes=none] -|==== -| Boost Exception | LEAF -| -[source,c++,options="nowrap"] ----- -try -{ - f(); -} -catch( boost::exception & e ) -{ - e << my_info(x); - throw; -} ----- -[.text-right] -https://www.boost.org/doc/libs/release/libs/exception/doc/exception.html[`boost::exception`] \| https://www.boost.org/doc/libs/release/libs/exception/doc/exception_operator_shl.html[`operator<<`] -| -[source,c++,options="nowrap"] ----- -auto load = leaf::on_error( my_info{x} ); - -f(); ----- -[.text-right] -<> -|==== +* https://www.boost.org/doc/libs/release/libs/exception/doc/boost-exception.html[Boost Exception] -.Obtaining arbitrary info at the point of the catch -[cols="1a,1a",options="header",stripes=none] -|==== -| Boost Exception | LEAF -| -[source,c++,options="nowrap"] ----- -try -{ - f(); -} -catch( my_exception & e ) -{ - if( T * v = get_error_info(e) ) - { - //my_info is available in e. - } -} ----- -[.text-right] -https://www.boost.org/doc/libs/release/libs/exception/doc/get_error_info.html[`boost::get_error_info`] -| -[source,c++,options="nowrap"] ----- -leaf::try_catch( - [] - { - f(); // throws - } - [](my_exception &, my_info const & x) - { - //my_info is available with - //the caught exception. - } ); ----- -[.text-right] -<> -|==== +Below we offer a comparison of Boost LEAF to these alternatives. -.Transporting of error objects -[cols="1a,1a",options="header",stripes=none] -|==== -| Boost Exception | LEAF -| All supplied https://www.boost.org/doc/libs/release/libs/exception/doc/error_info.html[`boost::error_info`] objects are allocated dynamically and stored in the https://www.boost.org/doc/libs/release/libs/exception/doc/exception.html[`boost::exception`] subobject of exception objects. -| User-defined error objects are stored statically in the scope of <>, but only if their types are needed to handle errors; otherwise they are discarded. -|==== +[[std_expected]] +=== Comparison to `std::expected` -.Transporting of error objects across thread boundaries -[cols="1a,1a",options="header",stripes=none] -|==== -| Boost Exception | LEAF -| https://www.boost.org/doc/libs/release/libs/exception/doc/exception_ptr.html[`boost::exception_ptr`] automatically captures https://www.boost.org/doc/libs/release/libs/exception/doc/error_info.html[`boost::error_info`] objects stored in a `boost::exception` and can transport them across thread boundaries. -| Transporting error objects across thread boundaries requires the use of <>. -|==== +`std::expected`, introduced in C++23, is a vocabulary type for functions that return either a value of type `T` or an error of type `E`. It is similar to `leaf::result` in purpose but differs in design: -.Printing of error objects in automatically-generated diagnostic information messages -[cols="1a,1a",options="header",stripes=none] -|==== -| Boost Exception | LEAF -| `boost::error_info` types may define conversion to `std::string` by providing `to_string` overloads *or* by overloading `operator<<` for `std::ostream`. -| LEAF does not use `to_string`. Error types may define `operator<<` overloads for `std::ostream`. -|==== +* `std::expected` encodes the error type `E` in the function signature. `leaf::result` does not specify an error type; error objects are transported separately. +* With `std::expected`, a function can only return a single error object of type `E`. LEAF allows associating multiple error objects of different types with a single failure. +* LEAF's <> allows intermediate functions to attach additional context as errors propagate, without modifying function signatures. -[WARNING] -==== -The fact that Boost Exception stores all supplied `boost::error_info` objects -- while LEAF discards them if they aren't needed -- affects the completeness of the message we get when we print `leaf::<>` objects, compared to the string returned by https://www.boost.org/doc/libs/release/libs/exception/doc/diagnostic_information.html[`boost::diagnostic_information`]. - -If the user requires a complete diagnostic message, the solution is to use `leaf::<>`. In this case, before unused error objects are discarded by LEAF, they are converted to string and printed. Note that this allocates memory dynamically. -==== +The choice between them depends on whether encoding error types in function signatures is desired, and whether associating multiple error objects with a single failure is needed. ''' [[boost_outcome]] === Comparison to Boost Outcome -==== Design Differences - -Like LEAF, the https://ned14.github.io/outcome[Boost Outcome] library is designed to work in low latency environments. It provides two class templates, `result<>` and `outcome<>`: - -* `result` can be used as the return type in `noexcept` functions which may fail, where `T` specifies the type of the return value in case of success, while `EC` is an "error code" type. Semantically, `result` is similar to `std::variant`. Naturally, `EC` defaults to `std::error_code`. -* `outcome` is similar to `result<>`, but in case of failure, in addition to the "error code" type `EC` it can hold a "pointer" object of type `EP`, which defaults to `std::exception_ptr`. - -NOTE: `NVP` is a policy type used to customize the behavior of `.value()` when the `result<>` or the `outcome<>` object contains an error. - -The idea is to use `result<>` to communicate failures which can be fully specified by an "error code", and `outcome<>` to communicate failures that require additional information. - -Another way to describe this design is that `result<>` is used when it suffices to return an error object of some static type `EC`, while `outcome<>` can also transport a polymorphic error object, using the pointer type `EP`. +Like LEAF, https://ned14.github.io/outcome[Boost Outcome] is designed for low latency environments. It provides `result` and `outcome`, where `EC` is an error code type (defaulting to `std::error_code`) and `EP` is a pointer type for additional error information (defaulting to `std::exception_ptr`). -NOTE: In the default configuration of `outcome` the additional information -- or the additional polymorphic object -- is an exception object held by `std::exception_ptr`. This targets the use case when an exception thrown by a lower-level library function needs to be transported through some intermediate contexts that are not exception-safe, to a higher-level context able to handle it. LEAF directly supports this use as well, see <>. +The key design difference is in how error information is transported: -Similar reasoning drives the design of LEAF as well. The difference is that while both libraries recognize the need to transport "something else" in addition to an "error code", LEAF provides an efficient solution to this problem, while Outcome shifts this burden to the user. - -The `leaf::result<>` template deletes both `EC` and `EP`, which decouples it from the type of the error objects that are transported in case of a failure. This enables lower-level functions to freely communicate anything and everything they "know" about the failure: error code, even multiple error codes, file names, URLs, port numbers, etc. At the same time, the higher-level error handling functions control which of this information is needed in a specific client program and which is not. This is ideal, because: - -* Authors of lower-level library functions lack context to determine which of the information that is both relevant to the error _and_ naturally available to them needs to be communicated in order for a particular client program to recover from that error; -* Authors of higher-level error handling functions can easily and confidently make this determination, which they communicate naturally to LEAF, by simply writing the different error handlers. LEAF will transport the needed error objects while discarding the ones handlers don't care to use, saving resources. +* Outcome encodes error types in function signatures via the `EC` and `EP` template parameters, giving callers explicit visibility of possible error types. +* LEAF decouples `leaf::result` from error types entirely. Error objects are transported separately to error handling scopes, where the handlers determine which types are needed. TIP: The LEAF examples include an adaptation of the program from the https://ned14.github.io/outcome/tutorial/essential/result/[Boost Outcome `result<>` tutorial]. You can https://github.com/boostorg/leaf/blob/master/example/print_half.cpp?ts=4[view it on GitHub]. -NOTE: Programs using LEAF for error handling are not required to use `leaf::result`; for example, it is possible to use `outcome::result` with LEAF. +NOTE: LEAF is compatible with `outcome::result`; you don't have to use `leaf::result`. [[interoperability]] ==== The Interoperability Problem -The Boost Outcome documentation discusses the important problem of bringing together multiple libraries -- each using its own error reporting mechanism -- and incorporating them in a robust error handling infrastructure in a client program. - -Users are advised that whenever possible they should use a common error handling system throughout their entire codebase, but because this is not practical, both the `result<>` and the `outcome<>` templates can carry user-defined "payloads". +The Boost Outcome documentation discusses the challenge of integrating multiple libraries with different error types: -The following analysis is from the Boost Outcome documentation: ==== If library A uses `result`, and library B uses `result` and so on, there becomes a problem for the application writer who is bringing in these third party dependencies and tying them together into an application. As a general rule, each third party library author will not have built in explicit interoperation support for unknown other third party libraries. The problem therefore lands with the application writer. @@ -6097,157 +5609,27 @@ The application writer has one of three choices: . In the application, the form of result used is `result>` where `E1, E2 …` are the failure types for every third party library in use in the application. This has the advantage of preserving the original information exactly, but comes with a certain amount of use inconvenience and maybe excessive coupling between high level layers and implementation detail. -. One can translate/map the third party’s failure type into the application’s failure type at the point of the failure exiting the third party library and entering the application. One might do this, say, with a C preprocessor macro wrapping every invocation of the third party API from the application. This approach may lose the original failure detail, or mis-map under certain circumstances if the mapping between the two systems is not one-one. +. One can translate/map the third party's failure type into the application's failure type at the point of the failure exiting the third party library and entering the application. One might do this, say, with a C preprocessor macro wrapping every invocation of the third party API from the application. This approach may lose the original failure detail, or mis-map under certain circumstances if the mapping between the two systems is not one-one. -. One can type erase the third party’s failure type into some application failure type, which can later be reconstituted if necessary. *This is the cleanest solution with the least coupling issues and no problems with mis-mapping*, but it almost certainly requires the use of `malloc` which the previous two did not. +. One can type erase the third party's failure type into some application failure type, which can later be reconstituted if necessary. *This is the cleanest solution with the least coupling issues and no problems with mis-mapping*, but it almost certainly requires the use of `malloc` which the previous two did not. ==== -The analysis above (emphasis added) is clear and precise, but LEAF and Boost Outcome tackle the interoperability problem differently: - -* The Boost Outcome design asserts that the "cleanest" solution based on type-erasure is suboptimal ("almost certainly requires the use of `malloc`pass:[]"), and instead provides a system for injecting custom converters into the `outcome::convert` namespace, used to translate between library-specific and program-wide error types, even though this approach "may lose the original failure detail". - -* The LEAF design asserts that coupling the signatures of <> functions with the static types of the error objects they need to forward to the caller <>, and instead transports error objects directly to error handling scopes where they are stored statically, effectively implementing the third choice outlined above (without the use of `malloc`). - -Further, consider that Outcome aims to hopefully become _the_ one error handling API all libraries would use, and in theory everyone would benefit from uniformity and standardization. But the reality is that this is wishful thinking. In fact, that reality is reflected in the design of `outcome::result<>`, in its lack of commitment to using `std::error_code` for its intended purpose: to be _the_ standard type for transporting error codes. The fact is that `std::error_code` became _yet another_ error code type programmers need to understand and support. - -In contrast, the design of LEAF acknowledges that {CPP} programmers don't even agree on what a string is. If your project uses 10 different libraries, this probably means 15 different ways to report errors, sometimes across uncooperative interfaces (e.g. C APIs). LEAF helps you get the job done. - -== Benchmark - -https://github.com/boostorg/leaf/blob/master/benchmark/benchmark.md[This benchmark] compares the performance of LEAF, Boost Outcome and `tl::expected`. - -== Running the Unit Tests - -The unit tests can be run with https://mesonbuild.com[Meson Build] or with Boost Build. To run the unit tests: - -=== Meson Build - -Clone LEAF into any local directory and execute: - -[source,sh] ----- -cd leaf -meson bld/debug -cd bld/debug -meson test ----- - -See `meson_options.txt` found in the root directory for available build options. - -=== Boost Build - -Assuming the current working directory is `/libs/leaf`: - -[source,sh] ----- -../../b2 test ----- - -[[configuration]] -== Configuration - -The following configuration macros are recognized: - -* `BOOST_LEAF_CFG_DIAGNOSTICS`: Defining this macro as `0` stubs out both <> and <> (if the macro is left undefined, LEAF defines it as `1`). - -* `BOOST_LEAF_CFG_STD_SYSTEM_ERROR`: Defining this macro as `0` disables the `std::error_code` / `std::error_condition` integration. In this case LEAF does not `#include `, which may be too heavy for embedded platforms (if the macro is left undefined, LEAF defines it as `1`). - -* `BOOST_LEAF_CFG_STD_STRING`: Defining this macro as `0` disables all use of `std::string` (this requires `BOOST_LEAF_CFG_DIAGNOSTICS=0` as well). In this case LEAF does not `#include ` which may be too heavy for embedded platforms (if the macro is left undefined, LEAF defines it as `1`). - -* `BOOST_LEAF_CFG_CAPTURE`: Defining this macro as `0` disables the ability of `leaf::result` to transport errors between threads. In this case LEAF does not `#include `, which may be too heavy for embedded platforms (if the macro is left undefined, LEAF defines it as `1`). - -* `BOOST_LEAF_CFG_GNUC_STMTEXPR`: This macro controls whether or not <> is defined in terms of a https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html[GNU C statement expression], which enables its use to check for errors similarly to how the questionmark operator works in some languages (see <>). By default the macro is defined as `1` under `pass:[__GNUC__]`, otherwise as `0`. - -* `BOOST_LEAF_CFG_WIN32`: Defining this macro as 1 enables the default constructor in <>, and the automatic conversion to string (via `FormatMessageA`) when <> is printed. If the macro is left undefined, LEAF defines it as `0` (even on windows, since including `windows.h` is generally not desirable). Note that the `e_LastError` type itself is available on all platforms, there is no need for conditional compilation in error handlers that use it. - -* `BOOST_LEAF_NO_EXCEPTIONS`: Disables all exception handling support. If left undefined, LEAF defines it automatically based on the compiler configuration (e.g. `-fno-exceptions`). - -* `BOOST_LEAF_NO_THREADS`: Disables all thread safety in LEAF. - -[[configuring_tls_access]] -=== Configuring TLS Access - -LEAF requires support for thread-local `void` pointers. By default, this is implemented by means of the {CPP}11 `thread_local` keyword, but in order to support <>, it is possible to configure LEAF to use an array of thread local pointers instead, by defining `BOOST_LEAF_USE_TLS_ARRAY`. In this case, the user is required to define the following two functions to implement the required TLS access: - -[source,c++] ----- -namespace boost { namespace leaf { - -namespace tls -{ - void * read_void_ptr( int tls_index ) noexcept; - void write_void_ptr( int tls_index, void * p ) noexcept; -} - -} } ----- - -TIP: For efficiency, `read_void_ptr` and `write_void_ptr` should be defined `inline`. - -Under `BOOST_LEAF_USE_TLS_ARRAY` the following additional configuration macros are recognized: +Boost Outcome addresses this by providing converters in the `outcome::convert` namespace to translate between error types (option 2). -* `BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX` specifies the start TLS array index available to LEAF (if the macro is left undefined, LEAF defines it as `0`). - -* `BOOST_LEAF_CFG_TLS_ARRAY_SIZE` may be defined to specify the size of the TLS array. In this case TLS indices are validated via `BOOST_LEAF_ASSERT` before being passed to `read_void_ptr` / `write_void_ptr`. - -* `BOOST_LEAF_CFG_TLS_INDEX_TYPE` may be defined to specify the integral type used to store assigned TLS indices (if the macro is left undefined, LEAF defines it as `unsigned char`). - -TIP: Reporting error objects of types that are not used by the program to handle failures does not consume TLS pointers. The minimum size of the TLS pointer array required by LEAF is the total number of different types used as arguments to error handlers (in the entire program), plus one. - -WARNING: Beware of `read_void_ptr`/`write_void_ptr` accessing thread local pointers beyond the static boundaries of the thread local pointer array; this will likely result in undefined behavior. +LEAF takes a different approach: error objects are transported directly to error handling scopes where storage is allocated statically, implementing option 3 without dynamic allocation. -[[embedded_platforms]] -=== Embedded Platforms - -Defining `BOOST_LEAF_EMBEDDED` is equivalent to the following: - -[source,c++] ----- -#ifndef BOOST_LEAF_CFG_DIAGNOSTICS -# define BOOST_LEAF_CFG_DIAGNOSTICS 0 -#endif - -#ifndef BOOST_LEAF_CFG_STD_SYSTEM_ERROR -# define BOOST_LEAF_CFG_STD_SYSTEM_ERROR 0 -#endif - -#ifndef BOOST_LEAF_CFG_STD_STRING -# define BOOST_LEAF_CFG_STD_STRING 0 -#endif - -#ifndef BOOST_LEAF_CFG_CAPTURE -# define BOOST_LEAF_CFG_CAPTURE 0 -#endif ----- - -LEAF supports FreeRTOS out of the box, please define `BOOST_LEAF_TLS_FREERTOS` (in which case LEAF automatically defines `BOOST_LEAF_EMBEDDED`, if it is not defined already). - -For other embedded platforms, please define `BOOST_LEAF_USE_TLS_ARRAY`, see <>. - -If your program does not use concurrency at all, simply define `BOOST_LEAF_NO_THREADS`, which requires no TLS support at all (but is NOT thread-safe). - -[[portability]] -== Portability - -The source code is compatible with {CPP}11 or newer. - -LEAF uses thread-local storage (only for pointers). By default, this is implemented via the {CPP}11 `thread_local` storage class specifier, but the library is easily configurable to use any platform-specific TLS API instead (it ships with built-in support for FreeRTOS). See <>. - -== Limitations +''' -When using dynamic linking, it is required that error types are declared with `default` visibility, e.g.: +[[boost_exception]] +=== Comparison to Boost Exception -[source,c++] ----- -struct __attribute__ ((visibility ("default"))) my_error_info -{ - int value; -}; ----- +Both LEAF and https://www.boost.org/doc/libs/release/libs/exception/doc/boost-exception.html[Boost Exception] allow transporting arbitrary error information with exceptions. The key design differences: -This works as expected except on Windows, where thread-local storage is not shared between the individual binary modules. For this reason, to transport error objects across DLL boundaries, it is required that they're captured in a <>, just like when <>. +* Boost Exception stores error objects in the exception object itself (requiring dynamic allocation). LEAF stores error objects in the error handling scope, discarding those not needed by handlers. +* Boost Exception can only augment exceptions deriving from `boost::exception`. LEAF can augment any exception type. +* Boost Exception automatically captures error objects across thread boundaries via `boost::exception_ptr`. LEAF requires explicit use of <>. -TIP: When using dynamic linking, it is always best to define module interfaces in terms of C (and implement them in {CPP} if appropriate). +NOTE: LEAF can access Boost Exception error information using its error handling interface. See <>. == Acknowledgements diff --git a/doc/whitepaper.md b/doc/whitepaper.md index 6af95b31..d7e49cfe 100644 --- a/doc/whitepaper.md +++ b/doc/whitepaper.md @@ -241,7 +241,7 @@ The above function computes a `float` value based on the contents of the specifi In case of failure to `open()`, our function stays out of the way: the error code is communicated from `open()` (which sets the `errno`) *directly* to an *error handling* function up the call stack (which examines the `errno` in order to understand the failure), while the return value of each intermediate function needs only communicate a single bit of data (the *failure flag*). -The major drawback of this appoach is that the *failure flag* is not communicated uniformly, which means that *error neutral* functions can't check for errors generically (e.g. each layer needs to know about the different `INVALID_VALUE`s). +The major drawback of this approach is that the *failure flag* is not communicated uniformly, which means that *error neutral* functions can't check for errors generically (e.g. each layer needs to know about the different `INVALID_VALUE`s). ### 6.2. C++ Exceptions @@ -357,7 +357,7 @@ Using LEAF, *error handling* functions match error objects similarly to the way * Each handler can specify multiple objects to be matched by type, rather than only one. * The error objects are matched dynamically, but solely based on their static type. This allows *all* error objects to be allocated on the stack, using automatic storage duration. -Whithout exception handling, this is achieved using the following syntax: +Without exception handling, this is achieved using the following syntax: ```c++ leaf::handle_all( diff --git a/doc/zajo-dark.css b/doc/zajo-dark.css index 5d7986a0..4247e85e 100644 --- a/doc/zajo-dark.css +++ b/doc/zajo-dark.css @@ -448,7 +448,7 @@ a:hover{color:#00cc99} a:focus{color:#FFFFFF} h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{font-family:"Quicksand","DejaVu Sans",sans-serif;font-weight:300;font-style:normal;color:#00cc99;text-rendering:optimizeLegibility;margin-top:1em;margin-bottom:.5em;line-height:1.4em} code{font-family:"Anonymous Pro","DejaVu Sans Mono",monospace;font-weight:400;color:black} -*:not(pre)>code{font-size:1.08em;font-style:normal!important;letter-spacing:0;padding:0 0;word-spacing:-.15em;background-color:transparent;-webkit-border-radius:0;border-radius:0;line-height:1.45;text-rendering:optimizeLegibility;word-wrap:break-word;color:white} +*:not(pre)>code{font-size:1.0em;font-style:normal!important;letter-spacing:0;padding:0 0;word-spacing:-.15em;background-color:transparent;-webkit-border-radius:0;border-radius:0;line-height:1.45;text-rendering:optimizeLegibility;word-wrap:break-word;color:white} pre,pre>code{line-height:1.45;color:rgba(255,255,255,.67);font-family:"Anonymous Pro","DejaVu Sans Mono",monospace;font-weight:400;text-rendering:optimizeLegibility;font-size:1.05em;background-color:#101010} a:not(pre)>code:hover {color:#00cc99} kbd{font-family:"Anonymous Pro","DejaVu Sans Mono",monospace;display:inline-block;color:rgba(0,0,0,.8);font-size:.65em;line-height:1.45;background-color:#f7f7f7;border:1px solid #ccc;-webkit-border-radius:3px;border-radius:3px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em white inset;box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em #fff inset;margin:0 .15em;padding:.2em .5em;vertical-align:middle;position:relative;top:-.1em;white-space:nowrap} diff --git a/doc/zajo-light.css b/doc/zajo-light.css index ac0dd299..89a5cdaf 100644 --- a/doc/zajo-light.css +++ b/doc/zajo-light.css @@ -442,7 +442,7 @@ a:hover{color:#4101a7} a:focus{color:#000000} h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{font-family:"Quicksand","DejaVu Sans",sans-serif;font-weight:300;font-style:normal;color:#4101a7;text-rendering:optimizeLegibility;margin-top:1em;margin-bottom:.5em;line-height:1.4em} code{font-family:"Anonymous Pro","DejaVu Sans Mono",monospace;font-weight:400;color:black} -*:not(pre)>code{font-size:1.08em;font-style:normal!important;letter-spacing:0;padding:0 0;word-spacing:-.15em;background-color:transparent;-webkit-border-radius:0;border-radius:0;line-height:1.45;text-rendering:optimizeLegibility;word-wrap:break-word} +*:not(pre)>code{font-size:1.0em;font-style:normal!important;letter-spacing:0;padding:0 0;word-spacing:-.15em;background-color:transparent;-webkit-border-radius:0;border-radius:0;line-height:1.45;text-rendering:optimizeLegibility;word-wrap:break-word} pre,pre>code{line-height:1.45;color:rgba(0,0,0,.9);font-family:"Anonymous Pro","DejaVu Sans Mono",monospace;font-weight:400;text-rendering:optimizeLegibility;font-size:1.05em;background-color:#f7f8f7} a:not(pre)>code:hover {color:#4101a7} kbd{font-family:"Anonymous Pro","DejaVu Sans Mono",monospace;display:inline-block;color:rgba(0,0,0,.8);font-size:.65em;line-height:1.45;background-color:#f7f7f7;border:1px solid #ccc;-webkit-border-radius:3px;border-radius:3px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em white inset;box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em #fff inset;margin:0 .15em;padding:.2em .5em;vertical-align:middle;position:relative;top:-.1em;white-space:nowrap} diff --git a/example/asio_beast_leaf_rpc.cpp b/example/asio_beast_leaf_rpc.cpp deleted file mode 100644 index 8201a2ac..00000000 --- a/example/asio_beast_leaf_rpc.cpp +++ /dev/null @@ -1,565 +0,0 @@ -// Copyright (c) 2019 Sorin Fetche - -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - -// PLEASE NOTE: This example requires the Boost 1.70 version of Asio and Beast, -// which at the time of this writing is in beta. - -// Example of a composed asynchronous operation which uses the LEAF library for -// error handling and reporting. -// -// Examples of running: -// - in one terminal (re)run: ./asio_beast_leaf_rpc_v3 0.0.0.0 8080 -// - in another run: -// curl localhost:8080 -v -d "sum 0 1 2 3" -// generating errors returned to the client: -// curl localhost:8080 -v -X DELETE -d "" -// curl localhost:8080 -v -d "mul 1 2x3" -// curl localhost:8080 -v -d "div 1 0" -// curl localhost:8080 -v -d "mod 1" -// -// Runs that showcase the error handling on the server side: -// - error starting the server: -// ./asio_beast_leaf_rpc_v3 0.0.0.0 80 -// - error while running the server logic: -// ./asio_beast_leaf_rpc_v3 0.0.0.0 8080 -// curl localhost:8080 -v -d "error-quit" -// -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace beast = boost::beast; -namespace http = beast::http; -namespace leaf = boost::leaf; -namespace net = boost::asio; - -namespace { -using error_code = boost::system::error_code; -} // namespace - -// The operation being performed when an error occurs. -struct e_last_operation { - std::string_view value; -}; - -// The HTTP request type. -using request_t = http::request; -// The HTTP response type. -using response_t = http::response; - -response_t handle_request(request_t &&request); - -// A composed asynchronous operation that implements a basic remote calculator -// over HTTP. It receives from the remote side commands such as: -// sum 1 2 3 -// div 3 2 -// mod 1 0 -// in the body of POST requests and sends back the result. -// -// Besides the calculator related commands, it also offer a special command: -// - `error_quit` that asks the server to simulate a server side error that -// leads to the connection being dropped. -// -// From the error handling perspective there are three parts of the implementation: -// - the handling of an HTTP request and creating the response to send back -// (see handle_request) -// - the parsing and execution of the remote command we received as the body of -// an an HTTP POST request -// (see execute_command()) -// - this composed asynchronous operation which calls them, -// -// This example operation is based on: -// - https://github.com/boostorg/beast/blob/b02f59ff9126c5a17f816852efbbd0ed20305930/example/echo-op/echo_op.cpp -// - part of -// https://github.com/boostorg/beast/blob/b02f59ff9126c5a17f816852efbbd0ed20305930/example/advanced/server/advanced_server.cpp -// -template -auto async_demo_rpc(AsyncStream &stream, ErrorContext &error_context, CompletionToken &&token) -> - typename net::async_result::type, void(leaf::result)>::return_type { - - static_assert(beast::is_async_stream::value, "AsyncStream requirements not met"); - - using handler_type = - typename net::async_completion)>::completion_handler_type; - using base_type = beast::stable_async_base>; - struct internal_op : base_type { - // This object must have a stable address - struct temporary_data { - beast::flat_buffer buffer; - std::optional> parser; - std::optional response; - }; - - AsyncStream &m_stream; - ErrorContext &m_error_context; - temporary_data &m_data; - bool m_write_and_quit; - - internal_op(AsyncStream &stream, ErrorContext &error_context, handler_type &&handler) - : base_type{std::move(handler), stream.get_executor()}, m_stream{stream}, m_error_context{error_context}, - m_data{beast::allocate_stable(*this)}, m_write_and_quit{false} { - start_read_request(); - } - - void operator()(error_code ec, std::size_t /*bytes_transferred*/ = 0) { - leaf::result result_continue_execution; - { - auto active_context = activate_context(m_error_context); - auto load = leaf::on_error(e_last_operation{m_data.response ? "async_demo_rpc::continuation-write" - : "async_demo_rpc::continuation-read"}); - if (ec == http::error::end_of_stream) { - // The remote side closed the connection. - result_continue_execution = false; - } else if (ec) { - result_continue_execution = leaf::new_error(ec); - } else { - result_continue_execution = leaf::exception_to_result([&]() -> leaf::result { - if (!m_data.response) { - // Process the request we received. - m_data.response = handle_request(std::move(m_data.parser->release())); - m_write_and_quit = m_data.response->need_eof(); - http::async_write(m_stream, *m_data.response, std::move(*this)); - return true; - } - - // If getting here, we completed a write operation. - m_data.response.reset(); - // And start reading a new message if not quitting (i.e. - // the message semantics of the last response we sent - // required an end of file) - if (!m_write_and_quit) { - start_read_request(); - return true; - } - - // We didn't initiate any new async operation above, so - // we will not continue the execution. - return false; - }); - } - // The activation object and load_last_operation need to be - // reset before calling the completion handler This is because, - // in general, the completion handler may be called directly or - // posted and if posted, it could execute in another thread. - // This means that regardless of how the handler gets to be - // actually called we must ensure that it is not called with the - // error context active. Note: An error context cannot be - // activated twice - } - if (!result_continue_execution) { - // We don't continue the execution due to an error, calling the - // completion handler - this->complete_now(result_continue_execution.error()); - } else if( !*result_continue_execution ) { - // We don't continue the execution due to the flag not being - // set, calling the completion handler - this->complete_now(leaf::result{}); - } - } - - void start_read_request() { - m_data.parser.emplace(); - m_data.parser->body_limit(1024); - http::async_read(m_stream, m_data.buffer, *m_data.parser, std::move(*this)); - } - }; - - auto initiation = [](auto &&completion_handler, AsyncStream *stream, ErrorContext *error_context) { - internal_op op{*stream, *error_context, std::forward(completion_handler)}; - }; - - // We are in the "initiation" part of the async operation. - [[maybe_unused]] auto load = leaf::on_error(e_last_operation{"async_demo_rpc::initiation"}); - return net::async_initiate)>(initiation, token, &stream, &error_context); -} - -// The location of a int64 parse error. It refers the range of characters from -// which the parsing was done. -struct e_parse_int64_error { - using location_base = std::pair; - struct location : public location_base { - using location_base::location_base; - - friend std::ostream &operator<<(std::ostream &os, location const &value) { - auto const &sv = value.first; - std::size_t pos = std::distance(sv.begin(), value.second); - if (pos == 0) { - os << "->\"" << sv << "\""; - } else if (pos < sv.size()) { - os << "\"" << sv.substr(0, pos) << "\"->\"" << sv.substr(pos) << "\""; - } else { - os << "\"" << sv << "\"<-"; - } - return os; - } - }; - - location value; -}; - -// Parses an integer from a string_view. -leaf::result parse_int64(std::string_view word) { - auto const begin = word.begin(); - auto const end = word.end(); - std::int64_t value = 0; - auto i = begin; - bool result = boost::spirit::qi::parse(i, end, boost::spirit::long_long, value); - if (!result || i != end) { - return leaf::new_error(e_parse_int64_error{std::make_pair(word, i)}); - } - return value; -} - -// The command being executed while we get an error. It refers the range of -// characters from which the command was extracted. -struct e_command { - std::string_view value; -}; - -// The details about an incorrect number of arguments error Some commands may -// accept a variable number of arguments (e.g. greater than 1 would mean [2, -// SIZE_MAX]). -struct e_unexpected_arg_count { - struct arg_info { - std::size_t count; - std::size_t min; - std::size_t max; - - friend std::ostream &operator<<(std::ostream &os, arg_info const &value) { - os << value.count << " (required: "; - if (value.min == value.max) { - os << value.min; - } else if (value.max < SIZE_MAX) { - os << "[" << value.min << ", " << value.max << "]"; - } else { - os << "[" << value.min << ", MAX]"; - } - os << ")"; - return os; - } - }; - - arg_info value; -}; - -// The HTTP status that should be returned in case we get into an error. -struct e_http_status { - http::status value; -}; - -// Unexpected HTTP method. -struct e_unexpected_http_method { - http::verb value; -}; - -// The E-type that describes the `error_quit` command as an error condition. -struct e_error_quit { - struct none_t {}; - none_t value; -}; - -// Processes a remote command. -leaf::result execute_command(std::string_view line) { - // Split the command in words. - std::list words; // or std::deque words; - - char const *const ws = "\t \r\n"; - auto skip_ws = [&](std::string_view &line) { - if (auto pos = line.find_first_not_of(ws); pos != std::string_view::npos) { - line = line.substr(pos); - } else { - line = std::string_view{}; - } - }; - - skip_ws(line); - while (!line.empty()) { - std::string_view word; - if (auto pos = line.find_first_of(ws); pos != std::string_view::npos) { - word = line.substr(0, pos); - line = line.substr(pos + 1); - } else { - word = line; - line = std::string_view{}; - } - - if (!word.empty()) { - words.push_back(word); - } - skip_ws(line); - } - - static char const *const help = "Help:\n" - " error-quit Simulated error to end the session\n" - " sum * Addition\n" - " sub + Substraction\n" - " mul * Multiplication\n" - " div + Division\n" - " mod Remainder\n" - " This message"; - - if (words.empty()) { - return std::string(help); - } - - auto command = words.front(); - words.pop_front(); - - auto load_cmd = leaf::on_error(e_command{command}, e_http_status{http::status::bad_request}); - std::string response; - - if (command == "error-quit") { - return leaf::new_error(e_error_quit{}); - } else if (command == "sum") { - std::int64_t sum = 0; - for (auto const &w : words) { - BOOST_LEAF_AUTO(i, parse_int64(w)); - sum += i; - } - response = std::to_string(sum); - } else if (command == "sub") { - if (words.size() < 2) { - return leaf::new_error(e_unexpected_arg_count{words.size(), 2, SIZE_MAX}); - } - BOOST_LEAF_AUTO(sub, parse_int64(words.front())); - words.pop_front(); - for (auto const &w : words) { - BOOST_LEAF_AUTO(i, parse_int64(w)); - sub -= i; - } - response = std::to_string(sub); - } else if (command == "mul") { - std::int64_t mul = 1; - for (auto const &w : words) { - BOOST_LEAF_AUTO(i, parse_int64(w)); - mul *= i; - } - response = std::to_string(mul); - } else if (command == "div") { - if (words.size() < 2) { - return leaf::new_error(e_unexpected_arg_count{words.size(), 2, SIZE_MAX}); - } - BOOST_LEAF_AUTO(div, parse_int64(words.front())); - words.pop_front(); - for (auto const &w : words) { - BOOST_LEAF_AUTO(i, parse_int64(w)); - if (i == 0) { - // In some cases this command execution function might throw, - // not just return an error. - throw std::runtime_error{"division by zero"}; - } - div /= i; - } - response = std::to_string(div); - } else if (command == "mod") { - if (words.size() != 2) { - return leaf::new_error(e_unexpected_arg_count{words.size(), 2, 2}); - } - BOOST_LEAF_AUTO(i1, parse_int64(words.front())); - words.pop_front(); - BOOST_LEAF_AUTO(i2, parse_int64(words.front())); - words.pop_front(); - if (i2 == 0) { - // In some cases this command execution function might throw, not - // just return an error. - throw leaf::exception(std::runtime_error{"division by zero"}); - } - response = std::to_string(i1 % i2); - } else { - response = help; - } - - return response; -} - -std::string diagnostic_to_str(leaf::verbose_diagnostic_info const &diag) { - auto str = boost::str(boost::format("%1%") % diag); - boost::algorithm::replace_all(str, "\n", "\n "); - return "\nDetailed error diagnostic:\n----\n" + str + "\n----"; -}; - -// Handles an HTTP request and returns the response to send back. -response_t handle_request(request_t &&request) { - - auto msg_prefix = [](e_command const *cmd) { - if (cmd != nullptr) { - return boost::str(boost::format("Error (%1%):") % cmd->value); - } - return std::string("Error:"); - }; - - auto make_sr = [](e_http_status const *status, std::string &&response) { - return std::make_pair(status != nullptr ? status->value : http::status::internal_server_error, - std::move(response)); - }; - - // In this variant of the RPC example we execute the remote command and - // handle any errors coming from it in one place (using - // `leaf::try_handle_all`). - auto pair_status_response = leaf::try_handle_all( - [&]() -> leaf::result> { - if (request.method() != http::verb::post) { - return leaf::new_error(e_unexpected_http_method{http::verb::post}, - e_http_status{http::status::bad_request}); - } - BOOST_LEAF_AUTO(response, execute_command(request.body())); - return std::make_pair(http::status::ok, std::move(response)); - }, - // For the `error_quit` command and associated error condition we have - // the error handler itself fail (by throwing). This means that the - // server will not send any response to the client, it will just - // shutdown the connection. This implementation showcases two aspects: - // - that the implementation of error handling can fail, too - // - how the asynchronous operation calling this error handling function - // reacts to this failure. - [](e_error_quit const &) -> std::pair { throw std::runtime_error("error_quit"); }, - // For the rest of error conditions we just build a message to be sent - // to the remote client. - [&](e_parse_int64_error const &e, e_http_status const *status, e_command const *cmd, - leaf::verbose_diagnostic_info const &diag) { - return make_sr(status, boost::str(boost::format("%1% int64 parse error: %2%") % msg_prefix(cmd) % e.value) + - diagnostic_to_str(diag)); - }, - [&](e_unexpected_arg_count const &e, e_http_status const *status, e_command const *cmd, - leaf::verbose_diagnostic_info const &diag) { - return make_sr(status, - boost::str(boost::format("%1% wrong argument count: %2%") % msg_prefix(cmd) % e.value) + - diagnostic_to_str(diag)); - }, - [&](e_unexpected_http_method const &e, e_http_status const *status, e_command const *cmd, - leaf::verbose_diagnostic_info const &diag) { - return make_sr(status, boost::str(boost::format("%1% unexpected HTTP method. Expected: %2%") % - msg_prefix(cmd) % e.value) + - diagnostic_to_str(diag)); - }, - [&](std::exception const & e, e_http_status const *status, e_command const *cmd, - leaf::verbose_diagnostic_info const &diag) { - return make_sr(status, boost::str(boost::format("%1% %2%") % msg_prefix(cmd) % e.what()) + - diagnostic_to_str(diag)); - }, - [&](e_http_status const *status, e_command const *cmd, leaf::verbose_diagnostic_info const &diag) { - return make_sr(status, boost::str(boost::format("%1% unknown failure") % msg_prefix(cmd)) + - diagnostic_to_str(diag)); - }); - response_t response{pair_status_response.first, request.version()}; - response.set(http::field::server, "Example-with-" BOOST_BEAST_VERSION_STRING); - response.set(http::field::content_type, "text/plain"); - response.keep_alive(request.keep_alive()); - pair_status_response.second += "\n"; - response.body() = std::move(pair_status_response.second); - response.prepare_payload(); - return response; -} - -int main(int argc, char **argv) { - auto msg_prefix = [](e_last_operation const *op) { - if (op != nullptr) { - return boost::str(boost::format("Error (%1%): ") % op->value); - } - return std::string("Error: "); - }; - - // Error handler for internal server internal errors (not communicated to - // the remote client). - auto error_handlers = std::make_tuple( - [&](std::exception_ptr const &ep, e_last_operation const *op) { - return leaf::try_handle_all( - [&]() -> leaf::result { std::rethrow_exception(ep); }, - [&](std::exception const & e, leaf::verbose_diagnostic_info const &diag) { - std::cerr << msg_prefix(op) << e.what() << " (captured)" << diagnostic_to_str(diag) - << std::endl; - return -11; - }, - [&](leaf::verbose_diagnostic_info const &diag) { - std::cerr << msg_prefix(op) << "unknown (captured)" << diagnostic_to_str(diag) << std::endl; - return -12; - }); - }, - [&](std::exception const & e, e_last_operation const *op, leaf::verbose_diagnostic_info const &diag) { - std::cerr << msg_prefix(op) << e.what() << diagnostic_to_str(diag) << std::endl; - return -21; - }, - [&](error_code ec, leaf::verbose_diagnostic_info const &diag, e_last_operation const *op) { - std::cerr << msg_prefix(op) << ec << ":" << ec.message() << diagnostic_to_str(diag) << std::endl; - return -22; - }, - [&](leaf::verbose_diagnostic_info const &diag, e_last_operation const *op) { - std::cerr << msg_prefix(op) << "unknown" << diagnostic_to_str(diag) << std::endl; - return -23; - }); - - // Top level try block and error handler. It will handle errors from - // starting the server for example failure to bind to a given port (e.g. - // ports less than 1024 if not running as root) - return leaf::try_handle_all( - [&]() -> leaf::result { - auto load = leaf::on_error(e_last_operation{"main"}); - if (argc != 3) { - std::cerr << "Usage: " << argv[0] << "
" << std::endl; - std::cerr << "Example:\n " << argv[0] << " 0.0.0.0 8080" << std::endl; - return -1; - } - - auto const address{net::ip::make_address(argv[1])}; - auto const port{static_cast(std::atoi(argv[2]))}; - net::ip::tcp::endpoint const endpoint{address, port}; - - net::io_context io_context; - - // Start the server acceptor and wait for a client. - net::ip::tcp::acceptor acceptor{io_context, endpoint}; - - auto local_endpoint = acceptor.local_endpoint(); - auto address_try_msg = acceptor.local_endpoint().address().to_string(); - if (address_try_msg == "0.0.0.0") { - address_try_msg = "localhost"; - } - std::cout << "Server: Started on: " << local_endpoint << std::endl; - std::cout << "Try in a different terminal:\n" - << " curl " << address_try_msg << ":" << local_endpoint.port() << " -d \"\"\nor\n" - << " curl " << address_try_msg << ":" << local_endpoint.port() << " -d \"sum 1 2 3\"" - << std::endl; - - auto socket = acceptor.accept(); - std::cout << "Server: Client connected: " << socket.remote_endpoint() << std::endl; - - // The error context for the async operation. - auto error_context = leaf::make_context(error_handlers); - int rv = 0; - async_demo_rpc(socket, error_context, [&](leaf::result result) { - // Note: In case we wanted to add some additional information to - // the error associated with the result we would need to - // activate the error context - auto active_context = activate_context(error_context); - if (result) { - std::cout << "Server: Client work completed successfully" << std::endl; - rv = 0; - } else { - // Handle errors from running the server logic - leaf::result result_int{result.error()}; - rv = error_context.handle_error(result_int.error(), error_handlers); - } - }); - io_context.run(); - - // Let the remote side know we are shutting down. - error_code ignored; - socket.shutdown(net::ip::tcp::socket::shutdown_both, ignored); - return rv; - }, - error_handlers); -} diff --git a/example/error_log.cpp b/example/error_log.cpp index c8ccc81a..b64e8aa0 100644 --- a/example/error_log.cpp +++ b/example/error_log.cpp @@ -1,5 +1,4 @@ -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. - +// Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) @@ -133,14 +132,14 @@ int main() namespace boost { - BOOST_LEAF_NORETURN void throw_exception( std::exception const & e ) + [[noreturn]] void throw_exception( std::exception const & e ) { std::cerr << "Terminating due to a C++ exception under BOOST_LEAF_NO_EXCEPTIONS: " << e.what(); std::terminate(); } struct source_location; - BOOST_LEAF_NORETURN void throw_exception( std::exception const & e, boost::source_location const & ) + [[noreturn]] void throw_exception( std::exception const & e, boost::source_location const & ) { throw_exception(e); } diff --git a/example/error_trace.cpp b/example/error_trace.cpp index 706f577e..0bba6ba5 100644 --- a/example/error_trace.cpp +++ b/example/error_trace.cpp @@ -1,5 +1,4 @@ -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. - +// Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) @@ -133,14 +132,14 @@ int main() namespace boost { - BOOST_LEAF_NORETURN void throw_exception( std::exception const & e ) + [[noreturn]] void throw_exception( std::exception const & e ) { std::cerr << "Terminating due to a C++ exception under BOOST_LEAF_NO_EXCEPTIONS: " << e.what(); std::terminate(); } struct source_location; - BOOST_LEAF_NORETURN void throw_exception( std::exception const & e, boost::source_location const & ) + [[noreturn]] void throw_exception( std::exception const & e, boost::source_location const & ) { throw_exception(e); } diff --git a/example/exception_to_result.cpp b/example/exception_to_result.cpp index 793f6777..16c18ef0 100644 --- a/example/exception_to_result.cpp +++ b/example/exception_to_result.cpp @@ -1,5 +1,4 @@ -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. - +// Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) @@ -68,12 +67,12 @@ int main() return { }; }, - []( error_a const & e ) + []( error_a const & ) { std::cerr << "Error A!" << std::endl; }, - []( error_b const & e ) + []( error_b const & ) { std::cerr << "Error B!" << std::endl; }, diff --git a/example/lua_callback_eh.cpp b/example/lua_callback_exceptions.cpp similarity index 96% rename from example/lua_callback_eh.cpp rename to example/lua_callback_exceptions.cpp index 4e87f267..fae54a28 100644 --- a/example/lua_callback_eh.cpp +++ b/example/lua_callback_exceptions.cpp @@ -1,5 +1,4 @@ -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. - +// Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) @@ -12,6 +11,7 @@ extern "C" { } #include #include +#include #include namespace leaf = boost::leaf; @@ -75,7 +75,7 @@ int do_work( lua_State * L ) } else { - throw leaf::exception(ec1); + leaf::throw_exception(ec1); } } @@ -127,7 +127,7 @@ int call_lua( lua_State * L ) // cur_err.assigned_error_id() will return a new leaf::error_id, // otherwise we'll be working with the original error reported // by a C++ exception out of do_work. - throw leaf::exception( cur_err.assigned_error_id().load( e_lua_pcall_error{err}, e_lua_error_message{std::move(msg)} ) ); + leaf::throw_exception( cur_err.assigned_error_id().load( e_lua_pcall_error{err}, e_lua_error_message{std::move(msg)} ) ); } else { diff --git a/example/lua_callback_result.cpp b/example/lua_callback_result.cpp index 47ac6839..db4d510b 100644 --- a/example/lua_callback_result.cpp +++ b/example/lua_callback_result.cpp @@ -1,5 +1,4 @@ -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. - +// Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) @@ -12,6 +11,7 @@ extern "C" { } #include #include +#include #include namespace leaf = boost::leaf; @@ -158,14 +158,14 @@ int main() namespace boost { - BOOST_LEAF_NORETURN void throw_exception( std::exception const & e ) + [[noreturn]] void throw_exception( std::exception const & e ) { std::cerr << "Terminating due to a C++ exception under BOOST_LEAF_NO_EXCEPTIONS: " << e.what(); std::terminate(); } struct source_location; - BOOST_LEAF_NORETURN void throw_exception( std::exception const & e, boost::source_location const & ) + [[noreturn]] void throw_exception( std::exception const & e, boost::source_location const & ) { throw_exception(e); } diff --git a/example/print_file/print_file_eh.cpp b/example/print_file/print_file_exceptions.cpp similarity index 85% rename from example/print_file/print_file_eh.cpp rename to example/print_file/print_file_exceptions.cpp index 69361e40..e235153e 100644 --- a/example/print_file/print_file_eh.cpp +++ b/example/print_file/print_file_exceptions.cpp @@ -1,5 +1,4 @@ -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. - +// Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) @@ -8,10 +7,11 @@ // It reads a text file in a buffer and prints it to std::cout, using LEAF to // handle errors. This version uses exception handling. The version that does -// not use exception handling is in print_file_result.cpp. +// not use exception handling is in print_file_leaf_result.cpp. #include #include +#include #include namespace leaf = boost::leaf; @@ -40,10 +40,10 @@ char const * parse_command_line( int argc, char const * argv[] ); std::shared_ptr file_open( char const * file_name ); // Return the size of the file. -int file_size( FILE & f ); +std::size_t file_size( FILE & f ); // Read size bytes from f into buf. -void file_read( FILE & f, void * buf, int size ); +void file_read( FILE & f, void * buf, std::size_t size ); // The main function, which handles all errors. @@ -59,7 +59,7 @@ int main( int argc, char const * argv[] ) std::shared_ptr f = file_open(file_name); - int s = file_size(*f); + std::size_t s = file_size(*f); std::string buffer(1 + s, '\0'); file_read(*f, &buffer[0], buffer.size()-1); @@ -67,7 +67,7 @@ int main( int argc, char const * argv[] ) std::cout << buffer; std::cout.flush(); if( std::cout.fail() ) - throw leaf::exception(output_error, leaf::e_errno{errno}); + leaf::throw_exception(output_error, leaf::e_errno{errno}); return 0; }, @@ -149,10 +149,10 @@ int main( int argc, char const * argv[] ) // Parse the command line, return the file name. char const * parse_command_line( int argc, char const * argv[] ) { - if( argc==2 ) + if( argc == 2 ) return argv[1]; else - throw leaf::exception(bad_command_line); + leaf::throw_exception(bad_command_line); } @@ -162,37 +162,37 @@ std::shared_ptr file_open( char const * file_name ) if( FILE * f = fopen(file_name, "rb") ) return std::shared_ptr(f, &fclose); else - throw leaf::exception(open_error, leaf::e_errno{errno}); + leaf::throw_exception(open_error, leaf::e_errno{errno}); } // Return the size of the file. -int file_size( FILE & f ) +std::size_t file_size( FILE & f ) { auto load = leaf::on_error([] { return leaf::e_errno{errno}; }); if( fseek(&f, 0, SEEK_END) ) - throw leaf::exception(size_error); + leaf::throw_exception(size_error); - int s = ftell(&f); - if( s==-1L ) - throw leaf::exception(size_error); + long s = ftell(&f); + if( s == -1L ) + leaf::throw_exception(size_error); if( fseek(&f,0,SEEK_SET) ) - throw leaf::exception(size_error); + leaf::throw_exception(size_error); - return s; + return std::size_t(s); } // Read size bytes from f into buf. -void file_read( FILE & f, void * buf, int size ) +void file_read( FILE & f, void * buf, std::size_t size ) { - int n = fread(buf, 1, size, &f); + std::size_t n = fread(buf, 1, size, &f); if( ferror(&f) ) - throw leaf::exception(read_error, leaf::e_errno{errno}); + leaf::throw_exception(read_error, leaf::e_errno{errno}); - if( n!=size ) - throw leaf::exception(eof_error); + if( n != size ) + leaf::throw_exception(eof_error); } diff --git a/example/print_file/print_file_result.cpp b/example/print_file/print_file_leaf_result.cpp similarity index 90% rename from example/print_file/print_file_result.cpp rename to example/print_file/print_file_leaf_result.cpp index 46f5af25..4c670696 100644 --- a/example/print_file/print_file_result.cpp +++ b/example/print_file/print_file_leaf_result.cpp @@ -1,5 +1,4 @@ -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. - +// Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) @@ -8,10 +7,11 @@ // It reads a text file in a buffer and prints it to std::cout, using LEAF to // handle errors. This version does not use exception handling. The version that -// does use exception handling is in print_file_eh.cpp. +// does use exception handling is in print_file_exceptions.cpp. #include #include +#include #include namespace leaf = boost::leaf; @@ -44,10 +44,10 @@ result parse_command_line( int argc, char const * argv[] ); result> file_open( char const * file_name ); // Return the size of the file. -result file_size( FILE & f ); +result file_size( FILE & f ); // Read size bytes from f into buf. -result file_read( FILE & f, void * buf, int size ); +result file_read( FILE & f, void * buf, std::size_t size ); // The main function, which handles all errors. @@ -153,7 +153,7 @@ int main( int argc, char const * argv[] ) // Parse the command line, return the file name. result parse_command_line( int argc, char const * argv[] ) { - if( argc==2 ) + if( argc == 2 ) return argv[1]; else return leaf::new_error(bad_command_line); @@ -171,33 +171,33 @@ result> file_open( char const * file_name ) // Return the size of the file. -result file_size( FILE & f ) +result file_size( FILE & f ) { auto load = leaf::on_error([] { return leaf::e_errno{errno}; }); if( fseek(&f, 0, SEEK_END) ) return leaf::new_error(size_error); - int s = ftell(&f); - if( s==-1L ) + long s = ftell(&f); + if( s == -1L ) return leaf::new_error(size_error); if( fseek(&f,0,SEEK_SET) ) return leaf::new_error(size_error); - return s; + return std::size_t(s); } // Read size bytes from f into buf. -result file_read( FILE & f, void * buf, int size ) +result file_read( FILE & f, void * buf, std::size_t size ) { - int n = fread(buf, 1, size, &f); + std::size_t n = fread(buf, 1, size, &f); if( ferror(&f) ) return leaf::new_error(read_error, leaf::e_errno{errno}); - if( n!=size ) + if( n != size ) return leaf::new_error(eof_error); return { }; @@ -209,14 +209,14 @@ result file_read( FILE & f, void * buf, int size ) namespace boost { - BOOST_LEAF_NORETURN void throw_exception( std::exception const & e ) + [[noreturn]] void throw_exception( std::exception const & e ) { std::cerr << "Terminating due to a C++ exception under BOOST_LEAF_NO_EXCEPTIONS: " << e.what(); std::terminate(); } struct source_location; - BOOST_LEAF_NORETURN void throw_exception( std::exception const & e, boost::source_location const & ) + [[noreturn]] void throw_exception( std::exception const & e, boost::source_location const & ) { throw_exception(e); } diff --git a/example/print_file/print_file_outcome_result.cpp b/example/print_file/print_file_system_result.cpp similarity index 80% rename from example/print_file/print_file_outcome_result.cpp rename to example/print_file/print_file_system_result.cpp index 6710829d..468e115a 100644 --- a/example/print_file/print_file_outcome_result.cpp +++ b/example/print_file/print_file_system_result.cpp @@ -1,21 +1,21 @@ -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. - +// Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // This is the program presented in -// https://boostorg.github.io/leaf/#introduction-result, converted to use -// outcome::result instead of leaf::result. +// https://boostorg.github.io/leaf/#introduction-result. // It reads a text file in a buffer and prints it to std::cout, using LEAF to -// handle errors. This version does not use exception handling. +// handle errors. This version does not use exception handling. The version that +// does use exception handling is in print_file_exceptions.cpp. + -#include #include +#include #include +#include #include -namespace outcome = boost::outcome_v2; namespace leaf = boost::leaf; @@ -32,12 +32,12 @@ enum error_code template -using result = outcome::std_result; +using result = boost::system::result; -// To enable LEAF to work with outcome::result, we need to specialize the +// To enable LEAF to work with boost::system::result, we need to specialize the // is_result_type template: namespace boost { namespace leaf { - template struct is_result_type>: std::true_type { }; + template struct is_result_type>: std::true_type { }; } } @@ -52,10 +52,10 @@ result parse_command_line( int argc, char const * argv[] ); result> file_open( char const * file_name ); // Return the size of the file. -result file_size( FILE & f ); +result file_size( FILE & f ); // Read size bytes from f into buf. -result file_read( FILE & f, void * buf, int size ); +result file_read( FILE & f, void * buf, std::size_t size ); // The main function, which handles all errors. @@ -79,7 +79,7 @@ int main( int argc, char const * argv[] ) std::cout << buffer; std::cout.flush(); if( std::cout.fail() ) - return leaf::new_error(output_error, leaf::e_errno{errno}).to_error_code(); + return leaf::new_error(output_error, leaf::e_errno{errno}); return 0; }, @@ -161,10 +161,10 @@ int main( int argc, char const * argv[] ) // Parse the command line, return the file name. result parse_command_line( int argc, char const * argv[] ) { - if( argc==2 ) + if( argc == 2 ) return argv[1]; else - return leaf::new_error(bad_command_line).to_error_code(); + return leaf::new_error(bad_command_line); } @@ -174,41 +174,41 @@ result> file_open( char const * file_name ) if( FILE * f = fopen(file_name, "rb") ) return std::shared_ptr(f, &fclose); else - return leaf::new_error(open_error, leaf::e_errno{errno}).to_error_code(); + return leaf::new_error(open_error, leaf::e_errno{errno}); } // Return the size of the file. -result file_size( FILE & f ) +result file_size( FILE & f ) { auto load = leaf::on_error([] { return leaf::e_errno{errno}; }); if( fseek(&f, 0, SEEK_END) ) - return leaf::new_error(size_error).to_error_code(); + return leaf::new_error(size_error); - int s = ftell(&f); - if( s==-1L ) - return leaf::new_error(size_error).to_error_code(); + long s = ftell(&f); + if( s == -1L ) + return leaf::new_error(size_error); if( fseek(&f,0,SEEK_SET) ) - return leaf::new_error(size_error).to_error_code(); + return leaf::new_error(size_error); - return s; + return std::size_t(s); } // Read size bytes from f into buf. -result file_read( FILE & f, void * buf, int size ) +result file_read( FILE & f, void * buf, std::size_t size ) { - int n = fread(buf, 1, size, &f); + std::size_t n = fread(buf, 1, size, &f); if( ferror(&f) ) - return leaf::new_error(read_error, leaf::e_errno{errno}).to_error_code(); + return leaf::new_error(read_error, leaf::e_errno{errno}); - if( n!=size ) - return leaf::new_error(eof_error).to_error_code(); + if( n != size ) + return leaf::new_error(eof_error); - return outcome::success(); + return { }; } //////////////////////////////////////// @@ -217,14 +217,14 @@ result file_read( FILE & f, void * buf, int size ) namespace boost { - BOOST_LEAF_NORETURN void throw_exception( std::exception const & e ) + BOOST_NORETURN void throw_exception( std::exception const & e ) { std::cerr << "Terminating due to a C++ exception under BOOST_LEAF_NO_EXCEPTIONS: " << e.what(); std::terminate(); } struct source_location; - BOOST_LEAF_NORETURN void throw_exception( std::exception const & e, boost::source_location const & ) + BOOST_NORETURN void throw_exception( std::exception const & e, boost::source_location const & ) { throw_exception(e); } diff --git a/example/print_file/readme.md b/example/print_file/readme.md index 3c5a51cd..702580ef 100644 --- a/example/print_file/readme.md +++ b/example/print_file/readme.md @@ -1,16 +1,14 @@ # Print File Example -This directory has three versions of the same simple program, which reads a -file, prints it to standard out and handles errors using LEAF, each using a -different variation on error handling: +This directory contains several versions of a trivial program which takes a file name on the command line and prints it. Each version uses a different error handling implementation. -* [print_file_result.cpp](./print_file_result.cpp) reports errors with +* [print_file_leaf_result.cpp](./print_file_leaf_result.cpp) reports errors with `leaf::result`, using an error code `enum` for classification of failures. -* [print_file_outcome_result.cpp](./print_file_outcome_result.cpp) is the same - as the above, but using `outcome::result`. This demonstrates the ability - to transport arbitrary error objects through APIs that do not use - `leaf::result`. +* [print_file_system_result.cpp](./print_file_system_result.cpp) is the same as + above, but using `boost::system::result` instead of `leaf::result`. + This demonstrates the ability of LEAF to transport arbitrary error objects using an + external result type, rather than `boost::leaf::result`. -* [print_file_eh.cpp](./print_file_eh.cpp) throws on error, using an error code +* [print_file_exceptions.cpp](./print_file_exceptions.cpp) throws on error, using an error code `enum` for classification of failures. diff --git a/example/print_half.cpp b/example/print_half.cpp index f6caaa8e..71bda06e 100644 --- a/example/print_half.cpp +++ b/example/print_half.cpp @@ -1,5 +1,4 @@ -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. - +// Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) @@ -104,14 +103,14 @@ int main( int argc, char const * argv[] ) namespace boost { - BOOST_LEAF_NORETURN void throw_exception( std::exception const & e ) + [[noreturn]] void throw_exception( std::exception const & e ) { std::cerr << "Terminating due to a C++ exception under BOOST_LEAF_NO_EXCEPTIONS: " << e.what(); std::terminate(); } struct source_location; - BOOST_LEAF_NORETURN void throw_exception( std::exception const & e, boost::source_location const & ) + [[noreturn]] void throw_exception( std::exception const & e, boost::source_location const & ) { throw_exception(e); } diff --git a/example/readme.md b/example/readme.md index 3e98584a..d783ac67 100644 --- a/example/readme.md +++ b/example/readme.md @@ -1,13 +1,12 @@ # Example Programs Using LEAF to Handle Errors -* [print_file](./print_file): The complete example from the [Five Minute Introduction](https://boostorg.github.io/leaf/#introduction). This directory contains several versions of the same program, each using a different error handling style. +* [print_file](./print_file): This directory contains several versions of a trivial program which takes a file name on the command line and prints it. Each version uses a different error handling implementation. -* [capture_in_result.cpp](https://github.com/boostorg/leaf/blob/master/example/capture_in_result.cpp?ts=4): Shows how to transport error objects between threads in a `leaf::result` object. -* [capture_in_exception.cpp](https://github.com/boostorg/leaf/blob/master/example/capture_in_exception.cpp?ts=4): Shows how to transport error objects between threads in an exception object. +* [try_capture_all_result.cpp](https://github.com/boostorg/leaf/blob/master/example/try_capture_all_result.cpp?ts=4): Shows how to transport error objects between threads in a `leaf::result` object without using exception handling. +* [try_capture_all_exceptions.cpp](https://github.com/boostorg/leaf/blob/master/example/try_capture_all_exceptions.cpp?ts=4): Shows how to transport error objects between threads in a `leaf::result` object using exception handling. * [lua_callback_result.cpp](https://github.com/boostorg/leaf/blob/master/example/lua_callback_result.cpp?ts=4): Transporting arbitrary error objects through an uncooperative C API. -* [lua_callback_eh.cpp](https://github.com/boostorg/leaf/blob/master/example/lua_callback_eh.cpp?ts=4): Transporting arbitrary error objects through an uncooperative exception-safe API. +* [lua_callback_exceptions.cpp](https://github.com/boostorg/leaf/blob/master/example/lua_callback_exceptions.cpp?ts=4): Transporting arbitrary error objects through an uncooperative API using exceptions. * [exception_to_result.cpp](https://github.com/boostorg/leaf/blob/master/example/exception_to_result.cpp?ts=4): Demonstrates how to transport exceptions through a `noexcept` layer in the program. * [exception_error_log.cpp](https://github.com/boostorg/leaf/blob/master/example/error_log.cpp?ts=4): Using `accumulate` to produce an error log. * [exception_error_trace.cpp](https://github.com/boostorg/leaf/blob/master/example/error_trace.cpp?ts=4): Same as above, but the log is recorded in a `std::deque` rather than just printed. * [print_half.cpp](https://github.com/boostorg/leaf/blob/master/example/print_half.cpp?ts=4): This is a Boost Outcome example adapted to LEAF, demonstrating the use of `try_handle_some` to handle some errors, forwarding any other error to the caller. -* [asio_beast_leaf_rpc.cpp](https://github.com/boostorg/leaf/blob/master/example/asio_beast_leaf_rpc.cpp?ts=4): A simple RPC calculator implemented with Beast+ASIO+LEAF. diff --git a/example/capture_in_exception.cpp b/example/try_capture_all_exceptions.cpp similarity index 58% rename from example/capture_in_exception.cpp rename to example/try_capture_all_exceptions.cpp index c203affa..91a8c6f5 100644 --- a/example/capture_in_exception.cpp +++ b/example/try_capture_all_exceptions.cpp @@ -1,5 +1,4 @@ -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. - +// Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) @@ -7,6 +6,20 @@ // objects between threads, using exception handling. See capture_in_result.cpp // for the version that does not use exception handling. +#include + +#if !BOOST_LEAF_CFG_CAPTURE || defined(BOOST_LEAF_NO_EXCEPTIONS) + +#include + +int main() +{ + std::cout << "Unit test not applicable." << std::endl; + return 0; +} + +#else + #include #include #include @@ -14,6 +27,7 @@ #include #include #include +#include namespace leaf = boost::leaf; @@ -33,7 +47,7 @@ task_result task() if( succeed ) return { }; else - throw leaf::exception( + leaf::throw_exception( e_thread_id{std::this_thread::get_id()}, e_failure_info1{"info"}, e_failure_info2{42} ); @@ -43,30 +57,12 @@ int main() { int const task_count = 42; - // The error_handlers are used in this thread (see leaf::try_catch below). - // The arguments passed to individual lambdas are transported from the - // worker thread to the main thread automatically. - auto error_handlers = std::make_tuple( - []( e_failure_info1 const & v1, e_failure_info2 const & v2, e_thread_id const & tid ) - { - std::cerr << "Error in thread " << tid.value << "! failure_info1: " << v1.value << ", failure_info2: " << v2.value << std::endl; - }, - []( leaf::diagnostic_info const & unmatched ) - { - std::cerr << - "Unknown failure detected" << std::endl << - "Cryptic diagnostic information follows" << std::endl << - unmatched; - } ); - // Container to collect the generated std::future objects. - std::vector> fut; + std::vector>> fut; // Launch the tasks, but rather than launching the task function directly, - // we launch a wrapper function which calls leaf::capture, passing a context - // object that will hold the error objects reported from the task in case it - // throws. The error types the context is able to hold statically are - // automatically deduced from the type of the error_handlers tuple. + // we use try_capture_all: in case of a failure, the returned leaf::result<> + // will capture all error objects. std::generate_n( std::back_inserter(fut), task_count, [&] { @@ -74,7 +70,7 @@ int main() std::launch::async, [&] { - return leaf::capture(leaf::make_shared_context(error_handlers), &task); + return leaf::try_capture_all(task); } ); } ); @@ -86,12 +82,24 @@ int main() leaf::try_catch( [&] { - task_result r = f.get(); + task_result r = f.get().value(); // Success! Use r to access task_result. std::cout << "Success!" << std::endl; (void) r; // Presumably we'll somehow use the task_result. }, - error_handlers ); + []( e_failure_info1 const & v1, e_failure_info2 const & v2, e_thread_id const & tid ) + { + std::cerr << "Error in thread " << tid.value << "! failure_info1: " << v1.value << ", failure_info2: " << v2.value << std::endl; + }, + []( leaf::diagnostic_info const & unmatched ) + { + std::cerr << + "Unknown failure detected" << std::endl << + "Cryptic diagnostic information follows" << std::endl << + unmatched; + } ); } } + +#endif diff --git a/example/capture_in_result.cpp b/example/try_capture_all_result.cpp similarity index 61% rename from example/capture_in_result.cpp rename to example/try_capture_all_result.cpp index f2aec02f..d2d17b80 100644 --- a/example/capture_in_result.cpp +++ b/example/try_capture_all_result.cpp @@ -1,12 +1,25 @@ -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. - +// Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // This is a simple program that demonstrates the use of LEAF to transport error -// objects between threads, without using exception handling. See capture_eh.cpp +// objects between threads, without using exception handling. See try_capture_all_exceptions.cpp // for the version that uses exception handling. +#include + +#if !BOOST_LEAF_CFG_CAPTURE + +#include + +int main() +{ + std::cout << "Unit test not applicable." << std::endl; + return 0; +} + +#else + #include #include #include @@ -14,6 +27,7 @@ #include #include #include +#include namespace leaf = boost::leaf; @@ -43,30 +57,12 @@ int main() { int const task_count = 42; - // The error_handlers are used in this thread (see leaf::try_handle_all - // below). The arguments passed to individual lambdas are transported from - // the worker thread to the main thread automatically. - auto error_handlers = std::make_tuple( - []( e_failure_info1 const & v1, e_failure_info2 const & v2, e_thread_id const & tid ) - { - std::cerr << "Error in thread " << tid.value << "! failure_info1: " << v1.value << ", failure_info2: " << v2.value << std::endl; - }, - []( leaf::diagnostic_info const & unmatched ) - { - std::cerr << - "Unknown failure detected" << std::endl << - "Cryptic diagnostic information follows" << std::endl << - unmatched; - } ); - // Container to collect the generated std::future objects. std::vector>> fut; // Launch the tasks, but rather than launching the task function directly, - // we launch a wrapper function which calls leaf::capture, passing a context - // object that will hold the error objects reported from the task in case of - // an error. The error types the context is able to hold statically are - // automatically deduced from the type of the error_handlers tuple. + // we use leaf::try_capture_all: in case of a failure, the returned leaf::result<> + // will capture all error objects. std::generate_n( std::back_inserter(fut), task_count, [&] { @@ -74,7 +70,7 @@ int main() std::launch::async, [&] { - return leaf::capture(leaf::make_shared_context(error_handlers), &task); + return leaf::try_capture_all(task); } ); } ); @@ -86,14 +82,24 @@ int main() leaf::try_handle_all( [&]() -> leaf::result { - BOOST_LEAF_AUTO(r,f.get()); + BOOST_LEAF_AUTO(r, f.get()); // Success! Use r to access task_result. std::cout << "Success!" << std::endl; (void) r; // Presumably we'll somehow use the task_result. return { }; }, - error_handlers ); + []( e_failure_info1 const & v1, e_failure_info2 const & v2, e_thread_id const & tid ) + { + std::cerr << "Error in thread " << tid.value << "! failure_info1: " << v1.value << ", failure_info2: " << v2.value << std::endl; + }, + []( leaf::diagnostic_info const & unmatched ) + { + std::cerr << + "Unknown failure detected" << std::endl << + "Cryptic diagnostic information follows" << std::endl << + unmatched; + } ); } } @@ -103,17 +109,19 @@ int main() namespace boost { - BOOST_LEAF_NORETURN void throw_exception( std::exception const & e ) + [[noreturn]] void throw_exception( std::exception const & e ) { std::cerr << "Terminating due to a C++ exception under BOOST_LEAF_NO_EXCEPTIONS: " << e.what(); std::terminate(); } struct source_location; - BOOST_LEAF_NORETURN void throw_exception( std::exception const & e, boost::source_location const & ) + [[noreturn]] void throw_exception( std::exception const & e, boost::source_location const & ) { throw_exception(e); } } #endif + +#endif diff --git a/gen/generate_single_header.py b/gen/generate_single_header.py index 623fddfb..5eed44e6 100644 --- a/gen/generate_single_header.py +++ b/gen/generate_single_header.py @@ -1,6 +1,6 @@ """ - Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. + Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc. Copyright (c) Sorin Fetche Distributed under the Boost Software License, Version 1.0. (See accompanying @@ -18,33 +18,53 @@ import argparse import os +import filecmp import re from datetime import date import subprocess -included = {} -total_line_count = 11 +def compare_and_update(old_file, new_file): + if not os.path.exists(old_file): + os.rename(new_file, old_file) + elif filecmp.cmp(old_file, new_file, shallow=False): + os.remove(new_file) + else: + os.remove(old_file) + os.rename(new_file, old_file) -def append(input_file_name, input_file, output_file, regex_includes, include_folder): +included = {} +total_line_count = 14 +def append(input_file_name, input_file, output_file, regex_includes, include_folder, line_directive_prefix, depth): global total_line_count + inside_copyright = False line_count = 1 for line in input_file: line_count += 1 + if 'Emil Dotchevski' in line: + inside_copyright = True + if inside_copyright: + if line.startswith('//') : + continue + if not line.strip(): + inside_copyright = False + if depth > 0: + output_file.write('%s#line %d "%s"\n' % (line_directive_prefix, line_count, input_file_name)) + continue result = regex_includes.search(line) if result: - next_input_file_name = result.group("include") + next_input_file_name = result.group('include') if next_input_file_name in included: - output_file.write("// Expanded at line %d: %s" % (included[next_input_file_name], line)) + output_file.write('// %s // Expanded at line %d\n' % (line.strip(), included[next_input_file_name])) total_line_count += 1 else: included[next_input_file_name] = total_line_count - print("%s (%d)" % (next_input_file_name, total_line_count)) - with open(os.path.join(include_folder, next_input_file_name), "r") as next_input_file: - output_file.write('// >>> %s#line 1 "%s"\n' % (line, next_input_file_name)) + print('%s (%d)' % (next_input_file_name, total_line_count)) + with open(os.path.join(include_folder, next_input_file_name), 'r') as next_input_file: + output_file.write('// >>> %s' % (line)) total_line_count += 2 - append(next_input_file_name, next_input_file, output_file, regex_includes, include_folder) - if not ('include/boost/leaf/detail/all.hpp' in input_file_name): - output_file.write('// <<< %s#line %d "%s"\n' % (line, line_count, input_file_name)) + append(next_input_file_name, next_input_file, output_file, regex_includes, include_folder, line_directive_prefix, depth + 1) + if depth > 0: + output_file.write('// <<< %s%s#line %d "%s"\n' % (line, line_directive_prefix, line_count, input_file_name)) total_line_count += 2 else: output_file.write(line) @@ -52,41 +72,49 @@ def append(input_file_name, input_file, output_file, regex_includes, include_fol def _main(): parser = argparse.ArgumentParser( - description="Generates a single include file from a file including multiple C/C++ headers") - parser.add_argument("-i", "--input", action="store", type=str, default="in.cpp", - help="Input file including the headers to be merged") - parser.add_argument("-o", "--output", action="store", type=str, default="out.cpp", - help="Output file. NOTE: It will be overwritten!") - parser.add_argument("-p", "--path", action="store", type=str, default=".", - help="Include path") - parser.add_argument("--hash", action="store", type=str, - help="The git hash to print in the output file, e.g. the output of \"git rev-parse HEAD\"") - parser.add_argument("prefix", action="store", type=str, - help="Non-empty include file prefix (e.g. a/b)") + description='Generates a single include file from a file including multiple C/C++ headers') + parser.add_argument('-i', '--input', action='store', type=str, default='in.cpp', + help='Input file including the headers to be merged') + parser.add_argument('-o', '--output', action='store', type=str, default='out.cpp', + help='Output file. NOTE: It will be overwritten!') + parser.add_argument('-p', '--path', action='store', type=str, default='.', + help='Include path') + parser.add_argument('--hash', action='store', type=str, + help='The git hash to print in the output file, e.g. the output of "git rev-parse HEAD"') + parser.add_argument('prefix', action='store', type=str, + help='Non-empty include file prefix (e.g. a/b)') + parser.add_argument('--linerefs', action='store_true', + help='Output #line references to the original files. By default the line references are written commented out') args = parser.parse_args() regex_includes = re.compile(r"""^\s*#[\t\s]*include[\t\s]*("|\<)(?P%s.*)("|\>)""" % args.prefix) - print("Rebuilding %s:" % args.input) - with open(args.output, 'w') as output_file, open(args.input, 'r') as input_file: - output_file.write( + print('Rebuilding %s:' % args.input) + tmp_file_name = args.output + '.tmp' + with open(tmp_file_name, 'w') as tmp_file, open(args.input, 'r') as input_file: + tmp_file.write( '#ifndef BOOST_LEAF_HPP_INCLUDED\n' '#define BOOST_LEAF_HPP_INCLUDED\n' '\n' - '// LEAF single header distribution. Do not edit.\n' - '\n' - '// Generated on ' + date.today().strftime("%m/%d/%Y")) + '// Boost LEAF single header distribution. Do not edit.\n' + '// Generated on ' + date.today().strftime('%b %d, %Y')) if args.hash: - output_file.write( + tmp_file.write( ' from https://github.com/boostorg/leaf/tree/' + args.hash[0:7]) - output_file.write( + tmp_file.write( '.\n' - '// Latest version of this file: https://raw.githubusercontent.com/boostorg/leaf/gh-pages/leaf.hpp.\n' + '\n' + '// Latest published version of this file: https://raw.githubusercontent.com/boostorg/leaf/gh-pages/leaf.hpp.\n' + '\n' + '// Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc.\n' + '// Distributed under the Boost Software License, Version 1.0. (See accompanying\n' + '// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n' '\n') - append(args.input, input_file, output_file, regex_includes, args.path) - output_file.write( + append(args.input, input_file, tmp_file, regex_includes, args.path, '' if args.linerefs else '// ', 0) + tmp_file.write( '\n' - '#endif\n' ) -# print("%d" % total_line_count) + '#endif // BOOST_LEAF_HPP_INCLUDED\n' ) + compare_and_update(args.output, tmp_file_name) +# print('%d' % total_line_count) if __name__ == "__main__": _main() diff --git a/include/boost/leaf.hpp b/include/boost/leaf.hpp index 743221b6..84aa7bec 100644 --- a/include/boost/leaf.hpp +++ b/include/boost/leaf.hpp @@ -1,11 +1,10 @@ #ifndef BOOST_LEAF_HPP_INCLUDED #define BOOST_LEAF_HPP_INCLUDED -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. - +// Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include -#endif +#endif // #ifndef BOOST_LEAF_HPP_INCLUDED diff --git a/include/boost/leaf/capture.hpp b/include/boost/leaf/capture.hpp deleted file mode 100644 index 6455eb2d..00000000 --- a/include/boost/leaf/capture.hpp +++ /dev/null @@ -1,235 +0,0 @@ -#ifndef BOOST_LEAF_CAPTURE_HPP_INCLUDED -#define BOOST_LEAF_CAPTURE_HPP_INCLUDED - -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. - -// Distributed under the Boost Software License, Version 1.0. (See accompanying -// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) - -#include -#include -#include - -#if BOOST_LEAF_CFG_CAPTURE - -namespace boost { namespace leaf { - -namespace leaf_detail -{ - template ::value> - struct is_result_tag; - - template - struct is_result_tag - { - }; - - template - struct is_result_tag - { - }; -} - -#ifdef BOOST_LEAF_NO_EXCEPTIONS - -namespace leaf_detail -{ - template - inline - decltype(std::declval()(std::forward(std::declval())...)) - capture_impl(is_result_tag, context_ptr && ctx, F && f, A... a) noexcept - { - auto active_context = activate_context(*ctx); - return std::forward(f)(std::forward(a)...); - } - - template - inline - decltype(std::declval()(std::forward(std::declval())...)) - capture_impl(is_result_tag, context_ptr && ctx, F && f, A... a) noexcept - { - auto active_context = activate_context(*ctx); - if( auto r = std::forward(f)(std::forward(a)...) ) - return r; - else - { - ctx->captured_id_ = r.error(); - return std::move(ctx); - } - } - - template - inline - decltype(std::declval().get()) - future_get_impl(is_result_tag, Future & fut) noexcept - { - return fut.get(); - } - - template - inline - decltype(std::declval().get()) - future_get_impl(is_result_tag, Future & fut) noexcept - { - if( auto r = fut.get() ) - return r; - else - return error_id(r.error()); // unloads - } -} - -#else - -namespace leaf_detail -{ - class capturing_exception: - public std::exception - { - std::exception_ptr ex_; - context_ptr ctx_; - - public: - - capturing_exception(std::exception_ptr && ex, context_ptr && ctx) noexcept: - ex_(std::move(ex)), - ctx_(std::move(ctx)) - { - BOOST_LEAF_ASSERT(ex_); - BOOST_LEAF_ASSERT(ctx_); - BOOST_LEAF_ASSERT(ctx_->captured_id_); - } - - [[noreturn]] void unload_and_rethrow_original_exception() const - { - BOOST_LEAF_ASSERT(ctx_->captured_id_); - tls::write_uint32(ctx_->captured_id_.value()); - ctx_->propagate(ctx_->captured_id_); - std::rethrow_exception(ex_); - } - - template - void print( std::basic_ostream & os ) const - { - ctx_->print(os); - } - }; - - template - inline - decltype(std::declval()(std::forward(std::declval())...)) - capture_impl(is_result_tag, context_ptr && ctx, F && f, A... a) - { - auto active_context = activate_context(*ctx); - error_monitor cur_err; - try - { - return std::forward(f)(std::forward(a)...); - } - catch( capturing_exception const & ) - { - throw; - } - catch( exception_base const & e ) - { - ctx->captured_id_ = e.get_error_id(); - throw_exception( capturing_exception(std::current_exception(), std::move(ctx)) ); - } - catch(...) - { - ctx->captured_id_ = cur_err.assigned_error_id(); - throw_exception( capturing_exception(std::current_exception(), std::move(ctx)) ); - } - } - - template - inline - decltype(std::declval()(std::forward(std::declval())...)) - capture_impl(is_result_tag, context_ptr && ctx, F && f, A... a) - { - auto active_context = activate_context(*ctx); - error_monitor cur_err; - try - { - if( auto && r = std::forward(f)(std::forward(a)...) ) - return std::move(r); - else - { - ctx->captured_id_ = r.error(); - return std::move(ctx); - } - } - catch( capturing_exception const & ) - { - throw; - } - catch( exception_base const & e ) - { - ctx->captured_id_ = e.get_error_id(); - throw_exception( capturing_exception(std::current_exception(), std::move(ctx)) ); - } - catch(...) - { - ctx->captured_id_ = cur_err.assigned_error_id(); - throw_exception( capturing_exception(std::current_exception(), std::move(ctx)) ); - } - } - - template - inline - decltype(std::declval().get()) - future_get_impl(is_result_tag, Future & fut ) - { - try - { - return fut.get(); - } - catch( capturing_exception const & cap ) - { - cap.unload_and_rethrow_original_exception(); - } - } - - template - inline - decltype(std::declval().get()) - future_get_impl(is_result_tag, Future & fut ) - { - try - { - if( auto r = fut.get() ) - return r; - else - return error_id(r.error()); // unloads - } - catch( capturing_exception const & cap ) - { - cap.unload_and_rethrow_original_exception(); - } - } -} - -#endif - -template -inline -decltype(std::declval()(std::forward(std::declval())...)) -capture(context_ptr && ctx, F && f, A... a) -{ - using namespace leaf_detail; - return capture_impl(is_result_tag()(std::forward(std::declval())...))>(), std::move(ctx), std::forward(f), std::forward(a)...); -} - -template -inline -decltype(std::declval().get()) -future_get( Future & fut ) -{ - using namespace leaf_detail; - return future_get_impl(is_result_tag().get())>(), fut); -} - -} } - -#endif - -#endif diff --git a/include/boost/leaf/common.hpp b/include/boost/leaf/common.hpp index 2069f55a..4eac22e0 100644 --- a/include/boost/leaf/common.hpp +++ b/include/boost/leaf/common.hpp @@ -1,8 +1,7 @@ #ifndef BOOST_LEAF_COMMON_HPP_INCLUDED #define BOOST_LEAF_COMMON_HPP_INCLUDED -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. - +// Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) @@ -10,13 +9,15 @@ #include #include +#include +#include + #if BOOST_LEAF_CFG_STD_STRING # include #endif -#include + #if BOOST_LEAF_CFG_WIN32 # include -# include # ifdef min # undef min # endif @@ -27,41 +28,41 @@ namespace boost { namespace leaf { -struct BOOST_LEAF_SYMBOL_VISIBLE e_api_function { char const * value; }; +struct e_api_function { char const * value; }; #if BOOST_LEAF_CFG_STD_STRING -struct BOOST_LEAF_SYMBOL_VISIBLE e_file_name +struct e_file_name { std::string value; }; #else -struct BOOST_LEAF_SYMBOL_VISIBLE e_file_name +struct e_file_name { - constexpr static char const * const value = ""; + char const * value = ""; BOOST_LEAF_CONSTEXPR explicit e_file_name( char const * ) { } }; #endif -struct BOOST_LEAF_SYMBOL_VISIBLE e_errno +struct e_errno { int value; - explicit e_errno(int value=errno): value(value) { } + explicit e_errno(int val=errno): value(val) { } template - friend std::basic_ostream & operator<<(std::basic_ostream & os, e_errno const & err) + friend std::ostream & operator<<(std::basic_ostream & os, e_errno const & err) { - return os << type() << ": " << err.value << ", \"" << std::strerror(err.value) << '"'; + return os << err.value << ", \"" << std::strerror(err.value) << '"'; } }; -struct BOOST_LEAF_SYMBOL_VISIBLE e_type_info_name { char const * value; }; +struct e_type_info_name { char const * value; }; -struct BOOST_LEAF_SYMBOL_VISIBLE e_at_line { int value; }; +struct e_at_line { int value; }; namespace windows { @@ -69,13 +70,13 @@ namespace windows { unsigned value; - explicit e_LastError(unsigned value): value(value) { } + explicit e_LastError(unsigned val): value(val) { } #if BOOST_LEAF_CFG_WIN32 e_LastError(): value(GetLastError()) { } template - friend std::basic_ostream & operator<<(std::basic_ostream & os, e_LastError const & err) + friend std::ostream & operator<<(std::basic_ostream & os, e_LastError const & err) { struct msg_buf { @@ -95,18 +96,18 @@ namespace windows { BOOST_LEAF_ASSERT(mb.p != nullptr); char * z = std::strchr((LPSTR)mb.p,0); - if( z[-1] == '\n' ) + if( z != (LPSTR)mb.p && z[-1] == '\n' ) *--z = 0; - if( z[-1] == '\r' ) + if( z != (LPSTR)mb.p && z[-1] == '\r' ) *--z = 0; - return os << type() << ": " << err.value << ", \"" << (LPCSTR)mb.p << '"'; + return os << err.value << ", \"" << (LPCSTR)mb.p << '"'; } return os; } -#endif +#endif // #if BOOST_LEAF_CFG_WIN32 }; -} +} // namespace windows -} } +} } // namespace boost::leaf -#endif +#endif // #ifndef BOOST_LEAF_COMMON_HPP_INCLUDED diff --git a/include/boost/leaf/config.hpp b/include/boost/leaf/config.hpp index 7c7e7d2b..87a4e123 100644 --- a/include/boost/leaf/config.hpp +++ b/include/boost/leaf/config.hpp @@ -1,59 +1,39 @@ #ifndef BOOST_LEAF_CONFIG_HPP_INCLUDED #define BOOST_LEAF_CONFIG_HPP_INCLUDED -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. - +// Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// The following is based in part on Boost Config. - -// (C) Copyright John Maddock 2001 - 2003. -// (C) Copyright Martin Wille 2003. -// (C) Copyright Guillaume Melquiond 2003. - -#ifndef BOOST_LEAF_ASSERT -# include -# define BOOST_LEAF_ASSERT assert -#endif - -//////////////////////////////////////// - -#ifdef BOOST_LEAF_DIAGNOSTICS -# warning BOOST_LEAF_DIAGNOSTICS has been renamed to BOOST_LEAF_CFG_DIAGNOSTICS. -# define BOOST_LEAF_CFG_DIAGNOSTICS BOOST_LEAF_DIAGNOSTICS -#endif - -//////////////////////////////////////// +#include +#include #ifdef BOOST_LEAF_TLS_FREERTOS - # ifndef BOOST_LEAF_EMBEDDED # define BOOST_LEAF_EMBEDDED # endif - #endif -//////////////////////////////////////// - #ifdef BOOST_LEAF_EMBEDDED - # ifndef BOOST_LEAF_CFG_DIAGNOSTICS # define BOOST_LEAF_CFG_DIAGNOSTICS 0 # endif - # ifndef BOOST_LEAF_CFG_STD_SYSTEM_ERROR # define BOOST_LEAF_CFG_STD_SYSTEM_ERROR 0 # endif - # ifndef BOOST_LEAF_CFG_STD_STRING # define BOOST_LEAF_CFG_STD_STRING 0 # endif - # ifndef BOOST_LEAF_CFG_CAPTURE # define BOOST_LEAF_CFG_CAPTURE 0 # endif +#endif // #ifdef BOOST_LEAF_EMBEDDED +//////////////////////////////////////// + +#ifndef BOOST_LEAF_ASSERT +# include +# define BOOST_LEAF_ASSERT assert #endif //////////////////////////////////////// @@ -86,135 +66,103 @@ # endif #endif -#if BOOST_LEAF_CFG_DIAGNOSTICS!=0 && BOOST_LEAF_CFG_DIAGNOSTICS!=1 +#ifndef BOOST_LEAF_CFG_DIAGNOSTICS_FIRST_DELIMITER +# define BOOST_LEAF_CFG_DIAGNOSTICS_FIRST_DELIMITER "\n " +#endif + +#ifndef BOOST_LEAF_CFG_DIAGNOSTICS_DELIMITER +# define BOOST_LEAF_CFG_DIAGNOSTICS_DELIMITER "\n " +#endif + +#if BOOST_LEAF_CFG_DIAGNOSTICS != 0 && BOOST_LEAF_CFG_DIAGNOSTICS != 1 # error BOOST_LEAF_CFG_DIAGNOSTICS must be 0 or 1. #endif -#if BOOST_LEAF_CFG_STD_SYSTEM_ERROR!=0 && BOOST_LEAF_CFG_STD_SYSTEM_ERROR!=1 +#if BOOST_LEAF_CFG_STD_SYSTEM_ERROR != 0 && BOOST_LEAF_CFG_STD_SYSTEM_ERROR != 1 # error BOOST_LEAF_CFG_STD_SYSTEM_ERROR must be 0 or 1. #endif -#if BOOST_LEAF_CFG_STD_STRING!=0 && BOOST_LEAF_CFG_STD_STRING!=1 +#if BOOST_LEAF_CFG_STD_STRING != 0 && BOOST_LEAF_CFG_STD_STRING != 1 # error BOOST_LEAF_CFG_STD_STRING must be 0 or 1. #endif -#if BOOST_LEAF_CFG_CAPTURE!=0 && BOOST_LEAF_CFG_CAPTURE!=1 +#if BOOST_LEAF_CFG_CAPTURE != 0 && BOOST_LEAF_CFG_CAPTURE != 1 # error BOOST_LEAF_CFG_CAPTURE must be 0 or 1. #endif -#if BOOST_LEAF_CFG_DIAGNOSTICS && !BOOST_LEAF_CFG_STD_STRING -# error BOOST_LEAF_CFG_DIAGNOSTICS requires the use of std::string +#if BOOST_LEAF_CFG_WIN32 != 0 && BOOST_LEAF_CFG_WIN32 != 1 && BOOST_LEAF_CFG_WIN32 != 2 +# error BOOST_LEAF_CFG_WIN32 must be 0 or 1 or 2. #endif -#if BOOST_LEAF_CFG_WIN32!=0 && BOOST_LEAF_CFG_WIN32!=1 -# error BOOST_LEAF_CFG_WIN32 must be 0 or 1. +#if BOOST_LEAF_CFG_WIN32 && !defined(_WIN32) +# warning "Ignoring BOOST_LEAF_CFG_WIN32 because _WIN32 is not defined" +# define BOOST_LEAF_CFG_WIN32 0 #endif -#if BOOST_LEAF_CFG_GNUC_STMTEXPR!=0 && BOOST_LEAF_CFG_GNUC_STMTEXPR!=1 +#if BOOST_LEAF_CFG_GNUC_STMTEXPR != 0 && BOOST_LEAF_CFG_GNUC_STMTEXPR != 1 # error BOOST_LEAF_CFG_GNUC_STMTEXPR must be 0 or 1. #endif +#if BOOST_LEAF_CFG_DIAGNOSTICS && !BOOST_LEAF_CFG_STD_STRING +# error BOOST_LEAF_CFG_DIAGNOSTICS requires BOOST_LEAF_CFG_STD_STRING, which has been disabled. +#endif + +#if BOOST_LEAF_CFG_STD_SYSTEM_ERROR && !BOOST_LEAF_CFG_STD_STRING +# error BOOST_LEAF_CFG_STD_SYSTEM_ERROR requires BOOST_LEAF_CFG_STD_STRING, which has been disabled. +#endif + //////////////////////////////////////// -// Configure BOOST_LEAF_NO_EXCEPTIONS, unless already #defined -#ifndef BOOST_LEAF_NO_EXCEPTIONS +#ifndef BOOST_LEAF_PRETTY_FUNCTION +# if defined(_MSC_VER) && !defined(__clang__) && !defined(__GNUC__) +# define BOOST_LEAF_PRETTY_FUNCTION __FUNCSIG__ +# else +# define BOOST_LEAF_PRETTY_FUNCTION __PRETTY_FUNCTION__ +# endif +#endif + +//////////////////////////////////////// +#ifndef BOOST_LEAF_NO_EXCEPTIONS +// The following is based in part on Boost Config. +// (C) Copyright John Maddock 2001 - 2003. +// (C) Copyright Martin Wille 2003. +// (C) Copyright Guillaume Melquiond 2003. # if defined(__clang__) && !defined(__ibmxl__) // Clang C++ emulates GCC, so it has to appear early. - # if !__has_feature(cxx_exceptions) # define BOOST_LEAF_NO_EXCEPTIONS # endif - -# elif defined(__DMC__) -// Digital Mars C++ - -# if !defined(_CPPUNWIND) -# define BOOST_LEAF_NO_EXCEPTIONS -# endif - # elif defined(__GNUC__) && !defined(__ibmxl__) // GNU C++: - # if !defined(__EXCEPTIONS) # define BOOST_LEAF_NO_EXCEPTIONS # endif - -# elif defined(__KCC) -// Kai C++ - -# if !defined(_EXCEPTIONS) -# define BOOST_LEAF_NO_EXCEPTIONS -# endif - # elif defined(__CODEGEARC__) // CodeGear - must be checked for before Borland - # if !defined(_CPPUNWIND) && !defined(__EXCEPTIONS) # define BOOST_LEAF_NO_EXCEPTIONS # endif - -# elif defined(__BORLANDC__) -// Borland - -# if !defined(_CPPUNWIND) && !defined(__EXCEPTIONS) -# define BOOST_LEAF_NO_EXCEPTIONS -# endif - -# elif defined(__MWERKS__) -// Metrowerks CodeWarrior - -# if !__option(exceptions) -# define BOOST_LEAF_NO_EXCEPTIONS -# endif - # elif defined(__IBMCPP__) && defined(__COMPILER_VER__) && defined(__MVS__) // IBM z/OS XL C/C++ - # if !defined(_CPPUNWIND) && !defined(__EXCEPTIONS) # define BOOST_LEAF_NO_EXCEPTIONS # endif - # elif defined(__ibmxl__) // IBM XL C/C++ for Linux (Little Endian) - # if !__has_feature(cxx_exceptions) # define BOOST_LEAF_NO_EXCEPTIONS # endif - # elif defined(_MSC_VER) // Microsoft Visual C++ -// // Must remain the last #elif since some other vendors (Metrowerks, for // example) also #define _MSC_VER - # if !_CPPUNWIND # define BOOST_LEAF_NO_EXCEPTIONS # endif # endif -#endif - -#ifdef BOOST_NORETURN -# define BOOST_LEAF_NORETURN BOOST_NORETURN -#else -# if defined(_MSC_VER) -# define BOOST_LEAF_NORETURN __declspec(noreturn) -# elif defined(__GNUC__) -# define BOOST_LEAF_NORETURN __attribute__ ((__noreturn__)) -# elif defined(__has_attribute) && defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x5130) -# if __has_attribute(noreturn) -# define BOOST_LEAF_NORETURN [[noreturn]] -# endif -# elif defined(__has_cpp_attribute) -# if __has_cpp_attribute(noreturn) -# define BOOST_LEAF_NORETURN [[noreturn]] -# endif -# endif -#endif -#if !defined(BOOST_LEAF_NORETURN) -# define BOOST_LEAF_NORETURN -#endif +#endif // #ifndef BOOST_LEAF_NO_EXCEPTIONS //////////////////////////////////////// @@ -226,13 +174,19 @@ //////////////////////////////////////// -#ifndef BOOST_LEAF_NODISCARD -# if __cplusplus >= 201703L -# define BOOST_LEAF_NODISCARD [[nodiscard]] -# else -# define BOOST_LEAF_NODISCARD +#if defined(__has_attribute) && defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x5130) +# if __has_attribute(nodiscard) +# define BOOST_LEAF_ATTRIBUTE_NODISCARD [[nodiscard]] +# endif +#elif defined(__has_cpp_attribute) +// require c++17 regardless of compiler +# if __has_cpp_attribute(nodiscard) && __cplusplus >= 201703L +# define BOOST_LEAF_ATTRIBUTE_NODISCARD [[nodiscard]] # endif #endif +#ifndef BOOST_LEAF_ATTRIBUTE_NODISCARD +# define BOOST_LEAF_ATTRIBUTE_NODISCARD +#endif //////////////////////////////////////// @@ -246,8 +200,17 @@ //////////////////////////////////////// +#ifndef BOOST_LEAF_DEPRECATED +# if __cplusplus > 201402L +# define BOOST_LEAF_DEPRECATED(msg) [[deprecated(msg)]] +# else +# define BOOST_LEAF_DEPRECATED(msg) +# endif +#endif + +//////////////////////////////////////// + #ifndef BOOST_LEAF_NO_EXCEPTIONS -# include # if (defined(__cpp_lib_uncaught_exceptions) && __cpp_lib_uncaught_exceptions >= 201411L) || (defined(_MSC_VER) && _MSC_VER >= 1900) # define BOOST_LEAF_STD_UNCAUGHT_EXCEPTIONS 1 # else @@ -258,11 +221,13 @@ //////////////////////////////////////// #ifdef __GNUC__ -# define BOOST_LEAF_SYMBOL_VISIBLE __attribute__((__visibility__("default"))) +# define BOOST_LEAF_SYMBOL_VISIBLE [[gnu::visibility("default")]] #else # define BOOST_LEAF_SYMBOL_VISIBLE #endif +#include + //////////////////////////////////////// #if defined(__GNUC__) && !(defined(__clang__) || defined(__INTEL_COMPILER) || defined(__ICL) || defined(__ICC) || defined(__ECC)) && (__GNUC__ * 100 + __GNUC_MINOR__) < 409 @@ -273,9 +238,36 @@ //////////////////////////////////////// -// Configure TLS access -#include +#ifdef _MSC_VER +# define BOOST_LEAF_UNREACHABLE __assume(0) +#else +# define BOOST_LEAF_UNREACHABLE __builtin_unreachable() +#endif //////////////////////////////////////// +namespace boost +{ + [[noreturn]] void throw_exception( std::exception const & ); // user defined +} + +namespace boost { namespace leaf { + +template +[[noreturn]] void throw_exception_( T && e ) +{ +#ifdef BOOST_LEAF_NO_EXCEPTIONS + ::boost::throw_exception(std::move(e)); +#else + throw std::move(e); #endif +} + +} } + +//////////////////////////////////////// + +// Configure TLS access +#include + +#endif // #ifndef BOOST_LEAF_CONFIG_HPP_INCLUDED diff --git a/include/boost/leaf/config/tls.hpp b/include/boost/leaf/config/tls.hpp index 279bafb2..a495383b 100644 --- a/include/boost/leaf/config/tls.hpp +++ b/include/boost/leaf/config/tls.hpp @@ -1,13 +1,68 @@ #ifndef BOOST_LEAF_CONFIG_TLS_HPP_INCLUDED #define BOOST_LEAF_CONFIG_TLS_HPP_INCLUDED -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. - +// Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +namespace boost { namespace leaf { + +// The following declarations specify the thread local storage API used +// internally by LEAF. To port LEAF to a new TLS API, provide definitions for +// each of these functions. +namespace tls +{ + // Generate the next unique error_id. Values start at 1 and increment by 4. + // Error ids must be unique for the lifetime of the process, and this + // function must be thread-safe. Postcondition: (id & 3) == 1 && id != 0. + // + // This function may not fail. + unsigned generate_next_error_id() noexcept; + + // Write x to the TLS for the current error_id. The initial value for each + // thread must be 0. Precondition: x == 0 or (x & 3) == 1. + // + // This function may not fail. + void write_current_error_id( unsigned x ) noexcept; + + // Read the current error_id for this thread. The initial value for each + // thread must be 0. + // + // This function may not fail. + unsigned read_current_error_id() noexcept; + + // Reserve TLS storage for T. The TLS may be allocated dynamically on the + // first call to reserve_ptr, but subsequent calls must reuse the same + // TLS. On platforms where allocation is not needed, this function is + // still defined but does nothing. + // + // This function may throw on allocation failure. + template + void reserve_ptr(); + + // Write p to the TLS previously reserved for T by a call to reserve_ptr. + // It is illegal to call write_ptr without a prior successful call to + // reserve_ptr. + // + // This function may not fail. + template + void write_ptr( T * p ) noexcept; + + // Read the T * value previously written in the TLS for T. Returns nullptr + // if TLS for T has not yet been reserved. + // + // This function may not fail. + template + T * read_ptr() noexcept; +} // namespace tls + +} } // namespace boost::leaf + #if defined(BOOST_LEAF_TLS_FREERTOS) # include +# ifndef BOOST_LEAF_USE_TLS_ARRAY +# define BOOST_LEAF_USE_TLS_ARRAY +# endif #endif #ifndef BOOST_LEAF_USE_TLS_ARRAY @@ -24,10 +79,12 @@ #if defined BOOST_LEAF_USE_TLS_ARRAY # include +#elif BOOST_LEAF_CFG_WIN32 == 2 +# include #elif defined(BOOST_LEAF_NO_THREADS) # include #else # include #endif -#endif +#endif // #ifndef BOOST_LEAF_CONFIG_TLS_HPP_INCLUDED \ No newline at end of file diff --git a/include/boost/leaf/config/tls_array.hpp b/include/boost/leaf/config/tls_array.hpp index f194c56c..a595022e 100644 --- a/include/boost/leaf/config/tls_array.hpp +++ b/include/boost/leaf/config/tls_array.hpp @@ -1,16 +1,15 @@ #ifndef BOOST_LEAF_CONFIG_TLS_ARRAY_HPP_INCLUDED #define BOOST_LEAF_CONFIG_TLS_ARRAY_HPP_INCLUDED -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. -// Copyright (c) 2022 Khalil Estell - +// Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// LEAF requires thread local storage support for pointers and for uin32_t values. +// Copyright (c) 2022 Khalil Estell -// This header implements thread local storage for pointers and for uint32_t -// values for platforms that support thread local pointers by index. +// This header implements the TLS API specified in tls.hpp for platforms that +// provide TLS by indexing an array (this is typical for embedded platforms). +// The array is accessed via user-defined functions. namespace boost { namespace leaf { @@ -26,8 +25,8 @@ namespace tls //////////////////////////////////////// -#include #include +#include #include #include @@ -53,29 +52,44 @@ static_assert((BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX) >= 0, namespace boost { namespace leaf { -namespace leaf_detail +namespace detail { using atomic_unsigned_int = std::atomic; -} -namespace tls -{ + template + struct BOOST_LEAF_SYMBOL_VISIBLE id_factory + { + static atomic_unsigned_int counter; + }; + + template + atomic_unsigned_int id_factory::counter(1); + template class BOOST_LEAF_SYMBOL_VISIBLE index_counter { static int c_; - public: - - static BOOST_LEAF_CFG_TLS_INDEX_TYPE next() + BOOST_LEAF_ALWAYS_INLINE static BOOST_LEAF_CFG_TLS_INDEX_TYPE next_() noexcept { int idx = ++c_; - BOOST_LEAF_ASSERT(idx > (BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX)); + BOOST_LEAF_ASSERT(idx > (BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX + 1)); BOOST_LEAF_ASSERT(idx < (BOOST_LEAF_CFG_TLS_ARRAY_SIZE)); return idx; } + + public: + + template + BOOST_LEAF_ALWAYS_INLINE static BOOST_LEAF_CFG_TLS_INDEX_TYPE next() noexcept + { + return next_(); + } }; + template + int index_counter::c_ = BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX + 1; + template struct BOOST_LEAF_SYMBOL_VISIBLE tls_index { @@ -83,70 +97,72 @@ namespace tls }; template - struct BOOST_LEAF_SYMBOL_VISIBLE alloc_tls_index + BOOST_LEAF_CFG_TLS_INDEX_TYPE tls_index::idx = BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX + 1; + + template + struct BOOST_LEAF_SYMBOL_VISIBLE reserve_tls_index { static BOOST_LEAF_CFG_TLS_INDEX_TYPE const idx; }; template - int index_counter::c_ = BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX; + BOOST_LEAF_CFG_TLS_INDEX_TYPE const reserve_tls_index::idx = tls_index::idx = index_counter<>::next(); +} // namespace detail - template - BOOST_LEAF_CFG_TLS_INDEX_TYPE tls_index::idx = BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX; +} } // namespace boost::leaf - template - BOOST_LEAF_CFG_TLS_INDEX_TYPE const alloc_tls_index::idx = tls_index::idx = index_counter<>::next(); +//////////////////////////////////////// - //////////////////////////////////////// +namespace boost { namespace leaf { - template - T * read_ptr() noexcept +namespace tls +{ + BOOST_LEAF_ALWAYS_INLINE unsigned generate_next_error_id() noexcept { - int tls_idx = tls_index::idx; - if( tls_idx == (BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX) ) - return nullptr; - --tls_idx; - return reinterpret_cast(read_void_ptr(tls_idx)); + unsigned id = (detail::id_factory<>::counter += 4); + BOOST_LEAF_ASSERT((id&3) == 1); + return id; } - template - void write_ptr( T * p ) noexcept + BOOST_LEAF_ALWAYS_INLINE void write_current_error_id( unsigned x ) noexcept { - int tls_idx = alloc_tls_index::idx; - --tls_idx; - write_void_ptr(tls_idx, p); - BOOST_LEAF_ASSERT(read_void_ptr(tls_idx) == p); + static_assert(sizeof(std::intptr_t) >= sizeof(unsigned), "Incompatible tls_array implementation"); + write_void_ptr(BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX, (void *) (std::intptr_t) x); } - //////////////////////////////////////// - - template - std::uint32_t read_uint32() noexcept + BOOST_LEAF_ALWAYS_INLINE unsigned read_current_error_id() noexcept { - static_assert(sizeof(std::intptr_t) >= sizeof(std::uint32_t), "Incompatible tls_array implementation"); - return (std::uint32_t) (std::intptr_t) (void *) read_ptr(); + static_assert(sizeof(std::intptr_t) >= sizeof(unsigned), "Incompatible tls_array implementation"); + return (unsigned) (std::intptr_t) read_void_ptr(BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX); } - template - void write_uint32( std::uint32_t x ) noexcept + template + BOOST_LEAF_ALWAYS_INLINE void reserve_ptr() { - static_assert(sizeof(std::intptr_t) >= sizeof(std::uint32_t), "Incompatible tls_array implementation"); - write_ptr((Tag *) (void *) (std::intptr_t) x); + (void) detail::reserve_tls_index::idx; } - template - void uint32_increment() noexcept + template + BOOST_LEAF_ALWAYS_INLINE void write_ptr( T * p ) noexcept { - write_uint32(read_uint32() + 1); + int tls_idx = detail::tls_index::idx; + BOOST_LEAF_ASSERT(tls_idx != (BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX + 1)); + --tls_idx; + write_void_ptr(tls_idx, p); + BOOST_LEAF_ASSERT(read_void_ptr(tls_idx) == p); } - template - void uint32_decrement() noexcept + template + BOOST_LEAF_ALWAYS_INLINE T * read_ptr() noexcept { - write_uint32(read_uint32() - 1); + int tls_idx = detail::tls_index::idx; + if( tls_idx == (BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX + 1) ) + return nullptr; + --tls_idx; + return reinterpret_cast(read_void_ptr(tls_idx)); } -} +} // namespace tls -} } +} } // namespace boost::leaf -#endif +#endif // #ifndef BOOST_LEAF_CONFIG_TLS_ARRAY_HPP_INCLUDED diff --git a/include/boost/leaf/config/tls_cpp11.hpp b/include/boost/leaf/config/tls_cpp11.hpp index dbc6711e..f5aa5c74 100644 --- a/include/boost/leaf/config/tls_cpp11.hpp +++ b/include/boost/leaf/config/tls_cpp11.hpp @@ -1,28 +1,34 @@ #ifndef BOOST_LEAF_CONFIG_TLS_CPP11_HPP_INCLUDED #define BOOST_LEAF_CONFIG_TLS_CPP11_HPP_INCLUDED -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. - +// Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// LEAF requires thread local storage support for pointers and for uin32_t values. - -// This header implements thread local storage for pointers and for uint32_t -// values using the C++11 built-in thread_local storage class specifier. +// This header implements the TLS API specified in tls.hpp using the C++11 +// built-in thread_local storage class specifier. On Windows, this +// implementation does not allow error objects to cross DLL boundaries. If this +// is required, define BOOST_LEAF_CFG_WIN32=2 before including any LEAF headers +// to enable the alternative implementation defined in tls_win32.hpp. -#include #include +#include namespace boost { namespace leaf { -namespace leaf_detail +namespace detail { using atomic_unsigned_int = std::atomic; -} -namespace tls -{ + template + struct BOOST_LEAF_SYMBOL_VISIBLE id_factory + { + static atomic_unsigned_int counter; + }; + + template + atomic_unsigned_int id_factory::counter(1); + template struct BOOST_LEAF_SYMBOL_VISIBLE ptr { @@ -32,54 +38,59 @@ namespace tls template thread_local T * ptr::p; - template - T * read_ptr() noexcept + template + struct BOOST_LEAF_SYMBOL_VISIBLE current_error_id_storage { - return ptr::p; - } + static thread_local unsigned x; + }; template - void write_ptr( T * p ) noexcept - { - ptr::p = p; - } + thread_local unsigned current_error_id_storage::x; +} // namespace detail - //////////////////////////////////////// +} } // namespace boost::leaf - template - struct BOOST_LEAF_SYMBOL_VISIBLE tagged_uint32 +//////////////////////////////////////// + +namespace boost { namespace leaf { + +namespace tls +{ + BOOST_LEAF_ALWAYS_INLINE unsigned generate_next_error_id() noexcept { - static thread_local std::uint32_t x; - }; + unsigned id = (detail::id_factory<>::counter += 4); + BOOST_LEAF_ASSERT((id&3) == 1); + return id; + } - template - thread_local std::uint32_t tagged_uint32::x; + BOOST_LEAF_ALWAYS_INLINE void write_current_error_id( unsigned x ) noexcept + { + detail::current_error_id_storage<>::x = x; + } - template - std::uint32_t read_uint32() noexcept + BOOST_LEAF_ALWAYS_INLINE unsigned read_current_error_id() noexcept { - return tagged_uint32::x; + return detail::current_error_id_storage<>::x; } - template - void write_uint32( std::uint32_t x ) noexcept + template + BOOST_LEAF_ALWAYS_INLINE void reserve_ptr() { - tagged_uint32::x = x; } - template - void uint32_increment() noexcept + template + BOOST_LEAF_ALWAYS_INLINE void write_ptr( T * p ) noexcept { - ++tagged_uint32::x; + detail::ptr::p = p; } - template - void uint32_decrement() noexcept + template + BOOST_LEAF_ALWAYS_INLINE T * read_ptr() noexcept { - --tagged_uint32::x; + return detail::ptr::p; } -} +} // namespace tls -} } +} } // namespace boost::leaf -#endif +#endif // #ifndef BOOST_LEAF_CONFIG_TLS_CPP11_HPP_INCLUDED diff --git a/include/boost/leaf/config/tls_freertos.hpp b/include/boost/leaf/config/tls_freertos.hpp index a2678693..0c817e4b 100644 --- a/include/boost/leaf/config/tls_freertos.hpp +++ b/include/boost/leaf/config/tls_freertos.hpp @@ -1,17 +1,17 @@ #ifndef BOOST_LEAF_CONFIG_TLS_FREERTOS_HPP_INCLUDED #define BOOST_LEAF_CONFIG_TLS_FREERTOS_HPP_INCLUDED -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. -// Copyright (c) 2022 Khalil Estell - +// Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -#include +// Copyright (c) 2022 Khalil Estell -#ifndef BOOST_LEAF_USE_TLS_ARRAY -# define BOOST_LEAF_USE_TLS_ARRAY -#endif +// This header implements the TLS API specified in tls.hpp via the FreeTOS +// pvTaskGetThreadLocalStoragePointer / pvTaskSetThreadLocalStoragePointer +// functions, using the more general implementation defined in tls_array.hpp. + +#include #ifndef BOOST_LEAF_CFG_TLS_ARRAY_SIZE # define BOOST_LEAF_CFG_TLS_ARRAY_SIZE configNUM_THREAD_LOCAL_STORAGE_POINTERS @@ -26,12 +26,12 @@ namespace tls { // See https://www.freertos.org/thread-local-storage-pointers.html. - inline void * read_void_ptr( int tls_index ) noexcept + BOOST_LEAF_ALWAYS_INLINE void * read_void_ptr( int tls_index ) noexcept { return pvTaskGetThreadLocalStoragePointer(0, tls_index); } - inline void write_void_ptr( int tls_index, void * p ) noexcept + BOOST_LEAF_ALWAYS_INLINE void write_void_ptr( int tls_index, void * p ) noexcept { vTaskSetThreadLocalStoragePointer(0, tls_index, p); } @@ -39,4 +39,4 @@ namespace tls } } -#endif +#endif // #ifndef BOOST_LEAF_CONFIG_TLS_FREERTOS_HPP_INCLUDED diff --git a/include/boost/leaf/config/tls_globals.hpp b/include/boost/leaf/config/tls_globals.hpp index 0dc92ffc..66f3d57f 100644 --- a/include/boost/leaf/config/tls_globals.hpp +++ b/include/boost/leaf/config/tls_globals.hpp @@ -1,27 +1,30 @@ #ifndef BOOST_LEAF_CONFIG_TLS_GLOBALS_HPP_INCLUDED #define BOOST_LEAF_CONFIG_TLS_GLOBALS_HPP_INCLUDED -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. - +// Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -// LEAF requires thread local storage support for pointers and for uin32_t values. - -// This header implements "thread local" storage for pointers and for uint32_t -// values using globals, which is suitable for single thread environments. +// This header implements the TLS API specified in tls.hpp using globals, which +// is suitable for single thread environments. #include namespace boost { namespace leaf { -namespace leaf_detail +namespace detail { using atomic_unsigned_int = unsigned int; -} -namespace tls -{ + template + struct BOOST_LEAF_SYMBOL_VISIBLE id_factory + { + static atomic_unsigned_int counter; + }; + + template + atomic_unsigned_int id_factory::counter = 1; + template struct BOOST_LEAF_SYMBOL_VISIBLE ptr { @@ -31,54 +34,59 @@ namespace tls template T * ptr::p; - template - T * read_ptr() noexcept + template + struct BOOST_LEAF_SYMBOL_VISIBLE current_error_id_storage { - return ptr::p; - } + static unsigned x; + }; template - void write_ptr( T * p ) noexcept - { - ptr::p = p; - } + unsigned current_error_id_storage::x = 0; +} // namespace detail + +} } // namespace boost::leaf - //////////////////////////////////////// +//////////////////////////////////////// + +namespace boost { namespace leaf { - template - struct BOOST_LEAF_SYMBOL_VISIBLE tagged_uint32 +namespace tls +{ + BOOST_LEAF_ALWAYS_INLINE unsigned generate_next_error_id() noexcept { - static std::uint32_t x; - }; + unsigned id = (detail::id_factory<>::counter += 4); + BOOST_LEAF_ASSERT((id&3) == 1); + return id; + } - template - std::uint32_t tagged_uint32::x; + BOOST_LEAF_ALWAYS_INLINE void write_current_error_id( unsigned v ) noexcept + { + detail::current_error_id_storage<>::x = v; + } - template - std::uint32_t read_uint32() noexcept + BOOST_LEAF_ALWAYS_INLINE unsigned read_current_error_id() noexcept { - return tagged_uint32::x; + return detail::current_error_id_storage<>::x; } - template - void write_uint32( std::uint32_t x ) noexcept + template + BOOST_LEAF_ALWAYS_INLINE void reserve_ptr() { - tagged_uint32::x = x; } - template - void uint32_increment() noexcept + template + BOOST_LEAF_ALWAYS_INLINE void write_ptr( T * p ) noexcept { - ++tagged_uint32::x; + detail::ptr::p = p; } - template - void uint32_decrement() noexcept + template + BOOST_LEAF_ALWAYS_INLINE T * read_ptr() noexcept { - --tagged_uint32::x; + return detail::ptr::p; } -} +} // namespace tls -} } +} } // namespace boost::leaf -#endif +#endif // #ifndef BOOST_LEAF_CONFIG_TLS_GLOBALS_HPP_INCLUDED diff --git a/include/boost/leaf/config/tls_win32.hpp b/include/boost/leaf/config/tls_win32.hpp new file mode 100644 index 00000000..cfa69ea4 --- /dev/null +++ b/include/boost/leaf/config/tls_win32.hpp @@ -0,0 +1,495 @@ +#ifndef BOOST_LEAF_CONFIG_TLS_WIN32_HPP_INCLUDED +#define BOOST_LEAF_CONFIG_TLS_WIN32_HPP_INCLUDED + +// Copyright 2025 Emil Dotchevski and Reverge Studios, Inc. +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +// This header implements the TLS API specified in tls.hpp using Win32 TLS +// functions, allowing error objects to cross DLL boundaries on Windows. This +// implementation is enabled by defining BOOST_LEAF_CFG_WIN32=2 before including +// any LEAF headers. + +#ifndef _WIN32 +# error "This header is only for Windows" +#endif + +#include +#include +#include +#include +#include +#include +#ifdef min +# undef min +#endif +#ifdef max +# undef max +#endif + +namespace boost { namespace leaf { + +// Thrown on TLS allocation failure. +class win32_tls_error: + public std::runtime_error +{ +public: + explicit win32_tls_error(char const * what) noexcept: + std::runtime_error(what) + { + } +}; + +namespace detail +{ + __declspec(noreturn) inline void raise_fail_fast(NTSTATUS status) noexcept + { + EXCEPTION_RECORD rec = {}; + rec.ExceptionCode = status; + rec.ExceptionFlags = EXCEPTION_NONCONTINUABLE; + RaiseFailFastException(&rec, nullptr, 0); + BOOST_LEAF_UNREACHABLE; + } + + template + T * heap_new(Args && ... args) noexcept + { + void * mem = HeapAlloc(GetProcessHeap(), 0, sizeof(T)); + if (!mem) + { + raise_fail_fast(STATUS_NO_MEMORY); + BOOST_LEAF_UNREACHABLE; + } + return new (mem) T(static_cast(args)...); + } + + template + void heap_delete(T * p) noexcept + { + if (p) + { + p->~T(); + BOOL r = HeapFree(GetProcessHeap(), 0, p); + BOOST_LEAF_ASSERT(r), (void) r; + } + } + + template + class heap_allocator + { + public: + + using value_type = T; + + heap_allocator() noexcept = default; + + template + heap_allocator(heap_allocator const &) noexcept + { + } + + T * allocate(std::size_t n) noexcept + { + if (void * p = HeapAlloc(GetProcessHeap(), 0, n * sizeof(T))) + return static_cast(p); + raise_fail_fast(STATUS_NO_MEMORY); + BOOST_LEAF_UNREACHABLE; + } + + void deallocate(T * p, std::size_t) noexcept + { + BOOL r = HeapFree(GetProcessHeap(), 0, p); + BOOST_LEAF_ASSERT(r), (void) r; + } + + friend bool operator==(heap_allocator const &, heap_allocator const &) noexcept { return true; } + friend bool operator!=(heap_allocator const &, heap_allocator const &) noexcept { return false; } + }; + + class critical_section_lock + { + critical_section_lock(critical_section_lock const &) = delete; + critical_section_lock & operator=(critical_section_lock const &) = delete; + + CRITICAL_SECTION & cs_; + + public: + + explicit critical_section_lock(CRITICAL_SECTION & cs) noexcept: + cs_(cs) + { + EnterCriticalSection(&cs_); + } + + ~critical_section_lock() noexcept + { + LeaveCriticalSection(&cs_); + } + }; + + using atomic_unsigned_int = std::atomic; + + template + struct cpp11_hash_step + { + BOOST_LEAF_ALWAYS_INLINE constexpr static std::uint32_t compute(char const (&str)[N], std::uint32_t hash) noexcept + { + return cpp11_hash_step::compute(str, (hash ^ static_cast(str[I])) * 16777619u); + } + }; + + template + struct cpp11_hash_step + { + BOOST_LEAF_ALWAYS_INLINE constexpr static std::uint32_t compute(char const (&)[N], std::uint32_t hash) noexcept + { + return hash; + } + }; + + template + BOOST_LEAF_ALWAYS_INLINE constexpr std::uint32_t cpp11_hash_string(char const (&str)[N]) noexcept + { + return cpp11_hash_step::compute(str, 2166136261u); // str[N-2] is the last character before the \0. + } +} // namespace detail + +namespace n +{ + template + BOOST_LEAF_ALWAYS_INLINE constexpr std::uint32_t __cdecl h() noexcept + { + return detail::cpp11_hash_string(BOOST_LEAF_PRETTY_FUNCTION); + } +} + +namespace detail +{ + template + BOOST_LEAF_ALWAYS_INLINE constexpr std::uint32_t type_hash() noexcept + { + return n::h(); + } +} + +} } // namespace boost::leaf + +//////////////////////////////////////// + +namespace boost { namespace leaf { + +namespace detail +{ + class slot_map + { + slot_map(slot_map const &) = delete; + slot_map & operator=(slot_map const &) = delete; + + class tls_slot_index + { + tls_slot_index(tls_slot_index const &) = delete; + tls_slot_index & operator=(tls_slot_index const &) = delete; + tls_slot_index & operator=(tls_slot_index &&) = delete; + + DWORD idx_; + + public: + + BOOST_LEAF_ALWAYS_INLINE tls_slot_index(): + idx_(TlsAlloc()) + { + if (idx_ == TLS_OUT_OF_INDEXES) + throw_exception_(win32_tls_error("TLS_OUT_OF_INDEXES")); + } + + BOOST_LEAF_ALWAYS_INLINE ~tls_slot_index() noexcept + { + if (idx_ == TLS_OUT_OF_INDEXES) + return; + BOOL r = TlsFree(idx_); + BOOST_LEAF_ASSERT(r), (void) r; + } + + BOOST_LEAF_ALWAYS_INLINE tls_slot_index(tls_slot_index && other) noexcept: + idx_(other.idx_) + { + other.idx_ = TLS_OUT_OF_INDEXES; + } + + BOOST_LEAF_ALWAYS_INLINE DWORD get() const noexcept + { + BOOST_LEAF_ASSERT(idx_ != TLS_OUT_OF_INDEXES); + return idx_; + } + }; + + int refcount_; + HANDLE const mapping_; + tls_slot_index const error_id_slot_; + mutable CRITICAL_SECTION cs_; + std::unordered_map< + std::uint32_t, + tls_slot_index, + std::hash, + std::equal_to, + heap_allocator>> map_; + atomic_unsigned_int error_id_storage_; + + public: + + explicit slot_map(HANDLE mapping) noexcept: + refcount_(1), + mapping_(mapping), + error_id_storage_(1) + { + BOOST_LEAF_ASSERT(mapping != INVALID_HANDLE_VALUE); + InitializeCriticalSection(&cs_); + } + + ~slot_map() noexcept + { + DeleteCriticalSection(&cs_); + BOOL r = CloseHandle(mapping_); + BOOST_LEAF_ASSERT(r), (void) r; + } + + BOOST_LEAF_ALWAYS_INLINE void add_ref() noexcept + { + BOOST_LEAF_ASSERT(refcount_ >= 1); + ++refcount_; + } + + BOOST_LEAF_ALWAYS_INLINE void release() noexcept + { + --refcount_; + BOOST_LEAF_ASSERT(refcount_ >= 0); + if (refcount_ == 0) + heap_delete(this); + } + + DWORD check(std::uint32_t type_hash) const noexcept + { + critical_section_lock lock(cs_); + auto it = map_.find(type_hash); + return (it != map_.end()) ? it->second.get() : TLS_OUT_OF_INDEXES; + } + + DWORD get(std::uint32_t type_hash) + { + critical_section_lock lock(cs_); + DWORD idx = map_[type_hash].get(); + BOOST_LEAF_ASSERT(idx != TLS_OUT_OF_INDEXES); + return idx; + } + + BOOST_LEAF_ALWAYS_INLINE DWORD error_id_slot() const noexcept + { + return error_id_slot_.get(); + } + + BOOST_LEAF_ALWAYS_INLINE atomic_unsigned_int & error_id_storage() noexcept + { + return error_id_storage_; + } + }; // class slot_map + + class module_state + { + module_state(module_state const &) = delete; + module_state & operator=(module_state const &) = delete; + + static constexpr unsigned tls_failure_create_mapping = 0x01; + static constexpr unsigned tls_failure_map_view = 0x02; + + void * hinstance_; + unsigned tls_failures_; + slot_map * sm_; + + public: + + constexpr module_state() noexcept: + hinstance_(nullptr), + tls_failures_(0), + sm_(nullptr) + { + } + + BOOST_LEAF_ALWAYS_INLINE slot_map & sm() const noexcept + { + BOOST_LEAF_ASSERT(hinstance_); + BOOST_LEAF_ASSERT(!(tls_failures_ & tls_failure_create_mapping)); + BOOST_LEAF_ASSERT(!(tls_failures_ & tls_failure_map_view)); + BOOST_LEAF_ASSERT(sm_); + return *sm_; + } + + BOOST_LEAF_ALWAYS_INLINE void update(PVOID hinstDLL, DWORD dwReason) noexcept + { + if (dwReason == DLL_PROCESS_ATTACH) + { + hinstance_ = hinstDLL; + char name[32] = "Local\\boost_leaf_"; + { + constexpr static char const hex[] = "0123456789ABCDEF"; + DWORD pid = GetCurrentProcessId(); + for (int i = 7; i >= 0; --i) + { + name[17 + i] = hex[pid & 0xf]; + pid >>= 4; + } + name[25] = '\0'; + } + HANDLE mapping = CreateFileMappingA(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, sizeof(slot_map *), name); + DWORD mapping_status = GetLastError(); + if (!mapping) + { + tls_failures_ |= tls_failure_create_mapping; + return; + } + BOOST_LEAF_ASSERT(mapping_status == ERROR_ALREADY_EXISTS || mapping_status == ERROR_SUCCESS); + bool is_first_module = (mapping_status == ERROR_SUCCESS); + slot_map * * mapped_ptr = static_cast(MapViewOfFile(mapping, FILE_MAP_WRITE, 0, 0, sizeof(slot_map *))); + if (!mapped_ptr) + { + tls_failures_ |= tls_failure_map_view; + BOOL r = CloseHandle(mapping); + BOOST_LEAF_ASSERT(r), (void) r; + return; + } + if (is_first_module) + sm_ = *mapped_ptr = heap_new(mapping); + else + { + sm_ = *mapped_ptr; + sm_->add_ref(); + BOOL r = CloseHandle(mapping); + BOOST_LEAF_ASSERT(r), (void) r; + } + UnmapViewOfFile(mapped_ptr); + } + else if (dwReason == DLL_PROCESS_DETACH) + { + BOOST_LEAF_ASSERT(sm_ || tls_failures_); + if (sm_) + { + sm_->release(); + sm_ = nullptr; + } + } + } + }; // class module_state + + template + struct module + { + static module_state state; + }; + + template + module_state module::state; + + BOOST_LEAF_ALWAYS_INLINE unsigned generate_next_error_id() noexcept + { + static atomic_unsigned_int & counter = module<>::state.sm().error_id_storage(); + unsigned id = (counter += 4); + BOOST_LEAF_ASSERT((id&3) == 1); + return id; + } + + inline void NTAPI tls_callback(PVOID hinstDLL, DWORD dwReason, PVOID) noexcept + { + module<>::state.update(hinstDLL, dwReason); + } + +#ifdef _MSC_VER +# pragma section(".CRT$XLB", long, read) +# pragma data_seg(push, ".CRT$XLB") + +extern "C" __declspec(selectany) PIMAGE_TLS_CALLBACK boost_leaf_tls_callback = tls_callback; + +# pragma data_seg(pop) +# ifdef _WIN64 +# pragma comment(linker, "/INCLUDE:boost_leaf_tls_callback") +# else +# pragma comment(linker, "/INCLUDE:_boost_leaf_tls_callback") +# endif +#elif defined(__GNUC__) +# pragma GCC diagnostic push +# pragma GCC diagnostic ignored "-Wattributes" + +extern "C" __attribute__((used, selectany)) PIMAGE_TLS_CALLBACK boost_leaf_tls_callback __attribute__((section(".CRT$XLB"))) = tls_callback; + +# pragma GCC diagnostic pop +#else +# error Unknown compiler, unable to define .CRT$XLB section +#endif +} // namespace detail + +} } // namespace boost::leaf + +//////////////////////////////////////// + +namespace boost { namespace leaf { + +namespace tls +{ + BOOST_LEAF_ALWAYS_INLINE unsigned generate_next_error_id() noexcept + { + return detail::generate_next_error_id(); + } + + BOOST_LEAF_ALWAYS_INLINE void write_current_error_id(unsigned x) noexcept + { + using namespace detail; + DWORD slot = module<>::state.sm().error_id_slot(); + BOOL r = TlsSetValue(slot, reinterpret_cast(static_cast(x))); + BOOST_LEAF_ASSERT(r), (void) r; + } + + BOOST_LEAF_ALWAYS_INLINE unsigned read_current_error_id() noexcept + { + using namespace detail; + DWORD slot = module<>::state.sm().error_id_slot(); + LPVOID value = TlsGetValue(slot); + BOOST_LEAF_ASSERT(GetLastError() == ERROR_SUCCESS); + return static_cast(reinterpret_cast(value)); + } + + template + BOOST_LEAF_ALWAYS_INLINE void reserve_ptr() + { + using namespace detail; + thread_local DWORD const cached_slot = module<>::state.sm().get(type_hash()); + BOOST_LEAF_ASSERT(cached_slot != TLS_OUT_OF_INDEXES), (void) cached_slot; + } + + template + BOOST_LEAF_ALWAYS_INLINE void write_ptr(T * p) noexcept + { + using namespace detail; + thread_local DWORD const cached_slot = module<>::state.sm().check(type_hash()); + DWORD slot = cached_slot; + BOOST_LEAF_ASSERT(slot != TLS_OUT_OF_INDEXES); + BOOL r = TlsSetValue(slot, p); + BOOST_LEAF_ASSERT(r), (void) r; + } + + template + BOOST_LEAF_ALWAYS_INLINE T * read_ptr() noexcept + { + using namespace detail; + thread_local DWORD cached_slot = TLS_OUT_OF_INDEXES; + if (cached_slot == TLS_OUT_OF_INDEXES) + cached_slot = module<>::state.sm().check(type_hash()); + DWORD slot = cached_slot; + if (slot == TLS_OUT_OF_INDEXES) + return nullptr; + LPVOID value = TlsGetValue(slot); + BOOST_LEAF_ASSERT(GetLastError() == ERROR_SUCCESS); + return static_cast(value); + } +} // namespace tls + +} } // namespace boost::leaf + +#endif // #ifndef BOOST_LEAF_CONFIG_TLS_WIN32_HPP_INCLUDED diff --git a/include/boost/leaf/config/visibility.hpp b/include/boost/leaf/config/visibility.hpp new file mode 100644 index 00000000..86615bb4 --- /dev/null +++ b/include/boost/leaf/config/visibility.hpp @@ -0,0 +1,45 @@ +#ifndef BOOST_LEAF_CONFIG_VISIBILITY_HPP_INCLUDED +#define BOOST_LEAF_CONFIG_VISIBILITY_HPP_INCLUDED + +// Copyright 2018-2024 Emil Dotchevski and Reverge Studios, Inc. +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +namespace boost { namespace leaf { + +class BOOST_LEAF_SYMBOL_VISIBLE error_id; +class BOOST_LEAF_SYMBOL_VISIBLE error_info; +class BOOST_LEAF_SYMBOL_VISIBLE diagnostic_info; +class BOOST_LEAF_SYMBOL_VISIBLE diagnostic_details; + +struct BOOST_LEAF_SYMBOL_VISIBLE e_api_function; +struct BOOST_LEAF_SYMBOL_VISIBLE e_file_name; +struct BOOST_LEAF_SYMBOL_VISIBLE e_errno; +struct BOOST_LEAF_SYMBOL_VISIBLE e_type_info_name; +struct BOOST_LEAF_SYMBOL_VISIBLE e_at_line; +struct BOOST_LEAF_SYMBOL_VISIBLE e_source_location; + +class BOOST_LEAF_SYMBOL_VISIBLE bad_result; +template class BOOST_LEAF_SYMBOL_VISIBLE result; + +namespace detail +{ + template class BOOST_LEAF_SYMBOL_VISIBLE slot; + + class BOOST_LEAF_SYMBOL_VISIBLE exception_base; + + template class BOOST_LEAF_SYMBOL_VISIBLE exception; + +#if BOOST_LEAF_CFG_CAPTURE + class BOOST_LEAF_SYMBOL_VISIBLE dynamic_allocator; +#endif + +#if BOOST_LEAF_CFG_STD_SYSTEM_ERROR + class BOOST_LEAF_SYMBOL_VISIBLE leaf_error_category; + template struct BOOST_LEAF_SYMBOL_VISIBLE get_leaf_error_category; +#endif +} + +} } // namespace boost::leaf + +#endif // BOOST_LEAF_CONFIG_VISIBILITY_HPP_INCLUDED diff --git a/include/boost/leaf/context.hpp b/include/boost/leaf/context.hpp index 0ac45d20..63518f30 100644 --- a/include/boost/leaf/context.hpp +++ b/include/boost/leaf/context.hpp @@ -1,8 +1,7 @@ #ifndef BOOST_LEAF_CONTEXT_HPP_INCLUDED #define BOOST_LEAF_CONTEXT_HPP_INCLUDED -// Copyright 2018-2022 Emil Dotchevski and Reverge Studios, Inc. - +// Copyright 2018-2025 Emil Dotchevski and Reverge Studios, Inc. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) @@ -10,21 +9,21 @@ #include #if !defined(BOOST_LEAF_NO_THREADS) && !defined(NDEBUG) -# include +# include #endif namespace boost { namespace leaf { class error_info; class diagnostic_info; -class verbose_diagnostic_info; +class diagnostic_details; template struct is_predicate: std::false_type { }; -namespace leaf_detail +namespace detail { template struct is_exception: std::is_base_of::type> @@ -41,6 +40,7 @@ namespace leaf_detail struct handler_argument_traits_defaults { using error_type = typename std::decay::type; + using context_types = leaf_detail_mp11::mp_list; constexpr static bool always_available = false; template @@ -58,7 +58,7 @@ namespace leaf_detail static_assert(!is_predicate::value, "Handlers must take predicate arguments by value"); static_assert(!std::is_same::value, "Handlers must take leaf::error_info arguments by const &"); static_assert(!std::is_same::value, "Handlers must take leaf::diagnostic_info arguments by const &"); - static_assert(!std::is_same::value, "Handlers must take leaf::verbose_diagnostic_info arguments by const &"); + static_assert(!std::is_same::value, "Handlers must take leaf::diagnostic_details arguments by const &"); }; template @@ -81,10 +81,10 @@ namespace leaf_detail } }; - template + template struct handler_argument_always_available { - using error_type = E; + using context_types = leaf_detail_mp11::mp_list; constexpr static bool always_available = true; template @@ -102,7 +102,7 @@ namespace leaf_detail template <> struct handler_argument_traits { - using error_type = void; + using context_types = leaf_detail_mp11::mp_list<>; constexpr static bool always_available = false; template @@ -125,120 +125,115 @@ namespace leaf_detail } }; - template <> - struct handler_argument_traits: handler_argument_always_available + template + struct handler_argument_traits_require_by_value { - template - BOOST_LEAF_CONSTEXPR static error_info const & get( Tup const &, error_info const & ei ) noexcept + static_assert(sizeof(E) == 0, "Error handlers must take this type by value"); + }; +} // namespace detail + +//////////////////////////////////////// + +namespace detail +{ + template + struct get_dispatch + { + static BOOST_LEAF_CONSTEXPR T const * get(T const * x) noexcept { - return ei; + return x; + } + static BOOST_LEAF_CONSTEXPR T const * get(void const *) noexcept + { + return nullptr; } }; - template - struct handler_argument_traits_require_by_value + template + BOOST_LEAF_CONSTEXPR inline T * find_in_tuple(std::tuple<> const &) { - static_assert(sizeof(E) == 0, "Error handlers must take this type by value"); - }; -} + return nullptr; + } + + template + BOOST_LEAF_CONSTEXPR inline typename std::enable_if::type const * + find_in_tuple(std::tuple const & t) noexcept + { + return get_dispatch::get(&std::get(t)); + } + + template + BOOST_LEAF_CONSTEXPR inline typename std::enable_if::type const * + find_in_tuple(std::tuple const & t) noexcept + { + if( T const * x = get_dispatch::get(&std::get(t)) ) + return x; + else + return find_in_tuple(t); + } +} // namespace detail //////////////////////////////////////// -namespace leaf_detail +namespace detail { - template + template struct tuple_for_each { - BOOST_LEAF_CONSTEXPR static void activate( Tuple & tup ) noexcept + BOOST_LEAF_CONSTEXPR static void activate( Tup & tup ) noexcept { static_assert(!std::is_same(tup))>::type>::value, "Bug in LEAF: context type deduction"); - tuple_for_each::activate(tup); + tuple_for_each::activate(tup); std::get(tup).activate(); } - BOOST_LEAF_CONSTEXPR static void deactivate( Tuple & tup ) noexcept + BOOST_LEAF_CONSTEXPR static void deactivate( Tup & tup ) noexcept { static_assert(!std::is_same(tup))>::type>::value, "Bug in LEAF: context type deduction"); std::get(tup).deactivate(); - tuple_for_each::deactivate(tup); + tuple_for_each::deactivate(tup); } - BOOST_LEAF_CONSTEXPR static void propagate( Tuple & tup, int err_id ) noexcept - { - static_assert(!std::is_same(tup))>::type>::value, "Bug in LEAF: context type deduction"); - auto & sl = std::get(tup); - sl.propagate(err_id); - tuple_for_each::propagate(tup, err_id); - } - - BOOST_LEAF_CONSTEXPR static void propagate_captured( Tuple & tup, int err_id ) noexcept + BOOST_LEAF_CONSTEXPR static void unload( Tup & tup, int err_id ) noexcept { static_assert(!std::is_same(tup))>::type>::value, "Bug in LEAF: context type deduction"); BOOST_LEAF_ASSERT(err_id != 0); auto & sl = std::get(tup); - if( sl.has_value(err_id) ) - load_slot(err_id, std::move(sl).value(err_id)); - tuple_for_each::propagate_captured(tup, err_id); + sl.unload(err_id); + tuple_for_each::unload(tup, err_id); } template - static void print( std::basic_ostream & os, void const * tup, int key_to_print ) + static void print(std::basic_ostream & os, void const * tup, error_id to_print, char const * & prefix) { BOOST_LEAF_ASSERT(tup != nullptr); - tuple_for_each::print(os, tup, key_to_print); - std::get(*static_cast(tup)).print(os, key_to_print); + tuple_for_each::print(os, tup, to_print, prefix); + std::get(*static_cast(tup)).print(os, to_print, prefix); } }; - template - struct tuple_for_each<0, Tuple> + template + struct tuple_for_each<0, Tup> { - BOOST_LEAF_CONSTEXPR static void activate( Tuple & ) noexcept { } - BOOST_LEAF_CONSTEXPR static void deactivate( Tuple & ) noexcept { } - BOOST_LEAF_CONSTEXPR static void propagate( Tuple &, int ) noexcept { } - BOOST_LEAF_CONSTEXPR static void propagate_captured( Tuple &, int ) noexcept { } + BOOST_LEAF_CONSTEXPR static void activate( Tup & ) noexcept { } + BOOST_LEAF_CONSTEXPR static void deactivate( Tup & ) noexcept { } + BOOST_LEAF_CONSTEXPR static void unload( Tup &, int ) noexcept { } template - BOOST_LEAF_CONSTEXPR static void print( std::basic_ostream &, void const *, int ) { } - }; -} - -//////////////////////////////////////////// - -#if BOOST_LEAF_CFG_DIAGNOSTICS - -namespace leaf_detail -{ - template struct requires_unexpected { constexpr static bool value = false; }; - template struct requires_unexpected { constexpr static bool value = requires_unexpected::value; }; - template struct requires_unexpected { constexpr static bool value = requires_unexpected::value; }; - template struct requires_unexpected { constexpr static bool value = requires_unexpected::value; }; - template <> struct requires_unexpected { constexpr static bool value = true; }; - template <> struct requires_unexpected { constexpr static bool value = true; }; - - template - struct unexpected_requested; - - template