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..5bec173e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,24 +17,23 @@ jobs: fail-fast: false matrix: include: - - toolset: gcc-4.8 - cxxstd: "11" - os: ubuntu-18.04 - install: g++-4.8 - toolset: gcc-5 cxxstd: "11,14,1z" - os: ubuntu-18.04 + os: ubuntu-latest + container: ubuntu:18.04 install: g++-5 - toolset: gcc-6 cxxstd: "11,14,1z" - os: ubuntu-18.04 + os: ubuntu-latest + container: ubuntu:18.04 install: g++-6 - toolset: gcc-7 cxxstd: "11,14" - os: ubuntu-18.04 + os: ubuntu-latest + container: ubuntu:18.04 - toolset: gcc-8 cxxstd: "11,14,17,2a" - os: ubuntu-18.04 + os: ubuntu-20.04 install: g++-8 - toolset: gcc-9 cxxstd: "11,14,17,2a" @@ -44,33 +43,49 @@ jobs: os: ubuntu-20.04 install: g++-10 - toolset: gcc-11 - cxxstd: "11,14,17,2a" - os: ubuntu-20.04 - install: g++-11 + cxxstd: "11,14,17,20" + 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: 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 + os: ubuntu-20.04 install: clang-6.0 - toolset: clang compiler: clang++-7 cxxstd: "11,14,17" - os: ubuntu-18.04 + os: ubuntu-20.04 install: clang-7 - toolset: clang compiler: clang++-8 @@ -79,47 +94,126 @@ jobs: install: clang-8 - toolset: clang compiler: clang++-9 - cxxstd: "11,14,17,2a" + cxxstd: "11,14,17" os: ubuntu-20.04 install: clang-9 - toolset: clang compiler: clang++-10 cxxstd: "11,14,17,2a" os: ubuntu-20.04 - install: clang-10 - toolset: clang compiler: clang++-11 cxxstd: "11,14,17,2a" os: ubuntu-20.04 - install: clang-11 - toolset: clang compiler: clang++-12 - cxxstd: "11,14,17,2a" + cxxstd: "11,14,17,20" os: ubuntu-20.04 - 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.10 + os: ubuntu-latest + install: clang-19 + - toolset: clang + cxxstd: "11,14,17,20,2b" + os: macos-13 + - toolset: clang + cxxstd: "11,14,17,20,2b" + os: macos-14 + - toolset: clang + cxxstd: "11,14,17,20,2b" + os: macos-15 runs-on: ${{matrix.os}} + container: + image: ${{matrix.container}} + volumes: + - /node20217:/node20217:rw,rshared + - ${{ startsWith(matrix.container, 'ubuntu:1') && '/node20217:/__e/node20:ro,rshared' || ' ' }} + + defaults: + run: + shell: bash + steps: - - uses: actions/checkout@v2 + - name: Setup container environment + if: matrix.container + run: | + apt-get update + apt-get -y install sudo python3 git g++ curl xz-utils + + - name: Install nodejs20glibc2.17 + if: ${{ startsWith( matrix.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}} + run: | + sudo apt-get update + sudo apt-get -y install ${{matrix.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 @@ -131,26 +225,30 @@ jobs: - 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.toolset}} cxxstd=${{matrix.cxxstd}} ${ADDRMD:+address-model=$ADDRMD} 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 windows: strategy: fail-fast: false matrix: include: - - toolset: msvc-14.1 - cxxstd: "14,17,latest" - addrmd: 32,64 - os: windows-2016 - toolset: msvc-14.2 - cxxstd: "14,17,latest" + cxxstd: "14,17,20,latest" addrmd: 32,64 os: windows-2019 + - toolset: msvc-14.3 + cxxstd: "14,17,20,latest" + addrmd: 32,64 + 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 @@ -159,30 +257,37 @@ jobs: runs-on: ${{matrix.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 libs/%LIBRARY%/test toolset=${{matrix.toolset}} cxxstd=${{matrix.cxxstd}} address-model=${{matrix.addrmd}} ${{matrix.embedmanifest}} 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/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..f94f55c3 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_examples=true -D leaf_lua_examples=true _bld/debug && meson setup -D leaf_boost_examples=false -D single_header=true _bld/debug_single_header && meson setup -D leaf_boost_examples=true -D leaf_lua_examples=true _bld/release --buildtype release && meson setup -D 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 cpp_eh=none -D leaf_boost_examples=true -D leaf_lua_examples=true _bld/debug && meson setup -D cpp_eh=none -D leaf_boost_examples=true -D single_header=true _bld/debug_single_header && meson setup -D cpp_eh=none -D leaf_boost_examples=true -D leaf_lua_examples=true _bld/release --buildtype release && meson setup -D cpp_eh=none -D leaf_boost_examples=true -D single_header=true _bld/release_single_header --buildtype release", + "problemMatcher": [] + }, + { + "label": "Setup Meson build directories (no diagnostics)", + "type": "shell", + "command": "cd ${workspaceRoot} && meson setup -D leaf_diagnostics=0 -D leaf_boost_examples=true -D leaf_lua_examples=true _bld/debug && meson setup -D leaf_diagnostics=0 -D leaf_boost_examples=true -D single_header=true _bld/debug_single_header && meson setup -D leaf_diagnostics=0 -D leaf_boost_examples=true -D leaf_lua_examples=true _bld/release --buildtype release && meson setup -D leaf_diagnostics=0 -D leaf_boost_examples=true -D single_header=true _bld/release_single_header --buildtype release", + "problemMatcher": [] + }, + { + "label": "Setup Meson build directories (no capture)", + "type": "shell", + "command": "cd ${workspaceRoot} && meson setup -D leaf_capture=0 -D leaf_boost_examples=true -D leaf_lua_examples=true _bld/debug && meson setup -D leaf_capture=0 -D leaf_boost_examples=true -D single_header=true _bld/debug_single_header && meson setup -D leaf_capture=0 -D leaf_boost_examples=true -D leaf_lua_examples=true _bld/release --buildtype release && meson setup -D leaf_capture=0 -D leaf_boost_examples=true -D single_header=true _bld/release_single_header --buildtype release", + "problemMatcher": [] + }, + { + "label": "Setup Meson build directories (no Boost)", + "type": "shell", + "command": "cd ${workspaceRoot} && meson setup -D leaf_lua_examples=true _bld/debug && meson setup -D single_header=true _bld/debug_single_header && meson setup -D leaf_lua_examples=true _bld/release --buildtype release && meson setup -D 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 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 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 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 single_header=true _bld/release_single_header --buildtype release", "problemMatcher": [] }, { @@ -28,12 +58,12 @@ }, "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" ] } }, @@ -44,12 +74,12 @@ "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" ] } }, @@ -60,12 +90,12 @@ "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" ] } }, @@ -76,15 +106,15 @@ "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", + "command": "../../b2 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 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", "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 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 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": "$gcc", "fileLocation": [ "relative", - "${workspaceRoot}/bld/release" + "${workspaceRoot}/_bld/release" ] } }, @@ -95,12 +125,15 @@ }, "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} || cat ./meson-logs/testlog.txt)", + }, "problemMatcher": { "base": "$gcc", "fileLocation": [ "relative", - "${workspaceRoot}/bld/debug" + "${workspaceRoot}/_bld/debug" ] } } diff --git a/README.md b/README.md index a8241876..c204a980 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-2024 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/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..ed4517ad 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,7 +61,7 @@ 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. @@ -75,15 +72,15 @@ What is a failure? It is simply the inability of a function to return a valid re 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`. -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. +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 is rare that it needs to access any error objects. They are only needed once an error handling scope is reached. -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. +Therefore what would have been a `result` becomes `result`, which stores the discriminant and (optionally) a `T`, while error objects are delivered directly to the error handling scope where they are 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. === Reporting Errors -A function that reports an error is pretty straight-forward: +A function that reports an error: [source,c++] ---- @@ -209,11 +206,11 @@ leaf::result r = leaf::try_handle_some( [.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 `err1`. 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. -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++] ---- @@ -229,7 +226,7 @@ leaf::result r = leaf::try_handle_some( []( leaf::match ) -> leaf::result { - // Handle err::e1 + // Handle err1::e1 or err1::e3 }, []( err1 e ) -> leaf::result @@ -240,15 +237,15 @@ leaf::result r = leaf::try_handle_some( [.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 `err1` is available, and its value is either `err1::e1` or `err1::e3`. -* 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 `err1` 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++] ---- @@ -347,7 +344,7 @@ leaf::result r = leaf::try_handle_some( [.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; @@ -390,7 +387,7 @@ leaf::result r = leaf::try_handle_some( []( 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 @@ -422,7 +419,7 @@ leaf::result r = leaf::try_handle_some( []( 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,9 +427,9 @@ 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 @@ -469,7 +466,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: @@ -530,7 +527,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++] ---- @@ -596,9 +593,9 @@ 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 does `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++] ---- @@ -629,24 +626,24 @@ enum class err2 { e1, e2 }; T f() { if( error_detected ) - throw leaf::exception(err1::e1, err2::e2); + leaf::throw_exception(err1::e1, err2::e2); // 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 usual 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!"), err1::e1, err2::e2); ---- -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 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 +698,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++] ---- @@ -756,7 +753,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 ) @@ -799,45 +796,14 @@ lib3::result r = leaf::try_handle_some( ''' -[[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, 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 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`. @@ -852,14 +818,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_same`, `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 +861,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 +890,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 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 +933,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,51 +957,51 @@ 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: @@ -1059,31 +1023,27 @@ return leaf::try_handle_some( [] { - return f(); // returns leaf::result + return f(); // Returns leaf::result }, - []( my_error e ) - { <1> + []( my_error e ) // handle my_error objects + { switch(e) { case my_error::e1: - ....; <2> + ....; // Handle e1 error values break; case my_error::e2: case my_error::e3: - ....; <3> + ....; // Handle e2 and e3 error values break; default: - ....; <4> + ....; // Handle bad my_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 `my_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: @@ -1097,25 +1057,22 @@ return leaf::try_handle_some( }, []( leaf::match m ) - { <1> + { assert(m.matched == my_error::e1); ....; }, []( leaf::match m ) - { <2> + { assert(m.matched == my_error::e2 || m.matched == my_error::e3); ....; }, []( my_error e ) - { <3> + { ....; } ); ---- -<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 +1085,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,7 +1094,7 @@ 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++] ---- @@ -1153,17 +1110,17 @@ 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`, 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: @@ -1195,7 +1152,7 @@ leaf::try_handle_all( [.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++] ---- @@ -1222,7 +1179,7 @@ leaf::try_handle_all( }); ---- -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++] ---- @@ -1278,14 +1235,14 @@ Error handling functions accept a `std::tuple` of error handlers in place of any ''' [[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 +1251,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 +1261,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++] ---- @@ -1359,32 +1285,6 @@ return leaf::try_handle_some( 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 +1300,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 +1404,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 +1487,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 +1498,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`: @@ -1647,7 +1570,7 @@ leaf::result compute_answer() noexcept [.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. +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`). @@ -1666,7 +1589,7 @@ leaf::result print_answer() noexcept [.text-right] <> | <> -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. +Finally, here is the scope that handles the errors -- it will work correctly regardless of whether `error_a` and `error_b` objects are thrown as exceptions or not. [source,c++] ---- @@ -1704,7 +1627,7 @@ NOTE: The complete program illustrating this technique is available https://gith [[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. +Communicating information pertaining to a failure detected in a C callback is tricky, because C callbacks are limited to a specific function signature, which may not use {CPP} types. 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. @@ -1728,9 +1651,9 @@ std::shared_ptr init_lua_state() noexcept lua_register(&*L, "do_work", &do_work); //<2> luaL_dostring(&*L, "\ //<3> -\n function call_do_work()\ -\n return do_work()\ -\n end"); +\n function call_do_work()\ +\n return do_work()\ +\n end"); return L; } @@ -1777,7 +1700,7 @@ int do_work( lua_State * L ) noexcept <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: +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: [source,c++] ---- @@ -1840,10 +1763,7 @@ int main() noexcept [](leaf::error_info const & unmatched) { - std::cerr << - "Unknown failure detected" << std::endl << - "Cryptic diagnostic information follows" << std::endl << - unmatched; + std::cerr << "Unknown failure detected\n" << unmatched; } ); } ---- @@ -1856,7 +1776,7 @@ int main() noexcept 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]. +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 (instead of `leaf::result`) to safely communicate errors out of the `do_work` function: https://github.com/boostorg/leaf/blob/master/example/lua_callback_exceptions.cpp?ts=4[lua_callback_exceptions.cpp]. '''' @@ -1888,25 +1808,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 +1842,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). -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++] ---- @@ -1947,22 +1870,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 +1894,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`. @@ -2281,6 +2204,56 @@ A standalone single-header option is available; please see <>. [[synopsis-reporting]] === Error Reporting +[[common.hpp]] +==== `common.hpp` + +==== +.#include +[source,c++] +---- +namespace boost { namespace leaf { + + struct e_api_function { char const * value; }; + + struct e_file_name { std::string value; }; + + struct e_type_info_name { char const * value; }; + + struct e_at_line { int value; }; + + struct e_errno + { + int value; + explicit e_errno(int value=errno); + + template + friend std::ostream & operator<<( std::basic_ostream &, e_errno const &); + }; + + namespace windows + { + struct e_LastError + { + unsigned value; + + explicit e_LastError(unsigned value); + +#if BOOST_LEAF_CFG_WIN32 + e_LastError(); + + template + friend std::ostream & operator<<( std::basic_ostream &, e_LastError const &); +#endif + }; + } + +} } +---- + +[.text-right] +Reference: <> | <> | <> | <> | <> | <> | <> +==== + [[error.hpp]] ==== `error.hpp` @@ -2313,7 +2286,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; @@ -2323,27 +2297,7 @@ namespace boost { namespace leaf { error_id current_error() noexcept; - ////////////////////////////////////////// - - class polymorphic_context - { - protected: - - polymorphic_context() noexcept = default; - ~polymorphic_context() noexcept = default; - - 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; - }; - - ////////////////////////////////////////// + //////////////////////////////////////// template class context_activator @@ -2382,64 +2336,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 +2447,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 +2514,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 +2569,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 +2600,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 +2620,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 +2680,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 +2697,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]] @@ -2887,6 +2811,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 +2868,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 +2876,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` @@ -3025,82 +2933,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 +2947,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`. @@ -3220,46 +3052,16 @@ auto ctx = leaf::make_context( <1> ''' -[[make_shared_context]] -=== `make_shared_context` +[[new_error]] +=== `new_error` -.#include +.#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` - -.#include -[source,c++] ----- -namespace boost { namespace leaf { - - template - error_id new_error(Item && ... item) noexcept; + template + error_id new_error(Item && ... item) noexcept; } } ---- @@ -3323,6 +3125,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 fuction 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 `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` @@ -3345,7 +3223,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 +3256,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 +3356,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. @@ -3536,7 +3447,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 +3469,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 +3496,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 +3508,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 +3521,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 +3567,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 +3582,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 +3592,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 +3641,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 +3668,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 +3729,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 +3743,8 @@ Effects: :: Prints all error objects currently stored in `*this`, together with ''' -[[context::propagate]] -==== `propagate` +[[context::unload]] +==== `unload` .#include [source,c++] @@ -3834,13 +3752,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: :: @@ -3884,10 +3802,47 @@ For automatic deduction of `Ctx`, use <>. ''' +[[diagnostic_details]] +=== `diagnostic_details` + +.#include +[source,c++] +---- +namespace boost { namespace leaf { + + class diagnostic_details: public error_info + { + //Constructors unspecified + + template + friend std::ostream & operator<<( std::basic_ostream &, diagnostic_details const & ); + }; + +} } +---- + +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 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 includes the types and the values of all such error objects (but see <>). + +[NOTE] +-- +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_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`. + +''' + [[diagnostic_info]] === `diagnostic_info` -.#include +.#include [source,c++] ---- namespace boost { namespace leaf { @@ -3896,7 +3851,8 @@ namespace boost { namespace leaf { { //Constructors unspecified - friend std::ostream & operator<<( std::ostream & os, diagnostic_info const & x ); + template + friend std::ostream & operator<<( std::basic_ostream &, diagnostic_info const & ); }; } } @@ -3910,14 +3866,12 @@ The additional information is limited to the type name of the first such error o [NOTE] -- -The behavior of `diagnostic_info` (and <>) is affected by the value of the macro `BOOST_LEAF_CFG_DIAGNOSTICS`: +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` @@ -3949,7 +3903,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 +3953,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 +3992,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`. @@ -4236,7 +4191,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 +4240,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 +4268,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 +4315,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 +4336,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 +4349,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 +4416,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 +4474,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 +4491,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 +4546,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 +4710,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 synonim for `T`. + +''' + [[result::bad_result]] Effects: :: If `*this` is in <>, returns a reference to the stored value, otherwise throws `bad_result`. @@ -4797,39 +4776,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 +4826,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 &`; @@ -5381,7 +5361,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 +5504,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,41 +5523,145 @@ 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: -[source,c++] -.#include ----- -#define BOOST_LEAF_THROW_EXCEPTION throw BOOST_LEAF_EXCEPTION ----- +* `BOOST_LEAF_CFG_DIAGNOSTICS`: Defining this macro as `0` stubs out both <> and <> (if the macro is left undefined, LEAF defines it as `1`). -Effects: :: Throws the exception object returned by <>. +* `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`). -[[rationale]] -== Design +* `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`). -=== Rationale +* `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`). -Definition: :: Objects that carry information about error conditions are called error objects. For example, objects of type `std::error_code` are error objects. +* `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`. -NOTE: The following reasoning is independent of the mechanism used to transport error objects, whether it is exception handling or anything else. +* `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. -Definition: :: Depending on their interaction with error objects, functions can be classified as follows: -* *Error initiating*: functions that initiate error conditions by creating new error objects. -* *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. +* `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`). -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. +* `BOOST_LEAF_NO_THREADS`: Disables all thread safety in LEAF. -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. +[[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_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. + +[[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). + +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. + +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 <>. + +== 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 +---- + +[[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. + +NOTE: The following reasoning is independent of the mechanism used to transport error objects, whether it is exception handling or anything else. + +Definition: :: Depending on their interaction with error objects, functions can be classified as follows: +* *Error initiating*: functions that initiate error conditions by creating new error objects. +* *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. + +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. Finally, _error handling_ functions, by definition, have the full context they need to deal with at least some, if not all, failures. In their scope it is an absolute necessity that the author knows exactly what information must be communicated by lower level functions in order to recover from each error condition. Specifically, none of this necessary information can be treated as implementation details; in this case, the coupling which is to be avoided in _error neutral_ functions is in fact desirable. @@ -5671,7 +5755,7 @@ leaf::try_catch( [.text-right] <> | <> | <> -Similar syntax works without exception handling as well. Below is the same snippet, written using `<>`: +Similar syntax works without exception handling as well. Below is the same snippet, written using `<>`: [source,c++] ---- @@ -5708,185 +5792,21 @@ return leaf::try_handle_some( [.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. +== Limitations -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: +When using dynamic linking, it is required that error types are declared with `default` visibility, e.g.: [source,c++] ---- -struct attempted_location -{ - std::string path; - error ec; -}; - -struct config_error +struct __attribute__ ((visibility ("default"))) my_error_info { - attempted_location current_dir, user_dir, app_dir; + int value; }; - -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. +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. -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. +TIP: When using dynamic linking, it is always best to define module interfaces in terms of C (and implement them in {CPP} if appropriate). == Alternatives to LEAF @@ -5943,12 +5863,12 @@ https://www.boost.org/doc/libs/release/libs/exception/doc/exception_operator_shl | [source,c++,options="nowrap"] ---- -throw leaf::exception( my_exception(), +leaf::throw_exception( my_exception(), my_info{x}, my_info{y} ); ---- [.text-right] -<> +<> |==== .Augmenting exceptions in error neutral contexts @@ -6046,9 +5966,9 @@ leaf::try_catch( [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`]. +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. +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. ==== ''' @@ -6112,143 +6032,6 @@ Further, consider that Outcome aims to hopefully become _the_ one error handling 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_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. - -[[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.: - -[source,c++] ----- -struct __attribute__ ((visibility ("default"))) my_error_info -{ - int value; -}; ----- - -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 <>. - -TIP: When using dynamic linking, it is always best to define module interfaces in terms of C (and implement them in {CPP} if appropriate). - == Acknowledgements Special thanks to Peter Dimov and Sorin Fetche. 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..ea19e8cb 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-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) @@ -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..c3299b95 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-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) @@ -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..d6e3a7b3 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-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) @@ -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..ecad96f6 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-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) @@ -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..fc7a046f 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-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) @@ -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..adf54f7f 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-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) @@ -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..a32ec549 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-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) @@ -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..b5addfb5 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-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) // 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..050e1f6f 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 implementaiton. -* [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..1211d277 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-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) @@ -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..8b5f4086 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 implementaiton. -* [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..4372482b 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-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) @@ -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..617f77da 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-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) // 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..ea190af1 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-2024 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-2024 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..8c2b181a 100644 --- a/include/boost/leaf.hpp +++ b/include/boost/leaf.hpp @@ -1,8 +1,7 @@ #ifndef BOOST_LEAF_HPP_INCLUDED #define BOOST_LEAF_HPP_INCLUDED -// 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) 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..05ec9871 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-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) @@ -10,10 +9,13 @@ #include #include +#include +#include + #if BOOST_LEAF_CFG_STD_STRING # include #endif -#include + #if BOOST_LEAF_CFG_WIN32 # include # include @@ -40,7 +42,7 @@ struct BOOST_LEAF_SYMBOL_VISIBLE e_file_name struct BOOST_LEAF_SYMBOL_VISIBLE e_file_name { - constexpr static char const * const value = ""; + char const * value = ""; BOOST_LEAF_CONSTEXPR explicit e_file_name( char const * ) { } }; @@ -50,12 +52,12 @@ struct BOOST_LEAF_SYMBOL_VISIBLE 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) << '"'; } }; @@ -69,13 +71,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 { @@ -99,7 +101,7 @@ namespace windows *--z = 0; if( z[-1] == '\r' ) *--z = 0; - return os << type() << ": " << err.value << ", \"" << (LPCSTR)mb.p << '"'; + return os << err.value << ", \"" << (LPCSTR)mb.p << '"'; } return os; } @@ -109,4 +111,4 @@ namespace windows } } -#endif +#endif // BOOST_LEAF_COMMON_HPP_INCLUDED diff --git a/include/boost/leaf/config.hpp b/include/boost/leaf/config.hpp index 7c7e7d2b..a744c101 100644 --- a/include/boost/leaf/config.hpp +++ b/include/boost/leaf/config.hpp @@ -1,59 +1,36 @@ #ifndef BOOST_LEAF_CONFIG_HPP_INCLUDED #define BOOST_LEAF_CONFIG_HPP_INCLUDED -// 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) -// 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 - -//////////////////////////////////////// - #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 + +//////////////////////////////////////// +#ifndef BOOST_LEAF_ASSERT +# include +# define BOOST_LEAF_ASSERT assert #endif //////////////////////////////////////// @@ -86,108 +63,92 @@ # 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_WIN32 != 0 && BOOST_LEAF_CFG_WIN32 != 1 +# error BOOST_LEAF_CFG_WIN32 must be 0 or 1. +#endif + +#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 the use of std::string +# error BOOST_LEAF_CFG_DIAGNOSTICS requires BOOST_LEAF_CFG_STD_STRING, which has been disabled. #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_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 -#if BOOST_LEAF_CFG_GNUC_STMTEXPR!=0 && BOOST_LEAF_CFG_GNUC_STMTEXPR!=1 -# error BOOST_LEAF_CFG_GNUC_STMTEXPR must be 0 or 1. +//////////////////////////////////////// + +#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 //////////////////////////////////////// -// Configure BOOST_LEAF_NO_EXCEPTIONS, unless already #defined #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 @@ -195,27 +156,6 @@ #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 - //////////////////////////////////////// #ifdef _MSC_VER @@ -226,12 +166,18 @@ //////////////////////////////////////// -#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,6 +192,16 @@ //////////////////////////////////////// +#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) @@ -258,7 +214,7 @@ //////////////////////////////////////// #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 @@ -276,6 +232,4 @@ // Configure TLS access #include -//////////////////////////////////////// - -#endif +#endif // BOOST_LEAF_CONFIG_HPP_INCLUDED diff --git a/include/boost/leaf/config/tls.hpp b/include/boost/leaf/config/tls.hpp index 279bafb2..0dd42489 100644 --- a/include/boost/leaf/config/tls.hpp +++ b/include/boost/leaf/config/tls.hpp @@ -1,8 +1,7 @@ #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-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) @@ -30,4 +29,4 @@ # include #endif -#endif +#endif // BOOST_LEAF_CONFIG_TLS_HPP_INCLUDED diff --git a/include/boost/leaf/config/tls_array.hpp b/include/boost/leaf/config/tls_array.hpp index f194c56c..456e50f9 100644 --- a/include/boost/leaf/config/tls_array.hpp +++ b/include/boost/leaf/config/tls_array.hpp @@ -1,15 +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-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) +// Copyright (c) 2022 Khalil Estell + // 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 +// This header implements thread local storage for pointers and for unsigned int // values for platforms that support thread local pointers by index. namespace boost { namespace leaf { @@ -53,7 +53,7 @@ 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; } @@ -65,15 +65,21 @@ namespace tls { static int c_; - public: - - static BOOST_LEAF_CFG_TLS_INDEX_TYPE next() + 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_SIZE)); return idx; } + + public: + + template + static BOOST_LEAF_CFG_TLS_INDEX_TYPE next() noexcept + { + return next_(); // Set breakpoint here to monitor TLS index allocation for T. + } }; template @@ -95,7 +101,7 @@ namespace tls BOOST_LEAF_CFG_TLS_INDEX_TYPE tls_index::idx = BOOST_LEAF_CFG_TLS_ARRAY_START_INDEX; template - BOOST_LEAF_CFG_TLS_INDEX_TYPE const alloc_tls_index::idx = tls_index::idx = index_counter<>::next(); + BOOST_LEAF_CFG_TLS_INDEX_TYPE const alloc_tls_index::idx = tls_index::idx = index_counter<>::next(); //////////////////////////////////////// @@ -121,32 +127,20 @@ namespace tls //////////////////////////////////////// template - std::uint32_t read_uint32() noexcept + unsigned read_uint() 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) (void *) read_ptr(); } template - void write_uint32( std::uint32_t x ) noexcept + void write_uint( unsigned x ) noexcept { - static_assert(sizeof(std::intptr_t) >= sizeof(std::uint32_t), "Incompatible tls_array implementation"); + static_assert(sizeof(std::intptr_t) >= sizeof(unsigned), "Incompatible tls_array implementation"); write_ptr((Tag *) (void *) (std::intptr_t) x); } - - template - void uint32_increment() noexcept - { - write_uint32(read_uint32() + 1); - } - - template - void uint32_decrement() noexcept - { - write_uint32(read_uint32() - 1); - } } } } -#endif +#endif // 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..9828c77a 100644 --- a/include/boost/leaf/config/tls_cpp11.hpp +++ b/include/boost/leaf/config/tls_cpp11.hpp @@ -1,14 +1,13 @@ #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-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) // 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 +// This header implements thread local storage for pointers and for unsigned int // values using the C++11 built-in thread_local storage class specifier. #include @@ -16,7 +15,7 @@ namespace boost { namespace leaf { -namespace leaf_detail +namespace detail { using atomic_unsigned_int = std::atomic; } @@ -47,39 +46,27 @@ namespace tls //////////////////////////////////////// template - struct BOOST_LEAF_SYMBOL_VISIBLE tagged_uint32 + struct BOOST_LEAF_SYMBOL_VISIBLE tagged_uint { - static thread_local std::uint32_t x; + static thread_local unsigned x; }; template - thread_local std::uint32_t tagged_uint32::x; - - template - std::uint32_t read_uint32() noexcept - { - return tagged_uint32::x; - } - - template - void write_uint32( std::uint32_t x ) noexcept - { - tagged_uint32::x = x; - } + thread_local unsigned tagged_uint::x; template - void uint32_increment() noexcept + unsigned read_uint() noexcept { - ++tagged_uint32::x; + return tagged_uint::x; } template - void uint32_decrement() noexcept + void write_uint( unsigned x ) noexcept { - --tagged_uint32::x; + tagged_uint::x = x; } } } } -#endif +#endif // 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..d1d0be98 100644 --- a/include/boost/leaf/config/tls_freertos.hpp +++ b/include/boost/leaf/config/tls_freertos.hpp @@ -1,12 +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-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) +// Copyright (c) 2022 Khalil Estell + +// LEAF requires thread local storage support for pointers and for uin32_t values. + +// This header implements "thread local" storage via FreeTOS functions +// pvTaskGetThreadLocalStoragePointer / pvTaskSetThreadLocalStoragePointer + #include #ifndef BOOST_LEAF_USE_TLS_ARRAY @@ -39,4 +44,4 @@ namespace tls } } -#endif +#endif // 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..5e9b1e90 100644 --- a/include/boost/leaf/config/tls_globals.hpp +++ b/include/boost/leaf/config/tls_globals.hpp @@ -1,21 +1,20 @@ #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-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) // 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 +// This header implements "thread local" storage for pointers and for unsigned int // values 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; } @@ -46,39 +45,27 @@ namespace tls //////////////////////////////////////// template - struct BOOST_LEAF_SYMBOL_VISIBLE tagged_uint32 + struct BOOST_LEAF_SYMBOL_VISIBLE tagged_uint { - static std::uint32_t x; + static unsigned x; }; template - std::uint32_t tagged_uint32::x; - - template - std::uint32_t read_uint32() noexcept - { - return tagged_uint32::x; - } - - template - void write_uint32( std::uint32_t x ) noexcept - { - tagged_uint32::x = x; - } + unsigned tagged_uint::x; template - void uint32_increment() noexcept + unsigned read_uint() noexcept { - ++tagged_uint32::x; + return tagged_uint::x; } template - void uint32_decrement() noexcept + void write_uint( unsigned x ) noexcept { - --tagged_uint32::x; + tagged_uint::x = x; } } } } -#endif +#endif // BOOST_LEAF_CONFIG_TLS_GLOBALS_HPP_INCLUDED diff --git a/include/boost/leaf/context.hpp b/include/boost/leaf/context.hpp index 0ac45d20..15dcb22c 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-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) @@ -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 +{ + template + struct get_dispatch + { + static BOOST_LEAF_CONSTEXPR T const * get(T const * x) noexcept + { + return x; + } + static BOOST_LEAF_CONSTEXPR T const * get(void const *) noexcept { - return ei; + 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 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); - } - - 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); + tuple_for_each::deactivate(tup); } - 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 ) { } + BOOST_LEAF_CONSTEXPR static void print(std::basic_ostream &, void const *, error_id, char const * &) { } }; -} - -//////////////////////////////////////////// - -#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